FastAPI Asynchronous Tasks: Handling Time-Consuming Operations with BackgroundTasks
In web development, directly handling time-consuming operations (such as sending emails and generating reports) in API endpoints will block user waiting and affect experience. FastAPI's `BackgroundTasks` can execute such tasks asynchronously after the request response, avoiding blocking. `BackgroundTasks` is a class provided by FastAPI that automatically executes background tasks after the request processing is completed without blocking the interface response. It only requires three steps: import `BackgroundTasks`, declare the `bg` parameter in the route function, and register the time-consuming function and parameters through `bg.add_task()`. Example: Simulating the generation of a large file (taking 5 seconds). After the user submits the request, the interface immediately returns success, and the file generation is completed asynchronously in the background. Key points: Tasks are executed after the response, support positional/keyword parameters and sequential execution, suitable for I/O-intensive tasks (such as file reading/writing), not suitable for CPU-intensive tasks; exceptions are not caught, and task failures need to be handled by oneself; unexecuted tasks will be lost when the application restarts or crashes, so it is not suitable for persistent tasks. `BackgroundTasks` is lightweight and easy to use, improving user experience through quick responses, and is suitable for non-critical path time-consuming operations.
Read MoreNginx Dynamic and Static Content Separation: Speed Up and Stabilize Your Website Loading
Nginx static-dynamic separation separates static resources (images, CSS, JS, etc.) from dynamic resources (PHP, APIs, etc.). Nginx focuses on quickly returning static resources, while backend servers handle dynamic requests. This approach can improve page loading speed, reduce backend pressure, and enhance scalability (static resources can be deployed on CDNs, and dynamic requests can use load balancing). The core of implementation is distinguishing requests using Nginx's `location` directive: static resources (e.g., `.jpg`, `.js`) are directly returned using the `root` directive with specified paths; dynamic requests (e.g., `.php`) are forwarded to the backend (e.g., PHP-FPM) via `fastcgi_pass` or similar. In practice, within the `server` block of the Nginx configuration file, use `~*` to match static suffixes and set paths, and `~` to match dynamic requests and forward them to the backend. After verification, restart Nginx to apply the changes and optimize website performance.
Read More