2016-04-27 75 views
4

我想能夠在同一端口上的不同目錄上同時運行多個扭曲的代理服務器,並且我想我可能會使用燒瓶。 所以這裏是我的代碼:如何用燒瓶運行扭曲?

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') 

但每當我運行該腳本,我得到一個內部服務器錯誤,我假設,因爲當app.run被稱爲端口80,reactor.run不能在80端口監聽以及。我想知道是否有這樣的工作,或者我做錯了什麼。任何幫助非常感謝,謝謝!

+0

你嘗試使用不同的端口? –

+0

是的,我嘗試使用不同的端口。它導致該網站根本不出現 – Cristian

回答

6

您可以使用來自Twisted的WSGIResource is ReverseProxy。

UPDATE:增加了一個更爲複雜的例子是設置在/ my_flask一個WSGIResource並在反向代理/例如

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() 

嘗試運行上面的本地主機,然後訪問本地主機:8081/my_flask /示例或localhost:8081/example

+0

謝謝這實際上工作得很好,唯一的是,我不知道我會在哪裏或如何實現代理功能來呈現其他服務器的資源? – Cristian

+0

更新了我的答案 – Eduardo

+1

我試圖用那個確切的代碼,但我一直得到'沒有這樣的資源','沒有這樣的孩子資源' – Cristian

6

您應該試一試klein。它由大多數twisted核心開發人員製作和使用。語法非常類似於flask,因此如果您已經有一個可運行的flask應用程序,則不必重寫很多內容。因此,像下面應該工作:

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 

鏈接

+0

我實際上已經嘗試過使用克萊因,但我不斷收到錯誤我試試看,去http://stackoverflow.com/questions/37013869/how-do-i-run-klein-with-twisted – Cristian

+0

這個問題的答案是準確的。我忽略了一個事實,即你試圖在同一個接口上聽同一個端口,這會拋出錯誤。理論上你可以對80端口的流量進行負載平衡,但這可能是過度的。 –