Python 中使用 Flask 框架

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 '

Home

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

''' @app.route('/signin', methods=['POST']) def signin(): if request.form['username']=='admin' and request.form['password']=='password': return '

Hello, admin!

' return '

Bad username or password.

' 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


  Please Sign In


  {% if message %}
  

{{ message }}

{% endif %}
Please sign in:

# templates/signin-ok.html


  Welcome, {{ username }}


  

Welcome, {{ username }}!

运行:

$ 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框架。

你可能感兴趣的:(python)