gpt4 book ai didi

python - 谷歌应用引擎中python中间件的301重定向

转载 作者:太空宇宙 更新时间:2023-11-04 01:24:30 24 4
gpt4 key购买 nike

我有一个在谷歌应用引擎中运行的 python 中间件类,我试图在其中执行 301 重定向:

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)

这是一个简化版本,但说明了问题。我找不到有关如何从中间件执行 302/301 重定向的任何信息!所有信息都与从处理程序或其他一些框架执行此操作相关,这些方法都会在 google app engine 中产生错误。

这是我的 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)

最佳答案

我猜问题出在您的中间件是您应用的最外层包装器。当您从应用程序内部引发异常时,它会被默认的 webapp 中间件捕获并设置状态代码。但是,由于您的中间件不在其中,因此无法捕获它。

但是我认为在这种情况下不需要异常(exception)。您要做的就是设置 302 状态代码和位置 header 。所以就这样做:

if response.status_int == 404:
start_response('301 Redirect', [('Location', 'http://www.example.com/'),])
return []
else:
return response(environ, start_response)

关于python - 谷歌应用引擎中python中间件的301重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18916687/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com