0

I am requesting data via an API and store these JSON data in variables. Goal is to store these data in a MySQL database using SQLAlchemy (Python, Flask).

The current load has multiple stops and each stop could have multiple actions. After session.commit() the tour_stop_to_add gets inserted in the database and it gets an id assigned.

Therefore, the id of tour_stop_to_add is available. Also, the type gets transformed successfully to the requested enum and transportOrderNumber is also available as a string.

The data types of the model are equivalent with the types provided for the object creation. The values of the dict stored in 'action' are present and available.

Classes for stop and action

class TourStop(db.Model):
    __tablename__ = "tour_stop"

    id = db.Column(db.Integer, primary_key=True)

    actions = db.relationship("TourStopAction", backref="tour_stop", lazy=False)


class ActionType(Enum):
    PICKUP = 'PICKUP'
    DELIVERY = 'DELIVERY'


class TourStopAction(db.Model):
    __tablename__ = "tour_stop_action"

    id = db.Column(db.Integer, primary_key=True)

    tour_stop_id = db.Column(db.Integer, db.ForeignKey('tour_stop.id'), nullable=False)

    type = db.Column(db.Enum(ActionType), nullable=False)
    transport_order_number = db.Column(db.String(255), nullable=False)

Extract from the code trying to persist stops and actions

for stop in load.get('tourStops'):
    tour_stop_to_add = TourStop(...)
    session.add(tour_stop_to_add)
    session.commit()

    for action in stop.get('actions'):
        tour_stop_action_to_add = TourStopAction(tour_stop=tour_stop_to_add.id, type=ActionType(action.get('type')), transport_order_number=action.get('transportOrderNumber'))
        session.add(tour_stop_action_to_add)

The following error occurs when creating an object of TourStopAction.

Traceback (most recent call last):
  File "../venv/lib/python3.6/site-packages/flask/app.py", line 2309, in __call__
    return self.wsgi_app(environ, start_response)
  File "../venv/lib/python3.6/site-packages/flask/app.py", line 2295, in wsgi_app
    response = self.handle_exception(e)
  File "../venv/lib/python3.6/site-packages/flask/app.py", line 1741, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "../venv/lib/python3.6/site-packages/flask/_compat.py", line 35, in reraise
    raise value
  File "../venv/lib/python3.6/site-packages/flask/app.py", line 2292, in wsgi_app
    response = self.full_dispatch_request()
  File "../venv/lib/python3.6/site-packages/flask/app.py", line 1815, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "../venv/lib/python3.6/site-packages/flask/app.py", line 1718, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "../venv/lib/python3.6/site-packages/flask/_compat.py", line 35, in reraise
    raise value
  File "../venv/lib/python3.6/site-packages/flask/app.py", line 1813, in full_dispatch_request
    rv = self.dispatch_request()
  File "../venv/lib/python3.6/site-packages/flask/app.py", line 1799, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "../views/views.py", line 26, in import_loads_api
    import_loads()
  File "../services/historical_data/import_historical_data.py", line 53, in import_loads
    store_loads(loads_json)
  File "../services/historical_data/import_historical_data.py", line 81, in store_loads
    transport_order_number=action.get('transportOrderNumber'))
  File "<string>", line 4, in __init__

  File "../venv/lib/python3.6/site-packages/sqlalchemy/orm/state.py", line 424, in _initialize_instance
    manager.dispatch.init_failure(self, args, kwargs)
  File "../venv/lib/python3.6/site-packages/sqlalchemy/util/langhelpers.py", line 66, in __exit__
    compat.reraise(exc_type, exc_value, exc_tb)
  File "../venv/lib/python3.6/site-packages/sqlalchemy/util/compat.py", line 249, in reraise
    raise value
  File "../venv/lib/python3.6/site-packages/sqlalchemy/orm/state.py", line 421, in _initialize_instance
    return manager.original_init(*mixed[1:], **kwargs)
  File "../venv/lib/python3.6/site-packages/sqlalchemy/ext/declarative/base.py", line 748, in _declarative_constructor
    setattr(self, k, kwargs[k])
  File "../venv/lib/python3.6/site-packages/sqlalchemy/orm/attributes.py", line 229, in __set__
    instance_dict(instance), value, None)
  File "../venv/lib/python3.6/site-packages/sqlalchemy/orm/attributes.py", line 815, in set
    value = self.fire_replace_event(state, dict_, value, old, initiator)
  File "../venv/lib/python3.6/site-packages/sqlalchemy/orm/attributes.py", line 835, in fire_replace_event
    state, value, previous, initiator or self._replace_token)
  File "../venv/lib/python3.6/site-packages/sqlalchemy/orm/attributes.py", line 1183, in emit_backref_from_scalar_set_event
    child_state, child_dict = instance_state(child),\
AttributeError: 'int' object has no attribute '_sa_instance_state'

AttributeError: 'int' object has no attribute '_sa_instance_state'

Please try to help in how I could create and persist tour_stop_to_add successfully.

Felix Seifert
  • 552
  • 1
  • 9
  • 19
  • have you investigated the object at the line causing trouble? a quick try/except should give you a better idea. `try: tour_stop_action_to_add =.... (2 lines of code); except AttributeError: print(repr(action);raise AttributeError` – e.s. Jan 11 '19 at 21:06
  • @e.s. I tried investigating the objection creation like recommended. This show the values of the dict stored in the variable action. {'type': 'PICKUP', 'transportOrderNumber': 'TO123456789'} Anyway, these were checked already before using the debug function of my IDE. – Felix Seifert Jan 11 '19 at 21:41

0 Answers0