Python email.utils.format_datetime() Examples

The following are 30 code examples of email.utils.format_datetime(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module email.utils , or try the search function .
Example #1
Source File: robot.py    From pybotvac with MIT License 6 votes vote down vote up
def __call__(self, request):
        # We have to format the date according to RFC 2616
        # https://tools.ietf.org/html/rfc2616#section-14.18

        now = datetime.now(timezone.utc)
        date = format_datetime(now, True)

        try:
            # Attempt to decode request.body (assume bytes received)
            msg = '\n'.join([self.serial.lower(), date, request.body.decode('utf8')])
        except AttributeError:
            # Decode failed, assume request.body is already type str
            msg = '\n'.join([self.serial.lower(), date, request.body])

        signing = hmac.new(key=self.secret.encode('utf8'),
                           msg=msg.encode('utf8'),
                           digestmod=hashlib.sha256)

        request.headers['Date'] = date
        request.headers['Authorization'] = "NEATOAPP " + signing.hexdigest()

        return request 
Example #2
Source File: views.py    From Django-2-Web-Development-Cookbook-Third-Edition with MIT License 6 votes vote down vote up
def render_js(request, template_name, cache=True, *args, **kwargs):
    response = render(request, template_name, *args, **kwargs)
    response["Content-Type"] = \
        "application/javascript; charset=UTF-8"
    if cache:
        now = datetime.now(timezone.utc)
        response["Last-Modified"] = format_datetime(now,
                                                    usegmt=True)

        # cache in the browser for 1 month
        expires = now + timedelta(days=31)
        response["Expires"] = format_datetime(expires,
                                              usegmt=True)
    else:
        response["Pragma"] = "No-Cache"
    return response 
Example #3
Source File: views.py    From Django-2-Web-Development-Cookbook-Third-Edition with MIT License 6 votes vote down vote up
def render_js(request, template_name, cache=True, *args, **kwargs):
    response = render(request, template_name, *args, **kwargs)
    response["Content-Type"] = \
        "application/javascript; charset=UTF-8"
    if cache:
        now = datetime.now(timezone.utc)
        response["Last-Modified"] = format_datetime(now,
                                                    usegmt=True)

        # cache in the browser for 1 month
        expires = now + timedelta(days=31)
        response["Expires"] = format_datetime(expires,
                                              usegmt=True)
    else:
        response["Pragma"] = "No-Cache"
    return response 
Example #4
Source File: views.py    From Django-2-Web-Development-Cookbook-Third-Edition with MIT License 6 votes vote down vote up
def render_js(request, template_name, cache=True, *args, **kwargs):
    response = render(request, template_name, *args, **kwargs)
    response["Content-Type"] = \
        "application/javascript; charset=UTF-8"
    if cache:
        now = datetime.now(timezone.utc)
        response["Last-Modified"] = format_datetime(now,
                                                    usegmt=True)

        # cache in the browser for 1 month
        expires = now + timedelta(days=31)
        response["Expires"] = format_datetime(expires,
                                              usegmt=True)
    else:
        response["Pragma"] = "No-Cache"
    return response 
Example #5
Source File: views.py    From Django-2-Web-Development-Cookbook-Third-Edition with MIT License 6 votes vote down vote up
def render_js(request, template_name, cache=True, *args, **kwargs):
    response = render(request, template_name, *args, **kwargs)
    response["Content-Type"] = \
        "application/javascript; charset=UTF-8"
    if cache:
        now = datetime.now(timezone.utc)
        response["Last-Modified"] = format_datetime(now,
                                                    usegmt=True)

        # cache in the browser for 1 month
        expires = now + timedelta(days=31)
        response["Expires"] = format_datetime(expires,
                                              usegmt=True)
    else:
        response["Pragma"] = "No-Cache"
    return response 
Example #6
Source File: views.py    From Django-2-Web-Development-Cookbook-Third-Edition with MIT License 6 votes vote down vote up
def render_js(request, template_name, cache=True, *args, **kwargs):
    response = render(request, template_name, *args, **kwargs)
    response["Content-Type"] = \
        "application/javascript; charset=UTF-8"
    if cache:
        now = datetime.now(timezone.utc)
        response["Last-Modified"] = format_datetime(now,
                                                    usegmt=True)

        # cache in the browser for 1 month
        expires = now + timedelta(days=31)
        response["Expires"] = format_datetime(expires,
                                              usegmt=True)
    else:
        response["Pragma"] = "No-Cache"
    return response 
Example #7
Source File: views.py    From Django-2-Web-Development-Cookbook-Third-Edition with MIT License 6 votes vote down vote up
def render_js(request, template_name, cache=True, *args, **kwargs):
    response = render(request, template_name, *args, **kwargs)
    response["Content-Type"] = \
        "application/javascript; charset=UTF-8"
    if cache:
        now = datetime.now(timezone.utc)
        response["Last-Modified"] = format_datetime(now,
                                                    usegmt=True)

        # cache in the browser for 1 month
        expires = now + timedelta(days=31)
        response["Expires"] = format_datetime(expires,
                                              usegmt=True)
    else:
        response["Pragma"] = "No-Cache"
    return response 
Example #8
Source File: views.py    From Django-2-Web-Development-Cookbook-Third-Edition with MIT License 6 votes vote down vote up
def render_js(request, template_name, cache=True, *args, **kwargs):
    response = render(request, template_name, *args, **kwargs)
    response["Content-Type"] = \
        "application/javascript; charset=UTF-8"
    if cache:
        now = datetime.now(timezone.utc)
        response["Last-Modified"] = format_datetime(now,
                                                    usegmt=True)

        # cache in the browser for 1 month
        expires = now + timedelta(days=31)
        response["Expires"] = format_datetime(expires,
                                              usegmt=True)
    else:
        response["Pragma"] = "No-Cache"
    return response 
Example #9
Source File: views.py    From Django-2-Web-Development-Cookbook-Third-Edition with MIT License 6 votes vote down vote up
def render_js(request, template_name, cache=True, *args, **kwargs):
    response = render(request, template_name, *args, **kwargs)
    response["Content-Type"] = \
        "application/javascript; charset=UTF-8"
    if cache:
        now = datetime.now(timezone.utc)
        response["Last-Modified"] = format_datetime(now,
                                                    usegmt=True)

        # cache in the browser for 1 month
        expires = now + timedelta(days=31)
        response["Expires"] = format_datetime(expires,
                                              usegmt=True)
    else:
        response["Pragma"] = "No-Cache"
    return response 
Example #10
Source File: views.py    From Django-2-Web-Development-Cookbook-Third-Edition with MIT License 6 votes vote down vote up
def render_js(request, template_name, cache=True, *args, **kwargs):
    response = render(request, template_name, *args, **kwargs)
    response["Content-Type"] = \
        "application/javascript; charset=UTF-8"
    if cache:
        now = datetime.now(timezone.utc)
        response["Last-Modified"] = format_datetime(now,
                                                    usegmt=True)

        # cache in the browser for 1 month
        expires = now + timedelta(days=31)
        response["Expires"] = format_datetime(expires,
                                              usegmt=True)
    else:
        response["Pragma"] = "No-Cache"
    return response 
Example #11
Source File: views.py    From Django-2-Web-Development-Cookbook-Third-Edition with MIT License 6 votes vote down vote up
def render_js(request, template_name, cache=True, *args, **kwargs):
    response = render(request, template_name, *args, **kwargs)
    response["Content-Type"] = \
        "application/javascript; charset=UTF-8"
    if cache:
        now = datetime.now(timezone.utc)
        response["Last-Modified"] = format_datetime(now,
                                                    usegmt=True)

        # cache in the browser for 1 month
        expires = now + timedelta(days=31)
        response["Expires"] = format_datetime(expires,
                                              usegmt=True)
    else:
        response["Pragma"] = "No-Cache"
    return response 
Example #12
Source File: views.py    From Django-2-Web-Development-Cookbook-Third-Edition with MIT License 6 votes vote down vote up
def render_js(request, template_name, cache=True, *args, **kwargs):
    response = render(request, template_name, *args, **kwargs)
    response["Content-Type"] = \
        "application/javascript; charset=UTF-8"
    if cache:
        now = datetime.now(timezone.utc)
        response["Last-Modified"] = format_datetime(now,
                                                    usegmt=True)

        # cache in the browser for 1 month
        expires = now + timedelta(days=31)
        response["Expires"] = format_datetime(expires,
                                              usegmt=True)
    else:
        response["Pragma"] = "No-Cache"
    return response 
Example #13
Source File: views.py    From Django-2-Web-Development-Cookbook-Third-Edition with MIT License 6 votes vote down vote up
def render_js(request, template_name, cache=True, *args, **kwargs):
    response = render(request, template_name, *args, **kwargs)
    response["Content-Type"] = \
        "application/javascript; charset=UTF-8"
    if cache:
        now = datetime.now(timezone.utc)
        response["Last-Modified"] = format_datetime(now,
                                                    usegmt=True)

        # cache in the browser for 1 month
        expires = now + timedelta(days=31)
        response["Expires"] = format_datetime(expires,
                                              usegmt=True)
    else:
        response["Pragma"] = "No-Cache"
    return response 
Example #14
Source File: decorators.py    From uclapi with MIT License 5 votes vote down vote up
def _get_last_modified_header(redis_key=None):
    # Default last modified is the UTC time now
    last_modified = format_datetime(
        datetime.datetime.utcnow().replace(tzinfo=timezone.utc),
        usegmt=True
    )

    # If we haven't been passed a Redis key, we just return the
    # current timeztamp as a last modified header.
    if redis_key is None:
        return last_modified

    # We have been given a Redis key, so attempt to pull it from Redis
    r = redis.Redis(host=REDIS_UCLAPI_HOST)
    redis_key = "http:headers:Last-Modified:" + redis_key
    value = r.get(redis_key)

    if value:
        # Convert the Redis bytes response to a string.
        value = value.decode('utf-8')

        # We need the UTC timezone so that we can convert to it.
        utc_tz = pytz.timezone("UTC")

        # Parse the ISO 8601 timestamp from Redis and represent it as UTC
        utc_timestamp = ciso8601.parse_datetime(value).astimezone(utc_tz)

        # Format the datetime object as per the HTTP Header RFC.
        # We replace the inner tzinfo in the timestamp to force it to be a UTC
        # timestamp as opposed to a naive one; this is a requirement for the
        # format_datetime function.
        last_modified = format_datetime(
            utc_timestamp.replace(tzinfo=timezone.utc),
            usegmt=True
        )

    return last_modified 
Example #15
Source File: scriptresults.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def fmt_time(dt):
    """Return None if None otherwise returned formatted datetime."""
    if dt is None:
        return None
    else:
        return format_datetime(dt) 
Example #16
Source File: scriptresults.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def results(cls, script_set):
        results = []
        for script_result in filter_script_results(
            script_set, script_set.filters, script_set.hardware_type
        ):
            result = {
                "id": script_result.id,
                "created": format_datetime(script_result.created),
                "updated": format_datetime(script_result.updated),
                "name": script_result.name,
                "status": script_result.status,
                "status_name": script_result.status_name,
                "exit_status": script_result.exit_status,
                "started": fmt_time(script_result.started),
                "ended": fmt_time(script_result.ended),
                "runtime": script_result.runtime,
                "starttime": script_result.starttime,
                "endtime": script_result.endtime,
                "estimated_runtime": script_result.estimated_runtime,
                "parameters": script_result.parameters,
                "script_id": script_result.script_id,
                "script_revision_id": script_result.script_version_id,
                "suppressed": script_result.suppressed,
            }
            if script_set.include_output:
                result["output"] = b64encode(script_result.output)
                result["stdout"] = b64encode(script_result.stdout)
                result["stderr"] = b64encode(script_result.stderr)
                result["result"] = b64encode(script_result.result)
            results.append(result)
        return results 
Example #17
Source File: dhcpsnippets.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def history(handler, dhcp_snippet):
        return [
            {
                "id": value.id,
                "value": value.data,
                "created": format_datetime(value.created),
            }
            for value in dhcp_snippet.value.previous_versions()
        ] 
Example #18
Source File: test_bootresources.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def create_bootloader_simplestream(self, stream_version=None):
        if stream_version is None:
            stream_version = "1"
        product = (
            "com.ubuntu.maas:daily:%s:bootloader-download" % stream_version
        )
        version = datetime.now().date().strftime("%Y%m%d.0")
        versions = {
            version: {
                "items": {
                    BOOT_RESOURCE_FILE_TYPE.BOOTLOADER: {
                        "sha256": factory.make_name("sha256"),
                        "path": factory.make_name("path"),
                        "ftype": BOOT_RESOURCE_FILE_TYPE.BOOTLOADER,
                        "size": random.randint(0, 2 ** 64),
                    }
                }
            }
        }
        products = {
            product: {
                "label": "daily",
                "os": "grub-efi-signed",
                "arch": "amd64",
                "bootloader-type": "uefi",
                "version": version,
                "versions": versions,
            }
        }
        src = {
            "datatype": "image-downloads",
            "format": "products:1.0",
            "updated": format_datetime(datetime.now()),
            "products": products,
            "content_id": "com.ubuntu.maas:daily:1:bootloader-download",
        }
        return src, product, version 
Example #19
Source File: dhcpsnippet.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def dehydrate(self, obj, data, for_list=False):
        """Add DHCPSnippet value history to `data`."""
        data["history"] = [
            {
                "id": value.id,
                "value": value.data,
                "created": format_datetime(value.created),
            }
            for value in obj.value.previous_versions()
        ]
        return data 
Example #20
Source File: test_dhcpsnippet.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def dehydrate_dhcp_snippet(self, dhcp_snippet):
        node_system_id = None
        subnet_id = None
        if dhcp_snippet.subnet is not None:
            subnet_id = dhcp_snippet.subnet.id
        elif dhcp_snippet.node is not None:
            node_system_id = dhcp_snippet.node.system_id
        return {
            "id": dhcp_snippet.id,
            "name": dhcp_snippet.name,
            "description": dhcp_snippet.description,
            "value": dhcp_snippet.value.data,
            "history": [
                {
                    "id": value.id,
                    "value": value.data,
                    "created": format_datetime(value.created),
                }
                for value in dhcp_snippet.value.previous_versions()
            ],
            "enabled": dhcp_snippet.enabled,
            "node": node_system_id,
            "subnet": subnet_id,
            "updated": dehydrate_datetime(dhcp_snippet.updated),
            "created": dehydrate_datetime(dhcp_snippet.created),
        } 
Example #21
Source File: headerregistry.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def parse(cls, value, kwds):
        if not value:
            kwds['defects'].append(errors.HeaderMissingRequiredValue())
            kwds['datetime'] = None
            kwds['decoded'] = ''
            kwds['parse_tree'] = parser.TokenList()
            return
        if isinstance(value, str):
            value = utils.parsedate_to_datetime(value)
        kwds['datetime'] = value
        kwds['decoded'] = utils.format_datetime(kwds['datetime'])
        kwds['parse_tree'] = cls.value_parser(kwds['decoded']) 
Example #22
Source File: headerregistry.py    From android_universal with MIT License 5 votes vote down vote up
def parse(cls, value, kwds):
        if not value:
            kwds['defects'].append(errors.HeaderMissingRequiredValue())
            kwds['datetime'] = None
            kwds['decoded'] = ''
            kwds['parse_tree'] = parser.TokenList()
            return
        if isinstance(value, str):
            value = utils.parsedate_to_datetime(value)
        kwds['datetime'] = value
        kwds['decoded'] = utils.format_datetime(kwds['datetime'])
        kwds['parse_tree'] = cls.value_parser(kwds['decoded']) 
Example #23
Source File: test_utils.py    From android_universal with MIT License 5 votes vote down vote up
def test_naive_datetime(self):
        self.assertEqual(utils.format_datetime(self.naive_dt),
                         self.datestring + ' -0000') 
Example #24
Source File: test_utils.py    From android_universal with MIT License 5 votes vote down vote up
def test_aware_datetime(self):
        self.assertEqual(utils.format_datetime(self.aware_dt),
                         self.datestring + self.offsetstring) 
Example #25
Source File: test_utils.py    From android_universal with MIT License 5 votes vote down vote up
def test_usegmt(self):
        utc_dt = datetime.datetime(*self.dateargs,
                                   tzinfo=datetime.timezone.utc)
        self.assertEqual(utils.format_datetime(utc_dt, usegmt=True),
                         self.datestring + ' GMT') 
Example #26
Source File: test_utils.py    From android_universal with MIT License 5 votes vote down vote up
def test_usegmt_with_naive_datetime_raises(self):
        with self.assertRaises(ValueError):
            utils.format_datetime(self.naive_dt, usegmt=True) 
Example #27
Source File: test_utils.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def test_usegmt_with_naive_datetime_raises(self):
        with self.assertRaises(ValueError):
            utils.format_datetime(self.naive_dt, usegmt=True) 
Example #28
Source File: headerregistry.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def parse(cls, value, kwds):
        if not value:
            kwds['defects'].append(errors.HeaderMissingRequiredValue())
            kwds['datetime'] = None
            kwds['decoded'] = ''
            kwds['parse_tree'] = parser.TokenList()
            return
        if isinstance(value, str):
            value = utils.parsedate_to_datetime(value)
        kwds['datetime'] = value
        kwds['decoded'] = utils.format_datetime(kwds['datetime'])
        kwds['parse_tree'] = cls.value_parser(kwds['decoded']) 
Example #29
Source File: test_utils.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_naive_datetime(self):
        self.assertEqual(utils.format_datetime(self.naive_dt),
                         self.datestring + ' -0000') 
Example #30
Source File: test_utils.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_aware_datetime(self):
        self.assertEqual(utils.format_datetime(self.aware_dt),
                         self.datestring + self.offsetstring)