我正在构建一个Web应用程序,用户应在其中放置一些数字,服务器将计算一些函数并生成一些图。计算和绘图在单独的模块(* .py文件)中进行。 现在的问题是将它们集成在一起。
让我说我的计算发生在compute.py和plotting.py中,
所以我必须将它们导入为:
import calculate
import plotting
根据用户给我的输入内容,我必须进行计算和绘图,因此一开始我会定义一个用于执行此操作的函数
def calculation(a,b)
#do something and
#save the plots
#and give me the result
然后是我的烧瓶:
app = Flask(__name__)
if __name__ == '__main__':
app.run(debug=True,port=8080)
calculation(a,b)
但是有计算功能,从不运行。但是Flask可以正常运行,并且还可以呈现我的其他html页面,但是计算功能永远无法运行。
似乎是什么问题?此外,我发现在启动flask应用程序时,print()函数也不起作用。
答案 0 :(得分:3)
app.run
会阻塞。您必须事先通过烧瓶路径调用该函数或在后台调用该函数。
答案 1 :(得分:0)
您需要从应用路由中调用该函数。例如:
string filename = "MyFile.txt"; // Make this dynamic from the actual file
byte[] filedata = System.IO.File.ReadAllBytes(filepath);
string contentType = MimeMapping.GetMimeMapping(filepath);
var contentDisposition = new System.Net.Mime.ContentDisposition
{
FileName = filename,
Inline = true
};
Response.AppendHeader("Content-Disposition", contentDisposition.ToString());
return File(filedata, contentType);
为方便起见,应将其放在您的主应用脚本中。
如果您真的想要按照自己的方式进行操作,则@app.route('/calculate')
def calculation(a,b)
#do something and
#save the plots
#and give me the result
return
应该在calculation(a,b)
之上运行,但显然会返回一些内容,以便可以在应用程序的其他地方使用。但是结果无法传递到app.run()
。
答案 2 :(得分:0)
如上所述,app.run()
运行一个应用程序,启动后没有任何代码。
此外,您的代码没有多大意义。如您所说,您希望用户能够进行一些计算。因此,您可能希望他或她输入一些数据。启动应用程序时您无法这样做。
因此,正如 smallpants 所说,您想要创建一个页面,用户可以与之交互。 看起来可能像这样(使用 smallpants 答案):
@app.route('/calculate')
def calculation()
a = 1
b = 2
return template(result.html, result=a+b)
-但此处用户无法输入任何内容。
所以,也许像这样:
@app.route('/calculate/<int:a>/<int:b>')
def calculation(a,b)
return template(result.html, result=a+b)
-在这里用户可以向url输入数据。
或者页面形式(我建议flask-wtforms)
为了使您的应用稍微MVC,我建议您将页面输入(应该是表格,url参数...),然后从{{ 1}}文件。
学习Flask祝您好运!