【发布时间】:2012-09-10 12:03:05
【问题描述】:
我正在使用 GAE,Google App Engine 和使用 Python 的 Webapp。
我一直在尝试实现自定义错误处理程序或模板,或者按照这些思路。 GAE 提供了一些文档here,但是它在示例中没有提供足够的实现(对我来说)。
我还在另一个 StackOverflow 问题 here 上查看了所有这些精彩示例 - 但无法理解如何将其实现到我当前的 main.py 文件中。
import os
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
from google.appengine.ext.webapp import template
class MainHandler(webapp.RequestHandler):
def get (self, q):
if q is None:
q = 'static/index.html'
path = os.path.join (os.path.dirname (__file__), q)
self.response.headers ['Content-Type'] = 'text/html'
self.response.out.write (template.render (path, {}))
def main ():
application = webapp.WSGIApplication ([('/(.*html)?', MainHandler)], debug=False)
util.run_wsgi_app (application)
if __name__ == '__main__':
main ()
我尝试创建另一个类,并在MainHandler 之前实现它,并在MainHandler 中实现一个新的def。我唯一一次显示 404,它是全局显示的,这意味着即使 index.html 文件也是“404”。
我尝试的最后一件事是按照以下方式实现:
if not os.path.exists (_file_):
self.redirect(/static/error/404.html)
我的 app.yaml 文件是:
application: appname
version: 1
runtime: python
api_version: 1
error_handlers:
- file: static/error/404.html
- error_code: over_quota
file: static/error/404.html
handlers:
- url: /(.*\.(gif|png|jpg|ico|js|css))
static_files: \1
upload: (.*\.(gif|png|jpg|ico|js|css))
- url: /robots.txt
static_files: robots.txt
upload: robots.txt
- url: /favicon.ico
static_files: favicon.ico
upload: favicon.ico
- url: .*
script: main.py
我找不到任何有关 404 处理程序实现的指南/教程,只有代码摘录。
非常感谢大家!
编辑: 根据下面 Hans 的说明,当文件系统中不存在文件(或目录)时,我想返回 404。
我试过了:
class ErrorHandler(webapp.RequestHandler):
def get(self):
if not os.path.isfile(_file_):
self.redirect('/static/error/404.html')
无济于事。正确的实现/语法是什么?
编辑: 前往沃斯考萨
import os
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
from google.appengine.ext.webapp import template
import logging
import webapp2
def handle_404(request, response, exception):
logging.exception(exception)
response.write('Oops! I could swear this page was here!')
response.set_status(404)
def handle_500(request, response, exception):
logging.exception(exception)
response.write('A server error occurred!')
response.set_status(500)
app = webapp2.WSGIApplication([
webapp2.Route('/', handler='handlers.HomeHandler', name='home')
])
app.error_handlers[404] = handle_404
app.error_handlers[500] = handle_500
class MainHandler(webapp.RequestHandler):
def get (self, q):
if q is None:
q = 'static/index.html'
path = os.path.join (os.path.dirname (__file__), q)
self.response.headers ['Content-Type'] = 'text/html'
self.response.out.write (template.render (path, {}))
def main ():
application = webapp.WSGIApplication ([('/(.*html)?', MainHandler)], debug=True)
util.run_wsgi_app (application)
if __name__ == '__main__':
main ()
【问题讨论】:
标签: python google-app-engine web-applications