Instruction file imported from richardnguyen99/video-pipeline (
.github/instructions/backend/python.instructions.md). Copyright stays with the author.
Tech stack
python3.14as the core programming language.fastapias the web framework for building APIs and server-side applications.sqlmodelas the ORM for database interactions and model definitions.postgresqlas the core database for the application.redisas the caching layer between application and database to improve performance and reduce database load.celeryas the task queue for handling asynchronous tasks and background jobs.rabbitmqas the message broker for Celery to facilitate communication between the application and the task queue.alembicas the database migration tool for managing schema changes and versioning.pytestas the testing framework for writing and executing unit tests, integration tests, and end-to-end tests.pytest-asyncioas the plugin for pytest to support testing of asynchronous code and coroutines.blackas the code formatter.isortas the import sorting tool.pylintas the static code analysis tool.pre-commitas the tool for managing and maintaining pre-commit hooks to enforce code quality and consistency.
Coding conventions
- ALWAYS use virtual environments for managing project dependencies.
- Use
requirements.txtto manage project dependencies. - Follow PEP 8 guidelines for code style and formatting.
- Write docstrings for all public modules, classes, and functions following the PEP 257 conventions.
- Use type hints for function arguments and return types.
- Prefer using f-strings for string formatting.
- Keep lines under 79 characters to maintain code readability.
- Use blank lines to separate top-level function and class definitions.
- Avoid using mutable default arguments in function definitions.
- Use list comprehensions and generator expressions for concise and readable code when appropriate.
- Prefer using
withstatements for resource management to ensure proper cleanup. - Avoid using bare
exceptclauses; catch specific exceptions to handle errors appropriately. - Use
async/awaitsyntax for asynchronous programming to write non-blocking code. - Use
isortto automatically sort imports for better readability and maintainability. - Use
blackto automatically format code according to PEP 8 standards. - Use
pylintto perform static code analysis and enforce coding standards. - Use 4 spaces for indentation instead of tabs.
- Use double quotes for strings.
- Always add a trailing comma after the last element in a list, tuple, or dictionary.
- Always add a trailing comma after the last argument in a function call.
- Always add a trailing comma after the last argument in an object instantiation.
- Add an empty line after docstrings in functions and classes
- Add an empty line before return statements in functions, except for one-liner functions.
- Add empty lines around
if,for, andwhileblocks to improve code readability, except when the block is either the first or last statement in a function. - HTTP status codes must not be used with explicit number code. Either they are used from libraries or the app components define them as enum.
- Unused parameters that are required for the function's signature must have prefix _ to avoid linting errors/warnings.
- Do not disable/suppress/ignore a test/linting/format error, unless prompts specify so.
- Invalid input yields a 400 HTTP status error code.
- Missing authentication / authorization information yields a 401 HTTP status error code.
- Requests with not-supported Origin and Referer headers yields a 403 HTTP status error code.
- Invalid / Not Found URLs yields a 404 HTTP status error code.
FAST API
- Use
FastAPIfor building APIs. - Follow the official FastAPI documentation for best practices and recommended patterns.
- Use Pydantic models for request validation and response serialization.
- Use asynchronous endpoints whenever possible to improve performance and scalability.
- Each leaf route should be a separate file.
- Non-leaf routes should be a folder containing the relevant leaf route files. and should include an
__init__.pyfile to make it a proper Python package. - Use routers to organize and modularize your API endpoints.
- Use named status codes instead of numeric literals
Routing
- Define routes clearly and consistently.
- Use meaningful and descriptive route names.
- Group related routes together using routers.
- Keep route handlers focused on handling HTTP requests and responses, delegating business logic to separate service layers.
- The same route can have multiple HTTP methods (GET, POST, PUT, DELETE) defined separately in the same route handler file.
ORM and Models
- Use PostgresQL as the core database for the application.
- Use SQLModel as the core ORM for defining database models and interacting with the database.
- Define each model in a separate file to maintain modularity and readability.
- Use relationships to define associations between models where appropriate.
- Avoid raw SQL queries; prefer using the ORM's query capabilities for database interactions.
- Use migrations to manage database schema changes consistently.
- Support type hints for model fields
- Declare static methods using the
@staticmethoddecorator inside model classes for model-related utility functions such asUser.get_by_id(). - Use class methods with the
@classmethoddecorator for operations that involve the class itself rather than an instance, such asUser.create(). - Use the
__repr__method to provide a meaningful string representation of model instances for debugging and logging purposes. - Prefer
sqlmodel's methods, functions, and types to native Python likes. For example, usesqlmodel.sql.sqltypes.AutoStringinstead ofstrfor string fields in models to leverage the ORM's capabilities and ensure compatibility with the database. - Use asynchronous database sessions and methods to work with the database in a non-blocking manner.
- Use
sqlmodel.ext.asyncio.session.AsyncSessionto type-hint the session parameter in model methods that interact with the database. - Use
asyncto declare asynchronous methods that work with async sessions andawaitto call asynchronous methods within those methods. - Add cascade delete to relationships where appropriate.
Testing
- Use
pytestas the testing framework for writing and executing unit tests. - Use
pytest-asyncioto support testing of asynchronous code and coroutines.
Unit Testing
- Enable test on commit using
pre-commithooks to ensure that tests are run before code is committed. - Use mock data and fixtures to isolate unit tests and avoid dependencies on external systems.
- Test each file in the
backend/app/servicesfolder, except the module init file. - Each return should be tested in separate cases.