Skip to content
Browse files

Make fields importable from top-level module and add Date

This adds a custom `Date` field which respects

This also exposes elasticsearch_dsl's fields from the top-level
module, so that all fields are imported from the same place:

from elasticsearch_metrics import Keyword, Date

This approach was the same used in webargs, which uses
marshmallow fields under the hood but overrides a single
field. Discussion: marshmallow-code/webargs#61 (comment)

close #18
  • Loading branch information...
sloria committed Aug 20, 2018
1 parent 4a93c40 commit f3ec035c4892aa116d91be18b3448d21b9efbcf2
Showing with 41 additions and 0 deletions.
  1. +2 −0 elasticsearch_metrics/
  2. +27 −0 elasticsearch_metrics/
  3. +12 −0 tests/
@@ -3,6 +3,8 @@
from elasticsearch_dsl.connections import connections
from django.utils.module_loading import autodiscover_modules

from .field import * # noqa

__version__ = "0.0.0"

default_app_config = "elasticsearch_metrics.ElasticsearchMetricsConfig"
@@ -0,0 +1,27 @@
from django.conf import settings
from elasticsearch_dsl import field as edsl_field

__all__ = ["Date"]
# Expose all fields from elasticsearch_dsl.field
# We do this instead of 'from elasticsearch_dsl.field import *' because elasticsearch_metrics
# has its own subclass of Date
for each in (
for field_name in dir(edsl_field)
if field_name != "Date" and not field_name.startswith("_")
field = getattr(edsl_field, each)
is_field_subclass = isinstance(field, type) and issubclass(field, edsl_field.Field)
if field is edsl_field.Field or is_field_subclass:
globals()[each] = field

class Date(edsl_field.Date):
"""Same as `elasticsearch_dsl.field.Date` except that this respects
the TIMEZONE Django setting.

def __init__(self, default_timezone=None, *args, **kwargs):
default_timezone = default_timezone or getattr(settings, "TIMEZONE", None)
super(Date, self).__init__(default_timezone=default_timezone, *args, **kwargs)
@@ -0,0 +1,12 @@
import pytest
from dateutil import tz

from elasticsearch_metrics import Date

class TestDate:
@pytest.mark.parametrize("timezone", ["America/Chicago", "UTC"])
def test_respects_timezone_setting(self, settings, timezone):
settings.TIMEZONE = timezone
field = Date()
assert field._default_timezone == tz.gettz(timezone)

0 comments on commit f3ec035

Please sign in to comment.
You can’t perform that action at this time.