2

So I am using Django and Python 3.9. I get a KeyError at /myapp/myroute, to which it tells me the value of the key I tried. The problem is it points to line 929, which is 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"]

I've done some googling, and granted I may be looking for the wrong thing, but does anyone have any possible suggestions as to what the problem is? If you could include any other similar problems and solutions to them in your answer, that'd be super helpful. Thank you.

Stack Trace:

 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'

Answer for my specific case:

So I really don't fully understand what was happening, but here are a few more clues. I already have this set up behind apache - ie, I've completed the move to production steps. I was running systemctl start httpd to restart (instead of systemctl restart httpd - oops) the server, which explains why some of my code changes were being reflected, while others (for instance changing some of the settings.py configuration settings) were not reflected. I guess the output from django runs a cat on the erroring file and heads and tails it to output it to the webpage (and due to using start and not restart), so that's why the lines where jumping around and displaying the wrong error? Anyways, the error is being thrown on the right line.

Shmack
  • 1,933
  • 2
  • 18
  • 23
  • 1
    Can you post the stack trace and error message. Ideally you'd post a minimum example that show the error, but that is a pain with django? Also have you tried walking through the commands using django-shell to see if you can trigger it that way? – WombatPM Oct 28 '22 at 02:39
  • I updated the question, but I mean thats the problem, is that I don't know how to recreate the error. I was hoping that someone would have like a general statement as to how this would happen. But I posted some of my code just in case there was something blatant that I was missing. – Shmack Oct 28 '22 at 02:47
  • Mmmm this can happen when the source code has been modified but it is using a cached bytecode fine – juanpa.arrivillaga Oct 28 '22 at 02:58
  • At some point in time, the call to request.session['qrp'] is failing because the key is not found. Problem is you are deep into the nested calls. Some things to try: configure your site to use the django-debug-toolbar so you can better probe what is going on or add a bunch of logging to this function so you can trace how request.session changes through the steps. – WombatPM Oct 28 '22 at 07:24
  • @Wombat but the function is erroring on a line wayyy before the actual call to `request.session['qrp']`. I might have to try `django-debug-toolbar` - thanks for the recommendation. – Shmack Oct 28 '22 at 14:35
  • You may be expecting too much. Debuggers (and that's really what this is) do the best they can with the information they have, poking through and decompiling machine code, but they aren't perfect. That's especially true if you are optimizing. – Tim Roberts Oct 29 '22 at 19:04
  • I think this could truly be an interesting question to have a community answer to - so I am considering revising my original post to remove any content in regards to my specific use case and make it a general question that we can append answers to. Thoughts? – Shmack Oct 29 '22 at 19:09
  • The general question is already answered here so no need. [python - Why does error traceback show edited script instead of what actually ran? - Stack Overflow](https://stackoverflow.com/questions/55492150/why-does-error-traceback-show-edited-script-instead-of-what-actually-ran) – user202729 Nov 02 '22 at 04:25
  • @user202729 so then what is the usual protocol - do I delete this question or leave it as is? is that more up to user preference? I did get +2 upvotes, so I guess I'd not want to delete it :) – Shmack Nov 02 '22 at 04:34

0 Answers0