我如何基本验证添加到一个Python REST请求? [英] How do I add basic authentication to a Python REST request?

查看:250
本文介绍了我如何基本验证添加到一个Python REST请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下简单的Python code,使一个简单的POST请求到REST服务 -

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)

问题是,该URL用于调用REST服务现在需要基本身份验证(用户名和密码)。我怎么可以将用户名和密码/基本验证这个code,尽可能简单?

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?

推荐答案

如果基本身份验证= HTTP验证,使用:

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)

如果不是,请使用机械化 cookielib 来作出登录额外要求,但如果服务您访问具有XML API,这个API当然包括权威性了。

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年编辑:通过一切手段,使用请求库!它提供上述所有在一个单一的电话。

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

这篇关于我如何基本验证添加到一个Python REST请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆