Skip to content

Instantly share code, notes, and snippets.

@takwas
Created November 13, 2015 00:46
Show Gist options
  • Save takwas/ebf539f8edd35181bd85 to your computer and use it in GitHub Desktop.
Save takwas/ebf539f8edd35181bd85 to your computer and use it in GitHub Desktop.
Debugging: UndefinedError: 'flask.ctx._AppCtxGlobals object' has no attribute 'user'
# File: Controllers.py (in Blueprint module)
# ...
# this function is called before every request
@user.before_request
def load_notifs():
# This function should load before every request to
# check for any new notifications and messages
g.notifications = []
g.unread_notif_count = 0
g.unread_notif_ids = []
g.inboxes = []
g.outboxes = []
g.unread_msg_count = 0
g.unread_msg_ids = []
if session.get('in_session'): # if user is in session
param_dict = {}
param_dict['username'] = session.get('username')
user = db_ops.ret_val(db_ops.User, param_dict) # retrieve user from DB
g.user = user
# Inner function to get number of unread notifications
def get_unread_notif_count(notifs):
unread_count = 0
if notifs is not None:
for notif in notifs:
if notif.notif_status=='Unread':
g.unread_notif_ids.append(notif.notif_id)
unread_count += 1
return unread_count
#end function
# Inner function to get number of unread messages
def get_unread_msg_count(msgs):
unread_count = 0
if msgs is not None:
for msg in msgs:
if msg.msg_status=='Unread':
g.unread_msg_ids.append(msg.msg_id)
unread_count += 1
return unread_count
#end function
if g.user is not None:
# load notifications
param_dict.clear()
param_dict['notif_owner_id'] = user.user_id
notifications = db_ops.ret_all_val(db_ops.Notification, param_dict) # load all users notifications
g.notifications = notifications
unread_notif_count = get_unread_notif_count(notifications) #len(all_unread_notifs)
g.unread_notif_count = unread_notif_count
####TODO: Implement feature to include messages to and from admin
# load inbox messages
param_dict.clear()
param_dict['msg_recp_id'] = user.user_id
inboxes = db_ops.ret_all_val(db_ops.Message, param_dict) # load all user's received messages
g.inboxes = inboxes
unread_msg_count = get_unread_msg_count(inboxes) #len(all_unread_msgss)
g.unread_msg_count = unread_msg_count
# load outbox messages
param_dict.clear()
param_dict['msg_sender_id'] = user.user_id
outboxes = db_ops.ret_all_val(db_ops.Message, param_dict) # load all user's sent messages
g.outboxes = outboxes
####TODO: Implement this
# get number of unread events
# def get_unread_events_count():
# param_dict = {}
# param_dict[]
# events = db_ops.ret_all_val(db_ops.EventPost)
# return len(events)
else:
utils.del_session(session)
# ...
# VIEW FUNCTIONS:
@user.route('/')
@user.route('/index')
def index():
if session.get('in_session', False):
return redirect(url_for('user.feeds'))
return render_template('user/index.html', login_form = LoginForm())
@user.route('/feeds', methods=['GET', 'POST'])
def feeds():
# no user in session; go to homepage
if session.get('in_session', False) is False:
return redirect(url_for('user.index'))
else:
# user simply visiting feeds page; render the page, providing a forms alongside
if request.method=='GET':
status_post_form = StatusPostForm()
image_post_form = ImagePostForm()
return render_template('user/feeds.html', status_post_form=status_post_form, image_post_form=image_post_form)
# user submitting a form
elif request.method=='POST':
#initialize form types
status_post_form = None
image_post_form = None
# check type of form being submitted
if 'content_fld' in request.form:
# form is a status update form; process accordingly
status_post_form = StatusPostForm(request.form)
# form input was valid
if status_post_form.validate_on_submit():
param_dict = {}
param_dict['post_owner_id'] = g.user.user_id
param_dict['content'] = status_post_form.content_fld.data.decode('utf-8')
param_dict['img_name'] = status_post_form.img_fld.data or None
db_ops.insert_val(db_ops.StatusPost, param_dict)
flash("New status posted successfully!")
# form input was invalid
else:
flash("Your status post was not submitted.")
else:
# form is an image upload form; process accordingly
image_post_form = ImagePostForm(request.form)
# form input was valid
if image_post_form.validate_on_submit():
# retrieve uploaded image file object from request
img_file = request.files.get('img_fld', None)
if img_file is not None:
#config['IMG_ALLOWED_EXTENSIONS'] is imported from forms.py
image_was_saved, img_name = utils.save_image(img_file=request.files['img_fld'], \
upload_folder=flask.current_app.config['GALLERY_IMG_UPLOADS_FOLDER']+g.user.username+"/", \
allowed_extensions=config['IMG_ALLOWED_EXTENSIONS'], prefix=g.user.username)
print "HEREEEEEEEEEEEEEEEEEEEEEEEEE 33333"
if image_was_saved:
param_dict = {}
param_dict['img_poster_id'] = g.user.user_id
param_dict['img_name'] = img_name
print "FOLDER: %r\nFILENAME: %r" %(flask.current_app.config['GALLERY_IMG_UPLOADS_FOLDER'], img_name) ####DEBUG
db_ops.insert_val(db_ops.ImagePost, param_dict)
print "HEREEEEEEEEEEEEEEEEEEEEEEEEE 4444"
flash("New image uploaded successfully!")
else:
flash("Your image failed to upload. Image was not saved.")
else:
flash("Your image failed to upload. No image provided.")
# form input was invalid
else:
flash("Your image failed to upload. Form input invalid!")
# reload feeds page as a 'GET' request
return redirect(url_for('user.feeds'))
# Jinja2 Template
<!-- File: include_navbar.html -->
<nav class="navbar navbar-default navbar-static-top wantedo navbar-fixed-top" role="navigation" style="">
<div class="container-fluid">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#"> <img src="../static/image/krohx.png" alt=""></a>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav">
<li class="active"><a href="{{url_for('user.index')}}">SanctaCrux Alumni</a></li>
<li></li>
<li>
<div class="navbar_session_wrap">
<form accept-charset="UTF-8" action="/search" class="navbar-form navbar-left" data-remote="true" id="search" method="post"><div style="display:none"><input name="utf8" value="✓" type="hidden"></div>
<div class="form-group">
<i class="icon-magnifier"></i>
<input class="search_field form-control" id="query" name="query" placeholder="Search" type="text">
</div>
</form>
</div> <!-- navbar_session_wrap -->
</li>
</ul>
{%if session.in_session%}
<ul class="nav navbar-nav navbar-right">
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">
<img src="{{url_for('static', filename=config.PROFILE_IMG_UPLOADS_FOLDER + g.user.user_details.profile_img_name|default(config.DEFAULT_SILHOUETTE_UNKNOWN))}}" alt="img_{{session.f_name|lower}}" class="nav_profile_image" width="100" height="100" />
Hi {{ session.l_name|default('user')|title }}!
<b class="caret"></b>
</a>
<ul class="dropdown-menu" style="min-width: 350px;">
<div class="row" style="margin-left: 0px; margin-right: 0px;">
<div class="col-sm-6" style="padding-right: 0px; margin-right: 0px;">
<li class="dropdown-header">MY STUFF</li>
<li><a href="#">Placeholder 1</a></li>
<li><a href="#">Placeholder 2</a></li>
</div>
<div class="col-sm-6" style="padding-right: 0px; margin-right: 0px;">
<li class="dropdown-header">MY ACCOUNT</li>
<li><a href="{{url_for('user.profile')}}">Profile</a></li>
<li><a href="{{url_for('user.settings_account')}}">Settings</a></li>
<li class="divider"></li>
<li><a href="{{url_for('user.login')}}" class="signout">Signout</a></li>
</div>
</div> <!-- row -->
</ul>
</li>
</ul>
<ul class="nav navbar-nav navbar-right">
{####TODO: Segun PLEASE EDIT THIS MSGS & NOTIFICATIONS AREA#}
<li class="dropdown">{#Display Messages count#}
<a href="{{url_for('user.messages')}}">
<strong class="glyphicon glyphicon-envelope"></strong>
<sup class="subp">
{% if g.unread_msg_count==None or g.unread_msg_count < 1 %}
{{''}}
{% elif g.unread_msg_count > 99 %}
{{"99+"}}
{% else%}
{{g.unread_msg_count}}
{%endif%}
</sup>
</a>
</li>
<li class="dropdown">{#Display Notifications count#}
<a href="{{url_for('user.notifications')}}">
<strong class="glyphicon glyphicon-bell"></strong>
<sup class="subp">
{% if g.unread_notif_count==None or g.unread_notif_count < 1 %}
{{''}}
{% elif g.unread_notif_count > 99 %}
{{"99+"}}
{% else%}
{{g.unread_notif_count}}
{%endif%}
</sup>
</a>
</li>
</ul>
{%else%}
{#No user in session#}
<ul class="nav navbar-nav navbar-right">
<li class="dropdown">
<a href="{{url_for('user.login')}}">
<strong class="glyphicon glyphicon-log-in"></strong>
Sign in
</a>
</li>
</ul>
{%endif%}
</div><!-- /.navbar-collapse -->
</div><!-- /.container-fluid -->
</nav>
# Traceback
Traceback (most recent call last):
File "/home/acetakwas/dev/my_virtualenvs/flask_venv/lib/python2.7/site-packages/flask/app.py", line 1836, in __call__
return self.wsgi_app(environ, start_response)
File "/home/acetakwas/dev/my_virtualenvs/flask_venv/lib/python2.7/site-packages/flask/app.py", line 1820, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "/home/acetakwas/dev/my_virtualenvs/flask_venv/lib/python2.7/site-packages/flask/app.py", line 1403, in handle_exception
reraise(exc_type, exc_value, tb)
File "/home/acetakwas/dev/my_virtualenvs/flask_venv/lib/python2.7/site-packages/flask/app.py", line 1817, in wsgi_app
response = self.full_dispatch_request()
File "/home/acetakwas/dev/my_virtualenvs/flask_venv/lib/python2.7/site-packages/flask/app.py", line 1477, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/home/acetakwas/dev/my_virtualenvs/flask_venv/lib/python2.7/site-packages/flask/app.py", line 1370, in handle_user_exception
return self.handle_http_exception(e)
File "/home/acetakwas/dev/my_virtualenvs/flask_venv/lib/python2.7/site-packages/flask/app.py", line 1330, in handle_http_exception
return handler(e)
File "/home/acetakwas/dev/web_dev/flask_web_dev/proj/sancta_crux/sancta_crux/sancta_crux_app/user_mod/errors.py", line 8, in page_not_found
return render_template('404.html'), 404
File "/home/acetakwas/dev/my_virtualenvs/flask_venv/lib/python2.7/site-packages/flask/templating.py", line 128, in render_template
context, ctx.app)
File "/home/acetakwas/dev/my_virtualenvs/flask_venv/lib/python2.7/site-packages/flask/templating.py", line 110, in _render
rv = template.render(context)
File "/home/acetakwas/dev/my_virtualenvs/flask_venv/lib/python2.7/site-packages/jinja2/environment.py", line 969, in render
return self.environment.handle_exception(exc_info, True)
File "/home/acetakwas/dev/my_virtualenvs/flask_venv/lib/python2.7/site-packages/jinja2/environment.py", line 742, in handle_exception
reraise(exc_type, exc_value, tb)
File "/home/acetakwas/dev/web_dev/flask_web_dev/proj/sancta_crux/sancta_crux/sancta_crux_app/templates/404.html", line 3, in top-level template code
{% extends "base.html" %}
File "/home/acetakwas/dev/web_dev/flask_web_dev/proj/sancta_crux/sancta_crux/sancta_crux_app/templates/base.html", line 3, in top-level template code
{% extends "bootstrap/base.html" %}
File "/home/acetakwas/dev/my_virtualenvs/flask_venv/lib/python2.7/site-packages/flask_bootstrap/templates/bootstrap/base.html", line 1, in top-level template code
{% block doc -%}
File "/home/acetakwas/dev/my_virtualenvs/flask_venv/lib/python2.7/site-packages/flask_bootstrap/templates/bootstrap/base.html", line 4, in block "doc"
{%- block html %}
File "/home/acetakwas/dev/my_virtualenvs/flask_venv/lib/python2.7/site-packages/flask_bootstrap/templates/bootstrap/base.html", line 20, in block "html"
{% block body -%}
File "/home/acetakwas/dev/my_virtualenvs/flask_venv/lib/python2.7/site-packages/flask_bootstrap/templates/bootstrap/base.html", line 21, in block "body"
{% block navbar %}
File "/home/acetakwas/dev/web_dev/flask_web_dev/proj/sancta_crux/sancta_crux/sancta_crux_app/templates/404.html", line 7, in block "navbar"
{{ super() }}
File "/home/acetakwas/dev/web_dev/flask_web_dev/proj/sancta_crux/sancta_crux/sancta_crux_app/templates/base.html", line 65, in block "navbar"
{%include 'include_navbar.html'%}
File "/home/acetakwas/dev/web_dev/flask_web_dev/proj/sancta_crux/sancta_crux/sancta_crux_app/templates/include_navbar.html", line 35, in top-level template code
<img src="{{url_for('static', filename=config.PROFILE_IMG_UPLOADS_FOLDER + g.user.user_details.profile_img_name|default(config.DEFAULT_SILHOUETTE_UNKNOWN))}}" alt="img_{{session.f_name|lower}}" class="nav_profile_image" width="100" height="100" />
File "/home/acetakwas/dev/my_virtualenvs/flask_venv/lib/python2.7/site-packages/jinja2/environment.py", line 397, in getattr
return getattr(obj, attribute)
UndefinedError: 'flask.ctx._AppCtxGlobals object' has no attribute 'user'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment