简体   繁体   English

无法正确提供烧瓶中的静态文件

[英]Can't properly serve static files in flask

I am trying to serve a static image to a css file using flask. 我正在尝试使用flask将静态图像提供给CSS文件。 I am using render_template() to to get the html file, and I have a static directory for my css and javascript. 我正在使用render_template()来获取html文件,并且我的CSS和javascript有一个静态目录。 My other image is loading, but the image that I am referencing from the css file is not working and I get his from the flask terminal: GET /static/static/res/typewriter.jpg HTTP/1.1" 404 我的其他图像正在加载,但是我从css文件引用的图像不起作用,并且从flask终端获取了该图像: GET /static/static/res/typewriter.jpg HTTP/1.1" 404

I tried typing in the path in my browser and it works fine 我尝试在浏览器中输入路径,但效果很好

This is how I am referencing the image since the CSS file is already in the static directory. 因为CSS文件已经在静态目录中,所以这就是我引用图像的方式。 background-image: url("/res/typewriter.jpg");

I hope there is an easy fix for this, especially since I am new to this stuff. 我希望对此有一个简单的解决方法,尤其是因为我是新手。 Thanks! 谢谢!

In your html file you should have this in the header: 在您的html文件中,您应该在标题中包含以下内容:

<link rel= "stylesheet" type= "text/css" href= "{{ url_for('static',filename='mainpage.css') }}"> 

... as long as your static directory is named static. ...,只要您的静态目录名为static。 In several of my Flask applications I am importing Bootstrap css like so: 在我的几个Flask应用程序中,我正在导入Bootstrap css,如下所示:

  <link rel=stylesheet type=text/css href="{{ url_for('static', filename='bootstrap.css') }}">

Ensure you are visiting http://127.0.0.1:5000 in your browser (unless you changed the default). 确保您正在浏览器中访问http://127.0.0.1:5000 (除非您更改了默认设置)。

Also here is a random example of how I serve images from the static directory: 这也是我如何从静态目录中投放图片的随机示例:

h1 class="display-3"> <img src="/static/title_welcome.png" alt="about"></h1>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM