Issues with getting JSON data from AJAX POST - python

The AJAX call looks like this:
json_dictionary = {url : url, profile_dict: dictionary, final_dict : final_dictionary}
$.ajax({
url: "https://localhost:8090/add_profile_data",
type: "POST",
data: JSON.stringify(json_dictionary),
contentType:'application/json',
success:function() {
console.log('added profile data')
}
})
The client side looks like this:
#app.route('/add_profile_data', methods=['POST', 'GET', 'OPTIONS'])
def add():
data = request.json
print(type(data))
That works, and the result from print is <type 'dict'>
Also, when I print the data object, everything is there.
However, when I try:
#app.route('/add_profile_data', methods=['POST', 'GET', 'OPTIONS'])
def add():
data = request.json
print(data.keys())
I get an error: AttributeError: 'NoneType' object has no attribute 'keys'
I don't understand why this is happening? Any thoughts?
Update:
Changed the server to this, and now seeing NoneType for print(type(data))
Server:
#app.route('/add_profile_data', methods=['POST', 'GET', 'OPTIONS'])
def add():
data = request.json
print(type(data))
print(data.keys())
Response:
<type 'NoneType'>
127.0.0.1 - - [04/Jan/2017 09:13:47] "OPTIONS /add_profile_data HTTP/1.1" 500 -
Traceback (most recent call last):
File "/Library/Python/2.7/site-packages/flask/app.py", line 2000, in __call__
return self.wsgi_app(environ, start_response)
File "/Library/Python/2.7/site-packages/flask/app.py", line 1991, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "/Library/Python/2.7/site-packages/flask_cors/extension.py", line 161, in wrapped_function
return cors_after_request(app.make_response(f(*args, **kwargs)))
File "/Library/Python/2.7/site-packages/flask/app.py", line 1567, in handle_exception
reraise(exc_type, exc_value, tb)
File "/Library/Python/2.7/site-packages/flask/app.py", line 1988, in wsgi_app
response = self.full_dispatch_request()
File "/Library/Python/2.7/site-packages/flask/app.py", line 1641, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/Library/Python/2.7/site-packages/flask_cors/extension.py", line 161, in wrapped_function
return cors_after_request(app.make_response(f(*args, **kwargs)))
File "/Library/Python/2.7/site-packages/flask/app.py", line 1544, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/Library/Python/2.7/site-packages/flask/app.py", line 1639, in full_dispatch_request
rv = self.dispatch_request()
File "/Library/Python/2.7/site-packages/flask/app.py", line 1625, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/Users/morganallen/Dropbox/Coding_Projects/Prediction_Server/prediction_v2.py", line 172, in add
print(data.keys())
AttributeError: 'NoneType' object has no attribute 'keys'
Any reason why I am seeing NoneType?

127.0.0.1 - - [04/Jan/2017 09:13:47] "OPTIONS /add_profile_data HTTP/1.1" 500
An OPTIONS request will not include JSON.
Edit your code to only check the JSON if the method is POST.
For example:
#app.route('/add_profile_data', methods=['POST', 'GET'])
def add():
if request.method == 'POST':
data = request.json
print(type(data))
print(data.keys())

Related

ERROR: TypeError: Object of type ColumnClause is not JSON serializable Python3

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.

How do I route data from one page to other in flask?

I have a page index.html that has to send two values to main.html. From index.html, I send an ajax request to /api/session_load with a json object data. I call the redirect function to main
#app.route('/')
def index():
return render_template('index.html')
#app.route('/main')
def main(names):
print('Hello-main')
print('main', names, type(names))
return render_template('main.html', nomens = names)
#app.route('/api/session_load', methods=['GET', 'POST'])
def session_load():
if request.method == "POST":
data = json.loads(request.get_data())
global session_name
global file_name
session_name = data['session_name']
file_name = data['file_name']
print('sess', data, type(data))
return redirect(url_for('main', names = data))
This is the output
* Restarting with stat
* Debugger is active!
* Debugger PIN: 147-211-412
sess {'file_name': 'sample.txt', 'session_name': 'asfds'} <class 'dict'>
127.0.0.1 - - [09/May/2019 00:04:32] "POST /api/session_load HTTP/1.1" 302 -
127.0.0.1 - - [09/May/2019 00:04:32] "GET /main?names=%7B%27file_name%27%3A+%27sample.txt%27%2C+%27session_name%27%3A+%27asfds%27%7D HTTP/1.1" 500 -
Traceback (most recent call last):
File "/Users/300041738/.arun-venv3/lib/python3.7/site-packages/flask/app.py", line 2309, in __call__
return self.wsgi_app(environ, start_response)
File "/Users/300041738/.arun-venv3/lib/python3.7/site-packages/flask/app.py", line 2295, in wsgi_app
response = self.handle_exception(e)
File "/Users/300041738/.arun-venv3/lib/python3.7/site-packages/flask/app.py", line 1741, in handle_exception
reraise(exc_type, exc_value, tb)
File "/Users/300041738/.arun-venv3/lib/python3.7/site-packages/flask/_compat.py", line 35, in reraise
raise value
File "/Users/300041738/.arun-venv3/lib/python3.7/site-packages/flask/app.py", line 2292, in wsgi_app
response = self.full_dispatch_request()
File "/Users/300041738/.arun-venv3/lib/python3.7/site-packages/flask/app.py", line 1815, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/Users/300041738/.arun-venv3/lib/python3.7/site-packages/flask/app.py", line 1718, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/Users/300041738/.arun-venv3/lib/python3.7/site-packages/flask/_compat.py", line 35, in reraise
raise value
File "/Users/300041738/.arun-venv3/lib/python3.7/site-packages/flask/app.py", line 1813, in full_dispatch_request
rv = self.dispatch_request()
File "/Users/300041738/.arun-venv3/lib/python3.7/site-packages/flask/app.py", line 1799, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
TypeError: main() missing 1 required positional argument: 'names'
main.html file has proper templating with {{ nomens }}. Both statements of main() don't print.
#app.route('/main') should be #app.route('/main/<string:names>'). You need to tell flask the url is expecting something else after your route name.

Python: str(bytes object) in jsonify causes TypeError: Object of type 'bytes' is not JSON serializable

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')

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)])

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