I'm writing a porting a basic python script and creating a similarly basic Flask application. I have a file consisting of a bunch of functions that I'd like access to within 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'd have access to all of the functions from my original script and make use of them within my getRankingsList()
function. I've googled around and can't seem to sort out how to do this, however.
Any idea
You can use the import statement to import functions from other files into the main file in the Flask. You can also use the 'from' statement with the 'import' statement to import a specific function from other files into your main flask file.
What is a helper function in Python? A helper function is a function that performs part of the computation of another function following the DRY (Don't repeat yourself) concept.
Debug modeA Flask application is started by calling the run() method. However, while the application is under development, it should be restarted manually for each change in the code. To avoid this inconvenience, enable debug support. The server will then reload itself if the code changes.
Simply have another python script file (for example helpers.py
) in the same directory as your main flask .py file.
Then at the top of your main flask file, you can do import helpers
which will let you access any function in helpers by adding helpers.
before it (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 the functions directly in your code.
Just import your file as usual and use 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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With