我正在尝试为即将推出的API创建一个Python Wrapper,到目前为止,我一直相处得很好,但我一直在碰到同样的问题。在发出POST请求以通过API向游戏添加mod时,我将以下dict项提供给POST请求
{'name': "Necro's Test Mod", 'name_id': None, 'summary': "This is a test mod submitted through the API using python's request library.", 'description': "I'm only about 43% sure this will actually work, whats more likely is that it will fail and return some messed up error with some even weirder error message before i am contacted by the mod.io developper saying they have personally revoked my api key (This isn't actually true i just need words", 'homepage': 'www.edain.wikia.com', 'metadata_blob': 'None', 'stock': 1, 'tags': ['cool', 'python', 'api'], 'logo': <_io.BufferedReader name='C:\\Users\\Clement\\Pictures\\Background\\7z6cSaI-lord-of-the-rings-wallpaper-hd.jpg'>}
这个词典添加如下
BASE_PATH = "https://api.test.mod.io/v1"
headers = {
'Authorization': 'Bearer ' + client.access_token,
'Content-Type': 'multipart/form-data',
'Accept': 'application/json'
}
r = requests.post(BASE_PATH + '/games/181/mods'.format(self.id), files = dict, headers = headers)
然而,它返回以下回溯,让我相信API返回空白响应
Traceback (most recent call last):
File "C:\Users\Clement\Desktop\mod.io\test.py", line 40, in <module>
new_mod = game.add_mod(newmod)
File "C:\Users\Clement\Desktop\mod.io\modio\game.py", line 83, in add_mod
r = requests.post(BASE_PATH + '/games/{}/mods'.format(self.id), files = mod.__dict__, headers = headers)
File "C:\Users\Clement\AppData\Local\Programs\Python\Python36\lib\site-packages\requests\api.py", line 112, in post
return request('post', url, data=data, json=json, **kwargs)
File "C:\Users\Clement\AppData\Local\Programs\Python\Python36\lib\site-packages\requests\api.py", line 58, in request
return session.request(method=method, url=url, **kwargs)
File "C:\Users\Clement\AppData\Local\Programs\Python\Python36\lib\site-packages\requests\sessions.py", line 494, in request
prep = self.prepare_request(req)
File "C:\Users\Clement\AppData\Local\Programs\Python\Python36\lib\site-packages\requests\sessions.py", line 437, in prepare_request
hooks=merge_hooks(request.hooks, self.hooks),
File "C:\Users\Clement\AppData\Local\Programs\Python\Python36\lib\site-packages\requests\models.py", line 308, in prepare
self.prepare_body(data, files, json)
File "C:\Users\Clement\AppData\Local\Programs\Python\Python36\lib\site-packages\requests\models.py", line 496, in prepare_body
(body, content_type) = self._encode_files(files, data)
File "C:\Users\Clement\AppData\Local\Programs\Python\Python36\lib\site-packages\requests\models.py", line 159, in _encode_files
fdata = fp.read()
AttributeError: 'NoneType' object has no attribute 'read'
这是我正在尝试的特定POST请求的documentation。
答案 0 :(得分:0)
files
参数用于文件上传。您可能希望在此使用data
。
r = requests.post(
BASE_PATH + '/games/181/mods'.format(self.id),
data = dict,
headers = headers
)
您收到此错误,因为请求期望name_id
的值为具有read()
方法的文件指针。但是在你的有效载荷中它是None
。
并且不要使用dict
作为变量名称。