这里的一名学生,目前正在学习 Flask 并学习如何使用 request.endpoint。
当我尝试打印它时,它显示“静态”。我希望它打印当前路线,例如:“index”或“login”
这是我的控制台的一个示例:
127.0.0.1 - - [28/Apr/2024 11:12:35] "GET /static/css/style.css HTTP/1.1" 304 -
before_request
static
似乎没有捕捉到正确的路线;相反,它会为我的 JavaScript 或 CSS 文件选取路线,并且适用于每条路线。我希望它打印当前路线,例如:“index”或“login”而不是“static”
如何正确打印 request.endpoint,但不排除我的 CSS 和 JS 路由?”
我的部分代码:
main.py
@app.before_request
def before_request():
print("before_request")
if 'username' not in session:
print(request.endpoint)
@app.route('/', methods = ['GET', 'POST'])
def index():
if 'username' in session:
username = session['username']
print(username)
title = "Curso Flask"
return render_template('index.html', title = title,)
base.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>{%block title%} {%endblock%}</title>
<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='css/style.css') }}">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
</head>
<body>
<h1>Hola mundo desde mi base.html</h1>
<!--Ejemplo de flash message para recibir el response de un mensaje-->
{% with messages = get_flashed_messages() %}
{% if messages %}
<ul>
{% for message in messages %}
<li>{{message}}</li>
{%endfor%}
</ul>
{%endif%}
{%endwith%}
{% block content %}
{% endblock %}
<script type="text/javascript" src="{{ url_for('static', filename='js/jquery.js') }}"></script>
</body>
</html>
索引.html
{% extends 'base/base.html'%}
{% block title %} {{ title }} {%endblock%}
{% block content %}
<h2>Hola mundo desde mi index.html</h2>
<!--Esto es para importar el macro-->
{% from "_macro.html" import show_list_h %}
<!--Esto es para llamar al macro-->
{{ show_list_h('Hola mundo desde mi macro')}}
{% endblock %}
还有更多,但我将其浓缩为我认为最相关的内容。
对我来说,它似乎工作正常。
当浏览器发出请求时,它将请求您在 HTML 中链接的不同资源。因此,如果您的
index.html
中有 .js 文件、.css 和 favicon,那么浏览器将发出多个请求来获取资源以正确显示您的网站。
例如,如果我的
index.html
有一个 .css 和一个图标,则输出如下所示:
index
127.0.0.1 - - [28/Apr/2024 22:56:34] "GET / HTTP/1.1" 200 -
static
127.0.0.1 - - [28/Apr/2024 22:56:34] "GET /static/style.min.css HTTP/1.1" 200 -
static
127.0.0.1 - - [28/Apr/2024 22:56:34] "GET /static/favicon.png HTTP/1.1" 200 -
在你的Python代码中,每次你的应用程序收到请求,它都会执行
before_request()
,其中包括对CSS、JavaScript等资源的请求以及对服务器的几乎所有请求。
您可以简单地添加另一个条件,以便仅在端点不是时才打印
static
@app.before_request
def before_request():
print("before_request")
if 'username' not in session and request.endpoint != "static":
print(request.endpoint)