Pythonリクエストrequests,request
31029 ワード
1 request
1.1 getリクエスト
1.2 post要求
2 requests
2.1要求方式
シーケンス番号
リクエストモード
説明
1
HEAD
要求ページヘッダ
2
GET
指定したページ情報を要求し、エンティティ本体に戻ります.
3
POST
指定されたリソースにデータを送信して処理要求を行い、データが要求体に含まれている場合、POST要求は新しいリソースの確立または既存のリソースの変更を引き起こす可能性がある.
4
PUT
指定したドキュメントの内容の代わりに、クライアントからサーバに送信されるデータ
5
DELETE
リクエストサーバ指定ページの削除
2.2要求データ get post
2.2.1辞書型データ
2.2.2 jsonデータ
2.2.3 form-dataデータ結果情報
2.3応答内容
シーケンス番号
応答内容
説明
1
res.encoding
現在のエンコーディングの取得
2
res.encoding=‘utf-8’
エンコーディングの設定
3
res.text
戻り内容をencodingで解析し、戻りデータ型を文字列とする
4
res.content
バイト形式bytesで応答体を返す
5
res.headers
サーバ応答ヘッダをディクショナリオブジェクトで格納します.このディクショナリは特殊です.ディクショナリのキーは大文字と小文字を区別しません.キーが存在しない場合はNoneを返します.
6
res.status_code
レスポンスステータスコード
7
res.raw
元の応答体とurllibのresponseオブジェクトを返し、res.rawを使用します.read
8
res.ok
res.okのブール値を表示して、ログインが成功したかどうかを確認します.
9
res.json
リクエスト内容をjson形式で返し、ディクショナリタイプdictを返します.
10
res.raise_for_status()
失敗したリクエスト(200以外の応答)が例外を放出
2.4戻りデータ requests.models.Response形式 dictフォーマット strフォーマット flask.wrappers.Response形式(Json形式) flask.wrappers.Response形式(Json形式)
2.5ヘッダ情報及び要求体データ取得
2.5.1シーン
クライアント:要求サービス側、携帯ヘッダ情報と要求体情報;サービス側:クライアントの要求を受け入れ、クライアントが携帯するヘッダ情報と要求体情報を取得する.
2.5.2応用クライアントclient.py サービス側server.py プロセス実行サービス:
クライアントの実行結果
3 urllib
urlを要求し、パラメータモジュールを解析します.
3.1 py 2およびpy 3リクエストモジュール
python 3使用:urllib.request python 2使用:urllib 2
3.2ソース
【python2:urllib2】
【Result】
【python3:urllib.request】
【Result】
4まとめ flaskはrequestおよびrequests要求によって異なるパラメータを取得するために使用される. requestはflask内蔵で、ユーザー入力パラメータを取得します. requests urlパラメータを取得します. pythonバックグラウンドは文字列を返す必要があり、基本的にjson文字列を主とする. python 2要求url使用モジュール:urllib 2、要求結果直接read()メソッドは文字列に解析される. python 3要求url使用モジュール:urllib.リクエスト結果はread()メソッドを用いてbytesとして解析され、decode(「utf-8」)を文字列として復号する必要がある.
[参考文献][1]https://blog.csdn.net/mr_evanchen/article/details/77879967 [2]https://www.cnblogs.com/insane-Mr-Li/p/9145152.html [3]https://blog.csdn.net/z714405489/article/details/83061867 [4]https://www.cnblogs.com/derek1184405959/p/8448875.html
更新ing
1.1 getリクエスト
from flask import request
#get
variable = 'abcd'
request.args.get('variable')
#form
<form>
<input name="variable" type="text">
</form>
request.form.get('variable')
# json
{
"key":"xindaqi"
}
request.json.get("key")
1.2 post要求
from flask import request
{'variable':'abce', 'v':'value1'}
request.json['variable']
request.form['variable']
2 requests
2.1要求方式
シーケンス番号
リクエストモード
説明
1
HEAD
要求ページヘッダ
2
GET
指定したページ情報を要求し、エンティティ本体に戻ります.
3
POST
指定されたリソースにデータを送信して処理要求を行い、データが要求体に含まれている場合、POST要求は新しいリソースの確立または既存のリソースの変更を引き起こす可能性がある.
4
PUT
指定したドキュメントの内容の代わりに、クライアントからサーバに送信されるデータ
5
DELETE
リクエストサーバ指定ページの削除
2.2要求データ
res = requests.get(url, data=None, json=None, headers=headers, **kwargs)
url:
data: ,
json: ,json
headers: ,json
**kwargs:request
res = requests.post(url, data=None, json=None, headers=headers, **kwargs)
url:
data: ,
json: ,json
headers: ,json
**kwargs:request
2.2.1辞書型データ
import requests
data = {'key1':'value1', 'key2':'value2'}
res = requests.post(url, data=data)
2.2.2 jsonデータ
import requests, json
data = {'key1':'value1','data':{'key2':'value2'}}
headers = {"X-AuthToken":"from client"}
res = request.post(url, json=data, headers=headers)
2.2.3 form-dataデータ
import requests, json
url = "object url"
data = {
"name":(None, "xindaqi"),
"sex":(None, "male")
"image":("image.jpg", open("./path/image.jpg", "rb"))
}
res = requests.post(url, data=data)
print("Request body: {}".format(res.request.body))
print("Request headers: {}".format(res.request.headers))
Request body: name=xindaqi&sex=male
Request headers: {'User-Agent': 'python-requests/2.18.4', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive', 'Content-Length': '84', 'Content-Type': 'application/x-www-form-urlencoded'}
2.3応答内容
シーケンス番号
応答内容
説明
1
res.encoding
現在のエンコーディングの取得
2
res.encoding=‘utf-8’
エンコーディングの設定
3
res.text
戻り内容をencodingで解析し、戻りデータ型を文字列とする
4
res.content
バイト形式bytesで応答体を返す
5
res.headers
サーバ応答ヘッダをディクショナリオブジェクトで格納します.このディクショナリは特殊です.ディクショナリのキーは大文字と小文字を区別しません.キーが存在しない場合はNoneを返します.
6
res.status_code
レスポンスステータスコード
7
res.raw
元の応答体とurllibのresponseオブジェクトを返し、res.rawを使用します.read
8
res.ok
res.okのブール値を表示して、ログインが成功したかどうかを確認します.
9
res.json
リクエスト内容をjson形式で返し、ディクショナリタイプdictを返します.
10
res.raise_for_status()
失敗したリクエスト(200以外の応答)が例外を放出
2.4戻りデータ
res = requests.post(url, json=data)
print(type(res))
#
<class 'requests.models.Response'>
res = requests.post(url, json=data)
res = res.json()
print(type(res))
#
<class 'dict'>
res = requests.post(url, json=data)
res = res.json()
res = json.dumps(res)
print(type(res))
#
<class 'str'>
res = requests.post(url, json=data)
res = res.json()
res = json.dumps(res)
res = Response(res, mimeType="application/json")
print(type(res))
#
<class 'flask.wrappers.Response'>
import requests
from flask import jsonify
res = requests.post(url, json=data)
res = res.json()
res = jsonify(res)
print(type(res))
#
<class 'flask.wrappers.Response'>
2.5ヘッダ情報及び要求体データ取得
2.5.1シーン
クライアント:要求サービス側、携帯ヘッダ情報と要求体情報;サービス側:クライアントの要求を受け入れ、クライアントが携帯するヘッダ情報と要求体情報を取得する.
2.5.2応用
import requests
url = "http://127.0.0.1:8090/api/header-infos"
data = {"name":"xiaohong", "address":"heilongjiang"}
headers = {"X-AuthToken":"from client"}
res = requests.post(url, json=data, headers=headers)
from flask import Flask, request, Blueprint
from flask_cors import CORS
header_infos = Blueprint("header_info", __name__, url_prefix="/api")
@header_infos.route("/header-infos", methods=["GET", "POST"])
def header_test():
'''
headers: Cache-Control: no-cache
Postman-Token: f5c59a9a-475d-466b-bb2d-64c48ad8f07a
User-Agent: PostmanRuntime/7.2.0
Accept: */*
Host: localhost:8090
Cookie: JSESSIONID=F86435226AF347A3890C6D2D5CE39ED8
Accept-Encoding: gzip, deflate
Connection: keep-alive
'''
header_full_infos = request.headers
# reqeuest header information
header_authentication = header_full_infos["X-AuthToken"]
# reqeust body information
request_body = request.json["name"]
print("header full information:
{}".format(header_full_infos))
print("type of headers:
{}".format(type(header_full_infos)))
print("Header authentication:
{}".format(header_authentication))
print("Body:
{}".format(request_body))
return "success"
def init_app():
app = Flask(__name__)
app.register_blueprint(header_infos)
return app
app = init_app()
CORS(app, supports_credentials=True)
if __name__ == "__main__":
app.run(host="0.0.0.0", port=8090, debug=True)
python3.6 server.py
クライアントの実行
python3.6 client.py
header full information:
Host: 127.0.0.1:8090
User-Agent: python-requests/2.22.0
Accept-Encoding: gzip, deflate
Accept: */*
Connection: keep-alive
X-Authtoken: from client
Content-Length: 47
Content-Type: application/json
type of headers:
Header authentication:
from client
Body:
xiaohong
3 urllib
urlを要求し、パラメータモジュールを解析します.
3.1 py 2およびpy 3リクエストモジュール
python 3使用:urllib.request python 2使用:urllib 2
3.2ソース
【python2:urllib2】
def py2request(url):
import urllib2
response = urllib2.urlopen(url)
response = response.read()
return type(response), response
if __name__ == "__main__":
url = "https://gist.githubusercontent.com/aaronmarkham/cd3a6b6ac071eca6f7b4a6e40e6038aa/raw/9edb4038a37da6b5a44c3b5bc52e448ff09bfe5b/alexnet_codes"
# type_res, res = py2request(url)
type_res, res = py3request(url)
print("type of response: {}
resposne: {}".format(type_res, res))
【Result】
type of response:
resposne: {
0: 'tench, Tinca tinca',
1: 'goldfish, Carassius auratus',
2: 'great white shark, white shark, man-eater, man-eating shark, Carcharodon carcharias',
3: 'tiger shark, Galeocerdo cuvieri',
4: 'hammerhead, hammerhead shark',
}
【python3:urllib.request】
def py3request(url):
import urllib.request
# url
response = urllib.request.urlopen(url)
# ,bytes
response = response.read()
return type(response), response
if __name__ == "__main__":
url = "https://gist.githubusercontent.com/aaronmarkham/cd3a6b6ac071eca6f7b4a6e40e6038aa/raw/9edb4038a37da6b5a44c3b5bc52e448ff09bfe5b/alexnet_codes"
# type_res, res = py2request(url)
type_res, res = py3request(url)
print("type of response: {}
resposne: {}".format(type_res, res))
# python3 ,
response = res.decode("utf-8")
print("Response: {}".format(response))
【Result】
type of response:
resposne: b'{
0: \'tench, Tinca tinca\',
1: \'goldfish, Carassius auratus\',
2: \'great white shark, white shark, man-eater, man-eating shark, Carcharodon carcharias\',
3: \'tiger shark, Galeocerdo cuvieri\',
4: \'hammerhead, hammerhead shark\',}
Response: {
0: 'tench, Tinca tinca',
1: 'goldfish, Carassius auratus',
2: 'great white shark, white shark, man-eater, man-eating shark, Carcharodon carcharias',
3: 'tiger shark, Galeocerdo cuvieri',
4: 'hammerhead, hammerhead shark',}
4まとめ
[参考文献][1]https://blog.csdn.net/mr_evanchen/article/details/77879967 [2]https://www.cnblogs.com/insane-Mr-Li/p/9145152.html [3]https://blog.csdn.net/z714405489/article/details/83061867 [4]https://www.cnblogs.com/derek1184405959/p/8448875.html
更新ing