Reputation: 5332
I have a python middleware class running in google app engine that I'm trying to perform a 301 redirect in:
from webob import Request
from webob.exc import HTTPMovedPermanently
from urlparse import urlparse
class MyMiddleware(object):
def __init__(self, app):
self.app = app
def __call__(self, environ, start_response):
request = Request(environ)
response = request.get_response(self.app)
if response.status_int == 404:
raise HTTPMovedPermanently(location="/")
return response(environ, start_response)
This is a simplified version, but illustrates the problem. I can't find any information on how to perform a 302/301 redirect from middleware! All information relates to doing it from a handler or some other framework and these methods all produce errors in google app engine.
This is my main.py:
import os
import webapp2
import jinja2
from seo import *
from notfound import *
JINJA_ENVIRONMENT = jinja2.Environment(
loader = jinja2.FileSystemLoader(os.path.dirname(__file__)),
extensions = ['jinja2.ext.autoescape'])
class MainHandler(webapp2.RequestHandler):
def get(self):
template = JINJA_ENVIRONMENT.get_template('home.html')
self.response.write(template.render())
app = webapp2.WSGIApplication([
('/', MainHandler)
], debug = True)
app = MyMiddleware(app)
Upvotes: 2
Views: 972
Reputation: 704
In the app.yaml
file of your python project, include the following line in the handler section.
handlers:
- url: /.*
redirect_http_response_code: 301
Upvotes: 0
Reputation: 599610
I'm guessing the problem is that your middleware is the very outer wrapper of your app. When you raise the exception from inside your app, then it is caught by the default webapp middleware and the status code is set. However, since your middleware is outside that, there's nothing to catch it.
However I think the exception is unnecessary in this case. All you want to do is to set the 302 status code and the location header. So just do that:
if response.status_int == 404:
start_response('301 Redirect', [('Location', 'http://www.example.com/'),])
return []
else:
return response(environ, start_response)
Upvotes: 1