from flask import Flask app = Flask(__name__) @app.route('/') def hello(): return "Hello, Flask!"
@app.route()
decorator. The @app.route()
decorator takes a URL as the argument and a function as the value. The function that you pass to the @app.route()
decorator will be called when the URL is requested.@app.route('/user/<username>') def show_user(username): return f"Hello, {username}!"
redirect()
function to redirect to another URL.
from flask import redirect @app.route('/old-url') def old_url(): return redirect('/new-url')
@app.errorhandler()
decorator. The @app.errorhandler()
decorator takes an error code as the argument and a function as the value. The function that you pass to the @app.errorhandler()
decorator will be called when the error code is encountered.In Flask, you can handle errors using error handlers and exception handling. Flask provides ways to customize error pages for different HTTP status codes and also allows you to handle exceptions that might occur during the execution of your application. Let’s look at both methods:Error Handlers: Flask allows you to create custom error handlers for specific HTTP status codes. You can use the @app.errorhandler
decorator to define error handlers for various status codes.
from flask import Flask, render_template app = Flask(__name__) @app.route('/') def index(): return "Hello, Flask!" # Custom error handler for 404 Not Found @app.errorhandler(404) def page_not_found(error): return render_template('404.html'), 404 # Custom error handler for 500 Internal Server Error @app.errorhandler(500) def internal_server_error(error): return "Internal Server Error", 500 if __name__ == '__main__': app.run(debug=True)
Exception handling in Flask allows you to catch and handle exceptions that occur during the execution of your application. You can use the try
, except
, and finally
blocks to handle exceptions and respond accordingly.
from flask import Flask, render_template app = Flask(__name__) @app.route('/') def index(): return "Hello, Flask!" @app.route('/divide/<int:num>') def divide_by_zero(num): try: result = 10 / num return f"The result is: {result}" except ZeroDivisionError: return "Error: Cannot divide by zero." except Exception as e: return f"An error occurred: {str(e)}" if __name__ == '__main__': app.run(debug=True)
from flask_wtf import FlaskForm from wtforms import StringField, SubmitField class MyForm(FlaskForm): name = StringField('Name') submit = SubmitField('Submit')
from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///mydatabase.db' db = SQLAlchemy(app)
class User(db.Model): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(80), unique=True, nullable=False) email = db.Column(db.String(120), unique=True, nullable=False) def __repr__(self): return f'<User {self.username}>'
from flask import Flask from flask_restful import Resource, Api app = Flask(__name__) api = Api(app) class HelloWorld(Resource): def get(self): return {'message': 'Hello, World!'} api.add_resource(HelloWorld, '/') if __name__ == '__main__': app.run(debug=True)
from flask_jwt import JWT, jwt_required, current_identity from werkzeug.security import safe_str_cmp # Sample user class class User: def __init__(self, id, username, password): self.id = id self.username = username self.password = password # Dummy user data users = [ User(1, 'user1', 'password1'), User(2, 'user2', 'password2') ] # JWT authentication functions def authenticate(username, password): user = next((user for user in users if user.username == username), None) if user and safe_str_cmp(user.password.encode('utf-8'), password.encode('utf-8')): return user def identity(payload): user_id = payload['identity'] return next((user for user in users if user.id == user_id), None) app.config['SECRET_KEY'] = 'super-secret-key' jwt = JWT(app, authenticate, identity) @app.route('/protected') @jwt_required() def protected(): return f'Hello, {current_identity.username}!'
from flask_caching import Cache app = Flask(__name__) app.config['CACHE_TYPE'] = 'simple' cache = Cache(app) @app.route('/slow') @cache.cached(timeout=60) def slow_function(): # Expensive calculation or operation return "Slow response" if __name__ == '__main__': app.run(debug=True)
from flask import Flask, render_template from flask_socketio import SocketIO app = Flask(__name__) app.config['SECRET_KEY'] = 'secret_key' socketio = SocketIO(app) @app.route('/') def index(): return render_template('index.html') @socketio.on('message') def handle_message(message): print('Received message: ', message) socketio.send('Message received: ' + message) if __name__ == '__main__': socketio.run(app, debug=True)
In Flask, you can handle these HTTP requests using different route decorators (@app.route) to specify the URL patterns for each type.
In Flask, you can handle both GET and POST requests using the route decorators (@app.route) and request methods in view functions.
debug
parameter to True
when creating the Flask application:
from flask import Flask app = Flask(__name__) app.debug = True
from flask import Flask app = Flask(__name__) @app.route('/') def index(): return "Hello, Flask!" with app.test_client() as client: response = client.get('/') print(response.data) # Output: b'Hello, Flask!'
What is Flask?
Flask is a web development framework. It provides a lot libraries for building lightweight web applications in python. Flask is considered by many as a micro-framework due to the fact that it only provides the essential components – things like routing, request handling, sessions, and so on. It provides you with libraries, tools, and modules to develop web applications like a blog, wiki, or even a commercial website. It’s considered “beginner friendly” because it doesn’t have boilerplate code or dependencies which can distract from the primary function of an application. Data handling handling for example, the developer can write a custom module or use an extension.
What is Flask used for?
Flask is mainly used for backend development, but it makes use of a templating language called Jinja2 which is used to create HTML, XML or other markup formats that are returned to the user via an HTTP request.
Note that in this series of tutorial, we’ll be using Flask as a backend framework and React as a frontend framework.
Resources
https://flask.palletsprojects.com/en/1.1.x/testing/