Error with Folium iframe and Flask - python

I've experimented quite a bit / searched through solutions here on the site, but so far am having trouble displaying a folium map within an iframe when the holding page is served from Flask.
wiki
app
__init.py__
routes.py
static
map_test.html
templates
map.html
Basic overview: on map.html, I have an iframe where I am trying to source the map_test.html file, a sample Folium map.
Does anyone have any thoughts on what to rearrange or fix? My thinking is the static folder, the map.html, and map_test.html files are all in the right location, but my routing is wrong. Any help is appreciated!
Here are the various code bits.
init.py
app = Flask(__name__, static_folder='static')
routes.py
#app.route('/map/')
def map():
map = folium.Map(
location = [37.852995, -120.999986],
tiles = 'Stamen Terrain',
detect_retina = True,
prefer_canvas = True,
zoom_start = 4
)
startLat_1 = 34.286565
startLong_1 = -118.561021
clusterData_1 = [retLatLong(startLat_1, startLong_1) for i in range(100)]
plugins.FastMarkerCluster(clusterData_1).add_to(map)
map_path = app.root_path + '/' + 'static/map_test.html'
map.save(map_path)
return render_template('map.html')
#app.route('/static/map_test.html')
def map_data():
return send_file(url_for('static', filename = 'map_test.html'))
map.html
<div>
<iframe src="{{url_for('static', filename = 'map_test.html')}}" height="600" width="800">
</iframe>
</div>
Through the code above, I'm able to successfully generate map_test.html in the static folder, but cannot figure how/why to route it properly into the iframe.
The error from the current code configuration above is:
IOError: [Errno 2] No such file or directory: '/static/map_test.html'
127.0.0.1 - - [27/Mar/2018 13:01:50] "GET /static/map_test.html HTTP 1.1" 500

Related

Android emulator how to display image to remote destination in flask

I was referring to this github https://github.com/ahmedfgad/AndroidFlask and https://heartbeat.comet.ml/uploading-images-from-android-to-a-python-based-flask-server-691e4092a95e. I was unable to display the images into the remote destination from android emulator. I dont think the source code that they provide, do display images to the remote destination using flask.
Below is my github. It shows all the changes I have made.
https://github.com/2100723/AndroidEmulator/tree/main. I have made changes to the flask_server.py and images_template.html which is located in the templates folder . I need in the image to display in the remote host.
My android emulator has managed to save my images from emulator in the file call static whenever press connect to server & upload enter image description here. All I left is to send my image to a remote destination.
#Flask_server.py
import flask
import werkzeug
import time
app = flask.Flask(__name__, static_folder='static')
#app.route('/', methods = ['GET', 'POST'])
def handle_request():
image_paths = []
files_ids = list(flask.request.files)
print("\nNumber of Received Images : ", len(files_ids))
image_num = 1
for file_id in files_ids:
print("\nSaving Image ", str(image_num), "/", len(files_ids))
imagefile = flask.request.files[file_id]
filename = werkzeug.utils.secure_filename(imagefile.filename)
print("Image Filename : " + imagefile.filename)
timestr = time.strftime("%Y%m%d-%H%M%S")
file_path = timestr+'_'+filename
imagefile.save(file_path)
image_paths.append(filename)
image_num = image_num + 1
print("\n")
return flask.render_template('image_template.html', images=image_paths)
app.run(host="0.0.0.0", port=5000, debug=True)
#image_template.html
<!doctype html>
<html>
<head>
<title>Image Gallery</title>
</head>
<body>
<h1>Image Gallery</h1>
{% for image in images %}
<img src="{{ url_for('static', filename=image) }}" alt="image" width="200">
{% endfor %}
</body>
</html>
I try changing my Flask_server.py code and adding image_template.html to make my code to display to the remote server using flask. Nothing is display in the remote destination using flask

Why URLs from 'static' does not working for preview in flask?

I am trying to show some preview in Flask from user-uploaded images static/uploads and found that URLs generated by url_for('static', filename=image_file_path) do not work as I'd like.
I am getting out a path like: /static/uploads/0321.jpg
and after putting it in HTML img src={{ image_url_list[0] }} I see no preview (with URL: http://127.0.0.1:5000/static/uploads/0321.jpg if I copy the empty image address)
It is 404 error:GET /static/uploads/03020011.jpg HTTP/1.1" 404 -
The file is in its place and I can access it inside the App if remove the first slash static/uploads/0321.jpg
Actually, I'd like to get the working URLs not only for preview but have them externally visible for other sites (but not freely explorable by other users just typing static/uploads in browser).
So, please, advise me what am I doing wrong?

Dynamic plotly visualization (or image) in Flask Python

I've got a plotly visualization ('viz.html') in a html format. I've embedded it in my webpage using Flask's url_for() syntax, referencing the static folder:
<iframe id="igraph" scrolling="no" style="border:none;" seamless="seamless" src="{{ url_for('static', filename='viz.html') }}" height="400" width="120%"></iframe>
It deploys with no issues. However, my 'viz.html' will be rewritten frequently, updating itself with new data points. The updated visualization won't show with a control + R or webpage refresh. If I press control + F5 and do a cache refresh, then updated visualization will show.
I want users to be able to see the updated visualization without having to manually refresh the cache. So far I've tried:
Reloading flask app when file changes are detected in 'static' folder (Reload Flask app when template file changes)
check_folder = './static'
check_files = []
for dirname, dirs, files in os.walk(check_folder):
for filename in files:
filename = os.path.join(check_folder, filename)
check_files += [filename]
app.run(debug = True, extra_files = check_files)
Disabling browser cacheing on html page (http://cristian.sulea.net/blog/disable-browser-caching-with-meta-html-tags)
<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
<meta http-equiv="Pragma" content="no-cache" />
<meta http-equiv="Expires" content="0" />
Disabling Python on Flask Cacheing
resp.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
resp.headers["Pragma"] = "no-cache"
resp.headers["Expires"] = "0"
Would like to know, is what I'm trying to do even possible?
If it's possible how can I go about doing it? Advice appreciated!
I am not a web developer but I worked with a few closely for 3 years. As far as I know, there is no way to control what other browsers saved as cache. If my browser has a version saved in the cache, it will use that one. Usually, browsers will check if all the files are updated, and eventually, it will refresh for everyone. I actually heard developers being asked "why didn't you fix what I told you?" and they were like, "I have, just hard refresh." So I don't think there is a way. IDK if anything new is out there.
I figured it out!
Instead of writing the plotly fig to a viz.html file, do viz = Markup(fig) in flask:
#app.route("/index/",methods=["POST", "GET"])
def foo():
from flask import Markup
# include_plotlyjs = True builds in the js library
# output_type = 'div' outputs the html code
viz = plot(fig, include_plotlyjs = True, output_type = 'div')
# Markup directly renders the html code
viz = Markup(viz)
return render_template('foo.html', viz = viz)
In foo.html, you can directly use viz as so:
<html>
<body>
viz
</body>
<html>
viola!

jQuery doesn't work when delivered with flask but works otherwise [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 pretty new to python, even less experienced with flask, and I cannot figure out this issue. I have the following simple web page with jQuery functionality that works great when I double click the file and open it in a browser:
<!DOCTYPE html>
<html>
<head>
<script src="jquery-3.3.1.js"></script>
</head>
<body>
<script type="text/javascript">
$(document).ready(function() {
$("#updateBtn").on("click", function() {
text = "<h2>The div has been updated!</h2>";
$("#jQuery_div").html(text);
});
});
</script>
<div>
<h1>This is a non-jQuery div</h1>
</div>
<div id="jQuery_div">
<h2>This div should update with jQuery</h2>
</div>
<button id="updateBtn">update</button>
</body>
</html>
However, when flask delivers the web page on localhost:5000, the jQuery functionality is no longer present. My python is as follows:
from flask import Flask, render_template
app = Flask(__name__)
#app.route('/')
def render():
return render_template("jquery_test.html")
if __name__ == "__main__":
app.run(port=5000, debug=True)
My app's file tree is:
/AJAX_practice
ajax_practice.py
/templates
jquery-3.3.1.js
jquery_test.html
I was trying to follow this tutorial when I couldn't get the "echo" button to work. In my efforts to debug, I have slowly chipped away and drastically simplified the program to the above code to see why I cannot get my jQuery to work through flask. I am still at a loss. I am running the flask app by pressing F5 in IDLE, with no errors in Python 2.7.13 Shell, and the Terminal (from which I started IDLE with $ sudo idle) showing:
my ip - - [date and time] "GET / HTTP/1.1" 200 -
my ip - - [date and time] "GET /jquery-3.3.1.js HTTP/1.1" 404 -
From this, my best guess is that flask cannot find the jquery.3.3.1.js file, though I have tried putting it everywhere in the file tree with no luck. I cannot use the script src to https for jQuery dependencies, as my server will eventually be on a non-internet connected LAN. Am I on the right track? If so, how does flask find and/or navigate jQuery dependencies? Can anyone point me towards some documentation that might help my fundamental understanding of this issue?
Any help on this matter would be greatly appreciated.
You are trying to serve JavaScript file from templates folder. Add a static folder and use that to serve static content.
in your case create a directory structure like "static/js/jquery.min.js"
and then add script reference like this
<script src="{{url_for('static', filename='js/jquery.min.js')}}"></script>
See this :
http://exploreflask.com/en/latest/static.html
If you don't want to keep it in "static" folder and use another local directory you can use send_from_directory as shown in this example :
https://stackoverflow.com/a/20648053/2118215
This has always worked for me with Flask in the past:
<script src="{{ url_for('static', filename='jquery-3.3.1.js') }}"></script>
'static' is the name of the folder it's in (and the 'static' folder is in the root of my project). You can edit this to suit your preferred structure and naming, so change 'static' to 'templates' if that's where you'd rather keep your jquery file, although I would recommend keeping it in a separate folder from your HTML templates, purely in the interests of keeping your project well organised.
I believe the path to jquery should be /templates/jquery-3.3.1.js
On me flask server when i serve jquery it has the full path from the home directory: /static/js/jquery.min.js

Serving image with flask

I have a program which generates an image. Now I want to use Flask to make this picture accessible to other users, but I can’t display this image with the following code:
#!/usr/bin/python2
#coding: utf-8
from flask import *
app = Flask(__name__)
#app.run(host='0.0.0.0')
#app.route('/')
def index():
return render_template('hello.html')
if __name__ == '__main__':
app.run(debug=True,host='0.0.0.0')
My template hello.html is:
<!doctype html>
<title>Hello from Flask</title>
<h1>Hello World!</h1>
<img src="./weather-plot.png">
When I run this program and visit the page, I see this:
192.168.0.61 - - [10/Jul/2013 10:22:09] "GET / HTTP/1.1" 200 -
192.168.0.61 - - [10/Jul/2013 10:22:09] "GET /weather-plot.png HTTP/1.1" 200 -
And in my browser I see the title, but not the picture. What’s wrong?
By the way, is there a better method to display a picture without anything else? Maybe I don’t have to use a template?
Are you sure the image is indeed in the location ./, i.e. in the root of your project?
In any case, it is better to use Flask's url_for() method to determine URLs (see http://flask.pocoo.org/docs/api/#flask.url_for) This makes sure that when you move things around, the URLs don't break.

Categories