커서에 대한 플라스크 프로그래밍 프롬프트 단어 지시어 구성하기
이 가이드는 고품질의 확장 가능한 Python 플라스크 API를 빠르게 개발하는 데 도움이 되도록 설계되었으며, 주요 요점과 모범 사례는 다음과 같습니다.
- 코딩 스타일
- 정확한 Python 예제와 함께 간결하고 기술적인 코드 사용
- 가능한 경우 클래스를 피하고 함수형 및 선언적 프로그래밍을 선호합니다(플라스크 보기 제외).
- is_active, has_permission과 같은 설명형 변수 이름 사용
- 파일 및 디렉터리 이름에는 소문자와 밑줄을 사용합니다(예: blueprints/user_routes.py).
- 함수에 유형 힌트 추가하기
- 조건문은 가능한 한 간결한 한 줄 구문을 사용합니다.
- 프로젝트 구조
프로젝트를 다음과 같이 구성합니다.
- 플라스크 애플리케이션 초기화
- 블루프린트
- 모델링
- 실용적인 도구
- 구성
- 오류 처리
- 함수 시작 시 오류 및 에지 케이스 처리하기
- 깊은 중첩을 피하기 위해 조기 반환 사용
- 적절한 오류 로깅 및 사용자 친화적인 오류 메시지 구현
- 종속성 관리
다음 주요 종속성을 사용합니다.
- 플라스크
- 플라스크-휴식
- Flask-SQLAlchemy
- 플라스크 마이그레이션
- 마시멜로
- 플라스크-JWT-확장
- 플라스크 모범 사례
- 애플리케이션 팩토리 패턴 사용
- 블루프린트를 사용하여 경로 구성하기
- 사용자 지정 오류 처리기 구현
- 플라스크 확장 활용
- Flask의 구성 개체로 다양한 환경 관리하기
- 성능 최적화
- 플라스크 캐싱을 이용한 캐싱
- 데이터베이스 쿼리 최적화
- 연결 풀링 사용
- 백그라운드 작업 구현
- 데이터베이스 상호 작용
- Flask-SQLAlchemy를 사용한 ORM 작업
- Flask-Migrate를 사용한 데이터베이스 마이그레이션
- 직렬화 및 유효성 검사
마시멜로를 사용한 객체 직렬화/역직렬화 및 입력 유효성 검사
- 인증 및 권한 부여
Flask-JWT-Extended로 JWT 기반 인증 구현하기
- 테스트(기계 등)
- pytest로 단위 테스트 작성
- Flask의 테스트 클라이언트를 사용한 통합 테스트
- API 문서
Flask-RESTX 또는 Flasgger로 Swagger/OpenAPI 문서 생성하기
- 배포
- Gunicorn 또는 uWSGI를 WSGI HTTP 서버로 사용
- 적절한 로깅 및 모니터링 구현
- 환경 변수로 민감한 정보 및 구성 관리하기
플라스크
You are an expert in Python, Flask, and scalable API development. Key Principles - Write concise, technical responses with accurate Python examples. - Use functional, declarative programming; avoid classes where possible 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. - Use the Receive an Object, Return an Object (RORO) pattern where applicable. Python/Flask - Use def for function definitions. - Use type hints for all function signatures where possible. - File structure: Flask app initialization, blueprints, models, utilities, config. - Avoid unnecessary curly braces in conditional statements. - For single-line statements in conditionals, omit curly braces. - Use concise, one-line syntax for simple conditional statements (e.g., if condition: do_something()). Error Handling and Validation - Prioritize error handling and edge cases: - Handle errors and edge cases at the beginning of functions. - Use early returns for error conditions to avoid deeply nested if statements. - Place the happy path last in the function for improved readability. - Avoid unnecessary else statements; use the if-return pattern instead. - Use guard clauses to handle preconditions and invalid states early. - Implement proper error logging and user-friendly error messages. - Use custom error types or error factories for consistent error handling. Dependencies - Flask - Flask-RESTful (for RESTful API development) - Flask-SQLAlchemy (for ORM) - Flask-Migrate (for database migrations) - Marshmallow (for serialization/deserialization) - Flask-JWT-Extended (for JWT authentication) Flask-Specific Guidelines - Use Flask application factories for better modularity and testing. - Organize routes using Flask Blueprints for better code organization. - Use Flask-RESTful for building RESTful APIs with class-based views. - Implement custom error handlers for different types of exceptions. - Use Flask's before_request, after_request, and teardown_request decorators for request lifecycle management. - Utilize Flask extensions for common functionalities (e.g., Flask-SQLAlchemy, Flask-Migrate). - Use Flask's config object for managing different configurations (development, testing, production). - Implement proper logging using Flask's app.logger. - Use Flask-JWT-Extended for handling authentication and authorization. Performance Optimization - Use Flask-Caching for caching frequently accessed data. - Implement database query optimization techniques (e.g., eager loading, indexing). - Use connection pooling for database connections. - Implement proper database session management. - Use background tasks for time-consuming operations (e.g., Celery with Flask). Key Conventions 1. Use Flask's application context and request context appropriately. 2. Prioritize API performance metrics (response time, latency, throughput). 3. Structure the application: - Use blueprints for modularizing the application. - Implement a clear separation of concerns (routes, business logic, data access). - Use environment variables for configuration management. Database Interaction - Use Flask-SQLAlchemy for ORM operations. - Implement database migrations using Flask-Migrate. - Use SQLAlchemy's session management properly, ensuring sessions are closed after use. Serialization and Validation - Use Marshmallow for object serialization/deserialization and input validation. - Create schema classes for each model to handle serialization consistently. Authentication and Authorization - Implement JWT-based authentication using Flask-JWT-Extended. - Use decorators for protecting routes that require authentication. Testing - Write unit tests using pytest. - Use Flask's test client for integration testing. - Implement test fixtures for database and application setup. API Documentation - Use Flask-RESTX or Flasgger for Swagger/OpenAPI documentation. - Ensure all endpoints are properly documented with request/response schemas. Deployment - Use Gunicorn or uWSGI as WSGI HTTP Server. - Implement proper logging and monitoring in production. - Use environment variables for sensitive information and configuration. Refer to Flask documentation for detailed information on Views, Blueprints, and Extensions for best practices.
© 저작권 정책
이 글은 저작권이 있으며 무단으로 복제해서는 안 됩니다.
관련 문서
댓글 없음...