Raul2018

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

From: https://mp.weixin.qq.com/s/QgGyn2efYtVKI65RwXoiEA

------------------------------------------------------------------------------------

import pytest
import json
import requests
from requests.auth import HTTPBasicAuth
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.util.retry import Retry

class Test_Json_And_Requests:

def test_1json(self):
# 创建JSON数据
data = {
"name": "John",
"age": 30,
"city": "New York"
}
json_data = json.dumps(data) # 将Python对象转换为JSON字符串
print(json_data) # 输出:{"name": "John", "age": 30, "city": "New York"}
# 解析JSON数据
json_string = '{"name": "Jane", "age": 28, "city": "San Francisco"}'
parsed_data = json.loads(json_string) # 将JSON字符串转换为Python字典
print(parsed_data) # 输出:{'name': 'Jane', 'age': 28, 'city': 'San Francisco'

def test_2requests(self):
response = requests.get('https://api.github.com')
print(response.status_code) # 输出HTTP状态码,如:200
print(response.json()) # 输出响应体内容(假设响应是JSON格式)
# 保存完整的响应信息
with open('github_response.json', 'w') as f:
json.dump(response.json(), f)

def test_3get(self):
params = {'q': 'Python requests', 'sort': 'stars'}
response = requests.get('https://api.github.com/search/repositories', params=params)
repos = response.json()['items']
for repo in repos[:5]: # 打印前5个搜索结果
print(repo['full_name'])

def test_4post(self):
payload = {'key1': 'value1', 'key2': 'value2'}
headers = {'Content-Type': 'application/json'}
response = requests.post('http://httpbin.org/post', json=payload, headers=headers)
print(response.json())

def test_5timeout(self):
requests.get('https://api.github.com', timeout=2) # 设置超时时间为2秒

def test_6deal_cookies(self):
# 保存cookies
response = requests.get('https://api.github.com')
cookies = response.cookies
# 发送带有cookies的请求
res = requests.get('https://api.github.com', cookies=cookies)
print(res.json())
assert len(res.json()) > 1

def test_7http_headers(self):
headers = {'User-Agent': 'My-Custom-UA'}
response = requests.get('http://httpbin.org/headers', headers=headers)
print(response.text)

def test_8downlaod_files(self):
url = r'https://example.com/image.jpg' # should use an available url
response = requests.get(url)
# 写入本地文件
with open('image.jpg', 'wb') as f:
f.write(response.content)

def test_9authtication(self):
response = requests.get('http://test-gssc-rs.gwm.cn:9800/#/login', auth=HTTPBasicAuth('98702085', 'xx'))
print(response.json())

def test_10retry(self):
# 创建一个重试策略
retry_strategy = Retry(
total=3,
status_forcelist=[429, 500, 502, 503, 504],
backoff_factor=1,
)
# 添加重试策略到适配器
adapter = HTTPAdapter(max_retries=retry_strategy)
# 将适配器添加到会话
session = requests.Session()
session.mount('http://', adapter)
session.mount('https://', adapter)
response = session.get('https://api.github.com')

if __name__ == '__main__':
Test_Json_And_Requests().test_10retry()
posted on 2024-04-28 20:26  Raul2018  阅读(4)  评论(0编辑  收藏  举报