How do I run Klein with twisted?

断了今生、忘了曾经 提交于 2020-01-06 03:21:52

问题


I'm trying to run klein with twisted, so I can run twisted scripts on different paths (exp: example.com/example1, example.com/example2). So I made a simple script:

from klein import run, route, Klein
from twisted.internet import reactor
from twisted.web import proxy, server
from twisted.python import log

@route('/example')
def home(request):
    site = server.Site(proxy.ReverseProxyResource('www.example.com', 80, b''))
    reactor.listenTCP(80, site)
    reactor.run()

run("My_IP_Address", 80)

But whenever I run this script I get an Error: twisted.internet.error.CannotListenError: Couldn't listen on any:80: [Errno 98] Address already in use. I'm very new to Klein, and I'm not sure how it works, Could anybody tell me what it is I'm doing wrong? thanks!


回答1:


This exception that you're getting seems fairly clear it says:

Couldn't listen on any:80: [Errno 98] Address already in use.

it happens when port number you're trying to use is already used by some other services. This other service can be either something other than Twisted or two Twisted services. I'm going to assume you dont have anything else listening on port 80 (e.g. nginx or apache or some other web server, note that 80 is default HTTP port so many services can be listening there) and that your problem is caused by starting two twisted web services.

In your case you are trying to start two services listening on one port.

run("My_IP_Address", 80)

starts one service listening on port 80.

After receiving request on /example route you're trying to start another service on this same port:

site = server.Site(proxy.ReverseProxyResource('www.example.com', 80, b''))
reactor.listenTCP(80, site)
reactor.run()

this does not make logical sense, you can't have two services running on same port. This is why you get this exception. Also your call to reactor.run() is useless, run() imported from klein already starts reactor.

If you really do need to start some server after some request (this seems like very unusual use case) start it on a different port. But maybe you should simply start with official documentation and examples there?



来源:https://stackoverflow.com/questions/37013869/how-do-i-run-klein-with-twisted

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