Forums

Flask static is driving me nuts

Flask is great, so far I've managed to serve basic pages, use templates for format and Bootstrap to make things look great. BUT! I've wasted eons trying to understand the dynamics of the static folder. Suppose my app goes and returns numbers I've computed elsewhere in python. I can easily return these via a dict that I feed to a template inside the templates folder.

Now suppose the dict also has the filenames of relevant output inside static/out, for instance static/out/file1.txt, static/out/file2.txt, how can I serve links to those files on my page? I've tried url_for, etc.

There's not really much we can do to help with such a general query, except point you at some docs: http://exploreflask.readthedocs.io/en/latest/static.html, http://flask.pocoo.org/docs/0.11/quickstart/#static-files. Also check that your generated html contains links to your static assets that correspond with where they are served.

Another option is to use the PythonAnywhere static files mapping on your web app so Flask doesn't serve your static assets. Docs here: http://help.pythonanywhere.com/pages/StaticFiles/

sergiolucerovera, is this what you're looking for:

from flask import send_from_directory

# Setup the flask app.
app = Flask(__name__, static_folder='static')

@app.route('/serve')
def serve_file():
    filename = "" # TODO: figure out your filename.
    return send_from_directory(app.static_folder, filename)

OK, I've managed to solve my problem.

import os
from pprint import pprint
from flask import Flask, render_template, url_for

def psum(p):
    return sum(pow(ix,-p) for ix in xrange(1,10000))

app = Flask(__name__)
APP_ROOT = os.path.dirname(os.path.abspath(__file__))   # refers to application_top
APP_STATIC = os.path.join(APP_ROOT, 'static')
URL_TEMPLATE = "<A HREF='%s'>link</A>"
psum_data = [(p,psum(p)) for p in xrange(1,10)]       # problem data

@app.route('/')
def start_page():
    return render_template('psumplot.html', data=psum_data)

@app.route('/plot', methods=['GET'])
def plot_page():
    filename = 'psum.txt'
    fullfilename = os.path.join(APP_STATIC, filename)
    pprint(psum_data, open(fullfilename,'w'))
    return URL_TEMPLATE %(url_for('static',filename=filename))

So I guess my next question is: what if I want to deploy this on a different server, not run by pythonanywhere? Is there something particular about the WSGI setup that I should observe?

That depends very much on what web application stack the other server was running. You'd probably need to set up some nginx or Apache configuration to specify where your static files were.