Unable to get event and add event annotation when using PGSQL
When using postgresql some queries fails with DataError.

This is due to the way SQLalchemy constructs the query, and the way we pass in the searchindex name to the filter.

diff --git a/timesketch/api/v1/resources.py b/timesketch/api/v1/resources.py
index 8e8822e0..6b1aa8ec 100644
--- a/timesketch/api/v1/resources.py
+++ b/timesketch/api/v1/resources.py
@@ -374,7 +374,8 @@ class EventResource(ResourceMixin, Resource):
         args = self.parser.parse_args()
         sketch = Sketch.query.get_with_acl(sketch_id)
         searchindex_id = args.get(u'searchindex_id')
-        searchindex = SearchIndex.query.get(searchindex_id)
+        searchindex = SearchIndex.query.filter_by(
+            index_name=searchindex_id).first()
         event_id = args.get(u'event_id')
         indices = [t.searchindex.index_name for t in sketch.timelines]
 
@@ -428,7 +429,8 @@ class EventAnnotationResource(ResourceMixin, Resource):
             indices = [t.searchindex.index_name for t in sketch.timelines]
             annotation_type = form.annotation_type.data
             searchindex_id = form.searchindex_id.data
-            searchindex = SearchIndex.query.get(searchindex_id)
+            searchindex = SearchIndex.query.filter_by(
+                index_name=searchindex_id).first()
             event_id = form.event_id.data
             event_type = form.event_type.data
 
diff --git a/timesketch/api/v1/resources_test.py b/timesketch/api/v1/resources_test.py
index 954f3d77..6d2f14a2 100644
--- a/timesketch/api/v1/resources_test.py
+++ b/timesketch/api/v1/resources_test.py
@@ -149,9 +149,6 @@ class EventResourceTest(BaseTest):
     """Test EventResource."""
     resource_url = u'/api/v1/sketches/1/event/'
     expected_response = {
-        u'meta': {
-            u'comments': []
-        },
         u'objects': {
             u'timestamp_desc': u'',
             u'timestamp': 1410895419859714,
@@ -172,7 +169,7 @@ class EventResourceTest(BaseTest):
         self.login()
         response = self.client.get(
             self.resource_url + u'?searchindex_id=test&event_id=test')
-        self.assertDictEqual(response.json, self.expected_response)
+        self.assertDictContainsSubset(self.expected_response, response.json)
         self.assert200(response)
 
     @mock.patch(
diff --git a/wsgi.py b/wsgi.py
index 896b1b6e..996e578b 100644
--- a/wsgi.py
+++ b/wsgi.py
@@ -33,5 +33,11 @@ Example configuration for Apache with mod_wsgi (a2enmod mod_wsgi):
 #execfile(activate_virtualenv, dict(__file__=activate_virtualenv))
 
 from timesketch import create_app
+from timesketch.models import db_session
 
 application = create_app()
+
+# Remove the session after every request or app shutdown.
+@application.teardown_appcontext
+def shutdown_session(exception=None):
+    db_session.remove()
['timesketch/api/v1/resources.py', 'wsgi.py', 'timesketch/api/v1/resources_test.py']