This article mainly introduces Python's use of Baidu API to upload files to Baidu online storage for code sharing. This article uses a third-party library poster and provides links in the article, for more information about how to obtain access_token, see the OAuth 2.0 API opened by Baidu. We will not introduce it here.
Third-party Python library
Poster
The code is as follows:
# Coding: UTF-8
Import urllib
Import urllib2
_ Author _ = 'admin'
From poster. encode import multipart_encode
From poster. streaminghttp import register_openers
Register_openers ()
Def upload (fileName ):
"""
Upload files to Baidu Cloud through Baidu developer API
"""
Principal en, headers = multipart_encode ({"file": open ("E: \ PHPTest \ Test1 \ % s" % fileName, "rb ")})
Baseurl = "https://pcs.baidu.com/rest/2.0/pcs/file? "
Args = {
"Method": "upload ",
"Access_token": "0. a2834e35964a7b0704252wef160507c1.2592000.1386326697.1060338330-1668780 ",
"Path": "/apps/ResourceSharing/% s" % fileName
}
Encodeargs = urllib. urlencode (args)
Url = baseurl + encodeargs
Print (url)
Request = urllib2.Request (url, en, headers)
Result = urllib2.urlopen (request). read ()
Print (result)
Upload ("host.txt ")