使用twisted.web服务器导入问题

Car*_*ers 1 python twisted twisted.web

我刚刚开始使用twisted.web,我在将Python模块导入.rpy脚本时遇到了麻烦.

C:\py\twisted\mysite.py,我有这个:

from twisted.web.resource import Resource
from twisted.web import server

class MySite(Resource):
    def render_GET(self, request):
        request.write("<!DOCTYPE html>")
        request.write("<html><head>")
        request.write("<title>Twisted Driven Site</title>")
        request.write("</head><body>")
        request.write("<h1>Twisted Driven Website</h1>")
        request.write("<p>Prepath: <pre>{0}</pre></p>".format(request.prepath))
        request.write("</body></html>")
        request.finish()
        return server.NOT_DONE_YET
Run Code Online (Sandbox Code Playgroud)

C:\py\twisted\index.rpy,我有这个:

import mysite
reload(mysite)

resource = mysite.MySite()
Run Code Online (Sandbox Code Playgroud)

twistd -n web --port 8888 --path C:\py\twisted在命令提示符下运行,服务器启动成功.但是当我请求时,localhost:8888我得到了一个源自ImportError的(巨大的)堆栈跟踪:

<type 'exceptions.ImportError'>: No module named mysite

我可以从解释器导入模块,如果我只是index.rpy作为python脚本执行,我不会得到导入错误.关于这个主题的文档有点模糊,它只是说"但是,在Python模块中定义Resource子类通常是一个更好的主意.为了使模块中的更改可见,您必须重新启动Python进程,或重新加载模块:"(从这里开始).

有谁知道这样做的正确方法?

Jea*_*one 5

简短回答:你需要设置PYTHONPATH来包含C:\py\twisted.

答案很长......

一个RPY脚本基本上只是一些Python代码,就像任何其他的Python代码.因此,rpy脚本中的导入就像在任何其他Python代码中导入一样.对于最常见的情况,这意味着sys.path按顺序逐个访问目录,如果.py找到与导入名称匹配的文件,则该文件用于定义模块.

sys.path主要是从静态定义填充,包括C:\ Python26\Lib \和PYTHONPATH环境变量.但是,还有一件值得了解的事情.当您运行"python"时,当前工作目录将添加到前面sys.path.当你运行"python C:\ foo\bar\baz.py",C:\foo\bar\' is added to the front ofsys.path . But when you run "twistd ...", nothing useful is added tosys.path`时.

最后一个行为可能解释了为什么如果直接运行rpy脚本,或者如果运行python并尝试以交互方式导入模块,但在使用twistd时失败,则测试工作原因.当您从以twistd开头的服务器运行rpy脚本时,添加C:\py\twistedPYTHONPATH环境变量应该使模块可导入.