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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With