Flask: want to import helper function file
I am writing porting a basic python script and creating a similar basic Flask application. I have a file consisting of many functions that I would like to have in my Flask application.
Here's what I have so far for my views:
from flask import render_template
from app import app
def getRankingList():
return 'hey everyone!'
@app.route("/")
@app.route("/index")
def index():
rankingsList = getRankingsList()
return render_template('index.html', rankingsList = rankingsList)
if __name__ == '__main__':
app.run(debug=True)
Ideally, I will have access to all functions from my original script and use them in my function getRankingsList()
. I've searched google and don't seem to figure out how to do this.
Any idea
source to share
Just add another python script file (for example helpers.py
) in the same directory as your main flash .py file. Then at the top of your main stick file you can do import helpers
which will allow you to access any function in the helpers by adding before it helpers.
(for example helpers.exampleFunction()
). Or you can do from helpers import exampleFunction
and use exampleFunction()
directly in your code. Or from helpers import *
to import and use all functions directly in your code.
source to share
Just import the file as usual and use the following functions from it:
# foo.py
def bar():
return 'hey everyone!'
And in the main file:
# main.py
from flask import render_template
from app import app
from foo import bar
def getRankingList():
return 'hey everyone!'
@app.route("/")
@app.route("/index")
def index():
rankingsList = getRankingsList()
baz = bar() # Function from your foo.py
return render_template('index.html', rankingsList=rankingsList)
if __name__ == '__main__':
app.run(debug=True)
source to share