We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
key error in POST ticket
**Describe the bug**
<!-- A clear and concise description of what the bug is. -->
The server returns HTTP 500 when posting Tickets. 

Request:
```
{
  "data": {
    "relationships": {
      "event": {
        "data": {
          "type": "event",
          "id": "{{event}}"
        }
      }
    },
    "attributes": {
      "name": "test ticket for demo",
      "description": "some description",
      "type": "VIP-ticket",
      "price": "1.00",
      "quantity": "15",
      "is-description-visible": "false",
      "position": "1",
      "is-fee-absorbed": "false",
      "sales-starts-at": "2018-06-01T01:24:47.500127+00:00",
      "sales-ends-at": "2018-06-30T00:24:47.500127+00:00",
      "is-hidden": "true",
      "min-order": "1",
      "max-order": "1"
    },
    "type": "ticket"
  }
}
```


**Stacktrace**
```
Traceback (most recent call last):
  File "/home/srv_twry/anaconda3/envs/open-event-server/lib/python3.6/site-packages/flask/app.py", line 2309, in __call__
    return self.wsgi_app(environ, start_response)
  File "/media/srv_twry/work/Projects/Community-Projects/Fossasia/open-event-server/app/__init__.py", line 66, in __call__
    return self.app(environ, start_response)
  File "/home/srv_twry/anaconda3/envs/open-event-server/lib/python3.6/site-packages/flask/app.py", line 2295, in wsgi_app
    response = self.handle_exception(e)
  File "/home/srv_twry/anaconda3/envs/open-event-server/lib/python3.6/site-packages/flask_cors/extension.py", line 161, in wrapped_function
    return cors_after_request(app.make_response(f(*args, **kwargs)))
  File "/home/srv_twry/anaconda3/envs/open-event-server/lib/python3.6/site-packages/flask_cors/extension.py", line 161, in wrapped_function
    return cors_after_request(app.make_response(f(*args, **kwargs)))
  File "/home/srv_twry/anaconda3/envs/open-event-server/lib/python3.6/site-packages/flask/app.py", line 1741, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "/home/srv_twry/anaconda3/envs/open-event-server/lib/python3.6/site-packages/flask/_compat.py", line 35, in reraise
    raise value
  File "/home/srv_twry/anaconda3/envs/open-event-server/lib/python3.6/site-packages/flask/app.py", line 2292, in wsgi_app
    response = self.full_dispatch_request()
  File "/home/srv_twry/anaconda3/envs/open-event-server/lib/python3.6/site-packages/flask/app.py", line 1815, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/home/srv_twry/anaconda3/envs/open-event-server/lib/python3.6/site-packages/flask_cors/extension.py", line 161, in wrapped_function
    return cors_after_request(app.make_response(f(*args, **kwargs)))
  File "/home/srv_twry/anaconda3/envs/open-event-server/lib/python3.6/site-packages/flask_cors/extension.py", line 161, in wrapped_function
    return cors_after_request(app.make_response(f(*args, **kwargs)))
  File "/home/srv_twry/anaconda3/envs/open-event-server/lib/python3.6/site-packages/flask/app.py", line 1718, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "/home/srv_twry/anaconda3/envs/open-event-server/lib/python3.6/site-packages/flask/_compat.py", line 35, in reraise
    raise value
  File "/home/srv_twry/anaconda3/envs/open-event-server/lib/python3.6/site-packages/flask/app.py", line 1813, in full_dispatch_request
    rv = self.dispatch_request()
  File "/home/srv_twry/anaconda3/envs/open-event-server/lib/python3.6/site-packages/flask/app.py", line 1799, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "/media/srv_twry/work/Projects/Community-Projects/Fossasia/open-event-server/src/flask-rest-jsonapi/flask_rest_jsonapi/decorators.py", line 32, in wrapper
    return func(*args, **kwargs)
  File "/home/srv_twry/anaconda3/envs/open-event-server/lib/python3.6/site-packages/flask/views.py", line 88, in view
    return self.dispatch_request(*args, **kwargs)
  File "/media/srv_twry/work/Projects/Community-Projects/Fossasia/open-event-server/src/flask-rest-jsonapi/flask_rest_jsonapi/resource.py", line 68, in dispatch_request
    response = method(*args, **kwargs)
  File "/media/srv_twry/work/Projects/Community-Projects/Fossasia/open-event-server/src/flask-rest-jsonapi/flask_rest_jsonapi/decorators.py", line 56, in wrapper
    return func(*args, **kwargs)
  File "/media/srv_twry/work/Projects/Community-Projects/Fossasia/open-event-server/src/flask-rest-jsonapi/flask_rest_jsonapi/resource.py", line 202, in post
    self.before_post(args, kwargs, data=data)
  File "/media/srv_twry/work/Projects/Community-Projects/Fossasia/open-event-server/app/api/tickets.py", line 37, in before_post
    "Event: {} not found".format(data['event_id']))
KeyError: 'event_id'
```

--- 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/tickets.py`
Content:
```
1 from flask import request, current_app
2 from flask_rest_jsonapi import ResourceDetail, ResourceList, ResourceRelationship
3 from flask_rest_jsonapi.exceptions import ObjectNotFound
4 from flask_jwt import current_identity as current_user, _jwt_required
5 
6 from app.api.bootstrap import api
7 from app.api.helpers.db import safe_query
8 from app.api.helpers.permission_manager import has_access
9 from app.api.helpers.query import event_query
10 from app.api.helpers.utilities import require_relationship
11 from app.api.schema.tickets import TicketSchema, TicketSchemaPublic
12 from app.models import db
13 from app.models.access_code import AccessCode
14 from app.models.order import Order
15 from app.models.ticket import Ticket, TicketTag, ticket_tags_table
16 from app.models.event import Event
17 from app.models.ticket_holder import TicketHolder
18 from app.api.helpers.exceptions import ConflictException, MethodNotAllowed
19 from app.api.helpers.db import get_count
20 
21 
22 class TicketListPost(ResourceList):
23     """
24     Create and List Tickets
25     """
26     def before_post(self, args, kwargs, data):
27         """
28         before post method to check for required relationship and proper permission
29         :param args:
30         :param kwargs:
31         :param data:
32         :return:
33         """
34         require_relationship(['event'], data)
35         if not has_access('is_coorganizer', event_id=data['event']):
36             raise ObjectNotFound({'parameter': 'event_id'},
37                                  "Event: {} not found".format(data['event_id']))
38 
39         if get_count(db.session.query(Ticket.id).filter_by(name=data['name'], event_id=int(data['event']),
40                                                            deleted_at=None)) > 0:
41             raise ConflictException({'pointer': '/data/attributes/name'}, "Ticket already exists")
42 
43         if get_count(db.session.query(Event).filter_by(id=int(data['event']), is_ticketing_enabled=False)) > 0:
44             raise MethodNotAllowed({'parameter': 'event_id'}, "Ticketing is disabled for this Event")
45 
46     schema = TicketSchema
47     methods = ['POST', ]
48     data_layer = {'session': db.session,
49                   'model': Ticket}
50 
51 
52 class TicketList(ResourceList):
53     """
54     List Tickets based on different params
55     """
56     def before_get(self, args, view_kwargs):
57         """
58         before get method to get the resource id for assigning schema
59         :param args:
60         :param view_kwargs:
61         :return:
62         """
63         if view_kwargs.get('ticket_tag_id') or view_kwargs.get('access_code_id') or view_kwargs.get('order_identifier'):
64             self.schema = TicketSchemaPublic
65 
66     def query(self, view_kwargs):
67         """
68         query method for resource list
69         :param view_kwargs:
70         :return:
71         """
72 
73         if 'Authorization' in request.headers:
74             _jwt_required(current_app.config['JWT_DEFAULT_REALM'])
75             if current_user.is_super_admin or current_user.is_admin:
76                 query_ = self.session.query(Ticket)
77             elif view_kwargs.get('event_id') and has_access('is_organizer', event_id=view_kwargs['event_id']):
78                 query_ = self.session.query(Ticket)
79             else:
80                 query_ = self.session.query(Ticket).filter_by(is_hidden=False)
81         else:
82             query_ = self.session.query(Ticket).filter_by(is_hidden=False)
83 
84         if view_kwargs.get('ticket_tag_id'):
85             ticket_tag = safe_query(self, TicketTag, 'id', view_kwargs['ticket_tag_id'], 'ticket_tag_id')
86             query_ = query_.join(ticket_tags_table).filter_by(ticket_tag_id=ticket_tag.id)
87         query_ = event_query(self, query_, view_kwargs)
88         if view_kwargs.get('access_code_id'):
89             access_code = safe_query(self, AccessCode, 'id', view_kwargs['access_code_id'], 'access_code_id')
90             # access_code - ticket :: many-to-many relationship
91             query_ = Ticket.query.filter(Ticket.access_codes.any(id=access_code.id))
92 
93         if view_kwargs.get('order_identifier'):
94             order = safe_query(self, Order, 'identifier', view_kwargs['order_identifier'], 'order_identifier')
95             ticket_ids = []
96             for ticket in order.tickets:
97                 ticket_ids.append(ticket.id)
98             query_ = query_.filter(Ticket.id.in_(tuple(ticket_ids)))
99 
100         return query_
101 
102     view_kwargs = True
103     methods = ['GET', ]
104     decorators = (api.has_permission('is_coorganizer', fetch='event_id',
105                   fetch_as="event_id", model=Ticket, methods="POST",
106                   check=lambda a: a.get('event_id') or a.get('event_identifier')),)
107     schema = TicketSchema
108     data_layer = {'session': db.session,
109                   'model': Ticket,
110                   'methods': {
111                       'query': query,
112                   }}
113 
114 
115 class TicketDetail(ResourceDetail):
116     """
117     Ticket Resource
118     """
119     def before_get(self, args, view_kwargs):
120         """
121         before get method to get the resource id for assigning schema
122         :param args:
123         :param view_kwargs:
124         :return:
125         """
126         if view_kwargs.get('attendee_id'):
127             self.schema = TicketSchemaPublic
128 
129     def before_get_object(self, view_kwargs):
130         """
131         before get object method to get the resource id for fetching details
132         :param view_kwargs:
133         :return:
134         """
135         if view_kwargs.get('attendee_id') is not None:
136             attendee = safe_query(self, TicketHolder, 'id', view_kwargs['attendee_id'], 'attendee_id')
137             if attendee.ticket_id is not None:
138                 view_kwargs['id'] = attendee.ticket_id
139             else:
140                 view_kwargs['id'] = None
141 
142     decorators = (api.has_permission('is_coorganizer', fetch='event_id',
143                   fetch_as="event_id", model=Ticket, methods="PATCH,DELETE"),)
144     schema = TicketSchema
145     data_layer = {'session': db.session,
146                   'model': Ticket,
147                   'methods': {
148                       'before_get_object': before_get_object
149                   }}
150 
151 
152 class TicketRelationshipRequired(ResourceRelationship):
153     """
154     Tickets Relationship (Required)
155     """
156     decorators = (api.has_permission('is_coorganizer', fetch='event_id',
157                                      fetch_as="event_id", model=Ticket, methods="PATCH"),)
158     methods = ['GET', 'PATCH']
159     schema = TicketSchema
160     data_layer = {'session': db.session,
161                   'model': Ticket}
162 
163 
164 class TicketRelationshipOptional(ResourceRelationship):
165     """
166     Tickets Relationship (Optional)
167     """
168     decorators = (api.has_permission('is_coorganizer', fetch='event_id',
169                                      fetch_as="event_id", model=Ticket, methods="PATCH,DELETE"),)
170     schema = TicketSchema
171     data_layer = {'session': db.session,
172                   'model': Ticket}
173
```
--- 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()

```

diff --git a/app/api/tickets.py b/app/api/tickets.py
--- a/app/api/tickets.py
+++ b/app/api/tickets.py
@@ -18,7 +18,6 @@
 from app.api.helpers.exceptions import ConflictException, MethodNotAllowed
 from app.api.helpers.db import get_count
 
-
 class TicketListPost(ResourceList):
     """
     Create and List Tickets
@@ -34,7 +33,7 @@
         require_relationship(['event'], data)
         if not has_access('is_coorganizer', event_id=data['event']):
             raise ObjectNotFound({'parameter': 'event_id'},
-                                 "Event: {} not found".format(data['event_id']))
+                                 "Event: {} not found".format(data['event']))
 
         if get_count(db.session.query(Ticket.id).filter_by(name=data['name'], event_id=int(data['event']),
                                                            deleted_at=None)) > 0:

{"golden_diff": "diff --git a/app/api/tickets.py b/app/api/tickets.py\n--- a/app/api/tickets.py\n+++ b/app/api/tickets.py\n@@ -18,7 +18,6 @@\n from app.api.helpers.exceptions import ConflictException, MethodNotAllowed\n from app.api.helpers.db import get_count\n \n-\n class TicketListPost(ResourceList):\n     \"\"\"\n     Create and List Tickets\n@@ -34,7 +33,7 @@\n         require_relationship(['event'], data)\n         if not has_access('is_coorganizer', event_id=data['event']):\n             raise ObjectNotFound({'parameter': 'event_id'},\n-                                 \"Event: {} not found\".format(data['event_id']))\n+                                 \"Event: {} not found\".format(data['event']))\n \n         if get_count(db.session.query(Ticket.id).filter_by(name=data['name'], event_id=int(data['event']),\n                                                            deleted_at=None)) > 0:\n", "issue": "key error in POST ticket\n**Describe the bug**\r\n<!-- A clear and concise description of what the bug is. -->\r\nThe server returns HTTP 500 when posting Tickets. \r\n\r\nRequest:\r\n```\r\n{\r\n  \"data\": {\r\n    \"relationships\": {\r\n      \"event\": {\r\n        \"data\": {\r\n          \"type\": \"event\",\r\n          \"id\": \"{{event}}\"\r\n        }\r\n      }\r\n    },\r\n    \"attributes\": {\r\n      \"name\": \"test ticket for demo\",\r\n      \"description\": \"some description\",\r\n      \"type\": \"VIP-ticket\",\r\n      \"price\": \"1.00\",\r\n      \"quantity\": \"15\",\r\n      \"is-description-visible\": \"false\",\r\n      \"position\": \"1\",\r\n      \"is-fee-absorbed\": \"false\",\r\n      \"sales-starts-at\": \"2018-06-01T01:24:47.500127+00:00\",\r\n      \"sales-ends-at\": \"2018-06-30T00:24:47.500127+00:00\",\r\n      \"is-hidden\": \"true\",\r\n      \"min-order\": \"1\",\r\n      \"max-order\": \"1\"\r\n    },\r\n    \"type\": \"ticket\"\r\n  }\r\n}\r\n```\r\n\r\n\r\n**Stacktrace**\r\n```\r\nTraceback (most recent call last):\r\n  File \"/home/srv_twry/anaconda3/envs/open-event-server/lib/python3.6/site-packages/flask/app.py\", line 2309, in __call__\r\n    return self.wsgi_app(environ, start_response)\r\n  File \"/media/srv_twry/work/Projects/Community-Projects/Fossasia/open-event-server/app/__init__.py\", line 66, in __call__\r\n    return self.app(environ, start_response)\r\n  File \"/home/srv_twry/anaconda3/envs/open-event-server/lib/python3.6/site-packages/flask/app.py\", line 2295, in wsgi_app\r\n    response = self.handle_exception(e)\r\n  File \"/home/srv_twry/anaconda3/envs/open-event-server/lib/python3.6/site-packages/flask_cors/extension.py\", line 161, in wrapped_function\r\n    return cors_after_request(app.make_response(f(*args, **kwargs)))\r\n  File \"/home/srv_twry/anaconda3/envs/open-event-server/lib/python3.6/site-packages/flask_cors/extension.py\", line 161, in wrapped_function\r\n    return cors_after_request(app.make_response(f(*args, **kwargs)))\r\n  File \"/home/srv_twry/anaconda3/envs/open-event-server/lib/python3.6/site-packages/flask/app.py\", line 1741, in handle_exception\r\n    reraise(exc_type, exc_value, tb)\r\n  File \"/home/srv_twry/anaconda3/envs/open-event-server/lib/python3.6/site-packages/flask/_compat.py\", line 35, in reraise\r\n    raise value\r\n  File \"/home/srv_twry/anaconda3/envs/open-event-server/lib/python3.6/site-packages/flask/app.py\", line 2292, in wsgi_app\r\n    response = self.full_dispatch_request()\r\n  File \"/home/srv_twry/anaconda3/envs/open-event-server/lib/python3.6/site-packages/flask/app.py\", line 1815, in full_dispatch_request\r\n    rv = self.handle_user_exception(e)\r\n  File \"/home/srv_twry/anaconda3/envs/open-event-server/lib/python3.6/site-packages/flask_cors/extension.py\", line 161, in wrapped_function\r\n    return cors_after_request(app.make_response(f(*args, **kwargs)))\r\n  File \"/home/srv_twry/anaconda3/envs/open-event-server/lib/python3.6/site-packages/flask_cors/extension.py\", line 161, in wrapped_function\r\n    return cors_after_request(app.make_response(f(*args, **kwargs)))\r\n  File \"/home/srv_twry/anaconda3/envs/open-event-server/lib/python3.6/site-packages/flask/app.py\", line 1718, in handle_user_exception\r\n    reraise(exc_type, exc_value, tb)\r\n  File \"/home/srv_twry/anaconda3/envs/open-event-server/lib/python3.6/site-packages/flask/_compat.py\", line 35, in reraise\r\n    raise value\r\n  File \"/home/srv_twry/anaconda3/envs/open-event-server/lib/python3.6/site-packages/flask/app.py\", line 1813, in full_dispatch_request\r\n    rv = self.dispatch_request()\r\n  File \"/home/srv_twry/anaconda3/envs/open-event-server/lib/python3.6/site-packages/flask/app.py\", line 1799, in dispatch_request\r\n    return self.view_functions[rule.endpoint](**req.view_args)\r\n  File \"/media/srv_twry/work/Projects/Community-Projects/Fossasia/open-event-server/src/flask-rest-jsonapi/flask_rest_jsonapi/decorators.py\", line 32, in wrapper\r\n    return func(*args, **kwargs)\r\n  File \"/home/srv_twry/anaconda3/envs/open-event-server/lib/python3.6/site-packages/flask/views.py\", line 88, in view\r\n    return self.dispatch_request(*args, **kwargs)\r\n  File \"/media/srv_twry/work/Projects/Community-Projects/Fossasia/open-event-server/src/flask-rest-jsonapi/flask_rest_jsonapi/resource.py\", line 68, in dispatch_request\r\n    response = method(*args, **kwargs)\r\n  File \"/media/srv_twry/work/Projects/Community-Projects/Fossasia/open-event-server/src/flask-rest-jsonapi/flask_rest_jsonapi/decorators.py\", line 56, in wrapper\r\n    return func(*args, **kwargs)\r\n  File \"/media/srv_twry/work/Projects/Community-Projects/Fossasia/open-event-server/src/flask-rest-jsonapi/flask_rest_jsonapi/resource.py\", line 202, in post\r\n    self.before_post(args, kwargs, data=data)\r\n  File \"/media/srv_twry/work/Projects/Community-Projects/Fossasia/open-event-server/app/api/tickets.py\", line 37, in before_post\r\n    \"Event: {} not found\".format(data['event_id']))\r\nKeyError: 'event_id'\r\n```\n", "before_files": [{"content": "from flask import request, current_app\nfrom flask_rest_jsonapi import ResourceDetail, ResourceList, ResourceRelationship\nfrom flask_rest_jsonapi.exceptions import ObjectNotFound\nfrom flask_jwt import current_identity as current_user, _jwt_required\n\nfrom app.api.bootstrap import api\nfrom app.api.helpers.db import safe_query\nfrom app.api.helpers.permission_manager import has_access\nfrom app.api.helpers.query import event_query\nfrom app.api.helpers.utilities import require_relationship\nfrom app.api.schema.tickets import TicketSchema, TicketSchemaPublic\nfrom app.models import db\nfrom app.models.access_code import AccessCode\nfrom app.models.order import Order\nfrom app.models.ticket import Ticket, TicketTag, ticket_tags_table\nfrom app.models.event import Event\nfrom app.models.ticket_holder import TicketHolder\nfrom app.api.helpers.exceptions import ConflictException, MethodNotAllowed\nfrom app.api.helpers.db import get_count\n\n\nclass TicketListPost(ResourceList):\n    \"\"\"\n    Create and List Tickets\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_coorganizer', event_id=data['event']):\n            raise ObjectNotFound({'parameter': 'event_id'},\n                                 \"Event: {} not found\".format(data['event_id']))\n\n        if get_count(db.session.query(Ticket.id).filter_by(name=data['name'], event_id=int(data['event']),\n                                                           deleted_at=None)) > 0:\n            raise ConflictException({'pointer': '/data/attributes/name'}, \"Ticket already exists\")\n\n        if get_count(db.session.query(Event).filter_by(id=int(data['event']), is_ticketing_enabled=False)) > 0:\n            raise MethodNotAllowed({'parameter': 'event_id'}, \"Ticketing is disabled for this Event\")\n\n    schema = TicketSchema\n    methods = ['POST', ]\n    data_layer = {'session': db.session,\n                  'model': Ticket}\n\n\nclass TicketList(ResourceList):\n    \"\"\"\n    List Tickets based on different params\n    \"\"\"\n    def before_get(self, args, view_kwargs):\n        \"\"\"\n        before get method to get the resource id for assigning schema\n        :param args:\n        :param view_kwargs:\n        :return:\n        \"\"\"\n        if view_kwargs.get('ticket_tag_id') or view_kwargs.get('access_code_id') or view_kwargs.get('order_identifier'):\n            self.schema = TicketSchemaPublic\n\n    def query(self, view_kwargs):\n        \"\"\"\n        query method for resource list\n        :param view_kwargs:\n        :return:\n        \"\"\"\n\n        if 'Authorization' in request.headers:\n            _jwt_required(current_app.config['JWT_DEFAULT_REALM'])\n            if current_user.is_super_admin or current_user.is_admin:\n                query_ = self.session.query(Ticket)\n            elif view_kwargs.get('event_id') and has_access('is_organizer', event_id=view_kwargs['event_id']):\n                query_ = self.session.query(Ticket)\n            else:\n                query_ = self.session.query(Ticket).filter_by(is_hidden=False)\n        else:\n            query_ = self.session.query(Ticket).filter_by(is_hidden=False)\n\n        if view_kwargs.get('ticket_tag_id'):\n            ticket_tag = safe_query(self, TicketTag, 'id', view_kwargs['ticket_tag_id'], 'ticket_tag_id')\n            query_ = query_.join(ticket_tags_table).filter_by(ticket_tag_id=ticket_tag.id)\n        query_ = event_query(self, query_, view_kwargs)\n        if view_kwargs.get('access_code_id'):\n            access_code = safe_query(self, AccessCode, 'id', view_kwargs['access_code_id'], 'access_code_id')\n            # access_code - ticket :: many-to-many relationship\n            query_ = Ticket.query.filter(Ticket.access_codes.any(id=access_code.id))\n\n        if view_kwargs.get('order_identifier'):\n            order = safe_query(self, Order, 'identifier', view_kwargs['order_identifier'], 'order_identifier')\n            ticket_ids = []\n            for ticket in order.tickets:\n                ticket_ids.append(ticket.id)\n            query_ = query_.filter(Ticket.id.in_(tuple(ticket_ids)))\n\n        return query_\n\n    view_kwargs = True\n    methods = ['GET', ]\n    decorators = (api.has_permission('is_coorganizer', fetch='event_id',\n                  fetch_as=\"event_id\", model=Ticket, methods=\"POST\",\n                  check=lambda a: a.get('event_id') or a.get('event_identifier')),)\n    schema = TicketSchema\n    data_layer = {'session': db.session,\n                  'model': Ticket,\n                  'methods': {\n                      'query': query,\n                  }}\n\n\nclass TicketDetail(ResourceDetail):\n    \"\"\"\n    Ticket Resource\n    \"\"\"\n    def before_get(self, args, view_kwargs):\n        \"\"\"\n        before get method to get the resource id for assigning schema\n        :param args:\n        :param view_kwargs:\n        :return:\n        \"\"\"\n        if view_kwargs.get('attendee_id'):\n            self.schema = TicketSchemaPublic\n\n    def before_get_object(self, view_kwargs):\n        \"\"\"\n        before get object method to get the resource id for fetching details\n        :param view_kwargs:\n        :return:\n        \"\"\"\n        if view_kwargs.get('attendee_id') is not None:\n            attendee = safe_query(self, TicketHolder, 'id', view_kwargs['attendee_id'], 'attendee_id')\n            if attendee.ticket_id is not None:\n                view_kwargs['id'] = attendee.ticket_id\n            else:\n                view_kwargs['id'] = None\n\n    decorators = (api.has_permission('is_coorganizer', fetch='event_id',\n                  fetch_as=\"event_id\", model=Ticket, methods=\"PATCH,DELETE\"),)\n    schema = TicketSchema\n    data_layer = {'session': db.session,\n                  'model': Ticket,\n                  'methods': {\n                      'before_get_object': before_get_object\n                  }}\n\n\nclass TicketRelationshipRequired(ResourceRelationship):\n    \"\"\"\n    Tickets Relationship (Required)\n    \"\"\"\n    decorators = (api.has_permission('is_coorganizer', fetch='event_id',\n                                     fetch_as=\"event_id\", model=Ticket, methods=\"PATCH\"),)\n    methods = ['GET', 'PATCH']\n    schema = TicketSchema\n    data_layer = {'session': db.session,\n                  'model': Ticket}\n\n\nclass TicketRelationshipOptional(ResourceRelationship):\n    \"\"\"\n    Tickets Relationship (Optional)\n    \"\"\"\n    decorators = (api.has_permission('is_coorganizer', fetch='event_id',\n                                     fetch_as=\"event_id\", model=Ticket, methods=\"PATCH,DELETE\"),)\n    schema = TicketSchema\n    data_layer = {'session': db.session,\n                  'model': Ticket}\n", "path": "app/api/tickets.py"}], "after_files": [{"content": "from flask import request, current_app\nfrom flask_rest_jsonapi import ResourceDetail, ResourceList, ResourceRelationship\nfrom flask_rest_jsonapi.exceptions import ObjectNotFound\nfrom flask_jwt import current_identity as current_user, _jwt_required\n\nfrom app.api.bootstrap import api\nfrom app.api.helpers.db import safe_query\nfrom app.api.helpers.permission_manager import has_access\nfrom app.api.helpers.query import event_query\nfrom app.api.helpers.utilities import require_relationship\nfrom app.api.schema.tickets import TicketSchema, TicketSchemaPublic\nfrom app.models import db\nfrom app.models.access_code import AccessCode\nfrom app.models.order import Order\nfrom app.models.ticket import Ticket, TicketTag, ticket_tags_table\nfrom app.models.event import Event\nfrom app.models.ticket_holder import TicketHolder\nfrom app.api.helpers.exceptions import ConflictException, MethodNotAllowed\nfrom app.api.helpers.db import get_count\n\nclass TicketListPost(ResourceList):\n    \"\"\"\n    Create and List Tickets\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_coorganizer', event_id=data['event']):\n            raise ObjectNotFound({'parameter': 'event_id'},\n                                 \"Event: {} not found\".format(data['event']))\n\n        if get_count(db.session.query(Ticket.id).filter_by(name=data['name'], event_id=int(data['event']),\n                                                           deleted_at=None)) > 0:\n            raise ConflictException({'pointer': '/data/attributes/name'}, \"Ticket already exists\")\n\n        if get_count(db.session.query(Event).filter_by(id=int(data['event']), is_ticketing_enabled=False)) > 0:\n            raise MethodNotAllowed({'parameter': 'event_id'}, \"Ticketing is disabled for this Event\")\n\n    schema = TicketSchema\n    methods = ['POST', ]\n    data_layer = {'session': db.session,\n                  'model': Ticket}\n\n\nclass TicketList(ResourceList):\n    \"\"\"\n    List Tickets based on different params\n    \"\"\"\n    def before_get(self, args, view_kwargs):\n        \"\"\"\n        before get method to get the resource id for assigning schema\n        :param args:\n        :param view_kwargs:\n        :return:\n        \"\"\"\n        if view_kwargs.get('ticket_tag_id') or view_kwargs.get('access_code_id') or view_kwargs.get('order_identifier'):\n            self.schema = TicketSchemaPublic\n\n    def query(self, view_kwargs):\n        \"\"\"\n        query method for resource list\n        :param view_kwargs:\n        :return:\n        \"\"\"\n\n        if 'Authorization' in request.headers:\n            _jwt_required(current_app.config['JWT_DEFAULT_REALM'])\n            if current_user.is_super_admin or current_user.is_admin:\n                query_ = self.session.query(Ticket)\n            elif view_kwargs.get('event_id') and has_access('is_organizer', event_id=view_kwargs['event_id']):\n                query_ = self.session.query(Ticket)\n            else:\n                query_ = self.session.query(Ticket).filter_by(is_hidden=False)\n        else:\n            query_ = self.session.query(Ticket).filter_by(is_hidden=False)\n\n        if view_kwargs.get('ticket_tag_id'):\n            ticket_tag = safe_query(self, TicketTag, 'id', view_kwargs['ticket_tag_id'], 'ticket_tag_id')\n            query_ = query_.join(ticket_tags_table).filter_by(ticket_tag_id=ticket_tag.id)\n        query_ = event_query(self, query_, view_kwargs)\n        if view_kwargs.get('access_code_id'):\n            access_code = safe_query(self, AccessCode, 'id', view_kwargs['access_code_id'], 'access_code_id')\n            # access_code - ticket :: many-to-many relationship\n            query_ = Ticket.query.filter(Ticket.access_codes.any(id=access_code.id))\n\n        if view_kwargs.get('order_identifier'):\n            order = safe_query(self, Order, 'identifier', view_kwargs['order_identifier'], 'order_identifier')\n            ticket_ids = []\n            for ticket in order.tickets:\n                ticket_ids.append(ticket.id)\n            query_ = query_.filter(Ticket.id.in_(tuple(ticket_ids)))\n\n        return query_\n\n    view_kwargs = True\n    methods = ['GET', ]\n    decorators = (api.has_permission('is_coorganizer', fetch='event_id',\n                  fetch_as=\"event_id\", model=Ticket, methods=\"POST\",\n                  check=lambda a: a.get('event_id') or a.get('event_identifier')),)\n    schema = TicketSchema\n    data_layer = {'session': db.session,\n                  'model': Ticket,\n                  'methods': {\n                      'query': query,\n                  }}\n\n\nclass TicketDetail(ResourceDetail):\n    \"\"\"\n    Ticket Resource\n    \"\"\"\n    def before_get(self, args, view_kwargs):\n        \"\"\"\n        before get method to get the resource id for assigning schema\n        :param args:\n        :param view_kwargs:\n        :return:\n        \"\"\"\n        if view_kwargs.get('attendee_id'):\n            self.schema = TicketSchemaPublic\n\n    def before_get_object(self, view_kwargs):\n        \"\"\"\n        before get object method to get the resource id for fetching details\n        :param view_kwargs:\n        :return:\n        \"\"\"\n        if view_kwargs.get('attendee_id') is not None:\n            attendee = safe_query(self, TicketHolder, 'id', view_kwargs['attendee_id'], 'attendee_id')\n            if attendee.ticket_id is not None:\n                view_kwargs['id'] = attendee.ticket_id\n            else:\n                view_kwargs['id'] = None\n\n    decorators = (api.has_permission('is_coorganizer', fetch='event_id',\n                  fetch_as=\"event_id\", model=Ticket, methods=\"PATCH,DELETE\"),)\n    schema = TicketSchema\n    data_layer = {'session': db.session,\n                  'model': Ticket,\n                  'methods': {\n                      'before_get_object': before_get_object\n                  }}\n\n\nclass TicketRelationshipRequired(ResourceRelationship):\n    \"\"\"\n    Tickets Relationship (Required)\n    \"\"\"\n    decorators = (api.has_permission('is_coorganizer', fetch='event_id',\n                                     fetch_as=\"event_id\", model=Ticket, methods=\"PATCH\"),)\n    methods = ['GET', 'PATCH']\n    schema = TicketSchema\n    data_layer = {'session': db.session,\n                  'model': Ticket}\n\n\nclass TicketRelationshipOptional(ResourceRelationship):\n    \"\"\"\n    Tickets Relationship (Optional)\n    \"\"\"\n    decorators = (api.has_permission('is_coorganizer', fetch='event_id',\n                                     fetch_as=\"event_id\", model=Ticket, methods=\"PATCH,DELETE\"),)\n    schema = TicketSchema\n    data_layer = {'session': db.session,\n                  'model': Ticket}\n", "path": "app/api/tickets.py"}]}