Python的web项目如何进行动态重载和热部署?

Python014

Python的web项目如何进行动态重载和热部署?,第1张

真正意义上的代码热部署应该是类似erlang那样的,将代码更新到节点后不停服务,不断连接的自动应用新代码。auto reload什么的还是会造成业务瞬间中断。我感觉是可以从wsgi容器级别上实现,比如更新代码后检测到文件变更,然后通知容器创建新的wsgi application的实例,之后所有新的请求都发送到新的wdgi application实例上。等旧wsgi application实例的最后一个请求返回后就将其回收掉。不过貌似没有看到类似的实现

这个没有最佳解法吧,看个人理解……

下面是我的理解:

1. 不同的策略分为不同的类,提供一个统一的接口,比如

#strategy.py

class UserRate(object):

def __init__(self, comment_per_user_min=10):

#init

def check(self, userdata):

#检查用户数据,超过限制即报警

class UserDupContent(object):

def __init__(self, content_send_per_user=10):

#init

def check(self, userdata):

#检查用户数据

2. 使用依赖注入将策略注入到检查程序:

class Guarder(object):

def addStrategy(self, strategy):

#添加一个策略

def check(self, userdata):

#使用已经添加的策略逐个检查

#返回检查结果

def reload_from(self, conf):

#解析配置并创建相应对象

self.addStrategy(strategy)

@classmethod

def create(cls, conf=''):

obj = cls()

if conf:

obj.reload_from(conf)

3. 调用Guarder实例检查

guarder=Guarder.create('antispam.ini')

def index():

if guarder.check(userdata):

pass

else:

#error

def admin_reload_guarder():

'''根据web请求运行时重载配置'''

import strategy

reload(strategy)

guarder.reload(conf)

示例配置文件:

#antispam.ini

[strategies]

inst=usercontent,userrate

[usercontent]

type=strategy.UserDupContent

init.comment_per_user_min=5

[userrate]

type=strategy.UserRate

init.content_send_per_user=5

以上能够完成的功能如下:

1. 隔离了策略代码,使用依赖注入的方式完成

2. 策略本身是duck typing,灵活扩充

3. 策略代码文件strategy.py不停止服务器热部署

当然,配置文件可以调整格式,直接用python代码写都可以