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

♀尐吖头ヾ 提交于 2019-12-08 20:39:42

问题


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.


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/9253773/the-sample-python-twisted-event-driven-web-application-increments-request-count

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!