Python Tornado没有这样的文件或目录

时间:2016-01-27 00:54:17

标签: python json web path tornado

我使用Tornado使用python创建网站。我有一个包含字典列表的JSON文件(或者如果应用程序第一次运行时没有),我试图在向DB运行查询后插入一个新字典。

总之,我的问题是我运行的代码将数据插入到我的json文件中,并且在我通过运行我的python文件并在其末尾调用方法来测试它时工作正常。但是,当我运行我的Tornado服务器并通过单击un按钮调用我的Tornado请求处理程序中的方法时,我收到此错误“IOError:[Errno 2]没有这样的文件或目录”。我是Tornado的新手,所以我不知道问题可能是什么。以下是详细信息:

我的项目具有以下结构:

Project/
|-- connector/
|   |-- DBConnector.py
|
|-- data/
|   |-- history.json (does not exist when the app runs for the 1st time)
|
|-- web
|   |-- css
|   |-- fonts
|   |-- js
|   |-- views
|-- server.py

我的history.json文件可以为空,也可以包含字典列表,如下所示:

[
 {"a":"a", "b":"b", "c":"c", "d":"d"},
 {"e":"e", "f":"f", "g":"g", "h":"h"}
]

现在,我在我的DBConnector.py文件中包含的MyMySQLConnection类中有以下方法。此方法执行mysql select和insert查询,然后将包含所选值的字典追加到history.json JSON文件中:

class MyMySQLConnection():

    def insert_history_data(self, s_id):
        #MySQL Select occurs by s_id and result is used for insertion
        #MySQL insert occurs. j, k ,l, m are the same values as inserted.
        insert_dict = {"j":"j", "k":"k", "l":"l", "m":"m"
        if(os.path.isfile("../data/history.json")):
            try:
                with open("../data/history.json", "r") as f:
                    json_file = json.load(f)
                    json_file.append(insert_dict)
                    f.close()
                    with open('../data/history.json', 'w') as f:
                        f.write(json.dumps(json_file, indent=4))
                    return True
            except:
                print "Something went wrong (history.json existed)."
                return False
        else:
            try:
                f = file("../data/history.json", "w")
                f.close()
                with open('../data/history.json', 'a+') as outfile:
                    arr = []
                    arr.append(insert_dict)
                    json.dump(arr, outfile, indent=4)
                return True
            except:
                print "Something went wrong.(history.json did not existed)"
                return False

在我的DBConnection文件的末尾,我有以下代码(我没有包含数据库连接方法或查询,因为我测试了DB方法,它们工作正常):

my_con = MyMySQLConnection("user", "pwd")
result = my_con.insert_history_data()

因此,当我将DBConnector.py作为python脚本运行时,我只是在我的PyCharm IDE中使用运行选项而不是DBConnector.py,它运行得非常好。第一次运行它时,history.json文件在“'../data/history.json'”目录中创建,第一个字典被附加到它。下次我运行它时,每个字典都附加到存在于“../data/history.json”路径中的history.json文件中。

然而,当我运行我的服务器并通过单击我的Web界面中的按钮来调用该方法时,我收到以下错误(我必须删除try:except:我的代码中的标签以获取错误):

IOError: [Errno 2] No such file or directory: '../data/history.json'

错误由包含以下行的代码行生成:

f = file("../data/history.json", "w")

当文件存在时(我通过运行DBConnector.py python文件创建它)并且我调用该方法,我在同一行中得到相同的错误(因此,路径应该是问题)。

那么,如果通过将DBConnector.py类作为python脚本运行,代码完全正常,我为什么会收到此错误?我唯一的猜测是,在我的Tornado服务器处理程序中实例化的MyMySQLConnector类上调用我的方法时,Tornado在找到路径“../data/history.json”时遇到了问题,然而,这对我来说没有任何意义,因为我所有的我文件包含在同一个项目中。

这就是我启动我的Tornado服务器的方式:

if __name__ == "__main__":
    logging.log(logging.INFO, 'Deploying service...')
    app = tornado.web.Application([
        (r"/", MainHandler),
        (r"/add-translate", AddTransHandler),
        (r"/static/(.*)", tornado.web.StaticFileHandler,{"path": settings["static_path"]})
    ], **settings)
    app.listen("8888")

这是我的设置:

settings = {"template_path": os.path.dirname(__file__),
            "static_path": os.path.join(os.path.dirname(__file__),"web"),
            "debug": True
            }

这是我正在使用的处理程序:

class AddTransHandler(tornado.web.RequestHandler):
    def get(self):
        s_id= self.get_argument("s_id")
        #my_con is a MyMySQLConnection instance that another method initializes.
        global my_con
        answer = []

        if my_con is None:
            answer.append([{"connection": "False"}])
        else:
            result = my_con.insert_history_data(s_id)
            answer.append(result)
        logging.log(logging.INFO, "Sending insert result...")
        self.write(json.dumps(answer))

谢谢!

3 个答案:

答案 0 :(得分:1)

尝试使用文件的完整路径。将其添加到主目录:

CURRENT_ROOT = os.path.abspath(os.path.dirname(__file__))

这就是使用文件('name_file')的文件:

file_path = os.path.join(PROJECT_ROOT, 'data', 'history.json')

答案 1 :(得分:0)

从包结构的外观来看,您试图从history.json目录之外的上层目录中获取Project

f = file("data/history.json", "w")

Python将从代码的相对目录中获取这样的文件。

此方法或other应该有效。

答案 2 :(得分:0)

您应该在脚本中使用绝对路径,因为当您运行服务时,所有路径都相对于服务器文件。

因此,您可以在OS库中使用以下路径:

os.path.join(os.path.dirname(__file__),"../data/history.json")

希望有所帮助!