Flask return http error

The Python micro framework for building web applications. - flask/errorhandling.rst at main · pallets/flask

Handling Application Errors

Applications fail, servers fail. Sooner or later you will see an exception
in production. Even if your code is 100% correct, you will still see
exceptions from time to time. Why? Because everything else involved will
fail. Here are some situations where perfectly fine code can lead to server
errors:

  • the client terminated the request early and the application was still
    reading from the incoming data
  • the database server was overloaded and could not handle the query
  • a filesystem is full
  • a harddrive crashed
  • a backend server overloaded
  • a programming error in a library you are using
  • network connection of the server to another system failed

And that’s just a small sample of issues you could be facing. So how do we
deal with that sort of problem? By default if your application runs in
production mode, and an exception is raised Flask will display a very simple
page for you and log the exception to the :attr:`~flask.Flask.logger`.

But there is more you can do, and we will cover some better setups to deal
with errors including custom exceptions and 3rd party tools.

Error Logging Tools

Sending error mails, even if just for critical ones, can become
overwhelming if enough users are hitting the error and log files are
typically never looked at. This is why we recommend using Sentry for dealing with application errors. It’s
available as a source-available project on GitHub and is also available as a hosted version which you can try for free. Sentry
aggregates duplicate errors, captures the full stack trace and local
variables for debugging, and sends you mails based on new errors or
frequency thresholds.

To use Sentry you need to install the sentry-sdk client with extra
flask dependencies.

$ pip install sentry-sdk[flask]

And then add this to your Flask app:

import sentry_sdk
from sentry_sdk.integrations.flask import FlaskIntegration

sentry_sdk.init('YOUR_DSN_HERE', integrations=[FlaskIntegration()])

The YOUR_DSN_HERE value needs to be replaced with the DSN value you
get from your Sentry installation.

After installation, failures leading to an Internal Server Error
are automatically reported to Sentry and from there you can
receive error notifications.

See also:

  • Sentry also supports catching errors from a worker queue
    (RQ, Celery, etc.) in a similar fashion. See the Python SDK docs for more information.
  • Getting started with Sentry
  • Flask-specific documentation

Error Handlers

When an error occurs in Flask, an appropriate HTTP status code will be
returned. 400-499 indicate errors with the client’s request data, or
about the data requested. 500-599 indicate errors with the server or
application itself.

You might want to show custom error pages to the user when an error occurs.
This can be done by registering error handlers.

An error handler is a function that returns a response when a type of error is
raised, similar to how a view is a function that returns a response when a
request URL is matched. It is passed the instance of the error being handled,
which is most likely a :exc:`~werkzeug.exceptions.HTTPException`.

The status code of the response will not be set to the handler’s code. Make
sure to provide the appropriate HTTP status code when returning a response from
a handler.

Registering

Register handlers by decorating a function with
:meth:`~flask.Flask.errorhandler`. Or use
:meth:`~flask.Flask.register_error_handler` to register the function later.
Remember to set the error code when returning the response.

@app.errorhandler(werkzeug.exceptions.BadRequest)
def handle_bad_request(e):
    return 'bad request!', 400

# or, without the decorator
app.register_error_handler(400, handle_bad_request)

:exc:`werkzeug.exceptions.HTTPException` subclasses like
:exc:`~werkzeug.exceptions.BadRequest` and their HTTP codes are interchangeable
when registering handlers. (BadRequest.code == 400)

Non-standard HTTP codes cannot be registered by code because they are not known
by Werkzeug. Instead, define a subclass of
:class:`~werkzeug.exceptions.HTTPException` with the appropriate code and
register and raise that exception class.

class InsufficientStorage(werkzeug.exceptions.HTTPException):
    code = 507
    description = 'Not enough storage space.'

app.register_error_handler(InsufficientStorage, handle_507)

raise InsufficientStorage()

Handlers can be registered for any exception class, not just
:exc:`~werkzeug.exceptions.HTTPException` subclasses or HTTP status
codes. Handlers can be registered for a specific class, or for all subclasses
of a parent class.

Handling

When building a Flask application you will run into exceptions. If some part
of your code breaks while handling a request (and you have no error handlers
registered), a «500 Internal Server Error»
(:exc:`~werkzeug.exceptions.InternalServerError`) will be returned by default.
Similarly, «404 Not Found»
(:exc:`~werkzeug.exceptions.NotFound`) error will occur if a request is sent to an unregistered route.
If a route receives an unallowed request method, a «405 Method Not Allowed»
(:exc:`~werkzeug.exceptions.MethodNotAllowed`) will be raised. These are all
subclasses of :class:`~werkzeug.exceptions.HTTPException` and are provided by
default in Flask.

Flask gives you the ability to raise any HTTP exception registered by
Werkzeug. However, the default HTTP exceptions return simple exception
pages. You might want to show custom error pages to the user when an error occurs.
This can be done by registering error handlers.

When Flask catches an exception while handling a request, it is first looked up by code.
If no handler is registered for the code, Flask looks up the error by its class hierarchy; the most specific handler is chosen.
If no handler is registered, :class:`~werkzeug.exceptions.HTTPException` subclasses show a
generic message about their code, while other exceptions are converted to a
generic «500 Internal Server Error».

For example, if an instance of :exc:`ConnectionRefusedError` is raised,
and a handler is registered for :exc:`ConnectionError` and
:exc:`ConnectionRefusedError`, the more specific :exc:`ConnectionRefusedError`
handler is called with the exception instance to generate the response.

Handlers registered on the blueprint take precedence over those registered
globally on the application, assuming a blueprint is handling the request that
raises the exception. However, the blueprint cannot handle 404 routing errors
because the 404 occurs at the routing level before the blueprint can be
determined.

Generic Exception Handlers

It is possible to register error handlers for very generic base classes
such as HTTPException or even Exception. However, be aware that
these will catch more than you might expect.

For example, an error handler for HTTPException might be useful for turning
the default HTML errors pages into JSON. However, this
handler will trigger for things you don’t cause directly, such as 404
and 405 errors during routing. Be sure to craft your handler carefully
so you don’t lose information about the HTTP error.

from flask import json
from werkzeug.exceptions import HTTPException

@app.errorhandler(HTTPException)
def handle_exception(e):
    """Return JSON instead of HTML for HTTP errors."""
    # start with the correct headers and status code from the error
    response = e.get_response()
    # replace the body with JSON
    response.data = json.dumps({
        "code": e.code,
        "name": e.name,
        "description": e.description,
    })
    response.content_type = "application/json"
    return response

An error handler for Exception might seem useful for changing how
all errors, even unhandled ones, are presented to the user. However,
this is similar to doing except Exception: in Python, it will
capture all otherwise unhandled errors, including all HTTP status
codes.

In most cases it will be safer to register handlers for more
specific exceptions. Since HTTPException instances are valid WSGI
responses, you could also pass them through directly.

from werkzeug.exceptions import HTTPException

@app.errorhandler(Exception)
def handle_exception(e):
    # pass through HTTP errors
    if isinstance(e, HTTPException):
        return e

    # now you're handling non-HTTP exceptions only
    return render_template("500_generic.html", e=e), 500

Error handlers still respect the exception class hierarchy. If you
register handlers for both HTTPException and Exception, the
Exception handler will not handle HTTPException subclasses
because it the HTTPException handler is more specific.

Unhandled Exceptions

When there is no error handler registered for an exception, a 500
Internal Server Error will be returned instead. See
:meth:`flask.Flask.handle_exception` for information about this
behavior.

If there is an error handler registered for InternalServerError,
this will be invoked. As of Flask 1.1.0, this error handler will always
be passed an instance of InternalServerError, not the original
unhandled error.

The original error is available as e.original_exception.

An error handler for «500 Internal Server Error» will be passed uncaught
exceptions in addition to explicit 500 errors. In debug mode, a handler
for «500 Internal Server Error» will not be used. Instead, the
interactive debugger will be shown.

Custom Error Pages

Sometimes when building a Flask application, you might want to raise a
:exc:`~werkzeug.exceptions.HTTPException` to signal to the user that
something is wrong with the request. Fortunately, Flask comes with a handy
:func:`~flask.abort` function that aborts a request with a HTTP error from
werkzeug as desired. It will also provide a plain black and white error page
for you with a basic description, but nothing fancy.

Depending on the error code it is less or more likely for the user to
actually see such an error.

Consider the code below, we might have a user profile route, and if the user
fails to pass a username we can raise a «400 Bad Request». If the user passes a
username and we can’t find it, we raise a «404 Not Found».

from flask import abort, render_template, request

# a username needs to be supplied in the query args
# a successful request would be like /profile?username=jack
@app.route("/profile")
def user_profile():
    username = request.arg.get("username")
    # if a username isn't supplied in the request, return a 400 bad request
    if username is None:
        abort(400)

    user = get_user(username=username)
    # if a user can't be found by their username, return 404 not found
    if user is None:
        abort(404)

    return render_template("profile.html", user=user)

Here is another example implementation for a «404 Page Not Found» exception:

from flask import render_template

@app.errorhandler(404)
def page_not_found(e):
    # note that we set the 404 status explicitly
    return render_template('404.html'), 404

When using :doc:`/patterns/appfactories`:

from flask import Flask, render_template

def page_not_found(e):
  return render_template('404.html'), 404

def create_app(config_filename):
    app = Flask(__name__)
    app.register_error_handler(404, page_not_found)
    return app

An example template might be this:

{% extends "layout.html" %}
{% block title %}Page Not Found{% endblock %}
{% block body %}
  <h1>Page Not Found</h1>
  <p>What you were looking for is just not there.
  <p><a href="{{ url_for('index') }}">go somewhere nice</a>
{% endblock %}

Further Examples

The above examples wouldn’t actually be an improvement on the default
exception pages. We can create a custom 500.html template like this:

{% extends "layout.html" %}
{% block title %}Internal Server Error{% endblock %}
{% block body %}
  <h1>Internal Server Error</h1>
  <p>Oops... we seem to have made a mistake, sorry!</p>
  <p><a href="{{ url_for('index') }}">Go somewhere nice instead</a>
{% endblock %}

It can be implemented by rendering the template on «500 Internal Server Error»:

from flask import render_template

@app.errorhandler(500)
def internal_server_error(e):
    # note that we set the 500 status explicitly
    return render_template('500.html'), 500

When using :doc:`/patterns/appfactories`:

from flask import Flask, render_template

def internal_server_error(e):
  return render_template('500.html'), 500

def create_app():
    app = Flask(__name__)
    app.register_error_handler(500, internal_server_error)
    return app

When using :doc:`/blueprints`:

from flask import Blueprint

blog = Blueprint('blog', __name__)

# as a decorator
@blog.errorhandler(500)
def internal_server_error(e):
    return render_template('500.html'), 500

# or with register_error_handler
blog.register_error_handler(500, internal_server_error)

Blueprint Error Handlers

In :doc:`/blueprints`, most error handlers will work as expected.
However, there is a caveat concerning handlers for 404 and 405
exceptions. These error handlers are only invoked from an appropriate
raise statement or a call to abort in another of the blueprint’s
view functions; they are not invoked by, e.g., an invalid URL access.

This is because the blueprint does not «own» a certain URL space, so
the application instance has no way of knowing which blueprint error
handler it should run if given an invalid URL. If you would like to
execute different handling strategies for these errors based on URL
prefixes, they may be defined at the application level using the
request proxy object.

from flask import jsonify, render_template

# at the application level
# not the blueprint level
@app.errorhandler(404)
def page_not_found(e):
    # if a request is in our blog URL space
    if request.path.startswith('/blog/'):
        # we return a custom blog 404 page
        return render_template("blog/404.html"), 404
    else:
        # otherwise we return our generic site-wide 404 page
        return render_template("404.html"), 404

@app.errorhandler(405)
def method_not_allowed(e):
    # if a request has the wrong method to our API
    if request.path.startswith('/api/'):
        # we return a json saying so
        return jsonify(message="Method Not Allowed"), 405
    else:
        # otherwise we return a generic site-wide 405 page
        return render_template("405.html"), 405

Returning API Errors as JSON

When building APIs in Flask, some developers realise that the built-in
exceptions are not expressive enough for APIs and that the content type of
:mimetype:`text/html` they are emitting is not very useful for API consumers.

Using the same techniques as above and :func:`~flask.json.jsonify` we can return JSON
responses to API errors. :func:`~flask.abort` is called
with a description parameter. The error handler will
use that as the JSON error message, and set the status code to 404.

from flask import abort, jsonify

@app.errorhandler(404)
def resource_not_found(e):
    return jsonify(error=str(e)), 404

@app.route("/cheese")
def get_one_cheese():
    resource = get_resource()

    if resource is None:
        abort(404, description="Resource not found")

    return jsonify(resource)

We can also create custom exception classes. For instance, we can
introduce a new custom exception for an API that can take a proper human readable message,
a status code for the error and some optional payload to give more context
for the error.

This is a simple example:

from flask import jsonify, request

class InvalidAPIUsage(Exception):
    status_code = 400

    def __init__(self, message, status_code=None, payload=None):
        super().__init__()
        self.message = message
        if status_code is not None:
            self.status_code = status_code
        self.payload = payload

    def to_dict(self):
        rv = dict(self.payload or ())
        rv['message'] = self.message
        return rv

@app.errorhandler(InvalidAPIUsage)
def invalid_api_usage(e):
    return jsonify(e.to_dict()), e.status_code

# an API app route for getting user information
# a correct request might be /api/user?user_id=420
@app.route("/api/user")
def user_api(user_id):
    user_id = request.arg.get("user_id")
    if not user_id:
        raise InvalidAPIUsage("No user id provided!")

    user = get_user(user_id=user_id)
    if not user:
        raise InvalidAPIUsage("No such user!", status_code=404)

    return jsonify(user.to_dict())

A view can now raise that exception with an error message. Additionally
some extra payload can be provided as a dictionary through the payload
parameter.

Logging

See :doc:`/logging` for information about how to log exceptions, such as
by emailing them to admins.

Debugging

See :doc:`/debugging` for information about how to debug errors in
development and production.

Applications fail, servers fail. Sooner or later you will see an exception
in production. Even if your code is 100% correct, you will still see
exceptions from time to time. Why? Because everything else involved will
fail. Here are some situations where perfectly fine code can lead to server
errors:

  • the client terminated the request early and the application was still
    reading from the incoming data

  • the database server was overloaded and could not handle the query

  • a filesystem is full

  • a harddrive crashed

  • a backend server overloaded

  • a programming error in a library you are using

  • network connection of the server to another system failed

And that’s just a small sample of issues you could be facing. So how do we
deal with that sort of problem? By default if your application runs in
production mode, and an exception is raised Flask will display a very simple
page for you and log the exception to the logger.

But there is more you can do, and we will cover some better setups to deal
with errors including custom exceptions and 3rd party tools.

Error Logging Tools¶

Sending error mails, even if just for critical ones, can become
overwhelming if enough users are hitting the error and log files are
typically never looked at. This is why we recommend using Sentry for dealing with application errors. It’s
available as a source-available project on GitHub and is also available as a hosted version which you can try for free. Sentry
aggregates duplicate errors, captures the full stack trace and local
variables for debugging, and sends you mails based on new errors or
frequency thresholds.

To use Sentry you need to install the sentry-sdk client with extra
flask dependencies.

$ pip install sentry-sdk[flask]

And then add this to your Flask app:

import sentry_sdk
from sentry_sdk.integrations.flask import FlaskIntegration

sentry_sdk.init('YOUR_DSN_HERE', integrations=[FlaskIntegration()])

The YOUR_DSN_HERE value needs to be replaced with the DSN value you
get from your Sentry installation.

After installation, failures leading to an Internal Server Error
are automatically reported to Sentry and from there you can
receive error notifications.

See also:

  • Sentry also supports catching errors from a worker queue
    (RQ, Celery, etc.) in a similar fashion. See the Python SDK docs for more information.

  • Getting started with Sentry

  • Flask-specific documentation

Error Handlers¶

When an error occurs in Flask, an appropriate HTTP status code will be
returned. 400-499 indicate errors with the client’s request data, or
about the data requested. 500-599 indicate errors with the server or
application itself.

You might want to show custom error pages to the user when an error occurs.
This can be done by registering error handlers.

An error handler is a function that returns a response when a type of error is
raised, similar to how a view is a function that returns a response when a
request URL is matched. It is passed the instance of the error being handled,
which is most likely a HTTPException.

The status code of the response will not be set to the handler’s code. Make
sure to provide the appropriate HTTP status code when returning a response from
a handler.

Registering¶

Register handlers by decorating a function with
errorhandler(). Or use
register_error_handler() to register the function later.
Remember to set the error code when returning the response.

@app.errorhandler(werkzeug.exceptions.BadRequest)
def handle_bad_request(e):
    return 'bad request!', 400

# or, without the decorator
app.register_error_handler(400, handle_bad_request)

werkzeug.exceptions.HTTPException subclasses like
BadRequest and their HTTP codes are interchangeable
when registering handlers. (BadRequest.code == 400)

Non-standard HTTP codes cannot be registered by code because they are not known
by Werkzeug. Instead, define a subclass of
HTTPException with the appropriate code and
register and raise that exception class.

class InsufficientStorage(werkzeug.exceptions.HTTPException):
    code = 507
    description = 'Not enough storage space.'

app.register_error_handler(InsufficientStorage, handle_507)

raise InsufficientStorage()

Handlers can be registered for any exception class, not just
HTTPException subclasses or HTTP status
codes. Handlers can be registered for a specific class, or for all subclasses
of a parent class.

Handling¶

When building a Flask application you will run into exceptions. If some part
of your code breaks while handling a request (and you have no error handlers
registered), a “500 Internal Server Error”
(InternalServerError) will be returned by default.
Similarly, “404 Not Found”
(NotFound) error will occur if a request is sent to an unregistered route.
If a route receives an unallowed request method, a “405 Method Not Allowed”
(MethodNotAllowed) will be raised. These are all
subclasses of HTTPException and are provided by
default in Flask.

Flask gives you the ability to raise any HTTP exception registered by
Werkzeug. However, the default HTTP exceptions return simple exception
pages. You might want to show custom error pages to the user when an error occurs.
This can be done by registering error handlers.

When Flask catches an exception while handling a request, it is first looked up by code.
If no handler is registered for the code, Flask looks up the error by its class hierarchy; the most specific handler is chosen.
If no handler is registered, HTTPException subclasses show a
generic message about their code, while other exceptions are converted to a
generic “500 Internal Server Error”.

For example, if an instance of ConnectionRefusedError is raised,
and a handler is registered for ConnectionError and
ConnectionRefusedError, the more specific ConnectionRefusedError
handler is called with the exception instance to generate the response.

Handlers registered on the blueprint take precedence over those registered
globally on the application, assuming a blueprint is handling the request that
raises the exception. However, the blueprint cannot handle 404 routing errors
because the 404 occurs at the routing level before the blueprint can be
determined.

Generic Exception Handlers¶

It is possible to register error handlers for very generic base classes
such as HTTPException or even Exception. However, be aware that
these will catch more than you might expect.

For example, an error handler for HTTPException might be useful for turning
the default HTML errors pages into JSON. However, this
handler will trigger for things you don’t cause directly, such as 404
and 405 errors during routing. Be sure to craft your handler carefully
so you don’t lose information about the HTTP error.

from flask import json
from werkzeug.exceptions import HTTPException

@app.errorhandler(HTTPException)
def handle_exception(e):
    """Return JSON instead of HTML for HTTP errors."""
    # start with the correct headers and status code from the error
    response = e.get_response()
    # replace the body with JSON
    response.data = json.dumps({
        "code": e.code,
        "name": e.name,
        "description": e.description,
    })
    response.content_type = "application/json"
    return response

An error handler for Exception might seem useful for changing how
all errors, even unhandled ones, are presented to the user. However,
this is similar to doing except Exception: in Python, it will
capture all otherwise unhandled errors, including all HTTP status
codes.

In most cases it will be safer to register handlers for more
specific exceptions. Since HTTPException instances are valid WSGI
responses, you could also pass them through directly.

from werkzeug.exceptions import HTTPException

@app.errorhandler(Exception)
def handle_exception(e):
    # pass through HTTP errors
    if isinstance(e, HTTPException):
        return e

    # now you're handling non-HTTP exceptions only
    return render_template("500_generic.html", e=e), 500

Error handlers still respect the exception class hierarchy. If you
register handlers for both HTTPException and Exception, the
Exception handler will not handle HTTPException subclasses
because it the HTTPException handler is more specific.

Unhandled Exceptions¶

When there is no error handler registered for an exception, a 500
Internal Server Error will be returned instead. See
flask.Flask.handle_exception() for information about this
behavior.

If there is an error handler registered for InternalServerError,
this will be invoked. As of Flask 1.1.0, this error handler will always
be passed an instance of InternalServerError, not the original
unhandled error.

The original error is available as e.original_exception.

An error handler for “500 Internal Server Error” will be passed uncaught
exceptions in addition to explicit 500 errors. In debug mode, a handler
for “500 Internal Server Error” will not be used. Instead, the
interactive debugger will be shown.

Custom Error Pages¶

Sometimes when building a Flask application, you might want to raise a
HTTPException to signal to the user that
something is wrong with the request. Fortunately, Flask comes with a handy
abort() function that aborts a request with a HTTP error from
werkzeug as desired. It will also provide a plain black and white error page
for you with a basic description, but nothing fancy.

Depending on the error code it is less or more likely for the user to
actually see such an error.

Consider the code below, we might have a user profile route, and if the user
fails to pass a username we can raise a “400 Bad Request”. If the user passes a
username and we can’t find it, we raise a “404 Not Found”.

from flask import abort, render_template, request

# a username needs to be supplied in the query args
# a successful request would be like /profile?username=jack
@app.route("/profile")
def user_profile():
    username = request.arg.get("username")
    # if a username isn't supplied in the request, return a 400 bad request
    if username is None:
        abort(400)

    user = get_user(username=username)
    # if a user can't be found by their username, return 404 not found
    if user is None:
        abort(404)

    return render_template("profile.html", user=user)

Here is another example implementation for a “404 Page Not Found” exception:

from flask import render_template

@app.errorhandler(404)
def page_not_found(e):
    # note that we set the 404 status explicitly
    return render_template('404.html'), 404

When using Application Factories:

from flask import Flask, render_template

def page_not_found(e):
  return render_template('404.html'), 404

def create_app(config_filename):
    app = Flask(__name__)
    app.register_error_handler(404, page_not_found)
    return app

An example template might be this:

{% extends "layout.html" %}
{% block title %}Page Not Found{% endblock %}
{% block body %}
  <h1>Page Not Found</h1>
  <p>What you were looking for is just not there.
  <p><a href="{{ url_for('index') }}">go somewhere nice</a>
{% endblock %}

Further Examples¶

The above examples wouldn’t actually be an improvement on the default
exception pages. We can create a custom 500.html template like this:

{% extends "layout.html" %}
{% block title %}Internal Server Error{% endblock %}
{% block body %}
  <h1>Internal Server Error</h1>
  <p>Oops... we seem to have made a mistake, sorry!</p>
  <p><a href="{{ url_for('index') }}">Go somewhere nice instead</a>
{% endblock %}

It can be implemented by rendering the template on “500 Internal Server Error”:

from flask import render_template

@app.errorhandler(500)
def internal_server_error(e):
    # note that we set the 500 status explicitly
    return render_template('500.html'), 500

When using Application Factories:

from flask import Flask, render_template

def internal_server_error(e):
  return render_template('500.html'), 500

def create_app():
    app = Flask(__name__)
    app.register_error_handler(500, internal_server_error)
    return app

When using Modular Applications with Blueprints:

from flask import Blueprint

blog = Blueprint('blog', __name__)

# as a decorator
@blog.errorhandler(500)
def internal_server_error(e):
    return render_template('500.html'), 500

# or with register_error_handler
blog.register_error_handler(500, internal_server_error)

Blueprint Error Handlers¶

In Modular Applications with Blueprints, most error handlers will work as expected.
However, there is a caveat concerning handlers for 404 and 405
exceptions. These error handlers are only invoked from an appropriate
raise statement or a call to abort in another of the blueprint’s
view functions; they are not invoked by, e.g., an invalid URL access.

This is because the blueprint does not “own” a certain URL space, so
the application instance has no way of knowing which blueprint error
handler it should run if given an invalid URL. If you would like to
execute different handling strategies for these errors based on URL
prefixes, they may be defined at the application level using the
request proxy object.

from flask import jsonify, render_template

# at the application level
# not the blueprint level
@app.errorhandler(404)
def page_not_found(e):
    # if a request is in our blog URL space
    if request.path.startswith('/blog/'):
        # we return a custom blog 404 page
        return render_template("blog/404.html"), 404
    else:
        # otherwise we return our generic site-wide 404 page
        return render_template("404.html"), 404

@app.errorhandler(405)
def method_not_allowed(e):
    # if a request has the wrong method to our API
    if request.path.startswith('/api/'):
        # we return a json saying so
        return jsonify(message="Method Not Allowed"), 405
    else:
        # otherwise we return a generic site-wide 405 page
        return render_template("405.html"), 405

Returning API Errors as JSON¶

When building APIs in Flask, some developers realise that the built-in
exceptions are not expressive enough for APIs and that the content type of
text/html they are emitting is not very useful for API consumers.

Using the same techniques as above and jsonify() we can return JSON
responses to API errors. abort() is called
with a description parameter. The error handler will
use that as the JSON error message, and set the status code to 404.

from flask import abort, jsonify

@app.errorhandler(404)
def resource_not_found(e):
    return jsonify(error=str(e)), 404

@app.route("/cheese")
def get_one_cheese():
    resource = get_resource()

    if resource is None:
        abort(404, description="Resource not found")

    return jsonify(resource)

We can also create custom exception classes. For instance, we can
introduce a new custom exception for an API that can take a proper human readable message,
a status code for the error and some optional payload to give more context
for the error.

This is a simple example:

from flask import jsonify, request

class InvalidAPIUsage(Exception):
    status_code = 400

    def __init__(self, message, status_code=None, payload=None):
        super().__init__()
        self.message = message
        if status_code is not None:
            self.status_code = status_code
        self.payload = payload

    def to_dict(self):
        rv = dict(self.payload or ())
        rv['message'] = self.message
        return rv

@app.errorhandler(InvalidAPIUsage)
def invalid_api_usage(e):
    return jsonify(e.to_dict()), e.status_code

# an API app route for getting user information
# a correct request might be /api/user?user_id=420
@app.route("/api/user")
def user_api(user_id):
    user_id = request.arg.get("user_id")
    if not user_id:
        raise InvalidAPIUsage("No user id provided!")

    user = get_user(user_id=user_id)
    if not user:
        raise InvalidAPIUsage("No such user!", status_code=404)

    return jsonify(user.to_dict())

A view can now raise that exception with an error message. Additionally
some extra payload can be provided as a dictionary through the payload
parameter.

Logging¶

See Logging for information about how to log exceptions, such as
by emailing them to admins.

Debugging¶

See Debugging Application Errors for information about how to debug errors in
development and production.

We’re using Flask for one of our API’s and I was just wondering if anyone knew how to return a HTTP response 201?

For errors such as 404 we can call:

from flask import abort
abort(404)

But for 201 I get

LookupError: no exception for 201

Do I need to create my own exception like this in the docs?

Kevin Brown-Silva's user avatar

asked Oct 19, 2011 at 15:48

ingh.am's user avatar

2

You can use Response to return any http status code.

> from flask import Response
> return Response("{'a':'b'}", status=201, mimetype='application/json')

answered Sep 13, 2017 at 13:52

Yasir's user avatar

YasirYasir

4,4576 gold badges22 silver badges19 bronze badges

0

You can read about it here.

return render_template('page.html'), 201

answered Oct 19, 2011 at 16:23

Iacks's user avatar

IacksIacks

3,7092 gold badges20 silver badges24 bronze badges

2

You can do

result = {'a': 'b'}
return result, 201

if you want to return a JSON data in the response along with the error code
You can read about responses here and here for make_response API details

answered Jan 25, 2019 at 8:28

Kishan K's user avatar

Kishan KKishan K

5815 silver badges17 bronze badges

0

As lacks suggested send status code in return statement
and if you are storing it in some variable like

notfound = 404
invalid = 403
ok = 200

and using

return xyz, notfound

than time make sure its type is int not str. as I faced this small issue
also here is list of status code followed globally
http://www.w3.org/Protocols/HTTP/HTRESP.html

Hope it helps.

answered Jul 18, 2014 at 12:22

Harsh Daftary's user avatar

Harsh DaftaryHarsh Daftary

2,5351 gold badge13 silver badges12 bronze badges

1

In your flask code, you should ideally specify the MIME type as often as possible, as well:

return html_page_str, 200, {'ContentType':'text/html'}

return json.dumps({'success':True}), 200, {'ContentType':'application/json'}

…etc

Axe's user avatar

Axe

6,2153 gold badges30 silver badges38 bronze badges

answered Sep 11, 2017 at 16:51

Ben Wheeler's user avatar

Ben WheelerBen Wheeler

6,5332 gold badges44 silver badges55 bronze badges

Ripping off Luc’s comment here, but to return a blank response, like a 201 the simplest option is to use the following return in your route.

return "", 201

So for example:

    @app.route('/database', methods=["PUT"])
    def database():
        update_database(request)
        return "", 201

answered Jan 26, 2021 at 11:12

Matt Copperwaite's user avatar

you can also use flask_api for sending response

from flask_api import status

@app.route('/your-api/')
def empty_view(self):
    content = {'your content here'}
    return content, status.HTTP_201_CREATED

you can find reference here http://www.flaskapi.org/api-guide/status-codes/

answered Oct 12, 2019 at 11:04

Pushprajsinh Chudasama's user avatar

1

In my case I had to combine the above in order to make it work

return Response(json.dumps({'Error': 'Error in payload'}), 
status=422, 
mimetype="application/json")

answered Oct 3, 2019 at 10:29

Cheetara's user avatar

CheetaraCheetara

1651 gold badge5 silver badges14 bronze badges

Dependent on how the API is created, normally with a 201 (created) you would return the resource which was created. For example if it was creating a user account you would do something like:

return {"data": {"username": "test","id":"fdsf345"}}, 201

Note the postfixed number is the status code returned.

Alternatively, you may want to send a message to the client such as:

return {"msg": "Created Successfully"}, 201

answered Dec 4, 2019 at 7:34

Croc's user avatar

CrocCroc

7717 silver badges13 bronze badges

for error 404 you can

def post():
    #either pass or get error 
    post = Model.query.get_or_404()
    return jsonify(post.to_json())

for 201 success

def new_post():
    post = Model.from_json(request.json)
    return jsonify(post.to_json()), 201, 
      {'Location': url_for('api.get_post', id=post.id, _external=True)}

answered Apr 19, 2021 at 5:27

Josie Koay's user avatar

Josie KoayJosie Koay

6375 silver badges8 bronze badges

You just need to add your status code after your returning data like this:

from flask import Flask

app = Flask(__name__)
@app.route('/')
def hello_world():  # put application's code here
    return 'Hello World!',201
if __name__ == '__main__':
    app.run()

It’s a basic flask project. After starting it and you will find that when we request http://127.0.0.1:5000/ you will get a status 201 from web broswer console.

answered Dec 18, 2021 at 14:01

Xie Yuchen's user avatar

1

So, if you are using flask_restful Package for API’s
returning 201 would becomes like

def bla(*args, **kwargs):
    ...
    return data, 201

where data should be any hashable/ JsonSerialiable value, like dict, string.

answered Dec 4, 2019 at 4:48

Deepak Sharma's user avatar

  1. Home
  2. Flask tutorial
  3. Custom Response and Hook Points in Flask

Last updated on July 27, 2020


Custom Response #

Flask provides three different patterns for creating response:

  1. As a string or using a template engine.
  2. As a response object.
  3. As a tuple in the form (response, status, headers) or (response, headers).

Let’s take a look at these patterns one by one.

Creating Response as a String #

@app.route('/books/<genre>')
def books(genre):
    return "All Books in {} category".format(genre)

So far we have used this pattern to send the response to the client. When Flask sees that we are returning a string from a view function it automatically converts the string into a response object ( using make_response() method ) with string as the body of the response, HTTP status code of 200 and content-type header set to text/html. Most of the time that’s all you need. However, sometimes you would need to set some additional headers before sending the response to the client. For such cases, you have to create the response using the make_response() function.

Creating response using make_response() #

The syntax of the make_response() is as follows:

res_obj = make_response(res_body, status_code=200)

The res_body is the required argument which represents the response body and status_code is the optional HTTP status code which defaults to 200.

The following listing shows how to set additional headers using the make_response() function.

from flask import Flask, make_response, 

@app.route('/books/<genre>')
def books(genre):
    res = make_response("All Books in {} category".format(genre))
    res.headers['Content-Type'] = 'text/plain'
    res.headers['Server'] = 'Foobar'
    return res

The following listing shows how you can return HTTP 404 error using the make_response() function.

@app.route('/')
def http_404_handler():
    return make_response("<h2>404 Error</h2>", 400)

Setting cookies is another common task in a web application. The make_response() function makes this operation very easy. The following listing set two cookies in the client’s browser.

@app.route('/set-cookie')
def set_cookie():
    res = make_response("Cookie setter")    
    res.set_cookie("favorite-color", "skyblue")
    res.set_cookie("favorite-font", "sans-serif")
    return res

Note: We are discussing cookies in detail in lesson Cookies in Flask.

The cookies set by the above listing will last until the browser session. We can set the expiration time of cookie by passing number of seconds as a third argument to the set_cookie() method. For example:

@app.route('/cookie')
def set_cookie():
    res = make_response("Cookie setter")
    res.set_cookie("favorite-color", "skyblue", 60*60*24*15)
    res.set_cookie("favorite-font", "sans-serif", 60*60*24*15)
    return res

This listing sets the expiration time of the cookies to 15 days.

Creating Response using Tuples #

The last pattern to create response is to use tuples in one of the following formats:

(response, status, headers) 

(response, headers) 

(response, status)

The response is a string which represents the body of the response, status is the HTTP status code it can be integer or string and headers is a dictionary containing header values.

@app.route('/')
def http_500_handler():
    return ("<h2>500 Error</h2>", 500)

This view function will return HTTP 500 Internal Server Error. Since we can omit parentheses while creating tuples, the above code can also be written as follows:

@app.route('/')
def http_500_handler():
    return "<h2>500 Error</h2>", 500

The following listing shows how to set headers using tuples:

@app.route('/')
def render_markdown():
    return "## Heading", 200, {'Content-Type': 'text/markdown'}

Can you guess what the following view function does?

@app.route('/transfer')
def transfer():
    return "", 302, {'location': 'http://localhost:5000/login'}

This view function redirects the user to http://localhost:5000/login using HTTP 302 response code (a temporary redirect). Redirecting a user to a different page is so common that Flask provides a helper function called redirect() to make the job easier.

from flask import Flask, redirect

@app.route('/transfer')
def transfer():
    return redirect("http://localhost:5000/login")

By default, redirect() performs a HTTP 302 redirect, to perform a HTTP 301 redirect pass the HTTP status code of 301 to the redirect() function as follows:

from flask import Flask, redirect

@app.route('/transfer')
def transfer():
    return redirect("http://localhost:5000/login", code=301)

Hook Points #

In a web application, it is quite common to execute some code before after every request. For example, let’s say we want to log the IP address of users who are visiting our application or authenticate a user before displaying hidden pages. Rather than duplicating such code inside every view function (which would be crazy) Flask provides following decorators for such scenarios:

  • before_first_request: This decorator registers a function to execute before the first request is handled.

  • before_request: This decorator registers a function to execute before a request is handled.

  • after_request: This decorator registers a function to execute after a request is handled. The registered function will not be called in case an unhandled exception occurred in the request handler. The function must accept a response object and return the same or new response.

  • teardown_request: Similar to after_request decorator but the registered function will always execute regardless of whether the request handler throws an exception or not.

Note that if the function registered by before_request decorator returns a response then the request handler will not be called.

The following listing demonstrates how to utilize hooks points in Flask. Create a new file named hooks.py with the code as shown below:

flask_app/hooks.py

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
from flask import Flask, request, g

app = Flask(__name__)

@app.before_first_request
def before_first_request():
    print("before_first_request() called")

@app.before_request
def before_request():
    print("before_request() called")

@app.after_request
def after_request(response):
    print("after_request() called")
    return response

@app.route("/")
def index():
    print("index() called")
    return '<p>Testings Request Hooks</p>'


if __name__ == "__main__":
    app.run(debug=True)

Start the server and make your first request by visiting http://localhost:5000/. In the standard output of the shell that runs the server you should get following output:

before_first_request() called
before_request() called
index() called
after_request() called

Note: Server request logs are omitted for brevity.

Refresh the page and this time you should get the following output in the shell.

before_request() called
index() called
after_request() called

As this is our second request before_first_request() function is not executed.

Aborting Request using abort() #

Flask provides a function named abort() for terminating a request with a specific error code like 404, 500 and so on. For example:

from flask import Flask, abort

@app.route('/')
def index():
    abort(404)
    # code after abort() execution will never be executed

This view function will return a generic 404 page that looks like this:

The abort() will display similar pages for other types of errors. If you want to customize the error pages use errorhandler decorator which is discussed next.

Custom Error Pages #

The errorhandler decorator is used to create custom error pages. It accepts a single argument which is the HTTP error code for which you are creating custom error page. Open hooks.py file and create custom error pages for HTTP 404 and HTTP 500 errors using errorhandler decorator as follows (changes are highlighted):

flask_app/hooks.py

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
from flask import Flask, request, g, abort
#...
#...
@app.after_request
def after_request(response):
    print("after_request() called")
    return response

@app.errorhandler(404)
def http_404_handler(error):
    return "<p>HTTP 404 Error Encountered</p>", 404

@app.errorhandler(500)
def http_500_handler(error):
    return "<p>HTTP 500 Error Encountered</p>", 500

@app.route("/")
def index():
    # print("index() called")
    # return '<p>Testings Request Hooks</p>'
    abort(404)  

if __name__ == "__main__":
#...

Notice that both error handlers takes a single argument named error which contains additional information about the type of error occurred.

If you now visit the root URL, you will get the following response:



Ezoic

Время прочтения
14 мин

Просмотры 50K

blog.miguelgrinberg.com

Miguel Grinberg


<<< предыдущая следующая >>>

Эта статья является переводом седьмой части нового издания учебника Мигеля Гринберга, выпуск которого автор планирует завершить в мае 2018.Прежний перевод давно утратил свою актуальность.

Я, со своей стороны, постараюсь не отставать с переводом.


Это седьмая глава серии Flask Mega-Tutorial, в которой я расскажу вам, как выполнять обработку ошибок в приложении Flask.

Для справки ниже приведен список статей этой серии.

Примечание 1: Если вы ищете старые версии данного курса, это здесь.

Примечание 2: Если вдруг Вы хотели бы выступить в поддержку моей(Мигеля) работы в этом блоге, или просто не имеете терпения дожидаться неделю статьи, я (Мигель Гринберг)предлагаю полную версию данного руководства упакованную электронную книгу или видео. Для получения более подробной информации посетите learn.miguelgrinberg.com.

В этой главе я перехожу от кодирования новых функций для моего микроблогического приложения и вместо этого обсужу несколько стратегий борьбы с ошибками, которые неизменно появляются в любом программном проекте. Чтобы проиллюстрировать эту тему, я намеренно допустил ошибку в коде, который я добавил в главе 6. Прежде чем продолжить чтение, посмотрите, сможете ли вы его найти!

Ссылки GitHub для этой главы: Browse, Zip, Diff.

Обработка ошибок в Flask

Что происходит, когда возникает ошибка в приложении Flask? Лучший способ узнать это — испытать это самому. Запустите приложение и убедитесь, что у вас зарегистрировано не менее двух пользователей. Войдите в систему как один из пользователей, откройте страницу профиля и нажмите ссылку «Изменить». В редакторе профиля попробуйте изменить имя пользователя на существующее имя другого пользователя, который уже зарегистрирован, и попытайтесь применить исправления! Это приведет к появлению страшной страницы «Internal Server Error» ( «Внутренняя ошибка сервера» ):

В сеансе терминала, на котором запущено приложение, вы видите трассировку стека ошибки. Трассировки стека чрезвычайно полезны при отладке ошибок, поскольку они показывают последовательность вызовов в этом стеке, вплоть до строки, вызвавшей ошибку:

(venv) $ flask run
 * Serving Flask app "microblog"
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
[2017-09-14 22:40:02,027] ERROR in app: Exception on /edit_profile [POST]
Traceback (most recent call last):
  File "/home/miguel/microblog/venv/lib/python3.6/site-packages/sqlalchemy/engine/base.py", line 1182, in _execute_context
    context)
  File "/home/miguel/microblog/venv/lib/python3.6/site-packages/sqlalchemy/engine/default.py", line 470, in do_execute
    cursor.execute(statement, parameters)
sqlite3.IntegrityError: UNIQUE constraint failed: user.username

Трассировка стека указывает, чем вызвана ошибка. Приложение позволяет пользователю изменять имя пользователя без проверки, что новое имя пользователя не совпадает с другим пользователем, уже находящимся в системе. Ошибка возникает из SQLAlchemy, которая пытается записать новое имя пользователя в базу данных, но база данных отвергает его, потому что столбец имени пользователя определен с unique = True.

Важно, что страница с ошибкой, представленная пользователю, не содержит много информации об ошибке, и это правильно. Я определенно не хочу, чтобы пользователи узнали, что авария была вызвана ошибкой базы данных или какой базой данных я пользуюсь, а также именами таблиц и полей в моей базе данных. Вся эта информация должна быть внутренней.

Есть несколько вещей, которые далеки от идеала. У меня есть страница с ошибкой, которая безобразна и не соответствует макету приложения. У меня также есть важные трассировки стека приложений, которые сбрасываются на терминале, и мне нужно постоянно следить за тем, чтобы я не пропустил никаких ошибок. И, конечно, у меня есть ошибка. Я собираюсь решить все эти проблемы, но сначала поговорим о режиме отладки Flask.

Режим отладки

То, как ошибки обрабатываются выше, отлично подходит для системы, которая работает на production сервере. Если есть ошибка, пользователь получает страницу с неопределенной ошибкой (хотя я собираюсь сделать эту страницу с ошибкой более приятной), а важные данные об ошибке — в выводе сервера или в файле журнала.

Но когда вы разрабатываете приложение, вы можете включить режим отладки, режим, в котором Flask выводит действительно хороший отладчик непосредственно в ваш браузер. Чтобы активировать режим отладки, остановите приложение, а затем установите следующую переменную среды:

(venv) $ export FLASK_DEBUG=1

Если вы работаете в ОС Microsoft Windows, не забудьте использовать set вместо экспорта.

После того, как вы установили FLASK_DEBUG, перезапустите сервер. Строки на вашем терминале будут немного отличаться от того, что вы привыкли видеть:

(venv) microblog2 $ flask run
 * Serving Flask app "microblog"
 * Forcing debug mode on
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 177-562-960

Теперь устроим приложению аварийный сбой еще раз, чтобы увидеть интерактивный отладчик в вашем браузере:

Отладчик позволяет развернуть каждый уровень стека и увидеть соответствующий исходный код. Вы также можете открыть Python для любого из фреймов и выполнить любые допустимые выражения Python, например, чтобы проверить значения переменных.

Крайне важно, чтобы вы никогда не запускали приложение Flask в режиме отладки на рабочем сервере. Отладчик позволяет удаленно выполнять код на сервере, поэтому он может стать неожиданным подарком злоумышленнику, который хочет проникнуть в ваше приложение или на ваш сервер. В качестве дополнительной меры безопасности отладчик, запущенный в браузере, закроется, и при первом использовании запросит PIN-код, который вы можете увидеть на выходе команды flask run.

Поскольку я говорю о режиме отладки, следует упомянуть про вторую важную функцию, которая включена в режиме отладки — перезагрузка. Это очень полезная функция разработки, которая автоматически перезапускает приложение при изменении исходного файла. Если вы выполните flask run в режиме отладки, можно продолжать работать в своем приложении и при каждом сохранении файла, приложение перезапустится, чтобы забрать новый код.

Пользовательские страницы ошибок

Flask предоставляет механизм приложения для создания собственных страниц ошибок, так что вашим пользователям не нужно видеть простые и скучные значения по умолчанию. В качестве примера давайте определим пользовательские страницы ошибок для ошибок HTTP 404 и 500, двух наиболее распространенных. Определение страниц для других ошибок работает одинаково.

Чтобы объявить пользовательский обработчик ошибок, используется декоратор @errorhandler. Я собираюсь поместить обработчики ошибок в новый модуль app/errors.py.

from flask import render_template
from app import app, db

@app.errorhandler(404)
def not_found_error(error):
    return render_template('404.html'), 404

@app.errorhandler(500)
def internal_error(error):
    db.session.rollback()
    return render_template('500.html'), 500

Функции ошибок работают аналогично функциям просмотра. Для этих двух ошибок я возвращаю содержимое их соответствующих шаблонов. Обратите внимание, что обе функции возвращают второе значение после шаблона, который является номером кода ошибки. Для всех функций представления, которые я создал до сих пор, мне не нужно было добавлять второе возвращаемое значение, потому что по умолчанию 200 (код состояния для успешного завершения) — это то, что я хотел. Сейчас это страницы с ошибками, поэтому я хочу, чтобы код состояния ответа это отражал.

Обработчик ошибок для 500-й ошибки может быть вызван после возникновения сбоя базы данных, которая на самом деле была вызвана умышленным случаем дубликата имени пользователя. Чтобы убедиться, что неудачные сеансы базы данных не мешают доступу к базе данных, вызванным шаблоном, я выдаю откат сеанса. Это сбрасывает сеанс в чистое состояние.

Вот шаблон для ошибки 404:

{% extends "base.html" %}

{% block content %}
    <h1>File Not Found</h1>
    <p><a href="{{ url_for('index') }}">Back</a></p>
{% endblock %}

И вот одна из ошибок 500:

{% extends "base.html" %}

{% block content %}
    <h1>An unexpected error has occurred</h1>
    <p>The administrator has been notified. Sorry for the inconvenience!</p>
    <p><a href="{{ url_for('index') }}">Back</a></p>
{% endblock %}

Оба шаблона наследуют шаблон base.html, так что страница с ошибками имеет тот же внешний вид, что и обычные страницы приложения.

Чтобы получить эти обработчики ошибок, зарегистрированные в Flask, мне нужно импортировать новый модуль app/errors.py после создания экземпляра приложения:

# ...

from app import routes, models, errors

Если вы установили FLASK_DEBUG = 0 в сеансе терминала и затем снова вызвали ошибку повторного имени пользователя, вы увидите более приятную страницу с ошибкой.

Или так! Рекомендую придумать что то свое в качестве упражнения.

Отправка ошибок по электронной почте

Другая проблема с обработкой ошибок по умолчанию, предоставляемой Flask, заключается в том, что нет уведомлений! Трассировка стека ошибки печатается на терминале, а это означает, что вывод процесса сервера должен контролироваться на обнаружение ошибок. Когда вы запускаете приложение во время разработки, это нормально, но как только приложение будет развернуто на production сервере, никто не будет смотреть на результат, поэтому необходимо создать более надежное решение.

Я думаю, что очень важно, чтобы я активно реагировал на ошибки. Если в production версии приложения возникает ошибка, я хочу знать сразу. Таким образом, моим первым решением будет сконфигурировать Flask для отправки мне сообщения по email сразу после возникновения ошибки с трассировкой стека ошибки в сообщении электронной почты.

Первым шагом является добавление данных сервера электронной почты в файл конфигурации:

class Config(object):
    # ...
    MAIL_SERVER = os.environ.get('MAIL_SERVER')
    MAIL_PORT = int(os.environ.get('MAIL_PORT') or 25)
    MAIL_USE_TLS = os.environ.get('MAIL_USE_TLS') is not None
    MAIL_USERNAME = os.environ.get('MAIL_USERNAME')
    MAIL_PASSWORD = os.environ.get('MAIL_PASSWORD')
    ADMINS = ['your-email@example.com']

Переменные конфигурации для электронной почты содержат сервер и порт, флаг для включения зашифрованных соединений и необязательное имя пользователя и пароль. Пять переменных конфигурации получены из их сопоставлений переменным среды. Если сервер электронной почты не установлен в среде, то я буду использовать это как знак того, что ошибки электронной почты должны быть отключены. Порт сервера электронной почты также можно указать в переменной среды, но если он не установлен, используется стандартный порт 25. Учетные данные почтового сервера по умолчанию не используются, но могут быть предоставлены при необходимости. Переменная конфигурации ADMINS представляет собой список адресов электронной почты, которые будут получать отчеты об ошибках, поэтому ваш собственный адрес электронной почты должен быть в этом списке.

Flask использует пакет logging Python для ведения своих журналов, а этот пакет уже имеет возможность отправлять журналы по электронной почте. Все, что мне нужно сделать, чтобы отправлять электронные сообщения, содержащие ошибки, — это добавить экземпляр SMTPHandler в объект журнала Flask, которым является app.logger:

import logging
from logging.handlers import SMTPHandler

# ...

if not app.debug:
    if app.config['MAIL_SERVER']:
        auth = None
        if app.config['MAIL_USERNAME'] or app.config['MAIL_PASSWORD']:
            auth = (app.config['MAIL_USERNAME'], app.config['MAIL_PASSWORD'])
        secure = None
        if app.config['MAIL_USE_TLS']:
            secure = ()
        mail_handler = SMTPHandler(
            mailhost=(app.config['MAIL_SERVER'], app.config['MAIL_PORT']),
            fromaddr='no-reply@' + app.config['MAIL_SERVER'],
            toaddrs=app.config['ADMINS'], subject='Microblog Failure',
            credentials=auth, secure=secure)
        mail_handler.setLevel(logging.ERROR)
        app.logger.addHandler(mail_handler)

Как видно, я включил регистратор электронной почты только, когда приложение работает без режима отладки, что определено приложением в app.debug как True, а также когда сервер электронной почты существует в конфигурации.

Настройка почтового регистратора несколько утомительна из-за необходимости обрабатывать дополнительные параметры безопасности, которые присутствуют на многих серверах электронной почты. Но в сущности, вышеприведенный код создает экземпляр SMTPHandler, устанавливает его уровень, чтобы он отправлял только сообщения об ошибках, а не предупреждения, информационные или отладочные сообщения и, наконец, прикреплял их к app.logger из Flask.

Существует два подхода к проверке работоспособности этой функции. Самый простой способ — использовать SMTP-сервер отладки от Python. Это ложный почтовый сервер, который принимает сообщения электронной почты, но вместо их отправки выводит их на консоль. Чтобы запустить этот сервер, откройте второй сеанс терминала и запустите на нем следующую команду:

(venv) $ python -m smtpd -n -c DebuggingServer localhost:8025

Оставьте запущенный SMTP-сервер отладки и вернитесь к своему первому терминалу и установите export MAIL_SERVER = localhost и MAIL_PORT = 8025 (используйте set вместо export, если вы используете Microsoft Windows). Убедитесь, что для переменной FLASK_DEBUG установлено значение 0 или не установлено вообще, так как приложение не будет отправлять электронные письма в режиме отладки.
Запустите приложение и вызовите ошибку SQLAlchemy еще раз, чтобы узнать, как сеанс терминала, на котором работает поддельный почтовый сервер, показывает электронное письмо с полным содержимым стека ошибки.

Второй метод тестирования для этой функции — настроить настоящий почтовый сервер. Ниже приведена конфигурация для использования почтового сервера для учетной записи Gmail:

export MAIL_SERVER=smtp.googlemail.com
export MAIL_PORT=587
export MAIL_USE_TLS=1
export MAIL_USERNAME=<your-gmail-username>
export MAIL_PASSWORD=<your-gmail-password>

Если вы используете Microsoft Windows, не забудьте использовать set вместо export в каждой из приведенной выше инструкции.

Функции безопасности вашей учетной записи Gmail могут препятствовать приложению отправлять электронную почту через нее, если вы явно не разрешаете «less secure apps» («менее безопасным приложениям») доступ к вашей учетной записи Gmail. Прочитать об этом можно здесь, и если вас беспокоит безопасность вашей учетной записи, можно создать вторичную учетную запись, которую настройте только для проверки электронной почты, или временно включите разрешение для менее безопасных приложений на время запуска этого теста, а затем вернитесь к умолчанию.

Запись лога в файл

Получение ошибок по электронной почте полезно, но иногда недостаточно. Есть некоторые случаи сбоя, которые не описываются исключением Python и не являются серьезной проблемой, но они все равно могут быть достаточно интересными для сохранения в целях отладки. По этой причине я также буду поддерживать логфайл для приложения.

Чтобы включить ведение журнала другого обработчика, на этот раз типа RotatingFileHandler необходимо включить logger приложения аналогично обработчику электронной почты.

# ...
from logging.handlers import RotatingFileHandler
import os

# ...

if not app.debug:
    # ...

    if not os.path.exists('logs'):
        os.mkdir('logs')
    file_handler = RotatingFileHandler('logs/microblog.log', maxBytes=10240,
                                       backupCount=10)
    file_handler.setFormatter(logging.Formatter(
        '%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]'))
    file_handler.setLevel(logging.INFO)
    app.logger.addHandler(file_handler)

    app.logger.setLevel(logging.INFO)
    app.logger.info('Microblog startup')

Я пишу логфайл с именем microblog.log в каталоге logs, который я создаю, если он еще не существует.

Класс RotatingFileHandler удобен, потому что он переписывает журналы, гарантируя, что файлы журнала не будут слишком большими, если приложение работает в течение длительного времени. В этом случае я ограничиваю размер логфайла 10 КБ, и храню последние десять файлов журнала в качестве резервных копий.

Класс logging.Formatter предоставляет настройку формата сообщений журнала. Поскольку эти сообщения отправляются в файл, я хочу, чтобы они содержали как можно больше информации. Поэтому я использую формат, который включает отметку времени, уровень ведения журнала,
сообщение, исходный файл и номер строки, откуда возникла запись в журнале.

Чтобы сделать регистрацию более полезной, я также понижаю уровень ведения журнала до категории INFO, как в регистраторе приложений, так и в обработчике файлов. Если вы не знакомы с категориями ведения журнала, это DEBUG, INFO, WARNING,ERROR и CRITICAL в порядке возрастания степени тяжести.

В качестве первого полезного использования логфайла сервер записывает строку в журнал каждый раз, когда он запускается. Когда приложение запускается на production сервере, эти записи журнала сообщают вам, когда сервер был перезапущен.

Исправление дубля имени пользователя

Я слишком долго использовал ошибку дублирования имени пользователя. Теперь, когда я показал вам, как подготовить приложение для обработки подобных ошибок, я могу наконец-то это исправить.

Если вы помните, RegistrationForm уже выполняет проверку для имен пользователей, но требования формы редактирования немного отличаются. Во время регистрации мне нужно убедиться, что имя пользователя, введенное в форму, не существует в базе данных. В форме профиля редактирования я должен выполнить ту же проверку, но с одним исключением. Если пользователь оставляет исходное имя пользователя нетронутым, то проверка должна его разрешить, поскольку это имя пользователя уже назначено этому пользователю. Ниже вы можете увидеть, как я выполнил проверку имени пользователя для этой формы:

class EditProfileForm(FlaskForm):
    username = StringField('Username', validators=[DataRequired()])
    about_me = TextAreaField('About me', validators=[Length(min=0, max=140)])
    submit = SubmitField('Submit')

    def __init__(self, original_username, *args, **kwargs):
        super(EditProfileForm, self).__init__(*args, **kwargs)
        self.original_username = original_username

    def validate_username(self, username):
        if username.data != self.original_username:
            user = User.query.filter_by(username=self.username.data).first()
            if user is not None:
                raise ValidationError('Please use a different username.')

Реализация выполняется в специальном методе проверки, функция super в конструкторе класса, который принимает исходное имя пользователя в качестве аргумента. Это имя пользователя сохраняется как переменная экземпляра и проверяется в методе validate_username(). Если имя пользователя, введенное в форму, совпадает с исходным именем пользователя, то нет причин проверять базу данных на наличие дубликатов.

Чтобы использовать этот новый метод проверки, мне нужно добавить исходный аргумент имени пользователя в функцию вида, где создается объект формы:

@app.route('/edit_profile', methods=['GET', 'POST'])
@login_required
def edit_profile():
    form = EditProfileForm(current_user.username)
    # ...

Теперь ошибка исправлена, и дубликаты в форме профиля редактирования будут предотвращены в большинстве случаев. Это не идеальное решение, поскольку оно может не работать, когда два или несколько процессов одновременно обращаются к базе данных. В этой ситуации состояние гонки может привести к валидации, но спустя мгновение при попытке переименования база данных уже была изменена другим процессом и не может переименовать пользователя. Это несколько маловероятно, за исключением очень занятых приложений, у которых много серверных процессов, поэтому я пока не буду беспокоиться об этом.

На этом этапе вы можете попытаться воспроизвести ошибку еще раз, чтобы увидеть, как ее предотвращает метод проверки формы.

<<< предыдущая следующая >>>

P.S.

Работа над ошибками

От переводчика

Решил я проверить получение сообщений ошибки админу на почту. Для этого я испортил модуль routes.py. Для этой самой «порчи», я закомментировал декоратор @app.route('/edit_profile', methods=['GET', 'POST']) перед def edit_profile(). В итоге получил ошибку и в файл лога все это вывалилось, а вот письмо не прилетело. Я использую Python 3.3. Возможно в более новых версиях этого и не случится. Но в Windows 7 с русской раскладкой это случилось.

При попытке отправить сообщение админу приложение получило ошибку кодировки при формировании сообщения. В окне консоли содержались такие строки:

Как видим ссылка указывает на директорию в стандартном питоне, а не в виртуальном окружении.

logging в 3-й версии является стандартной библиотекой Python, поэтому вам не нужно устанавливать ее используя pip.

Про стандартные модули

И модуль протоколирования, который вы можете найти в PyPI, устаревший, а не Python3-совместимый.

(Согласно файлу README его последняя версия была выпущена 02 марта 2005 года.)

Поэтому просто не пытайтесь установить logging.
Возьмите новый модуль в стандартной библиотеке как должное. Если вам принципиально использовать его в виртальной библиотеке.

После копии в venvLib logging импортируется из виртуальной среды

Еще раз получаю ошибку

logging теперь виртуальный. А вот smtplib стандартный.

Не думаю, что надо тащить все библиотеки из стандартной среды в виртуальную.
Ошибка от этого не исчезнет.

Про стандартный модуль email

Проблема с кодировкой в сообщении решается использованием стандартного пакета email для создания сообщения с указанием предпочитаемой кодировки.

Вот пример с просторов интернета для этого пакета :

# -*- coding: utf-8 -*-
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import quopri
def QuoHead(String):
    s = quopri.encodestring(String.encode('UTF-8'), 1, 0)
    return "=?utf-8?Q?" + s.decode('UTF-8') + "?="
FIOin = "Хрюша Степашкин"
emailout = "some@test.ru"
emailin = "some2@test.ru"
msg = MIMEMultipart()
msg["Subject"] = QuoHead("Добрый день " + FIOin).replace('=n', '')
msg["From"] = (QuoHead("Каркуша Федоровна") + "  <" + emailout + ">").replace('=n', '') 
msg["To"] = (QuoHead(FIOin) + "  <" + emailin + ">").replace('=n', '')
m = """Добрый день.
  Это тестовое письмо.
Пожалуйста, не отвечайте на него."""
text = MIMEText(m.encode('utf-8'), 'plain', 'UTF-8')
msg.attach(text)
print(msg.as_string())

Но, как это применить для отправки сообщений об ошибке?!
Может кто-то предложит в комментариях к статье.

В модуле flask-mail эта ситуевина вроде как поправлена. Но тут используется logging и smtplib

В итоге пока так. Поправил я строку в модуле smtplib.py .

Добавил encode('utf-8')

И после перезапуска сервера при искусственной ошибке я, наконец-то, получил сообщение на почту.

<<< предыдущая следующая >>>

Работа с ошибками приложения

Приложения отказывают,серверы отказывают.Рано или поздно вы увидите исключение в производстве.Даже если ваш код на 100% правильный,вы все равно будете время от времени видеть исключения.Почему? Потому что все остальное,что задействовано в коде,не работает.Вот несколько ситуаций,когда совершенно правильный код может привести к ошибкам сервера:

  • клиент завершил запрос раньше времени,а приложение все еще считывало входящие данные
  • сервер базы данных был перегружен и не смог обработать запрос
  • файловая система заполнена
  • разбился жесткий диск
  • перегрузка внутреннего сервера
  • программная ошибка в используемой вами библиотеке
  • сетевое подключение сервера к другой системе не удалось

И это лишь небольшая часть проблем, с которыми вы можете столкнуться. Итак, как нам справиться с такой проблемой? По умолчанию, если ваше приложение работает в производственном режиме и возникает исключение, Flask отобразит для вас очень простую страницу и зарегистрирует исключение в logger .

Но есть и другие возможности,и мы расскажем о некоторых лучших настройках для работы с ошибками,включая пользовательские исключения и инструменты сторонних производителей.

Инструменты протоколирования ошибок

Отправка сообщений об ошибках, даже если это критические сообщения, может стать чрезмерным, если достаточное количество пользователей сталкивается с ошибкой, а файлы журналов обычно никогда не просматриваются. Вот почему мы рекомендуем использовать Sentry для работы с ошибками приложений. Он доступен в виде проекта с исходным кодом на GitHub , а также доступен в виде размещенной версии , которую вы можете попробовать бесплатно. Sentry собирает повторяющиеся ошибки, фиксирует полную трассировку стека и локальные переменные для отладки и отправляет вам письма на основе новых ошибок или пороговых значений частоты.

Чтобы использовать Sentry, вам необходимо установить клиент sentry-sdk с дополнительными зависимостями flask .

$ pip install sentry-sdk[flask]

А затем добавьте это в ваше приложение Flask:

import sentry_sdk
from sentry_sdk.integrations.flask import FlaskIntegration

sentry_sdk.init('YOUR_DSN_HERE', integrations=[FlaskIntegration()])

Значение YOUR_DSN_HERE необходимо заменить значением DSN, полученным при установке Sentry.

После установки сбои,приводящие к внутренней ошибке сервера,автоматически сообщаются в Sentry,откуда вы можете получать уведомления об ошибках.

See also:

  • Sentry также поддерживает перехват ошибок из рабочей очереди (RQ, Celery и т. Д.) Аналогичным образом. Дополнительную информацию см. В документации Python SDK .
  • Начало работы с Sentry
  • Flask-specific documentation

Error Handlers

Когда во Flask возникает ошибка, будет возвращен соответствующий код состояния HTTP . 400-499 указывают на ошибки в данных запроса клиента или в запрошенных данных. 500-599 указывают на ошибки сервера или самого приложения.

Вы можете захотеть показывать пользователю пользовательские страницы ошибок при возникновении ошибки.Это можно сделать,зарегистрировав обработчики ошибок.

Обработчик ошибок — это функция, которая возвращает ответ при возникновении ошибки определенного типа, подобно тому, как представление — это функция, возвращающая ответ при совпадении URL-адреса запроса. Ему передается экземпляр обрабатываемой ошибки, который, скорее всего, является HTTPException .

Код состояния ответа не будет установлен на код обработчика.При возврате ответа от обработчика обязательно указывайте соответствующий код состояния HTTP.

Registering

Зарегистрируйте обработчики, украсив функцию errorhandler() . Или используйте register_error_handler() чтобы зарегистрировать функцию позже. Не забудьте установить код ошибки при возврате ответа.

@app.errorhandler(werkzeug.exceptions.BadRequest)
def handle_bad_request(e):
    return 'bad request!', 400


app.register_error_handler(400, handle_bad_request)

Подклассы werkzeug.exceptions.HTTPException ,такие как BadRequest , и их HTTP-коды взаимозаменяемы при регистрации обработчиков. ( BadRequest.code == 400 )

Нестандартные коды HTTP не могут быть зарегистрированы с помощью кода, поскольку они неизвестны Werkzeug. Вместо этого определите подкласс HTTPException с соответствующим кодом, зарегистрируйте и поднимите этот класс исключения.

class InsufficientStorage(werkzeug.exceptions.HTTPException):
    code = 507
    description = 'Not enough storage space.'

app.register_error_handler(InsufficientStorage, handle_507)

raise InsufficientStorage()

Обработчики могут быть зарегистрированы для любого класса исключений, а не только для подклассов HTTPException или кодов состояния HTTP. Обработчики могут быть зарегистрированы для определенного класса или для всех подклассов родительского класса.

Handling

При создании приложения Flask вы столкнетесь с исключениями. Если какая-то часть вашего кода сломается при обработке запроса (и у вас нет зарегистрированных обработчиков ошибок), по умолчанию будет возвращено «500 Internal Server Error» ( InternalServerError ).Точно так же ошибка «404 Not Found» ( NotFound ) возникает, если запрос отправляется на незарегистрированный маршрут. Если маршрут получает неразрешенный метод запроса, будет поднято «Метод 405 не разрешен» ( MethodNotAllowed ).Все они являются подклассами HTTPException и по умолчанию предоставляются во Flask.

Flask дает вам возможность поднять любое исключение HTTP,зарегистрированное Werkzeug.Однако HTTP-исключения по умолчанию возвращают простые страницы исключений.Возможно,вы захотите показывать пользователю пользовательские страницы ошибок при возникновении ошибки.Это можно сделать,зарегистрировав обработчики ошибок.

Когда Flask перехватывает исключение при обработке запроса, оно сначала ищется по коду. Если для кода не зарегистрирован обработчик, Flask ищет ошибку по иерархии классов; выбирается наиболее конкретный обработчик. Если обработчик не зарегистрирован, подклассы HTTPException отображают общее сообщение об их коде, в то время как другие исключения преобразуются в общее сообщение «500 Internal Server Error».

Например, если возникает экземпляр ConnectionRefusedError и зарегистрирован обработчик для ConnectionError и ConnectionRefusedError , более конкретный обработчик ConnectionRefusedError вызывается с экземпляром исключения для генерации ответа.

Обработчики,зарегистрированные на чертеже,имеют приоритет над обработчиками,зарегистрированными глобально в приложении,при условии,что чертеж обрабатывает запрос,вызвавший исключение.Однако блюпринт не может обрабатывать ошибки маршрутизации 404,поскольку 404 происходит на уровне маршрутизации до того,как можно определить блюпринт.

Общие обработчики исключений

Можно зарегистрировать обработчики ошибок для очень общих базовых классов, таких как HTTPException или даже Exception . Однако имейте в виду, что они поймают больше, чем вы могли ожидать.

Например, обработчик ошибок для HTTPException может быть полезен для преобразования страниц ошибок HTML по умолчанию в формат JSON. Однако этот обработчик срабатывает для вещей, которые вы не вызываете напрямую, таких как ошибки 404 и 405 во время маршрутизации. Тщательно создавайте свой обработчик, чтобы не потерять информацию об ошибке HTTP.

from flask import json
from werkzeug.exceptions import HTTPException

@app.errorhandler(HTTPException)
def handle_exception(e):
    """Return JSON instead of HTML for HTTP errors."""
    
    response = e.get_response()
    
    response.data = json.dumps({
        "code": e.code,
        "name": e.name,
        "description": e.description,
    })
    response.content_type = "application/json"
    return response

Обработчик ошибок для Exception может показаться полезным для изменения способа представления пользователю всех ошибок, даже необработанных. Однако это похоже на выполнение, except Exception: в Python он фиксирует все необработанные в противном случае ошибки, включая все коды состояния HTTP.

В большинстве случаев будет безопаснее зарегистрировать обработчики для более конкретных исключений. Поскольку экземпляры HTTPException являются действительными ответами WSGI, вы также можете передать их напрямую.

from werkzeug.exceptions import HTTPException

@app.errorhandler(Exception)
def handle_exception(e):
    
    if isinstance(e, HTTPException):
        return e

    
    return render_template("500_generic.html", e=e), 500

Обработчики ошибок по-прежнему соблюдают иерархию классов исключений. Если вы зарегистрируете обработчики как для HTTPException ,так и для Exception , обработчик Exception не будет обрабатывать подклассы HTTPException , поскольку он является более конкретным обработчиком HTTPException .

Unhandled Exceptions

Если для исключения не зарегистрирован обработчик ошибок, вместо этого будет возвращена ошибка 500 Internal Server Error. См. flask.Flask.handle_exception() для получения информации об этом поведении.

Если для InternalServerError зарегистрирован обработчик ошибок , он будет вызван. Начиная с Flask 1.1.0, этому обработчику ошибок всегда будет передаваться экземпляр InternalServerError , а не исходная необработанная ошибка.

Исходная ошибка доступна как e.original_exception .

В обработчик ошибки «500 Internal Server Error» будут передаваться не пойманные исключения в дополнение к явным 500 ошибкам.В режиме отладки обработчик для «500 Internal Server Error» не будет использоваться.Вместо этого будет показан интерактивный отладчик.

Пользовательские страницы ошибок

Иногда при создании приложения Flask вы можете захотеть создать исключение HTTPException , чтобы сообщить пользователю, что с запросом что-то не так. К счастью, Flask поставляется с удобной функцией abort() , которая прерывает запрос с ошибкой HTTP от werkzeug по желанию. Он также предоставит вам простую черно-белую страницу ошибки с основным описанием, но ничего особенного.

В зависимости от кода ошибки вероятность того,что пользователь действительно увидит такую ошибку,меньше или больше.

Рассмотрим код ниже,у нас может быть маршрут профиля пользователя,и если пользователь не передает имя пользователя,мы можем выдать сообщение «400 Bad Request».Если пользователь передает имя пользователя,но мы не можем его найти,мы выдаем сообщение «404 Not Found».

from flask import abort, render_template, request



@app.route("/profile")
def user_profile():
    username = request.arg.get("username")
    
    if username is None:
        abort(400)

    user = get_user(username=username)
    
    if user is None:
        abort(404)

    return render_template("profile.html", user=user)

Вот еще один пример реализации исключения «404 Page Not Found»:

from flask import render_template

@app.errorhandler(404)
def page_not_found(e):
    
    return render_template('404.html'), 404

При использовании фабрик приложений :

from flask import Flask, render_template

def page_not_found(e):
  return render_template('404.html'), 404

def create_app(config_filename):
    app = Flask(__name__)
    app.register_error_handler(404, page_not_found)
    return app

Пример шаблона может быть следующим:

{% extends "layout.html" %}
{% block title %}Page Not Found{% endblock %}
{% block body %}
  <h1>Page Not Found</h1>
  <p>What you were looking for is just not there.
  <p><a href="{{ url_for('index') }}">go somewhere nice</a>
{% endblock %}

Further Examples

Приведенные выше примеры на самом деле не являются улучшением стандартных страниц исключений.Мы можем создать пользовательский шаблон 500.html следующим образом:

{% extends "layout.html" %}
{% block title %}Internal Server Error{% endblock %}
{% block body %}
  <h1>Internal Server Error</h1>
  <p>Oops... we seem to have made a mistake, sorry!</p>
  <p><a href="{{ url_for('index') }}">Go somewhere nice instead</a>
{% endblock %}

Это можно реализовать путем рендеринга шаблона при «500 Internal Server Error»:

from flask import render_template

@app.errorhandler(500)
def internal_server_error(e):
    
    return render_template('500.html'), 500

При использовании фабрик приложений :

from flask import Flask, render_template

def internal_server_error(e):
  return render_template('500.html'), 500

def create_app():
    app = Flask(__name__)
    app.register_error_handler(500, internal_server_error)
    return app

При использовании модульных приложений с Blueprints :

from flask import Blueprint

blog = Blueprint('blog', __name__)


@blog.errorhandler(500)
def internal_server_error(e):
    return render_template('500.html'), 500


blog.register_error_handler(500, internal_server_error)

Обработчики ошибок чертежей

В Modular Applications with Blueprints большинство обработчиков ошибок будут работать должным образом. Однако есть предостережение относительно обработчиков исключений 404 и 405. Эти обработчики ошибок вызываются только из соответствующего оператора raise или вызова abort в другой функции представления схемы; они не вызываются, например, недопустимым доступом по URL-адресу.

Это связано с тем, что схема не «владеет» определенным пространством URL-адресов, поэтому экземпляр приложения не может узнать, какой обработчик ошибок схемы следует запустить, если указан недопустимый URL-адрес. Если вы хотите использовать разные стратегии обработки этих ошибок на основе префиксов URL, их можно определить на уровне приложения с помощью прокси-объекта request

from flask import jsonify, render_template



@app.errorhandler(404)
def page_not_found(e):
    
    if request.path.startswith('/blog/'):
        
        return render_template("blog/404.html"), 404
    else:
        
        return render_template("404.html"), 404

@app.errorhandler(405)
def method_not_allowed(e):
    
    if request.path.startswith('/api/'):
        
        return jsonify(message="Method Not Allowed"), 405
    else:
        
        return render_template("405.html"), 405

Возврат ошибок API в формате JSON

При создании API-интерфейсов во Flask некоторые разработчики понимают, что встроенные исключения недостаточно выразительны для API-интерфейсов и что тип содержимого text / html, который они генерируют, не очень полезен для потребителей API.

Используя те же методы, что и выше, и jsonify() , мы можем возвращать ответы JSON на ошибки API. abort() вызывается с параметром description . Обработчик ошибок будет использовать это как сообщение об ошибке JSON и установит код состояния 404.

from flask import abort, jsonify

@app.errorhandler(404)
def resource_not_found(e):
    return jsonify(error=str(e)), 404

@app.route("/cheese")
def get_one_cheese():
    resource = get_resource()

    if resource is None:
        abort(404, description="Resource not found")

    return jsonify(resource)

Мы также можем создавать пользовательские классы исключений.Например,мы можем создать новое пользовательское исключение для API,которое может принимать сообщение,читаемое человеком,код состояния ошибки и некоторую необязательную полезную нагрузку для создания дополнительного контекста ошибки.

Это простой пример:

from flask import jsonify, request

class InvalidAPIUsage(Exception):
    status_code = 400

    def __init__(self, message, status_code=None, payload=None):
        super().__init__()
        self.message = message
        if status_code is not None:
            self.status_code = status_code
        self.payload = payload

    def to_dict(self):
        rv = dict(self.payload or ())
        rv['message'] = self.message
        return rv

@app.errorhandler(InvalidAPIUsage)
def invalid_api_usage(e):
    return jsonify(e.to_dict()), e.status_code



@app.route("/api/user")
def user_api(user_id):
    user_id = request.arg.get("user_id")
    if not user_id:
        raise InvalidAPIUsage("No user id provided!")

    user = get_user(user_id=user_id)
    if not user:
        raise InvalidAPIUsage("No such user!", status_code=404)

    return jsonify(user.to_dict())

Теперь представление может вызвать это исключение с сообщением об ошибке. Кроме того, некоторая дополнительная полезная нагрузка может быть предоставлена ​​в виде словаря через параметр payload .

Logging

См. Ведение журнала для получения информации о том, как регистрировать исключения, например, отправляя их администраторам по электронной почте.

Debugging

См. Отладка ошибок приложений для получения информации о том, как отлаживать ошибки при разработке и производстве.


Flask

2.2

  • Waitress

  • Проектные решения во Flask

  • Extensions

  • Installation

Ответ сервера

Flask предлагает три варианта для создания ответа:

  1. В виде строки или с помощью шаблонизатора
  2. Объекта ответа
  3. Кортежа в формате (response, status, headers) или (response, headers)

Далее о каждом поподробнее.

Создание ответа в виде строки

@app.route('/books/')
def books(genre):
    return "All Books in {} category".format(genre)

До сих пор этот способ использовался, чтобы отправлять ответ клиенту. Когда Flask видит, что из функции представления возвращается строка, он автоматически конвертирует ее в объект ответа (с помощью метода make_response()) со строкой, содержащей тело ответа, статус-код HTTP 200 и значение text/html в заголовке content-type. В большинстве случаев это — все, что нужно. Но иногда необходимы дополнительные заголовки перед отправлением ответа клиенту. Для этого создавать ответ нужно с помощью функции make_response().

Создание ответа с помощью make_response()

Синтаксис make_response() следующий:

res_obj = make_response(res_body, status_code=200)

res_body — обязательный аргумент, представляющий собой тело ответа, а status_code — опциональный, по умолчанию его значение равно 200.

Следующий код показывает, как добавить дополнительные заголовки с помощью функции make_response().

from flask import Flask, make_response,

@app.route('/books/')
def books(genre):
    res = make_response("All Books in {} category".format(genre))
    res.headers['Content-Type'] = 'text/plain'
    res.headers['Server'] = 'Foobar'
    return res

Следующий — демонстрирует, как вернуть ошибку 404 с помощью make_response().

@app.route('/')
def http_404_handler():
    return make_response("

404 Error

"
, 400)

Настройка куки — еще одна базовая задача для любого веб-приложения. Функция make_response() максимально ее упрощает. Следующий код устанавливает два куки в клиентском браузере.

@app.route('/set-cookie')
def set_cookie():
    res = make_response("Cookie setter")
    res.set_cookie("favorite-color", "skyblue")
    res.set_cookie("favorite-font", "sans-serif")
    return res

Примечание: куки обсуждаются подробно в уроке «Куки во Flask».

Куки, заданные в вышеуказанном коде, будут активны до конца сессии в браузере. Можно указать собственную дату истечения их срока, передав в качестве третьего аргумента в методе set_cookie() количество секунд. Например:

@app.route('/set-cookie')
def set_cookie():
    res = make_response("Cookie setter")
    res.set_cookie("favorite-color", "skyblue", 60*60*24*15)
    res.set_cookie("favorite-font", "sans-serif", 60*60*24*15)
    return res

Здесь, у куки будут храниться 15 дней.

Создание ответов с помощью кортежей

Последний способ создать ответ — использовать кортежи в одном из следующих форматов:

(response, status, headers)

(response, headers)

(response, status)

response — строка, представляющая собой тело ответа, status — код состояния HTTP, который может быть указан в виде целого числа или строки, а headers — словарь со значениями заголовков.

@app.route('/')
def http_500_handler():
    return ("

500 Error

"
, 500)

Функция представления вернет ошибку HTTP 500 Internal Server Error. Поскольку при создании кортежей можно не писать скобки, вышеуказанный код можно переписать следующим образом:

@app.route('/')
def http_500_handler():
    return "

500 Error

"
, 500

Следующий код демонстрирует, как указать заголовки с помощью кортежей:

@app.route('/')
def render_markdown():
    return "## Heading", 200, {'Content-Type': 'text/markdown'}

Сможете догадаться, что делает следующая функция?

@app.route('/transfer')
def transfer():
    return "", 302, {'location': 'https://localhost:5000/login'}

Функция представления перенаправляет пользователя на https://localhost:5000/login с помощью ответа 302 (временное перенаправление). Перенаправление пользователей — настолько распространенная практика, что во Flask для этого есть даже отдельная функция redirect().

from flask import Flask, redirect

@app.route('/transfer')
def transfer():
    return redirect("https://localhost:5000/login")

По умолчанию, redirect() осуществляет 302 редиректы. Чтобы использовать 301, нужно указать это в функции redirect():

from flask import Flask, redirect

@app.route('/transfer')
def transfer():
    return redirect("https://localhost:5000/login", code=301)

Перехват запросов

В веб-приложениях часто нужно исполнить определенный код до или после запроса. Например, нужно вывести весь список IP-адресов пользователей, которые используют приложение или авторизовать пользователя до того как показывать ему скрытые страницы. Вместе того чтобы копировать один и тот же код внутри каждой функции представления, Flask предлагает следующие декораторы:

  • before_first_request: этот декоратор выполняет функцию еще до обработки первого запроса
  • before_request: выполняет функцию до обработки запроса
  • after_request: выполняет функцию после обработки запроса. Такая функция не будет вызвана при возникновении исключений в обработчике запросов. Она должна принять объект ответа и вернуть тот же или новый ответ.
  • teardown_request: этот декоратор похож на after_request. Но вызванная функция всегда будет выполняться вне зависимости от того, возвращает ли обработчик исключение или нет.

Стоит отметить, что если функция в before_request возвращает ответ, тогда обработчик запросов не вызывается.

Следующий код демонстрирует, как использовать эти точки перехвата во Flask. Нужно создать новый файл hooks.py с таким кодом:

from flask import Flask, request, g

app = Flask(__name__)

@app.before_first_request
def before_first_request():
    print("before_first_request() called")

@app.before_request
def before_request():
    print("before_request() called")

@app.after_request
def after_request(response):
    print("after_request() called")
    return response

@app.route("/")
def index():
    print("index() called")
    return '

Testings Request Hooks

'
if __name__ == "__main__": app.run(debug=True)

После этого необходимо запустить сервер и сделать первый запрос, перейдя на страницу https://localhost:5000/. В консоли, где был запущен сервер, должен появиться следующий вывод:

before_first_request() called
before_request() called
index() called
after_request() called

Примечание: записи о запросах к серверу опущены для краткости.

После перезагрузки страницы отобразится следующий вывод.

before_request() called
index() called
after_request() called

Поскольку это второй запрос, функция before_first_request() не будет вызываться.

Отмена запроса с помощью abort()

Flask предлагает функцию abort() для отмены запроса с конкретным типом ошибки: 404, 500 и так далее. Например:

from  flask import  Flask,  abort

@app.route('/')
def index():
    abort(404)
    # код после выполнения abort() не выполняется

Эта функция представления вернет стандартную страницу ошибки 404, которая выглядит вот так:
функция вернет страницу ошибки 404

abort() покажет похожие страницы для других типов ошибок. Если нужно изменить внешний вид страниц с ошибками, необходимо использовать декоратор errorhandler.

Изменение страниц ошибок

Декоратор errorhandler используется для создания пользовательских страниц с ошибками. Он принимает один аргумент — ошибку HTTP, — для которой создается страница. Откроем файл hooks.py для создания кастомных страниц ошибок 404 и 500 с помощью декоратора:

from flask import Flask, request, g, abort
#...
#...
@app.after_request
def after_request(response):
    print("after_request() called")
    return response

@app.errorhandler(404)
def http_404_handler(error):
    return "

HTTP 404 Error Encountered

"
, 404 @app.errorhandler(500) def http_500_handler(error): return "

HTTP 500 Error Encountered

"
, 500 @app.route("/") def index(): # print("index() called") # return '

Testings Request Hooks

'
abort(404) if __name__ == "__main__": #...

Стоит отметить, что оба обработчика ошибок принимают один аргумент error, который содержит дополнительную информацию о типе ошибки.

Если сейчас посетить корневой URL, отобразится следующий ответ:
кастомная страница ошибки 404

Понравилась статья? Поделить с друзьями:
  • Flask return 404 error
  • Flask register error handler
  • Flask migrate error target database is not up to date
  • Flask json error
  • Flask internal server error render template