Saravanan666/pypi-org huggingface dataset:
Package: tornado-httpclient-session
A mimic inspired by the session feature inRequests,
it adds support toTornadothat allows you to persist
context such as cookies and other parameters across requests’ fetching fromtornado.httpclient.THIS IS SESSION ABOUT CLIENT, NOT SERVER!Installationpip install tornado-httpclient-sessionUsagefromtornado.httpclientimportHTTPClientfromhttpclient_sessionimportSessions=Session(HTTPClient)# AsyncHTTPClient defaultr=s.fetch('https://github.com')print(r.headers['set-cookie'])# Inspect cookies returnd from Githubr=s.fetch('https://github.com')# Fetching carrys cookiesprint(r.request.headers['cookie'])# Inspect cookies attachedTestingpython setup.py testOr for all supported environments:toxDevelopment ProgressPersistences of:Cookies ✔Referrer ✘Authorization ✘Any Suggestions Welcome!
Package: tornado-http-firewall
tornado-http-firewallAn HTTP proxy that utilizes ACLs to control access to URIs.NOTE: Consider this software alpha and extremely buggy and insecure.  You
probably shouldn't use this unless you're desparate for something like me. Pull
requests are welcome and encouraged.Requires Python>=3.6Usageusage: thfirewall [-h] [-a ADDRESS] [-p PORT] [-t TARGET] [-c CONFIG] [-d]

An HTTP proxy that utilizes ACLs to control access to URIs

optional arguments:
  -h, --help            show this help message and exit
  -a ADDRESS, --address ADDRESS
                        Port number to listen on
  -p PORT, --port PORT  Port number to listen on
  -t TARGET, --target TARGET
                        The target top level URL to forward requests
  -c CONFIG, --config CONFIG
                        The ACL config YAML file
  -d, --debug           Show debug messagesACL Config FormatHere's an example ACL file.  This is a whitelist.  All URLs are evaluated
from each path part at a time until one matches.  So if someone requests/api/v0/get/QmASFD..., it will first see if/apiis allowed, then/api/v0, etc...publicis the only named role.  Every other one should be by IP address.---
roles:
  public:
    - /api/v0/get
    - /api/v0/pin/ls
  127.0.0.1:
    - /api/v0/ping
Package: tornado-image-streamer
tornado-image-streamerAn image streamer over the Internet. A tornado backend is used to configure
a JPEG image streamer using either server "push" mode, or client "get" mode.
All communication is streamed using HTML5 websockets for maximum throughput.Technolgies usedClient side:jquerywebsocketsHTML5Server side:Python3 (Python2 is not supported)Tornado (WebSocketHandler)PILnumpyopencvBasic InstallationActivate a Python virtual environment and execute the following command,pipinstall-Utornado-image-streamerTest the application,tornado_image_streamer--simulateLinux Developer InstallationInstall a virtual environment,mkdir~/venvcd~/venv
python3-mvirtualenv--python=/usr/bin/python3tis_envsourcetis_env/bin/activateActivate the virtual environment,source~/venv/tis_env/bin/activateInstall this package,pipinstall-U-egit+https://gitlab.com/hsmit/tornado-image-streamer.git#egg=tornado_image_streamerTest the application,pythontest2/src/tornado-image-streamer/tornado_image_streamer/run.py-sUser installationIn your current python3 environment execute the following,pipinstall-Ugit+https://gitlab.com/hsmit/tornado-image-streamer.git#egg=tornado_image_streamerTest the application,tornado_image_streamer--helpUsage$tornado_image_streamer--help
Usage:tornado_image_streamer[OPTIONS]Tornadowebserverthatstreamswebcamimagesoverthenetwork.

Options:-p,--portINTEGERIPportusedforthewebserver(default:8888)-s,--simulateEnablesimulatedcamera.-m,--mode[get|push]Themodeofoperation(default:push).--helpShowthismessageandexit.
Package: tornadoist
tornadoist-currently- provides Mixins to execute code outsidetornado.ioloop.IOLoopto avoid blocking. These are:CeleryMixin: Celery TasksProcessMixin: Functions in separate processBoth support results, avoids polling or timeouts. More info below.Demo app included. (Celery withmongodb://preconfigured in demo app)CeleryMixinCeleryMixinis a Mixin class to use withtornado.web.RequestHandlerthat provides a Tornado-like interface to running Celery tasks on TornadoServer.HowTOUsingtornado.genfrom tornado import web, gen
from tornadoist import CeleryMixin

class CeleryHandler(tornado.web.RequestHandler, CeleryMixin):
    @web.asynchronous
    @gen.engine
    def get(self):
        result = yield gen.Task(self.add_task, some_task, 'somearg')
        self.write('Hello %s World!' % result)
        self.finish()Or using explicit callbackclass CeleryHandler(tornado.web.RequestHandler, CeleryMixin):
    @tornado.web.asynchronous
    def get(self):
        self.add_task(some_task, callback=self._on_result)

    def _on_result(self, result):
        do_something_with_result(result)
        self.finish()ProcessMixinProcessMixinis a Mixin class to use withtornado.web.RequestHandlerthat provides a Tornado-like interface to running functions withmultiprocessing.Processoutside IOLoop.HowTOUsingtornado.genfrom tornado import web, gen
from tornadoist import ProcessMixin

class ProcessHandler(tornado.web.RequestHandler, ProcessMixin):
    @tornado.web.asynchronous
    @tornado.gen.engine
    def get(self):
        result = yield tornado.gen.Task(self.add_task, my_blocking_function,
                                        'somearg', some_kwarg=42)
        self.write('Hello Process World! %s' % result)
        self.finish()LicenseApache License, Version 2.0
Package: tornadoist2
pip install tornadoist2tornadoist-currently- provides Mixins to execute code outsidetornado.ioloop.IOLoopto avoid blocking. These are:CeleryMixin: Celery TasksProcessMixin: Functions in separate processBoth support results, avoids polling or timeouts. More info below.Demo app included. (Celery withmongodb://preconfigured in demo app)CeleryMixinCeleryMixinis a Mixin class to use withtornado.web.RequestHandlerthat provides a Tornado-like interface to running Celery tasks on TornadoServer.HowTOUsingtornado.genfrom tornado import web, gen
from tornadoist2 import CeleryMixin

class CeleryHandler(tornado.web.RequestHandler, CeleryMixin):
    @web.asynchronous
    @gen.engine
    def get(self):
        result = yield gen.Task(self.add_task, some_task, 'somearg')
        self.write('Hello %s World!' % result)
        self.finish()Or using explicit callbackclass CeleryHandler(tornado.web.RequestHandler, CeleryMixin):
    @tornado.web.asynchronous
    def get(self):
        self.add_task(some_task, callback=self._on_result)

    def _on_result(self, result):
        do_something_with_result(result)
        self.finish()ProcessMixinProcessMixinis a Mixin class to use withtornado.web.RequestHandlerthat provides a Tornado-like interface to running functions withmultiprocessing.Processoutside IOLoop.HowTOUsingtornado.genfrom tornado import web, gen
from tornadoist import ProcessMixin

class ProcessHandler(tornado.web.RequestHandler, ProcessMixin):
    @tornado.web.asynchronous
    @tornado.gen.engine
    def get(self):
        result = yield tornado.gen.Task(self.add_task, my_blocking_function,
                                        'somearg', some_kwarg=42)
        self.write('Hello Process World! %s' % result)
        self.finish()LicenseApache License, Version 2.0
Package: tornado-jinja2
This package makes you have the ability that using Jiaja2 Template Engine with Tornado Web Framework.
It will replace the default Tornado Templates.How to use:Import Jinja2Loader to your projectfromtornado_jinja2importJinja2LoaderPass the instance of Jinja2Loader totornado.web.Applicationas the value of “template_loader” parameter.
You can use the particular Loader from jinja2 and configuring jinaja2 environment by your self.importtornado.webimportjinja2# Create a instance of Jinja2Loaderjinja2_env=jinja2.Environment(loader=jinja2.FileSystemLoader('template/path/'),autoescape=False)jinja2_loader=Jinja2Loader(jinja2_env)# Give it to Tornado to replace the default Loader.settings=dict(template_loader=jinja2_loader)application=tornado.web.Application(handler=[],**settings)
Package: tornado-jsonapi
Tornado_jsonapiTornado_jsonapi is a Python 3.3+ library for creating JSON API (as perjsonapi.orgspecification) usingTornadoweb framework. It featuressemi-automatic API generation using providedJSON schemaof resource;support for arbitrary data sources, including SQLAlchemy and PostgreSQL (via
DBAPI2 support layer);support for asynchronous data source operations;strictjsonapi.orgspecification conformance.Usageimportsqlite3importtornado.ioloopimporttornado.webimporttornado_jsonapi.handlersimporttornado_jsonapi.resourceschema={"title":"post","properties":{"text":{"type":"string"},"author":{"type":"string"}}}res=tornado_jsonapi.resource.DBAPI2Resource(schema,sqlite3,sqlite3.connect(':memory:'))res._create_table()application=tornado.web.Application([(r"/api/posts/([^/]*)",tornado_jsonapi.handlers.APIHandler,dict(resource=res))])application.listen(8888)tornado.ioloop.IOLoop.current().start()Installation$pipinstalltornado_jsonapiDocumentationhttps://tornado_jsonapi.readthedocs.orgRoadmapa.k.a. TODOimprove documentation :pensive:automatic API doc generation based on JSON schema;MongoDB/Motor support;support for API testing.LicenseThis project is licensed under the MIT License.Changelog0.1.4 (2020-01-24)Added support for column blacklisting and pagination, thanks to Zachary Gorak.0.1.3 (2016-04-07)Fixed incompatibility with latest python-jsonschema-objectsUpdated obsolete requirementsAdjusted supported Python versions0.1.2 (2016-04-07)Fixed dependencies issue preventing installation in environment with LANG=C0.1.0 (2016-03-21)First release.
Package: tornado-jsonrpc
JSON RPC implementation for tornadoThis implementation follow JSONRPC 2.0 specification.REQUIREMENTSpython >= 3.5 (async/await is used in the package)INSTALLATIONpip install tornado_jsonrpcUSAGEIt is so simple:Just createviews.pydef some_view(request: RequestHandler, *args, **kwargs):  # 
     """
     args: positional params, which You pass when call jsonrpc method
     kwargs: named params, which You pass when call jsonrpc method
     """

     return {'foo': 'bar'}  # any JSON serializable object (dict or list for example)And then createtornado_app.py, where You define tornado Application:from tornado_jsonrpc import JSONRPCHandler
 from tornado.ioloop import IOLoop
 from tornado.web import Application

 from your_package import views

 Application(
     [
         ('/api', views.JSONRPCHandler, dict(views=views)),
     ],
 ).listen(8888)

 IOLoop.current().start()You can also use CORSIgnoreJSONRPCHandler to receive requests from all sources
or WithCredentialsJSONRPCHandler to also receive cookies with request.CONTRIBUTEIf You have found an error or want to offer changes - create a pull request, and I will review it as soon as possible!
Package: tornado-jsonrpc2
🐍🌪️ tornado-jsonrpc2AJSON-RPCrequest handler forTornado.It follows the specifications forJSON-RPC 2.0and1.0.
Differences between the versions are describedherein short form.
By default both versions will be handled and answers are made according to the version detected for the request.The aim is to have a spec-compliant handler that can be set up in a flexible way.RequirementsThe current requirement for this is to have at least Python 3.6 and Tornado 5.PythonThe usage ofjson.JSONDecodeErrorleads to the minimum version Python 3.6.The usage ofasync/awaitmeans the lowest ever supported version will be Python 3.5.
While currently not in focus having this running on Python 3.5 may become an option.UsageTo allow for flexible configuration theJSONRPCHandlerwill have to be passed a parameterresponse_creatorwhich takes an callable that the request in form will get passed to.
The request is an instance oftornado_jsonrpc2.jsonrpc.JSONRPCRequestwith the attributesmethodandparams(andidandversionshould they be required).The following example shows how this can be used to execute methods on a backend instance.
By using functools we are able to create a function that only requires the request as an parameter.importfunctoolsimporttornado.webfromtornado_jsonrpc2.handlerimportJSONRPCHandlerfromtornado_jsonrpc2.exceptionsimportMethodNotFoundclassMyBackend:defsubtract(self,minuend,subtrahend):returnminuend-subtrahendasyncdefcreate_response(request,backend):try:method=getattr(backend,request.method)exceptAttributeError:raiseMethodNotFound("Method{!r}not found!".format(request.method))try:params=request.paramsexceptAttributeError:returnmethod()ifisinstance(params,list):returnmethod(*params)elifisinstance(params,dict):returnmethod(**params)defmake_app():simple_creator=functools.partial(create_response,backend=MyBackend())returntornado.web.Application([(r"/jsonrpc",JSONRPCHandler,{"response_creator":simple_creator}),])if__name__=="__main__":app=make_app()app.listen(8888)tornado.ioloop.IOLoop.current().start()You can access this example app on port 8888 with curl:$ curl --insecure --data '{"jsonrpc": "2.0", "method": "subtract", "params": [5, 1], "id": 1}' http://localhost:8888/jsonrpc

{"jsonrpc": "2.0", "id": 1, "result": 4}You can also name the parameters:$ curl --insecure --data '{"jsonrpc": "2.0", "method": "subtract", "params": {"minuend": 5, "subtrahend": 1}, "id": 1}' http://localhost:8888/jsonrpc

{"jsonrpc": "2.0", "id": 1, "result": 4}Handling specific JSON-RPC versionsBy default the handler will process JSON-RPC 1.0 and 2.0.
It is possible to configure the handler to only work with one specific
version by adding a keyversionwith the value"1.0"or"2.0"to
the route spec.The following example adds a specific route for each version:defmake_app():simple_creator=functools.partial(create_response,backend=MyBackend())returntornado.web.Application([(r"/jsonrpc",JSONRPCHandler,{"response_creator":simple_creator}),(r"/jsonrpc1",JSONRPCHandler,{"version":"1.0","response_creator":simple_creator}),(r"/jsonrpc2",JSONRPCHandler,{"version":"2.0","response_creator":simple_creator}),])
Package: tornado-m2crypto
tornado_m2cryptoThis extension is meant to run tornado with M2Crypto instead of the standard python SSLDependenciesOf course, you need M2Crypto
You need a patched version of Tornado: git+https://github.com/DIRACGrid/tornado.git@iostreamConfigurableHow to useThe tornado_m2crypto/tests directory contains several examples.
Basically, just take any normal https server with tornado you want, and add the following at the beginning# Patching
# needed because some direct calls to ssl_wrap_socket in TCPServer
from tornado_m2crypto.m2netutil import m2_wrap_socket
import tornado.netutil
tornado.netutil.ssl_wrap_socket = m2_wrap_socket


# Dynamically configurable
import tornado.iostream
tornado.iostream.SSLIOStream.configure('tornado_m2crypto.m2iostream.M2IOStream')


import tornado.httputil
tornado.httputil.HTTPServerRequest.configure('tornado_m2crypto.m2httputil.M2HTTPServerRequest')How to testThere are several types of tests.Unit testAlmost a copy paste of the SSLIOStream tests from tornado:tox -rHTTPS testA simple HTTPS servertox -r -e m2io_httpsYou can then talk to you using (only requiresrequestspackage)python test_client.pyDIRAC testAn HTTPS server converting the certificate to "DIRAC certificates"tox -r -e m2io_diracYou can talk to it the same way as the normal HTTPS test, and you can give it a proxy
Package: tornadomail
Tornado mail============Asynchronous email sending(SMTP) library for Tornado. Port of django.mail.Installation------------Using pip: `pip install tornadomail`From source: `git clone git://github.com/equeny/tornadomail.git; cd tornadomail; python setup.py install`Usage-----EmailMessage, EmailMultiAlternatives are almost identical to django classes, except send function is async and can receive callback argument.from tornadomail.message import EmailMessage, EmailMultiAlternativesfrom tornadomail.backends.smtp import EmailBackendclass Application(tornado.web.Application):@propertydef mail_connection(self):return EmailBackend('smtp.gmail.com', 587, '<your google mail>', '<your google password>',True)class MainHandler(tornado.web.RequestHandler):@propertydef mail_connection(self):return self.application.mail_connectiondef get(self):self.render("index.html")def post(self):def _finish(num):print 'sended %d message(s)' % numself.render("index.html")message = EmailMessage(self.get_argument('subject'),self.get_argument('message'),'<your google mail>',[self.get_argument('email')],connection=self.mail_connection)message.send()#callback=_finish)self.render("index.html")Requirements------------The following two python libraries are required* [tornado>=2.1](http://github.com/facebook/tornado)Issues------Please report any issues via [github issues](https://github.com/equeny/tornadomail/issues)
Package: tornado-middleware
Tornado MiddlewaresMiddleware support for Tornado FrameworkInstallpipinstalltornado-middlewareExampleCreate a simple middleware onRequestHandlerclass.fromtornado_middlewareimportMiddlewareHandlerclassIndexHandler(MiddlewareHandler):asyncdefmiddleware_echo(self,next):print("Middleware triggered")awaitnext()defget(self):print("Function triggered")self.set_status(200)self.finish("<html><body><h1>Hello Middleware</h1></body></html>")Create a separately middlewarefromtornado_middlewareimportMiddlewareHandlerfromtornado.webimportRequestHandlerclassEchoMiddleware(MiddlewareHandler):asyncdefmiddleware_echo(self,next):print("Middleware triggered")awaitnext()classIndexHandler(EchoMiddleware,RequestHandler):defget(self):print("Function triggered")self.set_status(200)self.finish("<html><body><h1>Hello Middleware</h1></body></html>")
Package: tornado-mixpanel
Tornado Mixpanel is an async library for Mixpanel service. This library allows
for server-side integration of Mixpanel.InstallationAutomatic installation:$pipinstalltornado-mixpanelTornado Mixpanel is listed inPyPIand can be installed withpiporeasy_install.Manual installation: Download the latest source fromPyPI.tar xvzf tornado-mixpanel-$VERSION.tar.gz
cd tornado-mixpanel-$VERSION
python setup.py build
sudo python setup.py installThe Tornado Mixpanel source code ishosted on GitHub.ExampleHere is a simple example:#!/usr/bin/env python2.7# -*- coding: utf-8 -*-importtracebackfromtornadoimportgen,ioloopfromtornado_mixpanel.clientimportAsyncMixpanelClient@gen.coroutinedefrun():client=AsyncMixpanelClient('<mixpanel-token>')raw_input('Press (enter) to continue...')try:r=yieldclient.track('user-xxxx','steps',{'step_one':True,'step_two':False})printrr=yieldclient.people_set('client-xxxx',{'fullname':'Alejandro Bernardis'})printrr=yieldclient.people_append('client-xxxx',{'age':31,'locale':'es_AR'})printrexcept:printtraceback.format_exc()ioloop.IOLoop.current().stop()if__name__=='__main__':run()ioloop.IOLoop.instance().start()And buffer example:#!/usr/bin/env python2.7# -*- coding: utf-8 -*-importtimeimporttracebackfromtornadoimportgen,ioloopfromtornado_mixpanel.clientimportAsyncMixpanelClient@gen.coroutinedefrun():client=AsyncMixpanelClient('<mixpanel-token>',True)raw_input('Press (enter) to continue...')try:username=int(time.time())print'Tracking...'foriinxrange(10):yieldclient.track(username,'item_%s'%i,{'i':i})time.sleep(1)print'-*-'*20r=yieldclient.consumer.flush()printrexcept:printtraceback.format_exc()ioloop.IOLoop.current().stop()if__name__=='__main__':run()ioloop.IOLoop.instance().start()LicenseThe MIT License (MIT)Copyright (c) 2015 Alejandro Bernardis and contributors.  See AUTHORS
for more details.Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the “Software”), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
Package: tornado-models
tornado-modelssqlalchemy and redis for tornadoInstallationpip install tornado-modelsUsagesqlalchemyfrom tornado.web import Application
from tornado_models.sqlalchemy import SQLAlchemy

from my_app.handlers import IndexHandler

app = Application(
    ((r'/', IndexHandler),),
    db=SQLAlchemy(database_url)
 )

##################################

from tornado_models.sqlalchemy import SQLAlchemy

db = SQLAlchemy(url=database_url)

class User(db.Model):
    id = Column(BigInteger, primary_key=True)
    username = Column(String(255), unique=True)

##################################

from tornado_models.sqlalchemy import SessionMixin
from tornado_models import as_future

class NativeCoroutineRequestHandler(SessionMixin, RequestHandler):
    async def get(self):
        with self.db_session() as session:
            count = await as_future(session.query(User).count())

        self.write('{} users so far!'.format(count))redisfrom tornado.web import Application
from tornado_models.redis import Redis

from my_app.handlers import IndexHandler

app = Application(
    ((r'/', IndexHandler),),
    redis=Redis(pool_options(dict(host='localhost', port=6379, db=0)))
 )

##################################

from tornado_models.redis import RedisMixin
from tornado_models import as_future

class NativeCoroutineRequestHandler(RedisMixin, RequestHandler):
    async def get(self):
        with self.redis_session() as session:
            value = await as_future(session.get('key'))

        self.write('redis value is {}!'.format(value))Demo Projecthttps://tornado-sqlalchemy.readthedocs.io/en/stable/
Package: tornado_msgpack
Yet another MessagePack RPC for Pythonhistory20130827 0.4 add loggingsamplesdemo#!/usr/bin/env python

port=28080

import tornado_msgpack
dispatcher=tornado_msgpack.Dispatcher()
def add(a, b):
    return a+b
dispatcher.add_handler("add", add)

with tornado_msgpack.ServerLoop("", port, dispatcher.on_message):
    with tornado_msgpack.ClientLoop("localhost", port) as client:
        print(client.call_sync("add", 3, 4))server#!/usr/bin/env python

import tornado_msgpack
import tornado

port=18080

# dispatcher
dispatcher=tornado_msgpack.Dispatcher()
def add(a, b):
    return a+b
dispatcher.add_handler("add", add)

# server
server_loop=tornado.ioloop.IOLoop()
server=tornado_msgpack.Server(server_loop, dispatcher.on_message)
server.listen(port)

import signal
def handler(signum, frame):
    server_loop.stop()
signal.signal(signal.SIGINT, handler)

try:
    # blocking...
    server_loop.start()
except ex as KeyboardInterrupt:
    passclient#!/usr/bin/env python
import tornado_msgpack
import tornado
import threading

host="127.0.0.1"
port=18080

client_loop=tornado.ioloop.IOLoop()
client_thread=threading.Thread(target=lambda : client_loop.start())

# connecion status
def on_status(session):
    print("status changed: "+session.status)
client=tornado_msgpack.Client(client_loop, on_status)

client.session.connect(host, port)
try:
    client_thread.start()

    # sync
    result=client.call_sync("add", 3, 4)

    # async
    future=client.call_async("add", 5, 6)
    future.join() # wait server respone
    msgpack_rpc=future.message
    result=msgpack_rpc[3]

    # async_with_callback
    def on_receive(msgpack_rpc):
        print(msgpack_rpc)
    future=client.call_async_with_callback(on_receive, "add", 5, 6)
    future.join() # wait server respone

finally:
    client_loop.stop()
    client_thread.join()