【问题标题】:Exception handling in Python (webapp2, Google App Engine)Python 中的异常处理(webapp2、Google App Engine)
【发布时间】:2013-09-09 18:59:39
【问题描述】:

我尝试使用关于如何处理异常的建议函数:

http://webapp-improved.appspot.com/guide/exceptions.html

在 main.py 中:

def handle_404(request, response, exception):
        logging.exception(exception)
        response.write('404 Error')
        response.set_status(404)

def handle_500(request, response, exception):
    logging.exception(exception)
    response.write('A server error occurred!')
    response.set_status(500)

class AdminPage(webapp2.RequestHandler):
    def get(self):
    ...
    admin_id = admin.user_id()
    queues = httpRequests.get_queues(admin_id)

app = webapp2.WSGIApplication(...)

app.error_handlers[404] = handle_404
app.error_handlers[500] = handle_500

httpRequests.py中的函数:

def get_queues(admin_id):

    url = "http://localhost:8080/api/" + admin_id + "/queues"
    result = urlfetch.fetch(url)

    if (result.status_code == 200):
        received_data = json.loads(result.content)
        return received_data

API中被调用的函数:

class Queues(webapp2.RequestHandler): 
    def get(self, admin_id): 
        queues = queues(admin_id)
        if queues == []:
            self.abort(404)
        else:
            self.response.write(json.dumps(queues))

我在 httpRequests.py 中的 get_queues 卡住了。 urlfetch如何处理HTTP异常?

【问题讨论】:

    标签: python google-app-engine webapp2 urlfetch


    【解决方案1】:

    另一种处理错误的方法是使用handle_exception 创建一个BaseHandler,并让所有其他处理程序扩展它。一个完整的工作示例如下所示:

    import webapp2
    from google.appengine.api import urlfetch
    
    class BaseHandler(webapp2.RequestHandler):
      def handle_exception(self, exception, debug_mode):
        if isinstance(exception, urlfetch.DownloadError):
          self.response.out.write('Oups...!')
        else:
          # Display a generic 500 error page.
          pass
    
    class MainHandler(BaseHandler):
      def get(self):
        url = "http://www.google.commm/"
        result = urlfetch.fetch(url)
        self.response.write('Hello world!')
    
    
    app = webapp2.WSGIApplication([
        ('/', MainHandler)
      ], debug=True)
    

    一个更好的解决方案是在调试模式下运行时抛出异常,并在生产运行时以更友好的方式处理它们。取自another example,您可以为您的BaseHandler 执行类似的操作并根据需要扩展它:

    class BaseHandler(webapp2.RequestHandler):
      def handle_exception(self, exception, debug_mode):
        if not debug_mode:
          super(BaseHandler, self).handle_exception(exception, debug_mode)
        else:
          if isinstance(exception, urlfetch.DownloadError):
            # Display a download-specific error page
            pass
          else:
            # Display a generic 500 error page.
            pass
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-10-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-13
      相关资源
      最近更新 更多