1

我希望使用 Flask 来托管一个单页网站,该网站将允许用户上传一个 CSV,该 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,我刚刚读到它很容易设置!

非常感谢!!

4

1 回答 1

2

这是一个(非常简单的)基于食谱示例在 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 上)读取上传的文件并将其保存到指定路径。

于 2013-05-17T16:54:25.870 回答