Redirect user in Python + Google App Engine

2019-04-24 23:03发布

I'm trying to do a simple redirection after logging the user. I thought I could use the print "Location:..." method but that doesn't seem to do the trick.

class MainPage(webapp.RequestHandler):
    def get(self):

        ip = self.request.remote_addr
        log = Log()
        log.ip_address = ip
        log.put()
        print "Location:http://www.appurl.com"

2条回答
仙女界的扛把子
2楼-- · 2019-04-24 23:39

Another option would be to do it directly on appengine_config.py

i.e. if you want to redirect everything to "http://www.google.com" you could add the following:

def webapp_add_wsgi_middleware(app):

    return webapp.WSGIApplication([('/*', webapp.RedirectHandler.new_factory('http://www.google.com', permanent=True))], debug=True)

i.e. if you want to do something based on the host you could do:

def webapp_add_wsgi_middleware(app):

    if 'mydomain.com' in os.environ.get('HTTP_HOST'):
        return webapp.WSGIApplication([('/*', webapp.RedirectHandler.new_factory('http://www.google.com/', permanent=True))],
    debug=True)
    else:
        return app
查看更多
何必那么认真
3楼-- · 2019-04-24 23:41

RequestHandler has a redirect() method that you can use. It takes two parameters, the first one being the url to redirect to, and the second one a boolean value. If you pass true, it sends a 301 code to indicate a permanent redirect, if you don't pass it an explicit value, it defaults to false, and sends the client a 302 code to indicate a temporary redirect.

Something like this:

class MainPage(webapp.RequestHandler):
    def get(self):

        ip = self.request.remote_addr
        log = Log()
        log.ip_address = ip
        log.put()
        self.redirect("http://www.appurl.com") # replaced this -> print "Location:http://www.appurl.com"
查看更多
登录 后发表回答