changing html image based on passed data by python with flask - python

return render_template('homepage.html',imgName=filenameD)
PYTHON
<img src= {{ name }} alt="something" style="width:500px;height:600px;">
HTML
im trying to change the image on my website based on the data I pass to it with python flask but the image does not show up, im using something called jinja?

The image is not shown because you are referencing a non-existent variable in your template. Change your <img> tag to
<img src="{{ imgName }}" alt="something" style="width:500px;height:600px;">
and make sure that filenameD contains the path to your image and not only its name i.e. it should be something like /static/image.png.
Also, always surround your attribute values with "" to prevent XSS attacks, see Flask's security docs.

Try this:
Python
return render_template('homepage.html',name=filename)
HTML
<img src = "{{url_for('static', filename=name) }}" alt="something" style="width:500px;height:600px;">
Your image must be located inside 'static' folder and named as usually ('myimg.png', etc)

Related

Adding a variable string to an expression in Airium (Python)

I'm working on a little jig that generates a static gallery page based on a folder full of images. My current hangup is generating the HTML itself-
I used Airium to reverse-translate my existing HTML to Airium's python code, and added the variables I want to modify for each anchor tag in a loop. But I can't for the life of me figure out how to get it to let me add 'thumblink'. I'm not sure why it's treating it so differently from the others, my guess is that Airium expects foo:bar but not foo:bar(xyz) with xyz being the only part I want to pull out and modify.
from airium import Airium
imagelink = "image name here" # after pulling image filename from list
thumblink = "thumb link here" # after resizing image to thumb size
artistname = "artist name here" # after extracting artist name from filename
a = Airium()
with a.a(href='javascript:void(0);', **{'data-image': imagelink}):
with a.div(klass='imagebox', style='background-image:url(images/2015-12-29kippy.png)'):
a.div(klass='artistname', _t= artistname)
html = str(a) # cast to string
print(html) # print to console
where "images/2015-12-29kippy.png" is what I'd replace with string variable "thumblink".
image and artist do translate correctly in the output after testing -
<a href="javascript:void(0);" data-image="image name here">
<div class="imagebox" style="background-image:url(images/2015-12-29kippy.png)">
<div class="artistname">artist name here</div>
</div>
</a>
>>>

Images appear fine when I preview HTML page directly, but appear broken when same page is returned from flask [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 2 years ago.
working on a small project, for which I have an HTML page. For now it is a static page, with everything hard-coded.
When I preview it locally, it appears fine. But when the same page is returned from flask using render_template, the image link appears broken.
Following is the structure of directory:
/
-server.py
--templates/
---org_dashboard.html
---img_avatar.png
Im attaching screenshots as well as code snippets from return function, and the corresponding HTML code.
Python/flask code:
#app.route('/org_dashboard', methods=['GET', 'POST'])
def org_dashboard():
return render_template('org_dashboard.html')
Corresponding HTML code with image path:
<div class="card-columns">
<div class="card">
<img src="img_avatar.png" alt="Avatar" style="width:100%">
<div class="container">
<h4><b>John Doe</b></h4>
<p>Architect & Engineer</p>
</div>
</div>
</div>
When returned from localhost by flask. Notice the link appears broken:
Click here to view image
When viewed directly by opening the HTML file. Image appears fine Click here to view screenshot
The problem is that your image path is implying something that is only true in a static local HTML file.
src="img_avatar.png" tells the browser that the file is located in the same folder as the current page.
You need to change this to a relative path like this: src="/static/img_avatar.png" and then move the file to the /static folder in your project root.
Flask makes the assumption that you will do this and automatically adds a static view that takes a path relative to the project_root/static directory and serves it.

Using AngularJS to show images from API (flask app)

I'm trying to show some badge images I made for a RANK APP I've been working for. It's 10 images that should be shown specific for each driver.
I'm not an expert on coding, but I keep searching and studying ways to solve the problem I've been through.
I firstly tried to send base64 images from the API to the browser, using this code:
<!-- language: python -->
for img in imglist: #loop for creating a list of base64 images from a list of image dir.
imgcode = base64.encodestring(open(imgdir + img,"rb").read())
imgcodelist.append(imgcode)
for driver in sortdriverList: #loop for taking drivers points and turn it into RANK img
if (driver['Races'] < 21):
driver['Rank'] = str(imgcodelist[9])
[...]
The second loop is longer than that, stil what I've shown to you above makes any driver that wasn't participating in more than 21 races, be part of a 'NON CLASSIFIED' badge.
I used AngularJS to try to show the base64 image using the code below.
'<html>'
<td><img src="data:image/png;base64,{{ '{{driver.Rank}}'}}"></td>
[driver.Rank] should be the base64 code string. When I run the app, the image is not shown, instead I see the very code of the image inside the table =/
Then I tried to turn [driver.Rank] into a dir string for "img src=", using the codes below.
<!-- language: python -->
imglist = ["notclassified.png", etc...]
imgdir = "static/images/"
for item in sortdriverList:
if (item['Races'] < 21):
item['Points'] = imgdir + imglist[9]
and in my HTML I changed the img src to:
'<html>'
<img src= {{ '{{driver.Rank}}' }}>
and now it shows the directory of the images.
I've been searching for CSS ways to make it possible.
I coudn't find a solution yet.
It's hard to tell what's going on since only segments are pasted, but I'm guessing it has to do with how you are escaping the code. Maybe you could paste the generated code in chrome.
Sometimes seeing a working example helps.
angular.module('App', [])
.controller('DriverCtrl', DriverCtrl);
function DriverCtrl($scope) {
// base64 encode 1x1 black pixel
this.Rank = 'R0lGODlhAQABAIAAAAUEBAAAACwAAAAAAQABAAACAkQBADs=';
}
<div ng-app="App">
<div ng-controller="DriverCtrl as driver">
<div>Rank: {{driver.Rank}}</div>
<span>Image:</span>
<img ng-src="data:image/png;base64,{{driver.Rank}}">
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

How do you serve a dynamically downloaded image to a browser using flask?

I'm working with an IP camera. I can use a URL such as this one to grab a static image off the camera:
http://Username:Password#IP_of_Camera:Port/streaming/channels/1/picture
What I want to do is have python/flask download the image from that URL when the client loads the page, and embed the image into the page using an img tag.
If I have a template that looks something like this:
<html>
<head>
<title>Test</title>
</head>
<body>
<img src="{{ image }}">
</body>
</html>
how do I replace the {{ image }} with the downloaded image?
Would I use urllib/requests to download the image to flask's static folder, replace {{ image }} with something like {{ url_for('static', filename="temp_image.png") }}, and then delete the image from the static folder when the page loads? Would I download it someplace else instead (other than the static folder)? Or is there some other way to do it that keeps the image in memory?
PS. I know it's possible to replace {{ image }} with that URL directly, but that reveals the username/password/IP/port of the camera to the client.
I would add a masking route on flask that fetches and serves the image directly.
Lets say domain.com/image/user1/cam1
Your server would typically make a http request to the camera and once it receives a response, you can straight up serve it as a Response object with appropriate mimetype.
In this case, the image you fetched from camera resides in your RAM.
#app.route('image/<userID>/<camID>')
def fun(userID,camID):
# fetch the picture from appropriate cam
pic = requests.get('http://'+
'Username:Password'+ # dynamically replace user id / password/ auth
'#IP_of_Camera:Port'+ #dynamically replace port / IP
'/streaming/channels/1/picture')
# do processing of pic here..
return Response(pic,mimetype="image/png")
However, if this image needs to be served over and over again, then you might wanna cache it. In which case, I would pick something closer to your approach.
If you want to stream the camera images, it is a whole different ballgame.
import requests
url = "http://Username:Password#IP_of_Camera:Port/streaming/channels/1/picture"
response = requests.get(url)
if response.status_code == 200:
f = open("/your/static/dir/temp.png", 'wb')
f.write(response.content)
f.close()
{{ url_for('static' filename="temp.png") }}
Not sure why you would need to delete it, but I guess you could if you thought that was required

Get Flask to show image not located in the static directory

I'm trying to display images located in a folder which is not the default static folder.
My template looks like:
{% extends "layout.html" %}
{% block body %}
Albums
{% for album in albums %}
<img src="{{ album ['ThumbPath'] }}">
{% endfor %}
{% endblock %}
The generated HTML looks like:
<!doctype html>
<title>iPhoto</title>
<link rel=stylesheet type=text/css href="/static/style.css">
<div class=page>
<h1>iPhoto</h1>
<img src="/Users/Darrell/Pictures/iPhoto Library/Thumbnails/2013/08/09/20130809-180444/t264vvMaQM+GJosBP+4q+Q/_DSC1225.jpg">
<img src="/Users/Darrell/Pictures/iPhoto Library/Thumbnails/2013/08/09/20130809-181030/urU3jqSKRgGNNP1MjKhpvg/_DSC1268.jpg">
<img src="/Users/Darrell/Pictures/iPhoto Library/Thumbnails/2013/08/09/20130809-181037/1zYyNYReRg+Sizx8v4BUkw/_DSC0923.jpg">
<img src="/Users/Darrell/Pictures/iPhoto Library/Thumbnails/2013/08/09/20130809-181038/sKzEEB3jSf6GBs2heQIviA/Kelly.jpg">
</div>
How can get the images to be rendered on the generated webpage.
The path to the image is correct.
It is no option to copy all images to the static folder.
Darrell
Look like you have file system path instead site. When you start resource with / then path will start from site root (absolute path for site, without slash or with ./ or ../ is relative) for example if you have site http://test.com then / will be http://test.com/ or /test will be http://test.com/test. You can set path with specific protocol protocol:// or identical for current site // for another sites. You always can found errors with wrong (full) urls in your browser error console.
To get access to file system you must use file:// protocol and you urls will be like file:///Users/Darrell/Pictures/.... But it will work only for your computer and can have security issues. You also can set symbolic link for this files to static folder and this resolve security issues, but not resolve issue with only your computer. To completely resolve this issue better publish this files to your application or on public (private) web servers for images or another static.
So here is my project path. I wrote a simple function that would work by allowing it to render on the webpage. I am not a 100% sure if it would work once deployed, so I will update if it does work when deployed.
<img alt="" src="{{ url_for('send_file', filename=image_url) }}" id ="img"/>
This is the code of the HTML element and here is its corresponding code in Python on the server side.
def getImageName(x):
"""
Dealing with Unix Path names and Windows PathNames
"""
if platform.system() == 'Linux':
return x[x.rfind("/")+1:]
return x[x.rfind("\\")+1: ]
def getFolder(x):
y = []
if platform.system() == 'Linux':
y = x.split("/")
else:
y = x.split("\\")
# print(y)
cat_name = ""
if "roomImage" in x:
cat_name+="roomImage/" + y[-2]
elif "lobbyImage" in x:
cat_name+="lobbyImage"
elif "miscImage" in x:
cat_name += "miscImage/" + y[-2]
elif "washroomImage" in x:
cat_name += "washroomImage"
else:
cat_name += "facadeImage"
return cat_name + "/"
#app.route("/send_file/<filename>")
def send_file(filename):
return send_from_directory(app.config["UPLOAD_FOLDER"] +"/" + getFolder(filename) , getImageName(filename))
This works for the most part.
By the way, image_url is supposed to the be the absolute path of the image that you can pass as an argument to the Jinja2 template via render_template like so:
return render_template("/contentpage.html",image_url=imgurl)
Don't forget to import send_from_directory and set app.config["UPLOAD_FOLDER"] to the appropriate directory. This isn't the most efficient way to do it

Categories

Resources