给cherrypy 打gevent WSGIServer的patch

1. patch Serving 类

2. 关闭python的原生WSGIServer

具体使用例子参考 我的开源项目  https://github.com/thomashuang/Lilac

#!/usr/bin/env python

import cherrypy
from cherrypy import _cprequest
from cherrypy.lib import httputil
import sys
import logging
from cherrypy.process import servers LOGGER = logging.getLogger('web.patch') try:
from greenlet import getcurrent as get_ident
except ImportError:
LOGGER.ERROR('You shall install Gevent, if wanna use gevent wsgi server')
exit(1) def patch_cherrypy():
cherrypy.serving = GreenletServing() class GreenletServing(object):
__slots__ = ('__local__', ) def __init__(self):
object.__setattr__(self, '__local__', {})
ident = get_ident()
self.__local__[ident] = {
'request': _cprequest.Request(httputil.Host("127.0.0.1", 80), httputil.Host("127.0.0.1", 1111)),
'response': _cprequest.Response()
} def load(self, request, response):
self.__local__[get_ident()] = {
'request': request,
'response': response
} def __getattr__(self, name):
try:
return self.__local__[get_ident()][name]
except KeyError:
raise AttributeError(name) def __setattr__(self, name, value):
ident = get_ident()
local = self.__local__
try:
local[ident][name] = value
except KeyError:
local[ident] = {name: value} def clear(self):
"""Clear all attributes of the current greenlet."""
del self.__local__[get_ident()]
#!/usr/bin/env python

import cherrypy
import sys
import logging
from cherrypy.process import servers LOGGER = logging.getLogger('web.server') class GeventWSGIServer(object): """Adapter for a gevent.wsgi.WSGIServer.""" def __init__(self, *args, **kwargs):
from lilac.web.patch import patch_cherrypy patch_cherrypy()
self.args = args
self.kwargs = kwargs
self.ready = False def start(self):
"""Start the GeventWSGIServer."""
# We have to instantiate the server class here because its __init__
from gevent.wsgi import WSGIServer self.ready = True
LOGGER.debug('Starting Gevent WSGI Server...')
self.httpd = WSGIServer(*self.args, **self.kwargs)
self.httpd.serve_forever() def stop(self):
"""Stop the HTTP server."""
LOGGER.debug('Stoping Gevent WSGI Server...')
self.ready = False
self.httpd.stop() class WebServer(object): def __init__(self, server_name='Sola', host='127.0.0.1', port=8080, use_gevent=True, debug=False, encoding='UTF-8'):
self.server_name = server_name
self.host = host
self.port = port
self.debug = debug
self.encoding = encoding
self.use_gevent = use_gevent
self.config = self.gen_config()
self.bootstrap() def bootstrap(self):
"""You can intialize more configs or settings in here"""
pass def gen_config(self):
conf = {
'global':
{
'server.socket_host': self.host,
'server.socket_port': self.port,
'engine.autoreload.on': self.debug,
#'log.screen': self.debug,
'log.error_file': '',
'log.access_file': '',
'request.error_response': self.handle_internal_exception,
'tools.decode.on': True,
"tools.encode.on": True,
'tools.encode.encoding': self.encoding,
'tools.gzip.on': True,
'tools.log_headers.on': False,
'request.show_tracebacks': False,
}
}
if self.use_gevent:
conf['global']['environment'] = 'embedded' return conf def set_404_pape(self, not_found_handler):
"""Custom not found page"""
self.config['global']['error_page.404'] = not_found_handler def asset(self, path, asset_path):
"""Set servering Static directory"""
self.config[path] = {
'tools.staticdir.on': True,
'tools.staticdir.dir': asset_path
} def handle_internal_exception(self):
"""Handle the unknow exception and also throw 5xx status and push message to frontend"""
cls, e, tb = sys.exc_info() LOGGER.exception('Unhandled Error %s', e)
resp = cherrypy.response
resp.status = 500
resp.content_type = 'text/html; charset=UTF-8' if cherrypy.request.method != 'HEAD':
resp.body = ["""<html>
<head><title>Internal Server Error </title></head>
<body><p>An error occurred: <b>%s</b></p></body>
</html> """ % (str(e))] def new_route(self):
return cherrypy.dispatch.RoutesDispatcher() def create_app(self):
raise NotImplemented('Must implement create_app in Subclass') def _bootstrap_app(self):
ctl, routes = self.create_app()
cherrypy.config.clear()
config = {'/': {'request.dispatch': routes}, 'global': self.config}
config.update(self.config)
cherrypy.config.update(config)
return cherrypy.tree.mount(ctl, '/', config) def serve_forever(self):
engine = cherrypy.engine
if hasattr(engine, "signal_handler"):
engine.signal_handler.subscribe()
if hasattr(engine, "console_control_handler"):
engine.console_control_handler.subscribe()
app = self._bootstrap_app()
try:
if self.use_gevent:
# Turn off autoreload when using *cgi.
#cherrypy.config.update({'engine.autoreload_on': False})
addr = cherrypy.server.bind_addr
cherrypy.server.unsubscribe()
f = GeventWSGIServer(addr, app, log=None)
s = servers.ServerAdapter(engine, httpserver=f, bind_addr=addr)
s.subscribe()
engine.start()
else:
cherrypy.quickstart(app)
except KeyboardInterrupt:
self.stop()
else:
engine.block() def stop(self):
cherrypy.engine.stop()

cherrypy & gevent patch的更多相关文章

  1. 高并发异步uwsgi+web.py+gevent

    为什么用web.py? python的web框架有很多,比如webpy.flask.bottle等,但是为什么我们选了webpy呢?想了好久,未果,硬要给解释,我想可能原因有两个:第一个是兄弟项目组用 ...

  2. 协程--gevent模块(单线程高并发)

    先恶补一下知识点,上节回顾 上下文切换:当CPU从执行一个线程切换到执行另外一个线程的时候,它需要先存储当前线程的本地的数据,程序指针等,然后载入另一个线程的本地数据,程序指针等,最后才开始执行.这种 ...

  3. [转载]python gevent

    原地址: http://www.liaoxuefeng.com/wiki/001374738125095c955c1e6d8bb493182103fac9270762a000/001407503089 ...

  4. 流动python - 写port扫描仪和各种并发尝试(多线程/多进程/gevent/futures)

    port扫描仪的原理非常easy.没有什么比操作更socket,能够connect它认为,port打开. import socket def scan(port): s = socket.socket ...

  5. gevent拾遗

      在前文已经介绍过了gevent的调度流程,本文介绍gevent一些重要的模块,包括Timeout,Event\AsynResult, Semphore, socket patch,这些模块都涉及当 ...

  6. Python并发编程协程(Coroutine)之Gevent

    Gevent官网文档地址:http://www.gevent.org/contents.html 基本概念 我们通常所说的协程Coroutine其实是corporate routine的缩写,直接翻译 ...

  7. gevent程序员指南

    gevent程序员指南 由Gevent社区编写 gevent是一个基于libev的并发库.它为各种并发和网络相关的任务提供了整洁的API.   介绍 本指南假定读者有中级Python水平,但不要求有其 ...

  8. python中的猴子补丁Monkey Patch

    python中的猴子补丁Monkey Patch 什么是猴子补丁 the term monkey patch only refers to dynamic modifications of a cla ...

  9. 协程----greenlet模块,gevent模块

    1.协程初识,greenlet模块 2.gevent模块(需要pip安装) 一.协程初识,greenlet模块: 协程:是单线程下的并发,又称微线程,纤程.英文名Coroutine.一句话说明什么是线 ...

随机推荐

  1. Oracle及其相关软件历史版本下载地址

    https://edelivery.oracle.com/osdc/faces/Home.jspx 打开上面这个链接,输入自己或可用的帐号即可. 搜索到自己想要下载的软件后,点击,软件会添加到购物车中 ...

  2. Suricata的总体架构

    Suricata的总体架构  报文检测系统通常四大部分,报文获取.报文解码.报文检测.日志记录:suricata不同的功能安装模块划分,一个模块的输出是另一个模块的输入,suricata通过线程将模块 ...

  3. Spark-SQL连接Hive

    第一步:修个Hive的配置文件hive-site.xml 添加如下属性,取消本地元数据服务: <property> <name>hive.metastore.local< ...

  4. idea使用Git提交代码时忽略指定文件或文件夹

    简述 使用idea编写代码并使用git作为版本控制器的时候,常常不需要提交配置文件以及一些其他不需要提交的文件,可以使用.ignore插件来在上传的时候忽略一些文件或文件夹. 安装 注意:安装完成之后 ...

  5. 严重 [RMI TCP Connection(2)-127.0.0.1] org.apache.catalina.core.ContainerBase.addChildInternal ContainerBase.addChild: start:解决

    严重 [RMI TCP Connection(2)-127.0.0.1] org.apache.catalina.core.ContainerBase.addChildInternal Contain ...

  6. 微信小程序组件解读和分析:一、view(视图容器 )

    view组件说明:    视图容器    跟HTML代码中的DIV一样,可以包裹其他的组件,也可以被包裹在其他的组件内部.用起来比较自由随意,没有固定的结构. view组件的用法: 示例项目的wxml ...

  7. dnsquery - 使用解析程序查询域名服务器

    SYNOPSIS(总览) dnsquery [-n nameserver ] [-t type ] [-c class ] [-r retry ] [-p period ] [-d ] [-s ] [ ...

  8. Linux目录结构及详细介绍

    /:根目录,位于Linux文件系统目录结构的顶层,一般根目录下只存放目录,不要存放文件,/etc./bin./dev./lib./sbin应该和根目录放置在一个分区中. /bin,/usr/bin:该 ...

  9. VsCode使用之HTML 中 CSS Class 智能提示

    HTML 中 CSS Class 智能提示 安装插件:HTML CSS Support 设置中添加以下代码: "editor.parameterHints": true, &quo ...

  10. this.$Message.success('提示信息') 少写了一个c 导致报错

    this.$Message.success('提示信息') 少写了一个c 导致报错 而且 $Message 输出还没显示,导致我以为是没有 $Message 对象了,其实全局对象直接调用即可