Saravanan666/pypi-org huggingface dataset:
Package: fastapi-limiterx
fastapi-limiterxIntroductionFastAPI-Limiterx is a rate limiting tool forfastapiroutes with lua script.RequirementsredisInstallJust install from pypi>pipinstallfastapi-limiterxQuick StartFastAPI-Limiterx is simple to use, which just provide a dependencyRateLimiter, the following example allow2times
request per5seconds in route/.importaioredisimportuvicornfromfastapiimportDepends,FastAPIfromfastapi_limiterximportFastAPILimiterfromfastapi_limiterx.dependsimportRateLimiterapp=FastAPI()@app.on_event("startup")asyncdefstartup():redis=awaitaioredis.from_url("redis://localhost",encoding="utf-8",decode_responses=True)awaitFastAPILimiter.init(redis)@app.get("/",dependencies=[Depends(RateLimiter(times=2,seconds=5))])asyncdefindex():return{"msg":"Hello World"}if__name__=="__main__":uvicorn.run("main:app",debug=True,reload=True)UsageThere are some config inFastAPILimiter.init.redisTheredisinstance ofaioredis.prefixPrefix of redis key.identifierIdentifier of route limit, default isip, you can override it such asuseridand so on.asyncdefdefault_identifier(request:Request):forwarded=request.headers.get("X-Forwarded-For")ifforwarded:returnforwarded.split(",")[0]returnrequest.client.host+":"+request.scope["path"]callbackCallback when access is forbidden, default is raiseHTTPExceptionwith429status code.asyncdefdefault_callback(request:Request,response:Response,pexpire:int):"""default callback when too many requests:param request::param pexpire: The remaining milliseconds:param response::return:"""expire=ceil(pexpire/1000)raiseHTTPException(HTTP_429_TOO_MANY_REQUESTS,"Too Many Requests",headers={"Retry-After":str(expire)})Multiple limitersYou can use multiple limiters in one route.@app.get("/multiple",dependencies=[Depends(RateLimiter(times=1,seconds=5)),Depends(RateLimiter(times=2,seconds=15)),],)asyncdefmultiple():return{"msg":"Hello World"}Not that you should note the dependencies orders, keep lower of result ofseconds/timesat the first.Rate limiting within a websocket.While the above examples work with rest requests, FastAPI also allows easy usage
of websockets, which require a slightly different approach.Because websockets are likely to be long lived, you may want to rate limit in
response to data sent over the socket.You can do this by rate limiting within the body of the websocket handler:@app.websocket("/ws")asyncdefwebsocket_endpoint(websocket:WebSocket):awaitwebsocket.accept()ratelimit=WebSocketRateLimiter(times=1,seconds=5)whileTrue:try:data=awaitwebsocket.receive_text()awaitratelimit(websocket,context_key=data)# NB: context_key is optionalawaitwebsocket.send_text(f"Hello, world")exceptWebSocketRateLimitException:# Thrown when rate limit exceeded.awaitwebsocket.send_text(f"Hello again")Lua scriptThe lua script used.localkey=KEYS[1]locallimit=tonumber(ARGV[1])localexpire_time=ARGV[2]localcurrent=tonumber(redis.call('get',key)or"0")ifcurrent>0thenifcurrent+1>limitthenreturnredis.call("PTTL",key)elseredis.call("INCR",key)return0endelseredis.call("SET",key,1,"px",expire_time)return0endLicenseThis project is licensed under theApache-2.0License.
Package: fastapi-localization
fastapi_localizationfastapi_localization- provides a simple language localization from Accept-Language header in your application.Installation$pipinstallfastapi-localizationExample with small fastapi applicationfromtypingimportListfrompydanticimportBaseModelfromfastapi_localizationimportTranslateJsonResponsefromfastapi_localizationimportTranslatableStringFieldclassLanguageTranslatableSchema(BaseModel):code:strtitle:TranslatableStringField@app.get('/language',response_class=TranslateJsonResponse,response_model=List[LanguageTranslatableSchema])asyncdeflanguages():return[{'code':'ru','title':'Russia'},{'code':'en','title':'English'}]# Russia$curl--location--requestGET'http://127.0.0.1:8000/language'\--header'Accept-Language: ru'[{"code":"ru","title":"Русский"},{"code":"en","title":"Английский"}]# English$curl--location--requestGET'http://127.0.0.1:8000/language'\--header'Accept-Language: en'[{"code":"ru","title":"Russia"},{"code":"en","title":"English"}]manual partial translationfromfastapi_localizationimportTranslateJsonResponsefromfastapi_localizationimportlazy_gettextas_@app.get('/country',response_class=TranslateJsonResponse)asyncdefcountries():return[{'code':'ru','title':_('Russia')},{'code':'us','title':'USA'}]# Russian$curl--location--requestGET'http://127.0.0.1:8000/country'\--header'Accept-Language: ru'[{"code":"ru","title":"Русский"},{"code":"us","title":"USA"}]# English$curl--location--requestGET'http://127.0.0.1:8000/country'\--header'Accept-Language: en'[{"code":"ru","title":"Russia"},{"code":"us","title":"USA"}]error validationfrompydanticimportBaseModel,EmailStrfromfastapi_localizationimportTranslateJsonResponseclassInputSchema(BaseModel):email=EmailStr()@app.post('/input',response_class=TranslateJsonResponse)asyncdefcountries(value:InputSchema):returnvalue# Russia$curl--location--requestPOST'http://127.0.0.1:8000/input'\--header'Accept-Language: ru'\--header'Content-Type: application/json'\--data-raw'{"email": "invalid_email"}'{"detail":[{"loc":["body","email"],"msg":"значение не является действительным адресом электронной почты","type":"value_error.email"}]}# English$curl--location--requestPOST'http://127.0.0.1:8000/input'\--header'Accept-Language: en'\--header'Content-Type: application/json'\--data-raw'{"email": "invalid_email"}'{"detail":[{"loc":["body","email"],"msg":"value is not a valid email address","type":"value_error.email"}]}Applicationsource code
Package: fastapi-log
Fastapi Route LogA FastAPI router for logging every request.Installation$ pip install fastapi_logDashboard testingcdfastapi_route_loguvicorndev.main:app--reloadcheck the url:http://localhost:8000/fastapi_dashboardCredential for DashboardUername : adminPassword : 12345Code Samplefromfastapi_log.log_requestimportLoggingRouteapp=FastAPI()app.router.route_class=LoggingRouteExample/Testuvicornexample.main:app--reloadSample OutputDASHBOARDOutput{"type":"request","uuid":"e024302b-f11b-4dbb-aadf-46a2ce702411","env":null,"region":null,"name":null,"method":"POST","useragent":{"family":"Firefox","major":88,"minor":0,"patch":"88.0","device":{"family":"Other","brand":null,"model":null,"major":"0","minor":"0","patch":"0"},"os":{"family":"Ubuntu","major":0,"minor":0,"patch":""}},"url":"/test","query":{},"body":{"name":"Prasanna","userName":"Karthick","age":"NULL","Degree":0},"length":null,"ts":"2021-05-16 22:50:41"}{"type":"metrics","uuid":"e024302b-f11b-4dbb-aadf-46a2ce702411","env":null,"region":null,"name":null,"method":"POST","status_code":200,"url":"/test","query":{},"length":"65","latency":"0.15","ts":"2021-05-16 22:50:41"}INFO:127.0.0.1:35984-"POST /test HTTP/1.1"200OKMore Features are coming up - Keep waiting
Package: fastapi-logger
FastAPI Logger is a powerful Python package designed to seamlessly integrate with FastAPI applications, providing advanced request logging capabilities. With FastAPI Logger, you can capture essential details about incoming requests, including sender IP, port, processing time, and more.FeaturesRequest Details:Log sender IP, port, request URL, and processing time for each incoming request.Customizable Logging:Easily customize the logging behavior to include additional parameters or adapt it to your specific requirements.Integration with FastAPI:Integrate the logger seamlessly into your FastAPI application using the provided decorator.Efficient and Lightweight:FastAPI Logger is designed to be efficient and lightweight, ensuring minimal impact on the performance of your FastAPI application.InstallationYou can install FastAPI Logger using pip:pipinstallfastapi-loggerUsage
Getting started with FastAPI Logger is straightforward. Simply import the log_request decorator and apply it to your FastAPI endpoints:from fastapi import FastAPI, Request
from fastapi_logger.logger import log_request

app = FastAPI()

@app.get("/example")
@log_request
def read_item(request: Request):
    # Your endpoint logic here
    return {"message": "Hello, World!"}
```

FastAPI Logger empowers you to gain valuable insights into your FastAPI application's traffic and performance effortlessly.
Package: fastapi-logging
Wrapper para trabalhar com a API do Cloud LoggingProcedimento para upload no PypiPré requisitosInstalar pacotes pythonpython3 -m pip install --upgrade setuptools build wheel twineBuild e enviar ao PYPIpython3 -m buildpython3 -m twine upload dist/*Instalar o pacote no projetopip install fastapi-loggingUtilização da bibliotecaEssa biblioteca espera que você passe o schema dos dados da tabelaAconselho criar um arquivo de schema.py ou model.py onde seja definido a estrutura de dados da tabela.Instanciar o MiddlewareCom o schema definido, você deve instanciar um classefromstarlette.middlewareimportMiddlewarefromfastapi.middleware.corsimportCORSMiddlewarefromstarlette_context.middleware.raw_middlewareimportRawContextMiddlewarefromfastapi_logging.loggingimportLogMidddlewarefromfastapi_logging.loggingimportloggingfromfastapi_logging.loggingimportTracePluginfromstarlette_contextimportcontext,pluginsmiddlewares=[Middleware(RawContextMiddleware,plugins=(plugins.CorrelationIdPlugin(),TracePlugin(),plugins.RequestIdPlugin(),),),Middleware(LogMidddleware),Middleware(CORSMiddleware,allow_origins=BACKEND_CORS_ORIGINS,allow_credentials=True,allow_methods=["*"],allow_headers=["*"],)]app=FastAPI(title='Iris Typification',openapi_url="/api/v1/openapi.json",middleware=middlewares)Principais operaçõesUsando a classe, você pode executar algumas operações para auxiliar no densenvolvimentoLogginglogging.info({"key": "value"})
Package: fastapi-lowlevel-pagination
Fast PaginationDescriptionA lowlevel, fast and easy to use package for creating and managing your own pagination system while FastAPI.Keeping the pagination system simple was the main goal of this package.You provide your own database querying logic and the pagination system will handle the rest.ExampleImportsimportfast_paginationaspgRoutes@router.get(...,response_model=pg.generate_response_schema(SomeModel))asyncdefsome_route(pagination:pg.Pagination[SomeModel]=Depends(pg.get_pagination_dependency(offset_kwargs={...},limit_kwargs={...},filter_kwargs={...})),...# additional route dependencies goes here):returnawaitpagination.paginate(func=db_query_func,...# func kwargs goes here)Servicesasyncdefdb_query_func(page_request:PageRequest,**extra_kwargs)->dict:...# db query logic goes herereturn{'results':results,'total_items':total_items}
Package: fastapi-magic-router
🪄 FastAPI Magic Router ✨Have you come here seeking a magical way to define FastAPI routes?app=FastAPI()route=magic_router(app)route("GET     /api/users          ",user.list_)route("GET     /api/users/{user_id}",user.get)route("POST    /api/users          ",user.create)route("PATCH   /api/users/{user_id}",user.update)route("DELETE  /api/users/{user_id}",user.delete_)Come, I shall grant you your wish!Default Router vs Magic RouterfromfastapiimportFastAPIfrompydanticimportBaseModelfrommagic_routerimportmagic_router,magicclassResponse(BaseModel):path:str# Default Router -----------------------------------------------------------------------app=FastAPI()not_so_magical_path="/api/not-so-magical"asyncdefnot_so_magical_endpoint():returnResponse(path=not_so_magical_path)app.get(not_so_magical_path,response_model=Response,tags=["main"],operation_id="not_so_magical_endpoint",name="not_so_magical_endpoint",)(not_so_magical_endpoint)# Magic Router -------------------------------------------------------------------------route=magic_router(app)asyncdefmagical_endpoint()->Response:returnResponse(path=magic(magical_endpoint).path)route("GET /api/magical",magical_endpoint)# --------------------------------------------------------------------------------------
Package: fastapi-mail
Fastapi-mailThe fastapi-mail is a simple lightweight mail system, for sending emails and attachments(individual && bulk)🔨  Installationpython3-mvenv.venvsource.venv/bin/activate

pipinstallfastapi-mailforaioredisandhttpx

pipinstall'fastapi-mail[aioredis]'pipinstall'fastapi-mail[httpx]'Alternatively, if you prefer to usepoetryfor package dependencies:poetryshell

poetryaddfastapi-mailforaioredisandhttpx

poetryadd'fastapi-mail[aioredis]'poetryadd'fastapi-mail[httpx]'Documentation:FastApi-MAILThe key features are:sending emails either with FastApi or using asyncio modulesending emails using FastApi background task managmentsending files either from form-data or files from serverUsing Jinja2 HTML Templatesemail utils (utility allows you to check temporary email addresses, you can block any email or domain)email utils has two available classesDefaultCheckerandWhoIsXmlApiUnittests using FastapiMailMore information onGetting-StartedGuidefromtypingimportListfromfastapiimportBackgroundTasks,FastAPIfromfastapi_mailimportConnectionConfig,FastMail,MessageSchema,MessageTypefrompydanticimportBaseModel,EmailStrfromstarlette.responsesimportJSONResponseclassEmailSchema(BaseModel):email:List[EmailStr]conf=ConnectionConfig(MAIL_USERNAME="username",MAIL_PASSWORD="**********",MAIL_FROM="test@email.com",MAIL_PORT=465,MAIL_SERVER="mail server",MAIL_STARTTLS=False,MAIL_SSL_TLS=True,USE_CREDENTIALS=True,VALIDATE_CERTS=True)app=FastAPI()html="""<p>Thanks for using Fastapi-mail</p>"""@app.post("/email")asyncdefsimple_send(email:EmailSchema)->JSONResponse:message=MessageSchema(subject="Fastapi-Mail module",recipients=email.dict().get("email"),body=html,subtype=MessageType.html)fm=FastMail(conf)awaitfm.send_message(message)returnJSONResponse(status_code=200,content={"message":"email has been sent"})List of ExamplesFor more examples of using fastapi-mail please check:examplesection.Contributors ✨Thanks goes to these wonderfulPeopleContributingContributions of any kind are welcome!Before you start, please readCONTRIBUTINGLICENSEMIT
Package: fastapi-mailer
Fastapi-mailThe fastapi-mail simple lightweight mail system, sending emails and attachments(individual && bulk)🔨  Installation$pipinstallfastapi-mailDocumentation:FastApi-MAILThe key features are:sending emails with either with FastApi or using asyncio modulesending emails using FastApi background task managmentsending files either from form-data or files from serverUsing Jinja2 HTML Templatesemail utils (utility allows you to check temporary email addresses, you can block any email or domain)email utils has two available classesDefaultCheckerandWhoIsXmlApiUnittests using FastapiMailMore information onGetting-StartedGuidefromfastapiimportFastAPI,BackgroundTasks,UploadFile,File,Formfromstarlette.responsesimportJSONResponsefromstarlette.requestsimportRequestfromfastapi_mailimportFastMail,MessageSchema,ConnectionConfigfrompydanticimportBaseModel,EmailStrfromtypingimportListclassEmailSchema(BaseModel):email:List[EmailStr]conf=ConnectionConfig(MAIL_USERNAME="YourUsername",MAIL_PASSWORD="strong_password",MAIL_FROM="your@email.com",MAIL_PORT=587,MAIL_SERVER="your mail server",MAIL_TLS=True,MAIL_SSL=False,USE_CREDENTIALS=True,VALIDATE_CERTS=True)app=FastAPI()html="""<p>Thanks for using Fastapi-mail</p>"""@app.post("/email")asyncdefsimple_send(email:EmailSchema)->JSONResponse:message=MessageSchema(subject="Fastapi-Mail module",recipients=email.dict().get("email"),# List of recipients, as many as you can passbody=html,subtype="html")fm=FastMail(conf)awaitfm.send_message(message)returnJSONResponse(status_code=200,content={"message":"email has been sent"})List of ExamplesFor more examples of using fastapi-mail please checkexamplesectionContributingFeel free to open issues and send pull requests.Contributors ✨Thanks goes to these wonderful people (🚧):🚧🚧Sabuhi Shukurov💬👀🚧Tural Muradov📖👀🔧Hasan Aliyev📖🚧👀Ashwani🚧Leon Xu🚧Gabriel Oliveira📖🚧Onothoja Marho📖🚧🔧Tim Kiely🚧Dmitriy Solodkiy🚧Peter Boers🚧James Valentine📖🚧🔧Gogoku📖🚧🔧Kucera-Lukas📖🚧🔧LLYX📖🚧🔧floodpants🚧André Felipe Dias📖👀🔧Wojtek Jurkowlaniec📖👀🔧This project follows theall-contributorsspecification.
Contributions of any kind are welcome!Before you start please readCONTRIBUTINGLICENSEMIT
Package: fastapi-mailman
📬 Fastapi-Mailman🔥 Porting Django's email implementation to your FastAPI applications.Fastapi-Mailman is a Fastapi extension providing simple email sending capabilities. It's actually a hard fork ofwaynerv'sflask-mailmanmodule. I have tried to implement the same features for theFastapitoo.It was meant to replace the basic Fastapi-Mail with a better warranty and more features.⛲ Key Features:Easy to use.Backend based email sender.Customisable backend class.Proper testcases.Proper documentation.🔗 Important Links:Github RepoPYPIDocumentation💯 UsageFastapi-Mailman ported Django's email implementation to your Fastapi applications, which may be the best mail sending implementation that's available for python.The way of using this extension is almost the same as Django.Documentation:https://marktennyson.github.io/fastapi-mailman.🪜 Basic ExamplefromfastapiimportFastAPIimportuvicornasuvfromfastapi_mailmanimportMail,EmailMessagefromfastapi_mailman.configimportConnectionConfigapp=FastAPI(debug=True)config=config=ConnectionConfig(MAIL_USERNAME='example@domain.com',MAIL_PASSWORD="7655tgrf443%$",MAIL_BACKEND='smtp',MAIL_SERVER='smtp.gmail.com',MAIL_PORT=587,MAIL_USE_TLS=True,MAIL_USE_SSL=False,MAIL_DEFAULT_SENDER='example@domain.com',)mail=Mail(config)@app.get("/send-base")asyncdefsend_base():msg=EmailMessage('this is subject','this is message',to=['aniketsarkar@yahoo.com'])awaitmsg.send()return{"Hello":"World"}@app.get("/send-mail")asyncdefcheck_send_mail():awaitmail.send_mail("this is subject","this is message",None,["aniketsarkar@yahoo.com"])return{"Hello":"World"}if__name__=="__main__":uv.run(app,port=8082,debug=True)🚇 Development🧑‍💻 Contribution procedure.Create a new issue on github.Fork and clone this repository.Make some changes as required.Write unit test to showcase its functionality.Submit a pull request under themasterbranch.🖨️ Run this project on your local machine.To run this project on your local machine pleaseclick here❤️ ContributorsCredits goes to these peoples:📝 LicenseMITCopyright (c) 2021 Aniket Sarkar(aniketsarkar@yahoo.com)
Package: fastapi-maintenance-mode
FastAPI Maintenance Mode MiddlewareFastAPI Maintenance Mode Middleware is a Python package that provides middleware for enabling maintenance mode in FastAPI applications. When maintenance mode is enabled, all incoming requests will receive a 503 Service Unavailable response indicating that the service is temporarily unavailable due to maintenance.InstallationYou can install the package usingpip:pipinstallfastapi-maintenance-modeExamplefromfastapiimportFastAPIfromfastapi_maintenance_modeimportMaintenanceModeMiddlewareapp=FastAPI()app.add_middleware(MaintenanceModeMiddleware,is_maintenance_mode=True)@app.get("/")asyncdefroot():return{"status":"Ok"}
Package: fastapi-microservice-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 testpypiIncrease the version inpyproject.tomlRun command$./build_and_test.shHow to publish new versionIncrease the version inpyproject.tomlRun command$./build_and_publish.sh
Package: fastapi-middleware
FastAPImiddlewareIntroductionfastapi-middlewareis a set of middlewares forFastAPIframework.Installationpipinstallfastapi-middlewareUsageTo use middleware, you need to import it and add to your FastAPI app:fromfastapiimportFastAPI...fromfastapi_middlewareimportSQLQueriesMiddleware,RequestVarsMiddleware...app=FastAPI()...# set desired logging levellogging.getLogger("fastapi-middleware").setLevel(logging.DEBUG)# add desired middlewareapp.add_middleware(SQLQueriesMiddleware)app.add_middleware(RequestVarsMiddleware)
Package: fastapi-middleware-logger
FastAPI MiddleWare LoggerThis library is a very simple tool to simplify custom formatting of logs for FastAPI.
It's almost entirely based on thisanswerfrom SO.UsageThe design of this library is made to be very simple to use. Instead of instantiatingFastAPI, just instatiateFastAPIMiddleWareLogger:fromfastapi_middleware_logger.fastapi_middleware_loggerimportadd_custom_loggerfromfastapi_middleware_loggerimportFastAPIMiddleWareLoggerimportloggingfromfastapiimportFastAPIlogging.basicConfig(level=logging.INFO)app=FastAPIMiddleWareLogger()# app = FastAPI()# app = add_custom_logger(app)@app.get("/")defget_index():return{"status":"ok"}@app.get("/error")defget_error():raiseTypeError("Some error happened !")Another way to add custom loggers is to useadd_custom_logger.Custom loggerIf the request is handled properly, thecustom_loggerwill be called.
Thecustom_loggercan take the following arguments:request_body: body of the request as astringrequest_headers: headers of the request as adictionaryrequest_query_params: query parameters of the request as adictionaryrequest_method: method of the request as astringrequest_url: URL of the request as astringresponse_body: body of the response as astringresponse_headers: headers of the response as adictionaryresponse_media_type: media type of the response as astringresponse_status_code: status code of the response as anintegerBy default, thecustom_loggerwill print out all of these arguments.Custom error loggerIf the request throws an exception, thecustom_error_loggerwill be called.
Thecustom_error_loggercan take the following arguments:request_body: body of the request as astringrequest_headers: headers of the request as adictionaryrequest_query_params: query parameters of the request as adictionaryrequest_method: method of the request as astringrequest_url: URL of the request as astringerror_message: message of the exception as astringUsualuvicorn/fastapilogs can be kept by usingdisable_uvicorn_logging=False.
This could be used to perform other operations but I have not, nor will, tested it.