Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Flask Basic Concepts

Flask Basic Concepts

In the previous chapter we learned how to create a first Flask application. In this chapter we will take a detailed look at some basic concepts of Flask.

Understanding Flask's basic concepts is very important for developing efficient web applications.

The following is a detailed explanation of Flask's main basic concepts:

1. Routing (Routing)

Routing is the mapping from URLs to Python functions. Flask allows you to define routes so that when a user visits a specific URL, Flask calls the corresponding view function to handle the request.

Example

from

flask

import

Flask

app

=

Flask

(

name

)

@

app.

route

(

'/'

)

def

home

(

)

:

   

return

'Welcome to the Home Page!'

@

app.

route

(

'/about'

)

def

about

(

)

:

   

return

'This is the About Page.'

2. View Functions (View Functions)

A view function is a Python function that handles a request and returns a response. They usually take a request object as a parameter and return a response object, or directly return content such as a string or HTML.

Example

from

flask

import

request

@

app.

route

(

'/greet/'

)

def

greet

(

name

)

:

   

return

f

'Hello, {name}!'

The greet function receives the name parameter from the URL and returns a string response.

3. Request Object (Request Object)

The request object contains information about the request sent by the client, including the request method, URL, headers, form data, and so on. Flask provides the request object to access this information.

Example

from

flask

import

request

@

app.

route

(

'/submit'

,

methods

=

[

'POST'

]

)

def

submit

(

)

:

    username

=

request.

form

.

get

(

'username'

)

   

return

f

'Hello, {username}!'

request.form.get('username'): gets the username field from form data in a POST request.

4. Response Object (Response Object)

The response object contains information about the response sent to the client, including the status code, headers, and response body. By default, Flask uses strings and HTML directly as the response body.

Example

from

flask

import

make_response

@

app.

route

(

'/custom_response'

)

def

custom_response

(

)

:

    response

=

make_response

(

'This is a custom response!'

)

    response.

headers

[

'X-Custom-Header'

]

=

'Value'

   

return

response

make_response: creates a custom response object and sets the X-Custom-Header response header.

5. Templates (Templates)

Flask uses the Jinja2 template engine to render HTML templates. Templates allow you to embed Python code in HTML to dynamically generate web page content.

Example

from

flask

import

render_template

@

app.

route

(

'/hello/'

)

def

hello

(

name

)

:

   

return

render_template

(

'hello.html'

,

name

=

name

)

Template file (templates/hello.html):

Example

   

<p>Hello</p>

   

Hello, {{ name }}!

6. Application Factory (Application Factory)

An application factory is a Python function used to create and configure Flask application instances. This approach allows you to create multiple application instances, or to initialize an application with different configurations.

Example

from

flask

import

Flask

def

create_app

(

config_name

)

:

    app

=

Flask

(

name

)

    app.

config

.

from_object

(

config_name

)

   

from

.

import

routes

    app.

register_blueprint

(

routes.

bp

)

   

return

app

The create_app function creates a Flask application instance and loads configuration from a configuration object.

7. Configuration Objects (Configuration Objects)

Configuration objects are used to set various configuration options for an application, such as database connection strings, debug mode, and so on. A Flask application can be configured by setting values directly or by loading a configuration file.

Example

class

Config:

    DEBUG

=

True

    SECRET_KEY

=

'mysecretkey'

    SQLALCHEMY_DATABASE_URI

=

'sqlite:///mydatabase.db'

app.config.from_object(Config): loads configuration items from the Config class into the application configuration.

8. Blueprints (Blueprints)

A blueprint is a way of organizing code in Flask. It allows you to group related view functions, templates, and static files together, and to reuse them across multiple applications.

Example

from

flask

import

Blueprint

bp

=

Blueprint

(

'main'

,

name

)

@

bp.

route

(

'/'

)

def

home

(

)

:

   

return

'Home Page'

Register a blueprint (app/init.py):

Example

from

flask

import

Flask

from

.

routes

import

bp

as

main_bp

def

create_app

(

)

:

    app

=

Flask

(

name

)

    app.

register_blueprint

(

main_bp

)

   

return

app

9. Static Files (Static Files)

Static files are files that are not executed by the server, such as CSS, JavaScript, and image files. Flask provides a simple way to serve these files.

Example of accessing a static file:





Static file directory: place static files in the static folder, and Flask will serve them automatically.

10. Extensions (Extensions)

Flask has many extensions that can add extra functionality, such as database integration, form validation, user authentication, and so on. These extensions provide more advanced features and third-party integrations.

Example

from

flask_sqlalchemy

import

SQLAlchemy

app.

config

[

'SQLALCHEMY_DATABASE_URI'

]

=

'sqlite:///mydatabase.db'

db

=

SQLAlchemy

(

app

)

SQLAlchemy: an extension for database integration.

11. Sessions (Sessions)

Flask uses client-side sessions to store user information so that it can remember their state as they browse the application. Session data is stored in a cookie on the client and is signed and encrypted on the server.

Example

from

flask

import

session

An automatically generated secret key

app.

secret_key

=

'your_secret_key_here'

@

app.

route

(

'/set_session/'

)

def

set_session

(

username

)

:

    session

[

'username'

]

=

username

   

return

f

'Session set for {username}'

@

app.

route

(

'/get_session'

)

def

get_session

(

)

:

    username

=

session.

get

(

'username'

)

   

return

f

'Hello, {username}!'

if

username

else

'No session data'

The session object is used to access and store session data.

You can use Python's built-in secrets module to generate a strongly random secret key.

python3 -c 'import secrets; print(secrets.token_hex())'

12. Error Handling (Error Handling)

Flask allows you to define error handling functions that are called when specific errors occur. You can customize error pages or handling logic.

Example

@

app.

errorhandler

(

404

)

def

page_not_found

(

e

)

:

   

return

'Page not found'

,

404

@

app.

errorhandler

(

500

)

def

internal_server_error

(

e

)

:

   

return

'Internal server error'

,

500

@app.errorhandler(404): defines a handler for 404 errors, returning a custom error page.