list index out of range on sqlalchemy query - python

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

Related

ValueError generic WSGI request error too many values to unpack (expected 2)

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.

How to send jwt token in json format?

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!

Pass WTForms form data to a Celery task

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)

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

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

How can insert a new object in one table after updating another table in flask-sqlalchemy

I am using Flask-Sqlalchemy orm in my project.
I have to insert a new object in one table, whenever there is an update on another table.So, I chose models_committed signal.But, the object is not inserted.
#models_committed.connect_via(app)
def on_models_committed(sender, changes):
print "signal",changes
for obj, change in changes:
if obj.__table__.strip() == 'task':
print "works"
obj = TaskHistory(task_id=target.id, task_status_id=target.task_status_id, reason=target.reason)
print "History Object",obj
db.session.add(obj)
db.session.commit()
Traceback:
Short version:
**sqlalchemy.exc.InvalidRequestError
InvalidRequestError: This session is in 'committed' state; no further SQL can be emitted within this transaction.**
Long version:
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1836, in __call__
return self.wsgi_app(environ, start_response)
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1820, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1403, in handle_exception
reraise(exc_type, exc_value, tb)
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1817, in wsgi_app
response = self.full_dispatch_request()
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1477, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1381, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1475, in full_dispatch_request
rv = self.dispatch_request()
File "/usr/local/lib/python2.7/dist-packages/flask_debugtoolbar/__init__.py", line 125, in dispatch_request
return view_func(**req.view_args)
File "/usr/lib/python2.7/cProfile.py", line 149, in runcall
return func(*args, **kw)
File "/usr/local/lib/python2.7/dist-packages/flask_superadmin/base.py", line 37, in inner
return f(self, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/flask_superadmin/base.py", line 37, in inner
return f(self, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/flask_superadmin/base.py", line 37, in inner
return f(self, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/flask_superadmin/base.py", line 37, in inner
return f(self, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/flask_superadmin/model/base.py", line 345, in edit
pk=self.get_pk(instance), instance=instance)
File "/usr/local/lib/python2.7/dist-packages/flask_superadmin/base.py", line 169, in render
return render_template(template, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/flask/templating.py", line 128, in render_template
context, ctx.app)
File "/usr/local/lib/python2.7/dist-packages/flask/templating.py", line 110, in _render
rv = template.render(context)
File "/usr/share/pyshared/jinja2/environment.py", line 969, in render
return self.environment.handle_exception(exc_info, True)
File "/usr/share/pyshared/jinja2/environment.py", line 742, in handle_exception
reraise(exc_type, exc_value, tb)
File "/usr/local/lib/python2.7/dist-packages/flask_superadmin/templates/admin/model/edit.html", line 3, in top-level template code
{% set name = admin_view.get_display_name() %}
File "/usr/local/lib/python2.7/dist-packages/flask_superadmin/templates/admin/layout.html", line 21, in top-level template code
{% block page_body %}
File "/usr/local/lib/python2.7/dist-packages/flask_superadmin/templates/admin/layout.html", line 70, in block "page_body"
{% block body %}{% endblock %}
File "/usr/local/lib/python2.7/dist-packages/flask_superadmin/templates/admin/model/edit.html", line 26, in block "body"
{{ lib.render_form(form, extra(), admin_view.can_edit, admin_view.can_delete) }}
File "/usr/local/lib/python2.7/dist-packages/flask_superadmin/templates/admin/_macros.html", line 192, in template
{{ render_formfield(form) }}
File "/usr/local/lib/python2.7/dist-packages/flask_superadmin/templates/admin/_macros.html", line 180, in template
{{ render_ff(form._fields[field_name]) }}
File "/usr/local/lib/python2.7/dist-packages/flask_superadmin/templates/admin/_macros.html", line 142, in template
{{ ff(class=class) }}
File "/usr/local/lib/python2.7/dist-packages/wtforms/fields/core.py", line 139, in __call__
return self.widget(self, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/flask_superadmin/form.py", line 96, in __call__
return super(ChosenSelectWidget, self).__call__(field, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/wtforms/widgets/core.py", line 243, in __call__
for val, label, selected in field.iter_choices():
File "/usr/local/lib/python2.7/dist-packages/wtforms/ext/sqlalchemy/fields.py", line 108, in iter_choices
for pk, obj in self._get_object_list():
File "/usr/local/lib/python2.7/dist-packages/wtforms/ext/sqlalchemy/fields.py", line 101, in _get_object_list
self._object_list = list((text_type(get_pk(obj)), obj) for obj in query)
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/query.py", line 2404, in __iter__
return self._execute_and_instances(context)
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/query.py", line 2417, in _execute_and_instances
close_with_result=True)
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/query.py", line 2408, in _connection_from_session
**kw)
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/session.py", line 843, in connection
close_with_result=close_with_result)
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/session.py", line 847, in _connection_for_bind
return self.transaction._connection_for_bind(engine)
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/session.py", line 298, in _connection_for_bind
self._assert_active()
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/session.py", line 192, in _assert_active
"This session is in 'committed' state; no further "
InvalidRequestError: This session is in 'committed' state; no further SQL can be emitted within this transaction.
Could you assist me on solving this issue?
Tools I am using: Python 2.7, Flask, SqlAlchemy
#models_committed.connect_via(app)
def on_models_committed(sender, changes):
db_name = app.config["DB_NAME"]
db_user = app.config["DB_USER"]
db_pwd = app.config["DB_PWD"]
conn = psycopg2.connect("dbname='%s' user='%s' host='localhost' password='%s'" %(db_name, db_user, db_pwd))
query = "INSERT INTO task_history(task_id, task_status_id, updated_on, updated_by, reason)" +\
"VALUES (%s, %s, '%s', %s, '%s')"
cur = conn.cursor()
for obj, change in changes:
if str(obj.__table__).strip() == 'task':
cur.execute(query % (obj.id, obj.task_status_id, "now()", 2, "Thats it"))
conn.commit()
My Solution(I have answered my question):
created seperate connection using psycopg2
Inserted new object
This is not a solution, you've only gone around the problem. You should be looking at why you've reassigned obj within the for loop. Removing that reassignment would have likely solved your problem.

Categories