3.4 KiB
Flask is an essential Python library for web development, offering a lightweight and modular micro web framework for building web applications. It provides the tools, libraries, and technologies to allow developers to build a web application. Flask supports extensions that can add application features as if they were implemented in Flask itself. Here's a concise reference guide for common use cases with Flask:
# `Flask` Reference Guide
## Installation
pip install Flask
## Basic Usage
### Creating a Simple Flask Application
```python
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello, World!'
if __name__ == '__main__':
app.run(debug=True)
This code snippet creates a basic web application that responds with "Hello, World!" when you access the root URL.
Running the Application
By default, the Flask application will run on localhost port 5000. To run the application, execute the Python script directly, and navigate to http://127.0.0.1:5000/ in a web browser.
Routing
Flask allows you to map URLs to Python functions, enabling dynamic content generation based on URL parameters.
@app.route('/user/<username>')
def show_user_profile(username):
# show the user profile for that user
return 'User %s' % escape(username)
Templates
Flask integrates with Jinja2 templating engine, allowing for dynamic content generation in HTML.
from flask import render_template
@app.route('/hello/<name>')
def hello(name=None):
return render_template('hello.html', name=name)
This will render an HTML template located in the templates folder.
Static Files
Static files such as JavaScript, CSS, and images can be served from the static directory.
<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
Request Data
Access data sent by the client using Flask's request object.
from flask import request
@app.route('/login', methods=['POST'])
def login():
username = request.form['username']
password = request.form['password']
# Logic for login
Redirects and Errors
Flask supports redirects and custom error handling.
from flask import abort, redirect, url_for
@app.route('/redirect')
def redirect_example():
return redirect(url_for('hello_world'))
@app.errorhandler(404)
def page_not_found(error):
return render_template('page_not_found.html'), 404
Flask Extensions
Flask can be extended with various extensions available in the Flask ecosystem for ORM, form validation, authentication, and more.
- Flask-SQLAlchemy for ORM.
- Flask-WTF for forms.
- Flask-Login for authentication.
Deploying Flask Applications
Flask applications can be deployed in various ways, including traditional web servers like Apache or Nginx using WSGI, as well as containerized environments like Docker, or platforms like Heroku, AWS Elastic Beanstalk, and Google App Engine.
Flask is designed to be easy to use and extend, making it suitable for building everything from simple web services to complex web applications. With a strong focus on documentation and community, Flask has become a popular choice among Python developers for web development tasks.
Flask's simplicity and flexibility, allowing for the quick development of web applications with minimal setup, have made it particularly popular in the Python community for both beginners and experienced developers.