Django View uses decorator to catch database connection exception
"Too late to explain." Go straight to the code.
from django.shortcuts import render, redirectfrom models import Hostsfrom django import forms# Create your views here.def database_error(request, message): if message == '' or message is None: message = 'Error detail is not given. ' context = { 'database_error': message, } return render(request, 'exception/error.html', context)def database_error_decorator(func): from functools import wraps from django.utils.decorators import available_attrs def decorator(view_func): @wraps(view_func, assigned=available_attrs(view_func)) def _wrapped_view(request, *args, **kwargs): try: return view_func(request, *args, **kwargs) except Exception as e: return database_error(request, message=e.message) return _wrapped_view return decorator(func)@database_error_decoratordef list_hosts(request): hosts = Hosts.objects.order_by('-hosts_hosts') context = { 'hosts': hosts } return render(request, 'inventory/hosts/list_hosts.html', context)
If an error is generated due to an abnormal database connection or a reason on the database that view cannot obtain the content in the database, if it is printed directly to the user, the user may be confused and the user experience is very unfriendly. Therefore, if possible, a simple self-test can be performed before the application starts to check whether the database can be connected properly, etc., but this check is generally not detailed enough to check whether a column in a certain table in the database exists, then it is time to catch these exceptions.
It is obviously not a good idea to catch these exceptions repeatedly in every database-related def in every view. A good idea is to use decorators to catch these exceptions. Decorators can be written exactly as in "from django.contrib.auth.decorators import login_required", as in this example. In fact, each kind of programming is similar to learn, whether Shell or Python, the method comes with a lot of good examples for us to learn, do not repeat the manufacture of wheels, stand on the shoulders of giants can see farther!
tag: decorator catch exception, decorator, exception
--end--