Python calls API interface in several ways 2018-01-08 gaoeb97nd ... Turn from One_day_day ... Modify share: I believe that the students who have done automated operations have used API interfaces to accomplish certain actions. API is a set of mature system necessary interface, can be called by other systems or scripts, which is also a compulsory operation of automation. This article introduces several ways to invoke the API in Python, and here are the libraries that will be used in Python. -Urllib2-httplib2-pycurl-requests urllib2import urllib2, Urllibgithub_url = ' Https://api.github.com/user/repos ' Password_manager = Urllib2. Httppasswordmgrwithdefaultrealm () Password_manager.add_password (None, Github_url, ' user ', ' * * * ') auth = urllib2. Httpbasicauthhandler (Password_manager) # Create an authentication Handleropener = Urllib2.build_opener (auth) # Create an Opener with the authentication Handlerurllib2.install_opener (opener) # Install the opener ... request = Urllib2. Request (Github_url, Urllib.urlencode ({' name ': ' Test repo ', ' description ': ' Some Test Repository '}) # Manual encoding Requiredhandler = Urllib2.urlopen (Request) print Handler.read () 2. Httplib2import urllib, Httplib2github_url = ' H = httplib2. Http (". Cache") h.add_credentials ("User", "******", "data = Urllib.urlencode ({" Name ":" Test "}) RESP, cOntent = H.request (Github_url, "POST", data) print Content3. Pycurlimport Pycurl, Jsongithub_url = "User_pwd =" user:***** "data = Json.dumps ({" Name ":" Test_repo "," description ":" Som E test Repo "}) c = Pycurl. Curl () c.setopt (Pycurl. URL, Github_url) c.setopt (Pycurl. Userpwd, User_pwd) c.setopt (Pycurl. POST, 1) c.setopt (Pycurl. Postfields, data) C.perform () 4. Requestsimport requests, Jsongithub_url = "data = Json.dumps ({' name ': ' Test ', ' description ': ' Some Test Repo '}) R = Requests . Post (Github_url, data, auth= (' user ', ' * * * * ')) print R.json can invoke the API to perform the action, but requests this way the code is the most concise, clearest, and recommended. This article from the "Linux and Network" blog, reproduced please contact the author!
Several ways that Python calls API interfaces