How to catch all the errors in all views? - python

I know we can use try and except function to catch the error. But everyday I monitor the sentry, the system always get an exception in any views. As usual I put try and except to catch the errors in the views.
My question is. Is it possible to catch all the errors from any views in just one function? Then the user will redirect to another page. Where is the best place to do this? I'm thinking about middleware but I don't have knowledge about it.

yes, can handle all exceptions from any view. try Googling "django middleware exception", you'll find many solutions .

Related

Django: How to get template debug info to user on syntaxerror

I have a page where users can submit their own template into a textarea, for now it needs to be that simple. However since it is user generated input i need to verify they don't do stuff that breaks the rest of my application and simultaneously giving useful feedback as to what they did wrong if they did something wrong.
For the purpose of giving useful feedback i want something similair looking to what django supplies me with (using django 1.4):
The above bit in particular. I'm putting the user template in a django template so i don't have to verify syntax errors and stuff myself. That looks something like this:
try:
template = get_template_from_string(user_input)
template.render(context=Context())
except:
do something to ouptut the error
The render call is needed otherwise not exceptions are thrown at all.
I have tried printing the exception and it's arguments, but that only gives very limited info. I also tried using traceback but that never gives back line numbers or anything within the template, only to where the exception is thrown in the python code. I also couldn't find anything using Google and my search through Django source code have left me wondering where the actual error page is generated...
So basically my question is; how do i get the bit of information shown in the image?
EDIT
To clarify: I want users to be able to make templates so these templates can be used while sending emails. Since the Django templating engine is already present I figured i would use that one instead of something else.
The templates themselves are made safe using this snippet and some parsing of my own for the variables. Everything works so far except the useful debug message to the user. So far all I've got on that is: "Something went wrong while parsing your template, unexpected block tag extends" (for example), which I would like to be more like the image shown above.
I just hit same issue. In my case it isn't required to have such a detail traceback. So I did it like that, using models clean method
from django.core.exceptions import ValidationError
from django.core.urlresolvers import NoReverseMatch
from django.db import models
from django.template.base import Template, TemplateSyntaxError
from django.template.context import Context
class MyTemplate(models.Model):
template = models.TextField()
def clean(self):
try:
Template(self.tempalte).render(Context({}))
except TemplateSyntaxError as tse:
raise ValidationError('TemplateSyntaxError: %s' % tse)
except NoReverseMatch as nrm:
raise ValidationError('NoReverseMatch: %s' % nrm)

Python/Django: automatically log when exceptions occur, including request info

I have created a function log_error(request, traceback), which I call in my exceptions. This writes error information to the database. Now, before I open up every one of my views and add this in an exception handler, is there a way to automatically have all exceptions raise to a function, which then calls this?
I have seen this Python error logging, which says to write your own version of sys.excepthook. This function is automatically called when there is an exception. I tried this, but my_excepthook was not called even though I copy-pasted the solution into views.py and raised an error. However, I didn't try too hard because it's not getting all the information that I need, anyway. I also need request so I can log information abut the user, url, etc.
Maybe that's asking too much?
(I'm using Django, but this does not seem like a Django-specific thing) Edit: yes, it is.
J.F Sebastian's suggestion worked. This is a Django solution.
In settings.py MIDDLEWARE_CLASSES:
(I added it as the last one, not sure if this is right or will cause errors down the line. Works for now.)
'myapp.middleware.ExceptionMiddleware',
In myapp.middleware.py:
import traceback
class ExceptionMiddleware(object):
def process_exception(self, request, exception):
log_error(traceback, request)
That's it. log_error is my function and writes to the database. It also appears from the documentation https://docs.djangoproject.com/en/dev/howto/error-reporting/ that I can get the local variables as well as the request attributes.

How to get the permission attached to the called view in Pyramid?

In my forbidden view, I want to redirect all members to their dashboard if they visit a page for guests, and I want to redirect all guests to the login page if they visit a page for members. This is easy enough.
However, there are some cases where I need to throw an HTTPForbidden error which is not the cause of a failed permission and simply display the reason to the user. How can I determine whether an HTTPForbidden is a result of a failed permission or some other reason? I suppose I could do some weird stuff with pyramid.security.has_permission (haven't tried it yet), but there has to be an easier way.
An old question from 2011 where it was stated that this was on the to do list How to check what permission failed in authorization in pyramid (pylons 2)?
This is not exactly what you asked for but it may still help you.
The right answer to your question was already given: you'd better raise a specific exception that is more appropriate than HTTPForbidden.
But if you really want to change the behavior of your forbidden view depending on the missing permission that triggered the HTTPForbidden exception, you need to grab its name.
The name of the missing permission can be found inside the HTTPForbidden exception object in HTTPForbidden.result.permission.
But first, the HTTPForbidden exception needs to be passed as a context of your forbidden view.
For instance, here is how I use this in my webapps to inform the user why he cannot access a particular feature so that he can
ask a manager to re-configure ACL accordingly if appropriate.
#forbidden_view_config(renderer='/forbidden.mako')
def forbidden(context, request):
return { 'required_permission': context.result.permission }
It works with pyramid 1.4.
I couldn't find anything in the documentation so I hacked this by debugging pyramid.
This is more a workaround than a clean solution.
I haven't tested it, but what I'd try to do is to raise something else than HTTPForbidden in the places where you do this manually. You can even subclass HTTPForbidden:
class WeDontLikeYourFace(HTTPForbidden):
pass
def my_view(context, request):
if request['face'] != 'beautyful':
raise WeDontLikeYourFace("go away")
Then you can register a custom view for your custom exception, or do some if/else stuff in the common view method registered for HTTPForbidden.
You can also add custom fields to your subclass to pass any information you need.

Best way to implement business logic rules in tastypie?

The frontend of this project will have business rules built in using JS but the backend of this app which is built in tastypie will enforce these rules. Putting rules in models seems a bit messy and it would be nice to have the rules somewhere in each ModelResource class.
Which methods should I override and how should I best report restrictions and exceptions back?
The type of logic will be along the lines of
if field_x = 5 and request.user != 2:
complain and don't process request
send back error
The hydrate method looks like a good place to do checking but I'm not certain how I'd raise exceptions properly and explain via those exceptions what went wrong. Any ideas?
I was reading through the documentation in alphabetical order and finally came across: http://django-tastypie.readthedocs.org/en/latest/validation.html

How do I customize formish error messages?

I'm using formish to handle web forms but I don't like the automatically generated error messages when validation fails. Where do I customize those error messages?
The best place for feedback on formish is in the google groups which is linked to from the http://form.ish.io page..
As for customising the error messages, the best way would be to create your own validator (which is pretty simple, have a look in the validatish module). However, you've inspired me to think about making all of the validators take a custom argument for each type of message... I'll have a think about that one. If you struggle customising your own errors, drop into the google group...
I've added custom messages to the validatish module for you .. If you get it from github, you'll see how it works (you pass a dictionary of messages to the validate function or object - e.g. Required(messages={'required': 'dont forget it!'}) )
If you need a release for it quickly, let me know..

Categories

Resources