【问题标题】:Flask: Is it possible to Mask a URL with variables?Flask:是否可以使用变量屏蔽 URL?
【发布时间】:2018-01-10 10:15:47
【问题描述】:

我想将变量从一个站点传递到另一个站点。 这没问题,因为有很多方法可以做到这一点。 不过,我正在努力解决如何在 URL 中“隐藏”这些变量,但又能够获取这些值。 前任。: 如果我使用'request.args.get':

@page.route('/users', methods=['GET', 'POST'])
def users():
    user = request.args.get('user')
    return render_template('users.html', user=user)

当我点击链接时,生成的 URL 是: http://localhost:5000/users?user=john

我的目标是访问“John”部分中的“用户”页面,但用户在 URL 路径中看到的只是 http://localhost:5000/users

【问题讨论】:

  • 只使用post而不是get?
  • 请问你为什么要隐藏它?
  • @gonczor:因为另一个页面有其他用户的“锚点”,我用 JQuery 动态隐藏和显示。例如,当用户 John us 被隐藏并显示用户“Blabla”时,URL 会保留“JOHN”。这没什么大不了的,只是让我很烦。

标签: python flask


【解决方案1】:

如果您只想隐藏变量名,那么您可以使用转换器创建类似'users/<str:username>' 的路由。你的网址是http://localhost:5000/users/john

您可以在此处找到文档:http://exploreflask.com/en/latest/views.html#built-in-converters

请注意,完全隐藏变量意味着您的用户将无法为他们所在的页面添加书签。另外,如果他们无论如何都为/users 添加书签,您将不得不发现您的变量未发送或遇到错误的情况。

【讨论】:

  • 谢谢,虽然我已经尝试过了,但并不是我想要的。锚点和用户是动态生成的,因此书签不是问题。
【解决方案2】:

我能够通过以下方式实现我的目标:

window.history.pushState({"html":response.html,"pageTitle":response.pageTitle},"", "/users/");

我不是 Web 开发者,只是 Python/Flask 爱好者,并且知道“window.history.pushState()”是为了其他目的。我也知道它是 HTML5 功能,并非所有浏览器都兼容。但是,嘿,它成功了;)。

除非有人指出我不应该使用这种方法的原因,否则这是我的解决方案。

感谢大家的宝贵时间

【讨论】:

    【解决方案3】:

    Post 方法可以隐藏 URL 中的数据和变量。所以你需要将它集成到你的项目中。这是一个例子。

    app.py:

    from flask import Flask, render_template, request
    
    app = Flask(__name__)
    
    @app.route('/users', methods=['GET', 'POST'])
    def show_users():
        if request.method == 'POST':
            username = request.form.get("username", None)
            return render_template('post_example.html', username = username)
        else:
            return render_template('post_example.html')
    
    if __name__ == '__main__':
        app.run(debug = True)
    

    post_example.html:

    <html>
      <head></head>
      <body>
        {% if username %}
          Passed username: {{ username }}
        {% endif %}
        <form action="/users" method="post">
          Username: <input type="text" name="username">
          <input type="submit" name="submit" value="Submit">
        </form>
      </body>
    </html>
    

    输出:

    您可以查看HTTP方法in Flask official documentation here

    【讨论】:

    • 这就是我需要的。虽然我的应用程序有点复杂。转发到“用户”页面的链接位于树形菜单中。并且可能有数百个用户总是在树中动态生成。我将尝试在我的代码中实现它。谢谢!
    猜你喜欢
    • 2017-10-31
    • 1970-01-01
    • 2022-01-08
    • 2018-10-21
    • 1970-01-01
    • 1970-01-01
    • 2017-05-13
    • 1970-01-01
    相关资源
    最近更新 更多