@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

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

3 个评论
只是用post代替get?
我可以问你为什么要隐藏它吗?
@gonczor: 因为另一个页面有其他用户的'锚',我用JQuery动态地隐藏和显示。例如,当用户John被隐藏而用户'Blabla'被显示时,URL上会保留'JOHN'。 这没什么大不了的,只是让我很烦。
python
flask
Dumb  admin
Dumb admin
发布于 2018-01-10
3 个回答
Tekay37
Tekay37
发布于 2018-01-10
0 人赞同

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

你可以在这里找到该文件。http://exploreflask.com/en/latest/views.html#built-in-converters

请注意,完全隐藏变量将意味着,你的用户将失去对他们所处页面进行书签的能力。另外,如果他们无论如何都要把/users加入书签,你就必须抓住你的变量没有被发送或遇到错误的情况。

谢谢,虽然我已经尝试过了,但这并不是我想要的。锚点和用户是动态生成的,因此书签不是一个问题。
Dumb  admin
Dumb admin
发布于 2018-01-10
已采纳
0 人赞同

我能够使用实现我的目标。

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

我不是Web Dev'er,只是一个Python/Flask爱好者,知道'window.history.pushState()'是为了其他目的。我也知道这是一个HTML5特性,并非所有的浏览器都兼容。但是,嘿,它做到了这一点;).

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

谢谢大家的时间

arsho
arsho
发布于 2018-01-10
0 人赞同

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:

<head></head> {% 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>