python - 使用 Flask 将 URL 加载到 iFrame

标签 python flask

我是 Flask 的新手并且 我正在尝试创建类似 Stumbleupon 的网站,但在将内容加载到 iFrame 时遇到问题。我只是想不通如何在单击 <a> 时遍历每个 url 并将它们加载到 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 中显示相同的页面。

关于python - 使用 Flask 将 URL 加载到 iFrame,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29721403/

相关文章:

python - 添加记录器导致can't pickle _thread.RLock objects错误

python - 3D 等高线图集中的级别数是多少?

python - 找到密集向量的最大值,将其设置为 1,其余设置为 0 [pyspark]

javascript - 我的 ' index.py' 代码有什么问题?

python - 使用 Pycharm 在 Windows 下启动应用程序时出现 UnicodeDecodeError

python - Scikit Learn roc_auc_score 和 ROC Plot 的正确输入

python - 使用 whoosh_search 和分页时出现 sqlalchemy 错误

python - 尝试将 Flask-mysql 与 python 一起使用

python - 访问 Flask 测试响应中的所有 cookie

python - 你是如何用docker迭代开发的?