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.
I have a Flask server and if I send POST request without body everything works. But, when I want to send a String as JSON, I get error 400. I use Volley on Android for the request. What am I missing? Is a Flask problem or a Volley problem? Thanks in advance.
Flask function on server (note that if I print request.data I get exactly what I sent):
def upd():
if request.method == 'POST':
data = request.data
if not os.path.exists("/home/tuzzo/stg/res/%s"%request.form['chiave']):
os.makedirs("/home/tuzzo/stg/res/%s"%request.form['chiave'])
os.makedirs("/home/tuzzo/stg/res/%s/download"%request.form['chiave'])
os.makedirs("/home/tuzzo/stg/res/%s/header"%request.form['chiave'])
if not data is None:
with open('/home/tuzzo/stg/res/%s/download/jsonEx.json'%request.form['chiave'], 'w') as outfile:
simplejson.dump(data, outfile)
with open('/home/tuzzo/stg/res/%s/manifest.xml'%request.form['chiave'], 'w') as xmlfile:
xmlfile.write("<?xml version="1.0" encoding="UTF-8"?><channel><item><json>http://tuzzo.pythonanywhere.com/download/"+request.form['chiave']+"/jsonEx.json</json></item></channel>")
addEx(request.form['chiave'])
return request.form['chiave']
My request with Volley on Android (if I only use params it works):
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.d("exfrom","response db: "+response);
chiave=response;
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(),"Fail database",Toast.LENGTH_SHORT).show();
Log.d("tuzzo","err volley: "+ error);
}}
}){
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("Content-Type", "application/json");
return params;
}
@Override
protected Map<String, String> getParams() throws AuthFailureError {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SimpleDateFormat myFormat = new SimpleDateFormat("dd/MM/yyyy", Locale.ITALY);
Map<String, String> params = new HashMap<>();
params.put("nameEx", String.valueOf(prefs.getString("exhtitle",null)));
params.put("descrEx", String.valueOf(prefs.getString("exhdescr",null)));
params.put("longDescr", String.valueOf(longdescr.getText()));
params.put("idCategories", String.valueOf(catmap.get(String.valueOf(spin_cat.getText()).toLowerCase())));
try {
params.put("startDate", myFormat.format(myFormat.parse(startDate.getText().toString())));
params.put("endDate", myFormat.format(myFormat.parse(endDate.getText().toString())));
Log.d("testdate", "start: " + myFormat.format(myFormat.parse(startDate.getText().toString())));
Log.d("testdate", "end: " + myFormat.format(myFormat.parse(endDate.getText().toString())));
}catch (ParseException e){
Log.e("testdate","error: "+e);
}
params.put("idMuseums", String.valueOf(musmap.get(String.valueOf(spin_mus.getText()).toLowerCase())));
params.put("chiave", String.valueOf(prefs.getString("exhkey",null)));
return params;
}
@Override
public byte[] getBody() throws AuthFailureError {
try {
return full == null ? null : full.getBytes("utf-8");
} catch (UnsupportedEncodingException uee) {
Log.d("volleyuee", "uee: "+uee);
return null;
}
}
@Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
};
Issue
I intend to send a video to a flask server with the post request sent from an android application. I get this error
werkzeug.exceptions.BadRequestKeyError: 400 Bad Request: The browser (or proxy) sent a request that this server could not understand.
KeyError: 'file'
Below is the python code for the flask server. Note that I am trying to get the content of the files (MultiDict) for debugging purpose using the for loop. I get no output on the powershell window. Also, since the error is KeyError: 'file'
, I understand that the files variable is null?
from flask import Flask, request, jsonify
path_upload_folder = 'C:\Users\vishw\Desktop\cse535a3_uploads\uploads'
app = Flask(__name__)
app.config['path_upload_folder'] = path_upload_folder
@app.route('/mainapp', methods=['GET', 'POST'])
def upload_video():
print('Started')
if request.method == 'POST':
keys = request.files.keys()
for each in keys:
print(each)
sent_file = request.files['file']
sent_file.save(app.config['path_upload_folder'] + '\' + secure_filename(sent_file.filename))
return jsonify(operation_status="true")
return jsonify(operation_status="false")
app.run(host="0.0.0.0", port=5000, debug=True)
Here is the relevant code for the android application
public class ExampleGesture extends AppCompatActivity {
private final int VIDEO_CAPTURE = 1;
private VideoView example_gesture;
private boolean captured_video = false;
private MediaType object_mediatype;
private Intent intent_record_video;
private File file_media;
private String name_file;
private String gesture_received;
private String address_server_ipv4;
private String port_number;
private String posturl;
private int count_files = -1;
private int [] count_practice; //= ((MainApplication)getApplication()).count_practice;
private HashMap links;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_example_gesture);
// Log.i("APP: ", getApplication().getClass().getSimpleName());
Log.i("EG: ", "Under Super");
Log.i("EXAMACTTHREAD: ", String.valueOf((Thread.currentThread()).getId()));
Context context_current = getApplicationContext();
new Thread(new Runnable() {
public void run() {
Log.i("EXAMACTTHREADNEW: ", String.valueOf((Thread.currentThread()).getId()));
// Log.i("EG: ", "Setting COntent View");
count_practice = ((MainApplication)getApplication()).count_practice;
Intent intent_current = getIntent();
String gesture = intent_current.getStringExtra("EXTRA_GESTURE");
gesture_received = gesture;
ArrayAdapter<CharSequence> arrayAdapter_gestures = ArrayAdapter.createFromResource(context_current,
R.array.list_gestures,
android.R.layout.simple_spinner_item);
// Log.i("ARRAY: ", String.valueOf(arrayAdapter_gestures.getCount()));
links = new HashMap();
for (int index = 0; index < arrayAdapter_gestures.getCount(); ++index) {
// Log.i("ARRAY: ", (arrayAdapter_gestures.getItem(index)).toString());
if (!((arrayAdapter_gestures.getItem(index)).toString().equals("Select Gesture"))) {
links.put((arrayAdapter_gestures.getItem(index)).toString(), 0);
}
}
// Log.i("GESTURE: ", gesture);
String path_file = "/sdcard/Movies/";
if (gesture == "FanUp") {
path_file = path_file + "H-IncreaseFanSpeed.mp4";
} else if (gesture == "FanDown") {
path_file = path_file + "H-DecreaseFanSpeed.mp4";
} else path_file = path_file + "H-" + gesture + ".mp4";
Uri u1 = Uri.fromFile(new File(path_file));
example_gesture = (VideoView)findViewById(R.id.videoView_gesture);
example_gesture.setVideoURI(u1);
example_gesture.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer arg_mp) { example_gesture.start(); }
});
example_gesture.start();
Button button_record = (Button) findViewById(R.id.button_record);
button_record.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg_view) {
intent_record_video = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
intent_record_video.putExtra(MediaStore.EXTRA_DURATION_LIMIT, 5);
File k = new File("/storage/self/primary/DCIM/Camera/");
count_files = (k.list()).length;
startActivityForResult(intent_record_video, VIDEO_CAPTURE);
}
});
Button button_previous_screen = (Button) findViewById(R.id.button_previous_screen);
button_previous_screen.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg_view) {
startActivity(new Intent(getApplicationContext(), MainActivity.class));
}
});
Button button_upload = (Button) findViewById(R.id.button_upload);
button_upload.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg_view) {
if (name_file.length() > 0) {
RequestBody postbody = RequestBody.create(object_mediatype, file_media);
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(posturl)
.post(postbody)
.build();
Log.i("REQUEST: ", "Throwing a request");
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(final Call call, final IOException e) {
call.cancel();
Log.i("REQUEST: ", "Call canceled");
}
@Override
public void onResponse(Call call, final Response response) throws IOException {
}
});
name_file = "";
}
}
});
address_server_ipv4 = "192.168.0.113";
port_number = "5000";
posturl = "http://" + address_server_ipv4 + ":" + port_number + "/mainapp";
Thread.currentThread().interrupt();
}
}).start();
}
@Override
protected void onResume() {
super.onResume();
Log.i("THREAD: ", "ran the resume thread");
File file = new File("/storage/self/primary/DCIM/Camera/");
String[] list_files = file.list();
if (list_files.length > count_files && count_files != -1) {
captured_video = true;
count_files = list_files.length;
}
if (!example_gesture.isPlaying()) {
example_gesture.start();
}
if (captured_video) {
// File file = new File("/storage/self/primary/DCIM/Camera/");
// String[] list_files = file.list();
for (int index = 0; index < list_files.length; ++index) {
if ((list_files[index]).charAt(0) == 'V') {
File f = new File(file.getPath() +'/' + list_files[index]);
name_file = file.getPath() + '/' + gesture_received
+ "_PRACTICE_"
+ count_practice[(int) links.get(gesture_received)] + "_desai.mp4";
File f2 = new File(name_file);
boolean result = f.renameTo(f2);
file_media = f2;
++count_practice[(int) links.get(gesture_received)];
break;
}
}
captured_video = false;
object_mediatype = MediaType.parse("video/mp4");
}
}
}
As I proposed before, is the files variable in the Request null? I.e the file is not being sent? Also, kindly give your opinion on whether am I sending the video file in a correct way or not. It would be most generous of you to show me the correct way If I am mistaken as well.
Solution
Forgot to answer it instantly since assignment deadlines, but you want to focus on the name of the file you are sending in that request and the name you use in the flask program. That’s all I can recall right now.
EDIT:
sent_file = request.files['file']
, here, ‘file’ should be ‘name’ of the the information sent in the RequestBody
Answered By – Vishwad
This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0
Работа с ошибками приложения
Приложения отказывают,серверы отказывают.Рано или поздно вы увидите исключение в производстве.Даже если ваш код на 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