📜 ⬆️ ⬇️

Torskel - simplify the routine in Tornado

I often have to do small servers on tornado. In some projects, you need support for working with redis, in some you don’t. In others, you need to render ReactJS. And all need logging. For a start, I picked up a local pypi repository, collected my work in a python package and enjoyed my life. It was enough to install the package, import classes from it, follow it and happily saw the code further.

And then there was a thought - and not to share their work with people? So I present to you the torskel package.

At once I will make a reservation that he is friends only with Python 3.5+ since it uses async / await at all.

This is a tornado wrapper that allows you to get basic functionality out of the box:
')
Installing the library - pip install torskel

Asynchronous work with Redis


Disabled by default, to enable, you must set the use_redis option to True and make pip install aioredis

Usage example:

 import asyncio from torskel.torskel_app import TorskelServer from torskel.torskel_handler import TorskelHandler import tornado.web from tornado.options import options options.define('use_redis', default=True, help='use redis', type=bool) class RedisApplication(TorskelServer): def __init__(self, handlers, **settings): super().__init__(handlers, **settings) self.greeting = 'Hello redis!' class RedisHandler(TorskelHandler): async def get(self): my_key = self.get_hash_str('my_key') await self.set_redis_exp_val(my_key, self.application.greeting, 3000, convert_to_json=False) res = await self.get_redis_val(my_key, from_json=False) self.write(res) await self.del_redis_val(my_key) self.finish() redis_app = RedisApplication(handlers=[(r"/", RedisHandler)]) if __name__ == '__main__': redis_app.listen(8888) loop = asyncio.get_event_loop() redis_app.init_with_loop(loop) loop.run_forever() tornado.ioloop.IOLoop.instance().start() 

The list of available options with default values:

Determines whether to use radishes at all

 use_redis=False 

Default connection via socket file

 use_redis_socket=True 

Create a pool of connections - minimum 5, maximum 10

 redis_min_con=5 redis_max_con=10 

How to get to the radish?

 redis_host='127.0.0.1' redis_port=6379 redis_socket='/var/run/redis/redis.sock' 

Configure authorization

 redis_psw=''    redis_db=1 

We send a log on mail


Configured with the following options:

 options.define('use_mail_logging', default=False, help='SMTP log handler', type=bool) options.define("log_mail_subj", default='', type=str) options.define("log_mail_from", default='', type=str) options.define("log_mail_to", default=[], type=list) options.define("log_mail_host", default='', type=str) options.define("log_mail_user", default='', type=str) options.define("log_mail_psw", default='', type=str) 

I think there is no need for special explanations, the names of the options speak for themselves.

Http requests


Just a wrapper over a standard Tornad AsyncHttpClient

 import tornado.web from torskel.torskel_app import TorskelServer from torskel.torskel_handler i mport TorskelHandler class HelloHttpHandler(TorskelHandler): async def get(self): res = await self.http_request_get('http://example.com') self.write(res) self.finish() hello_http_app = TorskelServer(handlers=[(r"/", HelloHttpHandler)]) if __name__ == '__main__': hello_http_app.listen(8888) tornado.ioloop.IOLoop.instance().start() 

ReactJS support


Enabled by use_reactjs option. You also need to make pip install jinja2. Here we will need a set of js-developer, npm, webpack / gulp and other babels.

Render occurs function react_render . It is assumed that your html template, you connect the script with the line

  <script src = "{{assets ['main'] ['js']}}"> </ script> 

This moment is rather thin and in the future I plan to finalize it.

 import tornado.web import os from tornado.web import url from tornado.options import options, define from torskel.torskel_app import TorskelServer from torskel.torskel_handler import TorskelHandler settings = {} options.define('use_reactjs', default=True, help='use reactjs', type=bool) options.define("react_assets_file", default='webpack-assets.json', type=str) class MainHandler(TorskelHandler): def get(self): self.react_render('index.html') self.finish() handlers = [ url(r"/", MainHandler, name="IndexPage"), ] class HelloReactApplication(TorskelServer): def __init__(self, handlers, **settings): super().__init__(handlers, **settings) hello_react = HelloReactApplication(handlers, root_dir=os.path.dirname(__file__), **settings) if __name__ == "__main__": hello_react.listen(options.port) tornado.ioloop.IOLoop.current().start() 

This is still the alpha version of the library. The plans still add support for creating pools of connections to various databases.

PS

Github link
github.com/frostspb/torskel

Source: https://habr.com/ru/post/342968/


All Articles