Blogz (KeyError when using @app.before_request)


I have everything on my Blogz assignment complete except when a viewer(someone not signed in) goes into a specific blog and clicks on the user name. It should return back to the user page with all that users blogs but I’m getting a KeyError. What is crazy is that this redirect works when a user is signed in so I know it probably has something to do with my @app.before_request.

My_blogs is the route that is giving me this problem.

Is this an error because there isn’t a user technically signed in? How can I go about fixing it? I’ve made several attempts of creating variables and conditional statements but nothing is working.


Usually I get a key error when it tries to load a page/follow a path but by another route where the required input is not asked for. Setting up a separate GET and POST for the path fixes things.


I replaced the else statement under my_blogs with:
if request.method == ‘POST’:
return redirect('singleuser.html)
and I got the error again. Am I putting it in the wrong place?


Well, so the viewer, who is not logged in, will have provided no username. So they may have no username in the session data, which you call. If, when they click the link to the blog, that sets the username in your session data, then there should be information behind that variable. Does that make sense?


Okay. So I need to add something behind the username = session[‘username’].first() that will allow a viewer to see the blog page of the selected user? I’m not sure if I know which variable you are referring to.


Of course, if you do that, it would make it seem like the viewer WAS the user. The main thing is, if you call a variable, and then use it to navigate, it has to have a value.

There has to be a way to allow navigation to the user’s page, both for the user and for a viewer. That would be up to you to code that.


Okay thanks! I get it! I just need to figure out how to code it. Thank you for your help!


For sure, I hope it helped.