Python Rest客户端api上传文件

Mal*_*amy 2 python api rest upload

我正在使用Python 2.7。我的 Rest 服务器端 API 工作正常,我可以使用 Postman 上传 zip 文件。我正在尝试使用 Rest 客户端 api 上传 zip 文件。我尝试了请求包,但无法发送文件。我收到错误:缺少文件参数。

这是我的 python 服务器端代码:

@ns.route('/upload_file', strict_slashes=False)
class Upload(Resource):
    @api.expect(upload_parser)
    def post(self):

        args = upload_parser.parse_args()
        file_nameup = args.file.filename 
Run Code Online (Sandbox Code Playgroud)

这是其余的 api 客户端代码:

import requests
from requests.auth import HTTPBasicAuth
import json

headers={'Username': 'abc@gmail.com', 'apikey':'123-e01b', 'Content-Type':'application/zip'}
f = open('C:/Users/ADMIN/Downloads/abc.zip', 'rb')

files = {"file": f}

resp = requests.post("https://.../analytics/upload_file", files=files, headers=headers )

print resp.text   

print "status code " + str(resp.status_code)

if resp.status_code == 200:
    print ("Success")
    print resp.json()
else:
    print ("Failure")
Run Code Online (Sandbox Code Playgroud)

这是我的错误:{"message":"输入有效负载验证失败","errors":{"file":"上传的文件中缺少必需的参数"}状态代码 400 失败

在邮递员中,我传递了一个 zip 文件,其正文中以“file”作为键,值作为 abc.zip 文件。效果很好。我尝试使用 httplib 库,但失败,因为我的帖子 url 不包含端口号。这是 httplib 的错误:

python HttpClientEx.py Traceback(最近一次调用):文件“HttpClientEx.py”,第 4 行,在 h = http.client.HTTPConnection(url) 文件“c:\python27\Lib\httplib.py”,第 736 行, in init (self.host, self.port) = self._get_hostport(host, port) File "c:\python27\Lib\httplib.py", line 777, in _get_hostport raise InvalidURL("nonnumeric port: '%s' " % host[i+1:]) httplib.InvalidURL: 非数字端口: '// ....net/analytics/upload_file'

如何调用 Rest url post 并使用 urllib 库上传文件。请建议在休息客户端上传文件的任何其他方法。谢谢。

我发现了另一个重复的帖子:

Python 请求 - 使用 multipart/form-data 发布 zip 文件

那里提到的解决方案不起作用。我发现需要提供文件的完整路径,否则无法工作。

eat*_*ish 5

使用 urllib3 模块。

https://urllib3.readthedocs.io/en/latest/user-guide.html

文件和二进制数据

对于使用 multipart/form-data 编码上传文件,您可以使用与表单数据相同的方法,并将文件字段指定为 (file_name, file_data) 的元组:

with open('example.txt') as fp:
    file_data = fp.read()
r = http.request(
    'POST',
    'http://httpbin.org/post',
    fields={ 
        'filefield': ('example.txt', file_data),
    })

json.loads(r.data.decode('utf-8'))['files']
Run Code Online (Sandbox Code Playgroud)