import json
import logging

from aiohttp.web import Response
from aiohttp.web import middleware

log = logging.getLogger(__name__)


@middleware
async def auto_committer(request, handler) -> Response:
    response = await handler(request)
    if request.method.lower() in ['post', 'put']:
        if 400 <= response.status < 600:
            request.app['session_instance'].rollback()
            log.info('automatically rolled back changes to database')
        else:
            request.app['session_instance'].commit()
            log.info('automatically committed changes to database')

    return response


@middleware
async def json_error_handler(request, handler) -> Response:
    response = await handler(request)
    if 400 <= response.status < 600:
        log.info('HTTP Status %d / JSON Error handler middleware active' % response.status)
        data = {
            'type': 'error',
            'status': response.status,
            'error_message': response.text,
        }
        log.debug(data)
        response.text = json.dumps(data)
    return response

@@ -282,16 +282,58 @@
 'put'%5D:%0A
+        if request.app%5B'autocommit'%5D:%0A    
         
@@ -357,32 +357,36 @@
 e.status %3C 600:%0A
+    
             requ
@@ -428,32 +428,36 @@
 k()%0A            
+ 
+   
 log.info('automa
@@ -506,16 +506,20 @@
         
+    
 else:%0A  
@@ -520,32 +520,36 @@
 se:%0A            
+ 
+   
 request.app%5B'ses
@@ -573,16 +573,20 @@
 ommit()%0A
+    
         

fix middleware to take autocommit into account