gpt4 book ai didi

python - 使用 Flask 将 URL 加载到 iFrame

转载 作者:行者123 更新时间:2023-12-04 02:02:30 25 4
gpt4 key购买 nike

我是 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com