python - 使用 Flask 生成动态 URL

标签 python flask

我正在尝试构建一个简单的 flask 页面,显示文本/链接字典中的链接:

urls = {'look at this page': www.example.com, 'another_page': www.example2.com}   

@app.route('/my_page')
def index(urls=urls):
    return render_template('my_page.html',urls=urls)

我的模板页面如下所示:

{%- block content %}
{%- for url in urls %}
    <a href="{{ url_for(urls.get(url)) }}">{{ url }}</a>
{%- endfor %}
{%- endblock content %}

我似乎不太明白如何创建这样的动态网址。该代码产生此错误:

TypeError: 'NoneType' object has no attribute '__getitem__'

有人可以指出我的问题或解决方案吗?

更新:这是我更新的代码:

  @app.route('/my_page')
    def index():
        context = {'urls': urls}
        return render_template('index.html', context=context)

模板:

{%- block content %}
    {% for key, data in context.items() %}
        {% for text, url in data.items() %}
            <a href="{{ url }}">{{ text }}</a>
        {% endfor %}
    {% endfor %}
{%- endblock content %}

这个解决方案很接近,但是每个链接都前面加上我的应用程序的网址。换句话说,我明白了:

<a href="http://127.0.0.1:8000/www.example.com">look at this page</a>

我只想:

<a href="http://www.example.com">look at this page</a>

最佳答案

试试这个:

urls = {
    'A search engine.': 'http://google.com',
    'Great support site': 'http://stackoverflow.com'
}

@app.route('/my_page')
def index(): # why was there urls=urls here before?
    return render_template('my_page.html',urls=urls)
<小时/>
{%- block content %}
{%- for text, url in urls.iteritems() %}
    <a href="{{ url }}">{{ text }}</a>
{%- endfor %}
{%- endblock content %}

url_for 仅用于使用 Flask 构建 URL。就像你的情况一样:

print url_for('index') # will print '/my_page' ... just a string, no magic here

url_for 将端点名称作为第一个参数,默认情况下是 View 函数的名称。因此, View 函数 index() 的端点名称就是 'index'

关于python - 使用 Flask 生成动态 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17689130/

相关文章:

javascript - 什么是相当于 'var myNumber = dictionary[' myNumber'] 的 python || 3个

python - 是否可以在打印之前清理冗长的 python 正则表达式?

python - Flask 登录和委托(delegate)人 - 即使我已登录,current_user 也是匿名的

python - flask的应用上下文和全局连接

python - 如何让selenium与新页面的新HTML元素交互

python 字符串每两个字符到字节 - 快速完成

python - Pandas:以 10 分钟为间隔绘制时间直方图

python - 多对多使用 Flask-SQLAlchemy 返回原始 sql 而不是执行

python - Flask 重定向新标签

python - Flask 和 Flask_login - 组织代码