Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loading URLs into an iFrame using Flask

Tags:

python

flask

I'm new to Flask and I'm trying to create a Stumbleupon like website but I'm having problems while loading the content into an iFrame. I just cant figure it out how to iterate through each url and load them into the iFrame while clicking in the <a> tag.

Here is what I've done:

app.py

from flask import Flask, render_template
app = Flask(__name__)

@app.route("/")
def index():
    urls = [
        'http://www.w3schools.com',
        'http://techcrunch.com/',
        'https://www.fayerwayer.com/',
    ]
    return render_template('index.html', urls=urls)

if __name__ == "__main__":
    app.run(debug=True)

templates/layout.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <link rel="stylesheet" type="text/css" href="/static/css/normalize.css"/>
    <link rel="stylesheet" type="text/css" href="/static/css/foundation.css"/>

</head>
<body>
    <nav class="top-bar">
        <h3 align="center"><a href="?????">Stumble</a></h3>
    </nav>

    {% block content %} 
    {% endblock content %}

</body>
</html>

templates/index.html

{% extends 'layout.html' %}
{% block content %}
    <iframe frameborder='0' noresize='noresize' style='position: absolute; background: transparent; width: 100%; height:100%;' src="????????" frameborder="0"></iframe>
{% endblock content %}
like image 474
Yelp Avatar asked Jun 10 '26 06:06

Yelp


1 Answers

After adding import random at the top of your app.py file you could structure your code like this:

def index():
    urls = [
        'http://www.w3schools.com',
        'http://techcrunch.com/',
        'https://www.fayerwayer.com/',
    ]

    iframe = random.choice(urls)

    return render_template('index.html', iframe=iframe)

Then access the value in your template:

<iframe frameborder='0' noresize='noresize' style='position: absolute; background: transparent; width: 100%; height:100%;' src="{{ iframe }}" frameborder="0"></iframe>

And simply set the Stumble button to refresh the page.

<h3 align="center"><a href="/">Stumble</a></h3>

This will be pretty basic, but it will have the behaviour you're describing.

An improvement will be to use the session object to make sure that two subsequent requests do not display the same page inside the iframe.

like image 104
Claudiu Avatar answered Jun 13 '26 14:06

Claudiu