twisted location header redirect

2019-05-22 23:28发布

From the render_GET method of a Resource in twisted, is it possible to redirect to a different url entirely (hosted elsewhere)

request.redirect(url) doesn't appear to do anything, and neither does twisted.web.util.Redirect

The equivalent in php would be,

header('location:'.$url);

EDIT

this is the code I'm running

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

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

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

3条回答
beautiful°
2楼-- · 2019-05-22 23:53

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()
查看更多
迷人小祖宗
3楼-- · 2019-05-22 23:55

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

查看更多
Fickle 薄情
4楼-- · 2019-05-22 23:57

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
查看更多
登录 后发表回答