twisted-有密码保护的页面

from twisted.web import client, error as weberror

from twisted.internet import reactor

import sys, getpass, base64



def printPage(data):

    print data

    reactor.stop( )



def checkHTTPError(failure, url):

    failure.trap(weberror.Error)

    if failure.value.status == '401':

        print >> sys.stderr, failure.getErrorMessage( )

        # prompt for user name and password

        username = raw_input("User name: ")

        password = getpass.getpass("Password: ")

        basicAuth = base64.encodestring("%s:%s" % (username, password))

        authHeader = "Basic " + basicAuth.strip( )

        # try to fetch the page again with authentication

        return client.getPage(

            url, headers={"Authorization": authHeader})

    else:

        return failure



def printError(failure):

    print >> sys.stderr, "Error:", failure.getErrorMessage( )

    reactor.stop( )



if len(sys.argv) == 2:

    url = sys.argv[1]

    client.getPage(url).addErrback(

        checkHTTPError, url).addCallback(

        printPage).addErrback(

        printError)

    reactor.run( )

else:

    print "Usage: %s <URL>" % sys.argv[0]

 

 

checkHTTPError是从client.getPage返回的Deferred调用 ,在printPage和printError处理函数之前

twisted.python.failure.Failure对象被checkHTTPError调用

本例中checkHTTPError检查HTTP响应代码,failure.value是一个Exception对象,如果状态是401,则使用Authorization头,否则进行标准错误处理

你可能感兴趣的:(密码)