关于python:Python-中使用-Flask-框架

53次阅读

共计 2008 个字符,预计需要花费 6 分钟才能阅读完成。

Flask 框架

$ pip install flask

写一个 app.py,解决 3 个 URL,别离是:

  • GET /:首页,返回 Home
  • GET /signin:登录页,显示登录表单;
  • POST /signin:解决登录表单,显示登录后果。
from flask import Flask
from flask import request

app = Flask(__name__)

@app.route('/', methods=['GET', 'POST'])
def home():
    return '<h1>Home</h1>'

@app.route('/signin', methods=['GET'])
def signin_form():
    return '''<form action="/signin"method="post">
              <p><input name="username"></p>
              <p><input name="password" type="password"></p>
              <p><button type="submit">Sign In</button></p>
              </form>'''@app.route('/signin', methods=['POST'])
def signin():
    if request.form['username']=='admin' and request.form['password']=='password':
        return '<h3>Hello, admin!</h3>'
    return '<h3>Bad username or password.</h3>'

if __name__ == '__main__':
    app.run()

应用模板

Flask 默认反对的模板是 jinja2,所以咱们先装置 jinja2:

$ pip install jinja2

批改 app.py

# app.py

from flask import Flask, request, render_template

app = Flask(__name__)

@app.route('/', methods=['GET', 'POST'])
def home():
    return render_template('home.html')

@app.route('/signin', methods=['GET'])
def signin_form():
    return render_template('form.html')

@app.route('/signin', methods=['POST'])
def signin():
    username = request.form['username']
    password = request.form['password']
    if username=='admin' and password=='password':
        return render_template('signin-ok.html', username=username)
    return render_template('form.html', message='Bad username or password', username=username)

if __name__ == '__main__':
    app.run()

减少模板文件:

# templates/form.html
<html>
<head>
  <title>Please Sign In</title>
</head>
<body>
  {% if message %}
  <p style="color:red">{{message}}</p>
  {% endif %}
  <form action="/signin" method="post">
    <legend>Please sign in:</legend>
    <p><input name="username" placeholder="Username" value="{{username}}"></p>
    <p><input name="password" placeholder="Password" type="password"></p>
    <p><button type="submit">Sign In</button></p>
  </form>
</body>
</html>
# templates/signin-ok.html
<html>
<head>
  <title>Welcome, {{username}}</title>
</head>
<body>
  <p>Welcome, {{username}}!</p>
</body>
</html>

运行:

$ python app.py 
 * Running on http://127.0.0.1:5000/

除了 Flask,常见的 Python Web 框架还有:

  • Django:全能型 Web 框架;
  • web.py:一个玲珑的 Web 框架;
  • Bottle:和 Flask 相似的 Web 框架;
  • Tornado:Facebook 的开源异步 Web 框架。

正文完
 0