开发者

Access files from web.py urls

I'm using web.py for a small project and I have files I want the user to be able to access in /files directory on the server. I can't seem to find how to retur开发者_JS百科n a file on a GET request so I can't work how to do this.

Exactly want to do essentially is:

urls = ('/files/+', 'files')

class files:

  def GET(self)

    #RETURN SOME FILE

Is there a simple way to return a file from a GET request?


Playing around I came up with this webpy GET method:

def GET(self):
    request = web.input( path=None )
    getPath = request.path
    if os.path.exists( getPath ):
        getFile = file( getPath, 'rb' )
        web.header('Content-type','application/octet-stream')
        web.header('Content-transfer-encoding','base64') 
        return base64.standard_b64encode( getFile.read( ) )
    else:
        raise web.notfound( )

Other respondants are correct when they advise you consider carefully the security implications. In my case we will include code like this to an administrative web service that will be (should be!) available only within our internal LAN.


You can read the contents of a file and stream them down to the user, but I don't believe that a file handle is serializable.

It would seem to be a potential security hole to allow users to access and modify files on the server or to copy files down to their own machine. I think you should reassess what you're trying to accomplish.


This is how I do it by using generator and not reading the whole file into memory:

    web.header("Content-Disposition", "attachment; filename=%s" % doc.filename)
    web.header("Content-Type", doc.filetype)
    web.header("Transfer-Encoding","chunked")
    f = open(os.path.join(config.upload_dir, doc.path, doc.filename), "rb")
    while 1:
        buf = f.read(1024 * 8)
        if not buf:
            break
        yield buf
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜