Saravanan666/pypi-org huggingface dataset:
Package: sanic-openapi3
Sanic OpenAPI v3Give your Sanic API an OpenAPI v3 specification.
Based on originalSanic OpenAPIextension.Installationpipinstallsanic-openapi3UsageImport blueprint and use simple decorators to document routes:fromsanic_openapi3importopenapi,openapi_blueprint@app.get("/user/<user_id:int>")@openapi.summary("Fetches a user by ID")@openapi.response(200,{"user":{"name":str,"id":int}})asyncdefget_user(request,user_id):...@app.post("/user")@openapi.summary("Creates a user")@openapi.body({"user":{"name":str}})asyncdefcreate_user(request):...app.blueprint(openapi_blueprint)You'll now have a specification at the URL/openapi.json.
Your routes will be automatically categorized by their blueprints.Model your input/outputclassCar:make=strmodel=stryear=intclassGarage:spaces=intcars=[Car]@app.get("/garage")@openapi.summary("Gets the whole garage")@openapi.response(200,Garage)asyncdefget_garage(request):returnjson({"spaces":2,"cars":[{"make":"Nissan","model":"370Z"}]})Get more descriptiveclassCar:make=doc.String("Who made the car")model=doc.String("Type of car.  This will vary by make")year=doc.Integer("4-digit year of the car",required=False)classGarage:spaces=doc.Integer("How many cars can fit in the garage")cars=doc.List(Car,description="All cars in the garage")Configure all the thingsapp.config.OPENAPI_VERSION='1.0.0'app.config.OPENAPI_TITLE='Car API'app.config.OPENAPI_DESCRIPTION='Car API'app.config.OPENAPI_TERMS_OF_SERVICE='https://example.com/terms'app.config.OPENAPI_CONTACT_EMAIL='mail@example.com'app.config.OPENAPI_CONTACT_NAME='mail@example.com'
Package: sanic-pw
# Sanic-PWA port of the [Flask-PW](https://github.com/klen/flask-pw) package for [Sanic framework](https://github.com/channelcat/sanic).# Features- Configuring Peewee ORM like in Flask with SQLAlchemy- Migrate commands (create, rollback, etc.) via:- using commands as a part of Sanic-Script- click CLI- Pre- and post-signals support for saving and deleting# Requirements- Python 3.6+ (older not tested)# Dependency noteFor using the 2nd version of Peewee ORM, please use `sanic-pw==0.1.0`.# Using## InstallingFor installing Sanic-PW use the following command:```pip install sanic-pw```## List of available settings| Config parameter | Description |  Default value ||------------------|-------------|----------------|| PEEWEE_DATABASE_URI      | A connection URI                                        | `'sqlite:///peewee.sqlite'`  || PEEWEE_CONNECTION_PARAMS | Connection parameters for Peewee ORM                    | `{}`                         || PEEWEE_MIGRATE_DIR       | Path to directory with migrations                       | `'migrations'`               || PEEWEE_MIGRATE_TABLE     | Name of database table with migrations                  | `'migratehistory'`           || PEEWEE_MODELS_MODULE     | Path to module which contains you applications' Models  | `''`                         || PEEWEE_MODELS_IGNORE     | Models which should be ignored in migrations            | `[]`                         || PEEWEE_MODELS_CLASS      | Base models class                                       | `<sanic_pw.Model>`           || PEEWEE_MANUAL            | Don't connect to db when request starts and close when it ends automatically | `False` || PEEWEE_USE_READ_SLAVES   | Use database slaves for reading data when coming `SELECT ...` queries        | `True`  || PEEWEE_READ_SLAVES       | A list of nodes which can be used for reading                                | `[]`    |## MigrationsIf you're using the Sanic-Script package, then append a new command to your manager:```pythonfrom sanic_pw import Peewee# ...app.db = Peewee(app)manager = Manager(app)manager.add_command('db', app.db.manager)```For a case when you're prefer to use click it almost the same:```pythonfrom sanic_pw import Peewee# ...app.db = Peewee(app)app.db.cli()```After it, you can use database `create`, `migrate` or `rollback` commands.
Package: sanicpydantic
sanicpydanticPydantic validation for Sanic frameworkInstall:pipinstallsanicpydanticExample:frompydanticimportBaseModelfromsanic_pydanticimportRequestValidatorvalidator=RequestValidator()...classQueryModel(BaseModel):str_param:strint_param:intbool_param:bool@app.get('/')@validator(query_schema=QueryModel)defget_endpoint(request,query_:QueryModel):...classJsonModel(BaseModel):str_field:strint_field:intbool_field:bool@app.post('/')@validator(json_schema=JsonModel)defpost_endpoint(request,json_:JsonModel):...
Package: sanic-pydantic
Sanic PyndaticDescriptionA library for parsing and validating http requests for sanic web-framework using pydantic libraryFull documentationhereRequirementspython >= 3.7How to installpipinstallsanic-pydanticDependenciespydanticExamplefromsanic_pydanticimportwebargsfromsanicimportSanicfromsanic.responseimportjsonfrompydanticimportBaseModelapp=Sanic("new app")classPathModel(BaseModel):id:intclassQueryModel(BaseModel):name:strclassBodyModel(BaseModel):age:intclassHeadersModel(BaseModel):api_key:str=Field(alias="x-api-key")@app.route("/get/<id:int>",methods=["GET"])@webargs(path=PathModel,headers=HeadersModel)defexample_get_endpoint_params(request,id,**kwargs):response=json({"id":id})returnresponse@app.route("/get-request",methods=["GET"])@webargs(query=QueryModel)defexample_get_endpoint(request,**kwargs):print(kwargs)response=json(kwargs)returnresponse@app.route("/post-request",methods=["POST"])@webargs(query=QueryModel,body=BodyModel)defexample_post_endpoint(request,**kwargs):print(kwargs)response=json(kwargs)returnresponse@app.route("/async-get-request",methods=["GET"])@webargs(query=QueryModel)asyncdefasync_example_get_endpoint(request,**kwargs):print(kwargs)response=json(kwargs)returnresponse@app.route("/async-post-request",methods=["POST"])@webargs(query=QueryModel,body=BodyModel)asyncdefasync_example_post_endpoint(request,**kwargs):print(kwargs)response=json(kwargs)returnresponseif__name__=="__main__":app.run(host="0.0.0.0",port=8000)
Package: sanic-quill
sanic-quillSanic-quill is a port of Flask-quill (https://github.com/drewdru/flask-quill/) to Sanic ecosystem. (wtforms widget for quill.js editor (https://github.com/quilljs/quill))Quill.js is a modern WYSIWYG editor built for compatibility and extensibility.To add routes with edit form:from sanic_quill import add_editoreditor will be able on the route /editHow to useCheck sample in ‘examples’.To add  WYSIWYG editor to edit any data/fields you need to define 2 methods:get_data (used by editor to get information for model to edit in form)save_data (used by editor to save changes from the form)Editor expect 3 fields in data:‘title’,‘body’,‘preview’fromsanic_quillimportadd_editor...# your Sanic app code# with defining app = Sanic()...defget_data(_id):""" this method defines logic to send to 'edit' form data of the object """forpostinposts:ifpost['id']==_id:post['title']=post['title']post['content']=post['text']post['preview']=post['preview']returnpostdefsave_data(_id,data):"""
        this method defines logic to save data from 'edit' form

        data comes like a dict with: content, content_preview and title fields,
        you need map it to your structure
    """fornum,postinenumerate(posts):ifpost['id']==_id:print('Update post')post['title']=data['title']post['text']=data['content']post['description']=data['preview']breakadd_editor(app,get_data,save_data)After that you will have routes ‘/edit?’id=$id_of_your_data_item_to_editAlso you can define a path where to save an images and route that will be used to serve uploaded images by default it is ‘/img’:add_editor(app,get_data,save_data,img_folder="/path/for/images",route_for_img='/custom_route')
Package: sanic-redis-extend
sanic-redisRedis support for sanic.Built on top ofaioredis.InstallationYou can install this package as usual with pip:pip install sanic-redis-extendConfigFor example:redis://[[username]:[password]]@localhost:6379/0
rediss://[[username]:[password]]@localhost:6379/0
unix://[[username]:[password]]@/path/to/socket.sock?db=0ExamplefromsanicimportSanicfromsanic.responseimporttextfromsanic_redis_extendimportSanicRedisExtendapp=Sanic(__name__)app.config.update({'REDIS':"redis://default:xxx@127.0.0.1:6379/1",})redis=SanicRedisExtend()redis.init_app(app)@app.route('/')asyncdeftest3(request):# request.app.ctx.{redis_name}, the {redis_name} == config_name.lower()asyncwithrequest.app.ctx.redisasr:awaitr.set('key1','value1')result=awaitr.get('key1')returntext(str(result))if__name__=='__main__':app.run()
Package: sanic-redis-extension
Redis support for Sanic frameworkFeaturesBased on theredislibraryEasy to use and configurate for your own projectsInstallationThis package should be installed using pip:pip install sanic-redis-extensionExamplefromsanicimportSanic,responsefromsanic_redis_extimportRedisExtensionapp=Sanic(__name__)# Configuration for Redisapp.config.update({"REDIS_HOST":"127.0.0.1","REDIS_PORT":6379,"REDIS_DATABASE":0,"REDIS_MAX_CONNECTIONS":15,})RedisExtension(app)# Connection pool is available as `app.ctx.redis` or `app.ctx.extensions['redis']`@app.route("/")asyncdefhandle(request):awaitrequest.app.ctx.redis.set('test-my-key','value')val=awaitrequest.app.ctx.redis.get('test-my-key')returnresponse.text(val.decode('utf-8'))LicenseThe sanic-redis-extension is published under BSD license. For more details readLICENSEfile.
Package: sanic-restful-api
Sanic-RESTful-ApiSimple framework for creating REST APIsIntroduceAfter writing Sanic for a long time, I found that there was no framework similar to flask-restful, so I wrote one myself.flask-restfulDocumentclick meInstallationpip install sanic-restful-apiSimple usesfromsanicimportSanicfromsanic_restful_apiimportreqparse,abort,Api,Resourceapp=Sanic(__name__)api=Api(app)TODOS={'todo1':{'task':'build an API'},'todo2':{'task':'?????'},'todo3':{'task':'profit!'},}defabort_if_todo_doesnt_exist(todo_id):iftodo_idnotinTODOS:abort(404,message="Todo{}doesn't exist".format(todo_id))parser=reqparse.RequestParser()parser.add_argument('task')# Todo#   show a single todo item and lets you delete themclassTodo(Resource):asyncdefget(self,request,todo_id):abort_if_todo_doesnt_exist(todo_id)returnTODOS[todo_id]asyncdefdelete(self,request,todo_id):abort_if_todo_doesnt_exist(todo_id)delTODOS[todo_id]return'',204asyncdefput(self,request,todo_id):args=parser.parse_args(request)task={'task':args['task']}TODOS[todo_id]=taskreturntask,201# TodoList#   shows a list of all todos, and lets you POST to add new tasksclassTodoList(Resource):asyncdefget(self,request):returnTODOSasyncdefpost(self,request):args=parser.parse_args(request)todo_id='todo%d'%(len(TODOS)+1)TODOS[todo_id]={'task':args['task']}returnTODOS[todo_id],201### Actually setup the Api resource routing here##api.add_resource(TodoList,'/todos')api.add_resource(Todo,'/todos/<todo_id:string>')if__name__=='__main__':app.run(debug=True)
Package: sanic-restful-resources
sanic-restful-resourcesSimple library for creating RESTful APIs with sanicFeaturessimplicityschematics integrationexceptions handlingunified response format100% coverageUsagepython3-mpipinstallsanic-restful-resourcesExampleusers=[{'name':'Michael'},{'name':'Ivan'}]classUserPostSchema(Model):name=StringType(required=True)@resource('/users')classUsers:asyncdefget(self,request):returnusers@validate(user_data=UserPostSchema)asyncdefpost(self,request,user_data):users.append({'name':user_data.name})return'',204More examples inthis folder.Guideresource(uri='')- return decorator for classes that will be
considered RESTful resources. This decorator automatically extends
HTTPMethodView (refer to sanic documentation for details). You can
provide resource URI through decorator or by class attributeuri.
You can provide decorators for all the methods through class
attributedecorators.Examples of possible return values for handlers:return"data",200,{"X-Custom-Header":"Value"}return"data",200return"data"return{"arg":"val"}return["val1","val2"]return"",201returnsanic.response.json# .text, .html, e.t.c.Api(name='API', url_prefix)- class for aggregating resources
and registrating them in the sanic application. Internally it uses
blueprints. Basic workflow:fromsanicimportSanicfromresourcesimportUser,Usersapp=Sanic()api=Api(url_prefix='/api/v1')api.add_resource(User)api.add_resource(Users)api.init_app(app)# ...validate(**models)- decorator for methods, that will validate
incoming data with provided models from Schematics library. Successfully
validated and parsed models will be passed as keyword arguments to
the handler method. If any model fails to validate - handler will
not be called.error(description=None, details=None, status=400, **kwargs- method
for returning errors from handlers.collect_args(request)- method for getting data from all possible
sources of data in the request.
Package: sanic-rollbar
Sanic-Rollbar=============A Rollbar plugin for Sanic, inspired by flask-rollbar.Free software: MIT license## Installation```bashpip install sanic-rollbar```## UsageSet your Rollbar token in config file, like:```pythonROLLBAR_TOKEN = os.getenv('ROLLBAR_TOKEN')```In your Sanic app, initialize the plugin:```pythonfrom sanic import Sanic, responsefrom sanic_rollbar import SanicRollbarfrom yourapp import configapp = Sanic(__name__)app.config.from_object(config)SanicRollbar(app)```Changelog=========0.1.0 (2017-12-20)------------------* First sketch.
Package: sanic-route
sanic_route扩展了 Sanic 的路由装饰器，使得通过一次注册就加载整个模块包括其子模块内全部被 @http_* 装饰的处理器。使用和示例# 通过 pip 安装pipinstallsanic_route示例示例结构如下，通过执行 python demo.py 来启动示例。demo.py
example
  |- __init__.py
  |- controller
        |- __init__.py
        |- bar.py
        |- foo.py# demo.pyfromsanicimportSanicfromsanic.responseimportjsonfromsanic_routeimportattachfromexampleimportcontrollerapp=Sanic("sanic_route_debug_app")# 注册整个模块内被 @http_* 装饰器标记的路由attach(app,controller)@app.route('/')asyncdeftest(request):'''原本的 sanic 路由'''returnjson({'hello':'world'})if__name__=='__main__':app.run()# example/controller/__init__.py# 注册了 /example.html 的路由。fromsanic.responseimportjsonfromsanic_routeimporthttp_get@http_get('/example.html')asyncdefindex(request):returnjson({'hello':'world'})# example/controller/bar.py# 注册了 /bar/index.html 和 /bar/info/<bid:int>' 的路由。fromsanic.responseimportjsonfromsanic_routeimporthttp_getclassBarController:''''''@http_get('/bar/index.html')asyncdefindex(self,request):''''''page=request.args.get('p',[1])[0]returnjson({'bar':'index','page':page})@http_get('/bar/info/<bid:int>')asyncdefinfo(self,request,bid):returnjson({'bar':bid})# example/controller/foo.pyfromsanic.responseimportjsonfromsanic_routeimporthttp_any,http_delete,http_post,http_putclassFooController:''''''@http_post('/foo/post')asyncdefindex(self,request):''''''returnjson({'foo':'post'})@http_any('/foo/any')asyncdefrequest_any(self,request):''''''returnjson({'foo':'any'})@http_delete('/foo/delete/<fid:int>')asyncdefdelete_one(self,request,fid):''''''returnjson({'foo':'delete','fid':fid})@http_put('/foo/put')asyncdefput_one(self,request):''''''returnjson({'foo':'put'})开发与发布注：如果要扩展本库，可以 fork 后添加自己的修改。# 安装 setup.py 依赖的库。pipinstallran# 安装本地的本库进环境 用于调试。pipinstall-e.-ihttps://pypi.python.org/pypi# 安装发布打包的工具。pipinstalltwinewheel# 打包pythonsetup.pysdistbdist_wheel# 上传twineuploaddist/*# 发布后可以指定源更新，这样可以测试发布后的效果。pipinstall--upgradesuoran-ihttps://pypi.python.org/pypi
Package: sanic-sass
Sanic-sass 0.1.0A simple and pythonic way to implement Sass & SCSS into Sanic without using webpack!FeaturesOn the fly compiling to speed up development with our middleware.Compile your entire application at once for at productionExamplesPrecompiledfromsanicimportSanicfromsanic_sassimportSassManifestwebserver=Sanic(name='precompiled')manifest=SassManifest('/static/css','./css','./hidden',css_type='sass')manifest.compile_webapp(webserver,register_static=True)webserver.run(host='0.0.0.0',port=8000)As middelwarefromsanicimportSanicfromsanic_sassimportSassManifestwebserver=Sanic(name='middelware')manifest=SassManifest('/static/css','./css','./hidden',css_type='scss')manifest.middelware(webserver)webserver.run(host='0.0.0.0',port=8000,debug=True)
Package: sanic-scheduler
# Sanic SchedulerSanic Scheduler runs a functions on a schedule.## InstallationAutomatic installation:```bash$ pip install sanic-scheduler```Sanic Scheduler is listed in [PyPI](https://pypi.python.org/pypi/sanic-scheduler) and can be installed with pip or easy_install.Manual installation:```bash$ git clone https://github.com/asmodius/sanic-scheduler.git$ cd sanic_scheduler$ python setup.py install```Sanic Scheduler source code is [hosted on GitHub](https://github.com/asmodius/sanic-scheduler)## Usage```pythonimport asynciofrom datetime import datetime, time, timedeltafrom sanic import Sanicfrom sanic_scheduler import SanicScheduler, taskapp = Sanic()scheduler = SanicScheduler(app)@task(timedelta(seconds=30))def hello(app):"""Runs the function every 30 seconds."""print("Hello, {0}".format(app), datetime.now())@task(timedelta(hours=1), time(hour=1, minute=30))async def foo_bar(_):"""Runs the function every 1 hours after 1:30."""print("Foo", datetime.now())await asyncio.sleep(1)print("Bar")@task(timedelta(minutes=2), timedelta(seconds=10))def baz(_):"""Runs the function every 2 minutes after 10 seconds."""print("Baz", datetime.now())@task(start=timedelta(seconds=10))def another(_):"""Run the function after 10 seconds once."""print("another", datetime.now())if __name__ == "__main__":app.run(host='127.0.0.1', port=5000, debug=True)```
Package: sanic-secure-session
Gotta get your sessions fast!=============================Cookie-based sessions are still a common way to track users's sessions.Flask and Django have really good support for server-side sessions, but not Sanic yet.So `sanic-secure-session` is an attempt to create a simple yet enough secure session support for Sanic.* Server-side sessions (currently only Redis backend implemented)* Signed session cookie (sure, using `itsdangerous`)* Easily extensible backends (only serialization and storage-related logic there)## Usage example```pythonfrom datetime import timedeltaimport asyncio_redisfrom sanic import Sanicfrom sanic.response import textfrom sanic_secure_session import SanicSessionfrom sanic_secure_session.backends.redis import RedisStorageBackendclass RedisPool:"""A simple wrapper class that allows you to share a connectionpool across your application."""_pool = Noneasync def get_pool(self):if not self._pool:self._pool = await asyncio_redis.Pool.create(host='localhost', port=6379, poolsize=10)return self._poolredis_pool = RedisPool()storage_backend = RedisStorageBackend(redis_connection=redis_pool.get_pool)app = Sanic()SanicSession(app, secret_key='aeNgaif6Ieyishoh', storage_backend=storage_backend,ttl=timedelta(minutes=1), http_only=True, secure=True)@app.route("/")async def index(request):# interact with the session like a normal dictif not request['session'].get('foo'):request['session']['foo'] = 0request['session']['foo'] += 1return text({'cookies': request.cookies,'session': request['session']})if __name__ == "__main__":app.run(host="0.0.0.0", port=8000, debug=True)```
Package: sanic-sentry
Sanic-Sentry – Sentry integration to sanic web server.Requirementspython >= 3.5InstallationSanic-Sentryshould be installed using pip:pip install sanic-sentryUsageTo initialize plugin you can pass ‘app’ to __init__:>>>fromsanicimportSanic>>>fromsanic_sentryimportSanicSentry>>>app=Sanic(__name__)>>>plugin=SanicSentry(app)Or useinit_appto reverse dependency:>>>plugin=SanicSentry()>>>plugin.init_app(app)Optional parameters:SENTRY_DSN- Sentry DSN for your application:If not set raven will fallback to SENTRY_DSN environment variable. Not setting either will disable raven.>>>app.config['SENTRY_DSN']='http://public:secret@example.com/1'SENTRY_PARAMS- Configure advanced parameters for sentry:Explained inhttps://docs.sentry.io/clients/python/advanced/>>>app.config['SENTRY_PARAMS']={..."release":"myapp_v0.4",..."environment":"production",...}
Package: sanic-sentry-error-handler
Sentry error handler for Sanic web serverRequirementspython >= 3.5Installationsanic-sentry-error-handlershould be installed using pip:pip install sanic-sentry-error-handlerUsageSENTRY_DSN- Sentry DSN for your applicationTo begin we’ll set up a Sanic app:>>>fromsanicimportSanic>>>fromsanic_sentryimportSanicSentryErrorHandler>>>app=Sanic(__name__)>>>app.error_handler=SanicSentryErrorHandler('http://public:secret@example.com/1')If your application uses theSanic exception handling viewsyou might consider using decorator for intercepting the exceptions.>>>fromsanicimportresponse,Sanic>>>fromsanic_sentryimportSanicSentryErrorHandler>>>>>>sentry_client=SanicSentryErrorHandler('http://public:secret@example.com/1')>>>app=Sanic(__name__)>>>>>>>>>@app.exception([Exception,])>>>@sentry_client.intercept_exception>>>defhandle_exception_500(request,exception):>>>returnresponse.json({"description":"Internal Server Error"},status=500)
Package: sanic-service-utils
sanic-service-utilsset of utils to use with sanic frameworkInstallationsanic-service-utilsis available as a python library on Pypi. Installation is very simple using pip :$pipinstallsanic-service-utilsThis will installsanic-service-utilsas well as external dependency.Basic usageBasicallysanic-service-utilsis just set of blueprints for sanic and additional stuff. You should name you app correctly to use this set.BlueprintsAll blueprints can be found inlistenersmodule.anji_orm_configuration:Basically, setupregisterwhen you start app and stop it, when you stop app. Blueprint use variablesANJI_ORM_CONNECTION_STRINGfrom configuration to configure register.sentry_configuration:Configure sentry for web server, use variableSENTRY_DSNfrom configuration.backgroun_task_configuration:Set empty list like variabletasks_listto sanic app that will be cancelled on server stop. Please, use listenerafter_server_startto add new tasks.aiohttp_session_configuration:Just configure aiohttp settion likeasync_sessionvariable for app.jinja_session_configuration:Just configure jinja render system likejinjavariable for app.log_configuration:Just configure logging for app by app name.sanic_session_configuration:Configure sanic session plugin, you should add variablesession_interfacewith SessionIntreface object to sanic app object.
Package: sanic-session
Sanic session management for humans:warning: Warning: This poject in Pull-Request-Only mode. I don't use Sanic anymore for any of my projects and will not make any changes by my own in foreseeable future. I recommend to use AIOHTTP since it more mature and have bigger adoption (I'm not judging by github stars only). Though I will accept pull requests from others if you want to see updates in the code.sanic_sessionis session management extension forSanicthat integrates server-backed sessions with most convenient API.sanic_sessionprovides a number ofsession interfacesfor you to store a client's session data. The interfaces available right now are:Redis (supports both driversaioredisandasyncio_redis)Memcache (viaaiomcache)Mongodb (viasanic_motorandpymongo)In-Memory (suitable for testing and development environments)InstallationInstall withpip(there is other options for different drivers, check documentation):pip install sanic_sessionor if you preferPipenv:pipenv install sanic_sessionDocumentationDocumentation is available atsanic-session.readthedocs.io.Also, make sure you readOWASP's Session Management Cheat Sheetfor some really useful info on session management.ExampleA simple example uses the in-memory session interface.fromsanicimportSanicfromsanic.responseimporttextfromsanic_sessionimportSession,InMemorySessionInterfaceapp=Sanic()session=Session(app,interface=InMemorySessionInterface())@app.route("/")asyncdefindex(request):# interact with the session like a normal dictifnotrequest.ctx.session.get('foo'):request.ctx.session['foo']=0request.ctx.session['foo']+=1returntext(request.ctx.session['foo'])if__name__=="__main__":app.run(host="0.0.0.0",port=8000)Examples of using redis and memcache backed sessions can be found in the documentation, underUsing the Interfaces.— ⭐️ —