Flask獲取請求參數


4.3 獲取請求參數

from flask import request

 

就是 Flask 中表示當前請求的 request 對象,request對象中保存了一次HTTP請求的一切信息。前三個比較常用:

在python2中在非英文字符前加字母’u’可以解決編碼錯誤問題

U’中國’  %  sa  

 

# 接口  api

# 127.0.0.1:5000/index?city=shenzhen&country=china  查詢字符串 QueryString

@app.route("/index", methods=["GET", "POST"])

def index():

    # request中包含了前端發送過來的所有請求數據

    # form和data是用來提取請求體數據

    # 通過requset.form可以直接提取請求體中的表單格式的數據, 是一個類字典的對象

    # 通過get方法只能拿到多個同名參數的第一個

    name = request.form.get("name")

    age = request.form.get("age")

    name_li = request.form.getlist("name")

 

    # 如果是請求體的數據不是表單格式的(如json格式),可以通過request.data獲取

    print("request.data: %s" % request.data)

 

    # args是用來提取url中的參數(查詢字符串)

    city = request.args.get("city")

    return "hello name=%s, age=%s, city=%s, name_li=%s" % (name, age, city, name_li)

 

4.3.1 上傳文件

已上傳的文件存儲在內存或是文件系統中一個臨時的位置。你可以通過請求對象的 files 屬性訪問它們。每個上傳的文件都會存儲在這個字典里。它表現近乎為一個標准的 Python file 對象,但它還有一個 save() 方法,這個方法允許你把文件保存到服務器的文件系統上。這里是一個用它保存文件的例子:

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')
# coding:utf-8

from flask import Flask, request

app = Flask(__name__)

@app.route("/upload", methods=["POST"])

def upload():

    """接受前端傳送過來的文件"""

    file_obj = request.files.get("pic")

    if file_obj is None:

        # 表示沒有發送文件

        return "未上傳文件"

 

    # 將文件保存到本地

    # # 1. 創建一個文件

    # f = open("./demo.png", "wb")

    # # 2. 向文件寫內容

    # data = file_obj.read()

    # f.write(data)

    # # 3. 關閉文件

    # f.close()

 

    # 直接使用上傳的文件對象保存,相當於上面的文件操作open(),close()進行封裝

    file_obj.save("./demo1.png")

    return "上傳成功"

 

if __name__ == '__main__':

    app.run(debug=True)

 

如果你想知道上傳前文件在客戶端的文件名是什么,你可以訪問 filename 屬性。但請記住, 永遠不要信任這個值,這個值是可以偽造的。如果你要把文件按客戶端提供的文件名存儲在服務器上,那么請把它傳遞給 Werkzeug 提供的 secure_filename() 函數:

 

from flask import request
from werkzeug 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))
    ...

 

上下文件管理器(with)

class Foo(object):

    def __enter__(self):

        """進入with語句的時候被with調用"""

        print("enter called")

 

    def __exit__(self, exc_type, exc_val, exc_tb):

        """離開with語句的時候被with調用"""

        print("exit called")

        print("exc_type: %s" % exc_type)

        print("exc_val: %s" % exc_val)

        print("exc_tb: %s" % exc_tb)

 

with Foo() as foo:

    print("hello python")

    a = 1 / 0

    print("hello end")

 

 

# 進入with語句的時候,with幫助我們調用對象的__enter__方法,

# 離開with語句的時候,with幫助我們調用對象的__exit__方法4.4 abort函數與自定義異常處理

4.4.1 abort函數

From flask import Flask,request,abort,Response

 

@app.route("/login", methods=["GET"])

def login():

    # name = request.form.get()

    # pwd = request.form.get()

    name = ""

    pwd = ""

    if name != "zhangsan" or pwd != "admin":

        # 使用abort函數可以立即終止視圖函數的執行

        # 並可以返回給前端特定的信息

        # 1 傳遞狀態碼信息, 必須是標准的http狀態碼

        abort(404)

        # # 2. 傳遞響應體信息

        # resp = Response("login failed")

        # abort(resp)

 

return "login success"

 

4.4.2 自定義異常處理

@app.errorhandler(404)

def error(e):

    return '您請求的頁面不存在了,請確認后再次訪問!%s'%e

 

 

4.5 返回的響應數據

4.5.1 元組

可以返回一個元組,這樣的元組必須是 (response, status, headers) 的形式,且至少包含一個元素。 status 值會覆蓋狀態代碼, headers 可以是一個列表或字典,作為額外的消息標頭值。

 

@app.route("/index")

def index():

    # 1 使用元祖,返回自定義的響應信息

    #        響應體       狀態碼 響應頭

    # return "index page", 400, [("Itcast", "pyton"), ("City", "shenzhen")]

    # return "index page", 400, {"Itcast1": "python1", "City1": "sz1"}

    # return "index page", 666, {"Itcast1": "python1", "City1": "sz1"}

    # return "index page", "666 itcast status", {"Itcast1": "python1", "City1": "sz1"}

    # return "index page", "666 itcast status"

 

    # 2 使用make_response 來構造響應信息

    resp = make_response("index page 2")

    resp.status = "999 itcast"  # 設置狀態碼

    resp.headers["city"] = "sz"  # 設置響應頭

    return resp

 

 

4.5.2 make_response

resp = make_response()

resp.headers[“sample”] = “value”

resp.status = “404 not found”

 

 

4.6 使用jsonify返回json數據

from flask import Flask, jsonify

import json

 

app = Flask(__name__)

 

@app.route("/index")

def index():

    # json就是字符串

    data = {

        "name": "python",

        "age": 24

    }

    # # json.dumps(字典)  將python的字典轉換為json字符串

    # # json.loads(字符串)  將字符串轉換為python中的字典

    #

    # json_str = json.dumps(data)

    #

    # return json_str, 200, {"Content-Type": "application/json"}

 

    # jsonify幫助轉為json數據,並設置響應頭 Content-Type 為application/json

    # return jsonify(data)

 

    return jsonify(city="sz", country="china")

 

4.5 重定向

from flask import redirect

 

 

4.6 設置和讀取cookie

From flask import make_response

 

@app.route("/set_cookie")

def set_cookie():

    resp = make_response("success")

    # 設置cookie, 默認有效期是臨時cookie,瀏覽器關閉就失效

    resp.set_cookie("Itcast", "Python")

    resp.set_cookie("Itcast1", "Python1")

    # max_age設置有效期,單位:秒

    resp.set_cookie("Itcast2", "Python1", max_age=3600)

    resp.headers["Set-Cookie"] = "Itcast3=Python3; Expires=Sat, 18-Nov-2017 04:36:04 GMT; Max-Age=3600; Path=/"

    return resp

 

@app.route("/get_cookie")

def get_cookie():

    c = request.cookies.get("Itcast")

    return c

 

@app.route("/delete_cookie")

def delete_cookie():

    resp = make_response("del success")

    # 刪除cookie

    resp.delete_cookie("Itcast1")

return resp4.7 session

 

設置和讀取session

from flask import session,

 

# flask的session需要用到的秘鑰字符串

app.config["SECRET_KEY"] = "dhsodfhisfhosdhf29fy989"

# flask默認把session保存到了cookie中

 

@app.route("/login")

def login():

    # 設置session數據

    session["name"] = "python"

    session["mobile"] = "18611111111"

    return "login success"

 

 

@app.route("/index")

def index():

    # 獲取session數據

    name = session.get("name")

    return "hello %s" % name

 

4.8 請求上下文與應用上下文

線程局部變量

請求上下文(request context)  

requestsession都屬於請求上下文對象。

 

應用上下文(application context)

current_appg都屬於應用上下文對象。

 

current_app:表示當前運行程序文件的程序實例。

g:處理請求時,用於臨時存儲的對象,每次請求都會重設這個變量。

 

4.9 請求鈎子

請求鈎子是通過裝飾器的形式實現,Flask支持如下四種請求鈎子:

before_first_request:在處理第一個請求前運行。

@app.before_first_request

before_request:在每次請求前運行。

after_request(response):如果沒有未處理的異常拋出,在每次請求后運行。

teardown_request(response):在每次請求后運行,即使有未處理的異常拋出。

@app.route("/index")

def index():

    print("index 被執行")

    a = 1 / 0

    return "index page"

 

@app.route("/hello")

def hello():

    print("hello 被執行")

    return "hello page"

 

@app.before_first_request

def handle_before_first_request():

    """在第一次請求處理之前先被執行"""

    print("handle_before_first_request 被執行")

 

@app.before_request

def handle_before_request():

    """在每次請求之前都被執行"""

    print("handle_before_request 被執行")

 

@app.after_request

def handle_after_request(response):

    """在每次請求(視圖函數處理)之后都被執行, 前提是視圖函數沒有出現異常"""

    print("handle_after_request 被執行")

    return response

 

@app.teardown_request

def handle_teardown_request(response):

"""在每次請求 (視圖函數處理)之后都被執行, 無論視圖函數是否出現異常,都被執行, 工作在非調試模式時 debug=False"""

“””請求的路徑”””

    path = request.path

    if path == url_for("index"):

        print("在請求鈎子中判斷請求的視圖邏輯: index")

    elif path == url_for("hello"):

        print("在請求鈎子中判斷請求的視圖邏輯: hello")

    print("handle_teardown_request 被執行")

    return response

 

5. Flask-Script擴展命令行

pip install Flask-Script

 

from flask import Flask
from flask_script import Manager

app = Flask(__name__)

manager = Manager(app)

@app.route('/')
def index():
    return '床前明月光'

if __name__ == "__main__":
    manager.run()    ...

python 10_flask_script.py --help

python 10_flask_scrip.py runserver

>>> app.url_map

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM