[Twisted-Python] HTTP client with authorization
Johan Lübcke
johan.lubcke at appload.net
Tue Mar 18 05:58:53 MST 2003
Hi
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,
self.factory.http_password)
auth = "Basic " +
base64.encodestring(cred).replace('\012','')
self.sendHeader('Authorization', auth)
self.endHeaders()
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: signature.asc
Type: application/pgp-signature
Size: 189 bytes
Desc: This is a digitally signed message part
URL: </pipermail/twisted-python/attachments/20030318/5ddcdcb5/attachment.sig>
More information about the Twisted-Python
mailing list