2013-05-17 312 views
0

我正在尋找使用Flask來託管單頁網站,該網站允許用戶上傳將被解析並放入數據庫的CSV。所有的數據庫參數都是完整的(通過另一個Python腳本中的SQLalchemy),一旦腳本訪問了CSV,我就可以完成所有工作,我只需要幫助獲取它。將CSV上傳到Flask進行後臺處理

這裏的情景:

1. User directs browser at URL (probably something like 
    http://xxx.xxx.xxx.xxx/upload/) 
2. User chooses CSV to upload 
3. User presses upload 
4. File is uploaded and processed, but user is sent to a thank you page while our 
    script is still working on the CSV (so that their disconnect doesn't cause the 
    script to abort). 

如果CSV將保留在服務器上(事實上,它可能較好,因爲我們就會有一個備份,以防處理偏差去)

這是很酷我想我想要的是一個監聽套接字的守護進程,但是我對此並沒有真正的經驗,也不知道從哪裏開始配置它或設置Flask。

如果你認爲Flask以外的其他框架會比較容易,那麼一定要讓我知道,我沒有和Flask綁在一起,我剛纔讀到它很容易設置!

非常感謝!

+0

Flask和web.py都會添加偵聽端口上傳入連接的代碼。只要腳本正在運行,您的網站就會運行。 –

回答

1

下面是根據cook book example在web.py處理文件上傳(非常輕微簡化的)例子(閃存例子,我有經驗較少用,看起來更容易):

import web 

urls = ('/', 'Upload') 

class Upload: 
    def GET(self): 
     web.header("Content-Type","text/html; charset=utf-8") 
     return """ 
       <form method="POST" enctype="multipart/form-data" action=""> 
       <input type="file" name="myfile" /> 
       <br/> 
       <input type="submit" /> 
       """ 

    def POST(self): 
     x = web.input(myfile={}) 
     filedir = '/uploads' # change this to the directory you want to store the file in. 
     if 'myfile' in x: # to check if the file-object is created 
      filepath=x.myfile.filename.replace('\\','/') # replaces the windows-style slashes with linux ones. 
      filename=filepath.split('/')[-1] # splits the and chooses the last part (the filename with extension) 
      fout = open(filedir +'/'+ filename,'wb') # creates the file where the uploaded file should be stored 
      fout.write(x.myfile.file.read()) # writes the uploaded file to the newly created file. 
      fout.close() # closes the file, upload complete. 
     raise web.seeother('/') 

if __name__ == "__main__": 
    app = web.application(urls, globals()) 
    app.run() 

這呈現上傳表單,然後(在POST上)讀取上傳的文件並將其保存到指定路徑。