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/
Related
Hi i'm getting this error. TypeError: Object of type ColumnClause is not JSON serializable.
Whole thing:
[2020-10-26 22:17:58,448] ERROR in app: Exception on /all-user [GET]
Traceback (most recent call last):
File "c:\users\ryand\.virtualenvs\main-api-ucgvpon1\lib\site-packages\flask\app.py", line 2447, in wsgi_app
response = self.full_dispatch_request()
File "c:\users\ryand\.virtualenvs\main-api-ucgvpon1\lib\site-packages\flask\app.py", line 1952, in full_dispatch_request
rv = self.handle_user_exception(e)
File "c:\users\ryand\.virtualenvs\main-api-ucgvpon1\lib\site-packages\flask\app.py", line 1821, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "c:\users\ryand\.virtualenvs\main-api-ucgvpon1\lib\site-packages\flask\_compat.py", line 39, in reraise
raise value
File "c:\users\ryand\.virtualenvs\main-api-ucgvpon1\lib\site-packages\flask\app.py", line 1950, in full_dispatch_request
rv = self.dispatch_request()
File "c:\users\ryand\.virtualenvs\main-api-ucgvpon1\lib\site-packages\flask\app.py", line 1936, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "C:\Users\ryand\Desktop\mealplansfree\main-api\api.py", line 36, in decorated
return f(*args, **kwargs)
File "C:\Users\ryand\Desktop\mealplansfree\main-api\api.py", line 59, in get_all_users
return jsonify({'users' : output})
File "c:\users\ryand\.virtualenvs\main-api-ucgvpon1\lib\site-packages\flask\json\__init__.py", line 370, in jsonify
dumps(data, indent=indent, separators=separators) + "\n",
File "c:\users\ryand\.virtualenvs\main-api-ucgvpon1\lib\site-packages\flask\json\__init__.py", line 211, in dumps
rv = _json.dumps(obj, **kwargs)
File "c:\users\ryand\appdata\local\programs\python\python38-32\lib\json\__init__.py", line 234, in dumps
return cls(
File "c:\users\ryand\appdata\local\programs\python\python38-32\lib\json\encoder.py", line 199, in encode
chunks = self.iterencode(o, _one_shot=True)
File "c:\users\ryand\appdata\local\programs\python\python38-32\lib\json\encoder.py", line 257, in iterencode
return _iterencode(o, 0)
File "c:\users\ryand\.virtualenvs\main-api-ucgvpon1\lib\site-packages\flask\json\__init__.py", line 100, in default
return _json.JSONEncoder.default(self, o)
File "c:\users\ryand\appdata\local\programs\python\python38-32\lib\json\encoder.py", line 179, in default
raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type ColumnClause is not JSON serializable
Here is the code for the above.
#app.route('/all-user', methods=['GET'])
#application_required
def get_all_users():
users = User.query.all()
output = []
for user in users:
user_data = {}
user_data['user_id'] = user.user_id
user_data['full_name'] = user.full_name
user_data['username'] = user.username
user_data['password'] = user.password
user_data['admin'] = user.admin
output.append(user_data)
return jsonify({'users' : output})
here is the secret key check
def application_required(f):
#wraps(f)
def decorated(*args, **kwargs):
token = None
if 'x-access-key' in request.headers:
token = request.headers['x-access-key']
if not token:
return jsonify({'message' : 'ERROR x-access-key missing or incorrect.'}), 401
if token == app.config['SECRET_KEY']:
return f(*args, **kwargs)
else:
return jsonify({'message' : 'ERROR x-access-key missing or incorrect.'}), 401
return decorated
If anyone knows whats going on or could guide me through whats going on and how to debug these that would be great!
I found the answer here: SQLAlchemy warning: column won't be part of the declarative mapping
I had missed in my User model in the username it was a lowercase c and not upper case C. This fixed the error and is now working. Thanks!
The cause can be data type. You are using lot of data types. Try to reduce data type changes.
I'm trying to figure out API with python. And want to send back some already encrypted jwt token.
When I'm trying to return jwt token in return method sends back Error's and Error's page in postman app shows up. But when printing it inside console everything works fine.
class Login(Resource):
def post(self):
json_data = request.get_json(force=True)
un = json_data['username']
pw = json_data['password']
encoded_jwt = jwt.encode({'username': un, 'password': pw}, 'OH HI MARK', algorithm='HS256')
print(encoded_jwt)
return jsonify(token = encoded_jwt)
I'm excpecting to get this token `
b'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6ImhpIiwicGFzc3dvcmQiOiJwYXNzd29yZCJ9.MQ-hwWabt13E4KMFxPztSUr6RYwsZZ-tT0sdv2s0vU0'
But getting bunch of error.
Edit:
Asked to add Error's.
Traceback (most recent call last):
File "D:\FinallySomethingWork\venv\lib\site-packages\flask\app.py", line 2309, in __call__
return self.wsgi_app(environ, start_response)
File "D:\FinallySomethingWork\venv\lib\site-packages\flask\app.py", line 2295, in wsgi_app
response = self.handle_exception(e)
File "D:\FinallySomethingWork\venv\lib\site-packages\flask_restful\__init__.py", line 269, in error_router
return original_handler(e)
File "D:\FinallySomethingWork\venv\lib\site-packages\flask\app.py", line 1741, in handle_exception
reraise(exc_type, exc_value, tb)
File "D:\FinallySomethingWork\venv\lib\site-packages\flask\_compat.py", line 34, in reraise
raise value.with_traceback(tb)
File "D:\FinallySomethingWork\venv\lib\site-packages\flask\app.py", line 2292, in wsgi_app
response = self.full_dispatch_request()
File "D:\FinallySomethingWork\venv\lib\site-packages\flask\app.py", line 1815, in full_dispatch_request
rv = self.handle_user_exception(e)
File "D:\FinallySomethingWork\venv\lib\site-packages\flask_restful\__init__.py", line 269, in error_router
return original_handler(e)
File "D:\FinallySomethingWork\venv\lib\site-packages\flask\app.py", line 1718, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "D:\FinallySomethingWork\venv\lib\site-packages\flask\_compat.py", line 34, in reraise
raise value.with_traceback(tb)
File "D:\FinallySomethingWork\venv\lib\site-packages\flask\app.py", line 1813, in full_dispatch_request
rv = self.dispatch_request()
File "D:\FinallySomethingWork\venv\lib\site-packages\flask\app.py", line 1799, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "D:\FinallySomethingWork\venv\lib\site-packages\flask_restful\__init__.py", line 458, in wrapper
resp = resource(*args, **kwargs)
File "D:\FinallySomethingWork\venv\lib\site-packages\flask\views.py", line 88, in view
return self.dispatch_request(*args, **kwargs)
File "D:\FinallySomethingWork\venv\lib\site-packages\flask_restful\__init__.py", line 573, in dispatch_request
resp = meth(*args, **kwargs)
File "D:\FinallySomethingWork\Yeah\app.py", line 16, in post
return jsonify(token = encoded_jwt)
File "D:\FinallySomethingWork\venv\lib\site-packages\flask\json\__init__.py", line 321, in jsonify
dumps(data, indent=indent, separators=separators) + '\n',
File "D:\FinallySomethingWork\venv\lib\site-packages\flask\json\__init__.py", line 179, in dumps
rv = _json.dumps(obj, **kwargs)
File "C:\Users\Denis\AppData\Local\Programs\Python\Python37-32\lib\json\__init__.py", line 238, in dumps
**kw).encode(obj)
File "C:\Users\Denis\AppData\Local\Programs\Python\Python37-32\lib\json\encoder.py", line 201, in encode
chunks = list(chunks)
File "C:\Users\Denis\AppData\Local\Programs\Python\Python37-32\lib\json\encoder.py", line 431, in _iterencode
yield from _iterencode_dict(o, _current_indent_level)
File "C:\Users\Denis\AppData\Local\Programs\Python\Python37-32\lib\json\encoder.py", line 405, in _iterencode_dict
yield from chunks
File "C:\Users\Denis\AppData\Local\Programs\Python\Python37-32\lib\json\encoder.py", line 438, in _iterencode
o = _default(o)
File "D:\FinallySomethingWork\venv\lib\site-packages\flask\json\__init__.py", line 81, in default
return _json.JSONEncoder.default(self, o)
File "C:\Users\Denis\AppData\Local\Programs\Python\Python37-32\lib\json\encoder.py", line 179, in default
raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type bytes is not JSON serializable
The error message says:
TypeError: Object of type bytes is not JSON serializable
That means, encoded_jwt is a byte array which can't be serialized into a JSON.
You first have to convert it to a string:
return jsonify(token = encoded_jwt.decode("utf-8"))
On a sidenote: don't put the password into the token!
I sent a request to my API but it throws TypeError: Object of type 'bytes' is not JSON serializable. It also returns a 500 INTERNAL SERVER ERROR.
Code:
def login():
data = request.json
if(data['token'] != 'xxxxxxxxxxx'):
return jsonify(), 401
user = User.objects(npm=data['npm']).first()
if(user == None):
del data['token']
user = User(**data)
user.major = Major.objects(name=data['major']).first()
user.role = 'user'
user.save()
token = jwt.encode({
'user_id': str(user.id)
}, secret_key, algorithm='HS256')
return jsonify({
'user_id': str(user.id),
'token': token,
'major_id': str(user.major.id)
}), 200
Traceback:
Traceback (most recent call last):
File "c:\users\anisha\env\lib\site-packages\flask\app.py", line 2292, in wsgi_app
response = self.full_dispatch_request()
File "c:\users\anisha\env\lib\site-packages\flask\app.py", line 1815, in full_dispatch_request
rv = self.handle_user_exception(e)
File "c:\users\anisha\env\lib\site-packages\flask_cors\extension.py", line 161, in wrapped_function
return cors_after_request(app.make_response(f(*args, **kwargs)))
File "c:\users\anisha\env\lib\site-packages\flask\app.py", line 1718, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "c:\users\anisha\env\lib\site-packages\flask\_compat.py", line 35, in reraise
raise value
File "c:\users\anisha\env\lib\site-packages\flask\app.py", line 1813, in full_dispatch_request
rv = self.dispatch_request()
File "c:\users\anisha\env\lib\site-packages\flask\app.py", line 1799, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "c:\users\anisha\env\lib\site-packages\flask_cors\decorator.py", line 128, in wrapped_function
resp = make_response(f(*args, **kwargs))
File "C:\Users\Anisha\sunjadv2-server\app.py", line 69, in login
'major_id': str(user.major.id)
File "c:\users\anisha\env\lib\site-packages\flask\json\__init__.py", line 321, in jsonify
dumps(data, indent=indent, separators=separators) + '\n',
File "c:\users\anisha\env\lib\site-packages\flask\json\__init__.py", line 179, in dumps
rv = _json.dumps(obj, **kwargs)
File "C:\Users\Anisha\AppData\Local\Programs\Python\Python36\lib\json\__init__.py", line 238, in dumps
**kw).encode(obj)
File "C:\Users\Anisha\AppData\Local\Programs\Python\Python36\lib\json\encoder.py", line 199, in encode
chunks = self.iterencode(o, _one_shot=True)
File "C:\Users\Anisha\AppData\Local\Programs\Python\Python36\lib\json\encoder.py", line 257, in iterencode
return _iterencode(o, 0)
File "c:\users\anisha\env\lib\site-packages\flask\json\__init__.py", line 81, in default
return _json.JSONEncoder.default(self, o)
File "C:\Users\Anisha\AppData\Local\Programs\Python\Python36\lib\json\encoder.py", line 180, in default
o.__class__.__name__)
TypeError: Object of type 'bytes' is not JSON serializable
When I do print("major_id: " + str(user.major.id)) it will print major_id: 5b55e986f15bf336e0b820fe to console. Why does str(user.major.id) seen as bytes type in jsonify? I've tried to delete 'major_id': str(user.major.id) but then line 'token': token will cause the same error.
Thank you.
It seems that your data may not be properly decoded. You could try to decode your data before jsonifying it.
For example, instead of using token directly, try using: token.decode('utf-8')
I want to pass the validated data from a WTForms form to a Celery task. When I try to pass the form, I get kombu.exceptions.EncodeError: Object of type 'MyForm' is not JSON serializable. How can I pass the data from WTForms to a Celery task? Do I need to write a custom serializer?
File "/usr/local/lib/python3.6/site-packages/flask/app.py", line 1997, in __call__
return self.wsgi_app(environ, start_response)
File "/usr/local/lib/python3.6/site-packages/flask/app.py", line 1985, in wsgi_app
response = self.handle_exception(e)
File "/usr/local/lib/python3.6/site-packages/flask/app.py", line 1540, in handle_exception
reraise(exc_type, exc_value, tb)
File "/usr/local/lib/python3.6/site-packages/flask/_compat.py", line 33, in reraise
raise value
File "/usr/local/lib/python3.6/site-packages/flask/app.py", line 1982, in wsgi_app
response = self.full_dispatch_request()
File "/usr/local/lib/python3.6/site-packages/flask/app.py", line 1614, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/usr/local/lib/python3.6/site-packages/flask/app.py", line 1517, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/usr/local/lib/python3.6/site-packages/flask/_compat.py", line 33, in reraise
raise value
File "/usr/local/lib/python3.6/site-packages/flask/app.py", line 1612, in full_dispatch_request
rv = self.dispatch_request()
File "/usr/local/lib/python3.6/site-packages/flask/app.py", line 1598, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/home/galander/Desktop/Projekty/PDf generator/pdf-generator-master/pdf-generator/main.py", line 64, in submit
generate.delay(form, new_pdf)
File "/home/galander/.local/lib/python3.6/site-packages/celery/app/task.py", line 413, in delay
return self.apply_async(args, kwargs)
File "/home/galander/.local/lib/python3.6/site-packages/celery/app/task.py", line 536, in apply_async
**options
File "/home/galander/.local/lib/python3.6/site-packages/celery/app/base.py", line 737, in send_task
amqp.send_task_message(P, name, message, **options)
File "/home/galander/.local/lib/python3.6/site-packages/celery/app/amqp.py", line 554, in send_task_message
**properties
File "/home/galander/.local/lib/python3.6/site-packages/kombu/messaging.py", line 169, in publish
compression, headers)
File "/home/galander/.local/lib/python3.6/site-packages/kombu/messaging.py", line 252, in _prepare
body) = dumps(body, serializer=serializer)
File "/home/galander/.local/lib/python3.6/site-packages/kombu/serialization.py", line 221, in dumps
payload = encoder(data)
File "/usr/local/lib/python3.6/contextlib.py", line 99, in __exit__
self.gen.throw(type, value, traceback)
File "/home/galander/.local/lib/python3.6/site-packages/kombu/serialization.py", line 54, in _reraise_errors
reraise(wrapper, wrapper(exc), sys.exc_info()[2])
File "/home/galander/.local/lib/python3.6/site-packages/vine/five.py", line 178, in reraise
raise value.with_traceback(tb)
File "/home/galander/.local/lib/python3.6/site-packages/kombu/serialization.py", line 50, in _reraise_errors
yield
File "/home/galander/.local/lib/python3.6/site-packages/kombu/serialization.py", line 221, in dumps
payload = encoder(data)
File "/home/galander/.local/lib/python3.6/site-packages/kombu/utils/json.py", line 72, in dumps
**dict(default_kwargs, **kwargs))
File "/usr/local/lib/python3.6/json/__init__.py", line 238, in dumps
**kw).encode(obj)
File "/usr/local/lib/python3.6/json/encoder.py", line 199, in encode
chunks = self.iterencode(o, _one_shot=True)
File "/usr/local/lib/python3.6/json/encoder.py", line 257, in iterencode
return _iterencode(o, 0)
File "/home/galander/.local/lib/python3.6/site-packages/kombu/utils/json.py", line 62, in default
return super(JSONEncoder, self).default(o)
File "/usr/local/lib/python3.6/json/encoder.py", line 180, in default
o.__class__.__name__)
kombu.exceptions.EncodeError: Object of type 'MyForm' is not JSON serializable
class MyForm(FlaskForm):
name_of_the_file = StringField()
first_name = StringField()
number = DecimalField()
date = DateField()
#app.route('/submit', methods=['GET', 'POST'])
def submit():
form = MyForm()
if form.validate_on_submit():
generate.delay(form)
return '', 202
return render_template('submit.html', form=form)
#celery.task()
def generate(form):
...
Like what the error is telling you, the celery task is trying to serialize an Object. That is not possible.
Instead you could serialize the request.form.
This is untested, but something like this should work:
class MyForm(FlaskForm):
name_of_the_file = StringField()
first_name = StringField()
number = DecimalField()
date = DateField()
#app.route('/submit', methods=['GET', 'POST'])
def submit():
if request.method == 'POST':
form = MyForm(request.form)
if form.validate_on_submit():
generate.delay(request.form)
return '', 202
else:
form = MyForm()
return render_template('submit.html', form=form)
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)