Forums

works on localhost but not on pythonanywhere

hello and I hope this email finds you well given the health crisis! I have a very strange problem. I have a function, extractImages(folder) which returns a list of image:

def extractImages(folder):
# variable to store links to the images in the folder
images = []
if os.path.exists(folder):
    entries = os.scandir(folder)
    for entry in entries:
        #print(entry)
        if entry.is_file():
            filename = entry.name
            if allowed_file(filename):
                filepath = os.path.join("/" + folder, filename)
                images.append(os.path.normpath(filepath))
return images

The have the home endpoint that calls this function:

@app.route('/', methods=['GET'])
@app.route('/index', methods=['GET'])
@app.route('/home', methods=['GET'])
def home():
    images = {
        'carousel': extractImages(CAROUSEL_FOLDER),
        'gallery': extractImages(GALLERY_FOLDER)
    }
    return render_template('home.html', title='Home', images=images)

The template:

{% block content %}
<p>Carousel images: {{ images['carousel'] }}</p>
<p>Gallery images: {{ images['gallery'] }}</p>

<img src="{{ images['gallery'][0] }}" \>

{% endblock content %}

On localhost, this works great: <p>Carousel images: ['\static\images\carousel\slide-1.jpg', '\static\images\carousel\slide-2.jpg', '\static\images\carousel\slide-3.jpg', '\static\images\carousel\slide-4.jpg']</p> <p>Gallery images: ['\static\images\gallery\1.jfif', '\static\images\gallery\10.jfif', '\static\images\gallery\11.jfif', '\static\images\gallery\12.jfif', '\static\images\gallery\13.jfif', '\static\images\gallery\14.jfif', '\static\images\gallery\15.jfif', '\static\images\gallery\16.jfif', '\static\images\gallery\2.jfif', '\static\images\gallery\3.jfif', '\static\images\gallery\4.jfif', '\static\images\gallery\5.jfif', '\static\images\gallery\6.jfif', '\static\images\gallery\7.jfif', '\static\images\gallery\8.jfif', '\static\images\gallery\9.jfif']</p>

<p>But when I deploy it to pythonanywhere, the images dictionary which i passed to the template is empty!!! Please help!</p>

You're probably using relative paths without paying attention to what the working directory is. See http://help.pythonanywhere.com/pages/NoSuchFileOrDirectory/ for more details.

I doubt this is the problem because the extractImages() function does return the same list of links when I run it from PYTHONANYWHERE command line:

    extractImages(CAROUSEL_FOLDER) * Serving Flask app "__main__" (lazy loading)
   * Environment: production
    WARNING: This is a development server. Do not use it in a production deployment.
    Use a production WSGI server instead.
   * Debug mode: on
    Traceback (most recent call last):
   File "/home/najibfahs/testing/app.py", line 414, in <module>
    app.run(debug=True)
   File "/usr/lib/python3.8/site-packages/flask/app.py", line 990, in run
    run_simple(host, port, self, **options)
   File "/usr/lib/python3.8/site-packages/werkzeug/serving.py", line 988, in run_simple
    s.bind(server_address)
  OSError: [Errno 98] Address already in use
 >>> extractImages(CAROUSEL_FOLDER)
 ['/static/images/carousel/slide-2.jpg', '/static/images/carousel/slide-4.jpg', '/static/images/carousel/slide-1.jpg', '/static/images/carousel/slide-3.jpg']
 >>> extractImages(GALLERY_FOLDER)
   ['/static/images/gallery/5.jfif', '/static/images/gallery/14.jfif', '/static/images/gallery/7.jfif', 
   '/static/images/gallery/3.jfif', '/static/images/gallery/2.jfif', '/static/ima
  ges/gallery/1.jfif', '/static/images/gallery/4.jfif', '/static/images/gallery/13.jfif', '/static/images/gallery/10.jfif', 
 '/static/images/gallery/6.jfif', '/static/images/gallery/
 16.jfif', '/static/images/gallery/8.jfif', '/static/images/gallery/15.jfif', '/static/images/gallery/12.jfif', 
 '/static/images/gallery/9.jfif', '/static/images/gallery/11.jfif']
 >>>

So i do get the desired output from the function when executed on pythonanywhere. but for some reason, i dont get the output from the home endpoint.

When you run it in the console, you have cd'd into a specific directory. That is what sets the working directory. If you are using relative paths and you have not set the working directory in your web app to the correct directory, then you will have this problem.

@Glenn After my 2nd post (response to the first reply), I did visit the link you provided (http://help.pythonanywhere.com/pages/NoSuchFileOrDirectory/). You were right! That fixed my issue. instead of checking the relative path of the folder passed to the extractImages(folder) function, I modified to become an absolute path:

abspath = os.path.join(os.path.dirname(os.path.abspath(__file__)), folder)

So the extractImages function became:

def extractImages(folder):
# variable to store links to the images in the folder
images = []
#use below abspath for localhost
#abspath = folder

#use below abspath for deployed version on python anywhere
abspath = os.path.join(os.path.dirname(os.path.abspath(__file__)), folder)
print(abspath)

if os.path.exists(abspath):
    entries = os.scandir(abspath)
    for entry in entries:
        #print(entry)
        if entry.is_file():
            filename = entry.name
            if allowed_file(filename):
                filepath = os.path.normpath(os.path.join(abspath, filename))
                print(filepath)
                images.append(filepath)
return images

This also explains why my upload forms are failing! thanks a lot!

Excellent, glad we could help!

There is a small error in the code.<br /> This line:

filepath = os.path.normpath(os.path.join(abspath, filename))

should be:

filepath = os.path.normpath(os.path.join(folder, filename))