目录

前文列表

用 Flask 来写个轻博客 (1) — 创建项目

用 Flask 来写个轻博客 (2) — Hello World!

用 Flask 来写个轻博客 (3) — (M)VC_连接 MySQL 和 SQLAlchemy

用 Flask 来写个轻博客 (4) — (M)VC_创建数据模型和表

用 Flask 来写个轻博客 (5) — (M)VC_SQLAlchemy 的 CRUD 详解

用 Flask 来写个轻博客 (6) — (M)VC_models 的关系(one to many)

用 Flask 来写个轻博客 (7) — (M)VC_models 的关系(many to many)

用 Flask 来写个轻博客 (8) — (M)VC_Alembic 管理数据库结构的升级和降级

用 Flask 来写个轻博客 (9) — M(V)C_Jinja 语法基础快速概览

用 Flask 来写个轻博客 (10) — M(V)C_Jinja 常用过滤器与 Flask 特殊变量及方法

用 Flask 来写个轻博客 (11) — M(V)C_创建视图函数

用 Flask 来写个轻博客 (12) — M(V)C_编写和继承 Jinja 模板

用 Flask 来写个轻博客 (13) — M(V)C_WTForms 服务端表单检验

用 Flask 来写个轻博客 (14) — M(V)C_实现项目首页的模板

实现 post() 视图函数

  • views.py

    在原有的基础上对视图函数 post() 进行修改.
from uuid import uuid4
import datetime from forms import CommentForm @app.route('/post/<string:post_id>', methods=('GET', 'POST'))
def post(post_id):
"""View function for post page""" # Form object: `Comment`
form = CommentForm()
# form.validate_on_submit() will be true and return the
# data object to form instance from user enter,
# when the HTTP request is POST
if form.validate_on_submit():
new_comment = Comment(id=str(uuid4()),
name=form.name.data)
new_comment.text = form.text.data
new_comment.date = datetime.datetime.now()
new_comment.post_id = post_id
db.session.add(new_comment)
db.session.commit() post = Post.query.get_or_404(post_id)
tags = post.tags
comments = post.comments.order_by(Comment.date.desc()).all()
recent, top_tags = sidebar_data() return render_template('post.html',
post=post,
tags=tags,
comments=comments,
form=form,
recent=recent,
top_tags=top_tags)

NOTE: CommentForm 类是在 用 Flask 来写个轻博客 (13) — M(V)C_WTForms 服务端表单检验 中定义的, 需要将其导入到该模块中.

  • 需要在视图函数 post() 中添加接收 HTTP POST 请求, 路由方法 route() 默认只接收 HTTP GET 请求.

  • 在视图函数中创建一个 form 对象, 并以此来获取用户在输入框中输入的数据对象.

  • form.validata_on_submit() 方法会隐式的判断该 HTTP 请求是不是 POST, 若是, 则将请求中提交的表单数据对象传入上述的 form 对象并进行数据检验.

  • 若提交的表单数据对象通过了 form 对象的检验, 则 form.validata_on_submit() 返回为 True 并且将这些数据传给 form 对象, 成为其实例属性.

  • 之后我们就能够通过表单对象 form 来调用其实例属性, 并且赋值给 models 对象, 最后存入到数据库中.

  • 最后, 因为在 post.html 页面需要显示这些评论, 所以该模板文件也需要传入 form 对象含有的实例属性值, 那么我们直接在视图函数 post() 中 直接将 form 对象传入到 render_template() 就好了.

在 post.html 中添加表单

{% extends "base.html"%}
{% block title %}{{ post.name }}{% endblock %} <!-- Replace the BODY of template base.html -->
{% block body %}
<h3>{{ post.title }}</h3>
{{ post.publish_date }}:
{{ post.text }} <div class="col-lg-12">
<h3>New Comment:</h3>
<!-- Set the form -->
<form method="POST" action="{{ url_for('post', post_id=post.id)
}}">
{{ form.hidden_tag() }}
<div>
<!-- Field: `name` label -->
{{ form.name.label }}
{% if form.name.errors %}
{% for e in form.name.errors %}
<p class="help-block">{{ e }}</p>
{% endfor %}
{% endif %}
{{ form.name(class_="form-control") }}
</div>
<div class="form-group">
{{ form.text.label }}
{% if form.text.errors %}
{% for e in form.text.errors %}
<p class="help-block">{{ e }}</p>
{% endfor %}
{% endif %}
{{ form.text(class_='form-control') }}
</div>
<input class="btn btn-primary" type="submit" value="Add Comment">
</form>
</div>
{% endblock %}
  • form.hidden_tag(): 提供了预防跨站请求伪造的机制, 常用于表单页面
  • field.errors: 列表类型, 用于显示验证失败后的提示信息
  • {{ form.name(class_="form-control") }}: 把字段本身作为方法调用, 会渲染作用于该字段的的 HTML 代码.
  • field.label: 为输入框生成对应的 label 标签的 HTML 代码.

效果

查看是否写入到了数据库:

mysql> select * from comments where name='jmilkfan';
+--------------------------------------+----------+------+---------------------+--------------------------------------+
| id | name | text | date | post_id |
+--------------------------------------+----------+------+---------------------+--------------------------------------+
| 0cea03ec-76b4-4ba4-b781-6a0bf056078b | jmilkfan | HI | 2016-11-25 17:21:05 | 35c8b4f3-c231-4b32-b139-f7647714b87e |
+--------------------------------------+----------+------+---------------------+--------------------------------------+
1 row in set (0.00 sec)

ERROR LOG:

(env)fanguiju@fanguiju:/opt/JmilkFan-s-Blog$ python manage.py server
/opt/JmilkFan-s-Blog/env/local/lib/python2.7/site-packages/flask/exthook.py:71: ExtDeprecationWarning: Importing flask.ext.script is deprecated, use flask_script instead.
.format(x=modname), ExtDeprecationWarning
/opt/JmilkFan-s-Blog/env/local/lib/python2.7/site-packages/flask/exthook.py:71: ExtDeprecationWarning: Importing flask.ext.migrate is deprecated, use flask_migrate instead.
.format(x=modname), ExtDeprecationWarning
/opt/JmilkFan-s-Blog/env/local/lib/python2.7/site-packages/flask/exthook.py:71: ExtDeprecationWarning: Importing flask.ext.sqlalchemy is deprecated, use flask_sqlalchemy instead.
.format(x=modname), ExtDeprecationWarning
/opt/JmilkFan-s-Blog/env/local/lib/python2.7/site-packages/flask_sqlalchemy/__init__.py:800: UserWarning: SQLALCHEMY_TRACK_MODIFICATIONS adds significant overhead and will be disabled by default in the future. Set it to True to suppress this warning.
warnings.warn('SQLALCHEMY_TRACK_MODIFICATIONS adds significant overhead and will be disabled by default in the future. Set it to True to suppress this warning.')
Traceback (most recent call last):
File "manage.py", line 35, in <module>
manager.run()
File "/opt/JmilkFan-s-Blog/env/local/lib/python2.7/site-packages/flask_script/__init__.py", line 412, in run
result = self.handle(sys.argv[0], sys.argv[1:])
File "/opt/JmilkFan-s-Blog/env/local/lib/python2.7/site-packages/flask_script/__init__.py", line 383, in handle
res = handle(*args, **config)
File "/opt/JmilkFan-s-Blog/env/local/lib/python2.7/site-packages/flask_script/commands.py", line 425, in __call__
**self.server_options)
File "/opt/JmilkFan-s-Blog/env/local/lib/python2.7/site-packages/flask/app.py", line 843, in run
run_simple(host, port, self, **options)
File "/opt/JmilkFan-s-Blog/env/local/lib/python2.7/site-packages/werkzeug/serving.py", line 677, in run_simple
s.bind((hostname, port))
File "/usr/lib/python2.7/socket.py", line 224, in meth
return getattr(self._sock,name)(*args)
socket.error: [Errno 98] Address already in use

TSG: 在该运行的环境中, Server() 默认的 IP 或 PORT 被占用了. 所以在 manage.py 中手动的设定其 IP 或 PORT.

manager.add_command("server", Server(host='127.0.0.1', port=8089))

最新文章

  1. Spark Shuffle原理、Shuffle操作问题解决和参数调优
  2. [Android]Android端ORM框架——RapidORM(v2.0)
  3. Linux基础练习题
  4. iTestSharp的简单应用
  5. C#软件设计——小话设计模式原则之:单一职责原则SRP
  6. CSS3支持box-flex弹性布局
  7. SPOJ PHRASES 后缀数组
  8. JS算法总结
  9. debian之samba服务器搭建
  10. [JS] JavaScript由浅入深(1) 基本特性
  11. grails-domain-id 无生成策略,由程序控制
  12. CSS常用样式整理
  13. CentOS 7 终端设置屏幕分辨率
  14. Python多线程同步命令行模拟进度显示
  15. webStorm和Sublime使用列编辑命令
  16. 自己实现一个nullptr
  17. Maven项目配置logback
  18. 【转】10个非常有用的网页设计工具 | Goodfav Magazine
  19. 反Nim博弈
  20. MySQL优化小案例:key_buffer_size

热门文章

  1. CPU C-States Power Saving Modes
  2. Oracle 表空间、用户
  3. Git 内部原理
  4. HBaseRegionServer宕机数据恢复
  5. Android深度探索-卷1第三章心得体会
  6. Cocos2d 之FlyBird开发---GameScore类
  7. CSDN如何转载别人的博客
  8. (4.10)sql server导入导出
  9. HDFS 工具类
  10. python删除某一行