使用 Flask 将 URL 加载到 iFrame

Loading URLs into an iFrame using Flask

我是 Flask 的新手并且 我正在尝试创建类似 Stumbleupon 的网站,但在将内容加载到 iFrame 时遇到问题。我只是不知道如何遍历每个 url 并在单击 <a> 标记时将它们加载到 iFrame 中。

这是我所做的:

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 %}

在 app.py 文件的顶部添加 import random 后,您可以像这样构建代码:

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)

然后访问模板中的值:

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

只需设置 Stumble 按钮即可刷新页面。

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

这将是非常基本的,但它将具有您所描述的行为。

一项改进是使用 session 对象来确保两个后续请求不会在 iframe 中显示同一页面。