hc99 commited on
Commit
35b5a81
·
verified ·
1 Parent(s): 5e07a1f

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. testbed/django__django/django/contrib/__init__.py +0 -0
  2. testbed/django__django/django/contrib/sites/__init__.py +0 -0
  3. testbed/django__django/django/contrib/sites/admin.py +8 -0
  4. testbed/django__django/django/contrib/sites/apps.py +17 -0
  5. testbed/django__django/django/contrib/sites/checks.py +14 -0
  6. testbed/django__django/django/contrib/sites/locale/ckb/LC_MESSAGES/django.mo +0 -0
  7. testbed/django__django/django/contrib/sites/locale/ckb/LC_MESSAGES/django.po +36 -0
  8. testbed/django__django/django/contrib/sites/locale/te/LC_MESSAGES/django.mo +0 -0
  9. testbed/django__django/django/contrib/sites/locale/tr/LC_MESSAGES/django.mo +0 -0
  10. testbed/django__django/django/contrib/sites/locale/tr/LC_MESSAGES/django.po +39 -0
  11. testbed/django__django/django/contrib/sites/locale/tt/LC_MESSAGES/django.mo +0 -0
  12. testbed/django__django/django/contrib/sites/locale/udm/LC_MESSAGES/django.mo +0 -0
  13. testbed/django__django/django/contrib/sites/locale/udm/LC_MESSAGES/django.po +35 -0
  14. testbed/django__django/django/contrib/sites/locale/ur/LC_MESSAGES/django.mo +0 -0
  15. testbed/django__django/django/contrib/sites/locale/ur/LC_MESSAGES/django.po +35 -0
  16. testbed/django__django/django/contrib/sites/locale/uz/LC_MESSAGES/django.mo +0 -0
  17. testbed/django__django/django/contrib/sites/locale/uz/LC_MESSAGES/django.po +35 -0
  18. testbed/django__django/django/contrib/sites/locale/vi/LC_MESSAGES/django.mo +0 -0
  19. testbed/django__django/django/contrib/sites/locale/vi/LC_MESSAGES/django.po +38 -0
  20. testbed/django__django/django/contrib/sites/locale/zh_Hans/LC_MESSAGES/django.mo +0 -0
  21. testbed/django__django/django/contrib/sites/locale/zh_Hans/LC_MESSAGES/django.po +37 -0
  22. testbed/django__django/django/contrib/sites/locale/zh_Hant/LC_MESSAGES/django.mo +0 -0
  23. testbed/django__django/django/contrib/sites/locale/zh_Hant/LC_MESSAGES/django.po +39 -0
  24. testbed/django__django/django/contrib/sites/management.py +47 -0
  25. testbed/django__django/django/contrib/sites/managers.py +65 -0
  26. testbed/django__django/django/contrib/sites/middleware.py +12 -0
  27. testbed/django__django/django/contrib/sites/migrations/0001_initial.py +43 -0
  28. testbed/django__django/django/contrib/sites/migrations/0002_alter_domain_unique.py +21 -0
  29. testbed/django__django/django/contrib/sites/migrations/__init__.py +0 -0
  30. testbed/django__django/django/contrib/sites/models.py +120 -0
  31. testbed/django__django/django/contrib/sites/requests.py +20 -0
  32. testbed/django__django/django/contrib/sites/shortcuts.py +18 -0
  33. testbed/django__django/django/contrib/staticfiles/__init__.py +0 -0
  34. testbed/django__django/django/contrib/staticfiles/apps.py +13 -0
  35. testbed/django__django/django/contrib/staticfiles/checks.py +14 -0
  36. testbed/django__django/django/contrib/staticfiles/finders.py +326 -0
  37. testbed/django__django/django/contrib/staticfiles/handlers.py +115 -0
  38. testbed/django__django/django/contrib/staticfiles/management/__init__.py +0 -0
  39. testbed/django__django/django/contrib/staticfiles/management/commands/__init__.py +0 -0
  40. testbed/django__django/django/contrib/staticfiles/management/commands/collectstatic.py +379 -0
  41. testbed/django__django/django/contrib/staticfiles/management/commands/findstatic.py +48 -0
  42. testbed/django__django/django/contrib/staticfiles/management/commands/runserver.py +36 -0
  43. testbed/django__django/django/contrib/staticfiles/storage.py +543 -0
  44. testbed/django__django/django/contrib/staticfiles/testing.py +13 -0
  45. testbed/django__django/django/contrib/staticfiles/urls.py +19 -0
  46. testbed/django__django/django/contrib/staticfiles/utils.py +71 -0
  47. testbed/django__django/django/contrib/staticfiles/views.py +39 -0
  48. testbed/django__django/django/contrib/syndication/__init__.py +0 -0
  49. testbed/django__django/django/contrib/syndication/apps.py +7 -0
  50. testbed/django__django/django/contrib/syndication/views.py +234 -0
testbed/django__django/django/contrib/__init__.py ADDED
File without changes
testbed/django__django/django/contrib/sites/__init__.py ADDED
File without changes
testbed/django__django/django/contrib/sites/admin.py ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ from django.contrib import admin
2
+ from django.contrib.sites.models import Site
3
+
4
+
5
+ @admin.register(Site)
6
+ class SiteAdmin(admin.ModelAdmin):
7
+ list_display = ("domain", "name")
8
+ search_fields = ("domain", "name")
testbed/django__django/django/contrib/sites/apps.py ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from django.apps import AppConfig
2
+ from django.contrib.sites.checks import check_site_id
3
+ from django.core import checks
4
+ from django.db.models.signals import post_migrate
5
+ from django.utils.translation import gettext_lazy as _
6
+
7
+ from .management import create_default_site
8
+
9
+
10
+ class SitesConfig(AppConfig):
11
+ default_auto_field = "django.db.models.AutoField"
12
+ name = "django.contrib.sites"
13
+ verbose_name = _("Sites")
14
+
15
+ def ready(self):
16
+ post_migrate.connect(create_default_site, sender=self)
17
+ checks.register(check_site_id, checks.Tags.sites)
testbed/django__django/django/contrib/sites/checks.py ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from types import NoneType
2
+
3
+ from django.conf import settings
4
+ from django.core.checks import Error
5
+
6
+
7
+ def check_site_id(app_configs, **kwargs):
8
+ if hasattr(settings, "SITE_ID") and not isinstance(
9
+ settings.SITE_ID, (NoneType, int)
10
+ ):
11
+ return [
12
+ Error("The SITE_ID setting must be an integer", id="sites.E101"),
13
+ ]
14
+ return []
testbed/django__django/django/contrib/sites/locale/ckb/LC_MESSAGES/django.mo ADDED
Binary file (843 Bytes). View file
 
testbed/django__django/django/contrib/sites/locale/ckb/LC_MESSAGES/django.po ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is distributed under the same license as the Django package.
2
+ #
3
+ # Translators:
4
+ # kosar tofiq <kosar.belana@gmail.com>, 2020
5
+ msgid ""
6
+ msgstr ""
7
+ "Project-Id-Version: django\n"
8
+ "Report-Msgid-Bugs-To: \n"
9
+ "POT-Creation-Date: 2015-01-17 11:07+0100\n"
10
+ "PO-Revision-Date: 2023-04-24 18:05+0000\n"
11
+ "Last-Translator: kosar tofiq <kosar.belana@gmail.com>, 2020\n"
12
+ "Language-Team: Central Kurdish (http://www.transifex.com/django/django/"
13
+ "language/ckb/)\n"
14
+ "MIME-Version: 1.0\n"
15
+ "Content-Type: text/plain; charset=UTF-8\n"
16
+ "Content-Transfer-Encoding: 8bit\n"
17
+ "Language: ckb\n"
18
+ "Plural-Forms: nplurals=2; plural=(n != 1);\n"
19
+
20
+ msgid "Sites"
21
+ msgstr "ماڵپەڕەکان"
22
+
23
+ msgid "The domain name cannot contain any spaces or tabs."
24
+ msgstr "ناوی دۆمەین نابێت بۆشایی یان تابی تێدابێت."
25
+
26
+ msgid "domain name"
27
+ msgstr "ناوی دۆمەین"
28
+
29
+ msgid "display name"
30
+ msgstr "ناوی پیشاندان"
31
+
32
+ msgid "site"
33
+ msgstr "ماڵپەڕ"
34
+
35
+ msgid "sites"
36
+ msgstr "ماڵپەڕەکان"
testbed/django__django/django/contrib/sites/locale/te/LC_MESSAGES/django.mo ADDED
Binary file (687 Bytes). View file
 
testbed/django__django/django/contrib/sites/locale/tr/LC_MESSAGES/django.mo ADDED
Binary file (758 Bytes). View file
 
testbed/django__django/django/contrib/sites/locale/tr/LC_MESSAGES/django.po ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is distributed under the same license as the Django package.
2
+ #
3
+ # Translators:
4
+ # Ahmet Emre Aladağ <emre.aladag@isik.edu.tr>, 2014
5
+ # BouRock, 2014
6
+ # Caner Başaran <basaran.caner@protonmail.com>, 2013
7
+ # Jannis Leidel <jannis@leidel.info>, 2011
8
+ msgid ""
9
+ msgstr ""
10
+ "Project-Id-Version: django\n"
11
+ "Report-Msgid-Bugs-To: \n"
12
+ "POT-Creation-Date: 2015-01-17 11:07+0100\n"
13
+ "PO-Revision-Date: 2017-09-23 18:54+0000\n"
14
+ "Last-Translator: Jannis Leidel <jannis@leidel.info>\n"
15
+ "Language-Team: Turkish (http://www.transifex.com/django/django/language/"
16
+ "tr/)\n"
17
+ "MIME-Version: 1.0\n"
18
+ "Content-Type: text/plain; charset=UTF-8\n"
19
+ "Content-Transfer-Encoding: 8bit\n"
20
+ "Language: tr\n"
21
+ "Plural-Forms: nplurals=2; plural=(n > 1);\n"
22
+
23
+ msgid "Sites"
24
+ msgstr "Siteler"
25
+
26
+ msgid "The domain name cannot contain any spaces or tabs."
27
+ msgstr "Etki alanı adı, herhangi bir boşluk ya da sekme içeremez."
28
+
29
+ msgid "domain name"
30
+ msgstr "etki alanı adı"
31
+
32
+ msgid "display name"
33
+ msgstr "görünen isim"
34
+
35
+ msgid "site"
36
+ msgstr "site"
37
+
38
+ msgid "sites"
39
+ msgstr "siteler"
testbed/django__django/django/contrib/sites/locale/tt/LC_MESSAGES/django.mo ADDED
Binary file (706 Bytes). View file
 
testbed/django__django/django/contrib/sites/locale/udm/LC_MESSAGES/django.mo ADDED
Binary file (462 Bytes). View file
 
testbed/django__django/django/contrib/sites/locale/udm/LC_MESSAGES/django.po ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is distributed under the same license as the Django package.
2
+ #
3
+ # Translators:
4
+ msgid ""
5
+ msgstr ""
6
+ "Project-Id-Version: django\n"
7
+ "Report-Msgid-Bugs-To: \n"
8
+ "POT-Creation-Date: 2015-01-17 11:07+0100\n"
9
+ "PO-Revision-Date: 2014-10-05 20:13+0000\n"
10
+ "Last-Translator: Jannis Leidel <jannis@leidel.info>\n"
11
+ "Language-Team: Udmurt (http://www.transifex.com/projects/p/django/language/"
12
+ "udm/)\n"
13
+ "MIME-Version: 1.0\n"
14
+ "Content-Type: text/plain; charset=UTF-8\n"
15
+ "Content-Transfer-Encoding: 8bit\n"
16
+ "Language: udm\n"
17
+ "Plural-Forms: nplurals=1; plural=0;\n"
18
+
19
+ msgid "Sites"
20
+ msgstr ""
21
+
22
+ msgid "The domain name cannot contain any spaces or tabs."
23
+ msgstr ""
24
+
25
+ msgid "domain name"
26
+ msgstr ""
27
+
28
+ msgid "display name"
29
+ msgstr ""
30
+
31
+ msgid "site"
32
+ msgstr ""
33
+
34
+ msgid "sites"
35
+ msgstr ""
testbed/django__django/django/contrib/sites/locale/ur/LC_MESSAGES/django.mo ADDED
Binary file (654 Bytes). View file
 
testbed/django__django/django/contrib/sites/locale/ur/LC_MESSAGES/django.po ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is distributed under the same license as the Django package.
2
+ #
3
+ # Translators:
4
+ # Mansoorulhaq Mansoor <mnsrknp@gmail.com>, 2011
5
+ msgid ""
6
+ msgstr ""
7
+ "Project-Id-Version: django\n"
8
+ "Report-Msgid-Bugs-To: \n"
9
+ "POT-Creation-Date: 2015-01-17 11:07+0100\n"
10
+ "PO-Revision-Date: 2017-09-19 16:40+0000\n"
11
+ "Last-Translator: Jannis Leidel <jannis@leidel.info>\n"
12
+ "Language-Team: Urdu (http://www.transifex.com/django/django/language/ur/)\n"
13
+ "MIME-Version: 1.0\n"
14
+ "Content-Type: text/plain; charset=UTF-8\n"
15
+ "Content-Transfer-Encoding: 8bit\n"
16
+ "Language: ur\n"
17
+ "Plural-Forms: nplurals=2; plural=(n != 1);\n"
18
+
19
+ msgid "Sites"
20
+ msgstr ""
21
+
22
+ msgid "The domain name cannot contain any spaces or tabs."
23
+ msgstr ""
24
+
25
+ msgid "domain name"
26
+ msgstr "ڈومین کا نام"
27
+
28
+ msgid "display name"
29
+ msgstr "ظاھر ھونے والا نام"
30
+
31
+ msgid "site"
32
+ msgstr "سائٹ"
33
+
34
+ msgid "sites"
35
+ msgstr "سائٹس"
testbed/django__django/django/contrib/sites/locale/uz/LC_MESSAGES/django.mo ADDED
Binary file (799 Bytes). View file
 
testbed/django__django/django/contrib/sites/locale/uz/LC_MESSAGES/django.po ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is distributed under the same license as the Django package.
2
+ #
3
+ # Translators:
4
+ # Nuruddin Iminokhunov <nuruddin.iminohunov@gmail.com>, 2016
5
+ msgid ""
6
+ msgstr ""
7
+ "Project-Id-Version: django\n"
8
+ "Report-Msgid-Bugs-To: \n"
9
+ "POT-Creation-Date: 2015-01-17 11:07+0100\n"
10
+ "PO-Revision-Date: 2017-09-23 01:18+0000\n"
11
+ "Last-Translator: Nuruddin Iminokhunov <nuruddin.iminohunov@gmail.com>\n"
12
+ "Language-Team: Uzbek (http://www.transifex.com/django/django/language/uz/)\n"
13
+ "MIME-Version: 1.0\n"
14
+ "Content-Type: text/plain; charset=UTF-8\n"
15
+ "Content-Transfer-Encoding: 8bit\n"
16
+ "Language: uz\n"
17
+ "Plural-Forms: nplurals=1; plural=0;\n"
18
+
19
+ msgid "Sites"
20
+ msgstr "Saytlar"
21
+
22
+ msgid "The domain name cannot contain any spaces or tabs."
23
+ msgstr "Domen ismi tab`lar va bo'shliqlarsiz bo'lishi kerak"
24
+
25
+ msgid "domain name"
26
+ msgstr "domen nomi"
27
+
28
+ msgid "display name"
29
+ msgstr "ko'rsatiladigan ismi"
30
+
31
+ msgid "site"
32
+ msgstr "sayt"
33
+
34
+ msgid "sites"
35
+ msgstr "saytlar"
testbed/django__django/django/contrib/sites/locale/vi/LC_MESSAGES/django.mo ADDED
Binary file (762 Bytes). View file
 
testbed/django__django/django/contrib/sites/locale/vi/LC_MESSAGES/django.po ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is distributed under the same license as the Django package.
2
+ #
3
+ # Translators:
4
+ # Jannis Leidel <jannis@leidel.info>, 2011
5
+ # Thanh Le Viet <lethanhx2k@gmail.com>, 2013
6
+ # Tran <hongdiepkien@gmail.com>, 2011
7
+ msgid ""
8
+ msgstr ""
9
+ "Project-Id-Version: django\n"
10
+ "Report-Msgid-Bugs-To: \n"
11
+ "POT-Creation-Date: 2015-01-17 11:07+0100\n"
12
+ "PO-Revision-Date: 2017-09-23 18:54+0000\n"
13
+ "Last-Translator: Tran Van <vantxm@yahoo.co.uk>\n"
14
+ "Language-Team: Vietnamese (http://www.transifex.com/django/django/language/"
15
+ "vi/)\n"
16
+ "MIME-Version: 1.0\n"
17
+ "Content-Type: text/plain; charset=UTF-8\n"
18
+ "Content-Transfer-Encoding: 8bit\n"
19
+ "Language: vi\n"
20
+ "Plural-Forms: nplurals=1; plural=0;\n"
21
+
22
+ msgid "Sites"
23
+ msgstr ""
24
+
25
+ msgid "The domain name cannot contain any spaces or tabs."
26
+ msgstr "Tên miền không gồm kí tự trống hoặc tab"
27
+
28
+ msgid "domain name"
29
+ msgstr "Tên miền"
30
+
31
+ msgid "display name"
32
+ msgstr "Tên hiển thị"
33
+
34
+ msgid "site"
35
+ msgstr "trang web"
36
+
37
+ msgid "sites"
38
+ msgstr "các trang web"
testbed/django__django/django/contrib/sites/locale/zh_Hans/LC_MESSAGES/django.mo ADDED
Binary file (779 Bytes). View file
 
testbed/django__django/django/contrib/sites/locale/zh_Hans/LC_MESSAGES/django.po ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is distributed under the same license as the Django package.
2
+ #
3
+ # Translators:
4
+ # Jannis Leidel <jannis@leidel.info>, 2011
5
+ # Ronald White <ouyanghongyu@gmail.com>, 2014
6
+ msgid ""
7
+ msgstr ""
8
+ "Project-Id-Version: django\n"
9
+ "Report-Msgid-Bugs-To: \n"
10
+ "POT-Creation-Date: 2015-01-17 11:07+0100\n"
11
+ "PO-Revision-Date: 2017-09-19 16:40+0000\n"
12
+ "Last-Translator: Jannis Leidel <jannis@leidel.info>\n"
13
+ "Language-Team: Chinese (China) (http://www.transifex.com/django/django/"
14
+ "language/zh_CN/)\n"
15
+ "MIME-Version: 1.0\n"
16
+ "Content-Type: text/plain; charset=UTF-8\n"
17
+ "Content-Transfer-Encoding: 8bit\n"
18
+ "Language: zh_CN\n"
19
+ "Plural-Forms: nplurals=1; plural=0;\n"
20
+
21
+ msgid "Sites"
22
+ msgstr "站点"
23
+
24
+ msgid "The domain name cannot contain any spaces or tabs."
25
+ msgstr "域名不能包含任何空格或制表符。"
26
+
27
+ msgid "domain name"
28
+ msgstr "域名"
29
+
30
+ msgid "display name"
31
+ msgstr "显示名称"
32
+
33
+ msgid "site"
34
+ msgstr "站点"
35
+
36
+ msgid "sites"
37
+ msgstr "站点"
testbed/django__django/django/contrib/sites/locale/zh_Hant/LC_MESSAGES/django.mo ADDED
Binary file (790 Bytes). View file
 
testbed/django__django/django/contrib/sites/locale/zh_Hant/LC_MESSAGES/django.po ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is distributed under the same license as the Django package.
2
+ #
3
+ # Translators:
4
+ # Chen Chun-Chia <ccc.larc@gmail.com>, 2015
5
+ # Jannis Leidel <jannis@leidel.info>, 2011
6
+ # mail6543210 <mail6543210@yahoo.com.tw>, 2013
7
+ # Tzu-ping Chung <uranusjr@gmail.com>, 2016
8
+ msgid ""
9
+ msgstr ""
10
+ "Project-Id-Version: django\n"
11
+ "Report-Msgid-Bugs-To: \n"
12
+ "POT-Creation-Date: 2015-01-17 11:07+0100\n"
13
+ "PO-Revision-Date: 2017-09-19 16:40+0000\n"
14
+ "Last-Translator: Tzu-ping Chung <uranusjr@gmail.com>\n"
15
+ "Language-Team: Chinese (Taiwan) (http://www.transifex.com/django/django/"
16
+ "language/zh_TW/)\n"
17
+ "MIME-Version: 1.0\n"
18
+ "Content-Type: text/plain; charset=UTF-8\n"
19
+ "Content-Transfer-Encoding: 8bit\n"
20
+ "Language: zh_TW\n"
21
+ "Plural-Forms: nplurals=1; plural=0;\n"
22
+
23
+ msgid "Sites"
24
+ msgstr "網站"
25
+
26
+ msgid "The domain name cannot contain any spaces or tabs."
27
+ msgstr "網域名稱不能包含空格或定位字元。"
28
+
29
+ msgid "domain name"
30
+ msgstr "網域名稱"
31
+
32
+ msgid "display name"
33
+ msgstr "顯示名稱"
34
+
35
+ msgid "site"
36
+ msgstr "網站"
37
+
38
+ msgid "sites"
39
+ msgstr "網站"
testbed/django__django/django/contrib/sites/management.py ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Creates the default Site object.
3
+ """
4
+
5
+ from django.apps import apps as global_apps
6
+ from django.conf import settings
7
+ from django.core.management.color import no_style
8
+ from django.db import DEFAULT_DB_ALIAS, connections, router
9
+
10
+
11
+ def create_default_site(
12
+ app_config,
13
+ verbosity=2,
14
+ interactive=True,
15
+ using=DEFAULT_DB_ALIAS,
16
+ apps=global_apps,
17
+ **kwargs,
18
+ ):
19
+ try:
20
+ Site = apps.get_model("sites", "Site")
21
+ except LookupError:
22
+ return
23
+
24
+ if not router.allow_migrate_model(using, Site):
25
+ return
26
+
27
+ if not Site.objects.using(using).exists():
28
+ # The default settings set SITE_ID = 1, and some tests in Django's test
29
+ # suite rely on this value. However, if database sequences are reused
30
+ # (e.g. in the test suite after flush/syncdb), it isn't guaranteed that
31
+ # the next id will be 1, so we coerce it. See #15573 and #16353. This
32
+ # can also crop up outside of tests - see #15346.
33
+ if verbosity >= 2:
34
+ print("Creating example.com Site object")
35
+ Site(
36
+ pk=getattr(settings, "SITE_ID", 1), domain="example.com", name="example.com"
37
+ ).save(using=using)
38
+
39
+ # We set an explicit pk instead of relying on auto-incrementation,
40
+ # so we need to reset the database sequence. See #17415.
41
+ sequence_sql = connections[using].ops.sequence_reset_sql(no_style(), [Site])
42
+ if sequence_sql:
43
+ if verbosity >= 2:
44
+ print("Resetting sequence")
45
+ with connections[using].cursor() as cursor:
46
+ for command in sequence_sql:
47
+ cursor.execute(command)
testbed/django__django/django/contrib/sites/managers.py ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from django.conf import settings
2
+ from django.core import checks
3
+ from django.core.exceptions import FieldDoesNotExist
4
+ from django.db import models
5
+
6
+
7
+ class CurrentSiteManager(models.Manager):
8
+ "Use this to limit objects to those associated with the current site."
9
+
10
+ use_in_migrations = True
11
+
12
+ def __init__(self, field_name=None):
13
+ super().__init__()
14
+ self.__field_name = field_name
15
+
16
+ def check(self, **kwargs):
17
+ errors = super().check(**kwargs)
18
+ errors.extend(self._check_field_name())
19
+ return errors
20
+
21
+ def _check_field_name(self):
22
+ field_name = self._get_field_name()
23
+ try:
24
+ field = self.model._meta.get_field(field_name)
25
+ except FieldDoesNotExist:
26
+ return [
27
+ checks.Error(
28
+ "CurrentSiteManager could not find a field named '%s'."
29
+ % field_name,
30
+ obj=self,
31
+ id="sites.E001",
32
+ )
33
+ ]
34
+
35
+ if not field.many_to_many and not isinstance(field, (models.ForeignKey)):
36
+ return [
37
+ checks.Error(
38
+ "CurrentSiteManager cannot use '%s.%s' as it is not a foreign key "
39
+ "or a many-to-many field."
40
+ % (self.model._meta.object_name, field_name),
41
+ obj=self,
42
+ id="sites.E002",
43
+ )
44
+ ]
45
+
46
+ return []
47
+
48
+ def _get_field_name(self):
49
+ """Return self.__field_name or 'site' or 'sites'."""
50
+
51
+ if not self.__field_name:
52
+ try:
53
+ self.model._meta.get_field("site")
54
+ except FieldDoesNotExist:
55
+ self.__field_name = "sites"
56
+ else:
57
+ self.__field_name = "site"
58
+ return self.__field_name
59
+
60
+ def get_queryset(self):
61
+ return (
62
+ super()
63
+ .get_queryset()
64
+ .filter(**{self._get_field_name() + "__id": settings.SITE_ID})
65
+ )
testbed/django__django/django/contrib/sites/middleware.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from django.utils.deprecation import MiddlewareMixin
2
+
3
+ from .shortcuts import get_current_site
4
+
5
+
6
+ class CurrentSiteMiddleware(MiddlewareMixin):
7
+ """
8
+ Middleware that sets `site` attribute to request object.
9
+ """
10
+
11
+ def process_request(self, request):
12
+ request.site = get_current_site(request)
testbed/django__django/django/contrib/sites/migrations/0001_initial.py ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import django.contrib.sites.models
2
+ from django.contrib.sites.models import _simple_domain_name_validator
3
+ from django.db import migrations, models
4
+
5
+
6
+ class Migration(migrations.Migration):
7
+ dependencies = []
8
+
9
+ operations = [
10
+ migrations.CreateModel(
11
+ name="Site",
12
+ fields=[
13
+ (
14
+ "id",
15
+ models.AutoField(
16
+ verbose_name="ID",
17
+ serialize=False,
18
+ auto_created=True,
19
+ primary_key=True,
20
+ ),
21
+ ),
22
+ (
23
+ "domain",
24
+ models.CharField(
25
+ max_length=100,
26
+ verbose_name="domain name",
27
+ validators=[_simple_domain_name_validator],
28
+ ),
29
+ ),
30
+ ("name", models.CharField(max_length=50, verbose_name="display name")),
31
+ ],
32
+ options={
33
+ "ordering": ["domain"],
34
+ "db_table": "django_site",
35
+ "verbose_name": "site",
36
+ "verbose_name_plural": "sites",
37
+ },
38
+ bases=(models.Model,),
39
+ managers=[
40
+ ("objects", django.contrib.sites.models.SiteManager()),
41
+ ],
42
+ ),
43
+ ]
testbed/django__django/django/contrib/sites/migrations/0002_alter_domain_unique.py ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import django.contrib.sites.models
2
+ from django.db import migrations, models
3
+
4
+
5
+ class Migration(migrations.Migration):
6
+ dependencies = [
7
+ ("sites", "0001_initial"),
8
+ ]
9
+
10
+ operations = [
11
+ migrations.AlterField(
12
+ model_name="site",
13
+ name="domain",
14
+ field=models.CharField(
15
+ max_length=100,
16
+ unique=True,
17
+ validators=[django.contrib.sites.models._simple_domain_name_validator],
18
+ verbose_name="domain name",
19
+ ),
20
+ ),
21
+ ]
testbed/django__django/django/contrib/sites/migrations/__init__.py ADDED
File without changes
testbed/django__django/django/contrib/sites/models.py ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import string
2
+
3
+ from django.core.exceptions import ImproperlyConfigured, ValidationError
4
+ from django.db import models
5
+ from django.db.models.signals import pre_delete, pre_save
6
+ from django.http.request import split_domain_port
7
+ from django.utils.translation import gettext_lazy as _
8
+
9
+ SITE_CACHE = {}
10
+
11
+
12
+ def _simple_domain_name_validator(value):
13
+ """
14
+ Validate that the given value contains no whitespaces to prevent common
15
+ typos.
16
+ """
17
+ checks = ((s in value) for s in string.whitespace)
18
+ if any(checks):
19
+ raise ValidationError(
20
+ _("The domain name cannot contain any spaces or tabs."),
21
+ code="invalid",
22
+ )
23
+
24
+
25
+ class SiteManager(models.Manager):
26
+ use_in_migrations = True
27
+
28
+ def _get_site_by_id(self, site_id):
29
+ if site_id not in SITE_CACHE:
30
+ site = self.get(pk=site_id)
31
+ SITE_CACHE[site_id] = site
32
+ return SITE_CACHE[site_id]
33
+
34
+ def _get_site_by_request(self, request):
35
+ host = request.get_host()
36
+ try:
37
+ # First attempt to look up the site by host with or without port.
38
+ if host not in SITE_CACHE:
39
+ SITE_CACHE[host] = self.get(domain__iexact=host)
40
+ return SITE_CACHE[host]
41
+ except Site.DoesNotExist:
42
+ # Fallback to looking up site after stripping port from the host.
43
+ domain, port = split_domain_port(host)
44
+ if domain not in SITE_CACHE:
45
+ SITE_CACHE[domain] = self.get(domain__iexact=domain)
46
+ return SITE_CACHE[domain]
47
+
48
+ def get_current(self, request=None):
49
+ """
50
+ Return the current Site based on the SITE_ID in the project's settings.
51
+ If SITE_ID isn't defined, return the site with domain matching
52
+ request.get_host(). The ``Site`` object is cached the first time it's
53
+ retrieved from the database.
54
+ """
55
+ from django.conf import settings
56
+
57
+ if getattr(settings, "SITE_ID", ""):
58
+ site_id = settings.SITE_ID
59
+ return self._get_site_by_id(site_id)
60
+ elif request:
61
+ return self._get_site_by_request(request)
62
+
63
+ raise ImproperlyConfigured(
64
+ 'You\'re using the Django "sites framework" without having '
65
+ "set the SITE_ID setting. Create a site in your database and "
66
+ "set the SITE_ID setting or pass a request to "
67
+ "Site.objects.get_current() to fix this error."
68
+ )
69
+
70
+ def clear_cache(self):
71
+ """Clear the ``Site`` object cache."""
72
+ global SITE_CACHE
73
+ SITE_CACHE = {}
74
+
75
+ def get_by_natural_key(self, domain):
76
+ return self.get(domain=domain)
77
+
78
+
79
+ class Site(models.Model):
80
+ domain = models.CharField(
81
+ _("domain name"),
82
+ max_length=100,
83
+ validators=[_simple_domain_name_validator],
84
+ unique=True,
85
+ )
86
+ name = models.CharField(_("display name"), max_length=50)
87
+
88
+ objects = SiteManager()
89
+
90
+ class Meta:
91
+ db_table = "django_site"
92
+ verbose_name = _("site")
93
+ verbose_name_plural = _("sites")
94
+ ordering = ["domain"]
95
+
96
+ def __str__(self):
97
+ return self.domain
98
+
99
+ def natural_key(self):
100
+ return (self.domain,)
101
+
102
+
103
+ def clear_site_cache(sender, **kwargs):
104
+ """
105
+ Clear the cache (if primed) each time a site is saved or deleted.
106
+ """
107
+ instance = kwargs["instance"]
108
+ using = kwargs["using"]
109
+ try:
110
+ del SITE_CACHE[instance.pk]
111
+ except KeyError:
112
+ pass
113
+ try:
114
+ del SITE_CACHE[Site.objects.using(using).get(pk=instance.pk).domain]
115
+ except (KeyError, Site.DoesNotExist):
116
+ pass
117
+
118
+
119
+ pre_save.connect(clear_site_cache, sender=Site)
120
+ pre_delete.connect(clear_site_cache, sender=Site)
testbed/django__django/django/contrib/sites/requests.py ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ class RequestSite:
2
+ """
3
+ A class that shares the primary interface of Site (i.e., it has ``domain``
4
+ and ``name`` attributes) but gets its data from an HttpRequest object
5
+ rather than from a database.
6
+
7
+ The save() and delete() methods raise NotImplementedError.
8
+ """
9
+
10
+ def __init__(self, request):
11
+ self.domain = self.name = request.get_host()
12
+
13
+ def __str__(self):
14
+ return self.domain
15
+
16
+ def save(self, force_insert=False, force_update=False):
17
+ raise NotImplementedError("RequestSite cannot be saved.")
18
+
19
+ def delete(self):
20
+ raise NotImplementedError("RequestSite cannot be deleted.")
testbed/django__django/django/contrib/sites/shortcuts.py ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from django.apps import apps
2
+
3
+ from .requests import RequestSite
4
+
5
+
6
+ def get_current_site(request):
7
+ """
8
+ Check if contrib.sites is installed and return either the current
9
+ ``Site`` object or a ``RequestSite`` object based on the request.
10
+ """
11
+ # Import is inside the function because its point is to avoid importing the
12
+ # Site models when django.contrib.sites isn't installed.
13
+ if apps.is_installed("django.contrib.sites"):
14
+ from .models import Site
15
+
16
+ return Site.objects.get_current(request)
17
+ else:
18
+ return RequestSite(request)
testbed/django__django/django/contrib/staticfiles/__init__.py ADDED
File without changes
testbed/django__django/django/contrib/staticfiles/apps.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from django.apps import AppConfig
2
+ from django.contrib.staticfiles.checks import check_finders
3
+ from django.core import checks
4
+ from django.utils.translation import gettext_lazy as _
5
+
6
+
7
+ class StaticFilesConfig(AppConfig):
8
+ name = "django.contrib.staticfiles"
9
+ verbose_name = _("Static Files")
10
+ ignore_patterns = ["CVS", ".*", "*~"]
11
+
12
+ def ready(self):
13
+ checks.register(check_finders, checks.Tags.staticfiles)
testbed/django__django/django/contrib/staticfiles/checks.py ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from django.contrib.staticfiles.finders import get_finders
2
+
3
+
4
+ def check_finders(app_configs=None, **kwargs):
5
+ """Check all registered staticfiles finders."""
6
+ errors = []
7
+ for finder in get_finders():
8
+ try:
9
+ finder_errors = finder.check()
10
+ except NotImplementedError:
11
+ pass
12
+ else:
13
+ errors.extend(finder_errors)
14
+ return errors
testbed/django__django/django/contrib/staticfiles/finders.py ADDED
@@ -0,0 +1,326 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import functools
2
+ import os
3
+
4
+ from django.apps import apps
5
+ from django.conf import settings
6
+ from django.contrib.staticfiles import utils
7
+ from django.core.checks import Error, Warning
8
+ from django.core.exceptions import ImproperlyConfigured
9
+ from django.core.files.storage import FileSystemStorage, Storage, default_storage
10
+ from django.utils._os import safe_join
11
+ from django.utils.functional import LazyObject, empty
12
+ from django.utils.module_loading import import_string
13
+
14
+ # To keep track on which directories the finder has searched the static files.
15
+ searched_locations = []
16
+
17
+
18
+ class BaseFinder:
19
+ """
20
+ A base file finder to be used for custom staticfiles finder classes.
21
+ """
22
+
23
+ def check(self, **kwargs):
24
+ raise NotImplementedError(
25
+ "subclasses may provide a check() method to verify the finder is "
26
+ "configured correctly."
27
+ )
28
+
29
+ def find(self, path, all=False):
30
+ """
31
+ Given a relative file path, find an absolute file path.
32
+
33
+ If the ``all`` parameter is False (default) return only the first found
34
+ file path; if True, return a list of all found files paths.
35
+ """
36
+ raise NotImplementedError(
37
+ "subclasses of BaseFinder must provide a find() method"
38
+ )
39
+
40
+ def list(self, ignore_patterns):
41
+ """
42
+ Given an optional list of paths to ignore, return a two item iterable
43
+ consisting of the relative path and storage instance.
44
+ """
45
+ raise NotImplementedError(
46
+ "subclasses of BaseFinder must provide a list() method"
47
+ )
48
+
49
+
50
+ class FileSystemFinder(BaseFinder):
51
+ """
52
+ A static files finder that uses the ``STATICFILES_DIRS`` setting
53
+ to locate files.
54
+ """
55
+
56
+ def __init__(self, app_names=None, *args, **kwargs):
57
+ # List of locations with static files
58
+ self.locations = []
59
+ # Maps dir paths to an appropriate storage instance
60
+ self.storages = {}
61
+ for root in settings.STATICFILES_DIRS:
62
+ if isinstance(root, (list, tuple)):
63
+ prefix, root = root
64
+ else:
65
+ prefix = ""
66
+ if (prefix, root) not in self.locations:
67
+ self.locations.append((prefix, root))
68
+ for prefix, root in self.locations:
69
+ filesystem_storage = FileSystemStorage(location=root)
70
+ filesystem_storage.prefix = prefix
71
+ self.storages[root] = filesystem_storage
72
+ super().__init__(*args, **kwargs)
73
+
74
+ def check(self, **kwargs):
75
+ errors = []
76
+ if not isinstance(settings.STATICFILES_DIRS, (list, tuple)):
77
+ errors.append(
78
+ Error(
79
+ "The STATICFILES_DIRS setting is not a tuple or list.",
80
+ hint="Perhaps you forgot a trailing comma?",
81
+ id="staticfiles.E001",
82
+ )
83
+ )
84
+ return errors
85
+ for root in settings.STATICFILES_DIRS:
86
+ if isinstance(root, (list, tuple)):
87
+ prefix, root = root
88
+ if prefix.endswith("/"):
89
+ errors.append(
90
+ Error(
91
+ "The prefix %r in the STATICFILES_DIRS setting must "
92
+ "not end with a slash." % prefix,
93
+ id="staticfiles.E003",
94
+ )
95
+ )
96
+ if settings.STATIC_ROOT and os.path.abspath(
97
+ settings.STATIC_ROOT
98
+ ) == os.path.abspath(root):
99
+ errors.append(
100
+ Error(
101
+ "The STATICFILES_DIRS setting should not contain the "
102
+ "STATIC_ROOT setting.",
103
+ id="staticfiles.E002",
104
+ )
105
+ )
106
+ if not os.path.isdir(root):
107
+ errors.append(
108
+ Warning(
109
+ f"The directory '{root}' in the STATICFILES_DIRS setting "
110
+ f"does not exist.",
111
+ id="staticfiles.W004",
112
+ )
113
+ )
114
+ return errors
115
+
116
+ def find(self, path, all=False):
117
+ """
118
+ Look for files in the extra locations as defined in STATICFILES_DIRS.
119
+ """
120
+ matches = []
121
+ for prefix, root in self.locations:
122
+ if root not in searched_locations:
123
+ searched_locations.append(root)
124
+ matched_path = self.find_location(root, path, prefix)
125
+ if matched_path:
126
+ if not all:
127
+ return matched_path
128
+ matches.append(matched_path)
129
+ return matches
130
+
131
+ def find_location(self, root, path, prefix=None):
132
+ """
133
+ Find a requested static file in a location and return the found
134
+ absolute path (or ``None`` if no match).
135
+ """
136
+ if prefix:
137
+ prefix = "%s%s" % (prefix, os.sep)
138
+ if not path.startswith(prefix):
139
+ return None
140
+ path = path.removeprefix(prefix)
141
+ path = safe_join(root, path)
142
+ if os.path.exists(path):
143
+ return path
144
+
145
+ def list(self, ignore_patterns):
146
+ """
147
+ List all files in all locations.
148
+ """
149
+ for prefix, root in self.locations:
150
+ # Skip nonexistent directories.
151
+ if os.path.isdir(root):
152
+ storage = self.storages[root]
153
+ for path in utils.get_files(storage, ignore_patterns):
154
+ yield path, storage
155
+
156
+
157
+ class AppDirectoriesFinder(BaseFinder):
158
+ """
159
+ A static files finder that looks in the directory of each app as
160
+ specified in the source_dir attribute.
161
+ """
162
+
163
+ storage_class = FileSystemStorage
164
+ source_dir = "static"
165
+
166
+ def __init__(self, app_names=None, *args, **kwargs):
167
+ # The list of apps that are handled
168
+ self.apps = []
169
+ # Mapping of app names to storage instances
170
+ self.storages = {}
171
+ app_configs = apps.get_app_configs()
172
+ if app_names:
173
+ app_names = set(app_names)
174
+ app_configs = [ac for ac in app_configs if ac.name in app_names]
175
+ for app_config in app_configs:
176
+ app_storage = self.storage_class(
177
+ os.path.join(app_config.path, self.source_dir)
178
+ )
179
+ if os.path.isdir(app_storage.location):
180
+ self.storages[app_config.name] = app_storage
181
+ if app_config.name not in self.apps:
182
+ self.apps.append(app_config.name)
183
+ super().__init__(*args, **kwargs)
184
+
185
+ def list(self, ignore_patterns):
186
+ """
187
+ List all files in all app storages.
188
+ """
189
+ for storage in self.storages.values():
190
+ if storage.exists(""): # check if storage location exists
191
+ for path in utils.get_files(storage, ignore_patterns):
192
+ yield path, storage
193
+
194
+ def find(self, path, all=False):
195
+ """
196
+ Look for files in the app directories.
197
+ """
198
+ matches = []
199
+ for app in self.apps:
200
+ app_location = self.storages[app].location
201
+ if app_location not in searched_locations:
202
+ searched_locations.append(app_location)
203
+ match = self.find_in_app(app, path)
204
+ if match:
205
+ if not all:
206
+ return match
207
+ matches.append(match)
208
+ return matches
209
+
210
+ def find_in_app(self, app, path):
211
+ """
212
+ Find a requested static file in an app's static locations.
213
+ """
214
+ storage = self.storages.get(app)
215
+ # Only try to find a file if the source dir actually exists.
216
+ if storage and storage.exists(path):
217
+ matched_path = storage.path(path)
218
+ if matched_path:
219
+ return matched_path
220
+
221
+
222
+ class BaseStorageFinder(BaseFinder):
223
+ """
224
+ A base static files finder to be used to extended
225
+ with an own storage class.
226
+ """
227
+
228
+ storage = None
229
+
230
+ def __init__(self, storage=None, *args, **kwargs):
231
+ if storage is not None:
232
+ self.storage = storage
233
+ if self.storage is None:
234
+ raise ImproperlyConfigured(
235
+ "The staticfiles storage finder %r "
236
+ "doesn't have a storage class "
237
+ "assigned." % self.__class__
238
+ )
239
+ # Make sure we have a storage instance here.
240
+ if not isinstance(self.storage, (Storage, LazyObject)):
241
+ self.storage = self.storage()
242
+ super().__init__(*args, **kwargs)
243
+
244
+ def find(self, path, all=False):
245
+ """
246
+ Look for files in the default file storage, if it's local.
247
+ """
248
+ try:
249
+ self.storage.path("")
250
+ except NotImplementedError:
251
+ pass
252
+ else:
253
+ if self.storage.location not in searched_locations:
254
+ searched_locations.append(self.storage.location)
255
+ if self.storage.exists(path):
256
+ match = self.storage.path(path)
257
+ if all:
258
+ match = [match]
259
+ return match
260
+ return []
261
+
262
+ def list(self, ignore_patterns):
263
+ """
264
+ List all files of the storage.
265
+ """
266
+ for path in utils.get_files(self.storage, ignore_patterns):
267
+ yield path, self.storage
268
+
269
+
270
+ class DefaultStorageFinder(BaseStorageFinder):
271
+ """
272
+ A static files finder that uses the default storage backend.
273
+ """
274
+
275
+ storage = default_storage
276
+
277
+ def __init__(self, *args, **kwargs):
278
+ super().__init__(*args, **kwargs)
279
+ base_location = getattr(self.storage, "base_location", empty)
280
+ if not base_location:
281
+ raise ImproperlyConfigured(
282
+ "The storage backend of the "
283
+ "staticfiles finder %r doesn't have "
284
+ "a valid location." % self.__class__
285
+ )
286
+
287
+
288
+ def find(path, all=False):
289
+ """
290
+ Find a static file with the given path using all enabled finders.
291
+
292
+ If ``all`` is ``False`` (default), return the first matching
293
+ absolute path (or ``None`` if no match). Otherwise return a list.
294
+ """
295
+ searched_locations[:] = []
296
+ matches = []
297
+ for finder in get_finders():
298
+ result = finder.find(path, all=all)
299
+ if not all and result:
300
+ return result
301
+ if not isinstance(result, (list, tuple)):
302
+ result = [result]
303
+ matches.extend(result)
304
+ if matches:
305
+ return matches
306
+ # No match.
307
+ return [] if all else None
308
+
309
+
310
+ def get_finders():
311
+ for finder_path in settings.STATICFILES_FINDERS:
312
+ yield get_finder(finder_path)
313
+
314
+
315
+ @functools.cache
316
+ def get_finder(import_path):
317
+ """
318
+ Import the staticfiles finder class described by import_path, where
319
+ import_path is the full Python path to the class.
320
+ """
321
+ Finder = import_string(import_path)
322
+ if not issubclass(Finder, BaseFinder):
323
+ raise ImproperlyConfigured(
324
+ 'Finder "%s" is not a subclass of "%s"' % (Finder, BaseFinder)
325
+ )
326
+ return Finder()
testbed/django__django/django/contrib/staticfiles/handlers.py ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from urllib.parse import urlparse
2
+ from urllib.request import url2pathname
3
+
4
+ from asgiref.sync import sync_to_async
5
+
6
+ from django.conf import settings
7
+ from django.contrib.staticfiles import utils
8
+ from django.contrib.staticfiles.views import serve
9
+ from django.core.handlers.asgi import ASGIHandler
10
+ from django.core.handlers.exception import response_for_exception
11
+ from django.core.handlers.wsgi import WSGIHandler, get_path_info
12
+ from django.http import Http404
13
+
14
+
15
+ class StaticFilesHandlerMixin:
16
+ """
17
+ Common methods used by WSGI and ASGI handlers.
18
+ """
19
+
20
+ # May be used to differentiate between handler types (e.g. in a
21
+ # request_finished signal)
22
+ handles_files = True
23
+
24
+ def load_middleware(self):
25
+ # Middleware are already loaded for self.application; no need to reload
26
+ # them for self.
27
+ pass
28
+
29
+ def get_base_url(self):
30
+ utils.check_settings()
31
+ return settings.STATIC_URL
32
+
33
+ def _should_handle(self, path):
34
+ """
35
+ Check if the path should be handled. Ignore the path if:
36
+ * the host is provided as part of the base_url
37
+ * the request's path isn't under the media path (or equal)
38
+ """
39
+ return path.startswith(self.base_url[2]) and not self.base_url[1]
40
+
41
+ def file_path(self, url):
42
+ """
43
+ Return the relative path to the media file on disk for the given URL.
44
+ """
45
+ relative_url = url.removeprefix(self.base_url[2])
46
+ return url2pathname(relative_url)
47
+
48
+ def serve(self, request):
49
+ """Serve the request path."""
50
+ return serve(request, self.file_path(request.path), insecure=True)
51
+
52
+ def get_response(self, request):
53
+ try:
54
+ return self.serve(request)
55
+ except Http404 as e:
56
+ return response_for_exception(request, e)
57
+
58
+ async def get_response_async(self, request):
59
+ try:
60
+ return await sync_to_async(self.serve, thread_sensitive=False)(request)
61
+ except Http404 as e:
62
+ return await sync_to_async(response_for_exception, thread_sensitive=False)(
63
+ request, e
64
+ )
65
+
66
+
67
+ class StaticFilesHandler(StaticFilesHandlerMixin, WSGIHandler):
68
+ """
69
+ WSGI middleware that intercepts calls to the static files directory, as
70
+ defined by the STATIC_URL setting, and serves those files.
71
+ """
72
+
73
+ def __init__(self, application):
74
+ self.application = application
75
+ self.base_url = urlparse(self.get_base_url())
76
+ super().__init__()
77
+
78
+ def __call__(self, environ, start_response):
79
+ if not self._should_handle(get_path_info(environ)):
80
+ return self.application(environ, start_response)
81
+ return super().__call__(environ, start_response)
82
+
83
+
84
+ class ASGIStaticFilesHandler(StaticFilesHandlerMixin, ASGIHandler):
85
+ """
86
+ ASGI application which wraps another and intercepts requests for static
87
+ files, passing them off to Django's static file serving.
88
+ """
89
+
90
+ def __init__(self, application):
91
+ self.application = application
92
+ self.base_url = urlparse(self.get_base_url())
93
+
94
+ async def __call__(self, scope, receive, send):
95
+ # Only even look at HTTP requests
96
+ if scope["type"] == "http" and self._should_handle(scope["path"]):
97
+ # Serve static content
98
+ # (the one thing super() doesn't do is __call__, apparently)
99
+ return await super().__call__(scope, receive, send)
100
+ # Hand off to the main app
101
+ return await self.application(scope, receive, send)
102
+
103
+ async def get_response_async(self, request):
104
+ response = await super().get_response_async(request)
105
+ response._resource_closers.append(request.close)
106
+ # FileResponse is not async compatible.
107
+ if response.streaming and not response.is_async:
108
+ _iterator = response.streaming_content
109
+
110
+ async def awrapper():
111
+ for part in await sync_to_async(list)(_iterator):
112
+ yield part
113
+
114
+ response.streaming_content = awrapper()
115
+ return response
testbed/django__django/django/contrib/staticfiles/management/__init__.py ADDED
File without changes
testbed/django__django/django/contrib/staticfiles/management/commands/__init__.py ADDED
File without changes
testbed/django__django/django/contrib/staticfiles/management/commands/collectstatic.py ADDED
@@ -0,0 +1,379 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ from django.apps import apps
4
+ from django.contrib.staticfiles.finders import get_finders
5
+ from django.contrib.staticfiles.storage import staticfiles_storage
6
+ from django.core.checks import Tags
7
+ from django.core.files.storage import FileSystemStorage
8
+ from django.core.management.base import BaseCommand, CommandError
9
+ from django.core.management.color import no_style
10
+ from django.utils.functional import cached_property
11
+
12
+
13
+ class Command(BaseCommand):
14
+ """
15
+ Copies or symlinks static files from different locations to the
16
+ settings.STATIC_ROOT.
17
+ """
18
+
19
+ help = "Collect static files in a single location."
20
+ requires_system_checks = [Tags.staticfiles]
21
+
22
+ def __init__(self, *args, **kwargs):
23
+ super().__init__(*args, **kwargs)
24
+ self.copied_files = []
25
+ self.symlinked_files = []
26
+ self.unmodified_files = []
27
+ self.post_processed_files = []
28
+ self.storage = staticfiles_storage
29
+ self.style = no_style()
30
+
31
+ @cached_property
32
+ def local(self):
33
+ try:
34
+ self.storage.path("")
35
+ except NotImplementedError:
36
+ return False
37
+ return True
38
+
39
+ def add_arguments(self, parser):
40
+ parser.add_argument(
41
+ "--noinput",
42
+ "--no-input",
43
+ action="store_false",
44
+ dest="interactive",
45
+ help="Do NOT prompt the user for input of any kind.",
46
+ )
47
+ parser.add_argument(
48
+ "--no-post-process",
49
+ action="store_false",
50
+ dest="post_process",
51
+ help="Do NOT post process collected files.",
52
+ )
53
+ parser.add_argument(
54
+ "-i",
55
+ "--ignore",
56
+ action="append",
57
+ default=[],
58
+ dest="ignore_patterns",
59
+ metavar="PATTERN",
60
+ help="Ignore files or directories matching this glob-style "
61
+ "pattern. Use multiple times to ignore more.",
62
+ )
63
+ parser.add_argument(
64
+ "-n",
65
+ "--dry-run",
66
+ action="store_true",
67
+ help="Do everything except modify the filesystem.",
68
+ )
69
+ parser.add_argument(
70
+ "-c",
71
+ "--clear",
72
+ action="store_true",
73
+ help="Clear the existing files using the storage "
74
+ "before trying to copy or link the original file.",
75
+ )
76
+ parser.add_argument(
77
+ "-l",
78
+ "--link",
79
+ action="store_true",
80
+ help="Create a symbolic link to each file instead of copying.",
81
+ )
82
+ parser.add_argument(
83
+ "--no-default-ignore",
84
+ action="store_false",
85
+ dest="use_default_ignore_patterns",
86
+ help=(
87
+ "Don't ignore the common private glob-style patterns (defaults to "
88
+ "'CVS', '.*' and '*~')."
89
+ ),
90
+ )
91
+
92
+ def set_options(self, **options):
93
+ """
94
+ Set instance variables based on an options dict
95
+ """
96
+ self.interactive = options["interactive"]
97
+ self.verbosity = options["verbosity"]
98
+ self.symlink = options["link"]
99
+ self.clear = options["clear"]
100
+ self.dry_run = options["dry_run"]
101
+ ignore_patterns = options["ignore_patterns"]
102
+ if options["use_default_ignore_patterns"]:
103
+ ignore_patterns += apps.get_app_config("staticfiles").ignore_patterns
104
+ self.ignore_patterns = list({os.path.normpath(p) for p in ignore_patterns})
105
+ self.post_process = options["post_process"]
106
+
107
+ def collect(self):
108
+ """
109
+ Perform the bulk of the work of collectstatic.
110
+
111
+ Split off from handle() to facilitate testing.
112
+ """
113
+ if self.symlink and not self.local:
114
+ raise CommandError("Can't symlink to a remote destination.")
115
+
116
+ if self.clear:
117
+ self.clear_dir("")
118
+
119
+ if self.symlink:
120
+ handler = self.link_file
121
+ else:
122
+ handler = self.copy_file
123
+
124
+ found_files = {}
125
+ for finder in get_finders():
126
+ for path, storage in finder.list(self.ignore_patterns):
127
+ # Prefix the relative path if the source storage contains it
128
+ if getattr(storage, "prefix", None):
129
+ prefixed_path = os.path.join(storage.prefix, path)
130
+ else:
131
+ prefixed_path = path
132
+
133
+ if prefixed_path not in found_files:
134
+ found_files[prefixed_path] = (storage, path)
135
+ handler(path, prefixed_path, storage)
136
+ else:
137
+ self.log(
138
+ "Found another file with the destination path '%s'. It "
139
+ "will be ignored since only the first encountered file "
140
+ "is collected. If this is not what you want, make sure "
141
+ "every static file has a unique path." % prefixed_path,
142
+ level=1,
143
+ )
144
+
145
+ # Storage backends may define a post_process() method.
146
+ if self.post_process and hasattr(self.storage, "post_process"):
147
+ processor = self.storage.post_process(found_files, dry_run=self.dry_run)
148
+ for original_path, processed_path, processed in processor:
149
+ if isinstance(processed, Exception):
150
+ self.stderr.write("Post-processing '%s' failed!" % original_path)
151
+ # Add a blank line before the traceback, otherwise it's
152
+ # too easy to miss the relevant part of the error message.
153
+ self.stderr.write()
154
+ raise processed
155
+ if processed:
156
+ self.log(
157
+ "Post-processed '%s' as '%s'" % (original_path, processed_path),
158
+ level=2,
159
+ )
160
+ self.post_processed_files.append(original_path)
161
+ else:
162
+ self.log("Skipped post-processing '%s'" % original_path)
163
+
164
+ return {
165
+ "modified": self.copied_files + self.symlinked_files,
166
+ "unmodified": self.unmodified_files,
167
+ "post_processed": self.post_processed_files,
168
+ }
169
+
170
+ def handle(self, **options):
171
+ self.set_options(**options)
172
+ message = ["\n"]
173
+ if self.dry_run:
174
+ message.append(
175
+ "You have activated the --dry-run option so no files will be "
176
+ "modified.\n\n"
177
+ )
178
+
179
+ message.append(
180
+ "You have requested to collect static files at the destination\n"
181
+ "location as specified in your settings"
182
+ )
183
+
184
+ if self.is_local_storage() and self.storage.location:
185
+ destination_path = self.storage.location
186
+ message.append(":\n\n %s\n\n" % destination_path)
187
+ should_warn_user = self.storage.exists(destination_path) and any(
188
+ self.storage.listdir(destination_path)
189
+ )
190
+ else:
191
+ destination_path = None
192
+ message.append(".\n\n")
193
+ # Destination files existence not checked; play it safe and warn.
194
+ should_warn_user = True
195
+
196
+ if self.interactive and should_warn_user:
197
+ if self.clear:
198
+ message.append("This will DELETE ALL FILES in this location!\n")
199
+ else:
200
+ message.append("This will overwrite existing files!\n")
201
+
202
+ message.append(
203
+ "Are you sure you want to do this?\n\n"
204
+ "Type 'yes' to continue, or 'no' to cancel: "
205
+ )
206
+ if input("".join(message)) != "yes":
207
+ raise CommandError("Collecting static files cancelled.")
208
+
209
+ collected = self.collect()
210
+
211
+ if self.verbosity >= 1:
212
+ modified_count = len(collected["modified"])
213
+ unmodified_count = len(collected["unmodified"])
214
+ post_processed_count = len(collected["post_processed"])
215
+ return (
216
+ "\n%(modified_count)s %(identifier)s %(action)s"
217
+ "%(destination)s%(unmodified)s%(post_processed)s."
218
+ ) % {
219
+ "modified_count": modified_count,
220
+ "identifier": "static file" + ("" if modified_count == 1 else "s"),
221
+ "action": "symlinked" if self.symlink else "copied",
222
+ "destination": (
223
+ " to '%s'" % destination_path if destination_path else ""
224
+ ),
225
+ "unmodified": (
226
+ ", %s unmodified" % unmodified_count
227
+ if collected["unmodified"]
228
+ else ""
229
+ ),
230
+ "post_processed": (
231
+ collected["post_processed"]
232
+ and ", %s post-processed" % post_processed_count
233
+ or ""
234
+ ),
235
+ }
236
+
237
+ def log(self, msg, level=2):
238
+ """
239
+ Small log helper
240
+ """
241
+ if self.verbosity >= level:
242
+ self.stdout.write(msg)
243
+
244
+ def is_local_storage(self):
245
+ return isinstance(self.storage, FileSystemStorage)
246
+
247
+ def clear_dir(self, path):
248
+ """
249
+ Delete the given relative path using the destination storage backend.
250
+ """
251
+ if not self.storage.exists(path):
252
+ return
253
+
254
+ dirs, files = self.storage.listdir(path)
255
+ for f in files:
256
+ fpath = os.path.join(path, f)
257
+ if self.dry_run:
258
+ self.log("Pretending to delete '%s'" % fpath, level=1)
259
+ else:
260
+ self.log("Deleting '%s'" % fpath, level=1)
261
+ try:
262
+ full_path = self.storage.path(fpath)
263
+ except NotImplementedError:
264
+ self.storage.delete(fpath)
265
+ else:
266
+ if not os.path.exists(full_path) and os.path.lexists(full_path):
267
+ # Delete broken symlinks
268
+ os.unlink(full_path)
269
+ else:
270
+ self.storage.delete(fpath)
271
+ for d in dirs:
272
+ self.clear_dir(os.path.join(path, d))
273
+
274
+ def delete_file(self, path, prefixed_path, source_storage):
275
+ """
276
+ Check if the target file should be deleted if it already exists.
277
+ """
278
+ if self.storage.exists(prefixed_path):
279
+ try:
280
+ # When was the target file modified last time?
281
+ target_last_modified = self.storage.get_modified_time(prefixed_path)
282
+ except (OSError, NotImplementedError, AttributeError):
283
+ # The storage doesn't support get_modified_time() or failed
284
+ pass
285
+ else:
286
+ try:
287
+ # When was the source file modified last time?
288
+ source_last_modified = source_storage.get_modified_time(path)
289
+ except (OSError, NotImplementedError, AttributeError):
290
+ pass
291
+ else:
292
+ # The full path of the target file
293
+ if self.local:
294
+ full_path = self.storage.path(prefixed_path)
295
+ # If it's --link mode and the path isn't a link (i.e.
296
+ # the previous collectstatic wasn't with --link) or if
297
+ # it's non-link mode and the path is a link (i.e. the
298
+ # previous collectstatic was with --link), the old
299
+ # links/files must be deleted so it's not safe to skip
300
+ # unmodified files.
301
+ can_skip_unmodified_files = not (
302
+ self.symlink ^ os.path.islink(full_path)
303
+ )
304
+ else:
305
+ # In remote storages, skipping is only based on the
306
+ # modified times since symlinks aren't relevant.
307
+ can_skip_unmodified_files = True
308
+ # Avoid sub-second precision (see #14665, #19540)
309
+ file_is_unmodified = target_last_modified.replace(
310
+ microsecond=0
311
+ ) >= source_last_modified.replace(microsecond=0)
312
+ if file_is_unmodified and can_skip_unmodified_files:
313
+ if prefixed_path not in self.unmodified_files:
314
+ self.unmodified_files.append(prefixed_path)
315
+ self.log("Skipping '%s' (not modified)" % path)
316
+ return False
317
+ # Then delete the existing file if really needed
318
+ if self.dry_run:
319
+ self.log("Pretending to delete '%s'" % path)
320
+ else:
321
+ self.log("Deleting '%s'" % path)
322
+ self.storage.delete(prefixed_path)
323
+ return True
324
+
325
+ def link_file(self, path, prefixed_path, source_storage):
326
+ """
327
+ Attempt to link ``path``
328
+ """
329
+ # Skip this file if it was already copied earlier
330
+ if prefixed_path in self.symlinked_files:
331
+ return self.log("Skipping '%s' (already linked earlier)" % path)
332
+ # Delete the target file if needed or break
333
+ if not self.delete_file(path, prefixed_path, source_storage):
334
+ return
335
+ # The full path of the source file
336
+ source_path = source_storage.path(path)
337
+ # Finally link the file
338
+ if self.dry_run:
339
+ self.log("Pretending to link '%s'" % source_path, level=1)
340
+ else:
341
+ self.log("Linking '%s'" % source_path, level=2)
342
+ full_path = self.storage.path(prefixed_path)
343
+ os.makedirs(os.path.dirname(full_path), exist_ok=True)
344
+ try:
345
+ if os.path.lexists(full_path):
346
+ os.unlink(full_path)
347
+ os.symlink(source_path, full_path)
348
+ except NotImplementedError:
349
+ import platform
350
+
351
+ raise CommandError(
352
+ "Symlinking is not supported in this "
353
+ "platform (%s)." % platform.platform()
354
+ )
355
+ except OSError as e:
356
+ raise CommandError(e)
357
+ if prefixed_path not in self.symlinked_files:
358
+ self.symlinked_files.append(prefixed_path)
359
+
360
+ def copy_file(self, path, prefixed_path, source_storage):
361
+ """
362
+ Attempt to copy ``path`` with storage
363
+ """
364
+ # Skip this file if it was already copied earlier
365
+ if prefixed_path in self.copied_files:
366
+ return self.log("Skipping '%s' (already copied earlier)" % path)
367
+ # Delete the target file if needed or break
368
+ if not self.delete_file(path, prefixed_path, source_storage):
369
+ return
370
+ # The full path of the source file
371
+ source_path = source_storage.path(path)
372
+ # Finally start copying
373
+ if self.dry_run:
374
+ self.log("Pretending to copy '%s'" % source_path, level=1)
375
+ else:
376
+ self.log("Copying '%s'" % source_path, level=2)
377
+ with source_storage.open(path) as source_file:
378
+ self.storage.save(prefixed_path, source_file)
379
+ self.copied_files.append(prefixed_path)
testbed/django__django/django/contrib/staticfiles/management/commands/findstatic.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ from django.contrib.staticfiles import finders
4
+ from django.core.management.base import LabelCommand
5
+
6
+
7
+ class Command(LabelCommand):
8
+ help = "Finds the absolute paths for the given static file(s)."
9
+ label = "staticfile"
10
+
11
+ def add_arguments(self, parser):
12
+ super().add_arguments(parser)
13
+ parser.add_argument(
14
+ "--first",
15
+ action="store_false",
16
+ dest="all",
17
+ help="Only return the first match for each static file.",
18
+ )
19
+
20
+ def handle_label(self, path, **options):
21
+ verbosity = options["verbosity"]
22
+ result = finders.find(path, all=options["all"])
23
+ if verbosity >= 2:
24
+ searched_locations = (
25
+ "\nLooking in the following locations:\n %s"
26
+ % "\n ".join([str(loc) for loc in finders.searched_locations])
27
+ )
28
+ else:
29
+ searched_locations = ""
30
+ if result:
31
+ if not isinstance(result, (list, tuple)):
32
+ result = [result]
33
+ result = (os.path.realpath(path) for path in result)
34
+ if verbosity >= 1:
35
+ file_list = "\n ".join(result)
36
+ return "Found '%s' here:\n %s%s" % (
37
+ path,
38
+ file_list,
39
+ searched_locations,
40
+ )
41
+ else:
42
+ return "\n".join(result)
43
+ else:
44
+ message = ["No matching file found for '%s'." % path]
45
+ if verbosity >= 2:
46
+ message.append(searched_locations)
47
+ if verbosity >= 1:
48
+ self.stderr.write("\n".join(message))
testbed/django__django/django/contrib/staticfiles/management/commands/runserver.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from django.conf import settings
2
+ from django.contrib.staticfiles.handlers import StaticFilesHandler
3
+ from django.core.management.commands.runserver import Command as RunserverCommand
4
+
5
+
6
+ class Command(RunserverCommand):
7
+ help = (
8
+ "Starts a lightweight web server for development and also serves static files."
9
+ )
10
+
11
+ def add_arguments(self, parser):
12
+ super().add_arguments(parser)
13
+ parser.add_argument(
14
+ "--nostatic",
15
+ action="store_false",
16
+ dest="use_static_handler",
17
+ help="Tells Django to NOT automatically serve static files at STATIC_URL.",
18
+ )
19
+ parser.add_argument(
20
+ "--insecure",
21
+ action="store_true",
22
+ dest="insecure_serving",
23
+ help="Allows serving static files even if DEBUG is False.",
24
+ )
25
+
26
+ def get_handler(self, *args, **options):
27
+ """
28
+ Return the static files serving handler wrapping the default handler,
29
+ if static files should be served. Otherwise return the default handler.
30
+ """
31
+ handler = super().get_handler(*args, **options)
32
+ use_static_handler = options["use_static_handler"]
33
+ insecure_serving = options["insecure_serving"]
34
+ if use_static_handler and (settings.DEBUG or insecure_serving):
35
+ return StaticFilesHandler(handler)
36
+ return handler
testbed/django__django/django/contrib/staticfiles/storage.py ADDED
@@ -0,0 +1,543 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import os
3
+ import posixpath
4
+ import re
5
+ from hashlib import md5
6
+ from urllib.parse import unquote, urldefrag, urlsplit, urlunsplit
7
+
8
+ from django.conf import STATICFILES_STORAGE_ALIAS, settings
9
+ from django.contrib.staticfiles.utils import check_settings, matches_patterns
10
+ from django.core.exceptions import ImproperlyConfigured
11
+ from django.core.files.base import ContentFile
12
+ from django.core.files.storage import FileSystemStorage, storages
13
+ from django.utils.functional import LazyObject
14
+
15
+
16
+ class StaticFilesStorage(FileSystemStorage):
17
+ """
18
+ Standard file system storage for static files.
19
+
20
+ The defaults for ``location`` and ``base_url`` are
21
+ ``STATIC_ROOT`` and ``STATIC_URL``.
22
+ """
23
+
24
+ def __init__(self, location=None, base_url=None, *args, **kwargs):
25
+ if location is None:
26
+ location = settings.STATIC_ROOT
27
+ if base_url is None:
28
+ base_url = settings.STATIC_URL
29
+ check_settings(base_url)
30
+ super().__init__(location, base_url, *args, **kwargs)
31
+ # FileSystemStorage fallbacks to MEDIA_ROOT when location
32
+ # is empty, so we restore the empty value.
33
+ if not location:
34
+ self.base_location = None
35
+ self.location = None
36
+
37
+ def path(self, name):
38
+ if not self.location:
39
+ raise ImproperlyConfigured(
40
+ "You're using the staticfiles app "
41
+ "without having set the STATIC_ROOT "
42
+ "setting to a filesystem path."
43
+ )
44
+ return super().path(name)
45
+
46
+
47
+ class HashedFilesMixin:
48
+ default_template = """url("%(url)s")"""
49
+ max_post_process_passes = 5
50
+ support_js_module_import_aggregation = False
51
+ _js_module_import_aggregation_patterns = (
52
+ "*.js",
53
+ (
54
+ (
55
+ (
56
+ r"""(?P<matched>import(?s:(?P<import>[\s\{].*?))"""
57
+ r"""\s*from\s*['"](?P<url>[\.\/].*?)["']\s*;)"""
58
+ ),
59
+ """import%(import)s from "%(url)s";""",
60
+ ),
61
+ (
62
+ (
63
+ r"""(?P<matched>export(?s:(?P<exports>[\s\{].*?))"""
64
+ r"""\s*from\s*["'](?P<url>[\.\/].*?)["']\s*;)"""
65
+ ),
66
+ """export%(exports)s from "%(url)s";""",
67
+ ),
68
+ (
69
+ r"""(?P<matched>import\s*['"](?P<url>[\.\/].*?)["']\s*;)""",
70
+ """import"%(url)s";""",
71
+ ),
72
+ (
73
+ r"""(?P<matched>import\(["'](?P<url>.*?)["']\))""",
74
+ """import("%(url)s")""",
75
+ ),
76
+ ),
77
+ )
78
+ patterns = (
79
+ (
80
+ "*.css",
81
+ (
82
+ r"""(?P<matched>url\(['"]{0,1}\s*(?P<url>.*?)["']{0,1}\))""",
83
+ (
84
+ r"""(?P<matched>@import\s*["']\s*(?P<url>.*?)["'])""",
85
+ """@import url("%(url)s")""",
86
+ ),
87
+ (
88
+ (
89
+ r"(?m)^(?P<matched>/\*#[ \t]"
90
+ r"(?-i:sourceMappingURL)=(?P<url>.*)[ \t]*\*/)$"
91
+ ),
92
+ "/*# sourceMappingURL=%(url)s */",
93
+ ),
94
+ ),
95
+ ),
96
+ (
97
+ "*.js",
98
+ (
99
+ (
100
+ r"(?m)^(?P<matched>//# (?-i:sourceMappingURL)=(?P<url>.*))$",
101
+ "//# sourceMappingURL=%(url)s",
102
+ ),
103
+ ),
104
+ ),
105
+ )
106
+ keep_intermediate_files = True
107
+
108
+ def __init__(self, *args, **kwargs):
109
+ if self.support_js_module_import_aggregation:
110
+ self.patterns += (self._js_module_import_aggregation_patterns,)
111
+ super().__init__(*args, **kwargs)
112
+ self._patterns = {}
113
+ self.hashed_files = {}
114
+ for extension, patterns in self.patterns:
115
+ for pattern in patterns:
116
+ if isinstance(pattern, (tuple, list)):
117
+ pattern, template = pattern
118
+ else:
119
+ template = self.default_template
120
+ compiled = re.compile(pattern, re.IGNORECASE)
121
+ self._patterns.setdefault(extension, []).append((compiled, template))
122
+
123
+ def file_hash(self, name, content=None):
124
+ """
125
+ Return a hash of the file with the given name and optional content.
126
+ """
127
+ if content is None:
128
+ return None
129
+ hasher = md5(usedforsecurity=False)
130
+ for chunk in content.chunks():
131
+ hasher.update(chunk)
132
+ return hasher.hexdigest()[:12]
133
+
134
+ def hashed_name(self, name, content=None, filename=None):
135
+ # `filename` is the name of file to hash if `content` isn't given.
136
+ # `name` is the base name to construct the new hashed filename from.
137
+ parsed_name = urlsplit(unquote(name))
138
+ clean_name = parsed_name.path.strip()
139
+ filename = (filename and urlsplit(unquote(filename)).path.strip()) or clean_name
140
+ opened = content is None
141
+ if opened:
142
+ if not self.exists(filename):
143
+ raise ValueError(
144
+ "The file '%s' could not be found with %r." % (filename, self)
145
+ )
146
+ try:
147
+ content = self.open(filename)
148
+ except OSError:
149
+ # Handle directory paths and fragments
150
+ return name
151
+ try:
152
+ file_hash = self.file_hash(clean_name, content)
153
+ finally:
154
+ if opened:
155
+ content.close()
156
+ path, filename = os.path.split(clean_name)
157
+ root, ext = os.path.splitext(filename)
158
+ file_hash = (".%s" % file_hash) if file_hash else ""
159
+ hashed_name = os.path.join(path, "%s%s%s" % (root, file_hash, ext))
160
+ unparsed_name = list(parsed_name)
161
+ unparsed_name[2] = hashed_name
162
+ # Special casing for a @font-face hack, like url(myfont.eot?#iefix")
163
+ # http://www.fontspring.com/blog/the-new-bulletproof-font-face-syntax
164
+ if "?#" in name and not unparsed_name[3]:
165
+ unparsed_name[2] += "?"
166
+ return urlunsplit(unparsed_name)
167
+
168
+ def _url(self, hashed_name_func, name, force=False, hashed_files=None):
169
+ """
170
+ Return the non-hashed URL in DEBUG mode.
171
+ """
172
+ if settings.DEBUG and not force:
173
+ hashed_name, fragment = name, ""
174
+ else:
175
+ clean_name, fragment = urldefrag(name)
176
+ if urlsplit(clean_name).path.endswith("/"): # don't hash paths
177
+ hashed_name = name
178
+ else:
179
+ args = (clean_name,)
180
+ if hashed_files is not None:
181
+ args += (hashed_files,)
182
+ hashed_name = hashed_name_func(*args)
183
+
184
+ final_url = super().url(hashed_name)
185
+
186
+ # Special casing for a @font-face hack, like url(myfont.eot?#iefix")
187
+ # http://www.fontspring.com/blog/the-new-bulletproof-font-face-syntax
188
+ query_fragment = "?#" in name # [sic!]
189
+ if fragment or query_fragment:
190
+ urlparts = list(urlsplit(final_url))
191
+ if fragment and not urlparts[4]:
192
+ urlparts[4] = fragment
193
+ if query_fragment and not urlparts[3]:
194
+ urlparts[2] += "?"
195
+ final_url = urlunsplit(urlparts)
196
+
197
+ return unquote(final_url)
198
+
199
+ def url(self, name, force=False):
200
+ """
201
+ Return the non-hashed URL in DEBUG mode.
202
+ """
203
+ return self._url(self.stored_name, name, force)
204
+
205
+ def url_converter(self, name, hashed_files, template=None):
206
+ """
207
+ Return the custom URL converter for the given file name.
208
+ """
209
+ if template is None:
210
+ template = self.default_template
211
+
212
+ def converter(matchobj):
213
+ """
214
+ Convert the matched URL to a normalized and hashed URL.
215
+
216
+ This requires figuring out which files the matched URL resolves
217
+ to and calling the url() method of the storage.
218
+ """
219
+ matches = matchobj.groupdict()
220
+ matched = matches["matched"]
221
+ url = matches["url"]
222
+
223
+ # Ignore absolute/protocol-relative and data-uri URLs.
224
+ if re.match(r"^[a-z]+:", url):
225
+ return matched
226
+
227
+ # Ignore absolute URLs that don't point to a static file (dynamic
228
+ # CSS / JS?). Note that STATIC_URL cannot be empty.
229
+ if url.startswith("/") and not url.startswith(settings.STATIC_URL):
230
+ return matched
231
+
232
+ # Strip off the fragment so a path-like fragment won't interfere.
233
+ url_path, fragment = urldefrag(url)
234
+
235
+ # Ignore URLs without a path
236
+ if not url_path:
237
+ return matched
238
+
239
+ if url_path.startswith("/"):
240
+ # Otherwise the condition above would have returned prematurely.
241
+ assert url_path.startswith(settings.STATIC_URL)
242
+ target_name = url_path.removeprefix(settings.STATIC_URL)
243
+ else:
244
+ # We're using the posixpath module to mix paths and URLs conveniently.
245
+ source_name = name if os.sep == "/" else name.replace(os.sep, "/")
246
+ target_name = posixpath.join(posixpath.dirname(source_name), url_path)
247
+
248
+ # Determine the hashed name of the target file with the storage backend.
249
+ hashed_url = self._url(
250
+ self._stored_name,
251
+ unquote(target_name),
252
+ force=True,
253
+ hashed_files=hashed_files,
254
+ )
255
+
256
+ transformed_url = "/".join(
257
+ url_path.split("/")[:-1] + hashed_url.split("/")[-1:]
258
+ )
259
+
260
+ # Restore the fragment that was stripped off earlier.
261
+ if fragment:
262
+ transformed_url += ("?#" if "?#" in url else "#") + fragment
263
+
264
+ # Return the hashed version to the file
265
+ matches["url"] = unquote(transformed_url)
266
+ return template % matches
267
+
268
+ return converter
269
+
270
+ def post_process(self, paths, dry_run=False, **options):
271
+ """
272
+ Post process the given dictionary of files (called from collectstatic).
273
+
274
+ Processing is actually two separate operations:
275
+
276
+ 1. renaming files to include a hash of their content for cache-busting,
277
+ and copying those files to the target storage.
278
+ 2. adjusting files which contain references to other files so they
279
+ refer to the cache-busting filenames.
280
+
281
+ If either of these are performed on a file, then that file is considered
282
+ post-processed.
283
+ """
284
+ # don't even dare to process the files if we're in dry run mode
285
+ if dry_run:
286
+ return
287
+
288
+ # where to store the new paths
289
+ hashed_files = {}
290
+
291
+ # build a list of adjustable files
292
+ adjustable_paths = [
293
+ path for path in paths if matches_patterns(path, self._patterns)
294
+ ]
295
+
296
+ # Adjustable files to yield at end, keyed by the original path.
297
+ processed_adjustable_paths = {}
298
+
299
+ # Do a single pass first. Post-process all files once, yielding not
300
+ # adjustable files and exceptions, and collecting adjustable files.
301
+ for name, hashed_name, processed, _ in self._post_process(
302
+ paths, adjustable_paths, hashed_files
303
+ ):
304
+ if name not in adjustable_paths or isinstance(processed, Exception):
305
+ yield name, hashed_name, processed
306
+ else:
307
+ processed_adjustable_paths[name] = (name, hashed_name, processed)
308
+
309
+ paths = {path: paths[path] for path in adjustable_paths}
310
+ substitutions = False
311
+
312
+ for i in range(self.max_post_process_passes):
313
+ substitutions = False
314
+ for name, hashed_name, processed, subst in self._post_process(
315
+ paths, adjustable_paths, hashed_files
316
+ ):
317
+ # Overwrite since hashed_name may be newer.
318
+ processed_adjustable_paths[name] = (name, hashed_name, processed)
319
+ substitutions = substitutions or subst
320
+
321
+ if not substitutions:
322
+ break
323
+
324
+ if substitutions:
325
+ yield "All", None, RuntimeError("Max post-process passes exceeded.")
326
+
327
+ # Store the processed paths
328
+ self.hashed_files.update(hashed_files)
329
+
330
+ # Yield adjustable files with final, hashed name.
331
+ yield from processed_adjustable_paths.values()
332
+
333
+ def _post_process(self, paths, adjustable_paths, hashed_files):
334
+ # Sort the files by directory level
335
+ def path_level(name):
336
+ return len(name.split(os.sep))
337
+
338
+ for name in sorted(paths, key=path_level, reverse=True):
339
+ substitutions = True
340
+ # use the original, local file, not the copied-but-unprocessed
341
+ # file, which might be somewhere far away, like S3
342
+ storage, path = paths[name]
343
+ with storage.open(path) as original_file:
344
+ cleaned_name = self.clean_name(name)
345
+ hash_key = self.hash_key(cleaned_name)
346
+
347
+ # generate the hash with the original content, even for
348
+ # adjustable files.
349
+ if hash_key not in hashed_files:
350
+ hashed_name = self.hashed_name(name, original_file)
351
+ else:
352
+ hashed_name = hashed_files[hash_key]
353
+
354
+ # then get the original's file content..
355
+ if hasattr(original_file, "seek"):
356
+ original_file.seek(0)
357
+
358
+ hashed_file_exists = self.exists(hashed_name)
359
+ processed = False
360
+
361
+ # ..to apply each replacement pattern to the content
362
+ if name in adjustable_paths:
363
+ old_hashed_name = hashed_name
364
+ try:
365
+ content = original_file.read().decode("utf-8")
366
+ except UnicodeDecodeError as exc:
367
+ yield name, None, exc, False
368
+ for extension, patterns in self._patterns.items():
369
+ if matches_patterns(path, (extension,)):
370
+ for pattern, template in patterns:
371
+ converter = self.url_converter(
372
+ name, hashed_files, template
373
+ )
374
+ try:
375
+ content = pattern.sub(converter, content)
376
+ except ValueError as exc:
377
+ yield name, None, exc, False
378
+ if hashed_file_exists:
379
+ self.delete(hashed_name)
380
+ # then save the processed result
381
+ content_file = ContentFile(content.encode())
382
+ if self.keep_intermediate_files:
383
+ # Save intermediate file for reference
384
+ self._save(hashed_name, content_file)
385
+ hashed_name = self.hashed_name(name, content_file)
386
+
387
+ if self.exists(hashed_name):
388
+ self.delete(hashed_name)
389
+
390
+ saved_name = self._save(hashed_name, content_file)
391
+ hashed_name = self.clean_name(saved_name)
392
+ # If the file hash stayed the same, this file didn't change
393
+ if old_hashed_name == hashed_name:
394
+ substitutions = False
395
+ processed = True
396
+
397
+ if not processed:
398
+ # or handle the case in which neither processing nor
399
+ # a change to the original file happened
400
+ if not hashed_file_exists:
401
+ processed = True
402
+ saved_name = self._save(hashed_name, original_file)
403
+ hashed_name = self.clean_name(saved_name)
404
+
405
+ # and then set the cache accordingly
406
+ hashed_files[hash_key] = hashed_name
407
+
408
+ yield name, hashed_name, processed, substitutions
409
+
410
+ def clean_name(self, name):
411
+ return name.replace("\\", "/")
412
+
413
+ def hash_key(self, name):
414
+ return name
415
+
416
+ def _stored_name(self, name, hashed_files):
417
+ # Normalize the path to avoid multiple names for the same file like
418
+ # ../foo/bar.css and ../foo/../foo/bar.css which normalize to the same
419
+ # path.
420
+ name = posixpath.normpath(name)
421
+ cleaned_name = self.clean_name(name)
422
+ hash_key = self.hash_key(cleaned_name)
423
+ cache_name = hashed_files.get(hash_key)
424
+ if cache_name is None:
425
+ cache_name = self.clean_name(self.hashed_name(name))
426
+ return cache_name
427
+
428
+ def stored_name(self, name):
429
+ cleaned_name = self.clean_name(name)
430
+ hash_key = self.hash_key(cleaned_name)
431
+ cache_name = self.hashed_files.get(hash_key)
432
+ if cache_name:
433
+ return cache_name
434
+ # No cached name found, recalculate it from the files.
435
+ intermediate_name = name
436
+ for i in range(self.max_post_process_passes + 1):
437
+ cache_name = self.clean_name(
438
+ self.hashed_name(name, content=None, filename=intermediate_name)
439
+ )
440
+ if intermediate_name == cache_name:
441
+ # Store the hashed name if there was a miss.
442
+ self.hashed_files[hash_key] = cache_name
443
+ return cache_name
444
+ else:
445
+ # Move on to the next intermediate file.
446
+ intermediate_name = cache_name
447
+ # If the cache name can't be determined after the max number of passes,
448
+ # the intermediate files on disk may be corrupt; avoid an infinite loop.
449
+ raise ValueError("The name '%s' could not be hashed with %r." % (name, self))
450
+
451
+
452
+ class ManifestFilesMixin(HashedFilesMixin):
453
+ manifest_version = "1.1" # the manifest format standard
454
+ manifest_name = "staticfiles.json"
455
+ manifest_strict = True
456
+ keep_intermediate_files = False
457
+
458
+ def __init__(self, *args, manifest_storage=None, **kwargs):
459
+ super().__init__(*args, **kwargs)
460
+ if manifest_storage is None:
461
+ manifest_storage = self
462
+ self.manifest_storage = manifest_storage
463
+ self.hashed_files, self.manifest_hash = self.load_manifest()
464
+
465
+ def read_manifest(self):
466
+ try:
467
+ with self.manifest_storage.open(self.manifest_name) as manifest:
468
+ return manifest.read().decode()
469
+ except FileNotFoundError:
470
+ return None
471
+
472
+ def load_manifest(self):
473
+ content = self.read_manifest()
474
+ if content is None:
475
+ return {}, ""
476
+ try:
477
+ stored = json.loads(content)
478
+ except json.JSONDecodeError:
479
+ pass
480
+ else:
481
+ version = stored.get("version")
482
+ if version in ("1.0", "1.1"):
483
+ return stored.get("paths", {}), stored.get("hash", "")
484
+ raise ValueError(
485
+ "Couldn't load manifest '%s' (version %s)"
486
+ % (self.manifest_name, self.manifest_version)
487
+ )
488
+
489
+ def post_process(self, *args, **kwargs):
490
+ self.hashed_files = {}
491
+ yield from super().post_process(*args, **kwargs)
492
+ if not kwargs.get("dry_run"):
493
+ self.save_manifest()
494
+
495
+ def save_manifest(self):
496
+ self.manifest_hash = self.file_hash(
497
+ None, ContentFile(json.dumps(sorted(self.hashed_files.items())).encode())
498
+ )
499
+ payload = {
500
+ "paths": self.hashed_files,
501
+ "version": self.manifest_version,
502
+ "hash": self.manifest_hash,
503
+ }
504
+ if self.manifest_storage.exists(self.manifest_name):
505
+ self.manifest_storage.delete(self.manifest_name)
506
+ contents = json.dumps(payload).encode()
507
+ self.manifest_storage._save(self.manifest_name, ContentFile(contents))
508
+
509
+ def stored_name(self, name):
510
+ parsed_name = urlsplit(unquote(name))
511
+ clean_name = parsed_name.path.strip()
512
+ hash_key = self.hash_key(clean_name)
513
+ cache_name = self.hashed_files.get(hash_key)
514
+ if cache_name is None:
515
+ if self.manifest_strict:
516
+ raise ValueError(
517
+ "Missing staticfiles manifest entry for '%s'" % clean_name
518
+ )
519
+ cache_name = self.clean_name(self.hashed_name(name))
520
+ unparsed_name = list(parsed_name)
521
+ unparsed_name[2] = cache_name
522
+ # Special casing for a @font-face hack, like url(myfont.eot?#iefix")
523
+ # http://www.fontspring.com/blog/the-new-bulletproof-font-face-syntax
524
+ if "?#" in name and not unparsed_name[3]:
525
+ unparsed_name[2] += "?"
526
+ return urlunsplit(unparsed_name)
527
+
528
+
529
+ class ManifestStaticFilesStorage(ManifestFilesMixin, StaticFilesStorage):
530
+ """
531
+ A static file system storage backend which also saves
532
+ hashed copies of the files it saves.
533
+ """
534
+
535
+ pass
536
+
537
+
538
+ class ConfiguredStorage(LazyObject):
539
+ def _setup(self):
540
+ self._wrapped = storages[STATICFILES_STORAGE_ALIAS]
541
+
542
+
543
+ staticfiles_storage = ConfiguredStorage()
testbed/django__django/django/contrib/staticfiles/testing.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from django.contrib.staticfiles.handlers import StaticFilesHandler
2
+ from django.test import LiveServerTestCase
3
+
4
+
5
+ class StaticLiveServerTestCase(LiveServerTestCase):
6
+ """
7
+ Extend django.test.LiveServerTestCase to transparently overlay at test
8
+ execution-time the assets provided by the staticfiles app finders. This
9
+ means you don't need to run collectstatic before or as a part of your tests
10
+ setup.
11
+ """
12
+
13
+ static_handler = StaticFilesHandler
testbed/django__django/django/contrib/staticfiles/urls.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from django.conf import settings
2
+ from django.conf.urls.static import static
3
+ from django.contrib.staticfiles.views import serve
4
+
5
+ urlpatterns = []
6
+
7
+
8
+ def staticfiles_urlpatterns(prefix=None):
9
+ """
10
+ Helper function to return a URL pattern for serving static files.
11
+ """
12
+ if prefix is None:
13
+ prefix = settings.STATIC_URL
14
+ return static(prefix, view=serve)
15
+
16
+
17
+ # Only append if urlpatterns are empty
18
+ if settings.DEBUG and not urlpatterns:
19
+ urlpatterns += staticfiles_urlpatterns()
testbed/django__django/django/contrib/staticfiles/utils.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import fnmatch
2
+ import os
3
+
4
+ from django.conf import settings
5
+ from django.core.exceptions import ImproperlyConfigured
6
+
7
+
8
+ def matches_patterns(path, patterns):
9
+ """
10
+ Return True or False depending on whether the ``path`` should be
11
+ ignored (if it matches any pattern in ``ignore_patterns``).
12
+ """
13
+ return any(fnmatch.fnmatchcase(path, pattern) for pattern in patterns)
14
+
15
+
16
+ def get_files(storage, ignore_patterns=None, location=""):
17
+ """
18
+ Recursively walk the storage directories yielding the paths
19
+ of all files that should be copied.
20
+ """
21
+ if ignore_patterns is None:
22
+ ignore_patterns = []
23
+ directories, files = storage.listdir(location)
24
+ for fn in files:
25
+ # Match only the basename.
26
+ if matches_patterns(fn, ignore_patterns):
27
+ continue
28
+ if location:
29
+ fn = os.path.join(location, fn)
30
+ # Match the full file path.
31
+ if matches_patterns(fn, ignore_patterns):
32
+ continue
33
+ yield fn
34
+ for dir in directories:
35
+ if matches_patterns(dir, ignore_patterns):
36
+ continue
37
+ if location:
38
+ dir = os.path.join(location, dir)
39
+ yield from get_files(storage, ignore_patterns, dir)
40
+
41
+
42
+ def check_settings(base_url=None):
43
+ """
44
+ Check if the staticfiles settings have sane values.
45
+ """
46
+ if base_url is None:
47
+ base_url = settings.STATIC_URL
48
+ if not base_url:
49
+ raise ImproperlyConfigured(
50
+ "You're using the staticfiles app "
51
+ "without having set the required STATIC_URL setting."
52
+ )
53
+ if settings.MEDIA_URL == base_url:
54
+ raise ImproperlyConfigured(
55
+ "The MEDIA_URL and STATIC_URL settings must have different values"
56
+ )
57
+ if (
58
+ settings.DEBUG
59
+ and settings.MEDIA_URL
60
+ and settings.STATIC_URL
61
+ and settings.MEDIA_URL.startswith(settings.STATIC_URL)
62
+ ):
63
+ raise ImproperlyConfigured(
64
+ "runserver can't serve media if MEDIA_URL is within STATIC_URL."
65
+ )
66
+ if (settings.MEDIA_ROOT and settings.STATIC_ROOT) and (
67
+ settings.MEDIA_ROOT == settings.STATIC_ROOT
68
+ ):
69
+ raise ImproperlyConfigured(
70
+ "The MEDIA_ROOT and STATIC_ROOT settings must have different values"
71
+ )
testbed/django__django/django/contrib/staticfiles/views.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Views and functions for serving static files. These are only to be used during
3
+ development, and SHOULD NOT be used in a production setting.
4
+
5
+ """
6
+ import os
7
+ import posixpath
8
+
9
+ from django.conf import settings
10
+ from django.contrib.staticfiles import finders
11
+ from django.http import Http404
12
+ from django.views import static
13
+
14
+
15
+ def serve(request, path, insecure=False, **kwargs):
16
+ """
17
+ Serve static files below a given point in the directory structure or
18
+ from locations inferred from the staticfiles finders.
19
+
20
+ To use, put a URL pattern such as::
21
+
22
+ from django.contrib.staticfiles import views
23
+
24
+ path('<path:path>', views.serve)
25
+
26
+ in your URLconf.
27
+
28
+ It uses the django.views.static.serve() view to serve the found files.
29
+ """
30
+ if not settings.DEBUG and not insecure:
31
+ raise Http404
32
+ normalized_path = posixpath.normpath(path).lstrip("/")
33
+ absolute_path = finders.find(normalized_path)
34
+ if not absolute_path:
35
+ if path.endswith("/") or path == "":
36
+ raise Http404("Directory indexes are not allowed here.")
37
+ raise Http404("'%s' could not be found" % path)
38
+ document_root, path = os.path.split(absolute_path)
39
+ return static.serve(request, path, document_root=document_root, **kwargs)
testbed/django__django/django/contrib/syndication/__init__.py ADDED
File without changes
testbed/django__django/django/contrib/syndication/apps.py ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ from django.apps import AppConfig
2
+ from django.utils.translation import gettext_lazy as _
3
+
4
+
5
+ class SyndicationConfig(AppConfig):
6
+ name = "django.contrib.syndication"
7
+ verbose_name = _("Syndication")
testbed/django__django/django/contrib/syndication/views.py ADDED
@@ -0,0 +1,234 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from inspect import getattr_static, unwrap
2
+
3
+ from django.contrib.sites.shortcuts import get_current_site
4
+ from django.core.exceptions import ImproperlyConfigured, ObjectDoesNotExist
5
+ from django.http import Http404, HttpResponse
6
+ from django.template import TemplateDoesNotExist, loader
7
+ from django.utils import feedgenerator
8
+ from django.utils.encoding import iri_to_uri
9
+ from django.utils.html import escape
10
+ from django.utils.http import http_date
11
+ from django.utils.timezone import get_default_timezone, is_naive, make_aware
12
+ from django.utils.translation import get_language
13
+
14
+
15
+ def add_domain(domain, url, secure=False):
16
+ protocol = "https" if secure else "http"
17
+ if url.startswith("//"):
18
+ # Support network-path reference (see #16753) - RSS requires a protocol
19
+ url = "%s:%s" % (protocol, url)
20
+ elif not url.startswith(("http://", "https://", "mailto:")):
21
+ url = iri_to_uri("%s://%s%s" % (protocol, domain, url))
22
+ return url
23
+
24
+
25
+ class FeedDoesNotExist(ObjectDoesNotExist):
26
+ pass
27
+
28
+
29
+ class Feed:
30
+ feed_type = feedgenerator.DefaultFeed
31
+ title_template = None
32
+ description_template = None
33
+ language = None
34
+
35
+ def __call__(self, request, *args, **kwargs):
36
+ try:
37
+ obj = self.get_object(request, *args, **kwargs)
38
+ except ObjectDoesNotExist:
39
+ raise Http404("Feed object does not exist.")
40
+ feedgen = self.get_feed(obj, request)
41
+ response = HttpResponse(content_type=feedgen.content_type)
42
+ if hasattr(self, "item_pubdate") or hasattr(self, "item_updateddate"):
43
+ # if item_pubdate or item_updateddate is defined for the feed, set
44
+ # header so as ConditionalGetMiddleware is able to send 304 NOT MODIFIED
45
+ response.headers["Last-Modified"] = http_date(
46
+ feedgen.latest_post_date().timestamp()
47
+ )
48
+ feedgen.write(response, "utf-8")
49
+ return response
50
+
51
+ def item_title(self, item):
52
+ # Titles should be double escaped by default (see #6533)
53
+ return escape(str(item))
54
+
55
+ def item_description(self, item):
56
+ return str(item)
57
+
58
+ def item_link(self, item):
59
+ try:
60
+ return item.get_absolute_url()
61
+ except AttributeError:
62
+ raise ImproperlyConfigured(
63
+ "Give your %s class a get_absolute_url() method, or define an "
64
+ "item_link() method in your Feed class." % item.__class__.__name__
65
+ )
66
+
67
+ def item_enclosures(self, item):
68
+ enc_url = self._get_dynamic_attr("item_enclosure_url", item)
69
+ if enc_url:
70
+ enc = feedgenerator.Enclosure(
71
+ url=str(enc_url),
72
+ length=str(self._get_dynamic_attr("item_enclosure_length", item)),
73
+ mime_type=str(self._get_dynamic_attr("item_enclosure_mime_type", item)),
74
+ )
75
+ return [enc]
76
+ return []
77
+
78
+ def _get_dynamic_attr(self, attname, obj, default=None):
79
+ try:
80
+ attr = getattr(self, attname)
81
+ except AttributeError:
82
+ return default
83
+ if callable(attr):
84
+ # Check co_argcount rather than try/excepting the function and
85
+ # catching the TypeError, because something inside the function
86
+ # may raise the TypeError. This technique is more accurate.
87
+ func = unwrap(attr)
88
+ try:
89
+ code = func.__code__
90
+ except AttributeError:
91
+ func = unwrap(attr.__call__)
92
+ code = func.__code__
93
+ # If function doesn't have arguments and it is not a static method,
94
+ # it was decorated without using @functools.wraps.
95
+ if not code.co_argcount and not isinstance(
96
+ getattr_static(self, func.__name__, None), staticmethod
97
+ ):
98
+ raise ImproperlyConfigured(
99
+ f"Feed method {attname!r} decorated by {func.__name__!r} needs to "
100
+ f"use @functools.wraps."
101
+ )
102
+ if code.co_argcount == 2: # one argument is 'self'
103
+ return attr(obj)
104
+ else:
105
+ return attr()
106
+ return attr
107
+
108
+ def feed_extra_kwargs(self, obj):
109
+ """
110
+ Return an extra keyword arguments dictionary that is used when
111
+ initializing the feed generator.
112
+ """
113
+ return {}
114
+
115
+ def item_extra_kwargs(self, item):
116
+ """
117
+ Return an extra keyword arguments dictionary that is used with
118
+ the `add_item` call of the feed generator.
119
+ """
120
+ return {}
121
+
122
+ def get_object(self, request, *args, **kwargs):
123
+ return None
124
+
125
+ def get_context_data(self, **kwargs):
126
+ """
127
+ Return a dictionary to use as extra context if either
128
+ ``self.description_template`` or ``self.item_template`` are used.
129
+
130
+ Default implementation preserves the old behavior
131
+ of using {'obj': item, 'site': current_site} as the context.
132
+ """
133
+ return {"obj": kwargs.get("item"), "site": kwargs.get("site")}
134
+
135
+ def get_feed(self, obj, request):
136
+ """
137
+ Return a feedgenerator.DefaultFeed object, fully populated, for
138
+ this feed. Raise FeedDoesNotExist for invalid parameters.
139
+ """
140
+ current_site = get_current_site(request)
141
+
142
+ link = self._get_dynamic_attr("link", obj)
143
+ link = add_domain(current_site.domain, link, request.is_secure())
144
+
145
+ feed = self.feed_type(
146
+ title=self._get_dynamic_attr("title", obj),
147
+ subtitle=self._get_dynamic_attr("subtitle", obj),
148
+ link=link,
149
+ description=self._get_dynamic_attr("description", obj),
150
+ language=self.language or get_language(),
151
+ feed_url=add_domain(
152
+ current_site.domain,
153
+ self._get_dynamic_attr("feed_url", obj) or request.path,
154
+ request.is_secure(),
155
+ ),
156
+ author_name=self._get_dynamic_attr("author_name", obj),
157
+ author_link=self._get_dynamic_attr("author_link", obj),
158
+ author_email=self._get_dynamic_attr("author_email", obj),
159
+ categories=self._get_dynamic_attr("categories", obj),
160
+ feed_copyright=self._get_dynamic_attr("feed_copyright", obj),
161
+ feed_guid=self._get_dynamic_attr("feed_guid", obj),
162
+ ttl=self._get_dynamic_attr("ttl", obj),
163
+ **self.feed_extra_kwargs(obj),
164
+ )
165
+
166
+ title_tmp = None
167
+ if self.title_template is not None:
168
+ try:
169
+ title_tmp = loader.get_template(self.title_template)
170
+ except TemplateDoesNotExist:
171
+ pass
172
+
173
+ description_tmp = None
174
+ if self.description_template is not None:
175
+ try:
176
+ description_tmp = loader.get_template(self.description_template)
177
+ except TemplateDoesNotExist:
178
+ pass
179
+
180
+ for item in self._get_dynamic_attr("items", obj):
181
+ context = self.get_context_data(
182
+ item=item, site=current_site, obj=obj, request=request
183
+ )
184
+ if title_tmp is not None:
185
+ title = title_tmp.render(context, request)
186
+ else:
187
+ title = self._get_dynamic_attr("item_title", item)
188
+ if description_tmp is not None:
189
+ description = description_tmp.render(context, request)
190
+ else:
191
+ description = self._get_dynamic_attr("item_description", item)
192
+ link = add_domain(
193
+ current_site.domain,
194
+ self._get_dynamic_attr("item_link", item),
195
+ request.is_secure(),
196
+ )
197
+ enclosures = self._get_dynamic_attr("item_enclosures", item)
198
+ author_name = self._get_dynamic_attr("item_author_name", item)
199
+ if author_name is not None:
200
+ author_email = self._get_dynamic_attr("item_author_email", item)
201
+ author_link = self._get_dynamic_attr("item_author_link", item)
202
+ else:
203
+ author_email = author_link = None
204
+
205
+ tz = get_default_timezone()
206
+
207
+ pubdate = self._get_dynamic_attr("item_pubdate", item)
208
+ if pubdate and is_naive(pubdate):
209
+ pubdate = make_aware(pubdate, tz)
210
+
211
+ updateddate = self._get_dynamic_attr("item_updateddate", item)
212
+ if updateddate and is_naive(updateddate):
213
+ updateddate = make_aware(updateddate, tz)
214
+
215
+ feed.add_item(
216
+ title=title,
217
+ link=link,
218
+ description=description,
219
+ unique_id=self._get_dynamic_attr("item_guid", item, link),
220
+ unique_id_is_permalink=self._get_dynamic_attr(
221
+ "item_guid_is_permalink", item
222
+ ),
223
+ enclosures=enclosures,
224
+ pubdate=pubdate,
225
+ updateddate=updateddate,
226
+ author_name=author_name,
227
+ author_email=author_email,
228
+ author_link=author_link,
229
+ comments=self._get_dynamic_attr("item_comments", item),
230
+ categories=self._get_dynamic_attr("item_categories", item),
231
+ item_copyright=self._get_dynamic_attr("item_copyright", item),
232
+ **self.item_extra_kwargs(item),
233
+ )
234
+ return feed