Integrating a web template with Flask [duplicate] - python

This question already has answers here:
How to serve static files in Flask
(24 answers)
Application not picking up .css file (flask/python) [duplicate]
(13 answers)
Closed 4 years ago.
I have downloaded a website template and I want to integrate it with flask. Basically, this template contains asset folder which contains the css and js files. I know that by using render_template('index.html'), I can call index.html on localhost. But when I do so, the webpage is not rendered properly. I think flask is not able to load the js, css, etc files in that folder (templates folder).
My template folder has index.html along with assets folder and othe folders. I am using the code shown below to actually run the index.html.
from flask import Flask, render_template
import os
app = Flask(__name__)
#app.route('/')
def homepage():
return render_template("index.html")
if __name__ == '__main__':
app.run(debug=True)
So, index.html is loading but it is not loading the css files, etc. Because if that is not loaded, my webpage looks dull. Its simply some text on white screen. I think the problem is with loading the static files because I get an error saying that there is no folder assets on localhost.
Thanks in advance.

You need to reference the static files inside your template like this:
<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
And ensure you put the stylesheets in the static directory of your project. You can also configure which directory contains static assets with something like:
app = Flask(__name__, static_folder="static_dir")

Related

How can I add images to Flask?

I need to add an image to my Flask webpage. And in my index.html file in templates directory there is this tag: <img src="image.jpg">
from flask import Flask, render_template
app = Flask(__name__)
#app.route("/")
def index():
return render_template("index.html")
#app.route("/image.jpg")
def image():
return render_template("image.jpg")
- it does not work. I wanted an image in my webpage, but in my terminal it says that there is a 404 error with getting the image.
[Where does flask look for image files? More information can be found here.]
If you wish to render the image in the index.html file, replace the image tag in the index.html file with the following.
<img src="{{ url_for('static', filename='image.jpg') }}" />
You MUST put the image file in a folder named static at which all static files are located. This is vital as it is where the Flask framework finds the required resources at.
When you put
#app.route("/image.jpg")
def image():
return render_template("image.jpg")
you are creating a route called /image.jpg. When you go to this route, Flask will find a template, which is basically a file that ends with .html inside the templates folder. However, a static file like an image cannot be inside the templates folder.

Serving static files in flask, output is the file name instead of it's contents [duplicate]

This question already has answers here:
How to serve static files in Flask
(24 answers)
Link to Flask static files with url_for
(2 answers)
Closed 4 years ago.
I'm trying to serve 2 static files named index.html and main.js in flask. My code is as follows:
from flask import Flask, url_for
app = Flask(__name__)
#app.route('/')
def host_html():
return url_for('static', filename='index.html')
#app.route('/map.js')
def host_map():
return url_for('static', filename='map.js')
if __name__ == '__main__':
app.run()
The output however on the web page is /static/index.html. What am I missing?
url_for function just returns a url, not the actual file. What you want to use in this case is send_from_directory: http://flask.pocoo.org/docs/1.0/api/#flask.send_from_directory
In general, i guess what you really want to do, is to use url_for in i a jinja template, which you return by render_template.

Flask url_for - incorrect static folder path

I'm trying to add an image to my quiz.html page with Flask using:
<img src='{{url_for('static', filename='img/question-mark.png')}}' alt='' >
When I look at the page source, it's interpreted as:
http://127.0.0.1:5000/quiz/static/img/question-mark.png rather than:
http://127.0.0.1:5000/static/img/question-mark.png
Yet, my .css files and .js files load in quiz.html using the same syntax just fine. How can I get the correct static file path?
My current structure is:
|-app.py
|-templates/
|-main.html
|-quiz.html
|-static/
|-css/
|-img/
app.py
from flask import Flask, render_template
app = Flask(__name__)
#app.route('/')
def homepage():
return render_template("main.html")
#app.route('/quiz/')
def quiz():
return render_template("quiz.html")
if __name__=="__main__":
app.run(debug=True)
You don't need a Jinja script to write a static image source. Just write:
<img src="/static/img/question-mark.png">
All the static resources are automatically served under /static.

Flask web page cannot find image file

On a Raspberry Pi, I have written a simple Flask app that displays the server's current date and time on a web page. That part works great.
The page should also display an image. That part doesn't work. The image is stored in the photos folder under the app folder: Web_Test/photos.
I use a css file that is stored in a static folder, and that works great.
I use url_for to create the URL to the image:
<p><img src="{{url_for('photos', filename='image1.jpg')}}"></p>
Since photos is not a known endpoint for the url_for command, I used: app.add_url_rule('/photos/<path:filename>', view_func=app.send_static_file) to add the photos folder as an endpoint.
Every time I access the web page from a web browser, my command window, that I ran python (python3 photo.py) from, shows GET /photos/image1/jpg HTTP/1.1" 404.
There are no specific errors, but also no image.
I have read many of the posts on here about this issue, but nothing has helped.
This is my photo.py code:
from flask import Flask, render_template
import datetime
app = Flask(__name__)
app.add_url_rule('/photos/<path:filename>', endpoint='photos', view_func=app.send_static_file)
#app.route('/')
def photo():
now = datetime.datetime.now()
timeString = now.strftime("%Y-%m-%d %H:%M")
templateData = {
'title' : 'Latest Photo',
'time' : timeString
}
return render_template('photo1.html', **templateData)
if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0', port=80)
This is my photo1.html code:
<!DOCTYPE html>
<head>
<link rel="stylesheet" href='/static/style.css' />
<title>{{title}}</title>
</head>
<body>
<h1>Latest Photo</h1>
<h2>Current date and time: {{time}}</h2>
<p> <img src="{{url_for('photos', filename='image1.jpg')}}"></p>
</body>
</html>
Any thoughts or suggestions would be greatly appreciated.
Thanks!
The way your program is currently written, the image will be visible if you reorganize the project layout like this:
project
├── app.py
├── static
│   └── image1.jpg
└── templates
   └── photo1.html
The fact that you want to use send_static_file to display photos suggests that photos are static resources. If that's the case, then it would be better to:
1) Move image1.jpg to static/photos/image1.jpg
2) Change the template like this:
<p> <img src="{{url_for('static', filename='photos/image1.jpg')}}"></p>
3) Drop the app.add_url_rule('/photos/<path:filename>', ...) in app.py
I just created a folder named "static" in the project folder and moved my images to it and my problem got solved.
app.py
static
|----image.jpg
templates
|----index.html
and changed index.html file like this:
<img src="/static/image.jpg">

Setting URLS for REST API using Flask [duplicate]

This question already has answers here:
Flask raises TemplateNotFound error even though template file exists
(13 answers)
Closed 6 years ago.
I have two files - app.py which contains the code for a REST API and another page index.html which displays some contents of the API using AngularJS. Currently, I have to open the index.html file from the browser to get it working (after the server http://localhost:5000 is deployed).
I tried
#app.route('/')
def index():
return render_template('/index.html',
title='Home')
It is giving the error "TemplateNotFound: /index.html". Currently, app.py and index.html are in the same directory. How do I change the format to let Flask know that it has to render the page index.html on this URL.
In flask, templates should be located in a directory called templates
Your app should look like :
./app.py
./templates/index.html
http://flask.pocoo.org/docs/0.10/tutorial/templates/ :
Put the following templates into the templates folder
Try removing the slash from the template path. It is not necessary when the files are in the same directory.
return render_template('index.html',
title='Home')

Categories

Resources