prompt: We are currently solving the following issue within our repository. Here is the issue text:
  --- BEGIN ISSUE ---
  Internal Server Error thrown for patching a nonexistent session
  **Describe the bug**
  <!-- A clear and concise description of what the bug is. -->
  HTTP 500 error is thrown when a patch request is sent for a session which doesn't exist.
  
  **To Reproduce**
  Steps to reproduce the behavior:
  1. Send a patch request for a session which doesn't exist
  
  **Expected behavior**
  <!-- A clear and concise description of what you expected to happen. -->
  A proper error should be sent.
  
  Working on fixing this.
  
  --- 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/schema/sessions.py`
  Content:
  ```
  1 from marshmallow import validates_schema, validate
  2 from marshmallow_jsonapi import fields
  3 from marshmallow_jsonapi.flask import Relationship
  4 
  5 from app.api.helpers.exceptions import UnprocessableEntity, ForbiddenException
  6 from app.api.helpers.permission_manager import has_access
  7 from app.api.helpers.utilities import dasherize
  8 from app.api.schema.base import SoftDeletionSchema
  9 from app.models.session import Session
  10 from utils.common import use_defaults
  11 
  12 
  13 @use_defaults()
  14 class SessionSchema(SoftDeletionSchema):
  15     """
  16     Api schema for Session Model
  17     """
  18 
  19     class Meta:
  20         """
  21         Meta class for Session Api Schema
  22         """
  23         type_ = 'session'
  24         self_view = 'v1.session_detail'
  25         self_view_kwargs = {'id': '<id>'}
  26         inflect = dasherize
  27 
  28     @validates_schema(pass_original=True)
  29     def validate_date(self, data, original_data):
  30         if 'id' in original_data['data']:
  31             session = Session.query.filter_by(id=original_data['data']['id']).one()
  32 
  33             if 'starts_at' not in data:
  34                 data['starts_at'] = session.starts_at
  35 
  36             if 'ends_at' not in data:
  37                 data['ends_at'] = session.ends_at
  38 
  39             if 'event' not in data:
  40                 data['event'] = session.event_id
  41 
  42         if data['starts_at'] and data['ends_at']:
  43             if data['starts_at'] >= data['ends_at']:
  44                 raise UnprocessableEntity(
  45                     {'pointer': '/data/attributes/ends-at'}, "ends-at should be after starts-at")
  46 
  47         if 'state' in data:
  48             if data['state'] is not 'draft' or not 'pending':
  49                 if not has_access('is_coorganizer', event_id=data['event']):
  50                     return ForbiddenException({'source': ''}, 'Co-organizer access is required.')
  51 
  52         if 'track' in data:
  53             if not has_access('is_coorganizer', event_id=data['event']):
  54                 return ForbiddenException({'source': ''}, 'Co-organizer access is required.')
  55 
  56         if 'microlocation' in data:
  57             if not has_access('is_coorganizer', event_id=data['event']):
  58                 return ForbiddenException({'source': ''}, 'Co-organizer access is required.')
  59 
  60     id = fields.Str(dump_only=True)
  61     title = fields.Str(required=True)
  62     subtitle = fields.Str(allow_none=True)
  63     level = fields.Int(allow_none=True)
  64     short_abstract = fields.Str(allow_none=True)
  65     long_abstract = fields.Str(allow_none=True)
  66     comments = fields.Str(allow_none=True)
  67     starts_at = fields.DateTime(allow_none=True)
  68     ends_at = fields.DateTime(allow_none=True)
  69     language = fields.Str(allow_none=True)
  70     slides_url = fields.Url(allow_none=True)
  71     video_url = fields.Url(allow_none=True)
  72     audio_url = fields.Url(allow_none=True)
  73     signup_url = fields.Url(allow_none=True)
  74     state = fields.Str(validate=validate.OneOf(choices=["pending", "accepted", "confirmed", "rejected", "draft"]),
  75                        allow_none=True, default='draft')
  76     created_at = fields.DateTime(dump_only=True)
  77     deleted_at = fields.DateTime(dump_only=True)
  78     submitted_at = fields.DateTime(allow_none=True)
  79     is_mail_sent = fields.Boolean()
  80     last_modified_at = fields.DateTime(dump_only=True)
  81     send_email = fields.Boolean(load_only=True, allow_none=True)
  82     average_rating = fields.Float(dump_only=True)
  83     microlocation = Relationship(attribute='microlocation',
  84                                  self_view='v1.session_microlocation',
  85                                  self_view_kwargs={'id': '<id>'},
  86                                  related_view='v1.microlocation_detail',
  87                                  related_view_kwargs={'session_id': '<id>'},
  88                                  schema='MicrolocationSchema',
  89                                  type_='microlocation')
  90     track = Relationship(attribute='track',
  91                          self_view='v1.session_track',
  92                          self_view_kwargs={'id': '<id>'},
  93                          related_view='v1.track_detail',
  94                          related_view_kwargs={'session_id': '<id>'},
  95                          schema='TrackSchema',
  96                          type_='track')
  97     session_type = Relationship(attribute='session_type',
  98                                 self_view='v1.session_session_type',
  99                                 self_view_kwargs={'id': '<id>'},
  100                                 related_view='v1.session_type_detail',
  101                                 related_view_kwargs={'session_id': '<id>'},
  102                                 schema='SessionTypeSchema',
  103                                 type_='session-type')
  104     event = Relationship(attribute='event',
  105                          self_view='v1.session_event',
  106                          self_view_kwargs={'id': '<id>'},
  107                          related_view='v1.event_detail',
  108                          related_view_kwargs={'session_id': '<id>'},
  109                          schema='EventSchemaPublic',
  110                          type_='event')
  111     feedbacks = Relationship(attribute='feedbacks',
  112                              self_view='v1.session_feedbacks',
  113                              self_view_kwargs={'id': '<id>'},
  114                              related_view='v1.feedback_list',
  115                              related_view_kwargs={'session_id': '<id>'},
  116                              schema='FeedbackSchema',
  117                              many=True,
  118                              type_='feedback')
  119     speakers = Relationship(attribute='speakers',
  120                             many=True,
  121                             self_view='v1.session_speaker',
  122                             self_view_kwargs={'id': '<id>'},
  123                             related_view='v1.speaker_list',
  124                             related_view_kwargs={'session_id': '<id>'},
  125                             schema='SpeakerSchema',
  126                             type_='speaker')
  127     creator = Relationship(attribute='user',
  128                            self_view='v1.session_user',
  129                            self_view_kwargs={'id': '<id>'},
  130                            related_view='v1.user_detail',
  131                            related_view_kwargs={'session_id': '<id>'},
  132                            schema='UserSchemaPublic',
  133                            type_='user')
  134
  ```
  --- 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/schema/sessions.py b/app/api/schema/sessions.py
  --- a/app/api/schema/sessions.py
  +++ b/app/api/schema/sessions.py
  @@ -1,6 +1,8 @@
  +from flask_rest_jsonapi.exceptions import ObjectNotFound
   from marshmallow import validates_schema, validate
   from marshmallow_jsonapi import fields
   from marshmallow_jsonapi.flask import Relationship
  +from sqlalchemy.orm.exc import NoResultFound
   
   from app.api.helpers.exceptions import UnprocessableEntity, ForbiddenException
   from app.api.helpers.permission_manager import has_access
  @@ -28,7 +30,10 @@
       @validates_schema(pass_original=True)
       def validate_date(self, data, original_data):
           if 'id' in original_data['data']:
  -            session = Session.query.filter_by(id=original_data['data']['id']).one()
  +            try:
  +                session = Session.query.filter_by(id=original_data['data']['id']).one()
  +            except NoResultFound:
  +                raise ObjectNotFound({'parameter': '{id}'}, "Session: not found")
   
               if 'starts_at' not in data:
                   data['starts_at'] = session.starts_at
  
verification_info: {"golden_diff": "diff --git a/app/api/schema/sessions.py b/app/api/schema/sessions.py\n--- a/app/api/schema/sessions.py\n+++ b/app/api/schema/sessions.py\n@@ -1,6 +1,8 @@\n+from flask_rest_jsonapi.exceptions import ObjectNotFound\n from marshmallow import validates_schema, validate\n from marshmallow_jsonapi import fields\n from marshmallow_jsonapi.flask import Relationship\n+from sqlalchemy.orm.exc import NoResultFound\n \n from app.api.helpers.exceptions import UnprocessableEntity, ForbiddenException\n from app.api.helpers.permission_manager import has_access\n@@ -28,7 +30,10 @@\n     @validates_schema(pass_original=True)\n     def validate_date(self, data, original_data):\n         if 'id' in original_data['data']:\n-            session = Session.query.filter_by(id=original_data['data']['id']).one()\n+            try:\n+                session = Session.query.filter_by(id=original_data['data']['id']).one()\n+            except NoResultFound:\n+                raise ObjectNotFound({'parameter': '{id}'}, \"Session: not found\")\n \n             if 'starts_at' not in data:\n                 data['starts_at'] = session.starts_at\n", "issue": "Internal Server Error thrown for patching a nonexistent session\n**Describe the bug**\r\n<!-- A clear and concise description of what the bug is. -->\r\nHTTP 500 error is thrown when a patch request is sent for a session which doesn't exist.\r\n\r\n**To Reproduce**\r\nSteps to reproduce the behavior:\r\n1. Send a patch request for a session which doesn't exist\r\n\r\n**Expected behavior**\r\n<!-- A clear and concise description of what you expected to happen. -->\r\nA proper error should be sent.\r\n\r\nWorking on fixing this.\n", "before_files": [{"content": "from marshmallow import validates_schema, validate\nfrom marshmallow_jsonapi import fields\nfrom marshmallow_jsonapi.flask import Relationship\n\nfrom app.api.helpers.exceptions import UnprocessableEntity, ForbiddenException\nfrom app.api.helpers.permission_manager import has_access\nfrom app.api.helpers.utilities import dasherize\nfrom app.api.schema.base import SoftDeletionSchema\nfrom app.models.session import Session\nfrom utils.common import use_defaults\n\n\n@use_defaults()\nclass SessionSchema(SoftDeletionSchema):\n    \"\"\"\n    Api schema for Session Model\n    \"\"\"\n\n    class Meta:\n        \"\"\"\n        Meta class for Session Api Schema\n        \"\"\"\n        type_ = 'session'\n        self_view = 'v1.session_detail'\n        self_view_kwargs = {'id': '<id>'}\n        inflect = dasherize\n\n    @validates_schema(pass_original=True)\n    def validate_date(self, data, original_data):\n        if 'id' in original_data['data']:\n            session = Session.query.filter_by(id=original_data['data']['id']).one()\n\n            if 'starts_at' not in data:\n                data['starts_at'] = session.starts_at\n\n            if 'ends_at' not in data:\n                data['ends_at'] = session.ends_at\n\n            if 'event' not in data:\n                data['event'] = session.event_id\n\n        if data['starts_at'] and data['ends_at']:\n            if data['starts_at'] >= data['ends_at']:\n                raise UnprocessableEntity(\n                    {'pointer': '/data/attributes/ends-at'}, \"ends-at should be after starts-at\")\n\n        if 'state' in data:\n            if data['state'] is not 'draft' or not 'pending':\n                if not has_access('is_coorganizer', event_id=data['event']):\n                    return ForbiddenException({'source': ''}, 'Co-organizer access is required.')\n\n        if 'track' in data:\n            if not has_access('is_coorganizer', event_id=data['event']):\n                return ForbiddenException({'source': ''}, 'Co-organizer access is required.')\n\n        if 'microlocation' in data:\n            if not has_access('is_coorganizer', event_id=data['event']):\n                return ForbiddenException({'source': ''}, 'Co-organizer access is required.')\n\n    id = fields.Str(dump_only=True)\n    title = fields.Str(required=True)\n    subtitle = fields.Str(allow_none=True)\n    level = fields.Int(allow_none=True)\n    short_abstract = fields.Str(allow_none=True)\n    long_abstract = fields.Str(allow_none=True)\n    comments = fields.Str(allow_none=True)\n    starts_at = fields.DateTime(allow_none=True)\n    ends_at = fields.DateTime(allow_none=True)\n    language = fields.Str(allow_none=True)\n    slides_url = fields.Url(allow_none=True)\n    video_url = fields.Url(allow_none=True)\n    audio_url = fields.Url(allow_none=True)\n    signup_url = fields.Url(allow_none=True)\n    state = fields.Str(validate=validate.OneOf(choices=[\"pending\", \"accepted\", \"confirmed\", \"rejected\", \"draft\"]),\n                       allow_none=True, default='draft')\n    created_at = fields.DateTime(dump_only=True)\n    deleted_at = fields.DateTime(dump_only=True)\n    submitted_at = fields.DateTime(allow_none=True)\n    is_mail_sent = fields.Boolean()\n    last_modified_at = fields.DateTime(dump_only=True)\n    send_email = fields.Boolean(load_only=True, allow_none=True)\n    average_rating = fields.Float(dump_only=True)\n    microlocation = Relationship(attribute='microlocation',\n                                 self_view='v1.session_microlocation',\n                                 self_view_kwargs={'id': '<id>'},\n                                 related_view='v1.microlocation_detail',\n                                 related_view_kwargs={'session_id': '<id>'},\n                                 schema='MicrolocationSchema',\n                                 type_='microlocation')\n    track = Relationship(attribute='track',\n                         self_view='v1.session_track',\n                         self_view_kwargs={'id': '<id>'},\n                         related_view='v1.track_detail',\n                         related_view_kwargs={'session_id': '<id>'},\n                         schema='TrackSchema',\n                         type_='track')\n    session_type = Relationship(attribute='session_type',\n                                self_view='v1.session_session_type',\n                                self_view_kwargs={'id': '<id>'},\n                                related_view='v1.session_type_detail',\n                                related_view_kwargs={'session_id': '<id>'},\n                                schema='SessionTypeSchema',\n                                type_='session-type')\n    event = Relationship(attribute='event',\n                         self_view='v1.session_event',\n                         self_view_kwargs={'id': '<id>'},\n                         related_view='v1.event_detail',\n                         related_view_kwargs={'session_id': '<id>'},\n                         schema='EventSchemaPublic',\n                         type_='event')\n    feedbacks = Relationship(attribute='feedbacks',\n                             self_view='v1.session_feedbacks',\n                             self_view_kwargs={'id': '<id>'},\n                             related_view='v1.feedback_list',\n                             related_view_kwargs={'session_id': '<id>'},\n                             schema='FeedbackSchema',\n                             many=True,\n                             type_='feedback')\n    speakers = Relationship(attribute='speakers',\n                            many=True,\n                            self_view='v1.session_speaker',\n                            self_view_kwargs={'id': '<id>'},\n                            related_view='v1.speaker_list',\n                            related_view_kwargs={'session_id': '<id>'},\n                            schema='SpeakerSchema',\n                            type_='speaker')\n    creator = Relationship(attribute='user',\n                           self_view='v1.session_user',\n                           self_view_kwargs={'id': '<id>'},\n                           related_view='v1.user_detail',\n                           related_view_kwargs={'session_id': '<id>'},\n                           schema='UserSchemaPublic',\n                           type_='user')\n", "path": "app/api/schema/sessions.py"}], "after_files": [{"content": "from flask_rest_jsonapi.exceptions import ObjectNotFound\nfrom marshmallow import validates_schema, validate\nfrom marshmallow_jsonapi import fields\nfrom marshmallow_jsonapi.flask import Relationship\nfrom sqlalchemy.orm.exc import NoResultFound\n\nfrom app.api.helpers.exceptions import UnprocessableEntity, ForbiddenException\nfrom app.api.helpers.permission_manager import has_access\nfrom app.api.helpers.utilities import dasherize\nfrom app.api.schema.base import SoftDeletionSchema\nfrom app.models.session import Session\nfrom utils.common import use_defaults\n\n\n@use_defaults()\nclass SessionSchema(SoftDeletionSchema):\n    \"\"\"\n    Api schema for Session Model\n    \"\"\"\n\n    class Meta:\n        \"\"\"\n        Meta class for Session Api Schema\n        \"\"\"\n        type_ = 'session'\n        self_view = 'v1.session_detail'\n        self_view_kwargs = {'id': '<id>'}\n        inflect = dasherize\n\n    @validates_schema(pass_original=True)\n    def validate_date(self, data, original_data):\n        if 'id' in original_data['data']:\n            try:\n                session = Session.query.filter_by(id=original_data['data']['id']).one()\n            except NoResultFound:\n                raise ObjectNotFound({'parameter': '{id}'}, \"Session: not found\")\n\n            if 'starts_at' not in data:\n                data['starts_at'] = session.starts_at\n\n            if 'ends_at' not in data:\n                data['ends_at'] = session.ends_at\n\n            if 'event' not in data:\n                data['event'] = session.event_id\n\n        if data['starts_at'] and data['ends_at']:\n            if data['starts_at'] >= data['ends_at']:\n                raise UnprocessableEntity(\n                    {'pointer': '/data/attributes/ends-at'}, \"ends-at should be after starts-at\")\n\n        if 'state' in data:\n            if data['state'] is not 'draft' or not 'pending':\n                if not has_access('is_coorganizer', event_id=data['event']):\n                    return ForbiddenException({'source': ''}, 'Co-organizer access is required.')\n\n        if 'track' in data:\n            if not has_access('is_coorganizer', event_id=data['event']):\n                return ForbiddenException({'source': ''}, 'Co-organizer access is required.')\n\n        if 'microlocation' in data:\n            if not has_access('is_coorganizer', event_id=data['event']):\n                return ForbiddenException({'source': ''}, 'Co-organizer access is required.')\n\n    id = fields.Str(dump_only=True)\n    title = fields.Str(required=True)\n    subtitle = fields.Str(allow_none=True)\n    level = fields.Int(allow_none=True)\n    short_abstract = fields.Str(allow_none=True)\n    long_abstract = fields.Str(allow_none=True)\n    comments = fields.Str(allow_none=True)\n    starts_at = fields.DateTime(allow_none=True)\n    ends_at = fields.DateTime(allow_none=True)\n    language = fields.Str(allow_none=True)\n    slides_url = fields.Url(allow_none=True)\n    video_url = fields.Url(allow_none=True)\n    audio_url = fields.Url(allow_none=True)\n    signup_url = fields.Url(allow_none=True)\n    state = fields.Str(validate=validate.OneOf(choices=[\"pending\", \"accepted\", \"confirmed\", \"rejected\", \"draft\"]),\n                       allow_none=True, default='draft')\n    created_at = fields.DateTime(dump_only=True)\n    deleted_at = fields.DateTime(dump_only=True)\n    submitted_at = fields.DateTime(allow_none=True)\n    is_mail_sent = fields.Boolean()\n    last_modified_at = fields.DateTime(dump_only=True)\n    send_email = fields.Boolean(load_only=True, allow_none=True)\n    average_rating = fields.Float(dump_only=True)\n    microlocation = Relationship(attribute='microlocation',\n                                 self_view='v1.session_microlocation',\n                                 self_view_kwargs={'id': '<id>'},\n                                 related_view='v1.microlocation_detail',\n                                 related_view_kwargs={'session_id': '<id>'},\n                                 schema='MicrolocationSchema',\n                                 type_='microlocation')\n    track = Relationship(attribute='track',\n                         self_view='v1.session_track',\n                         self_view_kwargs={'id': '<id>'},\n                         related_view='v1.track_detail',\n                         related_view_kwargs={'session_id': '<id>'},\n                         schema='TrackSchema',\n                         type_='track')\n    session_type = Relationship(attribute='session_type',\n                                self_view='v1.session_session_type',\n                                self_view_kwargs={'id': '<id>'},\n                                related_view='v1.session_type_detail',\n                                related_view_kwargs={'session_id': '<id>'},\n                                schema='SessionTypeSchema',\n                                type_='session-type')\n    event = Relationship(attribute='event',\n                         self_view='v1.session_event',\n                         self_view_kwargs={'id': '<id>'},\n                         related_view='v1.event_detail',\n                         related_view_kwargs={'session_id': '<id>'},\n                         schema='EventSchemaPublic',\n                         type_='event')\n    feedbacks = Relationship(attribute='feedbacks',\n                             self_view='v1.session_feedbacks',\n                             self_view_kwargs={'id': '<id>'},\n                             related_view='v1.feedback_list',\n                             related_view_kwargs={'session_id': '<id>'},\n                             schema='FeedbackSchema',\n                             many=True,\n                             type_='feedback')\n    speakers = Relationship(attribute='speakers',\n                            many=True,\n                            self_view='v1.session_speaker',\n                            self_view_kwargs={'id': '<id>'},\n                            related_view='v1.speaker_list',\n                            related_view_kwargs={'session_id': '<id>'},\n                            schema='SpeakerSchema',\n                            type_='speaker')\n    creator = Relationship(attribute='user',\n                           self_view='v1.session_user',\n                           self_view_kwargs={'id': '<id>'},\n                           related_view='v1.user_detail',\n                           related_view_kwargs={'session_id': '<id>'},\n                           schema='UserSchemaPublic',\n                           type_='user')\n", "path": "app/api/schema/sessions.py"}]}