Skip to content

Commit b211131

Browse files
committed
fix: refactor Flask init code
1 parent 7f30c17 commit b211131

File tree

3 files changed

+46
-50
lines changed

3 files changed

+46
-50
lines changed

aw_server/rest.py

Lines changed: 0 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,9 @@
11
import json
22
import traceback
3-
from datetime import datetime, timedelta
43
from functools import wraps
54
from threading import Lock
65
from typing import Dict
76

8-
import flask.json.provider
97
import iso8601
108
from aw_core import schema
119
from aw_core.models import Event
@@ -53,20 +51,6 @@ def decorator(*args, **kwargs):
5351
api = Api(blueprint, doc="/", decorators=[host_header_check])
5452

5553

56-
# TODO: Clean up JSONEncoder code?
57-
# Move to server.py
58-
class CustomJSONProvider(flask.json.provider.DefaultJSONProvider):
59-
def default(self, obj, *args, **kwargs):
60-
try:
61-
if isinstance(obj, datetime):
62-
return obj.isoformat()
63-
if isinstance(obj, timedelta):
64-
return obj.total_seconds()
65-
except TypeError:
66-
pass
67-
return super().default(obj)
68-
69-
7054
# Loads event and bucket schema from JSONSchema in aw_core
7155
event = api.schema_model("Event", schema.get_json_schema("event"))
7256
bucket = api.schema_model("Bucket", schema.get_json_schema("bucket"))

aw_server/server.py

Lines changed: 44 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,10 @@
11
import logging
22
import os
3+
from datetime import datetime, timedelta
34
from typing import Dict, List
45

56
import aw_datastore
7+
import flask.json.provider
68
from aw_datastore import Datastore
79
from flask import (
810
Blueprint,
@@ -26,40 +28,50 @@
2628

2729

2830
class AWFlask(Flask):
29-
def __init__(self, name, testing: bool, *args, **kwargs):
30-
self.json_provider_class = rest.CustomJSONProvider
31-
32-
# Only pretty-print JSON if in testing mode (because of performance)
31+
def __init__(
32+
self,
33+
host: str,
34+
testing: bool,
35+
storage_method=None,
36+
cors_origins=[],
37+
custom_static=dict(),
38+
*args,
39+
**kwargs
40+
):
41+
name = "aw-server"
42+
self.json_provider_class = CustomJSONProvider
43+
# only prettyprint JSON if testing (due to perf)
3344
self.json_provider_class.compact = not testing
3445

3546
# Initialize Flask
3647
Flask.__init__(self, name, *args, **kwargs)
37-
38-
# Is set on later initialization
39-
self.api: ServerAPI = None # type: ignore
40-
41-
42-
def create_app(
43-
host: str, testing=True, storage_method=None, cors_origins=[], custom_static=dict()
44-
) -> AWFlask:
45-
app = AWFlask("aw-server", testing, static_folder=static_folder, static_url_path="")
46-
47-
with app.app_context():
48-
_config_cors(cors_origins, testing)
49-
50-
app.register_blueprint(root)
51-
app.register_blueprint(rest.blueprint)
52-
app.register_blueprint(get_custom_static_blueprint(custom_static))
53-
54-
if storage_method is None:
55-
storage_method = aw_datastore.get_storage_methods()["memory"]
56-
db = Datastore(storage_method, testing=testing)
57-
app.api = ServerAPI(db=db, testing=testing)
58-
59-
# needed for host-header check
60-
app.config["HOST"] = host
61-
62-
return app
48+
self.config["HOST"] = host # needed for host-header check
49+
with self.app_context():
50+
_config_cors(cors_origins, testing)
51+
52+
# Initialize datastore and API
53+
if storage_method is None:
54+
storage_method = aw_datastore.get_storage_methods()["memory"]
55+
db = Datastore(storage_method, testing=testing)
56+
self.api = ServerAPI(db=db, testing=testing)
57+
58+
self.register_blueprint(root)
59+
self.register_blueprint(rest.blueprint)
60+
self.register_blueprint(get_custom_static_blueprint(custom_static))
61+
62+
63+
class CustomJSONProvider(flask.json.provider.DefaultJSONProvider):
64+
# encoding/decoding of datetime as iso8601 strings
65+
# encoding of timedelta as second floats
66+
def default(self, obj, *args, **kwargs):
67+
try:
68+
if isinstance(obj, datetime):
69+
return obj.isoformat()
70+
if isinstance(obj, timedelta):
71+
return obj.total_seconds()
72+
except TypeError:
73+
pass
74+
return super().default(obj)
6375

6476

6577
@root.route("/")
@@ -105,10 +117,10 @@ def _start(
105117
cors_origins: List[str] = [],
106118
custom_static: Dict[str, str] = dict(),
107119
):
108-
app = create_app(
120+
app = AWFlask(
109121
host,
110-
storage_method=storage_method,
111122
testing=testing,
123+
storage_method=storage_method,
112124
cors_origins=cors_origins,
113125
custom_static=custom_static,
114126
)

tests/conftest.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,14 @@
11
import logging
22

33
import pytest
4-
from aw_server.server import create_app
4+
from aw_server.server import AWFlask
55

66
logging.basicConfig(level=logging.WARN)
77

88

99
@pytest.fixture(scope="session")
1010
def app():
11-
return create_app("127.0.0.1", testing=True)
11+
return AWFlask("127.0.0.1", testing=True)
1212

1313

1414
@pytest.fixture(scope="session")

0 commit comments

Comments
 (0)