[Twisted-Python] HTTP client with authorization

Johan Lübcke johan.lubcke at appload.net
Tue Mar 18 07:58:53 EST 2003


I've just started to use twisted for a small project to relay GSM SMS
messages to Zope, and for that I need to do HTTP requests with basic
authentication. Would this be something that would be interesting to
have in twisted.web.client?

I ended up with this:

import base64
import twisted.internet.reactor
import twisted.web.client
import urlparse

class AuthHTTPPageGetter(twisted.web.client.HTTPPageGetter):

    def connectionMade(self):
        self.sendCommand('GET', self.factory.url)
        self.sendHeader('Host', self.factory.host)
        self.sendHeader('User-Agent', self.factory.agent)

        if self.factory.http_user:
            cred = '%s:%s' % (self.factory.http_user,
            auth = "Basic " +
            self.sendHeader('Authorization', auth)

        self.headers = {}

def _parse(url):
    parsed = urlparse.urlparse(url)
    path = urlparse.urlunparse(('','')+parsed[2:])
    host, port = parsed[1], 80
    if ':' in host:
        host, port = host.split(':')
        port = int(port)
    return host, port, path

def getPage(url, http_user=None, http_password=None):
    host, port, url = _parse(url)
    factory = twisted.web.client.HTTPClientFactory(host, url)
    factory.http_user = http_user
    factory.http_password = http_password
    factory.protocol = AuthHTTPPageGetter
    twisted.internet.reactor.connectTCP(host, port, factory)
    return factory.deferred

Thanks for a great framework! Comming from asyncore, twisted makes
things quite a lot easier...

  / Johan

Johan Lübcke, System Architect                         Appload Nordic AB          
Mobile: +46 730 632303                            http://www.appload.com
Office: +46 8 4420933                    mailto:johan.lubcke at appload.com

-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 189 bytes
Desc: This is a digitally signed message part
Url : http://twistedmatrix.com/pipermail/twisted-python/attachments/20030318/5ddcdcb5/attachment.pgp 

More information about the Twisted-Python mailing list