Python/Django报错指向错误行?KeyError定位异常排查
问题:Django路由访问出现KeyError且错误行显示异常
使用Django + Python 3.9,访问路由/myapp/myroute时触发KeyError at /myapp/myroute,提示了对应的键值,但错误堆栈指向第929行的else:语句,并非实际出错位置。
相关代码
# this is the path to the main image if "filename" in request.session: if "file_url" in request.session: ip = request.session["file_url"] # error here - this is line 925 in my code else: s3 = boto3.client('s3') ip = f"""{request.session["iam"]}/image/{request.session["filename"]}""" request.session["file_url"] = ip if ip != us.ImagePath: change = True else: return redirect("index") s3r = boto3.resource("s3") obj = None if "qrp" not in request.session: request.session["qrp"] = "" try: request.session["qrp"] = f"""{request.session["iam"]}/sub_image/{str(request.session["usid"])}.png""" obj = s3r.Object('iet-ticket-bucket', qrfn) obj.load() except botocore.exceptions.ClientError as e: if e.response["Error"]["Code"] == "404": img = q.make(json.dumps({"id": request.session["usid"], "storename": ""})) iba = io.BytesIO() img.save(iba, format="PNG") s3 = boto3.client('s3') s3.put_object(Bucket="iet-ticket-bucket", Key=request.session["qrp"], Body=iba.getvalue(), ContentType="image/png") request.session["qrp"] = qrp change = True # where the error should be qrp = request.session["qrp"]
堆栈跟踪信息
Traceback (most recent call last): File "/home/ec2-user/django/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/home/ec2-user/django/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/ec2-user/DjangoProjects/appws/app/views.py", line 926, in thank_you else: File "/home/ec2-user/django/django/contrib/sessions/backends/base.py", line 53, in __getitem__ return self._session[key] KeyError: 'qrp'
排查结果
经排查,问题根源在于服务器部署在Apache后,仅执行systemctl start httpd而非systemctl restart httpd重启服务,导致代码更新不彻底,错误行显示异常。实际错误发生在qrp = request.session["qrp"]行。
内容的提问来源于stack exchange,提问作者Shmack
相关产品推荐
相关产品推荐

