Inexplicable KeyError in my flask code in the traceback - python

This bug is driving me nuts. I am trying to create the backend of a website in python using flask. I am getting the following error and traceback:
KeyError
KeyError: 'person_id'
Traceback (most recent call last)
This is the Copy/Paste friendly version of the traceback. You can also paste this traceback into a gist:
Traceback (most recent call last):
File "/home/antonina/Desktop/ant/neo4j-flask/lib/python2.7/site-packages/flask/app.py", line 1997, in __call__
return self.wsgi_app(environ, start_response)
File "/home/antonina/Desktop/ant/neo4j-flask/lib/python2.7/site-packages/flask/app.py", line 1985, in wsgi_app
response = self.handle_exception(e)
File "/home/antonina/Desktop/ant/neo4j-flask/lib/python2.7/site-packages/flask/app.py", line 1540, in handle_exception
reraise(exc_type, exc_value, tb)
File "/home/antonina/Desktop/ant/neo4j-flask/lib/python2.7/site-packages/flask/app.py", line 1982, in wsgi_app
response = self.full_dispatch_request()
File "/home/antonina/Desktop/ant/neo4j-flask/lib/python2.7/site-packages/flask/app.py", line 1614, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/home/antonina/Desktop/ant/neo4j-flask/lib/python2.7/site-packages/flask/app.py", line 1517, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/home/antonina/Desktop/ant/neo4j-flask/lib/python2.7/site-packages/flask/app.py", line 1612, in full_dispatch_request
rv = self.dispatch_request()
File "/home/antonina/Desktop/ant/neo4j-flask/lib/python2.7/site-packages/flask/app.py", line 1598, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/home/antonina/Desktop/ant/nic/blog/views.py", line 310, in family_tree
subject_id = session['person_id']
File "/home/antonina/Desktop/ant/neo4j-flask/lib/python2.7/site-packages/werkzeug/local.py", line 377, in <lambda>
__getitem__ = lambda x, i: x._get_current_object()[i]
KeyError: 'person_id'
Also in other form of this traceback:
KeyError
KeyError: 'person_id'
Traceback (most recent call last)
File "/home/antonina/Desktop/ant/neo4j-flask/lib/python2.7/site-packages/flask/app.py", line 1997, in __call__
return self.wsgi_app(environ, start_response)
File "/home/antonina/Desktop/ant/neo4j-flask/lib/python2.7/site-packages/flask/app.py", line 1985, in wsgi_app
[Open an interactive python shell in this frame] response = self.handle_exception(e)
File "/home/antonina/Desktop/ant/neo4j-flask/lib/python2.7/site-packages/flask/app.py", line 1540, in handle_exception
reraise(exc_type, exc_value, tb)
File "/home/antonina/Desktop/ant/neo4j-flask/lib/python2.7/site-packages/flask/app.py", line 1982, in wsgi_app
response = self.full_dispatch_request()
File "/home/antonina/Desktop/ant/neo4j-flask/lib/python2.7/site-packages/flask/app.py", line 1614, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/home/antonina/Desktop/ant/neo4j-flask/lib/python2.7/site-packages/flask/app.py", line 1517, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/home/antonina/Desktop/ant/neo4j-flask/lib/python2.7/site-packages/flask/app.py", line 1612, in full_dispatch_request
rv = self.dispatch_request()
File "/home/antonina/Desktop/ant/neo4j-flask/lib/python2.7/site-packages/flask/app.py", line 1598, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/home/antonina/Desktop/ant/nic/blog/views.py", line 310, in family_tree
subject_id = session['person_id']
File "/home/antonina/Desktop/ant/neo4j-flask/lib/python2.7/site-packages/werkzeug/local.py", line 377, in <lambda>
__getitem__ = lambda x, i: x._get_current_object()[i]
KeyError: 'person_id'
The relevant code is the following, specifically in 3rd line which in my code has line number 310:
#app.route('/family_tree', methods=['GET','POST'])
def family_tree():
subject_id = session['person_id']
if request.method == 'POST':
if request.form['Select'] != 'RETURN' :
subject_id = request.form['Select']
if(subject_id == 'Not_registered') :
subject_id = session['person_id']
else :
return redirect(url_for('person'))
father = mother = ['Not_registered','Not_registered','Not_registered','Not_registered','Not_registered','Not_registered']
siblings = []
mother_node, father_node = Person(subject_id).get_parents()
if (mother_node) :
mother_id = (mother_node[0]['mother.person_id'])
mother = mother_id.split(';')
mother.append(mother_id)
mother.append(get_prof_pic(mother_id))
for sibling in Person(mother_id).get_children_mother() :
if sibling not in siblings and sibling != None and sibling['person.person_id'] != subject_id :
siblings.append(sibling)
if (father_node) :
father_id = (father_node[0]['father.person_id'])
father = father_id.split(';')
father.append(father_id)
father.append(get_prof_pic(father_id))
for sibling in Person(father_id).get_children_father() :
if sibling not in siblings and sibling != None and sibling['person.person_id'] != subject_id :
siblings.append(sibling)
subject = subject_id.split(';')
subject.append(subject_id)
subject.append(get_prof_pic(subject_id))
sibling_list = []
for sibling in siblings :
tmp = sibling['person.person_id'].split(';')
tmp.append(sibling['person.person_id'])
tmp.append(get_prof_pic(sibling['person.person_id']))
sibling_list.append(tmp)
children_f = Person(subject_id).get_children_father()
children_m = Person(subject_id).get_children_mother()
child_list = []
children = []
for child in children_f:
if child not in children and child != None :
children.append(child)
for child in children_m:
if child not in children and child != None :
children.append(child)
for child in children :
tmp = child['person.person_id'].split(';')
tmp.append(child['person.person_id'])
tmp.append(get_prof_pic(child['person.person_id']))
child_list.append(tmp)
return render_template('family_tree.html',
subject=subject,
mother=mother,
father=father,
sibling_list=sibling_list,
child_list=child_list
)

Related

KeyError: 'condition_name' while running python code

i am new to coding. I know all the geniuses are here.
I'm trying to run a python Data science project from git hub.
Here is the link to github : https://github.com/Sparxxz/Flood-Rainfall-Disaster-Prediction-Website
I am getting this error
KeyError: 'condition_name'
Traceback (most recent call last):
File "/home/walia/.local/lib/python3.6/site-packages/flask/app.py", line 2463, in __call__
return self.wsgi_app(environ, start_response)
File "/home/walia/.local/lib/python3.6/site-packages/flask/app.py", line 2449, in wsgi_app
response = self.handle_exception(e)
File "/home/walia/.local/lib/python3.6/site-packages/flask/app.py", line 1866, in handle_exception
reraise(exc_type, exc_value, tb)
File "/home/walia/.local/lib/python3.6/site-packages/flask/_compat.py", line 39, in reraise
raise value
File "/home/walia/.local/lib/python3.6/site-packages/flask/app.py", line 2446, in wsgi_app
response = self.full_dispatch_request()
File "/home/walia/.local/lib/python3.6/site-packages/flask/app.py", line 1951, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/home/walia/.local/lib/python3.6/site-packages/flask/app.py", line 1820, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/home/walia/.local/lib/python3.6/site-packages/flask/_compat.py", line 39, in reraise
raise value
File "/home/walia/.local/lib/python3.6/site-packages/flask/app.py", line 1949, in full_dispatch_request
rv = self.dispatch_request()
File "/home/walia/.local/lib/python3.6/site-packages/flask/app.py", line 1935, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/home/walia/Flood-Rainfall-Disaster-Prediction-Website/sourceCode/main.py", line 64, in floodResult
results_dict=driver.drive(river,user_date)
File "/home/walia/Flood-Rainfall-Disaster-Prediction-Website/sourceCode/driver.py", line 94, in drive
d1=dp.discharge_forecast(filename,wtd)
File "/home/walia/Flood-Rainfall-Disaster-Prediction-Website/sourceCode/discharge_prophet.py", line 163, in discharge_forecast
df4,df2_forecast=predicting_data(wtd)
File "/home/walia/Flood-Rainfall-Disaster-Prediction-Website/sourceCode/discharge_prophet.py", line 155, in predicting_data
df2_forecast = df2_prophet.predict(df2_forecast)
File "/home/walia/.local/lib/python3.6/site-packages/fbprophet/forecaster.py", line 1172, in predict
df = self.setup_dataframe(df.copy())
File "/home/walia/.local/lib/python3.6/site-packages/fbprophet/forecaster.py", line 257, in setup_dataframe
condition_name = props['condition_name']
KeyError: 'condition_name'
This is my predicting_data function
def predicting_data(i=1):
if i==0:
#For testing
# Make a future dataframe for (2 Years)
df2_forecast = df2_prophet.make_future_dataframe(periods=30*25 , freq='D')
# Make predictions
df2_forecast = df2_prophet.predict(df2_forecast)
df3=df2_forecast[['ds','yhat']]
df3.shape,df1.shape,df2.shape
df4=df3.iloc[6940:-20,:]
else:
#For Future prediction of 2019
# Make a future dataframe for 12 months
df2_forecast = df2_prophet.make_future_dataframe(periods=30*12 , freq='D',include_history=False)
# Make predictions
df2_forecast = df2_prophet.predict(df2_forecast)
df3=df2_forecast[['ds','yhat']]
#df3.shape,df1.shape,df2.shape
df4=df3.iloc[:,:]
return df4,df2_forecast
Please help.

ValueError: Type names and field names must be valid identifiers: namedtuple

I have the following in a flask view function (_I'm using python 3.6):
#login_required
#main.route('/dashboard', methods=['GET', 'POST'])
def dashboard():
if request.method =='POST':
dash_data = namedtuple('dash_data',[('posting', str), ('folder', str)])
print(request.form.get('posting'))
posted_data= dash_data(posting=request.form.get('posting'),folder=request.form.get('folder'))
I'm getting:
Traceback (most recent call last):
File "...\lib\site-packages\flask\app.py", line 1997, in __call__
return self.wsgi_app(environ, start_response)
File "...\lib\site-packages\flask\app.py", line 1985, in wsgi_app
response = self.handle_exception(e)
File "...\lib\site-packages\flask\app.py", line 1540, in handle_exception
reraise(exc_type, exc_value, tb)
File "...\lib\site-packages\flask\_compat.py", line 33, in reraise
raise value
File "...\lib\site-packages\flask\app.py", line 1982, in wsgi_app
response = self.full_dispatch_request()
File "...\lib\site-packages\flask\app.py", line 1614, in full_dispatch_request
rv = self.handle_user_exception(e)
File "...\lib\site-packages\flask\app.py", line 1517, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "...\lib\site-packages\flask\_compat.py", line 33, in reraise
raise value
File "...\lib\site-packages\flask\app.py", line 1612, in full_dispatch_request
rv = self.dispatch_request()
File "...\lib\site-packages\flask\app.py", line 1598, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "E:\ENVS\r3\posterizer2\app\main\views.py", line 387, in cl_dash
Cl_dash_data = namedtuple('cl_dash_data',[('posting', str), ('folder', str)])
File "...\lib\collections\__init__.py", line 403, in namedtuple
'identifiers: %r' % name)
ValueError: Type names and field names must be valid identifiers: "('posting', <class 'str'>)"
What am I doing wrong?
namedtuple objects don't accept a list of (attribute, type) tuples, they just expect an iterable of attributes (or a single string):
namedtuple('dash_data', ('posting', 'folder'))
Or:
namedtuple('dash_data', 'posting folder')
Refer to the documentation for how to use namedtuple.
maybe you can use NamedTuple from typing module
using like follow:
from typing import NamedTuple
dash_data = NamedTuple('dash_data',[('posting', str), ('folder', str)])

Python Flask WTF save from fields without listing all request.froms in route

Hi want to save the information being posted to the database. I am using python flask and this is the way i attempted it.
#app.route('/add-new-song',methods=['GET','POST'])
def add_new_song():
form = NewSongForm(request.form)
if form.validate_on_submit():
new_song = SongBook()
form.populate_obj(new_song)
db.session.add(new_song)
db.session.commit()
return render_template('add-new-song.html',form=form)
When i try this i get this error:
TypeError: __ init __() takes exactly 6 arguments (1 given)
Any thoughts on how to do this?
here are the models
class SongBook(db.Model):
id = db.Column(db.Integer, primary_key=True)
song_book = db.Column(db.String(80))
title = db.Column(db.String(120))
artist = db.Column(db.String(120))
disc_number = db.Column(db.String(120))
track_number = db.Column(db.String(120))
def __init__(self, song_book, title, artist, disc_number, track_number):
self.song_book = song_book
self.title = title
self.artist = artist
self.disc_number = disc_number
self.track_number = track_number
trace back
TypeError: __init__() takes exactly 6 arguments (1 given)
Traceback (most recent call last)
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 2000, in __call__
return self.wsgi_app(environ, start_response)
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1991, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "/usr/local/lib/python2.7/dist-packages/flask_restful/__init__.py", line 271, in error_router
return original_handler(e)
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1567, in handle_exception
reraise(exc_type, exc_value, tb)
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1988, in wsgi_app
response = self.full_dispatch_request()
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1641, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/usr/local/lib/python2.7/dist-packages/flask_restful/__init__.py", line 271, in error_router
return original_handler(e)
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1544, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1639, in full_dispatch_request
rv = self.dispatch_request()
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1625, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/home/a/Desktop/ddtkaraoke.com/app.py", line 118, in add_new_song
new_song = SongBook()
TypeError: __init__() takes exactly 6 arguments (1 given)

Error when adding image to MongoDB list of images in Flask-Admin

I have this model:
class Merchandise(Document):
image_gallery = ListField(ImageField(collection_name='image'))
When I add an image in Flask-Admin, I get this error:
Traceback (most recent call last):
File "/home/lov3catch/lov3catch_venvs/profit_sellet/lib/python2.7/site-packages/flask/app.py", line 1836, in __call__
return self.wsgi_app(environ, start_response)
File "/home/lov3catch/lov3catch_venvs/profit_sellet/lib/python2.7/site-packages/flask/app.py", line 1820, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "/home/lov3catch/lov3catch_venvs/profit_sellet/lib/python2.7/site-packages/flask/app.py", line 1403, in handle_exception
reraise(exc_type, exc_value, tb)
File "/home/lov3catch/lov3catch_venvs/profit_sellet/lib/python2.7/site-packages/flask/app.py", line 1817, in wsgi_app
response = self.full_dispatch_request()
File "/home/lov3catch/lov3catch_venvs/profit_sellet/lib/python2.7/site-packages/flask/app.py", line 1477, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/home/lov3catch/lov3catch_venvs/profit_sellet/lib/python2.7/site-packages/flask/app.py", line 1381, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/home/lov3catch/lov3catch_venvs/profit_sellet/lib/python2.7/site-packages/flask/app.py", line 1475, in full_dispatch_request
rv = self.dispatch_request()
File "/home/lov3catch/lov3catch_venvs/profit_sellet/lib/python2.7/site-packages/flask/app.py", line 1461, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/home/lov3catch/lov3catch_venvs/profit_sellet/lib/python2.7/site-packages/flask_admin/base.py", line 68, in inner
return self._run_view(f, *args, **kwargs)
File "/home/lov3catch/lov3catch_venvs/profit_sellet/lib/python2.7/site-packages/flask_admin/base.py", line 344, in _run_view
return fn(self, *args, **kwargs)
File "/home/lov3catch/lov3catch_venvs/profit_sellet/lib/python2.7/site-packages/flask_admin/model/base.py", line 1374, in edit_view
if self.update_model(form, model):
File "/home/lov3catch/lov3catch_venvs/profit_sellet/lib/python2.7/site-packages/flask_admin/contrib/mongoengine/view.py", line 536, in update_model
if not self.handle_view_exception(ex):
File "/home/lov3catch/lov3catch_venvs/profit_sellet/lib/python2.7/site-packages/flask_admin/contrib/mongoengine/view.py", line 534, in update_model
model.save()
File "/home/lov3catch/lov3catch_venvs/profit_sellet/lib/python2.7/site-packages/mongoengine/document.py", line 224, in save
self.validate(clean=clean)
File "/home/lov3catch/lov3catch_venvs/profit_sellet/lib/python2.7/site-packages/mongoengine/base/document.py", line 323, in validate
raise ValidationError(message, errors=errors)
ValidationError: ValidationError (Merchandise:54c0190f39731e3198f93c6d) ('NoneType' object has no attribute 'grid_id': ['image_gallery'])
How do I fix this?
something like this
class Media(EmbeddedDocument):
img = ImageField(collection_name='image')
class Merchandise(Document):
image_gallery = ListField(EmbeddedDocumentField(Media))

GAE ndb put() argument error

I am trying to save an object to GAE's datastore. When doing this I am getting the error:
Traceback (most recent call last):
File "/Users/Soderstrom/google-cloud-sdk/.install/.backup/platform/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/runtime/wsgi.py", line 267, in Handle
result = handler(dict(self._environ), self._StartResponse)
File "/Users/Soderstrom/PycharmProjects/MyApp/lib/python2.7/site-packages/flask/app.py", line 1836, in __call__
return self.wsgi_app(environ, start_response)
File "/Users/Soderstrom/PycharmProjects/MyApp/lib/python2.7/site-packages/flask/app.py", line 1820, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "/Users/Soderstrom/PycharmProjects/MyApp/lib/python2.7/site-packages/flask/app.py", line 1403, in handle_exception
reraise(exc_type, exc_value, tb)
File "/Users/Soderstrom/PycharmProjects/MyApp/lib/python2.7/site-packages/flask/app.py", line 1817, in wsgi_app
response = self.full_dispatch_request()
File "/Users/Soderstrom/PycharmProjects/MyApp/lib/python2.7/site-packages/flask/app.py", line 1477, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/Users/Soderstrom/PycharmProjects/MyApp/lib/python2.7/site-packages/flask/app.py", line 1381, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/Users/Soderstrom/PycharmProjects/MyApp/lib/python2.7/site-packages/flask/app.py", line 1475, in full_dispatch_request
rv = self.dispatch_request()
File "/Users/Soderstrom/PycharmProjects/MyApp/lib/python2.7/site-packages/flask/app.py", line 1461, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/Users/Soderstrom/PycharmProjects/MyApp/main.py", line 559, in backends
db.save(v.getFastigheter(), '1')
TypeError: put() takes exactly 1 argument (2 given)
This is independent of the actual amount of arguments passed to the entity creator.
db.save(v.getSomeData(), '1') <- main.py, line 559
db.load('1')
This is the db module:
class ndbc(ndb.Model):
val = ndb.PickleProperty(compressed=True, indexed=False)
key_name = ndb.PickleProperty(indexed=True)
#classmethod
def set(cls, key_t, val_t):
entity = cls(val=val, key_name=key)
entity.put()
return val_t
def save(obj, name):
return ndbc.set(name, obj)
Don't you mean entity = cls(val=val_t, key_name=key_t)? Also, key_name is an old db property. For ndb, you should use id:
https://docs.google.com/document/d/1AefylbadN456_Z7BZOpZEXDq8cR8LYu7QgI7bt5V0Iw/mobilebasic
Not sure id can be a PickleProperty. Interested to see if this works.

Categories