Python uploads files using post

Source: Internet
Author: User
Tags urlencode

Foreword: Because the project needs to do the interface test to upload the file this request, when checking the data found using requests to do upload file is very simple, so down the library to complete. The follow-up will sometimes see if you can do it with traditional urllib2.

First you have to have a requests:

Https://github.com/kennethreitz/requests

and import it in.

Then:

def post (self,url,param_dict,param_header,file = ", Param_type = ' X-www-form-urlencode '):
" "
@ Function: Package Post mode
@paramType: Refers to the passed-in parameter type, which can be form-data, X-www-form-urlencode, JSON
" "
Respone_code = None
respone = None
Try:
if Param_type = = ' X-www-form-urlencode ':
params = param_dict
elif Param_type = = ' json ':
params = json.dumps (param_dict)
if File = = ':
ret = Requests.post (self. Server+url, Data=params, Headers=param_header)
Else:

Files = {' file ': Open (file, ' RB ')}
ret = Requests.post (self. Server+url, data=params, headers=param_header,files = files)
Respone_code = Ret.status_code
Respone = Ret.text
except requests. Httperror, E:
Respone_code = E.getcode ()
Respone = E.read (). Decode ("Utf-8")

Return Respone_code,respone

Also attached http://blog.csdn.net/iloveyin/article/details/21444613, this blog in detail describes the use of requests this library method

Python uploads files using post

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.