Location
标头需要绝对网址,例如http://example.com
.
302 Found响应代码表明我们应该提供一个简短的超文本注释,其中包含指向新 URI 的超链接。redirectTo()
正是这样做的:
from twisted.web import server, resource
from twisted.web.util import redirectTo
from twisted.internet import reactor
class HelloResource(resource.Resource):
isLeaf = True
def render_GET(self, request):
return redirectTo('http://example.com', request)
reactor.listenTCP(8080, server.Site(HelloResource()))
reactor.run()
或使用Redirect
:
from twisted.web import server
from twisted.web.util import Redirect
from twisted.internet import reactor
reactor.listenTCP(8080, server.Site(Redirect("http://example.com")))
reactor.run()
或者只是使用web
twistd插件,放入redirect.rpy
文件:
from twisted.web.util import Redirect
resource = Redirect("http://example.com")
跑:
$ twistd -n web --port tcp:8080:localhost --resource-script redirect.rpy
只是为了演示,下面是实现的redirectTo()
样子:
def redirect_to(url, request):
request.setResponseCode(302) # Found
request.setHeader("Location", url)
request.setHeader("Content-Type", "text/html; charset=UTF-8")
return """put html with a link to %(url)s here""" % dict(url=url) # body