将CSV上传到Flask进行后台处理

时间:2013-05-17 01:39:51

标签: python file-upload csv flask

我希望使用Flask来托管单页网站,该网站允许用户上传将被解析并放入数据库的CSV。所有的数据库恶作剧都是完整的(通过另一个Python脚本中的SQLalchemy),一旦脚本可以访问CSV,我就可以解决所有问题,我只需要帮助就可以实现它。

以下是该方案:

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,我只是读到它很容易设置!

非常感谢!!

1 个答案:

答案 0 :(得分:1)

以下是基于cook book example处理web.py中文件上传的(非常简单的简化)示例(Flash示例,我的经验较少,看起来更简单):

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上)读取上传的文件并将其保存到指定的路径。