Python之flask使用技巧

Python之flask使用技巧

使用方法都寫在程序裏面的註釋中,請盡情享用,如果您覺得不錯可以點個贊哦🙂
代碼如下:

"""
Tips:
所有帶@app裝飾器的函數會自動調用,其他不帶裝飾器的函數必須手動調用纔會執行

"""
# -*- coding:utf-8 -*-
from flask import Flask, Request, render_template, url_for, redirect

__author__ = 'Evan'
app = Flask(__name__, template_folder='templates')  # 初始化Flask,定義模板文件夾爲"templates"


# 創建根目錄
@app.route('/')
def root_directory():
    # 返回一個字符串到網頁
    return "I'm root directory"
    # return redirect(url_for('login'))  # 重定向到login函數


# 創建Login目錄
@app.route('/login', methods=['GET', 'POST'])  # 配置訪問方式:GET和POST均可訪問
def login():
    print('Login method: {}'.format(Request.method))  # 打印請求的方法
    if Request.method == 'GET':
        return 'Request method is GET'
    elif Request.method == 'POST':
        return 'Request method is POST'
    else:
        return 'Request method is {}'.format(Request.method)


# 使用外部文件(外部文件會在template_folder定義的文件夾內查找)
@app.route('/display/')
def display_page():
    # 返回一個html頁面
    return render_template('test.html')


# URL字段抓取(格式: <converter:variable_name>)
@app.route('/user/<username>/')
def ask_username(username):
    """
    URL字段抓取用法:
    @app.route('/user/<int:username>/')  # 抓取/user/後面的整形字段,如果不符合規則會報錯
    @app.route('/user/<float:username>/')  # 抓取/user/後面的浮點形字段,如果不符合規則會報錯
    @app.route('/user/<path:username>/')  # 抓取/user/後面的所有字段(包含/),如果不符合規則會報錯
    :param username: 抓取/user/後面的所有字段(不包含/)賦值給username
    :return:
    """
    if username == 'Evan':
        return 'Welcome back'
    else:
        return "Hi {}".format(username)


# 使用url_for動態生成新的URL(原先的URL和更改後的URL都可以訪問)
def generate_new_url():
    """
    url_for使用方法:
    param - endpoint: 接受函數名作爲參數,爲此函數生成新的URL
    param - **values: 接受函數內的形參作爲參數,也接受未知變量名,未知變量名會添加到URL末尾作爲查詢參數
    :return:
    """
    with app.test_request_context():
        print(url_for(endpoint='display_page', username='Evan'))  # 生成新的URL:/display/?username=Evan
        print(url_for(endpoint='ask_username', username='Jane'))  # 生成新的URL:/user/Jane/


def main():
    # app.run(host='0.0.0.0')  # 使服務器可被網絡內其他設備訪問(不配置host,只能用本地電腦訪問)
    app.run(debug=True)  # 啓用Debug模式,服務器會在代碼修改後自動重新載入(慎用,有安全隱患)


if __name__ == '__main__':
    main()

執行結果:

* Serving Flask app "flask_sample" (lazy loading)
 * Environment: production
   WARNING: This is a development server. Do not use it in a production deployment.
   Use a production WSGI server instead.
 * Debug mode: on
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 214-366-588
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章