Saravanan666/pypi-org huggingface dataset:
Package: fastapi-dependency
fastapi-dependencyWhen you use FastAPI, you might be tempted to createsync(def) dependencies on which you actually don't perform thread blocking operations.
The thing is that FastAPI will always run yoursyncdependencies in a thread pool, which is not necessary.The goal of this package is to makeexplicitif you want to run a dependency in a thread pool.InstallationThe package is available onPyPI:pipinstallfastapi-dependencyUsageThis package is really small and contains simple functions:DependsSignature:Depends(dependency: Callable[..., Any] | None = None, *, use_cache: bool = True, use_thread_pool: bool | None = None)This function is a drop-in replacement forfastapi.Dependsand it has the same signature.
The only difference is that it has an extra parameter:use_thread_pool.If you want to run a dependency in a thread pool, you can setuse_thread_pooltoTrue.fromfastapiimportFastAPIfromfastapi_dependencyimportDependsapp=FastAPI()defdependency():return"Hello World!"@app.get("/")defindex(message:str=Depends(dependency,use_thread_pool=True)):return{"message":message}If you don't setuse_thread_poolonsyncdependencies, it will raise aRuntimeError.ThreadDependsSignature:ThreadDepends(dependency: Callable[..., Any] | None = None, *, use_cache: bool = True)This function is a drop-in replacement forfastapi.Dependsand it has the same signature.
The only difference is that it will always run the dependency in a thread pool.fromfastapiimportFastAPIfromfastapi_dependencyimportThreadDependsapp=FastAPI()defdependency():return"Hello World!"@app.get("/")defindex(message:str=ThreadDepends(dependency)):return{"message":message}ThreadlessDependsSignature:ThreadlessDepends(dependency: Callable[..., Any] | None = None, *, use_cache: bool = True)This function is a drop-in replacement forfastapi.Dependsand it has the same signature.
The only difference is that it will never run the dependency in a thread pool.fromfastapiimportFastAPIfromfastapi_dependencyimportThreadlessDependsapp=FastAPI()defdependency():return"Hello World!"@app.get("/")defindex(message:str=ThreadlessDepends(dependency)):return{"message":message}SecurityThe analogous functions forfastapi.Securityare:SecurityThreadSecurityThreadlessSecurityLicenseThis project is licensed under the terms of the MIT license.
Package: fastapi-depends-ext
FastAPI depends extensionIntroductionSometimes your FastAPI dependencies have to get value from functions cannot be available on initialization. The problem is particularly acute to use class dependencies with inheritance. This project try to solve problem of modifyDependsafter application initialization.Installationpip install fastapi-depends-extTutorialDependsAttrfromtypingimportListfromfastapiimportDependsfromfastapiimportFastAPIfromfastapiimportQueryfrompydanticimportconintfromfastapi_depends_extimportDependsAttrfromfastapi_depends_extimportDependsAttrBinderclassItemsPaginated(DependsAttrBinder):_items=list(range(100))asyncdefget_page(self,page:conint(ge=1)=Query(1)):returnpageasyncdefitems(self,page:int=DependsAttr("get_page")):_slice=slice(page*10,(page+1)*10)returnself._items[_slice]classItemsSquarePaginated(ItemsPaginated):asyncdefitems(self,items:List[int]=DependsAttr("items",from_super=True)):return[i**2foriinitems]app=FastAPI()@app.get("/")defitems_list(items:List[int]=Depends(ItemsPaginated().items))->List[int]:returnitems@app.get("/square")defitems_list_square(items:List[int]=Depends(ItemsSquarePaginated().items))->List[int]:returnitemsUseDependsAttrtoDependsfrom current instance attributes. All examples useasyncio, but you can write all methods synchronous.DependsAttrsupport next properties:class variables (must containscallableobject)class methodsstatic methodsinstance methodsproperty(must returncallablethat will be used as dependency)Your class must inherit fromDependsAttrBinderand attributes must beDependsAttr.DependsAttrBinderautomatically patch all methods withDependsAttrby instance attributes.DependsAttrarguments:method_name-str, name of instance attribute to use as dependencyfrom_super-bool, on true, will use attributemethod_namefrom super class likesuper().method_name()use_cache-bool, allow to cache depends result for the same dependencies in requestDependsExtUseless(?) class created to proof of concept of patching methods and correct workFastAPIapplications.DependsExtallow you define default values of method arguments afterFastAPIendpoint has been created.Example:fromfastapiimportFastAPIfromfastapiimportQueryfromfastapi_depends_extimportDependsExtdefpagination(page:int=Query()):returnpagedepends=DependsExt(pagination)app=FastAPI()@app.on_event("startup")defsetup_depends():depends.bind(page=Query(1))@app.get("/")defget_method(value:int=depends)->int:returnvalueIs equivalent forfromfastapiimportDependsfromfastapiimportFastAPIfromfastapiimportQuerydefpagination(page:int=Query(1)):returnpageapp=FastAPI()@app.get("/")defget_method(value:int=Depends(pagination))->int:returnvalue
Package: fastapidi
FastAPI DIThis library to integratepyjectintofastapito use diInstallpipinstallfastapidiUsingfromfastapidiimportFastAPIDI,get_dependencyclassTest:deftest(self):return"123"app=FastAPIDI()app.container.add_singleton(Test,Test)@app.get("/")asyncdeftest(dependency:Test=get_dependency(Test)):returndependency.test()
Package: fastapi-di
fastapi_diExtracted the dependency injection process from fastapi.
Dependency injection by fastapi_di is only available in the async environment.RequirementPython 3.8+Installationpoetryinstallfastapi_diGetting startedDependency injection is done by decorating the function and calling do as follows.importasynciofromfastapiimportDependsfromfastapi_diimportDIdi=DI()defget_db():yield{1:{"id":1,"name":"bob","memo":""}}@di.task()asyncdefupdate_user(db=Depends(get_db),*,user_id:int,memo:str):record=db[user_id]record["memo"]=memoreturnrecordasyncdefmain():returnawaitupdate_user.do(user_id=1,memo="test")result=asyncio.run(main())print(result)# => {'id': 1, 'name': 'bob', 'memo': 'test'}}warningThis library is in the experimental stage.
Package: fastapi-discord
FastAPI Discord (OAuth)Support for "Login with Discord"/ Discord OAuth for FastAPI.InstallPIP Packagefastapi-discordExampleYou can find the Example inexpamples/fromtypingimportListfromfastapiimportDepends,FastAPIfromfastapi.responsesimportJSONResponsefromfastapi_discordimportDiscordOAuthClient,RateLimited,Unauthorized,Userfromfastapi_discord.exceptionsimportClientSessionNotInitializedfromfastapi_discord.modelsimportGuildPreviewapp=FastAPI()discord=DiscordOAuthClient("<client-id>","<client-secret>","<redirect-url>",("identify","guilds","email"))# scopes@app.on_event("startup")asyncdefon_startup():awaitdiscord.init()@app.get("/login")asyncdeflogin():return{"url":discord.oauth_login_url}@app.get("/callback")asyncdefcallback(code:str):token,refresh_token=awaitdiscord.get_access_token(code)return{"access_token":token,"refresh_token":refresh_token}@app.get("/authenticated",dependencies=[Depends(discord.requires_authorization)],response_model=bool,)asyncdefisAuthenticated(token:str=Depends(discord.get_token)):try:auth=awaitdiscord.isAuthenticated(token)returnauthexceptUnauthorized:returnFalse@app.exception_handler(Unauthorized)asyncdefunauthorized_error_handler(_,__):returnJSONResponse({"error":"Unauthorized"},status_code=401)@app.exception_handler(RateLimited)asyncdefrate_limit_error_handler(_,e:RateLimited):returnJSONResponse({"error":"RateLimited","retry":e.retry_after,"message":e.message},status_code=429,)@app.exception_handler(ClientSessionNotInitialized)asyncdefclient_session_error_handler(_,e:ClientSessionNotInitialized):print(e)returnJSONResponse({"error":"Internal Error"},status_code=500)@app.get("/user",dependencies=[Depends(discord.requires_authorization)],response_model=User)asyncdefget_user(user:User=Depends(discord.user)):returnuser@app.get("/guilds",dependencies=[Depends(discord.requires_authorization)],response_model=List[GuildPreview],)asyncdefget_guilds(guilds:List=Depends(discord.guilds)):returnguildsInspired byStarlette-DiscordQuart-Discord-OAuthQuart-DiscordThanks to @jnawk and @nwunderly
Package: fastapi-doc-http-response
Para ler este README em portugês do Brasil, cliqueaqui.FastAPI Doc HTTP ResponseFastAPI Doc HTTP Response is a Python package that facilitates the definition of standard HTTP responses for FastAPI APIs and allows for easy addition of HTTP returns to the API documentation. With this package, you can easily create standard responses for the most common HTTP status codes.FastAPI provides automatic documentation for your routes, including the expected HTTP responses for each route. By default, FastAPI only includes a few HTTP return codes in the documentation. With FastAPI Doc HTTP Response, you can easily add other HTTP return codes, ensuring that your API documentation is complete and accurate.InstallationYou can install FastAPI Doc HTTP Response using pip:pipinstallfastapi-doc-http-responseUsageTo use FastAPI Doc HTTP Response in your FastAPI application, simply import theget_responsesfunction from the package and call it with a list of HTTP status codes that you want to define:fromfastapiimportFastAPIfromfastapi_doc_http_responseimportget_responsesapp=FastAPI()@app.get("/xpto",responses=get_responses(201,400,401,403))asyncdefxpto():# ...The code above will define the following standard HTTP responses for the/xptoroute:201 Created400 Bad Request401 Unauthorized403 ForbiddenThese return codes will also be automatically added to the API documentation generated by FastAPI.Note that it is not necessary to define an HTTP return code for the 200 OK and 422 Unprocessable Entity statuses, as they are already defined by default by FastAPI.Supported HTTP Return CodesThe HTTP return codes supported by FastAPI Doc HTTP Response are:100 Continue201 Created202 Accepted203 Non-Authoritative Information204 No Content206 Partial Content207 Multi-Status208 Already Reported226 IM Used300 Multiple Choices301 Moved Permanently302 Found303 See Other304 Not Modified305 Use Proxy306 Switch Proxy307 Temporary Redirect308 Permanent Redirect400 Bad Request401 Unauthorized402 Payment Required403 Forbidden404 Not Found405 Method Not Allowed406 Not Acceptable407 Proxy Authentication Required408 Request Timeout409 Conflict410 Gone411 Length Required412 Precondition Failed413 Payload Too Large414 URI Too Long416 Range Not Satisfiable417 Expectation Failed418 I'm a teapot420 Enhance Your Calm423 Locked424 Failed Dependency425 Unordered Collection426 Upgrade Required429 Too Many Requests431 Request Header Fields Too Large444 No Response449 Retry With450 Blocked by Windows Parental Controls451 Unavailable For Legal Reasons494 Request Header Too Large500 Internal Server ErrorLicenseThis package is licensed under theMIT License. See theLICENSEfile for details.
Package: fastapi-docx
fastapi-docxAdd HTTPException responses to a FastAPI OpenAPI specDocumentation:https://saran33.github.io/fastapi-docxSource Code:https://github.com/Saran33/fastapi-docxFastAPI-docx extends the FastAPI OpenAPI spec to include all possibleHTTPExceptionor custom Exception response schemas that may be raised within path operations.The key features are:Document Exception Responses: Automatically find all possible respones within path operations, whether they originate from aHTTPExceptionraised by the endpoint function directly, in a nested function, class method, or callable class instance, or by the fastAPI dependency-injection system.Include Custom Exceptions: Optionally find and document any custom Exception types if using custom Exception handlers in your FastAPI application.Generate Exception schemas: A defaultHTTPExceptionSchemawill be added to the OpenAPI specification. The default can be modified to use any otherPydanticmodel. An additional schema for app-specific custom Exceptions can also be included.DependenciesPydantic V2: From version 1.0 of fastapi-docx, Pydantic V2 is required. For Pydantic V1 support, use fastapi-docx version 0.2.LicenseThis project is licensed under the terms of the MIT license.
Package: fastapi-dynamic-routers
fastapi_dynamic_routers is a Python library that simplifies the management of routes in FastAPI applications. It provides a clean and efficient way to register routes dynamically, enabling you to keep your codebase organized and maintainable, even as your application grows.Key Features:Simplicity: The library comes with a straightforward implementation that seamlessly integrates with your FastAPI application.Ease of Use: With just a few lines of code, you can include or exclude routes from your application, providing the flexibility you need during development.Organized Codebase: By dynamically registering routes, you can maintain a clean and well-structured codebase, even in large-scale projects.Usage Example:# main.pyfromfastapiimportFastAPIfromfastapi_dynamic_routersimportRoutersapp=FastAPI()# List of router modules to include dynamicallyURLS=['path.to.APIRouter.instantiate','...']# Initialize the dynamic routersrouters=Routers(app,URLS)()In this example, simply modify theURLSlist to add or remove routes from your FastAPI application. The dynamic routes includer will handle the registration, keeping your main file clean and focused.
Package: fastapi-easy-cache
Fastapi easy cacheAn easy to use tool for caching fastapi returnings using sqlite as backendWhen should I use fastapi-easy-cache?Returning json serializable dataUsing GET methodReturning dynamic but repeated data (like data refresh everyday)Don't have complicated requirements and too lazy to build a tool yourselfWhen should I NOT use fastapi-easy-cache?Returning not json serializable data (bytes, datetime, etc)Using POST methodReturning frequently changing data (like data refresh every second)Need advanced features (recommend:fastapi-cache)InstallationWe recommend you have fastapi installedpipinstallfastapi-easy-cacheUsageInitializingThe following code willcreate a sqlite database indbPathsotore cache in filesystemimportfastapi_easy_cachefastapi_easy_cache.apiCache(db_path='./temp/cache',in_memory=False)argsdb_path: path to sqlite database
in_memory: set up cache in memory, db_path will be database name when set to TrueUsingYou just need to add@cache(expire=20)under fastapi route decorator, add flil in expire time and it's all done.expireis counted in secondfromfastapi_easy_cacheimportcache@app.get('/testCache/{path}')@cache(expire=20)deftest(path):data=pathreturndataWith GET route with arguments, you must add request: Request to your functionfromstarlette.requestsimportRequestfromfastapi_easy_cacheimportcache@app.get('/testCacheWithArg/{path}')@cache(expire=20)deftestArg(path,arg1,arg2,request:Request):data={'path':path,'arg1':arg1,'arg2':arg2}returndata
Package: fastapi-entity-auth
FastAPI Entity AuthSource Code:https://github.com/gangstand/fastapi-entity-authDocumentation:https://gangstand.github.io/fastapi-entity-auth/FeaturesA FastAPI extension that provides support for JWT authentication (secure, easy to use, and lightweight).Access tokens and refresh tokensFreshness TokensRevoking TokensSupport for WebSocket authorizationSupport for adding custom claims to JSON Web TokensStoring tokens in cookies and CSRF protectionInstallationThe easiest way to start working with this extension with pippipinstallfastapi-entity-authIf you want to use asymmetric (public/private) key signing algorithms, include thecryptographyextra requirements.pipinstallcryptographyLicenseThis project is licensed under the terms of the MIT license.
Package: fastapienv
Your ModuleA Python module that creates a Python environment and generates FastAPI boilerplate code.This Module can even run your project as soon as it creates entire environment Make sure to use other parameters.InstallationYou can install the module using pip:UsageTo use the module, import it and call thecreateFastApiEnvironmentfunction:importfastapienv# for creating just python environment and fast api boiler plate codecreateFastApiEnvironment('{{your_prefered_env_name}}')# here is the example for all the options provided in my modulecreateFastApiEnvironment("myenv",activate_env=True,start_server=True,server_host="localhost",server_port=8000,server_reload=True)# activate_env will activate the environment after creating it.# start_server will start the fast api server using uvicorn.# server_host will be used to give the ip address or host name.# server_port will be used to change the port number at which your fast api server should run# server_reload will be used for dynamic reloading of your server if any changes happens to your files.
Package: fastapi-error-logger
FastAPI Error LoggerFastAPI Error Logger is a utility for logging API errors in a FastAPI application. It captures relevant information about the request, such as request body, path parameters, query parameters, headers, and more, and logs this information along with the error details.InstallationInstall the package using pip:pipinstallfastapi-error-loggerFunction ParametersThe log_api_error function takes the following parameters:request: FastAPI Request object.
status_code: HTTP status code for the error.
personalized_message: Optional personalized error message.
Make sure to customize the error handling in your FastAPI application according to your requirements.Usage/ExamplefromfastapiimportFastAPI,Request
fromfastapi.responsesimportJSONResponse
fromfastapi_error_logger.api_loggerimportlog_api_errorapp=FastAPI()@app.exception_handler(Exception)asyncdefhandle_api_error(request:Request,exc:Exception):# Log API error using the log_api_error functionawaitlog_api_error(request,status_code=500,personalized_message="An internal server error occurred.")# Return a custom error responsereturnJSONResponse(content={"error":"Internal Server Error"},status_code=500)@app.get("/")asyncdeftrigger_error():# Simulate an error for demonstration purposesraiseValueError("This is a simulated error.")if__name__=="__main__":importuvicornuvicorn.run(app,host="127.0.0.1",port=8000)
Package: fastapi-event
fastapi-eventfastapi-event is event dispatcher for FastAPI framework.Installationpip3installfastapi-eventUsageMake Eventfromfastapi_eventimportBaseEventclassTestEvent(BaseEvent):asyncdefrun(self,parameter=None):...InheritBaseEventand overriderun()method.fromfastapi_eventimportBaseEventclassFirstEvent(BaseEvent):ORDER=1# HERE(Optional)asyncdefrun(self,parameter=None):...classSecondEvent(BaseEvent):ORDER=2# HERE(Optional)asyncdefrun(self,parameter=None):...If you want to determine the order between events, specifyORDERin your event.Then, regardless of the order in which the events are stored, they will be executed in the order specified inORDERvariable.However,ORDERdoes not work whenrun_at_once=True.Parameter(optional)frompydanticimportBaseModelclassTestEventParameter(BaseModel):id:strpw:strIn case of need parameter, you have to inheritBaseModeland set fields.MiddlewarefromfastapiimportFastAPIfromfastapi_eventimportEventHandlerMiddlewareapp=FastAPI()app.add_middleware(EventHandlerMiddleware)EventListenerfromfastapi_eventimportEventListener@EventListener()asyncdeftest():...Set@EventListener()decorator on the function that emits the event.@EventListener(run_at_once=False)If you passrun_at_once=False, it will execute in the order in whichstore()is called. (or according to theORDERvariable defined in the event)Otherwise, it will execute throughasyncio.gather()to run at once.Store eventfromfastapi_eventimportEventListener,event_handler@EventListener()asyncdeftest():awaitevent_handler.store(event=TestEvent,parameter=TestParameter(id="hide",pw="hide"),# Optional)Store your event to handler viastore()method. (parameter is optional)An event will be emitted after the function has finished executing.
Package: fastapi-exception
FastAPI ExceptionSetup python environmentpython3-mvenvvenvActive the python environemt.venv/bin/activateInstall requirementspipinstall-rrequirements.txtHow to use# Init FastAPI# config/exception.pyfromconfig.i18nimporti18n_servicefromfastapi_exceptionimportFastApiExceptionFastApiException.init()FastApiException.init(translator_service=i18n_service)# pass translator_service if we integrate with i18n
Package: fastapi-exceptions
FastAPIexceptionsIntroductionfastapi-exceptionsis a set of standard http exceptions based on starlette exceptions.Installation>pipinstallfastapi-exceptionsUsageInstead of duplication of exceptions codes and their details for standard cases:fromfastapiimportHTTPExceptionfromstarletteimportstatus# some app logic ...raiseHTTPException(status_code=status.HTTP_401_UNAUTHORIZED,detail='Authentication credentials were not provided',)you can simply import exceptions and use wherever you need:fromfastapi_exceptions.exceptionsimportNotAuthenticated# some app logic ...raiseNotAuthenticated()and, of course, modify details if needed:# some app logic ...raiseNotAuthenticated(detail='No authentication header')
Package: fastapi-exceptionshandler
Routes Manager for FastAPIStandardize and handle exceptions inFastAPImore elegantly.Installation$pipinstallfastapi-exceptionshandlerExampleYou can automatically handleallexceptions usingfastapi-routesmanager.
Simply register theAPIExceptionManagerto theRouteManagersRegistry.Don't forget to use theManagedAPIRouterNote:by default Validation errors are not captured. To do so, useAPIExceptionManager(capture_validation=True)instead.fromfastapiimportFastAPIfromfastapi_routesmanagerimportRouteManagersRegistry,ManagedAPIRouterfromfastapi_exceptionshandlerimportAPIExceptionManagerRouteManagersRegistry.register_route_manager(APIExceptionManager)# Register managerapp=FastAPI()router=ManagedAPIRouter()@router.get("/")# Use router instead of appdefread_root():return1/0app.include_router(router)# Include the router to the appOr you can handle exceptions manually...fromfastapiimportFastAPIfromfastapi_exceptionshandlerimportAPIExceptionHandlerapp=FastAPI()@app.get("/")defread_root():try:return1/0exceptExceptionasexc:returnawaitAPIExceptionHandler.unhandled(exc)Create a custom exception class and error code, thenRun it$uvicornmain:app--reloadCheck itBrowse tohttp://127.0.0.1:8000you should see this json:{"errorCode": "InternalError", "message": "Internal Server Error"}Creating custom exceptionsIn order to create a custom exception you need to extendAPIExceptionand create anEnumclass.Note:if you want to captureonlyAPIExceptionthen useAPIExceptionManager(capture_unhandled=False)fromenumimportEnumfromfastapiimportFastAPIfromfastapi_routesmanagerimportRouteManagersRegistry,ManagedAPIRouterfromfastapi_exceptionshandlerimportAPIExceptionManager,APIExceptionRouteManagersRegistry.register_route_manager(APIExceptionManager)# Register managerapp=FastAPI()router=ManagedAPIRouter()classCustomException(APIException):status_code=401classErrorCode(Enum):CustomExceptionCode="Custom Exception Message"@router.get("/")# Use router instead of appdefread_root():raiseCustomException(CustomException.ErrorCode.CustomExceptionCode)app.include_router(router)# Include the router to the appThen you should get a401response with this body{"errorCode": "CustomExceptionCode", "message": "Custom Exception Message"}Or you can handle exceptions manually...@app.get("/")defread_root():try:raiseCustomException(CustomException.ErrorCode.CustomExceptionCode)exceptAPIExceptionasexc:returnawaitAPIExceptionHandler.handled(exc)exceptExceptionasexc:# Handle all exceptionsreturnawaitAPIExceptionHandler.unhandled(exc)Note:TheErrorCodeclass doesn't need to be insideCustomExceptionand can be shared with another exceptions as well.