Saravanan666/pypi-org huggingface dataset:
Package: sanic_session_2
### sanic_sessionsanic_session is an extension for sanic that integrates server-backed sessions with a Flask-like API.sanic_session provides a number of *session interfaces* for you to store a client's session data. The interfaces available right now are:* Redis (using aioredis, asyncio_redis)* Memcache (using aiomemcache)* MongoDB (using sanic_motor)* In-Memory (suitable for testing and development environments)Forked from: https://github.com/subyraman/sanic_sessionAdded more easy installation, fixed code a little bit.## InstallationInstall with `pip`:`pip install sanic_session`## ExamplesA simple example uses the in-memory session interface.```pythonfrom sanic import Sanicfrom sanic.response import textimport sanic_sessionapp = Sanic()sanic_session.install_middleware(app, 'InMemorySessionInterface')@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)```Using sanic_session with Redis via asyncio_redis.Install sanic_session to use with asyncio_redis driver: `pip install sanic_session[asyncio_redis]````pythonimport asyncio_redisfrom sanic import Sanicfrom sanic.response import textimport sanic_sessionapp = Sanic()# general (for all app) redis pool# (should be filled asynchronously after server start)asyncio_redis_pool = None@app.listener ('before_server_start')async def general_before_server_start (app, loop):global asyncio_redis_poolasyncio_redis_pool = await asyncio_redis.Pool.create(host='127.0.0.1', port=6379, poolsize=2)sanic_session.install_middleware (app, 'AsyncioRedisSessionInterface', asyncio_redis_pool)@app.listener ('after_server_stop')async def general_after_server_stop (app, loop):asyncio_redis_pool.close ()@app.route("/")async def test(request):# interact with the session like a normal dictif not request['session'].get('foo'):request['session']['foo'] = 0request['session']['foo'] += 1response = text(request['session']['foo'])return responseif __name__ == "__main__":app.run(host="0.0.0.0", port=8000, debug=True)```Using sanic_session with Memcache via aiomemcache.Install sanic_session to use with aiomemcache driver: `pip install sanic_session[aiomcache]````pythonimport aiomcacheimport uvloopfrom sanic import Sanicfrom sanic.response import textimport sanic_sessionapp = Sanic()# create a uvloop to pass into the memcache client and sanicloop = uvloop.new_event_loop()# create a memcache clientclient = aiomcache.Client("127.0.0.1", 11211, loop=loop)# install sanic_session middleware with memcache clientsanic_session.install_middleware (app, 'MemcacheSessionInterface', client)@app.route("/")async def test(request):# interact with the session like a normal dictif not request['session'].get('foo'):request['session']['foo'] = 0request['session']['foo'] += 1response = text(request['session']['foo'])return responseif __name__ == "__main__":app.run(host="0.0.0.0", port=8000, debug=True, loop=loop)```
Package: sanic-simple-restful
Gotta simplify your REST APIs creation!Sanic's built-inHTTPMethodViewis a useful thing, but sometimes one wants more sugar.Whay not?Usage exampleimportloggingfromsanicimportSanicfromsanic_restfulimportApi,ApiEndpointlogger=logging.getLogger(__name__)app=Sanic()@app.middleware('response')asyncdefcors_headers(request,response):"""Add CORS headers to all responses, including errors."""response.headers['Access-Control-Allow-Origin']=request.headers.get('Origin','*')response.headers['Access-Control-Allow-Credentials']='true'response.headers['Access-Control-Allow-Methods']='POST, PUT, PATCH, DELETE, OPTIONS, GET'response.headers['Access-Control-Allow-Headers']="X-Requested-With,X-Prototype-Version,"\"Content-Type,Cache-Control,Pragma,Origin,Cookie"response.headers['Access-Control-Max-Age']='3600'classTodoResource(ApiEndpoint):# method_decorators = [auth.auth_required]endpoint='todos/<todo_id>'asyncdefget(self,request,todo_id):return{'id':todo_id}asyncdefpost(self,request,todo_id):return{'id':todo_id},201api=Api(app,[TodoResource],'/v0.9/')if__name__=="__main__":app.run(host="0.0.0.0",port=8000,debug=True)And let's try it:$httpPOSThttp://localhost:8000/v0.9/todos/1
HTTP/1.1201Created
Access-Control-Allow-Credentials:trueAccess-Control-Allow-Headers:X-Requested-With,X-Prototype-Version,Content-Type,Cache-Control,Pragma,Origin,Cookie
Access-Control-Allow-Methods:POST,PUT,PATCH,DELETE,OPTIONS,GET
Access-Control-Allow-Origin:*
Access-Control-Max-Age:3600Connection:keep-alive
Content-Length:10Content-Type:application/json
Keep-Alive:5{"id":"1"}
Package: sanic-simple-swagger
# Sanic OpenAPIReal project in [https://github.com/huge-success/sanic-openapi](https://github.com/huge-success/sanic-openapi/blob/master/README.md)This project just extends functional and fix some bugs
![Example Swagger UI](https://raw.githubusercontent.com/huge-success/sanic-openapi/master/images/code-to-ui.png“Swagger UI”)#[Git Documentation](https://github.com/FerdinaKusumah/sanic_simple_swagger)## Installation`shell pip installsanic-simple-swagger`#### Add OpenAPI and Swagger UI:`python from sanic_simple_swagger import swagger_blueprint, openapi_blueprint app.blueprint(openapi_blueprint) app.blueprint(swagger_blueprint) `You’ll now have a Swagger UI at the URL/swagger/index.html.Your routes will be automatically categorized by their blueprints.### Configure all the things`pythonapp.config['API_VERSION']= '1.0.0'app.config['API_TITLE']= 'Swagger Petstore'app.config['API_DESCRIPTION']= 'This is a sample server Petstore server. You can find out more about Swagger at[http://swagger.io](http://swagger.io)or on [irc.freenode.net,#swagger](http://swagger.io/irc/).For this sample, you can use the api key`special-key`to test the authorization filters.'app.config['API_TERMS_OF_SERVICE']='http://swagger.io/terms/'app.config['API_CONTACT_EMAIL']='http://swagger.io/terms/'app.config['API_LICENSE_NAME']= 'Apache 2.0'app.config['API_LICENSE_URL']='http://www.apache.org/licenses/LICENSE-2.0.html'app.config['schemes']= ['http', 'https'] `## Reference
1. [Sanic](https://github.com/huge-success/sanic)
2. [Sanic OpenAPI](https://github.com/huge-success/sanic-openapi)
Package: sanic-skywalking-middleware
Sanic SkywalkingThis package help you integrate Skywalking APM in Sanic applications easily through Skywalking Python Agent.If you'd like to explore more about Apache Skywalking and Python agent, you can visitApache Skywalking GithubApache Skywalking Python AgentInstallationRun the following command:$pipinstallsanic-skywalking-middlewareUsageSimple initilize a SanicSkywalingMiddleware with a Sanic instance and Skywalking collector address.fromsanic_skywalking_middlewareimportSanicSkywalingMiddlewareSanicSkywalingMiddleware(app,service='Sanic Skywalking Demo Service',collector='127.0.0.1:11800')ExamplesSeeExamplesto view and run an example of Sanic applications with Skywalking integrated.
Package: sanic-sockjs
sanic_sockjsis aSockJSintegration forSanic.  SockJS interface
is implemented as aSanicroute. Its possible to create any number
of different sockjs routes, ie/sockjs/*or/mycustom-sockjs/*. You can provide different session implementation
and management for each sockjs route.Simple Sanic web server is required:[server:main]
use = egg:gunicorn#main
host = 0.0.0.0
port = 8080
worker = sanic.worker.GunicornWorkerExample of sockjs route:def main(global_settings, **settings):
    app = Sanic(__main__)
    @app.get('/')
    def index(request):
        ...


    sanic_sockjs.add_endpoint(app, prefix='/sockjs', handler=chatSession)
    app.run("127.0.0.1", 8080)Client side code:<script src="//cdn.jsdelivr.net/npm/sockjs-client@1/dist/sockjs.js"></script>
<script>
    var sock = new SockJS('http://localhost:8080/sockjs');

    sock.onopen = function() {
      console.log('open');
    };

    sock.onmessage = function(obj) {
      console.log(obj);
    };

    sock.onclose = function() {
      console.log('close');
    };
</script>Supported transportswebsockethybi-10xhr-streamingxhr-pollingiframe-xhr-pollingiframe-eventsource (EventSourceused from aniframe via
postMessage)iframe-htmlfile (HtmlFileused from aniframe via postMessage.jsonp-pollingRequirementsPython >= 3.6Sanic >= 19.3.1https://github.com/huge-success/sanicExamplesYou can find severalexamplesin the sanic_sockjs repository at github.https://github.com/ashleysommer/sanic-sockjs/tree/master/examplesLicensesockjs is offered under the Apache 2 license.CHANGES0.1.0 (2020-04-08)Initial releasePorted from aiohttp/SockJSWorks on all Sanic 19.3.1-to-19.12.2
Package: sanic-sse
Sanic Server-Sent Events extensionA Sanic extension for HTML5server-sent eventssupport, inspired byflask-sseandaiohttp-sse.InstallInstallation process as simple as:$pipinstallsanic_sseExampleServer example:fromhttpimportHTTPStatusfromsanicimportSanicfromsanic.responseimportjson,json_dumpsfromsanic.exceptionsimportabortfromsanic_sseimportSse# This function is optional callback before sse request# You can use it for authorization purpose or something elseasyncdefbefore_sse_request(request):ifrequest.headers.get("Auth","")!="some_token":abort(HTTPStatus.UNAUTHORIZED,"Bad auth token")sanic_app=Sanic()# The default sse url is /sse but you can set it via init argument url.Sse(sanic_app,url="/events",before_request_func=before_sse_request)# or you can use init_app method@sanic_app.route("/send",methods=["POST"])asyncdefsend_event(request):# if channel_id is None than event will be send to all subscriberschannel_id=request.json.get("channel_id")# optional arguments: event_id - str, event - str, retry - int# data should always be strtry:awaitrequest.app.sse_send(json_dumps(request.json),channel_id=channel_id)exceptKeyError:abort(HTTPStatus.NOT_FOUND,"channel not found")returnjson({"status":"ok"})if__name__=="__main__":sanic_app.run(host="0.0.0.0",port=8000)Client example (powered bysseclient-pyandrequests):importjsonimportpprintimportrequestsimportsseclienturl="http://127.0.0.1:8000/events"# you may set channel_id parameter to receive special events# url = "http://127.0.0.1:8000/events?channel_id=foo"response=requests.get(url,stream=True)client=sseclient.SSEClient(response)foreventinclient.events():print(event.id)print(event.event)print(event.retry)pprint.pprint(json.loads(event.data))Requirementspython3.5+sanic0.7.0+
Package: sanic-sse-py3
sanic_sse
########安装
==========.. code-block:: shellpip install sanic-sse-py3示例
==========2.1 代码.. code-block:: pythonimport os
import sys
from sanic import Sanic
from sanic.response import html

sys.path.insert(0, os.path.join(os.path.dirname(__file__), os.pardir, os.pardir))

from sse.api.urls import sse_bgp
from sse import SseApp

app = Sanic(name="sse")

SSE_CONFIG = {
    "pubsub_options": {
        "redis_host": os.getenv("SSE_REDIS_HOST", "127.0.0.1"),
        "redis_port": int(os.getenv("SSE_REDIS_PORT", "16379")),
        "redis_passwd": os.getenv("SSE_REDIS_PASSWD", ""),
    },
    "ping_interval": int(os.getenv("SSE_PING_INTERVAL", 10)),

}


def init_app(_app):
    _app.ctx.sse_config = SSE_CONFIG
    SseApp(_app)
    _app.blueprint(sse_bgp)


@app.route("/index", methods=["GET"])
async def index(request):
    event = request.args.get("event", "test")
    url = f"sse/event/listen?event={event}"
    d = """
        <html>
        <body>
          <script>
                var source = new EventSource("%s");
                source.onmessage = function(e) {
                    console.log("xxxxxxx");
                    document.getElementById('response').innerHTML + e.data + "<br>";
                }
          </script>
          <h1>Getting server updates</h1>
          <div id="response"></div>
        </body>
    </html>
    """ % url
    return html(body=d)


if __name__ == "__main__":
    init_app(app)
    app.run(host="0.0.0.0", port=8008, workers=10)2.2 接口.. code-block:: shellGET /sse/event/send?event=test
GET /sse/event/listen?event=test&client_id=
GET /sse/event/terminate?event=test&client_id=
Package: sanic-swagger
sanic-swaggerAnnotate yourSanicendpoints, and
automatically generate aSwagger/OpenAPIcompatible JSON spec file.This project is a fork of bothsanic-openapiandsanic-attrs.As such, you can write all of your models asattrswhich gives you the handy
ability to usecattrsfor dealing with your
serialization and deserialization of your models to and from JSON.
Package: sanic-swagger-ui
Sanic Swagger UISimple Sanic blueprint for addingSwagger UIto your sanic application.Inspired byflask-swagger-ui.InstallationYou can install it usingpip.pipinstallsanic_swagger_uiUsagefromsanicimportSanicfromsanicimportresponsefromsanic_swagger_uiimportget_swaggerui_blueprintapp=Sanic(__name__)STATIC_URL='/static'app.static(STATIC_URL,'./static')# set static dir pathSWAGGER_URL='/swagger'DOCS_PATH=STATIC_URL+'/swagger/index.yaml'# serves files from the static dirswaggerui_blueprint=get_swaggerui_blueprint(DOCS_PATH,SWAGGER_URL,app_name='Swagger BP Test')app.blueprint(swaggerui_blueprint)@app.route('/')asyncdefindex(req):returnresponse.html(('Hello World from Sanic''<br>''Click <a href="/swagger/docs">here</a> to view swagger docs'),status=200)if__name__=='__main__':app.run(debug=True)You can find this example inexamplesdirectory in this repository.Please add an issue if you want something added here or if you find a bug.
Package: sanic-synchro-ctx
Sanic-Synchro-CtxPlugin to provide an App context that is shared across multiple workersCan use native python SyncManager backend, or Redis if you want. (Redis is much faster).Installation$pip3installsanic-synchro-ctxOr in a python virtualenv(these example commandline instructions are for a Linux/Unix based OS)$python3-mvirtualenv--python=python3--no-site-packages.venv
$source./.venv/bin/activate
$pip3installsanicsanic-synchro-ctxTo exit the virtual enviornment:$deactivateRedis ExtensionYou can install the relevant Redis libraries for this plugin, with the installable redis extension:$pip3installsanic-synchro-ctx[redis]That is the same as running:$pip3install"sanic-synchro-ctx""aioredis>=2.0""hiredis>=1.0"CompatibilityWorks with Python 3.8 and greater.Works with Sanic v21.9.0 and greater.If you are installing the redis library separately, use aioredis >= 2.0UsageA very simple example, it uses the native python SyncManager backend, doesn't require a Redis connection.fromsanic_synchro_ctximportSanicSynchroCtxapp=Sanic("sample")s=SanicSynchroCtx(app)@app.after_server_startdefhandler(app,loop=None):# This will only set this value if it doesn't already exist# So only the first worker will set this valueapp.ctx.synchro.set_default({"counter":0})@app.route("/inc")defincrement(request:Request):# atomic increment operationcounter=request.app.ctx.synchro.increment("counter")print("counter:{}".format(counter),flush=True)returnhtml("<p>Incremented!</p>")@app.route("/count")defincrement(request:Request):# Get from shared context:counter=request.app.ctx.synchro.counterprint("counter:{}".format(counter),flush=True)returnhtml(f"<p>count:{counter}</p>")app.run("127.0.0.1",port=8000,workers=8)Redis example:fromsanic_synchro_ctximportSanicSynchroCtxredis=aioredis.from_url("redis://localhost")app=Sanic("sample")s=SanicSynchroCtx(app,backend="redis",redis_client=redis)@app.after_server_startasyncdefhandler(app,loop=None):# This will only set this value if it doesn't already exist# So only the first worker will set this valueawaitapp.ctx.synchro.set_default({"counter":0})@app.route("/inc")asyncdefincrement(request:Request):# atomic increment operationcounter=awaitrequest.app.ctx.synchro.increment("counter")print(f"counter:{counter}",flush=True)returnhtml("<p>Incremented!</p>")@app.route("/count")asyncdefincrement(request:Request):# Get from shared context:counter=awaitrequest.app.ctx.synchro.counterprint(f"counter:{counter}",flush=True)returnhtml(f"<p>count:{counter}</p>")app.run("127.0.0.1",port=8000,workers=8)ChangelogA comprehensive changelog is kept in theCHANGELOG file.BenchmarksI've done some basic benchmarks. SyncManager works surprisingly well, but Redis backend is much faster.LicenseThis repository is licensed under the MIT License. See theLICENSE deedfor details.
Package: sanic-testing
Sanic Core TestThis package is meant to be the core testing utility and clients for testing Sanic applications. It is mainly derived fromsanic.testingwhich has (or will be) removed from the main Sanic repository in the future.DocumentationGetting Startedpip install sanic-testingThe package is meant to create an almost seemless transition. Therefore, after loading the package, it will attach itself to your Sanic instance and insert test clients.fromsanicimportSanicfromsanic_testingimportTestManagersanic_app=Sanic(__name__)TestManager(sanic_app)This will provide access to both the sync (sanic.test_client) and async (sanic.asgi_client) clients. Both of these clients are also available directly on theTestManagerinstance.Writing a sync testTesting should be pretty much the same as when the test client was inside Sanic core. The difference is just that you need to runTestManager.importpytest@pytest.fixturedefapp():sanic_app=Sanic(__name__)TestManager(sanic_app)@sanic_app.get("/")defbasic(request):returnresponse.text("foo")returnsanic_appdeftest_basic_test_client(app):request,response=app.test_client.get("/")assertresponse.body==b"foo"assertresponse.status==200Writing an async testTesting of an async method is best done withpytest-asyncioinstalled. Again, the following test should look familiar to anyone that has usedasgi_clientin the Sanic core package before.The main benefit of using theasgi_clientis that it is able to reach inside your application, and execute your handlers without ever having to stand up a server or make a network call.importpytest@pytest.fixturedefapp():sanic_app=Sanic(__name__)TestManager(sanic_app)@sanic_app.get("/")defbasic(request):returnresponse.text("foo")returnsanic_app@pytest.mark.asyncioasyncdeftest_basic_asgi_client(app):request,response=awaitapp.asgi_client.get("/")assertresponse.body==b"foo"assertresponse.status==200
Package: sanic-to-json
sanic-to-jsonGenerate a PostmanJSONfile from aSanic app. The JSON file can directly uploaded into thePostman clientor through theirAPI.Using the postmanschemawe can build Postman Collections using python endpoints from Sanic (Flask apps need testing). The script parses the Sanic app. It searches for blueprints. The blueprints, through routes, provide docs strings data. The doc string data is used to populate a Postman formatted JSON file. The JSON file can then be uploaded to Postman as a collection.Once we have Postman formatted JSON we can create API documentation through the PostmanAPIHow to useto execute an example runpython -m examples.example_scriptwhich executesfromsanic_to_jsonimportgenerate_sanic_jsonfromexamples.appimportappgenerate_sanic_json("Test API",app,filename="postman_collection.json")The above code formats the Postman collection with 'Test API' and doc strings from Sanic app,app, and yieldspostman_collection.jsonTo addbodyandheaderelements to Postman JSONPlacingINIin doc string will cause the text below to be loaded into a python config object, which then get converted to the appropiate headers and JSON body in Posttman.For example, as found inendpoint-threeINI
    [request]
    headers = {"Content-Type": "application/json"}
    body = {"username": "{{username}}", "password": "{{password}}"}To add query parametersSimilar to above placing sections under INI that are prefixed will start a example request.
For example, as found inendpoint-one"""Return text from request.
       
    INI
    [request]
    headers = {"Content-Type": "application/json","x-amz-sns-message-type": "Notification"}
    query = ?day=1&temp=F
    """How to document Sanic app and BlueprintsAs the example shows, the Sanic app should have a.docattribute. This doc string will serve as the introduction to the API in Postman docs, e.g.,app.__doc__ = "This API does stuff."Blueprints should also include a doc string, this will serve as the description to each collection folder in Postman. Again seeexamplesfolderbp1.__doc__ = "This is the doc string for blueprint1."Note: You can't send a JSON body with GET method.How to installpip install sanic-to-jsonContributorsSee theGitHub contributor pageLicensesanic-to-json is open source softwarelicensed as MIT.
Package: sanic-token-auth
Token-based authentication is the most common way of protecting your APIs from unwanted folk.Sometimes you need to do thingsfast(you know, get it to prodyesterday)
and you do not really have time to implement a proper authentication layer.Okay, are you fine with a temporary solution? There’s nothing more permanent than temporary, right.If you can:provide a simple async token verifier (say, checking it in memcached or Redis)orhard-code a token in your app prototype,and alsosent the token in a request headerthen we are ready to go.Usage examplefromsanicimportSanicfromsanic.responseimporttextfromsanic_token_authimportSanicTokenAuthapp=Sanic()auth=SanicTokenAuth(app,secret_key='utee3Quaaxohh1Oo',header='X-My-App-Auth-Token')@app.route("/")asyncdefindex(request):returntext("Go to /protected")@app.route("/protected")@auth.auth_requiredasyncdefprotected(request):returntext("Welcome!")if__name__=="__main__":app.run(host="0.0.0.0",port=8000,debug=True)And let’s try it:$curlhttp://localhost:8000/protected-H"X-My-App-Auth-Token: utee3Quaaxohh1Oo"Welcome!If you omit theheaderargument, you can instead send a token in eitherAuthorization: Bearer <yourtoken>orAuthorization: Token <yourtoken>header.TODO:[ ] Documenttoken_verifierand implement examples of using of[ ] Implement “protect all” behaviour
Package: sanic-utils
sanic-utilsA suite of useful Sanic utilitiesfrom_jsonA decorator for Sanic endpoints to grab the json from the request and pass it in as a parameter.
Default Sanic approach:fromsanicimportSanic,responsefromsanic.requestimportRequestapp=Sanic("App Name")classExampleInput:name:stridentifier:str@app.post("/test")asyncdeftest(request:Request):json=request.jsonmessage=None# convert json to object in whatever prefered wayreturnresponse.text("done")if__name__=="__main__":app.run(host="0.0.0.0",port=8112)Usage of the decorator:fromdataclassesimportdataclassfromdataclasses_jsonimportdataclass_jsonfromsanicimportSanic,responsefromsanic.requestimportRequestfromsanic_utils.from_jsonimportfrom_jsonapp=Sanic("App Name")@dataclass_json@dataclassclassExampleInput:name:stridentifier:str@app.post("/test")@from_json(message_type=ExampleInput)asyncdeftest(request:Request,message:ExampleInput):print(message)returnresponse.text("done")if__name__=="__main__":app.run(host="0.0.0.0",port=8112)UsageMark endpoint method with @from_json decorator passing in a single param, the resulting message type.
The message type should be marked with @dataclass_json and @dataclass.Dependenciessanic 20.6.3dataclasses 0.6dataclasses-json 0.5.1CONTRIBUTINGLICENSE
Package: sanic-validation
sanic-validationsanic-validation is an extension to sanic that simplifies validating request data.Installationpip install sanic-validationDocumentationDocumentation is available atReadTheDocs.Usage examplefrom sanic import Sanic
from sanic.response import json
from sanic_validation import validate_args

app = Sanic('demo-app')

schema = {'name': {'type': 'string', 'required': True}}


@app.route('/')
@validate_args(schema)
async def hello(request):
    return json({'message': 'Hello ' + request.args['name']})

app.run('0.0.0.0')Building the documentationRequirementsPythonSphinxmakeBuildingpython setup.py install
cd docs
make html