No project description provided
Project description
Flask Dependency
Dependency injection is a powerful concept that allows you to manage and inject dependencies into your application
components. In Flask, we can create a simple dependency injection system inspired by FastAPI's Depends
.
Approach
-
Create a Dependency Class: We'll define a class called
Depends
that will handle our dependencies. This class will allow us to declare dependencies for specific route handlers. -
Decorator for Dependency Resolution: We'll create a decorator that inspects the function and resolves any dependencies when called. This decorator will be applied to our route handlers.
-
Dependency Functions: We'll define individual functions (similar to FastAPI's dependencies) that represent our dependencies. These functions will be called automatically when needed.
Sample Code
# app.py
from flask import Flask, Blueprint
from pydantic import BaseModel
from flask_dependency import BackgroundTask, Depends, route, FormModel
app = Flask(__name__)
blueprint = Blueprint("example_blueprint", __name__)
app.debug = True
def sample_task(duration):
import time
time.sleep(duration)
return f"Slept for {duration} seconds"
# Example Backgraund Task
@route(blueprint, "/backgraund_task", methods=["POST"], endpoint="route_test")
def route_test(background_task: BackgroundTask = Depends()):
background_task.run(sample_task, 1)
return {"message": "OK"}
class InputModelForm(FormModel):
id: int
name: str
class ResponseInputModelForm(BaseModel):
id: int
name: str
class Config:
orm_mode = True
# Example Form
@route(blueprint, "/example_form", methods=["POST"], endpoint="route_test", response_schema=ResponseInputModelForm)
def route_test(input_data: InputModelForm = Depends()):
return {"message": "success"}
app.register_blueprint(blueprint)
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Hashes for flask_dependency-0.1.0-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 195e642d11a7c6d9364f991b6ac0352348c226b9d0ffac0980805009b9e0c714 |
|
MD5 | 69d0d2f3fa440f7a54c1c42b57dfffab |
|
BLAKE2b-256 | c45a6682899504e8a281675ecaf061aceb237cfeafb1ff3a86fb5d8d3b3542ce |