Saravanan666/pypi-org huggingface dataset:
Package: fastapi-apscheduler
fastapi-apschedulerInstallationpipinstallfastapi-apschedulerUsagefromfastapiimportFastAPIfromfastapi_apscheduler.utilsimportget_loggerfromfastapi_apscheduler.routersimportget_jobs_routerfromfastapi_apscheduler.schedulerimportlifespanlogger=get_logger(__name__)app=FastAPI(lifespan=lifespan)app.include_router(get_jobs_router(),prefix="/scheduler",tags=["scheduler"])asyncdefpytest_job():logger.info("test_job")Build and publish to pypi with poetrypoetrybuild

Buildingfastapi-apscheduler(0.0.x)-Buildingsdist-Builtfastapi_apscheduler-0.0.x.tar.gz-Buildingwheel-Builtfastapi_apscheduler-0.0.x-py3-none-any.whl

poetrypublish

Publishingfastapi-apscheduler(0.0.x)toPyPI-Uploadingfastapi_apscheduler-0.0.x-py3-none-any.whl100%Run local instance of worker with uvicornuvicornexample.main:app--workers1--port8084--log-leveldebug--env-fileexample/.envTODO:add CIadd tests to CIadd coverage to CI
Package: fastapi-asyncapi-docs
fastest-asyncapiUse pydantic model to construct asyncapi docs and serve inside your asyncapi appInstallationInstall usingpiporpoetrypoetryaddfastest-asyncapiUsageDescribe your specification using pydantic modelsfromasyncapi_container.asyncapi.spec.v3.infoimportInfofromasyncapi_container.containers.v3.simple_specimportSimpleSpecV3fromasyncapi_container.custom_typesimportRoutingMapfrompydanticimportBaseModel,FieldclassCustomer(BaseModel):first_name:str=Field(...,title='First Name')last_name:str=Field(...,title='Last Name')email:str=Field(...,title='Email',format="email",description="Person's email to deliver order info")country:str=Field(...,title='Country')zipcode:str=Field(...,title='Zipcode')city:str=Field(...,title='City')street:str=Field(...,title='Street')apartment:str=Field(...,title='Apartment')classOrderSchemaV1(BaseModel):product_id:int=Field(...,title='Product Id')quantity:int=Field(...,title='Quantity')customer:CustomerclassMySpecialServiceAsyncAPISpecV3(SimpleSpecV3):info:Info=Info(title="My special Service",version="1.0.0",description="Service for making orders")sends:RoutingMap={"shop.orders.v1":[OrderSchemaV1,]}receives:RoutingMap={}Configurefast-and-async-apiapp using asyncapi spec definition from above Mountfastapi-asyncapiurls.fromfastapiimportFastAPIfromfastest_asyncapi.views.sync.v3.asyncapiimportfastest_asyncapi_appapp=FastAPI()fastest_asyncapi_app.configure(asyncapi_spec_classes=[MySpecialServiceAsyncAPISpecV3])app.mount("/docs/",fastest_asyncapi_app)Enjoy your results by navigating todocs/asyncapi/v3/PS: images generated by AI
Package: fastapi-auth0
DescriptionIntegrate FastAPI withhttps://auth0.comin a simple and elegant way.
Get automatic Swagger UI support for the implicit scheme (along others), which means that signing in using social providers is only a few clicks away with no additional code.Installationpip install fastapi-auth0RequirementsReading auth0 docs is recommended in order to understand the following concepts:API's and audienceApplicationsGrant typesPermissions and scopesThis library cannot do magic if the auth0 tenant is not configured correctly!Email field requirementsIn order to get email for Auth0User, the API must have "openid profile email" permission and the rule "Add email to access token" must be added with the matching namespace, seetests.
The security is not affected in any way if we don't do this, but we need to if we want to know the user email's address. Otherwise, email field will always beNone.Swagger UI login requirementsIn order to utilize the interactive docs for the implicit flow, the callback url must be registered on the auth0 dashboard. For swagger this url is{SWAGGER_DOCS_URL}/oauth2-redirect, so if you are running FastAPI on localhost:8000, that becomeshttp://localhost:8000/docs/oauth2-redirect. Add it to "Allowed Callback URLs" for the application which you intend to login with (the client_id you input for Auth0ImplicitBearer authorization).In order to logout and login with another user, it's necessary to manually call GEThttps://{auth0_domain}/v2/logout, becacause the Swagger UI logout button is not able to clear 3rd party session / cookies.Example usagefromfastapiimportFastAPI,Depends,Securityfromfastapi_auth0importAuth0,Auth0Userauth=Auth0(domain='your-tenant.auth0.com',api_audience='your-api-identifier',scopes={'read:blabla':''})app=FastAPI()@app.get("/public")defget_public():return{"message":"Anonymous user"}@app.get("/secure",dependencies=[Depends(auth.implicit_scheme)])defget_secure(user:Auth0User=Security(auth.get_user,scopes=['read:blabla'])):return{"message":f"{user}"}Example user responses:id='Art2l2uCeCQk5zDVbZzNZmQkLJXLd9Uy@clients'permissions=['read:blabla']email=None# user is M2M appid='auth0|5fe72b8eb2ac50006f725451'permissions=['read:blabla']email='some.user@outlook.com'# user signed up using auth0 databaseid='google-oauth2|115595596713285791346'permissions=['read:blabla']email='other.user@gmail.com'# user signed up using googleVideo tutorialhttps://youtu.be/cGRdFjgAy9s
Package: fastapi-authenticator
fastapi-authenticatorfastapi authenticator for google cloud tasksInstallationserver:pip3 install fastapi-authenticatorclient:pip3 install gcp-taskqueueUsageserver:fromfastapiimportDepends,FastAPIfromfastapi_authenticatorimportGoogleCloudTask,google_cloud_task,google_cloud_authapp=FastAPI()@app.post("/task1")deftask_handler(claims:dict=Depends(google_cloud_auth),task:GoogleCloudTask:Depends(google_cloud_task)):...client:fromgcp_taskqueueimportTaskQueuequeue=TaskQueue(queue_id="your-queue-name")queue.create_http_task("https://url",deadline=300)DeploymentService Account UserRole is needed for the client to generate oidc token.
Package: fastapi-authkit
FastAPI AuthKitFastAPI-authkit is an extenstion to provide oauth-oidc authentication/authorization and user management for fastapi.Features and supported OIDC providersLogin/SignUp based on following providers:GoogleTwitterGithubZoomSSO (OKTA)Facebook (Coming soon...)Microsoft (Coming soon...)Apple (Coming soon...)User management (Coming soon...)InstallationInstallFastAPI AuthKitwith pippipinstallfastapi_authkitUsage/Examplesimportfastapifromfastapi_authkitimport(OAuthApp,AuthSetting,AuthProviders,)fromfastapi_authkit.utilsimportjwtfake_db={}SECRET_KEY="This is a secret key"classAuthLogic(AuthProviders.IAuthLogic):header:dict[str,str]={"alg":"HS256"}asyncdeflogin(self,userinfo:AuthProviders.UserInfoModel)->AuthProviders.Token|None:ifuserinfo.nameinfake_db:returnAuthProviders.Token(jwt.encode(header=self.header,key=SECRET_KEY,payload=userinfo.dict(),).decode())asyncdefsingup(self,userinfo:AuthProviders.UserInfoModel)->None:globalfake_dbfake_db[userinfo.name]=userinfoapp:fastapi.FastAPI=fastapi.FastAPI()auth_router:fastapi.APIRouter=fastapi.APIRouter(prefix="/auth")auth_app:OAuthApp=OAuthApp(app=app,secret_key=SECRET_KEY)auth_vias:AuthProviders.AuthVia=AuthProviders.AuthVia(oapp=auth_app.oauth,vias=(AuthSetting(name="google",client_id="{{client-id}}",client_secret="{{client-secret}}",client_kwargs=dict(scope="openid profile"),).dict(),AuthSetting(name="github",client_id="{{client-id}}",client_secret="{{client-secret}}",client_kwargs=dict(scope="user:email"),).dict(),AuthSetting(name="zoom",client_id="{{client-id}}",client_secret="{{client-secret}}",client_kwargs=dict(scope="openid profile"),).dict(),AuthSetting(name="okta",client_id="{{client-id}}",client_secret="{{client-secret}}",api_base_url="https://dev-ea46b3xduc1q1lb4.us.auth0.com",client_kwargs=dict(scope="openid profile"),).dict(),AuthSetting(name="twitter",client_id="{{twitter-client-id}}",client_secret="{{twitter-client-secret}}",client_kwargs=dict(scope="users.read"),).dict(),),)auth_logic:AuthLogic=AuthLogic()AuthProviders.GoogleAuthenticationMethod(router=auth_router,oauth_app=auth_app,auth_vias=auth_vias,auth_logic=auth_logic,)AuthProviders.ZoomAuthenticationMethod(router=auth_router,oauth_app=auth_app,auth_vias=auth_vias,auth_logic=auth_logic,)AuthProviders.GithubAuthenticationMethod(router=auth_router,oauth_app=auth_app,auth_vias=auth_vias,auth_logic=auth_logic,)AuthProviders.OktaAuthenticationMethod(router=auth_router,oauth_app=auth_app,auth_vias=auth_vias,auth_logic=auth_logic,)AuthProviders.TwitterAuthenticationMethod(router=auth_router,oauth_app=auth_app,auth_vias=auth_vias,auth_logic=auth_logic,)Authors@LegopapuridaContributingContributions are always welcome!Seecontributing.mdfor ways to get started.Please adhere to this project'scode of conduct.LicenseMITSupportFor support, emailpapuridalego@gmail.comor join our Telegram Group (Ask us in email).FeedbackIf you have any feedback, please reach out to us atpapuridalego@gmail.com
Package: fastapi-authlib
fastapi-authlibfastapi-authlib provides easy integration between FastAPI and openid connection in your application.
Provides the initialization and dependencies of oidc, aiming to unify authentication management and
reduce the difficulty of use.Installinginstall and update using pip:pipinstallfastapi-authlibExamplesCreate settings for examples,settings.pyconfig={'database':'sqlite+aiosqlite:////tmp/oidc_demo.db','oauth_client_id':'client_id','oauth_client_secret':'client_secret','oauth_conf_url':'conf_url','secret_key':'secret_key','router_prefix':'',}settings.py is a simple configuration file of the use case, which mainly provides the database link,
the necessary parameters used by oidc, the session authentication key and the routing prefix.Please use your authentication server configuration to populate the parameter value prefixed with oauth.
Other parameters can be modified according to the actual situation.Create api route,api_router.pyfromfastapiimportAPIRouterfromstarlette.requestsimportRequestrouter=APIRouter()@router.get('/index')asyncdefindex(*,request:Request,):"""User"""user_info=request.state.userreturn{'name':user_info.get('user_name')}For authenticated api, you can userequest.state.userto get the current user.Create oidc demo entry,main.py"""main"""importuvicornfromfastapiimportDepends,FastAPIfromfastapi_sa.databaseimportdbfromfastapi_sa.middlewareimportDBSessionMiddlewarefromfastapi_authlib.oidcimportOIDCClientfromfastapi_authlib.utils.auth_dependencyimportcheck_auth_dependsfromapi_routerimportindexfrom.settingsimportconfigclassOIDCDemo:"""OIDCDemo"""def__init__(self,settings:dict):self.settings=settingsself.router_prefix=self.settings.get('router_prefix')defrun(self):"""Run"""# Early environment initializationapp=FastAPI(title='FastAPIOIDCSupportDemo',version='0.1.0')db.init(self.settings.get('database'))# Oidc environment initializationclient=OIDCClient(app=app,**config)# If you only init app, you should use init_app() insteadclient.init_oidc()# Customize the environment initialization# add dependencies to the interface that needs to be authenticatedapp.include_router(index.router,tags=['index'],prefix=config.get('router_prefix'),dependencies=[Depends(check_auth_depends)])app.add_middleware(DBSessionMiddleware)returnappif__name__=='__main__':client_app=OIDCDemo(config).run()uvicorn.run(client_app,host="0.0.0.0",port=8001)Use StepCreate app and init dbInit the environment of oidc, If you don't want to do data migration, you should use init_app method.
Usually database migration and oidc initialization are performed togetherRegister routing and other middleware, the DBSessionMiddleware is requiredStart a fastapi server with uvicorn or otherOtherProvide the following apis/login/auth/logout/usersBased onFastAPISQLAlchemyFastapi-saAuthlibDevelopYou may need to read thedevelop documentto use SRC Layout in your IDE.
Package: fastapi-auth-middlewares
FastAPI Auth MiddlewareFastAPI Auth Middlewawre is a middleware for securing FastAPI application. It provides a convenient way to secure your FastAPI routes and endpoints using jwt tokens.FeaturesSeamless integration with FastAPI applications.Easily protect routes and endpoints with JWT authentication.Lightweight and designed for simplicity.RequirementsPython 3.8FastAPIobvisouly 😁😁😁😊😊PyJWTInstallation$pipinstallfastapi_auth_middlewaresExampleCreate itCreate a filemain.pywith:fromfastapiimportFastAPI,Requestfromfastapi_auth_middlewaresimportJwtAuthMiddlewareapp=FastAPI(title="Secured Project",version="1.0",)app.add_middleware(JwtAuthMiddleware,secret_key="your_secret_key",algorithms=["HS256"],# Excluding Documentation (OpenAPI and favicon routes) and health check routes from authenticationpublic_paths=["/docs","/favicon.ico","/openapi.json","/api/health"],)@app.get("/api/health")asyncdefhealth():return{"message":"server is up and running."},200@app.get("/protected")asyncdefprotected_route(request:Request):# Access the decoded_token from the middlewaredecoded_token=request.state.user# Your logic using the decoded_tokenuser_id=decoded_token.get("user_id")username=decoded_token.get("username")return{"message":"This is a protected route","user_id":user_id,"username":username,}Run itRun the server with:$uvicornmain:app--reloadINFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)INFO:     Started reloader process [28720]INFO:     Started server process [28722]INFO:     Waiting for application startup.INFO:     Application startup complete.ContributingFeel free to contribute to this project.LicenseThis project is licensed under the terms of the MIT license.
Package: fastapi-auth-user
Default auth service based on FastApi frameworkInstallation$pipinstallfastapi-auth-userorfor poetry:$poetryinit$poetryaddfastapi-auth-userExampleCreate itCreate a filemain.pywith:importuvicornfromfastapi_auth_userimportauth_appif__name__=="__main__":uvicorn.run(auth_app,host="localhost",port=3000)Run itRun the server with:$poetryrunmain.pyor$python3main.pyINFO:  Started server process [12484]INFO:  Waiting for application startup.INFO:  Application startup complete.INFO:  Uvicorn running on http://localhost:3000 (Press CTRL+C to quit)Check itOpen your browser athttp://localhost:3000/docs.You will see:You already created an API that:All methodCRUDforUSERmodel`.All methodCRUDforRolemodel`.Login user with oauth2Profile this userEnv fileDB_USER=<YOU USER NAME DB>                      #'postgres'DB_PASSWORD=<YOU DATABASE PASSWORD>             #'root'DB_HOST=<YOU DATABASE HOST>                     #'localhost'DB_NAME=<YOU DATABASE NAME>                     #'auth_db'DATABASE_URL=<YOU DATABASE URL>                 #'postgresql://${DB_USER}:${DB_PASSWORD}@${DB_HOST}/${DB_NAME}'ACCESS_TOKEN_EXPIRE_MINUTES=<TIME FOR TOKEN>    #30SECRET_KEY=<SECRET KEY>                         #'secret_key'ALGORITHM=<HASH ALGORITHM>                      #'HS256'
Package: fastapi-azure-auth
FastAPI-Azure-AuthAzure AD Authentication for FastAPI apps made easy.🚀 DescriptionFastAPI is a modern, fast (high-performance), web framework for building APIs with Python, based on standard Python type hints.At Intility we use FastAPI for both internal (single-tenant) and customer-facing (multi-tenant) APIs. This package enables our developers (and you 😊) to create features without worrying about authentication and authorization.Also,we're hiring!📚 ResourcesThedocumentationcontains a full tutorial on how to configure Azure AD
and FastAPI for single- and multi-tenant applications as well as B2C apps. It includes examples on how to lock down
your APIs to certain scopes, tenants, roles etc. For first time users it's strongly advised to set up your
application exactly how it's described there, and then alter it to your needs later.MIT License|Documentation|GitHub⚡ SetupThis is a tl;dr intended to give you an idea of what this package does and how to use it.
For a more in-depth tutorial and settings reference you should read thedocumentation.1. Install this library:pipinstallfastapi-azure-auth# orpoetryaddfastapi-azure-auth2. Configure your FastAPI appIncludeswagger_ui_oauth2_redirect_urlandswagger_ui_init_oauthin your FastAPI app initialization:# file: main.pyapp=FastAPI(...swagger_ui_oauth2_redirect_url='/oauth2-redirect',swagger_ui_init_oauth={'usePkceWithAuthorizationCodeGrant':True,'clientId':settings.OPENAPI_CLIENT_ID,},)3. Setup CORSEnsure you have CORS enabled for your local environment, such ashttp://localhost:8000.4. Configure FastAPI-Azure-AuthConfigure eitherSingleTenantAzureAuthorizationCodeBearer,MultiTenantAzureAuthorizationCodeBearerorB2CMultiTenantAuthorizationCodeBearer# file: demoproj/api/dependencies.pyfromfastapi_azure_auth.authimportSingleTenantAzureAuthorizationCodeBearerazure_scheme=SingleTenantAzureAuthorizationCodeBearer(app_client_id=settings.APP_CLIENT_ID,tenant_id=settings.TENANT_ID,scopes={f'api://{settings.APP_CLIENT_ID}/user_impersonation':'user_impersonation',})or for multi-tenant applications:# file: demoproj/api/dependencies.pyfromfastapi_azure_auth.authimportMultiTenantAzureAuthorizationCodeBearerazure_scheme=MultiTenantAzureAuthorizationCodeBearer(app_client_id=settings.APP_CLIENT_ID,scopes={f'api://{settings.APP_CLIENT_ID}/user_impersonation':'user_impersonation',},validate_iss=False)To validate theiss, configure aniss_callable.5. Configure dependenciesAddazure_schemeas a dependency for your views/routers, using eitherSecurity()orDepends().# file: main.pyfromdemoproj.api.dependenciesimportazure_schemeapp.include_router(api_router,prefix=settings.API_V1_STR,dependencies=[Security(azure_scheme,scopes=['user_impersonation'])])6. Load config on startupOptional but recommended.# file: main.py@app.on_event('startup')asyncdefload_config()->None:"""Load OpenID config on startup."""awaitazure_scheme.openid_config.load_config()📄 Example OpenAPI documentationYour OpenAPI documentation will get anAuthorizebutton, which can be used to authenticate.The user can select which scopes to authenticate with, based on your configuration.
Package: fastapi-bearer-auth
FastAPI Bearer AuthA simple FastAPI auth module implementingOAuth2 with Password (and hashing), Bearer with JWT tokens, including user signup, signin routes.InstallingWorks on python3.6+pipinstallfastapi-bearer-authExample of using#!/usr/bin/env python# coding: utf-8# yc@2020/08/27frompydanticimportBaseModelfromfastapiimportFastAPI,Dependsimportfastapi_bearer_authasfbaclassUserOut(BaseModel):username:strapp=FastAPI(title='Test App')# simple in-memory dbusers={}# Two required handler: handle_get_user_by_name and handle_create_user@fba.handle_get_user_by_nameasyncdefget_user_by_name(name):returnusers.get(name)@fba.handle_create_userasyncdefcreate_user(username,password):ifawaitget_user_by_name(username):raiseValueError('Username{}exists'.format(username))user={'username':username,'password':awaitfba.call_config('get_password_hash',password),}users[username]=userreturnuser# Three router depends available: fba.signup, fba.signin and fba.get_current_user# fba.signup resolve to User object@app.post('/user/signup',response_model=UserOut)asyncdefsignup(user=Depends(fba.signup)):returnuser# fba.signin resolve to {user: <user_object>, token: {token_type, access_token}}@app.post('/user/signin')asyncdefsignin(ret=Depends(fba.signin)):returnret['token']# fba.get_current_user resolve to User object or a HTTP 401 response@app.get('/user/me',response_model=UserOut)asyncdefme(user=Depends(fba.get_current_user)):returnuserNow head tohttp://127.0.0.1:8000/docsto test the API. Note themeroute, usingfba.get_current_userdependency to restrict resource for authenticated user.There's a simple command to achive this without writing any code:uvicornfastapi_bearer_auth.test:appCustomizeIn addition toget_user_by_name(name)andcreate_user(username, password), there're other functions can be override (withhandle_prefix):authenticate(username, password)verify_password(plain_password, hashed_password)get_password_hash(password)You can call all those functions withfba.call_config(name, *args, **kwargs).Also some params:ACCESS_TOKEN_EXPIRE_MINUTESALGORITHMSECRET_KEYUse something likefba.set_config({'SECRET_KEY': 'xxx', ...})to change it.The default tokenUrl for openapi docs isuser/signin, you can override this by setting env varTOKEN_URL.
Package: fastapi-better-di
fastapi-better-diWhat is this ?fastapi-better-diis a utility that allows you to use DI in fastapi without Depends()Installationpipinstallfastapi_better_diExamples# app.pyimportuvicornfromfastapiimportFastAPIfromfastapi_better_di.patcher.autoimportis_pathed# functions were patched immediately after importassertis_pathed(),"Something went wrong"classMyType:def__init__(self,value):self.value=valueapp=FastAPI()app.dependency_overrides[MyType]=lambda:MyType(123)@app.get("/")defhandler(my_type:MyType):# <- DI without `Depends()`assertmy_type.value==123returnmy_typeif__name__=="__main__":uvicorn.run(app)See all examplesUsagePatching:Auto patching: patches classes when importing:fromfastapi_better_di.patcher.autoimportis_pathed# The classes were patched immediately after import# To check if everything is OK, use assertassertis_pathed(),"Something went wrong"Manual patching: you need to callpatch()by yourself:fromfastapi_better_di.patcher.manualimportpatch,is_pathedpatch()# To check if everything is OK, use assertassertis_pathed(),"Something went wrong"ExamplesIMPORTANT: You can still use= Depends()without a function as an argument,
and it won't add unnecessary arguments to the swagger.Related issue:fastapi issueIMPORTANT: The main app(FastAPI) anddependency_overridesmust be initialized before importing routers!How it worksfastapi-better-disimply patch the handler function and add= Depends(func)as the default argument
Package: fastapibugmaker
一、安装（python版本建议3.7以上）pipinstalldubborequests二、升级包pipinstall--upgradedubborequests三、示例获取dubbo服务详情# 导入importdubborequests# 获取dubbo服务详情data=dubborequests.search('cn.com.xxx.sso.ehr.api.dubbo.SsoEmpInfoService')获取服务下的所有方法# 导入importdubborequests# 获取dubbo服务下的所有方法data=dubborequests.list('cn.com.xxx.sso.ehr.api.dubbo.SsoEmpInfoService')# 获取dubbo服务指定的方法data=dubborequests.list('cn.com.xxx.sso.ehr.api.dubbo.SsoEmpInfoService','login')通过zookeeper获取服务的ip和端口, Telnet命令测试dubbo接口importdubborequestsfromdubborequestsimportConfig# 先配置zookeeper中心地址Config.zookeeper_url_list=['192.168.240.15:2181','192.168.240.15:2182','192.168.240.15:2183']invoke_data={"service_name":"cn.com.xxxxx.sso.ehr.api.dubbo.SsoEmpInfoService","method_name":"login","data":{"account":"xxxx","password":"xxxx"}}# 通过zookeeper获取服务的ip和端口, Telnet命令测试dubbo接口data=dubborequests.zk_invoke(*invoke_data)Telnet命令测试dubbo接口importdubborequestsinvoke_data={"ip":'xxxx',"port":7777,"service_name":"cn.com.xxxxx.sso.ehr.api.dubbo.SsoEmpInfoService","method_name":"login","data":{"account":"xxxx","password":"xxxx"}}# Telnet命令测试dubbo接口data=dubborequests.telnet_invoke(*invoke_data)