使用Python请求模块上传文件

时间:2014-09-08 19:29:54

标签: python python-requests

我需要使用soap端点url加载文件...当我使用下面的代码加载它时,文件正在加载,但它们不是可读的格式...当我使用SOAPUI工具加载时,它加载正确...

import requests

xml = '''<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
                xmlns:v1="http://s.sa.com/services/Attachment/v1.0">
   <soapenv:Header/>
   <soapenv:Body>
      <v1:attachment>
         <filename>FUZZY.csv</filename>
         <data>cid:138641430598</data>
      </v1:attachment>
   </soapenv:Body>
</soapenv:Envelope>'''
target_url =  'https://s.sa.com:443/soatest/FileAttachmentService'
headers = {'Content-Type': 'text/xml','charset':'utf-8'}
r = requests.post(target_url,data=xml,headers=headers,auth=('3user1',''))
print 'r.text = ', r.text
print 'r.content = ', r.content
print 'r.status_code = ', r.status_code

新变化: -

files = {'file':open('./FUZZY.csv','rb')}
print files
r = requests.post(target_url,files=files,data=xml,headers=headers,auth=('p3user1',''))

错误:

Traceback (most recent call last):
  File "soapcall_python.py", line 18, in <module>
    r = requests.post(target_url,files=files,data=xml,headers=headers,auth=('p3user1',''))
  File "/opt/python2.7/lib/python2.7/site-packages/requests-2.3.0-py2.7.egg/requests/api.py", line 88, in post
    return request('post', url, data=data, **kwargs)
  File "/opt/python2.7/lib/python2.7/site-packages/requests-2.3.0-py2.7.egg/requests/api.py", line 44, in request
    return session.request(method=method, url=url, **kwargs)
  File "/opt/python2.7/lib/python2.7/site-packages/requests-2.3.0-py2.7.egg/requests/sessions.py", line 418, in request
    prep = self.prepare_request(req)
  File "/opt/python2.7/lib/python2.7/site-packages/requests-2.3.0-py2.7.egg/requests/sessions.py", line 356, in prepare_request
    hooks=merge_hooks(request.hooks, self.hooks),
  File "/opt/python2.7/lib/python2.7/site-packages/requests-2.3.0-py2.7.egg/requests/models.py", line 297, in prepare
    self.prepare_body(data, files)
  File "/opt/python2.7/lib/python2.7/site-packages/requests-2.3.0-py2.7.egg/requests/models.py", line 432, in prepare_body
    (body, content_type) = self._encode_files(files, data)
  File "/opt/python2.7/lib/python2.7/site-packages/requests-2.3.0-py2.7.egg/requests/models.py", line 109, in _encode_files
    raise ValueError("Data must not be a string.")
ValueError: Data must not be a string.

1 个答案:

答案 0 :(得分:2)

您无法在任何地方发送文件内容。您只是发送一个文件的引用,该文件在服务器可以看到的任何地方都不存在。

正如SOAP references to attachments的文档所解释的那样,执行此操作的方法是发送MIME-multipart消息。如果您正在使用CID引用机制,cid不是某个任意字符串,则必须匹配MIME信封中邮件的Content-ID标头。

POST a Multipart-Encoded Filerequests个文档解释了如何在MIME请求中将文件内容作为消息发送;简要地:

with open('FUZZY.csv', 'rb') as f:
    files = {'file': f}
    r = requests.post(target_url,
                      data=xml, headers=headers, auth=('3user1',''), 
                      files=files)

但是,这种简单的方法无法让您访问将在邮件封面下生成的Content-ID。因此,如果您想使用CID参考机制,则需要手动生成MIME信封(例如,使用email.mail.MIMEMultipart)并将整个内容作为data字符串发送。