Saravanan666/pypi-org huggingface dataset:
Package: fastapi-route-logger-middleware
fastapi-route-loggerBasic middleware to log requests made to routes in FastAPI applications.Installationpip install fastapi-route-logger-middlewareUsageThe component is FastAPI middleware.app.add_middleware(RouteLoggerMiddleware)Additional arguments can be provided, when needed:logger- The Logger instance to use. Defaults to the default logger (logging.getLogger(__name__)).skip_routes- A list of strings that represent the start of routes that should not be logged. Default is an empty
list. This is a "begins with" type match so an entry of"/health"will block the routes/health/checkand/healthcheck.skip_regexes- A list of regex strings that will be matched against routes that should not be logged. Default is an empty
list. This uses compiled regexes and matches against the entire path. An entry of".*/health"will not log the routes/healthand/api/1.0/health.Thesample-sitein the code repository
contains a sample FastAPI site with this middleware integrated. Check the includedreadmefor more information.
Package: fastapi-router
FastAPI-RouterEfficient Backend, Agile Development.installation from Test PyPIpipinstall-ihttps://test.pypi.org/simple/--extra-index-urlhttps://pypi.python.org/simple/fastapi-routerFastAPI-Router is a plugin for applications built withFastAPIthat enables the development of backend applications with a workflow similar to Next.js. This means you can create efficient and modern backend applications with FastAPI-Router, taking advantage of its capabilities in a manner akin to the workflow in Next.js.Example:fromfastapiimportFastAPIfromfastapi_routerimportinit_main_route# Init FastAPI applicationapp=FastAPI()# Init fastapi-routeinit_main_route(app)API Folder organizationIn the FastAPI-Router library, the organization of files within the directory mirrors the route structure, akin to the approach inNext.js.Each nested folder signifies a route segment, aligning with a corresponding segment in the URL path.However, the definition of a route doesn't become publicly accessible until a route.py file is added to the respective route segment. This file, acting as the handler, determines the behavior and functionality associated with the specific endpoint. FastAPI-Router leverages this file structure to seamlessly generate and map routes, providing an intuitive and efficient way to structure and manage API endpoints.route.pyA route file enables the creation of customized request handlers for a specified route. It supports the following HTTP methods:GET,POST,PUT,PATCH,DELETE,HEAD,TRACEandOPTIONS.defGET():...defPOST():...defPUT():...defPATH():...defDELETE():...defHEAD():...defTRACE():...defOPTIONS():...By default, fastapi-router expects a folder named'api'to exist. In case you need to change the name or have a project where you want to implement fastapi-router without that specific name, you can modify this by passingpathDiras an argument to theinit_main_routefunction.Example:# For root folderinit_main_route(app,pathDir='app')init_main_route(app2,pathDir='app/routes')If the name'route'doesn't suit you and you want to change it to another name to define the methods of the routes, you can passnameRouteFileas an argument to theinit_main_routefunction.Example:# Changing the route file nameinit_main_route(app,nameRouteFile='methods')
Package: fastapi-router-controller
fastapi-router-controllerA FastAPI utility to allow Controller Class usageInstallation:install the packagepip install fastapi-router-controllerHow to useHere we see a Fastapi CBV (class based view) application
with class wide Basic Auth dependencies.importuvicornfrompydanticimportBaseModelfromfastapi_router_controllerimportControllerfromfastapiimportAPIRouter,Depends,FastAPI,HTTPException,statusfromfastapi.securityimportHTTPBasic,HTTPBasicCredentialsrouter=APIRouter()controller=Controller(router)security=HTTPBasic()defverify_auth(credentials:HTTPBasicCredentials=Depends(security)):correct_username=credentials.username=="john"correct_password=credentials.password=="silver"ifnot(correct_usernameandcorrect_password):raiseHTTPException(status_code=status.HTTP_401_UNAUTHORIZED,detail="Incorrect auth",headers={"WWW-Authenticate":"Basic"},)returncredentials.usernameclassFoo(BaseModel):bar:str="wow"asyncdefamazing_fn():returnFoo(bar="amazing_variable")@controller.resource()classExampleController:# add class wide dependencies e.g. authdependencies=[Depends(verify_auth)]# you can define in the Controller init some FastApi Dependency and them are automatically loaded in controller methodsdef__init__(self,x:Foo=Depends(amazing_fn)):self.x=x@controller.route.get("/some_api",summary="A sample description",response_model=Foo)defsample_api(self):print(self.x.bar)# -> amazing_variablereturnself.x# Load the controller to the main FastAPI appapp=FastAPI(title="A sample application using fastapi_router_controller",version="0.1.0")app.include_router(ExampleController.router())uvicorn.run(app,host="0.0.0.0",port=9090)ScreenshotAll you expect from FastapiAlso the login dialogFor some Example use-cases visit the example folder
Package: fastapi-routesmanager
Routes Manager for FastAPIManipulate requests beforeFastAPIprocesses them (even before middlewares), and responses once finished.Installation$pipinstallfastapi-routesmanagerExampleUsing exampleHeadersLoggerfrom this package.fromtypingimportUnionfromfastapiimportFastAPIfromfastapi_routesmanagerimportHeadersLogger,RouteManagersRegistry,ManagedAPIRouterimportlogginglogging.basicConfig(level=logging.DEBUG)# Needed to get DEBUG outputRouteManagersRegistry.register_route_manager(HeadersLogger)# Register managerapp=FastAPI()router=ManagedAPIRouter()@router.get("/")# Use router instead of appdefread_root():return{"Hello":"World"}@router.get("/items/{item_id}")defread_item(item_id:int,q:Union[str,None]=None):return{"item_id":item_id,"q":q}app.include_router(router)# Include the router to the appOr you can register multiple managers at onceRouteManagersRegistry.register_route_managers([HeadersLogger,ExceptionLogger])Run it$uvicornmain:app--reloadCheck itBrowse tohttp://127.0.0.1:8000and check the server console.
You should see something like this showing the headers#DEBUG:headers_logger:Requestsheaders:Headers({'host':'localhost:8000','user-agent':'Mozilla Firefox','accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8','accept-language':'es-AR,es;q=0.8,en-US;q=0.5,en;q=0.3','accept-encoding':'gzip','dnt':'1','connection':'keep-alive','upgrade-insecure-requests':'1','sec-fetch-dest':'document','sec-fetch-mode':'navigate','sec-fetch-site':'none'})#DEBUG:headers_logger:Responseheaders:MutableHeaders({'content-length':'17','content-type':'application/json'})#INFO:127.0.0.1:49370-"GET /1 HTTP/1.1"200OKCreating custom ManagerIn order to create a custom manager you need to extendRouteManagerand declare anasync def run(...)method.Within this method you can access the request, execute it and get the response.fromfastapi_routesmanagerimportRouteManagerfromstarlette.requestsimportRequestfromstarlette.responsesimportResponsefromtypingimportCallable,List,Type,OptionalclassCustomManager(RouteManager):asyncdefrun(self,request:Request,call_next:Callable,remaining_managers:List[Type[RouteManager]],)->Optional[Response]:# This will run the request through FastAPIresponse:Response=awaitcall_next(request,remaining_managers)returnresponseIn theremaining_managerslist you will find all remaining managers to be run. You can modify this list to add or remove managers dynamically.
Package: fastapi-rowsecurity
FastAPI Row Security 🚣‍♂️Row-Level Security (RLS) in SQLAlchemy for PostgreSQL withRow Security Policies:Restrict access to specific rows 🔒 minimizing unauthorized data exposure.Perfect for Scalability and Multi-Tenancy: keep the data playground organized 🏢, ensuring each tenant plays in their own sandbox.WarningUnderstand that thedatabase superuserbypasses all permission checks, except the right to log in. This is a dangerous privilege and should not be used in combination with RLS.InstallationUse pip to install from PyPI:pip install fastapi-rowsecurityBasic UsageIn your SQLAlchemy model, create aclassmethodnamed__rls_policies__that returns a list ofPermissiveorRestrictivepolicies:fromfastapi_rowsecurityimportPermissive,set_rls_policiesfromfastapi_rowsecurity.principalsimportAuthenticated,UserOwnerBase=declarative_base()set_rls_policies(Base)# <- create all policiesclassItem(Base):__tablename__="items"id=Column(Integer,primary_key=True)title=Column(String,index=True)owner_id=Column(Integer,ForeignKey("users.id"))owner=relationship("User",back_populates="items")@classmethoddef__rls_policies__(cls):return[Permissive(principal=Authenticated,policy="SELECT"),Permissive(principal=UserOwner,policy=["INSERT","UPDATE","DELETE"]),]The above implies that any authenticated user can read all items; but can only insert, update or delete owned items.principal: any Boolean expression as a string;policy: any ofALL/SELECT/INSERT/UPDATE/DELETE.Next, attach thecurrent_user_id(or otherruntime parametersthat you need) to the user session:# ... def get_session() -> Session:session.execute(text(f"SET app.current_user_id ={current_user_id}"))Find a simple example in the.Backlog first releaseChange policies when model changes (prio!!)Documentationthen ...Support for AlembicHow to deal withBYPASSRLSsuch as table owners?When item is tried to delete, no error is raised?Python 3.11Final noteAt the moment this module is work-in-progress and therefore experimental. All feedback and ideas are 100% welcome! So feel free to contribute or reach out to me!
Package: fastapi-sa
fastapi-safastapi-sa provides a simple integration between FastAPI and SQLAlchemy in your application.
you can use decorators or middleware to transaction management.Installinginstall and update using pip:pipinstallfastapi-saExamplesCreate models for examples,models.pyfrompydanticimportBaseModelfromsqlalchemyimportColumn,Integer,Stringfromsqlalchemy.ormimportdeclarative_baseBase=declarative_base()classUser(Base):"""UserModel"""__tablename__='user'id=Column(Integer,primary_key=True)name=Column(String(255))age=Column(Integer)classUserSchema(BaseModel):"""user schema"""id:intname:strage:intclassConfig:"""config"""orm_mode=TrueDatabase migrations for examplescode for create tables, also you can use database migrations.fromsqlalchemyimportcreate_enginefrommodelsimportBaseengine=create_engine('sqlite+aiosqlite:////tmp/test.db')Base.metadata.create_all(engine)DB init for examplesfromfastapi_sa.databaseimportdbdb.init(url='sqlite+aiosqlite:////tmp/test.db')Usage 1: fastapi middlewarefromfastapiimportFastAPIfromsqlalchemyimportselectfromfastapi_sa.databaseimportdbfromfastapi_sa.middlewareimportDBSessionMiddlewarefromtests.example.dbimportUser,UserSchemaapp=FastAPI()app.add_middleware(DBSessionMiddleware)@app.get('/users')asyncdefget_users():"""get all users"""result=awaitdb.session.scalars(select(User))objs=[UserSchema.from_orm(i)foriinresult.all()]returnobjsUsage 2: other asynchronous database operationsfromsqlalchemyimportselectfromfastapi_sa.databaseimportdb,session_ctxfromtests.example.dbimportUser,UserSchema@session_ctxasyncdefget_users():"""get users"""results=awaitdb.session.scalars(select(User))objs=[UserSchema.from_orm(i)foriinresults.all()]returnobjsUsage 3: with fixtures in pytestimportpytestfromfastapi_sa.databaseimportdb@pytest.fixture()defdb_session_ctx():"""db session context"""token=db.set_session_ctx()yielddb.reset_session_ctx(token)@pytest.fixture()asyncdefsession(db_session_ctx):"""session fixture"""asyncwithdb.session.begin():yielddb.sessionIf you initialize data in fixture, please usefromfastapi_sa.databaseimportdbfrommodelsimportUserasyncwithdb():users=User(name='aoo',age=12)db.session.add(users)awaitdb.session.flush()if you test class methods, please useimportpytestfromsqlalchemyimportfunc,selectfrommodelsimportUser,UserSchemafromfastapi_sa.databaseimportdbclassUserRepository:"""user repository"""@propertydefmodel(self):"""model"""returnUserasyncdefget_all(self):"""get all"""result=awaitdb.session.scalars(select(self.model))objs=[UserSchema.from_orm(i)foriinresult.all()]returnobjs# the test case is as follows@pytest.fixture()defrepo():"""repo"""returnUserRepository()@pytest.mark.asyncioasyncdeftest_get_all(session,init_user,repo):"""test get all"""objs=awaitrepo.get_all()length=awaitsession.scalar(select(func.count()).select_from(User))assertlen(objs)==lengthSimilar designFastAPI-SQLAlchemyBased onFastAPISQLAlchemyDevelopYou may need to read thedevelop documentto use SRC Layout in your IDE.
Package: fastapi-sa-orm-filter
FastAPI SQLAlchemy FilterPackage that helps to implement easy objects filtering and sorting for applications
build on FastAPI and SQLAlchemy.
For using you just need to define your custom filter with filtered fields and applied operators.
Supported operators, datatypes and example of work you can find below.Installationpipinstallfastapi-sa-orm-filterCompatibilityv 0.2.0Python: >= 3.8Fastapi: >= 0.100Pydantic: >= 2.0.0SQLAlchemy: >= 1.4.36, < 2.1.0v 0.1.5Python: >= 3.8Fastapi: <= 0.100Pydantic: < 2.0.0SQLAlchemy: == 1.4QuickstartfromfastapiimportFastAPI
fromfastapi.paramsimportQuery
fromfastapi_sa_orm_filter.mainimportFilterCore
fromfastapi_sa_orm_filter.operatorsimportOperatorsasops

fromdb.baseimportget_session
fromdb.modelsimportMyModelapp=FastAPI()# Define fields and operators for filtermy_objects_filter={'my_model_field_name':[ops.eq,ops.in_],'my_model_field_name':[ops.between,ops.eq,ops.gt,ops.lt,ops.in_],'my_model_field_name':[ops.like,ops.startswith,ops.contains,ops.in_],'my_model_field_name':[ops.between,ops.not_eq,ops.gte,ops.lte]}@app.get("/")asyncdefget_filtered_objects(filter_query:str=Query(default=''),db:AsyncSession=Depends(get_session))->List[MyModel]:my_filter=FilterCore(MyModel,my_objects_filter)query=my_filter.get_query(filter_query)res=awaitdb.execute(query)returnres.scalars().all()Example of work# Input query string'''salary_from__in_=60,70,80&created_at__between=2023-05-01,2023-05-05|category__eq=Medicine&order_by=-id,category'''# Returned SQLAlchemy orm query exact as:select(model).where(or_(and_(model.salary_from.in_(60,70,80),model.created_at.between(2023-05-01,2023-05-05)),model.category=='Medicine').order_by(model.id.desc(),model.category.asc())Supported query string formatfield_name__eq=valuefield_name__in_=value1,value2field_name__eq=value&field_name__in_=value1,value2field_name__eq=value&field_name__in_=value1,value2&order_by=-field_nameModify query for custom selection# Create a class inherited from FilterCore and rewrite 'get_unordered_query' method.# 0.2.0 VersionclassCustomFilter(FilterCore):defget_select_query_part(self):custom_select=select(self.model.id,self.model.is_active,func.sum(self.model.salary_from).label("sum_salary_from"),self.model.category)returncustom_selectdefget_group_by_query_part(self):return[self.model.is_active]# 0.1.5 Version# Original method is:defget_unordered_query(self,conditions):unordered_query=select(self._model).filter(or_(*conditions))returnunordered_query# Rewrite example:classCustomFilter(FilterCore):defget_unordered_query(self,conditions):unordered_query=select(self.model.field_name1,self.model.field_name2,func.sum(self.model.field_name3).label("field_name3"),self.model.field_name4).filter(or_(*conditions)).group_by(self.model.field_name2)returnunordered_querySupported SQLAlchemy datatypes:DATETIMEDATEINTEGERFLOATTEXTVARCHAREnum(VARCHAR())BOOLEANAvailable filter operators:eqgtltgteltein_startswithendswithbetweenlikeilikecontainsicontainsnot_eqnot_innot_likenot_between
Package: fastapi-sa-orm-filter-2
FastAPI SQLAlchemy FilterPackage that helps to implement easy objects filtering and sorting for applications
build on FastAPI and SQLAlchemy.
For using you just need to define your custom filter with filtered fields and applied operators.
Supported operators, datatypes and example of work you can find below.Installationpipinstallfastapi-sa-orm-filter-2QuickstartfromfastapiimportFastAPI
fromfastapi.paramsimportQuery
fromfastapi_sa_orm_filter.mainimportFilterCore
fromfastapi_sa_orm_filter.operatorsimportOperatorsasops

fromdb.baseimportget_session
fromdb.modelsimportMyModelapp=FastAPI()# Define fields and operators for filtermy_objects_filter={'my_model_field_name':[ops.eq,ops.in_],'my_model_field_name':[ops.between,ops.eq,ops.gt,ops.lt,ops.in_],'my_model_field_name':[ops.like,ops.startswith,ops.contains,ops.in_],'my_model_field_name':[ops.between,ops.not_eq,ops.gte,ops.lte]}@app.get("/")asyncdefget_filtered_objects(filter_query:str=Query(default=''),db:AsyncSession=Depends(get_session))->List[MyModel]:my_filter=FilterCore(MyModel,my_objects_filter)query=my_filter.get_query(filter_query)res=awaitdb.execute(query)returnres.scalars().all()Example of work# Input query string'''salary_from__in_=60,70,80&created_at__between=2023-05-01,2023-05-05|category__eq=Medicine&order_by=-id,category'''# Returned SQLAlchemy orm query exact as:select(model).where(or_(and_(model.salary_from.in_(60,70,80),model.created_at.between(2023-05-01,2023-05-05)),model.category=='Medicine').order_by(model.id.desc(),model.category.asc())Supported query string formatfield_name__eq=valuefield_name__in_=value1,value2field_name__eq=value&field_name__in_=value1,value2field_name__eq=value&field_name__in_=value1,value2&order_by=-field_nameModify query for custom selection# Create a class inherited from FilterCore and rewrite 'get_unordered_query' method.# Original method is:defget_unordered_query(self,conditions):unordered_query=select(self._model).filter(or_(*conditions))returnunordered_query# Rewrite example:classCustomFilter(FilterCore):defget_unordered_query(self,conditions):unordered_query=select(self.model.field_name1,self.model.field_name2,func.sum(self.model.field_name3).label("field_name3"),self.model.field_name4).filter(or_(*conditions)).group_by(self.model.field_name2)returnunordered_querySupported SQLAlchemy datatypes:DATETIMEDATEINTEGERFLOATTEXTVARCHAREnum(VARCHAR())BOOLEANAvailable filter operators:eqgtltgteltein_startswithendswithbetweenlikeilikecontainsicontainsnot_eqnot_innot_likenot_betweenFor suggestions and questions, feel free to contact me through emailzhydykalex@ukr.net
Package: fastapi-satella-metrics
fastapi-satella-metricsfastapi-satella-metrics is an application to seamlessly measure your FastAPI
application using Satella's metrics.Example use:importfastapifromfastapi_satella_metricsimportSatellaMetricsMiddlewareapp=fastapi.FastAPI()app.add_middleware(SatellaMetricsMiddleware)If you want to exclude /metrics endpoint from being metricized:app.add_middleware(SatellaMetricsMiddleware,exclude_metrics_endpoint=True)Or to use your metrics:summary_metric=getMetric("requests_summary","summary",quantiles=[0.2,0.5,0.9,0.95,0.99])histogram_metric=getMetric("requests_histogram","histogram")response_codes_metric=getMetric("requests_response_codes","counter")app.add_middleware(SatellaMetricsMiddleware,summary_metric=summary_metric,histogram_metric=histogram_metric,response_codes_metric=response_codes_metric,)To launch a Prometheus exporter use the following snippet:fromsatella.instrumentation.metrics.exportersimportPrometheusHTTPExporterThreadphet=PrometheusHTTPExporterThread('0.0.0.0',8080,{'service_name':'my_service'})phet.start()Or, if you desire to export your metrics within FastAPI, just use:importfastapifromfastapi_satella_metrics.prometheus_exporterimportPrometheusExporterapp=fastapi.FastAPI()app.include_router(PrometheusExporter({'service_name':'my_service'}))
Package: fastapi_scheduler
FastAPI-Scheduler## Project IntroductionFastAPI-Scheduleris a simple scheduled task managementFastAPIextension library based onAPScheduler.Installpipinstallfastapi-schedulerSimple examplemain.py:fromfastapiimportFastAPIfromfastapi_amis_admin.admin.settingsimportSettingsfromfastapi_amis_admin.admin.siteimportAdminSitefromdatetimeimportdatefromfastapi_schedulerimportSchedulerAdmin# Create `FastAPI` applicationapp=FastAPI()# Create `AdminSite` instancesite=AdminSite(settings=Settings(database_url_async='sqlite+aiosqlite:///amisadmin.db'))# # Custom timed task scheduler# from apscheduler.schedulers.asyncio import AsyncIOScheduler# from apscheduler.jobstores.redis import RedisJobStore# # Use `RedisJobStore` to create a job store# scheduler = AsyncIOScheduler(jobstores={'default':RedisJobStore(db=2,host="127.0.0.1",port=6379,password="test")})# scheduler = SchedulerAdmin.bind(site,scheduler=scheduler)# Create an instance of the scheduled task scheduler `SchedulerAdmin`scheduler=SchedulerAdmin.bind(site)# Add scheduled tasks, refer to the official documentation: https://apscheduler.readthedocs.io/en/master/# use when you want to run the job at fixed intervals of time@scheduler.scheduled_job('interval',seconds=60)definterval_task_test():print('interval task is run...')# use when you want to run the job periodically at certain time(s) of day@scheduler.scheduled_job('cron',hour=3,minute=30)defcron_task_test():print('cron task is run...')# use when you want to run the job just once at a certain point of time@scheduler.scheduled_job('date',run_date=date(2022,11,11))defdate_task_test():print('date task is run...')@app.on_event("startup")asyncdefstartup():# Mount the background management systemsite.mount_app(app)# Start the scheduled task schedulerscheduler.start()if__name__=='__main__':importuvicornuvicorn.run(app,debug=True)Interface/UI previewOpenhttp://127.0.0.1:8000/admin/in your browser:Dependent projectsFastAPI-Amis-AdminAPScheduleragreementThe project follows the Apache2.0 license agreement.
Package: fastapi-script
FastAPI-ScriptAn extension for FastAPI.Getting StartedInstallationFirst you have to installfastapi-scriptlike this:pipinstallfastapi-scriptQuick TutorialWe need to create a Python module to manage your script commands, such asmanage.py:importasynciofromfastapiimportFastAPIfromfastapi_scriptimportManagerapp=FastAPI()manager=Manager(app)@manager.commandasyncdeftest_without_params():print('test_without_params')@manager.commandasyncdeftest_one_params(name):print(f'test_one_params, name:{name}')@manager.commandasyncdeftest_many_params(name,age=0):print(f'test_many_params, name:{name}, age:{age}')@manager.option('-n','--name',dest='name',help='input your name')asyncdefoption_one_params(name):print(f'option_one_params, name:{name}')@manager.option('-n','--name',dest='name',help='input your name')@manager.option('-s','--score',dest='score',help='input your score')asyncdefoption_many_params(name,score):print(f'option_many_params, name:{name}, score:{score}')if__name__=='__main__':asyncio.run(manager.run())Next, we can manipulate the above script like this:$pythonmanage.pytest_without_params
test_with_no_param

$pythonmanage.pytest_one_paramslaozhang
test_one_params,name:laozhang

$pythonmanage.pytest_many_paramslaozhang--age20test_many_params,name:laozhang,age:20$pythonmanage.pyoption_one_params-nlaozhang
option_one_params,name:laozhang

$pythonmanage.pyoption_one_params--namelaozhang
option_one_params,name:laozhang

$pythonmanage.pyoption_many_params-nlaozhang-s90option_many_params,name:laozhang,score:90$pythonmanage.pyoption_many_params--namelaozhang--score90option_many_params,name:laozhang,score:90We can use the--helpparameter to view all of the currently managed commands:pythonmanage.py--helpIn addition to using the decorator above, we can also use the inherited Command class to do this：importasynciofromfastapiimportFastAPIfromfastapi_scriptimportManager,Command,Optionapp=FastAPI()manager=Manager(app)classHelloCommand(Command):defget_options(self):return[Option('-n','--name',dest='name',help='input your name'),Option('-s','--score',dest='score',help='input your score')]defrun(self,*args,**kwargs):print(f'hello command, args:{args}, kwargs:{kwargs}')manager.add_command('hello',HelloCommand())if__name__=='__main__':asyncio.run(manager.run())And then we can use it like this：$pythonmanage.pyhello-nlaozhang-s90hellocommand,args:(),kwargs:{'name':'laozhang','score':'90'}