簡體   English   中英

Python Tornado沒有這樣的文件或目錄

[英]Python Tornado No such file or directory

我正在使用Tornado使用python創建一個網站。 我有一個包含字典列表的JSON文件(如果應用程序是第一次運行,則不包含該列表),並且在對數據庫運行查詢后,我試圖向其中插入新字典。

總而言之,我的問題是我運行了一個代碼,將數據插入到json文件中,並且當我通過運行python文件並在其末尾調用該方法進行測試時,可以完美地工作。 但是,當我運行Tornado服務器並通過單擊一個按鈕在Tornado請求處理程序中調用該方法時,出現此錯誤“ IOError:[Errno 2] No such file or directory”。 我是龍卷風的新手,所以我不知道可能是什么問題。 詳細信息如下:

我的項目具有以下結構:

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"}
]

現在,在我的MyMySQLConnection類中包含以下方法,該類包含在DBConnector.py文件中。 此方法執行mysql選擇並插入查詢,然后將包含所選值的字典追加到我的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文件的末尾,我有以下代碼(在測試數據庫方法時,我沒有包括數據庫連接方法或查詢,它們可以正常工作):

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

因此,當我以python腳本的形式運行DBConnector.py時,就是我在PyCharm IDE中只是在DBConnector.py上使用了運行選項,所以運行得很好。 首次運行該文件時,將在“'../data/history.json'”目錄中創建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”時遇到問題,但是,這對我來說沒有任何意義文件包含在同一項目中。

這是我初始化龍卷風服務器的方式:

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))

謝謝!

嘗試對文件使用完整路徑。 將此添加到主目錄:

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

然后將其歸檔到您使用file('name_file')的位置

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

從包結構的外觀來看,您試圖從Project目錄之外的上層目錄中獲取history.json

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

Python將從代碼的相對目錄中抓取此類文件。

此方法或一種方法都應該起作用。

您應該在腳本中使用絕對路徑,因為在運行服務時,所有路徑都是相對於服務器文件的。

因此,您可以在OS庫中使用以下路徑:

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

希望有幫助!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM