关于文章 tornado

django linux python tornado wsgi

使用tornado回调启动django

使用tornado回调启动django

使用tornado回调启动django

import os
import sys
from tornado.options import options, define, parse_command_line
import django.core.handlers.wsgi
import tornado.httpserver
import tornado.ioloop
import tornado.web
import tornado.wsgi
from django.core.wsgi import get_wsgi_application
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
os.environ['DJANGO_SETTINGS_MODULE'] = "tornago.settings"

define('port', type=int, default=8000)


def main():
    parse_command_line()
    wsgi_app = tornado.wsgi.WSGIContainer(get_wsgi_application())
    tornado_app = tornado.web.Application(

        [('.*', tornado.web.FallbackHandler, dict(fallback=wsgi_app)),]
    )
    server = tornado.httpserver.HTTPServer(tornado_app)
    server.listen(options.port)
    tornado.ioloop.IOLoop.instance().start()

if __name__ == '__main__':
    main()
aiohttp asyncio callback linux tornado

aiohttp 类 tornado 代码风格模式去开发 !!!完美阿!!!!

使用aiohttp进行tornado代码风格的开发

仔细读了一下 aiohttp 的文档

http://aiohttp.readthedocs.io/en/stable/index.html

= = 竟然!!!

竟然有了!!!!!

类tornado开发特色的!!! 贼开心

from aiohttp import web
class basic(web.View):
    def out(self,text):
        return web.Response(text=text)
class Index(basic):
    async def get(self):
        name = self.request.match_info.get('name', "Anonymous")
        text = "Hello, " + name
        return self.out(text=text)
app = web.Application()
app.add_routes([web.view('/', Index),])
if __name__ == "__main__":
    web.run_app(app)
city ip log tornado

tornado 异步日志统计获取IP地址和对应城市

异步日志统计获取IP地址和对应城市

ip转城市

直接贴代码

class Singleton(type):
    _instances = {}

    def __call__(cls, *args, **kwargs):
        if cls not in cls._instances:
            cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
        return cls._instances[cls]


class SearchIp(metaclass=Singleton):
    def __init__(self):
        try:
            dbpath = os.path.abspath("./utils/ip/ip2region.db")
            self.search = Ip2Region(dbpath)
        except IOError:
            log.error("err connect db",IOError.errno)
        else:
            log.info("db connect success")

    def getSession(self):
        return self.search
    def searchCity(self,ip):
        try:
            if self.getSession().isip(ip):
                city =  self.getSession().btreeSearch(ip=ip).get("region","火星").decode("utf-8")
            else:
                city = "火星"
        except IOError:
            log.error(IOError)
            city = "火星"
            return city
        else:
            return city
    def close(self):
        self.search.close()

单例模式 然后ip转城市

异步存到mongodb

class baseHttp (tornado.web.RequestHandler):
    executor = ThreadPoolExecutor(100)

        @tornado.web.asynchronous
        @tornado.gen.coroutine
        def initialize(self):
            yield self.logsave()

        @run_on_executor
        def logsave(self):
            ipDao.saveLog(self.request.remote_ip,self.request.uri,self.request.headers.get("User-Agent","鬼知道"))

似乎还凑活~~

python threadpoolexecutor tornado

python tornado ThreadPoolExecutor实现异步

tornado

#!/bin/env python
# -*- coding:utf-8 -*-
## 异步demo
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
from tornado import httpclient
import tornado.gen
from tornado import gen
from tornado.concurrent import run_on_executor
from concurrent.futures import ThreadPoolExecutor
import time
from tornado.options import define, options
define("port", default=8000, help="run on the given port", type=int)
class SleepHandler(tornado.web.RequestHandler):
    executor = ThreadPoolExecutor(10000)
    @tornado.web.asynchronous
    @tornado.gen.coroutine
    def get(self):
        # 假如你执行的异步会返回值被继续调用可以这样(只是为了演示),否则直接yield就行
        res = yield self.sleep()
        self.write("when i sleep %s s" % res)
        self.finish()
    @run_on_executor
    def sleep(self):
        for a in  range(1,900000):
            print(a)
        return 5
class JustNowHandler(tornado.web.RequestHandler):
    def get(self):
        self.write("i hope just now see you")
if __name__ == "__main__":
    tornado.options.parse_command_line()
    app = tornado.web.Application(handlers=[
            (r"/sleep", SleepHandler), (r"/justnow", JustNowHandler)])
    http_server = tornado.httpserver.HTTPServer(app)
    http_server.listen(options.port)
    tornado.ioloop.IOLoop.instance().start()