PyV8在服务端运行自动崩溃问题 注意的是PyV8并非是线程安全的,因此在多线程环境下要加入全局锁。
近来想在服务端架设WSGI + PyV8去自动解析JavaScript代码,然后返回解析后的数据给客户端。但是发现,在nginx配置后,客户端一请求,服务端的python脚本自动崩溃。
见代码:
def myapp(environ, start_response): res = "OK" header = [('Content-Type', 'text/plain')] jsfile= open("D:otspython\getsign.js", "rb"); ctxt=PyV8.JSContext() ctxt.__enter__() ctxt.eval(jsfile.read().encode('utf-8')) getSign=ctxt.locals.getsign res = getSign() jsfile.close() res = res.encode('utf-8') start_response('200 OK',header) return res if __name__ == '__main__': WSGIServer(myapp,bindAddress=('127.0.0.1',8011)).run()
然后百思不得其解,一直在网上寻找资料,一直得不到具体的解决方案。后来重新看了PyV8的文档,发现了这样的一个重大问题:
然后重新写了一下代码,加入了全局锁,
PyV8.JSLocker(),问题得以解决。见如下代码:
def myapp(environ, start_response): res = "OK" header = [('Content-Type', 'text/plain')] jsfile= open("D:otspython\getsign.js", "rb"); with PyV8.JSLocker():'''加入全局锁机制''' ctxt=PyV8.JSContext() ctxt.__enter__() ctxt.eval(jsfile.read().encode('utf-8')) getSign=ctxt.locals.getsign res = getSign() ctxt.leave()'''退出全局锁''' jsfile.close() res = res.encode('utf-8') start_response('200 OK',header) return res if __name__ == '__main__': WSGIServer(myapp,bindAddress=('127.0.0.1',8011)).run()