English 中文(简体)
血清2支持先发制人认证吗?
原标题:does urllib2 support preemptive authentication authentication?

我正试图获得教育、科学和技术部的预报。

我可以在库勒/REST客户(国际调查工具)工作,使预先认证成为可能。

但是,使用lli2,似乎不支持这种说法,我无法找到扭转这种局面的办法。

感谢:

最佳回答

在此,根据<代码>urllib2.HTTPBasicAuthHandler的代码,采用一种简单的防范性吉大港山区基本手法。 除<代码>Authorization的头盔将添加到every申请中与URL匹配。 请注意,应当使用<代码>。 HTTPPasswordMgrWithDefaultReal。 这是因为,由于你再次成为先发制人,因此在的挑战中没有任何回头。

class PreemptiveBasicAuthHandler(urllib2.BaseHandler):

        def __init__(self, password_mgr=None):
                if password_mgr is None:
                        password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
                self.passwd = password_mgr
                self.add_password = self.passwd.add_password

        def http_request(self,req):
                uri = req.get_full_url()
                user, pw = self.passwd.find_user_password(None,uri)
                #logging.debug( ADDING REQUEST HEADER for uri (%s): %s:%s ,uri,user,pw)
                if pw is None: return req

                raw = "%s:%s" % (user, pw)
                auth =  Basic %s  % base64.b64encode(raw).strip()
                req.add_unredirected_header( Authorization , auth)
                return req
问题回答

类似于@thom-nichols的回答;但次分类HTTPBasicAuthHandler也处理HTTPS的要求。

import urllib2
import base64

class PreemptiveBasicAuthHandler(urllib2.HTTPBasicAuthHandler):
       Preemptive basic auth.

    Instead of waiting for a 403 to then retry with the credentials,
    send the credentials if the url is handled by the password manager.
    Note: please use realm=None when calling add_password.   
    def http_request(self, req):
        url = req.get_full_url()
        realm = None
        # this is very similar to the code from retry_http_basic_auth()
        # but returns a request object.
        user, pw = self.passwd.find_user_password(realm, url)
        if pw:
            raw = "%s:%s" % (user, pw)
            auth =  Basic %s  % base64.b64encode(raw).strip()
            req.add_unredirected_header(self.auth_header, auth)
        return req

    https_request = http_request

这里是处理一个不送你401<>/code>的jenkins服务器的例子。 使用<代码>urllib2.install_ opener使事情变得容易。

jenkins_url = "https://jenkins.example.com"
username = "johndoe"
api_token = "some-cryptic-value"

auth_handler = PreemptiveBasicAuthHandler()
auth_handler.add_password(
    realm=None, # default realm.
    uri=jenkins_url,
    user=username,
    passwd=api_token)
opener = urllib2.build_opener(auth_handler)
urllib2.install_opener(opener)

根据需要何种认证,你可以人工发送授权书负责人,在你发出机构之前添加他们的请求。





相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...

热门标签