Flask REST API Project Initialization and Environment Configuration
Establish a root folder named flask_service. Inside this, organize the resources as follows:
- app_core: Main application package containing entry points.
- modules_v1: Package housing API versioning (specifically version 1.0).
- settings: Contains configuration logic separated from logic.
- output/logs: Directory reserved for runtime log files.
- cli_runner.py: Script responsible for launching the development server.
Component Overview
- cli_runner.py: Handles application bootstrapping and database lifecycle management.
- app_core/: Initializes core Flask objects including the app instance, database connections, security mechanisms (CSRF), and caching layers.
- modules_v1/: Houses the business logic endpoints.
- settings.py: Centralizes all enviroment parameters passed to the application factory.
- output/logs: Captures execution traces and error reports.
Core Implementation Strategy
Application Factory and Extensions
In the main package entry, we establish global extension instances before applying them to the app context. This utilizes a deferred loading strategy.
# coding:utf-8
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_wtf.csrf import CSRFProtect
from flask_session import Session
from settings import settings_registry
import redis
import logging
from logging.handlers import RotatingFileHandler
# Initialize extensions globally for lazy binding later
sqlalchemy_db = SQLAlchemy()
csrf_protector = CSRFProtect()
redis_connection = None
# Configure default logging level
logging.basicConfig(level=logging.WARNING)
# Set up rotating file handler for persistent logging
log_handler = RotatingFileHandler(filename="output/logs/trace.log", maxBytes=104857600, backupCount=10)
log_formatter = logging.Formatter(fmt='%(levelname)s %(filename)s:%(lineno)d %(message)s')
log_handler.setFormatter(log_formatter)
logging.getLogger().addHandler(log_handler)
def create_app(config_identifier):
app = Flask(__name__)
env_config = settings_registry[config_identifier]
app.config.from_object(env_config)
sqlalchemy_db.init_app(app)
csrf_protector.init_app(app)
Session(app)
global redis_connection
redis_connection = redis.StrictRedis(
host=env_config.REDIS_HOST,
port=env_config.REDIS_PORT,
db=env_config.DB_NUM
)
from modules_v1 import module_routes
app.register_blueprint(module_routes, url_prefix='/api/v1_0')
return app
Configuration Management
Define base and derived configurations to support different environments.
# coding:utf-8
import redis
class BaseConfig:
# Database Connection String
SQLALCHEMY_DATABASE_URI = "mysql+pymysql://admin:secure_password@localhost/project_db"
SQLALCHEMY_TRACK_MODIFICATIONS = True
# Security Key for Signing Cookies
SECRET_KEY = 'xYz9AbCdEfGhIjKlMnOpQrStUvWxYz1234567890!'
# Redis Integration Settings
REDIS_HOST = '127.0.0.1'
REDIS_PORT = 6379
DB_NUM = 1
# Session Lifecycle Configuration
PERMANENT_SESSION_LIFETIME = 86400
SESSION_TYPE = 'redis'
SESSION_USE_SIGNER = True
SESSION_REDIS = redis.StrictRedis(host=REDIS_HOST, port=REDIS_PORT)
class DevelopmentEnv(BaseConfig):
DEBUG = True
class ProductionEnv(BaseConfig):
pass
settings_registry = {
'dev': DevelopmentEnv,
'prod': ProductionEnv
}
Blueprint Definition
Register the API routes under a distinct namespace.
# coding:utf-8
from flask import Blueprint
module_routes = Blueprint('api_v1', __name__)
from routes.home import status_endpoint
Route Implementation
Implement a sample endpoint to verify integration between the router and database.
# coding:utf-8
from . import module_routes
from app_core import sqlalchemy_db
import logging
@module_routes.route('/health_check')
def status_endpoint():
try:
# Simulate a potential error for logging verification
result = 1 / 0
except Exception as e:
logging.error(str(e))
return 'Service Status: Operational DB connection verified'
Execution and Testing
Launch the server via the command line tool.
python cli_runner.py runserver
Verify accessibility via browser or curl:
http://127.0.0.1:5000/api/v1_0/health_check
Any runtime exceptions encountered during requests will be persisted to the designated log file in the output/logs directory.