Search code examples
web2pypythonanywhere

My web2py application cannot find a file on pythonanywhere


My web2py application cannot find a file on pythonanywhere.

Controller:

def RA_download():
    import os
    path = os.path.join(request.folder,"uploads","ra.txt")
    return dict(path=path)

View

<a href="{{=path}}" download>Download ra.txt</a>

{{=BEAUTIFY(response._vars)}}

The file exists

enter image description here

But when I click on the link. it says "no file"

enter image description here

Here is the link to the application

http://speakertgorobots.pythonanywhere.com/MCEdit/default/RA_download


Solution

  • web2py does not serve files by specifying the operating system filepath as the URL. Rather, you must either put the file in the application's /static folder (and generate a URL relative to that folder) or serve the file via a controller.

    If you place the file in the root of the /static folder, the link would look like this:

    <a href="{{=URL('static', 'ra.txt')}}" download>Download ra.txt</a>
    

    If you want to leave the file in the /uploads folder (or some other location), you need to create a controller to serve it. For example:

    import os
    def serve_ra_file():
        return response.stream(os.path.join(request.folder, 'ra.txt'), attachment=True)
    

    and the link would be:

    <a href="{{=URL('default', 'serve_ra_file')}}" download>Download ra.txt</a>