Skip to content

Commit

Permalink
fix: fixed updated JSON handling in Flask 2.3+
Browse files Browse the repository at this point in the history
  • Loading branch information
ErikBjare committed Jul 6, 2023
1 parent a2fa352 commit 7f30c17
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 23 deletions.
16 changes: 3 additions & 13 deletions aw_server/rest.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
from threading import Lock
from typing import Dict

import flask.json.provider
import iso8601
from aw_core import schema
from aw_core.models import Event
Expand Down Expand Up @@ -54,10 +55,7 @@ def decorator(*args, **kwargs):

# TODO: Clean up JSONEncoder code?
# Move to server.py
class CustomJSONEncoder(json.JSONEncoder):
def __init__(self, *args, **kwargs):
super().__init__()

class CustomJSONProvider(flask.json.provider.DefaultJSONProvider):
def default(self, obj, *args, **kwargs):
try:
if isinstance(obj, datetime):
Expand All @@ -66,15 +64,7 @@ def default(self, obj, *args, **kwargs):
return obj.total_seconds()
except TypeError:
pass
return json.JSONEncoder.default(self, obj)


class AnyJson(fields.Raw):
def format(self, value):
if type(value) == dict:
return value
else:
return json.loads(value)
return super().default(obj)


# Loads event and bucket schema from JSONSchema in aw_core
Expand Down
20 changes: 10 additions & 10 deletions aw_server/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,13 @@


class AWFlask(Flask):
def __init__(self, name, *args, **kwargs):
def __init__(self, name, testing: bool, *args, **kwargs):
self.json_provider_class = rest.CustomJSONProvider

# Only pretty-print JSON if in testing mode (because of performance)
self.json_provider_class.compact = not testing

# Initialize Flask
Flask.__init__(self, name, *args, **kwargs)

# Is set on later initialization
Expand All @@ -36,23 +42,17 @@ def __init__(self, name, *args, **kwargs):
def create_app(
host: str, testing=True, storage_method=None, cors_origins=[], custom_static=dict()
) -> AWFlask:
app = AWFlask("aw-server", static_folder=static_folder, static_url_path="")

if storage_method is None:
storage_method = aw_datastore.get_storage_methods()["memory"]

# Only pretty-print JSON if in testing mode (because of performance)
app.config["JSONIFY_PRETTYPRINT_REGULAR"] = testing
app = AWFlask("aw-server", testing, static_folder=static_folder, static_url_path="")

with app.app_context():
_config_cors(cors_origins, testing)

app.json_encoder = rest.CustomJSONEncoder

app.register_blueprint(root)
app.register_blueprint(rest.blueprint)
app.register_blueprint(get_custom_static_blueprint(custom_static))

if storage_method is None:
storage_method = aw_datastore.get_storage_methods()["memory"]
db = Datastore(storage_method, testing=testing)
app.api = ServerAPI(db=db, testing=testing)

Expand Down

0 comments on commit 7f30c17

Please sign in to comment.