Saravanan666/pypi-org huggingface dataset:
Package: fastapi-utilities
🎨⚡️🔥 Reusable Utilities for FastAPISource Code:https://github.com/priyanshu-panwar/fastapi-utilitiesInspired From:dmontagu/fastapi-utils[🔥New🔥] FastAPI CLI ToolWith our CLI Tool you can get a skeleton project built to get you started with the code.How to useUsingpoetry:poetry run cli initUsingpip:python3 -m cli initFeaturesThis package includes a number of utilities to help reduce boilerplate and reuse common functionality across projects:🕒Repeated Tasks: Easily trigger periodic tasks on server startup usingrepeat_every.from fastapi_utilities import repeat_every

@router.on_event('startup')
@repeat_every(seconds=3)
async def print_hello():

    print("hello")👷Cron Jobs: Easily trigger cron jobs on server startup usingrepeat_atby providing a cron expression.from fastapi_utilities import repeat_at

@router.on_event("startup")
@repeat_at(cron="*/2 * * * *") #every 2nd minute
async def hey():
    print("hey")🕒Timer Middleware: Add a middleware to the FastAPI app that logs the time taken to process a request. Optionally, also logs the average response time.The average response time is reset after every (reset_after)100,000 requests.import asyncio
from fastapi import FastAPI, Request
from fastapi_utilities import add_timer_middleware

app = FastAPI()
add_timer_middleware(app, show_avg=True)


@app.get("/")
def read_root():
    return {"message": "Hello, World!"}Response Logs:INFO:     (fastapi-utilities) "GET - /" :: Time Taken :: 0.97 ms
INFO:     :: Average Response Time :: 0.97 msCached Sessions: Now use cached sessions along with context manager instead ofget_db.from fastapi import FastAPI
from .db import Base, engine
from fastapi_utilities import FastAPISessionMaker, repeat_every
from .models import User
import random

app = FastAPI()
Base.metadata.create_all(bind=engine)

session_maker = FastAPISessionMaker("sqlite:///db.sqlite3")


@app.on_event("startup")
@repeat_every(seconds=5, raise_exceptions=True)
async def startup():
    print("Starting up...")
    with session_maker.context_session() as session:
        x = User(id=random.randint(0, 10000))
        session.add(x)
    print("Startup complete!")RequirementsThis package is intended for use with any recent version of FastAPI and Python 3.7+.Installationpipinstallfastapi-utilitiesLicenseThis project is licensed under the terms of the MIT license.
Package: fastapi-utils
Reusable utilities for FastAPIDocumentation:https://fastapi-utils.davidmontague.xyzSource Code:https://github.com/dmontagu/fastapi-utilsFastAPIis a modern, fast web framework for building APIs with Python 3.6+.But if you're here, you probably already knew that!FeaturesThis package includes a number of utilities to help reduce boilerplate and reuse common functionality across projects:Class Based Views: Stop repeating the same dependencies over and over in the signature of related endpoints.Response-Model Inferring Router: Let FastAPI infer theresponse_modelto use based on your return type annotation.Repeated Tasks: Easily trigger periodic tasks on server startupTiming Middleware: Log basic timing information for every requestSQLAlchemy Sessions: TheFastAPISessionMakerclass provides an easily-customized SQLAlchemy Session dependencyOpenAPI Spec Simplification: Simplify your OpenAPI Operation IDs for cleaner output from OpenAPI GeneratorIt also adds a variety of more basic utilities that are useful across a wide variety of projects:APIModel: A reusablepydantic.BaseModel-derived base class with useful defaultsAPISettings: A subclass ofpydantic.BaseSettingsthat makes it easy to configure FastAPI through environment variablesString-Valued Enums: TheStrEnumandCamelStrEnumclasses make string-valued enums easier to maintainCamelCase Conversions: Convenience functions for converting strings fromsnake_casetocamelCaseorPascalCaseand backGUID Type: The provided GUID type makes it easy to use UUIDs as the primary keys for your database tablesSee thedocsfor more details and examples.RequirementsThis package is intended for use with any recent version of FastAPI (depending onpydantic>=1.0), and Python 3.6+.Installationpipinstallfastapi-utilsLicenseThis project is licensed under the terms of the MIT license.
Package: fastapi-utils-evo
Reusable utilities for FastAPIDocumentation:https://fastapi-utils.davidmontague.xyzSource Code:https://github.com/dmontagu/fastapi-utilsThis is a forked version of fatapi-utils developped by David Montagu.FeaturesThis package includes a number of utilities to help reduce boilerplate and reuse common functionality across projects:Class Based Views: Stop repeating the same dependencies over and over in the signature of related endpoints.Response-Model Inferring Router: Let FastAPI infer theresponse_modelto use based on your return type annotation.Repeated Tasks: Easily trigger periodic tasks on server startupTiming Middleware: Log basic timing information for every requestSQLAlchemy Sessions: TheFastAPISessionMakerclass provides an easily-customized SQLAlchemy Session dependencyOpenAPI Spec Simplification: Simplify your OpenAPI Operation IDs for cleaner output from OpenAPI GeneratorIt also adds a variety of more basic utilities that are useful across a wide variety of projects:APIModel: A reusablepydantic.BaseModel-derived base class with useful defaultsAPISettings: A subclass ofpydantic.BaseSettingsthat makes it easy to configure FastAPI through environment variablesString-Valued Enums: TheStrEnumandCamelStrEnumclasses make string-valued enums easier to maintainCamelCase Conversions: Convenience functions for converting strings fromsnake_casetocamelCaseorPascalCaseand backGUID Type: The provided GUID type makes it easy to use UUIDs as the primary keys for your database tablesSee thedocsfor more details and examples.RequirementsThis package is intended for use with any recent version of FastAPI (depending onpydantic>=1.0), and Python 3.7+.Installationpipinstallfastapi-utilsLicenseThis project is licensed under the terms of the MIT license.
Package: fastapi-utils-sqlalch2
Reusable utilities for FastAPIDocumentation:https://fastapi-utils.davidmontague.xyzSource Code:https://github.com/dmontagu/fastapi-utilsFastAPIis a modern, fast web framework for building APIs with Python 3.7+.But if you're here, you probably already knew that!FeaturesThis package includes a number of utilities to help reduce boilerplate and reuse common functionality across projects:Class Based Views: Stop repeating the same dependencies over and over in the signature of related endpoints.Response-Model Inferring Router: Let FastAPI infer theresponse_modelto use based on your return type annotation.Repeated Tasks: Easily trigger periodic tasks on server startupTiming Middleware: Log basic timing information for every requestSQLAlchemy Sessions: TheFastAPISessionMakerclass provides an easily-customized SQLAlchemy Session dependencyOpenAPI Spec Simplification: Simplify your OpenAPI Operation IDs for cleaner output from OpenAPI GeneratorIt also adds a variety of more basic utilities that are useful across a wide variety of projects:APIModel: A reusablepydantic.BaseModel-derived base class with useful defaultsAPISettings: A subclass ofpydantic.BaseSettingsthat makes it easy to configure FastAPI through environment variablesString-Valued Enums: TheStrEnumandCamelStrEnumclasses make string-valued enums easier to maintainCamelCase Conversions: Convenience functions for converting strings fromsnake_casetocamelCaseorPascalCaseand backGUID Type: The provided GUID type makes it easy to use UUIDs as the primary keys for your database tablesSee thedocsfor more details and examples.RequirementsThis package is intended for use with any recent version of FastAPI (depending onpydantic>=1.0), and Python 3.7+.Installationpipinstallfastapi-utilsLicenseThis project is licensed under the terms of the MIT license.
Package: fastapi-validation
FastAPI ValidationFastAPI Validation support both SQLAlchemy for sql database and BeanieODM for nosql Database.
To use the @Exists and @Unique decorator we need to set global-variable for the database_type
Check the sample code belowFor SQL Database using SQLAlchemy as ORMfromfastapi_validationimportDatabaseTypeEnumengine=create_engine(SQLALCHEMY_DATABASE_URL,echo=False,pool_size=50,max_overflow=100)global_db_session:Session=sessionmaker(autoflush=False,autobegin=True,bind=engine,join_transaction_mode='rollback_only')()defrun_with_global_session(callback):try:returncallback(global_db_session)exceptExceptionase:global_db_session.rollback()raiseeGlobalVariable.set('run_with_global_session',run_with_global_session)GlobalVariable.set('database_type',DatabaseTypeEnum.SQL)For Nosql Database using Beanie as ODMGlobalVariable.set('database_type',DatabaseTypeEnum.NOSQL)# We can skip this line because the defautl database_type is SQL
Package: fastapi-validation-i18n
error message with i18n support in FastAPI{"errors":[{"loc":["body","string"],"msg":"確保此值最多有 10 個字符","type":"value_error.any_str.max_length","ctx":{"limit_value":10}},{"loc":["body","nested","body"],"msg":"確保此值最多有 2 個字符","type":"value_error.any_str.max_length","ctx":{"limit_value":2}},{"loc":["body","nested","inner","inner_body"],"msg":"確保此值最多包含 2 個項目","type":"value_error.list.max_items","ctx":{"limit_value":2}},{"loc":["body","nested","inner","cat"],"msg":"鑑別器 'color' 和值 'ccc' 不匹配（允許的值: 'black', 'white'）","type":"value_error.discriminated_union.invalid_discriminator","ctx":{"discriminator_key":"color","discriminator_value":"ccc","allowed_values":"'black', 'white'"}}]}Attentionsupport pydantic v1 only now(2023/08/16)built-in locales arezh-TW, en-US, ja-JP, you can change the locales by yourselfHow to runpublish locales to your app path# default to "locale" in your project pathpoetryrunpublish-locale<your-path>[--locale]add middleware and exception handler to your FastAPI appfromfastapiimportFastAPIfromfastapi_validation_i18nimportI18nMiddleware,i18n_exception_handlerfromfastapi.exceptionsimportRequestValidationErrorapp=FastAPI()app.add_middleware(I18nMiddleware,locale_path='your-publish-path')app.add_exception_handler(RequestValidationError,i18n_exception_handler)start use itthere's 3 way to set localesetaccept-languageheader to your requestset an API withlocalein pathsetlocalequery parameter to your requestyou can see theexamplefor more detail
Package: fastapi-vers
fastapi_versAPI versioning concept for FastAPIpipinstallfastapi_versfromfastapiimportFastAPIfromfastapi_versimportAPIapi=API("0.3",app_kwds={"all":{"title":"Versioned API","version":"0.0"},"0.1":{"version":"0.1"},"0.2":{"version":"0.2"},})@api.app.get("/")asyncdefroot():return"Hello World!"@api.app.get("/foo")@api.version(["0.1-0.2"])asyncdeffoo():return"This endpoint available only for 0.1, 0.2 api versions"@api.app.get("/bar")@api.version(["0.1-latest"])asyncdefbar():return"This endpoint available for 0.1, 0.2, 0.3 api versions"app=FastAPI()app.mount("/api",api.get_versioned_app())"""http://localhost:8000/api/latesthttp://localhost:8000/api/0.1/foohttp://localhost:8000/api/0.2/foohttp://localhost:8000/api/0.1/barhttp://localhost:8000/api/0.2/barhttp://localhost:8000/api/0.3/bar"""
Package: fastapi-versioning
fastapi-versioningapi versioning for fastapi web applicationsInstallationpip install fastapi-versioningExamplesfromfastapiimportFastAPIfromfastapi_versioningimportVersionedFastAPI,versionapp=FastAPI(title="My App")@app.get("/greet")@version(1,0)defgreet_with_hello():return"Hello"@app.get("/greet")@version(1,1)defgreet_with_hi():return"Hi"app=VersionedFastAPI(app)this will generate two endpoints:/v1_0/greet
/v1_1/greetas well as:/docs
/v1_0/docs
/v1_1/docs
/v1_0/openapi.json
/v1_1/openapi.jsonThere's also the possibility of adding a set of additional endpoints that
redirect the most recent API version. To do that make the argumentenable_latesttrue:app=VersionedFastAPI(app,enable_latest=True)this will generate the following additional endpoints:/latest/greet
/latest/docs
/latest/openapi.jsonIn this example,/latestendpoints will reflect the same data as/v1.1.Try it out:pipinstallpipenv
pipenvinstall--dev
pipenvrunuvicornexample.annotation.app:app# pipenv run uvicorn example.folder_name.app:appUsage without minor versionfromfastapiimportFastAPIfromfastapi_versioningimportVersionedFastAPI,versionapp=FastAPI(title='My App')@app.get('/greet')@version(1)defgreet():return'Hello'@app.get('/greet')@version(2)defgreet():return'Hi'app=VersionedFastAPI(app,version_format='{major}',prefix_format='/v{major}')this will generate two endpoints:/v1/greet
/v2/greetas well as:/docs
/v1/docs
/v2/docs
/v1/openapi.json
/v2/openapi.jsonExtra FastAPI constructor argumentsIt's important to note that only thetitlefrom the original FastAPI will be
provided to the VersionedAPI app. If you have any middleware, event handlers
etc these arguments will also need to be provided to the VersionedAPI function
call, as in the example belowfromfastapiimportFastAPI,Requestfromfastapi_versioningimportVersionedFastAPI,versionfromstarlette.middlewareimportMiddlewarefromstarlette.middleware.sessionsimportSessionMiddlewareapp=FastAPI(title='My App',description='Greet uses with a nice message',middleware=[Middleware(SessionMiddleware,secret_key='mysecretkey')])@app.get('/greet')@version(1)defgreet(request:Request):request.session['last_version_used']=1return'Hello'@app.get('/greet')@version(2)defgreet(request:Request):request.session['last_version_used']=2return'Hi'@app.get('/version')deflast_version(request:Request):returnf'Your last greeting was sent from version{request.session["last_version_used"]}'app=VersionedFastAPI(app,version_format='{major}',prefix_format='/v{major}',description='Greet users with a nice message',middleware=[Middleware(SessionMiddleware,secret_key='mysecretkey')])
Package: fastapi-view
fastapi-viewA jinja2 view template helping function for FastAPI.Features:Simply setting and use function to return Jinja2TemplatesInstallationpipinstallfastapi-viewUsageConfiguringfastapi-viewjinja2 templates directory pathfromfastapi_viewimportview# setting root view templates directory pathview.views_directory="/your/jinja2/template/directory/path"Use view()fromfastapiimportFastAPIfromfastapi.requestsimportRequestfromfastapi_view.middlewareimportViewRequestMiddlewarefromfastapi_viewimportviewapp=FastAPI()app.add_middleware(ViewRequestMiddleware)@app.get("/")defindex():returnview("index",{"foo":"bar"})Use inertia renderfromfastapiimportFastAPIfromfastapi.requestsimportRequestfromfastapi_view.middlewareimportViewRequestMiddlewarefromfastapi_viewimportinertiaapp=FastAPI()app.add_middleware(ViewRequestMiddleware)@app.get("/inertia/page")definertia_index():returninertia.render("Index",props={"foo":"bar"})
Package: fastapi-views
fastapi-viewsFastAPI Class Views and utilitiesVersion: 0.1.1Documentation:https://performancemedia.github.io/fastapi-views/Repository:https://github.com/performancemedia/fastapi-viewsInstallationpipinstallfastapi-viewsUsagefromtypingimportOptionalfromuuidimportUUIDfromfastapi_viewsimportSerializer,ViewRouterfromfastapi_views.views.viewsetsimportAsyncAPIViewSetclassItemSchema(Serializer):id:UUIDname:strprice:intitems={}classMyViewSet(AsyncAPIViewSet):api_component_name="Item"serializer=ItemSchemaasyncdeflist(self):returnlist(items.values())asyncdefcreate(self,item:ItemSchema)->ItemSchema:items[item.id]=itemreturnitemasyncdefretrieve(self,id:UUID)->Optional[ItemSchema]:returnitems.get(id)asyncdefupdate(self,item:ItemSchema):items[item.id]=itemasyncdefdestroy(self,id:UUID)->None:items.pop(id,None)router=ViewRouter(prefix="/items")router.register_view(MyViewSet)# in app.py# app.include_router(router)FeaturesClass Based ViewsAPIViewsGenericViewsViewSetsBoth async and sync function supportNo dependencies on ORMOpenapi id simplification'Smart' and fast serialization using orjsonHttp Problem Details implementationAutomatic prometheus metrics exporterPluggable healthcheck helper
Package: fastapi-vite
fastapi-viteIntegration for FastAPI and Vite JSwhat?This package is designed to make working with javascript assets easier.fastapi-vite enables the jinja filters required to render asset URLs to jinja templatesInspired bydjango-vite@ [https://github.com/MrBin99/django-vite]installationInstall using pippipinstallfastapi-viteUsageConfigure Jinja templating for FastAPIimportfastapi_vitetemplates=Jinja2Templates(directory='templates')templates.env.globals['vite_hmr_client']=fastapi_vite.vite_hmr_clienttemplates.env.globals['vite_asset']=fastapi_vite.vite_assetConfigure ViteHere is an example used to test this pluginimport{defineConfig}from'vite'importreactRefreshfrom'@vitejs/plugin-react-refresh'constDotenv=require("dotenv");importpathfrom"path";Dotenv.config({path:path.join(__dirname,".env")});constSTATIC_URL=process.env.STATIC_URL;// https://vitejs.dev/config/exportdefaultdefineConfig({base:`${STATIC_URL}`,clearScreen:false,plugins:[reactRefresh(),],build:{target:"esnext",outDir:"./static/",emptyOutDir:true,assetsDir:"",manifest:true,rollupOptions:{input:"./assets/javascript/main.tsx"},},root:".",// You can change the root path as you wish})Configure Static AssetsConfigure Templates*render_vite_hmr no-op when in production.{{ render_vite_hmr_client() }}<scripttype="text/javascript"defersrc="{{ asset_url('javascript/main.tsx') }}"></script>
Package: fastapi-walletauth
FastAPI Wallet Authenticationfastapi-walletauth provides a simple way to authenticate users in FastAPI applications using a wallet.
It currently supports Ethereum and Solana wallets/signatures.Installationpipinstallfastapi-walletauthUsageAdding the authentication endpoints is as simple as importing theauthorization_routesfromfastapi_walletauth:fromfastapiimportFastAPIfromfastapi_walletauthimportauthorization_routesapp=FastAPI()app.include_router(authorization_routes)This will add the following endpoints to your application:POST /authentication/challenge: Returns a challenge for the user to signPOST /authentication/solve: Returns a Bearer token if the signature is validPOST /authentication/logout: Invalidates the current tokenPOST /authentication/refresh: Returns a new token if the current token is validYou can then useWalletAuthDepto protect your endpoints:fromfastapiimportFastAPIfromfastapi_walletauthimportWalletAuthDep,authorization_routesapp=FastAPI()app.include_router(authorization_routes)@app.get("/protected")defprotected(wa:WalletAuthDep):returnwa.addressSigning the challengeThe challenge is a serialized JSON object containing the following fields:message={"chain":"ETH","address":"0x...","app":"myapp","time":1688819493.8691394}PLEASE NOTE: Theappfield needs to be set to the name of your application. This is used to prevent replay attacks.exportFASTAPI_WALLETAUTH_APP=myappThe signature format depends on the wallet type and is specified in thechainfield. This signature is then sent to the/authentication/solveendpoint to obtain a Bearer token.LiabilityThis software is provided "as is" and "with all faults." I make no representations or warranties of any kind concerning
the safety, suitability, inaccuracies, typographical errors, or other harmful components of this
software. There are inherent dangers in the use of any software, especially cryptographic implementations. You are solely
responsible for determining whether this software is compatible with your machine and other software installed on your
computer. You are also solely responsible for the choice of a wallet and the security of your private keys. You
acknowledge and agree to waive any liability claim against me from any loss or damage of any kind arising out of or in
connection with your use of this software.
Package: fastapi-web-session
fastapi-web-sessionWeb sessions forFastAPI.Easily store and retrieve session data and still gain support for active connection registration. 🤩InstallingInstall and update using pip:pipinstallfastapi-web-sessionLinksLicense:Apache LicenseCode:https://github.com/amenezes/fastapi-web-sessionIssue tracker:https://github.com/amenezes/fastapi-web-session/issuesDocs:https://fastapi-web-session.amenezes.net
Package: fastapi-wraps
fastapi-wrapsfunctools.wrapsfor endpoints decorators in FastAPI.It updates the signature of the wrapped function
with parameters defined in the decorator's wrapper function.
All parameters of the wrapper function should have defaults assigned.It's advised to name the parameter with some prefix, for example__,
to avoid any name conflicts in decorated functions.To use the Request object in the decorator's wrapper function
use__request: Request = Depends(get_request)Installationpipinstallfastapi-wrapsExampledefsave_request(endpoint:Callable[P,Awaitable[RT]],)->Callable[P,Awaitable[RT]]:@fastapi_wraps(endpoint)asyncdefwrapper(*args:Any,__request:Request=Depends(get_request),__db:Db=Depends(get_db),**kwargs:Any,)->RT:__db.save(__request)response=awaitendpoint(*args,**kwargs)returnresponsereturnwrapperapp=FastAPI()@app.get("/")@save_requestasyncdefhello()->str:return"hello"Why?To use dependencies provided by FastAPI's DI framework all dependencies have to be declared in the signature of the endpoint.
Hence, the decorator cannot simply usefunctools.wraps, asfunctools.wrapsmaintains the signature of the wrapped function. Thefastapi_wrapsdecorator takes updates the resulting signature by merging parameters from thewrapperand thewrappedfunction.
Package: fastapix
FastAPI X:warning:This project is still under development.FeaturesThe most important feature are the project and component generators.Show environment variables the project is reading -fastapix env.Show application routes. -fastapix routes.Show application middlewares. -fastapix middlewares.Project generator -fastapix new app.Generate a new project.Generate Dockerfile.Component generator -fastapix new component.Generate a new component based on the current project structure.Plugin system. People will be able to create their own commands.Embed Flake8-FastAPI -fastapix lint.Embed formatter -fastapix format.Show information about the project -fastapix info.InstallationpipinstallfastapixLicenseThis project is licensed under the terms of the MIT license.
Package: fastapi-xml
FastAPI::XMLpip install fastapi-xmlA bridge betweenFastAPIandxsdata. Together,
fastapi handles xml data structures using dataclasses generated by xsdata. Whilst, fastapi handles the api calls, xsdata
covers xml serialisation and deserialization. In addition, openapi support works as well.fromdataclassesimportdataclass,fieldfromfastapiimportFastAPIfromfastapi_xmlimportadd_openapi_extensionfromfastapi_xmlimportNonJsonRoutefromfastapi_xmlimportXmlAppResponsefromfastapi_xmlimportXmlBody@dataclassclassHelloWorld:message:str=field(metadata={"example":"Foo","name":"Message","type":"Element"})app=FastAPI(title="FastAPI::XML",default_response_class=XmlAppResponse)app.router.route_class=NonJsonRouteadd_openapi_extension(app)@app.post("/echo",response_model=HelloWorld,tags=["Example"])defecho(x:HelloWorld=XmlBody())->HelloWorld:x.message+=" For ever!"returnxif__name__=="__main__":importuvicornuvicorn.run(app,host="127.0.0.1",port=8000)