2015-04-18 926 views
1

我是Flask的新手和 我试图创建像Stumbleupon一样的网站,但我在将内容加载到iFrame时遇到问题。我只是无法弄清楚如何迭代每个url并将它们加载到iframe中,同时单击<a>标签。使用Flask将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) 

模板/的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> 

模板/ 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 %} 

回答

1

你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内显示相同的页面。

+0

非常感谢!这完美的作品!我将实际添加会话对象,再次感谢您。 – Yelp

+0

你能告诉我如何使用会话对象吗?我不明白这些文档以及如何将它与'random.choice'一起使用。请给我一些提示。 – Yelp

+0

您必须将当前网址保存到会话中,然后您可以从'urls'列表中弹出,并从剩余的'random.choice'中选择,或者您可以随机选择一个网址直到您选择与会话中的内容不同。不要忘记在每次选择后更换您在会话中存储的网址。祝你好运! – Claudiu