08、wtforms集成到tornado中

作者: vannesspeng | 来源:发表于2018-12-28 14:26 被阅读8次

    项目GIthub源码地址:[https://github.com/vannesspeng/TornadoForum]

    虚拟环境中安装wtforms,tornado_wtforms

    pip install wtforms
    pip install tornado_wtforms

    本小节代码目录

    代码结构
    这里前端页面使用第六章中给出的message.html页面,[html、css代码](https://www.jianshu.com/p/a052624e73d3),之前已经给出,大家可以去第六章中获取。

    wtforms定义form表单并验证

    models.py

    from datetime import datetime
    
    from peewee import *
    from peewee import Model
    
    db = MySQLDatabase('message', host="127.0.0.1", port=3306, user="root", password="root")
    
    class Message(Model):
        id = AutoField(verbose_name="id")
        name = CharField(max_length=10, verbose_name="姓名")
        email = CharField(max_length=30, verbose_name="邮箱")
        address = CharField(max_length=30, verbose_name="地址")
        message = TextField(verbose_name="留言")
    
        class Meta:
            database = db
            table_name = "message"
    
    if __name__ == "__main__":
        db.create_tables([Message])
    
    

    定义Message Model对应的Form对象

    from wtforms.fields import StringField, TextAreaField
    from wtforms_tornado import Form
    from wtforms.validators import DataRequired, Length, Email
    
    class MessageForm(Form):
        name = StringField("姓名", validators=[DataRequired(message="请输入姓名"), Length(min=2,max=5, message="长度为2-5")])
        email = StringField("邮箱", validators=[Email(message="邮箱不合法")])
        address = StringField("地址", validators=[DataRequired(message="请填写地址")])
        message = TextAreaField("留言", validators=[DataRequired(message="请填写留言")])
    

    使用wtforms进行表单验证,再返回html

    # 1. 什么是模板
    import os
    
    from tornado.web import StaticFileHandler, RedirectHandler
    from aiomysql import create_pool
    import time
    from tornado import web
    import tornado
    from tornado.web import template
    from chapter_05.forms import MessageForm
    from chapter_05.models import Message
    
    class MainHandler(web.RequestHandler):
        def initialize(self, db):
            self.db = db
    
        async def get(self, *args, **kwargs):
            message_from = MessageForm()
            # 使用wtforms返回html
            self.render("message.html", message_form=message_from)
    
        async def post(self, *args, **kwargs):
            message_from = MessageForm(self.request.arguments)
            if message_from.validate():
                #验证通过, 获取具体的值并保存
                name = message_from.name.data
                email = message_from.email.data
                address = message_from.address.data
                message_data = message_from.message.data
    
                message = Message()
                message.name = name
                message.email = email
                message.address = address
                message.message = message_data
    
                message.save()
    
                self.render("message.html", message_form=message_from)
            else:
                self.render("message.html", message_form=message_from)
    
    
    settings = {
        "static_path": os.path.join(os.getcwd(), "static"),
        "static_url_prefix": "/static/",
        "template_path": "templates",
        "db": {
            "host": "127.0.0.1",
            "user": "root",
            "password": "root",
            "name": "message",
            "port": 3306
        }
    }
    
    if __name__ == "__main__":
        app = web.Application([
            ("/", MainHandler, {"db": settings["db"]}),
            # ("/static/(.*)", StaticFileHandler, {"path": "C:/projects/tornado_overview/chapter03/static"})
        ], debug=True, **settings)
        app.listen(8888)
        tornado.ioloop.IOLoop.current().start()
    

    由于wtform返回了form表单的html代码,那么message.html页面修改如下:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title></title>
        <link rel="stylesheet" type="text/css" href="{{ static_url('style.css') }}">
    </head>
    <body>
    <form action="/" method="post" class="smart-green">
        <h1>留言信息
            <span>请留下你的信息.</span>
        </h1>
        <!--<input id="id" type="hidden" name="id" value="{{ id }}" />-->
        {% autoescape None %}
        {% for field in message_form %}
            <span>{{ field.label.text }} :</span>
            {{ field(placeholder="请输入"+field.label.text) }}
    
            {% if field.errors %}
                {% for error_msg in field.errors %}
                    <div class="error-msg">{{ error_msg }}</div>
                {% end %}
                {% else %}
                    <div class="error-msg"></div>
            {% end %}
        {% end %}
        <label>
            <span>&nbsp;</span>
            <input type="submit" class="button" value="提交"/>
        </label>
    </form>
    
    </body>
    </html>
    

    相关文章

      网友评论

        本文标题:08、wtforms集成到tornado中

        本文链接:https://www.haomeiwen.com/subject/zasakqtx.html