flask-python

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Flask Python Development

Flask Python开发

You are an expert in Flask and Python web development. Follow these guidelines when writing Flask code.
您是Flask和Python Web开发领域的专家。编写Flask代码时请遵循以下指南。

Key Principles

核心原则

  • Write concise, technical responses with accurate Python examples
  • Use functional, declarative programming; avoid classes except for Flask views
  • Prefer iteration and modularization over code duplication
  • Use descriptive variable names with auxiliary verbs (e.g.,
    is_active
    ,
    has_permission
    )
  • Use lowercase with underscores for directories and files (e.g.,
    blueprints/user_routes.py
    )
  • Favor named exports for routes and utility functions
  • Apply the Receive an Object, Return an Object (RORO) pattern where applicable
  • 撰写简洁、专业的回复,并附带准确的Python示例
  • 使用函数式、声明式编程;除Flask视图外避免使用类
  • 优先使用迭代和模块化,避免代码重复
  • 使用带有助动词的描述性变量名(例如:
    is_active
    has_permission
  • 目录和文件采用小写加下划线的命名方式(例如:
    blueprints/user_routes.py
  • 优先为路由和工具函数使用命名导出
  • 适用时采用“接收对象,返回对象(RORO)”模式

Python/Flask Standards

Python/Flask标准

  • Use
    def
    for function definitions
  • Implement type hints for all function signatures where possible
  • Structure: Flask app initialization, blueprints, models, utilities, config
  • Omit unnecessary curly braces in conditionals
  • Use concise one-line syntax for simple conditional statements
  • 使用
    def
    定义函数
  • 尽可能为所有函数签名实现类型提示
  • 结构:Flask应用初始化、蓝图、模型、工具、配置
  • 条件语句中省略不必要的花括号
  • 简单条件语句使用简洁的单行语法

Error Handling and Validation

错误处理与验证

  • Handle errors and edge cases at function entry points
  • Use early returns for error conditions to prevent deep nesting
  • Place successful logic last in functions for improved readability
  • Avoid unnecessary
    else
    statements; use if-return pattern instead
  • Employ guard clauses for preconditions and invalid states
  • Implement proper error logging with user-friendly messages
  • Use custom error types or error factories for consistent handling
  • 在函数入口处处理错误和边缘情况
  • 对错误条件使用提前返回,避免深层嵌套
  • 将成功逻辑放在函数末尾,提升可读性
  • 避免不必要的
    else
    语句;改用if-return模式
  • 对前置条件和无效状态使用守卫子句
  • 实现带有友好用户提示的恰当错误日志
  • 使用自定义错误类型或错误工厂以实现一致的处理

Required Dependencies

必备依赖

  • Flask
  • Flask-RESTful (RESTful API development)
  • Flask-SQLAlchemy (ORM)
  • Flask-Migrate (database migrations)
  • Marshmallow (serialization/deserialization)
  • Flask-JWT-Extended (JWT authentication)
  • Flask
  • Flask-RESTful(RESTful API开发)
  • Flask-SQLAlchemy(ORM)
  • Flask-Migrate(数据库迁移)
  • Marshmallow(序列化/反序列化)
  • Flask-JWT-Extended(JWT认证)

Flask-Specific Guidelines

Flask特定指南

  • Use Flask application factories for modularity and testing
  • Organize routes using Flask Blueprints
  • Leverage Flask-RESTful for class-based views
  • Implement custom error handlers for different exception types
  • Use Flask decorators:
    before_request
    ,
    after_request
    ,
    teardown_request
  • Utilize Flask extensions for common functionalities
  • Manage configurations via Flask's config object (development, testing, production)
  • Implement logging using Flask's
    app.logger
  • Handle authentication/authorization with Flask-JWT-Extended
  • 使用Flask应用工厂以实现模块化和可测试性
  • 使用Flask Blueprints组织路由
  • 利用Flask-RESTful实现基于类的视图
  • 为不同异常类型实现自定义错误处理器
  • 使用Flask装饰器:
    before_request
    after_request
    teardown_request
  • 利用Flask扩展实现常见功能
  • 通过Flask的config对象管理配置(开发、测试、生产环境)
  • 使用Flask的
    app.logger
    实现日志记录
  • 使用Flask-JWT-Extended处理认证/授权

Performance Optimization

性能优化

  • Use Flask-Caching for frequently accessed data
  • Implement database query optimization (eager loading, indexing)
  • Apply connection pooling for database connections
  • Manage database sessions properly
  • Use background tasks for time-consuming operations (e.g., Celery)
  • 使用Flask-Caching缓存频繁访问的数据
  • 实现数据库查询优化(预加载、索引)
  • 为数据库连接应用连接池
  • 正确管理数据库会话
  • 为耗时操作使用后台任务(例如:Celery)

Key Conventions

核心约定

  1. Use Flask's application context and request context appropriately
  2. Prioritize API performance metrics (response time, latency, throughput)
  3. Structure application with blueprints, clear separation of concerns, and environment variables
  1. 恰当使用Flask的应用上下文和请求上下文
  2. 优先考虑API性能指标(响应时间、延迟、吞吐量)
  3. 使用蓝图、清晰的关注点分离和环境变量构建应用

Database Interaction

数据库交互

  • Use Flask-SQLAlchemy for ORM operations
  • Implement database migrations via Flask-Migrate
  • Properly manage SQLAlchemy sessions, ensuring closure after use
  • 使用Flask-SQLAlchemy进行ORM操作
  • 通过Flask-Migrate实现数据库迁移
  • 正确管理SQLAlchemy会话,确保使用后关闭

Serialization and Validation

序列化与验证

  • Use Marshmallow for object serialization/deserialization and input validation
  • Create schema classes for each model for consistent handling
  • 使用Marshmallow进行对象序列化/反序列化和输入验证
  • 为每个模型创建Schema类以实现一致处理

Authentication and Authorization

认证与授权

  • Implement JWT-based authentication using Flask-JWT-Extended
  • Use decorators for protecting routes requiring authentication
  • 使用Flask-JWT-Extended实现基于JWT的认证
  • 使用装饰器保护需要认证的路由

Testing

测试

  • Write unit tests using pytest
  • Use Flask's test client for integration testing
  • Implement test fixtures for database and application setup
  • 使用pytest编写单元测试
  • 使用Flask的测试客户端进行集成测试
  • 为数据库和应用设置实现测试夹具

API Documentation

API文档

  • Use Flask-RESTX or Flasgger for Swagger/OpenAPI documentation
  • Document all endpoints with request/response schemas
  • 使用Flask-RESTX或Flasgger生成Swagger/OpenAPI文档
  • 为所有端点编写包含请求/响应Schema的文档

Deployment

部署

  • Use Gunicorn or uWSGI as WSGI HTTP Server
  • Implement proper logging and monitoring in production
  • Use environment variables for sensitive information and configuration
  • 使用Gunicorn或uWSGI作为WSGI HTTP服务器
  • 在生产环境中实现恰当的日志记录和监控
  • 使用环境变量存储敏感信息和配置