[参考资料]:
Flask从入门到做出一个博客的大型教程(一)
Flask从入门到做出一个博客的大型教程(二)
Flask从入门到做出一个博客的大型教程(三)
Flask从入门到做出一个博客的大型教程(四)
Flask从入门到做出一个博客的大型教程(五)
我跟随上面的教程进行了实践,原作者(程序员duke)写的非常详细!
与原教程不一致的地方:
1.使用的是PostgreSQL数据库
对应的修改为:
插件安装:pip install psycopg2
连接串:postgresql://username:password@localhost:5432/db_name
2.用户头像使用了静态资源
因为国内访问Gravatar不稳定,所以放弃了使用在线图片(URL)的方法。
将用到的静态图片资源放在/app/static目录下,因为app目录是更目录,并且Flask(应该也是采用了常见的“约定大于配置”的方案)所以要求静态资源的路径必须是static。
routes.py写法
# 用户资料
@webapp.route('/user/<username>')
@login_required
def user(username):
tmp_user = User.query.filter_by(username=username).first_or_404()
posts = [
{'author': tmp_user, 'body': '测试Post #1号'},
{'author': tmp_user, 'body': '测试Post #2号'}
]
return render_template('user.html', user=tmp_user, posts=posts, file='/static/WALL-E.jpg')
对应的HTML写法
<td><img src="{{ file }}"></td>
【PS】还有一种使用图片流的做法,暂时没有深究,记录如下:
models.py中的写法
# 头像,获取本地图片流
def return_img_stream(self):
import base64
img_stream = ''
with open('res/images/WALL-E.jpg', 'r', encoding='utf-8') as img_f:
img_stream = img_f.read()
img_stream = base64.b64encode(img_stream)
return img_stream
对应的HTML写法
<td><img src="{{ post.author.return_img_stream() }}"></td>
完整的项目代码位置:
https://github.com/chenth0517/urination_record.git
支持Git clone,也支持SVN checkout