Flask 的消息提示语异常处理

Flaskapp.py:

      from flask import Flask, flash, render_template,request,abort

      app = Flask(__name__)

      app.secret_key = ‘123’  #用flash时要时使用它进行加密

      @app.route(‘/’)

      def hello_world():

           flash(‘hello feiniu’)

           render_template(‘index.html’)

     

      @app.route(‘/login’, method=[‘POST’])

      def login():

           form = request.form

           username = form.get(‘username)

           password = from.get(‘password’)

           if not username:

                 flash(“please input username”)

                 return render_template(“index.html”)

           if not password:

                 flash(“please input password”)

                 return render_template(“index.html”)

           if username == ‘feiniuchongtian’ and password == ‘123456’:

                 flash(“login success”)

                 return render_template(“index.html”)

           else:

                 flash(“username or password is wrong”)

                 return render_template(“index.html”)

 

     

@app.errorhandler(404)     #定义异常路由

      def not_found(e):

           return render_template(“404.html”)

      @app.route(‘/users/<user_id>’)

      def users(user_id):

           if int(user_id) == 1:

                 return render_template(“user.html”)

           else:

                 abort(404)

 

      if __name__ == ‘__main__’:

           app.run()

 

      index.html:

      ……

      <h1>Hello</h1>    

      <form action=’’/login” method=”post”>

           <input type=”text” name=”username”>

           <input type=”password” name=”password”>

           <input type=”submit” value=”Submit”>

</form>

      <h2>{{ get_flashed_messages()[0] }}</h2>

      ……

 

      404.html:

      ……

      <h1>您要找的页面去火星了</h1>

      ……

      user.html:

      ……

      <h1>User</h1>

      ……

posted @   飞牛冲天  阅读(173)  评论(0编辑  收藏  举报
努力加载评论中...
点击右上角即可分享
微信分享提示