Related
I don't know where my problem is. Because years is char field must be string not bool.
I feel really frustrated. What can I do to fix this problem?
Any sort of help will be much appreciated!
Please give me some suggestions. Thanks!
Here is my code:
class HreDetailList(models.EcoModel):
_name = "hre.detail.list"
def _compute_holiday_flag(self):
for record in self:
record.work_on_holiday = False
now_year = int(record.years[:4])
next_year = now_year + 1
holiday_obj = self.env['hra.holiday']
holiday_data = holiday_obj.search([('holi_yy', 'ilike', next_year),
('holi_name', '=', 'Xmas')])
change_obj = self.env['hre.changedtl']
change_data = change_obj.search([('hre_empbas_id.emp_no', '=', record.emp_no),
('trans_flag', '=', True),
('lt_startdate', '=like', record.years[:4] + '%')])
for change_datadtl in change_data:
if change_datadtl.chg_kind == '6M' or change_datadtl.chg_kind == '6N' or change_datadtl.chg_kind == '6L':
if holiday_data.holi_date >= change_datadtl.lt_startdate and holiday_data.holi_date <= change_datadtl.lt_enddate:
record.work_on_holiday = True
break
else:
record.work_on_holiday = False
years = fields.Char(string='Year', size=7, required=True)
work_on_holiday = fields.Boolean(compute=_compute_holiday_flag, string='Work on holiday')
I am getting following error: TypeError: 'bool' object is not subscriptable:
Odoo Server Error
Traceback (most recent call last):
File "/vagrant/odoo/odoo/addons/base/models/ir_http.py", line 237, in _dispatch
result = request.dispatch()
File "/vagrant/odoo/odoo/http.py", line 682, in dispatch
result = self._call_function(**self.params)
File "/vagrant/odoo/odoo/http.py", line 358, in _call_function
return checked_call(self.db, *args, **kwargs)
File "/vagrant/odoo/odoo/service/model.py", line 94, in wrapper
return f(dbname, *args, **kwargs)
File "/vagrant/odoo/odoo/http.py", line 346, in checked_call
result = self.endpoint(*a, **kw)
File "/vagrant/odoo/odoo/http.py", line 911, in __call__
return self.method(*args, **kw)
File "/vagrant/odoo/odoo/http.py", line 530, in response_wrap
response = f(*args, **kw)
File "/vagrant/odoo/addons/web/controllers/main.py", line 1359, in call_kw
return self._call_kw(model, method, args, kwargs)
File "/vagrant/odoo/addons/web/controllers/main.py", line 1351, in _call_kw
return call_kw(request.env[model], method, args, kwargs)
File "/vagrant/odoo/odoo/api.py", line 396, in call_kw
result = _call_kw_multi(method, model, args, kwargs)
File "/vagrant/odoo/odoo/api.py", line 383, in _call_kw_multi
result = method(recs, *args, **kwargs)
File "/vagrant/odoo/odoo/models.py", line 6165, in onchange
value = record[name]
File "/vagrant/odoo/odoo/models.py", line 5640, in __getitem__
return self._fields[key].__get__(self, type(self))
File "/vagrant/odoo/odoo/fields.py", line 972, in __get__
self.compute_value(recs)
File "/vagrant/odoo/odoo/fields.py", line 1111, in compute_value
records._compute_field_value(self)
File "/vagrant/odoo/odoo/models.py", line 4037, in _compute_field_value
field.compute(self)
File "/vagrant/odoo/addons/hre_formwork/models/hre_formwork.py", line 3887, in_compute_holiday_flag
now_year = int(record.years[:4])
Exception
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/vagrant/odoo/odoo/http.py", line 638, in _handle_exception
return super(JsonRequest, self)._handle_exception(exception)
File "/vagrant/odoo/odoo/http.py", line 314, in _handle_exception
raise exception.with_traceback(None) from new_cause
TypeError: 'bool' object is not subscriptable
I am running a flask application, to which I am getting an OPTIONS call, on the following URL,
/test//
The correct domain name is /test/user-name/. But somehow the username is missing in the options call.
The above scenario results in my application to break.
The traceback is as follows:
Traceback (most recent call last):
File "/home/company/Documents/project/lib/python3.8/site-packages/werkzeug/serving.py", line 323, in run_wsgi
execute(self.server.app)
File "/home/company/Documents/project/lib/python3.8/site-packages/werkzeug/serving.py", line 312, in execute
application_iter = app(environ, start_response)
File "/home/company/Documents/project/lib/python3.8/site-packages/flask/app.py", line 2464, in __call__
return self.wsgi_app(environ, start_response)
File "/home/company/Documents/project/lib/python3.8/site-packages/flask_request_id_header/middleware/__init__.py", line 51, in __call__
return self.app(environ, new_start_response)
File "/home/company/Documents/project/lib/python3.8/site-packages/newrelic/api/wsgi_application.py", line 664, in _nr_wsgi_application_wrapper_
result = _WSGIApplicationMiddleware(wrapped,
File "/home/company/Documents/project/lib/python3.8/site-packages/newrelic/api/wsgi_application.py", line 192, in __init__
self.iterable = self.application(self.request_environ,
File "/home/company/Documents/project/lib/python3.8/site-packages/flask/app.py", line 2450, in wsgi_app
response = self.handle_exception(e)
File "/home/company/Documents/project/lib/python3.8/site-packages/flask_cors/extension.py", line 161, in wrapped_function
return cors_after_request(app.make_response(f(*args, **kwargs)))
File "/home/company/Documents/project/lib/python3.8/site-packages/flask_restful/__init__.py", line 269, in error_router
return original_handler(e)
File "/home/company/Documents/project/lib/python3.8/site-packages/newrelic/hooks/framework_flask.py", line 108, in _nr_wrapper_Flask_handle_exception_
return wrapped(*args, **kwargs)
File "/home/company/Documents/project/lib/python3.8/site-packages/flask/app.py", line 1867, in handle_exception
reraise(exc_type, exc_value, tb)
File "/home/company/Documents/project/lib/python3.8/site-packages/flask/_compat.py", line 39, in reraise
raise value
File "/home/company/Documents/project/lib/python3.8/site-packages/flask/app.py", line 2447, in wsgi_app
response = self.full_dispatch_request()
File "/home/company/Documents/project/lib/python3.8/site-packages/flask/app.py", line 1952, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/home/company/Documents/project/lib/python3.8/site-packages/flask_cors/extension.py", line 161, in wrapped_function
return cors_after_request(app.make_response(f(*args, **kwargs)))
File "/home/company/Documents/project/lib/python3.8/site-packages/flask_restful/__init__.py", line 269, in error_router
return original_handler(e)
File "/home/company/Documents/project/lib/python3.8/site-packages/newrelic/hooks/framework_flask.py", line 108, in _nr_wrapper_Flask_handle_exception_
return wrapped(*args, **kwargs)
File "/home/company/Documents/project/lib/python3.8/site-packages/flask/app.py", line 1816, in handle_user_exception
return self.handle_http_exception(e)
File "/home/company/Documents/project/lib/python3.8/site-packages/newrelic/hooks/framework_flask.py", line 90, in _nr_wrapper_Flask_handle_http_exception_
return wrapped(*args, **kwargs)
File "/home/company/Documents/project/lib/python3.8/site-packages/flask/app.py", line 1744, in handle_http_exception
return handler(e)
File "/home/company/Documents/project/lib/python3.8/site-packages/newrelic/hooks/framework_flask.py", line 126, in _nr_wrapper_error_handler_
return wrapped(*args, **kwargs)
File "/home/company/Documents/project/service/app/code_service.py", line 81, in page_not_found
return Response(
File "/home/company/Documents/project/lib/python3.8/site-packages/werkzeug/wrappers/base_response.py", line 187, in __init__
self.headers = Headers(headers)
File "/home/company/Documents/project/lib/python3.8/site-packages/werkzeug/datastructures.py", line 958, in __init__
self.extend(defaults)
File "/home/company/Documents/project/lib/python3.8/site-packages/werkzeug/datastructures.py", line 1101, in extend
for key, value in iter_multi_items(args[0]):
ValueError: too many values to unpack (expected 2) | line-113 |
Kindly help me figure out the fix for this. Here is the link to the app.py file.
https://github.com/shubhamkumar0/medilink/blob/master/app.py
Thanks in Advance!
The response header was being passed as a set, which I changed to map and the issue got resolved. Thanks for your time.
I'm getting an index error when running a query / piece of code that clearly doesn't have index errors.
#cognito_required
def put(self, stage: str):
data = Default.validator.parse_args()
table = user_client_association_table
db.session.query().\
filter(table.c.client_id == data["client_id"]).\
filter(table.c.user_id == data["user_id"]).\
update({"is_default": 1})
db.session.commit()
return {
"data": {
"code": 200,
"message": f"The default user_id has been updated for the client {data['client_id']}",
}
}, 200
This is the full traceback:
Traceback (most recent call last):
File "/home/ericson/Workspace/concil-v4-api/venv/lib/python3.8/site-packages/werkzeug/serving.py", line 323, in run_wsgi
execute(self.server.app)
File "/home/ericson/Workspace/concil-v4-api/venv/lib/python3.8/site-packages/werkzeug/serving.py", line 312, in execute
application_iter = app(environ, start_response)
File "/home/ericson/Workspace/concil-v4-api/venv/lib/python3.8/site-packages/flask/app.py", line 2464, in __call__
return self.wsgi_app(environ, start_response)
File "/home/ericson/Workspace/concil-v4-api/venv/lib/python3.8/site-packages/flask/app.py", line 2450, in wsgi_app
response = self.handle_exception(e)
File "/home/ericson/Workspace/concil-v4-api/venv/lib/python3.8/site-packages/flask_cors/extension.py", line 165, in wrapped_function
return cors_after_request(app.make_response(f(*args, **kwargs)))
File "/home/ericson/Workspace/concil-v4-api/venv/lib/python3.8/site-packages/flask_restful/__init__.py", line 272, in error_router
return original_handler(e)
File "/home/ericson/Workspace/concil-v4-api/venv/lib/python3.8/site-packages/flask/app.py", line 1867, in handle_exception
reraise(exc_type, exc_value, tb)
File "/home/ericson/Workspace/concil-v4-api/venv/lib/python3.8/site-packages/flask/_compat.py", line 38, in reraise
raise value.with_traceback(tb)
File "/home/ericson/Workspace/concil-v4-api/venv/lib/python3.8/site-packages/flask/app.py", line 2447, in wsgi_app
response = self.full_dispatch_request()
File "/home/ericson/Workspace/concil-v4-api/venv/lib/python3.8/site-packages/flask/app.py", line 1952, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/home/ericson/Workspace/concil-v4-api/venv/lib/python3.8/site-packages/flask_cors/extension.py", line 165, in wrapped_function
return cors_after_request(app.make_response(f(*args, **kwargs)))
File "/home/ericson/Workspace/concil-v4-api/venv/lib/python3.8/site-packages/flask_restful/__init__.py", line 272, in error_router
return original_handler(e)
File "/home/ericson/Workspace/concil-v4-api/venv/lib/python3.8/site-packages/flask/app.py", line 1821, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/home/ericson/Workspace/concil-v4-api/venv/lib/python3.8/site-packages/flask/_compat.py", line 38, in reraise
raise value.with_traceback(tb)
File "/home/ericson/Workspace/concil-v4-api/venv/lib/python3.8/site-packages/flask/app.py", line 1950, in full_dispatch_request
rv = self.dispatch_request()
File "/home/ericson/Workspace/concil-v4-api/venv/lib/python3.8/site-packages/flask/app.py", line 1936, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/home/ericson/Workspace/concil-v4-api/venv/lib/python3.8/site-packages/flask_restful/__init__.py", line 468, in wrapper
resp = resource(*args, **kwargs)
File "/home/ericson/Workspace/concil-v4-api/venv/lib/python3.8/site-packages/flask/views.py", line 89, in view
return self.dispatch_request(*args, **kwargs)
File "/home/ericson/Workspace/concil-v4-api/venv/lib/python3.8/site-packages/flask_restful/__init__.py", line 583, in dispatch_request
resp = meth(*args, **kwargs)
File "/home/ericson/Workspace/concil-v4-api/src/services/cognito_auth.py", line 12, in check_params
return _validate_token(func, *args, **kwargs)
File "/home/ericson/Workspace/concil-v4-api/src/services/cognito_auth.py", line 31, in _validate_token
return func(*args, **kwargs)
File "/home/ericson/Workspace/concil-v4-api/src/resources/default/__init__.py", line 49, in put
db.session.query().\
File "/home/ericson/Workspace/concil-v4-api/venv/lib/python3.8/site-packages/sqlalchemy/orm/query.py", line 4033, in update
update_op = persistence.BulkUpdate.factory(
File "/home/ericson/Workspace/concil-v4-api/venv/lib/python3.8/site-packages/sqlalchemy/orm/persistence.py", line 1818, in factory
return BulkUD._factory(
File "/home/ericson/Workspace/concil-v4-api/venv/lib/python3.8/site-packages/sqlalchemy/orm/persistence.py", line 1691, in _factory
return klass(*arg)
File "/home/ericson/Workspace/concil-v4-api/venv/lib/python3.8/site-packages/sqlalchemy/orm/persistence.py", line 1812, in __init__
super(BulkUpdate, self).__init__(query)
File "/home/ericson/Workspace/concil-v4-api/venv/lib/python3.8/site-packages/sqlalchemy/orm/persistence.py", line 1651, in __init__
self.mapper = self.query._bind_mapper()
File "/home/ericson/Workspace/concil-v4-api/venv/lib/python3.8/site-packages/sqlalchemy/orm/query.py", line 425, in _bind_mapper
ezero = self._entity_zero()
File "/home/ericson/Workspace/concil-v4-api/venv/lib/python3.8/site-packages/sqlalchemy/orm/query.py", line 412, in _entity_zero
else self._query_entity_zero().entity_zero
File "/home/ericson/Workspace/concil-v4-api/venv/lib/python3.8/site-packages/sqlalchemy/orm/query.py", line 398, in _query_entity_zero
return self._entities[0]
IndexError: list index out of range
Any ideas of what could cause this?
The problem was that I was working with a table object. user_client_association_table is a Table object, and I needed to specify a model to be updated. So I defined a model just for this:
from db import db
import model
class UserClient(db.Model):
__bind_key__ = "DEV_BASIS"
__tablename__ = "tb_user_client"
__table_args__ = {'extend_existing': True}
ctid = db.Column(db.Integer, primary_key=True)
And then I imported it:
from model import UserClient
...
#cognito_required
def put(self, stage: str):
data = Default.validator.parse_args()
table = user_client_association_table
db.session.query(UserClient).\
filter(table.c.client_id == data["client_id"]).\
filter(table.c.user_id == data["user_id"]).\
update({"is_default": 0})
db.session.commit()
return {
"data": {
"code": 200,
"message": f"The default user_id has been updated for the client {data['client_id']}",
}
}, 200
Really obscure problem here, thanks #snakecharmerb
I'm studying Flask and now want to dump some data to json and print a piece of data to the web:
#app.route('/home')
def index():
if 'piece' in session:
m = session['piece']
session.clear()
# online_users = mongo.db.GOOG.find({'date': '2017-02-01'})
return render_template('index.html')
#app.route('/query', methods=['POST'])
def query():
# stockName = request.form['stockName']
print(request.json)
stockName = request.json['stockName']
stock = mongo.db[stockName]
m = stock.find({})
session['piece'] = m.clone()
mClone = m.clone()
docs = []
for doc in m:
one = json_util.dumps(doc, default=json_util.default)
docs.append(one)
docs = json_util.dumps(docs)
print type(docs)
s = str(mClone[4][u'high'])
print s
return s
the output is:
{u'stockName': u'GOOG'}
<type 'str'>
838.0
127.0.0.1 - - [11/Apr/2017 00:38:28] "POST /query HTTP/1.1" 500 -
Traceback (most recent call last):
File "G:\Python\Python27\lib\site-packages\flask\app.py", line 1994, in __call__
return self.wsgi_app(environ, start_response)
File "G:\Python\Python27\lib\site-packages\flask\app.py", line 1985, in wsgi_app
response = self.handle_exception(e)
File "G:\Python\Python27\lib\site-packages\flask\app.py", line 1540, in handle_exception
reraise(exc_type, exc_value, tb)
File "G:\Python\Python27\lib\site-packages\flask\app.py", line 1982, in wsgi_app
response = self.full_dispatch_request()
File "G:\Python\Python27\lib\site-packages\flask\app.py", line 1615, in full_dispatch_request
return self.finalize_request(rv)
File "G:\Python\Python27\lib\site-packages\flask\app.py", line 1632, in finalize_request
response = self.process_response(response)
File "G:\Python\Python27\lib\site-packages\flask\app.py", line 1858, in process_response
self.save_session(ctx.session, response)
File "G:\Python\Python27\lib\site-packages\flask\app.py", line 924, in save_session
return self.session_interface.save_session(self, session, response)
File "G:\Python\Python27\lib\site-packages\flask\sessions.py", line 363, in save_session
val = self.get_signing_serializer(app).dumps(dict(session))
File "G:\Python\Python27\lib\site-packages\itsdangerous.py", line 565, in dumps
payload = want_bytes(self.dump_payload(obj))
File "G:\Python\Python27\lib\site-packages\itsdangerous.py", line 847, in dump_payload
json = super(URLSafeSerializerMixin, self).dump_payload(obj)
File "G:\Python\Python27\lib\site-packages\itsdangerous.py", line 550, in dump_payload
return want_bytes(self.serializer.dumps(obj))
File "G:\Python\Python27\lib\site-packages\flask\sessions.py", line 85, in dumps
return json.dumps(_tag(value), separators=(',', ':'))
File "G:\Python\Python27\lib\site-packages\flask\json.py", line 123, in dumps
rv = _json.dumps(obj, **kwargs)
File "G:\Python\Python27\lib\site-packages\simplejson\__init__.py", line 397, in dumps
**kw).encode(obj)
File "G:\Python\Python27\lib\site-packages\simplejson\encoder.py", line 291, in encode
chunks = self.iterencode(o, _one_shot=True)
File "G:\Python\Python27\lib\site-packages\simplejson\encoder.py", line 373, in iterencode
return _iterencode(o, 0)
File "G:\Python\Python27\lib\site-packages\flask\json.py", line 80, in default
return _json.JSONEncoder.default(self, o)
File "G:\Python\Python27\lib\site-packages\simplejson\encoder.py", line 268, in default
raise TypeError(repr(o) + " is not JSON serializable")
TypeError: <pymongo.cursor.Cursor object at 0x035026B0> is not JSON serializable
I'm a bit curious about the error. It's like happening between print s and return s. Or would it be possible that after the post of query, /home is loaded again, but in this case, s should be returned to my web page.
Solved.
Seems session will excute by the end of the function, and m has been iterated, thus error appears.
Don't know if this explains correctly.
At first you need from flask import jsonify.
print type(docs)
s = str(mClone[4][u'high'])
print s
return jsonify({data: s})
here is the flask documentation link with an example:
http://flask.pocoo.org/docs/0.12/patterns/jquery/
I have these two models:
#################
### Usergroup ###
#################
class Usergroup(ndb.Model):
group_name = ndb.StringProperty(indexed = False, required = True)
is_admin_group = ndb.BooleanProperty(indexed = False, required = False, default = False)
############
### User ###
############
class User(ndb.Model):
fb_id = ndb.StringProperty(indexed = True, required = True)
fb_access_token = ndb.TextProperty(indexed = False, required = True)
email = ndb.StringProperty(indexed = True, required = True)
first_name = ndb.StringProperty(indexed = False, required = True)
last_name = ndb.StringProperty(indexed = False, required = True)
gender = ndb.StringProperty(indexed = False)
group_key = ndb.KeyProperty(indexed = False, required = False, kind = Usergroup, default = ndb.Key(Usergroup, 'member'))
join_date = ndb.DateTimeProperty(indexed = True, auto_now_add = True)
last_login = ndb.DateTimeProperty(indexed = True, auto_now_add = True, auto_now = False)
#app.route('/user/login', methods=['POST'])
def user_login():
me = exchange_token_me(request.form['accessToken'])
if me is not False:
user = user_find_or_register(me)
if user is not None:
register_session(user)
return 'success'
return 'error'
def user_find_or_register(user):
qry = User.query(User.fb_id == user['id'])
existing_user = qry.get()
if existing_user is not None:
existing_user.fb_access_token = user['access_token']
existing_user.fb_id = user['id']
existing_user.email = user['email']
existing_user.last_login = datetime.datetime.now()
existing_user.put()
return existing_user
new_user = User()
new_user.fb_id = user['id']
new_user.fb_access_token = user['access_token']
new_user.email = user['email']
new_user.first_name = user['first_name']
new_user.last_name = user['last_name']
new_user.gender = user['gender']
new_user.last_login = datetime.datetime.now()
#new_user.group_key = ndb.key(Usergroup, 'member')
key = new_user.put()
saved_user = key.get()
#key.delete() # DEBUG
if saved_user is not None:
return saved_user
def register_session(user):
session['fb_id'] = user.fb_id
session['first_name'] = user.first_name
session['last_name'] = user.last_name
session['group_key'] = user.group_key
session['loggedin'] = True
The Usergroup model has a small unique string as entity key. There is already a Usergroup whose key is 'member'
Whenever we create/save a user, it should use the key to the 'member' usergroup, but we get this error instead:
TypeError: Key('Usergroup', 'member') is not JSON serializable
Traceback:
ERROR 2016-10-18 14:32:40,572 app.py:1587] Exception on /user/login [POST]
Traceback (most recent call last):
File "/var/www/mywebsite/public_html/lib/flask/app.py", line 1988, in wsgi_app
response = self.full_dispatch_request()
File "/var/www/mywebsite/public_html/lib/flask/app.py", line 1643, in full_dispatch_request
response = self.process_response(response)
File "/var/www/mywebsite/public_html/lib/flask/app.py", line 1864, in process_response
self.save_session(ctx.session, response)
File "/var/www/mywebsite/public_html/lib/flask/app.py", line 926, in save_session
return self.session_interface.save_session(self, session, response)
File "/var/www/mywebsite/public_html/lib/flask/sessions.py", line 359, in save_session
val = self.get_signing_serializer(app).dumps(dict(session))
File "/var/www/mywebsite/public_html/lib/itsdangerous.py", line 565, in dumps
payload = want_bytes(self.dump_payload(obj))
File "/var/www/mywebsite/public_html/lib/itsdangerous.py", line 847, in dump_payload
json = super(URLSafeSerializerMixin, self).dump_payload(obj)
File "/var/www/mywebsite/public_html/lib/itsdangerous.py", line 550, in dump_payload
return want_bytes(self.serializer.dumps(obj))
File "/var/www/mywebsite/public_html/lib/flask/sessions.py", line 85, in dumps
return json.dumps(_tag(value), separators=(',', ':'))
File "/var/www/mywebsite/public_html/lib/flask/json.py", line 126, in dumps
rv = _json.dumps(obj, **kwargs)
File "/usr/lib/python2.7/json/__init__.py", line 251, in dumps
sort_keys=sort_keys, **kw).encode(obj)
File "/usr/lib/python2.7/json/encoder.py", line 209, in encode
chunks = list(chunks)
File "/usr/lib/python2.7/json/encoder.py", line 434, in _iterencode
for chunk in _iterencode_dict(o, _current_indent_level):
File "/usr/lib/python2.7/json/encoder.py", line 408, in _iterencode_dict
for chunk in chunks:
File "/usr/lib/python2.7/json/encoder.py", line 442, in _iterencode
o = _default(o)
File "/var/www/mywebsite/public_html/lib/flask/json.py", line 83, in default
return _json.JSONEncoder.default(self, o)
File "/usr/lib/python2.7/json/encoder.py", line 184, in default
raise TypeError(repr(o) + " is not JSON serializable")
TypeError: Key('Usergroup', 'member') is not JSON serializable
ERROR 2016-10-18 14:32:40,593 main.py:178] An error occurred during a request.
Traceback (most recent call last):
File "/var/www/mywebsite/public_html/lib/flask/app.py", line 1988, in wsgi_app
response = self.full_dispatch_request()
File "/var/www/mywebsite/public_html/lib/flask/app.py", line 1643, in full_dispatch_request
response = self.process_response(response)
File "/var/www/mywebsite/public_html/lib/flask/app.py", line 1864, in process_response
self.save_session(ctx.session, response)
File "/var/www/mywebsite/public_html/lib/flask/app.py", line 926, in save_session
return self.session_interface.save_session(self, session, response)
File "/var/www/mywebsite/public_html/lib/flask/sessions.py", line 359, in save_session
val = self.get_signing_serializer(app).dumps(dict(session))
File "/var/www/mywebsite/public_html/lib/itsdangerous.py", line 565, in dumps
payload = want_bytes(self.dump_payload(obj))
File "/var/www/mywebsite/public_html/lib/itsdangerous.py", line 847, in dump_payload
json = super(URLSafeSerializerMixin, self).dump_payload(obj)
File "/var/www/mywebsite/public_html/lib/itsdangerous.py", line 550, in dump_payload
return want_bytes(self.serializer.dumps(obj))
File "/var/www/mywebsite/public_html/lib/flask/sessions.py", line 85, in dumps
return json.dumps(_tag(value), separators=(',', ':'))
File "/var/www/mywebsite/public_html/lib/flask/json.py", line 126, in dumps
rv = _json.dumps(obj, **kwargs)
File "/usr/lib/python2.7/json/__init__.py", line 251, in dumps
sort_keys=sort_keys, **kw).encode(obj)
File "/usr/lib/python2.7/json/encoder.py", line 209, in encode
chunks = list(chunks)
File "/usr/lib/python2.7/json/encoder.py", line 434, in _iterencode
for chunk in _iterencode_dict(o, _current_indent_level):
File "/usr/lib/python2.7/json/encoder.py", line 408, in _iterencode_dict
for chunk in chunks:
File "/usr/lib/python2.7/json/encoder.py", line 442, in _iterencode
o = _default(o)
File "/var/www/mywebsite/public_html/lib/flask/json.py", line 83, in default
return _json.JSONEncoder.default(self, o)
File "/usr/lib/python2.7/json/encoder.py", line 184, in default
raise TypeError(repr(o) + " is not JSON serializable")
TypeError: Key('Usergroup', 'member') is not JSON serializable
INFO 2016-10-18 14:32:40,610 module.py:788] default: "POST /user/login HTTP/1.1" 500 27
UPDATE:
After Dan has spotted the problem, the solution is in the following function:
def register_session(user):
session['fb_id'] = user.fb_id
session['first_name'] = user.first_name
session['last_name'] = user.last_name
session['group_key'] = user.group_key.id() # Thanks Dan
session['loggedin'] = True
FWIW, a quick test with your code as models.py shows this to be working just fine, at least on the development server:
from models import User
user = User(email='email', username='username')
user.put()
produced:
This worked without even having a Usergroup entity - a key can exist without a matching entity. Of course, trying to follow the link to the Usergroup in the datastore viewer fails:
Traceback (most recent call last):
File "/home/usr_local/google_appengine_1.9.40/lib/webapp2-2.5.1/webapp2.py", line 1536, in __call__
rv = self.handle_exception(request, response, e)
File "/home/usr_local/google_appengine_1.9.40/lib/webapp2-2.5.1/webapp2.py", line 1530, in __call__
rv = self.router.dispatch(request, response)
File "/home/usr_local/google_appengine_1.9.40/lib/webapp2-2.5.1/webapp2.py", line 1278, in default_dispatcher
return route.handler_adapter(request, response)
File "/home/usr_local/google_appengine_1.9.40/lib/webapp2-2.5.1/webapp2.py", line 1102, in __call__
return handler.dispatch()
File "/home/usr_local/google_appengine/google/appengine/tools/devappserver2/admin/admin_request_handler.py", line 96, in dispatch
super(AdminRequestHandler, self).dispatch()
File "/home/usr_local/google_appengine_1.9.40/lib/webapp2-2.5.1/webapp2.py", line 572, in dispatch
return self.handle_exception(e, self.app.debug)
File "/home/usr_local/google_appengine_1.9.40/lib/webapp2-2.5.1/webapp2.py", line 570, in dispatch
return method(*args, **kwargs)
File "/home/usr_local/google_appengine/google/appengine/tools/devappserver2/admin/datastore_viewer.py", line 741, in get
entities = [datastore.Get(entity_key)]
File "/home/usr_local/google_appengine/google/appengine/api/datastore.py", line 671, in Get
return GetAsync(keys, **kwargs).get_result()
File "/home/usr_local/google_appengine/google/appengine/api/apiproxy_stub_map.py", line 613, in get_result
return self.__get_result_hook(self)
File "/home/usr_local/google_appengine/google/appengine/datastore/datastore_rpc.py", line 1717, in __get_hook
entities = extra_hook(entities)
File "/home/usr_local/google_appengine/google/appengine/api/datastore.py", line 640, in local_extra_hook
raise datastore_errors.EntityNotFoundError()
EntityNotFoundError
So you might want to show your actual code creating the entity and the full traceback, something else may be going on.
Your traceback indicates that the problem is not with creating the entity, but with saving your session:
File "/var/www/mywebsite/public_html/lib/flask/app.py", line 926, in save_session
return self.session_interface.save_session(self, session, response)
It appears you included in the session content the key object (possibly by including the entire User entity?), which is what causes the failure. For that purpose keys need to be serialized and you can use key.urlsafe() for that. See this answer for an example: https://stackoverflow.com/a/34835074/4495081
If indeed you included the entire User entity in the session you can just include its urlsafe key instead.
Yup, this is the source of your problem:
session['group_key'] = user.group_key
change it to:
session['group_key'] = user.group_key.urlsafe()
And you'll retrieve it like this:
urlsafe_key = session.get('group_key')
if urlsafe_key:
group_key = ndb.Key(urlsafe=urlsafe_key)