基本烧瓶:添加有用的功能

bcl*_*man 2 python flask

我已经编写了一个在终端中可用的python脚本,并使用Flask将其移植到Web上。我已经通过教程的部分消失(具体为:http://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-i-hello-world

我在将我使用的Python脚本中使用的所有功能放置在何处感到困难。author()使用此代码获得基本视图:

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)
Run Code Online (Sandbox Code Playgroud)

问题是我没有一个要调用的函数。我有15个左右,而且好像Flask只允许我为每个视图调用一个函数。所以我不太确定我的“主”函数将要调用的所有辅助函数都放在哪里。

以作者的示例代码为例。如果我有一个getPosts()返回后对象数组的函数,该放在哪里?

即使允许我将其放置在路由的主要功能下(无论如何我也认为不允许这样做),看来这样做很糟糕。

编辑:

这是我的views.py文件:

  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)
Run Code Online (Sandbox Code Playgroud)

Eli*_*ICA 5

您不局限于每个视图一个功能-您可以拥有任意数量的视图。

from flask import Flask
app = Flask(__name__)

def f():
    ...
def g():
    ...
@app.route('/index')
def index():
    <here you can use f and g>
    ...
Run Code Online (Sandbox Code Playgroud)

函数不需要与视图相对应-只有@app.route(...)装饰器可以做到这一点。

如果您有大量其他功能,则将它们放置在另一个文件中也可以。然后,您可以import文件并按上述方式使用它们。