Using Flask to embed a local HTML page [duplicate]

2020-06-04 09:58发布

问题:

So I am using this cool plugin called Folium which creates maps. The map gets created as a .html and every time you update the map it regenerates the html. So in order to display the map and my navbar and other stuff on the same page I think I would need to put map.html inside an iframe cage where it can refresh itself at will.

The map gets created thus:

map1 = folium.Map(location=[45.5, -73.61], width="100%", height="100%")
map1.save('./maps/map.html')

And I have tried iframeing it thus:

<iframe src="/maps/map.html"></iframe>

But I get 404 error

Someone yesterday suggested that I build an endpoint for it like this:

@app.route('/http://127.0.0.1:4995/maps/map')
def show_map():
return flask.send_file('/maps/map.html')

But I keep getting 404 error

回答1:

You have your route defined incorrectly. As you had it written, you defined the route for http://yourserver/http://127.0.0.1:4995/maps/map when instead what I think you wanted was http://yourserver/maps/map.html. To achieve this, you will want to use the following

@app.route('/maps/map.html')
def show_map():
    return flask.send_file('/maps/map.html')

Flask will automatically prepend your server's address (http://127.0.0.1:4995) to the beginning of any route that you define.

Also, in the template for your HTML, I would use url_for to get the URL for the map to avoid changes in your routes requiring changes to your templates.

<iframe src="{{ url_for('show_map') }}"></iframe>