Saravanan666/pypi-org huggingface dataset:
Package: sanic-ext
Sanic ExtensionsBuildDocsPackageSupportSanicstrives to be “Unopinionated and flexible”:Build the way you want to build without letting your tooling constrain you.But what happens when you want all the goodies? Sanic Extensions is an officially supported Sanic plugin to provide application developers with additional tools and features.FeaturesAuto create HEAD, OPTIONS, and TRACE endpointsCORS protectionPredefined, endpoint-specific response serializersArgument injection into route handlersOpenAPI documentation with Redoc and/or SwaggerRequest query arguments and body input validationInstallationpip install sanic[ext]
# OR
pip install sanic sanic-extGetting startedfromsanicimportSanicapp=Sanic("MyHelloWorldApp")Nothing new. Just start using Sanic and it will automatically be extended!Learn moreGo to theUser Guideto learn moreWarningSanic Extensions is still inALPHArelease. The API is not likely to change. It will move toBETAwith v22.3.
Package: sanic-ext-base
Forked from and based onhttps://github.com/Relrin/sanic-base-extension(sanic-base-extension)
Extensions were forked and modified to keep the code updated with
the latest version of dependecnies and to add additional functionalitysanic-ext-baseFlask-like extension support for Sanic frameworkFeaturesFlask-like style initializing and using with Sanic applicationsEasy to write a new extension and use it laterInstallationThis package should be installed using pip:pip install sanic-ext-baseExamplefromsanicimportSanicfromsanic_extimportBaseExtensionclassCustomExtension(BaseExtension):extension_name=app_attribute='custom'defhello(self,user):print("Hello,{}!".format(user))app=Sanic(__name__)CustomExtension()# available via `app.custom` or `app.extensions['custom']`app.custom.hello('world')# Hello, world!LicenseThe sanic-ext-base is published under BSD license. For more details readLICENSEfile.
Package: sanic-filter
Sanic filterRequired:Python: >=3.9SQLAlchemy: >=2.0.20OptionalSanic: >=23.3.0DataclassesInstallationpipinstallsanic-filterDescriptionYou define the fields you want to be able to filter on as well as the type of operatorname:str=Query(option='ilike')You can make some field mandatoryclassMyFilter(Filter)name:str=Query(option='ilike',required=True)Query?name=moon,sunsqlAlchemySELECT * FROM table WHERE table.name LIKE :name_1 OR table.name LIKE :name_2"Supported operators:likeilikein==!=If you want to search by JSON fields#SqlAlchemy modelproperties=Column(JSON,nullable=True)Filter supports one level of nestingcolor:str=Query(option='ilike’, json_column='properties',required=True)Query?name=moon,sunsqlAlchemySELECT * FROM table WHERE table.name LIKE :name_1 OR table.name LIKE :name_2"Returned fieldsYou can specify the returned fields of the models
Filterfields:str=Query(option='returned_fields')It will look like this
SqlAlchemy modelclassCar(BaseModel):__tablename__="cars"id=Column(UUID(as_uuid=True),primary_key=True,default=uuid.uuid4)name=Column(String,nullable=True)order=Column(String,nullable=True)properties=Column(JSON,nullable=True)Query?name=moon,sunsqlAlchemySELECT * FROM table WHERE table.name LIKE :name_1 OR table.name LIKE :name_2"The search for fields is performed automatically, if the field has the same name, use model namesqlalchemy modelsclassCar(BaseModel):__tablename__="cars"id=Column(UUID(as_uuid=True),primary_key=True,default=uuid.uuid4)classGarage(BaseModel):__tablename__=«garages»id=Column(UUID(as_uuid=True),primary_key=True,default=uuid.uuid4)filterid:str=Query(option='ilike',required=True,model=Car)routersquery.filter(select(Car,Garage))If you want to return fields with the same name, but from different models, use the alias parameter
id from Carcar_id:str=Query(option='ilike’,alias=‘id’,model=Car)garage_id:str=Query(option='ilike',alias=‘id’,model=Garage)
Package: sanic-fire
sanic-firesanic-fire is an extension for Sanic that adds support for writing external commands to your application.install$ pip install sanic-firequick start1.Step1: Create manager.py file in your project root directory.#!/usr/bin/python3
# -*- coding: utf-8 -*-

from sanic_fire import cmd
from sanic_fire.core import command_class, command_func


@command_class
class Hello(object):
    """ Annonation """
    
    def hello(self, value='world'):
        """ hello """
        return 'hello, ' + str(value)


@command_func
def sync_db():
    return 'init db'


if __name__ == '__main__':
    cmd()2.Step2: Run command on terminal:python3 manager.py sync_db
python3 manager.py Hello hello
Package: sanic-gunicorn
# sanic-gunicorn[Gunicorn](http://gunicorn.org/) worker for [Sanic](https://github.com/channelcat/sanic)## Installation`bash $ pip install-Usanic-gunicorn`## Usage`bash $ gunicorn--bindlocalhost:8000--worker-classsanic_gunicorn.Worker your_app_module:app `
Package: sanic-gzip
sanic-gzipA Sanic plugin to manage compression as a decoratorInstallationInstall withpip:pip install sanic-gzipUsageUsage is as simple as a decorator before your functionfromsanicimportSanicfromsanic_gzipimportcompressapp=Sanic(__name__)compress=Compress()@app.get("/logs")@compress.compress()asyncdefmy_verbose_function(request):The current version supports both gzip and deflate algorithms.OptionsConfig options are to be setted as init argument:Compression min. sizeCompression levelMIME types impactedNumber of threadused for compression
Package: sanic-healthcheck
sanic-healthchecksanic-healthcheckprovides a simple way to add health checks and readiness checks to
yourSanicapplication. This makes it easier to
monitor your application and ensure it is running in a health state. Monitoring or management
tools can ping these endpoints to determine application uptime and status, as well as perform
application restart to ensure your application isn't running in a degraded state.sanic-healthcheckwas inspired by and borrows fromRunscope/healthcheck.Installingpip install sanic-healthcheckDocumentationFor full project documentation, see:https://sanic-healthcheck.readthedocs.io/en/latest/ExampleBelow is a trivial example showcasing basic usage of sanic-healthcheckimportrandomfromsanicimportSanic,responsefromsanic_healthcheckimportHealthCheckapp=Sanic()health_check=HealthCheck(app)@app.route('/')asyncdeftest(request):returnresponse.json({'hello','world'})# Define checks for the health check.defcheck_health_random():ifrandom.random()>0.9:returnFalse,'the random number is > 0.9'returnTrue,'the random number is <= 0.9'if__name__=='__main__':health_check.add_check(check_health_random)app.run(host='0.0.0.0',port=8000)Licensesanic-healthcheckis licensed under the MIT license. SeeLICENSEfor details.
Package: sanic-ipware
This is a fork ofdjango-ipwareto work withSanic.OverviewBest attemptto get client’s IP address while keeping itDRY.NoticeThere is no real good “out-of-the-box” solution against fake IP addresses, aka “IP Address Spoofing”. You are encouraged to read theAdvanced userssection of this page and usetrusted_proxies_ipsand/orproxy_countfeatures to match your needs, especiallyifyou are planning to includesanic-ipwarein any authentication, security or “anti-fraud” related architecture.How to installThe best way to installsanic-ipwarewould be usingpip:pip install sanic-ipwareHow to useThere’s basically one method that should be usable fromsanic_ipware, calledget_client_ip. The result is aTuple[Optional[str], bool]of(ipaddr, routable).fromsanic_ipwareimportget_client_ip@app.get("/some/handler")asyncdefsomehandler(request):ip,routable=get_client_ip(request)ifipisnotNone:ifroutable:# we have a (probably) real, public ip address for userelse:# we have ip address, but it might not be public routableelse:# we don't have a ip address for the userAdvanced users# you can provide your own meta precedence order by using the# request_header_order in the function call:ip,routable=get_client_ip(request,request_header_order=['Forwarded-For','X-Forwarded-For'])# if you're going to do this a lot, wrap the function somewhere with# functools.partialfromfunctoolsimportpartialmy_get_client_ip=partial(get_client_ip,request_header_order=['Forwarded-For','X-Forwarded-For'])ip,routable=my_get_client_ip(request)# if you plan to use sanic_ipware in any authentication, security or# "anti-fraud" related architecture, you should configure it to only# "trust" one or more "known" proxy server(s)), in the function call:ip,routable=get_client_ip(request,proxy_trusted_ips=['198.84.193.158'])# you can perform the same functools.partial trick with these trusted IPsLicenseMIT, the same asdjango-ipwarelicense.Changelogv0.1.0 on 2018-09-28First release on PyPI. Not stable.
Package: sanic-json
sanic jsonA thin wrapper on sanic web framework to help writting JSON API.Recommond usejson-apiinstead. It's a abstraction library of this library.pip3 install sanic-jsonExmaplefileapi/random.pydefobj_to_dict(obj):ifnotobjorisinstance(obj,(str,int,float)):returnobjelifisinstance(obj,list):return[obj_to_dict(x)forxinobj]elifisinstance(obj,dict):return{k:obj_to_dict(v)fork,vinobj.items()}else:return{k:obj_to_dict(v)fork,vinobj.__dict__.items()}# the wrapper will get the args and kwargs value from the `request`asyncdefrandom_pohoto(req,count=10):res=api.photo.random(count=count)return{"data":obj_to_dict(res)}fileapp.pyfromsanicimportSanicfromsanic_jsonimportget_json_routefromapi.randomimportrandom_pohotoapp=Sanic()json_route=get_json_route(app)json_route("/api/random",random_pohoto)if__name__=="__main__":importosdebug=bool(os.getenv("DEBUG"))# hot reload in next release: https://github.com/channelcat/sanic/issues/168app.run(host="0.0.0.0",port=8000,debug=debug)
Package: sanic-jsonrpc
sanic-jsonrpcJSON-RPC 2.0 support for Sanic over HTTP and WebSocketFeaturesComplete JSON-RPC 2.0 Specification implementation, includingbatchAnnotation based type validationRequest and/or Notification routingConditional middlewareException handlersServer side NotificationsAccess to app and request objects via annotationExampleserver.pyfromsanicimportSanicfromsanic_jsonrpcimportSanicJsonrpcapp=Sanic('server')jsonrpc=SanicJsonrpc(app,post_route='/api/rpc/post',ws_route='/api/rpc/ws')@jsonrpcdefsub(a:int,b:int)->int:returna-bif__name__=='__main__':app.run(host='127.0.0.1',port=8000)client.pyfromasyncioimportget_event_loopfromaiohttpimportClientSessionasyncdefmain():url='http://127.0.0.1:8000/api/rpc'request={'jsonrpc':'2.0','method':'sub','params':[42,23],'id':1}asyncwithClientSession()assession:asyncwithsession.post(url+'/post',json=request)asresp:response=awaitresp.json()print(response['result'])# 19asyncwithsession.ws_connect(url+'/ws')asws:awaitws.send_json(request)response=awaitws.receive_json()print(response['result'])# 19if__name__=='__main__':get_event_loop().run_until_complete(main())
Package: sanic-jwt
Sanic JWTSanic JWT adds authentication protection and endpoints toSanic.It is botheasyto get up and running, andextensiblefor the
developer. It can act toprotect endpointsand also provideauthentication scoping, all wrapped into a niceJWT.Read the documentation|View the source codeWhat do I do?It's easy: (1) install, (2) initialize, and (3) authenticate.Install:pip install sanic-jwtInitialize:fromsanicimportSanicfromsanic_jwtimportInitializedefmy_authenticate(request,*args,**kwargs):...app=Sanic()Initialize(app,authenticate=my_authenticate)Authenticate:http://localhost/authCan I customize it?Definitely! Sanic JWT is made to allow developers to customize the operation to fit their needs.Check out the documentationto learn how.
Package: sanic-jwt-extended
Sanic-JWT-Extended (NOW PREPARING 1.0 RELEASE WITH MAJOR CHANGES)What is Sanic-JWT-Extended?Sanic-JWT-Extended is port of Flask-JWT-Extended for Sanic.When to use Sanic-JWT-Extended?Sanic-JWT-Extended not only adds support for using JSON Web Tokens (JWT) to Sanic for protecting views,
but also many helpful (andoptional) features  built in to make working with JSON Web Tokens
easier. These include:Support for adding custom claims to JSON Web TokensRefresh tokensToken freshness and separate view decorators to only allow fresh tokensRole-based access controlbuilt-in blacklist support<= WIPInstallationpipinstallsanic-jwt-extendedUsageView the documentation onlineGenerating DocumentationYou can generate a local copy of the documentation. After installing the requirements,
go to thedocsdirectory and run:$ make clean && make html
Package: sanickit
SanicKitSanicKit is a framework that applies some of the ideas of Svelte-kit to the Sanic web framework. In particular:File-path routingEasy deploymentThe framework is designed for multi-page apps - pages are rendered on the server and sent to the browser. Libraries such ashtmxcan be used to create a more SPA-like experience.Table of ContentsInstallationLicenseInstallationpip install sanickitLicenseSanicKitis distributed under the terms of theMITlicense.
Package: sanic-management-blueprint
# Sanic Management Blueprint[![Build Status](https://travis-ci.org/stone-payments/sanic-management-blueprint.svg?branch=master)](https://travis-ci.org/stone-payments/sanic-management-blueprint)This repository contains a project developed with Python3 :heart: with a blueprint that describe the necessary endpoints to meet the engineering goals.## Starting…This instructions should be enough to replicate the development enviroment of this project. If this is not the case, please, feel free to open a pull request.## PrerequisitesAfter cloning the project, you will need Python 3.5.## Environment` python3-mvenv /path/to/new/virtual/environment source venv/bin/activate pip install-rrequirements.txt `## SettingsTo successfully set up the project, a json file is needed. This file should be in path described in the enviroment variable CONFIG_FILE_PATH.Besides that, all of the project’s dependencies should be added with theAppInfo’s methodregister_resource. This method should receive a function that returnsTrueorFalsedepending on the dependency’s health.## RunningIf all goes right, you should be run therun.pyfile inside the samples folder.## TestingUnit tests:nosetests tests/unitCoverage:nosetests –with-coverage –cover-package=sanic_management_blueprint## Built WithPython 3.5.2## AuthorsBuild with :heart: by Team Satisfação do Cliente!## LicenseCopyright (C) 2018. Stone Pagamentos. All rights reserved.
Package: sanic-mongo
sanic-mongo====================sanic的mongodb异步工具,灵感来源自 `官方例子 <https://github.com/channelcat/sanic/blob/master/examples/sanic_motor.py).是[motor](https://motor.readthedocs.io/en/stable/tutorial-asyncio.html>`_ 的封装,目的只是为了简化操作.更新-----------------------* v1.7.1 修正了mongo连接权限可能引发的问题,现在可以配置每个连接是否是只能连database,默认为False.{"uri":xxxx,"only_db":True}* v1.6.0 修正了验证无法通过的问题* v1.5.0 将接口调整至和sanic-aioorm一致.特点 Features-------------------------* `motor <https://motor.readthedocs.io/en/stable/tutorial-asyncio.html>`_ 支持的操作都支持* 支持3.5版本以上的* 支持多数据库* 支持mongodb和gridfs依赖 Requirements-----------------------------1. motor>=1.12. pymongo>=3.4.03. sanic>=0.4.1安装 Installation--------------------------- ``pip install sanic-mongo``用法----------------------------mongo需要给`app.config`设置关键字`MONGO_URIS`,它是一个由mongodb名字和url组成的字典.同时也可以使用`Mongo.SetConfig(app,**kws)`来注册kws的内容到`MONGO_URIS`.而使用的时候可以访问`app.mongo[mongodb名字]`访问对应的dbgridfs与之类似,只是关键字是`GRIDFS_SETTINGS`,而访问需要使用`app.GridFS[GridFS名字]`例子 Example-----------------------------------1. mongodb.. code:: pythonfrom sanic import Sanicfrom sanic.response import jsonfrom sanic_mongo import Mongoapp = Sanic(__name__)mongo_uri = "mongodb://{host}:{port}/{database}".format(database='test',port=27017,host='localhost')Mongo.SetConfig(app,test=mongo_uri)Mongo(app)@app.get('/objects')async def get(request):docs = await app.mongo['test'].test_col.find().to_list(length=100)for doc in docs:doc['id'] = str(doc['_id'])del doc['_id']return json(docs)@app.post('/objects')async def new(request):doc = request.jsonprint(type(app.mongo['test']))object_id = await app.mongo['test']["test_col"].save(doc)return json({'object_id': str(object_id)})if __name__ == "__main__":app.run(host='127.0.0.1', port=8000,debug=True)2. gridfs.. code:: pythonfrom sanic import Sanicfrom sanic.response import json,textfrom sanic_mongo import GridFSapp = Sanic(__name__)mongo_uri = "mongodb://{host}:{port}/{database}".format(database='test',port=27017,host='localhost')GridFS.SetConfig(app,test_fs=(mongo_uri,"fs"))GridFS(app)@app.get('/pics')async def get(request):cursor = app.GridFS["test_fs"].find()result = [{i._id:i.name} async for i in cursor]return json({"result":result})@app.post('/pics')async def new(request):doc = request.files.get('file')async with app.GridFS["test_fs"].open_upload_stream(filename=doc.name,metadata={"contentType": doc.type}) as gridin:object_id = gridin._idawait gridin.write(doc.body)return json({'object_id': str(object_id)})if __name__ == "__main__":app.run(host='127.0.0.1', port=8000,debug=True)
Package: sanic-mongodb-extension
MongoDB with μMongo ODM support for Sanic frameworkFeaturesUsesmotor_asynciopackage for async queries to MongoDBGood integrated withuMongoODM, so that you can use it easily in your projectsInstallationThis package should be installed using pip:pip install sanic-mongodb-extensionExample#!/usr/bin/env python3fromsanicimportSanic,responsefromsanic_mongodb_extimportMongoDbExtensionfromumongoimportInstance,Document,MotorAsyncIOInstancefromumongo.fieldsimportStringFieldapp=Sanic(__name__)# Configuration for MongoDB and uMongoapp.config.update({"MONGODB_DATABASE":"app",# Make ensure that the `app` database is really exists"MONGODB_URI":"mongodb://root:root@mongodb:27017",# You can also specify custom connection options.# For more details check the official docs: https://api.mongodb.com/python/3.7.0/api/pymongo/mongo_client.html#pymongo.mongo_client.MongoClient"MONGODB_CONNECT_OPTIONS":{"minPoolSize":10,"maxPoolSize":50,},"LAZY_UMONGO":MotorAsyncIOInstance(),})# uMongo client is available as `app.mongodb` or `app.extensions['mongodb']`.# The lazy client will be available as `app.lazy_mongodb` only when the database was specified,# and which is a great choice for the structured projects.MongoDbExtension(app)# Describe the model@app.lazy_umongo.registerclassArtist(Document):name=StringField(required=True,allow_none=False)# And use it later for APIs@app.route("/")asyncdefhandle(request):artist=Artist(name="A new rockstar!")awaitartist.commit()returnresponse.json(artist.dump())if__name__=='__main__':app.run(host='0.0.0.0',port=8000)LicenseThe sanic-mongodb-extension is published under BSD license. For more details readLICENSEfile.Real project examplesOpen Matchmaking project:Auth/Auth microserviceGame servers pool microservicePlayer statistics microservice
Package: sanic-oauth
Simple OAuth library to work with sanic. Basically, just rewrited version ofaioauth_clientwith async/await syntax and some optimization. Can be used only with python 3.5/3.6.Available providers (in alphabetic order):AmazonBitBucketBitBucket v2Discord (thanks to @smlbiobot)EventbriteFacebookFlickrFoursquareGithubGitLabGoogleLinkedInMeetupok.ruPinterestPlurkTumblrTwitterVimeovk.comYahooYandexRequirementspython >= 3.6InstallationJust install via pip:pip install sanic_oauthNote, that to use blueprint correctly, you need to additionally installsanicandsanic-session.UsageSimple way for use this is blueprint with oauth configuration.But, before use it you need to:Createaiohttp.ClientSessionand bind to app likeasync_sessionvariable.Create session interface fromsanic-sessionpackage and bind it to app likesession_interfacevariable.Configureapp.configsettings. You should passOAUTH_PROVIDER, OAUTH_REDIRECT_URI, OAUTH_SCOPEand another settings, for example,OAUTH_CLIENT_ID, OAUTH_CLIENT_SECRET. Every setting withOAUTHprefix will be passed to oauth provider construction.Apply blueprintAdd decoratorlogin_requiredto routes, that required oauth.You can seeexamplefor more details.Advanced usageIf you don’t like current blueprint, you always can use providers directly and implements you own logic, like inold_example.
Package: sanic-oauthlib
Sanic-OAuthlib is an extension to Sanic that allows you to interact with
remote OAuth enabled applications. On the client site, it is a replacement
for Sanic-OAuth. But it does more than that, it also helps you to create
OAuth providers.Sanic-OAuthlib is a fork of Flask-OAuthlib, ported to sanic using the
SanicPluginsFramework.Sanic-OAuthlib relies onoauthlib.Features(These features are directly ported from Flask-OAuthLib)Support for OAuth 1.0a, 1.0, 1.1, OAuth2 clientFriendly API (same as Sanic-OAuth)Direct integration with Sanic using SanicPluginsFrameworkBasic support for remote method invocation of RESTful APIsSupport OAuth1 provider with HMAC and RSA signatureSupport OAuth2 provider with Bearer tokenAnd request more features atgithub issues.Security ReportingIf you found security bugs which can not be public, send me email atashleysommer@gmail.com.
Attachment with patch is welcome.InstallationInstalling sanic-oauthlib is simple withpip:$ pip install Sanic-OAuthlibIf you don’t have pip installed, try with easy_install:$ easy_install Sanic-OAuthlibAdditional NotesSee the original documentation for Flask-OAuthlib here:flask-oauthlib@readthedocs.If you are only interested in the client part, you can find some examples
in theexampledirectory.There is also adevelopment versionon GitHub.
Package: sanic-openapi
⚠️ This package is being replaced bySanic Extensions. The project will continue to be monitored, but no new features or major development is anticipated. Sanic Extensions contains a near 1:1 upgrade if you are using Sanic OpenAPI with OAS3. Ask in theforumsordiscord serverfor questions about upgrading.Sanic OpenAPIGive your Sanic API a UI and OpenAPI documentation, all for the price of free!Check outopen collectiveto learn more about helping to fund Sanic.Installationpipinstallsanic-openapiAdd Swagger UI with the OpenAPI spec:fromsanic_openapiimportswagger_blueprintapp.blueprint(swagger_blueprint)You'll now have a Swagger UI at the URL/swagger/and an OpenAPI 2.0 spec at/swagger/swagger.json.
Your routes will be automatically categorized by their blueprints.OpenAPI 2Here is an example to use Sanic-OpenAPI 2:fromsanicimportSanicfromsanic.responseimportjsonfromsanic_openapiimportopenapi2_blueprintapp=Sanic(name="AwesomeApi")app.blueprint(openapi2_blueprint)@app.route("/")asyncdeftest(request):returnjson({"hello":"world"})if__name__=="__main__":app.run(host="0.0.0.0",port=8000)And you can get your Swagger document athttp://localhost:8000/swaggerlike this:OpenAPI 3Here is an example to use Sanic-OpenAPI 3:fromsanicimportSanicfromsanic.responseimportjsonfromsanic_openapiimportopenapi3_blueprintapp=Sanic(name="AwesomeApi")app.blueprint(openapi3_blueprint)@app.route("/")asyncdeftest(request):returnjson({"hello":"world"})if__name__=="__main__":app.run(host="0.0.0.0",port=8000)And you can get your Swagger document athttp://localhost:8000/swaggerlike this:DocumentationPlease check the documentation onReadthedocsContributionAny contribution is welcome. If you don't know how to getting started, please check issues first and check ourContributing Guideto start you contribution.