Flask 路由相關操做

URL Route

  • URL 後接 / 做爲目錄級訪問
  • URL 後不接 / 做爲文件級訪問
from flask import Flask
app = Flask(__name__)

@app.route('/')
def index():
    return 'Index Page'

@app.route('/about')
def about():
    return 'The about page'
說明
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
from flask import Flask
app = Flask(__name__)

@app.route('/user/<username>')
def show_user_profile(username):
    # show the user profile for that user
    return 'User %s' % 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' % subpath
  • 可使用methods來指定該路由使用的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()

參考

URL Binding

使用url_for()方法能夠調用參數中的route方法,以便知足某種調用目的,如單元測試。css

from flask import Flask
from flask import Flask, url_for
app = Flask(__name__)

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'))

靜態文件伺候

靜態文件指應用使用的JavascriptCSS代碼及圖片資源文件。html

  • 在項目根目錄下建立static目錄
url_for('static', filename='style.css')

模板文件伺候

Flask會自動尋找templates目錄,因此原則上請不要自定義這個目錄的名字,且應該將其放在項目(或模塊)的根路徑下。python

from flask import Flask
from flask import render_template
app = Flask(__name__)

@app.route('/hello/')
@app.route('/hello/<name>')
def hello(name=None):
    return render_template('hello.html', name=name)
<body>
    Hello, World!

    from templates
</body>

參考

請求處理

Request

@app.route('/test', methods=['POST', 'GET'])
def test():
    error = None
    
    if request.method == 'POST':
        t1 = request.form['1']
        t2 = request.form['2']
    elif request.method == 'GET':
        # for URL `?key=value`
        t3 = request.args.get('key', '')
    else:
        error = 'Method is not POST or GET!'

    return render_template('test.html', error=error)

參考

文件上傳

  • 保存時從新指定文件名
from flask import request

@app.route('/upload', methods=['GET', 'POST'])
def upload_file():
    if request.method == 'POST':
        f = request.files['the_file']
        f.save('/var/www/uploads/uploaded_file.txt')
    ...
  • 保存時,使用上傳的文件名
from flask import request
from werkzeug.utils import secure_filename

@app.route('/upload', methods=['GET', 'POST'])
def upload_file():
    if request.method == 'POST':
        f = request.files['the_file']
        f.save('/var/www/uploads/' + secure_filename(f.filename))
    ...

參考

Cookies

  • 讀取cookie
from flask import request

@app.route('/')
def index():
    username = request.cookies.get('username')
    # use cookies.get(key) instead of cookies[key] to not get a
    # KeyError if the cookie is missing.
  • 寫入cookie
from flask import make_response

@app.route('/')
def index():
    resp = make_response(render_template(...))
    resp.set_cookie('username', 'the username')
    return resp

重定向

  • 使用url_for來找到URL地址
  • 使用redirect來重定向
from flask import abort, redirect, url_for

@app.route('/')
def index():
    return redirect(url_for('login'))
  • 使用abort來返回錯誤碼
@app.route('/login')
def login():
    abort(401)
    this_is_never_executed()
  • 使用@app.errorhandler()來處理錯誤碼對應的請求
from flask import render_template

@app.errorhandler(404)
def page_not_found(error):
    return render_template('page_not_found.html'), 404

參考

相關文章
相關標籤/搜索