prompt: We are currently solving the following issue within our repository. Here is the issue text:
  --- BEGIN ISSUE ---
  is_stripe_linked property does not set on connecting stripe account
  **Describe the bug**
  is_stripe_linked property does not set on connecting stripe account. It throws error.
  
  **Expected behavior**
  Property should set appropriately.
  
  **Error**
  ```
  Class 'sqlalchemy.orm.query.Query' is not mapped Traceback (most recent call last):
    File "/home/rs/Pradeep/github/open-event-server/env/lib/python3.5/site-packages/sqlalchemy/orm/session.py", line 1722, in add
      state = attributes.instance_state(instance)
  AttributeError: 'Query' object has no attribute '_sa_instance_state'
  
  During handling of the above exception, another exception occurred:
  
  Traceback (most recent call last):
    File "/home/rs/Pradeep/github/open-event-server/app/api/helpers/db.py", line 22, in save_to_db
      db.session.add(item)
    File "/home/rs/Pradeep/github/open-event-server/env/lib/python3.5/site-packages/sqlalchemy/orm/scoping.py", line 157, in do
      return getattr(self.registry(), name)(*args, **kwargs)
    File "/home/rs/Pradeep/github/open-event-server/env/lib/python3.5/site-packages/sqlalchemy/orm/session.py", line 1724, in add
      raise exc.UnmappedInstanceError(instance)
  sqlalchemy.orm.exc.UnmappedInstanceError: Class 'sqlalchemy.orm.query.Query' is not mapped
  ERROR:root:DB Exception! Class 'sqlalchemy.orm.query.Query' is not mapped
  ```
  
  --- END ISSUE ---
  
  Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
  --- BEGIN FILES ---
  Path: `app/api/stripe_authorization.py`
  Content:
  ```
  1 from flask_rest_jsonapi import ResourceDetail, ResourceList
  2 from sqlalchemy.orm.exc import NoResultFound
  3 
  4 from app.api.bootstrap import api
  5 from app.api.helpers.db import safe_query, get_count, save_to_db
  6 from app.api.helpers.exceptions import ForbiddenException, ConflictException, UnprocessableEntity
  7 from app.api.helpers.payment import StripePaymentsManager
  8 from app.api.helpers.permission_manager import has_access
  9 from app.api.helpers.permissions import jwt_required
  10 from app.api.helpers.utilities import require_relationship
  11 from app.api.schema.stripe_authorization import StripeAuthorizationSchema
  12 from app.models import db
  13 from app.models.event import Event
  14 from app.models.stripe_authorization import StripeAuthorization
  15 
  16 
  17 class StripeAuthorizationListPost(ResourceList):
  18     """
  19     List and Create Stripe Authorization
  20     """
  21     def before_post(self, args, kwargs, data):
  22         """
  23         before post method to check for required relationship and proper permission
  24         :param args:
  25         :param kwargs:
  26         :param data:
  27         :return:
  28         """
  29         require_relationship(['event'], data)
  30         if not has_access('is_organizer', event_id=data['event']):
  31             raise ForbiddenException({'source': ''}, "Minimum Organizer access required")
  32         if get_count(db.session.query(Event).filter_by(id=int(data['event']), can_pay_by_stripe=False)) > 0:
  33             raise ForbiddenException({'pointer': ''}, "Stripe payment is disabled for this Event")
  34 
  35     def before_create_object(self, data, view_kwargs):
  36         """
  37         method to check if stripe authorization object already exists for an event.
  38         Raises ConflictException if it already exists.
  39         If it doesn't, then uses the StripePaymentManager to get the other credentials from Stripe.
  40         :param data:
  41         :param view_kwargs:
  42         :return:
  43         """
  44         try:
  45             self.session.query(StripeAuthorization).filter_by(event_id=data['event'], deleted_at=None).one()
  46         except NoResultFound:
  47             credentials = StripePaymentsManager\
  48                 .get_event_organizer_credentials_from_stripe(data['stripe_auth_code'])
  49             if 'error' in credentials:
  50                 raise UnprocessableEntity({'pointer': '/data/stripe_auth_code'}, credentials['error_description'])
  51             data['stripe_secret_key'] = credentials['access_token']
  52             data['stripe_refresh_token'] = credentials['refresh_token']
  53             data['stripe_publishable_key'] = credentials['stripe_publishable_key']
  54             data['stripe_user_id'] = credentials['stripe_user_id']
  55         else:
  56             raise ConflictException({'pointer': '/data/relationships/event'},
  57                                     "Stripe Authorization already exists for this event")
  58 
  59     def after_create_object(self, stripe_authorization, data, view_kwargs):
  60         """
  61         after create object method for StripeAuthorizationListPost Class
  62         :param stripe_authorization: Stripe authorization created from mashmallow_jsonapi
  63         :param data:
  64         :param view_kwargs:
  65         :return:
  66         """
  67         event = db.session.query(Event).filter_by(id=int(data['event']))
  68         event.is_stripe_linked = True
  69         save_to_db(event)
  70 
  71     schema = StripeAuthorizationSchema
  72     decorators = (jwt_required, )
  73     methods = ['POST']
  74     data_layer = {'session': db.session,
  75                   'model': StripeAuthorization,
  76                   'methods': {
  77                       'before_create_object': before_create_object,
  78                       'after_create_object': after_create_object
  79                   }}
  80 
  81 
  82 class StripeAuthorizationDetail(ResourceDetail):
  83     """
  84     Stripe Authorization Detail Resource by ID
  85     """
  86     def before_get_object(self, view_kwargs):
  87         """
  88         method to get id of stripe authorization related to an event
  89         :param view_kwargs:
  90         :return:
  91         """
  92         if view_kwargs.get('event_identifier'):
  93             event = safe_query(self, Event, 'identifier', view_kwargs['event_identifier'], 'event_identifier')
  94             view_kwargs['event_id'] = event.id
  95 
  96         if view_kwargs.get('event_id'):
  97             stripe_authorization = \
  98                 safe_query(self, StripeAuthorization, 'event_id', view_kwargs['event_id'], 'event_id')
  99             view_kwargs['id'] = stripe_authorization.id
  100 
  101     def after_delete_object(self, stripe_authorization, view_kwargs):
  102         """Make work after delete object
  103         :param stripe_authorization: stripe authorization.
  104         :param dict view_kwargs: kwargs from the resource view
  105         """
  106         event = stripe_authorization.event
  107         event.is_stripe_linked = False
  108         save_to_db(event)
  109 
  110     decorators = (api.has_permission('is_coorganizer', fetch="event_id",
  111                                      fetch_as="event_id", model=StripeAuthorization),)
  112     schema = StripeAuthorizationSchema
  113     data_layer = {'session': db.session,
  114                   'model': StripeAuthorization,
  115                   'methods': {
  116                       'before_get_object': before_get_object,
  117                       'after_delete_object': after_delete_object
  118                   }}
  119 
  120 
  121 class StripeAuthorizationRelationship(ResourceDetail):
  122     """
  123     Stripe Authorization Relationship
  124     """
  125 
  126     decorators = (api.has_permission('is_coorganizer', fetch="event_id",
  127                                      fetch_as="event_id", model=StripeAuthorization),)
  128     schema = StripeAuthorizationSchema
  129     data_layer = {'session': db.session,
  130                   'model': StripeAuthorization}
  131
  ```
  --- END FILES ---
  
  Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.
  
  Here is an example:
  
  ```diff
  diff --git a/examples/server_async.py b/examples/server_async.py
  --- a/examples/server_async.py
  +++ b/examples/server_async.py
  @@ -313,4 +313,4 @@
   
   
   if __name__ == "__main__":
  -    asyncio.run(run_async_server("."), debug=True)
  +    asyncio.run(run_async_server(), debug=True)
  diff --git a/examples/server_sync.py b/examples/server_sync.py
  --- a/examples/server_sync.py
  +++ b/examples/server_sync.py
  @@ -313,5 +313,5 @@
   
   
   if __name__ == "__main__":
  -    server = run_sync_server(".")
  +    server = run_sync_server()
       server.shutdown()
  
  ```
  
golden_diff: diff --git a/app/api/stripe_authorization.py b/app/api/stripe_authorization.py
  --- a/app/api/stripe_authorization.py
  +++ b/app/api/stripe_authorization.py
  @@ -64,7 +64,7 @@
           :param view_kwargs:
           :return:
           """
  -        event = db.session.query(Event).filter_by(id=int(data['event']))
  +        event = db.session.query(Event).filter_by(id=int(data['event'])).one()
           event.is_stripe_linked = True
           save_to_db(event)
  
verification_info: {"golden_diff": "diff --git a/app/api/stripe_authorization.py b/app/api/stripe_authorization.py\n--- a/app/api/stripe_authorization.py\n+++ b/app/api/stripe_authorization.py\n@@ -64,7 +64,7 @@\n         :param view_kwargs:\n         :return:\n         \"\"\"\n-        event = db.session.query(Event).filter_by(id=int(data['event']))\n+        event = db.session.query(Event).filter_by(id=int(data['event'])).one()\n         event.is_stripe_linked = True\n         save_to_db(event)\n", "issue": "is_stripe_linked property does not set on connecting stripe account\n**Describe the bug**\r\nis_stripe_linked property does not set on connecting stripe account. It throws error.\r\n\r\n**Expected behavior**\r\nProperty should set appropriately.\r\n\r\n**Error**\r\n```\r\nClass 'sqlalchemy.orm.query.Query' is not mapped Traceback (most recent call last):\r\n  File \"/home/rs/Pradeep/github/open-event-server/env/lib/python3.5/site-packages/sqlalchemy/orm/session.py\", line 1722, in add\r\n    state = attributes.instance_state(instance)\r\nAttributeError: 'Query' object has no attribute '_sa_instance_state'\r\n\r\nDuring handling of the above exception, another exception occurred:\r\n\r\nTraceback (most recent call last):\r\n  File \"/home/rs/Pradeep/github/open-event-server/app/api/helpers/db.py\", line 22, in save_to_db\r\n    db.session.add(item)\r\n  File \"/home/rs/Pradeep/github/open-event-server/env/lib/python3.5/site-packages/sqlalchemy/orm/scoping.py\", line 157, in do\r\n    return getattr(self.registry(), name)(*args, **kwargs)\r\n  File \"/home/rs/Pradeep/github/open-event-server/env/lib/python3.5/site-packages/sqlalchemy/orm/session.py\", line 1724, in add\r\n    raise exc.UnmappedInstanceError(instance)\r\nsqlalchemy.orm.exc.UnmappedInstanceError: Class 'sqlalchemy.orm.query.Query' is not mapped\r\nERROR:root:DB Exception! Class 'sqlalchemy.orm.query.Query' is not mapped\r\n```\n", "before_files": [{"content": "from flask_rest_jsonapi import ResourceDetail, ResourceList\nfrom sqlalchemy.orm.exc import NoResultFound\n\nfrom app.api.bootstrap import api\nfrom app.api.helpers.db import safe_query, get_count, save_to_db\nfrom app.api.helpers.exceptions import ForbiddenException, ConflictException, UnprocessableEntity\nfrom app.api.helpers.payment import StripePaymentsManager\nfrom app.api.helpers.permission_manager import has_access\nfrom app.api.helpers.permissions import jwt_required\nfrom app.api.helpers.utilities import require_relationship\nfrom app.api.schema.stripe_authorization import StripeAuthorizationSchema\nfrom app.models import db\nfrom app.models.event import Event\nfrom app.models.stripe_authorization import StripeAuthorization\n\n\nclass StripeAuthorizationListPost(ResourceList):\n    \"\"\"\n    List and Create Stripe Authorization\n    \"\"\"\n    def before_post(self, args, kwargs, data):\n        \"\"\"\n        before post method to check for required relationship and proper permission\n        :param args:\n        :param kwargs:\n        :param data:\n        :return:\n        \"\"\"\n        require_relationship(['event'], data)\n        if not has_access('is_organizer', event_id=data['event']):\n            raise ForbiddenException({'source': ''}, \"Minimum Organizer access required\")\n        if get_count(db.session.query(Event).filter_by(id=int(data['event']), can_pay_by_stripe=False)) > 0:\n            raise ForbiddenException({'pointer': ''}, \"Stripe payment is disabled for this Event\")\n\n    def before_create_object(self, data, view_kwargs):\n        \"\"\"\n        method to check if stripe authorization object already exists for an event.\n        Raises ConflictException if it already exists.\n        If it doesn't, then uses the StripePaymentManager to get the other credentials from Stripe.\n        :param data:\n        :param view_kwargs:\n        :return:\n        \"\"\"\n        try:\n            self.session.query(StripeAuthorization).filter_by(event_id=data['event'], deleted_at=None).one()\n        except NoResultFound:\n            credentials = StripePaymentsManager\\\n                .get_event_organizer_credentials_from_stripe(data['stripe_auth_code'])\n            if 'error' in credentials:\n                raise UnprocessableEntity({'pointer': '/data/stripe_auth_code'}, credentials['error_description'])\n            data['stripe_secret_key'] = credentials['access_token']\n            data['stripe_refresh_token'] = credentials['refresh_token']\n            data['stripe_publishable_key'] = credentials['stripe_publishable_key']\n            data['stripe_user_id'] = credentials['stripe_user_id']\n        else:\n            raise ConflictException({'pointer': '/data/relationships/event'},\n                                    \"Stripe Authorization already exists for this event\")\n\n    def after_create_object(self, stripe_authorization, data, view_kwargs):\n        \"\"\"\n        after create object method for StripeAuthorizationListPost Class\n        :param stripe_authorization: Stripe authorization created from mashmallow_jsonapi\n        :param data:\n        :param view_kwargs:\n        :return:\n        \"\"\"\n        event = db.session.query(Event).filter_by(id=int(data['event']))\n        event.is_stripe_linked = True\n        save_to_db(event)\n\n    schema = StripeAuthorizationSchema\n    decorators = (jwt_required, )\n    methods = ['POST']\n    data_layer = {'session': db.session,\n                  'model': StripeAuthorization,\n                  'methods': {\n                      'before_create_object': before_create_object,\n                      'after_create_object': after_create_object\n                  }}\n\n\nclass StripeAuthorizationDetail(ResourceDetail):\n    \"\"\"\n    Stripe Authorization Detail Resource by ID\n    \"\"\"\n    def before_get_object(self, view_kwargs):\n        \"\"\"\n        method to get id of stripe authorization related to an event\n        :param view_kwargs:\n        :return:\n        \"\"\"\n        if view_kwargs.get('event_identifier'):\n            event = safe_query(self, Event, 'identifier', view_kwargs['event_identifier'], 'event_identifier')\n            view_kwargs['event_id'] = event.id\n\n        if view_kwargs.get('event_id'):\n            stripe_authorization = \\\n                safe_query(self, StripeAuthorization, 'event_id', view_kwargs['event_id'], 'event_id')\n            view_kwargs['id'] = stripe_authorization.id\n\n    def after_delete_object(self, stripe_authorization, view_kwargs):\n        \"\"\"Make work after delete object\n        :param stripe_authorization: stripe authorization.\n        :param dict view_kwargs: kwargs from the resource view\n        \"\"\"\n        event = stripe_authorization.event\n        event.is_stripe_linked = False\n        save_to_db(event)\n\n    decorators = (api.has_permission('is_coorganizer', fetch=\"event_id\",\n                                     fetch_as=\"event_id\", model=StripeAuthorization),)\n    schema = StripeAuthorizationSchema\n    data_layer = {'session': db.session,\n                  'model': StripeAuthorization,\n                  'methods': {\n                      'before_get_object': before_get_object,\n                      'after_delete_object': after_delete_object\n                  }}\n\n\nclass StripeAuthorizationRelationship(ResourceDetail):\n    \"\"\"\n    Stripe Authorization Relationship\n    \"\"\"\n\n    decorators = (api.has_permission('is_coorganizer', fetch=\"event_id\",\n                                     fetch_as=\"event_id\", model=StripeAuthorization),)\n    schema = StripeAuthorizationSchema\n    data_layer = {'session': db.session,\n                  'model': StripeAuthorization}\n", "path": "app/api/stripe_authorization.py"}], "after_files": [{"content": "from flask_rest_jsonapi import ResourceDetail, ResourceList\nfrom sqlalchemy.orm.exc import NoResultFound\n\nfrom app.api.bootstrap import api\nfrom app.api.helpers.db import safe_query, get_count, save_to_db\nfrom app.api.helpers.exceptions import ForbiddenException, ConflictException, UnprocessableEntity\nfrom app.api.helpers.payment import StripePaymentsManager\nfrom app.api.helpers.permission_manager import has_access\nfrom app.api.helpers.permissions import jwt_required\nfrom app.api.helpers.utilities import require_relationship\nfrom app.api.schema.stripe_authorization import StripeAuthorizationSchema\nfrom app.models import db\nfrom app.models.event import Event\nfrom app.models.stripe_authorization import StripeAuthorization\n\n\nclass StripeAuthorizationListPost(ResourceList):\n    \"\"\"\n    List and Create Stripe Authorization\n    \"\"\"\n    def before_post(self, args, kwargs, data):\n        \"\"\"\n        before post method to check for required relationship and proper permission\n        :param args:\n        :param kwargs:\n        :param data:\n        :return:\n        \"\"\"\n        require_relationship(['event'], data)\n        if not has_access('is_organizer', event_id=data['event']):\n            raise ForbiddenException({'source': ''}, \"Minimum Organizer access required\")\n        if get_count(db.session.query(Event).filter_by(id=int(data['event']), can_pay_by_stripe=False)) > 0:\n            raise ForbiddenException({'pointer': ''}, \"Stripe payment is disabled for this Event\")\n\n    def before_create_object(self, data, view_kwargs):\n        \"\"\"\n        method to check if stripe authorization object already exists for an event.\n        Raises ConflictException if it already exists.\n        If it doesn't, then uses the StripePaymentManager to get the other credentials from Stripe.\n        :param data:\n        :param view_kwargs:\n        :return:\n        \"\"\"\n        try:\n            self.session.query(StripeAuthorization).filter_by(event_id=data['event'], deleted_at=None).one()\n        except NoResultFound:\n            credentials = StripePaymentsManager\\\n                .get_event_organizer_credentials_from_stripe(data['stripe_auth_code'])\n            if 'error' in credentials:\n                raise UnprocessableEntity({'pointer': '/data/stripe_auth_code'}, credentials['error_description'])\n            data['stripe_secret_key'] = credentials['access_token']\n            data['stripe_refresh_token'] = credentials['refresh_token']\n            data['stripe_publishable_key'] = credentials['stripe_publishable_key']\n            data['stripe_user_id'] = credentials['stripe_user_id']\n        else:\n            raise ConflictException({'pointer': '/data/relationships/event'},\n                                    \"Stripe Authorization already exists for this event\")\n\n    def after_create_object(self, stripe_authorization, data, view_kwargs):\n        \"\"\"\n        after create object method for StripeAuthorizationListPost Class\n        :param stripe_authorization: Stripe authorization created from mashmallow_jsonapi\n        :param data:\n        :param view_kwargs:\n        :return:\n        \"\"\"\n        event = db.session.query(Event).filter_by(id=int(data['event'])).one()\n        event.is_stripe_linked = True\n        save_to_db(event)\n\n    schema = StripeAuthorizationSchema\n    decorators = (jwt_required, )\n    methods = ['POST']\n    data_layer = {'session': db.session,\n                  'model': StripeAuthorization,\n                  'methods': {\n                      'before_create_object': before_create_object,\n                      'after_create_object': after_create_object\n                  }}\n\n\nclass StripeAuthorizationDetail(ResourceDetail):\n    \"\"\"\n    Stripe Authorization Detail Resource by ID\n    \"\"\"\n    def before_get_object(self, view_kwargs):\n        \"\"\"\n        method to get id of stripe authorization related to an event\n        :param view_kwargs:\n        :return:\n        \"\"\"\n        if view_kwargs.get('event_identifier'):\n            event = safe_query(self, Event, 'identifier', view_kwargs['event_identifier'], 'event_identifier')\n            view_kwargs['event_id'] = event.id\n\n        if view_kwargs.get('event_id'):\n            stripe_authorization = \\\n                safe_query(self, StripeAuthorization, 'event_id', view_kwargs['event_id'], 'event_id')\n            view_kwargs['id'] = stripe_authorization.id\n\n    def after_delete_object(self, stripe_authorization, view_kwargs):\n        \"\"\"Make work after delete object\n        :param stripe_authorization: stripe authorization.\n        :param dict view_kwargs: kwargs from the resource view\n        \"\"\"\n        event = stripe_authorization.event\n        event.is_stripe_linked = False\n        save_to_db(event)\n\n    decorators = (api.has_permission('is_coorganizer', fetch=\"event_id\",\n                                     fetch_as=\"event_id\", model=StripeAuthorization),)\n    schema = StripeAuthorizationSchema\n    data_layer = {'session': db.session,\n                  'model': StripeAuthorization,\n                  'methods': {\n                      'before_get_object': before_get_object,\n                      'after_delete_object': after_delete_object\n                  }}\n\n\nclass StripeAuthorizationRelationship(ResourceDetail):\n    \"\"\"\n    Stripe Authorization Relationship\n    \"\"\"\n\n    decorators = (api.has_permission('is_coorganizer', fetch=\"event_id\",\n                                     fetch_as=\"event_id\", model=StripeAuthorization),)\n    schema = StripeAuthorizationSchema\n    data_layer = {'session': db.session,\n                  'model': StripeAuthorization}\n", "path": "app/api/stripe_authorization.py"}]}