FastAPI + SQLite: Quickly Build a Lightweight Database API Service
This article introduces the process of quickly building a "Student Information Management" database API service using FastAPI and SQLite. First, dependencies such as FastAPI, Uvicorn, and SQLAlchemy are installed via `pip`. SQLAlchemy's ORM is used to define student data models (including id, name, and age fields) and session management, with Pydantic models for data validation. The core implementation includes CRUD operations (create, read single/all students, update, delete). FastAPI routes bind HTTP methods (POST/GET/PUT/DELETE) to generate student management API endpoints. The database configuration uses SQLite, an embedded database that requires no additional server, with data stored in the `test.db` file. After starting the service with Uvicorn, FastAPI automatically generates Swagger UI documentation for easy testing. This lightweight and easy-to-use solution supports asynchronous operations, making it suitable for small-to-medium projects. Future expansions include multi-table associations or migration to PostgreSQL/MySQL.
Read MoreDetailed Explanation of FastAPI Dependency Injection: Basic and Advanced Usage of Depends
Dependency Injection (DI) core is to inject dependencies (such as database connections) into functions automatically by the system, rather than having the functions acquire them themselves, thereby enhancing code reusability and decoupling. FastAPI implements this through `Depends`, which involves two steps: defining a dependency function (to produce a dependency object, e.g., simulating a database connection), and declaring the dependency in the path function using `Depends(dependency_function)`, where FastAPI automatically calls and injects the result. Dependency functions can accept path/query parameters, such as querying a user based on a `user_id`. Advanced usages include: nested dependencies (dependencies on other dependencies), caching dependencies with `lru_cache` (singleton), asynchronous dependencies (adapting to asynchronous path functions), and combining with Pydantic for parameter validation. Core advantages: code reusability, decoupling (path functions only focus on business logic), testability (dependencies can be replaced with mocks), and extensibility (adding new dependencies only requires modifying the dependency function). Mastering `Depends` enables a clearer and more robust API structure.
Read MoreEnhancing FastAPI Documentation: Tips for Customizing Swagger UI
Swagger UI is the default API documentation tool for FastAPI, enabling interface visualization and testing. Customization can enhance its professionalism. For basic modifications, set parameters like title and description when creating the FastAPI instance to display personalized information on the `/docs` page. There are two styles customization methods: injecting CSS via middleware to quickly modify the background, navigation bar, etc.; or using static files to inject complex styles (e.g., logos). Sensitive information can be hidden by excluding fields with `Pydantic` model `Field(exclude=True)` or the interface `response_model_exclude`. Advanced techniques include layout adjustment, adding descriptions, and replacing buttons. The core implementation relies on basic information, CSS, and parameter control. Beginners can start with simple modifications while noting version compatibility.
Read MoreFlask Error Handling: Custom Exceptions and Logging
Error handling in Flask is crucial for application stability and user experience. This article introduces the core methods of error handling in Flask: ### 1. Default Error Handling Using the `@app.errorhandler(code_or_exception)` decorator, you can customize responses for status codes such as 404 and 500. For example, return a friendly message like "The page is lost". In production environments, debug mode should be disabled to prevent exposing stack traces. ### 2. Custom Exceptions Define exception classes (e.g., `UserNotFoundError`) to encapsulate business errors (e.g., user not found). Use `raise` to proactively throw these exceptions and `@app.errorhandler` to catch them, enabling modular error handling. ### 3. Logging Leverage Python’s `logging` module to configure file logging (with size limits and backups). Differentiate error importance using `INFO`/`ERROR` levels, and record critical error information in production for troubleshooting. ### Conclusion Flask error handling should combine friendly prompts (to avoid crashes), precise error location (via logging), and modular design (custom exceptions). Key techniques include using `errorhandler`, encapsulating business exceptions, configuring file logging, and distinguishing log levels.
Read MoreIntroduction to User Authentication: Implementing Simple Login and Permission Control with Flask Session
This article introduces implementing user authentication and permission control for web applications using the Flask framework and Session mechanism, suitable for beginners. It first clarifies the concepts of user authentication (verifying identity) and permission control (judging access rights), emphasizing that Session is used to store user status, and Flask's `session` object supports direct manipulation. For environment preparation, install Flask, create an application, and configure `secret_key` to encrypt sessions. To implement the login function: collect username and password through a form, verify them (simulating a user database), set `session['username']`, and redirect to the personal center upon successful login. For permission control, use the `@login_required` decorator to check the Session and protect pages requiring login (e.g., the personal center). Logout clears the user status by `session.pop('username')`. Core content includes: Session basics, login verification, permission decorators, and logout functionality. The article summarizes the learned knowledge points and expands on directions such as database connection, password encryption, and multi-role permissions. Flask Session provides a simple and secure solution that can be gradually used to build complex applications.
Read More