Python 基本功能:添加有用的功能
我已经编写了一个在终端中工作的python脚本,并正在使用Flask将其移植到web。我已经阅读了一部分教程(特别是:Python 基本功能:添加有用的功能,python,flask,Python,Flask,我已经编写了一个在终端中工作的python脚本,并正在使用Flask将其移植到web。我已经阅读了一部分教程(特别是:http://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-i-hello-world) 我正在努力将我在Python脚本中使用的所有函数放在哪里。作者()将此代码用于基本视图: def index(): user = {'nickname': 'Miguel'} # fake user po
http://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-i-hello-world
)
我正在努力将我在Python脚本中使用的所有函数放在哪里。作者()将此代码用于基本视图:
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)
问题是我没有一个函数可以调用。我有15个左右,看起来Flask只允许我在每个视图中调用一个函数。所以我不确定我的“main”函数将调用的所有助手函数都放在哪里
以作者的示例代码为例。如果我有一个返回post对象数组的函数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)
每个视图不局限于一个函数——可以有任意多个函数
from flask import Flask
app = Flask(__name__)
def f():
...
def g():
...
@app.route('/index')
def index():
<here you can use f and g>
...
从烧瓶导入烧瓶
app=烧瓶(名称)
def():
...
def g():
...
@应用程序路径(“/index”)
def index():
...
函数不需要与视图相对应——只有@app.route(…)
装饰器才能做到这一点
如果您有大量其他函数,那么将它们放在另一个文件中也不会有什么坏处。然后,您可以导入文件,并如上所述使用它们。好的,因此我将它们放在我的应用程序文件夹中的一个单独文件中(称为“helpfulffunctions.py”)。我的“views.py”文件顶部有“from app import helpfulffunctions”。然后,在索引中,我有一个名为“processGender(mainURL,genderTeam)”的函数,mainURL在helpfulffunctions.py中定义,我为genderTeam传入了一个字典。即便如此,我还是得到了“NameError:未定义全局名称'processGender'”…有什么想法吗?再次感谢!当我定义一个基本函数时,我会遇到类似的错误(正如你在上面的回答中所做的那样)。当我将其结果值保存到index()内的变量中时,会出现“全局名称‘user’is not defined”错误……我将助手放入一个类中,导入并实例化该类,并在主脚本中使用它。使用helpfulffunctions.py和flask主脚本更新代码,以查看问题所在。@b外行您的文件结构是什么?也就是说,你有什么
.py
文件,它们的名称是什么,什么导入了什么?@EliRose我有squashScraper作为我的主文件夹,其中有文件夹app、flask、my_p3_env、tmp和file run.py。在appfolder中,我有文件夹pycache、static、模板和文件helpfulffunctions.py和views.py。在FolderFlask中,我有文件夹bin、include、lib和文件pyvenv.cfg。在views.py中,我有[参见更新的问题]