python - 从 .html 文件读取内容的简单 Flask 应用程序。外部样式表被阻止?

标签 python css flask

我制作了一个非常简单的 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/

相关文章:

javascript - jQuery leaveNotice 插件和 Internet Explorer

python - ImportError : No module named site. Flask + uWSGI +virtualenv

jquery - 在 Flask 中使用 jQuery 自动完成

python - 使用 Nginx+uWSGI 在 Flask 中提供动态媒体

python - XGBRegressor 评分方法返回奇怪的值

python - 属性错误: 'pygame.Rect' object has no attribute 'rect' error when doing collision

css - 是否有根据 css 生成图像 Sprite 的繁重任务?

python - Scipy:Hermite 函数与正交权重的集成

python - 值(value)不相加

javascript - 如何在网站上制作 "Scroll further down"按钮?