- Table of contents
- Call between Javascript & Python with Flask: Method Not Allowed error 405
- Method Not Allowed flask error 405
- How To Handle Errors in a Flask Application
- Do I Have To Provide A Body Response Flask With Http 405 Error
- How to fix POST Error 405 Method Not Allowed with Flask Python?
Call between Javascript & Python with Flask: Method Not Allowed error 405
Flask only handles routes that are explicitly registered with it (/static/<path:file_path> is added for you automatically by Flask, which is why static files work). Files in the templates folder are not exposed as served resources by default but are passed through Jinja (generally) by the render_template function.
from flask import render_template from app import app @app.route('/') @app.route('/user_form.html', methods=["GET", "POST"]) def index(): return render_template("user_form.html")
<SCRIPT> function get_UserInputValues(form) { var getzipcode = document.getElementById('user_zip').value; var getcuisine = document.getElementById('cuisine').value; var selection1 = $("#slider1").slider("value"); var selection2 = $("#slider2").slider("value"); var selection3 = $("#slider3").slider("value"); var myurl = 'http://127.0.0.1:5000/mypython.py'; /*alert(getzipcode); alert(getcuisine); alert(selection1); alert(selection2); alert(selection3);*/ $('#myForm').submit(); $.ajax({url: myurl, type: "POST", data: {zip: getzipcode, cuisine:getcuisine}, dataType: 'json', done: onComplete}) } function onComplete(data) { alert(data); }; </SCRIPT>
def restaurant_choice(zipcode, cuisine): print "zipcode:", zipcode return "cuisine: ", cuisine restaurant_choice(getzipcode, getcuisine)
Method Not Allowed flask error 405
Teams. Q&A for work. Connect and share knowledge within a single location that is structured and easy to search. Learn more about Teams
error 405 method not found.
import os # Flask from flask import Flask, request, session, g, redirect, url_for, abort, render_template, flash, Markup, send_from_directory, escape from werkzeug import secure_filename from cultura import app # My app from include import User @app.route('/') def index(): return render_template('hello.html') @app.route('/registrazione', methods=['POST']) def registration(): if request.method == 'POST': username= request.form.username.data return render_template('registration.html', username=username) else : return render_template('registration.html')
<html> <head> <title>Form di registrazione </title> </head> <body> {{ username }} <form id='registration' action='/registrazione' method='post'> <fieldset > <legend>Registrazione utente</legend> <input type='hidden' name='submitted' id='submitted' value='1'/> <label for='name' >Nome: </label> <input type='text' name='name' id='name' maxlength="50" /> <br> <label for='email' >Indirizzo mail:</label> <input type='text' name='email' id='email' maxlength="50" /> <br> <label for='username' >UserName*:</label> <input type='text' name='username' id='username' maxlength="50" /> <br> <label for='password' >Password*:</label> <input type='password' name='password' id='password' maxlength="50" /> <br> <input type='submit' name='Submit' value='Submit' /> </fieldset> </form> </body> </html>
@app.route('/registrazione', methods=['GET', 'POST'])
@app.route('/registrazione', methods=['POST']) def registrazione(): if request.method == 'POST': username= request.form.username.data return render_template('registration.html', username=username) else : return render_template('registration.html')
@app.route("/registrazione") def render_registrazione() -> "html": return render_template("registrazione.html")
from flask import Flask, jsonify application = Flask(__name__, static_url_path='') @application.route('/') def activecalls(): return application.send_static_file('activecalls/active_calls_map.html') @application.route('/_getData', methods=['GET', 'POST']) def getData(): #hit the data, package it, put it into json. #ajax would have to hit this every so often to get latest data. arr = {} arr["blah"] = [] arr["blah"].append("stuff"); return jsonify(response=arr) if __name__ == '__main__': application.run()
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> </script> <script> $.ajax({ //url : "http://dev.consumerunited.com/wsgi/activecalls.py/_getData", url : "activecalls.py/_getData", type: "POST", data : formData, datatype : "jsonp", success: function(data, textStatus, jqXHR) { //data - response from server alert("'" + data.response.blah + "'"); }, error: function (jqXHR, textStatus, errorThrown) { alert("error: " + errorThrown); } }); </script>
import requests import json URL = "http://hostname.com.sa/fetchdata/" PARAMS = '{ "id":"111", "age":30, "city":"New Heaven"}' response = requests.post(url = URL, json = PARAMS) print(response.content)
Flask
I’m keep getting the 405 error, I’ve changed my code following the other related posts but still not working. routes.py. from flask import render_template, redirect, flash, url_for, abort, request. …
from flask import Flask from flask_restful import Api api = Api(app,errors=errors) api.add_resource(ResetPassword, '/api/reset')
from flask_restful import Resource, Api class CheckDifferenceApi(Resource): def ResetPassword(self):
How To Handle Errors in a Flask Application
nano app.py
from flask import Flask app = Flask(__name__) @app.route('/') def index(): return render_template('index.html')
export FLASK_APP=app
flask run
Output * Serving Flask app 'app' (lazy loading) * Environment: production WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead. * Debug mode: off * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
http://127.0.0.1:5000/
OutputInternal Server Error The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.
Output[2021-09-12 15:16:56,441] ERROR in app: Exception on / [GET] Traceback (most recent call last): File "/home/abd/.local/lib/python3.9/site-packages/flask/app.py", line 2070, in wsgi_app response = self.full_dispatch_request() File "/home/abd/.local/lib/python3.9/site-packages/flask/app.py", line 1515, in full_dispatch_request rv = self.handle_user_exception(e) File "/home/abd/.local/lib/python3.9/site-packages/flask/app.py", line 1513, in full_dispatch_request rv = self.dispatch_request() File "/home/abd/.local/lib/python3.9/site-packages/flask/app.py", line 1499, in dispatch_request return self.ensure_sync(self.view_functions[rule.endpoint])(**req.view_args) File "/home/abd/python/flask/series03/flask_app/app.py", line 8, in index return render_template('index.html') NameError: name 'render_template' is not defined 127.0.0.1 - - [12/Sep/2021 15:16:56] "GET / HTTP/1.1" 500 -
export FLASK_ENV=development
flask run
Output * Serving Flask app 'app' (lazy loading) * Environment: development * Debug mode: on * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit) * Restarting with stat * Debugger is active! * Debugger PIN: 120-484-907
nano app.py
from flask import Flask, render_template app = Flask(__name__) @app.route('/') def index(): return render_template('index.html')
Outputjinja2.exceptions.TemplateNotFound jinja2.exceptions.TemplateNotFound: index.html
mkdir templates nano templates/base.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>{% block title %} {% endblock %} - FlaskApp</title> <style> nav a { color: #d64161; font-size: 3em; margin-left: 50px; text-decoration: none; } </style> </head> <body> <nav> <a href="{{ url_for('index') }}">FlaskApp</a> <a href="#">About</a> </nav> <hr> <div class="content"> {% block content %} {% endblock %} </div> </body> </html>
nano templates/index.html
{% extends 'base.html' %} {% block content %} <h1>{% block title %} Index {% endblock %}</h1> <h2>Welcome to FlaskApp!</h2> {% endblock %}
nano app.py
# ... @app.route('/messages/<int:idx>') def message(idx): messages = ['Message Zero', 'Message One', 'Message Two'] return render_template('message.html', message=messages[idx])
nano templates/message.html
{% extends 'base.html' %} {% block content %} <h1>{% block title %} Messages {% endblock %}</h1> <h2>{{ message }}</h2> {% endblock %}
http://127.0.0.1:5000/messages/0 http://127.0.0.1:5000/messages/1 http://127.0.0.1:5000/messages/2 http://127.0.0.1:5000/messages/3
nano app.py
from flask import Flask, render_template, abort # ... # ... @app.route('/messages/<int:idx>') def message(idx): messages = ['Message Zero', 'Message One', 'Message Two'] try: return render_template('message.html', message=messages[idx]) except IndexError: abort(404)
http://127.0.0.1:5000/messages/3
Not Found The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.
nano app.py
from flask import Flask, render_template, abort app = Flask(__name__) @app.errorhandler(404) def page_not_found(error): return render_template('404.html'), 404 @app.route('/') def index(): return render_template('index.html') @app.route('/messages/<int:idx>') def message(idx): messages = ['Message Zero', 'Message One', 'Message Two'] try: return render_template('message.html', message=messages[idx]) except IndexError: abort(404)
nano templates/404.html
{% extends 'base.html' %} {% block content %} <h1>{% block title %} 404 Not Found. {% endblock %}</h1> <p>OOPS! Sammy couldn't find your page; looks like it doesn't exist.</p> <p>If you entered the URL manually, please check your spelling and try again.</p> {% endblock %}
http://127.0.0.1:5000/messages/3
nano app.py
# ... @app.errorhandler(404) def page_not_found(error): return render_template('404.html'), 404 @app.errorhandler(500) def internal_error(error): return render_template('500.html'), 500 # ...
# ... @app.route('/500') def error500(): abort(500)
nano templates/500.html
{% extends 'base.html' %} {% block content %} <h1>{% block title %} 500 Internal Server Error {% endblock %}</h1> <p>OOOOPS! Something went wrong on the server.</p> <p>Sammy is currently working on this issue. Please try again later.</p> {% endblock %}
http://127.0.0.1:5000/500
127.0.0.1 - - [21/Sep/2021 14:36:45] "GET /messages/1 HTTP/1.1" 200 - 127.0.0.1 - - [21/Sep/2021 14:36:52] "GET /messages/2 HTTP/1.1" 200 - 127.0.0.1 - - [21/Sep/2021 14:36:54] "GET /messages/3 HTTP/1.1" 404 -
nano app.py
# ... @app.route('/messages/<int:idx>') def message(idx): app.logger.info('Building the messages list...') messages = ['Message Zero', 'Message One', 'Message Two'] try: app.logger.debug('Get message with index: {}'.format(idx)) return render_template('message.html', message=messages[idx]) except IndexError: app.logger.error('Index {} is causing an IndexError'.format(idx)) abort(404) # ...
http://127.0.0.1:5000/messages/1
Output [2021-09-21 15:17:02,625] INFO in app: Building the messages list... [2021-09-21 15:17:02,626] DEBUG in app: Get message with index: 1 127.0.0.1 - - [21/Sep/2021 15:17:02] "GET /messages/1 HTTP/1.1" 200 -
http://127.0.0.1:5000/messages/3
Output[2021-09-21 15:33:43,899] INFO in app: Building the messages list... [2021-09-21 15:33:43,899] DEBUG in app: Get message with index: 3 [2021-09-21 15:33:43,900] ERROR in app: Index 3 is causing an IndexError 127.0.0.1 - - [21/Sep/2021 15:33:43] "GET /messages/3 HTTP/1.1" 404 -
Sometimes, we want to fix POST Error 405 Method Not Allowed with Flask Python. in this article, we’ll look at how to fix POST Error 405 Method Not Allowed with
@app.route('/template', methods=['GET', 'POST']) def template(): if request.method == 'POST': return "Hello" return render_template('index.html')
<form action="{{ url_for('template') }}" method="post"> ... </form>
Do I Have To Provide A Body Response Flask With Http 405 Error
Asp.NET Web API — 405 — HTTP verb used to access this page is not allowed — how to set handler mappings Flask: [405 error] with pagination and POST request. 1. Method Not Allowed. Flask …
# app.py from flask import Flask, render_template, request, redirect, json, url_for from flaskext.mysql import MySQL app = Flask(__name__) # Database connection info. Note that this is not a secure connection. app.config['MYSQL_DATABASE_USER'] = 'root' app.config['MYSQL_DATABASE_PASSWORD'] = '' app.config['MYSQL_DATABASE_DB'] = 'RamsterDB' app.config['MYSQL_DATABASE_HOST'] = 'localhost' mysql = MySQL() mysql.init_app(app) conn = mysql.connect() cursor = conn.cursor() mysql = MySQL() mysql.init_app(app) conn = mysql.connect() cursor = conn.cursor() @app.route('/') def main(): return render_template('search.html') @app.route('/showRegister', methods=['POST','GET']) def showRegister(): return render_template('register.html') @app.route('/register', methods=['POST, GET']) def register(): # read the posted values from the UI #try: _username = request.form['inputUsername'] _password = request.form['inputPassword'] # validate the received values if _username and _password: return json.dumps({'html': '<span>All fields good !!</span>'}) else: return json.dumps({'html': '<span>Enter the required fields</span>'}) #return render_template('register.html') if __name__ == '__main__': app.debug = True app.run()
<!DOCTYPE html> <html lang="en"> <head> <title>Ramster</title> <link rel="stylesheet" href="/static/index.css"> <script src="/static/js/jquery-1.11.2.js"></script> <script src="../static/js/register.js"></script> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, height=100%"> </head> <body> <div class="topnav"> <a href="login">Login</a> <a href="#">Register</a> </div> <div class="content"> <h2>Ramster</h2> <p>Register your team</p> <form class="example" method="post" action="" style="margin:left;max-width:600px"> <input type="text" name="inputUsername" id="inputUsername" placeholder="Username" required autofocus><br><br><br> <input type="text" name="inputPassword" id="inputPassword" placeholder="Password" required><br><br><br> <button id="btnRegister" class="example" type="submit">Register</button> </form> <!--<form class="example" method="post" action="" style="margin:left;max-width:600px"> <input type="text" placeholder="Username" name="inputUsername"> <input type="text" placeholder="Password" name="inputPassword"> <button type="submit">Register</button> </form> <p></p>--> </div> <div class="footer"> <p>Terms and Conditions</p> </div> </body> </html>
$(function() { $('#btnRegister').click(function() { $.ajax({ url: '/register', data: $('form').serialize(), type: 'POST', success: function(response) { console.log(response); }, error: function(error) { console.log(error); } }); }); });
jquery-1.11.2.js:9659 POST http://localhost:5000/register 405 (METHOD NOT ALLOWED)
@app.route('/register', methods=['POST, GET'])
@app.route('/register', methods=['POST', 'GET'])
error 405 method not found.
import os # Flask from flask import Flask, request, session, g, redirect, url_for, abort, render_template, flash, Markup, send_from_directory, escape from werkzeug import secure_filename from cultura import app # My app from include import User @app.route('/') def index(): return render_template('hello.html') @app.route('/registrazione', methods=['POST']) def registration(): if request.method == 'POST': username= request.form.username.data return render_template('registration.html', username=username) else : return render_template('registration.html')
<html> <head> <title>Form di registrazione </title> </head> <body> {{ username }} <form id='registration' action='/registrazione' method='post'> <fieldset > <legend>Registrazione utente</legend> <input type='hidden' name='submitted' id='submitted' value='1'/> <label for='name' >Nome: </label> <input type='text' name='name' id='name' maxlength="50" /> <br> <label for='email' >Indirizzo mail:</label> <input type='text' name='email' id='email' maxlength="50" /> <br> <label for='username' >UserName*:</label> <input type='text' name='username' id='username' maxlength="50" /> <br> <label for='password' >Password*:</label> <input type='password' name='password' id='password' maxlength="50" /> <br> <input type='submit' name='Submit' value='Submit' /> </fieldset> </form> </body> </html>
@app.route('/registrazione', methods=['GET', 'POST'])
@app.route("/registrazione") def render_registrazione() -> "html": return render_template("registrazione.html")
@app.route('/registrazione', methods=['POST']) def registrazione(): if request.method == 'POST': username= request.form.username.data return render_template('registration.html', username=username) else : return render_template('registration.html')
from flask import Flask, jsonify application = Flask(__name__, static_url_path='') @application.route('/') def activecalls(): return application.send_static_file('activecalls/active_calls_map.html') @application.route('/_getData', methods=['GET', 'POST']) def getData(): #hit the data, package it, put it into json. #ajax would have to hit this every so often to get latest data. arr = {} arr["blah"] = [] arr["blah"].append("stuff"); return jsonify(response=arr) if __name__ == '__main__': application.run()
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> </script> <script> $.ajax({ //url : "http://dev.consumerunited.com/wsgi/activecalls.py/_getData", url : "activecalls.py/_getData", type: "POST", data : formData, datatype : "jsonp", success: function(data, textStatus, jqXHR) { //data - response from server alert("'" + data.response.blah + "'"); }, error: function (jqXHR, textStatus, errorThrown) { alert("error: " + errorThrown); } }); </script>
import requests import json URL = "http://hostname.com.sa/fetchdata/" PARAMS = '{ "id":"111", "age":30, "city":"New Heaven"}' response = requests.post(url = URL, json = PARAMS) print(response.content)
@app.route('/template', methods=['GET', 'POST']) def template(): if request.method == 'POST': return("Hello") return render_template('index.html')
<html> <head> <title> Title </title> </head> <body> Enter Python to execute: <form action="/" method="post"> <input type="text" name="expression" /> <input type="submit" value="Execute" /> </form> </body> </html>
<form action="/" method="post">
<form action="{{ url_for('template') }}" method="post">
<form action="/" method="post">
<form method="post">
import json import requests payload = {'firstname':'John', 'lastname':'Smith'} url = 'http://localhost:5000/order' r = requests.post(url,json=payload)
from flask import Flask app = Flask(__name__) @app.route('/order', method='POST') def getjson(): print('hello')
r = requests.get('http://localhost:5000/order') print(r.status_code)
from flask import Flask, jsonify, request app = Flask(__name__) @app.route('/order', methods=['POST']) def getjson(): content = request.json return jsonify(content)
import json import requests payload = {'firstname':'John', 'lastname':'Smith'} url = 'http://localhost:5000/order' headers = {'Content-type': 'application/json', 'Accept': 'text/plain'} r = requests.post(url, data=json.dumps(payload), headers=headers) print(r.status_code) print(r.json())
200 {'firstname': 'John', 'lastname': 'Smith'}
# i am using CORS app = Flask(__name__, static_url_path='', static_folder='web/static', template_folder='web/templates') CORS(app) #flask server code @app.route('/login', methods=['GET', 'POST']) def login(): print('hi') global logingStatus global currentUser if request.method == 'POST': result = db.login(request.form['username'], request.form['password']) if result == 'success': logingStatus = True currentUser = db.getUserObj(request.form['username']) # print(type(currentUser), '<----') return redirect(url_for('dashboard')) else: return result else: logingStatus = False return render_template('login.html')
axios.post('/login/', { username: this.username, password: this.password }).then(function (response) { if(response.data.includes('ERROR')) { this.errorMessage = response.data this.isError = true } }).catch(function (error) { console.log(error); });
axios('/login',{...}); # error Failed to load resource: the server responded with a status of 400 (BAD REQUEST)
@app.route('/test', methods=['GET', 'POST']) def test(): return 'test' # response: test # headers access-control-allow-origin:*
axios.post('/login', {..})
@app.route('/login', methods=['GET', 'POST'])
<form method="POST"> <input type="text" id="adduser" name="add" placeholder="Username"> <button type="submit"><i class="icon-plus"></i></button><br> <label for="adduser"><small>Add user</small></label><br> </form>
... app = Flask(__name__) # I've also tried this without the resources tag and the after_request handler CORS(app, supports_credentials=True, resources={r"*": {"origins": "*"}}) @app.after_request def after_request(response): response.headers.add('Access-Control-Allow-Headers', 'Content-Type, Authorization') response.headers.add('Access-Control-Allow-Methods', 'GET, POST, PATCH, DELETE, OPTIONS') response.headers.add('Access-Control-Allow-Origin', '*') return response ... # Redacted some more GET endpoints ... @app.route("/folders/<path:subpath>", methods=['GET', 'POST']) def view_folder(subpath): # Gather user data and validate path ... if request.method == 'POST': # Handle data and update db pass # ... # Also tried redirect(url_for('view_folder', subpath=subpath)) return render_template('view_folder.html', folder=subpath)
General: Request URL: http://127.0.0.1:5000/static/main.css Request Method: GET Status Code: 405 METHOD NOT ALLOWED Remote Address: 127.0.0.1:5000 Referrer Policy: strict-origin-when-cross-origin Response Headers: Access-Control-Allow-Headers: Content-Type, Authorization Access-Control-Allow-Methods: GET, POST, PATCH, DELETE, OPTIONS Access-Control-Allow-Origin: * Allow: HEAD, GET, OPTIONS Content-Length: 178 Content-Type: text/html; charset=utf-8 Date: Sat, 16 Apr 2022 13:17:46 GMT Server: Werkzeug/2.1.1 Python/3.10.0
<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='main.css') }}" />
if request.method == 'POST': data = request.form
{"error": "Incorrect Credentials"}
from flask import Flask, jsonify, requestapp = Flask(__name__)@router.route("/user/login", methods=['POST'])def user_login(): if "email" in request.data and "password" in request.data: if check_user_exists(request.data["email"]): pass else: return jsonify({"error": "Incorrect Email",}), 403 if check_password_is_correct(request.data["email"], request.data["password"]): pass else: return jsonify({"error": "Incorrect Password",}), 403 else: return jsonify({"error": "Missing Credentials",}), 403 return "Success", 200app.run(debug=True)
{"error": "Incorrect Credentials", "code": 403, "request_id": "1234567"}
#...class APIAuthError(Exception): code = 403 description = "Authentication Error"#[email protected]("/user/login", methods=['POST'])def user_login(): if "email" not in request.data: raise APIAuthError('Missing email value') if "password" not in request.data: raise APIAuthError('Missing password value') if check_user_exists(request.data["email"]) and check_password_is_correct(request.data["email"], request.data["password"]): return "Success", 200 else: raise APIAuthError('Incorrect Credentials')
@app.errorhandler(APIAuthError)def handle_exception(err): """Return JSON instead of HTML for MyCustomError errors.""" response = { "error": err.description, "request_id": get_request_id_from_somewhere() } if len(err.args) > 0: response["message"] = err.args[0] return jsonify(response), err.code
@app.errorhandler(SQLAlchemyError)def handle_exception(err): """Handle DB connection errors """ if isinstance(err, sqlalchemy.exc.InternalError): response["message"] = "Unable to connect to DB" return jsonify(response), 555
@app.errorhandler(500)def handle_exception(err): """Return JSON instead of HTML for any other server error""" app.logger.error(f"Unknown Exception: {str(err)}") app.logger.debug(''.join(traceback.format_exception(etype=type(err), value=err, tb=err.__traceback__))) response = {"error": "Sorry, that error is on us, please contact support if this wasn't an accident"} return jsonify(response), 500
import unittest from flask import Flask, Blueprint, request app = Flask(__name__) myblueprint = Blueprint('myblueprint', __name__) @myblueprint.route('/', methods=['GET']) def hello(): return 'hello world!' myblueprint.errorhandler(405)(lambda e: ('myblueprint 405', 405)) app.register_blueprint(myblueprint) app.errorhandler(405)(lambda e: ('app 405', 405)) class BlueprintOrAppTestCase(unittest.TestCase): def setUp(self): self.client = app.test_client() def test_200(self): resp = self.client.get('/') self.assertEqual(resp.status_code, 200) def test_405(self): with app.test_client() as client: resp = client.post('/?http405') self.assertEqual(resp.status_code, 405) self.assertEqual(resp.get_data(True), 'myblueprint 405') self.assertEqual(request.blueprint, 'myblueprint') if __name__ == '__main__': # app.run(use_reloader=True) unittest.main()
.F ====================================================================== FAIL: test_405 (__main__.BlueprintOrAppTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "test.py", line 30, in test_405 self.assertEqual(resp.get_data(True), 'myblueprint 405') AssertionError: 'app 405' != 'myblueprint 405' - app 405 + myblueprint 405 ---------------------------------------------------------------------- Ran 2 tests in 0.013s FAILED (failures=1)
123456789
<html> <body> <form action = "http://localhost:5000/login" method = "post"> <p>Enter Name:</p> <p><input type = "text" name = "nm" /></p> <p><input type = "submit" value = "submit" /></p> </form> </body></html>
123456789101112131415161718
from flask import Flask, redirect, url_for, requestapp = Flask(__name__)@app.route('/success/<name>')def success(name): return 'welcome %s' % [email protected]('/login',methods = ['POST', 'GET'])def login(): if request.method == 'POST': user = request.form['nm'] return redirect(url_for('success',name = user)) else: user = request.args.get('nm') return redirect(url_for('success',name = user))if __name__ == '__main__': app.run(debug = True)
1
user = request.form['nm']
1
user = request.args.get('nm')
How to fix POST Error 405 Method Not Allowed with Flask Python?
How to get raw POST body in Python Flask regardless of Content-Type header? Sometimes, we want to get raw POST body in Python Flask regardless of Content-Type …
@app.route('/template', methods=['GET', 'POST']) def template(): if request.method == 'POST': return "Hello" return render_template('index.html')
<form action="{{ url_for('template') }}" method="post"> ... </form>
Next Lesson PHP Tutorial
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.
Работа с ошибками приложения
Приложения отказывают,серверы отказывают.Рано или поздно вы увидите исключение в производстве.Даже если ваш код на 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