Images in CSS don't load with Flask - python

I started out with the frontend (HTML, CSS) of my project. Then I made a Flask file containing the following code:
from flask import Flask, render_template
app = Flask(__name__)
#app.route("/", methods=["GET"])
def index():
return render_template('index.html')
if __name__ == '__main__':
port = int(5000)
app.run(host='0.0.0.0', port=port, debug=True)
index.HTML links to the CSS like so:
<link rel="stylesheet" type="text/css" href="/static/style.css">
I created the div like so:
<div class="header-container">
<div id="hero-overlay"></div>
</div>
and in the CSS I call on an image like so:
.header-container {
background-image: url('IMAGENAMEHERE.jpg');
width: 100%;
height: calc(100vh / 9 * 7);
top: 10px;
background-size: cover;
background-repeat: no-repeat;
background-position: center;
position: absolute;
z-index: -1000;
Since the CSS is in project/static and the image is in project/static/images I also tried:
background-image: url('images/IMAGENAMEHERE.jpg');
My folder layout is like this (MAC):
/project
project.py
/project/static
style.css
/project/static/images
contains the image
/project/templates
index.html
I'm very new to flask. This is my first attempt at building a web app.
Thank you!
EDIT================
Also tried:
Mapstructure:
| myprojectfolder
- project.py
- templates/
- static/
- style.css
- images/
- imagename.jpg
Py:
from flask import Flask, render_template
app = Flask(__name__, static_url_path='/static')
#app.route("/", methods=["GET"])
def index():
return render_template('index.html')
if __name__ == '__main__':
port = int(5000)
app.run(host='0.0.0.0', port=port, debug=True)
CSS:
.header-container {
background-image: url("/static/images/imagename.jpg");
================EDIT 2: THE FIX================
On Joost's advice, I moved all images to the static folder. All of a sudden the header loaded. However, the menu images did not, even though they were still pointing to the same exact folder: /static/images/.
You would expect all of them to not work as the images were now in static. I then moved the images back into the images folder and then all images started working. Almost seems like some sort of cache problem.
Py is now:
from flask import Flask, render_template
app = Flask(__name__, static_url_path='/static')
#app.route("/", methods=["GET"])
def index():
return render_template('index.html')
if __name__ == '__main__':
port = int(5000)
app.run(host='0.0.0.0', port=port, debug=True)
I guess here I'm telling flask where the static folder is in relation to the project folder.
Each image in CSS is called like this, which works:
background-image: url(/static/images/mobile-Music.png);

Try:
background-image: url("/static/images/IMAGENAMEHERE.jpg");
Your images has to be here:
/project/static/images/IMAGENAMEHERE.jpg
EDIT:
Try this mini example, and place an image called test.jpg in your static/images folder. I just tried it, and it works perfectly.
from flask import Flask, render_template_string
app = Flask(__name__)
#app.route('/testing')
def testing():
return render_template_string('<img href="/static/images/test.jpg"/>')

Related

Display image as background in Flask

I am giving my first steps on flask applications.
I would like to know how to show this image as a background and the html text on top?
import flask
app = flask.Flask(__name__)
app.config["DEBUG"] = True
#app.route('/', methods=['GET'])
def home():
return "<h1>Welcome to the API Service</h1><p>This site is a prototype API for displaying dashboards: quick_report, crime_locator.</p>"
app.run()
The most elegant way to solve it, using the templates.
First step is to create a static and templates directory, like this:
--static
|
-- image.png
-- templates
|
-- index.html
--app.py
index.html
<style>
body {
background-image: url("/static/image.png");
}
</style>
<body>
<h1>Welcome to the API Service</h1>
<p>This site is a prototype API for displaying dashboards: quick_report,crime_locator.</p>
</body>
app.py
import flask
app = flask.Flask(__name__, static_folder="static")
app.config["DEBUG"] = True
#app.route('/', methods=['GET'])
def home():
return flask.render_template('index.html')
app.run()

How can I set the 'static' folder when it is not on the index folder, with Flask?

I want to build a site. I have the index folder and the connected folder. Each folder also has a static folder. In the connected/static folder, I have the connected.css file, which I am trying to access, through my blueprint. However, the final page tries to access the connected.css from the index/static folder.
Where am I mistaking?
Useful code:
__init__.py:
from flask import Flask
from .index import index_routes
from .connected import connected_routes
def create_app():
app = Flask(__name__, template_folder="templates", static_folder="static")
app.register_blueprint(index_routes.index_bp)
app.register_blueprint(connected_routes.connected_bp, url_prefix='/connected')
return app
connected_routes.py
from flask import Blueprint
from flask import render_template
connected_bp = Blueprint('connected_bp', __name__, template_folder='templates', static_folder='static', url_prefix='/connected')
#connected_bp.route('/')
def connected():
return render_template('connected.html', title="Connected to Hattrick")
index_routes.py
from flask import Blueprint
from flask import render_template
index_bp = Blueprint('index_bp', __name__, template_folder='templates', static_folder='static')
#index_bp.route('/')
def home():
return render_template('index.html', title="The Best Match Predictor")
connected.html
<link href="{{url_for('static',filename='connected.css')}}" rel="stylesheet">
In the above line I have the problem.
Maybe give this a try:
<link href="{{url_for('connected.static',filename='connected.css')}}" rel="stylesheet">
For some elaboration: https://flask.palletsprojects.com/en/1.1.x/blueprints/#static-files

Python Eve serving static files from a given folder

I build a simple REST api with Eve and Python.
from flask import redirect, send_from_directory, render_template
from eve import Eve
import os
PWD = os.environ.get('PWD')
public = os.path.join(PWD, 'public')
app = Eve(static_folder=public)
# serve index.html
#app.route('/')
def index():
return send_from_directory(public, 'index.html')
# start the app
if __name__ == '__main__':
app.run()
Where I just serve a static HTML files from /public folder when / is requested.
I'm using bower to install bootstrap:
<link rel="stylesheet" type="text/css" href="bower_components/bootstrap/dist/css/bootstrap.css">
<link rel="stylesheet" type="text/css" href="bower_components/bootstrap/dist/css/bootstrap-theme.css">
But the problem is that the files are not being found although the path is correct.
Can someone explain me why is this happening?
It took me ages to figure this out. You have to import send_from_directory explicitly and also use __name__
from eve import Eve
from flask import send_from_directory
app = Eve(__name__, static_folder="static")
#app.route('/')
def index():
return send_from_directory("static", 'index.html')
app.run()
Then in settings.py:
URL_PREFIX="api"
Static file delivery:
http://127.0.0.1:5000/
http://127.0.0.1:5000/static/images/image.jpg
http://127.0.0.1:5000/static/css/style.css
API calls:
http://127.0.0.1:5000/api/person/
Apparently the path for my bower_components should be /public/bower_components/../../
I found in another thread a question regarding templates and it works quite well for static files, too:
template_folder = os.path.join(os.path.dirname(__file__), 'templates')
static_folder = os.path.join(os.path.dirname(__file__), 'static')
app = Eve(settings=settings, static_url_path='/static', template_folder=template_folder, static_folder=static_folder)

Fail to show an image using Flask

I want to show an image in the homepage of a python web application. So far I wrote the following program:
My directories and files
myWebApp/
app/
__init__.py
views.py
templates/
home.html
static/
Desert.jpg
run.py
__init__.py
from flask import Flask
app = Flask(__name__)
from app import views
views.py
from app import app
from flask import render_template
from flask import url_for
#app.route('/')
def root():
imag = url_for ('static', filename = 'Desert.jpg')
tle = "Hey"
return render_template('home.html', imag,tle)
home.html
<html>
<title>{{ tle }}</title>
<body>
<img src="{{ imag }}"/>
</body>
</html>
run.py
from app import app
if __name__ == "__main__":
app.run()
And when I run the run.py, I receive the following Internal Server Error:
What's wrong?
That's not the correct syntax for the render_template function. You need to use keyword arguments:
return render_template('home.html', imag=imag, tle=tle)

Flask-webage background image doesnt work

Below is a simple html code
index.html
<html>
<head>
<title>Webpage</title>
<link href="http://getbootstrap.com/dist/css/bootstrap.min.css" rel="stylesheet" >
<link href="http://getbootstrap.com/examples/jumbotron-narrow/jumbotron-narrow.css" rel="sylesheet">
</head>
<body>
<style type=text/css>
background-image: url("static/images/back.png");
</style>
<p>Does the Image Work? </p>
</body>
</html>
This is my Flask code:
app.py
from flask import Flask, render_template
app = Flask(__name__, static_url_path="static", static_folder="static")
#app.route("/")
def main():
return render_template("index.html")
if __name__ == '__main__':
app.run()
I get this error when I tried to inspect the page:
GET http://127.0.0.1:5000/static/images/back.png-404(NOT FOUND)
I read through a couple of other forums, but couldn't find any solution to this problem. My images are in the following folder:
Flaskapp
templates
static
images
back.png
When I open the index.html file, it works perfect, but when I try to run the python file to run the server, the background image isnt seen.
Not really sure how to proceed.
put the static folder next to the flask app
/FlaskApp
-app.py
static/
images/
-back.png
templates/
-index.html
....
you should not have to even tell flask about it... it will just know
app.py
from flask import Flask, render_template
app = Flask(__name__)
#app.route("/")
def main():
return render_template("index.html")
if __name__ == '__main__':
app.run()

Categories

Resources