【问题标题】:File Sharing Site in PythonPython 中的文件共享站点
【发布时间】:2011-02-23 10:30:29
【问题描述】:

我想设计一个简单的网站,一个人可以上传文件,然后将随机网址传递给某人,然后谁可以下载它。

此时,我有一个网页,有人可以在其中成功上传一个文件,该文件存储在我的网络服务器上的 /files/ 下。

python 脚本还会生成一个唯一的、随机的 5 个字母代码,该代码存储在识别文件的数据库中

我有另一个页面叫做retrieve,一个人应该去哪里,输入5个字母的代码,它应该会弹出一个文件框询问文件保存在哪里。

我的问题是:1)我如何检索文件以供下载?此时我的检索脚本,获取代码,获取文件在我的服务器上的位置,但我如何让浏览器开始下载?

2)如何阻止人们直接访问文件?我应该更改文件的权限吗?

【问题讨论】:

  • 这有点离题,但您可能应该生成一个散列(如 SHA1)并使用它而不是 5 个字母代码进行存储。这将防止同一文件的重复条目,并且是一种更强大的身份验证方法。

标签: python file-upload cgi


【解决方案1】:

您如何提供文件上传页面,以及如何让您的用户上传文件?
如果您使用 Python 的内置 HTTP 服务器模块,则应该没有任何问题。
无论如何,这是使用 Python 的内置模块完成文件服务部分的方式(只是基本思想)。

关于您的第二个问题,如果您首先使用这些模块,您可能不会问它,因为您必须明确提供特定文件。

import SocketServer
import BaseHTTPServer


class RequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):

    def do_GET(self):
        # The URL the client requested
        print self.path

        # analyze self.path, map the local file location...

        # open the file, load the data
        with open('test.py') as f: data = f.read()

        # send the headers
        self.send_response(200)
        self.send_header('Content-type', 'application/octet-stream') # you may change the content type
        self.end_headers()
        # If the file is not found, send error code 404 instead of 200 and display a message accordingly, as you wish.

        # wfile is a file-like object. writing data to it will send it to the client
        self.wfile.write(data)

        # XXX: Obviously, you might want to send the file in segments instead of loading it as a whole


if __name__ == '__main__':

    PORT = 8080 # XXX

    try:
        server = SocketServer.ThreadingTCPServer(('', 8080), RequestHandler)
        server.serve_forever()
    except KeyboardInterrupt:
        server.socket.close()

【讨论】:

  • 感谢您的回复。由于我刚刚开始学习python,我真的不明白这一点。我在我的机器上本地运行了这段代码,将 test.py 替换为 a5.pdf 并转到网址 127.0.0.1:8080。脚本提示下载文件,但下载了扩展名为 .dmz.part 的文件。如何让它下载整个文件?你能给我指点关于这个主题的好教程吗?
【解决方案2】:

您应该发送正确的 HTTP 响应,包含二进制数据并让浏览器对其做出反应。

如果你使用 Django,试试这个(我没有):

response = HttpResponse()
response['X-Sendfile'] = os.path.join(settings.MEDIA_ROOT, file.file.path)
content_type, encoding = mimetypes.guess_type(file.file.read())            
if not content_type:
    content_type = 'application/octet-stream'            
response['Content-Type'] = content_type            
response['Content-Length'] = file.file.size            
response['Content-Disposition'] = 'attachment; filename="%s"' % file.file.name
return response

来源:http://www.chicagodjango.com/blog/permission-based-file-serving/

【讨论】:

  • 感谢您的回复。我真的没有开始 django,所以不能说这是否可行。你能不能给我指出一个关于这个主题的好教程? urllib.urlretrieve 会有帮助吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-27
  • 1970-01-01
  • 1970-01-01
  • 2022-01-18
  • 2015-01-07
相关资源
最近更新 更多