Saravanan666/pypi-org huggingface dataset:
Package: fastapi_config
简体中文|EnglishFastAPI-ConfigProject IntroductionFast API-Configis a visual dynamic configuration management extension package based onFastAPI-Amis-Admin.Installpipinstallfastapi-configSimple examplemain.py:fromfastapiimportFastAPIfromfastapi_amis_adminimportamisfromfastapi_amis_admin.adminimportSettings,AdminSitefromfastapi_amis_admin.modelsimportFieldfromfastapi_configimportConfigModelAdmin,DbConfigStore,ConfigAdminfromsqlmodelimportSQLModelfrompydanticimportBaseModelfromtypingimportList# Create a `FastAPI` applicationapp=FastAPI()# Create `AdminSite` instancesite=AdminSite(settings=Settings(database_url_async='sqlite+aiosqlite:///amisadmin.db'))# Create a configuration repositorydbconfig=DbConfigStore(site.db)# Register Admin (optional)site.register_admin(ConfigModelAdmin)classContactCfg(BaseModel):name:str=Field("",title="Name")qq:List[str]=Field("",title="QQ")classSiteCfg(BaseModel):name:str=Field(...,title="Site Name")logo:str=Field("",title="Site LOGO",amis_form_item=amis.InputImage())contacts:List[ContactCfg]=Field([],title="Contact list")domains:List[str]=Field([],title='Domain list')classSiteCfgAdmin(ConfigAdmin):page_schema=amis.PageSchema(label='Site Config')schema=SiteCfgsite.register_admin(SiteCfgAdmin)@app.get('/config')asyncdefread_config():returnawaitdbconfig.get(SiteCfg)@app.on_event("startup")asyncdefstartup():# Mount the site to the FastAPI instancesite.mount_app(app)# Create database tables (required for first run)awaitsite.db.async_run_sync(SQLModel.metadata.create_all,is_session=False)if__name__=='__main__':importuvicornuvicorn.run(app,debug=True)Interface/UI PreviewOpenhttp://127.0.0.1:8000/admin/in your browser:Dependent projectFastAPI-Amis-AdminLicenseThe project follows the Apache2.0 license agreement.
Package: fastapi-controller
FastAPI ControllerWrite Fast API Controllers (Classes) that can inherit route information from it's parent. This also allows to create a path prefix from a template and add api version information in the template.This utility library is written on top offastapi-utils.Install$ pip install fastapi-controllerExampleimportuvicornfrompydanticimportBaseModelfromfastapiimportHeader,Depends,FastAPIfromfastapi_controllerimportcreate_controller,controller,register_controllers_to_app# Create a controller with a path prefix template that can use the# controller name and version as template variables# For a controller named PeopleController, {controller} is replaced# by `people`ControllerBase=create_controller("/v{version}/{controller}","1.0")defget_jwt_user(auth:str=Header(...))->str:""" Pretend this function gets a UserID from a JWT in the auth header """returnauthclassGetModel(BaseModel):hello:strclassDefaultController(ControllerBase):user_id:str=Depends(get_jwt_user)@controller.get("/",response_model=GetModel)defget_all(self)->dict:return{"hello":self.user_id}@controller.get("/{model_id}")defget_one(self,model_id:int):return{"one":model_id}classPeopleController(DefaultController):# The people controller will have the two GET routes from the# parent class as well as the post route defined here.@controller.post("/")defcreate(self):return{"create":self.user_id}classScheduledJobsController(DefaultController):# The jobs controller will have the two GET routes from the parent# class with one of the routes implementation overridden.defget_one(self,model_id:int):# This'll inherit the route information GET /{model_id} from the# parent class and override functionality of the routepassif__name__=='__main__':app=FastAPI()# This function registers all the child controllers who have# ControllerBase as their parent in their inheritance heirarchy.# Intermediate Controllers between the ControllerBase and the# Child Controllers are ignored# For e.g. For the following inheritance heirarchy# ControllerBase -> DefaultController -> DerivedController -> FunctionsController -> PeopleController# Only the PeopleController is used for registering# the API routes with all the routes defined in the parent controllers# available in the child controller.register_controllers_to_app(app,ControllerBase)uvicorn.run(app,host="0.0.0.0",port=8000)With the above example, the following API routes will be registered:GET  /v1.0/people/
GET  /v1.0/people/{model_id}
POST /v1.0/people/
GET  /v1.0/scheduled_jobs/
GET  /v1.0/scheduled_jobs/{model_id}
Package: fastapi-cors
fastapi-corsA simply scoped abstraction to provide CORS settings via environment variables to a Fastapi application.UsagefromfastapiimportFastAPI# during this next line `fastapi_cors.env` will read environment variables from .envfromfastapi_corsimportCORSapp=FastAPI()CORS(app)OpinionsA health check route is optionally added that displays these (but not other) environment variables.If you want to disable it, use the code belowfromfastapiimportFastAPI# during this next line `fastapi_cors.env` will read environment variables from .envfromfastapi_corsimportCORSapp=FastAPI()CORS(app,include_health_check=False)ConfigConfigure FastAPI as usual. Extra arguments (that can be accessed fromapp.extra):NameDefaultDescriptionHOST0.0.0.0Displayed in the Swagger title, withapp.title.PORT8000Where to mount the static directory. Disabled if value is falsy.LOG_LEVELinfolog level.ALLOW_ORIGINS["http://localhost","http://localhost:3000"]A list of origins that should be permitted to make cross-origin requests. E.g. ['https://example.org', 'https://www.example.org']. You can use ['*'] to allow any origin.These are the URLs clients can make requests fromALLOWED_CREDENTIALSTrueIndicate that cookies should be supported for cross-origin requests. Also, allow_origins cannot be set to ['*'] for credentials to be allowed, origins must be specified.ALLOWED_METHODS["*"]A list of HTTP methods that should be allowed for cross-origin requests. Defaults to ['*'] to allow all standard methods. You can use ['GET'] to reduce the list.ALLOWED_HEADERS["Access-Control-Allow-Origin"]A list of HTTP request headers that should be supported for cross-origin requests. You can use ['*'] to allow all headers. The Accept, Accept-Language, Content-Language and Content-Type headers are always allowed forsimple CORS requests⚠️allow_originsdefault is["http://localhost","http://localhost:3000"], not[](80 -> docs, 3000 -> frontend)⚠️allow_methodsdefault is["*"], not["GET"]⚠️allowed_credentialsdefault isTrue, notFalseSee theFastAPI documentation on CORSfor more informationExample EnvValues will be cast into alistofstr, as appropriate.HOST=0.0.0.0
PORT=8000
LOG_LEVEL=info
ALLOW_ORIGINS=http://localhost,http://localhost:3000
ALLOWED_CREDENTIALS=True
ALLOWED_METHODS=*
ALLOWED_HEADERS=Access-Control-Allow-OriginNote, this is not required unless you are changing a default or want to declare them all
Package: fastapi-cprofile
fastapi-cprofileA FastAPI Middleware with cProfile to help stats your service performance.
cProfile is a built-in python module that can perform profiling. It is the most commonly used profiler currently.Featuressupport custom cprofile param#Installation$ pip install fastapi-cprofileCode Samplefromfastapi_cprofile.profilerimportCProfileMiddlewareapp=FastAPI()app.add_middleware(CProfileMiddleware)add cprofile optionsfromfastapi_cprofile.profilerimportCProfileMiddlewareapp=FastAPI()app.add_middleware(CProfileMiddleware,enable=True,print_each_request=True,strip_dirs=False,sort_by='cumulative')or dump out file while shutdown your app then you can use gprof2dotgprof2dotto view it.fromfastapi_cprofile.profilerimportCProfileMiddlewareapp=FastAPI()app.add_middleware(CProfileMiddleware,enable=True,server_app=app,filename='/tmp/output.pstats',strip_dirs=False,sort_by='cumulative')LicenseMIT
Package: fastapi-crawler-scheduler
fastapi_crawler_scheduler使用fromfastapiimportFastAPIfromfastapi_crawler_schedulerimportTaskSchedulerapp=FastAPI()task_scheduler=TaskScheduler(app=app,ssl=False,project_name="project_name",server_name="server_name",redis_username='redis_username',redis_password='redis_password',redis_host="127.0.0.1",redis_port=6379,thread_pool_size=50,)添加|更新任务 - add_taskinterval类型defadd_spider(**crawler_info):print(f"add_spider ={crawler_info}")print("add_spider")trigger='interval'crawler_info={"topic":"interval insert_task","title_handler_name":"interval insert_task","seconds":4,}job_id='job_1'task_scheduler.add_task(func=add_spider,job_id=job_id,trigger=trigger,crawler_info=crawler_info,seconds=4)date类型defadd_spider(**crawler_info):print(f"add_spider ={crawler_info}")print("add_spider")trigger='date'crawler_info={"topic":"date insert_task","title_handler_name":"date insert_task","run_date":"2022-10-03 11:30:00",}job_id='job_1'run_date='2022-10-03 11:30:00'task_scheduler.add_task(func=add_spider,job_id=job_id,trigger=trigger,crawler_info=crawler_info,run_date=run_date,)cron类型defadd_spider(**crawler_info):print(f"add_spider ={crawler_info}")print("add_spider")job_id='job_1'trigger='cron'minute='*/2'crawler_info={"topic":"cron update_task","title_handler_name":"cron update_task","minute":minute,}task_scheduler.add_task(func=add_spider,job_id=job_id,trigger=trigger,crawler_info=crawler_info,minute=minute,)删除任务 - delete_taskjob_id='job_1'task_scheduler.delete_task(job_id=job_id)查看任务# 查看该项目的所有键task_scheduler.show_all_redis_key()# 查看该项目的所进程task_scheduler.show_all_redis_nodes()# 查看该项目的所有加载过的任务task_scheduler.show_all_redis_tasks()# 查看该项目使用的apscheduler.get_jobs()方法获得的所有任务task_scheduler.show_all_scheduler_get_jobs()# 查看该项目的apscheduler存储redis的所有任务task_scheduler.show_all_apscheduler_stores_jobs()# 查看该项目的的apscheduler存储redis的所有任务的run_ttimestask_scheduler.show_all_redis_apscheduler_run_times()# 查看该项目的所有任务不存在apscheduler存储redis的所有任务task_scheduler.show_all_task_not_in_stores_jobs()# 查看该项目的任务没有执行的项目（不包含只执行过一次的项目）task_scheduler.show_all_task_not_in_stores_run_times()task_scheduler.clear_project_keys()请求redis 脏数据   慎用task_scheduler.clear_project_keys()安装Pypi$ pip install fastapi-crawler-scheduler
Package: fastapi-create-app
FastAPI CREATE APPfastapi-create-app is a CLI tool for generating bare-bone FastAPI project.
When you runfastapi-create-app new [project_name], it generates the following project structure:.
├── app/
│   ├── __init__.py
│   ├── config/
│   │   ├── __init__.py
│   │   └── config.py
│   ├── database/
│   │   ├── __init__.py
│   │   └── database.py
│   ├── models/
│   │   ├── __init__.py
│   │   └── models.py
│   ├── routers/
│   │   ├── __init__.py
│   │   └── routes.py
│   ├── schemas/
│   │   ├── __init__.py
│   │   └── schemas.py
│   └── services/
│   │   ├── __init__.py
│   │   └── services.py
│   └── statics/
│   └── templates/
│   └── tests/
│   │   ├── __init__.py
│   │   └── tests.py
│   └── utils/
│       ├── __init__.py
│       └── utils.py
├── Dockerfile
├── docker-compose.yaml
├── [project_name]_ven
├── .env
├── .gitignore
├── requirements.txt
└── README.mdINSTALLATIONpip install fastapi-create-appCOMMANDfastapi-create-app new [project_name]This command initialized an empty git repository, create a virtual environment using the python builtinvenvby appending_evvto the project name, i.e[project_name]_env.Activate the virtual environment before installing dependencies.view project on github
Package: fastapi-crudrouter
⚡ Create CRUD routes with lighting speed⚡A dynamic FastAPI router that automatically creates CRUD routes for your modelsDocumentation:https://fastapi-crudrouter.awtkns.comSource Code:https://github.com/awtkns/fastapi-crudrouterTired of rewriting generic CRUD routes? Need to rapidly prototype a feature for a presentation
or a hackathon? Thankfully,fastapi-crudrouterhas your back. As an
extension to the APIRouter included withFastAPI, the FastAPI CRUDRouter will automatically
generate and document your CRUD routes for you, all you have to do is pass your model and maybe your database connection.FastAPI-CRUDRouter islighting fast, well tested, andproduction ready.Installationpipinstallfastapi-crudrouterBasic UsageBelow is a simple example of what the CRUDRouter can do. In just ten lines of code, you can generate all
the crud routes you need for any model. A full list of the routes generated can be foundhere.frompydanticimportBaseModelfromfastapiimportFastAPIfromfastapi_crudrouterimportMemoryCRUDRouterasCRUDRouterclassPotato(BaseModel):id:intcolor:strmass:floatapp=FastAPI()app.include_router(CRUDRouter(schema=Potato))Advanced Usagefastapi-crudrouter provides a number of features that allow you to get the most out of your automatically generated CRUD
routes. Listed below are some highlights.Automatic Pagination (docs)Ability to Provide Custom Create and Update Schemas (docs)Dynamic Generation of Create and Update Schemas (docs)Ability to Add, Customize, or Disable Specific Routes (docs)Native Support for FastAPI Dependency Injection (docs)Supported Backends / ORMsfastapi-crudrouter currently supports a number of backends / ORMs. Listed below are the backends currently supported. This list will
likely grow in future releases.In Memory (docs)SQLAlchemy (docs)Databases (async) (docs)Gino (async) (docs)Ormar (async) (docs)Tortoise ORM  (async) (docs)OpenAPI SupportBy default, all routes generated by the CRUDRouter will be documented according to OpenAPI spec.Below are the default routes created by the CRUDRouter shown in the generated OpenAPI documentation.The CRUDRouter is able to dynamically generate detailed documentation based on the models given to it.
Package: fastapi-crudrouter-as3445
⚡ Create CRUD routes with lighting speed⚡A dynamic FastAPI router that automatically creates CRUD routes for your modelsDocumentation:https://fastapi-crudrouter.awtkns.comSource Code:https://github.com/awtkns/fastapi-crudrouterTired of rewriting generic CRUD routes? Need to rapidly prototype a feature for a presentation
or a hackathon? Thankfully,fastapi-crudrouterhas your back. As an
extension to the APIRouter included withFastAPI, the FastAPI CRUDRouter will automatically
generate and document your CRUD routes for you, all you have to do is pass your model and maybe your database connection.FastAPI-CRUDRouter islighting fast, well tested, andproduction ready.Installationpipinstallfastapi-crudrouterBasic UsageBelow is a simple example of what the CRUDRouter can do. In just ten lines of code, you can generate all
the crud routes you need for any model. A full list of the routes generated can be foundhere.frompydanticimportBaseModelfromfastapiimportFastAPIfromfastapi_crudrouterimportMemoryCRUDRouterasCRUDRouterclassPotato(BaseModel):id:intcolor:strmass:floatapp=FastAPI()app.include_router(CRUDRouter(schema=Potato))Advanced Usagefastapi-crudrouter provides a number of features that allow you to get the most out of your automatically generated CRUD
routes. Listed below are some highlights.Automatic Pagination (docs)Ability to Provide Custom Create and Update Schemas (docs)Dynamic Generation of Create and Update Schemas (docs)Ability to Add, Customize, or Disable Specific Routes (docs)Native Support for FastAPI Dependency Injection (docs)Supported Backends / ORMsfastapi-crudrouter currently supports a number of backends / ORMs. Listed below are the backends currently supported. This list will
likely grow in future releases.In Memory (docs)SQLAlchemy (docs)Databases (async) (docs)Gino (async) (docs)Ormar (async) (docs)Tortoise ORM  (async) (docs)OpenAPI SupportBy default, all routes generated by the CRUDRouter will be documented according to OpenAPI spec.Below are the default routes created by the CRUDRouter shown in the generated OpenAPI documentation.The CRUDRouter is able to dynamically generate detailed documentation based on the models given to it.
Package: fastapi-crudrouter-async
⚡ Create CRUD routes with lighting speed⚡A dynamic FastAPI router that automatically creates CRUD routes for your modelsDocumentation:https://fastapi-crudrouter.awtkns.comSource Code:https://github.com/awtkns/fastapi-crudrouterTired of rewriting generic CRUD routes? Need to rapidly prototype a feature for a presentation
or a hackathon? Thankfully,fastapi-crudrouterhas your back. As an
extension to the APIRouter included withFastAPI, the FastAPI CRUDRouter will automatically
generate and document your CRUD routes for you, all you have to do is pass your model and maybe your database connection.FastAPI-CRUDRouter islighting fast, well tested, andproduction ready.Installationpipinstallfastapi-crudrouterBasic UsageBelow is a simple example of what the CRUDRouter can do. In just ten lines of code, you can generate all
the crud routes you need for any model. A full list of the routes generated can be foundhere.frompydanticimportBaseModelfromfastapiimportFastAPIfromfastapi_crudrouterimportMemoryCRUDRouterasCRUDRouterclassPotato(BaseModel):id:intcolor:strmass:floatapp=FastAPI()app.include_router(CRUDRouter(schema=Potato))Advanced Usagefastapi-crudrouter provides a number of features that allow you to get the most out of your automatically generated CRUD
routes. Listed below are some highlights.Automatic Pagination (docs)Ability to Provide Custom Create and Update Schemas (docs)Dynamic Generation of Create and Update Schemas (docs)Ability to Add, Customize, or Disable Specific Routes (docs)Native Support for FastAPI Dependency Injection (docs)Supported Backends / ORMsfastapi-crudrouter currently supports a number of backends / ORMs. Listed below are the backends currently supported. This list will
likely grow in future releases.In Memory (docs)SQLAlchemy (docs)Databases (async) (docs)Gino (async) (docs)Ormar (async) (docs)Tortoise ORM  (async) (docs)OpenAPI SupportBy default, all routes generated by the CRUDRouter will be documented according to OpenAPI spec.Below are the default routes created by the CRUDRouter shown in the generated OpenAPI documentation.The CRUDRouter is able to dynamically generate detailed documentation based on the models given to it.
Package: fastapi-crudrouter-mongodb
⚡ Create CRUD routes with lighting speed⚡A dynamic FastAPI router that automatically creates CRUD routes for your Mongodb models---Documentation:https://pierrod.github.io/fastapi-crudrouter-mongodb-doc/Source Code:https://github.com/pierrod/fastapi-crudrouter-mongodbCredits:Base projet and idea :awtknsConvert _id to id :mclate github guideTired of rewriting generic CRUD routes? Need to rapidly prototype a feature for a presentation
or a hackathon? Thankfully,fastapi-crudrouter-mongodbhas your back.As an extension to the APIRouter included withFastAPI, the FastAPI CRUDRouter will automatically
generate and document your CRUD routes for you, all you have to do is pass your model and maybe your database connection.Installationpipinstallfastapi-crudrouter-mongodbBasic UsageI will provide more examples in the future, but for now, here is a basic example of how to use the FastAPI CRUDRouter for Mongodb.fromdatetimeimportdatetimefromtypingimportList,Optional,UnionfromfastapiimportFastAPIfrompydanticimportFieldfromfastapi_crudrouter_mongodbimportCRUDRouter,MongoModel,MongoObjectId,CRUDLookupimportmotor.motor_asyncio# Database connection using motorclient=motor.motor_asyncio.AsyncIOMotorClient("mongodb://localhost:27017/local")db=client.local# ModelsclassMessageModel(MongoModel):id:Optional[MongoObjectId]=Field()message:struser_id:MongoObjectIdcreated_at:Optional[str]=datetime.now().strftime("%Y-%m-%d%H:%M:%S")updated_at:Optional[str]=datetime.now().strftime("%Y-%m-%d%H:%M:%S")classAddressModel(MongoModel):id:Optional[MongoObjectId]=Field()street:strcity:strstate:strzip:strclassUserModel(MongoModel):id:Optional[MongoObjectId]=Field()name:stremail:straddresses:Optional[List[AddressModel]]messages:Optional[Union[List[MessageModel],MessageModel]]=None# Instantiating the CRUDRouter, and a lookup for the messages# a User is a model that contains a list of embedded addresses and related to multiple messagesmessages_lookup=CRUDLookup(model=MessageModel,collection_name="messages",prefix="messages",local_field="_id",foreign_field="user_id")users_controller=CRUDRouter(model=UserModel,db=db,collection_name="users",lookups=[messages_lookup],prefix="/users",tags=["users"],)# Instantiating the FastAPI appapp=FastAPI()app.include_router(users_controller)OpenAPI SupportBy default, all routes generated by the CRUDRouter will be documented according to OpenAPI spec.Below are the default routes created by the CRUDRouter shown in the generated OpenAPI documentation.
Package: fastapi-csv
fastapi-csv  🏗️Create APIs from CSV files within seconds, using fastapi.This is a Python package to create APIs from CSV files, using a lightweight &
fully customizable wrapper aroundfastapi. Endpoints
and query parameters are auto-generated based on the column names and data types in the
CSV file. Its data is written to a (temporary) sqlite database, so the API is blazing
fast even for huge files.Installationpipinstallfastapi-csvHow to use it1. From the command lineThere's a simple CSV file in this repo for testing (people.csv). To start
an API for it, run one of:# from filefastapi-csvpeople.csv# directly from URLfastapi-csvhttps://raw.githubusercontent.com/jrieke/fastapi-csv/main/people.csvEither command should start a fastapi instance, which has auto-generated endpoints and
query parameters based on the CSV file. Here, the API has an endpoint/people(same name as the file), which can be queried using the CSV's column names, e.g. you can
do:/people?first_name=Rachel/people?last_name=Johnson&age=48Additionally, fastapi-csv creates some convenience query parameters for specific data
types, e.g./people&age_greaterThan=18(for int/float)/people&age_lessThanEqual=18(for int/float)/people&first_name_contains=ach(for string, watch out: this one is case sensitive!)Check out the API docs for more information and an interactive demo, they should be athttp://127.0.0.1:8000/docs2. From PythonCreate a filemy_file.py:fromfastapi_csvimportFastAPI_CSVapp=FastAPI_CSV("people.csv")Start from terminal just like a normal fastapi app:uvicornmy_file:appExtending the APIThe cool thing:FastAPI_CSVis just a wrapper aroundFastAPI. Therefore, you can do
all the stuff you can do with a normal fastapi instance, e.g. add a new endpoint:# Add a new endpoint, just like in normal fastapi@app.get("/hello")defhello(self):return{"Hello:","World"}In the future, you will also be able to easily modify existing endpoints that were
generated from the CSV file.Updating the dataIf your CSV file changes, you can update the API data with:app.update_database()Note that this will only update the data, not the API endpoints or query parameters.
To do that, you need to create a newFastAPI_CSVinstance or re-start uvicorn.
Package: fastapi-debug-toolbar
Debug Toolbar🐞A debug toolbar for FastAPI based on the original django-debug-toolbar.🐞Swagger UI&GraphQLare supported.Documentation:https://fastapi-debug-toolbar.domake.ioInstallationpipinstallfastapi-debug-toolbarQuickstartAddDebugToolbarMiddlewaremiddleware to your FastAPI application:fromdebug_toolbar.middlewareimportDebugToolbarMiddlewarefromfastapiimportFastAPIapp=FastAPI(debug=True)app.add_middleware(DebugToolbarMiddleware)SQLAlchemyPlease make sure to use the"Dependency Injection"system as described in theFastAPI docsand add theSQLAlchemyPanelto your panel list:app.add_middleware(DebugToolbarMiddleware,panels=["debug_toolbar.panels.sqlalchemy.SQLAlchemyPanel"],)Tortoise ORMAdd theTortoisePanelto your panel list:app.add_middleware(DebugToolbarMiddleware,panels=["debug_toolbar.panels.tortoise.TortoisePanel"],)
Package: fastapi-deferred-init
fastapi-deferred-initThe ProblemWhen using nested routers in a FastAPI project its start-up time can get long quite fast.
That is because every router re-calculates the routes defined by a nested router when including it and the pre-calculated values by the nested router never get used. In short: values in nested routers are calculated although they will never be used.The SolutionThis library provides a modified APIRoute that defers the calculation of values to the first actual attribute access. A router which uses the route as a default is also provided.CaveatWhen using the deferred APIRoute on every layer of the app, startup errors are deferred to the first time a route is called. So errors related to route registration might go undetected if the route is not tested at least once.