Saravanan666/pypi-org huggingface dataset:
Package: fastapi-migrations
Fastapi MigrationsThis library provides a small wrapper for alembic.NoticeUnder inital development. This can not be ready-for-production library.This can means:Breaking changes may be introducedPoor documentation and changeslogsNot totally testedBe forced to navigate through the source code to find out how it worksWait to a version > 0.1.0 for usage in production environments.InstallationYou can install this library with:pip3 install fastapi-migrationsUsageYou can use both programatically and by CLI (command line interface).Imagine your project foldersapp/
    cli/
        __init__.py
        action.py
    db/
        __init__.py
        base.py
    models/
        __init__.py
        my_model.py
    endpoints/
        __init__.py
        my_endpoint.py
    __init__.py
    config.py
    main.pyThis is an example ofmain.py:from fastapi import FastAPI
from fastapi_sqlalchemy import DBSessionMiddleware

# Load configs and endpoints
from app.config import settings
from app.endpoints import router

app: FastAPI = FastAPI(title=settings.project_name)

# register routes
app.include_router(router)

# add middlewares
app.add_middleware(DBSessionMiddleware, db_url=settings.database_uri)

if __name__ == '__main__':
    # Load cli commands
    from app.cli import app as cli

    cli()Then yourapp/cli/__init__.pycan be like:import typer

from fastapi_migrations.cli import MigrationsCli
import app.cli.action as action

# main cli app
app: typer.Typer = typer.Typer()

# these are our cli actions
app.add_typer(action.app, name='action', help='Common actions the app do')

# this line adds the fastapi-migrations cli commands to our app
app.add_typer(MigrationsCli())Now you can call your app from the command line and usefastapi-migrationslike:py app/main.py db showIf you want to use this library programatically, this is an example:The fileapp/cli/action.pycan be like:import typer
from fastapi_migrations import MigrationsConfig, Migrations

app: typer.Typer = typer.Typer()

@app.command()
def show() -> None:
    config = MigrationsConfig()

    migrations = Migrations(config)

    migrations.show()You can add this lines where you wish in your proyect. Here we ar adding it to a command line so we can call our app like:py app/main.py action showLicenseThis software is distributed underMIT license.
Package: fastapi-misskey
FastAPI MisskeyこのライブラリはFastAPIにMisskeyの認証を作成するお手伝いをするライブラリですExamplefromtypingimportOptionalfromfastapiimportDepends,FastAPIfromfastapi_misskey.clientimportMisskeyAuthClientapp=FastAPI()misskey=MisskeyAuthClient('https://example.com','test','http://localhost:8000/callback',description='FastAPI Misskey Auth')@app.get('/login')asyncdeflogin():return{'url':awaitmisskey.get_auth_url()}@app.get('/callback')asyncdefcallback(session:Optional[str]=None,token:Optional[str]=None):token,user=awaitmisskey.get_access_token(session,token)return{'token':token,'user':user}@app.get('/profile')asyncdefprofile(user=Depends(misskey.get_user)):ifuser.get('error'):returnuserelse:return{'user':user}Inspired byfastapi-discordThanks to @Tert0
Package: fastapi-mlflow
fastapi mlflowDeploymlflowmodels as JSON APIs usingFastAPIwith minimal new code.Installationpipinstallfastapi-mlflowFor running the app in production, you will also need an ASGI server, such asUvicornorHypercorn.Install on Apple Silicon (ARM / M1)If you experience problems installing on a newer generation Apple silicon based device,this solution from StackOverflowbefore retrying install has been found to help.brewinstallopenblasgfortranexportOPENBLAS="$(brew--prefixopenblas)"LicenseCopyright © 2022-23 Auto Trader Group plc.Apache-2.0ExamplesSimpleCreateCreate a filemain.pycontaining:fromfastapi_mlflow.applicationsimportbuild_appfrommlflow.pyfuncimportload_modelmodel=load_model("/Users/me/path/to/local/model")app=build_app(model)RunRun the server with:uvicornmain:appCheckOpen your browser athttp://127.0.0.1:8000/docsYou should see the automatically generated docs for your model, and be able to test it out using theTry it outbutton in the UI.Serve multiple modelsIt should be possible to host multiple models (assuming that they have compatible dependencies...) by leveragingFastAPIs Sub Applications:fromfastapiimportFastAPIfromfastapi_mlflow.applicationsimportbuild_appfrommlflow.pyfuncimportload_modelapp=FastAPI()model1=load_model("/Users/me/path/to/local/model1")model1_app=build_app(model1)app.mount("/model1",model1_app)model2=load_model("/Users/me/path/to/local/model2")model2_app=build_app(model2)app.mount("/model2",model2_app)RunandCheckas above.Custom routingIf you want more control over where and how the prediction end-point is mounted in your API, you can build the predictor function directly and use it as you need:frominspectimportsignaturefromfastapiimportFastAPIfromfastapi_mlflow.predictorsimportbuild_predictorfrommlflow.pyfuncimportload_modelmodel=load_model("/Users/me/path/to/local/model")predictor=build_predictor(model)app=FastAPI()app.add_api_route("/classify",predictor,response_model=signature(predictor).return_annotation,methods=["POST"],)RunandCheckas above.
Package: fastapi-modelrouter
fastapi-modelrouterFastAPI Router that creates CRUD routes for SqlAlchemy modelsFeaturesGenerates direct from SqlAlchemy Models CRUD routesno need to write Pydantic Basemodelskeep SqlAlchemy Models and routes in syncSimple to UseSupports composite primary keysSupports queryparamsInstallationpip install fastapi-modelrouterBasic Usagefrom fastapi import FastAPI
from modelrouter import ModelRouter

# setup Sqlalchemy Database
from sqlalchemy import create_engine, Column, String, Integer
from sqlalchemy.orm import sessionmaker, declarative_base

sqlalchemy_database_url = "sqlite:///:memory"

engine = create_engine(
    sqlalchemy_database_url, connect_args={"check_same_thread": False}
)
session_local = sessionmaker(autocommit=False, autoflush=False, bind=engine)

Base = declarative_base()


# Define Project Model
class Project(Base):
    __tablename__ = 'project'
    projectno = Column(String, primary_key=True)
    project = Column(String)
    state = Column(Integer, default=0)
    owner = Column(String)


Base.metadata.drop_all(bind=engine)
Base.metadata.create_all(bind=engine)


# Database session function
def get_db():
    db = session_local()
    try:
        yield db
    finally:
        db.close()


# Create FastApi
app = FastAPI()

# Create and include Modelrouter 
app.include_router(ModelRouter(Project, get_db))
Package: fastapi-module-register
fastapi_module_register介绍自动将tortoise/sqlalchemy 模型注册成fastapi 路由软件架构软件架构说明安装教程xxxxxxxxxxxx使用说明xxxxxxxxxxxx参与贡献Fork 本仓库新建 Feat_xxx 分支提交代码新建 Pull Request特技使用 Readme_XXX.md 来支持不同的语言，例如 Readme_en.md, Readme_zh.mdGitee 官方博客blog.gitee.com你可以https://gitee.com/explore这个地址来了解 Gitee 上的优秀开源项目GVP全称是 Gitee 最有价值开源项目，是综合评定出的优秀开源项目Gitee 官方提供的使用手册https://gitee.com/helpGitee 封面人物是一档用来展示 Gitee 会员风采的栏目https://gitee.com/gitee-stars/
Package: fastapi-modules
FastAPIALI-ModelsModelli SQLAlchemy e Pydantic per l'utilizzo in applicazioni Flask e FastapiInstallazione dell paccetto con pip da githubpip install -e git+ssh://git@github.com/giaca95/Fastapi-modules.git#egg=fastapi-modulesPer caricare su pypipython setup.py sdist

twine upload dist/*Classi SQLAlchemy presentiBuoni COVID-19 territorioAziendeEsterne:
    piva: str
    rag_soc: str

BuoniTagli:
    id: int
    cifra: str
    numero: int

AcquisizioneBuoniTestata:
    id: int
    piva: str
    dt_creazione: datetime

    dettagli = relationship("AcquisizioneBuoniDettagli")
    azienda = relationship(AziendeEsterne)

AcquisizioneBuoniDettagli:
    id: int
    id_taglio_buono: int
    qta_buono: int
    dt_inserimento: datetime
    id_testata_acquisizione: int

    buono = relationship("BuoniTagli")ODSDimNegozio:
    cod_negozio: str
    des_negozio: strRichieste volantiniOfferte:
    id: int
    descrizione: str

Linee:
    id: int
    descrizione: str

OfferteAnni:
    id_offerta: int
    anno: str

OfferteLinee:
    id_offerta: int
    id_linea: int

LineeNegozi:
    id_linea: int
    cod_negozio: str

Richieste:
    id: int
    anno: str
    id_offerta: int
    id_linea: int
    cod_negozio: str
    dt_inizio: datetime
    dt_fine: datetime
    invio_ora: bool
    dt_creazione: datetime
    utente: str
    stato: int

    emails = relationship("RichiesteEmail")
    punto_vendita = relationship(DimNegozio)
    offerta = relationship(Offerte)
    linea = relationship(Linee)

RichiesteEmail:
    id_richiesta: int
    email: str
Package: fastapi-mqtt
fastapi-mqttMQTT is a lightweight publish/subscribe messaging protocol designed for M2M (machine to machine) telemetry in low bandwidth environments.
Fastapi-mqtt is the client for working with MQTT.For more information about MQTT, please refer to here:MQTTFastapi-mqtt wraps aroundgmqttmodule. Gmqtt Python async client for MQTT client implementation.
Module has support of MQTT version 5.0 protocolDocumentation:FastApi-MQTTThe key feature are:MQTT specification avaliable with help decarator methods using callbacks:on_connect()on_disconnect()on_subscribe()on_message()subscribe(topic)MQTT Settings available withpydanticclassAuthentication to broker with credentialsunsubscribe certain topics and publish to certain topics🔨 Installationpipinstallfastapi-mqtt🕹 GuidefromfastapiimportFastAPIfromfastapi_mqttimportFastMQTT,MQTTConfigapp=FastAPI()mqtt_config=MQTTConfig()mqtt=FastMQTT(config=mqtt_config)mqtt.init_app(app)@mqtt.on_connect()defconnect(client,flags,rc,properties):mqtt.client.subscribe("/mqtt")# subscribing mqtt topicprint("Connected: ",client,flags,rc,properties)@mqtt.on_message()asyncdefmessage(client,topic,payload,qos,properties):print("Received message: ",topic,payload.decode(),qos,properties)@mqtt.subscribe("my/mqtt/topic/#")asyncdefmessage_to_topic(client,topic,payload,qos,properties):print("Received message to specific topic: ",topic,payload.decode(),qos,properties)@mqtt.subscribe("my/mqtt/topic/#",qos=2)asyncdefmessage_to_topic_with_high_qos(client,topic,payload,qos,properties):print("Received message to specific topic and QoS=2: ",topic,payload.decode(),qos,properties)@mqtt.on_disconnect()defdisconnect(client,packet,exc=None):print("Disconnected")@mqtt.on_subscribe()defsubscribe(client,mid,qos,properties):print("subscribed",client,mid,qos,properties)Publish method:asyncdeffunc():mqtt.publish("/mqtt","Hello from Fastapi")# publishing mqtt topicreturn{"result":True,"message":"Published"}Subscribe method:@mqtt.on_connect()defconnect(client,flags,rc,properties):mqtt.client.subscribe("/mqtt")# subscribing mqtt topicprint("Connected: ",client,flags,rc,properties)Changing connection paramsmqtt_config=MQTTConfig(host="mqtt.mosquito.org",port=1883,keepalive=60,username="username",password="strong_password",)mqtt=FastMQTT(config=mqtt_config)✅ TestingClone the repository and install it withpoetry.Run tests withpytest, using an external MQTT broker to connect (defaults to 'test.mosquitto.org').Explore the fastapi appexamplesand run them with uvicorn# (opc) Run a local mosquitto MQTT broker with dockerdockerrun-d--namemosquitto-p9001:9001-p1883:1883eclipse-mosquitto:1.6.15# Set host for test broker when running pytestTEST_BROKER_HOST=localhostpytest# Run the example apps against local broker, with uvicornTEST_BROKER_HOST=localhostuvicornexamples.app:app--port8000--reloadTEST_BROKER_HOST=localhostuvicornexamples.ws_app.app:application--port8000--reloadContributingFell free to open issue and send pull request.Thanks ToContributors.
Contributions of any kind are welcome!Before you start please readCONTRIBUTING
Package: fastapi-nest
FastAPI Controller and Route DecoratorsThis package provides a set of decorators and utilities to simplify the creation of FastAPI controllers and routes. It allows you to define controllers as classes and routes as methods within those classes, with automatic dependency injection of shared dependencies.FeaturesController Class: Define a group of related routes within a single class.Route Decorators: Easily define route handlers with specific HTTP methods (GET, POST, PUT, DELETE, PATCH, OPTIONS, HEAD, TRACE).Automatic Dependency Injection: UseDependsto inject dependencies into controller methods.Simple Integration: Integrate with existing FastAPI applications with minimal changes.InstallationTo use these decorators, ensure that you have FastAPI installed in your environment. If not, you can install it using pip:pipinstallfastapi-nestThen, include the provided code in your project or package it accordingly.UsageDefining a ControllerTo create a new controller, define a class and decorate it with@controller:fromnestimportcontroller@controller()classMyController:passDefining Route HandlersUse the provided HTTP method decorators to define route handlers within your controller:fromnestimportcontroller,get,post@controller()classMyController:@get("/items")defread_items(self):return{"message":"Reading items"}@post("/items")defcreate_item(self,item:dict):return{"message":"Creating item","item":item}Dependency InjectionUseDependsto inject dependencies into your route handlers:fromfastapiimportDependsfromnestimportcontroller,getdefget_current_user():# Logic to get the current userreturn{"user_id":1}@controller()classMyController:# attribute injectcurrent_user:dict=Depends(get_current_user)@get("/users/me")defread_current_user(self,current_user:dict=Depends(get_current_user)):assertself.current_user["user_id"]==current_user["user_id"]return{"message":"Reading current user","user":current_user}Registering Controllers with FastAPITo add your controller's routes to a FastAPI app, use theas_api_routerutility:fromfastapiimportFastAPIfromnestimportas_api_routerfrommy_controllerimportMyControllerapp=FastAPI()my_controller_router=as_api_router(MyController())app.include_router(my_controller_router)
Package: fastapi-nextauth-jwt
fastapi-nextauth-jwtThis project contains a FastAPI dependency that can be used to decrypt and validate JWTs generated by NextAuth.
The purpose of this project is to make it easy to use a FastAPI backend in projects that use Next.js and NextAuth
in the frontend.Besides JWT decryption and validation, NextAuth compatible cross-site request forgery (CSRF) protection is also implemented.InstallationGeneral usage:pipinstallfastapi-nextauth-jwtDevelopment:pipinstall"fastapi-nextauth-jwt[test]"UsagefromtypingimportAnnotatedfromfastapiimportFastAPI,Dependsfromfastapi_nextauth_jwtimportNextAuthJWTapp=FastAPI()JWT=NextAuthJWT(secret="y0uR_SuP3r_s3cr37_$3cr3t",)@app.get("/")asyncdefreturn_jwt(jwt:Annotated[dict,Depends(JWT)]):returnjwtThere are a few configuration options available in the NextAuthJWT constructor, but the most important one issecret,
which should be equivalent toNEXTAUTH_SECRETon the Next.js side. A real application would obviously not hardcode the secret like this,
but rely on theNEXTAUTH_SECRETenv var.It is also possible to enable or disable CSRF protection usingcsrf_prevention_enabled.
If this is not set, this will looks at the ENV environment variable. If this isdevthen CSRF protection will be disabled.
It is also possible to customize the HTTP verbs to which CSRF protection is applied.You should also set theNEXTAUTH_URLenvironment variable, as it is used to determine
whether or not secure cookies are being used. Or you can set the cookie names manually.ExamplesAsimple exampleis available in the examples folder. It uses Next.js URL rewrites to direct
requests to FastAPI. This is just one way to do it, putting both the backend and frontend
behind something like nginx would also be a good strategy. As long as the cookies can make it to FastAPI
you should be good to go!
Package: fastapi-oauth2
fastapi-oauth2FastAPI OAuth2 is a middleware-based social authentication mechanism supporting several OAuth2 providers. It leverages
thesocial-coreauthentication backends and integrates seamlessly
with FastAPI applications.IntegrationFor integrating the package into an existing FastAPI application, the router with OAuth2 routes and
theOAuth2Middlewarewith particularconfigsshould be added to the application.fromfastapiimportFastAPIfromfastapi_oauth2.middlewareimportOAuth2Middlewarefromfastapi_oauth2.routerimportrouterasoauth2_routerapp=FastAPI()app.include_router(oauth2_router)app.add_middleware(OAuth2Middleware,config=OAuth2Config(...))ContributeAny contribution is welcome. Always feel free to open an issue or a discussion if you have any questions not covered by
the documentation. If you have any ideas or suggestions, please, open a pull request. Your name will shine in our
contributors' list. Be proud of what you build!LicenseCopyright (C) 2023 Artyom Vancyan.MIT
Package: fastapi_oauth20
fastapi_oauth20在 FastAPI 中异步授权 OAuth2 客户端我们的目标是集成多个 CN 第三方客户端，敬请期待TODO:如果我们能够很容易获取测试客户端，对接将会很快发生library testsGoogle微信QQ抖音飞书钉钉微博百度GiteeGithub开源中国阿里云
Package: fastapi-odm-helper
FastAPI ODM HelperFastAPI ODM Helper helps us to work with beanie easier with lots of useful functionsHow to useBaseRepositoryfromfastapi_odm_helperimportBaseRepositoryfromusers.entities.userimportUserEntityclassUserRepository(BaseRepository[UserEntity]):_entity=UserEntity@Entity decoratorfromfastapi_odm_helperimportEntity@Entity()classUserEntity(BaseEntity):id:UUID
Package: fastapi-offline
OverviewFastAPIis awesome, but the documentation pages (Swagger or Redoc) all depend on external CDNs, which is problematic if you want to run on disconnected networks.This package includes the required files from the CDN and serves them locally.  It also provides a super-simple way to get a FastAPI instance configured to use those files.Under the hood, this simply automates the process described in the official documentationhere.InstallationYou can install this package from PyPi:pipinstallfastapi-offlineExampleGiven the example from theFastAPI tutorial:fromfastapiimportFastAPIapp=FastAPI()@app.get("/")asyncdefroot():return{"message":"Hello World"}Simply create afastapi_offline.FastAPIOfflineobject instead:fromfastapi_offlineimportFastAPIOfflineapp=FastAPIOffline()@app.get("/")asyncdefroot():return{"message":"Hello World"}Any options passed toFastAPIOffline()exceptdocs_url,redoc_url,favicon_url, andstatic_urlare passed through toFastAPI().docs_urlandredoc_urlare handled byfastapi-offline, and use the same syntax as normalfastapilibrary.static_urlcan be used to set the path for the static js/css files, e.g.static_url=/static-files(default:/static-offline-docs).Using a custom shortcut iconBy default, the FastAPIfavicon.pngis included and used as the shortcut icon on the docs pages.  If you want to use a different one, you can specify it with thefavicon_urlargument:app=FastAPIOffline(favicon_url="http://my.cool.site/favicon.png")LicensingThis code is released under the MIT license.Parts of Swagger are included in this package.  The original license (Apache 2.0) and copyright apply to those files.Parts of Redoc are included in this package.  The original license (MIT) and copyright apply to those files.The FastAPIfavicon.pngfile is included in this package.  The original license (MIT) and copyright apply to that file.
Package: fastapi-oidc
FastAPI OIDC:warning:Seethis issuefor
simple role-your-own example of checking OIDC tokens.Verify and decrypt 3rd party OIDC ID tokens to protect yourfastapiendpoints.Documentation:ReadTheDocsSource code:GithubInstallationpip install fastapi-oidcUsageVerify ID Tokens Issued by Third PartyThis is great if you just want to use something like Okta or google to handle
your auth. All you need to do is verify the token and then you can extract user ID info
from it.fromfastapiimportDependsfromfastapiimportFastAPI# Set up our OIDCfromfastapi_oidcimportIDTokenfromfastapi_oidcimportget_authOIDC_config={"client_id":"0oa1e3pv9opbyq2Gm4x7",# Audience can be omitted in which case the aud value defaults to client_id"audience":"https://yourapi.url.com/api","base_authorization_server_uri":"https://dev-126594.okta.com","issuer":"dev-126594.okta.com","signature_cache_ttl":3600,}authenticate_user:Callable=get_auth(**OIDC_config)app=FastAPI()@app.get("/protected")defprotected(id_token:IDToken=Depends(authenticate_user)):return{"Hello":"World","user_email":id_token.email}Using your own tokensThe IDToken class will accept any number of extra field but if you want to craft your
own token class and validation that's accounted for too.classCustomIDToken(fastapi_oidc.IDToken):custom_field:strcustom_default:float=3.14authenticate_user:Callable=get_auth(**OIDC_config,token_type=CustomIDToken)app=FastAPI()@app.get("/protected")defprotected(id_token:CustomIDToken=Depends(authenticate_user)):return{"Hello":"World","user_email":id_token.custom_default}
Package: fastapi-openapierrors
Identity LibThis Python package contains utilities enabling nicer error descriptions in
OpenAPI specs generated by FastAPI.UseInstallfastapi-openapierrorsusing pip:pip install fastapi-openapierrorsThe module can then be used asfastapi_openapierrorsto annotate routes:fromfastapiimportFastAPIfromfastapi_openapierrorsimportNotFoundResponse,BadRequestResponsefrompydanticimportBaseModelapp=FastAPI()classWidget(BaseModel):name:str@api.get('/widget/{name}',summary="Get a single widget",description="Get a single widget by name",response_model=Widget,responses={400:BadRequestResponse,404:NotFoundResponse})asyncdefget_widget(name:str=Path(...,example=f"frobnicator2000",title="The name of the widget")):# FastAPI automatically returns a Bad Request response if the request does# not match the route.# Look for widget by name.widget,was_found=get_widget_by_name(name)ifnotwas_found:raiseHTTPException(status_code=status.HTTP_404_NOT_FOUND)returnwidgetDeveloper quickstartThis project contains a dockerized testing environment which wrapstox.Tests can be run using the./test.shcommand:# Run all PyTest tests and Flake8 checks$./test.sh# Run just PyTest$./test.sh-epy3# Run a single test file within PyTest$./test.sh-epy3--tests/test_identifiers.py# Run a single test file within PyTest with verbose logging$./test.sh-epy3--tests/test_identifiers.py-vvv
Package: fastapi-openapi-generator
What this repository containsA Command Line Interface to save openapi file from a FastAPI applicationInstallation:install the packagepip install fastapi-openapi-generatorHow to usefastapi-openapi-gen main:app \
    --app-dir= # The path to mounth in the python path to import the module. \
    --output-dir= # The path where store the openapi template. \
    --file-name= # The name the openapi file will assume.
    --mock-class= # Use it to mock a package that is not usefully for the openapi generation and block the fastapi start
Package: fastapi-opentracing
fastapi-opentracingfastapi opentracing middleware works with istioinstall:pip install fastapi-opentracingexample:fromfastapiimportFastAPIimportuvicornfromfastapi_opentracingimportget_opentracing_span_headersfromfastapi_opentracing.middlewareimportOpenTracingMiddlewareapp=FastAPI()app.add_middleware(OpenTracingMiddleware)@app.get("/")asyncdefroot():carrier=awaitget_opentracing_span_headers()return{'span':carrier}if__name__=="__main__":uvicorn.run(app,host="0.0.0.0",port=8000)