基于你的第一段代码是我的第一次通过,但它不起作用。
它似乎适用于类似的东西GET /a
,但那是因为/<path>
不包括额外/
的 's. 所以任何比一层更深的东西都不会被代理。
调查@route
,它werkzeug
在下面使用似乎不允许任意通配符:
from klein import run
from klein import route
from twisted.web.proxy import ReverseProxyResource
@route('/', defaults={'path': ''})
@route('/<path>')
def home(request, path):
print "request: " + str(request)
print "path: " + path
return ReverseProxyResource('localhost', 8001, path.encode('utf-8'))
run("localhost", 8000)
但是,如果您下拉到twisted
,您可以简单地执行以下操作:
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""
This example demonstrates how to run a reverse proxy.
Run this example with:
$ python reverse-proxy.py
Then visit http://localhost:8000/ in your web browser.
"""
from twisted.internet import reactor
from twisted.web import proxy, server
site = server.Site(proxy.ReverseProxyResource('www.example.com', 80, ''))
reactor.listenTCP(8000, site)
reactor.run()
如果您想捕获、记录、修改等每个请求,您可以子类化ReverseProxyResource
和覆盖render()
. getChild()
注意:由于错误,您还必须覆盖:
from twisted.internet import reactor
from twisted.web import proxy
from twisted.web import server
from twisted.python.compat import urlquote
class MyReverseProxyResource(proxy.ReverseProxyResource):
def __init__(self, host='www.example.com', port=80, path='', reactor=reactor):
proxy.ReverseProxyResource.__init__(self, host, port, path, reactor)
def getChild(self, path, request):
# See https://twistedmatrix.com/trac/ticket/7806
return MyReverseProxyResource(
self.host, self.port, self.path + b'/' + urlquote(path, safe=b"").encode('utf-8'),
self.reactor)
def render(self, request):
print request
return proxy.ReverseProxyResource.render(self, request)
p = MyReverseProxyResource()
site = server.Site(p)
reactor.listenTCP(8000, site)
reactor.run()
输出:
<Request at 0x14e9f38 method=GET uri=/css/all.css?20130620 clientproto=HTTP/1.1>
<Request at 0x15003b0 method=GET uri=/ clientproto=HTTP/1.1>