【问题标题】:Google App Engine: Creating a custom error pageGoogle App Engine:创建自定义错误页面
【发布时间】:2014-01-27 02:10:23
【问题描述】:

我一直在开发的应用程序接受用户的输入,并根据关键字相应地输出一堆结果。我使用网络抓取来抓取结果。

这是相同的python代码:

import os
import webapp2
import jinja2
from google.appengine.ext import db
import urllib2
import re

template_dir = os.path.join(os.path.dirname(__file__), 'templates')
jinja_env = jinja2.Environment(loader = jinja2.FileSystemLoader(template_dir), autoescape=True)

class Handler(webapp2.RequestHandler):
    def write(self, *a, **kw):
        self.response.out.write(*a, **kw)
    def render_str(self, template, **params):
        t = jinja_env.get_template(template)
        return t.render(params)
    def render(self, template, **kw):
        self.write(self.render_str(template, **kw))

class MainPage(Handler):
    def get(self):
        self.render("formrss.html")
    def post(self):
        x = self.request.get("rssquery")
        url = "http://www.quora.com/" + x + "/rss"
        content = urllib2.urlopen(url).read()
        content = content.decode('utf-8')
        allTitles =  re.compile('<title>(.*?)</title>')
        allLinks = re.compile('<link>(.*?)</link>')
        list = re.findall(allTitles,content)
        linklist = re.findall(allLinks,content)
        self.render("frontrss.html", list = list, linklist = linklist)



app = webapp2.WSGIApplication([('/', MainPage)], debug=True)

现在,由于我是通过结合用户输入的关键字获得最终的url,所以从关键字获得的url总是有可能是无效的。因此,在这种情况下,用户会收到 404 错误。

这是应用程序的现场演示:

http://quorable.appspot.com/

如何避免此错误?或者更确切地说,如果获取的 url 不可用,如何为用户显示自定义消息?当用户输入的关键字无效时,我不希望用户认为应用程序已损坏或出现故障。

【问题讨论】:

    标签: python google-app-engine http-status-code-404


    【解决方案1】:
    import...
    
    def handleNone(request, response, exception):
        logging.exception(exception) # if you need some logging
        response.headers['Content-Type'] = 'text/html'
        response.write('No feed for this keywords. Go <a href="/">back</a>')
        response.set_status(404)
    
    app = webapp2.WSGIApplication([('/', MainPage)], debug=True)
    
    app.error_handlers[404] = handleNone
    

    顺便说一句,如果 Quora 服务器响应 404,你最好做一个重定向。 检查urllib2.urlopen()reference docs

    req = urllib2.Request(yourURL)
    try: urllib2.urlopen(req)
    except URLError as e:
        if e.code == 404:
            redirect_to_a_no_results_page() 
    else:
           fetch_the_results()
    

    【讨论】:

      猜你喜欢
      • 2021-09-25
      • 1970-01-01
      • 2016-05-16
      • 1970-01-01
      • 1970-01-01
      • 2016-09-02
      • 1970-01-01
      • 2019-05-28
      • 2015-04-21
      相关资源
      最近更新 更多