Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

the sample python twisted event driven web application increments request count by 2, why?

Tags:

python

twisted

The sample code for a basic web server given by http://twistedmatrix.com/trac/ seems to increment the request counter by two for each request, rather than by 1.

The code:

from twisted.web import server, resource
from twisted.internet import reactor

class HelloResource(resource.Resource):
    isLeaf = True
    numberRequests = 0

    def render_GET(self, request):
        self.numberRequests += 1
        request.setHeader("content-type", "text/plain")
        return "I am request #" + str(self.numberRequests) + "\n"

reactor.listenTCP(8080, server.Site(HelloResource()))
reactor.run()

Looking at the code, it looks like you should be able to connect to the url http://localhost:8080 and see:

I am request #1

Then refresh the page and see:

I am request #2

However, I see:

I am request #3

When I refresh again, I see:

I am request #5

So, judging from the counter, the server appears to call the function "render_GET" twice for each request. I am running this on Windows 7 using Python 2.7. Any idea what could be going on or is this expected behavior?

Update: The code is working perfectly, it's the browser that is being tricksy. Each page refresh, the browser sends a GET request for "/" and "/favicon.ico", which accounts for the incrementing by 2, because the render_GET function actually is being called twice per page refresh.

like image 731
jpreed00 Avatar asked Feb 12 '12 23:02

jpreed00


2 Answers

Browsers can behave in surprising ways. If you try printing the full request, you might find it is requesting "/" and also "favicon.ico", for example.

like image 86
Ned Batchelder Avatar answered Oct 18 '22 13:10

Ned Batchelder


The browser might be making a second request for the favicon.ico.

You should have your server print the request location when it gets a request. This would tell you if this is correct.

like image 41
Dan D. Avatar answered Oct 18 '22 14:10

Dan D.