首页 > 解决方案 > 通过 python 请求上传图像时出现错误 400(错误请求)

问题描述

我正在尝试通过 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": "child 'filename' failed because ['filename' is required]"\n }', '_content_consumed': True, '_next': None, 'status_code': 400, 'headers': {'Date': 'Fri, 26 Jun 2020 13:41:02 GMT', 'Content-Type': '应用程序/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': <urllib3.response.HTTPResponse object at 0x7f51f39c80a0>, 'url': 'https://api .sirv.com/v2/files/upload', 'encoding': 'utf-8', 'history': [], 'reason': 'Bad Request', 'cookies': <RequestsCookieJar[]>, 'elapsed ': datetime.timedelta(seconds=7, microseconds=408883), 'request': <PreparedRequest [POST]>, 'connection': <requests.adapters.HTTPAdapter object at 0x7f51f44422b0>}

从错误中,我怀疑服务器以某种方式没有检测到我的文件名参数。我使用这个文档作为查询 API 的指南。

摘要:我需要帮助来理解为什么会出现错误。

标签: pythonapiresthttpserver

解决方案


我得到了 Sirv 团队的一些帮助。原来,Sirv REST API 不仅需要本地文件的路径,还需要上传文件的路径。就我而言,我只声明了本地文件的路径。结果,服务器抛出了状态码 400,以及此消息;

子 'filename' 失败,因为 ['filename' is required]"

这是满足所有要求的修改代码;

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)

推荐阅读