twisted location header redirect

邮差的信 提交于 2019-12-06 04:41:38

I worked it out in the end with help from the other poster, with request.finish(), the redirect including http:// and returning NOT_DONE_YET

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

class Simple(resource.Resource):
    isLeaf = True
    def render_GET(self, request):
        request.redirect("http://www.google.com")
        request.finish()
        return server.NOT_DONE_YET

site = server.Site(Simple())
reactor.listenTCP(8080, site)
reactor.run()

Location header requires absolute url e.g., http://example.com.

302 Found response code says that we SHOULD provide a short hypertext note with a hyperlink to the new URI. redirectTo() does exactly that:

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

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

Or just using web twistd plugin, put in redirect.rpy file:

from twisted.web.util import Redirect

resource = Redirect("http://example.com")

run:

$ twistd -n web --port tcp:8080:localhost --resource-script redirect.rpy

Just for a demonstration, here's how an implementation of redirectTo() could look like:

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

You should be able to redirect by using request.redirect(url) and then calling request.finish(). Please verify that you are calling request.finish().

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