Saravanan666/pypi-org huggingface dataset:
Package: sanic-aioorm
sanic-aioorm===============================version: 0.0.5author: hszemail: hsz1273327@gmail.comFeature----------------------* simple to use, just like using flask's extension* design to take the place of sanic-peeweeExample-------------------------------model.py.. code:: pythonfrom sanic_aioorm import AioOrm, AioModelfrom peewee import Proxy, CharFielddb = Proxy()@AioOrm.registclass User(AioModel):username = CharField()class Meta:database = dbapp.py.. code:: pythonfrom sanic import Sanicfrom sanic.response import jsonfrom sanic_aioorm import AioOrmfrom ex_model import User, dbapp = Sanic()AioOrm.SetConfig(app, defaultdb="mysql://root:hsz881224@localhost:3306/test")orm = AioOrm(app)orm.init_proxys(defaultdb=db)orm.create_tables(User=[{'username': "hsz"}, {'username': "jojo"}])@app.get("/")async def testget(request):try:users = await User.select()except Exception as e:return json({"error": str(e)})else:return json({"hello": [await u.to_dict() for u in users]})@app.post("/")async def testpost(request):try:users = await User.create(request.json)except Exception as e:return json({"error": str(e)})else:return json({"hello": [u.to_dict() for u in users]})if __name__ == "__main__":app.run(host="0.0.0.0", port=4500)Install--------------------------------- ``python -m pip install sanic-aioorm``Limitations-----------* only support mysql and pgsql
Package: sanic-amqp
Forked from and based onhttps://github.com/Relrin/sanic-amqp-extension(sanic-amqp-extension)
Extensions were forked and modified to keep the code updated with
the latest version of dependecnies and to add additional functionalitysanic-amqpAMQP support for Sanic frameworkFeaturesBased on theaioamqplibraryProvides an opportunity to implement workers that works in backgroundInstallationThis package should be installed using pip:pip install sanic-amqpExamplefromsanicimportSanic,responsefromsanic_amqpimportAmqpExtension,AmqpWorkerapp=Sanic(__name__)# Configuration for RabbitMQapp.config.update({"AMQP_USERNAME":"guest","AMQP_PASSWORD":"guest","AMQP_HOST":"localhost","AMQP_PORT":5672,"AMQP_VIRTUAL_HOST":"vhost","AMQP_USING_SSL":False,})AmqpExtension(app)# AMQP is available as `app.amqp` or `app.extensions['amqp']`classCustomWorker(AmqpWorker):asyncdefrun(self,*args,**kwargs):transport,protocol=awaitself.connect()# create a new connection# and do some stuff here ...# Register workers after initializing the extensionapp.amqp.register_worker(CustomWorker(app))@app.route("/")asyncdefhandle(request):transport,protocol=awaitrequest.app.amqp.connect()# create a new connection# do some stuff here ...# P.S. but don't forget to close the connection after usingreturnresponse.text("It's works!")LicenseThe sanic-amqp is published under BSD license. For more details readLICENSEfile.
Package: sanic-amqp-extension
AMQP support for Sanic frameworkFeaturesBased on theaioamqplibraryProvides an opportunity to implement workers that works in backgroundInstallationThis package should be installed using pip:pip install sanic-amqp-extensionExamplefromsanicimportSanic,responsefromsanic_amqp_extimportAmqpExtension,AmqpWorkerapp=Sanic(__name__)# Configuration for RabbitMQapp.config.update({"AMQP_USERNAME":"guest","AMQP_PASSWORD":"guest","AMQP_HOST":"localhost","AMQP_PORT":5672,"AMQP_VIRTUAL_HOST":"vhost","AMQP_USING_SSL":False,})AmqpExtension(app)# AMQP is available as `app.amqp` or `app.extensions['amqp']`classCustomWorker(AmqpWorker):asyncdefrun(self,*args,**kwargs):transport,protocol=awaitself.connect()# create a new connection# and do some stuff here ...# Register workers after initializing the extensionapp.amqp.register_worker(CustomWorker(app))@app.route("/")asyncdefhandle(request):transport,protocol=awaitrequest.app.amqp.connect()# create a new connection# do some stuff here ...# P.S. but don't forget to close the connection after usingreturnresponse.text("It's works!")LicenseThe sanic-amqp-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-amqp-xtension
AMQP support for Sanic frameworkFeaturesBased on theaioamqplibraryProvides an opportunity to implement workers that works in backgroundInstallationThis package should be installed using pip:pip install sanic-amqp-extensionExamplefromsanicimportSanic,responsefromsanic_amqp_extimportAmqpExtension,AmqpWorkerapp=Sanic(__name__)# Configuration for RabbitMQapp.config.update({"AMQP_USERNAME":"guest","AMQP_PASSWORD":"guest","AMQP_HOST":"localhost","AMQP_PORT":5672,"AMQP_VIRTUAL_HOST":"vhost","AMQP_USING_SSL":False,})AmqpExtension(app)# AMQP is available as `app.amqp` or `app.extensions['amqp']`classCustomWorker(AmqpWorker):asyncdefrun(self,*args,**kwargs):transport,protocol=awaitself.connect()# create a new connection# and do some stuff here ...# Register workers after initializing the extensionapp.amqp.register_worker(CustomWorker(app))@app.route("/")asyncdefhandle(request):transport,protocol=awaitrequest.app.amqp.connect()# create a new connection# do some stuff here ...# P.S. but don't forget to close the connection after usingreturnresponse.text("It's works!")LicenseThe sanic-amqp-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_apache_accesslogs
# Sanic Apache Access LogsSanic Plugin to log access logs in common or combined format## How to use```pythonfrom sanic import Sanicfrom sanic.response import jsonfrom sanic_apache_accesslogs import AccessLogPluginapp = Sanic(__name__, configure_logging=False)AccessLogPlugin(app)@app.route('/', methods=['GET'])async def hello(request):return json({'hello': 'world'})if __name__ == '__main__':app.run(host='localhost', port=5000, access_log=False)```## Common or Combined?For choosing the format set the environment variable `ACCESSLOG_USE_COMBINED` to choose combined over common.## TODO(s)* Use Sanic configuration context to choose between the logging format.## ContactArnulfo Solisarnulfojr94@gmail.com
Package: sanic-api
Sanic-API让您的sanic服务程序更好的支持API文档、参数校验、日志打印、响应规范等特性无需任何多余改动，全自动生成openapi文档，使用更加方便基于pydantic的参数校验器，让接口的请求及响应更符合你的预期使用loguru库代替官方logging日志库，并对访问日志进行扩展，支持打印接口耗时、接口参数使用{code: 0, data: null, msg: ""}样式的接口返回对接口中的异常进行拦截，及自定义错误码接口返回样式可自定义配置截图路线图增加一键生成预设项目cli命令编写详细文档API接口增加请求头、URL路径参数收集和校验:安装使用 pip 安装 sanic-apipipinstallsanic-api使用方法/示例fromsanicimportSanic,textfromsanic_apiimportinit_apiapp=Sanic("Sanic-API")@app.get('/')asyncdefindex(request):returntext("Sanic-API Example")defmain():init_api(app)app.run(access_log=True)if__name__=='__main__':main()开发要部署这个项目，请运行pipinstallpdmpdmsync文档文档
Package: sanicargs
SanicargsParses query parameters and json body parameters forSanicusing type annotations.SurveyPlease fill outthis surveyif you are using Sanicargs, we are gathering feedback :-)InstallInstall with pip$ pip install sanicargsUsageUse theparse_parametersdecorator to parse query parameters (GET) or body parameters (POST) and type cast them together with path params inSanic's routes or blueprints like in thisexamplebelow:importdatetimefromsanicimportSanic,responsefromsanicargsimportparse_parametersapp=Sanic("test_sanic_app")@app.route("/me/<id>/birthdate",methods=['GET'])@parse_parametersasyncdeftest_datetime(req,id:str,birthdate:datetime.datetime):returnresponse.json({'id':id,'birthdate':birthdate.isoformat()})if__name__=="__main__":app.run(host="0.0.0.0",port=8080,access_log=False,debug=False)Test it running with$curl'http://0.0.0.0:8080/me/123/birthdate?birthdate=2017-10-30'Query parametersstr:ex: ?message=hello worldint:ex: ?age=100bool:ex: ?missing=falsedatetime.datetime:ex: ?currentdate=2017-10-30T10:10:30 or 2017-10-30datetime.date:ex: ?birthdate=2017-10-30List[str]:ex: ?words=you,me,them,weJSON body parameters{
"message": "hello word",
"age": 100,
"missing": false,
"currentDate": "2017-10-30",
"currentDateTime": "2017-10-30T10:10:30",
"words": ["you", "me", "them", "we"]
}Note about datetimesDates and datetimes are parsed without timezone information giving you a "naive datetime" object. See the note ondatetime.timestamp()about handling timezones if you require epoch format timestamps.Important notice about decoratorsThe sequence of decorators is, as usual, important in Python.You need to apply theparse_parametersdecorator as the first one executed which means closest to thedef.requestis mandatory!You should always have request as the first argument in your function in order to useparse_parameters.Notethatrequestarg can be renamed and even type-annotated as long as it is the first arg.
Package: sanic-asyncjinja2
sanic-asyncjinja2Jinja2 in async mode with Sanic [experimental]It is based onsanic-jinja2.
It provides two decorators @template and @stream_template.
The main change is in using render_async and generate_async for the decorator functions.@stream_template is just and experimental way to make HTTP response via sanic.response.stream
It gives you ability to decrease time to the first byte on response and stream long response during the processing template with data.Example codeimportasynciofromsanicimportSanicfromsanic_asyncjinja2importSanicAsyncJinja2app=Sanic(__name__)jinja=SanicAsyncJinja2()jinja.init_app(app)@app.route('/',methods=["GET",])@jinja.template("hello.html")defindex(request):return{"name":"world"}@app.route('/slow_query',methods=["GET",])@jinja.template("hello.html")asyncdefslow_handler(request):asyncdeffunc1():awaitasyncio.sleep(2)return"name"asyncdeffunc2():awaitasyncio.sleep(2)return"world"asyncdefgfunc(k,v):key,value=awaitasyncio.gather(k,v)return{key:value}f1=func1()f2=func2()g=awaitgfunc(f1,f2)returng# this is just a stupid idea# to win the time to the first byte on response# on one of our production servers# it is helpful with big responses@app.route('/simplestream',methods=["GET",])@jinja.stream_template("hello.html")asyncdefhandler2(request):very_long_text="Very long response here..."return{"name":"world","text":very_long_text}
Package: sanic-base-extension
Flask-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-base-extensionExamplefromsanicimportSanicfromsanic_base_extimportBaseExtensionclassCustomExtension(BaseExtension):extension_name=app_attribute='custom'defhello(self,user):print("Hello,{}!".format(user))app=Sanic(__name__)CustomExtension(app)# available via `app.custom` or `app.extensions['custom']`app.ctx.custom.hello('world')# Hello, world!LicenseThe sanic-base-extension is published under BSD license. For more details readLICENSEfile.
Package: sanic-beskar
sanic-beskarStable branch:masterCBTE (coding by trial and error) branch:devWorking example(s):examples/*.pyStrong, Simple, and Precise security for Sanic APIsThis project’s begining was fully lifted from the awesomeFlask-Praetorian.Whybeskar? Why not – what
is better than star wars (provided you ignore the fact ~the mandolorian~
was almost as lame as ~book of boba fett~)?
Superior armour should be used if you want superior protection.This package aims to provide that. Using token implemented by eitherPySETOorPyJWT,sanic-beskaruses a very simple interface to make sure that the users
accessing your API’s endpoints are provisioned with the correct roles for
access.The goal of this project is to offer simplistic protection, without
forcing nonsense, excessivly complicatated implimentation, or
mandated/opinionated ORM usage. Providing this usability for small
scaled Sanic applications, while allowing the flexibility and
scalability for enterprise grade solutions, seperates this from your
other options.Thesanic-beskarpackage can be used to:Hash passwords for storing in your databaseVerify plaintext passwords against the hashed, stored versionsGenerate authorization tokens upon verification of passwordsCheck requests to secured endpoints for authorized tokensSupply expiration of tokens and mechanisms for refreshing themEnsure that the users associated with tokens have necessary roles for accessParse user information from request headers for use in client route handlersSupport inclusion of custom user claims in tokensRegister new users using email verificationSupport OTP authentication as a dual factorProvide RBAC based protection of endpoints and resourcesAll of this is provided in a very simple to configure and initialize flask
extension. Though simple, the security provided bysanic-beskaris strong
due to the usage of the proven security technology of PASETO or JWT, along with
python’sPassLibpackage.Super-quick Startrequirements:pythonversions 3.7+install through pip:$ pip install sanic-beskarminimal usage example:example/basic.pyDocumentationThe complete documentation can be found at thesanic-beskar home page
Package: sanic-brogz
sanic_brogz is an extension which allows you to easily brotli compress
or gzip your Sanic responses. It is a fork of thesanic_compresspackage
which is a port of theFlask-Compressextension.InstallationInstall withpip:pip install sanic_brogzUsageUsage is simple. Simply pass in the Sanic app object to theCompressclass, and responses will be brotli compressed or gzipped.fromsanicimportSanicfromsanic_brogzimportCompressapp=Sanic(__name__)Compress(app)OptionsWithin the Sanic application config you can provide the following
settings to control the behavior of sanic_brogz. None of the settings
are required.COMPRESS_MIMETYPES: Set the list of mimetypes to compress here. -
Default:{'text/html','text/css','text/xml','application/json','application/javascript'}COMPRESS_LEVEL: Specifies the gzip compression level (1-9) or brotli
compression level (1-11). - Default:6COMPRESS_MIN_SIZE: Specifies the minimum size (in bytes) threshold
for compressing responses. - Default:500A higherCOMPRESS_LEVELwill result in a gzipped response that is
smaller, but the compression will take longer.Example of using custom configuration:fromsanicimportSanicfromsanic_brogzimportCompressapp=Sanic(__name__)app.config['COMPRESS_MIMETYPES']={'text/html','application/json'}app.config['COMPRESS_LEVEL']=4app.config['COMPRESS_MIN_SIZE']=300Compress(app)Note about compressing static files:Sanic is not at heart a file server. You should consider serving static
files with nginx or on a separate file server.
Package: sanic-camelcase-middleware
Sanic Camelcase MiddlewareMiddleware for camelizing request and response bodies for sanicFull documentation can be foundhereHow to installpipinstallsanic-camelcase-middlwareExamplefromsanicimportSanicfromsanic_camelcase_middlewareimportCamelizeapp=Sanic(__name__)Camelize(app)Full examplefromsanicimportSanicfromsanic.responseimportjsonfromsanic_camelcase_middlewareimportCamelizeapp=Sanic(__name__)Camelize(app)@app.route("/post",methods=["POST"])asyncdeftest(request):returnjson("is_camelcase":True,"message":request.json})if__name__=="__main__":app.run(host="0.0.0.0",port=8000)To disable the middleware for request payloadfromsanicimportSanicfromsanic_camelcase_middlewareimportCamelizeapp=Sanic(__name__)# default `decamelize_request=True`Camelize(app,decamelize_request=False)To disable the middleware for response bodyfromsanicimportSanicfromsanic_camelcase_middlewareimportCamelizeapp=Sanic(__name__)# default `camelize_response=True`Camelize(app,camelize_response=False)
Package: sanic_compress
sanic_compress is an extension which allows you to easily gzip your
Sanic responses. It is a port of theFlask-Compressextension.InstallationInstall withpip:pip install sanic_compressUsageUsage is simple. Simply pass in the Sanic app object to theCompressclass, and responses will be gzipped.fromsanicimportSanicfromsanic_compressimportCompressapp=Sanic(__name__)Compress(app)Alternatively, if you want to initialize theCompressclass later,
you can do so with theinit_appmethod;compress=Compress()app=Flask(__name__)compress.init_app(app)OptionsWithin the Sanic application config you can provide the following
settings to control the behavior of sanic_compress. None of the
settings are required.COMPRESS_MIMETYPES: Set the list of mimetypes to compress here. -
Default:['text/html','text/css','text/xml','application/json','application/javascript']COMPRESS_LEVEL: Specifies the gzip compression level (1-9). -
Default:6COMPRESS_MIN_SIZE: Specifies the minimum size (in bytes) threshold
for compressing responses. - Default:500A higherCOMPRESS_LEVELwill result in a gzipped response that is
smaller, but the compression will take longer.Example of using custom configuration:fromsanicimportSanicfromsanic_compressimportCompressapp=Sanic(__name__)app.config['COMPRESS_MIMETYPES']=set(['text/html','application/json'])app.config['COMPRESS_LEVEL']=4app.config['COMPRESS_MIN_SIZE']=300Compress(app)Note about gzipping static files:Sanic is not at heart a file server. You should consider serving static
files with nginx or on a separate file server.
Package: sanic-conf
sanic-confDjango-like settings for SanicQuick StartInstallationpip install sanic-confCreatesettings.pyfilesanic
├─ app.py
└─ settings.pyFill out the project settings# settings.py

PROXIES_COUNT = 1
REAL_IP_HEADER = 'X-Real-IP'Apply to Sanic configimportosfromsanicimportSanicfromsanic_confimportsettingsapp=Sanic(__name__,load_env=False)# settingsos.environ.setdefault('SANIC_SETTINGS_MODULE','settings')app.config.update_config(settings)Environment variablesNote that you can usedjango-environwith Sanic.pip install django-environ# settings.py

import environ
env = environ.Env(
    DEBUG=(bool, False)
)

# reading .env file
environ.Env.read_env()

# False if not in os.environ
DEBUG = env('DEBUG')

PROXIES_COUNT = 1
REAL_IP_HEADER = 'X-Real-IP'
Package: sanic-crud
sanic_crud is a REST API framework for creating a CRUD (Create/Retrieve/Update/Delete) API usingSanicandPeeWeeYou can use sanic_crud to automatically create an API from your PeeWee models, see how it works in theDocumentationContributions to the repository are welcome!ExamplefrompeeweeimportCharField,DateTimeField,SqliteDatabase,ModelimportdatetimefromsanicimportSanicfromsanic_crudimportgenerate_cruddb=SqliteDatabase('my_app.db')classBaseModel(Model):classMeta:database=dbclassPerson(BaseModel):name=CharField()email=CharField()create_datetime=DateTimeField(default=datetime.datetime.now,null=True)db.create_tables([Person])app=Sanic(__name__)generate_crud(app,[Person])app.run(host="0.0.0.0",port=8000,debug=True)Installationpython -m pip install sanic-crudDocumentationDocumentation can be found in thedocsdirectory.TODOSee Issues
Package: sanic_csrf
### sanic_csrfWorks with all modern web-browsers, which support SameSite cookies.(Firefox 60, Google Chrome 51, Opera 39 and later)Checks request for CSRF token.If CSRF is absent or invalid:If it's a get request - installs new token in cookie and redirects to same page.In other cases - raises 403 exception (forbidden).Requires some session middleware to be installed.That session plugin must use such interface:```pythonrequest['session'].get('variable') or request['session']['variable']request['session']['variable'] = 4```For example, this ones will fit:- 'sanic_session' (https://github.com/subyraman/sanic_session);- 'sanic_session' (https://github.com/vlad1777d/sanic_session)(fork of previous, more convenient middleware installation,can be used without package installation);## ExampleA simple example:```pythonfrom sanic import Sanicfrom sanic.response import textimport sanic_sessionimport sanic_csrfapp = Sanic()sanic_session.install_middleware(app, 'InMemorySessionInterface')sanic_csrf.install_middleware(app)@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(request['session']['foo'])if __name__ == "__main__":app.run(host="0.0.0.0", port=8000, debug=True)```
Package: sanic-dantic
sanic-danticsanic-dantic is a request parameter checking and parsing library based on
pydantic under the sanic frameworksanic-dantic is a request parameter checking and parsing library based on
pydantic under the sanic frameworkIt is based on pydantic, which can facilitate developers to quickly check and
obtain request parametersDocumentationIf you want more usage, please
clickhereInstallationpipinstallsanic-danticWhy use itDo you have to get the request parameters first every time you process them ?fromsanicimportSanicfromsanic.responseimportjsonapp=Sanic("SanicDanticExample")@app.route('/example')asyncdefpath_param_examples(request):name=request.get("name")age=request.get("age")ifnotisinstance(name,str)ornotisinstance(age,int):returnjson({"error":"parameter type error"})returnjson({"message":f"hello{name}are you{age}years old ?"})How terrible, and there is no good experience for developers at all.Therefore, sanic-dantic is to help you improve your development efficiency and
experience.It allows you to skip the process of type checking and parameter acquisition.How to useIt is based on pydantic, which can facilitate developers to quickly check and
obtain request parametersIn sanic-dantic, you can pass the pydantic model to different formal parameters
in parse_params to check and parse the values of different types of request
parametersYou can get all the parsed parameters by appending the formal parameter , and
get the value of the parameter through the attributeparamsfromsanicimportSanicfromsanic.responseimportjsonfromsanic_danticimportparse_params,BaseModelclassPerson(BaseModel):name:strage:intapp=Sanic("SanicDanticExample")@app.route('/example')@parse_params(path=Person)asyncdefpath_param_examples(request,params):print(params.ctx.name,params.ctx.age)returnjson({"message":f"hello{params.name}are you{params.age}years old ?"})Do you have a crush? Come and experience it!more usage please read
thedocumentation
Package: sanicdb
Home-page:https://github.com/veelion/sanicdbAuthor: veelion
Author-email:veelion@gmail.comLicense: BSD
Description: UNKNOWN
Platform: UNKNOWN
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Developers
Classifier: License :: BSD
Classifier: Programming Language :: Python :: 3.5
Classifier: Programming Language :: Python :: 3.6
Classifier: Programming Language :: Python :: 3.7
Package: sanic-devtools
BuildPackageDev tools for Sanic.This tool is highly inspired byaiohttp-devtools,aio-libs.Installationpipinstallsanic-devtoolsQuick Start⋊>~sdev--helpUsage:sdev[OPTIONS]COMMAND[ARGS]...Options:-V,--versionShowtheversionandexit.--helpShowthismessageandexit.Commands:newCreatesanewsanicprojectwithbatteriesincluded.runserverRunadevelopmentserverforanSanicapp.Usagesanic-devtoolsprovides several commands to help you develop Sanic Application easily.runserverProvides a simple local server for running your application while you’re developing, it helps you live reload your Sanic
application automatically while developing and having any code change.sdevrunserver<app-path>app-pathcan be a path to either a directory containing a recognized default file (app.py or main.py) or to a specific file.
The--app-factoryoption can be used to define which method is called from the app path file,
if not supplied some default method names are tried (app/app_factory/get_app/create_app).All runserver arguments can be set via environment variables.For more details, try:sdevrunserver--helpnewCreates a new sanic project with batteries included in seconds.sdevnew--output-dir<project-output-path>By default,sdevusescookiecutter-sanicas default template under the hood.
You may override it by passing--template-srcoption.For more details, try:sdevnew--helpAlso feel free to add any tool/command that helps developingSanicapplication smoothly, just create a PR/issue and let us know !Contributingsanic-devtoolsaccepts contributions on GitHub, in the form of issues or pull requests.Run unit tests.tox-epy36or./uraniumtestTest command locally../uranium./bin/sdevrunserver./example/app.py