Frontend and Backend Collaboration: Flask Template Rendering HTML Dynamic Data Example

This article introduces the basic method of implementing front - end and back - end data linkage rendering using the Flask framework. First, you need to install Flask and create a project structure (including app.py and templates folder). The back - end defines routes through @app.route, the view function prepares data (such as a user information dictionary), and passes the data to the front - end template using render_template. The front - end template uses Jinja2 syntax (variable output {{ }}, conditional judgment {% if %}, loop rendering {% for %}) to display the data. After running app.py and accessing localhost:5000, you can see the dynamically rendered user information. The core steps are: back - end data preparation and route rendering, and front - end template syntax parsing. After mastering this process, you can expand more data transfer and template reuse (such as multi - conditional judgment, list rendering), which is the basis for front - end and back - end collaboration in web development.

Read More
Beginners' Guide: Variables and Loop Syntax in Django Template Engine Jinja2

This article introduces the core syntax of variables and loops in the Django template engine Jinja2. The template engine combines backend data with HTML templates to generate web pages. As Django's default engine, Jinja2 is the focus here, with emphasis on variables and loops. Variable syntax: Variables are enclosed in double curly braces {{}}. They support strings, numbers, booleans, and lists (displayed directly). Dictionaries can be accessed using dot notation (.) or square brackets ([]), such as {{ user.name }} or {{ user["address"]["city"] }}. Note that undefined variables will cause errors, and variables in templates are not modifiable. Loop syntax: Use {% for variable in list %} to iterate. It is accompanied by forloop.counter (for counting), first/last (for marking the first and last elements), and {% empty %} to handle empty lists. Examples include looping through lists or lists of dictionaries (e.g., each dictionary in a user list). Summary: Mastering variables and loops enables quick data rendering. Subsequent articles will cover advanced topics such as conditions and filters.

Read More
3 Minutes to Understand: Defining and Using Routes in Python Web Development

This article introduces the concept of "routing" in web development and its application under the Flask framework. Routing is analogous to a restaurant waiter, responsible for receiving user requests (such as accessing a URL) and matching the corresponding processing logic (such as returning a web page), serving as the core that connects user requests with backend logic. The article focuses on the key usages of routing in Flask: 1. **Basic Routing**: Defined using `@app.route('/path')`, corresponding to a view function returning a response, such as the homepage at the root path `/`. 2. **Dynamic Parameters**: Receive user input via `<parameter_name>` or `<type:parameter_name>` (e.g., `int:post_id`), with automatic type conversion. 3. **HTTP Methods**: Specify allowed request methods using `methods=['GET','POST']`, combined with the `request` object to determine the request type. 4. **Reverse Lookup**: Dynamically generate routing URLs using `url_for('function_name', parameters)` to avoid hardcoding. The core is to achieve request distribution, parameter processing, and page interaction through routing. Mastering these basics can support page jumps and data interaction in web applications.

Read More
Django ORM Practical Guide: CRUD Operations with SQLite Database

This article introduces the operation methods of Django framework combined with SQLite database, focusing on the use of ORM tools. Django ORM allows database operations through Python code, avoiding the need to write complex SQL statements. SQLite is lightweight and easy to use, making it suitable for development and learning. Preparatory work includes: creating a new Django project (`startproject`/`startapp`), configuring SQLite by default in `settings.py`, defining models (such as a `User` class), and executing `makemigrations` and `migrate` to generate database tables. The core is the CRUD operations of Django ORM: **Creation** can be done via `create()` or instantiation followed by `save()`; **Reading** uses `all()`, `filter()`, `get()` (supporting conditions and sorting); **Updating** uses `update()` for batch operations or querying first then modifying; **Deletion** uses `delete()` for batch operations or querying first then deleting. It is important to note the lazy execution of QuerySet, using `unique=True` to prevent duplicates, and exception handling for `get()`. Summary: By defining models, migrating table structures, and calling ORM methods, database operations can be completed. The code is concise and easy to maintain, making it suitable for quickly getting started with web development.

Read More
RESTful API Getting Started: Developing a Simple GET Data Interface with Flask

This article introduces the concept of RESTful APIs and implementing a GET interface with Flask. RESTful APIs are HTTP-based front-end and back-end interaction architectures centered on resources, manipulating resources through GET/POST/PUT/DELETE operations, stateless, and returning JSON data. Flask is chosen for its lightweight and flexibility, making it suitable for beginner development. Flask can be installed via `pip install flask` (virtual environment is optional). Implementation involves two steps: first, define the root path `/` to return "Hello, Flask!", with the core code being the `@app.route('/')` decorator and the `return` statement with a string; second, implement the `/users` interface to return user list JSON data, requiring the import of `jsonify` and returning the converted list. After starting the application, access `http://localhost:5000/users` through a browser, curl, or Postman for testing. Core steps include: importing Flask, initializing the application, defining route functions, returning data, and starting the service. Future extensions can include more routes or database integration.

Read More
HTTP Requests and Responses: Fundamental Core Concepts in Python Web Development

In Python web development, HTTP is the core for communication between the client (e.g., a browser) and the server, based on the "request-response" mechanism. The client generates an HTTP request, which includes methods (GET/POST, etc.), URLs, header information (e.g., User-Agent, Cookie), and a request body (POST data). After processing, the server returns an HTTP response, which contains a status code (e.g., 200 for success, 404 for not found), response headers (e.g., Content-Type), and a response body (web pages/data). The process is: client sends a request → server parses and processes it → returns a response → client renders the response (e.g., HTML to render a web page). Python frameworks (e.g., Flask) simplify this process. In the example, Flask uses `request` to access the request and `return` to directly send back the response content. Understanding this mechanism is fundamental to web development and lays the foundation for advanced studies such as HTTPS and Cookies.

Read More