如何在Flask中追踪404错误请求的方法、URL及IP地址
如何在Flask的404错误处理器中追踪请求方法、URL和IP地址
嘿,这个问题其实很容易解决——Flask给我们提供了全局的request对象,不管是在正常路由还是错误处理器里,都能轻松拿到这些请求细节。下面我给你具体的实现方案:
核心思路
Flask的request对象包含了当前请求的所有元数据,我们只需要在404错误处理器中直接调用它的属性,就能获取到请求方法、URL和客户端IP,之后你可以选择把这些信息记录到日志,或者传递给404模板显示出来。
修改后的代码示例
首先更新你的错误处理器,同时可以配置日志来持久化记录这些信息:
from flask import Flask, render_template, request import logging app = Flask(__name__) # 配置日志,设置INFO级别方便查看请求详情 logging.basicConfig( level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s' ) logger = logging.getLogger(__name__) @app.route('/login', methods=['POST']) def login(): # 这里是你的登录逻辑 return "Login successful (demo response)" @app.errorhandler(404) def not_found(e): # 从request对象中提取关键信息 request_method = request.method requested_url = request.url client_ip = request.remote_addr # 将404错误信息记录到日志 logger.info(f"404 Error Triggered | Method: {request_method} | URL: {requested_url} | Client IP: {client_ip}") # 可选:把这些信息传递给404模板,在页面上展示给用户 return render_template( '404.html', method=request_method, url=requested_url, ip=client_ip ), 404
模板中展示请求信息(可选)
如果想在404页面上显示这些细节,你可以修改404.html模板:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>404 - Page Not Found</title> </head> <body> <h1>Oops! That page doesn't exist.</h1> <div class="request-details"> <p><strong>Request Method:</strong> {{ method }}</p> <p><strong>Requested URL:</strong> {{ url }}</p> <p><strong>Your IP Address:</strong> {{ ip }}</p> </div> </body> </html>
注意事项(部署到生产环境时)
如果你的Flask应用部署在反向代理(比如Nginx、Apache)后面,request.remote_addr可能会返回代理服务器的IP,而不是真实的客户端IP。这时候你需要:
- 确保代理服务器会转发
X-Forwarded-For请求头 - 在Flask中配置信任代理,或者手动提取真实IP:
注意:只有当你信任代理服务器时才这么做,避免被伪造的请求头欺骗。@app.before_request def get_real_ip(): if 'X-Forwarded-For' in request.headers: # X-Forwarded-For可能包含多个IP,取第一个就是真实客户端IP request.remote_addr = request.headers['X-Forwarded-For'].split(',')[0].strip()
这样一来,每次触发404错误时,你就能清晰地看到请求的所有关键信息了,不管是排查问题还是做访问分析都很有用。
内容的提问来源于stack exchange,提问作者BeoBeo
相关产品推荐
相关产品推荐

