简体   繁体   English

处理来自Python包的未处理异常

[英]Handle unhandled exception from Python package

I have successfully incorporated my Wordpress blog into my Django app through the-real-django-wordpress Python package ( Github ). 我已经通过real-django-wordpress Python软件包( Github )将Wordpress博客成功地合并到了Django应用程序中。

The only things I needed to do were to: 我唯一需要做的是:

  • add the Wordpress database credentials to the Django settings, 将Wordpress数据库凭据添加到Django设置中,
  • include the URLconf of the package into urls.py , 将包的URLconf包含在urls.py
  • override the package templates in order to display the posts the way I want. 覆盖软件包模板 ,以便以所需的方式显示帖子。

If however the Wordpress database happens to be offline, I get a Python exception. 但是,如果Wordpress数据库恰好处于脱机状态,则会收到Python异常。

OperationalError: (2003, "Can't connect to MySQL server on '10.0.2.2' (110)") OperationalError:(2003年,“无法连接到'10 .0.2.2'上的MySQL服务器(110)”)

The Python code being part of the package, and thus not in my code, where should I then handle the exception in order to display an error message? Python代码是软件包的一部分,因此不在我的代码中,那么我应该在哪里处理异常以显示错误消息?

Why not have your 500.html template simply display the error message you want? 为什么不让您的500.html模板仅显示所需的错误消息?

Otherwise, you could create a middleware to catch this error: 否则,您可以创建一个中间件来捕获此错误:

from django.shortcuts import render

class CatchOperationalError(object):
    def process_exception(self, request, exception):
        if type(exception).__name__ == 'OperationalError':  # replace with proper isinstance
            return render(request, 'wordpress_down.html')

https://docs.djangoproject.com/en/dev/topics/http/middleware/#process_exception https://docs.djangoproject.com/en/dev/topics/http/middleware/#process_exception

Another option would be to wrap each individual view in a try/except. 另一种选择是将每个单独的视图包装在try / except中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM