使用 Flask 将 URL 加载到 iFrame

Yel*_*elp 3 python flask

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

这是我所做的:

应用程序

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)
Run Code Online (Sandbox Code Playgroud)

模板/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>
Run Code Online (Sandbox Code Playgroud)

模板/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 %}
Run Code Online (Sandbox Code Playgroud)

Cla*_*diu 6

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

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)
Run Code Online (Sandbox Code Playgroud)

然后访问模板中的值:

<iframe frameborder='0' noresize='noresize' style='position: absolute; background: transparent; width: 100%; height:100%;' src="{{ iframe }}" frameborder="0"></iframe>
Run Code Online (Sandbox Code Playgroud)

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

<h3 align="center"><a href="/">Stumble</a></h3>
Run Code Online (Sandbox Code Playgroud)

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

一个改进是使用会话对象来确保两个后续请求不会在 iframe 内显示相同的页面。