Beginner-Friendly: Flask-Migrate Database Migration Tutorial
### Why Database Migration is Needed? As database structures evolve with changing requirements during development, manual modifications risk data loss or version chaos. Migration tools enable safe structural changes while preserving data, akin to "database version control." ### What is Flask-Migrate? It is a Flask extension built on Alembic, designed to manage database schema changes in conjunction with SQLAlchemy. It automatically generates migration scripts, eliminating the need for manual SQL writing. ### Installation and Initialization Install dependencies: `pip install flask flask-sqlalchemy flask-migrate`. Initialize: Set the `FLASK_APP` environment variable, then run `flask db init` to generate the `migrations` folder and define models (e.g., a `User` table). ### Core Migration Commands 1. **Initialize Migration Environment** (first time): `flask db init` generates the `migrations` folder. 2. **Generate Migration Script**: After modifying models, run `flask db migrate -m "description of changes"` to create the SQL script. 3. **Apply Migration**: Execute `flask db upgrade` to apply the changes. ### Practical Workflow 1. Modify the model (e.g., add an `age` field); 2. Generate the script: `
Read MoreFlask Project Structure: From Small Projects to Large Applications
The article emphasizes the importance of Flask project structure planning, which can avoid code chaos and enhance development and maintenance efficiency. It evolves from simple to complex in stages: a single file is only suitable for quick verification but becomes hard to maintain due to code clutter; medium-sized projects split into templates, static files, but further structural standardization is needed, such as separating configurations (config.py), centralizing route management (routes.py), and isolating data models (models.py); large projects use Blueprints to split functional modules (e.g., main module, user module, blog module), achieving single responsibility and independent reusability. Best practices include: managing dependencies with requirements.txt, storing sensitive configurations in environment variables, enabling debug mode during development and disabling it in production, and adding a test directory. The core principle is "splitting functions and ensuring single responsibility," and developing the habit of standardized structures facilitates future expansion.
Read MoreFlask Extensions Recommended: Flask-SQLAlchemy and User Authentication
This article introduces the necessity of Flask extensions and the use of core extensions. Flask itself is lightweight, and complex requirements require implementation through extensions. The article focuses on explaining two key extensions: Flask-SQLAlchemy: Integrates SQLAlchemy, allowing database operations through Python objects without writing SQL directly. After installation, configure the database URI, define models (such as the User class), and support table creation (db.create_all()), as well as CRUD operations (add, commit, query, etc.). Flask-Login: Handles user authentication and session management. Configure LoginManager and use Werkzeug for password hashing storage. Implement login (login_user) and logout (logout_user) functions, and protect routes with the @login_required decorator. The combination of these two extensions enables rapid construction of web applications with database and user systems. Beginners can get started by mastering basic configurations and core APIs (such as create_all and login_user). For production environments, security measures such as HTTPS and CSRF protection should be added.
Read MoreGetting Started with Flask Deployment: Gunicorn and Nginx Configuration Tutorial
This article introduces a solution for deploying Flask applications in a production environment: since Flask's built-in development server does not support high concurrency and is insecure, it needs to be paired with Gunicorn (a WSGI server) and Nginx (a reverse proxy). The steps are as follows: First, install Gunicorn (`pip install gunicorn`) and Nginx (for Ubuntu/Debian, use `apt install nginx`). When starting Gunicorn, use `gunicorn -w 4 -b 127.0.0.1:8000 app:app` (where `-w` sets the number of workers, `-b` binds the address and port, and `app:app` specifies the application entry). Next, configure Nginx by creating a configuration file (e.g., `flask_app`), set up reverse proxy to Gunicorn (`proxy_pass`), and handle static resources (`location /static`). Enable the configuration and restart Nginx. For verification, access `http://localhost` or test with `curl`. For advanced use, configure Gunicorn to start automatically on boot via systemd. Common issues include port occupation and incorrect static file paths, which require checking Gunicorn status or firewall rules. The core is running the application through Gunicorn and using Nginx.
Read MoreBlueprint in Flask: A Practical Approach to Modular Application Development
Flask blueprints are used to address the problem of chaotic route management as the application grows in functionality. They enable grouping routes by different modules, resulting in a clear project structure and easier code maintenance. The core advantages of using blueprints include modular grouping (such as splitting user and product functionalities), code isolation for team collaboration, reduced circular import errors, and support for reuse. In practice, first design the project structure: the main app.py imports blueprints from two modules (user and product), and each module has a routes.py to define routes. For example, user/routes.py creates the user blueprint and defines routes like /profile and /login, with product/routes.py following a similar pattern. The main app.py registers these blueprints using register_blueprint, and a url_prefix can be added for unified prefixes (e.g., /user/profile). Advanced usage includes isolating templates (template_folder) and static files (static_folder), as well as controlling path prefixes and subdomains through url_prefix and subdomain. Blueprints modularize complex applications and reduce maintenance costs. It is recommended to use them from the early stages of a project to foster good development habits.
Read MoreFrom Scratch: Flask Form Handling and WTForms Validation
This article introduces the core knowledge of handling forms in Flask using the Flask-WTF extension. Flask-WTF is built on WTForms and provides form creation, validation, and CSRF protection. For environment preparation, install `flask` and `flask-wtf`. The core is defining form classes that inherit from `FlaskForm`, using field types like `StringField` and `PasswordField`, and pairing them with validators such as `DataRequired` and `Email` to define rules (e.g., non-empty, format, length). In view functions, instantiate the form and use `form.validate_on_submit()` to handle POST requests and validate data integrity. Templates should use `form.hidden_tag()` to generate CSRF tokens and loop through `form.xxx.errors` to display error messages. After successful validation, retrieve data from `form.xxx.data` and combine it with database storage (e.g., SQLAlchemy). Key process: Define form class → View processing → Template rendering → Data validation and processing. Use WTForms validators to implement checks for non-empty, format, etc., combined with CSRF protection for security, enabling rapid construction of reliable form systems.
Read MoreFlask Session Management: Basic Applications of Cookies and Sessions
This article introduces two core methods of session management in Flask and their applications. Session management enables websites to "remember" user states (such as login information), which Flask implements through Cookies and Sessions. Cookies are small data (approximately 4KB) stored on the client side (browser), suitable for non-sensitive temporary information (e.g., usernames, theme settings). They can be set using `response.set_cookie()` and read with `request.cookies.get()`, but users can disable them, and they are not suitable for sensitive information. Sessions are stored on the server side, offering higher security and suitable for sensitive data (e.g., user IDs). A `secret_key` must first be set for encryption, and they are stored/retrieved via the `session` object, with clearing done using `pop()` or `clear()`. By default, they use in-memory storage, which is lost upon server restart; Redis persistence is recommended for production environments. Comparison: Cookies are lightweight and simple but less secure, while Sessions are secure and reliable but increase server pressure. In actual development, they are often used in combination: Cookies store the Session ID, and Sessions store core user states.
Read MoreLearn Flask Easily: Detailed Explanation of Request and Response Objects
In Flask, requests and responses are the core of web development. A request refers to data sent by a client (e.g., a browser), which can be accessed through the `request` object. Key properties include: `method` (HTTP method like GET/POST), `args` (URL parameters), `form` (form data), `cookies`, and `headers`. For example, GET requests retrieve parameters using `request.args`, while POST requests access form data via `request.form`. A response is the result returned by the application. Common methods to return responses include: returning a string, HTML (using `render_template`), JSON (using `jsonify`), redirection (using `redirect`), and custom status codes (e.g., 404). In a comprehensive example, form submissions (POST) use `request.form` to retrieve data. After validation, the application returns either a JSON or HTML response to achieve interaction. Key principles: GET is used to fetch data (parameters in the URL), while POST is for data submission (parameters in the request body). For responses, `jsonify` returns JSON, `render_template` returns HTML pages, `redirect` performs redirection, and `url_for` resolves route URLs.
Read MoreFlask Database Operations: A Beginner's Guide to SQLAlchemy ORM
ORM solves the maintenance difficulties of directly writing SQL in web development by simplifying operations through mapping database table structures with Python objects. Flask + SQLAlchemy is a commonly used combination, and you need to install `flask` and `flask-sqlalchemy` first. During initialization, configure the SQLite database path (e.g., `sqlite:///mydatabase.db`) and disable modification tracking. Define model classes (such as User) that inherit from `db.Model`, with class attributes corresponding to table fields (including primary keys and constraints). Use `db.create_all()` to automatically generate the tables. Core operations are session-based (`db.session`): creation (`add` + `commit`), reading (`query.all()`/`filter_by()`/`get()`), updating (modify attributes + `commit`), and deletion (`delete` + `commit`). After mastering this process, you can extend to databases like MySQL and explore advanced features such as relationship models.
Read MoreEssential Guide for Beginners: Flask Static File Configuration and Management
This article explains the configuration and management of Flask static files, covering basic to advanced content. Static files refer to CSS, JS, images, etc., that do not need to be dynamically generated by the server. By default, they are stored in the `static` folder at the project root directory. In templates, they are referenced using `url_for('static', filename='path')`, with the path being relative to the `static` folder. For customizing the path, the `static_folder` parameter can be specified when creating the Flask application, such as for an `assets` folder, with the reference method remaining unchanged. For advanced management, attention should be paid to version control (e.g., adding version numbers to filenames or using dynamic parameters) to avoid caching issues. Static files can be organized into subfolders by type, with full paths specified in references. Common issues include path errors (e.g., misspelling the folder name) and forgetting to use `url_for`. Solutions involve checking the `static_folder` and `filename`. In production environments, it is recommended to use a proxy like Nginx for serving static files. Key points: use the default `static` folder and `url_for` for references, modify `static_folder` for custom paths, manage with attention to hierarchy and caching, and prioritize checking configurations when path issues arise.
Read MoreFlask Template Engine Jinja2: From Basic Syntax to Page Rendering
Jinja2 is the default templating engine for Flask, used for dynamically rendering HTML by combining data with static pages. Core features include variables, conditional statements, loops, template inheritance and inclusion, as well as filters for variable processing. In terms of syntax, variables are embedded using `{{ }}`, conditions with `{% if %}`, and loops with `{% for %}` (supporting the loop state variable and empty list handling); templates inherit from parent templates via `extend` (defining blocks) and reuse fragments with `include`; filters use `|` (e.g., `truncate` to truncate text). In Flask, templates are stored in the `templates` folder and rendered by passing data through the `render_template` function. Mastering these core syntaxes can enhance web development efficiency, and it is recommended to consolidate through practice with template inheritance and data processing.
Read MorePython Web Development: A Quick Start with the Lightweight Flask Framework
This article introduces the basic content of Flask, a lightweight Python web framework, including: **Definition and Features**: Flask is a lightweight and flexible Python framework that encapsulates repetitive tasks (such as HTTP handling and route management). It has a low learning curve, strong scalability, and is suitable for quickly developing small websites or APIs. **Environment Setup**: Install it via `pip install flask` and verify the version with `flask --version`. **First Application**: Create `app.py` to instantiate Flask, define the root route with `@app.route('/')`, and start the server with `app.run(debug=True)`. Accessing `http://127.0.0.1:5000` will display "Hello, Flask!". **Routes and View Functions**: Support basic routes (e.g., `/about`) and dynamic parameters (e.g., `/user/<username>`). Parameter types include integers, paths, etc. (e.g., `/post/<int:post_id>`). **Templates and Static Files**: Use the Jinja2 template engine for dynamic rendering of variables, loops, and conditions (in the `templates` folder); static resources (CSS/JS) are placed in the `static` folder, accessed via `url_for('static', filename='...')`.
Read MoreFlask Introduction: Mastering Routes and View Functions from Scratch
This article is an introductory guide to Flask routes and view functions. First, install Flask using `pip install flask`. A basic example (code in `app.py`) demonstrates the first application: create a `Flask` instance, define the root route with `@app.route('/')`, and have the view function `index()` return "Hello, Flask!". After running, access `http://127.0.0.1:5000/` to view the result. Routes map URLs to view functions, categorized into two types: static routes (e.g., `/about` bound to the `about()` function) and dynamic routes (using `<parameter_name>`, e.g., `/user/<username>`, supporting type constraints like `int:post_id`). View functions process requests: they can return strings, HTML, and support HTTP methods (e.g., GET/POST) via the `methods` parameter. To return JSON, use `jsonify`. Start the development server with `app.run(debug=True)` for easier debugging. Key points: Route definition mapping, dynamic parameter handling for variable paths, view functions processing requests and returning responses (text, HTML, JSON, etc.), and specifying HTTP methods through `methods`. Mastering these enables building simple web applications, with subsequent topics to explore templates and static files.
Read MoreBootstrap 5 Fundamentals: A Guide to Using Containers, Rows, and Columns with Nesting
The layout of Bootstrap 5 centers around containers, rows, columns, and their nesting, forming the foundation for quickly building responsive pages. **Containers** are the "large boxes" of the layout, available in two types: `.container` features a fixed width that automatically adjusts its maximum width based on screen size (e.g., 768px when md ≥ 768px) and is centered; `.container-fluid` spans the full width of the screen. **Rows** serve as "horizontal carriers" within containers, nested inside them and using negative margins to counteract container padding. They are only used to wrap columns and support a 12-column grid system (maximum 12 columns per row). **Columns** are the core "cells," with class names following the format `col-[breakpoint]-[number of columns]`. Breakpoints include sm (576px), md (768px), etc. (five types total), and the sum of column numbers per row must equal 12 (e.g., `col-md-4` occupies 4/12 width). They support responsive layouts, displaying different column counts at various breakpoints. **Nesting** allows rows and columns to be placed within columns, implemented by nesting `.row` within the target column to create multi-level layouts, with internal columns still adhering to the 12-column rule. Core rule: Containers wrap rows, which wrap columns.
Read MoreBootstrap 5 Button Groups: Tips for Using Side-by-Side Buttons Effectively
Button Groups in Bootstrap 5 are used to arrange functionally related buttons side by side, solving spacing, alignment, and styling issues in traditional layouts without manual CSS. Core usage is as follows: - **Basic Horizontal Button Group**: Wrap buttons with `.btn-group`, add the `.btn` class and color classes (e.g., `.btn-primary`). Include `role="group"` and `aria-label` for accessibility. - **Size Control**: Apply `.btn-group-sm` (small) or `.btn-group-lg` (large) to the outer container to adjust overall size. - **Vertical Arrangement**: Replace `.btn-group` with `.btn-group-vertical` for buttons to stack vertically. - **Nested Functionality**: Support nested dropdown menus inside `.btn-group`, e.g., combining with the `.dropdown` component. - **Alignment**: Use Flex classes (e.g., `.d-flex justify-content-center`) for centering or right-aligned groups. **Notes**: Use class names correctly, add accessibility attributes, and avoid excessive nesting. Mastery enables efficient construction of clear operation interfaces and improved development efficiency. Key class names: `.btn-group`/`.btn-group-vertical`/`.btn-group-sm`/`.btn-group-lg`.
Read MoreBootstrap 5 Pagination Component: Quick Implementation Method for List Pagination
When displaying large lists of data in web development, using a pagination component can enhance user experience. The Bootstrap 5 pagination component enables the quick implementation of an aesthetically pleasing and fully functional pagination effect through a simple HTML structure and CSS class names. Before use, include Bootstrap 5 CSS (and optional JS and Bootstrap Icons). Its core structure is based on `<ul class="pagination">`, containing `<li class="page-item">` (page number container) and `<a class="page-link">` (clickable item). The `active` class marks the current page, while `disabled` handles disabled states (e.g., next/previous buttons on the first/last page). Common scenarios include: handling boundary pages with disabled states, centering alignment, incorporating icons (using Bootstrap Icons), and adjusting size (`.pagination-sm`/`.pagination-lg`). Expansion suggestions: use `<button>` instead of `<a>` for dynamic loading, generate page numbers dynamically based on total pages, avoid `href="#"`, and use semantic URLs for SEO benefits. The Bootstrap 5 pagination component requires no complex code; mastering core class names suffices for most scenarios. Complex interactions can be implemented in combination with JavaScript.
Read MoreBootstrap 5 Alerts: Styling and Scenarios for Notification Messages
The Bootstrap 5 Alert component is used to display prompt messages, status feedback, or operation results. It supports multiple styles, animations, and interactive features, and is fully responsive. To use it, you need to first include the Bootstrap 5 CSS and JS files. A basic alert is created using the `alert` class and color theme classes (such as `alert-primary` for blue, `alert-success` for green, etc.). The `alert-dismissible` class can be added to enable a close button, and `fade show` can be used to enable fade-in and fade-out animations. Functionally, the `alert-link` class can unify link colors, and JavaScript can control automatic hiding (e.g., closing after 5 seconds). Typical scenarios include form submission success prompts, deletion operation confirmations, system notifications, etc. For customization, default styles can be overridden via CSS. Mastering color classes, close buttons, animations, and JavaScript interactions allows flexible enhancement of user experience and prompt clarity.
Read MoreBootstrap 5 Progress Bars: A Guide to Using the Intuitive Progress Display Component
Bootstrap 5 progress bar is a component for displaying task completion in web pages. Its core structure consists of an outer `.progress` container and an inner `.progress-bar` (with progress set via the `width` property). It supports customization for multiple scenarios: - **Color**: Use `bg-*` classes (e.g., `bg-primary`) or custom `background-color`. - **Height**: Adjust via `h-*` utility classes or `style="height:xxx"`. - **Striped effect**: Add `.progress-bar-striped` with `bg-gradient` for a gradient look. - **Dynamic loading**: Use `.progress-bar-animated` for static animation or update width via JavaScript (e.g., simulating a download). - **Stacked tasks**: Display multiple `.progress-bar` elements for multi-task progress. - **Accessibility**: Include attributes like `aria-valuenow` to enhance accessibility. By leveraging class names and utility classes, it enables quick implementation of beautiful, intuitive progress displays to meet diverse needs.
Read MoreBootstrap 5 Form Groups: Tips for Grouping Controls and Aligning Labels
Bootstrap 5 form groups are a core tool for organizing form elements in web development. They wrap related controls using the `.form-group` class to achieve style consistency and layout management. Basic usage requires combining with `.form-label` (label styling), `.form-control` (input styling), and spacing classes (such as `mb-3`). There are three label alignment methods: horizontal arrangement (implemented with `.row` + `.col-*` to place labels and input fields in the same row), floating labels (`.form-floating`, where the label automatically floats when the input is focused), and vertical arrangement (default, with labels on top, suitable for short forms). When grouping controls, use `.form-check` for radio/multi-select buttons and `.form-select` for dropdown menus. By skillfully applying these techniques, you can build beautiful and user-friendly forms, enhancing the user experience. It is recommended to choose the alignment method according to the scenario and master the Bootstrap 5 form system proficiently.
Read MoreBootstrap 5 Navigation Components: Implementation of Tabs and Breadcrumb Navigation
To use Bootstrap 5 navigation components, you first need to include its CSS and JS files (including Popper.js) in your HTML. Core components include tab navigation and breadcrumb navigation. **Tab Navigation (Tabs)** is used for categorizing content switching: Implemented via `.nav-tabs` (or `.nav-pills` for pill-shaped navigation), it requires wrapping navigation items with `.nav`. Navigation buttons (`nav-link`) are associated with content panels using `data-bs-toggle="tab"` and `data-bs-target`. Content areas are wrapped in `.tab-content` containing `.tab-pane`, where `fade` and `active` classes control transitions and default display. Accessibility attributes are supported to enhance user experience. **Breadcrumb Navigation** displays page hierarchy: Wrapped with the `.breadcrumb` class and an ordered list, each level is represented by `.breadcrumb-item`, with `.active` marking the current page. The default separator can be customized via CSS (e.g., `content: "›"`). It is pure HTML/CSS and does not require JavaScript. **Summary**: Tabs rely on JS for content switching and are suitable for categorized content; breadcrumbs are static and ideal for hierarchical display. Both support accessibility attributes. Bootstrap 5 provides rich extensions (e.g., pill-style, custom separators), enabling quick implementation.
Read MoreBootstrap 5 Responsive Images: Image Solutions for Different Screens
Bootstrap 5 provides a responsive image solution centered around the `.img-fluid` class: images inherit 100% width from their parent container with automatic height scaling, preventing overflow and distortion. It requires layout classes like `.container` to control container size. Aesthetic enhancements include `.rounded` (rounded corners), `.rounded-circle` (circular shape), and `.img-thumbnail` (thumbnail style). Centering is achieved with `.d-block mx-auto`. The `.aspect-ratio` class (e.g., 16:9) fixes the width-to-height ratio. For advanced use, the `srcset` attribute can be combined to load appropriately sized images based on screen width, addressing issues like distortion, slow loading, and overflow. This approach eliminates the need for complex CSS, enabling multi-device adaptation with ease and improving user experience.
Read MoreBootstrap 5 Theme Color Customization: Customizing Brand Colors and Component Colors
This article introduces methods for customizing Bootstrap 5 theme colors to create interfaces that align with brand styles. The core is controlling theme colors through Sass variables, which enhances brand consistency and reduces duplicate code. The steps are as follows: First, install Bootstrap 5 and Sass (Node.js environment required), and create the SCSS folder structure. Next, define global variables in custom.scss, such as setting the primary color to #4285F4 (Google Blue), and override core variables. Then, you can fine-tune component colors, such as using the $btn-primary-bg variable for buttons, the $card-bg variable for cards, or temporary utility classes. Advanced techniques include enabling dark mode ($enable-dark-mode: true) and implementing dynamic switching via CSS variables. Note that variables must be defined before importing Bootstrap, and compile using a Sass tool to generate CSS. After mastering this, you can flexibly customize brand interfaces.
Read MoreBootstrap 5 Text Styling: Alignment, Weight, and Line Height Settings
The text styles in Bootstrap 5 enable control over alignment, thickness, and line height through concise class names, enhancing readability and visual effects. For text alignment: The basic alignment classes are `.text-start` (left), `.text-center` (center), and `.text-end` (right). Responsive alignment supports breakpoint-based settings (sm, md, lg, xl) with the syntax `.text-<breakpoint>-<alignment>`, e.g., `.text-md-center` centers text on medium screens and above. For text weight: Use `.font-weight-*` classes, such as `.font-weight-bold` (bold), `.font-weight-normal` (normal), `.font-weight-light` (light), as well as `.font-weight-bolder`/`.font-weight-lighter` (relatively bolder/lighter than the parent element). For line height: Set via `.line-height-*` classes, including default (`.line-height-base`, 1.5), compact (`.line-height-sm`), and loose (`.line-height-lg`). A comprehensive example demonstrates the combined use of classes, such as centered bold headings and responsive subheadings. In summary, mastering these three types of styles (alignment, weight, line height) through their respective class names allows for quick
Read MoreBootstrap 5 Float Utilities: Left/Right Floating and Clear Floats Methods
The floating utility classes in Bootstrap 5 simplify the implementation of element floating in web layout, allowing elements to break out of the document flow without complex CSS to achieve left/right floating and content wrapping. The basic classes are `float-start` (left float) and `float-end` (right float), which make elements align left or right respectively, with subsequent content automatically wrapping around them. When using floats, the parent container may experience height collapse due to child elements' floating. The `clearfix` class is required to clear floats and restore the parent container's normal height. Additionally, responsive floating is supported with the format `float-{breakpoint}-{direction}` (e.g., `float-sm-start` means left-floating on small screens), where breakpoints include `sm`, `md`, `lg`, etc. Cautions: Floated elements breaking out of the document flow may affect layout; avoid overuse, and combine with the grid system for complex layouts. The parent container must be paired with `clearfix` to prevent height collapse. Through these utility classes, beginners can quickly achieve flexible typography, such as effects of text-image mixing.
Read MoreBootstrap 5 Spacing Utilities: Quick Tips for Adjusting Element Distances
The spacing utility classes in Bootstrap 5 enable quick control of element padding and margin through predefined class names, eliminating the need for complex CSS. Their naming convention is `{property}-{sides}-{size}`: `m` denotes margin, `p` denotes padding; directions include t/b/s/e/x/y/all (top/bottom/start/end/horizontal/vertical/all); sizes 0-5 correspond to spacing from 0rem to 3rem (with larger values indicating greater spacing). In practice, basic usage examples include `p-3` (default padding), `pt-4` (top padding); multi-directional usage includes `mx-3` (horizontal margin), `py-5` (vertical padding); and all-directional spacing uses `p-4` instead of specifying four individual directional classes. For responsiveness, breakpoint prefixes (sm/md, etc.) can be added, such as `mt-sm-3` (top margin at small screen sizes). It is important to distinguish between margin (external distance affecting element position) and padding (internal distance expanding the element itself). Multiple class names can be combined, and the default `$spacer` variable supports custom spacing. By mastering these rules, layout adjustments can be efficiently achieved through class name combinations, enhancing development efficiency.
Read More