How do I add basic authentication to a Python REST request?

淺唱寂寞╮ 提交于 2019-12-09 06:28:12

问题


I have the following simple Python code that makes a simple post request to a REST service -

params= { "param1" : param1,
          "param2" : param2,
          "param3" : param3 }
xmlResults = urllib.urlopen(MY_APP_PATH, urllib.urlencode(params)).read()
results = MyResponseParser.parse(xmlResults)

The problem is that the url used to call the REST service will now require basic authentication (username and password). How can I incorporate a username and password / basic authentication into this code, as simply as possible?


回答1:


If basic authentication = HTTP authentication, use this:

import urllib
import urllib2

username = 'foo'
password = 'bar'

passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
passman.add_password(None, MY_APP_PATH, username, password)
authhandler = urllib2.HTTPBasicAuthHandler(passman)
opener = urllib2.build_opener(authhandler)
urllib2.install_opener(opener)

params= { "param1" : param1,
          "param2" : param2,
          "param3" : param3 }

xmlResults = urllib2.urlopen(MY_APP_PATH, urllib.urlencode(params)).read()
results = MyResponseParser.parse(xmlResults)

If not, use mechanize or cookielib to make an additional request for logging in. But if the service you access has an XML API, this API surely includes auth too.

2016 edit: By all means, use the requests library! It provides all of the above in a single call.




回答2:


You may want a library to abstract out some of the details. I've used restkit to great effect before. It handles HTTP auth.



来源:https://stackoverflow.com/questions/3702370/how-do-i-add-basic-authentication-to-a-python-rest-request

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!