Basic Flask: Adding Helpful Functions
Question: I've written a python script that works in terminal and am porting it to the
web using Flask. I've gone through parts of a tutorial (specifically:
`http://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-i-hello-
world`)

I'm struggling a bit with where to put all the functions I use in my Python
script. The author () uses this code for a basic view:

    
    
    def index():
        user = {'nickname': 'Miguel'}  # fake user
        posts = [  # fake array of posts
            { 
                'author': {'nickname': 'John'}, 
                'body': 'Beautiful day in Portland!' 
            },
            { 
                'author': {'nickname': 'Susan'}, 
                'body': 'The Avengers movie was so cool!' 
            }
        ]
        return render_template("index.html",
                               title='Home',
                               user=user,
                               posts=posts)
    

The problem is I don't have one function to call. I have 15 or so and it looks
like Flask only lets me call one function per view. So I'm not really sure
where to put all the helper functions that my "main" function will call.

Take the author's example code. If I had a function `getPosts()` that returns
an array of post objects, where would I put this?

Even if I'm allowed to put it under the route's main function (which I don't
think is allowed anyway), it seems like poor organization to do that.

Edit:

Here's my views.py file:

    
    
      1 from flask import Flask
      2 app = Flask(__name__)
      3 from flask import render_template
      4 from app import app
      5 from app import helpfulFunctions
      6
      7 def testFunction():
      8     return 5;
      9
     10 @app.route('/')
     11 @app.route('/index')
     12 def index():
     13     #allPlayers = processGender(mainURL, menTeams)
     14     myNum = testFunction()
     15     return render_template('index.html', title = 'Home', user = user)
    


Answer: You're not restricted to one function per view -- you can have as many as you
want.

    
    
    from flask import Flask
    app = Flask(__name__)
    
    def f():
        ...
    def g():
        ...
    @app.route('/index')
    def index():
        <here you can use f and g>
        ...
    

Functions don't need to correspond to views -- only the `@app.route(...)`
decorator makes it do that.

If you have a large number of other functions, it couldn't hurt to put them in
another file. Then you can `import` the file and use them as above.

