Flask giving an internal server error instead of rendering 404 - python

In my Flask app, I set up a 404 handler like this:
#app.errorhandler(404)
def page_not_found(e):
return render_template('404.html'), 404
However, when a user goes to an unrecognized URL, the system gives an internal server error instead of rendering my 404 template. Am I missing something?

Internal Server Error is HTTP error 500 rather than 404 and you haven't added error handler for it. This occurs when the server is unable to fulfill the client request properly. To add a gracious message when such error occurred, you can add a errorhandler like 404.
#app.errorhandler(500)
def exception_handler(e):
return render_template('500.html'), 500

There is likely an issue while rendering the 404 template which then triggers an internal server error.
I suggest checking the logs for your app.

This will also occur if you have debug set to true. Try setting debug to false and see if your custom 404 shows up then.

Related

CherryPy redirect to root on missing parameters error

I have a web server using CherryPy. I would like for users to be redirected to the root page if they try and access a page which requires parameters to be entered. If a user were to try and directly access:
localhost:8080/page
they will get an error message which looks something like:
404 Not Found
Missing parameters: parameter1,parameter2,...
Instead of this, I would like the user to be redirected to:
localhost:8080/
I have tried to change cherrypy.config such that whenever a 404 occurs, it checks the error message and sees if the issue is missing parameters. If this is not the issue, I would like the default 404 page to be shown. My code looks like this:
cherrypy.config.update({'error_page.404': error_page_404})
with the function error_page_404:
def error_page_404(status, message, traceback, version):
if message.startswith('Missing parameters'):
raise cherrypy.HTTPRedirect('/')
else:
raise cherrypy.HTTPError(status, message)
but when I try to access
localhost:8080/page,
I get the following error:
404 Not Found
Missing parameters: parameter1,parameter2
In addition, the custom error page failed:
cherrypy._cperror.HTTPRedirect: (['http://127.0.0.1:8080/'], 303)
Any thoughts?
Thank you!
I've managed to make a workaround by returning HTML code that redirects to the root:
def error_page_404(status, message, traceback, version):
if message.startswith('Missing parameters'):
return """<meta http-equiv="Refresh" content="0; url='/'" />"""
else:
return f'<h2>404 Not Found</h2>\n' \
f'<p>{message}</p>'
While this works for my purposes, I can't help but feel there must be a more native way of doing this in cherrypy

Output exception to browser when Flask app has error

When my deployed Flask application has an error, I only see a standard error message in the browser.
Internal Server Error
The server encountered an internal error and was unable to complete
your request. Either the server is overloaded or there is an error in
the application.
Going through the logs to find the error is inconvenient. How can I output the error to the browser instead?
For debugging purposes you may try this:
import traceback
#app.errorhandler(Exception)
def handle_500(e=None):
app.logger.error(traceback.format_exc())
return 'Internal server error occured', 500

Flask errors vs web service errors

I'm going through the RESTful web services chapter of the Flask web development book by Miguel Grinberg and he mentions that errors can be generated by Flask on its own or explicitly by the web service.
For errors generated by Flask, he uses a error handler like the following:
#main.app_errorhandler(404)
def page_not_found(e):
if request.accept mimetypes.accept_json and \
not request.accept_mimetypes.accept_html:
response = jsonify({'error': 'not found'})
response.status_code = 404
return response
return render_template('404.html'), 404
While errors generated by the web service, have no error handler:
def forbidden(message):
response = jsonify({'error': 'forbidden', 'message': message})
response.status_code = 403
return response
I don't really understand the difference between a flask generated error vs a web service generated error.
The first is an example of how to make a custom handler for an error that Flask will raise. For example, it will raise a 404 error with a default "not found" message if it doesn't recognize the path. The custom handler allows you to still return the 404 error, but with your own, nicer looking response instead.
The second is an example of how to change the code for your response, without handling a previously raised error. In this example, you would probably return forbidden() from another view if the user doesn't have permission. The response would have a 403 code, which your frontend would know how to handle.

Display a specific template when Django raises an exception

In my django app, I have multiple places where I raise a specific custom exception DeserializationError. My goal is to show/redirect to a pretty page to show the user this error, including the error message, when this error is raised. Basically, a page that says something like
Something went wrong. Please contact webmaster#email.com.
Error: DeserializationError. Message: SomeModel, "somemodel", does not exist.
Would this even be possible? I've been trying to search for a solution but haven't been able to find anything yet.
Most likely such errors will return HTTP 500 server error.
In django you can write your own custom view to handle such cases and return your own page with the html that you like.
The 500 (server error) view explains writing server error views. There are more types of errors handled as explained on same page.
An option for handling HTTP 500 errors, add this to your Settings file,
handler500 = 'mysite.views.my_custom_error_view'
and in the view, you can render the "error page" using
HttpResponseNotFound('<h1>Page not found</h1>')
the server_error() view will be overridden by handler500.

Pylons middleware 404

i'm new to Python and Pylons and want to know how it is possible to cancle the start routin of the pylons app.
I found the middleware and want to do something like this:
if error:
abort(404)
But this brings me a 500 internal Server Error Message if error is true instead of a 404 Not Found Message.
Could anyone tell me how i can interupt start routin of pylons?
Try adding a message in the call:
abort(404,"404 Not Found");
As well, you can customize the error documents. See:
http://wiki.pylonshq.com/display/pylonsdocs/Error+Documents#changing-the-template
The problem is with the condition not abort.
Try this way:
def test(self):
username = ''
if not username:
abort(404)

Categories