近來想在服務端架設WSGI + PyV8去自動解析JavaScript代碼,然後傳回解析後的資料給用戶端。但是發現,在nginx配置後,用戶端一請求,服務端的python腳本自動崩潰。
見代碼:
def myapp(environ, start_response):
res = "OK"
header = [('Content-Type', 'text/plain')]
jsfile= open("D:\ots\python\\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并非是線程安全的,是以在多線程環境下要加入全局鎖。
然後重新寫了一下代碼,加入了全局鎖,
PyV8.JSLocker(),問題得以解決。見如下代碼:
def myapp(environ, start_response):
res = "OK"
header = [('Content-Type', 'text/plain')]
jsfile= open("D:\ots\python\\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()