使用 https://www.cnblogs.com/caroline2016/p/17007956.html 建立的api测试下requests库怎么使用。
模拟登录时laravel api那边出现了 Session store not set on request. 错误。解决办法在app/Http/Kernel.php 中 api 中间件组中添加两行代码:
<?php
protected $middlewareGroups = [
...
'api' => [
...
\App\Http\Middleware\EncryptCookies::class, // <------- 添加的代码
\Illuminate\Session\Middleware\StartSession::class, // <------ 添加的代码
],
];
demo
import requests
import concurrent.futures
import requests.adapters
from requests.auth import HTTPBasicAuth
url = "http://127.0.0.1:8000"
url_get = "http://127.0.0.1:8000/api/data/getPoem?p=1"
url_post = "http://127.0.0.1:8000/login"
# 设置请求头
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36",
}
headers_api = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36",
"Authorization": "Bearer 69|3eSTphCsfIrv1gOg3fGqNmwouJEpRwxymUc6Bvt3",
}
params = {}
response = requests.get(url_get, headers=headers_api, params=params)
if response.status_code == 200:
# 查看响应码
print(response.status_code) # 200
# 查看完整url地址
print(response.url) # http://127.0.0.1:8000/api/data/getPoem?p=1
# 查看响应头部字符编码
print(response.encoding) # utf-8
# 查看响应头
print(response.headers)
# 查看cookies
print(response.cookies)
# 查看响应内容,返回Unicode格式的数据
print(response.text)
# 查看响应内容,返回字节流数据
print(response.content)
# 查看响应内容,返回JSON响应内容
print(response.json())
# 查看响应内容,返回原始响应内容
print(response.raw) # <urllib3.response.HTTPResponse object at 0x000001E38C6F00A0>
# 转换编码
response.encoding = "utf-8"
# cookies
cookiejar = response.cookies
cookiedict = requests.utils.dict_from_cookiejar(cookiejar)
print("cookiedict", cookiedict) # {'laravel_session': 'VS6SDGagCeub2h9c4WYzODpLGBERCJNiz2r78ZE1'}
# 会话管理
data = {"key": "[email protected]", "password": "12345678"}
session = requests.session()
session.headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36",
}
response1 = session.get(url)
response2 = session.post(url_post, data=data) # 模拟登录
r = session.get(url_get)
if r.status_code == 200:
print(response2.text) # {"token":"73|gxwyT2nV6RGLO7EuT6cncXaPryTTgouxyGTsIb7U","code":0,"userinfo":{"name":"bb","email":"[email protected]"}}
# 身份验证
response = requests.post(url_post, auth=HTTPBasicAuth("username", "password"), headers=headers)
if response.status_code == 200:
print(response.text)
# 代理设置
proxy = {"http": "http://username:password@ip:port"}
proxy = {"http": "http://ip:port"}
response = requests.get(url_get, proxies=proxy)
# SSL验证
response = requests.get("https://www.baidu.com/", verify=True)
print("verify", response)
# 错误处理
try:
response = requests.get(url_get, timeout=1, headers=headers_api)
response.raise_for_status()
except requests.exceptions.ConnectionError:
print("connect error")
except requests.exceptions.Timeout:
print("time out")
except requests.exceptions.HTTPError as err:
print("server error:", err)
else:
print("get data")
# 连接池
session = requests.session()
adapter = requests.adapters.HTTPAdapter(pool_connections=100, pool_maxsize=100)
session.mount("http://", adapter=adapter)
response = session.get(url_get)
# 持久连接
response = session.get(url_get, headers={"Connection": "keep-alive"})
# 并发
def fetch_data(url):
response = requests.get(url)
return response.text
urls = ["url1", "url2"]
with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
results = executor.map(fetch_data, urls)
for result in results:
print(result)
# 其它方法
response = requests.put(url, data=data)
response = requests.delete(url)
response = requests.head(url)
response = requests.options(url)
标签:get,url,session,使用,print,requests,response,python3 From: https://www.cnblogs.com/caroline2016/p/18322608