#! \ Urs \ bin \ env Python # encoding: UTF-8 # Set the encoding method from http2 import httpimport urllibdef readfileascontent (filename): # print filename try: with open (filename, 'rb ') as F: filecontent = f. read () failed t exception, E: Print 'the error message in readfileascontent (): '+ E. message return ''return filecontentdef get_content_type (filename): Import mimetypes return mimetypes. guess_type (filename) [0] Or 'application/octet-stream' def isfiledata (p_str): Import re r_C = Re. compile ("^ f '(. *) '$ ") rert = r_c.search (STR (p_str) # rert = Re. search ("^ f '(. *) '$ ", p_str) If rert: Return rert. group (1) else: Return none def encode_multipart_formdata (fields ): ''' this function is used to splice the content of the body in an HTTP request of multipart/form-data type to return the spliced body content and the Content-Type header definition ''' import random import OS boundary = '---------- % s' % ''. join (random. sample ('0123456789abcdef ', 15) CRLF =' \ r \ n' L = [] for (Key, value) in fields: filepath = isfiledata (value) If filepath: l. append ('--' + boundary) L. append ('content-Disposition: Form-data; name = "% s"; filename = "% s" '% (Key, OS. path. basename (filepath) L. append ('content-type: % s' % get_content_type (filepath) L. append ('') L. append (readfileascontent (filepath) else: l. append ('--' + boundary) L. append ('content-Disposition: Form-data; name = "% s" '% key) L. append ('') L. append (value) L. append ('--' + boundary + '--') L. append ('') Body = CRLF. join (l) content_type = 'multipart/form-data; boundary = % s' % boundary return content_type, body
Note that the dictionary value of the file data is in the format of f'/path/to/file'. The Calling method is as follows:
Form_data = [('gshopid ', '000000'), ("additems", R "f'd: \ case3guomei. XML '"), ('validatestring', '92c99a2a36f47c6aa2f0019caa0591d2')] form_data_re = encode_multipart_formdata (form_data) print form_data_re
The returned content is a tuples. The first parameter is the Content-Type value in the request header, and the second parameter is the content of the specific post. Then, use the POST method of httplib to send the message.