基于HTTP協(xié)議客戶端和服務(wù)端傳遞信息通常會(huì)把具體的內(nèi)容放在四個(gè)地方。
放在url的請(qǐng)求參數(shù)中,get和post都可以,不過大部分情況下以get居多。
POST 的form中,在服務(wù)端渲染表單盛行(struts,flask_wtf)的年代,登陸,注冊(cè)等基本都是把用戶填寫的信息放在form中。
post中的json格式,現(xiàn)在最佳的實(shí)踐方案就是前后端通過restful的API,傳遞json數(shù)據(jù)來進(jìn)行通信。
還有很多時(shí)候是需要獲取http的head信息,比如一些auth信息或者referer,useragent的信息等。
獲取url和form以及header內(nèi)容
Postman 發(fā)送的http測(cè)試請(qǐng)求
POST /test?x=valueX HTTP/1.1
Host: 127.0.0.1:5000
Content-Type: application/x-www-form-urlencoded
z: valueZ
Cache-Control: no-cache
Postman-Token: bb060ed5-783e-6470-05ee-f05a71df972c
y=valueY
處理請(qǐng)求:
from flask import request
@app.route('/test', methods=['GET', 'POST'])
def test():
# 獲取 url 參數(shù)內(nèi)容
x = request.args.get("x")
# 獲取 form 表單內(nèi)容
y = request.form.get("y")
# 獲取 http 頭部?jī)?nèi)容
z = request.headers.get("z")
print("x from url param: ", x)
print("y from form param: ", y)
print("z from headers: ", z)
return "test"
獲取json內(nèi)容
發(fā)起的請(qǐng)求
POST /test HTTP/1.1
Host: 127.0.0.1:5000
Content-Type: application/json
z: valueZ
Cache-Control: no-cache
Postman-Token: 2b3e8991-a48e-1653-c6e3-1b07d7411a29
{"url": "http://dig404.com"}
處理json請(qǐng)求
@app.route('/test', methods=['GET', 'POST'])
def test():
# 獲取json格式的body,返回直接就是dict類型
content = request.get_json(silent=True)
content.get('url', None)
print(content)
return ""
如果喜歡,您就給個(gè)贊唄。