python - Converting cURL POST into urllib2 without Requests -


i have curl command works in environment. need convert python 2.7 urllib equivalent , need assistance

curl command in question:

curl -k -v -xpost -h "authorization: bearer $token" -f file=@${local_filename} https://interesting_url.com/ 

i need ability support both header (-h) , form/file (-f) , have yet successful.

this post includes discussion on headers, have not been able '-f' equivalent working

with python3 can requests:

import requests  headers = {'authorization': 'bearer $token'}  files = [('file', open('${local_filename}', 'rb'))]  requests.post('https://interesting_url.com/', headers=headers, files=files, verify=false) 

uploading files urllib2 quite complicated task (example). suggest requests.

long answer without using pip , third-party packages

you can implement custom class multipartform , use encode files:

import itertools import mimetools import mimetypes cstringio import stringio import urllib import urllib2  class multipartform(object):     """accumulate data used when posting form."""      def __init__(self):         self.form_fields = []         self.files = []         self.boundary = mimetools.choose_boundary()         return      def get_content_type(self):         return 'multipart/form-data; boundary=%s' % self.boundary      def add_field(self, name, value):         """add simple field form data."""         self.form_fields.append((name, value))         return      def add_file(self, fieldname, filename, filehandle, mimetype=none):         """add file uploaded."""         body = filehandle.read()         if mimetype none:             mimetype = mimetypes.guess_type(filename)[0] or 'application/octet-stream'         self.files.append((fieldname, filename, mimetype, body))         return      def __str__(self):         """return string representing form data, including attached files."""         # build list of lists, each containing "lines" of         # request.  each part separated boundary string.         # once list built, return string each         # line separated '\r\n'.           parts = []         part_boundary = '--' + self.boundary          # add form fields         parts.extend(             [ part_boundary,               'content-disposition: form-data; name="%s"' % name,               '',               value,             ]             name, value in self.form_fields             )          # add files upload         parts.extend(             [ part_boundary,               'content-disposition: file; name="%s"; filename="%s"' % \                  (field_name, filename),               'content-type: %s' % content_type,               '',               body,             ]             field_name, filename, content_type, body in self.files             )          # flatten list , add closing boundary marker,         # return cr+lf separated data         flattened = list(itertools.chain(*parts))         flattened.append('--' + self.boundary + '--')         flattened.append('')         return '\r\n'.join(flattened)  open(`local_file.txt`) f:     form = multipartform()     form.add_file('file', `local_file`,                    filehandle=f)      # build request     request = urllib2.request('https://interesting_url.com/')     request.add_header('authorization', 'bearer $token')     body = str(form)     request.add_header('content-type', form.get_content_type())     request.add_header('content-length', len(body))     request.add_data(body)      print     print 'outgoing data:'     print request.get_data()      print     print 'server response:'     print urllib2.urlopen(request).read() 

the source


Comments

Popular posts from this blog

ios - MKAnnotationView layer is not of expected type: MKLayer -

ZeroMQ on Windows, with Qt Creator -

unity3d - Unity SceneManager.LoadScene quits application -