前言
在将API接口写好后供第三方使用前,需要自己先对所写之接口进行自测,经过尝试可行后,将方法记录如下。
登录
import requests
login_url = r'http://*****'
method = 'POST'
login_data = {'account': '****, 'password': '****'}
login_headers = {'Content-Type': 'application/json'}
response = requests.request(method, login_url, json=login_data, headers=login_headers)
print(response.status_code)
print(response.request.url)
print(response.request.body)
print(response.text)
print('over')
打印出来的结果如下,表示已登录成功
200
http://******
b'{"account": "*****", "password": "****"}'
{"success":true,"code":1,"title":"创建成功","message":{"expiresIn":****,"accessToken":"********"}}
over
上传文件
import os
import json
from requests_toolbelt import MultipartEncoder
upload_url = r'http://****'
file_path = r'C:/Users/ADMIN/Pictures/Camera Roll/yueji.jpg'
_, file_name = os.path.split(file_path)
token = json.loads(response.text)['message']['accessToken']
token = "Bearer" + " " + token
data_body = MultipartEncoder(fields=
{'key1': 'value1',
'key2': 'value2',
'key3': 'value3',
'img': (file_name, open(file_path, 'rb'), 'image/jpeg')
}
)
upload_headers = {"authorization": token,
'Content-Type': data_body.content_type}
res = requests.request(method, upload_url, data=data_body, headers=upload_headers)
print(res.status_code)
print(res.request.url)
print(res.request.body)
print(res.text)
print('over')
打印结果如下:
200
http://****
<MultipartEncoder: {'key1': 'value1',
'key2': 'value2',
'key3': 'value3',
'img': ('yueji.jpg', <_io.BufferedReader name='C:/Users/ADMIN/Pictures/Camera Roll/yueji.jpg'>, 'image/jpeg')}>
{"success":true,"code":1,"title":"保存数据成功","message":"上传成功"}
over
打印结果表明文件已上传成功。
END
参考资料
|