Saravanan666/pypi-org huggingface dataset:
Package: fastapi-range-response
Fastapi Range ResponseDescriptionHTTP range response for FastapiPart of the code is based on changes toBáiZéFileResponse实现了HTTP Range的响应类, 继承自starlette.response.Response, 可使用本机文件或sftp协议进行读取文件Installpip install fastapi_range_responseQuickStartA short example for fastapi applicationimportasyncioimportasyncsshfromfastapiimportFastAPIfromfastapiimportQueryfromfastapi_range_responseimportFileRangeResponse,AsyncsshRangeResponseapp=FastAPI()@app.get('/local_file')asyncdefdownload_local_file(full_path:str=Query()):returnFileRangeResponse(full_path,media_type='application/octet-stream')@app.get('/download_sftp_file')asyncdefdownload_sftp_file(full_path:str=Query()):ssh_client=awaitasyncio.wait_for(asyncssh.connect(host='xxx',port=22,username='xxx',password='xxxx',known_hosts=None),timeout=10)returnAsyncsshRangeResponse(full_path,ssh_client,done_close=True)if__name__=='__main__':importuvicornuvicorn.run(app)
Package: fastapi-ratelimiter
FastAPI Ratelimiter[]Documentation:https://fastapi-ratelimit.readthedocs.io/en/latest/Quick start:importasyncioimportaioredisimportuvicornfromfastapiimportFastAPI,Dependsfromstarlette.responsesimportJSONResponsefromfastapi_ratelimiterimportRateLimited,RedisDependencyMarkerfromfastapi_ratelimiter.strategiesimportBucketingRateLimitStrategyapp=FastAPI()redis=aioredis.from_url("redis://localhost")@app.get("/some_expensive_call",response_class=JSONResponse,dependencies=[Depends(RateLimited(BucketingRateLimitStrategy(rate="10/60s")))])asyncdefhandle_test_endpoint():awaitasyncio.sleep(5)return{"hello":"world"}app.dependency_overrides[RedisDependencyMarker]=lambda:redisif__name__=='__main__':uvicorn.run(app)
Package: fastapi-redis
Fastapi RedisThis package provides a client that integrates with Fastapi and provides a decorator to cache fastapi controllers responses.Installation$ pip install fastapi_redisUsageClientSetting the dataimportredis_clientfromfastapi_redisredis_client.set('some_key','some_data')Models can be saved as well and the client will serialize them to json:importredis_clientfromfastapi_redisfrompydantic.mainimportBaseModelMyModel(BaseModel):data:strredis_client.set('some_key',MyModel(data='some_data'))redis_client.set('some_key',MyModel(data='some_data_that_expires'),expiration=timedelta(days=1))The data can be saved using theFastapi Background Tasksso it wouldn't generate any delay on the response to the user:importredis_clientfromfastapi_redis@router.get('/')asyncdefmy_controller_method(background_tasks:BackgroundTasks):redis_client.set_in_background(background_tasks,'some_key','some_data')redis_client.set_in_background(background_tasks,'some_key',MyModel(data='some_data_that_expires'),expiration=timedelta(days=1))Getting the dataimportredis_clientfromfastapi_redissome_data=redis_client.get('some_key')@redis_cache decoratorThe@redis_cachedecorator can be used to cache the response from a controller. Any argument of the controller can be used to specify the key of the data to store and ifbackground_tasks: BackgroundTasksis defined as an argument it will store the data in the background as well:importredis_clientfromfastapi_redis@router.get('/resource/{id}')@router_cache('resource_{id}_{user.id}',timedelta(days=1))asyncdefmy_controller_method(id:str,user:User=Depends(get_current_user)background_tasks:BackgroundTasks):returnsome_data_that_will_be_cached
Package: fastapi-redis-rate-limiter
Fastapi redis rate limiter middlewareRedis Rate Limiter Middleware is a Python module that provides rate limiting functionality for FastAPI applications using Redis as the storage backend. It allows you to limit the number of requests a client can make within a specified time window.FeaturesSimple integration with FastAPI applicationsCustomizable rate limit and time windowUses Redis as the storage backend for efficient rate limitingEasy to configure and useInstallationInstall the Redis Rate Limiter Middleware module usingpip:pipinstallfastapi_redis_rate_limiterUsageHere's an example of how to use the Redis Rate Limiter Middleware in a FastAPI application:fromfastapiimportFastAPIfromfastapi_redis_rate_limiterimportRedisRateLimiterMiddleware,RedisClientapp=FastAPI()# Initialize the Redis clientredis_client=RedisClient(host="localhost",port=6379,db=0)# Apply the rate limiter middleware to the appapp.add_middleware(RedisRateLimiterMiddleware,redis_client=redis_client,limit=40,window=60)@app.get("/limited")asyncdeflimited():return{"message":"This is a protected endpoint."}# Run the FastAPI applicationif__name__=="__main__":importuvicornuvicorn.run(app,host="0.0.0.0",port=8000)In this example, we create a FastAPI application and initialize a Redis client usingRedisClient. Then, we addRedisRateLimiterMiddlewareto the app middleware usingadd_middlewareand by passing in Redis client, rate limit, and time window.Make sure to adjust the Redis connection parameters (host, port, and db) according to your Redis server configuration.ConfigurationThe RedisRateLimiterMiddleware accepts the following parameters:app(FastAPI): The FastAPI application instance.redis_client(RedisClient): The Redis client instance for interacting with Redis.limit(int): The maximum number of requests allowed within the time window.window(int): The time window in seconds within which the requests are limited (default: 60 seconds).Adjust thelimitandwindowvalues according to your desired rate limiting requirements.ContributionsContributions, issues, and feature requests are welcome! Feel free to open a new issue or submit a pull request on GitHub.LicenseThis project is licensed under the MIT License. See theLICENSEfile for details.
Package: fastapi-redis-session
fastapi-redis-sessionA redis-based session backend for Fastapi appsInstallpipinstall-Ufastapi-redis-sessionUsefromtypingimportAnyfromfastapiimportDepends,FastAPI,Request,Responsefromfastapi_redis_sessionimportdeleteSession,getSession,getSessionId,getSessionStorage,setSession,SessionStorageapp=FastAPI(title=__name__)@app.post("/setSession")asyncdef_setSession(request:Request,response:Response,sessionStorage:SessionStorage=Depends(getSessionStorage)):sessionData=awaitrequest.json()setSession(response,sessionData,sessionStorage)@app.get("/getSession")asyncdef_setSession(session:Any=Depends(getSession)):returnsession@app.post("/deleteSession")asyncdef_deleteSession(sessionId:str=Depends(getSessionId),sessionStorage:SessionStorage=Depends(getSessionStorage)):deleteSession(sessionId,sessionStorage)returnNoneConfigDeafult Configurl of Redis: redis://localhost:6379/0name of sessionId: ssidgenerator function of sessionId:lambda :uuid.uuid4().hexexpire time of session in redis: 6 hoursCustom Configfromfastapi_redis_session.configimportbasicConfigbasicConfig(redisURL="redis://localhost:6379/1",sessionIdName="sessionId",sessionIdGenerator=lambda:str(random.randint(1000,9999)),expireTime=timedelta(days=1),)
Package: fastapi-request-helper
FastAPI Request helperHow to useSet a variable# user_service.pyfromfastapiimportFastAPIfromfastapi_global_variableimportGlobalVariableapp=FastAPI(title="Application")GlobalVariable.set('app',app)Use variablefromfastapi_global_variableimportGlobalVariableprint(GlobalVariable.get_or_fail('app'))print(GlobalVariable.get('app'))DecoratorsFastAPI Request Helper provides lots of helpful decorators:Swagger docs decorators: @controller, @tag, @get, @post, @put, @delete, @patchRate limit request: @rate_limitFastAPI response model: @responseFastAPI guards: @guard, @guradsFastAPI response status: @statusFastAPI API info details: @description, @summary, @nameFastAPI API response status: @status_no_content, @status_ok, @status_createdHide API: @hidden_when(condition: boolean)Fast API Helper also provides Pagination Query params helper: PaginationParams# Samplefromfastapi_request_helperimport(controller,post,rate_limit,response,status_created,status_no_content,status_ok,tag,)@controller('authentications')@tag('Authentication')classAuthenticationController:def__init__(self,auth_service:AuthenticationService=Depends()):self.auth_service=auth_service@post('create-email-otp')@status_no_content()asyncdefcreate_email_otp(self):passHow to test in testpypiSetup file .pypirc$cd~/$vim.pypircCopy to file .pypirc[pypi]
username=****
password=****

[testpypi]
username=__token__
password=*****

[distutils]

index-servers =
  pypi
  testpypi
  gitlab

[gitlab]
repository = https://gitlab.com/api/v4/projects/50838104/packages/pypi
username = gitlab+deploy-token-3497403
password = ****Increase the version inpyproject.tomlRun command$./build_and_test.shinstall package$pipinstall--no-cache-dir--upgrade-ihttps://test.pypi.org/simple/fastapi-request-helper==x.y.z--no-dependencies
$pipinstall-ihttps://test.pypi.org/simple/fastapi-request-helper==x.y.zHow to publish new versionIncrease the version inpyproject.tomlRun command$./build_and_publish.sh
Package: fastapi-request-id
FastApi Request IDAugments each request with unique request_id attribute and provides request id logging helpers.Quickstartpipinstallfastapi-request-idimportlogging.configfromfastapi_request_idimport(RequestContextMiddleware,BaseExceptionHandler,get_request_id,get_headers,)fromfastapiimportFastAPI,Request,Responsefromfastapi.responsesimportJSONResponsefromhttpximportClientclassCustomExceptionHandler(BaseExceptionHandler):@staticmethoddefbuild_response(request:Request,exc:Exception)->Response:returnJSONResponse(status_code=200,content={'error':True,'request_id':get_request_id(),})app=FastAPI()app.add_middleware(RequestContextMiddleware)app.add_exception_handler(Exception,CustomExceptionHandler())LOGGING_CONFIG={'version':1,'disable_existing_loggers':True,'filters':{'RequestIdFilter':{'()':'fastapi_request_id.logging.RequestIdFilter',},},'handlers':{'default':{'level':'INFO','class':'logging.StreamHandler',"filters":["RequestIdFilter"]},},'loggers':{'':{'handlers':['default'],'level':'INFO','propagate':False},}}logging.config.dictConfig(LOGGING_CONFIG)logger=logging.getLogger()@app.get('/raise')defget_with_raise():raiseException('Raised error')@app.get('/')defroot():return{'request_id':get_request_id()}@app.get('/request')defrequest():headers=get_headers({'Authorization':"Bearer ...",})client=Client()response=client.get('http://localhost/request',headers=headers)returnresponse.json()
Package: fastapi-resource-server
FastAPI Resource ServerBuild an OIDC resource server using FastAPI.Your aplication receives the claims decoded from the access token.UsageRun keycloak on port 8888:dockercontainerrun--nameauth-server-d-p8888:8080\-eKEYCLOAK_USER=admin-eKEYCLOAK_PASSWORD=admin\jboss/keycloak:latestInstall dependenciespipinstallfastapifastapi_resource_serveruvicornCreate the main.py modulefromfastapiimportDepends,FastAPI,SecurityfrompydanticimportBaseModelfromfastapi_resource_serverimportJwtDecodeOptions,OidcResourceServerapp=FastAPI()decode_options=JwtDecodeOptions(verify_aud=False)auth_scheme=OidcResourceServer("http://localhost:8888/auth/realms/master",scheme_name="Keycloak",jwt_decode_options=decode_options,)classUser(BaseModel):username:strgiven_name:strfamily_name:stremail:strdefget_current_user(claims:dict=Security(auth_scheme)):claims.update(username=claims["preferred_username"])user=User.parse_obj(claims)returnuser@app.get("/users/me")defread_current_user(current_user:User=Depends(get_current_user)):returncurrent_userRun the applicationuvicornmain:app
Package: fastapi-responses
FastAPI ResponsesFindHTTPExceptions and turn them into documentedresponses. :tada:Installationpipinstallfastapi-responsesUsageThe simplest use case happens when we have a single exception being raised. We don't want to document the possible response manually, soFastAPI Responsescomes in handy.fromfastapiimportFastAPI,HTTPExceptionfromfastapi_responsesimportcustom_openapiapp=FastAPI()app.openapi=custom_openapi(app)@app.get("/{item_id}")defget_item(item_id:int):ifitem_id==0:raiseHTTPException(status_code=404,detail="Item not found.")return"Item exists!"Without FastAPI ResponsesWith FastAPI ResponsesRoadmapExtract HTTPException from stack.Extract any exception and document based on theexception_handlercontainer.Accept Python objects onHTTPExceptioninstantiation.LicenseThis project is licensed under the terms of the MIT license.
Package: fastapi-responseschema
☄️ FastAPI Response SchemaOverviewThis package extends theFastAPIresponse model schema allowing you to have a common response wrapper via afastapi.routing.APIRoute.This library supports Python versions>=3.8and FastAPI versions>=0.89.1.Getting startedInstall the packagepipinstallfastapi-responseschemaIf you are planning to use the pagination integration, you can install the package includingfastapi-paginationpipinstallfastapi-responseschema[pagination]UsagefromtypingimportGeneric,TypeVar,Any,Optional,ListfrompydanticimportBaseModelfromfastapiimportFastAPIfromfastapi_responseschemaimportAbstractResponseSchema,SchemaAPIRoute,wrap_app_responses# Build your "Response Schema"classResponseMetadata(BaseModel):error:boolmessage:Optional[str]T=TypeVar("T")classResponseSchema(AbstractResponseSchema[T],Generic[T]):data:Tmeta:ResponseMetadata@classmethoddeffrom_exception(cls,reason,status_code,message:str="Error",**others):returncls(data=reason,meta=ResponseMetadata(error=status_code>=400,message=message))@classmethoddeffrom_api_route(cls,content:Any,status_code:int,description:Optional[str]=None,**others):returncls(data=content,meta=ResponseMetadata(error=status_code>=400,message=description))# Create an APIRouteclassRoute(SchemaAPIRoute):response_schema=ResponseSchema# Integrate in FastAPI appapp=FastAPI()wrap_app_responses(app,Route)classItem(BaseModel):id:intname:str@app.get("/items",response_model=List[Item],description="This is a route")defget_operation():return[Item(id=1,name="ciao"),Item(id=2,name="hola"),Item(id=3,name="hello")]Te result ofGET /items:HTTP/1.1200OKcontent-length:131content-type:application/json{"data":[{"id":1,"name":"ciao"},{"id":2,"name":"hola"},{"id":3,"name":"hello"}],"meta":{"error":false,"message":"This is a route"}}DocsYou can find detailed info for this package in theDocumentation.ContributingContributions are very welcome!How to contributeJust open an issue or submit a pull request onGitHub.While submitting a pull request describe what changes have been made.More info onDocs sectionContributors Wall
Package: fastapi-rest
fastapi-restIntroductionFast restful API based on FastAPI and TortoiseORM.Installpipinstallfastapi-restQuick StartFirst, define yourListViewresource.fromfastapi_rest.resourceimportListViewclassUserList(ListView):model=Userfields=("name","age")Second, include router to your app.app.include_router(UserList.as_router())Now, you can visit the endpoint/userto get user list.ListViewExport the endpointGET /{resource}.classListView(Resource):paginator:Paginator=Paginator()fields:Optional[Tuple[str,...]]=Noneexclude:Optional[Tuple[str,...]]=Nonequeryset:Optional[QuerySet]=Nonequery:Optional[Type[BaseModel]]=NoneDetailViewExport the endpointGET /{resource}/{pk}.classDetailView(Resource):fields:Optional[Tuple[str,...]]=Noneexclude:Optional[Tuple[str,...]]=NoneCreateViewExport the endpointPOST /{resource}.classCreateView(Resource):schema:Optional[Type[BaseModel]]=NoneUpdateViewExport the endpointPUT /{resource}/{pk}.classUpdateView(Resource):schema:Type[BaseModel]DeleteViewExport the endpointDELETE /{resource}/{pk}.classDeleteView(Resource):passReferenceYou can see the exampleshere.LicenseThis project is licensed under theApache2.0License.
Package: fastapi-restful
Quicker FastApi developing toolsDocumentation:https://fastapi-restful.netlify.appSource Code:https://github.com/yuval9313/fastapi-restfulBase on:https://github.com/dmontagu/fastapi-utilsFastAPIis a modern, fast web framework for building APIs with Python 3.7+.But if you're here, you probably already knew that!FeaturesThis package includes a number of utilities to help reduce boilerplate and reuse common functionality across projects:Resource Class: Create CRUD with ease the OOP way withResourcebase class that lets you implement methods quick.Class Based Views: Stop repeating the same dependencies over and over in the signature of related endpoints.Response-Model Inferring Router: Let FastAPI infer theresponse_modelto use based on your return type annotation.Repeated Tasks: Easily trigger periodic tasks on server startupTiming Middleware: Log basic timing information for every requestOpenAPI Spec Simplification: Simplify your OpenAPI Operation IDs for cleaner output from OpenAPI GeneratorSQLAlchemy Sessions: TheFastAPISessionMakerclass provides an easily-customized SQLAlchemy Session dependencyIt also adds a variety of more basic utilities that are useful across a wide variety of projects:APIModel: A reusablepydantic.BaseModel-derived base class with useful defaultsAPISettings: A subclass ofpydantic.BaseSettingsthat makes it easy to configure FastAPI through environment variablesString-Valued Enums: TheStrEnumandCamelStrEnumclasses make string-valued enums easier to maintainCamelCase Conversions: Convenience functions for converting strings fromsnake_casetocamelCaseorPascalCaseand backGUID Type: The provided GUID type makes it easy to use UUIDs as the primary keys for your database tablesSee thedocsfor more details and examples.RequirementsThis package is intended for use with any recent version of FastAPI (depending onpydantic>=1.0), and Python 3.7+.Installationpipinstallfastapi-restful# For basic slim package :)pipinstallfastapi-restful[session]# To add sqlalchemy session makerpipinstallfastapi-restful[all]# For all the packagesLicenseThis project is licensed under the terms of the MIT license.
Package: fastapi-restful-extension
FastAPI-RESTful-Extension - is extension for FastAPI that allows you to easily create a REST API.Documentation:https://maximshumilo.github.io/fastapi-restful-extension/PyPI:https://pypi.org/project/fastapi-restful-extension/InstallationFastAPI-RESTful-Extension has the following dependencies:FastAPI <=0.78.0Python version:3.7, 3.8, 3.9or3.10From PyPIInstall package with pip frompypi.org$pipinstallfastapi-restful-extensionCollecting fastapi-restful-extension.........Installing collected packages: fastapi-restful-extensionSuccessfully installed fastapi-restful-extension-X.Y.Z
Package: fastapi-restful-myfork
Quicker FastApi developing toolsDocumentation:https://fastapi-restful.netlify.appSource Code:https://github.com/yuval9313/fastapi-restfulBase on:https://github.com/dmontagu/fastapi-utilsFastAPIis a modern, fast web framework for building APIs with Python 3.7+.But if you're here, you probably already knew that!FeaturesThis package includes a number of utilities to help reduce boilerplate and reuse common functionality across projects:Resource Class: Create CRUD with ease the OOP way withResourcebase class that lets you implement methods quick.Class Based Views: Stop repeating the same dependencies over and over in the signature of related endpoints.Repeated Tasks: Easily trigger periodic tasks on server startupTiming Middleware: Log basic timing information for every requestOpenAPI Spec Simplification: Simplify your OpenAPI Operation IDs for cleaner output from OpenAPI GeneratorSQLAlchemy Sessions: TheFastAPISessionMakerclass provides an easily-customized SQLAlchemy Session dependencyIt also adds a variety of more basic utilities that are useful across a wide variety of projects:APIModel: A reusablepydantic.BaseModel-derived base class with useful defaultsAPISettings: A subclass ofpydantic.BaseSettingsthat makes it easy to configure FastAPI through environment variablesString-Valued Enums: TheStrEnumandCamelStrEnumclasses make string-valued enums easier to maintainCamelCase Conversions: Convenience functions for converting strings fromsnake_casetocamelCaseorPascalCaseand backGUID Type: The provided GUID type makes it easy to use UUIDs as the primary keys for your database tablesSee thedocsfor more details and examples.RequirementsThis package is intended for use with any recent version of FastAPI (depending onpydantic>=1.0), and Python 3.7+.Installationpipinstallfastapi-restful# For basic slim package :)pipinstallfastapi-restful[session]# To add sqlalchemy session makerpipinstallfastapi-restful[all]# For all the packagesLicenseThis project is licensed under the terms of the MIT license.
Package: fastapi-rfc7807
fastapi-rfc7807FastAPImiddleware which translates server-side exceptions
intoRFC-7807compliant problem detail error responses.Installationfastapi_rfc7807requires Python 3.6+pip install fastapi_rfc7807UsageBelow is a simple example which shows the bare minimum needed to configure a FastAPI application
withfastapi_rfc7807.fromfastapiimportFastAPIfromfastapi_rfc7807importmiddlewareapp=FastAPI()middleware.register(app)@app.get('/error')asyncdeferror():raiseValueError('something went wrong')The resulting error returned from the server looks like:$curllocalhost:8000/error{"exc_type":"ValueError","type":"about:blank","title":"Unexpected Server Error","status":500,"detail":"something went wrong"}See theexamplesdirectory for additional examples.
Package: fastapirichlogger
FastAPIRichLoggerDescriptionFastAPIRichLogger is a robust and visually appealing logging system for FastAPI applications. Utilizing the power of therichlibrary, it enhances the standard logging capabilities with color-coded log levels, detailed request-response data, and a user-friendly format that improves both readability and debugging.InstallationInstall FastAPIRichLogger with pip:pipinstallfastapirichloggerUsageTo use FastAPIRichLogger in your FastAPI application, follow these steps:Import FastAPIRichLogger:fromfastapirichloggerimportFastAPIRichLoggerAdd Middleware to FastAPI:app=FastAPI()app.add_middleware(FastAPIRichLogger)FeaturesColor-Coded Logging: Easily distinguish between different log levels thanks to color coding.Request-Response Details: Logs include detailed information about HTTP requests and responses.Execution Time Tracking: Monitor the time taken for each request to process.Automatic Log ID Assignment: Each request gets a unique log identifier for easier tracking.ConfigurationFastAPIRichLogger allows configuration through environment variables. SetDEBUG=trueto enable detailed logging.ContributingContributions are what make the open-source community an amazing place to learn, inspire, and create. Any contributions you make aregreatly appreciated.Fork the ProjectCreate your Feature Branch (git checkout -b feature/AmazingFeature)Commit your Changes (git commit -m 'Add some AmazingFeature')Push to the Branch (git push origin feature/AmazingFeature)Open a Pull RequestLicenseDistributed under the MIT License. SeeLICENSE.mdfor more information.ContactKevin Saltarelli -kevinqz@gmail.comProject Link:https://github.com/kevinqz/fastapirichlogger
Package: fastapi-route-log
fastapi_route_logA FastAPI router for logging every requestInstallation$ pip install fastapi_route_logCode Samplefromfastapi_route_log.log_requestimportLoggingRouteapp=FastAPI()app.router.route_class=LoggingRouteExample/Testuvicornexample.main:app--reloadOutput{"type":"request","uuid":"29da7a45-e673-4b15-94bf-3e51737de6b3","env":null,"region":null,"name":null,"method":"POST","useragent":{"family":"insomnia","major":2020,"minor":5,"patch":"2020.5.0","device":{"family":"Other","brand":null,"model":null,"major":"0","minor":"0","patch":"0"},"os":{"family":"Other","major":0,"minor":0,"patch":""}},"url":"/hello_world","query":{"get":["hello"]},"body":{"rawMaterialName":"TC-407","manufacturerName":"Tokuriki Honten Co., Ltd.","name":"karthicks"},"length":null,"ts":"2021-04-01 18:48:19"}{"type":"metrics","uuid":"29da7a45-e673-4b15-94bf-3e51737de6b3","env":null,"region":null,"name":null,"method":"POST","status_code":200,"url":"/hello_world","query":{"get":["hello"]},"length":"113","latency":"0.26","ts":"2021-04-01 18:48:19"}INFO:127.0.0.1:45872-"POST /hello_world?get=hello HTTP/1.1"200OKLicenseMIT