Use Twisted getPage as urlopen?

I would like to use the Twisted non-blocking getPage method in webapp, but for this function it is quite difficult to use such a function compared to urlopen.

This is an example of what I'm trying to achieve:

def web_request(request):
   response = urllib.urlopen('http://www.example.org')
   return HttpResponse(len(response.read()))

Is it hard to have something like this with getPage?

+5
source share
2 answers

, (, , ), , . , . . , getPage - , urllib.urlopen. , , ( .) len() , ( .)

Twisted Deferreds, . getPage a Deferred, " ". , , Deferred, Deferred , . , :

def web_request(request)
    def callback(data):
        HttpResponse(len(data))
    d = getPage("http://www.example.org")
    d.addCallback(callback)
    return d

, web_request . , getPage, ? - web_request ? web_request ? , ? ( Twisted Deferred - , getPage, . , . )

Deferreds, , , , : twisted.internet.defer.inlineCallbacks. Python 2.5, , :

@defer.inlineCallbacks
def web_request(request)
    data = yield getPage("http://www.example.org")
    HttpResponse(len(data))

, d Deferred, , , web_request - defer.inlineCallbacks , Deferred.

+20

I , , URL- getPage. :

from twisted.web.client import getPage
from twisted.internet import reactor

url = 'http://aol.com'

def print_and_stop(output):
    print output
    if reactor.running:
       reactor.stop()

if __name__ == '__main__':
    print 'fetching', url
    d = getPage(url)
    d.addCallback(print_and_stop)
    reactor.run()

, , , Twisted (getPage ).

+4

All Articles