The pit of url_for in flask

page_not_found.html in the template file:

404 错误,<a href="{
   
   { url_for('hello')}}">点击跳转到首页</a>

The hello function is used in it

If app.py is written like this:

@app.route("/<name>")
def hello(name=None):
    # name = '<script>alert("bad")</script>'
    if name:
        return f"Hello, {escape(name)}"  # 对其转义是为了防止直接运行注入代码了
    # return f"Hello, {name}"  # 直接这样写 并且用户输入的是<script>alert("bad")</script> 则会弹窗!
    else: return "Hello, World!"

Then it will report an error saying that no value is assigned to name!

must be written like the following: The following is just another example!

@app.route("/hello3")
@app.route("/hello3/<name>")
def hello3(name=None):
    print("请求路径: \t",request.path)
    print("请求方法: \t",request.method)
    print(dir(request))
    print("---------------")
    for req in dir(request):
        # print(req)
        try:
            print(req,end=': ')
            exec('print(request.'+req+")")
        except:
            pass
    return render_template("hello.html",name=name)

If name is None and no value is assigned, the first hello3 route will be used! ! !

At the same time, it is also an operation that uses the same function, but the operation that name is None   

I feel that this is a pure anti-software operation. It is enough to write a route at first, and it is enough to write it down later. When the parameter is empty (if it is not set and the default is empty), you must write a route in which the parameter is empty! ! !

Just change the code of app.py to the following:

Just add the content of the first line:

@app.route("/")
@app.route("/<name>")
def hello(name=None):
    # name = '<script>alert("bad")</script>'
    if name:
        return f"Hello, {escape(name)}"  # 对其转义是为了防止直接运行注入代码了
    # return f"Hello, {name}"  # 直接这样写 并且用户输入的是<script>alert("bad")</script> 则会弹窗!
    else: return "Hello, World!"

Guess you like

Origin blog.csdn.net/conquer_galaxy/article/details/131573943