pruek0704 commited on
Commit
42ed366
·
1 Parent(s): 28d3d4c

update code edit text

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitignore +13 -17
  2. myenv/bin/Activate.ps1 +0 -247
  3. myenv/bin/activate +0 -70
  4. myenv/bin/activate.csh +0 -27
  5. myenv/bin/activate.fish +0 -69
  6. myenv/bin/django-admin +0 -8
  7. myenv/bin/pip +0 -8
  8. myenv/bin/pip3 +0 -8
  9. myenv/bin/pip3.12 +0 -8
  10. myenv/bin/python +0 -1
  11. myenv/bin/python3 +0 -1
  12. myenv/bin/python3.12 +0 -1
  13. myenv/bin/sqlformat +0 -8
  14. myenv/lib/python3.12/site-packages/asgiref-3.11.1.dist-info/INSTALLER +0 -1
  15. myenv/lib/python3.12/site-packages/asgiref-3.11.1.dist-info/METADATA +0 -247
  16. myenv/lib/python3.12/site-packages/asgiref-3.11.1.dist-info/RECORD +0 -27
  17. myenv/lib/python3.12/site-packages/asgiref-3.11.1.dist-info/WHEEL +0 -5
  18. myenv/lib/python3.12/site-packages/asgiref-3.11.1.dist-info/licenses/LICENSE +0 -27
  19. myenv/lib/python3.12/site-packages/asgiref-3.11.1.dist-info/top_level.txt +0 -1
  20. myenv/lib/python3.12/site-packages/asgiref/__init__.py +0 -1
  21. myenv/lib/python3.12/site-packages/asgiref/compatibility.py +0 -48
  22. myenv/lib/python3.12/site-packages/asgiref/current_thread_executor.py +0 -123
  23. myenv/lib/python3.12/site-packages/asgiref/local.py +0 -131
  24. myenv/lib/python3.12/site-packages/asgiref/py.typed +0 -0
  25. myenv/lib/python3.12/site-packages/asgiref/server.py +0 -173
  26. myenv/lib/python3.12/site-packages/asgiref/sync.py +0 -657
  27. myenv/lib/python3.12/site-packages/asgiref/testing.py +0 -137
  28. myenv/lib/python3.12/site-packages/asgiref/timeout.py +0 -118
  29. myenv/lib/python3.12/site-packages/asgiref/typing.py +0 -279
  30. myenv/lib/python3.12/site-packages/asgiref/wsgi.py +0 -197
  31. myenv/lib/python3.12/site-packages/django-6.0.2.dist-info/INSTALLER +0 -1
  32. myenv/lib/python3.12/site-packages/django-6.0.2.dist-info/METADATA +0 -93
  33. myenv/lib/python3.12/site-packages/django-6.0.2.dist-info/RECORD +0 -0
  34. myenv/lib/python3.12/site-packages/django-6.0.2.dist-info/REQUESTED +0 -0
  35. myenv/lib/python3.12/site-packages/django-6.0.2.dist-info/WHEEL +0 -5
  36. myenv/lib/python3.12/site-packages/django-6.0.2.dist-info/entry_points.txt +0 -2
  37. myenv/lib/python3.12/site-packages/django-6.0.2.dist-info/licenses/LICENSE +0 -27
  38. myenv/lib/python3.12/site-packages/django-6.0.2.dist-info/licenses/LICENSE.python +0 -288
  39. myenv/lib/python3.12/site-packages/django-6.0.2.dist-info/top_level.txt +0 -1
  40. myenv/lib/python3.12/site-packages/django/__init__.py +0 -24
  41. myenv/lib/python3.12/site-packages/django/__main__.py +0 -10
  42. myenv/lib/python3.12/site-packages/django/apps/__init__.py +0 -4
  43. myenv/lib/python3.12/site-packages/django/apps/config.py +0 -274
  44. myenv/lib/python3.12/site-packages/django/apps/registry.py +0 -438
  45. myenv/lib/python3.12/site-packages/django/conf/__init__.py +0 -257
  46. myenv/lib/python3.12/site-packages/django/conf/app_template/__init__.py-tpl +0 -0
  47. myenv/lib/python3.12/site-packages/django/conf/app_template/admin.py-tpl +0 -3
  48. myenv/lib/python3.12/site-packages/django/conf/app_template/apps.py-tpl +0 -5
  49. myenv/lib/python3.12/site-packages/django/conf/app_template/migrations/__init__.py-tpl +0 -0
  50. myenv/lib/python3.12/site-packages/django/conf/app_template/models.py-tpl +0 -3
.gitignore CHANGED
@@ -1,18 +1,14 @@
1
- db.sqlite3 echo .venv
2
- db.sqlite3
3
- .venv
4
- __pycache__
5
- *.pyc
6
- __pycache__
7
- *.pyc
8
- db.sqlite3
9
- .venv
10
- __pycache__
11
- *.pyc
12
- env//static
13
- src/db.sqlite3
14
  env/
15
- *.tar.gzsrc/static
16
- src/static
17
- container.db.sqlite3
18
- container.db.sqlite3
 
 
 
 
 
 
1
+ # .gitignore
2
+
3
+ # Environment folder
4
+ myenv/
 
 
 
 
 
 
 
 
 
5
  env/
6
+ .venv/
7
+ venv/
8
+
9
+ # Database
10
+ db.sqlite3
11
+
12
+ # Python compiled files
13
+ __pycache__/
14
+ *.pyc
myenv/bin/Activate.ps1 DELETED
@@ -1,247 +0,0 @@
1
- <#
2
- .Synopsis
3
- Activate a Python virtual environment for the current PowerShell session.
4
-
5
- .Description
6
- Pushes the python executable for a virtual environment to the front of the
7
- $Env:PATH environment variable and sets the prompt to signify that you are
8
- in a Python virtual environment. Makes use of the command line switches as
9
- well as the `pyvenv.cfg` file values present in the virtual environment.
10
-
11
- .Parameter VenvDir
12
- Path to the directory that contains the virtual environment to activate. The
13
- default value for this is the parent of the directory that the Activate.ps1
14
- script is located within.
15
-
16
- .Parameter Prompt
17
- The prompt prefix to display when this virtual environment is activated. By
18
- default, this prompt is the name of the virtual environment folder (VenvDir)
19
- surrounded by parentheses and followed by a single space (ie. '(.venv) ').
20
-
21
- .Example
22
- Activate.ps1
23
- Activates the Python virtual environment that contains the Activate.ps1 script.
24
-
25
- .Example
26
- Activate.ps1 -Verbose
27
- Activates the Python virtual environment that contains the Activate.ps1 script,
28
- and shows extra information about the activation as it executes.
29
-
30
- .Example
31
- Activate.ps1 -VenvDir C:\Users\MyUser\Common\.venv
32
- Activates the Python virtual environment located in the specified location.
33
-
34
- .Example
35
- Activate.ps1 -Prompt "MyPython"
36
- Activates the Python virtual environment that contains the Activate.ps1 script,
37
- and prefixes the current prompt with the specified string (surrounded in
38
- parentheses) while the virtual environment is active.
39
-
40
- .Notes
41
- On Windows, it may be required to enable this Activate.ps1 script by setting the
42
- execution policy for the user. You can do this by issuing the following PowerShell
43
- command:
44
-
45
- PS C:\> Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
46
-
47
- For more information on Execution Policies:
48
- https://go.microsoft.com/fwlink/?LinkID=135170
49
-
50
- #>
51
- Param(
52
- [Parameter(Mandatory = $false)]
53
- [String]
54
- $VenvDir,
55
- [Parameter(Mandatory = $false)]
56
- [String]
57
- $Prompt
58
- )
59
-
60
- <# Function declarations --------------------------------------------------- #>
61
-
62
- <#
63
- .Synopsis
64
- Remove all shell session elements added by the Activate script, including the
65
- addition of the virtual environment's Python executable from the beginning of
66
- the PATH variable.
67
-
68
- .Parameter NonDestructive
69
- If present, do not remove this function from the global namespace for the
70
- session.
71
-
72
- #>
73
- function global:deactivate ([switch]$NonDestructive) {
74
- # Revert to original values
75
-
76
- # The prior prompt:
77
- if (Test-Path -Path Function:_OLD_VIRTUAL_PROMPT) {
78
- Copy-Item -Path Function:_OLD_VIRTUAL_PROMPT -Destination Function:prompt
79
- Remove-Item -Path Function:_OLD_VIRTUAL_PROMPT
80
- }
81
-
82
- # The prior PYTHONHOME:
83
- if (Test-Path -Path Env:_OLD_VIRTUAL_PYTHONHOME) {
84
- Copy-Item -Path Env:_OLD_VIRTUAL_PYTHONHOME -Destination Env:PYTHONHOME
85
- Remove-Item -Path Env:_OLD_VIRTUAL_PYTHONHOME
86
- }
87
-
88
- # The prior PATH:
89
- if (Test-Path -Path Env:_OLD_VIRTUAL_PATH) {
90
- Copy-Item -Path Env:_OLD_VIRTUAL_PATH -Destination Env:PATH
91
- Remove-Item -Path Env:_OLD_VIRTUAL_PATH
92
- }
93
-
94
- # Just remove the VIRTUAL_ENV altogether:
95
- if (Test-Path -Path Env:VIRTUAL_ENV) {
96
- Remove-Item -Path env:VIRTUAL_ENV
97
- }
98
-
99
- # Just remove VIRTUAL_ENV_PROMPT altogether.
100
- if (Test-Path -Path Env:VIRTUAL_ENV_PROMPT) {
101
- Remove-Item -Path env:VIRTUAL_ENV_PROMPT
102
- }
103
-
104
- # Just remove the _PYTHON_VENV_PROMPT_PREFIX altogether:
105
- if (Get-Variable -Name "_PYTHON_VENV_PROMPT_PREFIX" -ErrorAction SilentlyContinue) {
106
- Remove-Variable -Name _PYTHON_VENV_PROMPT_PREFIX -Scope Global -Force
107
- }
108
-
109
- # Leave deactivate function in the global namespace if requested:
110
- if (-not $NonDestructive) {
111
- Remove-Item -Path function:deactivate
112
- }
113
- }
114
-
115
- <#
116
- .Description
117
- Get-PyVenvConfig parses the values from the pyvenv.cfg file located in the
118
- given folder, and returns them in a map.
119
-
120
- For each line in the pyvenv.cfg file, if that line can be parsed into exactly
121
- two strings separated by `=` (with any amount of whitespace surrounding the =)
122
- then it is considered a `key = value` line. The left hand string is the key,
123
- the right hand is the value.
124
-
125
- If the value starts with a `'` or a `"` then the first and last character is
126
- stripped from the value before being captured.
127
-
128
- .Parameter ConfigDir
129
- Path to the directory that contains the `pyvenv.cfg` file.
130
- #>
131
- function Get-PyVenvConfig(
132
- [String]
133
- $ConfigDir
134
- ) {
135
- Write-Verbose "Given ConfigDir=$ConfigDir, obtain values in pyvenv.cfg"
136
-
137
- # Ensure the file exists, and issue a warning if it doesn't (but still allow the function to continue).
138
- $pyvenvConfigPath = Join-Path -Resolve -Path $ConfigDir -ChildPath 'pyvenv.cfg' -ErrorAction Continue
139
-
140
- # An empty map will be returned if no config file is found.
141
- $pyvenvConfig = @{ }
142
-
143
- if ($pyvenvConfigPath) {
144
-
145
- Write-Verbose "File exists, parse `key = value` lines"
146
- $pyvenvConfigContent = Get-Content -Path $pyvenvConfigPath
147
-
148
- $pyvenvConfigContent | ForEach-Object {
149
- $keyval = $PSItem -split "\s*=\s*", 2
150
- if ($keyval[0] -and $keyval[1]) {
151
- $val = $keyval[1]
152
-
153
- # Remove extraneous quotations around a string value.
154
- if ("'""".Contains($val.Substring(0, 1))) {
155
- $val = $val.Substring(1, $val.Length - 2)
156
- }
157
-
158
- $pyvenvConfig[$keyval[0]] = $val
159
- Write-Verbose "Adding Key: '$($keyval[0])'='$val'"
160
- }
161
- }
162
- }
163
- return $pyvenvConfig
164
- }
165
-
166
-
167
- <# Begin Activate script --------------------------------------------------- #>
168
-
169
- # Determine the containing directory of this script
170
- $VenvExecPath = Split-Path -Parent $MyInvocation.MyCommand.Definition
171
- $VenvExecDir = Get-Item -Path $VenvExecPath
172
-
173
- Write-Verbose "Activation script is located in path: '$VenvExecPath'"
174
- Write-Verbose "VenvExecDir Fullname: '$($VenvExecDir.FullName)"
175
- Write-Verbose "VenvExecDir Name: '$($VenvExecDir.Name)"
176
-
177
- # Set values required in priority: CmdLine, ConfigFile, Default
178
- # First, get the location of the virtual environment, it might not be
179
- # VenvExecDir if specified on the command line.
180
- if ($VenvDir) {
181
- Write-Verbose "VenvDir given as parameter, using '$VenvDir' to determine values"
182
- }
183
- else {
184
- Write-Verbose "VenvDir not given as a parameter, using parent directory name as VenvDir."
185
- $VenvDir = $VenvExecDir.Parent.FullName.TrimEnd("\\/")
186
- Write-Verbose "VenvDir=$VenvDir"
187
- }
188
-
189
- # Next, read the `pyvenv.cfg` file to determine any required value such
190
- # as `prompt`.
191
- $pyvenvCfg = Get-PyVenvConfig -ConfigDir $VenvDir
192
-
193
- # Next, set the prompt from the command line, or the config file, or
194
- # just use the name of the virtual environment folder.
195
- if ($Prompt) {
196
- Write-Verbose "Prompt specified as argument, using '$Prompt'"
197
- }
198
- else {
199
- Write-Verbose "Prompt not specified as argument to script, checking pyvenv.cfg value"
200
- if ($pyvenvCfg -and $pyvenvCfg['prompt']) {
201
- Write-Verbose " Setting based on value in pyvenv.cfg='$($pyvenvCfg['prompt'])'"
202
- $Prompt = $pyvenvCfg['prompt'];
203
- }
204
- else {
205
- Write-Verbose " Setting prompt based on parent's directory's name. (Is the directory name passed to venv module when creating the virtual environment)"
206
- Write-Verbose " Got leaf-name of $VenvDir='$(Split-Path -Path $venvDir -Leaf)'"
207
- $Prompt = Split-Path -Path $venvDir -Leaf
208
- }
209
- }
210
-
211
- Write-Verbose "Prompt = '$Prompt'"
212
- Write-Verbose "VenvDir='$VenvDir'"
213
-
214
- # Deactivate any currently active virtual environment, but leave the
215
- # deactivate function in place.
216
- deactivate -nondestructive
217
-
218
- # Now set the environment variable VIRTUAL_ENV, used by many tools to determine
219
- # that there is an activated venv.
220
- $env:VIRTUAL_ENV = $VenvDir
221
-
222
- if (-not $Env:VIRTUAL_ENV_DISABLE_PROMPT) {
223
-
224
- Write-Verbose "Setting prompt to '$Prompt'"
225
-
226
- # Set the prompt to include the env name
227
- # Make sure _OLD_VIRTUAL_PROMPT is global
228
- function global:_OLD_VIRTUAL_PROMPT { "" }
229
- Copy-Item -Path function:prompt -Destination function:_OLD_VIRTUAL_PROMPT
230
- New-Variable -Name _PYTHON_VENV_PROMPT_PREFIX -Description "Python virtual environment prompt prefix" -Scope Global -Option ReadOnly -Visibility Public -Value $Prompt
231
-
232
- function global:prompt {
233
- Write-Host -NoNewline -ForegroundColor Green "($_PYTHON_VENV_PROMPT_PREFIX) "
234
- _OLD_VIRTUAL_PROMPT
235
- }
236
- $env:VIRTUAL_ENV_PROMPT = $Prompt
237
- }
238
-
239
- # Clear PYTHONHOME
240
- if (Test-Path -Path Env:PYTHONHOME) {
241
- Copy-Item -Path Env:PYTHONHOME -Destination Env:_OLD_VIRTUAL_PYTHONHOME
242
- Remove-Item -Path Env:PYTHONHOME
243
- }
244
-
245
- # Add the venv to the PATH
246
- Copy-Item -Path Env:PATH -Destination Env:_OLD_VIRTUAL_PATH
247
- $Env:PATH = "$VenvExecDir$([System.IO.Path]::PathSeparator)$Env:PATH"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
myenv/bin/activate DELETED
@@ -1,70 +0,0 @@
1
- # This file must be used with "source bin/activate" *from bash*
2
- # You cannot run it directly
3
-
4
- deactivate () {
5
- # reset old environment variables
6
- if [ -n "${_OLD_VIRTUAL_PATH:-}" ] ; then
7
- PATH="${_OLD_VIRTUAL_PATH:-}"
8
- export PATH
9
- unset _OLD_VIRTUAL_PATH
10
- fi
11
- if [ -n "${_OLD_VIRTUAL_PYTHONHOME:-}" ] ; then
12
- PYTHONHOME="${_OLD_VIRTUAL_PYTHONHOME:-}"
13
- export PYTHONHOME
14
- unset _OLD_VIRTUAL_PYTHONHOME
15
- fi
16
-
17
- # Call hash to forget past commands. Without forgetting
18
- # past commands the $PATH changes we made may not be respected
19
- hash -r 2> /dev/null
20
-
21
- if [ -n "${_OLD_VIRTUAL_PS1:-}" ] ; then
22
- PS1="${_OLD_VIRTUAL_PS1:-}"
23
- export PS1
24
- unset _OLD_VIRTUAL_PS1
25
- fi
26
-
27
- unset VIRTUAL_ENV
28
- unset VIRTUAL_ENV_PROMPT
29
- if [ ! "${1:-}" = "nondestructive" ] ; then
30
- # Self destruct!
31
- unset -f deactivate
32
- fi
33
- }
34
-
35
- # unset irrelevant variables
36
- deactivate nondestructive
37
-
38
- # on Windows, a path can contain colons and backslashes and has to be converted:
39
- if [ "${OSTYPE:-}" = "cygwin" ] || [ "${OSTYPE:-}" = "msys" ] ; then
40
- # transform D:\path\to\venv to /d/path/to/venv on MSYS
41
- # and to /cygdrive/d/path/to/venv on Cygwin
42
- export VIRTUAL_ENV=$(cygpath /home/anupong/TDD-DJANGO-feature-refactor-priority/myenv)
43
- else
44
- # use the path as-is
45
- export VIRTUAL_ENV=/home/anupong/TDD-DJANGO-feature-refactor-priority/myenv
46
- fi
47
-
48
- _OLD_VIRTUAL_PATH="$PATH"
49
- PATH="$VIRTUAL_ENV/"bin":$PATH"
50
- export PATH
51
-
52
- # unset PYTHONHOME if set
53
- # this will fail if PYTHONHOME is set to the empty string (which is bad anyway)
54
- # could use `if (set -u; : $PYTHONHOME) ;` in bash
55
- if [ -n "${PYTHONHOME:-}" ] ; then
56
- _OLD_VIRTUAL_PYTHONHOME="${PYTHONHOME:-}"
57
- unset PYTHONHOME
58
- fi
59
-
60
- if [ -z "${VIRTUAL_ENV_DISABLE_PROMPT:-}" ] ; then
61
- _OLD_VIRTUAL_PS1="${PS1:-}"
62
- PS1='(myenv) '"${PS1:-}"
63
- export PS1
64
- VIRTUAL_ENV_PROMPT='(myenv) '
65
- export VIRTUAL_ENV_PROMPT
66
- fi
67
-
68
- # Call hash to forget past commands. Without forgetting
69
- # past commands the $PATH changes we made may not be respected
70
- hash -r 2> /dev/null
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
myenv/bin/activate.csh DELETED
@@ -1,27 +0,0 @@
1
- # This file must be used with "source bin/activate.csh" *from csh*.
2
- # You cannot run it directly.
3
-
4
- # Created by Davide Di Blasi <davidedb@gmail.com>.
5
- # Ported to Python 3.3 venv by Andrew Svetlov <andrew.svetlov@gmail.com>
6
-
7
- alias deactivate 'test $?_OLD_VIRTUAL_PATH != 0 && setenv PATH "$_OLD_VIRTUAL_PATH" && unset _OLD_VIRTUAL_PATH; rehash; test $?_OLD_VIRTUAL_PROMPT != 0 && set prompt="$_OLD_VIRTUAL_PROMPT" && unset _OLD_VIRTUAL_PROMPT; unsetenv VIRTUAL_ENV; unsetenv VIRTUAL_ENV_PROMPT; test "\!:*" != "nondestructive" && unalias deactivate'
8
-
9
- # Unset irrelevant variables.
10
- deactivate nondestructive
11
-
12
- setenv VIRTUAL_ENV /home/anupong/TDD-DJANGO-feature-refactor-priority/myenv
13
-
14
- set _OLD_VIRTUAL_PATH="$PATH"
15
- setenv PATH "$VIRTUAL_ENV/"bin":$PATH"
16
-
17
-
18
- set _OLD_VIRTUAL_PROMPT="$prompt"
19
-
20
- if (! "$?VIRTUAL_ENV_DISABLE_PROMPT") then
21
- set prompt = '(myenv) '"$prompt"
22
- setenv VIRTUAL_ENV_PROMPT '(myenv) '
23
- endif
24
-
25
- alias pydoc python -m pydoc
26
-
27
- rehash
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
myenv/bin/activate.fish DELETED
@@ -1,69 +0,0 @@
1
- # This file must be used with "source <venv>/bin/activate.fish" *from fish*
2
- # (https://fishshell.com/). You cannot run it directly.
3
-
4
- function deactivate -d "Exit virtual environment and return to normal shell environment"
5
- # reset old environment variables
6
- if test -n "$_OLD_VIRTUAL_PATH"
7
- set -gx PATH $_OLD_VIRTUAL_PATH
8
- set -e _OLD_VIRTUAL_PATH
9
- end
10
- if test -n "$_OLD_VIRTUAL_PYTHONHOME"
11
- set -gx PYTHONHOME $_OLD_VIRTUAL_PYTHONHOME
12
- set -e _OLD_VIRTUAL_PYTHONHOME
13
- end
14
-
15
- if test -n "$_OLD_FISH_PROMPT_OVERRIDE"
16
- set -e _OLD_FISH_PROMPT_OVERRIDE
17
- # prevents error when using nested fish instances (Issue #93858)
18
- if functions -q _old_fish_prompt
19
- functions -e fish_prompt
20
- functions -c _old_fish_prompt fish_prompt
21
- functions -e _old_fish_prompt
22
- end
23
- end
24
-
25
- set -e VIRTUAL_ENV
26
- set -e VIRTUAL_ENV_PROMPT
27
- if test "$argv[1]" != "nondestructive"
28
- # Self-destruct!
29
- functions -e deactivate
30
- end
31
- end
32
-
33
- # Unset irrelevant variables.
34
- deactivate nondestructive
35
-
36
- set -gx VIRTUAL_ENV /home/anupong/TDD-DJANGO-feature-refactor-priority/myenv
37
-
38
- set -gx _OLD_VIRTUAL_PATH $PATH
39
- set -gx PATH "$VIRTUAL_ENV/"bin $PATH
40
-
41
- # Unset PYTHONHOME if set.
42
- if set -q PYTHONHOME
43
- set -gx _OLD_VIRTUAL_PYTHONHOME $PYTHONHOME
44
- set -e PYTHONHOME
45
- end
46
-
47
- if test -z "$VIRTUAL_ENV_DISABLE_PROMPT"
48
- # fish uses a function instead of an env var to generate the prompt.
49
-
50
- # Save the current fish_prompt function as the function _old_fish_prompt.
51
- functions -c fish_prompt _old_fish_prompt
52
-
53
- # With the original prompt function renamed, we can override with our own.
54
- function fish_prompt
55
- # Save the return status of the last command.
56
- set -l old_status $status
57
-
58
- # Output the venv prompt; color taken from the blue of the Python logo.
59
- printf "%s%s%s" (set_color 4B8BBE) '(myenv) ' (set_color normal)
60
-
61
- # Restore the return status of the previous command.
62
- echo "exit $old_status" | .
63
- # Output the original/"old" prompt.
64
- _old_fish_prompt
65
- end
66
-
67
- set -gx _OLD_FISH_PROMPT_OVERRIDE "$VIRTUAL_ENV"
68
- set -gx VIRTUAL_ENV_PROMPT '(myenv) '
69
- end
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
myenv/bin/django-admin DELETED
@@ -1,8 +0,0 @@
1
- #!/home/anupong/TDD-DJANGO-feature-refactor-priority/myenv/bin/python3
2
- # -*- coding: utf-8 -*-
3
- import re
4
- import sys
5
- from django.core.management import execute_from_command_line
6
- if __name__ == '__main__':
7
- sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
8
- sys.exit(execute_from_command_line())
 
 
 
 
 
 
 
 
 
myenv/bin/pip DELETED
@@ -1,8 +0,0 @@
1
- #!/home/anupong/TDD-DJANGO-feature-refactor-priority/myenv/bin/python3
2
- # -*- coding: utf-8 -*-
3
- import re
4
- import sys
5
- from pip._internal.cli.main import main
6
- if __name__ == '__main__':
7
- sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
8
- sys.exit(main())
 
 
 
 
 
 
 
 
 
myenv/bin/pip3 DELETED
@@ -1,8 +0,0 @@
1
- #!/home/anupong/TDD-DJANGO-feature-refactor-priority/myenv/bin/python3
2
- # -*- coding: utf-8 -*-
3
- import re
4
- import sys
5
- from pip._internal.cli.main import main
6
- if __name__ == '__main__':
7
- sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
8
- sys.exit(main())
 
 
 
 
 
 
 
 
 
myenv/bin/pip3.12 DELETED
@@ -1,8 +0,0 @@
1
- #!/home/anupong/TDD-DJANGO-feature-refactor-priority/myenv/bin/python3
2
- # -*- coding: utf-8 -*-
3
- import re
4
- import sys
5
- from pip._internal.cli.main import main
6
- if __name__ == '__main__':
7
- sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
8
- sys.exit(main())
 
 
 
 
 
 
 
 
 
myenv/bin/python DELETED
@@ -1 +0,0 @@
1
- python3
 
 
myenv/bin/python3 DELETED
@@ -1 +0,0 @@
1
- /usr/bin/python3
 
 
myenv/bin/python3.12 DELETED
@@ -1 +0,0 @@
1
- python3
 
 
myenv/bin/sqlformat DELETED
@@ -1,8 +0,0 @@
1
- #!/home/anupong/TDD-DJANGO-feature-refactor-priority/myenv/bin/python3
2
- # -*- coding: utf-8 -*-
3
- import re
4
- import sys
5
- from sqlparse.__main__ import main
6
- if __name__ == '__main__':
7
- sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
8
- sys.exit(main())
 
 
 
 
 
 
 
 
 
myenv/lib/python3.12/site-packages/asgiref-3.11.1.dist-info/INSTALLER DELETED
@@ -1 +0,0 @@
1
- pip
 
 
myenv/lib/python3.12/site-packages/asgiref-3.11.1.dist-info/METADATA DELETED
@@ -1,247 +0,0 @@
1
- Metadata-Version: 2.4
2
- Name: asgiref
3
- Version: 3.11.1
4
- Summary: ASGI specs, helper code, and adapters
5
- Home-page: https://github.com/django/asgiref/
6
- Author: Django Software Foundation
7
- Author-email: foundation@djangoproject.com
8
- License: BSD-3-Clause
9
- Project-URL: Documentation, https://asgi.readthedocs.io/
10
- Project-URL: Further Documentation, https://docs.djangoproject.com/en/stable/topics/async/#async-adapter-functions
11
- Project-URL: Changelog, https://github.com/django/asgiref/blob/master/CHANGELOG.txt
12
- Classifier: Development Status :: 5 - Production/Stable
13
- Classifier: Environment :: Web Environment
14
- Classifier: Intended Audience :: Developers
15
- Classifier: License :: OSI Approved :: BSD License
16
- Classifier: Operating System :: OS Independent
17
- Classifier: Programming Language :: Python
18
- Classifier: Programming Language :: Python :: 3
19
- Classifier: Programming Language :: Python :: 3 :: Only
20
- Classifier: Programming Language :: Python :: 3.9
21
- Classifier: Programming Language :: Python :: 3.10
22
- Classifier: Programming Language :: Python :: 3.11
23
- Classifier: Programming Language :: Python :: 3.12
24
- Classifier: Programming Language :: Python :: 3.13
25
- Classifier: Topic :: Internet :: WWW/HTTP
26
- Requires-Python: >=3.9
27
- License-File: LICENSE
28
- Requires-Dist: typing_extensions>=4; python_version < "3.11"
29
- Provides-Extra: tests
30
- Requires-Dist: pytest; extra == "tests"
31
- Requires-Dist: pytest-asyncio; extra == "tests"
32
- Requires-Dist: mypy>=1.14.0; extra == "tests"
33
- Dynamic: license-file
34
-
35
- asgiref
36
- =======
37
-
38
- .. image:: https://github.com/django/asgiref/actions/workflows/tests.yml/badge.svg
39
- :target: https://github.com/django/asgiref/actions/workflows/tests.yml
40
-
41
- .. image:: https://img.shields.io/pypi/v/asgiref.svg
42
- :target: https://pypi.python.org/pypi/asgiref
43
-
44
- ASGI is a standard for Python asynchronous web apps and servers to communicate
45
- with each other, and positioned as an asynchronous successor to WSGI. You can
46
- read more at https://asgi.readthedocs.io/en/latest/
47
-
48
- This package includes ASGI base libraries, such as:
49
-
50
- * Sync-to-async and async-to-sync function wrappers, ``asgiref.sync``
51
- * Server base classes, ``asgiref.server``
52
- * A WSGI-to-ASGI adapter, in ``asgiref.wsgi``
53
-
54
-
55
- Function wrappers
56
- -----------------
57
-
58
- These allow you to wrap or decorate async or sync functions to call them from
59
- the other style (so you can call async functions from a synchronous thread,
60
- or vice-versa).
61
-
62
- In particular:
63
-
64
- * AsyncToSync lets a synchronous subthread stop and wait while the async
65
- function is called on the main thread's event loop, and then control is
66
- returned to the thread when the async function is finished.
67
-
68
- * SyncToAsync lets async code call a synchronous function, which is run in
69
- a threadpool and control returned to the async coroutine when the synchronous
70
- function completes.
71
-
72
- The idea is to make it easier to call synchronous APIs from async code and
73
- asynchronous APIs from synchronous code so it's easier to transition code from
74
- one style to the other. In the case of Channels, we wrap the (synchronous)
75
- Django view system with SyncToAsync to allow it to run inside the (asynchronous)
76
- ASGI server.
77
-
78
- Note that exactly what threads things run in is very specific, and aimed to
79
- keep maximum compatibility with old synchronous code. See
80
- "Synchronous code & Threads" below for a full explanation. By default,
81
- ``sync_to_async`` will run all synchronous code in the program in the same
82
- thread for safety reasons; you can disable this for more performance with
83
- ``@sync_to_async(thread_sensitive=False)``, but make sure that your code does
84
- not rely on anything bound to threads (like database connections) when you do.
85
-
86
-
87
- Threadlocal replacement
88
- -----------------------
89
-
90
- This is a drop-in replacement for ``threading.local`` that works with both
91
- threads and asyncio Tasks. Even better, it will proxy values through from a
92
- task-local context to a thread-local context when you use ``sync_to_async``
93
- to run things in a threadpool, and vice-versa for ``async_to_sync``.
94
-
95
- If you instead want true thread- and task-safety, you can set
96
- ``thread_critical`` on the Local object to ensure this instead.
97
-
98
-
99
- Server base classes
100
- -------------------
101
-
102
- Includes a ``StatelessServer`` class which provides all the hard work of
103
- writing a stateless server (as in, does not handle direct incoming sockets
104
- but instead consumes external streams or sockets to work out what is happening).
105
-
106
- An example of such a server would be a chatbot server that connects out to
107
- a central chat server and provides a "connection scope" per user chatting to
108
- it. There's only one actual connection, but the server has to separate things
109
- into several scopes for easier writing of the code.
110
-
111
- You can see an example of this being used in `frequensgi <https://github.com/andrewgodwin/frequensgi>`_.
112
-
113
-
114
- WSGI-to-ASGI adapter
115
- --------------------
116
-
117
- Allows you to wrap a WSGI application so it appears as a valid ASGI application.
118
-
119
- Simply wrap it around your WSGI application like so::
120
-
121
- asgi_application = WsgiToAsgi(wsgi_application)
122
-
123
- The WSGI application will be run in a synchronous threadpool, and the wrapped
124
- ASGI application will be one that accepts ``http`` class messages.
125
-
126
- Please note that not all extended features of WSGI may be supported (such as
127
- file handles for incoming POST bodies).
128
-
129
-
130
- Dependencies
131
- ------------
132
-
133
- ``asgiref`` requires Python 3.9 or higher.
134
-
135
-
136
- Contributing
137
- ------------
138
-
139
- Please refer to the
140
- `main Channels contributing docs <https://github.com/django/channels/blob/master/CONTRIBUTING.rst>`_.
141
-
142
-
143
- Testing
144
- '''''''
145
-
146
- To run tests, make sure you have installed the ``tests`` extra with the package::
147
-
148
- cd asgiref/
149
- pip install -e .[tests]
150
- pytest
151
-
152
-
153
- Building the documentation
154
- ''''''''''''''''''''''''''
155
-
156
- The documentation uses `Sphinx <http://www.sphinx-doc.org>`_::
157
-
158
- cd asgiref/docs/
159
- pip install sphinx
160
-
161
- To build the docs, you can use the default tools::
162
-
163
- sphinx-build -b html . _build/html # or `make html`, if you've got make set up
164
- cd _build/html
165
- python -m http.server
166
-
167
- ...or you can use ``sphinx-autobuild`` to run a server and rebuild/reload
168
- your documentation changes automatically::
169
-
170
- pip install sphinx-autobuild
171
- sphinx-autobuild . _build/html
172
-
173
-
174
- Releasing
175
- '''''''''
176
-
177
- To release, first add details to CHANGELOG.txt and update the version number in ``asgiref/__init__.py``.
178
-
179
- Then, build and push the packages::
180
-
181
- python -m build
182
- twine upload dist/*
183
- rm -r asgiref.egg-info dist
184
-
185
-
186
- Implementation Details
187
- ----------------------
188
-
189
- Synchronous code & threads
190
- ''''''''''''''''''''''''''
191
-
192
- The ``asgiref.sync`` module provides two wrappers that let you go between
193
- asynchronous and synchronous code at will, while taking care of the rough edges
194
- for you.
195
-
196
- Unfortunately, the rough edges are numerous, and the code has to work especially
197
- hard to keep things in the same thread as much as possible. Notably, the
198
- restrictions we are working with are:
199
-
200
- * All synchronous code called through ``SyncToAsync`` and marked with
201
- ``thread_sensitive`` should run in the same thread as each other (and if the
202
- outer layer of the program is synchronous, the main thread)
203
-
204
- * If a thread already has a running async loop, ``AsyncToSync`` can't run things
205
- on that loop if it's blocked on synchronous code that is above you in the
206
- call stack.
207
-
208
- The first compromise you get to might be that ``thread_sensitive`` code should
209
- just run in the same thread and not spawn in a sub-thread, fulfilling the first
210
- restriction, but that immediately runs you into the second restriction.
211
-
212
- The only real solution is to essentially have a variant of ThreadPoolExecutor
213
- that executes any ``thread_sensitive`` code on the outermost synchronous
214
- thread - either the main thread, or a single spawned subthread.
215
-
216
- This means you now have two basic states:
217
-
218
- * If the outermost layer of your program is synchronous, then all async code
219
- run through ``AsyncToSync`` will run in a per-call event loop in arbitrary
220
- sub-threads, while all ``thread_sensitive`` code will run in the main thread.
221
-
222
- * If the outermost layer of your program is asynchronous, then all async code
223
- runs on the main thread's event loop, and all ``thread_sensitive`` synchronous
224
- code will run in a single shared sub-thread.
225
-
226
- Crucially, this means that in both cases there is a thread which is a shared
227
- resource that all ``thread_sensitive`` code must run on, and there is a chance
228
- that this thread is currently blocked on its own ``AsyncToSync`` call. Thus,
229
- ``AsyncToSync`` needs to act as an executor for thread code while it's blocking.
230
-
231
- The ``CurrentThreadExecutor`` class provides this functionality; rather than
232
- simply waiting on a Future, you can call its ``run_until_future`` method and
233
- it will run submitted code until that Future is done. This means that code
234
- inside the call can then run code on your thread.
235
-
236
-
237
- Maintenance and Security
238
- ------------------------
239
-
240
- To report security issues, please contact security@djangoproject.com. For GPG
241
- signatures and more security process information, see
242
- https://docs.djangoproject.com/en/dev/internals/security/.
243
-
244
- To report bugs or request new features, please open a new GitHub issue.
245
-
246
- This repository is part of the Channels project. For the shepherd and maintenance team, please see the
247
- `main Channels readme <https://github.com/django/channels/blob/master/README.rst>`_.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
myenv/lib/python3.12/site-packages/asgiref-3.11.1.dist-info/RECORD DELETED
@@ -1,27 +0,0 @@
1
- asgiref-3.11.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
2
- asgiref-3.11.1.dist-info/METADATA,sha256=aLePcJP6N7HpneCbacTmO_4Gc4b0PRSo2fWPwsWLeYQ,9287
3
- asgiref-3.11.1.dist-info/RECORD,,
4
- asgiref-3.11.1.dist-info/WHEEL,sha256=wUyA8OaulRlbfwMtmQsvNngGrxQHAvkKcvRmdizlJi0,92
5
- asgiref-3.11.1.dist-info/licenses/LICENSE,sha256=uEZBXRtRTpwd_xSiLeuQbXlLxUbKYSn5UKGM0JHipmk,1552
6
- asgiref-3.11.1.dist-info/top_level.txt,sha256=bokQjCzwwERhdBiPdvYEZa4cHxT4NCeAffQNUqJ8ssg,8
7
- asgiref/__init__.py,sha256=UuKR3QjWk9sJtn2huDFsPdSgtx1CgiEl2B4BUtVRd58,23
8
- asgiref/__pycache__/__init__.cpython-312.pyc,,
9
- asgiref/__pycache__/compatibility.cpython-312.pyc,,
10
- asgiref/__pycache__/current_thread_executor.cpython-312.pyc,,
11
- asgiref/__pycache__/local.cpython-312.pyc,,
12
- asgiref/__pycache__/server.cpython-312.pyc,,
13
- asgiref/__pycache__/sync.cpython-312.pyc,,
14
- asgiref/__pycache__/testing.cpython-312.pyc,,
15
- asgiref/__pycache__/timeout.cpython-312.pyc,,
16
- asgiref/__pycache__/typing.cpython-312.pyc,,
17
- asgiref/__pycache__/wsgi.cpython-312.pyc,,
18
- asgiref/compatibility.py,sha256=DhY1SOpOvOw0Y1lSEjCqg-znRUQKecG3LTaV48MZi68,1606
19
- asgiref/current_thread_executor.py,sha256=42CU1VODLTk-_PYise-cP1XgyAvI5Djc8f97owFzdrs,4157
20
- asgiref/local.py,sha256=ZZeWWIXptVU4GbNApMMWQ-skuglvodcQA5WpzJDMxh4,4912
21
- asgiref/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
22
- asgiref/server.py,sha256=3A68169Nuh2sTY_2O5JzRd_opKObWvvrEFcrXssq3kA,6311
23
- asgiref/sync.py,sha256=KHjSkYRZKIJ1cmBvxcloGrcnhvAuEfXCWCZAoxN8grg,22929
24
- asgiref/testing.py,sha256=U5wcs_-ZYTO5SIGfl80EqRAGv_T8BHrAhvAKRuuztT4,4421
25
- asgiref/timeout.py,sha256=LtGL-xQpG8JHprdsEUCMErJ0kNWj4qwWZhEHJ3iKu4s,3627
26
- asgiref/typing.py,sha256=Zi72AZlOyF1C7N14LLZnpAdfUH4ljoBqFdQo_bBKMq0,6290
27
- asgiref/wsgi.py,sha256=OSxanm5Qf-VfrOkAx62mYW0mOnh8pwaTz1099HbJzM0,7941
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
myenv/lib/python3.12/site-packages/asgiref-3.11.1.dist-info/WHEEL DELETED
@@ -1,5 +0,0 @@
1
- Wheel-Version: 1.0
2
- Generator: setuptools (80.10.2)
3
- Root-Is-Purelib: true
4
- Tag: py3-none-any
5
-
 
 
 
 
 
 
myenv/lib/python3.12/site-packages/asgiref-3.11.1.dist-info/licenses/LICENSE DELETED
@@ -1,27 +0,0 @@
1
- Copyright (c) Django Software Foundation and individual contributors.
2
- All rights reserved.
3
-
4
- Redistribution and use in source and binary forms, with or without modification,
5
- are permitted provided that the following conditions are met:
6
-
7
- 1. Redistributions of source code must retain the above copyright notice,
8
- this list of conditions and the following disclaimer.
9
-
10
- 2. Redistributions in binary form must reproduce the above copyright
11
- notice, this list of conditions and the following disclaimer in the
12
- documentation and/or other materials provided with the distribution.
13
-
14
- 3. Neither the name of Django nor the names of its contributors may be used
15
- to endorse or promote products derived from this software without
16
- specific prior written permission.
17
-
18
- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
19
- ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
20
- WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
21
- DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
22
- ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
23
- (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
24
- LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
25
- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
27
- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
myenv/lib/python3.12/site-packages/asgiref-3.11.1.dist-info/top_level.txt DELETED
@@ -1 +0,0 @@
1
- asgiref
 
 
myenv/lib/python3.12/site-packages/asgiref/__init__.py DELETED
@@ -1 +0,0 @@
1
- __version__ = "3.11.1"
 
 
myenv/lib/python3.12/site-packages/asgiref/compatibility.py DELETED
@@ -1,48 +0,0 @@
1
- import inspect
2
-
3
- from .sync import iscoroutinefunction
4
-
5
-
6
- def is_double_callable(application):
7
- """
8
- Tests to see if an application is a legacy-style (double-callable) application.
9
- """
10
- # Look for a hint on the object first
11
- if getattr(application, "_asgi_single_callable", False):
12
- return False
13
- if getattr(application, "_asgi_double_callable", False):
14
- return True
15
- # Uninstanted classes are double-callable
16
- if inspect.isclass(application):
17
- return True
18
- # Instanted classes depend on their __call__
19
- if hasattr(application, "__call__"):
20
- # We only check to see if its __call__ is a coroutine function -
21
- # if it's not, it still might be a coroutine function itself.
22
- if iscoroutinefunction(application.__call__):
23
- return False
24
- # Non-classes we just check directly
25
- return not iscoroutinefunction(application)
26
-
27
-
28
- def double_to_single_callable(application):
29
- """
30
- Transforms a double-callable ASGI application into a single-callable one.
31
- """
32
-
33
- async def new_application(scope, receive, send):
34
- instance = application(scope)
35
- return await instance(receive, send)
36
-
37
- return new_application
38
-
39
-
40
- def guarantee_single_callable(application):
41
- """
42
- Takes either a single- or double-callable application and always returns it
43
- in single-callable style. Use this to add backwards compatibility for ASGI
44
- 2.0 applications to your server/test harness/etc.
45
- """
46
- if is_double_callable(application):
47
- application = double_to_single_callable(application)
48
- return application
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
myenv/lib/python3.12/site-packages/asgiref/current_thread_executor.py DELETED
@@ -1,123 +0,0 @@
1
- import sys
2
- import threading
3
- from collections import deque
4
- from concurrent.futures import Executor, Future
5
- from typing import Any, Callable, TypeVar
6
-
7
- if sys.version_info >= (3, 10):
8
- from typing import ParamSpec
9
- else:
10
- from typing_extensions import ParamSpec
11
-
12
- _T = TypeVar("_T")
13
- _P = ParamSpec("_P")
14
- _R = TypeVar("_R")
15
-
16
-
17
- class _WorkItem:
18
- """
19
- Represents an item needing to be run in the executor.
20
- Copied from ThreadPoolExecutor (but it's private, so we're not going to rely on importing it)
21
- """
22
-
23
- def __init__(
24
- self,
25
- future: "Future[_R]",
26
- fn: Callable[_P, _R],
27
- *args: _P.args,
28
- **kwargs: _P.kwargs,
29
- ):
30
- self.future = future
31
- self.fn = fn
32
- self.args = args
33
- self.kwargs = kwargs
34
-
35
- def run(self) -> None:
36
- __traceback_hide__ = True # noqa: F841
37
- if not self.future.set_running_or_notify_cancel():
38
- return
39
- try:
40
- result = self.fn(*self.args, **self.kwargs)
41
- except BaseException as exc:
42
- self.future.set_exception(exc)
43
- # Break a reference cycle with the exception 'exc'
44
- self = None # type: ignore[assignment]
45
- else:
46
- self.future.set_result(result)
47
-
48
-
49
- class CurrentThreadExecutor(Executor):
50
- """
51
- An Executor that actually runs code in the thread it is instantiated in.
52
- Passed to other threads running async code, so they can run sync code in
53
- the thread they came from.
54
- """
55
-
56
- def __init__(self, old_executor: "CurrentThreadExecutor | None") -> None:
57
- self._work_thread = threading.current_thread()
58
- self._work_ready = threading.Condition(threading.Lock())
59
- self._work_items = deque[_WorkItem]() # synchronized by _work_ready
60
- self._broken = False # synchronized by _work_ready
61
- self._old_executor = old_executor
62
-
63
- def run_until_future(self, future: "Future[Any]") -> None:
64
- """
65
- Runs the code in the work queue until a result is available from the future.
66
- Should be run from the thread the executor is initialised in.
67
- """
68
- # Check we're in the right thread
69
- if threading.current_thread() != self._work_thread:
70
- raise RuntimeError(
71
- "You cannot run CurrentThreadExecutor from a different thread"
72
- )
73
-
74
- def done(future: "Future[Any]") -> None:
75
- with self._work_ready:
76
- self._broken = True
77
- self._work_ready.notify()
78
-
79
- future.add_done_callback(done)
80
- # Keep getting and running work items until the future we're waiting for
81
- # is done and the queue is empty.
82
- while True:
83
- with self._work_ready:
84
- while not self._work_items and not self._broken:
85
- self._work_ready.wait()
86
- if not self._work_items:
87
- break
88
- # Get a work item and run it
89
- work_item = self._work_items.popleft()
90
- work_item.run()
91
- del work_item
92
-
93
- def submit(
94
- self,
95
- fn: Callable[_P, _R],
96
- /,
97
- *args: _P.args,
98
- **kwargs: _P.kwargs,
99
- ) -> "Future[_R]":
100
- # Check they're not submitting from the same thread
101
- if threading.current_thread() == self._work_thread:
102
- raise RuntimeError(
103
- "You cannot submit onto CurrentThreadExecutor from its own thread"
104
- )
105
- f: "Future[_R]" = Future()
106
- work_item = _WorkItem(f, fn, *args, **kwargs)
107
-
108
- # Walk up the CurrentThreadExecutor stack to find the closest one still
109
- # running
110
- executor = self
111
- while True:
112
- with executor._work_ready:
113
- if not executor._broken:
114
- # Add to work queue
115
- executor._work_items.append(work_item)
116
- executor._work_ready.notify()
117
- break
118
- if executor._old_executor is None:
119
- raise RuntimeError("CurrentThreadExecutor already quit or is broken")
120
- executor = executor._old_executor
121
-
122
- # Return the future
123
- return f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
myenv/lib/python3.12/site-packages/asgiref/local.py DELETED
@@ -1,131 +0,0 @@
1
- import asyncio
2
- import contextlib
3
- import contextvars
4
- import threading
5
- from typing import Any, Dict, Union
6
-
7
-
8
- class _CVar:
9
- """Storage utility for Local."""
10
-
11
- def __init__(self) -> None:
12
- self._data: "contextvars.ContextVar[Dict[str, Any]]" = contextvars.ContextVar(
13
- "asgiref.local"
14
- )
15
-
16
- def __getattr__(self, key):
17
- storage_object = self._data.get({})
18
- try:
19
- return storage_object[key]
20
- except KeyError:
21
- raise AttributeError(f"{self!r} object has no attribute {key!r}")
22
-
23
- def __setattr__(self, key: str, value: Any) -> None:
24
- if key == "_data":
25
- return super().__setattr__(key, value)
26
-
27
- storage_object = self._data.get({}).copy()
28
- storage_object[key] = value
29
- self._data.set(storage_object)
30
-
31
- def __delattr__(self, key: str) -> None:
32
- storage_object = self._data.get({}).copy()
33
- if key in storage_object:
34
- del storage_object[key]
35
- self._data.set(storage_object)
36
- else:
37
- raise AttributeError(f"{self!r} object has no attribute {key!r}")
38
-
39
-
40
- class Local:
41
- """Local storage for async tasks.
42
-
43
- This is a namespace object (similar to `threading.local`) where data is
44
- also local to the current async task (if there is one).
45
-
46
- In async threads, local means in the same sense as the `contextvars`
47
- module - i.e. a value set in an async frame will be visible:
48
-
49
- - to other async code `await`-ed from this frame.
50
- - to tasks spawned using `asyncio` utilities (`create_task`, `wait_for`,
51
- `gather` and probably others).
52
- - to code scheduled in a sync thread using `sync_to_async`
53
-
54
- In "sync" threads (a thread with no async event loop running), the
55
- data is thread-local, but additionally shared with async code executed
56
- via the `async_to_sync` utility, which schedules async code in a new thread
57
- and copies context across to that thread.
58
-
59
- If `thread_critical` is True, then the local will only be visible per-thread,
60
- behaving exactly like `threading.local` if the thread is sync, and as
61
- `contextvars` if the thread is async. This allows genuinely thread-sensitive
62
- code (such as DB handles) to be kept stricly to their initial thread and
63
- disable the sharing across `sync_to_async` and `async_to_sync` wrapped calls.
64
-
65
- Unlike plain `contextvars` objects, this utility is threadsafe.
66
- """
67
-
68
- def __init__(self, thread_critical: bool = False) -> None:
69
- self._thread_critical = thread_critical
70
- self._thread_lock = threading.RLock()
71
-
72
- self._storage: "Union[threading.local, _CVar]"
73
-
74
- if thread_critical:
75
- # Thread-local storage
76
- self._storage = threading.local()
77
- else:
78
- # Contextvar storage
79
- self._storage = _CVar()
80
-
81
- @contextlib.contextmanager
82
- def _lock_storage(self):
83
- # Thread safe access to storage
84
- if self._thread_critical:
85
- is_async = True
86
- try:
87
- # this is a test for are we in a async or sync
88
- # thread - will raise RuntimeError if there is
89
- # no current loop
90
- asyncio.get_running_loop()
91
- except RuntimeError:
92
- is_async = False
93
- if not is_async:
94
- # We are in a sync thread, the storage is
95
- # just the plain thread local (i.e, "global within
96
- # this thread" - it doesn't matter where you are
97
- # in a call stack you see the same storage)
98
- yield self._storage
99
- else:
100
- # We are in an async thread - storage is still
101
- # local to this thread, but additionally should
102
- # behave like a context var (is only visible with
103
- # the same async call stack)
104
-
105
- # Ensure context exists in the current thread
106
- if not hasattr(self._storage, "cvar"):
107
- self._storage.cvar = _CVar()
108
-
109
- # self._storage is a thread local, so the members
110
- # can't be accessed in another thread (we don't
111
- # need any locks)
112
- yield self._storage.cvar
113
- else:
114
- # Lock for thread_critical=False as other threads
115
- # can access the exact same storage object
116
- with self._thread_lock:
117
- yield self._storage
118
-
119
- def __getattr__(self, key):
120
- with self._lock_storage() as storage:
121
- return getattr(storage, key)
122
-
123
- def __setattr__(self, key, value):
124
- if key in ("_local", "_storage", "_thread_critical", "_thread_lock"):
125
- return super().__setattr__(key, value)
126
- with self._lock_storage() as storage:
127
- setattr(storage, key, value)
128
-
129
- def __delattr__(self, key):
130
- with self._lock_storage() as storage:
131
- delattr(storage, key)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
myenv/lib/python3.12/site-packages/asgiref/py.typed DELETED
File without changes
myenv/lib/python3.12/site-packages/asgiref/server.py DELETED
@@ -1,173 +0,0 @@
1
- import asyncio
2
- import logging
3
- import time
4
- import traceback
5
-
6
- from .compatibility import guarantee_single_callable
7
-
8
- logger = logging.getLogger(__name__)
9
-
10
-
11
- class StatelessServer:
12
- """
13
- Base server class that handles basic concepts like application instance
14
- creation/pooling, exception handling, and similar, for stateless protocols
15
- (i.e. ones without actual incoming connections to the process)
16
-
17
- Your code should override the handle() method, doing whatever it needs to,
18
- and calling get_or_create_application_instance with a unique `scope_id`
19
- and `scope` for the scope it wants to get.
20
-
21
- If an application instance is found with the same `scope_id`, you are
22
- given its input queue, otherwise one is made for you with the scope provided
23
- and you are given that fresh new input queue. Either way, you should do
24
- something like:
25
-
26
- input_queue = self.get_or_create_application_instance(
27
- "user-123456",
28
- {"type": "testprotocol", "user_id": "123456", "username": "andrew"},
29
- )
30
- input_queue.put_nowait(message)
31
-
32
- If you try and create an application instance and there are already
33
- `max_application` instances, the oldest/least recently used one will be
34
- reclaimed and shut down to make space.
35
-
36
- Application coroutines that error will be found periodically (every 100ms
37
- by default) and have their exceptions printed to the console. Override
38
- application_exception() if you want to do more when this happens.
39
-
40
- If you override run(), make sure you handle things like launching the
41
- application checker.
42
- """
43
-
44
- application_checker_interval = 0.1
45
-
46
- def __init__(self, application, max_applications=1000):
47
- # Parameters
48
- self.application = application
49
- self.max_applications = max_applications
50
- # Initialisation
51
- self.application_instances = {}
52
-
53
- ### Mainloop and handling
54
-
55
- def run(self):
56
- """
57
- Runs the asyncio event loop with our handler loop.
58
- """
59
- event_loop = asyncio.get_event_loop()
60
- try:
61
- event_loop.run_until_complete(self.arun())
62
- except KeyboardInterrupt:
63
- logger.info("Exiting due to Ctrl-C/interrupt")
64
-
65
- async def arun(self):
66
- """
67
- Runs the asyncio event loop with our handler loop.
68
- """
69
-
70
- class Done(Exception):
71
- pass
72
-
73
- async def handle():
74
- await self.handle()
75
- raise Done
76
-
77
- try:
78
- await asyncio.gather(self.application_checker(), handle())
79
- except Done:
80
- pass
81
-
82
- async def handle(self):
83
- raise NotImplementedError("You must implement handle()")
84
-
85
- async def application_send(self, scope, message):
86
- """
87
- Receives outbound sends from applications and handles them.
88
- """
89
- raise NotImplementedError("You must implement application_send()")
90
-
91
- ### Application instance management
92
-
93
- def get_or_create_application_instance(self, scope_id, scope):
94
- """
95
- Creates an application instance and returns its queue.
96
- """
97
- if scope_id in self.application_instances:
98
- self.application_instances[scope_id]["last_used"] = time.time()
99
- return self.application_instances[scope_id]["input_queue"]
100
- # See if we need to delete an old one
101
- while len(self.application_instances) > self.max_applications:
102
- self.delete_oldest_application_instance()
103
- # Make an instance of the application
104
- input_queue = asyncio.Queue()
105
- application_instance = guarantee_single_callable(self.application)
106
- # Run it, and stash the future for later checking
107
- future = asyncio.ensure_future(
108
- application_instance(
109
- scope=scope,
110
- receive=input_queue.get,
111
- send=lambda message: self.application_send(scope, message),
112
- ),
113
- )
114
- self.application_instances[scope_id] = {
115
- "input_queue": input_queue,
116
- "future": future,
117
- "scope": scope,
118
- "last_used": time.time(),
119
- }
120
- return input_queue
121
-
122
- def delete_oldest_application_instance(self):
123
- """
124
- Finds and deletes the oldest application instance
125
- """
126
- oldest_time = min(
127
- details["last_used"] for details in self.application_instances.values()
128
- )
129
- for scope_id, details in self.application_instances.items():
130
- if details["last_used"] == oldest_time:
131
- self.delete_application_instance(scope_id)
132
- # Return to make sure we only delete one in case two have
133
- # the same oldest time
134
- return
135
-
136
- def delete_application_instance(self, scope_id):
137
- """
138
- Removes an application instance (makes sure its task is stopped,
139
- then removes it from the current set)
140
- """
141
- details = self.application_instances[scope_id]
142
- del self.application_instances[scope_id]
143
- if not details["future"].done():
144
- details["future"].cancel()
145
-
146
- async def application_checker(self):
147
- """
148
- Goes through the set of current application instance Futures and cleans up
149
- any that are done/prints exceptions for any that errored.
150
- """
151
- while True:
152
- await asyncio.sleep(self.application_checker_interval)
153
- for scope_id, details in list(self.application_instances.items()):
154
- if details["future"].done():
155
- exception = details["future"].exception()
156
- if exception:
157
- await self.application_exception(exception, details)
158
- try:
159
- del self.application_instances[scope_id]
160
- except KeyError:
161
- # Exception handling might have already got here before us. That's fine.
162
- pass
163
-
164
- async def application_exception(self, exception, application_details):
165
- """
166
- Called whenever an application coroutine has an exception.
167
- """
168
- logging.error(
169
- "Exception inside application: %s\n%s%s",
170
- exception,
171
- "".join(traceback.format_tb(exception.__traceback__)),
172
- f" {exception}",
173
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
myenv/lib/python3.12/site-packages/asgiref/sync.py DELETED
@@ -1,657 +0,0 @@
1
- import asyncio
2
- import asyncio.coroutines
3
- import contextvars
4
- import functools
5
- import inspect
6
- import os
7
- import sys
8
- import threading
9
- import warnings
10
- import weakref
11
- from concurrent.futures import Future, ThreadPoolExecutor
12
- from typing import (
13
- TYPE_CHECKING,
14
- Any,
15
- Awaitable,
16
- Callable,
17
- Coroutine,
18
- Dict,
19
- Generic,
20
- List,
21
- Optional,
22
- TypeVar,
23
- Union,
24
- overload,
25
- )
26
-
27
- from .current_thread_executor import CurrentThreadExecutor
28
- from .local import Local
29
-
30
- if sys.version_info >= (3, 10):
31
- from typing import ParamSpec
32
- else:
33
- from typing_extensions import ParamSpec
34
-
35
- if TYPE_CHECKING:
36
- # This is not available to import at runtime
37
- from _typeshed import OptExcInfo
38
-
39
- _F = TypeVar("_F", bound=Callable[..., Any])
40
- _P = ParamSpec("_P")
41
- _R = TypeVar("_R")
42
-
43
-
44
- def _restore_context(context: contextvars.Context) -> None:
45
- # Check for changes in contextvars, and set them to the current
46
- # context for downstream consumers
47
- for cvar in context:
48
- cvalue = context.get(cvar)
49
- try:
50
- if cvar.get() != cvalue:
51
- cvar.set(cvalue)
52
- except LookupError:
53
- cvar.set(cvalue)
54
-
55
-
56
- # Python 3.12 deprecates asyncio.iscoroutinefunction() as an alias for
57
- # inspect.iscoroutinefunction(), whilst also removing the _is_coroutine marker.
58
- # The latter is replaced with the inspect.markcoroutinefunction decorator.
59
- # Until 3.12 is the minimum supported Python version, provide a shim.
60
-
61
- if hasattr(inspect, "markcoroutinefunction"):
62
- iscoroutinefunction = inspect.iscoroutinefunction
63
- markcoroutinefunction: Callable[[_F], _F] = inspect.markcoroutinefunction
64
- else:
65
- iscoroutinefunction = asyncio.iscoroutinefunction # type: ignore[assignment]
66
-
67
- def markcoroutinefunction(func: _F) -> _F:
68
- func._is_coroutine = asyncio.coroutines._is_coroutine # type: ignore
69
- return func
70
-
71
-
72
- class AsyncSingleThreadContext:
73
- """Context manager to run async code inside the same thread.
74
-
75
- Normally, AsyncToSync functions run either inside a separate ThreadPoolExecutor or
76
- the main event loop if it exists. This context manager ensures that all AsyncToSync
77
- functions execute within the same thread.
78
-
79
- This context manager is re-entrant, so only the outer-most call to
80
- AsyncSingleThreadContext will set the context.
81
-
82
- Usage:
83
-
84
- >>> import asyncio
85
- >>> with AsyncSingleThreadContext():
86
- ... async_to_sync(asyncio.sleep(1))()
87
- """
88
-
89
- def __init__(self):
90
- self.token = None
91
-
92
- def __enter__(self):
93
- try:
94
- AsyncToSync.async_single_thread_context.get()
95
- except LookupError:
96
- self.token = AsyncToSync.async_single_thread_context.set(self)
97
-
98
- return self
99
-
100
- def __exit__(self, exc, value, tb):
101
- if not self.token:
102
- return
103
-
104
- executor = AsyncToSync.context_to_thread_executor.pop(self, None)
105
- if executor:
106
- executor.shutdown()
107
-
108
- AsyncToSync.async_single_thread_context.reset(self.token)
109
-
110
-
111
- class ThreadSensitiveContext:
112
- """Async context manager to manage context for thread sensitive mode
113
-
114
- This context manager controls which thread pool executor is used when in
115
- thread sensitive mode. By default, a single thread pool executor is shared
116
- within a process.
117
-
118
- The ThreadSensitiveContext() context manager may be used to specify a
119
- thread pool per context.
120
-
121
- This context manager is re-entrant, so only the outer-most call to
122
- ThreadSensitiveContext will set the context.
123
-
124
- Usage:
125
-
126
- >>> import time
127
- >>> async with ThreadSensitiveContext():
128
- ... await sync_to_async(time.sleep, 1)()
129
- """
130
-
131
- def __init__(self):
132
- self.token = None
133
-
134
- async def __aenter__(self):
135
- try:
136
- SyncToAsync.thread_sensitive_context.get()
137
- except LookupError:
138
- self.token = SyncToAsync.thread_sensitive_context.set(self)
139
-
140
- return self
141
-
142
- async def __aexit__(self, exc, value, tb):
143
- if not self.token:
144
- return
145
-
146
- executor = SyncToAsync.context_to_thread_executor.pop(self, None)
147
- if executor:
148
- executor.shutdown()
149
- SyncToAsync.thread_sensitive_context.reset(self.token)
150
-
151
-
152
- class AsyncToSync(Generic[_P, _R]):
153
- """
154
- Utility class which turns an awaitable that only works on the thread with
155
- the event loop into a synchronous callable that works in a subthread.
156
-
157
- If the call stack contains an async loop, the code runs there.
158
- Otherwise, the code runs in a new loop in a new thread.
159
-
160
- Either way, this thread then pauses and waits to run any thread_sensitive
161
- code called from further down the call stack using SyncToAsync, before
162
- finally exiting once the async task returns.
163
- """
164
-
165
- # Keeps a reference to the CurrentThreadExecutor in local context, so that
166
- # any sync_to_async inside the wrapped code can find it.
167
- executors: "Local" = Local()
168
-
169
- # When we can't find a CurrentThreadExecutor from the context, such as
170
- # inside create_task, we'll look it up here from the running event loop.
171
- loop_thread_executors: "Dict[asyncio.AbstractEventLoop, CurrentThreadExecutor]" = {}
172
-
173
- async_single_thread_context: "contextvars.ContextVar[AsyncSingleThreadContext]" = (
174
- contextvars.ContextVar("async_single_thread_context")
175
- )
176
-
177
- context_to_thread_executor: "weakref.WeakKeyDictionary[AsyncSingleThreadContext, ThreadPoolExecutor]" = (
178
- weakref.WeakKeyDictionary()
179
- )
180
-
181
- def __init__(
182
- self,
183
- awaitable: Union[
184
- Callable[_P, Coroutine[Any, Any, _R]],
185
- Callable[_P, Awaitable[_R]],
186
- ],
187
- force_new_loop: bool = False,
188
- ):
189
- if not callable(awaitable) or (
190
- not iscoroutinefunction(awaitable)
191
- and not iscoroutinefunction(getattr(awaitable, "__call__", awaitable))
192
- ):
193
- # Python does not have very reliable detection of async functions
194
- # (lots of false negatives) so this is just a warning.
195
- warnings.warn(
196
- "async_to_sync was passed a non-async-marked callable", stacklevel=2
197
- )
198
- self.awaitable = awaitable
199
- try:
200
- self.__self__ = self.awaitable.__self__ # type: ignore[union-attr]
201
- except AttributeError:
202
- pass
203
- self.force_new_loop = force_new_loop
204
- self.main_event_loop = None
205
- try:
206
- self.main_event_loop = asyncio.get_running_loop()
207
- except RuntimeError:
208
- # There's no event loop in this thread.
209
- pass
210
-
211
- def __call__(self, *args: _P.args, **kwargs: _P.kwargs) -> _R:
212
- __traceback_hide__ = True # noqa: F841
213
-
214
- if not self.force_new_loop and not self.main_event_loop:
215
- # There's no event loop in this thread. Look for the threadlocal if
216
- # we're inside SyncToAsync
217
- main_event_loop_pid = getattr(
218
- SyncToAsync.threadlocal, "main_event_loop_pid", None
219
- )
220
- # We make sure the parent loop is from the same process - if
221
- # they've forked, this is not going to be valid any more (#194)
222
- if main_event_loop_pid and main_event_loop_pid == os.getpid():
223
- self.main_event_loop = getattr(
224
- SyncToAsync.threadlocal, "main_event_loop", None
225
- )
226
-
227
- # You can't call AsyncToSync from a thread with a running event loop
228
- try:
229
- asyncio.get_running_loop()
230
- except RuntimeError:
231
- pass
232
- else:
233
- raise RuntimeError(
234
- "You cannot use AsyncToSync in the same thread as an async event loop - "
235
- "just await the async function directly."
236
- )
237
-
238
- # Make a future for the return information
239
- call_result: "Future[_R]" = Future()
240
-
241
- # Make a CurrentThreadExecutor we'll use to idle in this thread - we
242
- # need one for every sync frame, even if there's one above us in the
243
- # same thread.
244
- old_executor = getattr(self.executors, "current", None)
245
- current_executor = CurrentThreadExecutor(old_executor)
246
- self.executors.current = current_executor
247
-
248
- # Wrapping context in list so it can be reassigned from within
249
- # `main_wrap`.
250
- context = [contextvars.copy_context()]
251
-
252
- # Get task context so that parent task knows which task to propagate
253
- # an asyncio.CancelledError to.
254
- task_context = getattr(SyncToAsync.threadlocal, "task_context", None)
255
-
256
- # Use call_soon_threadsafe to schedule a synchronous callback on the
257
- # main event loop's thread if it's there, otherwise make a new loop
258
- # in this thread.
259
- try:
260
- awaitable = self.main_wrap(
261
- call_result,
262
- sys.exc_info(),
263
- task_context,
264
- context,
265
- # prepare an awaitable which can be passed as is to self.main_wrap,
266
- # so that `args` and `kwargs` don't need to be
267
- # destructured when passed to self.main_wrap
268
- # (which is required by `ParamSpec`)
269
- # as that may cause overlapping arguments
270
- self.awaitable(*args, **kwargs),
271
- )
272
-
273
- async def new_loop_wrap() -> None:
274
- loop = asyncio.get_running_loop()
275
- self.loop_thread_executors[loop] = current_executor
276
- try:
277
- await awaitable
278
- finally:
279
- del self.loop_thread_executors[loop]
280
-
281
- if self.main_event_loop is not None:
282
- try:
283
- self.main_event_loop.call_soon_threadsafe(
284
- self.main_event_loop.create_task, awaitable
285
- )
286
- except RuntimeError:
287
- running_in_main_event_loop = False
288
- else:
289
- running_in_main_event_loop = True
290
- # Run the CurrentThreadExecutor until the future is done.
291
- current_executor.run_until_future(call_result)
292
- else:
293
- running_in_main_event_loop = False
294
-
295
- if not running_in_main_event_loop:
296
- loop_executor = None
297
-
298
- if self.async_single_thread_context.get(None):
299
- single_thread_context = self.async_single_thread_context.get()
300
-
301
- if single_thread_context in self.context_to_thread_executor:
302
- loop_executor = self.context_to_thread_executor[
303
- single_thread_context
304
- ]
305
- else:
306
- loop_executor = ThreadPoolExecutor(max_workers=1)
307
- self.context_to_thread_executor[
308
- single_thread_context
309
- ] = loop_executor
310
- else:
311
- # Make our own event loop - in a new thread - and run inside that.
312
- loop_executor = ThreadPoolExecutor(max_workers=1)
313
-
314
- loop_future = loop_executor.submit(asyncio.run, new_loop_wrap())
315
- # Run the CurrentThreadExecutor until the future is done.
316
- current_executor.run_until_future(loop_future)
317
- # Wait for future and/or allow for exception propagation
318
- loop_future.result()
319
- finally:
320
- _restore_context(context[0])
321
- # Restore old current thread executor state
322
- self.executors.current = old_executor
323
-
324
- # Wait for results from the future.
325
- return call_result.result()
326
-
327
- def __get__(self, parent: Any, objtype: Any) -> Callable[_P, _R]:
328
- """
329
- Include self for methods
330
- """
331
- func = functools.partial(self.__call__, parent)
332
- return functools.update_wrapper(func, self.awaitable)
333
-
334
- async def main_wrap(
335
- self,
336
- call_result: "Future[_R]",
337
- exc_info: "OptExcInfo",
338
- task_context: "Optional[List[asyncio.Task[Any]]]",
339
- context: List[contextvars.Context],
340
- awaitable: Union[Coroutine[Any, Any, _R], Awaitable[_R]],
341
- ) -> None:
342
- """
343
- Wraps the awaitable with something that puts the result into the
344
- result/exception future.
345
- """
346
-
347
- __traceback_hide__ = True # noqa: F841
348
-
349
- if context is not None:
350
- _restore_context(context[0])
351
-
352
- current_task = asyncio.current_task()
353
- if current_task is not None and task_context is not None:
354
- task_context.append(current_task)
355
-
356
- try:
357
- # If we have an exception, run the function inside the except block
358
- # after raising it so exc_info is correctly populated.
359
- if exc_info[1]:
360
- try:
361
- raise exc_info[1]
362
- except BaseException:
363
- result = await awaitable
364
- else:
365
- result = await awaitable
366
- except BaseException as e:
367
- call_result.set_exception(e)
368
- else:
369
- call_result.set_result(result)
370
- finally:
371
- if current_task is not None and task_context is not None:
372
- task_context.remove(current_task)
373
- context[0] = contextvars.copy_context()
374
-
375
-
376
- class SyncToAsync(Generic[_P, _R]):
377
- """
378
- Utility class which turns a synchronous callable into an awaitable that
379
- runs in a threadpool. It also sets a threadlocal inside the thread so
380
- calls to AsyncToSync can escape it.
381
-
382
- If thread_sensitive is passed, the code will run in the same thread as any
383
- outer code. This is needed for underlying Python code that is not
384
- threadsafe (for example, code which handles SQLite database connections).
385
-
386
- If the outermost program is async (i.e. SyncToAsync is outermost), then
387
- this will be a dedicated single sub-thread that all sync code runs in,
388
- one after the other. If the outermost program is sync (i.e. AsyncToSync is
389
- outermost), this will just be the main thread. This is achieved by idling
390
- with a CurrentThreadExecutor while AsyncToSync is blocking its sync parent,
391
- rather than just blocking.
392
-
393
- If executor is passed in, that will be used instead of the loop's default executor.
394
- In order to pass in an executor, thread_sensitive must be set to False, otherwise
395
- a TypeError will be raised.
396
- """
397
-
398
- # Storage for main event loop references
399
- threadlocal = threading.local()
400
-
401
- # Single-thread executor for thread-sensitive code
402
- single_thread_executor = ThreadPoolExecutor(max_workers=1)
403
-
404
- # Maintain a contextvar for the current execution context. Optionally used
405
- # for thread sensitive mode.
406
- thread_sensitive_context: "contextvars.ContextVar[ThreadSensitiveContext]" = (
407
- contextvars.ContextVar("thread_sensitive_context")
408
- )
409
-
410
- # Contextvar that is used to detect if the single thread executor
411
- # would be awaited on while already being used in the same context
412
- deadlock_context: "contextvars.ContextVar[bool]" = contextvars.ContextVar(
413
- "deadlock_context"
414
- )
415
-
416
- # Maintaining a weak reference to the context ensures that thread pools are
417
- # erased once the context goes out of scope. This terminates the thread pool.
418
- context_to_thread_executor: "weakref.WeakKeyDictionary[ThreadSensitiveContext, ThreadPoolExecutor]" = (
419
- weakref.WeakKeyDictionary()
420
- )
421
-
422
- def __init__(
423
- self,
424
- func: Callable[_P, _R],
425
- thread_sensitive: bool = True,
426
- executor: Optional["ThreadPoolExecutor"] = None,
427
- context: Optional[contextvars.Context] = None,
428
- ) -> None:
429
- if (
430
- not callable(func)
431
- or iscoroutinefunction(func)
432
- or iscoroutinefunction(getattr(func, "__call__", func))
433
- ):
434
- raise TypeError("sync_to_async can only be applied to sync functions.")
435
-
436
- functools.update_wrapper(self, func)
437
- self.func = func
438
- self.context = context
439
-
440
- self._thread_sensitive = thread_sensitive
441
- markcoroutinefunction(self)
442
- if thread_sensitive and executor is not None:
443
- raise TypeError("executor must not be set when thread_sensitive is True")
444
- self._executor = executor
445
- try:
446
- self.__self__ = func.__self__ # type: ignore
447
- except AttributeError:
448
- pass
449
-
450
- async def __call__(self, *args: _P.args, **kwargs: _P.kwargs) -> _R:
451
- __traceback_hide__ = True # noqa: F841
452
- loop = asyncio.get_running_loop()
453
-
454
- # Work out what thread to run the code in
455
- if self._thread_sensitive:
456
- current_thread_executor = getattr(AsyncToSync.executors, "current", None)
457
- if current_thread_executor:
458
- # If we have a parent sync thread above somewhere, use that
459
- executor = current_thread_executor
460
- elif self.thread_sensitive_context.get(None):
461
- # If we have a way of retrieving the current context, attempt
462
- # to use a per-context thread pool executor
463
- thread_sensitive_context = self.thread_sensitive_context.get()
464
-
465
- if thread_sensitive_context in self.context_to_thread_executor:
466
- # Re-use thread executor in current context
467
- executor = self.context_to_thread_executor[thread_sensitive_context]
468
- else:
469
- # Create new thread executor in current context
470
- executor = ThreadPoolExecutor(max_workers=1)
471
- self.context_to_thread_executor[thread_sensitive_context] = executor
472
- elif loop in AsyncToSync.loop_thread_executors:
473
- # Re-use thread executor for running loop
474
- executor = AsyncToSync.loop_thread_executors[loop]
475
- elif self.deadlock_context.get(False):
476
- raise RuntimeError(
477
- "Single thread executor already being used, would deadlock"
478
- )
479
- else:
480
- # Otherwise, we run it in a fixed single thread
481
- executor = self.single_thread_executor
482
- self.deadlock_context.set(True)
483
- else:
484
- # Use the passed in executor, or the loop's default if it is None
485
- executor = self._executor
486
-
487
- context = contextvars.copy_context() if self.context is None else self.context
488
- child = functools.partial(self.func, *args, **kwargs)
489
- func = context.run
490
- task_context: List[asyncio.Task[Any]] = []
491
-
492
- # Run the code in the right thread
493
- exec_coro = loop.run_in_executor(
494
- executor,
495
- functools.partial(
496
- self.thread_handler,
497
- loop,
498
- sys.exc_info(),
499
- task_context,
500
- func,
501
- child,
502
- ),
503
- )
504
- ret: _R
505
- try:
506
- ret = await asyncio.shield(exec_coro)
507
- except asyncio.CancelledError:
508
- cancel_parent = True
509
- try:
510
- task = task_context[0]
511
- task.cancel()
512
- try:
513
- await task
514
- cancel_parent = False
515
- except asyncio.CancelledError:
516
- pass
517
- except IndexError:
518
- pass
519
- if exec_coro.done():
520
- raise
521
- if cancel_parent:
522
- exec_coro.cancel()
523
- ret = await exec_coro
524
- finally:
525
- if self.context is None:
526
- _restore_context(context)
527
- self.deadlock_context.set(False)
528
-
529
- return ret
530
-
531
- def __get__(
532
- self, parent: Any, objtype: Any
533
- ) -> Callable[_P, Coroutine[Any, Any, _R]]:
534
- """
535
- Include self for methods
536
- """
537
- func = functools.partial(self.__call__, parent)
538
- return functools.update_wrapper(func, self.func)
539
-
540
- def thread_handler(self, loop, exc_info, task_context, func, *args, **kwargs):
541
- """
542
- Wraps the sync application with exception handling.
543
- """
544
-
545
- __traceback_hide__ = True # noqa: F841
546
-
547
- # Set the threadlocal for AsyncToSync
548
- self.threadlocal.main_event_loop = loop
549
- self.threadlocal.main_event_loop_pid = os.getpid()
550
- self.threadlocal.task_context = task_context
551
-
552
- # Run the function
553
- # If we have an exception, run the function inside the except block
554
- # after raising it so exc_info is correctly populated.
555
- if exc_info[1]:
556
- try:
557
- raise exc_info[1]
558
- except BaseException:
559
- return func(*args, **kwargs)
560
- else:
561
- return func(*args, **kwargs)
562
-
563
-
564
- @overload
565
- def async_to_sync(
566
- *,
567
- force_new_loop: bool = False,
568
- ) -> Callable[
569
- [Union[Callable[_P, Coroutine[Any, Any, _R]], Callable[_P, Awaitable[_R]]]],
570
- Callable[_P, _R],
571
- ]:
572
- ...
573
-
574
-
575
- @overload
576
- def async_to_sync(
577
- awaitable: Union[
578
- Callable[_P, Coroutine[Any, Any, _R]],
579
- Callable[_P, Awaitable[_R]],
580
- ],
581
- *,
582
- force_new_loop: bool = False,
583
- ) -> Callable[_P, _R]:
584
- ...
585
-
586
-
587
- def async_to_sync(
588
- awaitable: Optional[
589
- Union[
590
- Callable[_P, Coroutine[Any, Any, _R]],
591
- Callable[_P, Awaitable[_R]],
592
- ]
593
- ] = None,
594
- *,
595
- force_new_loop: bool = False,
596
- ) -> Union[
597
- Callable[
598
- [Union[Callable[_P, Coroutine[Any, Any, _R]], Callable[_P, Awaitable[_R]]]],
599
- Callable[_P, _R],
600
- ],
601
- Callable[_P, _R],
602
- ]:
603
- if awaitable is None:
604
- return lambda f: AsyncToSync(
605
- f,
606
- force_new_loop=force_new_loop,
607
- )
608
- return AsyncToSync(
609
- awaitable,
610
- force_new_loop=force_new_loop,
611
- )
612
-
613
-
614
- @overload
615
- def sync_to_async(
616
- *,
617
- thread_sensitive: bool = True,
618
- executor: Optional["ThreadPoolExecutor"] = None,
619
- context: Optional[contextvars.Context] = None,
620
- ) -> Callable[[Callable[_P, _R]], Callable[_P, Coroutine[Any, Any, _R]]]:
621
- ...
622
-
623
-
624
- @overload
625
- def sync_to_async(
626
- func: Callable[_P, _R],
627
- *,
628
- thread_sensitive: bool = True,
629
- executor: Optional["ThreadPoolExecutor"] = None,
630
- context: Optional[contextvars.Context] = None,
631
- ) -> Callable[_P, Coroutine[Any, Any, _R]]:
632
- ...
633
-
634
-
635
- def sync_to_async(
636
- func: Optional[Callable[_P, _R]] = None,
637
- *,
638
- thread_sensitive: bool = True,
639
- executor: Optional["ThreadPoolExecutor"] = None,
640
- context: Optional[contextvars.Context] = None,
641
- ) -> Union[
642
- Callable[[Callable[_P, _R]], Callable[_P, Coroutine[Any, Any, _R]]],
643
- Callable[_P, Coroutine[Any, Any, _R]],
644
- ]:
645
- if func is None:
646
- return lambda f: SyncToAsync(
647
- f,
648
- thread_sensitive=thread_sensitive,
649
- executor=executor,
650
- context=context,
651
- )
652
- return SyncToAsync(
653
- func,
654
- thread_sensitive=thread_sensitive,
655
- executor=executor,
656
- context=context,
657
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
myenv/lib/python3.12/site-packages/asgiref/testing.py DELETED
@@ -1,137 +0,0 @@
1
- import asyncio
2
- import contextvars
3
- import time
4
-
5
- from .compatibility import guarantee_single_callable
6
- from .timeout import timeout as async_timeout
7
-
8
-
9
- class ApplicationCommunicator:
10
- """
11
- Runs an ASGI application in a test mode, allowing sending of
12
- messages to it and retrieval of messages it sends.
13
- """
14
-
15
- def __init__(self, application, scope):
16
- self._future = None
17
- self.application = guarantee_single_callable(application)
18
- self.scope = scope
19
- self._input_queue = None
20
- self._output_queue = None
21
-
22
- # For Python 3.9 we need to lazily bind the queues, on 3.10+ they bind the
23
- # event loop lazily.
24
- @property
25
- def input_queue(self):
26
- if self._input_queue is None:
27
- self._input_queue = asyncio.Queue()
28
- return self._input_queue
29
-
30
- @property
31
- def output_queue(self):
32
- if self._output_queue is None:
33
- self._output_queue = asyncio.Queue()
34
- return self._output_queue
35
-
36
- @property
37
- def future(self):
38
- if self._future is None:
39
- # Clear context - this ensures that context vars set in the testing scope
40
- # are not "leaked" into the application which would normally begin with
41
- # an empty context. In Python >= 3.11 this could also be written as:
42
- # asyncio.create_task(..., context=contextvars.Context())
43
- self._future = contextvars.Context().run(
44
- asyncio.create_task,
45
- self.application(
46
- self.scope, self.input_queue.get, self.output_queue.put
47
- ),
48
- )
49
- return self._future
50
-
51
- async def wait(self, timeout=1):
52
- """
53
- Waits for the application to stop itself and returns any exceptions.
54
- """
55
- try:
56
- async with async_timeout(timeout):
57
- try:
58
- await self.future
59
- self.future.result()
60
- except asyncio.CancelledError:
61
- pass
62
- finally:
63
- if not self.future.done():
64
- self.future.cancel()
65
- try:
66
- await self.future
67
- except asyncio.CancelledError:
68
- pass
69
-
70
- def stop(self, exceptions=True):
71
- future = self._future
72
- if future is None:
73
- return
74
-
75
- if not future.done():
76
- future.cancel()
77
- elif exceptions:
78
- # Give a chance to raise any exceptions
79
- future.result()
80
-
81
- def __del__(self):
82
- # Clean up on deletion
83
- try:
84
- self.stop(exceptions=False)
85
- except RuntimeError:
86
- # Event loop already stopped
87
- pass
88
-
89
- async def send_input(self, message):
90
- """
91
- Sends a single message to the application
92
- """
93
- # Make sure there's not an exception to raise from the task
94
- if self.future.done():
95
- self.future.result()
96
-
97
- # Give it the message
98
- await self.input_queue.put(message)
99
-
100
- async def receive_output(self, timeout=1):
101
- """
102
- Receives a single message from the application, with optional timeout.
103
- """
104
- # Make sure there's not an exception to raise from the task
105
- if self.future.done():
106
- self.future.result()
107
- # Wait and receive the message
108
- try:
109
- async with async_timeout(timeout):
110
- return await self.output_queue.get()
111
- except asyncio.TimeoutError as e:
112
- # See if we have another error to raise inside
113
- if self.future.done():
114
- self.future.result()
115
- else:
116
- self.future.cancel()
117
- try:
118
- await self.future
119
- except asyncio.CancelledError:
120
- pass
121
- raise e
122
-
123
- async def receive_nothing(self, timeout=0.1, interval=0.01):
124
- """
125
- Checks that there is no message to receive in the given time.
126
- """
127
- # Make sure there's not an exception to raise from the task
128
- if self.future.done():
129
- self.future.result()
130
-
131
- # `interval` has precedence over `timeout`
132
- start = time.monotonic()
133
- while time.monotonic() - start < timeout:
134
- if not self.output_queue.empty():
135
- return False
136
- await asyncio.sleep(interval)
137
- return self.output_queue.empty()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
myenv/lib/python3.12/site-packages/asgiref/timeout.py DELETED
@@ -1,118 +0,0 @@
1
- # This code is originally sourced from the aio-libs project "async_timeout",
2
- # under the Apache 2.0 license. You may see the original project at
3
- # https://github.com/aio-libs/async-timeout
4
-
5
- # It is vendored here to reduce chain-dependencies on this library, and
6
- # modified slightly to remove some features we don't use.
7
-
8
-
9
- import asyncio
10
- import warnings
11
- from types import TracebackType
12
- from typing import Any # noqa
13
- from typing import Optional, Type
14
-
15
-
16
- class timeout:
17
- """timeout context manager.
18
-
19
- Useful in cases when you want to apply timeout logic around block
20
- of code or in cases when asyncio.wait_for is not suitable. For example:
21
-
22
- >>> with timeout(0.001):
23
- ... async with aiohttp.get('https://github.com') as r:
24
- ... await r.text()
25
-
26
-
27
- timeout - value in seconds or None to disable timeout logic
28
- loop - asyncio compatible event loop
29
- """
30
-
31
- def __init__(
32
- self,
33
- timeout: Optional[float],
34
- *,
35
- loop: Optional[asyncio.AbstractEventLoop] = None,
36
- ) -> None:
37
- self._timeout = timeout
38
- if loop is None:
39
- loop = asyncio.get_running_loop()
40
- else:
41
- warnings.warn(
42
- """The loop argument to timeout() is deprecated.""", DeprecationWarning
43
- )
44
- self._loop = loop
45
- self._task = None # type: Optional[asyncio.Task[Any]]
46
- self._cancelled = False
47
- self._cancel_handler = None # type: Optional[asyncio.Handle]
48
- self._cancel_at = None # type: Optional[float]
49
-
50
- def __enter__(self) -> "timeout":
51
- return self._do_enter()
52
-
53
- def __exit__(
54
- self,
55
- exc_type: Type[BaseException],
56
- exc_val: BaseException,
57
- exc_tb: TracebackType,
58
- ) -> Optional[bool]:
59
- self._do_exit(exc_type)
60
- return None
61
-
62
- async def __aenter__(self) -> "timeout":
63
- return self._do_enter()
64
-
65
- async def __aexit__(
66
- self,
67
- exc_type: Type[BaseException],
68
- exc_val: BaseException,
69
- exc_tb: TracebackType,
70
- ) -> None:
71
- self._do_exit(exc_type)
72
-
73
- @property
74
- def expired(self) -> bool:
75
- return self._cancelled
76
-
77
- @property
78
- def remaining(self) -> Optional[float]:
79
- if self._cancel_at is not None:
80
- return max(self._cancel_at - self._loop.time(), 0.0)
81
- else:
82
- return None
83
-
84
- def _do_enter(self) -> "timeout":
85
- # Support Tornado 5- without timeout
86
- # Details: https://github.com/python/asyncio/issues/392
87
- if self._timeout is None:
88
- return self
89
-
90
- self._task = asyncio.current_task(self._loop)
91
- if self._task is None:
92
- raise RuntimeError(
93
- "Timeout context manager should be used " "inside a task"
94
- )
95
-
96
- if self._timeout <= 0:
97
- self._loop.call_soon(self._cancel_task)
98
- return self
99
-
100
- self._cancel_at = self._loop.time() + self._timeout
101
- self._cancel_handler = self._loop.call_at(self._cancel_at, self._cancel_task)
102
- return self
103
-
104
- def _do_exit(self, exc_type: Type[BaseException]) -> None:
105
- if exc_type is asyncio.CancelledError and self._cancelled:
106
- self._cancel_handler = None
107
- self._task = None
108
- raise asyncio.TimeoutError
109
- if self._timeout is not None and self._cancel_handler is not None:
110
- self._cancel_handler.cancel()
111
- self._cancel_handler = None
112
- self._task = None
113
- return None
114
-
115
- def _cancel_task(self) -> None:
116
- if self._task is not None:
117
- self._task.cancel()
118
- self._cancelled = True
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
myenv/lib/python3.12/site-packages/asgiref/typing.py DELETED
@@ -1,279 +0,0 @@
1
- import sys
2
- from typing import (
3
- Any,
4
- Awaitable,
5
- Callable,
6
- Dict,
7
- Iterable,
8
- Literal,
9
- Optional,
10
- Protocol,
11
- Tuple,
12
- Type,
13
- TypedDict,
14
- Union,
15
- )
16
-
17
- if sys.version_info >= (3, 11):
18
- from typing import NotRequired
19
- else:
20
- from typing_extensions import NotRequired
21
-
22
- __all__ = (
23
- "ASGIVersions",
24
- "HTTPScope",
25
- "WebSocketScope",
26
- "LifespanScope",
27
- "WWWScope",
28
- "Scope",
29
- "HTTPRequestEvent",
30
- "HTTPResponseStartEvent",
31
- "HTTPResponseBodyEvent",
32
- "HTTPResponseTrailersEvent",
33
- "HTTPResponsePathsendEvent",
34
- "HTTPServerPushEvent",
35
- "HTTPDisconnectEvent",
36
- "WebSocketConnectEvent",
37
- "WebSocketAcceptEvent",
38
- "WebSocketReceiveEvent",
39
- "WebSocketSendEvent",
40
- "WebSocketResponseStartEvent",
41
- "WebSocketResponseBodyEvent",
42
- "WebSocketDisconnectEvent",
43
- "WebSocketCloseEvent",
44
- "LifespanStartupEvent",
45
- "LifespanShutdownEvent",
46
- "LifespanStartupCompleteEvent",
47
- "LifespanStartupFailedEvent",
48
- "LifespanShutdownCompleteEvent",
49
- "LifespanShutdownFailedEvent",
50
- "ASGIReceiveEvent",
51
- "ASGISendEvent",
52
- "ASGIReceiveCallable",
53
- "ASGISendCallable",
54
- "ASGI2Protocol",
55
- "ASGI2Application",
56
- "ASGI3Application",
57
- "ASGIApplication",
58
- )
59
-
60
-
61
- class ASGIVersions(TypedDict):
62
- spec_version: str
63
- version: Union[Literal["2.0"], Literal["3.0"]]
64
-
65
-
66
- class HTTPScope(TypedDict):
67
- type: Literal["http"]
68
- asgi: ASGIVersions
69
- http_version: str
70
- method: str
71
- scheme: str
72
- path: str
73
- raw_path: bytes
74
- query_string: bytes
75
- root_path: str
76
- headers: Iterable[Tuple[bytes, bytes]]
77
- client: Optional[Tuple[str, int]]
78
- server: Optional[Tuple[str, Optional[int]]]
79
- state: NotRequired[Dict[str, Any]]
80
- extensions: Optional[Dict[str, Dict[object, object]]]
81
-
82
-
83
- class WebSocketScope(TypedDict):
84
- type: Literal["websocket"]
85
- asgi: ASGIVersions
86
- http_version: str
87
- scheme: str
88
- path: str
89
- raw_path: bytes
90
- query_string: bytes
91
- root_path: str
92
- headers: Iterable[Tuple[bytes, bytes]]
93
- client: Optional[Tuple[str, int]]
94
- server: Optional[Tuple[str, Optional[int]]]
95
- subprotocols: Iterable[str]
96
- state: NotRequired[Dict[str, Any]]
97
- extensions: Optional[Dict[str, Dict[object, object]]]
98
-
99
-
100
- class LifespanScope(TypedDict):
101
- type: Literal["lifespan"]
102
- asgi: ASGIVersions
103
- state: NotRequired[Dict[str, Any]]
104
-
105
-
106
- WWWScope = Union[HTTPScope, WebSocketScope]
107
- Scope = Union[HTTPScope, WebSocketScope, LifespanScope]
108
-
109
-
110
- class HTTPRequestEvent(TypedDict):
111
- type: Literal["http.request"]
112
- body: bytes
113
- more_body: bool
114
-
115
-
116
- class HTTPResponseDebugEvent(TypedDict):
117
- type: Literal["http.response.debug"]
118
- info: Dict[str, object]
119
-
120
-
121
- class HTTPResponseStartEvent(TypedDict):
122
- type: Literal["http.response.start"]
123
- status: int
124
- headers: Iterable[Tuple[bytes, bytes]]
125
- trailers: bool
126
-
127
-
128
- class HTTPResponseBodyEvent(TypedDict):
129
- type: Literal["http.response.body"]
130
- body: bytes
131
- more_body: bool
132
-
133
-
134
- class HTTPResponseTrailersEvent(TypedDict):
135
- type: Literal["http.response.trailers"]
136
- headers: Iterable[Tuple[bytes, bytes]]
137
- more_trailers: bool
138
-
139
-
140
- class HTTPResponsePathsendEvent(TypedDict):
141
- type: Literal["http.response.pathsend"]
142
- path: str
143
-
144
-
145
- class HTTPServerPushEvent(TypedDict):
146
- type: Literal["http.response.push"]
147
- path: str
148
- headers: Iterable[Tuple[bytes, bytes]]
149
-
150
-
151
- class HTTPDisconnectEvent(TypedDict):
152
- type: Literal["http.disconnect"]
153
-
154
-
155
- class WebSocketConnectEvent(TypedDict):
156
- type: Literal["websocket.connect"]
157
-
158
-
159
- class WebSocketAcceptEvent(TypedDict):
160
- type: Literal["websocket.accept"]
161
- subprotocol: Optional[str]
162
- headers: Iterable[Tuple[bytes, bytes]]
163
-
164
-
165
- class WebSocketReceiveEvent(TypedDict):
166
- type: Literal["websocket.receive"]
167
- bytes: Optional[bytes]
168
- text: Optional[str]
169
-
170
-
171
- class WebSocketSendEvent(TypedDict):
172
- type: Literal["websocket.send"]
173
- bytes: Optional[bytes]
174
- text: Optional[str]
175
-
176
-
177
- class WebSocketResponseStartEvent(TypedDict):
178
- type: Literal["websocket.http.response.start"]
179
- status: int
180
- headers: Iterable[Tuple[bytes, bytes]]
181
-
182
-
183
- class WebSocketResponseBodyEvent(TypedDict):
184
- type: Literal["websocket.http.response.body"]
185
- body: bytes
186
- more_body: bool
187
-
188
-
189
- class WebSocketDisconnectEvent(TypedDict):
190
- type: Literal["websocket.disconnect"]
191
- code: int
192
- reason: Optional[str]
193
-
194
-
195
- class WebSocketCloseEvent(TypedDict):
196
- type: Literal["websocket.close"]
197
- code: int
198
- reason: Optional[str]
199
-
200
-
201
- class LifespanStartupEvent(TypedDict):
202
- type: Literal["lifespan.startup"]
203
-
204
-
205
- class LifespanShutdownEvent(TypedDict):
206
- type: Literal["lifespan.shutdown"]
207
-
208
-
209
- class LifespanStartupCompleteEvent(TypedDict):
210
- type: Literal["lifespan.startup.complete"]
211
-
212
-
213
- class LifespanStartupFailedEvent(TypedDict):
214
- type: Literal["lifespan.startup.failed"]
215
- message: str
216
-
217
-
218
- class LifespanShutdownCompleteEvent(TypedDict):
219
- type: Literal["lifespan.shutdown.complete"]
220
-
221
-
222
- class LifespanShutdownFailedEvent(TypedDict):
223
- type: Literal["lifespan.shutdown.failed"]
224
- message: str
225
-
226
-
227
- ASGIReceiveEvent = Union[
228
- HTTPRequestEvent,
229
- HTTPDisconnectEvent,
230
- WebSocketConnectEvent,
231
- WebSocketReceiveEvent,
232
- WebSocketDisconnectEvent,
233
- LifespanStartupEvent,
234
- LifespanShutdownEvent,
235
- ]
236
-
237
-
238
- ASGISendEvent = Union[
239
- HTTPResponseStartEvent,
240
- HTTPResponseBodyEvent,
241
- HTTPResponseTrailersEvent,
242
- HTTPServerPushEvent,
243
- HTTPDisconnectEvent,
244
- WebSocketAcceptEvent,
245
- WebSocketSendEvent,
246
- WebSocketResponseStartEvent,
247
- WebSocketResponseBodyEvent,
248
- WebSocketCloseEvent,
249
- LifespanStartupCompleteEvent,
250
- LifespanStartupFailedEvent,
251
- LifespanShutdownCompleteEvent,
252
- LifespanShutdownFailedEvent,
253
- ]
254
-
255
-
256
- ASGIReceiveCallable = Callable[[], Awaitable[ASGIReceiveEvent]]
257
- ASGISendCallable = Callable[[ASGISendEvent], Awaitable[None]]
258
-
259
-
260
- class ASGI2Protocol(Protocol):
261
- def __init__(self, scope: Scope) -> None:
262
- ...
263
-
264
- async def __call__(
265
- self, receive: ASGIReceiveCallable, send: ASGISendCallable
266
- ) -> None:
267
- ...
268
-
269
-
270
- ASGI2Application = Type[ASGI2Protocol]
271
- ASGI3Application = Callable[
272
- [
273
- Scope,
274
- ASGIReceiveCallable,
275
- ASGISendCallable,
276
- ],
277
- Awaitable[None],
278
- ]
279
- ASGIApplication = Union[ASGI2Application, ASGI3Application]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
myenv/lib/python3.12/site-packages/asgiref/wsgi.py DELETED
@@ -1,197 +0,0 @@
1
- import sys
2
- from collections import defaultdict
3
- from tempfile import SpooledTemporaryFile
4
-
5
- from asgiref.sync import AsyncToSync, sync_to_async
6
-
7
-
8
- class WsgiToAsgi:
9
- """
10
- Wraps a WSGI application to make it into an ASGI application.
11
- """
12
-
13
- def __init__(self, wsgi_application, duplicate_header_limit=100):
14
- self.wsgi_application = wsgi_application
15
- self.duplicate_header_limit = duplicate_header_limit
16
-
17
- async def __call__(self, scope, receive, send):
18
- """
19
- ASGI application instantiation point.
20
- We return a new WsgiToAsgiInstance here with the WSGI app
21
- and the scope, ready to respond when it is __call__ed.
22
- """
23
- await WsgiToAsgiInstance(self.wsgi_application, self.duplicate_header_limit)(
24
- scope, receive, send
25
- )
26
-
27
-
28
- class WsgiToAsgiInstance:
29
- """
30
- Per-socket instance of a wrapped WSGI application
31
- """
32
-
33
- def __init__(self, wsgi_application, duplicate_header_limit=100):
34
- self.wsgi_application = wsgi_application
35
- self.duplicate_header_limit = duplicate_header_limit
36
- self.response_started = False
37
- self.response_content_length = None
38
-
39
- async def __call__(self, scope, receive, send):
40
- if scope["type"] != "http":
41
- raise ValueError("WSGI wrapper received a non-HTTP scope")
42
- self.scope = scope
43
- with SpooledTemporaryFile(max_size=65536) as body:
44
- # Alright, wait for the http.request messages
45
- while True:
46
- message = await receive()
47
- if message["type"] != "http.request":
48
- raise ValueError("WSGI wrapper received a non-HTTP-request message")
49
- body.write(message.get("body", b""))
50
- if not message.get("more_body"):
51
- break
52
- body.seek(0)
53
- # Wrap send so it can be called from the subthread
54
- self.sync_send = AsyncToSync(send)
55
- # Call the WSGI app
56
- await self.run_wsgi_app(body)
57
-
58
- def build_environ(self, scope, body):
59
- """
60
- Builds a scope and request body into a WSGI environ object.
61
- """
62
- script_name = scope.get("root_path", "").encode("utf8").decode("latin1")
63
- path_info = scope["path"].encode("utf8").decode("latin1")
64
- if path_info.startswith(script_name):
65
- path_info = path_info[len(script_name) :]
66
- environ = {
67
- "REQUEST_METHOD": scope["method"],
68
- "SCRIPT_NAME": script_name,
69
- "PATH_INFO": path_info,
70
- "QUERY_STRING": scope["query_string"].decode("ascii"),
71
- "SERVER_PROTOCOL": "HTTP/%s" % scope["http_version"],
72
- "wsgi.version": (1, 0),
73
- "wsgi.url_scheme": scope.get("scheme", "http"),
74
- "wsgi.input": body,
75
- "wsgi.errors": sys.stderr,
76
- "wsgi.multithread": True,
77
- "wsgi.multiprocess": True,
78
- "wsgi.run_once": False,
79
- }
80
- # Get server name and port - required in WSGI, not in ASGI
81
- if "server" in scope:
82
- environ["SERVER_NAME"] = scope["server"][0]
83
- environ["SERVER_PORT"] = str(scope["server"][1])
84
- else:
85
- environ["SERVER_NAME"] = "localhost"
86
- environ["SERVER_PORT"] = "80"
87
-
88
- if scope.get("client") is not None:
89
- environ["REMOTE_ADDR"] = scope["client"][0]
90
-
91
- # Go through headers and make them into environ entries
92
- _headers = defaultdict(list)
93
- for name, value in self.scope.get("headers", []):
94
- name = name.decode("latin1")
95
- if name == "content-length":
96
- corrected_name = "CONTENT_LENGTH"
97
- elif name == "content-type":
98
- corrected_name = "CONTENT_TYPE"
99
- else:
100
- corrected_name = "HTTP_%s" % name.upper().replace("-", "_")
101
- # HTTPbis say only ASCII chars are allowed in headers, but we latin1 just in case
102
- value = value.decode("latin1")
103
- if (
104
- self.duplicate_header_limit
105
- and len(_headers[corrected_name]) >= self.duplicate_header_limit
106
- ):
107
- raise ValueError(
108
- f"Too many duplicate headers: {corrected_name} exceeds limit of"
109
- f"{self.duplicate_header_limit}"
110
- )
111
- _headers[corrected_name].append(value)
112
- for name, values in _headers.items():
113
- environ[name] = ",".join(values)
114
- return environ
115
-
116
- def start_response(self, status, response_headers, exc_info=None):
117
- """
118
- WSGI start_response callable.
119
- """
120
- # Don't allow re-calling once response has begun
121
- if self.response_started:
122
- raise exc_info[1].with_traceback(exc_info[2])
123
- # Don't allow re-calling without exc_info
124
- if hasattr(self, "response_start") and exc_info is None:
125
- raise ValueError(
126
- "You cannot call start_response a second time without exc_info"
127
- )
128
- # Extract status code
129
- status_code, _ = status.split(" ", 1)
130
- status_code = int(status_code)
131
- # Extract headers
132
- headers = [
133
- (name.lower().encode("ascii"), value.encode("ascii"))
134
- for name, value in response_headers
135
- ]
136
- # Extract content-length
137
- self.response_content_length = None
138
- for name, value in response_headers:
139
- if name.lower() == "content-length":
140
- self.response_content_length = int(value)
141
- # Build and send response start message.
142
- self.response_start = {
143
- "type": "http.response.start",
144
- "status": status_code,
145
- "headers": headers,
146
- }
147
-
148
- @sync_to_async
149
- def run_wsgi_app(self, body):
150
- """
151
- Called in a subthread to run the WSGI app. We encapsulate like
152
- this so that the start_response callable is called in the same thread.
153
- """
154
- # Translate the scope and incoming request body into a WSGI environ
155
- try:
156
- environ = self.build_environ(self.scope, body)
157
- except ValueError:
158
- # Return 400 Bad Request if header limit exceeded
159
- self.sync_send(
160
- {
161
- "type": "http.response.start",
162
- "status": 400,
163
- "headers": [(b"content-type", b"text/plain")],
164
- }
165
- )
166
- self.sync_send(
167
- {
168
- "type": "http.response.body",
169
- "body": b"Bad Request: Too many duplicate headers",
170
- }
171
- )
172
- return
173
- # Run the WSGI app
174
- bytes_sent = 0
175
- for output in self.wsgi_application(environ, self.start_response):
176
- # If this is the first response, include the response headers
177
- if not self.response_started:
178
- self.response_started = True
179
- self.sync_send(self.response_start)
180
- # If the application supplies a Content-Length header
181
- if self.response_content_length is not None:
182
- # The server should not transmit more bytes to the client than the header allows
183
- bytes_allowed = self.response_content_length - bytes_sent
184
- if len(output) > bytes_allowed:
185
- output = output[:bytes_allowed]
186
- self.sync_send(
187
- {"type": "http.response.body", "body": output, "more_body": True}
188
- )
189
- bytes_sent += len(output)
190
- # The server should stop iterating over the response when enough data has been sent
191
- if bytes_sent == self.response_content_length:
192
- break
193
- # Close connection
194
- if not self.response_started:
195
- self.response_started = True
196
- self.sync_send(self.response_start)
197
- self.sync_send({"type": "http.response.body"})
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
myenv/lib/python3.12/site-packages/django-6.0.2.dist-info/INSTALLER DELETED
@@ -1 +0,0 @@
1
- pip
 
 
myenv/lib/python3.12/site-packages/django-6.0.2.dist-info/METADATA DELETED
@@ -1,93 +0,0 @@
1
- Metadata-Version: 2.4
2
- Name: Django
3
- Version: 6.0.2
4
- Summary: A high-level Python web framework that encourages rapid development and clean, pragmatic design.
5
- Author-email: Django Software Foundation <foundation@djangoproject.com>
6
- License-Expression: BSD-3-Clause
7
- Project-URL: Homepage, https://www.djangoproject.com/
8
- Project-URL: Documentation, https://docs.djangoproject.com/
9
- Project-URL: Release notes, https://docs.djangoproject.com/en/stable/releases/
10
- Project-URL: Funding, https://www.djangoproject.com/fundraising/
11
- Project-URL: Source, https://github.com/django/django
12
- Project-URL: Tracker, https://code.djangoproject.com/
13
- Classifier: Development Status :: 5 - Production/Stable
14
- Classifier: Environment :: Web Environment
15
- Classifier: Framework :: Django
16
- Classifier: Intended Audience :: Developers
17
- Classifier: Operating System :: OS Independent
18
- Classifier: Programming Language :: Python
19
- Classifier: Programming Language :: Python :: 3
20
- Classifier: Programming Language :: Python :: 3 :: Only
21
- Classifier: Programming Language :: Python :: 3.12
22
- Classifier: Programming Language :: Python :: 3.13
23
- Classifier: Programming Language :: Python :: 3.14
24
- Classifier: Topic :: Internet :: WWW/HTTP
25
- Classifier: Topic :: Internet :: WWW/HTTP :: Dynamic Content
26
- Classifier: Topic :: Internet :: WWW/HTTP :: WSGI
27
- Classifier: Topic :: Software Development :: Libraries :: Application Frameworks
28
- Classifier: Topic :: Software Development :: Libraries :: Python Modules
29
- Requires-Python: >=3.12
30
- Description-Content-Type: text/x-rst
31
- License-File: LICENSE
32
- License-File: LICENSE.python
33
- Requires-Dist: asgiref>=3.9.1
34
- Requires-Dist: sqlparse>=0.5.0
35
- Requires-Dist: tzdata; sys_platform == "win32"
36
- Provides-Extra: argon2
37
- Requires-Dist: argon2-cffi>=23.1.0; extra == "argon2"
38
- Provides-Extra: bcrypt
39
- Requires-Dist: bcrypt>=4.1.1; extra == "bcrypt"
40
- Dynamic: license-file
41
-
42
- ======
43
- Django
44
- ======
45
-
46
- Django is a high-level Python web framework that encourages rapid development
47
- and clean, pragmatic design. Thanks for checking it out.
48
-
49
- All documentation is in the "``docs``" directory and online at
50
- https://docs.djangoproject.com/en/stable/. If you're just getting started,
51
- here's how we recommend you read the docs:
52
-
53
- * First, read ``docs/intro/install.txt`` for instructions on installing Django.
54
-
55
- * Next, work through the tutorials in order (``docs/intro/tutorial01.txt``,
56
- ``docs/intro/tutorial02.txt``, etc.).
57
-
58
- * If you want to set up an actual deployment server, read
59
- ``docs/howto/deployment/index.txt`` for instructions.
60
-
61
- * You'll probably want to read through the topical guides (in ``docs/topics``)
62
- next; from there you can jump to the HOWTOs (in ``docs/howto``) for specific
63
- problems, and check out the reference (``docs/ref``) for gory details.
64
-
65
- * See ``docs/README`` for instructions on building an HTML version of the docs.
66
-
67
- Docs are updated rigorously. If you find any problems in the docs, or think
68
- they should be clarified in any way, please take 30 seconds to fill out a
69
- ticket here: https://code.djangoproject.com/newticket
70
-
71
- To get more help:
72
-
73
- * Join the `Django Discord community <https://chat.djangoproject.com>`_.
74
-
75
- * Join the community on the `Django Forum <https://forum.djangoproject.com/>`_.
76
-
77
- To contribute to Django:
78
-
79
- * Check out https://docs.djangoproject.com/en/dev/internals/contributing/ for
80
- information about getting involved.
81
-
82
- To run Django's test suite:
83
-
84
- * Follow the instructions in the "Unit tests" section of
85
- ``docs/internals/contributing/writing-code/unit-tests.txt``, published online at
86
- https://docs.djangoproject.com/en/dev/internals/contributing/writing-code/unit-tests/#running-the-unit-tests
87
-
88
- Supporting the Development of Django
89
- ====================================
90
-
91
- Django's development depends on your contributions.
92
-
93
- If you depend on Django, remember to support the Django Software Foundation: https://www.djangoproject.com/fundraising/
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
myenv/lib/python3.12/site-packages/django-6.0.2.dist-info/RECORD DELETED
The diff for this file is too large to render. See raw diff
 
myenv/lib/python3.12/site-packages/django-6.0.2.dist-info/REQUESTED DELETED
File without changes
myenv/lib/python3.12/site-packages/django-6.0.2.dist-info/WHEEL DELETED
@@ -1,5 +0,0 @@
1
- Wheel-Version: 1.0
2
- Generator: setuptools (80.10.2)
3
- Root-Is-Purelib: true
4
- Tag: py3-none-any
5
-
 
 
 
 
 
 
myenv/lib/python3.12/site-packages/django-6.0.2.dist-info/entry_points.txt DELETED
@@ -1,2 +0,0 @@
1
- [console_scripts]
2
- django-admin = django.core.management:execute_from_command_line
 
 
 
myenv/lib/python3.12/site-packages/django-6.0.2.dist-info/licenses/LICENSE DELETED
@@ -1,27 +0,0 @@
1
- Copyright (c) Django Software Foundation and individual contributors.
2
- All rights reserved.
3
-
4
- Redistribution and use in source and binary forms, with or without modification,
5
- are permitted provided that the following conditions are met:
6
-
7
- 1. Redistributions of source code must retain the above copyright notice,
8
- this list of conditions and the following disclaimer.
9
-
10
- 2. Redistributions in binary form must reproduce the above copyright
11
- notice, this list of conditions and the following disclaimer in the
12
- documentation and/or other materials provided with the distribution.
13
-
14
- 3. Neither the name of Django nor the names of its contributors may be used
15
- to endorse or promote products derived from this software without
16
- specific prior written permission.
17
-
18
- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
19
- ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
20
- WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
21
- DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
22
- ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
23
- (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
24
- LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
25
- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
27
- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
myenv/lib/python3.12/site-packages/django-6.0.2.dist-info/licenses/LICENSE.python DELETED
@@ -1,288 +0,0 @@
1
- Django is licensed under the three-clause BSD license; see the file
2
- LICENSE for details.
3
-
4
- Django includes code from the Python standard library, which is licensed under
5
- the Python license, a permissive open source license. The copyright and license
6
- is included below for compliance with Python's terms.
7
-
8
- ----------------------------------------------------------------------
9
-
10
- Copyright (c) 2001-present Python Software Foundation; All Rights Reserved
11
-
12
- A. HISTORY OF THE SOFTWARE
13
- ==========================
14
-
15
- Python was created in the early 1990s by Guido van Rossum at Stichting
16
- Mathematisch Centrum (CWI, see https://www.cwi.nl) in the Netherlands
17
- as a successor of a language called ABC. Guido remains Python's
18
- principal author, although it includes many contributions from others.
19
-
20
- In 1995, Guido continued his work on Python at the Corporation for
21
- National Research Initiatives (CNRI, see https://www.cnri.reston.va.us)
22
- in Reston, Virginia where he released several versions of the
23
- software.
24
-
25
- In May 2000, Guido and the Python core development team moved to
26
- BeOpen.com to form the BeOpen PythonLabs team. In October of the same
27
- year, the PythonLabs team moved to Digital Creations, which became
28
- Zope Corporation. In 2001, the Python Software Foundation (PSF, see
29
- https://www.python.org/psf/) was formed, a non-profit organization
30
- created specifically to own Python-related Intellectual Property.
31
- Zope Corporation was a sponsoring member of the PSF.
32
-
33
- All Python releases are Open Source (see https://opensource.org for
34
- the Open Source Definition). Historically, most, but not all, Python
35
- releases have also been GPL-compatible; the table below summarizes
36
- the various releases.
37
-
38
- Release Derived Year Owner GPL-
39
- from compatible? (1)
40
-
41
- 0.9.0 thru 1.2 1991-1995 CWI yes
42
- 1.3 thru 1.5.2 1.2 1995-1999 CNRI yes
43
- 1.6 1.5.2 2000 CNRI no
44
- 2.0 1.6 2000 BeOpen.com no
45
- 1.6.1 1.6 2001 CNRI yes (2)
46
- 2.1 2.0+1.6.1 2001 PSF no
47
- 2.0.1 2.0+1.6.1 2001 PSF yes
48
- 2.1.1 2.1+2.0.1 2001 PSF yes
49
- 2.1.2 2.1.1 2002 PSF yes
50
- 2.1.3 2.1.2 2002 PSF yes
51
- 2.2 and above 2.1.1 2001-now PSF yes
52
-
53
- Footnotes:
54
-
55
- (1) GPL-compatible doesn't mean that we're distributing Python under
56
- the GPL. All Python licenses, unlike the GPL, let you distribute
57
- a modified version without making your changes open source. The
58
- GPL-compatible licenses make it possible to combine Python with
59
- other software that is released under the GPL; the others don't.
60
-
61
- (2) According to Richard Stallman, 1.6.1 is not GPL-compatible,
62
- because its license has a choice of law clause. According to
63
- CNRI, however, Stallman's lawyer has told CNRI's lawyer that 1.6.1
64
- is "not incompatible" with the GPL.
65
-
66
- Thanks to the many outside volunteers who have worked under Guido's
67
- direction to make these releases possible.
68
-
69
-
70
- B. TERMS AND CONDITIONS FOR ACCESSING OR OTHERWISE USING PYTHON
71
- ===============================================================
72
-
73
- Python software and documentation are licensed under the
74
- Python Software Foundation License Version 2.
75
-
76
- Starting with Python 3.8.6, examples, recipes, and other code in
77
- the documentation are dual licensed under the PSF License Version 2
78
- and the Zero-Clause BSD license.
79
-
80
- Some software incorporated into Python is under different licenses.
81
- The licenses are listed with code falling under that license.
82
-
83
-
84
- PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2
85
- --------------------------------------------
86
-
87
- 1. This LICENSE AGREEMENT is between the Python Software Foundation
88
- ("PSF"), and the Individual or Organization ("Licensee") accessing and
89
- otherwise using this software ("Python") in source or binary form and
90
- its associated documentation.
91
-
92
- 2. Subject to the terms and conditions of this License Agreement, PSF hereby
93
- grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce,
94
- analyze, test, perform and/or display publicly, prepare derivative works,
95
- distribute, and otherwise use Python alone or in any derivative version,
96
- provided, however, that PSF's License Agreement and PSF's notice of copyright,
97
- i.e., "Copyright (c) 2001 Python Software Foundation; All Rights Reserved"
98
- are retained in Python alone or in any derivative version prepared by Licensee.
99
-
100
- 3. In the event Licensee prepares a derivative work that is based on
101
- or incorporates Python or any part thereof, and wants to make
102
- the derivative work available to others as provided herein, then
103
- Licensee hereby agrees to include in any such work a brief summary of
104
- the changes made to Python.
105
-
106
- 4. PSF is making Python available to Licensee on an "AS IS"
107
- basis. PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
108
- IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND
109
- DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS
110
- FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON WILL NOT
111
- INFRINGE ANY THIRD PARTY RIGHTS.
112
-
113
- 5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON
114
- FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS
115
- A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON,
116
- OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
117
-
118
- 6. This License Agreement will automatically terminate upon a material
119
- breach of its terms and conditions.
120
-
121
- 7. Nothing in this License Agreement shall be deemed to create any
122
- relationship of agency, partnership, or joint venture between PSF and
123
- Licensee. This License Agreement does not grant permission to use PSF
124
- trademarks or trade name in a trademark sense to endorse or promote
125
- products or services of Licensee, or any third party.
126
-
127
- 8. By copying, installing or otherwise using Python, Licensee
128
- agrees to be bound by the terms and conditions of this License
129
- Agreement.
130
-
131
-
132
- BEOPEN.COM LICENSE AGREEMENT FOR PYTHON 2.0
133
- -------------------------------------------
134
-
135
- BEOPEN PYTHON OPEN SOURCE LICENSE AGREEMENT VERSION 1
136
-
137
- 1. This LICENSE AGREEMENT is between BeOpen.com ("BeOpen"), having an
138
- office at 160 Saratoga Avenue, Santa Clara, CA 95051, and the
139
- Individual or Organization ("Licensee") accessing and otherwise using
140
- this software in source or binary form and its associated
141
- documentation ("the Software").
142
-
143
- 2. Subject to the terms and conditions of this BeOpen Python License
144
- Agreement, BeOpen hereby grants Licensee a non-exclusive,
145
- royalty-free, world-wide license to reproduce, analyze, test, perform
146
- and/or display publicly, prepare derivative works, distribute, and
147
- otherwise use the Software alone or in any derivative version,
148
- provided, however, that the BeOpen Python License is retained in the
149
- Software, alone or in any derivative version prepared by Licensee.
150
-
151
- 3. BeOpen is making the Software available to Licensee on an "AS IS"
152
- basis. BEOPEN MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
153
- IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, BEOPEN MAKES NO AND
154
- DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS
155
- FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF THE SOFTWARE WILL NOT
156
- INFRINGE ANY THIRD PARTY RIGHTS.
157
-
158
- 4. BEOPEN SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF THE
159
- SOFTWARE FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS
160
- AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THE SOFTWARE, OR ANY
161
- DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
162
-
163
- 5. This License Agreement will automatically terminate upon a material
164
- breach of its terms and conditions.
165
-
166
- 6. This License Agreement shall be governed by and interpreted in all
167
- respects by the law of the State of California, excluding conflict of
168
- law provisions. Nothing in this License Agreement shall be deemed to
169
- create any relationship of agency, partnership, or joint venture
170
- between BeOpen and Licensee. This License Agreement does not grant
171
- permission to use BeOpen trademarks or trade names in a trademark
172
- sense to endorse or promote products or services of Licensee, or any
173
- third party. As an exception, the "BeOpen Python" logos available at
174
- http://www.pythonlabs.com/logos.html may be used according to the
175
- permissions granted on that web page.
176
-
177
- 7. By copying, installing or otherwise using the software, Licensee
178
- agrees to be bound by the terms and conditions of this License
179
- Agreement.
180
-
181
-
182
- CNRI LICENSE AGREEMENT FOR PYTHON 1.6.1
183
- ---------------------------------------
184
-
185
- 1. This LICENSE AGREEMENT is between the Corporation for National
186
- Research Initiatives, having an office at 1895 Preston White Drive,
187
- Reston, VA 20191 ("CNRI"), and the Individual or Organization
188
- ("Licensee") accessing and otherwise using Python 1.6.1 software in
189
- source or binary form and its associated documentation.
190
-
191
- 2. Subject to the terms and conditions of this License Agreement, CNRI
192
- hereby grants Licensee a nonexclusive, royalty-free, world-wide
193
- license to reproduce, analyze, test, perform and/or display publicly,
194
- prepare derivative works, distribute, and otherwise use Python 1.6.1
195
- alone or in any derivative version, provided, however, that CNRI's
196
- License Agreement and CNRI's notice of copyright, i.e., "Copyright (c)
197
- 1995-2001 Corporation for National Research Initiatives; All Rights
198
- Reserved" are retained in Python 1.6.1 alone or in any derivative
199
- version prepared by Licensee. Alternately, in lieu of CNRI's License
200
- Agreement, Licensee may substitute the following text (omitting the
201
- quotes): "Python 1.6.1 is made available subject to the terms and
202
- conditions in CNRI's License Agreement. This Agreement together with
203
- Python 1.6.1 may be located on the internet using the following
204
- unique, persistent identifier (known as a handle): 1895.22/1013. This
205
- Agreement may also be obtained from a proxy server on the internet
206
- using the following URL: http://hdl.handle.net/1895.22/1013".
207
-
208
- 3. In the event Licensee prepares a derivative work that is based on
209
- or incorporates Python 1.6.1 or any part thereof, and wants to make
210
- the derivative work available to others as provided herein, then
211
- Licensee hereby agrees to include in any such work a brief summary of
212
- the changes made to Python 1.6.1.
213
-
214
- 4. CNRI is making Python 1.6.1 available to Licensee on an "AS IS"
215
- basis. CNRI MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
216
- IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, CNRI MAKES NO AND
217
- DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS
218
- FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON 1.6.1 WILL NOT
219
- INFRINGE ANY THIRD PARTY RIGHTS.
220
-
221
- 5. CNRI SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON
222
- 1.6.1 FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS
223
- A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 1.6.1,
224
- OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
225
-
226
- 6. This License Agreement will automatically terminate upon a material
227
- breach of its terms and conditions.
228
-
229
- 7. This License Agreement shall be governed by the federal
230
- intellectual property law of the United States, including without
231
- limitation the federal copyright law, and, to the extent such
232
- U.S. federal law does not apply, by the law of the Commonwealth of
233
- Virginia, excluding Virginia's conflict of law provisions.
234
- Notwithstanding the foregoing, with regard to derivative works based
235
- on Python 1.6.1 that incorporate non-separable material that was
236
- previously distributed under the GNU General Public License (GPL), the
237
- law of the Commonwealth of Virginia shall govern this License
238
- Agreement only as to issues arising under or with respect to
239
- Paragraphs 4, 5, and 7 of this License Agreement. Nothing in this
240
- License Agreement shall be deemed to create any relationship of
241
- agency, partnership, or joint venture between CNRI and Licensee. This
242
- License Agreement does not grant permission to use CNRI trademarks or
243
- trade name in a trademark sense to endorse or promote products or
244
- services of Licensee, or any third party.
245
-
246
- 8. By clicking on the "ACCEPT" button where indicated, or by copying,
247
- installing or otherwise using Python 1.6.1, Licensee agrees to be
248
- bound by the terms and conditions of this License Agreement.
249
-
250
- ACCEPT
251
-
252
-
253
- CWI LICENSE AGREEMENT FOR PYTHON 0.9.0 THROUGH 1.2
254
- --------------------------------------------------
255
-
256
- Copyright (c) 1991 - 1995, Stichting Mathematisch Centrum Amsterdam,
257
- The Netherlands. All rights reserved.
258
-
259
- Permission to use, copy, modify, and distribute this software and its
260
- documentation for any purpose and without fee is hereby granted,
261
- provided that the above copyright notice appear in all copies and that
262
- both that copyright notice and this permission notice appear in
263
- supporting documentation, and that the name of Stichting Mathematisch
264
- Centrum or CWI not be used in advertising or publicity pertaining to
265
- distribution of the software without specific, written prior
266
- permission.
267
-
268
- STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO
269
- THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
270
- FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE
271
- FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
272
- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
273
- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
274
- OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
275
-
276
- ZERO-CLAUSE BSD LICENSE FOR CODE IN THE PYTHON DOCUMENTATION
277
- ----------------------------------------------------------------------
278
-
279
- Permission to use, copy, modify, and/or distribute this software for any
280
- purpose with or without fee is hereby granted.
281
-
282
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
283
- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
284
- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
285
- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
286
- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
287
- OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
288
- PERFORMANCE OF THIS SOFTWARE.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
myenv/lib/python3.12/site-packages/django-6.0.2.dist-info/top_level.txt DELETED
@@ -1 +0,0 @@
1
- django
 
 
myenv/lib/python3.12/site-packages/django/__init__.py DELETED
@@ -1,24 +0,0 @@
1
- from django.utils.version import get_version
2
-
3
- VERSION = (6, 0, 2, "final", 0)
4
-
5
- __version__ = get_version(VERSION)
6
-
7
-
8
- def setup(set_prefix=True):
9
- """
10
- Configure the settings (this happens as a side effect of accessing the
11
- first setting), configure logging and populate the app registry.
12
- Set the thread-local urlresolvers script prefix if `set_prefix` is True.
13
- """
14
- from django.apps import apps
15
- from django.conf import settings
16
- from django.urls import set_script_prefix
17
- from django.utils.log import configure_logging
18
-
19
- configure_logging(settings.LOGGING_CONFIG, settings.LOGGING)
20
- if set_prefix:
21
- set_script_prefix(
22
- "/" if settings.FORCE_SCRIPT_NAME is None else settings.FORCE_SCRIPT_NAME
23
- )
24
- apps.populate(settings.INSTALLED_APPS)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
myenv/lib/python3.12/site-packages/django/__main__.py DELETED
@@ -1,10 +0,0 @@
1
- """
2
- Invokes django-admin when the django module is run as a script.
3
-
4
- Example: python -m django check
5
- """
6
-
7
- from django.core import management
8
-
9
- if __name__ == "__main__":
10
- management.execute_from_command_line()
 
 
 
 
 
 
 
 
 
 
 
myenv/lib/python3.12/site-packages/django/apps/__init__.py DELETED
@@ -1,4 +0,0 @@
1
- from .config import AppConfig
2
- from .registry import apps
3
-
4
- __all__ = ["AppConfig", "apps"]
 
 
 
 
 
myenv/lib/python3.12/site-packages/django/apps/config.py DELETED
@@ -1,274 +0,0 @@
1
- import inspect
2
- import os
3
- from importlib import import_module
4
-
5
- from django.core.exceptions import ImproperlyConfigured
6
- from django.utils.functional import cached_property
7
- from django.utils.module_loading import import_string, module_has_submodule
8
-
9
- APPS_MODULE_NAME = "apps"
10
- MODELS_MODULE_NAME = "models"
11
-
12
-
13
- class AppConfig:
14
- """Class representing a Django application and its configuration."""
15
-
16
- def __init__(self, app_name, app_module):
17
- # Full Python path to the application e.g. 'django.contrib.admin'.
18
- self.name = app_name
19
-
20
- # Root module for the application e.g. <module 'django.contrib.admin'
21
- # from 'django/contrib/admin/__init__.py'>.
22
- self.module = app_module
23
-
24
- # Reference to the Apps registry that holds this AppConfig. Set by the
25
- # registry when it registers the AppConfig instance.
26
- self.apps = None
27
-
28
- # The following attributes could be defined at the class level in a
29
- # subclass, hence the test-and-set pattern.
30
-
31
- # Last component of the Python path to the application e.g. 'admin'.
32
- # This value must be unique across a Django project.
33
- if not hasattr(self, "label"):
34
- self.label = app_name.rpartition(".")[2]
35
- if not self.label.isidentifier():
36
- raise ImproperlyConfigured(
37
- "The app label '%s' is not a valid Python identifier." % self.label
38
- )
39
-
40
- # Human-readable name for the application e.g. "Admin".
41
- if not hasattr(self, "verbose_name"):
42
- self.verbose_name = self.label.title()
43
-
44
- # Filesystem path to the application directory e.g.
45
- # '/path/to/django/contrib/admin'.
46
- if not hasattr(self, "path"):
47
- self.path = self._path_from_module(app_module)
48
-
49
- # Module containing models e.g. <module 'django.contrib.admin.models'
50
- # from 'django/contrib/admin/models.py'>. Set by import_models().
51
- # None if the application doesn't have a models module.
52
- self.models_module = None
53
-
54
- # Mapping of lowercase model names to model classes. Initially set to
55
- # None to prevent accidental access before import_models() runs.
56
- self.models = None
57
-
58
- def __repr__(self):
59
- return "<%s: %s>" % (self.__class__.__name__, self.label)
60
-
61
- @cached_property
62
- def default_auto_field(self):
63
- from django.conf import settings
64
-
65
- return settings.DEFAULT_AUTO_FIELD
66
-
67
- @property
68
- def _is_default_auto_field_overridden(self):
69
- return self.__class__.default_auto_field is not AppConfig.default_auto_field
70
-
71
- def _path_from_module(self, module):
72
- """Attempt to determine app's filesystem path from its module."""
73
- # See #21874 for extended discussion of the behavior of this method in
74
- # various cases.
75
- # Convert to list because __path__ may not support indexing.
76
- paths = list(getattr(module, "__path__", []))
77
- if len(paths) != 1:
78
- filename = getattr(module, "__file__", None)
79
- if filename is not None:
80
- paths = [os.path.dirname(filename)]
81
- else:
82
- # For unknown reasons, sometimes the list returned by __path__
83
- # contains duplicates that must be removed (#25246).
84
- paths = list(set(paths))
85
- if len(paths) > 1:
86
- raise ImproperlyConfigured(
87
- "The app module %r has multiple filesystem locations (%r); "
88
- "you must configure this app with an AppConfig subclass "
89
- "with a 'path' class attribute." % (module, paths)
90
- )
91
- elif not paths:
92
- raise ImproperlyConfigured(
93
- "The app module %r has no filesystem location, "
94
- "you must configure this app with an AppConfig subclass "
95
- "with a 'path' class attribute." % module
96
- )
97
- return paths[0]
98
-
99
- @classmethod
100
- def create(cls, entry):
101
- """
102
- Factory that creates an app config from an entry in INSTALLED_APPS.
103
- """
104
- # create() eventually returns app_config_class(app_name, app_module).
105
- app_config_class = None
106
- app_name = None
107
- app_module = None
108
-
109
- # If import_module succeeds, entry points to the app module.
110
- try:
111
- app_module = import_module(entry)
112
- except Exception:
113
- pass
114
- else:
115
- # If app_module has an apps submodule that defines a single
116
- # AppConfig subclass, use it automatically.
117
- # To prevent this, an AppConfig subclass can declare a class
118
- # variable default = False.
119
- # If the apps module defines more than one AppConfig subclass,
120
- # the default one can declare default = True.
121
- if module_has_submodule(app_module, APPS_MODULE_NAME):
122
- mod_path = "%s.%s" % (entry, APPS_MODULE_NAME)
123
- mod = import_module(mod_path)
124
- # Check if there's exactly one AppConfig candidate,
125
- # excluding those that explicitly define default = False.
126
- app_configs = [
127
- (name, candidate)
128
- for name, candidate in inspect.getmembers(mod, inspect.isclass)
129
- if (
130
- issubclass(candidate, cls)
131
- and candidate is not cls
132
- and getattr(candidate, "default", True)
133
- )
134
- ]
135
- if len(app_configs) == 1:
136
- app_config_class = app_configs[0][1]
137
- else:
138
- # Check if there's exactly one AppConfig subclass,
139
- # among those that explicitly define default = True.
140
- app_configs = [
141
- (name, candidate)
142
- for name, candidate in app_configs
143
- if getattr(candidate, "default", False)
144
- ]
145
- if len(app_configs) > 1:
146
- candidates = [repr(name) for name, _ in app_configs]
147
- raise RuntimeError(
148
- "%r declares more than one default AppConfig: "
149
- "%s." % (mod_path, ", ".join(candidates))
150
- )
151
- elif len(app_configs) == 1:
152
- app_config_class = app_configs[0][1]
153
-
154
- # Use the default app config class if we didn't find anything.
155
- if app_config_class is None:
156
- app_config_class = cls
157
- app_name = entry
158
-
159
- # If import_string succeeds, entry is an app config class.
160
- if app_config_class is None:
161
- try:
162
- app_config_class = import_string(entry)
163
- except Exception:
164
- pass
165
- # If both import_module and import_string failed, it means that entry
166
- # doesn't have a valid value.
167
- if app_module is None and app_config_class is None:
168
- # If the last component of entry starts with an uppercase letter,
169
- # then it was likely intended to be an app config class; if not,
170
- # an app module. Provide a nice error message in both cases.
171
- mod_path, _, cls_name = entry.rpartition(".")
172
- if mod_path and cls_name[0].isupper():
173
- # We could simply re-trigger the string import exception, but
174
- # we're going the extra mile and providing a better error
175
- # message for typos in INSTALLED_APPS.
176
- # This may raise ImportError, which is the best exception
177
- # possible if the module at mod_path cannot be imported.
178
- mod = import_module(mod_path)
179
- candidates = [
180
- repr(name)
181
- for name, candidate in inspect.getmembers(mod, inspect.isclass)
182
- if issubclass(candidate, cls) and candidate is not cls
183
- ]
184
- msg = "Module '%s' does not contain a '%s' class." % (
185
- mod_path,
186
- cls_name,
187
- )
188
- if candidates:
189
- msg += " Choices are: %s." % ", ".join(candidates)
190
- raise ImportError(msg)
191
- else:
192
- # Re-trigger the module import exception.
193
- import_module(entry)
194
-
195
- # Check for obvious errors. (This check prevents duck typing, but
196
- # it could be removed if it became a problem in practice.)
197
- if not issubclass(app_config_class, AppConfig):
198
- raise ImproperlyConfigured("'%s' isn't a subclass of AppConfig." % entry)
199
-
200
- # Obtain app name here rather than in AppClass.__init__ to keep
201
- # all error checking for entries in INSTALLED_APPS in one place.
202
- if app_name is None:
203
- try:
204
- app_name = app_config_class.name
205
- except AttributeError:
206
- raise ImproperlyConfigured("'%s' must supply a name attribute." % entry)
207
-
208
- # Ensure app_name points to a valid module.
209
- try:
210
- app_module = import_module(app_name)
211
- except ImportError:
212
- raise ImproperlyConfigured(
213
- "Cannot import '%s'. Check that '%s.%s.name' is correct."
214
- % (
215
- app_name,
216
- app_config_class.__module__,
217
- app_config_class.__qualname__,
218
- )
219
- )
220
-
221
- # Entry is a path to an app config class.
222
- return app_config_class(app_name, app_module)
223
-
224
- def get_model(self, model_name, require_ready=True):
225
- """
226
- Return the model with the given case-insensitive model_name.
227
-
228
- Raise LookupError if no model exists with this name.
229
- """
230
- if require_ready:
231
- self.apps.check_models_ready()
232
- else:
233
- self.apps.check_apps_ready()
234
- try:
235
- return self.models[model_name.lower()]
236
- except KeyError:
237
- raise LookupError(
238
- "App '%s' doesn't have a '%s' model." % (self.label, model_name)
239
- )
240
-
241
- def get_models(self, include_auto_created=False, include_swapped=False):
242
- """
243
- Return an iterable of models.
244
-
245
- By default, the following models aren't included:
246
-
247
- - auto-created models for many-to-many relations without
248
- an explicit intermediate table,
249
- - models that have been swapped out.
250
-
251
- Set the corresponding keyword argument to True to include such models.
252
- Keyword arguments aren't documented; they're a private API.
253
- """
254
- self.apps.check_models_ready()
255
- for model in self.models.values():
256
- if model._meta.auto_created and not include_auto_created:
257
- continue
258
- if model._meta.swapped and not include_swapped:
259
- continue
260
- yield model
261
-
262
- def import_models(self):
263
- # Dictionary of models for this app, primarily maintained in the
264
- # 'all_models' attribute of the Apps this AppConfig is attached to.
265
- self.models = self.apps.all_models[self.label]
266
-
267
- if module_has_submodule(self.module, MODELS_MODULE_NAME):
268
- models_module_name = "%s.%s" % (self.name, MODELS_MODULE_NAME)
269
- self.models_module = import_module(models_module_name)
270
-
271
- def ready(self):
272
- """
273
- Override this method in subclasses to run code when Django starts.
274
- """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
myenv/lib/python3.12/site-packages/django/apps/registry.py DELETED
@@ -1,438 +0,0 @@
1
- import functools
2
- import sys
3
- import threading
4
- import warnings
5
- from collections import Counter, defaultdict
6
- from functools import partial
7
-
8
- from django.core.exceptions import AppRegistryNotReady, ImproperlyConfigured
9
-
10
- from .config import AppConfig
11
-
12
-
13
- class Apps:
14
- """
15
- A registry that stores the configuration of installed applications.
16
-
17
- It also keeps track of models, e.g. to provide reverse relations.
18
- """
19
-
20
- def __init__(self, installed_apps=()):
21
- # installed_apps is set to None when creating the main registry
22
- # because it cannot be populated at that point. Other registries must
23
- # provide a list of installed apps and are populated immediately.
24
- if installed_apps is None and hasattr(sys.modules[__name__], "apps"):
25
- raise RuntimeError("You must supply an installed_apps argument.")
26
-
27
- # Mapping of app labels => model names => model classes. Every time a
28
- # model is imported, ModelBase.__new__ calls apps.register_model which
29
- # creates an entry in all_models. All imported models are registered,
30
- # regardless of whether they're defined in an installed application
31
- # and whether the registry has been populated. Since it isn't possible
32
- # to reimport a module safely (it could reexecute initialization code)
33
- # all_models is never overridden or reset.
34
- self.all_models = defaultdict(dict)
35
-
36
- # Mapping of labels to AppConfig instances for installed apps.
37
- self.app_configs = {}
38
-
39
- # Stack of app_configs. Used to store the current state in
40
- # set_available_apps and set_installed_apps.
41
- self.stored_app_configs = []
42
-
43
- # Whether the registry is populated.
44
- self.apps_ready = self.models_ready = self.ready = False
45
- # For the autoreloader.
46
- self.ready_event = threading.Event()
47
-
48
- # Lock for thread-safe population.
49
- self._lock = threading.RLock()
50
- self.loading = False
51
-
52
- # Maps ("app_label", "modelname") tuples to lists of functions to be
53
- # called when the corresponding model is ready. Used by this class's
54
- # `lazy_model_operation()` and `do_pending_operations()` methods.
55
- self._pending_operations = defaultdict(list)
56
-
57
- # Populate apps and models, unless it's the main registry.
58
- if installed_apps is not None:
59
- self.populate(installed_apps)
60
-
61
- def populate(self, installed_apps=None):
62
- """
63
- Load application configurations and models.
64
-
65
- Import each application module and then each model module.
66
-
67
- It is thread-safe and idempotent, but not reentrant.
68
- """
69
- if self.ready:
70
- return
71
-
72
- # populate() might be called by two threads in parallel on servers
73
- # that create threads before initializing the WSGI callable.
74
- with self._lock:
75
- if self.ready:
76
- return
77
-
78
- # An RLock prevents other threads from entering this section. The
79
- # compare and set operation below is atomic.
80
- if self.loading:
81
- # Prevent reentrant calls to avoid running AppConfig.ready()
82
- # methods twice.
83
- raise RuntimeError("populate() isn't reentrant")
84
- self.loading = True
85
-
86
- # Phase 1: initialize app configs and import app modules.
87
- for entry in installed_apps:
88
- if isinstance(entry, AppConfig):
89
- app_config = entry
90
- else:
91
- app_config = AppConfig.create(entry)
92
- if app_config.label in self.app_configs:
93
- raise ImproperlyConfigured(
94
- "Application labels aren't unique, "
95
- "duplicates: %s" % app_config.label
96
- )
97
-
98
- self.app_configs[app_config.label] = app_config
99
- app_config.apps = self
100
-
101
- # Check for duplicate app names.
102
- counts = Counter(
103
- app_config.name for app_config in self.app_configs.values()
104
- )
105
- duplicates = [name for name, count in counts.most_common() if count > 1]
106
- if duplicates:
107
- raise ImproperlyConfigured(
108
- "Application names aren't unique, "
109
- "duplicates: %s" % ", ".join(duplicates)
110
- )
111
-
112
- self.apps_ready = True
113
-
114
- # Phase 2: import models modules.
115
- for app_config in self.app_configs.values():
116
- app_config.import_models()
117
-
118
- self.clear_cache()
119
-
120
- self.models_ready = True
121
-
122
- # Phase 3: run ready() methods of app configs.
123
- for app_config in self.get_app_configs():
124
- app_config.ready()
125
-
126
- self.ready = True
127
- self.ready_event.set()
128
-
129
- def check_apps_ready(self):
130
- """Raise an exception if all apps haven't been imported yet."""
131
- if not self.apps_ready:
132
- from django.conf import settings
133
-
134
- # If "not ready" is due to unconfigured settings, accessing
135
- # INSTALLED_APPS raises a more helpful ImproperlyConfigured
136
- # exception.
137
- settings.INSTALLED_APPS
138
- raise AppRegistryNotReady("Apps aren't loaded yet.")
139
-
140
- def check_models_ready(self):
141
- """Raise an exception if all models haven't been imported yet."""
142
- if not self.models_ready:
143
- raise AppRegistryNotReady("Models aren't loaded yet.")
144
-
145
- def get_app_configs(self):
146
- """Import applications and return an iterable of app configs."""
147
- self.check_apps_ready()
148
- return self.app_configs.values()
149
-
150
- def get_app_config(self, app_label):
151
- """
152
- Import applications and returns an app config for the given label.
153
-
154
- Raise LookupError if no application exists with this label.
155
- """
156
- self.check_apps_ready()
157
- try:
158
- return self.app_configs[app_label]
159
- except KeyError:
160
- message = "No installed app with label '%s'." % app_label
161
- for app_config in self.get_app_configs():
162
- if app_config.name == app_label:
163
- message += " Did you mean '%s'?" % app_config.label
164
- break
165
- raise LookupError(message)
166
-
167
- # This method is performance-critical at least for Django's test suite.
168
- @functools.cache
169
- def get_models(self, include_auto_created=False, include_swapped=False):
170
- """
171
- Return a list of all installed models.
172
-
173
- By default, the following models aren't included:
174
-
175
- - auto-created models for many-to-many relations without
176
- an explicit intermediate table,
177
- - models that have been swapped out.
178
-
179
- Set the corresponding keyword argument to True to include such models.
180
- """
181
- self.check_models_ready()
182
-
183
- result = []
184
- for app_config in self.app_configs.values():
185
- result.extend(app_config.get_models(include_auto_created, include_swapped))
186
- return result
187
-
188
- def get_model(self, app_label, model_name=None, require_ready=True):
189
- """
190
- Return the model matching the given app_label and model_name.
191
-
192
- As a shortcut, app_label may be in the form <app_label>.<model_name>.
193
-
194
- model_name is case-insensitive.
195
-
196
- Raise LookupError if no application exists with this label, or no
197
- model exists with this name in the application. Raise ValueError if
198
- called with a single argument that doesn't contain exactly one dot.
199
- """
200
- if require_ready:
201
- self.check_models_ready()
202
- else:
203
- self.check_apps_ready()
204
-
205
- if model_name is None:
206
- app_label, model_name = app_label.split(".")
207
-
208
- app_config = self.get_app_config(app_label)
209
-
210
- if not require_ready and app_config.models is None:
211
- app_config.import_models()
212
-
213
- return app_config.get_model(model_name, require_ready=require_ready)
214
-
215
- def register_model(self, app_label, model):
216
- # Since this method is called when models are imported, it cannot
217
- # perform imports because of the risk of import loops. It mustn't
218
- # call get_app_config().
219
- model_name = model._meta.model_name
220
- app_models = self.all_models[app_label]
221
- if model_name in app_models:
222
- if (
223
- model.__name__ == app_models[model_name].__name__
224
- and model.__module__ == app_models[model_name].__module__
225
- ):
226
- warnings.warn(
227
- "Model '%s.%s' was already registered. Reloading models is not "
228
- "advised as it can lead to inconsistencies, most notably with "
229
- "related models." % (app_label, model_name),
230
- RuntimeWarning,
231
- stacklevel=2,
232
- )
233
- else:
234
- raise RuntimeError(
235
- "Conflicting '%s' models in application '%s': %s and %s."
236
- % (model_name, app_label, app_models[model_name], model)
237
- )
238
- app_models[model_name] = model
239
- self.do_pending_operations(model)
240
- self.clear_cache()
241
-
242
- def is_installed(self, app_name):
243
- """
244
- Check whether an application with this name exists in the registry.
245
-
246
- app_name is the full name of the app e.g. 'django.contrib.admin'.
247
- """
248
- self.check_apps_ready()
249
- return any(ac.name == app_name for ac in self.app_configs.values())
250
-
251
- def get_containing_app_config(self, object_name):
252
- """
253
- Look for an app config containing a given object.
254
-
255
- object_name is the dotted Python path to the object.
256
-
257
- Return the app config for the inner application in case of nesting.
258
- Return None if the object isn't in any registered app config.
259
- """
260
- self.check_apps_ready()
261
- candidates = []
262
- for app_config in self.app_configs.values():
263
- if object_name.startswith(app_config.name):
264
- subpath = object_name.removeprefix(app_config.name)
265
- if subpath == "" or subpath[0] == ".":
266
- candidates.append(app_config)
267
- if candidates:
268
- return sorted(candidates, key=lambda ac: -len(ac.name))[0]
269
-
270
- def get_registered_model(self, app_label, model_name):
271
- """
272
- Similar to get_model(), but doesn't require that an app exists with
273
- the given app_label.
274
-
275
- It's safe to call this method at import time, even while the registry
276
- is being populated.
277
- """
278
- model = self.all_models[app_label].get(model_name.lower())
279
- if model is None:
280
- raise LookupError("Model '%s.%s' not registered." % (app_label, model_name))
281
- return model
282
-
283
- @functools.cache
284
- def get_swappable_settings_name(self, to_string):
285
- """
286
- For a given model string (e.g. "auth.User"), return the name of the
287
- corresponding settings name if it refers to a swappable model. If the
288
- referred model is not swappable, return None.
289
-
290
- This method is decorated with @functools.cache because it's performance
291
- critical when it comes to migrations. Since the swappable settings
292
- don't change after Django has loaded the settings, there is no reason
293
- to get the respective settings attribute over and over again.
294
- """
295
- to_string = to_string.lower()
296
- for model in self.get_models(include_swapped=True):
297
- swapped = model._meta.swapped
298
- # Is this model swapped out for the model given by to_string?
299
- if swapped and swapped.lower() == to_string:
300
- return model._meta.swappable
301
- # Is this model swappable and the one given by to_string?
302
- if model._meta.swappable and model._meta.label_lower == to_string:
303
- return model._meta.swappable
304
- return None
305
-
306
- def set_available_apps(self, available):
307
- """
308
- Restrict the set of installed apps used by get_app_config[s].
309
-
310
- available must be an iterable of application names.
311
-
312
- set_available_apps() must be balanced with unset_available_apps().
313
-
314
- Primarily used for performance optimization in TransactionTestCase.
315
-
316
- This method is safe in the sense that it doesn't trigger any imports.
317
- """
318
- available = set(available)
319
- installed = {app_config.name for app_config in self.get_app_configs()}
320
- if not available.issubset(installed):
321
- raise ValueError(
322
- "Available apps isn't a subset of installed apps, extra apps: %s"
323
- % ", ".join(available - installed)
324
- )
325
-
326
- self.stored_app_configs.append(self.app_configs)
327
- self.app_configs = {
328
- label: app_config
329
- for label, app_config in self.app_configs.items()
330
- if app_config.name in available
331
- }
332
- self.clear_cache()
333
-
334
- def unset_available_apps(self):
335
- """Cancel a previous call to set_available_apps()."""
336
- self.app_configs = self.stored_app_configs.pop()
337
- self.clear_cache()
338
-
339
- def set_installed_apps(self, installed):
340
- """
341
- Enable a different set of installed apps for get_app_config[s].
342
-
343
- installed must be an iterable in the same format as INSTALLED_APPS.
344
-
345
- set_installed_apps() must be balanced with unset_installed_apps(),
346
- even if it exits with an exception.
347
-
348
- Primarily used as a receiver of the setting_changed signal in tests.
349
-
350
- This method may trigger new imports, which may add new models to the
351
- registry of all imported models. They will stay in the registry even
352
- after unset_installed_apps(). Since it isn't possible to replay
353
- imports safely (e.g. that could lead to registering listeners twice),
354
- models are registered when they're imported and never removed.
355
- """
356
- if not self.ready:
357
- raise AppRegistryNotReady("App registry isn't ready yet.")
358
- self.stored_app_configs.append(self.app_configs)
359
- self.app_configs = {}
360
- self.apps_ready = self.models_ready = self.loading = self.ready = False
361
- self.clear_cache()
362
- self.populate(installed)
363
-
364
- def unset_installed_apps(self):
365
- """Cancel a previous call to set_installed_apps()."""
366
- self.app_configs = self.stored_app_configs.pop()
367
- self.apps_ready = self.models_ready = self.ready = True
368
- self.clear_cache()
369
-
370
- def clear_cache(self):
371
- """
372
- Clear all internal caches, for methods that alter the app registry.
373
-
374
- This is mostly used in tests.
375
- """
376
- self.get_swappable_settings_name.cache_clear()
377
- # Call expire cache on each model. This will purge
378
- # the relation tree and the fields cache.
379
- self.get_models.cache_clear()
380
- if self.ready:
381
- # Circumvent self.get_models() to prevent that the cache is
382
- # refilled. This particularly prevents that an empty value is
383
- # cached while cloning.
384
- for app_config in self.app_configs.values():
385
- for model in app_config.get_models(include_auto_created=True):
386
- model._meta._expire_cache()
387
-
388
- def lazy_model_operation(self, function, *model_keys):
389
- """
390
- Take a function and a number of ("app_label", "modelname") tuples, and
391
- when all the corresponding models have been imported and registered,
392
- call the function with the model classes as its arguments.
393
-
394
- The function passed to this method must accept exactly n models as
395
- arguments, where n=len(model_keys).
396
- """
397
- # Base case: no arguments, just execute the function.
398
- if not model_keys:
399
- function()
400
- # Recursive case: take the head of model_keys, wait for the
401
- # corresponding model class to be imported and registered, then apply
402
- # that argument to the supplied function. Pass the resulting partial
403
- # to lazy_model_operation() along with the remaining model args and
404
- # repeat until all models are loaded and all arguments are applied.
405
- else:
406
- next_model, *more_models = model_keys
407
-
408
- # This will be executed after the class corresponding to next_model
409
- # has been imported and registered. The `func` attribute provides
410
- # duck-type compatibility with partials.
411
- def apply_next_model(model):
412
- next_function = partial(apply_next_model.func, model)
413
- self.lazy_model_operation(next_function, *more_models)
414
-
415
- apply_next_model.func = function
416
-
417
- # If the model has already been imported and registered, partially
418
- # apply it to the function now. If not, add it to the list of
419
- # pending operations for the model, where it will be executed with
420
- # the model class as its sole argument once the model is ready.
421
- try:
422
- model_class = self.get_registered_model(*next_model)
423
- except LookupError:
424
- self._pending_operations[next_model].append(apply_next_model)
425
- else:
426
- apply_next_model(model_class)
427
-
428
- def do_pending_operations(self, model):
429
- """
430
- Take a newly-prepared model and pass it to each function waiting for
431
- it. This is called at the very end of Apps.register_model().
432
- """
433
- key = model._meta.app_label, model._meta.model_name
434
- for function in self._pending_operations.pop(key, []):
435
- function(model)
436
-
437
-
438
- apps = Apps(installed_apps=None)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
myenv/lib/python3.12/site-packages/django/conf/__init__.py DELETED
@@ -1,257 +0,0 @@
1
- """
2
- Settings and configuration for Django.
3
-
4
- Read values from the module specified by the DJANGO_SETTINGS_MODULE environment
5
- variable, and then from django.conf.global_settings; see the global_settings.py
6
- for a list of all possible variables.
7
- """
8
-
9
- import importlib
10
- import os
11
- import time
12
- import traceback
13
- import warnings
14
- from pathlib import Path
15
-
16
- import django
17
- from django.conf import global_settings
18
- from django.core.exceptions import ImproperlyConfigured
19
- from django.utils.functional import LazyObject, empty
20
-
21
- ENVIRONMENT_VARIABLE = "DJANGO_SETTINGS_MODULE"
22
- DEFAULT_STORAGE_ALIAS = "default"
23
- STATICFILES_STORAGE_ALIAS = "staticfiles"
24
-
25
-
26
- class SettingsReference(str):
27
- """
28
- String subclass which references a current settings value. It's treated as
29
- the value in memory but serializes to a settings.NAME attribute reference.
30
- """
31
-
32
- def __new__(self, value, setting_name):
33
- return str.__new__(self, value)
34
-
35
- def __init__(self, value, setting_name):
36
- self.setting_name = setting_name
37
-
38
-
39
- class LazySettings(LazyObject):
40
- """
41
- A lazy proxy for either global Django settings or a custom settings object.
42
- The user can manually configure settings prior to using them. Otherwise,
43
- Django uses the settings module pointed to by DJANGO_SETTINGS_MODULE.
44
- """
45
-
46
- def _setup(self, name=None):
47
- """
48
- Load the settings module pointed to by the environment variable. This
49
- is used the first time settings are needed, if the user hasn't
50
- configured settings manually.
51
- """
52
- settings_module = os.environ.get(ENVIRONMENT_VARIABLE)
53
- if not settings_module:
54
- desc = ("setting %s" % name) if name else "settings"
55
- raise ImproperlyConfigured(
56
- "Requested %s, but settings are not configured. "
57
- "You must either define the environment variable %s "
58
- "or call settings.configure() before accessing settings."
59
- % (desc, ENVIRONMENT_VARIABLE)
60
- )
61
-
62
- self._wrapped = Settings(settings_module)
63
-
64
- def __repr__(self):
65
- # Hardcode the class name as otherwise it yields 'Settings'.
66
- if self._wrapped is empty:
67
- return "<LazySettings [Unevaluated]>"
68
- return '<LazySettings "%(settings_module)s">' % {
69
- "settings_module": self._wrapped.SETTINGS_MODULE,
70
- }
71
-
72
- def __getattr__(self, name):
73
- """Return the value of a setting and cache it in self.__dict__."""
74
- if (_wrapped := self._wrapped) is empty:
75
- self._setup(name)
76
- _wrapped = self._wrapped
77
- val = getattr(_wrapped, name)
78
-
79
- # Special case some settings which require further modification.
80
- # This is done here for performance reasons so the modified value is
81
- # cached.
82
- if name in {"MEDIA_URL", "STATIC_URL"} and val is not None:
83
- val = self._add_script_prefix(val)
84
- elif name == "SECRET_KEY" and not val:
85
- raise ImproperlyConfigured("The SECRET_KEY setting must not be empty.")
86
-
87
- self.__dict__[name] = val
88
- return val
89
-
90
- def __setattr__(self, name, value):
91
- """
92
- Set the value of setting. Clear all cached values if _wrapped changes
93
- (@override_settings does this) or clear single values when set.
94
- """
95
- if name == "_wrapped":
96
- self.__dict__.clear()
97
- else:
98
- self.__dict__.pop(name, None)
99
- super().__setattr__(name, value)
100
-
101
- def __delattr__(self, name):
102
- """Delete a setting and clear it from cache if needed."""
103
- super().__delattr__(name)
104
- self.__dict__.pop(name, None)
105
-
106
- def configure(self, default_settings=global_settings, **options):
107
- """
108
- Called to manually configure the settings. The 'default_settings'
109
- parameter sets where to retrieve any unspecified values from (its
110
- argument must support attribute access (__getattr__)).
111
- """
112
- if self._wrapped is not empty:
113
- raise RuntimeError("Settings already configured.")
114
- holder = UserSettingsHolder(default_settings)
115
- for name, value in options.items():
116
- if not name.isupper():
117
- raise TypeError("Setting %r must be uppercase." % name)
118
- setattr(holder, name, value)
119
- self._wrapped = holder
120
-
121
- @staticmethod
122
- def _add_script_prefix(value):
123
- """
124
- Add SCRIPT_NAME prefix to relative paths.
125
-
126
- Useful when the app is being served at a subpath and manually prefixing
127
- subpath to STATIC_URL and MEDIA_URL in settings is inconvenient.
128
- """
129
- # Don't apply prefix to absolute paths and URLs.
130
- if value.startswith(("http://", "https://", "/")):
131
- return value
132
- from django.urls import get_script_prefix
133
-
134
- return "%s%s" % (get_script_prefix(), value)
135
-
136
- @property
137
- def configured(self):
138
- """Return True if the settings have already been configured."""
139
- return self._wrapped is not empty
140
-
141
- def _show_deprecation_warning(self, message, category):
142
- stack = traceback.extract_stack()
143
- # Show a warning if the setting is used outside of Django.
144
- # Stack index: -1 this line, -2 the property, -3 the
145
- # LazyObject __getattribute__(), -4 the caller.
146
- filename, _, _, _ = stack[-4]
147
- if not filename.startswith(os.path.dirname(django.__file__)):
148
- warnings.warn(message, category, stacklevel=2)
149
-
150
-
151
- class Settings:
152
- def __init__(self, settings_module):
153
- # update this dict from global settings (but only for ALL_CAPS
154
- # settings)
155
- for setting in dir(global_settings):
156
- if setting.isupper():
157
- setattr(self, setting, getattr(global_settings, setting))
158
-
159
- # store the settings module in case someone later cares
160
- self.SETTINGS_MODULE = settings_module
161
-
162
- mod = importlib.import_module(self.SETTINGS_MODULE)
163
-
164
- tuple_settings = (
165
- "ALLOWED_HOSTS",
166
- "INSTALLED_APPS",
167
- "TEMPLATE_DIRS",
168
- "LOCALE_PATHS",
169
- "SECRET_KEY_FALLBACKS",
170
- )
171
- self._explicit_settings = set()
172
- for setting in dir(mod):
173
- if setting.isupper():
174
- setting_value = getattr(mod, setting)
175
-
176
- if setting in tuple_settings and not isinstance(
177
- setting_value, (list, tuple)
178
- ):
179
- raise ImproperlyConfigured(
180
- "The %s setting must be a list or a tuple." % setting
181
- )
182
- setattr(self, setting, setting_value)
183
- self._explicit_settings.add(setting)
184
-
185
- if hasattr(time, "tzset") and self.TIME_ZONE:
186
- # When we can, attempt to validate the timezone. If we can't find
187
- # this file, no check happens and it's harmless.
188
- zoneinfo_root = Path("/usr/share/zoneinfo")
189
- zone_info_file = zoneinfo_root.joinpath(*self.TIME_ZONE.split("/"))
190
- if zoneinfo_root.exists() and not zone_info_file.exists():
191
- raise ValueError("Incorrect timezone setting: %s" % self.TIME_ZONE)
192
- # Move the time zone info into os.environ. See ticket #2315 for why
193
- # we don't do this unconditionally (breaks Windows).
194
- os.environ["TZ"] = self.TIME_ZONE
195
- time.tzset()
196
-
197
- def is_overridden(self, setting):
198
- return setting in self._explicit_settings
199
-
200
- def __repr__(self):
201
- return '<%(cls)s "%(settings_module)s">' % {
202
- "cls": self.__class__.__name__,
203
- "settings_module": self.SETTINGS_MODULE,
204
- }
205
-
206
-
207
- class UserSettingsHolder:
208
- """Holder for user configured settings."""
209
-
210
- # SETTINGS_MODULE doesn't make much sense in the manually configured
211
- # (standalone) case.
212
- SETTINGS_MODULE = None
213
-
214
- def __init__(self, default_settings):
215
- """
216
- Requests for configuration variables not in this class are satisfied
217
- from the module specified in default_settings (if possible).
218
- """
219
- self.__dict__["_deleted"] = set()
220
- self.default_settings = default_settings
221
-
222
- def __getattr__(self, name):
223
- if not name.isupper() or name in self._deleted:
224
- raise AttributeError
225
- return getattr(self.default_settings, name)
226
-
227
- def __setattr__(self, name, value):
228
- self._deleted.discard(name)
229
- super().__setattr__(name, value)
230
-
231
- def __delattr__(self, name):
232
- self._deleted.add(name)
233
- if hasattr(self, name):
234
- super().__delattr__(name)
235
-
236
- def __dir__(self):
237
- return sorted(
238
- s
239
- for s in [*self.__dict__, *dir(self.default_settings)]
240
- if s not in self._deleted
241
- )
242
-
243
- def is_overridden(self, setting):
244
- deleted = setting in self._deleted
245
- set_locally = setting in self.__dict__
246
- set_on_default = getattr(
247
- self.default_settings, "is_overridden", lambda s: False
248
- )(setting)
249
- return deleted or set_locally or set_on_default
250
-
251
- def __repr__(self):
252
- return "<%(cls)s>" % {
253
- "cls": self.__class__.__name__,
254
- }
255
-
256
-
257
- settings = LazySettings()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
myenv/lib/python3.12/site-packages/django/conf/app_template/__init__.py-tpl DELETED
File without changes
myenv/lib/python3.12/site-packages/django/conf/app_template/admin.py-tpl DELETED
@@ -1,3 +0,0 @@
1
- from django.contrib import admin
2
-
3
- # Register your models here.
 
 
 
 
myenv/lib/python3.12/site-packages/django/conf/app_template/apps.py-tpl DELETED
@@ -1,5 +0,0 @@
1
- from django.apps import AppConfig
2
-
3
-
4
- class {{ camel_case_app_name }}Config(AppConfig):
5
- name = '{{ app_name }}'
 
 
 
 
 
 
myenv/lib/python3.12/site-packages/django/conf/app_template/migrations/__init__.py-tpl DELETED
File without changes
myenv/lib/python3.12/site-packages/django/conf/app_template/models.py-tpl DELETED
@@ -1,3 +0,0 @@
1
- from django.db import models
2
-
3
- # Create your models here.