Python django.contrib.staticfiles.storage.staticfiles_storage.url() Examples

The following are 30 code examples of django.contrib.staticfiles.storage.staticfiles_storage.url(). 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 django.contrib.staticfiles.storage.staticfiles_storage , or try the search function .
Example #1
Source File: jinja2.py    From intake with MIT License 6 votes vote down vote up
def environment(**options):
    env = Environment(**options)
    env.globals.update({
        'static': loudfail_static,
        'url': reverse,
        "content": "project.content.constants",
        "linkify": "project.jinja2.linkify",
        "current_local_time": "project.jinja2.current_local_time",
        "namify": "project.jinja2.namify",
        "url_with_ids": "project.jinja2.url_with_ids",
        "oxford_comma": "project.jinja2.oxford_comma",
        "contact_info_to_html": "project.jinja2.contact_info_to_html",
        "to_json": "project.jinja2.to_json",
        "humanize": "project.jinja2.humanize",
        "contact_method_verbs": "project.jinja2.contact_method_verbs",
        "format_phone_number": "project.jinja2.format_phone_number",
        "settings": "django.conf.settings",
        "local_time": "intake.utils.local_time",
    })
    return env 
Example #2
Source File: test_email.py    From Inboxen with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_rate_limit(self):
        url = urls.reverse("download-email-view", kwargs={"email": self.email.eid,
                                                          "inbox": self.email.inbox.inbox,
                                                          "domain": self.email.inbox.domain.domain})
        request = MockRequest(user=self.user)
        for i in range(settings.SINGLE_EMAIL_LIMIT_COUNT - 1):
            ratelimit.single_email_ratelimit.counter_increase(request)

        response = self.client.get(url)
        self.assertEqual(response.status_code, 200)

        response = self.client.get(url)
        self.assertEqual(response.status_code, 404)

        cache.cache.clear()

        response = self.client.get(url)
        self.assertEqual(response.status_code, 200) 
Example #3
Source File: test_email.py    From Inboxen with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_download(self):
        url = urls.reverse("download-email-view", kwargs={"email": self.email.eid,
                                                          "inbox": self.email.inbox.inbox,
                                                          "domain": self.email.inbox.domain.domain})
        response = self.client.get(url)
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response["Content-Disposition"],
                         "attachment; filename={}-{}.mbox".format(str(self.email.inbox), self.email.eid))
        self.assertEqual(response["Content-Type"], "application/mbox")

        with NamedTemporaryFile() as tmp:
            tmp.write(response.content)
            tmp.file.flush()  # just to be sure

            box = mailbox.mbox(tmp.name)
            self.assertEqual(len(box), 1) 
Example #4
Source File: test_email.py    From Inboxen with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_body_no_ask_images(self):
        self.user.inboxenprofile.display_images = models.UserProfile.NO_DISPLAY
        self.user.inboxenprofile.save()

        response = self.client.get(self.get_url())
        self.assertEqual(response.status_code, 200)
        self.assertEqual(len(response.context["email"]["bodies"]), 1)
        self.assertFalse(response.context["email"]["ask_images"] and response.context["email"]["has_images"])

        body = response.context["email"]["bodies"][0]
        self.assertIn(u"<p style=\"color:#fff\">&#160;</p>", body)
        self.assertIn(u"<p style=\"color:#fff\">&#163;&#163;&#163;</p>", body)
        self.assertNotIn(u"http://example.com/coolface.jpg", body)
        self.assertIn(u"img width=\"10\" height=\"10\"", body)
        self.assertIn(staticfiles_storage.url("imgs/placeholder.svg"), body)

        # premailer should have worked fine
        self.assertNotIn("Part of this message could not be parsed - it may not display correctly",
                         response.content.decode("utf-8"))

        # csp
        self.assertIn("style-src 'self' 'unsafe-inline';", response["content-security-policy"])
        self.assertIn("img-src 'self';", response["content-security-policy"])
        self.assertNotIn("img-src 'self' https:;", response["content-security-policy"]) 
Example #5
Source File: test_email.py    From Inboxen with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_body_encoding_without_imgDisplay(self):
        self.user.inboxenprofile.display_images = models.UserProfile.ASK
        self.user.inboxenprofile.save()

        response = self.client.get(self.get_url())
        self.assertEqual(response.status_code, 200)
        self.assertEqual(len(response.context["email"]["bodies"]), 1)
        self.assertTrue(response.context["email"]["ask_images"] and response.context["email"]["has_images"])

        body = response.context["email"]["bodies"][0]
        self.assertIn(u"<p style=\"color:#fff\">&#160;</p>", body)
        self.assertIn(u"<p style=\"color:#fff\">&#163;&#163;&#163;</p>", body)
        self.assertNotIn(u"http://example.com/coolface.jpg", body)
        self.assertIn(u"img width=\"10\" height=\"10\"", body)
        self.assertIn(staticfiles_storage.url("imgs/placeholder.svg"), body)

        # premailer should have worked fine
        self.assertNotIn("Part of this message could not be parsed - it may not display correctly",
                         response.content.decode("utf-8"))

        # csp
        self.assertIn("style-src 'self' 'unsafe-inline';", response["content-security-policy"])
        self.assertIn("img-src 'self';", response["content-security-policy"])
        self.assertNotIn("img-src 'self' https:;", response["content-security-policy"]) 
Example #6
Source File: test_email.py    From Inboxen with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_body_encoding_with_imgDisplay(self):
        self.user.inboxenprofile.display_images = models.UserProfile.ASK
        self.user.inboxenprofile.save()

        response = self.client.get(self.get_url() + "?imgDisplay=1")
        self.assertEqual(response.status_code, 200)
        self.assertEqual(len(response.context["email"]["bodies"]), 1)
        self.assertFalse(response.context["email"]["ask_images"] and response.context["email"]["has_images"])

        body = response.context["email"]["bodies"][0]
        self.assertIn(u"<p style=\"color:#fff\">&#160;</p>", body)
        self.assertIn(u"<p style=\"color:#fff\">&#163;&#163;&#163;</p>", body)
        self.assertIn(u"http://example.com/coolface.jpg", body)
        self.assertIn(u"img width=\"10\" height=\"10\"", body)
        self.assertNotIn(staticfiles_storage.url("imgs/placeholder.svg"), body)

        # premailer should have worked fine
        self.assertNotIn("Part of this message could not be parsed - it may not display correctly",
                         response.content.decode("utf-8"))

        # csp
        self.assertIn("style-src 'self' 'unsafe-inline';", response["content-security-policy"])
        self.assertIn("img-src 'self' https:;", response["content-security-policy"]) 
Example #7
Source File: test_email.py    From Inboxen with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_not_viewable(self):
        self.email.deleted = True
        self.email.save()

        url = urls.reverse("download-email-view", kwargs={"email": self.email.eid,
                                                          "inbox": self.email.inbox.inbox,
                                                          "domain": self.email.inbox.domain.domain})
        response = self.client.get(url)
        self.assertEqual(response.status_code, 404) 
Example #8
Source File: forms.py    From Tautulli with GNU General Public License v3.0 5 votes vote down vote up
def render(self, name, value, attrs=None, renderer=None):
        attrs = dict(self.attrs, **attrs)
        options = attrs.get('options', {})
        attrs["options"] = ''

        params = cloudinary.utils.build_upload_params(**options)
        if options.get("unsigned"):
            params = cloudinary.utils.cleanup_params(params)
        else:
            params = cloudinary.utils.sign_request(params, options)

        if 'resource_type' not in options:
            options['resource_type'] = 'auto'
        cloudinary_upload_url = cloudinary.utils.cloudinary_api_url("upload", **options)

        attrs["data-url"] = cloudinary_upload_url
        attrs["data-form-data"] = json.dumps(params)
        attrs["data-cloudinary-field"] = name
        chunk_size = options.get("chunk_size", None)
        if chunk_size:
            attrs["data-max-chunk-size"] = chunk_size
        attrs["class"] = " ".join(["cloudinary-fileupload", attrs.get("class", "")])

        widget = super(CloudinaryInput, self).render("file", None, attrs=attrs)
        if value:
            if isinstance(value, CloudinaryResource):
                value_string = value.get_presigned()
            else:
                value_string = value
            widget += forms.HiddenInput().render(name, value_string)
        return widget 
Example #9
Source File: template_extras.py    From openprescribing with MIT License 5 votes vote down vote up
def conditional_js(context, script_name):
    suffix = "" if context.get("DEBUG", True) else ".min"
    filename = "js/{}{}.js".format(script_name, suffix)
    url = staticfiles_storage.url(filename)
    tag = '<script src="{}"></script>'.format(url)
    return mark_safe(tag) 
Example #10
Source File: jinja2.py    From mercure with GNU General Public License v3.0 5 votes vote down vote up
def environment(**options):
    """Get jinja2 environment.

    :param options: Options
    :return env: return environment instance
    """
    env = Environment(**options)
    env.globals.update({
        'static': staticfiles_storage.url,
        'url': reverse,
        'LANGUAGES': settings.LANGUAGES,
        'translation': translation,
    })

    # add django filters
    env.filters['slugify'] = slugify

    # use django-bootstrap-form on jinja
    from bootstrapform.templatetags import bootstrap
    env.filters['bootstrap'] = bootstrap.bootstrap
    env.filters['bootstrap_horizontal'] = bootstrap.bootstrap_horizontal
    env.filters['bootstrap_inline'] = bootstrap.bootstrap_inline

    # add custom filters
    env.filters['fupper'] = fupper

    env.install_gettext_translations(translation)
    return env 
Example #11
Source File: test_email.py    From Inboxen with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_anonymous(self):
        response = self.client.get(settings.LOGOUT_URL, follow=True)
        url = urls.reverse("download-email-view", kwargs={"email": self.email.eid,
                                                          "inbox": self.email.inbox.inbox,
                                                          "domain": self.email.inbox.domain.domain})
        response = self.client.get(url)
        self.assertRedirects(response,
                             "{}?next={}".format(settings.LOGIN_URL, url),
                             fetch_redirect_response=False) 
Example #12
Source File: test_email.py    From Inboxen with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_html_a(self):
        response = self.client.get(self.get_url())
        self.assertEqual(response.status_code, 200)
        self.assertEqual(len(response.context["email"]["bodies"]), 1)
        body = response.context["email"]["bodies"][0]
        expected_string = '<a href="/click/?url=http%3A//example.com/%3Fq%3Dthing" target="_blank" rel="noreferrer">link</a>'  # noqa: E501
        self.assertIn(expected_string, body) 
Example #13
Source File: test_email.py    From Inboxen with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_unknown_tag_get_dropped(self):
        email = {"display_images": True, "eid": "abc"}
        expected_html = "".join([
            """<div><div><a href="/click/?url=https%3A//example.com" target="_blank" """,
            """rel="noreferrer"></a></div></div>""",
        ])

        text = """<html><body><details style="hi">{}</section></body></html>""".format(EMPTY_ANCHOR_TAG)
        returned_body = email_utils._clean_html_body(None, email, text, "ascii")
        self.assertEqual(returned_body, expected_html) 
Example #14
Source File: test_email.py    From Inboxen with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_clean_html_no_body(self):
        email = {"display_images": True}
        with mock.patch("inboxen.utils.email.messages.info", side_effect=self.failureException("Unexpected message")):
            returned_body = email_utils._clean_html_body(None, email, BODILESS_BODY, "utf-8")

            self.assertIn('<a href="/click/?url=http%3A//tinyletter.com/asym/confirm%3Fid%3Duuid"', returned_body) 
Example #15
Source File: models.py    From doccano with MIT License 5 votes vote down vote up
def image(self):
        return staticfiles_storage.url('assets/images/cats/text_classification.jpg') 
Example #16
Source File: test_email.py    From Inboxen with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_name_in_cc(self):
        header_data = self.content_type_header.data
        header_data.data = "text/html; charset=\"utf-8\"; name=\"Växjö.jpg\""
        header_data.save()

        url = urls.reverse("email-attachment", kwargs={"attachmentid": self.part.id})
        response = self.client.get(url)
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response["Content-Disposition"], "attachment; filename=\"Växjö.jpg\"") 
Example #17
Source File: test_email.py    From Inboxen with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_name_in_cd(self):
        factories.HeaderFactory(part=self.part, name="Content-Disposition", data="inline; filename=\"Växjö.jpg\"")
        url = urls.reverse("email-attachment", kwargs={"attachmentid": self.part.id})
        response = self.client.get(url)
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response["Content-Disposition"], "attachment; filename=\"Växjö.jpg\"") 
Example #18
Source File: test_email.py    From Inboxen with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_no_name(self):
        url = urls.reverse("email-attachment", kwargs={"attachmentid": self.part.id})
        response = self.client.get(url)
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response["Content-Disposition"], "attachment") 
Example #19
Source File: forms.py    From Tautulli with GNU General Public License v3.0 5 votes vote down vote up
def enable_callback(self, request):
        from django.contrib.staticfiles.storage import staticfiles_storage
        self.widget.attrs["options"]["callback"] = request.build_absolute_uri(
            staticfiles_storage.url("html/cloudinary_cors.html")) 
Example #20
Source File: test_email.py    From Inboxen with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_body_tag_get_turned_to_div(self):
        email = {"display_images": True, "eid": "abc"}
        expected_html = "".join([
            """<div><div style="hi"><a href="/click/?url=https%3A//example.com" target="_blank" """,
            """rel="noreferrer"></a></div></div>""",
        ])

        text = """<html><body style="hi">{}</body></html>""".format(EMPTY_ANCHOR_TAG)
        returned_body = email_utils._clean_html_body(None, email, text, "ascii")
        self.assertEqual(returned_body, expected_html) 
Example #21
Source File: test_email.py    From Inboxen with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_attachments_get(self):
        part = self.email.parts.get()
        url = urls.reverse("email-attachment", kwargs={"attachmentid": part.id})
        response = self.client.get(url)
        self.assertEqual(response.status_code, 200)
        self.assertIn("He l lo ß.jpg", response["Content-Disposition"]) 
Example #22
Source File: test_email.py    From Inboxen with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_attachments_get(self):
        part = self.email.parts.get()
        url = urls.reverse("email-attachment", kwargs={"attachmentid": part.id})
        response = self.client.get(url)
        self.assertEqual(response.status_code, 200)

        part_id = part.id + 1000
        url = urls.reverse("email-attachment", kwargs={"attachmentid": part_id})
        response = self.client.get(url)
        self.assertEqual(response.status_code, 404) 
Example #23
Source File: email.py    From Inboxen with GNU Affero General Public License v3.0 5 votes vote down vote up
def _load_external(self, url):
        """Don't load external resources"""
        return "" 
Example #24
Source File: tests.py    From django-oss-storage with MIT License 5 votes vote down vote up
def test_static_url(self):
        with self.save_file(storage=staticfiles_storage):
            url = staticfiles_storage.url("test.txt")
            logging.info("url: %s", url)
            response = requests.get(url)

            self.assertEqual(response.status_code, 200)
            self.assertEqual(response.content, b"test")
            self.assertEqual(response.headers['Content-Type'], "text/plain") 
Example #25
Source File: tests.py    From django-oss-storage with MIT License 5 votes vote down vote up
def test_url_cn(self):
        objname = to_unicode("本地文件名.txt")
        logging.info("objname: %s", objname)
        data = oss2.compat.to_bytes('我的座右铭')
        with self.save_file(objname, data) as name:
            self.assertEqual(name, objname)
            url = default_storage.url(objname)
            logging.info("url: %s", url)
            response = requests.get(url)
            self.assertEqual(response.status_code, 200)
            self.assertEqual(response.content, data)
            self.assertEqual(response.headers['Content-Type'], "text/plain") 
Example #26
Source File: tests.py    From django-oss-storage with MIT License 5 votes vote down vote up
def test_url(self):
        with self.save_file(name="folder/test?+123.txt"):
            url = default_storage.url("folder/test?+123.txt")
            logging.info("url: %s", url)
            response = requests.get(url)
            self.assertEqual(response.status_code, 200)
            self.assertEqual(response.content, b"test")
            self.assertEqual(response.headers['Content-Type'], "text/plain")

            auth = oss2.Auth(settings.OSS_ACCESS_KEY_ID, settings.OSS_ACCESS_KEY_SECRET)
            bucket = oss2.Bucket(auth, settings.OSS_ENDPOINT, settings.OSS_BUCKET_NAME)
            if bucket.get_bucket_acl().acl == 'private':
                self.assertEqual(url.find('.txt?') > 0, True)
            else:
                self.assertEqual(url.find('.txt?') > 0, False) 
Example #27
Source File: tests.py    From django-oss-storage with MIT License 5 votes vote down vote up
def test_save_big_file(self):
        with self.save_file(content=b"test" * 1000):
            logging.info("content type: %s", default_storage.content_type("test.txt"))
            self.assertEqual(default_storage.open("test.txt").read(), b"test" * 1000)
            self.assertEqual(requests.get(default_storage.url("test.txt")).content, b"test" * 1000) 
Example #28
Source File: tests.py    From django-oss-storage with MIT License 5 votes vote down vote up
def test_save_small_file(self):
        with self.save_file():
            logging.info("content type: %s", default_storage.content_type("test.txt"))
            self.assertEqual(default_storage.open("test.txt").read(), b"test")
            self.assertEqual(requests.get(default_storage.url("test.txt")).content, b"test") 
Example #29
Source File: models.py    From doccano with MIT License 5 votes vote down vote up
def image(self):
        return staticfiles_storage.url('images/cats/speech2text.jpg') 
Example #30
Source File: models.py    From doccano with MIT License 5 votes vote down vote up
def image(self):
        return staticfiles_storage.url('assets/images/cats/seq2seq.jpg')