Flask 静态文件

Web应用程序通常需要一个静态文件,例如支持显示网页的JavaScript文件或CSS文件。 通常,可以通过配置Web服务器提供这些服务,但在开发过程中,这些文件将从包中的静态文件夹或模块旁边提供,它将在应用程序的/static上提供。

使用特殊的端点“静态”来为静态文件生成URL。

在以下示例中,index.html中的HTML按钮的OnClick事件调用hello.js中定义的javascript函数,该函数在Flask应用程序的URL => / 中呈现。

#Filename:example.py#Copyright:2020ByNhooo#Authorby:www.shangmayuan.com#Date:2020-08-08fromflaskimportFlask,render_templateapp=Flask(__name__)@app.route("/")defindex():returnrender_template("index.html")if__name__=='__main__':app.run(debug=True)

index.html 中的HTML脚本如下所示。

#Filename:example.py#Copyright:2020ByNhooo#Authorby:www.shangmayuan.com#Date:2020-08-08<html><head><scripttype="text/javascript"src="{{url_for('static',filename='hello.js')}}"></script></head><body><inputtype="button"onclick="sayHello()"value="SayHello"/></body></html>

文件: hello.js 中定义包含 sayHello() 函数。

#Filename:example.py#Copyright:2020ByNhooo#Authorby:www.shangmayuan.com#Date:2020-08-08functionsayHello(){alert("HelloWorld")}
编辑于2024-05-20 12:12