lqshow
10/15/2017 - 3:40 PM

requests

python requests

使用requests

import requests

请求类型

类型requests方式
OPTIONSrequests.options
HEADrequests.head
GETrequests.get
PUTrequests.put
POSTrequests.post
DELETErequests.delete

传递URL参数

payload = {'key1': 'value1', 'key2': ['value2', 'value3']}
r = requests.get('http://httpbin.org/get', params=payload)

响应内容

文本

import json
response = r.text
response = json.loads(response)

JSON

response = r.json()

原始响应内容

r = requests.get('https://github.com/timeline.json', stream=True)
print(r.raw)

POST请求

表单形式

payload = {'key1': 'value1', 'key2': 'value2'}
r = requests.post("http://httpbin.org/post", data=payload)
print(r.text)

# output
#       {
#         ...
#         "form": {
#           "key2": "value2",
#           "key1": "value1"
#         },
#         ...
#       }

字符串形式

payload = {'some': 'data'}
url = 'http://httpbin.org/post'
r = requests.post(url, json=payload)
r = requests.post(url, data=json.dumps(payload))

# output
#       {
#           "data": "{\"some\": \"data\"}",
#           "json": {
#               "some": "data"
#             }
#       }

服务器响应

状态码

r.status_code

响应头

r.headers

Reference