美文网首页
falsk_用户登录系统练习

falsk_用户登录系统练习

作者: 圣_狒司机 | 来源:发表于2018-07-14 14:15 被阅读32次

    1. 在vs code中创建以下目录:

    www
    │ server.py
    ├─imgs
    └─templates
            base.html
            column.html
            index.html
            login.html
    

    server.py 是服务器文件,templates文件夹放置html模板,imgs放置图片,不要改变文件夹名称。

    2. server.py

    from flask import Flask,render_template,url_for,redirect,request
    from wtforms import Form,TextField,PasswordField
    from wtforms.validators import Required
    
    app = Flask(__name__)
    
    class LoginForm(Form):
        username = TextField('username',[Required()])
        password = PasswordField('password',[Required()])
    
    @app.route("/")
    def index():
        return render_template('index.html',message=["hello","world"])
    
    @app.route('/login',methods=["GET","POST"])
    def login():
        myForm = LoginForm(request.form)
        if request.method == "POST":
            if myForm.username.data == 'jack' and myForm.password.data == "123" and myForm.validate():
                return redirect(url_for('column'))
            else:
                return render_template('login.html',ticks='账户密码错误!',form=myForm)
        return render_template('login.html',form=myForm)
    
    @app.route('/column')
    def column():
        return render_template("column.html")
    
    if __name__ == '__main__':
        app.run(host='0.0.0.0',debug=True) 
    

    3. base.html

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>Document</title>
    </head>
    <body>
        <a href="{{ url_for('index')}}"> index </a> 
        <a href="{{ url_for('login')}}"> login </a> 
        <hr>
        {% block content %}
        {% endblock %}
    <div> 
        copyright superexpo ,all right recived!
    </div>  
    </body>
    </html>
    

    4. index.html

    {% extends "base.html" %}
    {% block content %}
    <h1>首页</h1>
    {% if ticks %}{{ticks}}{% endif %}
    {% for  m in message%}
    {{m}}<br>
    {% endfor %}
    {% endblock %}
    

    5. login.html

     {% extends "base.html" %}
    {% block content%}
    <h1>登录界面</h1>
    <form  method="post">
        username{{ form.username}}<br>
        password{{ form.password}}<br>
        <input type="submit" name="submit">
        <input type="reset"><br>
        {% if ticks %}{{ticks}}{% endif %}<br>
    </form>
    {% endblock %}
    

    6. column.html

    {% extends "base.html" %}
    {% block content%}
    <h1>验证通过!</h1>
    {% endblock %}
    

    小结:

    1. 手写html是非常费时费力的工作,好在我们有emmet工具,html:5 语法可以生成html框架,配合其他语法可以像写公式一样快速的写出大段html;
    2. 用wtform 插件取代硬写表单;
    3. 用 app.run(host='0.0.0.0',debug=True) 参数可以实现局域网内访问。

    相关文章

      网友评论

          本文标题:falsk_用户登录系统练习

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