Flask web page cannot find image file - python

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">

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.

Integrating a web template with Flask [duplicate]

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")

Got 404 error while using Flask framework

I was trying to run my html code using flask framework. When I tried to run the python script, it showed 404 error in the browser
<html>
<body>
<h1>Hello world!</h1>
</body>
</html>
python script:
from flask import Flask, render_template
app = Flask(__name__)
#app.route('/hello/<user>')
def hello_name(user):
return render_template('hello.html', name = user)
if __name__ == '__main__':
app.run(debug = True)
What is the reason of this error?
The code works fine.
Make sure that you keep the html file in templates folder. My folder structure is like this:
flask_app
├── hello.py
└── templates
└── hello.html
And also visiting the http://127.0.0.1:5000/ will cause the error as you did not define any view for root path.
While visiting the indexed path http://127.0.0.1:5000/hello/arsho I got the expected view:
Use jinja to print your name
<html>
<body>
<h1>Hello {{name}}</h1>
</body>
</html>
Go throught the flask quickstart

AngularJS directives don't seem to work with Python Flask

Even though my issue might be a common one, I couldn't find a clear answer for it.
I'm a beginner with AngularJS and there is a very simple code that is not working, and actually all my directives doesn't work.
Here is my small project
/templates
-index.html
-header.html
-script.js
mainapp.py
In index.html there is
<!DOCTYPE html>
<html data-ng-app>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
</head>
<body>
<div data-ng-include="'header.html'"></div>
</body>
</html>
in header.html
<div> I'm supposed to see this </div>
And mainapp.py
from flask import Flask, render_template
app = Flask(__name__)
#app.route("/")
def mainpage():
return render_template("index.html")
if __name__ == "__main__":
app.run(debug=True)
Nothing in script.js
When I'm running mainapp.py I'm expecting to see "I'm supposed to see this" but I don't because the directives doesn't seem to be working. However if I'm trying the html code alone (on Plunker for example) it's working fine.
I assume there is configuration that I need to do but I have no idea what, any ideas? (and if someone could provide an explanation for why it's not working that would be great)
Note that using data- before my directives doesn't change the issue.
Thanks
The issue has to do with how Flask handles static files vs. templates. The header.html file is really a static file in your situation, not a Flask template.
Change your directory structure to:
├── mainapp.py
├── static
│   └── partials
│   └── header.html
└── templates
└── index.html
Then update the ng-include to:
<div data-ng-include="'header.html'"></div>
If this were me, I wouldn't even use a "templates" directory. Just serve up a your index.html file from the static directory so that when an end user hits the main / route, Angular takes over. Then, you can just interact with the server-side via making AJAX requests against the RESTful API.

Setting up static folder path in Flask

Seems like my static files aren't being served properly. This is what it looks like right now:
myApp
__init__.py
static
img
js
bootstrap.min.js
etc.
This is what my app config in my __init__.py looks like:
app = Flask(__name__, static_url_path="", static_folder="static")
This is the error:
127.0.0.1 - - [01/Dec/2014 13:12:01] "GET /static/js/bootstrap.min.js HTTP/1.1" 404 -
As far as the url routing goes, no problems there, localhost/home routes to home, localhost/contact routes to contact, etc. But static files aren't being found :( Am I missing something?
NOTE: I'm hosting this on my Mac, purely local host
This is my __init__.py main method:
if __name__ == "__main__":
app.run(host='0.0.0.0', debug=True)
Running as:
python __init.py__
It looks like you are hardcoding to static file URLs. You tell Flask to server them with no URL prefix -- the default would have been /static -- but the log shows the request going to /static/js/bootstrap.min.js. You probably have something like the following in a template file.
<script src="/static/js/bootstrap.min.js"></script>
Instead, you should use url_for to create the URL for you. Change the above to
<script src="{{ url_for('static', filename='js/bootstrap.min.js') }}"></script>
This will result in
<script src="/js/bootstrap.min.js"></script>

Categories

Resources