Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask: Want to import file of helper functions

Tags:

python

flask

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

like image 610
anon_swe Avatar asked Jul 11 '15 20:07

anon_swe


People also ask

How do I import a function into a Flask?

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 are helper functions in Python?

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.

How do you run a function in Flask?

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.


2 Answers

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.

like image 56
cloudcrypt Avatar answered Sep 24 '22 22:09

cloudcrypt


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)
like image 34
Olexander Yermakov Avatar answered Sep 22 '22 22:09

Olexander Yermakov