gpt4 book ai didi

python - Python 中的异常处理(webapp2、Google App Engine)

转载 作者:太空狗 更新时间:2023-10-30 03:03:32 26 4
gpt4 key购买 nike

我尝试使用建议的函数来处理异常:

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 异常?

最佳答案

另一种处理错误的方法是使用 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)

更好的解决方案是在 Debug模式下运行时抛出异常,并在生产环境中以更友好的方式处理它们。取自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

关于python - Python 中的异常处理(webapp2、Google App Engine),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18644857/

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