1. Introduction to Flask
Flask is a lightweight Python web framework designed to help developers quickly build web applications. Compared to heavyweight frameworks like Django, Flask is more concise and flexible, ideal for small web projects development, and can even be used to build RESTful APIs.
The core features of Flask include:
- A concise API: Flask uses simple and intuitive APIs, and developers can get started quickly.
- High flexibility: Flask will not restrict developers' choices too much, it provides developers with more freedom.
- Extensibility: Flask supports rich extensions to meet various needs such as database, form verification, user authentication, etc.
2. Flask installation
To use Flask, you first need to install the Flask library. Open the command line and install it using pip:
pip install flask
3. Create a simple Flask application
-
Create a project folder
Suppose we want to create a name called
flask_demo
For the project, first create a folder:mkdir flask_demo cd flask_demo
-
Create Flask app
exist
flask_demo
Create a Python file under the folder, and write the following code in it:
from flask import Flask # Create a Flask instanceapp = Flask(__name__) # Define routes and view functions@('/') def hello_world(): return 'Hello, World!' # Start the applicationif __name__ == '__main__': (debug=True)
explain:
-
Flask(__name__)
: Create a Flask application instance,__name__
Parameters tell Flask in which module to be applied. -
@('/')
: Decorator, indicating execution when accessing the root URLhello_world
Function. -
(debug=True)
: Start the Flask application and enable debugging mode to facilitate viewing of error messages during development.
-
-
Run the application
Run the following command from the command line to start the Flask application:
python
After successful startup, visit the browser and enter
http://127.0.0.1:5000/
, you should be able to see the browser display "Hello, World!".
4. Flask routing and view
In Flask, the route is through the decorator@()
To define it, it associates the URL path with a view function (i.e. the function that handles the request).
For example, we can define different view functions for different paths:
@('/hello') def hello(): return 'Hello, Flask!' @('/goodbye') def goodbye(): return 'Goodbye, Flask!'
Visithttp://127.0.0.1:5000/hello
There will be returned to “Hello, Flask!” and visithttp://127.0.0.1:5000/goodbye
It will return “Goodbye, Flask!”.
V. Receive and process user input
Flask allows you to pass the request object (request
) Get user input data. Common ones areGET
andPOST
ask.
-
deal with
GET
askBy default, Flask uses
GET
Methods handle requests. When you access a URL, the browser will issue aGET
ask. You can passGet query parameters:
from flask import request @('/search') def search(): query = ('q') return f'You searched for: {query}'
Visit
http://127.0.0.1:5000/search?q=Flask
It will return “You searched for: Flask”. -
deal with
POST
askIf you need to process the data submitted by the form, you can use
POST
ask. Here is a simple form submission example:from flask import request, render_template @('/login', methods=['GET', 'POST']) def login(): if == 'POST': username = ['username'] password = ['password'] return f'Username: {username}, Password: {password}' return render_template('')
This view function handles
/login
Routing,GET
The request will return a login form.POST
The request will return the submitted username and password.
6. Template Engine Jinja2
Flask uses Jinja2 as the template engine for dynamic rendering of HTML pages. In templates, variables and control structures can be used (e.g.if
、for
etc.) to construct dynamic content.
For example, create a template:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Flask Template Example</title> </head> <body> <h1>Hello, {{ name }}!</h1> </body> </html>
Then pass in the view functionname
Variables:
from flask import render_template @('/greet') def greet(): return render_template('', name='Flask User')
Visithttp://127.0.0.1:5000/greet
, you will see "Hello, Flask User!".
7. Flask and database
Flask supports interaction with databases through extensions such as Flask-SQLAlchemy. SQLAlchemy is a powerful ORM (Object Relational Mapping) tool that maps database tables into Python classes and performs operations.
Install Flask-SQLAlchemy:
pip install flask_sqlalchemy
Then, configure the database in the Flask application and use SQLAlchemy for data manipulation:
from flask import Flask from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) ['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' db = SQLAlchemy(app) class User(): id = (, primary_key=True) username = ((150), unique=True, nullable=False) @('/add_user') def add_user(): user = User(username='John Doe') (user) () return 'User added successfully!'
8. Summary
Flask is a very flexible and lightweight web framework suitable for rapid development of web applications and APIs. It has a clean API, is easy to use, and can achieve more powerful features with rich extensions.
In this blog, we cover how to install Flask, create simple web applications, define routes, process user input, use the Jinja2 template engine, and interact with the database.
By mastering the basic usage of Flask, you can start building more complex web projects.
This is the end of this article about quickly building a web application in python flask. For more related content on building a web application in python flask, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!