Saravanan666/pypi-org huggingface dataset:
Package: fastapi-gino-viewsets
Inspired by Django Rest FrameworkPython 3.7+Install:pip installfastapi-gino-viewsetsGithub:https://github.com/basalex/fastapi_gino_viewsetsExamples of usage:Create your model and migrate databaseclassUser(db.Model):__tablename__='users'id=db.Column(db.Integer(),primary_key=True)username=db.Column(db.String(255),nullable=False,unique=True)email=db.Column(db.EmailType,nullable=False,unique=True)age=db.Column(db.Integer(),nullable=True)Then, you would want to use MainRouter classfromfastapi_gino_viewsetsimportMainRouterfromfastapi_gino_viewsetsimportViewsetrouter=MainRouter()@router.add_view('/user)classUserViewSet(ViewSet):model=UserThat’s it! Now all methods -> get[+list+filters], post, patch, put, deletes are available and ready for useAvailable Mixin and ViewSet classesAggregationMixin- Requires output_schema ->retrieve_aggregated_dataget_query[sync, async] - required to be manually implementedfilter_query - override to change filters behaviourListMixin- Used when you want to get a list of objects, main method ->retrieve_listmethodsbase_list_schema -> override base class for output schemaretrieve_list - it’s not recommended to be overridden, probably you just don’t need to use the mixinget_query[sync, async] - override to change default behaviourfilter_query - override to change filters behavioursort_query - override to change sort behaviourtotal - override to change total count calculationpaginate - override to change paginate behaviourprepare_data_hook - override for manipulating data after query executionRetrieveModelMixin- Get single object by id ->retrievemethodUpdateModelMixin- Update using PUT http ->updatemethodUpdateModelMixin- Update using PATCH http ->update_partialmethodDeleteModelMixin- Delete object by id ->deletemethodReadOnlyViewset- Providesretrieveandretrieve_listmethodsViewset- Prodiveds all methods from all mixins, but AggregationMixin
Package: fastapi-global-variable
FastAPI Global VariableHow to useSet a variable# user_service.pyfromfastapiimportFastAPIfromfastapi_global_variableimportGlobalVariableapp=FastAPI(title="Application")GlobalVariable.set('app',app)Use variablefromfastapi_global_variableimportGlobalVariableprint(GlobalVariable.get_or_fail('app'))print(GlobalVariable.get('app'))How to test in testpypiIncrease the version inpyproject.tomlRun command$../build_and_test.shHow to publish new versionIncrease the version inpyproject.tomlRun command$../build_and_publish.sh
Package: fastapi-google-iap
fastapi-google-iapA FastAPI plugin for Google Cloud Identity-Aware Proxy (IAP) authentication.Installationpipinstallfastapi-google-iapUsagefromfastapiimportFastAPIfromfastapi_google_iapimportGoogleIapMiddlewareapp=FastAPI()app.use_middleware(GoogleIapMiddleware,audience="/projects/999999999999/apps/example-project",unprotected_routes=["/healthz"],restrict_to_domains=["example.com"],)LicenseThis project is licensed under the terms of the MIT license.
Package: fastapi-health
FastAPI Health 🚑️The goal of this package is to help you to implement theHealth Check APIpattern.Installationpipinstallfastapi-healthQuick StartCreate the health check endpoint dynamically using different conditions. Each condition is a
callable, and you can even have dependencies inside of it:fromfastapiimportFastAPI,Dependsfromfastapi_healthimporthealthdefget_session():returnTruedefis_database_online(session:bool=Depends(get_session)):returnsessionapp=FastAPI()app.add_api_route("/health",health([is_database_online]))Advanced UsageThehealth()method receives the following parameters:conditions: A list of callables that represents the conditions of your API, it can return eitherboolor adict.success_output: An optional dictionary that will be the content response of a successful health call.failure_output: An optional dictionary analogous tosuccess_outputfor failure scenarios.success_status: An integer that overwrites the default status (200) in case of success.failure_status: An integer that overwrites the default status (503) in case of failure.It's important to notice that you can have apeculiarbehavior in case of hybrid return statements (boolanddict) on the conditions.
For example:fromfastapiimportFastAPIfromfastapi_healthimporthealthdefhealthy_condition():return{"database":"online"}defsick_condition():returnFalseapp=FastAPI()app.add_api_route("/health",health([healthy_condition,sick_condition]))This will generate a response composed by the status being 503 (defaultfailure_status), becausesick_conditionreturnsFalse, and the JSON body{"database": "online"}. It's not wrong, or a bug. It's meant to be like this.LicenseThis project is licensed under the terms of the MIT license.
Package: fastapi-healthcheck
fastapi_healthcheckEasy to use health check for your FastAPI.  This is the root module that will let you add implement and expand your usage of health checks, with FastAPI.This module does not contain any service checkers, but you can easily add them.  The other modules are not in this root module due to different dependencies required for each one.  This is made so you only bring in the packages that you need to not add extra packages.Installpip install fastapi-healthcheckorpoetry add fastapi-healthcheckAdding Health ChecksHere is what you need to get started.fromfastapiimportFastAPIfromfastapi_healthcheckimportHealthCheckFactory,healthCheckRoutefromfastapi_healthcheck_sqlalchemyimportHealthCheckSQLAlchemyapp=FastAPI()# Add Health Checks_healthChecks=HealthCheckFactory()# SQLAlchemy comes from fastapi-healthcheck-sqlalchemy_healthChecks.add(HealthCheckSQLAlchemy(alias='postgres db',connectionUri=cs.value,table=SmtpContactsSqlModel,tags=('postgres','db','sql01')))# This will check external URI and validate the response that is returned.# fastapi-healthcheck-uri_healthChecks.add(HealthCheckUri(alias='reddit',connectionUri="https://www.reddit.com/r/aww.json",tags=('external','reddit','aww')))app.add_api_route('/health',endpoint=healthCheckRoute(factory=_healthChecks))Returned DataWhen you request your health check, it will go and check all the entries that have been submitted and run a basic query against them.  If they come back as expected, then a status code is 200.  But if it runs into an error, it will return a 500 error.{"status":"Healthy","totalTimeTaken":"0:00:00.671642","entities":[{"alias":"postgres db","status":"Healthy","timeTaken":"0:00:00.009619","tags":["postgres","db","sql01"]},{"alias":"reddit","status":"Unhealthy","timeTaken":"0:00:00.661716","tags":["external","reddit","aww"]}]}Available Modulesfastapi_healthcheck_sqlalchemyfastapi_healthcheck_uriIf you have made a public service module and want to see it on this list, please open a new issue so we can add it to the list.Writing a custom moduleYou can easily expand on this core module to add other health checks for other services.  Generate a new service that pulls inHealthCheckInterfaceandHealthCheckBase.  With those, you can build the respective class around the interface.Once you have your service ready to go, add it to the HealthCheckFactory, and let the testing start.If you would like to see an example of a custom service seefastapi_healthcheck_sqlalchemy.  This will give you a better example of what you need to do to create your own module to interface with healthcheck.
Package: fastapi-healthcheck-flagman
FastAPI Healthcheck packageimportfastapi_healthcheckapp=FastAPI(...)classWorkerChecker(healthcheck.base.Base):defcheck(self):status=False# code that checks healthtime_passed_for_check=1.0return{"name":self.name,"status":status,"optional":self.optional,"time":time_passed_for_check}fastapi_healthcheck.add_health_route(app,name="Super-Resolution",checkers=[healthcheck.redis.Checker(),#built-in checkerWorkerChecker(name="Worker Checker")#custom checker])
Package: fastapi-healthchecks
FastAPI health checksConfigurable health checks endpoints for FastAPI applications.Quickstartapp=FastAPI()app.include_router(HealthcheckRouter(Probe(name="readiness",checks=[PostgreSqlCheck(host="db.example.com",username=...,password=...),RedisCheck(host="redis.example.com",username=...,password=...),],),Probe(name="liveness",checks=[...,],),),prefix="/health",)The probes from this example will be available asGET /health/readinessandGET /health/liveness.Bundled checksPostgreSqlCheck– checks PostgreSQL server availabilityRedisCheck– checks Redis server availabilityRabbitMqCheck– checks RabbitMQ server availabilitySettingsCheck– validates settings models based on pydantic BaseModelHttpCheck– checks availability of specified URLCephCheck– checks Ceph server availabilityCustom checksYou can create your own checks by providing customfastapi_healthchecks.checks.Checkimplementations. Like this:classMaintenanceCheck(Check):asyncdef__call__(self)->CheckResult:ifis_maintenance():returnCheckResult(name="Maintenance",passed=False,details="Closed for maintenance")else:returnCheckResult(name="Maintenance",passed=True)
Package: fastapi-healthcheck-sqlalchemy
fastapi-healthcheck-sqlalchemyA module built on top of fastapi_healthcheck to check the status of your SQLAlchemy connection.  This requires a Table given to the health check so it can run a count of rows against it.  As long as it returns a value, the connection is alive.Installpip install fastapi-healthcheck-sqlalchemyorpoetry add fastapi-healthcheck-sqlalchemyHow to useThis module just exposes the service layer that will be used to parse your middleware connection to your database.fromfastapiimportFastAPIfromfastapi_sqlalchemyimportDBSessionMiddlewarefromfastapi_healthcheckimportHealthCheckFactory,healthCheckRoutefromfastapi_healthcheck_sqlalchemyimportHealthCheckSQLAlchemyapp=FastAPI()# Bring SQLAlchemy online first.app.add_middleware(DBSessionMiddleware,db_url=cs.value)_healthChecks=HealthCheckFactory()_healthChecks.add(HealthCheckSQLAlchemy(# The name of the object for your referencealias='postgres db',# The Table that we will run a count method against.table=SmtpContactsSqlModel,tags=('postgres','db','sql01')))app.add_api_route('/health',endpoint=healthCheckRoute(factory=_healthChecks))
Package: fastapi-healthcheck-uri
fastapi_healthcheck_uriA module to have a FastAPI HealthCheck reach out to a URI to validate external service health.Adding Health ChecksHere is what you need to get started.fromfastapiimportFastAPIfromfastapi_healthcheckimportHealthCheckFactory,healthCheckRoutefromfastapi_healthcheck_uriimportHealthCheckUriapp=FastAPI()# Add Health Checks_healthChecks=HealthCheckFactory()_healthChecks.add(HealthCheckUri(alias='reddit',connectionUri="https://www.reddit.com/r/aww.json",tags=('external','reddit','aww'),healthyCode=200,unhealthyCode=500))app.add_api_route('/health',endpoint=healthCheckRoute(factory=_healthChecks))
Package: fastapi-health-monitor
FastAPI Health MonitorA health monitor for FastAPI applications which runs user provided background checks to determine the current overall health status of an API system.FeaturesMicroservices architecture health endpoint.Returns HTTP status codes. (200 OK / 503 unavailable)Can be used for Kubernetes liveness / readiness checks.Supports custom dependency and subcomponent checks.Simple ok/error checks or optional support for more detailed metrics.InstallationInstall using the pip package manager.pip install fastapi-health-monitorUsageThis example shows a FastAPI application which returns a dad joke from an external API.The checks are run every 10 seconds by default. This can be changed using an environment variableHEALTH_CHECK_DELAY_SECONDS.fromfastapiimportFastAPIimportrequests# Import health monitorfromfastapi_health_monitorimportHealthMonitor,ComponentHealth,HealthStatusapp=FastAPI()# Create health monitor instancemonitor=HealthMonitor(root_app=app,service_id="dadjokes",version="1",release_id="1.0.0",extra_notes=["environment=test"],health_endpoint="/health",)# Create a component check functiondefcheck_external_api(component:ComponentHealth):"""Check that external API returns 200 OK"""res=requests.get("https://icanhazdadjoke.com/",headers={"Accept":"application/json"})# Update status based on status codeifres.status_code==200:component.status=HealthStatus.OKelse:component.status=HealthStatus.ERRORreturncomponent# Add a component to the health monitormonitor.add_component(component_name="icanhazdadjoke.com",measurement_name="reachability",check_function=check_external_api,)@app.get("/")asyncdefroot():"""Return a dad joke from https://icanhazdadjoke.com/"""return(requests.get("https://icanhazdadjoke.com/",headers={"Accept":"application/json"}).json().get("joke"))Example response{"service_id":"dadjokes","status":"ok","version":"1","release_id":"1.0.0","notes":["startup_timestamp=2023-08-22T18:02:55.133246","last_checked_timestamp=2023-08-22T18:03:06.617896","environment=test"],"checks":{"icanhazdadjoke.com:reachability":{"component_name":"icanhazdadjoke.com","measurement_name":"reachability","status":"ok","time":"2023-08-22T18:03:06.617719"},"uptime":{"measurement_name":"uptime","component_type":"system","observed_value":11.484558,"observed_unit":"s","status":"ok","time":"2023-08-22T18:03:06.617811"}}}AuthorsFastAPI Health Monitor was created by Adam Kirchberger in 2023.LicenseMITSeeLICENSE.Change LogSeeCHANGELOG
Package: fastapi-healthz
fastapi_healthzStreamline your health checks with FastAPI using this user-friendly health check module. It serves as the foundational
component for integrating and enhancing health checks within FastAPI.This core module doesn't include any service checkers by default, but it offers a simple method for adding them. The
reason for housing various modules separately is to accommodate the distinct dependencies required for each, ensuring
that you only import the specific packages you need, thereby preventing any unnecessary package bloat.This package is Pydantic v2 compliant.Installpip install fastapi-healthzorpoetry add fastapi-healthzAdding Health ChecksHere is what you need to get started.fromfastapiimportFastAPIfromfastapi_healthzimport(HealthCheckRegistry,HealthCheckRabbitMQ,HealthCheckRedis,HealthCheckUri,HealthCheckDatabase,health_check_route,)app=FastAPI()# Add Health Checks_healthChecks=HealthCheckRegistry()# SQLAlchemy_healthChecks.add(HealthCheckDatabase(uri="dialect+driver://username:password@host:port/database"))# RabbitMQ_healthChecks.add(HealthCheckRabbitMQ(host="localhost",port=5672,vhost="",username="username",password="pwd",ssl=True))# Redis_healthChecks.add(HealthCheckRedis(uri="redis://[password:]host:port/database"))# This will check external URI and validate the response that is returned._healthChecks.add(HealthCheckUri(uri="https://www.reddit.com/r/aww.json"))app.add_api_route('/health',endpoint=health_check_route(registry=_healthChecks))Returned DataWhen you initiate a health check request, it will examine all the submitted entries and execute a fundamental query on
each of them. If the results conform to expectations, a status code of 200 is returned. However, if an error is
encountered, a 500 error response will be provided.{"status":"Healthy","totalTimeTaken":"0:00:00.671642","entities":[{"alias":"db","status":"Healthy","timeTaken":"0:00:00.009619","tags":["db"]},{"alias":"reddit","status":"Unhealthy","timeTaken":"0:00:00.661716","tags":["uri"]}]}Writing a custom checkerYou can effortlessly extend the functionality of this foundational module by incorporating additional health checks for
various services. Simply create a new service that imports the HealthCheckAbstract. Then, build the corresponding class
around this abstract.Once your service is prepared, integrate it into the HealthCheckRegistry, and you're all set to commence testing.
Package: fastapi-helper
FastAPI HelperSimple and customizable HTTP exceptionsimportuvicornfromfastapiimportFastAPIfromstarletteimportstatusfromstarlette.requestsimportRequestfromstarlette.responsesimportJSONResponsefromsrc.fastapi_fancy_exceptionsimportFancyHTTPExceptionapp=FastAPI()classAuthException(FancyHTTPException):code="auth_error"type="AuthError"message="Auth error"status_code=status.HTTP_401_UNAUTHORIZED@app.exception_handler(FancyHTTPException)asyncdefhttp_exception_accept_handler(request:Request,exc:FancyHTTPException)->JSONResponse:returnJSONResponse(status_code=exc.status_code,content=[{"code":exc.code,"type":exc.type,"message":exc.message}])@app.get("/")asyncdefroot():raiseAuthException()uvicorn.run(app,host="localhost",port=8000)This code will lead to this response with status code 401:[{"code":"auth_error","type":"AuthError","message":"Auth error"}]
Package: fastapi-helpers
Fastapi HelpersThis pip packages will help you to make your life easier when working with fastapi and ormar.For installing this package:pipinstallfastapi-helpersIf you need a default settings for your app, it includes an implementation BaseSettings of pydantic.fromfastapi_helpersimportDefaultSettingsfromutilsimportenv_pathfromtypingimportOptionalclassSettings(DefaultSettings):app_name="your-app-name"redis_url:Optional[str]='redis://localhost:6379'version:Optional[str]='1.0.0.0'port:Optional[str]="8000"env:Optional[str]="dev"#dev, test, prodsettings=Settings(env_path)If you need a logger, it includes an implementation a colored console, and in prod envs it will log to aws with the help of watchtower.fromfastapi_helpersimportDefaultLoggerfrom.configimportsettingslogger=DefaultLogger("your-app-name",settings)If you need to connect to a db superfast, the only thing you need to do is to:fromfastapi_helpersimportDbConfigfromcore.configimportsettingsfromcore.loggerimportloggerdb_config=DbConfig(settings,logger)There are other tools for making the usage of ormar and fastapi even easier.I would really like to make this tools bigger, but I´m looking for help for documenting this package.Happy codding!
Package: fastapi-hive
FastAPI HiveFastAPI Hive Framework, modulization code layout tools, decoupling codes into cornerstones and endpoints, developer-friendly, easy to be integratedThe classical code structure is compliant with function components view with the function folders, such as "api" folder for router registering, "models" folder for db and pydantic data model, just likefastapi-ml-skeleton.But from the system design view, the system is divided into serveral sub-service, such as "heartbeat" service and "house_price" service in the above example, each of two services contains "api" and "model" function components.With the help of fastapi-hive container_name, you can layout code structure by service style. For each service, it is defined as one endpoint, the codes are gathered in one endpoint folder, Also for the common functions, like db, auth, etc..., they are defined as cornerstones which are for constructing the hive(bee's home), and every bee are endpoints to go to hive.Go to detailed site for more informationFastAPI HiveThis repository contains a example app with cornerstones and endpoints folder which can be used to speed-up your next machine learning project. The code is fully tested and provides a preconfiguredtoxto quickly expand this sample code.To experiment and get a feeling on how to use this framework, follow the installation and setup instructions to run the example app and serve it with RESTful API, go toFastAPI Hivefor that.
Package: fastapi-hypermodel
FastAPI-HyperModelSimple hypermedia for FastAPIDocumentation:https://jtc42.github.io/fastapi-hypermodel/Source Code:https://github.com/jtc42/fastapi-hypermodelFastAPI-HyperModel is a FastAPI + Pydantic extension for simplifying
hypermedia-driven API development.Hypermedia consist of enriching API responses by providing links to other URIs
within the services to fetch related resources or perform certain actions. There
are several levels according to theHypermedia Maturity Model
Levels. Using
Hypermedia makes APIs reach Level 3 of theRichardson Maturity Model
(RMM), which involves
leveragingHypertext As The Engine Of Application State
(HATEOAS), that is, Hypermedia.Below are some examples of responses using hypermedia. For detailed examples,
check the docs.FormatResponseNo Hypermdia{"id_":"item01","name":"Foo","price":10.2,}Level 0 Hypermedia (URLFor){"id_":"item01","name":"Foo","price":10.2,"href":"/items/item01","update":"/items/item01"}Level 1 Hypermedia (HAL){"id_":"item01","name":"Foo","price":10.2,"_links":{"self":{"href":"/items/item01"},"update":{"href":"/items/item01"},},}Level 2 Hypermedia (Siren){"properties":{"id_":"item01","name":"Foo","price":10.2},"links":[{"rel":["self"],"href":"/items/item01"}],"actions":[{"name":"update","method":"PUT","href":"/items/item01","type":"application/x-www-form-urlencoded","fields":[{"name":"name","type":"text","value":"Foo"},{"name":"description","type":"text","value":"None"},{"name":"price","type":"number","value":"10.2"}]}]}Installationpip install fastapi-hypermodelLimitationsCurrently, query parameters will not resolve correctly. When generating a resource URL, ensure all parameters passed are path parameters, not query parameters.This is an upstream issue, being trackedhere.AttributionsHuge thanks to@christoefor building support for Pydantic 2.
Package: fastapi-idempotent
fastapi-idempotentHow to use package fastapi-idempotent# Install package using poetrypoetryaddfastapi-idempotent# Using pippipinstallfastapi-idempotentSet rate limit for FastAPI before starting serverExample codemain.py# Import packagefromfastapiimportFastAPI
fromfastapi_idempotentimportIdempotentMiddleWare
fromcore.configimportsettings# settings is class, where the configuration parameters are savedfromapi.responsesimportJSONResponse

...# Setup FastAPIapp=FastAPI(title=settings.PROJECT_NAME,version=settings.API_VERSION,openapi_url=f"{settings.API_V1_PATH}/openapi.json",default_response_class=JSONResponse,)Set idempotent for FastAPIUsing redis storage# Default idempotent expired is 10800sapp.add_middleware(IdempotentMiddleWare,redis_url=settings.IDEMPOTENT_STORAGE_URL,# type: str)orapp.add_middleware(IdempotentMiddleWare,idempotent_expired=settings.IDEMPOTENT_EXPIRED,# type: intredis_url=settings.IDEMPOTENT_STORAGE_URL,# type: str)Using memory storage# Default idempotent expired is 10800sapp.add_middleware(IdempotentMiddleWare,testing=True,# type: bool)orapp.add_middleware(IdempotentMiddleWare,idempotent_expired=settings.IDEMPOTENT_EXPIRED,# type: inttesting=True,# type: bool)
Package: fastapi-inferring-depends
FastAPI inferring DependsA wrapper around FastAPI's Depends function that infers its return type from its inputExamplefromfastapi_inferring_dependsimportDependsfromfastapiimportFastAPIrouter=FastAPI()asyncdefanswer_to_everything_dependency():return42@app.get("/answer")asyncdefget_answer_to_everything(answer_to_everything=Depends(answer_to_everything_dependency),):# type of answer_to_everything is 'int' (inferred from dependency)return{"answer":answer_to_everything}For more examples, look at the test/examplefilefor all supported inferences.