Saravanan666/pypi-org huggingface dataset:
Package: fastapi-explosion-extras
FastAPI ExtrasThis library is a collection of utilities for running FastAPI applications at Explosion AI.HttpizeErrorsAPIRouterThis custom router's main functionality is to handle errors per route instead of through a global exception handler by adding thehttpize_errorskeyword argument to the FastAPI route declaration. This allows each route to return normal informative Python errors instead of the FastAPIHTTPExceptionclass to get valid responses.It also times each request and sets theX-Response-Timeheader on the ResponseAn example route@router.get("/testing",httpize_errors={ValueError:400})deftest_route(i:int):ifi<1:raiseValueError("Bad Input Data")return{"i":i}If the ValueError is raised, this custom router knows to return a Response with a status code of 400 (Bad Request) and the message provided to theValueErrorUsageFastAPI doesn't have built-in support for overriding the app Router, however this is required since we add a new keyword argument to the route declaration. FastAPI doesn't pass**kwargsforward, it only passes explict named keyword arguments.To get around this, we need to overwrite the app router manually and refresh the routes after all of them have been included in the main app. This looks like:fromfastapiimportFastAPIfromfastapi_extrasimportHttpizeErrorsAPIRouter,init_appimportuvicorn# API Router (could be in another module)api_router=HttpizeErrorsAPIRouter(tags=["tests"])@api_router.get("/testing",httpize_errors={ValueError:400})deftest_route(i:int):ifi<1:raiseValueError("Bad Input Data")return{"i":i}# Main app definitionapp=FastAPI()# Overwrite App Router to use the custom HttpizeErrorsAPIRouterapp.router=HttpizeErrorsAPIRouter.from_app(app)# Include API Router from aboveapp.include_router(api_router)# Refresh the App (this rebuilds the Starlette Middleware Stack)init_app(app)uvicorn.run(app)
Package: fastapi-extend
1、installpip install fastapi_extend2、usefromsqlalchemyimportColumn,String,Integer,Float,DateTimefromsqlalchemy.ext.declarativeimportdeclarative_base# ORM(对象关系映射)的基类Base=declarative_base()fromfastapi_extend.serializerimportSerializerclassTrade(Base):__tablename__="trade"id=Column(Integer,primary_key=True)account=Column(String(20),default=None,nullable=False)trade_datetime=Column(DateTime)volume=Column(Float,default=None,nullable=False)price=Column(Float,default=0,nullable=False)order_id=Column(String(20))classTradeSer(Serializer):account:strtrade_datetime=Column(DateTime)volume:floatprice:floatorder_id:str1）、Paginationfromfastapi_extend.pagenatorimportPageNumberPaginationfrompydanticimportvalidatorfromsqlalchemyimportColumn,String,Integer,Float,DateTimepaginator=PageNumberPagination(params,Trade,TradeSer,exclude={"start","end"},)query=paginator.get_queryset()ifparams.start:query=query.where(Trade.trade_datetime>=params.start)ifparams.end:query=query.where(Trade.trade_datetime<=params.end)data=awaitpaginator.paginate_query(query,session)2)、Serializerfromfastapi_extend.serializerimportSerializerfrompydanticimportvalidatorclassTradeSer(Serializer):account:strvolume:floatprice:floatorder_id:str@validator("price")defprice_add(cls,v):returnv+10data_ser=TradeSer.dump(result.scalars(),many=True)
Package: fastapi-extended-route
Opinionated FastAPI Extended RouteA small utility for FastAPI/Starlette Route and Request to address the following:Request.url_fordoesn't allow addingquery parametersat the moment.URLobjects can't have multiple keys like/?key=value&key=anothervalue.With the following changes:MakeRequest.url_forto match path parameters and use unmatched params for query parameters.Provide a customRoutewhich has a newRequesttype.AllowURLobject to add multiple keys inquery params....Example:fromfastapiimportFastAPIfromfastapi.responsesimportPlainTextResponsefromfastapi_extended_routeimportRequest,Routedefindex(request:Request)->PlainTextResponse:url=request.url_for("index",key=value)# url == "http://testserver/?key=value"returnPlainTextResponse(url)app=FastAPI(routes=[Route("/",index,name="index")],)As you can see the only change is to useRoutefrom the package and
the newRequestobject will have a customizedurl_formethod which
handles both path parameters and query parameters.If/when these options are available in Starlette/FastAPI, this is no longer needed.
Package: fastapi-fancy-exceptions
FastAPI Fancy ExceptionsSample codeimportuvicornfromfastapiimportFastAPIfromstarletteimportstatusfromstarlette.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-fastcli
Fastapi CLI在使用 FastAPI 前，我个人使用 Flask 居多，比较喜欢 Flask 的 CLI，使用起来比较方便，这个项目就是解决 FastAPI 没有 CLI 的问题使用它自动加载项目中已有的 Typer 实例使用前假设我们的 CLI 代码在下面的路径app/cli/init.pyimporttyperapp=typer.Typer()@app.command()defversion():return"1.0.0"为了方便执行，我们需要在项目根目录新增一个入口文件如cli.py并添加下面的内容fromapp.cliimportappif__name__==__main__:app()最后执行pythoncli.py--help使用后使用 fastcli 由于 app.cli:app 在默认路径下，因此会自动加载，我们只需要运行下面的命令即可fastcli--help安装使用安装pipinstallfastapi-fastcli# 安装TAB自动补全fastcli--install-completion查看路由列表fastcliroutes启动 FastAPI 应用fastclirun在运行时所在的目录 查找下列路径- app.commands:app
- app.cli:app
- cli:app
- main:cli
- manage:cli
- app:cli你也通过环境变量TYPER_APP指定功能查看路由启动 FastAPI 应用（uvicron）
Package: fastapi-featureflags
FastAPI Feature FlagsVery simple implementation of feature flags for FastAPI.Minimum configuration requiredNo unnecessary dependenciesDoes its jobInstallingTo install the package from pip, first run:pipinstallfastapi-featureflagsUsageA simple example of feature flags:from fastapi_featureflags import FeatureFlags, feature_flag, feature_enabled

FeatureFlags(conf_from_url="https://pastebin.com/raw/4Ai3j2DC")
print("Enabled Features:", FeatureFlags.get_features())


@feature_flag("web_1")
def web_1_enabled():
    print("Feature Should be enabled: web_1")

web_1_enabled()

if feature_enabled("web_2"):
    print("Feature Should be disabled: web_2")You can get FF (feature flags) from aFile,URL,Dictionary or ENV Variables:FeatureFlags.load_conf_from_url("https://pastebin.com/raw/4Ai3j2DC")
FeatureFlags.load_conf_from_json("tests/features.json")
FeatureFlags.load_conf_from_dict({"web_1": True, "web_2": False})

FeatureFlags.reload_feature_flags()There is also a handler that recognizes if the "@feature_flag" wrapper is used and the flag is not registered in the config.
This way you can also use FF at runtime. Defaults to False, so it's safer if you forget the feature flag in the code.Functionget_featuresreturns a list of all registered FFYou can enable or disable functions on the fly withenable_featureorenable_featureWhen needed you can reload all feature flags withreload_feature_flags,
this is useful when you want to read and change features from URL.
All unregistered or on-the-fly created FF, that are not in the configuration will be omitted.For non-production testing, a router is available,
so you can see the paths in swagger-ui docs.
Useinclude_in_schema=Falsewhen defining the router for public deploymentsfrom fastapi_featureflags import router as ff_router
app.include_router(ff_router, prefix="/ff", tags=["FeatureFlags"])Contributing and Code of ConductContributing to fastapi-featureflagsAs an open source project, fastapi-featureflags welcomes contributions of many forms.Please read and follow ourContributing to fastapi-featureflagsCode of ConductAs a contributor, you can help us keep the fastapi-featureflags project open and inclusive.Please read and follow ourCode of Conduct
Package: fastapi-filter
FastAPI filterCompatibilityRequired:Python: >=3.8, <4.0Fastapi: >=0.100, <1.0Pydantic: >=2.0.0, <3.0.0OptionalMongoEngine: >=0.24.1, <0.28.0SQLAlchemy: >=1.4.36, <2.1.0Installation# Basic versionpipinstallfastapi-filter# With backendspipinstallfastapi-filter[all]# More selectivepipinstallfastapi-filter[sqlalchemy]pipinstallfastapi-filter[mongoengine]DocumentationPlease visit:https://fastapi-filter.netlify.app/ExamplesYou can play with examples:pipinstallpoetry
poetryinstall
pythonexamples/fastapi_filter_sqlalchemy.pyFilterhttps://user-images.githubusercontent.com/950449/176737541-0e36b72f-38e2-4368-abfa-8bbc0c82e8ae.mp4Order byhttps://user-images.githubusercontent.com/950449/176747056-ea82d6b9-cb3b-43eb-aec7-96ba0bc79e8b.mp4ContributionYou can run tests withpytest.pipinstallpoetry
poetryinstall--extrasall
pytest
Package: fastapi-filters
Introductionfastapi-filtersis a library that provides filtering/sorting feature forFastAPIapplications.Installationpipinstallfastapi-filtersQuickstartTo create filters you need either define them manually usingcreate_filtersfunction or automatically generate them
based on model usingcreate_filters_from_modelfunction.fromtypingimportListfromfastapiimportFastAPI,DependsfrompydanticimportBaseModel,Field# import all you need from fastapi-filtersfromfastapi_filtersimportcreate_filters,create_filters_from_model,FilterValuesapp=FastAPI()# create FastAPI appclassUserOut(BaseModel):# define your modelname:str=Field(...,example="Steve")surname:str=Field(...,example="Rogers")age:int=Field(...,example=102)@app.get("/users")asyncdefget_users_manual_filters(# manually define filtersfilters:FilterValues=Depends(create_filters(name=str,surname=str,age=int)),)->List[UserOut]:pass@app.get("/users")asyncdefget_users_auto_filters(# or automatically generate filters from pydantic modelfilters:FilterValues=Depends(create_filters_from_model(UserOut)),)->List[UserOut]:passCurrently,fastapi-filterssupportsSQLAlchemyintegration.fromfastapi_filters.ext.sqlalchemyimportapply_filters@app.get("/users")asyncdefget_users(db:AsyncSession=Depends(get_db),filters:FilterValues=Depends(create_filters_from_model(UserOut)),)->List[UserOut]:query=apply_filters(select(UserOut),filters)return(awaitdb.scalars(query)).all()
Package: fastapi-firebase
FastAPI Firebase integrationThis package contains some utilities to work with firebase in a FastAPI project.Example usageFor example, if you want to send the firebase app name:fromfastapiimportFastAPI,Dependsfromfastapi_firebaseimportsetup_firebase,firebase_appfromfirebase_admin.appimportAppapp=FastAPI()setup_firebase(app)@app.get("/appname")defget_appname(fb_app:App=Depends(firebase_app)):returnfb_app.nameSee thesetup_firebasedocumentation for how to initialize.
Package: fastapi-flask-auth
fastapi-flask-authLightweight FastAPI dependencies and authenticator that uses Flask session cookies for access control.Why would you want to base your FastAPI application's authentication on session cookies created by a Flask application?Well, imagine that you have a Flask application that handles authentication (probably withflask-login) among other tasks and you'd like to use FastAPI for some new routes, or maybe you just want to offload some work from Flask to FastAPI for convenience or performance reasons. In such a scenario, you probably don't want the client to authenticate at both server applications. What you can do instead is put both server applications behind a reverse proxy, let Flask handle authentication and do its job as before, and use Flask's session cookies for authentication in your FastAPI application with this library.Installation & UsageYou can install the library from PyPI withpip install fastapi-flask-auth.You will also need to install a Flask session decoder. If you're looking for a lightweight, zero-dependency decoder, giveflask-session-decodera try. You can do this manually withpip install flask-session-decoderor you can installfastapi-flask-authtogether with its default decoder dependency simply withpip install fastapi-flask-auth[decoder].With bothfastapi-flask-authandflask-session-decoderin place, you can set up the authenticator for your FastAPI application like this:fromfastapi_flask_authimportFlaskSessionAuthenticatorfromflask_session_decoderimportFlaskSessionDecoderdecoder=FlaskSessionDecoder(secret_key="the-secret-key-of-the-flask-app-that-created-the-cookie")flask_auth=FlaskSessionAuthenticator(decoder=decoder)Then, you can use the authenticator's FastAPI dependencies in your routes like this:fromfastapiimportDepends,FastAPIapp=FastAPI()@app.get("/get-session-cookie")defget_session_cookie(cookie:dict|None=Depends(flask_auth.get_session_cookie)):...@app.get("/requires-session-cookie")defrequires_session_cookie(cookie:dict=Depends(flask_auth.requires_session_cookie)):...@app.get("/get-user-id")defget_user_id(user_id:str|None=Depends(flask_auth.get_user_id)):...@app.get("/requires-session-cookie")defrequires_user_id(user_id:str=Depends(flask_auth.requires_user_id)):...DependenciesThe only dependency of this library isFastAPI.The default decoder dependency isflask-session-decoder, which has no further dependencies.DevelopmentUseblackfor code formatting andmypyfor static code analysis.License - MITThe library is open-sourced under the conditions of the MITlicense.
Package: fastapi-frame-stream
fastapi-frame-streamPackage to easily stream individual frames (MJPEG) using FastAPI.FastAPI server for publishing and viewing MJPEG streams.Raw image files and images as base64 strings can be sent to a 'video stream' and then consumed by any client.Quick startInstallingpip install fastapi-frame-streamRequirementsFastAPIuvicornNOTE:This package will also automatically install:imutilsopencv-pythonpython-miltipartHow to useServerYou can create a simple FastAPI server where it is possible to publish and get multiple streams.full codefromfastapiimportFastAPI,File,UploadFileimportuvicornfrompydanticimportBaseModelfromfastapi_frame_streamimportFrameStreamerapp=FastAPI()fs=FrameStreamer()classInputImg(BaseModel):img_base64str:str@app.post("/send_frame_from_string/{stream_id}")asyncdefsend_frame_from_string(stream_id:str,d:InputImg):awaitfs.send_frame(stream_id,d.img_base64str)@app.post("/send_frame_from_file/{stream_id}")asyncdefsend_frame_from_file(stream_id:str,file:UploadFile=File(...)):awaitfs.send_frame(stream_id,file)@app.get("/video_feed/{stream_id}")asyncdefvideo_feed(stream_id:str):returnfs.get_stream(stream_id)if__name__=='__main__':uvicorn.run(app,host="0.0.0.0",port=5000)ClientAny client can view a published image (MJPEG) stream using a simple<img>tag:full code<!DOCTYPE html><htmllang="en"><head><title>Testing fastapi-frame-stream</title></head><body><imgsrc="http://localhost:5000/video_feed/my_new_stream001"></body></html>All togetherIt is possible to upload an image file directly...... or to use any kind of application to convert the frames to base64 and send it to the web server:How it worksThe frames sent throught the web server are stored in a temporary (in memory) SQLite DB...... and the last frame of each stream is retrieved everytime a client wants to visualize the stream.
Package: fastapi-framework
A FastAPI Framework for things likeDatabase,Redis,Logging,JWT Authentication,Rate LimitsandSessionsInstallYou can install this Library with:pipinstallfastapi-frameworkDocumentationFor the Documentation clickhereFeatures✅ Database✅ Redis✅ Redis Publish/Subscribe✅ FastAPI JWT❌ FastAPI Permission System (for routes)✅ Rate Limits✅ Config Parser✅ Session SystemLicenseThis Project is Licensed under theMIT License
Package: fastapi-gateway-auto-generate
🔥 FastAPI Auto Generate GatewayA library that allows you to automate the process of creating an API Gateway📚 AboutThis is a library that enables the automation of the process of creating an API Gateway.
With its help, you can quickly and easily configure and deploy an API Gateway for your microservices architecture.
The library provides a simple and intuitive interface for configuration,
which reduces the time and effort required to manually set up the API Gateway.
Package: fast-api-gcs
fastapi-gcsFast API GCSRequirementsPython 3.7+Installation$pipinstallfast-api-gcs---> 100%ExampleCreate itCreate a filemain.pywith:fromfastapi_gcsimportFGCSUpload,FGCSGenerate,FGCSDeletefromfastapiimportFastAPI,File,UploadFileapp=FastAPI()#Upload File@app.post("/upload-file/")asyncdefcreate_upload_file(file:UploadFile):returnawaitFGCSUpload.file(project_id={google_project_id},bucket_name={google_bucket_name},file=file,file_path='my_data/test',maximum_size=2_097_152,allowed_extension=['png','jpg'],#file_name='my_file.png' #optional custom file name)#Upload File Response# {#     'file_name': 'my_file.png',#     'file_path': 'my_data/test/my_file.png',#     'file_size': '200 KB',#     'content_type': 'image/png'# }#Upload Encrypted File@app.post("/upload-ecrypted-file/")asyncdefcreate_upload_file(file:UploadFile):returnawaitFGCSUpload.encrypted_file(project_id={google_project_id},bucket_name={google_bucket_name},file=file,file_path='my_data/test',maximum_size=2_097_152,allowed_extension=['png','jpg'],#file_name='my_file.png' #optional custom file name)#Upload Encrypted File Response# {#     'file_name': 'my_file.png',#     'file_path': 'my_data/test/my_file.png',#     'file_size': '200 KB',#     'content_type': 'image/png',#     'encryption_key': 'xxxxxxxxxxxxxxxxxx'# }#Generate Signed Url@app.post("/generate-signed-url/")asyncdefcreate_upload_file(file_path:str):returnawaitFGCSGenerate.signed_url(project_id={google_project_id},bucket_name={google_bucket_name},file_path=file_path#'my_data/test/my_file.png',expiration_hour=1)#Response Generate Signed Url#https://storage.googleapis.com/example-bucket/cat.jpeg?X-Goog-Algorithm=#GOOG4-RSA-SHA256&X-Goog-Credential=example%40example-project.iam.gserviceaccount#.com%2F20181026%2Fus-central1%2Fstorage%2Fgoog4_request&X-Goog-Date=20181026T18#1309Z&X-Goog-Expires=900&X-Goog-SignedHeaders=host&X-Goog-Signature=247a2aa45f16#9edf4d187d54e7cc46e4731b1e6273242c4f4c39a1d2507a0e58706e25e3a85a7dbb891d62afa849#6def8e260c1db863d9ace85ff0a184b894b117fe46d1225c82f2aa19efd52cf21d3e2022b3b868dc#c1aca2741951ed5bf3bb25a34f5e9316a2841e8ff4c530b22ceaa1c5ce09c7cbb5732631510c2058#0e61723f5594de3aea497f195456a2ff2bdd0d13bad47289d8611b6f9cfeef0c46c91a455b94e90a#66924f722292d21e24d31dcfb38ce0c0f353ffa5a9756fc2a9f2b40bc2113206a81e324fc4fd6823#a29163fa845c8ae7eca1fcf6e5bb48b3200983c56c5ca81fffb151cca7402beddfc4a76b13344703#2ea7abedc098d2eb14a7#Delete File@app.post("/delete_file/")asyncdefcreate_upload_file(file_path:str):awaitFGCSDelete.file(project_id={google_project_id},bucket_name={google_bucket_name},file_path=file_path#'my_data/test/my_file.png')
Package: fastapi-gen
FastApi GenCreate LLM-enabled FastAPI applications without build configuration.FastApi Gen works on macOS and Linux.If something doesn’t work, pleasefile an issue.Quick Overviewpip3 install fastapi-genfastapi-gen my_appcd my_appmake start-devorpipx run fastapi-gen my_appcd my_appmake start-devIf you've previously installedfastapi-genglobally viapip3 install fastapi-gen, we recommend you reinstall the package usingpip3 install --upgrade --force-reinstall fastapi-genorpipx upgrade fastapi-gento ensure that you use the latest version.Then openhttp://localhost:8000/docsto see your app OpenAPI documentation.Available templates:Default - basic template with GET/POST examples.NLP - natural language processing template with examples how to use local Hugginface models for summarization, named-entity recognition and text generation using LLM.Langchain - template with examples how to use LangChain with local Hugginface models (LLMs) for text generation and question answering.Llama - template with examples how to use llama.cpp and llama-cpp-python with local Llama 2 for question asnwering.Important notes:Langchain template requires hardware to run and will automatically download required models, be patient.Llama template will download around 4GB model from Hugginface and >4GB of RAM.Each template includes not only code, but alsotests.Get Started ImmediatelyYoudon’tneed to install or configure depencendeices like FastApi or Pytest.They are preconfigured and hidden so that you can focus on the code.Create a project, and you’re good to go.Creating an AppYou’ll need to have Python 3.7+ or later version on your local development machine. We recommend using the latest LTS version. You can usepyenv(macOS/Linux) to switch Python versions between different projects.Basic templatepip3 install fastapi-genfastapi-gen my_apporpip3 install fastapi-genfastapi-gen my_app --template hello_worldNLP templatepip install fastapi-genfastapi-gen my_app --template nlpLangchain templatepip install fastapi-genfastapi-gen my_app --template LangchainLlama templatepip install fastapi-genfastapi-gen my_app --template llamaInside the newly created project, you can run some built-in commands:make startRuns the app in development mode.Openhttp://localhost:8000/docsto view OpenAPI documentation in the browser.The page will automatically reload if you make changes to the code.make testRuns tests.By default, runs tests related to files changed since the last commit.Licensefastapi-genis distributed under the terms of theMITlicense.
Package: fastapi-generator
DocumentDescriptionThis project is used to quickly generate fastapi project.Flow for Main Apprun main app commandconfig config.py db or set in environmentRequirementspython 3.8clickpandasdatabasesCommand# generate main app
fastapi main
# generate main app with orm
fastapi orm db_host db_name db_user db_pswd
# only generate orm
fastapi orm --only db_host db_name db_user db_pswd
fastapi orm localhost test test test
fastapi orm --mode t
# generate sub app
fastapi sub app-name
# generate api from sub app / if app not exist, create it.
fastapi api app-name api-name 
# run fastapi app
uvicorn app.main:app --reloadVersion0.5.1fix error import auth headers0.5.0update more tortoise ormuse more template code0.4.0support tortoise orm with mode t0.3.7add param is_only_orm0.3.6add orm generate0.3.5update command with click0.3generate api of sub app.0.2.1generate sub app with auto load api0.2generate sub app0.1.3auto load sub app0.1.2write main app project files0.1.1generate with orm0.1generate base app: can run it!0.0.2create main app files0.0.1only create app/main.py
Package: fastapi-geolocation
FastAPI Geolocationfastapi-geolocationis a simple middleware package for FastAPI that provides geolocation features by integrating IP-based location lookup. This package is particularly useful for FastAPI applications that need to determine the geographical location of their users.FeaturesEasy integration with FastAPI applications.Utilizes the GeoIP class from Django for location lookup.Provides an easy-to-use middleware that enriches requests with geolocation data.InstallationTo installfastapi-geolocation, run the following command:pipinstallfastapi-geolocationQuick StartHere is a simple example of how to use fastapi-geolocation in a FastAPI application:importaioredisfromfastapiimportFastAPI,Requestfromfastapi_geolocationimportGeoIPMiddlewareapp=FastAPI()redis_client=aioredis.from_url("redis://localhost",encoding="utf-8",decode_responses=True)app.add_middleware(GeoIPMiddleware,redis_client=redis_client,license_key="mykey")@app.get('/')asyncdefindex(request:Request):geo_data=request.state.georeturn{'country':geo_data.country.nameifgeo_dataelse'Unknown',}ConfigurationTo set up the middleware, you need to add it to your FastAPI application with the necessary parameters:redis_client: An instance of aioredis client for caching purpose.
license_key: Your MaxMind license key for the GeoIP database.UsageAfter adding the middleware to your FastAPI application, you can access the geolocation data in your route handlers using the request.state.geo property.ContributingContributions are welcome! If you would like to contribute to the project, please follow these steps:Fork the repository.
Create a new branch for your feature or fix.
Write your code and add tests if applicable.
Submit a pull request with a clear description of your changes.Licensefastapi-geolocation is open source software licensed as MIT.CreditsThis project was inspired by the GeoIP functionality in Django and has been adapted for use in FastAPI applications.