File Sharing Site in Python

[亡魂溺海] 提交于 2019-12-01 08:04:43

How do you serve the file-upload page, and how do you let your users upload files?
If you are using Python's built-in HTTP server modules you shouldn't have any problems.
Anyway, here's how the file serving part is done using Python's built-in modules (just the basic idea).

Regarding your second question, if you were using these modules in the first place you probably wouldn't have asked it because you'd have to explicitly serve specific files.

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

You should send the right HTTP Response, containing the binary data and making the browser react on it.

Try this (I haven't) if you're using 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

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!