Python请求下游服务模板积累
发送json请求:
import requests
payload = {
"参数1": "xxx",
"参数2": "xxx",
"参数3": "xxx"
}
# 使用json参数
resp_json = requests.post(url, headers=headers, json=payload)
发送表单对象:
import requests
# 将Content-Type注释掉(会自动加上)
headers = {
'Accept': 'application/json, text/plain, */*',
'Connection': 'keep-alive'
}
# 表单对象(将这个对象视为四行三列的表单,因为file文件字段字段是三列,所以其他的字段他的字段也必须是)
# 这里的 参数值、文件名、二进制文件流 需要你在实际使用时定义
# 假设 参数值 是字符串,文件名 是字符串,二进制文件流 是打开文件的二进制流
# 示例:
# 参数值 = "some_value"
# 文件名 = "example.txt"
# 二进制文件流 = open("example.txt", "rb")
# Content-Type 可以根据文件类型设置,例如文本文件是 "text/plain"
file_obj = {
'参数1': (None, "参数值", None),
'参数2': (None, "参数值", None),
"参数3": (None, "参数值", None),
'file': ("文件名", "二进制文件流", "Content-Type写在这里")
}
# 注意使用files
# fds_url 需要你在实际使用时定义
# 示例:fds_url = "https://example.com/upload"
resp = requests.post("fds_url", headers=headers, files=file_obj)
你可以根据实际情况对上述代码中的变量进行赋值。如果 二进制文件流 是文件,要确保以二进制模式打开文件。例如:
with open("your_file.txt", "rb") as file:
file_obj = {
'参数1': (None, "参数值", None),
'参数2': (None, "参数值", None),
"参数3": (None, "参数值", None),
'file': ("your_file.txt", file, "text/plain")
}
resp = requests.post("your_url", headers=headers, files=file_obj)
多次尝试请求模板:
# 假设 ServiceFailed 是自定义的异常类,这里简单定义一下
class ServiceFailed(Exception):
def __init__(self, error_code, message):
self.error_code = error_code
self.message = message
super().__init__(self.message)
# 发送三次请求,直到状态返回成功为止
for _ in range(3):
resp = requests.post(url, headers=headers, json=payload)
if resp.status_code == 200:
break
time.sleep(0.3)
if resp.status_code != 200:
raise ServiceFailed(
error_code=resp.status_code,
message=f"xxx错误信息, 错误描述:{resp.text}"
)
# 解析
resp_json = resp.json()
以上内容如有错误,恳请指正

浙公网安备 33010602011771号