Python Flask - Detailed Explanation for Quickly Building Web Applications

This article will explore Python Flask web services in detail. I will first briefly introduce Flask, and then gradually enter advanced concepts such as routing, templates, form processing, and database integration in Flask. The goal is to let everyone understand and master the skills of using Flask to create dynamic web applications.

1. Introduction to Flask

Flask is a lightweight Web Server Gateway Interface (WSGI) web application framework. It is designed to be easy to use, but also provides extensibility, and users can freely choose which third-party libraries to integrate it with. Flask is a "micro" framework, which means that its core functionality is very limited, but can be enhanced through a series of extensions.

Let's take a look at how to create a simple Flask application.

from flask import Flask
app = Flask(__name__)

@app.route('/')
def hello_world():
    return 'Hello, World!'

if __name__ == '__main__':
    app.run()

In this code, we first import the Flask module and create a Flask web server instance. Then, we define a route, ie /. This route is mapped to a function hello_worldthat returns the 'Hello, World!' string when the user visits this URL.

2. Flask routing

app.routeFlask makes defining routes simple and easy by providing decorators . But did you know we can also app.add_url_ruleadd routes directly via methods? This approach provides more flexibility, for example, different HTTP methods can be added to the route.

def hello():
    return "Hello, World!"

app.add_url_rule('/', 'hello', hello)

In the above code, app.add_url_rulethe first parameter of is the URL rule, the second parameter is the alias of the function, and the third parameter is the function to be mapped.

3. Flask Templates

Flask uses the jinja2 templating library. This library is very powerful and allows you to embed Python code in HTML. The following example shows how to use templates in a Flask application:

from flask import render_template

@app.route('/hello/<name>')
def hello(name):
    return render_template('hello.html', name=name)

render_templateFunction used to render a template. It receives the name of the template and some template variables as arguments, and returns the generated HTML content. In templates, you can use { { name }}to display the value of a variable.

4. Flask form processing

Flask-WTF is an extension library for handling web forms in Flask. It is based on WTF Python, a Python library for working with form data. Flask-WTF also features CSRF (Cross-Site Request Forgery) protection.

let us

Look at a simple example:

from flask import request
from flask_wtf import FlaskForm
from wtforms import StringField

class MyForm(FlaskForm):
    name = StringField('name')

@app.route('/submit', methods=('GET', 'POST'))
def submit():
    form = MyForm()
    if form.validate_on_submit():
        return 'Hello, %s' % form.name.data
    return render_template('submit.html', form=form)

In this example, we define a form class MyFormwith one namefield. Then, we submitcreate an instance of this class in the route and check if the form passes validation. If the form is valid, we return a welcome message; otherwise, we render a form template.

5. Flask database integration

Flask-SQLAlchemy is an extension library that provides SQLAlchemy support for Flask applications. SQLAlchemy is an ORM (Object Relational Mapping) tool in Python that can map classes to database tables.

from flask_sqlalchemy import SQLAlchemy

app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:tmp/test.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)

    def __repr__(self):
        return '<User %r>' % self.username

In this example, we first configure the URL of the database and then create an SQLAlchemyinstance. Next, we define a Userclass that inherits from db.Modeland has two properties: idand username. Both properties are columns of the database table.

6. Build a RESTful API with Flask

Flask-RESTful is an extension worth knowing when building web APIs. It provides an easy way to quickly create REST APIs. You can implement API resources by defining Python classes, and map HTTP methods (such as GET, POST) to methods of the class.

from flask_restful import Resource, Api

api = Api(app)

class HelloWorld(Resource):
    def get(self):
        return {'hello': 'world'}

api.add_resource(HelloWorld, '/')

In the above code, we first created an Api object, then defined a resource class , and implemented a method HelloWorldin this class . getFinally, we api.add_resourcebind HelloWorldthe class to /the URL using .

7. Flask Blueprint

Flask's blueprint feature allows us to organize larger and more complex applications. You can think of a blueprint as a subset of a Flask application that can have its own routes, templates, and static files.

Here is a simple example:

from flask import Blueprint

simple_page = Blueprint('simple_page', __name__)

@simple_page.route('/<page>')
def show(page):
    return 'Page %s' % page

In this example, we first created a simple_pageblueprint called , and then defined a route for this blueprint show.

8. Flask error handling

Flask allows us to customize the error handling function, when a specific HTTP error occurs, we can return a custom response. Here's an example of how to define a custom handler for 404 errors:

@app.errorhandler(404)
def page_not_found(error):
    return 'This page does not exist', 404

In this example, we use app.errorhandlera decorator to register a new error handling function. When a 404 error occurs, it will return a custom error message.

9. Flask request hook

Flask provides several decorators that we can use to register functions that are called at different stages of processing a request. These decorators include before_first_request, before_request, after_requestand teardown_request.

@app.before_request
def before_request():
    print("This is executed BEFORE each request.")

In this example, before_requestthe decorator's function will be executed before each request.

10. Cookies and Sessions in Flask

In web development, we often need to store user information, such as user preferences or login status. Flask provides two ways to accomplish this task, Cookies and Sessions.

Here's an example of how to set and read cookies in Flask:

@app.route('/set')
def setcookie():
    resp = make_response('Setting cookie!')
    resp.set_cookie('username', 'the username')
    return resp

@app.route('/get')
def getcookie():
    username = request.cookies.get('username')
    return 'The username is ' + username

In the above example, setcookiethe route sets a cookie named username, and getcookiethe route reads and returns the value of this cookie.

One more thing

Flask's test client allows us to simulate sending requests to our application and see the responses.

def test_index():
    client = app.test_client()
    response = client.get('/')
    assert response.status_code == 200

In the above code, we first create a test client. Then, we use this client to send a GET request to /the URL, and finally, we check if the status code of the response is 200.

This is just the tip of the iceberg of Flask's powerful functions. The charm of Flask is far more than that. It also has many rich extensions, such as Flask-Login for handling user authentication, Flask-Mail for sending emails, and Flask-Migrate for processing databases. migration etc.

If it is helpful, please pay more attention to the personal WeChat public account: [Python full perspective] TeahLead_KrisChang, 10+ years of experience in the Internet and artificial intelligence industry, 10+ years of experience in technology and business team management, Tongji Software Engineering Bachelor, Fudan Engineering Management Master, Aliyun certified cloud service senior architect, head of AI product business with hundreds of millions of revenue.

Guess you like

Origin blog.csdn.net/magicyangjay111/article/details/131458001