Exemplo n.º 1
0
    def _parse_date_params(self, params):
        """Parse the date params from the request

        :param MultiDict params: HTTP request arguments
        """
        date_filter_param = (params.get('date_filter') or '').strip().lower()

        try:
            start_date = params.get('start_date')
            if start_date:
                str_to_date(params.get(
                    'start_date'))  # validating if date can be parsed
        except:  # noqa
            raise SuperdeskApiError.badRequestError(
                'Invalid value for start date')

        try:
            end_date = params.get('end_date')
            if end_date:
                str_to_date(
                    params.get('end_date'))  # validating if date can be parsed
        except:  # noqa
            raise SuperdeskApiError.badRequestError(
                'Invalid value for end date')

        return date_filter_param, start_date, end_date
Exemplo n.º 2
0
def try_cast(v):
    try:
        str_to_date(v)  # try if it matches format
        return arrow.get(v).datetime  # return timezone aware time
    except:
        try:
            return ObjectId(v)
        except:
            return v
Exemplo n.º 3
0
def try_cast(v):
    try:
        str_to_date(v)  # try if it matches format
        return arrow.get(v).datetime  # return timezone aware time
    except:
        try:
            return ObjectId(v)
        except:
            return v
Exemplo n.º 4
0
def try_cast(v):
    # False and 0 are getting converted to datetime by arrow
    if v is None or isinstance(v, bool) or v == 0:
        return v

    try:
        str_to_date(v)  # try if it matches format
        return arrow.get(v).datetime  # return timezone aware time
    except Exception:
        try:
            return ObjectId(v)
        except Exception:
            return v
Exemplo n.º 5
0
def try_cast(v):
    """Cast string value to date or ObjectId if possible.

    :param v: string value
    """
    try:
        str_to_date(v)  # try if it matches format
        return arrow.get(v).datetime  # return timezone aware time
    except ValueError:
        try:
            return ObjectId(v)
        except InvalidId:
            return v
Exemplo n.º 6
0
def try_cast(v):
    # False and 0 are getting converted to datetime by arrow
    if v is None or isinstance(v, bool) or v is 0:
        return v

    try:
        str_to_date(v)  # try if it matches format
        return arrow.get(v).datetime  # return timezone aware time
    except:
        try:
            return ObjectId(v)
        except:
            return v
Exemplo n.º 7
0
    def assert_head(self, url):
        h = self.test_client.head(url)
        r = self.test_client.get(url)
        self.assertTrue(not h.data)

        if 'Expires' in r.headers:
            # there's a tiny chance that the two expire values will differ by
            # one second. See #316.
            head_expire = str_to_date(r.headers.pop('Expires'))
            get_expire = str_to_date(h.headers.pop('Expires'))
            d = head_expire - get_expire
            self.assertTrue(d.seconds in (0, 1))

        self.assertEqual(r.headers, h.headers)
Exemplo n.º 8
0
def producer_blogs_syndicate(producer_id, blog_id):
    data = request.get_json(silent=True) or {}
    consumer_blog_id = data.get('consumer_blog_id')
    auto_publish = data.get('auto_publish')
    auto_retrieve = data.get('auto_retrieve', True)
    start_date = data.get('start_date')

    if not consumer_blog_id:
        return api_error('Missing "consumer_blog_id" in form data.', 422)

    if start_date:
        try:
            start_date = str_to_date(start_date)
        except ValueError:
            return api_error('start_date is not valid.', 400)

    if request.method == 'DELETE':
        return _delete_producer_blogs_syndicate(producer_id, blog_id,
                                                consumer_blog_id)
    elif request.method == 'PATCH':
        return _update_producer_blogs_syndicate(producer_id, blog_id,
                                                consumer_blog_id,
                                                auto_retrieve, start_date)
    else:
        return _create_producer_blogs_syndicate(producer_id, blog_id,
                                                consumer_blog_id, auto_publish,
                                                auto_retrieve, start_date)
Exemplo n.º 9
0
 def visit_Str(self, node):
     """ Strings """
     try:
         value = str_to_date(node.s)
         self.current_value = value if value is not None else node.s
     except ValueError:
         self.current_value = node.s
Exemplo n.º 10
0
 def visit_Str(self, node):
     """ Strings """
     try:
         value = str_to_date(node.s)
         self.current_value = value if value is not None else node.s
     except ValueError:
         self.current_value = node.s
Exemplo n.º 11
0
def date_hook(json_data):
    for key, value in json_data.items():
        try:
            json_data[key] = str_to_date(value)
        except:
            pass
    return json_data
Exemplo n.º 12
0
def parse_date(datetime):
    """Return datetime instance for datetime."""
    if isinstance(datetime, str):
        try:
            return str_to_date(datetime)
        except ValueError:
            return arrow.get(datetime).datetime
    return datetime
Exemplo n.º 13
0
 def test_parse_string_to_date(self):
     expected_expression = \
         sqla_op.gt(self.model._updated,
                    str_to_date('Sun, 06 Nov 1994 08:49:37 GMT'))
     r = parse('_updated > "Sun, 06 Nov 1994 08:49:37 GMT"', self.model)
     self.assertEqual(type(r), list)
     self.assertTrue(len(r) == 1)
     self.assertTrue(expected_expression.compare(r[0]))
Exemplo n.º 14
0
 def test_parse_string_to_date(self):
     expected_expression = \
         sqla_op.gt(self.model._updated,
                    str_to_date('Sun, 06 Nov 1994 08:49:37 GMT'))
     r = parse('_updated > "Sun, 06 Nov 1994 08:49:37 GMT"', self.model)
     self.assertEqual(type(r), list)
     self.assertTrue(len(r) == 1)
     self.assertTrue(expected_expression.compare(r[0]))
Exemplo n.º 15
0
def range_date(query: ElasticRangeParams):
    date = str_to_date(query.date)

    return field_range(
        ElasticRangeParams(field=query.field,
                           time_zone=query.time_zone,
                           value_format=query.value_format,
                           gte=date.strftime('%Y-%m-%d') + '||/d',
                           lt=(date + timedelta(days=1)).strftime('%Y-%m-%d') +
                           '||/d'))
Exemplo n.º 16
0
 def __init__(self, asset: Dict[str, Any], file: Response):
     super().__init__()
     self.write(file.content)
     self.seek(0)
     self.content_type = asset["mimetype"]
     self.length = asset["length"]
     self._name = asset["name"]
     self.filename = asset["filename"]
     self.upload_date = str_to_date(asset["_updated"])
     self.md5 = asset["_etag"]
     self._id = asset["_id"]
Exemplo n.º 17
0
 def process_where(where, in_date_value=False):
     if not where:
         return where
     if isinstance(where, dict):
         for k, v in where.iteritems():
             where[k] = process_where(v, in_date_value or k == 'date_of_receipt')
     elif isinstance(where, (list, tuple)):
         return [process_where(x, in_date_value) for x in where]
     elif in_date_value and isinstance(where, basestring):
         try:
             return str_to_date(where)
         except ValueError:
             return where
     return where
 def _test_default_values(self, app, cls, updated_name='updated',
                          created_name='created'):
     # test updated and created fields if they are correctly generated
     now = datetime.utcnow()
     d = cls(a="xyz", b=29)
     updated = getattr(d, updated_name)
     created = getattr(d, created_name)
     self.assertEqual(type(updated), datetime)
     self.assertEqual(type(created), datetime)
     self.assertDateTimeAlmostEqual(updated, now)
     self.assertDateTimeAlmostEqual(created, now)
     d.save()
     # test real returned values
     json_data = app.get('/simpledoc/').get_json()
     created_attr = app.application.config['DATE_CREATED']
     created_str = json_data[config.ITEMS][0][created_attr]
     date_created = str_to_date(created_str)
     self.assertDateTimeAlmostEqual(now, date_created)
     d.delete()
Exemplo n.º 19
0
    def __init__(self,
                 field: str,
                 gt: str = None,
                 gte: str = None,
                 lt: str = None,
                 lte: str = None,
                 value_format: str = None,
                 time_zone: str = None,
                 start_of_week: int = None,
                 date_range: DATE_RANGE = None,
                 date: str = None):
        """Allows to easily set fields by name using kwargs"""

        self.field = field
        self.gt = gt
        self.gte = gte
        self.lt = lt
        self.lte = lte
        self.value_format = value_format
        self.time_zone = time_zone if time_zone else get_timezone_offset(
            app.config['DEFAULT_TIMEZONE'], utcnow())
        self.start_of_week = int(start_of_week or 0)
        self.date_range = date_range
        self.date = str_to_date(date) if date else None
Exemplo n.º 20
0
 def test_str_to_date(self):
     self.assertEqual(str_to_date(self.datestr), self.valid)
     self.assertRaises(ValueError, str_to_date, 'not-a-date')
     self.assertRaises(ValueError, str_to_date,
                       self.datestr.replace('GMT', 'UTC'))
Exemplo n.º 21
0
Arquivo: utils.py Projeto: sunbit/eve
 def test_str_to_date(self):
     self.assertEqual(str_to_date(self.datestr), self.valid)
     self.assertRaises(ValueError, str_to_date, "not-a-date")
     self.assertRaises(ValueError, str_to_date, self.datestr.replace("GMT", "UTC"))
Exemplo n.º 22
0
 def test_str_to_date(self):
     self.assertEqual(str_to_date(self.datestr), self.valid)
     self.assertRaises(ValueError, str_to_date, "not-a-date")
     self.assertRaises(ValueError, str_to_date,
                       self.datestr.replace("GMT", "UTC"))
Exemplo n.º 23
0
def approveExtensionRequest():
    """ 
    Approve ```extensionRequest``` 

    Accepts ```{_id: <extension request id>, reviewd_by: <reviewer user id>, status: <"APPROVED"/"REJECTED">}``` 
    as request json argument
    """
    response = {}
    try:
        # Get request parameters and perform sanity check
        if not request.json:
            raise ValueError("Empty json body provided!!!")

        _id = request.json['_id'] if '_id' in request.json else None
        reviewed_by = request.json[
            'reviewed_by'] if 'reviewed_by' in request.json else None
        status = request.json['status'] if 'status' in request.json else None
        logger.debug("_id: " + str(_id) + "   reviewed_by: " +
                     str(reviewed_by) + "   status: " + str(status))

        if not _id or not reviewed_by or not status in [
                "APPROVED", "REJECTED"
        ]:
            raise ValueError(
                "Must provide extensionRequest id, reviewer id and approval status!!!"
            )

        # Get extension request
        extensionRequests = app.data.driver.db['extensionRequests']
        extension_query = {"_id": ObjectId(_id)}
        extension_request = extensionRequests.find_one(extension_query,
                                                       sort=[("_created", -1)])
        if not extension_request:
            raise ValueError("Extension Request does not exist")
        if extension_request['status'] not in ['REQUESTED']:
            raise ValueError("Provision Request cannot be reviewed in " +
                             str(extension_request['status']) + " state")

        # Get provision request
        provisionRequests = app.data.driver.db['provisionRequests']
        provision_query = {
            "_id": ObjectId(extension_request['provision_request'])
        }
        provision_request = provisionRequests.find_one(provision_query,
                                                       sort=[("_created", -1)])
        if not provision_request:
            raise ValueError("Provision Request does not exist")
        if provision_request['status'] not in [
                'APPROVED', 'INITIATED', 'DEPLOYED', 'EXPIRED'
        ]:
            raise ValueError(
                "Provision Request cannot be extended in state: " +
                str(provision_request['status']))

        # Update provision request if extension "APPROVED"
        if status == "APPROVED":
            # find new expiration time
            expires_by = str_to_date(
                provision_request['expires_by']) + timedelta(
                    hours=extension_request['extend_by'])
            update = {"$set": {"status": "EXTENDED", "expires_by": expires_by}}
            ret = provisionRequests.update(provision_query,
                                           update,
                                           upsert=False)
            logger.debug("provision request update response: " + str(ret))

        # Update extension request
        update = {
            "$set": {
                "reviewed_by": ObjectId(reviewed_by),
                "status": status,
            }
        }
        ret = extensionRequests.update(extension_query, update, upsert=False)
        logger.debug("extension request update response: " + str(ret))

        # Create response object
        response = {"status": status, "_id": str(provision_request['_id'])}

        # Create notification for developer (requester)
        create_notification(title="Provision Request" + str(status),
                            description="Your provision request " +
                            str(provision_request["_id"]) + " has been " +
                            str(status),
                            user=provision_request["requested_by"])
    except ValueError as e:
        return Response(toJSON(failure_resp(str(e), 400)),
                        400,
                        mimetype='application/json')
    except Exception as e:
        return Response(toJSON(failure_resp(str(e), 500)),
                        500,
                        mimetype='application/json')
    return Response(toJSON(response), 200, mimetype='application/json')
Exemplo n.º 24
0
 def test_str_to_date(self):
     self.assertEqual(str_to_date(self.datestr), self.valid)
     self.assertRaises(ValueError, str_to_date, 'not-a-date')
     self.assertRaises(ValueError, str_to_date,
                       self.datestr.replace('GMT', 'UTC'))