Forums

how to call myfunc() from flask?

I have working flask routes to function handlers that correctly return html by extending another template and I want to call my own program from within one of these function handlers. Where should I put my program files in relation to the site directory for this to work on pythonanywhere and what is the correct way to call my program from within the function handler in the templates folder of the flask site directory (my program returns str) ?

{% extends "index.html" %}
{% block content %}
    <div class="jumbo">
        <p> {% print('baz') %} </p>
    </div>
{% endblock %}

For instance, baz is rendered correctly but I can't get the string returned from myfunc() to do this. How do I call myfunc() so it gets into this block? Is there any way to do this??? Where should mymodule.py be in my directory , where should it be imported? in my routes.py file? That doesn't seem to work... I'm lost ! sigh ....

well... the good news is I figured out my mistake and it works in the local env but the exact same files, directories, etc. don't work when uploaded here. in case it helps to understand my question, the answer locally was to import mymodule (includes myfunc) in routes.py and then call myfunc() in the route passing str to the function handler which includes it in the block with this {{ foo }} or {% print(foo) %}

@app.route('/whatever')
def whatever():
    foo = myfunc()
    return render_template('whatever.html', foo=foo)

This is what works locally but not when uploaded even though all the associated files are all in the root of mysite dir along with routes.py Any ideas how I can make this work? I posted this in error from my new paid account, sorry for the confusion

A couple of things to check:

  • did you hit "reload" after you made changes?
  • are you quite sure all the files + folders are in the same places as they are on your PC
  • is there anything in your error logs?

ahh... my problem was

f = open('filename.txt', 'r')

which needed to be

f = open('/home/username/mysite/filename.txt', 'r')

You can't assume the current directory but need to specify it? Is that because of virtualization or something?

glad you figured it out! yep, fully-specified paths are always a good bet.

One trick is to specify you path relative to the path of the current file, which you can do using python's magic __file__ builtin:

import os
my_folder = os.path.abspath(os.path.dirname(__file__))
parent_folder = os.path.join(my_folder, '..')
 #etc