예제 #1
0
파일: misc.py 프로젝트: EIDA/eidaws
def from_fdsnws_datetime(datestring, use_dateutil=True):
    """
    Parse a datestring from a string specified by the FDSNWS datetime
    specification.

    :param str datestring: String to be parsed
    :param bool use_dateutil: Make use of the :code:`dateutil` package if set
        to :code:`True`
    :returns: Datetime
    :rtype: :py:class:`datetime.datetime`

    See: http://www.fdsn.org/webservices/FDSN-WS-Specifications-1.1.pdf
    """
    IGNORE_TZ = True

    if len(datestring) == 10:
        # only YYYY-mm-dd is defined
        return datetime.datetime.combine(from_iso_date(datestring),
                                         datetime.time())
    else:
        # from marshmallow
        if not _iso8601_re.match(datestring):
            raise ValueError("Not a valid ISO8601-formatted string.")
        # Use dateutil's parser if possible
        if dateutil_available and use_dateutil:
            return parser.parse(datestring, ignoretz=IGNORE_TZ)
        else:
            # Strip off microseconds and timezone info.
            return datetime.datetime.strptime(datestring[:19],
                                              "%Y-%m-%dT%H:%M:%S")
예제 #2
0
 def _deserialize(self, value):
     """Deserialize an ISO8601-formatted date string to a
     :class:`datetime.date` object.
     """
     try:
         return utils.from_iso_date(value)
     except (TypeError, ValueError):
         msg = 'Could not deserialize {0!r} to a date object.'.format(value)
         raise UnmarshallingError(getattr(self, 'error', None) or msg)
예제 #3
0
파일: fields.py 프로젝트: synic/marshmallow
 def _deserialize(self, value, attr, data):
     """Deserialize an ISO8601-formatted date string to a
     :class:`datetime.date` object.
     """
     if not value:  # falsy values are invalid
         self.fail('invalid')
     try:
         return utils.from_iso_date(value)
     except (AttributeError, TypeError, ValueError):
         self.fail('invalid')
예제 #4
0
 def _deserialize(self, value, attr, data):
     """Deserialize an ISO8601-formatted date string to a
     :class:`datetime.date` object.
     """
     if not value:  # falsy values are invalid
         self.fail('invalid')
     try:
         return utils.from_iso_date(value)
     except (AttributeError, TypeError, ValueError):
         self.fail('invalid')
예제 #5
0
 def _deserialize(self, value):
     """Deserialize an ISO8601-formatted date string to a
     :class:`datetime.date` object.
     """
     msg = 'Could not deserialize {0!r} to a date object.'.format(value)
     err = ValidationError(getattr(self, 'error', None) or msg)
     if not value:  # falsy values are invalid
         raise err
     try:
         return utils.from_iso_date(value)
     except (AttributeError, TypeError, ValueError):
         raise err
예제 #6
0
    def post(self):
        user = get_current_user()

        try:
            schema = MealSchema()

            # make sure these match!
            if user.household_id != ns.payload["household_id"]:
                raise IndexError("User household does not match meal payload!")

            meal = Meal.create(
                date=from_iso_date(ns.payload["date"]),
                household_id=ns.payload["household_id"],
                recipes=[],
            )
            current_app.logger.debug(
                f"Created meal with ID #{meal.id} for {meal.date}")
            if "recipes" in ns.payload and len(ns.payload["recipes"]) > 0:
                for recipe_id in ns.payload["recipes"]:
                    recipe = Recipe.get_by_id(recipe_id)
                    meal.recipes.append(recipe)
                    current_app.logger.debug(
                        f"added {recipe.name} to meal #{meal.id}")
                meal.save()

        except ValueError as ve:
            current_app.logger.debug(
                f"Date format prevented meal from being created")
            return {"message": str(ve), "data": None}, 400
        except Exception as e:
            current_app.logger.error(f"Error while creating meal: {str(e)}")
            return {
                "message": f"Could not create meal. {str(e)}",
                "data": None
            }, 400

        return {
            "message": f"Created meal for {meal.date}",
            "data": schema.dump(meal),
        }, 201
예제 #7
0
def test_from_iso_date():
    d = dt.date(2014, 8, 21)
    iso_date = d.isoformat()
    result = utils.from_iso_date(iso_date)
    assert type(result) == dt.date
    assert_date_equal(result, d)
예제 #8
0
def test_from_iso_date(use_dateutil):
    d = dt.date(2014, 8, 21)
    iso_date = d.isoformat()
    result = utils.from_iso_date(iso_date, use_dateutil=use_dateutil)
    assert isinstance(result, dt.date)
    assert_date_equal(result, d)
예제 #9
0
def test_from_iso_date(use_dateutil):
    d = dt.date(2014, 8, 21)
    iso_date = d.isoformat()
    result = utils.from_iso_date(iso_date, use_dateutil=use_dateutil)
    assert isinstance(result, dt.date)
    assert_date_equal(result, d)