- 安裝INSTALL
pip install Flask
- 快速開始quickstart
app.py
from flask import Flask
# 引入Flask類誉察,他的實(shí)例將是我們的WSGI應(yīng)用
app = Flask(__name__)
# 創(chuàng)建Flask的實(shí)例灾螃,傳入?yún)?shù)鳖敷,當(dāng)前模塊的名字斩跌,一般默認(rèn)當(dāng)前模塊為主模塊宠进,名稱為__main__,也可使用__name__代替
@app.route('/')
def hello_world():
return 'Hello, World!'
# 使用route標(biāo)識(shí)URL
if __name__ == '__main__':
app.run(debug=True)
# 在命令行輸入python app.py即可啟動(dòng),傳入?yún)?shù)debug=True即可進(jìn)入調(diào)試模式
- 變量規(guī)則
from markupsafe import escape
@app.route('/user/<username>')
def show_user_profile(username):
# show the user profile for that user
return 'User %s' % escape(username)
@app.route('/post/<int:post_id>')
def show_post(post_id):
# show the post with the given id, the id is an integer
return 'Post %d' % post_id
@app.route('/path/<path:subpath>')
def show_subpath(subpath):
# show the subpath after /path/
return 'Subpath %s' % escape(subpath)
可以在route中傳遞變量 <variable_name>,也可以指定傳遞的變量的格式<converter:variable_name>
converter | desc |
---|---|
string | (default) accepts any text without a slash |
int | accepts positive integers |
float | accepts positive floating point values |
path | like string but also accepts slashes |
uuid | accepts UUID strings |
URL唯一性與重定向
@app.route('/projects/')
URL帶斜杠時(shí)屏箍,如果輸入的地址不帶斜杠,會(huì)被重定向胸哥,@app.route('/projects')
URL不帶斜杠時(shí)涯竟,如果輸入的地址帶有斜杠會(huì)404地址構(gòu)建
url_for()
from flask import Flask, url_for
from markupsafe import escape
app = Flask(__name__)
@app.route('/')
def index():
return 'index'
@app.route('/login')
def login():
return 'login'
@app.route('/user/<username>')
def profile(username):
return '{}\'s profile'.format(escape(username))
with app.test_request_context():
print(url_for('index'))
print(url_for('login'))
print(url_for('login', next='/'))
print(url_for('profile', username='John Doe'))
/
/login
/login?next=/
/user/John%20Doe
使用url_for()
之后,可以不用每次修改URL之后都去修改別的地方引用的URL空厌。
- HTTP方法
from flask import request
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
return do_the_login()
else:
return show_the_login_form()
- 使用模板
from flask import render_template
@app.route('/hello/')
@app.route('/hello/<name>')
def hello(name=None):
return render_template('hello.html', name=name)