我正在尝试通过python请求将图像上传到Sirv。这是我到目前为止所拥有的;
def upload_files(access_token, filename):
endpoint = "https://api.sirv.com/v2/files/upload"
headers = {'Content-Type' : 'application/json', 'authorization': 'bearer {}'.format(access_token)}
send_request = requests.post(endpoint, headers = headers, data = filename)
return send_request
access_token = "MY_ACCESS_TOKEN"
filename = {'filename': ('oldman.jpg', open('oldman.jpg', 'rb'))}
upload_files(access_token, filename)
我了解http状态代码。但是,我不明白我在做错什么,导致服务器抛出400。这是我得到的完整答复;
{'_ content':b'{\ n“ statusCode”:400,\ n“ error”:“ Bad Request”,\ n“ message”:“子'filename'失败,因为['filename'是 必填]“ \ n}','_ content_consumed':真,'_next':无, 'status_code':400,'headers':{'Date':'Fri,26 Jun 2020 13:41:02 GMT”,“ Content-Type”:“ application / json; charset = utf-8', 'Content-Length':'121','Connection':'keep-alive', 'access-control-allow-origin':'','access-control-expose-headers': '','cache-control':'no-cache','Server':'Sirv.API'},'raw':
,'url': 'https://api.sirv.com/v2/files/upload','encoding':'utf-8', “历史记录”:[],“原因”:“错误请求”,“ Cookie”: ,“经过”:datetime.timedelta(seconds = 7, 微秒= 408883),“请求”: , '连接': }
从该错误中,我怀疑服务器以某种方式未检测到我的文件名参数。 我使用this doc作为查询API的指南。
摘要:我需要帮助来了解为什么会出现错误。
答案 0 :(得分:0)
尝试一下:
def upload_files(access_token, filename):
endpoint = "https://api.sirv.com/v2/files/upload"
headers = {
"authorization": "bearer {}".format(access_token),
}
send_request = requests.post(endpoint, headers=headers, files=filename)
return send_request
尝试从标题中删除content-type
,它将由requests
库自动设置。
答案 1 :(得分:0)
我从Sirv团队那里得到了一些help。 事实证明,Sirv REST API不仅需要本地文件的路径,还需要上传文件的路径。就我而言,我只声明了本地文件的路径。结果,服务器随此消息一起抛出了状态代码400;
子级'文件名'失败,因为['文件名'是必需的”“
这是满足所有要求的修改后的代码;
def upload_files(access_token, local_file, upload_path):
endpoint = "https://api.sirv.com/v2/files/upload"
headers = {'Content-Type' : 'image/jpeg', 'authorization': 'bearer {}'.format(access_token)}
upload_path = {'filename': upload_path}
sirv_api_request = requests.post(endpoint, headers = headers, data = local_file, params = upload_path)
return sirv_api_request
local_file = open('oldman.jpg', 'rb')
upload_path = '/myfolder/oldman.jpg'
upload_file(access_token, local_file, upload_path)