Saravanan666/pypi-org huggingface dataset:
Package: fastapi-oracle
fastapi-oracleHelpers for using thepython-oracledblibrary with theFastAPIframework.Getting startedInstall a recent Python 3.x version (if you don't already have one).Create a project that usespython-oracledband FastAPI (if you don't already have one).Installfastapi-oracleas a dependency usingPoetry, pip, or similar:poetryaddfastapi-oracleSet DB config in environment variables:DB_HOST=foodbhost.aintitfootastic.comDB_PORT=1521DB_USER=foouserDB_PASSWORD=foopassDB_SERVICE_NAME=foodb1.aintitfootastic.comUse the utils:fromcollections.abcimportAsyncIterable,MappingfromcontextlibimportasynccontextmanagerfromtypingimportAny,AsyncGeneratorfromfastapiimportAPIRouter,Depends,FastAPI,Request,statusfromfastapi.responsesimportJSONResponsefromfastapi_oracleimport(DbPoolConnAndCursor,IntermittentDatabaseError,close_db_pools,cursor_rows_as_dicts,cursor_rows_as_gen,get_db_cursor,handle_db_errors,result_keys_to_lower,)fromloguruimportloggerfrompydanticimportBaseModelrouter=APIRouter()classFoo(BaseModel):id:intname:strasyncdefmap_list_foos_result_to_foos(result:AsyncIterable[Mapping[str,Any]])->AsyncGenerator[Foo,None]:"""Map a list foos DB result to a list of foos."""asyncforrowinresult:yieldFoo(**row)asyncdeflist_foos_query(db:DbPoolConnAndCursor)->AsyncGenerator[dict[str,Any],None]:"""List all foos."""cursor=awaitdb.conn.cursor()awaitcursor.execute("SELECT id, name FROM foo")cursor_rows_as_dicts(cursor)rows=(rowasyncforrowincursor_rows_as_gen(cursor))asyncforrowinresult_keys_to_lower(rows):yieldrow@handle_db_errorsasyncdef_get_foos(db:DbPoolConnAndCursor)->list[Foo]:result=list_foos_query(db)foos=[xasyncforxinmap_list_foos_result_to_foos(result)]returnfoos@router.get("/",response_model=list[Foo])asyncdefread_foos(db:DbPoolConnAndCursor=Depends(get_db_cursor)):foos=await_get_foos(db)logger.info(f"Fetched{len(foos)}foos")returnfoosasyncdefintermittent_database_error_handler(request:Request,exc:IntermittentDatabaseError,)->JSONResponse:returnJSONResponse(status_code=status.HTTP_503_SERVICE_UNAVAILABLE,content={"detail":[{"msg":f"{exc}","type":"intermittent_database_error",}],},)defget_app()->FastAPI:"""Create a FastAPI app instance."""@asynccontextmanagerasyncdeflifespan(app:FastAPI):yieldawaitclose_db_pools()app=FastAPI(lifespan=lifespan,exception_handlers={IntermittentDatabaseError:intermittent_database_error_handler,},)app.include_router(router)returnappDevelopingTo clone the repo:gitclonegit@github.com:Jaza/fastapi-oracle.gitTo automatically fix code style issues:./scripts/format.shTo verify code style and static typing:./scripts/verify.shTo run tests:./scripts/test.shTo run tests that need to connect to a real database:./scripts/testdb.shBuildingTo build the library:poetrybuildBuilt bySeertech.
Package: fastapi-ormar-utilities
FASTAPI-ORMAR-UTILITIESSmall package for better interaction with Ormar ORM.This package makes your views cleanerFeatures:Fully asyncCompatible with FastAPIIn my opinion Ormar is the best ORM for FastAPISupportselect_related()methodHandleNot foundexceptionsInstall with pippip install fastapi-ormar-utilities[all]Example usage:fromfastapiimportAPIRouter,Dependsfromfastapi_ormar_utilitiesimportBasefrom.modelsimportItem# import Ormar modelfrom.schemasimportItemCreate# import Pydantic modelrouter=APIRouter()classItemService(Base):model=Item@router.get('/')asyncdefget_items(service:ItemService=Depends()):returnawaitservice.fetch_all()@router.get('/')asyncdefget_items_with_related(service:ItemService=Depends()):# if you want to add related field to the queryreturnawaitservice.fetch_all(related_field='some_field')@router.post('/')asyncdefcreate_item(item_data:ItemCreate,service:ItemService=Depends()):returnawaitservice.create(item_data)
Package: fastapi-paginate
FastAPI PaginationInstallation# Basic versionpipinstallfastapi-paginate# All available integrationspipinstallfastapi-paginate[all]Available integrations:sqlalchemyginodatabasesormarormtortoisedjangopiccolosqlmodelmotormongoengineExamplefromfastapiimportFastAPIfrompydanticimportBaseModelfromfastapi_paginateimportPage,add_pagination,paginateapp=FastAPI()classUser(BaseModel):name:strsurname:strusers=[User(name='Yurii',surname='Karabas'),# ...]@app.get('/users',response_model=Page[User])asyncdefget_users():returnpaginate(users)add_pagination(app)This repo is forked fromfastapi-pagination.
Although original repository is already good enough, but I modified it according to my needs and published thinking it might be helpful for some.
Package: fastapi-pagination
Introductionfastapi-paginationis a Python library designed to simplify pagination in FastAPI applications.
It provides a set of utility functions and data models to help you paginate your database queries
and return paginated responses to your clients.Withfastapi-pagination, you can easily define pagination parameters in your FastAPI endpoint functions,
and use them to generate paginated responses that include the requested subset of your data.
The library supports a variety of pagination strategies, including cursor-based pagination and page-based pagination.fastapi-paginationis built on top of the popularfastapilibrary, and it works with a wide range
of SQL and NoSQL databases frameworks. It also supports async/await syntax and is compatible with Python 3.8 and higher.Features:Simplifies pagination in FastAPI applications.Supports a variety of pagination strategies, including cursor-based pagination and page-based paginationWorks with a wide range of SQL and NoSQL databases frameworks, includingSQLAlchemy,Tortoise ORM, andPyMongo.Supports async/await syntax.Compatible with Python 3.8 and higher.For more information on how to use fastapi-pagination, please refer to theofficial documentation.Installationpipinstallfastapi-paginationQuickstartAll you need to do is to usePageclass as a return type for your endpoint and callpaginatefunction
on data you want to paginate.fromfastapiimportFastAPIfrompydanticimportBaseModel,Field# import all you need from fastapi-paginationfromfastapi_paginationimportPage,add_pagination,paginateapp=FastAPI()# create FastAPI appclassUserOut(BaseModel):# define your modelname:str=Field(...,example="Steve")surname:str=Field(...,example="Rogers")users=[# create some data# ...]@app.get('/users')asyncdefget_users()->Page[UserOut]:# use Page[UserOut] as return type annotationreturnpaginate(users)# use paginate function to paginate your dataadd_pagination(app)# important! add pagination to your appPlease, be careful when you work with databases, because defaultpaginatewill require to load all data in memory.For instance, if you useSQLAlchemyyou can usepaginatefromfastapi_pagination.ext.sqlalchemymodule.fromsqlalchemyimportselectfromfastapi_pagination.ext.sqlalchemyimportpaginate@app.get('/users')defget_users(db:Session=Depends(get_db))->Page[UserOut]:returnpaginate(db,select(User).order_by(User.created_at))Code fromQuickstartwill generate OpenAPI schema as bellow:
Package: fastapi-pagination-utilities
FastAPI Pagination UtilitiesThis Python package contains utilities to aid in paginating responses from
FastAPI applications.UseInstallfastapi-pagination-utilitiesusing pip:pip install fastapi-pagination-utilitiesThe module can then be used asfastapi_pagination:fromfastapiimportFastAPIfromfastapi_paginationimport(CURSOR_QUERY,PAGE_SIZE_QUERY,PaginationDetails,PaginatedResults)frompydanticimportBaseModelapp=FastAPI()classWidget(BaseModel):name:str@app.get('/widgets',summary="List widgets",description="List all the widgers which are available."response_model=PaginatedResults[Widget])deflist_widgets(request:Request,cursor:Optional[str]=CURSOR_QUERY,page_size:Optional[int]=PAGE_SIZE_QUERY):# Get pagination.pagination=PaginationDetails(cursor,page_size)# list_widgets() should take a page size and offset and return a list of# results.results,has_more=list_widgets(pagination.offset,pagination.page_size)returnPaginatedResults(next=(str(request.url.include_query_params(cursor=pagination.next_cursor()))ifhas_moreelseNone),previous=(str(request.url.include_query_params(cursor=pagination.previous_cursor()))ifpagination.previous_cursor()elseNone),results=results)Developer 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-paseto-auth
FastAPI PASETO AuthDocumentation:https://chloe-ko.github.io/fastapi-paseto-authSource Code:https://github.com/Chloe-ko/fastapi-paseto-authFastAPI extension that provides PASETO (Plastform-AgnosticSEcurityTOkens) Auth supportPASETO are a simpler, yet more secure alternative to JWTs.If you were familiar with flask-jwt-extended or fastapi-jwt-auth this extension suitable for you, as this is forked from fastapi-jwt-auth which in turn used flask-jwt-extended as motivationFeaturesAccess tokens and refresh tokensFreshness TokensRevoking TokensSupport for adding custom claims to TokensBuilt-in Base64 Encoding of TokensCustom token typesInstallationThe easiest way to start working with this extension with pippipinstallfastapi-paseto-authRoadmapSupport for WebSocket authorizationFAQWhere's support for tokens in cookies?I mostly forked fastapi-jwt-auth because I needed a library to use for authentication using PASETO tokens in my private FastAPI Application. Which is why I only kept the functionality that I personally required.Personally, I'm not a fan of saving data in cookies, and cookie support made up a big part of the code which just didn't make sense for me to bother adapting.Hence, I likely will not be implementing support for storing PASETO tokens in cookies unless there is a considerable amount of people wanting it.However, I will gladly accept PRs implementing tokens in cookies if someone else wants to implement it.LicenseThis project is licensed under the terms of the MIT license.
Package: fastapi_passwordless
Passwordless Auth for FastAPIReady-to-use passwordless auth for FastAPIDocumentation:https://amirasaad.github.io/fastapi-passwordless/Source Code:https://github.com/amirasaad/fastapi-passwordlessAdd quickly a passwordless authentication system to yourFastAPIproject.FeaturesAuthenticate users by email.Authenticate users by phone.API key option for developer's API.LicenseThis project is licensed under the terms of the MIT license.
Package: fastapi-peewee-filter
fastapi-peewee-filter简介参考：https://github.com/arthurio/fastapi-filter但是这个 fastapi-filter 只支持 SQLAlchemy，所以我搞了一个 fastapi-peewee-filter 用于支持 peewee 这个 ORM安装Python 解释器:CPython : 3.8 及以上版本
Package: fastapi-plus
#Fastapi Plus
这是一个Python FastAPI项目工程库，包含DB、Redis、MongoDB、JSON等工具和基础服务类。Github: Fastapi Plus组件：FastAPI:https://fastapi.tiangolo.com/uvicorn:https://www.uvicorn.org/SQLAlchemy:https://www.sqlalchemy.org/PyMySQL:https://pymysql.readthedocs.io/REDIS:https://github.com/andymccurdy/redis-py
Package: fastapi-poe
fastapi_poeAn implementation of thePoe protocolusing
FastAPI.Write your own botThis package can also be used as a base to write your own bot. You can inherit fromPoeBotto make a bot:importfastapi_poeasfpclassEchoBot(fp.PoeBot):asyncdefget_response(self,request:fp.QueryRequest):last_message=request.query[-1].contentyieldfp.PartialResponse(text=last_message)if__name__=="__main__":fp.run(EchoBot(),allow_without_key=True)Now, run your bot usingpython <filename.py>.In a different terminal, runngrokto make it publicly
accessible.Use the publicly accessible url to integrate your bot withpoeEnable authenticationPoe servers send requests containing Authorization HTTP header in the format "Bearer
<access_key>"; the access key is configured in the bot settings page.To validate that the request is from the Poe servers, you can either set the environment
variable POE_ACCESS_KEY or pass the parameter access_key in the run function like:if__name__=="__main__":fp.run(EchoBot(),access_key=<key>)SamplesCheck out our starter coderepositoryfor some examples
you can use to get started with bot development.
Package: fastapi_project_pattern
FastAPI project pattern with toolsFastAPICeleryRabbitMQMongoDB(PyMongo)PostgreSQL(SQL Alchemmy, Alembic)Web SocketSend email with SendgridCloudinaryDeploymentsLocationCI/CD.gitlab-ci.ymlGitlab CI/CD.circleci/config.ymlCircleCI./scripts/aws/*.shAWS CodeDeploy./scripts/vps/*.shManual DeployInstallationpip install fastapi_project_patternfrompathlibimportPathfromfastapi_project_patternimportstart_creation# See help(start_creation) for morestart_creation(Path.cwd())
Package: fastapi-prometheus-exporter
fastapi-prometheus-exporterFastAPI Prometheus Exporter is a simple Prometheus exporter for FastAPI applications. It provides a set of metrics by default and allows you to add your own metrics as well.Installationpipinstallfastapi-prometheus-exporterorpoetryaddfastapi-prometheus-exporterUsagefromfastapiimportFastAPIfromfastapi_prometheus_exporterimportPrometheusExporterMiddlewareapp=FastAPI()PrometheusExporterMiddleware.setup(app=app,metrics_path="/metrics",# ignore_paths=["/healthz", "/metrics"],)Parametersapp: FastAPI application instanceignore_paths: List of paths to ignore. Default:[]metrics_path: Path to expose metrics. Default:/metricsmetrics_registry: Prometheus registry to use. Default:prometheus_client.CollectorRegistryrequest_latency_name: Name of the request latency metric. Default:http_request_duration_secondsrequest_latency_doc: Description of the request latency metric. Default:HTTP Request Latencyrequest_latency_buckets: Buckets for the request latency metric. Default:prometheus_client.Histogram.DEFAULT_BUCKETSrequest_latency_labels: Labels for the request latency metric. Default:["method", "endpoint", "http_status"]request_count_name: Name of the request count metric. Default:http_requests_totalrequest_count_doc: Description of the request count metric. Default:Total HTTP Requestsrequest_count_labels: Labels for the request count metric. Default:["method", "endpoint", "http_status"]MetricsDefault Metricshttp_request_duration_seconds: HTTP request latency in secondshttp_requests_total: Total HTTP requests
Package: fastapi-proxiedheadersmiddleware
HTTP Proxy Header support for FastAPIThis Python package allows transparent use of FastAPI-based solutions behind
proxies which setX-Forwarded-...headers. Applications will construct URLs
based on those headers rather than the incomingHostheader.UseInstallfastapi-proxiedheadersmiddlewareusing pip:pip install fastapi-proxiedheadersmiddlewareThe module can then be used asfastapi_proxiedheadersmiddlewarewhen creating
your FastAPI app:fromfastapiimportFastAPIfromfastapi_proxiedheadersmiddlewareimportProxiedHeadersMiddlewareapp=FastAPI()app.add_middleware(ProxiedHeadersMiddleware)The middleware respects the variousX-Forwarded-...headers and updates theHostheader to match.Developer 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-proxy-lib
FastAPI Proxy LibHTTP/WebSocket proxy for starlette/FastAPICI/CDCodePackageMetaDocumentation:https://wsh032.github.io/fastapi-proxy-lib/Source Code:https://github.com/WSH032/fastapi-proxy-lib/FeaturesOut of the box !Helper functionsto get FastAPIapp/routerfor proxy conveniently.OnlyStarletteis requiredfor it to work (FastAPIis optional).Support bothHTTPandWebSocketproxy.Supports all HTTP methods (GET,POST, etc.)Support bothreverseproxy andforwardproxy.Transparentlyandlosslesslyhandle all proxy requests,
IncludingHTTP headers,cookies,query parameters,body, etc.Asynchronous streaming transfer, supportfile proxy.other featuresStrict linting and strict-mode Pyright type checking.100%Type Completeness,Code coverage ofover 95%.Forced keep-alive connections, minimizing proxy latency.Handle errors as gracefully as possible.fastapi-proxy-libhas a well-designed mechanism behind the scenes to handle exceptional websocket disconnections for you.fastapi-proxy-libwill exit as gracefully as possible.FastAPI Proxy Libstands on the shoulders of giantshttpxfor HTTP proxyhttpx-wsfor WebSocket proxySo, it perfectly supports all features ofhttpx.AsyncClient, you can even use your customAsyncClient,Transport.exceptcookiesandbase_urlarguments, which are taken over byfastapi-proxy-libInstallation!!! noteWe follow semantic versioning.<br>
This is a young project, and before 1.0.0, there may be changes in the API (we try to avoid that).<br>
We will release security updates at any time, please try to keep the version updated, instead of pinning to the old version.<br>
pin to `major version` is recommended.<br>
visit our `CHANGELOG.md` for more info.pipinstallfastapi-proxy-libPerhaps you've noticed that we're installingfastapi-proxy-lib[standard]instead offastapi-proxy-lib. The difference is:The former will installFastAPIat the same time.The latter installs only the basic dependencies forfastapi-proxy-lib.If youonly need to use this library with Starlette, you only need to install the latter.Quick startWith the helper functions, get the FastAPI proxy server app is very convenient and out of the box:fromfastapi_proxy_lib.fastapi.appimportreverse_http_appapp=reverse_http_app(base_url="http://www.example.com/foo/")That's all! Now, you can launch the proxy server withuvicorn:uvicornmain:app--host127.0.0.1--port8000Then, visithttp://127.0.0.1:8000/bar?baz=1, you will get the response fromhttp://www.example.com/foo/bar?baz=1.Continue, please visit to our documentation 📚 for more details:support forFastAPI routeronlyStarlettedependencyWebSocketproxydevelopmentIf you find any issues, please don't hesitate toopen an issue.If you need assistance, feel free tostart a discussion.Follow ourCONTRIBUTING.md,PR Welcome!Security 😰❗: We value any security vulnerabilities,please report to us privately, pretty appreciated for that.English is not the native language of the author (me), so if you find any areas for improvement in the documentation, your feedback is welcome.If you think this project helpful, consider giving it a star, which makes me happy. :smile:LicenseThis project is licensed under the terms of theApache License 2.0.
Package: fastapi-pubsub
FastAPI Pub/SubA simple but yet elegant publish/subscribe socket implementation using FastAPI Websocket.Installationpip install fastapi-pubsubHow it worksFastAPI provides an awesome implementation of Websockets. But it can be painful to configure it to work as a publish/subscribe mechanism.FastAPI Pub/Sub implemented aBasePubSubWebSocketthat handles all client's connections under the hood. All you have to do is extend this class, overriding the methodgenerate_object_to_send(self)with your desired logic.fromfastapi_pubsubimportBasePubSubWebSocketclassSimplePubSubWebsocket(BasePubSubWebSocket):asyncdefgenerate_object_to_send(self):# any logic that you want to implement to send to connected usersconnections=self.connection_manager.get(self.websocket_id)return{"num_connected_clients":len(connections)}app=FastAPI()@app.websocket("/ws/connected_clients")asyncdefonline_players_endpoint(websocket:WebSocket):ssw=SimplePubSubWebsocket(websocket,'connected_clients')awaitssw.run()BasePubSubWebSocket constructor parametersParameterMandatoryDefaultDescriptionwebsocketyes-the fastapi websocket instancechannel_idyes-a custom unique id that identifies that operation. used by connection manager to group clients connected in the same channelredis_credentialsnoNone. if not passed, uses thedict in-memoryimplementationredis host, port, username, password and db configurationA minimum example of a server/client communication can be seenhere.Follow the instructions to see it working.ContributingDespite being full functional, this project is in a very early stage.Pull requests are very welcome!
Package: fastapi-query-conditions
fastapi-query-conditionsIntroductionFastAPI-Query-Conditions is a dependency that parses a query string into conditions using operators enclosed in square brackets.For example, if you send a request to/orders?amount[gte]=1000&amount[lt]=2000, you can use the query string as parsed conditions like this:{"gte":1000,"lt":2000}Install>pipinstallfastapi-query-conditionsQuick StartfromtypingimportDictfromfastapiimportDepends,FastAPIfromfastapi_query_conditionsimportquery_conditionsapp=FastAPI()@app.get("/items")defquery_items(amount:Dict[str,int]=Depends(query_conditions(field='amount',factory=int))):print(amount)returnamountThen, if you send a request to/items?amount[gte]=1000&amount[lt]=2000, you can check the following results.{'gte':1000,'lt':2000}Also, you can use various factory functions for your query parameter.fromdatetimeimportdatetimefromtypingimportDictfromfastapiimportDepends,FastAPIfromfastapi_query_conditionsimportquery_conditionsapp=FastAPI()@app.get("/orders")defquery_orders(time:Dict[str,int]=Depends(query_conditions(field='time',factory=datetime.fromisoformat))):print(time)returntimeThen, if you send a request to/orders?time[gte]=2022-10-18T12:00&time[lt]=2022-10-18T12:30, you can check the following results.{'gte':datetime.datetime(2022,10,18,12,0),'lt':datetime.datetime(2022,10,18,12,30)}
Package: fastapi-query-flatten
QueryFlattenMiddleware for FastAPIQueryFlattenMiddlewareis a custom middleware for FastAPI applications that flattens query parameters separated by a specified delimiter. This is particularly useful for endpoints that need to handle multiple values for the same query parameter without using the standard array format.FeaturesCustomizable Delimiter: Easily configure the delimiter used for splitting query parameter values.Seamless Integration: Works as middleware within any FastAPI application.Efficient Query Handling: Simplifies the process of handling multiple query parameters by flattening them, making endpoint logic cleaner and more straightforward.RequirementsPython 3.8.1+FastAPIInstallationTo installQueryFlattenMiddleware, you can use pip:pipinstallfastapi-query-flattenUsageTo useQueryFlattenMiddlewarein your FastAPI application, simply add it as middleware in your app instance. Specify the delimiter you want to use for splitting query parameter values. The default delimiter is a comma (,).ExamplefromfastapiimportFastAPIfromfastapi_query_flattenimportQueryFlattenMiddlewareapp=FastAPI()# Add QueryFlattenMiddleware with a custom delimiterapp.add_middleware(QueryFlattenMiddleware,delimiter=",")With the middleware in place, a request to/items/?filter=value1,value2,value3will be processed as if it were/items/?filter=value1&filter=value2&filter=value3, allowing thefilterquery parameter to be easily handled as multiple values.ContributingContributions are welcome! If you have a feature request, bug report, or a pull request, please open an issue or submit a PR on the project's repository.LicenseThis project is licensed under the MIT License - see the LICENSE file for details.
Package: fastapi-queue-task
FastAPI queueHow to useInstance the classQueuewithredisinstance andoptions# queue_config.pyfromfastapi_queue_taskimportQueuefromredis.asyncio.utilsimportfrom_urlredis=from_url(f"redis://#REDIS_HOST:#REDIS_PORT/#REDIS_DATABASE_NAME",encoding="utf-8",decode_responses=True,)queue=Queue(redis,options={'concurrency':10,'max_attempt':3})queue.run()Add task to queue:# mail_service.pyawaitqueue.add_to_queue(name="TASK_NAME",data:Any={})How to test in testpypiIncrease the version inpyproject.tomlRun command$../build_and_test.shHow to publish new versionIncrease the version inpyproject.tomlRun command$../build_and_publish.sh