How to run twisted with flask?

久未见 提交于 2019-12-03 09:57:30

问题


I wanna be able to run multiple twisted proxy servers on different directories on the same port simultaneously, and I figured I might use flask. so here's my code:

from flask import Flask
from twisted.internet import reactor
from twisted.web import proxy, server

app = Flask(__name__)
@app.route('/example')
def index():
    site = server.Site(proxy.ReverseProxyResource('www.example.com', 80, ''.encode("utf-8")))
    reactor.listenTCP(80, site)
    reactor.run()

app.run(port=80, host='My_IP')

But whenever I run this script, I get an Internal Server Error, I'm assuming because when app.run is called on port 80, the reactor.run can't be listening on port 80 as well. I wondering if there is some kind of work around to this, or what it is I'm doing wrong. Any help is greatly appreciated, Thanks!!


回答1:


You should give klein a try. It's made and used by most of the twisted core devs. The syntax is very much like flask so you won't have to rewrite much if you already have a working flask app. So something like the following should work:

from twisted.internet import reactor
from twisted.web import proxy, server
from klein import Klein

app = Klein()

@app.route('/example')
def home(request):
    site = server.Site(proxy.ReverseProxyResource('www.example.com', 80, ''.encode("utf-8")))
    reactor.listenTCP(80, site)

app.run('localhost', 8000)        # start the klein app on port 8000 and reactor event loop

Links

  • Klein Docs
  • Klein Github



回答2:


You can use the WSGIResource from Twisted istead of a ReverseProxy.

UPDATE: Added a more complex example that sets up a WSGIResource at /my_flask and a ReverseProxy at /example

from flask import Flask
from twisted.internet import reactor
from twisted.web.proxy import ReverseProxyResource
from twisted.web.resource import Resource
from twisted.web.server import Site
from twisted.web.wsgi import WSGIResource

app = Flask(__name__)


@app.route('/example')
def index():
    return 'My Twisted Flask'

flask_site = WSGIResource(reactor, reactor.getThreadPool(), app)

root = Resource()
root.putChild('my_flask', flask_site)

site_example = ReverseProxyResource('www.example.com', 80, '/')
root.putChild('example', site_example)


reactor.listenTCP(8081, Site(root))
reactor.run()

Try running the above in your localhost and then visiting localhost:8081/my_flask/example or localhost:8081/example



来源:https://stackoverflow.com/questions/36880184/how-to-run-twisted-with-flask

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