Saravanan666/pypi-org huggingface dataset:
Package: fastapi-sqlalchemy-toolkit
FastAPI SQLAlchemy ToolkitДокументация:https://e-kondr01.github.io/fastapi-sqlalchemy-toolkit/ru/FastAPI SQLAlchemy Toolkit— это библиотека для стекаFastAPI+ AsyncSQLAlchemy,
которая помогает решать следующие задачи:cнижение количества шаблонного, копипастного кода, который возникает при разработке
REST API и взаимодействии с СУБД черезSQLAlchemy;автоматическая валидация значений на уровне БД при создании и изменении объектов через API.ФункционалМетоды для CRUD-операций с объектами в БДФильтрация с обработкой необязательных параметров запроса (см. разделФильтрация)Декларативная сортировка с помощьюordering_depends(см. разделСортировка)Валидация существования внешних ключейВалидация уникальных ограниченийУпрощение CRUD-действий с M2M связямиУстановкаpipinstallfastapi-sqlalchemy-toolkitДемонстрацияПример использованияfastapi-sqlalchemy-toolkitв FastAPI приложении:https://github.com/e-kondr01/fastapi-sqlalchemy-toolkit/tree/master/examples/app
Package: fastapi-sqlmodel-crud
Project Introductionfastapi-sqlmodel-crudis a project based onFastAPI+SQLModel, which is used to quickly build Create, Read, Update, Delete common API interfaces.Installpipinstallfastapi-sqlmodel-crudSimple examplemain.py:fromtypingimportOptionalfromfastapiimportFastAPIfromsqlalchemy.ext.asyncioimportAsyncEngine,create_async_enginefromsqlmodelimportSQLModel,Fieldfromfastapi_amis_admin.crudimportSQLModelCrud# 1. Create SQLModel modelclassArticle(SQLModel,table=True):id:int=Field(default=None,primary_key=True,nullable=False)title:str=Field(title='ArticleTitle',max_length=200)description:Optional[str]=Field(default='',title='ArticleDescription',max_length=400)status:bool=Field(None,title='status')content:str=Field(title='ArticleContent')# 2. Create AsyncEnginedatabase_url='sqlite+aiosqlite:///amisadmin.db'engine:AsyncEngine=create_async_engine(database_url,future=True)# 3. Register crud routearticle_crud=SQLModelCrud(model=Article,engine=engine).register_crud()app=FastAPI(debug=True)# 4. Include the routerapp.include_router(article_crud.router)# 5. Create model database table (first run)@app.on_event("startup")asyncdefstartup():asyncwithengine.begin()asconn:awaitconn.run_sync(SQLModel.metadata.create_all)Development documentationhttps://docs.gh.amis.work/crud/SQLModelCrud/Dependent projectsFastAPISQLModelLicenceThe project follows the Apache2.0 license agreement.
Package: fastapi-sso
FastAPI SSOFastAPI plugin to enable SSO to most common providers (such as Facebook login, Google login and login via
Microsoft Office 365 account).This allows you to implement the famousLogin with Google/Facebook/Microsoftbuttons functionality on your
backend very easily.Documentation:https://tomasvotava.github.io/fastapi-sso/Source Code:https://github.com/tomasvotava/fastapi-ssoSecurity warningPlease note that versions preceding0.7.0had a security vulnerability.
The SSO instance could share state between requests, which could lead to security issues.Please update to0.7.0or newer.Also, the preferred way of using the SSO instances is to usewithstatement, which will ensure the state is cleared.
See example below.Support this projectIf you'd like to support this project, considerbuying me a coffee ☕.
I tend to process Pull Requests faster when properly caffeinated 😉.Supported login providersOfficialGoogleMicrosoftFacebookSpotifyFitbitGithub (credits toBrandlfor hint usingacceptheader)generic (seedocs)NotionContributedKakao (by Jae-Baek Song -thdwoqor)Naver (by 1tang2bang92) -1tang2bang92Gitlab (by Alessandro Pischedda) -Cereal84Line (by Jimmy Yeh) -jimmyyyehLinkedIn (by Alessandro Pischedda) -Cereal84SeeContributingfor a guide on how to contribute your own login provider.InstallationInstall usingpippip install fastapi-ssoInstall usingpoetrypoetry add fastapi-ssoContributingIf you'd like to contribute and add your specific login provider, please seeContributingfile.
Package: fastapi-standalone-docs
FastAPI Standalone DocsHost FastAPI Swagger UI and ReDoc without any third party CDNs. Handy if you want to be
able to use the docs offline or want to avoid loading content from 3rd party CDNs due to
privacy reasons.This library was heavily inspired byfastapi-offline-swagger-ui,
but we wanted a way to take it into use with less boilerplate code and also have it
hosted on PyPI.InstallationThe package is available on PyPI:pipinstallfastapi-standalone-docsUsageImportStandaloneDocsand pass in the FastAPI application to it:fromfastapiimportFastAPIfromfastapi_standalone_docsimportStandaloneDocsapp=FastAPI()StandaloneDocs(app=app)The static files will by default be served from subpaths of thedocs_urlandredoc_urlas you've specified in your FastAPI app. The library doesn't make any
assumption on any particular path being reserved for the library. And if you disable
either of the two UIs, the corresponding files won't either be served unnecessarily.This example would move the Swagger UI and the static files needed for it to the path/swaggerand disable the ReDoc interface and the static files needed by it:fromfastapiimportFastAPIfromfastapi_standalone_docsimportStandaloneDocsapp=FastAPI(docs_url="/swagger",redoc_url=None)StandaloneDocs(app=app)By default, the library will use the FastAPI favicons, and they're served from{docs_url}/fastapi/favicon.pngand{redoc_url}/fastapi/favicon.png. You can use your
own favicons like this, which will also disable the FastAPI icons:fromfastapiimportFastAPIfromfastapi_standalone_docsimportStandaloneDocsapp=FastAPI()StandaloneDocs(app=app,redoc_favicon_url="/favicon.png",swagger_favicon_url="/favicon.png",)To make the docs truly stand alone the Google Fonts are by default disabled (they are
used in the ReDoc interface). If you want to enable them just setwith_google_fonts=True, like this:fromfastapiimportFastAPIfromfastapi_standalone_docsimportStandaloneDocsapp=FastAPI()StandaloneDocs(app=app,with_google_fonts=True,)DisclaimerNote!If you create multiple FastAPI apps in the same runtime (quite unlikely
use-case), using StandaloneDocs on one of them will affect the other ones as well, as
the library patches two of the shared functions (get_swagger_ui_htmlandget_redoc_html). Thus the library should not be used in a such setup unless all the
apps will use StandaloneDocs with the same settings.DevelopmentPRs are welcome!This project is usingPoetryandpre-commit, so please ensure you've installed both. To set up
the project with them run:pre-commitinstall
poetryinstallRunning tests locally:poetryruninvoketestUpdating the static files from the CDNs:poetryrunupdate-fastapi-standalone-docsIf you want to test using it locally in some other project, in that project run this
(make sure to adjust the path to the local repo):poetryadd../fastapi-standalone-docs--editableLicenseThe code of this library itself is released under theMIT license. Please
however note that this library also contains parts ofReDoc, which is licensed under theMIT license,Swagger UI, which is licensed under theApache 2.0 License, as well as parts
ofFastAPI(the favicon), which is licensed
under theMIT license.
Package: fastapi-starter
FastAPI Starter ApplicationThis application serves as a starter for FastAPI applications which interact with a relational database and provide user authentication.SpecificationIn order to extend this starter for an application, perform the following actions:Install the starter application withpip install fastapi-starter.Define the following environment variables:APPLICATION_NAMEAPPLICATION_DESCRIPTIONDB_HOSTDB_NAMEDB_PASSWORDDB_USERDEBUGMAILGUN_API_KEYMAILGUN_DOMAIN_NAMEMAILGUN_SENDER_EMAILMAILGUN_SENDER_NAMESECRET_KEY (generate usingopenssl rand -hex 32)Define database models which inherit fromfastapi_starter.models.Base.Define schemas which utilise the following mixins fromfastapi_starter.schemaswhere appropriate:HasOwnerInDatabaseUpdatableDefine and includeFastAPI.APIRouters to thefastapi_starter.appapplication.Create database tables with:fromfastapi_starter.databaseimportenginefromfastapi_starter.modelsimportBaseBase.metadata.create_all(bind=engine)ComponentsThePyMySQLdriver is used withSQLAlchemyto provide a declarative interface between the FastAPI controllers and a MySQL database instance.TheFastAPI Another JWT Authplugin is used to provide JWT authentication to the FastAPI application.
Package: fastapi-startup
FastAPI StartupAn opinionated startup extension for FastAPI.Usagefromfastapi_startupimportFastAPIStartupapp=FastAPIStartup(site_name="My site",swagger_favicon_url="https://example.com/favicon.ico",)OpinionsThis is an opinionated way to start FastAPI:No ReDoc.Swagger is hosted at theroot_path.Swagger UI oAuth2 redirect URL is/oauth2-redirect.Endpoint/pingresponds with the plain text response "pong".Mounts static directory at/static(default).Title and site name in SwaggerAssets (expects these files in the directory./static/assets):Favicon -favicon.ico.Swagger CSS -swagger-ui.min.css.Swagger Bundle JS -swagger-ui-bundle.min.js.ConfigConfigure FastAPI as usual. Extra arguments (that can be accessed fromapp.extra):NameDefaultDescriptionsite_nameSwagger UIDisplayed in the Swagger title, withapp.title.static_dirstaticWhere to mount the static directory. Disabled if value is falsy.swagger_css_url/assets/swagger-ui.min.cssURL to Swagger UI CSS file.swagger_favicon_url/assets/favicon.icoURL to your Favicon.swagger_js_url/assets/swagger-ui-bundle.min.jsURL to Swagger JS bundle file.If theswagger_arguments starts with a "/" and static is mounted, they will be loaded from "static", else it will be treated as a URL.
Package: fastapi-static-digest
FastAPI Static DigestA Starlette/FastAPI plugin to digest and compress static files, and integrate with Jinja templates.pip install fastapi-static-digestOverviewThere are two classes: StaticDigest and StaticDigestCompiler.TheStaticDigestCompiler.compilermethod will produce the digested directory. TheStaticDigest(andstarlette.staticfiles.StaticFiles) should be configured to read this directory.The compilation can be added to your build process, for instance with aclickCLI command (see below). Alternatively, theFASTAPI_STATICDIGEST_RELOAD=1environment variable can be set to enable "hot reloading" during development.Usage# app.pyapp_root=Path(__file__).parentstatic_src=app_root/"static"static=StaticDigest(source_dir=static_src)routes=[Mount('/static',app=StaticFiles(directory=static.directory),name="static"),]app=Starlette(routes=routes)# manage.pyfrom.appimportapp_root@click.command()defcompile():src=app_root/"static"click.echo("Source dir%s"%src)compiler=StaticDigestCompiler(source_directory=src)compiler.compile()click.echo("Done.")Jinja2 Integration# app.pyapp_root=Path(__file__).parentstatic_src=app_root/"static"static=StaticDigest(source_dir=static_src)templates=Jinja2Templates(app_root/"templates")static.register_static_url_for(templates)routes=[Mount('/static',app=StaticFiles(directory=static.directory),name="static"),]app=Starlette(routes=routes)<!-- index.html -->{{ static_url_for("static", "app.css" )}}renders tohttps://myhost.com/static/app.92fede82119d2e012f890e1102080a45.cssDevelopmentPRs and issues are welcome!
Package: fast-api-stats
Api-StatsUpdates a json file with the function name whenever the function is calledI'm gonna use this with my api so im calling it api-statsDownload:pip install fast-api-statsExample Usage:fromfastapiimportFastAPIfromfastapistatsimportStatsapp=FastAPI()# Add this line if you want a custom location for you json fileStats.file_name="json_files/stats.json"# you can also make a variable with the class and use that instead of @Stats.update_statsupdate=Stats.update_stats@app.get("/name")@update(name="name")# if the name kwarg is not passed it will default to the function namedefshow_name(name:str):# This is just an example endpointreturn{"your_name":name}
Package: fastapi-storages
FastAPI StoragesA collection of backend storages and ORM extensions to simplify file management in FastAPI and Starlette projects.Similar todjango-storagesproject, but aiming to work with a wider range of database ORMs and backends.Documentation:https://aminalaee.dev/fastapi-storagesSource Code:https://github.com/aminalaee/fastapi-storagesInstallationpip install fastapi-storagespip install 'fastapi-storages[full]'Supported integrationsSQLAlchemySQLModelSQLAdminSupported storage backendsFileSystemStorageS3StorageExamplefromfastapiimportFastAPI,UploadFilefromsqlalchemyimportColumn,Integer,create_enginefromsqlalchemy.ormimportSession,declarative_basefromfastapi_storagesimportFileSystemStoragefromfastapi_storages.integrations.sqlalchemyimportFileTypeapp=FastAPI()Base=declarative_base()engine=create_engine("sqlite:///test.db")classExample(Base):__tablename__="example"id=Column(Integer,primary_key=True)file=Column(FileType(storage=FileSystemStorage(path="/tmp")))# Create database and tableBase.metadata.create_all(engine)@app.post("/upload/")defcreate_upload_file(file:UploadFile):example=Example(file=file)withSession(engine)assession:session.add(example)session.commit()return{"filename":example.file.name}
Package: fastapi_swagger2
fastapi_swagger2Swagger2 support for FastAPIReason behind this library:Few API GW services like Google Cloud API GW still support only Swagger 2.0 spec. Since FastAPI only supports OAS3, it is a challenge. Converting from OAS3 to Swagger 2.0 requires some manual steps which would hinder CI/CD.RequirementsPython 3.8+0.0.3 - FastAPI >= 0.79.0, <= 0.98.00.1.1 - FastAPI >= 0.99.0, <= 0.99.10.2.1 - FastAPI >= 0.100.0Installation$pipinstallfastapi_swagger2ExamplefromtypingimportUnionfromfastapiimportFastAPIfromfastapi_swagger2importFastAPISwagger2app=FastAPI()FastAPISwagger2(app)@app.get("/")defread_root():return{"Hello":"World"}@app.get("/items/{item_id}")defread_item(item_id:int,q:Union[str,None]=None):return{"item_id":item_id,"q":q}This adds following endpoints:http://localhost:8000/swagger2.jsonhttp://localhost:8000/swagger2/docshttp://localhost:8000/swagger2/redocDevelopment$pipinstall"/path/to/fastapi_swagger2/repo[test,all]"
Package: fastapi_tag
FastAPI TagDocumented & Enhance the Metadata of your API ✨A simple Package could be added to your FastAPI Project to enhance the metadata of your Project and documenting your API with more information.Source Code:https://github.com/yezz123/fastapi-tagInstall the project:pip install fastapi-tagFeatures 🎉Add a tag to your API, which can be used to filter the API documentation.Add a description to your API, which can be used to describe the API.Add a version to your API, which can be used to describe the version of the API and app.Provide some others features like:API_id: A unique identifier for the API.Audience: The audience of the API (e.g.public,internal,external).Tested in python 3.6 and up.Last Version of FastAPI :rocket:Usage 📚To Identify the Metadata of your API:fromfastapiimportFastAPIfromfastapi_tag.base.modelimportContact,Metadata,Versionfromfastapi_tag.core.applicationimportApplicationapp=FastAPI()defmetadata(app):returnMetadata(title="Hello World",version=Version(app="v0.1.1",api="v0.1.0"),description="A simple example of a FastAPI application.",contact=Contact(name="name",url="http://test.com",email=None),api_id="49786b4b-1889-46ec-bd72-27f332436e6f",audience="company-internal",)defapp(metadata):returnApplication("",metadata)We have alsoProblemclass thats depends on:title: The title of the problem.status: The status code of the problem.detail: A human-readable explanation specific to this occurrence of the problem.instance: A URI reference that identifies the specific occurrence of the problem.type: A URI reference that identifies the problem type.NameSpaceis a is a decorator that adds a route generator to the namespace object.for example:fromfastapi_tag.router.routersimportNamespaceroute=Namespace([])Format the code 💅Execute the following command to applypre-commitformatting:makelintTODO 🚧Extend theProblemclass to add more information.Add more features to theMetadataclass.Add more features to theVersionclass.Provide a detailed documentation forfastapi_tagpackage.License 🍻This project is licensed under the terms of the MIT license.
Package: fastapi-telegrambot
fastapi-telegrambotTelegramBot wrapped by FastAPIPrerequisiteCreate telegram bot. Bot's token is required.Usage - Runfromfastapi_telegrambotimportapplicationimportuvicornuvicorn.run('{}|application')Usage - APICheck the swagger. ( http://{host}:{port}/docs )Send a single text message.Send multiple text messages.TODOlogger
Package: fastapi_template
Flexible general-purpose template for FastAPI.Usage⚠️Git,PythonandPoetrymust be installed and accessible ⚠️Poetry version must be greater or equal than 1.1.8. Otherwise it won't be able to install SQLAlchemy.Templator in actionYou can install it directly from pypi with pip.python3-mpipinstallfastapi_template
python3-mfastapi_template# or fastapi_template# Answer all the questions# 🍪 Enjoy your new project 🍪cdnew_project
docker-compose-fdeploy/docker-compose.yml--project-directory.build
docker-compose-fdeploy/docker-compose.yml--project-directory.up--buildIf you want to install it from sources, try this:python3-mpipinstallpoetry
python3-mpipinstall.
python3-mfastapi_templateAlso, you can use it with docker.dockerrun--rm-it-v"$(pwd):/projects"s3rius/fastapi_templateFeaturesOne of the coolest features is that this project is extremely configurable.
You can choose between different databases and even ORMs, or
you can even generate a project without a database!
Currently SQLAlchemy 2.0, TortoiseORM, Piccolo and Ormar are supported.This project can run as TUI or CLI and has excellent code documentation.Generator features:Pydantic V2 (Where it's possible. Some libs doesn't have support);You can choose between GraphQL and REST api;Uvicorn and gunicorn;Different databases support;Different ORMs support;Optional migrations for each ORM except raw drivers;Optional redis support;Optional rabbitmq support;different CI\CD;Optional Kubernetes config generation;Optional Demo routers and models (This helps you to see how project is structured);Pre-commit integration;Generated tests with almost 90% coverage;Tests for the generator itself;Optional Prometheus integration;Optional Sentry integration;Optional Loguru logger;Optional Opentelemetry integration.Optional taskiq integration.This project can handle arguments passed through command line.$python-mfastapi_template--help

Usage:fastapi_template[OPTIONS]Options:-n,--nameTEXTNameofyourawesomeproject-V,--versionPrintscurrentversion--forceOwerritedirectoryifitexists--quiteDonotaskforfeaturesduringgeneration--api-type[rest|graphql]SelectAPItypeforyourapplication--db[none|sqlite|mysql|postgresql]Selectadatabaseforyourapp--orm[none|ormar|sqlalchemy|tortoise|psycopg|piccolo]ChooseObject–RelationalMapperlib--ci[none|gitlab_ci|github]SelectaCIforyourapp--redisAddredissupport--rabbitAddRabbitMQsupport--taskiqAddTaskiqsupport--migrationsAddMigrations--kubeAddkubernetesconfigs--dummyAdddummymodel--routersAddexamplerouters--swaggerAddselfhostedswagger--prometheusAddprometheuscompatiblemetrics--sentryAddsentryintegration--loguruAddlogurulogger--opentelemetryAddopentelemetryintegration--traefikAddstraefiklabelstodockercontainer--kafkaAddKafkasupport--gunicornAddgunicornserver--helpShowthismessageandexit.
Package: fastapi-testdb
fastapi-testdbFastAPIis a cool framework for building
fast and reliable API. It provides various tools to create an app you want. Also
it has convenient way to cover the code with tests. Read the articles for more
detailsTestingandTesting a Database.
It covers the most aspects of testing, but sadly one important thing was left
behind scenes. You have to recreate the database every time before run each test
to make testsreproducible, otherwise be ready to get unpredictible results
after every test run.This package helps you to make database tests reproducible.Installationpipinstallfastapi-testdbUsageLet's say you have a FastAPI instanceappwith dependencyconnect_dbto get a connection
to your database. Your SQLAlchemy ORM base class isBaseOrm. Common usage of TestDB for having
repeatable tests:First create a class by callcreate_testdb:fromfastapi_testdbimportcreate_testdbtestdb=create_testdb(app,connect_db,BaseOrm,dsn='sqlite:////tmp/your-testdb.sqlite')testdbis your new class type targeted to connect to the test database. In this case it is
an SQLite DB, but you can use other databases - PostgreSQL, MySQL and everything that
supported by SQLAlchemy.You have to passconnect_dbbecause this dependecy must be replaced on a test run for not
to harm you real database.BaseOrmwill be used to get metadata when the SQL tables create.Now you can use the new class for creating reproducible DB state:deftest_yourtestfunc():withtestdb()astdb:# In this `with` statement a new DB was created and all the tables from# `BaseOrm.metadata` were initiated. Now you have a completely empty tables in the DB.# Do your test here:...Usage as a decoratorIt is also possible to use this as a decorator:@testdb.initdbdeftest_yourtestfunc(tdb):# A new DB is ready for testing. Do your test below...Insert test dataA new DB has created empty. If you have to fill tables with some data, you can useprefill_ormmethod. For example, let you have an ORM class for users:classUserDB(BaseOrm):id:Mapped[int]=mapped_column(primary_key=True,index=True)name:Mapped[str]=mapped_column(index=True,unique=True)To have some content on testing, call the methodprefill_orm:@testdb.initdbdeftest_yourtestfunc(tdb):users_fixture=[{"id":1,"name":"Bob"},{"id":2,"name":"Henry"},]tdb.prefill_orm(UserDB,users_fixture)# Now you have your users in the table:withTestClient(app)asclient:client=app.get('/user/1')assertclient.status_code==200ContributionYou are welcome to make contribution and proposals for improvement!
Package: fastapi-third-party-auth
FastAPI Third Party AuthDocumentation:https://fastapi-third-party-auth.readthedocs.io/Source Code:https://github.com/aiwizo/fastapi-third-party-authSimple library for using a third party authentication service withFastAPI. Verifies and decrypts 3rd party
OpenID Connect tokens to protect your endpoints.Easily used with authentication services such as:Keycloak(open source)SuperTokens(open source)Auth0OktaFastAPI's generated interactive documentation supports the grant flows:GrantType.AUTHORIZATION_CODEGrantType.IMPLICITGrantType.PASSWORDGrantType.CLIENT_CREDENTIALSInstallationpoetry add fastapi-third-party-authOr, for the old-timers:pip install fastapi-third-party-authUsageSeethis examplefor how to usedocker-composeto set up authentication withfastapi-third-party-auth+Keycloak.Standard usagefromfastapiimportDependsfromfastapiimportFastAPIfromfastapiimportSecurityfromfastapiimportstatusfromfastapi_third_party_authimportAuthfromfastapi_third_party_authimportGrantTypefromfastapi_third_party_authimportKeycloakIDTokenauth=Auth(openid_connect_url="http://localhost:8080/auth/realms/my-realm/.well-known/openid-configuration",issuer="http://localhost:8080/auth/realms/my-realm",# optional, verification onlyclient_id="my-client",# optional, verification onlyscopes=["email"],# optional, verification onlygrant_types=[GrantType.IMPLICIT],# optional, docs onlyidtoken_model=KeycloakIDToken,# optional, verification only)app=FastAPI(title="Example",version="dev",dependencies=[Depends(auth)],)@app.get("/protected")defprotected(id_token:KeycloakIDToken=Security(auth.required)):returndict(message=f"You are{id_token.email}")Optional: Custom token validationThe IDToken class will accept any number of extra fields but you can also
validate fields in the token like this:classMyAuthenticatedUser(IDToken):custom_field:strcustom_default:float=3.14auth=Auth(...,idtoken_model=MyAuthenticatedUser,)