Rocket是一个轻量级,多线程,符合WSGI规范的web框架。

Rocket使用一个线程监听连接,接收到连接之后放到Queue中,有worker线程进行处理。

Rocket含有以下属性:

  • method - A string value indicating the type of Worker to use to answer the requests received by Rocket. The default is wsgi and will invoke the WSGIWorker class for handling requests. Go to theMethods section to see all available methods.
  • app_info - A dictionary that holds information that the Worker class specified in method will use for configuration. See the documentation in the Methods section for the Worker class you are using for details on what to put in this dictionary.
  • min_threads - An integer number of minimum Worker threads to run. This number must be greater than 0. Rocket will always have at least min_threads number of threads running at a time unless it is in the process of shutting down.
  • max_threads - An integer number of maximum Worker threads. This number must be greater than min_threads or 0. A max_threads of 0 (zero) indicates there to be no maximum thread count. Rocket will continue generating threads so long as there are unanswered connections in the request queue. If the running environment is limited by how many threads a process can own, consider that in addition to max_threads there will also be a monitor thread and listening thread running.
  • queue_size - An integer number of connections allowed to be queued before Rocket accepts them. This number is passed to the listen() function in the operating system’s socket library. It defaults toNone which either uses the operating system’s maximum or 5 if the OS max is not discoverable.
  • timeout - An integer number of seconds to listen to a connection for a new request before closing it. Defaults to 600.
  • handle_signals - A boolean indicating whether or not Rocket should respond to UNIX-style process signals (if the platform supports signals). Defaults to True.

min_threads 必须是一个大于0的数字,Rocket在同一时刻一定有大于min_threads在执行,默认这个值是10

max_threads 是指最多有多少个线程同时在执行,默认是没有限制的,对于cPython来说因为存在GIL,所以线程数量较多不存在问题;对于Jpython,由于是真正的多线程,如果web的瓶颈在于CPU,建议max_threads为CPU核数的1.5倍,避免多线程切换降低效率。

queue_size 是指默认可以接收的连接个数,通常这个值由系统决定。

Web.py中使用到了Rocket框架,初始代码如下:

class Rocket(object):
"""The Rocket class is responsible for handling threads and accepting and
dispatching connections.""" def __init__(self,
interfaces=('127.0.0.1', 8000),
method='wsgi',
app_info=None,
min_threads=None,
max_threads=None,
queue_size=None,
timeout=600,
handle_signals=True): self.handle_signals = handle_signals
self.startstop_lock = Lock()
self.timeout = timeout if not isinstance(interfaces, list):
self.interfaces = [interfaces]
else:
self.interfaces = interfaces if min_threads is None:
min_threads = DEFAULTS['MIN_THREADS'] if max_threads is None:
max_threads = DEFAULTS['MAX_THREADS'] if not queue_size:
if hasattr(socket, 'SOMAXCONN'):
queue_size = socket.SOMAXCONN
else:
queue_size = DEFAULTS['LISTEN_QUEUE_SIZE'] if max_threads and queue_size > max_threads:
queue_size = max_threads if isinstance(app_info, dict):
app_info['server_software'] = SERVER_SOFTWARE self.monitor_queue = Queue()
self.active_queue = Queue() self._threadpool = ThreadPool(get_method(method),
app_info=app_info,
active_queue=self.active_queue,
monitor_queue=self.monitor_queue,
min_threads=min_threads,
max_threads=max_threads) # Build our socket listeners
self.listeners = [Listener(
i, queue_size, self.active_queue) for i in self.interfaces]
for ndx in range(len(self.listeners) - 1, 0, -1):
if not self.listeners[ndx].ready:
del self.listeners[ndx] if not self.listeners:
log.critical("No interfaces to listen on...closing.")
sys.exit(1) def _sigterm(self, signum, frame):
log.info('Received SIGTERM')
self.stop() def _sighup(self, signum, frame):
log.info('Received SIGHUP')
self.restart() def start(self, background=False):
log.info('Starting %s' % SERVER_SOFTWARE) self.startstop_lock.acquire() try:
# Set up our shutdown signals
if self.handle_signals:
try:
import signal
signal.signal(signal.SIGTERM, self._sigterm)
signal.signal(signal.SIGUSR1, self._sighup)
except:
log.debug('This platform does not support signals.') # Start our worker threads
self._threadpool.start() # Start our monitor thread
self._monitor = Monitor(self.monitor_queue,
self.active_queue,
self.timeout,
self._threadpool)
self._monitor.setDaemon(True)
self._monitor.start() # I know that EXPR and A or B is bad but I'm keeping it for Py2.4
# compatibility.
str_extract = lambda l: (l.addr, l.port, l.secure and '*' or '') msg = 'Listening on sockets: '
msg += ', '.join(
['%s:%i%s' % str_extract(l) for l in self.listeners])
log.info(msg) for l in self.listeners:
l.start() finally:
self.startstop_lock.release() if background:
return while self._monitor.isAlive():
try:
time.sleep(THREAD_STOP_CHECK_INTERVAL)
except KeyboardInterrupt:
# Capture a keyboard interrupt when running from a console
break
except:
if self._monitor.isAlive():
log.error(traceback.format_exc())
continue return self.stop() def stop(self, stoplogging=False):
log.info('Stopping %s' % SERVER_SOFTWARE) self.startstop_lock.acquire() try:
# Stop listeners
for l in self.listeners:
l.ready = False # Encourage a context switch
time.sleep(0.01) for l in self.listeners:
if l.isAlive():
l.join() # Stop Monitor
self._monitor.stop()
if self._monitor.isAlive():
self._monitor.join() # Stop Worker threads
self._threadpool.stop() if stoplogging:
logging.shutdown()
msg = "Calling logging.shutdown() is now the responsibility of \
the application developer. Please update your \
applications to no longer call rocket.stop(True)"
try:
import warnings
raise warnings.DeprecationWarning(msg)
except ImportError:
raise RuntimeError(msg) finally:
self.startstop_lock.release() def restart(self):
self.stop()
self.start()

start方法中执行下列步骤:

1、启动关闭锁加锁

2、注册终止和重启的信号

3、启动worker线程池

4、启动监控线程,添加监控线程到线程池中

5、启动所有的监听线程

6、释放启动关闭锁

7、进入while(监控线程存活)循环,每次休眠1s

stop方法:

1、启动关闭锁加锁

2、所有监听线程设置ready标记为为False

3、等待所有监听线程结束

4、等待监控线程结束

5、关闭worker线程池

6、输出关闭log

7、释放启动关闭锁

web.py 学习(-)Rocket web框架的更多相关文章

  1. web.py学习心得

    1.注意判断数字时,如果是get传递的参数,一定要用int转换.不然出错. 2.$var 定义时,冒号后的内容不是python内容,需加上$符号.如$var naviId:$naviId. 3.各个模 ...

  2. web.py学习遇到的问题

    刚配置好了web.py运行所需要的环境,试着运行一个入门小实例,结果遇到了异常提示.不知道是什么原因导致的(是环境没配置好?还是……),暂时做个标记,记录一下. 运行的代码 import web ur ...

  3. ASP.NET MVC Web API 学习笔记---Web API概述及程序示例

    1. Web API简单说明 近来很多大型的平台都公开了Web API.比如百度地图 Web API,做过地图相关的人都熟悉.公开服务这种方式可以使它易于与各种各样的设备和客户端平台集成功能,以及通过 ...

  4. 【Python】【web.py】python web py入门-4-请求处理(上)

    python web py入门-4-请求处理(上) 2017年09月05日 23:07:24 Anthony_tester 阅读数:2907 标签: webpy入门请求处理 更多 个人分类: Pyth ...

  5. web.py 学习(二)Worker

    Rocket Server 启动一个线程监听客户端的连接,收到连接将连接放置到队列中.线程池中的Worker会以这个连接进行初始化.Rocket中Worker的基类是: class Worker(Th ...

  6. 【Python】【Web.py】python web py入门-5-请求处理(下)

    前面一篇,我们演示了如何获取GET和POST请求的参数信息,这篇我们介绍如何获取请求的头部信息,这个方法我们在前面一篇文章已经给出了.直接来看一个例子,首先,我们在hello.py文件新增一个方法,用 ...

  7. 简单而直接的Python web 框架:web.py

    web.py 是一个Python 的web 框架,它简单而且功能强大.web.py 是公开的,无论用于什么用途都是没有限制的. 先让大家感受一下web.py 的简单而强大: import web ur ...

  8. python学习笔记(十 四)、web.py

    使用web.py 通过python进行网页的编写,下面我们来简单了解一哈web.py 的使用 1 url处理 使用特定的url结构来解析我们发送的请求.如下面所示: urls = ( '/login' ...

  9. web.py开发

    web.py需要使用python2.X,所以安装python版本2.7.9 web.py 是一个轻量级Python web框架,它简单而且功能强大 web.py安装 安装python (1)使用pip ...

随机推荐

  1. Maven之(五)Maven仓库

    本地仓库 Maven一个很突出的功能就是jar包管理,一旦工程需要依赖哪些jar包,只需要在Maven的pom.xml配置一下,该jar包就会自动引入工程目录.初次听来会觉得很神奇,下面我们来探究一下 ...

  2. PRML 第二章mindmap

    PRML第二章的Mindmap,这一章读的比较快,主要是很多计算和证明的过程都跳过了,感觉不是特别需要认真去看每一个公式,能够记住每个小节的结论.公式就可以了.当然有能力.有时间的人还是可以认真读的, ...

  3. B+树概念学习

    转载自 从B树.B+树.B*树谈到R 树 1.用阶定义的B树 B 树又叫平衡多路查找树.一棵m阶的B 树 (注:切勿简单的认为一棵m阶的B树是m叉树,虽然存在四叉树,八叉树,KD树,及vp/R树/R* ...

  4. .net mvc 超过了最大请求长度 限制文件上传大小

    在我们的项目中遇到"超过了最大请求长度"如下图所示,是因为IIS默认请求长度4M,当请求长度大于这个值的时候报错,下面是解决方案. 解决方案:修改web.config文件 1.注意 ...

  5. char、varchar、varchar(2)的区别

    char是存储字节是一定的,例如char(10),存储内容为"java",那么实际存储的是"java      ",后面是6个空字符.按字节存储: varcha ...

  6. openstack私有云布署实践【11.2 计算nova - compute节点配置(办公网环境)】

    这里我只使用compute1节点配置为示例,其它节点的配置基本是一样的,只是声明的管理IP不同而已   计算节点 # yum install openstack-nova-compute sysfsu ...

  7. Oracle的闪回技术--闪回错误的DML操作

    提交DML操作后,该操作使用的还原段就可以被其它对象使用了,为了保证闪回操作时这些数据仍然被保存在还原段中,可能需要重新设置undo_retention参数,表示一个事务提交后,该事务的数据必须保存在 ...

  8. 关于java的设计模式(转)

    设计模式(Design Patterns) ——可复用面向对象软件的基础 设计模式(Design pattern)是一套被反复使用.多数人知晓的.经过分类编目的.代码设计经验的总结.使用设计模式是为了 ...

  9. 我在GNU/Linux下使用的桌面环境工具组合

    为了使GNU/Linux桌面环境下加载的程序较少以节省内存资源和提高启动时间,我目前并不使用重量级的桌面环境KDE和Gnome,甚至连登录窗界面gdm或xdm都不用,而是直接启动到控制台,登录后调用s ...

  10. Buffett saying

    1. 人生财富就像滚雪球,最重要的是发现很湿的雪和很长的坡. 2. 雪球想滚大,必须要有最坚实的核心:一生坚持的价值投资理念 价值投资一直是巴菲特投资理念的核心,他始终认为投资企业最重要的是要看准企业 ...