我制作了一个非常简单的 Flask 应用程序,它从 .html 文件中读取其内容。该应用程序除样式外均有效。奇怪的是,我的内联 css 代码有效,但外部样式表无效。我检查了语法,它应该可以工作。 Flask 是否以某种方式阻止读取 .css 文件?
可以查看文件夹中的文件here .这 3 个文件都在同一个文件夹中。
最佳答案
您的代码没有使用 Flask 提供文件服务,它只是读取文件并将其发送到浏览器 - 这就是 URL 无法正常工作的原因。
您需要从方法中渲染文件。
首先在您的.py
文件所在的目录中创建一个templates
文件夹,并将您的html 文件移动到该文件夹中。创建另一个名为 static
的文件夹,并将您的样式表放在该文件夹中。
你应该有
/flaskwp1.py
/templates
webcode.html
/static
webcodestyle.css
然后,调整你的代码:
from flask import Flask, render_template
app = Flask('flaskwp1')
# webcode = open('webcode.html').read() - not needed
@app.route('/')
def webprint():
return render_template('webcode.html')
if __name__ == '__main__':
app.run(host = '0.0.0.0', port = 3000)
编辑webcode.html
:
<link rel="stylesheet"
type="text/css"
href="/static/webcodestyle.css"/>
关于python - 从 .html 文件读取内容的简单 Flask 应用程序。外部样式表被阻止?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10372883/