Saravanan666/pypi-org huggingface dataset:
Package: fastapi-security-telegram-webhook
fastapi-security-telegram-webhookPlugin forFastAPIwhich allows you to secure your Telegram Bot API webhook
endpoint with IP restriction and an optional secret token.Telegram provides two ways of getting updates: long polling and webhook. When you use webhook you just register
endpoint address and telegram sends JSON to this address. If the bad guy finds out the address of your webhook, then
he can send fake "telegram updates" to your bot.Telegram doesn't provide any security features like signing or authentication mechanisms, so securing webhook is a task
for a bot developer.Thence, for securing your webhook you have only two option:Allow requests only from Telegram subnets.Telegram assuresthat they won't change.Use secret value in endpoint address, e.g./telegram-webhook/468e95826f224a60a4e9355ab76e0875. It will
complicate the brute force attack and you can easily change it if the value was compromised.This little plugin allows you to use both ways to secure.How to useUse pip or another package management util:pipinstallfastapi-security-telegram-webhookorpoetryaddfastapi-security-telegram-webhookorpipenvinstallfastapi-security-telegram-webhookPackage contains two Security objects:OnlyTelegramNetworkallows request only from telegram subnetsOnlyTelegramNetworkWithSecretadditionally checks secret in pathExample withOnlyTelegramNetworkWithSecret. Pay attention to{secret}in path operation, it's requiredfromfastapiimportFastAPI,Body,Dependsfromfastapi_security_telegram_webhookimportOnlyTelegramNetworkWithSecretapp=FastAPI()webhook_security=OnlyTelegramNetworkWithSecret(real_secret="your-secret-from-config-or-env")# {secret} in path and OnlyTelegramNetworkWithSecret as dependency:@app.post('/webhook/{secret}',dependencies=[Depends(webhook_security)])defprocess_telegram_update(update_raw=Body(...)):...Use behind proxyThe plugin usesstarlette.Request.client.hostfor extracting IP address of the request, so if your web-app is
behind proxy you should pass the real IP to the app.Foruvicornyou can use--proxy-headersas it describes indocumentation.
Package: fastapi-security-typeform
fastapi-security-typeformSecurity plugin forFastAPIwhich allows you checkTypeform signaturein your webhook endpoint.How to setup signing flow for your typeform webhookCurrent flowis herehttps://developer.typeform.com/webhooks/secure-your-webhooks/(it's little bit a lie aboutworking only via API)tl;dr:create a webhook via UI or APIgenerate random string (secret)update a webhook via UI or API with your secretHow to useUse pip or another package management util:pipinstallfastapi-security-typeformorpoetryaddfastapi-security-typeformorpipenvinstallfastapi-security-typeformThen initialize it with your webhook secret and pass it to endpoint as dependency.It will raise 403 error if signature isn't valid.fromfastapiimportDepends,FastAPIfromfastapi_security_typeformimportSignatureHeaderapp=FastAPI()signature_header_security=SignatureHeader(secret=b'{your_secret}')@app.post("/typeform_webhook")deftypeform_webhook(signature=Depends(signature_header_security)):...return{"success":True}
Package: fastapi-server-session
FastAPI Server-sided SessionFastAPI Server Session is a dependency-based extension for FastAPI that adds support for server-sided session management.At the moment, it supports using Redis as the session datastore. But in the future, it will support even more datastores including but not limited to SQL, MongoDB, etc.QuickstartfromfastapiimportDepends,FastAPIfromfastapi_server_sessionimportSessionManager,RedisSessionInterface,Sessionimportredisapi=FastAPI()session_manager=SessionManager(interface=RedisSessionInterface(redis.from_url("redis://localhost")))@api.get("/set")asyncdefset_session(session:Session=Depends(session_manager.use_session)):session["key"]="value"return{"status":"ok"}@api.get("/get")asyncdefget_session(session:Session=Depends(session_manager.use_session)):return{"value":session["key"]}# or session.get("key")ContributingIf you are considering to contribute, thanks a lot! We welcome all contributors here and, you can help out as well.Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.LicenseMITLicenseCopyright (c) 2022 DevGuyAhnafPermission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software isfurnished to do so, subject to the following conditions:The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
Package: fastapi-serviceutils
Installationpipinstallfastapi-serviceutilsUsageFor more details and usage see:readthedocsDevelopmentGetting startedAfter cloning the repository initialize the development environment using:makeinitThis will create the dev environment exampleservice/dev. Activate it using:poetryshellNote:Make sure to always activate the environment when you start working on the
project in a new terminal usingpoetryshellATTENTION:the environment should also be activated before usingmake.Updating dependenciesAfter each change in dependencies defined atpyproject.tomlrun the
following to ensure the environment-definition and lock-file are up to date:makeupdateChecking with linters and checkersTo run all pre-commit-hooks manually run:makecheckInfo about project-stateTo show summary about project run:makeinfoDocumentationThe project’s developer documentation is written using Sphinx.The documentation sources can be found in the docs subdirectory.The API-documentation is auto-generated from the docstrings of modules,
classes, and functions.
We’re using the Google docstring standard.To generate the documentation, run:makedocsThe output for generated HTML files is in thedocs/_builddirectory.TestsFor testing we usepytest, for details seePytest Docs.
To run all tests:maketests
Package: fastapi-sessions
FastAPI-SessionsDocumentation:https://jordanisaacs.github.io/fastapi-sessions/Source Code:https://github.com/jordanisaacs/fastapi-sessions/PyPI:https://pypi.org/project/fastapi-sessions/Quickly add session authentication to your FastAPI project.FastAPI Sessionsis designed to be user friendly and customizable.FeaturesDependency injection to protect routesCompatible with FastAPI's auto generated docsPydantic models for verifying session dataAbstract session backend so you can build one that fits your needsAbstract frontends to choose how you extract the session ids (cookies, header, etc.)Create verifiers based on the session dataMix and match frontends and backendsCurrently Included Backends/Frontends:BackendsIn memory dictionaryFrontendsSigned cookiesUpcoming:Documentation and user guidesMore backends and frontendsInstallationpipinstallfastapi-sessionsGetting StartedCheck out the guide to using fastapi-sessions:https://jordanisaacs.github.io/fastapi-sessions/guide/getting_started/
Package: fastapi-shell
fastapi-shellTable of ContentsInstallationLicenseInstallationpip install fastapi-shellUsageBegin a fastapi-shell session with default import rules:python -m fastapi_shellExcludesandboxandtestsmodules from session imports:python -m fastapi_shell --exclude sandbox testsOnly includeappmodules in session imports:python -m fastapi_shell --include appIncludeappmodules except fortestsin session imports:python -m fastapi_shell --include app --exclude testsRun code during session initialization:python -m fastapi_shell --run-code "import db; db.connect()"Licensefastapi-shellis distributed under the terms of theMITlicense.
Package: fastapi-signals
fastapi-signalsSignalling for FastAPI.Usage - SignalMiddlewareNB: Only one signal per function, must take request objectAdd middlewarefrom fastapi_signals import SignalMiddleware, signal
app = FastAPI()
app.add_midleware(SignalMiddleware, handler=signal)Add handlerSpecify how the fired signal should work.from fastapi_signals import signal
import asyncio

@signal.register
async def handler():
    await asyncio.sleep(3)
    print('Heyy, it works!')Fire signal in functionNote that only one signal call is allowed using backgroud task.from fastapi_signals import initiate_signal
@app.get("/")
async def endpoint(request):
    await initiate_signal('handler',some_data="value")
    return {"status":"Success"}Usage - TaskMiddlewareAny number of tasks, no request object needed.Add middlewarefrom fastapi_signals import TaskMiddleware
app = FastAPI()
app.add_midleware(TaskMiddleware)Write handlerSpecify how the fired task should work.async def handler():
    await asyncio.sleep(3)
    print('Heyy, it works!')Fire task in functionfrom fastapi_signals import initiate_task
@app.get("/")
async def endpoint():
    await initiate_task(handler,some_data="value")
    return {"status":"Success"}
Package: fastapi-simple-class-view
Class based view in FastApiThis package gives you convenient access for writing and maintaining class based
controllers in FastAPI frameworkInstall packagepipinstallfastapi-simple-class-viewQuickstartTypical app structureAn example of a typical application structure, you can redefine it at your discretion.
├──app
│├──__init__.py
│├──permissions.py
│├──scheme.py
│├──service.py
│├──urls.py
│└──view.pyview.pySimple writing of CRUD operation for user modelIt includes:permissions - Dict (checking for rights to a specific endpoint)py_model - Dict (the specific Pydantic schema to be used in the response or request)service - service class object (the service that will be used to make requests to the database)slug_field_type - Type (the type of slug field, used for the correct operation of the swagger)fromfastapi_simple_class_view.baseimportAPIViewfromfastapi_simple_class_view.mixinsimportGenericViewfromcollectionsimportdefaultdictfrom.permissionsimportis_superuser,is_customerfrom.schemeimportUserSchema,UserCreateUpdatefrom.serviceimportuser_serviceclassUsersView(GenericView,APIView):py_model=defaultdict(lambda:UserSchema,{'create':UserCreateUpdate,'update':UserCreateUpdate,})permissions=defaultdict(lambda:is_superuser,{'list':is_customer,})service=user_serviceslug_field_type=inturls.pyfromexample.app.viewimportUsersViewfromfastapi_simple_class_view.controllerimportAPIControllerapp_router=APIController()app_router.controller_register('/users/',UsersView())service.pyService that uses the sqlalchemy modelfromexample.databaseimportUsersModel,Databasefromfastapi_simple_class_view.baseimportBaseServiceclassUserService(BaseService):model=UsersModeluser_service=UserService(Database().session)ResultCompact recording will allow you to automatically create crud operations with the modelDetailed view of the remaining application filespermissions.pySimple example is the creation of permits based on class HttpBearerfromdataclassesimportdataclassfromfastapiimportDependsfromfastapi.securityimportHTTPBearer@dataclassclassUser:username:stris_superuser:booldefis_superuser(creds=Depends(HTTPBearer())):"""Check SuperUser by credentials:param creds::return: UserModel"""returnUser('admin',True)scheme.pyPydantic SchemefrompydanticimportBaseModelclassUserSchema(BaseModel):id:intusername:strSqlAlchemy model exampleclassUsersModel(Base):__tablename__='users'id=Column(Integer,primary_key=True,autoincrement=True)username=Column(VARCHAR(50))first_name=Column(VARCHAR(100))last_name=Column(VARCHAR(100))
Package: fastapi-simple-security
FastAPI simple securityAPI key based security package for FastAPI, focused on simplicity of use:Full functionality out of the box, no configuration requiredAPI key security with localsqlitebackend, working with both header and query parametersDefault 15 days deprecation for generated API keysKey creation, revocation, renewing, and usage logs handled through administrator endpointsNo dependencies, only requiringFastAPIand the python standard libraryThis module cannot be used for any kind of distributed deployment. It's goal is to help have some basic security features
for simple one-server API deployments, mostly during development.Installationpip install fastapi_simple_securityUsageCreating an applicationfromfastapi_simple_securityimportapi_key_router,api_key_securityfromfastapiimportDepends,FastAPIapp=FastAPI()app.include_router(api_key_router,prefix="/auth",tags=["_auth"])@app.get("/secure",dependencies=[Depends(api_key_security)])asyncdefsecure_endpoint():return{"message":"This is a secure endpoint"}Resulting app is:API key creation through docsStart your API and check the logs for the automatically generated secret key if you did not provide one through
environment variables.Go to/docson your API and inform this secret key in theAuthorize/Secret headerbox.
All the administrator endpoints only support header security to make sure the secret key is not inadvertently
shared when sharing an URL.Then, you can use/auth/newto generate a new API key.And finally, you can use this API key to access the secure endpoint.API key creation in pythonYou can of course automate API key acquisition through python withrequestsand directly querying the endpoints.If you do so, you can hide the endpoints from your API documentation with the environment variableFASTAPI_SIMPLE_SECURITY_HIDE_DOCS.ConfigurationEnvironment variables:FASTAPI_SIMPLE_SECURITY_SECRET: Secret administrator keyGenerated automatically on server startup if not providedAllows generation of new API keys, revoking of existing ones, and API key usage viewIt being compromised compromises the security of the APIFASTAPI_SIMPLE_SECURITY_HIDE_DOCS: Whether or not to hide the API key related endpoints from the documentationFASTAPI_SIMPLE_SECURITY_DB_LOCATION: Location of the local sqlite database filesqlite.dbin the running directory by defaultWhen running the app inside Docker, use a bind mount for persistenceFAST_API_SIMPLE_SECURITY_AUTOMATIC_EXPIRATION: Duration, in days, until an API key is deemed expired15 days by defaultContributingSetting up python environmentpoetryinstall
poetryshellSetting up pre-commit hookspre-commitinstallRunning testspytestRunning the dev environmentThe attached docker image runs a test app onlocalhost:8080with secret keyTEST_SECRET. Run it with:docker-composebuild&&docker-composeupNeeded contributionsMore options with sensible defaultsLogging per API key?More back-end options for API key storage?
Package: fastapi-sio
fastapi-sioSocket.io FastAPI integration library with first-class documentation using AsyncAPIThe usage of the library is very familiar to the experience you‘re used to in FastAPI. Automatic documentation, type hints everywhere and heavy use of Pydantic.FeaturesFirst-class generated specification & documentationUsespython_socketiounderneathFully typed using pydantic, including theAsyncAPI specStreamlined emit to clients (learn more in docs)Forces strictly to emit correct data type  (see the example)What‘s Missing?Serve AsyncAPI studio at /sio/docsUnfortunately, AsyncAPI studio doesn‘t work the same way as Swagger UI, there is currently no way to use CDN hosted built package and supply only single html file and URL with spec JSONSupport for more obscure fields of AsyncAPI, such astraits, ...Usage Examplefastapi_app=FastAPI()sio_app=FastAPISIO(app=fastapi_app)purr_channel=sio_app.create_emitter("purrs",model=PurrModel,summary="Channel for purrs",description="Receive any purrs here!",)@sio_app.on("rubs",model=BellyRubModel,summary="Channel for belly rubs",description="Send your belly rubs through here!",)asyncdefhandle_rub(sid,data):awaitpurr_channel.emit(PurrModel(loudness=2,detail="Purr for all listeners"))return"Ack to the one who rubbed"👉Check out the example AsyncAPI documentation output!By default (you can change these values):the Socket.io endpoint path is/sio/socket.io(thesocket.iopart is set automatically by some clients)The AsyncAPI spec file is at/sio/docs/asyncapi.jsonFind more in theexamples.Documentation & ReferenceRefer to the/docsdirectory to learn how to use this library in your project.TODO: This documentation will be hosted on Github Pages in the near future, hopefully.Contribution...Used byFeel free to open a PRto add your project or company to this list.
Package: fastapi-skywalking-trace
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-skywalking-traceUtilizaçã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_skywalking_trace.middlewareimportSkywalkingMiddlewaremiddlewares=[Middleware(SkywalkingMiddleware,service_name='extractor',collector_address='35.266.138.244:15870',protocol='http')]app=FastAPI(title='Iris Typification',openapi_url="/api/v1/openapi.json",middleware=middlewares)
Package: fastapi-slack
fastapi-slackSlack extension for FastAPI.Configuration - Environment Variablesslack_access_tokenBot User OAuth Access Token as defined in OAuth & Permissions menu of the slack app.slack_signing_secretApp signing secret as shown in Basic Information menu of the slack app in the App
Credentials section.SetupInclude fastapi-slack router:importfastapi_slackfromfastapiimportFastAPIapp=FastAPI()app.include_router(fastapi_slack.router)Slash CommandsDepending onfastapi_slack.SlashCommandvalidates Slack request signature and
extracts the info needed to process it:fromfastapiimportDepends,FastAPIfromfastapi_slackimportSlashCommand,routerapp=FastAPI()app.include_router(router)@app.post("/slash-commands")defprocess_commands(slash_command:SlashCommand=Depends()):pass
Package: fastapi-slackeventsapi
Slack Events API adapter for Python with FastAPISlackEventManager is a Python-based solution to recieve and parse events from Slack's Events APIThis is simple add to fastapi server SLack Events APIInstallationpipinstallfastapi-slackeventsapiWork SetupApp SetupDevelopment WorkflowUsageCreate simple FastAPI app and add SlackEventManager event handlerimportosimportuvicornfromfastapiimportFastAPIfromfastapi_slackeventsapiimportSlackEventManagersigning_secret=os.environ.get('SLACK_BOT_SIGNING_SECRET')app=FastAPI()slack_event_manger=SlackEventManager(singing_secret=signing_secret,endpoint='/slack/events/',app=app)@slack_event_manger.on('reaction_added')asyncdefreaction_added(event_data):emoji=event_data['event']['reaction']print(emoji)uvicorn.run(app,host='0.0.0.0')
Package: fastapi-soap
FastAPI SoapThis package helps to create Soap WebServices using FastAPI (What?!?!)MotivationI know, FastAPI is a REST micro framework, but sometimes is needed to expose a Soap Interface on a already running FastAPI application for an legacy client/application that only supports, well, the Soap protocol...Installation and dependenciesOnly FastAPI, Pydantic and Pydantic XML are required.First stepsfromfastapiimportFastAPIfrompydantic_xmlimportelementfromfastapi_soapimportSoapRouter,XMLBody,SoapResponsefromfastapi_soap.modelsimportBodyContentclassOperands(BodyContent,tag="Operands"):operands:list[float]=element(tag="Operand")classResult(BodyContent,tag="Result"):value:floatsoap=SoapRouter(name='Calculator',prefix='/Calculator')@soap.operation(name="SumOperation",request_model=Operands,response_model=Result)defsum_operation(body:Operands=XMLBody(Operands)):"""Receives an Operands object and returns a Result object.Args:body (Operands): Operands object with a list of operands"""result=sum(body.operands)returnSoapResponse(Result(value=result))app=FastAPI()app.include_router(soap)if__name__=='__main__':importuvicorn# Any Python ASGI web server can be useduvicorn.run("example.main:app")(This script is complete, it should run "as is")The WSDL is available on webservice root path for GET method.GET http://localhost:8000/Calculator?wsdlExamplesXML Request<soapenv:Envelopexmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"><soapenv:Body><Operands><!--Zero or more repetitions:--><Operand>1</Operand><Operand>2</Operand><Operand>3</Operand></Operands></soapenv:Envelope>For this example, the sum_operation function will receive an Pydantic object as bodyprint(body)# Output Operands(operands=[1.0, 2.0, 3.0])print(body.operands)# Output [1.0, 2.0, 3.0]
Package: fastapi-socketio
fastapi-socketioEasly integrate socket.io with your FastAPI app.InstallationInstall this plugin usingpip:$ pip install fastapi-socketioUsageTo add SocketIO support to FastAPI all you need to do is importSocketManagerand pass itFastAPIobject.# app.pyfromfastapiimportFastAPIfromfastapi_socketioimportSocketManagerapp=FastAPI()socket_manager=SocketManager(app=app)Now you can use SocketIO directly from yourFastAPIapp object.# socket_handlers.pyfrom.appimportapp@app.sio.on('join')asyncdefhandle_join(sid,*args,**kwargs):awaitapp.sio.emit('lobby','User joined')Or you can importSocketManagerobject that exposes most of the SocketIO functionality.# socket_handlers2.pyfrom.appimportsocket_managerassm@sm.on('leave')asyncdefhandle_leave(sid,*args,**kwargs):awaitsm.emit('lobby','User left')DevelopmentTo contribute to this library, first checkout the code. Then create a new virtual environment:cd fastapi-socketio
python -mvenv venv
source venv/bin/activateOr if you are usingpipenv:pipenv shellNow install the dependencies and tests:pip install -e '.[test]'To run the tests:pytestRun exampleTo run the examples simply run:PYTHONPATH=.pythonexamples/app.pyBefore running example make sure you have all dependencies installed.ContributorsFor list of contributors please reefer to CONTRIBUTORS.md file in this repository.
Package: fastapi-sqlalchemy-filter
FastAPI filterCompatibilityRequired:Python: >=3.8, <3.12Fastapi: >=0.78, <0.93Pydantic: >=1.10.0, <2.0.0SQLAlchemy: >=1.4.36, <2.1.0Installation# Lite versionpipinstallfastapi-sqlalchemy-filterDocumentationThis package was inspired byarthurioThe package is a lite version forSQLAlchemy onlywith a few modifications to it.Please visit this site to view the full documentation:https://fastapi-filter.netlify.app/Modifications / AdditionsYou can import theFilterclass and create a filter on the fly:fromfastapi_sqlalchemy_filterimportFilteruser_dict={'name':'Jon Snow','clan':'Targaryen'}user_filter=Filter(**user_dict)Package returnsNoneif an ordering field is not present on the class definition.Note: No user action is needed on this partThis function was modified from:...@propertydefordering_values(self):"""Check that the ordering field is present on the class definition."""try:returngetattr(self,self.Constants.ordering_field_name)exceptAttributeError:raiseAttributeError(f"Ordering field {self.Constants.ordering_field_name} is not defined. ""Make sure to add it to your filter class.")...To...@propertydefordering_values(self):"""Check that the ordering field is present on the class definition."""ifhasattr(self,self.Constants.ordering_field_name):returngetattr(self,self.Constants.ordering_field_name)returnNone
...