So, I'm experiencing some weird error with flask-restful and fields.Url that I can't really figure out why is there since it happens randomly. When running my application normally, it doesn't seem to happen, and it only fails randomly in tests.
It's worth noting that it only occurs on POST requests, and works with GET requests.
For reference, all the code is located at https://github.com/Tehnix/cred-server (with the temp fix applied).
Error
It seems that the creation of a URL field fails, while marshalling my data object. The full error is at the end of the question.
File "/Users/tehnix/Dropbox/github/Tehnix/cred/env/lib/python3.4/site-packages/werkzeug/routing.py", line 1678, in build
raise BuildError(endpoint, values, method)
werkzeug.routing.BuildError: ('events_item', {'_sa_instance_state': <sqlalchemy.orm.state.InstanceState object at 0x102df6d68>}, None)
Culprit
The endpoint is defined as,
# FILE: cred/routes.py
api.add_resource(EventsItem, '/events/<int:event_id>', endpoint='events_item')
I'm using the following to marshal my SQLAlchemy object,
# FILE: cred/resources/events.py
simple_event_fields = {
'id': flask.ext.restful.fields.Integer(attribute='event_id'),
'uri': flask.ext.restful.fields.Url('events_item', absolute=True),
}
where the fields.Url seems to fail for some reason. And finally the resource that handles the POST request,
# FILE: cred/resources/events.py
class Events(flask.ext.restful.Resource):
"""Methods going to the /events route."""
def post(self):
"""Create a new event and return the id and uri of the event."""
# Parse the POST args using the parser from flask-restful into event_args
# ...
# Create the event in the database
event = EventModel(
self.client,
event_args['name'],
event_args['location'],
event_args['action'],
event_args['value']
)
# Save the event in the database
db.session.add(event)
db.session.commit()
# Finally, convert the event object into our format by marshalling it,
# and returning the JSON object
return {
'status': 201,
'message': 'Created Event',
'event': marshal(event, simple_event_fields)
}, 201
As said in the start, it only occurs when running tests (and only sometimes), so it isn't critical per se, but it would still be nice not having to rerun tests a bunch of times just to see if it goes away and all others pass.
Test case
I'm using Flask-Testing, but it else it is pretty much unittests,
# FILE: cred/test/test_events.py
test_event = {
'event': {
'name': 'Temperature',
'location': 'Living Room',
'action': 'Temperature Above Setting',
'value': '5'
}
}
class BaseTestCase(flask.ext.testing.TestCase):
SQLALCHEMY_DATABASE_URI = "sqlite://"
TESTING = True
def create_app(self):
return app
def setUp(self):
"""Create a SQLite database for quick testing."""
cred.database.init_db(cred.database.db)
self.session_key = None
def tearDown(self):
"""Close the database file and unlink it."""
cred.database.db.session.remove()
cred.database.db.drop_all()
#testutil.authenticate('write')
def test_posting_a_complete_event(self):
"""Create a valid new event."""
# Post the request to the test server
response = self.client.post(
'/events',
data=json.dumps(test_event),
content_type='application/json'
)
resp = json.loads(response.data.decode('utf-8'))
# Run self.assertEqual on all items in a dict
testutil.assertEqual(self, {
response.status_code: 201,
resp['status']: 201,
resp['message']: 'Created Event',
'id' in resp['event']: True,
'uri' in resp['event']: True
})
In the above, test_posting_a_complete_event will fail randomly because of the uri item.
Full error output from nosetests
======================================================================
ERROR: Create a valid new event.
----------------------------------------------------------------------
Traceback (most recent call last):
File "/Users/tehnix/Dropbox/github/Tehnix/cred/cred/test/util.py", line 34, in wrapped
fun(self, *args, **kwargs)
File "/Users/tehnix/Dropbox/github/Tehnix/cred/cred/test/test_events.py", line 37, in test_posting_a_complete_event
resp = json.loads(response.data.decode('utf-8'))
File "/usr/local/Cellar/python3/3.4.2_1/Frameworks/Python.framework/Versions/3.4/lib/python3.4/json/__init__.py", line 318, in loads
return _default_decoder.decode(s)
File "/usr/local/Cellar/python3/3.4.2_1/Frameworks/Python.framework/Versions/3.4/lib/python3.4/json/decoder.py", line 343, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/local/Cellar/python3/3.4.2_1/Frameworks/Python.framework/Versions/3.4/lib/python3.4/json/decoder.py", line 361, in raw_decode
raise ValueError(errmsg("Expecting value", s, err.value)) from None
nose.proxy.ValueError: Expecting value: line 1 column 1 (char 0)
-------------------- >> begin captured logging << --------------------
cred-server: ERROR: Exception on /events [POST]
Traceback (most recent call last):
File "/Users/tehnix/Dropbox/github/Tehnix/cred/env/lib/python3.4/site-packages/flask/app.py", line 1817, in wsgi_app
response = self.full_dispatch_request()
File "/Users/tehnix/Dropbox/github/Tehnix/cred/env/lib/python3.4/site-packages/flask/app.py", line 1477, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/Users/tehnix/Dropbox/github/Tehnix/cred/env/lib/python3.4/site-packages/flask_restful/__init__.py", line 265, in error_router
return original_handler(e)
File "/Users/tehnix/Dropbox/github/Tehnix/cred/env/lib/python3.4/site-packages/flask/app.py", line 1381, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/Users/tehnix/Dropbox/github/Tehnix/cred/env/lib/python3.4/site-packages/flask/_compat.py", line 33, in reraise
raise value
File "/Users/tehnix/Dropbox/github/Tehnix/cred/env/lib/python3.4/site-packages/flask/app.py", line 1475, in full_dispatch_request
rv = self.dispatch_request()
File "/Users/tehnix/Dropbox/github/Tehnix/cred/env/lib/python3.4/site-packages/flask/app.py", line 1461, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/Users/tehnix/Dropbox/github/Tehnix/cred/env/lib/python3.4/site-packages/flask_restful/__init__.py", line 446, in wrapper
resp = resource(*args, **kwargs)
File "/Users/tehnix/Dropbox/github/Tehnix/cred/env/lib/python3.4/site-packages/flask/views.py", line 84, in view
return self.dispatch_request(*args, **kwargs)
File "/Users/tehnix/Dropbox/github/Tehnix/cred/env/lib/python3.4/site-packages/flask_restful/__init__.py", line 550, in dispatch_request
resp = meth(*args, **kwargs)
File "/Users/tehnix/Dropbox/github/Tehnix/cred/cred/resources/events.py", line 88, in post
'event': marshal(event, simple_event_fields)
File "/Users/tehnix/Dropbox/github/Tehnix/cred/env/lib/python3.4/site-packages/flask_restful/__init__.py", line 603, in marshal
return OrderedDict([(envelope, OrderedDict(items))]) if envelope else OrderedDict(items)
File "/Users/tehnix/Dropbox/github/Tehnix/cred/env/lib/python3.4/collections/__init__.py", line 56, in __init__
self.__update(*args, **kwds)
File "/Users/tehnix/Dropbox/github/Tehnix/cred/env/bin/../lib/python3.4/_collections_abc.py", line 602, in update
for key, value in other:
File "/Users/tehnix/Dropbox/github/Tehnix/cred/env/lib/python3.4/site-packages/flask_restful/__init__.py", line 602, in <genexpr>
for k, v in fields.items())
File "/Users/tehnix/Dropbox/github/Tehnix/cred/env/lib/python3.4/site-packages/flask_restful/fields.py", line 294, in output
o = urlparse(url_for(endpoint, _external=self.absolute, **data))
File "/Users/tehnix/Dropbox/github/Tehnix/cred/env/lib/python3.4/site-packages/flask/helpers.py", line 312, in url_for
return appctx.app.handle_url_build_error(error, endpoint, values)
File "/Users/tehnix/Dropbox/github/Tehnix/cred/env/lib/python3.4/site-packages/flask/app.py", line 1641, in handle_url_build_error
reraise(exc_type, exc_value, tb)
File "/Users/tehnix/Dropbox/github/Tehnix/cred/env/lib/python3.4/site-packages/flask/_compat.py", line 33, in reraise
raise value
File "/Users/tehnix/Dropbox/github/Tehnix/cred/env/lib/python3.4/site-packages/flask/helpers.py", line 305, in url_for
force_external=external)
File "/Users/tehnix/Dropbox/github/Tehnix/cred/env/lib/python3.4/site-packages/werkzeug/routing.py", line 1678, in build
raise BuildError(endpoint, values, method)
werkzeug.routing.BuildError: ('events_item', {'_sa_instance_state': <sqlalchemy.orm.state.InstanceState object at 0x102df6d68>}, None)
You need to assign events_items inside the 'fields.Url' before returning it.
This link How to add fields url for nested output fields in flask restful explains more
But if you are using Blueprints, add "." to the fields.Url eg
'uri': fields.Url('.events_items')
ref https://github.com/flask-restful/flask-restful/issues/266#issuecomment-46678118
Related
I am trying to post my python script on google cloud functions, but keep getting an error. I am getting an error when trying to update a field in a firestore document. Here's my code
driverDB = driverDB = db.collection('drivers')
driverList = []
for doc in driverDB.get():
driverList.append(doc.id)
for driver in range(0,len(driverList)):
routeDataDict = {
'route':routeByDriverDict[driver]
}
driverDB.document(driverList[driver]).update(routeDataDict)
routeByDriverDict[driver] also returns a nested dictionary.
So I am trying to pass that routeDataDict to firestore. For this, I get the following error:
File "/layers/google.python.pip/pip/lib/python3.8/site-packages/google/cloud/firestore_v1/field_path.py", line 272, in __init__ raise ValueError(error) ValueError: One or more components is not a string or is empty.
Not sure how to fix the situation. The update command doesn't seem to let me post a dictionary (even though it lets me do that in my jupyter notebook). I printed out the driverList[driver] and it correctly prints the doc ID, and routeDataDict correctly prints a dictionary that looks like this:
{'route': {'stop_1': {'name': 'Christa Bauer',
'address': '1980 Jay Street, Lakewood, CO 80214',
'phone': 3039106747,
'email': 'test#test.com',
'has_reusables': False,
'notes': None,
'zone': 1,
'leg_url': 'https://www.google.com/maps/dir//39.7471041,-105.0647146',
'seconds_until_arrival': 360.0,
'completed': False,
'num_containers_at_this_stop': 0},
'pay': '$50',
'partner': 'burger_hut',
'date': datetime.datetime(2020, 11, 24, 1, 7, 1, 90282)}}
The entire error message:
Traceback (most recent call last): File "/layers/google.python.pip/pip/lib/python3.8/site-packages/flask/app.py", line 2447, in wsgi_app response = self.full_dispatch_request() File "/layers/google.python.pip/pip/lib/python3.8/site-packages/flask/app.py",
line 1952, in full_dispatch_request rv = self.handle_user_exception(e) File "/layers/google.python.pip/pip/lib/python3.8/site-packages/flask/app.py", line 1821, in handle_user_exception reraise(exc_type, exc_value, tb) File "/layers/google.python.pip/pip/lib/python3.8/site-packages/flask/_compat.py", line 39, in reraise raise value File "/layers/google.python.pip/pip/lib/python3.8/site-packages/flask/app.py", line 1950, in full_dispatch_request rv = self.dispatch_request() File "/layers/google.python.pip/pip/lib/python3.8/site-packages/flask/app.py", line 1936, in dispatch_request return self.view_functions[rule.endpoint](**req.view_args) File "/layers/google.python.functions-framework/functions-framework/lib/python3.8/site-packages/functions_framework/__init__.py", line 66, in view_func return function(request._get_current_object()) File "/workspace/main.py", line 282, in routeCreatorMain driverDB.document('Lu2qHfOqtma48r7L2g4PsEDQizD2').update({'route':routeByDriverDict[driver]}) File "/layers/google.python.pip/pip/lib/python3.8/site-packages/google/cloud/firestore_v1/document.py",
line 284, in update batch, kwargs = self._prep_update(field_updates, option, retry, timeout) File "/layers/google.python.pip/pip/lib/python3.8/site-packages/google/cloud/firestore_v1/base_document.py",
line 232, in _prep_update batch.update(self, field_updates, option=option) File "/layers/google.python.pip/pip/lib/python3.8/site-packages/google/cloud/firestore_v1/base_batch.py",
line 126, in update write_pbs = _helpers.pbs_for_update( File "/layers/google.python.pip/pip/lib/python3.8/site-packages/google/cloud/firestore_v1/_helpers.py",
line 847, in pbs_for_update extractor = DocumentExtractorForUpdate(field_updates) File "/layers/google.python.pip/pip/lib/python3.8/site-packages/google/cloud/firestore_v1/_helpers.py",
line 798, in __init__ super(DocumentExtractorForUpdate, self).__init__(document_data) File "/layers/google.python.pip/pip/lib/python3.8/site-packages/google/cloud/firestore_v1/_helpers.py",
line 422, in __init__ for field_path, value in iterator: File "/layers/google.python.pip/pip/lib/python3.8/site-packages/google/cloud/firestore_v1/_helpers.py",
line 369, in extract_fields for s_path, s_value in extract_fields(value, field_path): File "/layers/google.python.pip/pip/lib/python3.8/site-packages/google/cloud/firestore_v1/_helpers.py",
line 369, in extract_fields for s_path, s_value in extract_fields(value, field_path): File "/layers/google.python.pip/pip/lib/python3.8/site-packages/google/cloud/firestore_v1/_helpers.py",
line 364, in extract_fields sub_key = FieldPath(key) File "/layers/google.python.pip/pip/lib/python3.8/site-packages/google/cloud/firestore_v1/field_path.py",
line 272, in __init__ raise ValueError(error) ValueError: One or more components is not a string or is empty.
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 get some data from a third-party API, and I always get the same result no matter how I do it.
This is my code:
row = db.execute("SELECT isbn, title, author, year FROM books WHERE \
isbn = :isbn",
{"isbn": isbn})
bookInfo = row.fetchall()
""" GOODREADS reviews """
# Read API key from env variable
key = os.getenv('GOODREADS_KEY')
# Query the api with key and ISBN as parameters
query = requests.get("https://www.goodreads.com/book/review_counts.json",
params={"key": key, "isbns": isbn})
# Convert the response to JSON
response = query.json()
# "Clean" the JSON before passing it to the bookInfo list
response = response['books'][0]
# Append it as the second element on the list. [1]
bookInfo.append(response)
""" Users reviews """
# Search book_id by ISBN
row = db.execute("SELECT id FROM books WHERE isbn = :isbn",
{"isbn": isbn})
# Save id into variable
book = row.fetchone() # (id,)
book = book[0]
# Fetch book reviews
results = db.execute("SELECT users.username, review, rate, \
to_char(date, 'DD Mon YY - HH24:MI:SS') as time \
FROM users \
INNER JOIN reviews \
ON users.id = reviews.user_id \
WHERE book_id = :book \
ORDER BY time",
{"book": book})
if results.rowcount == 0:
return render_template("error.html", message="kept you waiting, huh")
reviews = results.fetchall()
return render_template("book.html", bookInfo=bookInfo, reviews=reviews)
And this is the error:
Traceback (most recent call last):
File "c:\users\enrique mota\documents\project1\env\lib\site-packages\flask\app.py", line 2463, in __call__
return self.wsgi_app(environ, start_response)
File "c:\users\enrique mota\documents\project1\env\lib\site-packages\flask\app.py", line 2449, in wsgi_app
response = self.handle_exception(e)
File "c:\users\enrique mota\documents\project1\env\lib\site-packages\flask\app.py", line 1866, in handle_exception
reraise(exc_type, exc_value, tb)
File "c:\users\enrique mota\documents\project1\env\lib\site-packages\flask\_compat.py", line 39, in reraise
raise value
File "c:\users\enrique mota\documents\project1\env\lib\site-packages\flask\app.py", line 2446, in wsgi_app
response = self.full_dispatch_request()
File "c:\users\enrique mota\documents\project1\env\lib\site-packages\flask\app.py", line 1951, in full_dispatch_request
rv = self.handle_user_exception(e)
File "c:\users\enrique mota\documents\project1\env\lib\site-packages\flask\app.py", line 1820, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "c:\users\enrique mota\documents\project1\env\lib\site-packages\flask\_compat.py", line 39, in reraise
raise value
File "c:\users\enrique mota\documents\project1\env\lib\site-packages\flask\app.py", line 1949, in full_dispatch_request
rv = self.dispatch_request()
File "c:\users\enrique mota\documents\project1\env\lib\site-packages\flask\app.py", line 1935, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "C:\Users\Enrique Mota\Documents\project1\LR.py", line 9, in decorated_function
return f(*args, **kwargs)
File "C:\Users\Enrique Mota\Documents\project1\application.py", line 195, in book
response = query.json()
File "c:\users\enrique mota\documents\project1\env\lib\site-packages\requests\models.py", line 897, in json
return complexjson.loads(self.text, **kwargs)
File "C:\Users\Enrique Mota\AppData\Local\Programs\Python\Python37\lib\json\__init__.py", line 348, in loads
return _default_decoder.decode(s)
File "C:\Users\Enrique Mota\AppData\Local\Programs\Python\Python37\lib\json\decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Users\Enrique Mota\AppData\Local\Programs\Python\Python37\lib\json\decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
These are the parameters to get the book info:
Get review statistics given a list of ISBNs
Get review statistics for books given a list of ISBNs.
ISBNs can be specified as an array (e.g. isbns[]=0441172717&isbns[]=0141439602) or a single, comma-separated string (e.g. isbns=0441172717,0141439602).
You can mix ISBN10s and ISBN13s, but you'll receive a 422 error if you don't specify any, and you'll receive a 404 if none are found.
URL: https://www.goodreads.com/book/review_counts.json (sample url)
HTTP method: GET
Parameters:
key: Developer key (required).
isbns: Array of ISBNs or a comma separated string of ISBNs (1000 ISBNs per request max.)
format: json
callback: function to wrap JSON response
This is a sample URL:
https://www.goodreads.com/book/review_counts.json?isbns=0441172717%2C0141439602&key=IcOZSbhCZizWqiomGMUw
To my understanding, I only need two parameters which I specified in my code, no matter how I code the app, It always has that response/error, what I'm I doing wrong?
I did import json, os, jsonify, and requests btw.
You should check status code first.
if query.status_code == requests.codes['ok']:
response = query.json()
else:
# Do something else
The code below works so you need to check the params you send (key and isbns)
import requests
r = requests.get("https://www.goodreads.com/book/review_counts.json",
params={"key": 'IcOZSbhCZizWqiomGMUw', "isbns": '0441172717,0141439602'})
if r.status_code == 200:
print(r.json())
output
{'books': [{'id': 47173379, 'isbn': '0441172717', 'isbn13': '9780441172719', 'ratings_count': 85, 'reviews_count': 211, 'text_reviews_count': 5, 'work_ratings_count': 641157, 'work_reviews_count': 1080654, 'work_text_reviews_count': 17613, 'average_rating': '4.22'}, {'id': 1953, 'isbn': '0141439602', 'isbn13': '9780141439600', 'ratings_count': 705737, 'reviews_count': 1237587, 'text_reviews_count': 11902, 'work_ratings_count': 758306, 'work_reviews_count': 1389929, 'work_text_reviews_count': 15806, 'average_rating': '3.83'}]}
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'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/