gpt4 book ai didi

python - 如何让我的简单扭曲代理工作?

转载 作者:太空宇宙 更新时间:2023-11-03 13:53:34 25 4
gpt4 key购买 nike

我正在尝试使用 Twisted.Web框架。

注意三行注释(#line1、#line2、#line3)。我想创建一个代理(网关?),它将根据 url 将请求转发到两个服务器之一。如果我取消注释 1 或 2(并注释其余部分),请求将被代理到正确的服务器。但是,当然,它不会根据 URL 选择服务器。

from twisted.internet import reactor
from twisted.web import proxy, server
from twisted.web.resource import Resource

class Simple(Resource):
isLeaf = True
allowedMethods = ("GET","POST")

def getChild(self, name, request):
if name == "/" or name == "":
return proxy.ReverseProxyResource('localhost', 8086, '')
else:
return proxy.ReverseProxyResource('localhost', 8085, '')

simple = Simple()
# site = server.Site(proxy.ReverseProxyResource('localhost', 8085, '')) #line1
# site = server.Site(proxy.ReverseProxyResource('localhost', 8085, '')) #line2
site = server.Site(simple) #line3
reactor.listenTCP(8080, site)
reactor.run()

如上代码所示,当我运行此脚本并导航到服务器“localhost:8080/ANYTHING_AT_ALL”时,我得到以下响应。

Method Not Allowed

Your browser approached me (at /ANYTHING_AT_ALL) with the method "GET". I only allow the methods GET, POST here.

我不知道我做错了什么?任何帮助将不胜感激。

最佳答案

由于您的 Simple 类实现了 getChild() 方法,因此暗示这不是叶节点,但是,您声明它是叶节点通过设置 isLeaf = True。 (叶子节点怎么可能有 child ?)。

尝试将 isLeaf = True 更改为 isLeaf = False,您会发现它会按照您的预期重定向到代理。

来自 Resource.getChild 文档字符串:

... This will not be called if the class-level variable 'isLeaf' is set in
your subclass; instead, the 'postpath' attribute of the request will be
left as a list of the remaining path elements....

关于python - 如何让我的简单扭曲代理工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2269380/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com