Skip to content

Commit

Permalink
[IMP] Moved class AlchemyEncoder into blueprints namespace
Browse files Browse the repository at this point in the history
  • Loading branch information
c8y3 committed Oct 9, 2024
1 parent d5297d3 commit a1c24f6
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 43 deletions.
42 changes: 41 additions & 1 deletion source/app/blueprints/responses.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,14 +15,18 @@
# You should have received a copy of the GNU Lesser General Public License
# along with this program; if not, write to the Free Software Foundation,
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
import datetime
import decimal
import json
import pickle
import uuid

from flask import render_template
from flask import request
from sqlalchemy.orm import DeclarativeMeta

from app import TEMPLATE_PATH
from app import app
from app.util import AlchemyEncoder


# Set basic 404
Expand Down Expand Up @@ -57,3 +61,39 @@ def response_success(msg='', data=None):
"data": data if data is not None else []
}
return response(200, data=content)


class AlchemyEncoder(json.JSONEncoder):

def default(self, obj):
if isinstance(obj.__class__, DeclarativeMeta):
# an SQLAlchemy class
fields = {}
for field in [x for x in dir(obj) if not x.startswith('_') and x != 'metadata'
and x != 'query' and x != 'query_class']:
data = obj.__getattribute__(field)
try:
json.dumps(data) # this will fail on non-encodable values, like other classes
fields[field] = data
except TypeError:
fields[field] = None
# a json-encodable dict
return fields

if isinstance(obj, decimal.Decimal):
return str(obj)

if isinstance(obj, datetime.datetime) or isinstance(obj, datetime.date):
return obj.isoformat()

if isinstance(obj, uuid.UUID):
return str(obj)

else:
if obj.__class__ == bytes:
try:
return pickle.load(obj)
except Exception:
return str(obj)

return json.JSONEncoder.default(self, obj)
3 changes: 1 addition & 2 deletions source/app/blueprints/rest/manage/manage_tags.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,7 @@
from app.datamgmt.manage.manage_tags_db import get_filtered_tags
from app.schema.marshables import TagsSchema
from app.blueprints.access_controls import ac_api_requires
from app.util import AlchemyEncoder
from app.blueprints.responses import response_success
from app.blueprints.responses import response_success, AlchemyEncoder

manage_tags_rest_blueprint = Blueprint('manage_tags_rest', __name__)

Expand Down
40 changes: 0 additions & 40 deletions source/app/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,14 +22,11 @@
import datetime
import decimal
import hashlib
import json
import logging as log
import marshmallow
import pickle
import random
import shutil
import string
import uuid
import weakref
from cryptography.exceptions import InvalidSignature
from cryptography.hazmat.primitives import hashes
Expand All @@ -38,50 +35,13 @@
from flask_login import current_user
from pathlib import Path
from pyunpack import Archive
from sqlalchemy.ext.declarative import DeclarativeMeta
from sqlalchemy.orm.attributes import flag_modified

from app import app
from app import db
from app.models import Cases


class AlchemyEncoder(json.JSONEncoder):

def default(self, obj):
if isinstance(obj.__class__, DeclarativeMeta):
# an SQLAlchemy class
fields = {}
for field in [x for x in dir(obj) if not x.startswith('_') and x != 'metadata'
and x != 'query' and x != 'query_class']:
data = obj.__getattribute__(field)
try:
json.dumps(data) # this will fail on non-encodable values, like other classes
fields[field] = data
except TypeError:
fields[field] = None
# a json-encodable dict
return fields

if isinstance(obj, decimal.Decimal):
return str(obj)

if isinstance(obj, datetime.datetime) or isinstance(obj, datetime.date):
return obj.isoformat()

if isinstance(obj, uuid.UUID):
return str(obj)

else:
if obj.__class__ == bytes:
try:
return pickle.load(obj)
except Exception:
return str(obj)

return json.JSONEncoder.default(self, obj)


def DictDatetime(t):
dl = ['Y', 'm', 'd', 'H', 'M', 'S', 'f']
if type(t) is datetime.datetime:
Expand Down

0 comments on commit a1c24f6

Please sign in to comment.