在OpenShift示例中使用Python 3.3
OpenShift最近出版了一本书,叫做《OpenShift入门》。这本书对刚开始接触的人来说是个不错的指南。
在第三章,他们展示了如何修改一个模板应用,让它使用Python 2.7和Flask。我们的需求是使用Python 3.3。
在第19页,wsgi.py文件中的一个修改是:execfile(virtualenv, dict(file=virtualenv))。在Python 3.x中,execfile这个函数已经被淘汰了。StackOverflow上有一些例子说明如何转换,但我不太清楚怎么把那些应用到这个情况中。
有没有人对这个问题有一些见解呢?
2 个回答
0
如果你在使用Python3的
这是我的
#!/usr/bin/python
from flaskapp import app as application
if __name__ == '__main__':
from wsgiref.simple_server import make_server
httpd = make_server('0.0.0.0', 5000, application)
# Wait for a single request, serve it and quit.
#httpd.handle_request()
httpd.serve_forever()
4
正如在这个问题中提到的,你可以用下面的代码替换掉这一行:
execfile(virtualenv, dict(__file__=virtualenv))
用下面的代码替换后:
exec(compile(open(virtualenv, 'rb').read(), virtualenv, 'exec'), dict(__file__=virtualenv))
我觉得把这个代码分成几个简单的部分会更好。此外,我们还应该使用上下文管理器来处理文件:
with open(virtualenv, 'rb') as exec_file:
file_contents = exec_file.read()
compiled_code = compile(file_contents, virtualenv, 'exec')
exec_namespace = dict(__file__=virtualenv)
exec(compiled_code, exec_namespace)
这样分开写也会让调试变得更简单(实际上是可能的)。我还没有测试过这个,但应该是可以工作的。