diff --git a/.github/workflows/ci-cd.yml b/.github/workflows/ci-cd.yml new file mode 100644 index 000000000..3a34915cd --- /dev/null +++ b/.github/workflows/ci-cd.yml @@ -0,0 +1,70 @@ +name: DevSecOps-Pipeline + +on: + push: + branches: [ "main", "develop", "feature/ci-cd-pipeline" ] + pull_request: + branches: [ "main", "develop", "feature/ci-cd-pipeline" ] + +jobs: + security-scan: + runs-on: ubuntu-latest + permissions: + security-events: write + actions: read + contents: read + + steps: + - name: Checkout Code + uses: actions/checkout@v4 + + - name: Set up Python + uses: actions/setup-python@v5 + with: + python-version: '3.11' + + - name: Install Dependencies & Setup App + run: | + pip install "SQLAlchemy<2.0" "itsdangerous<2.1" "Werkzeug<2.1" Pillow + pip install flask==2.0.1 flask-sqlalchemy==2.5.1 flask-bcrypt flask-login flask-mail flask-wtf email_validator bandit pytest + + export SECRET_KEY="supersecretkey123" + export SQLALCHEMY_DATABASE_URI="sqlite:///site.db" + cd Python/Flask_Blog/11-Blueprints + python3 -c "from flaskblog import create_app, db; app = create_app(); app.app_context().push(); db.create_all()" + python3 run.py & + sleep 10 + + - name: Run SAST Scan (Bandit) + run: bandit -r ./Python/Flask_Blog/11-Blueprints -lll --exit-zero + + - name: Initialize CodeQL + uses: github/codeql-action/init@v3 + with: + languages: python + + - name: Perform CodeQL Analysis + uses: github/codeql-action/analyze@v3 + + - name: Create ZAP workspace + run: | + mkdir -p ${{ github.workspace }}/zap/wrk + chmod -R 777 ${{ github.workspace }}/zap/wrk + + - name: ZAP Scan Action + uses: zaproxy/action-baseline@v0.12.0 + with: + token: ${{ secrets.GITHUB_TOKEN }} + target: 'http://localhost:5000' + fail_action: false + + - name: Final Critical Check + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + count=$(gh api repos/${{ github.repository }}/code-scanning/alerts?state=open \ + --jq '[.[] | select(.rule.security_severity_level == "high" or .rule.security_severity_level == "critical")] | length') + if [ "$count" -gt 0 ]; then + echo "FAILURE: $count High/Critical vulnerabilities found." + exit 1 + fi diff --git a/BeautifulSoup/scrape.py b/BeautifulSoup/scrape.py index 42a191f1c..e56730526 100644 --- a/BeautifulSoup/scrape.py +++ b/BeautifulSoup/scrape.py @@ -2,7 +2,7 @@ import requests import csv -source = requests.get('http://coreyms.com').text +source = requests.get('http://coreyms.com', timeout=5).text soup = BeautifulSoup(source, 'lxml') diff --git a/Python-JSON/api.py b/Python-JSON/api.py index 0ce9f34d8..606abce24 100644 --- a/Python-JSON/api.py +++ b/Python-JSON/api.py @@ -1,8 +1,8 @@ -import json -from urllib.request import urlopen +import requests # Change the import at the top -with urlopen("https://finance.yahoo.com/webservice/v1/symbols/allcurrencies/quote?format=json") as response: - source = response.read() +# Replace the urlopen block with this: +response = requests.get("https://yahoo.com", timeout=5) +source = response.content data = json.loads(source) diff --git a/Python-Unit-Testing/employee.py b/Python-Unit-Testing/employee.py index 0470fe328..6e397f4b9 100644 --- a/Python-Unit-Testing/employee.py +++ b/Python-Unit-Testing/employee.py @@ -24,7 +24,7 @@ def apply_raise(self): self.pay = int(self.pay * self.raise_amt) def monthly_schedule(self, month): - response = requests.get(f'http://company.com/{self.last}/{month}') + response = requests.get(f'http://company.com/{self.last}/{month}', timeout=5) if response.ok: return response.text else: diff --git a/Python/Flask_Blog/01-Getting-Started/flaskblog.py b/Python/Flask_Blog/01-Getting-Started/flaskblog.py index 04deb7bd0..a5aa76104 100644 --- a/Python/Flask_Blog/01-Getting-Started/flaskblog.py +++ b/Python/Flask_Blog/01-Getting-Started/flaskblog.py @@ -14,4 +14,4 @@ def about(): if __name__ == '__main__': - app.run(debug=True) + app.run(debug=False) diff --git a/Python/Flask_Blog/02-Templates/flaskblog.py b/Python/Flask_Blog/02-Templates/flaskblog.py index a54bab8d2..0ce924b4a 100644 --- a/Python/Flask_Blog/02-Templates/flaskblog.py +++ b/Python/Flask_Blog/02-Templates/flaskblog.py @@ -29,4 +29,4 @@ def about(): if __name__ == '__main__': - app.run(debug=True) + app.run(debug=False) diff --git a/Python/Flask_Blog/03-Forms-and-Validation/flaskblog.py b/Python/Flask_Blog/03-Forms-and-Validation/flaskblog.py index 8c5d7398a..e52aa135d 100644 --- a/Python/Flask_Blog/03-Forms-and-Validation/flaskblog.py +++ b/Python/Flask_Blog/03-Forms-and-Validation/flaskblog.py @@ -53,4 +53,4 @@ def login(): if __name__ == '__main__': - app.run(debug=True) + app.run(debug=False) diff --git a/Python/Flask_Blog/04-Database/flaskblog.py b/Python/Flask_Blog/04-Database/flaskblog.py index 8f7f6571d..98055f277 100644 --- a/Python/Flask_Blog/04-Database/flaskblog.py +++ b/Python/Flask_Blog/04-Database/flaskblog.py @@ -81,4 +81,4 @@ def login(): if __name__ == '__main__': - app.run(debug=True) + app.run(debug=False) diff --git a/Python/Flask_Blog/05-Package-Structure/run.py b/Python/Flask_Blog/05-Package-Structure/run.py index b1324e6b3..0aa8134c0 100644 --- a/Python/Flask_Blog/05-Package-Structure/run.py +++ b/Python/Flask_Blog/05-Package-Structure/run.py @@ -1,4 +1,4 @@ from flaskblog import app if __name__ == '__main__': - app.run(debug=True) + app.run(debug=False) diff --git a/Python/Flask_Blog/06-Login-Auth/run.py b/Python/Flask_Blog/06-Login-Auth/run.py index b1324e6b3..0aa8134c0 100644 --- a/Python/Flask_Blog/06-Login-Auth/run.py +++ b/Python/Flask_Blog/06-Login-Auth/run.py @@ -1,4 +1,4 @@ from flaskblog import app if __name__ == '__main__': - app.run(debug=True) + app.run(debug=False) diff --git a/Python/Flask_Blog/07-User-Account-Profile-Pic/run.py b/Python/Flask_Blog/07-User-Account-Profile-Pic/run.py index b1324e6b3..0aa8134c0 100644 --- a/Python/Flask_Blog/07-User-Account-Profile-Pic/run.py +++ b/Python/Flask_Blog/07-User-Account-Profile-Pic/run.py @@ -1,4 +1,4 @@ from flaskblog import app if __name__ == '__main__': - app.run(debug=True) + app.run(debug=False) diff --git a/Python/Flask_Blog/08-Posts/run.py b/Python/Flask_Blog/08-Posts/run.py index b1324e6b3..0aa8134c0 100644 --- a/Python/Flask_Blog/08-Posts/run.py +++ b/Python/Flask_Blog/08-Posts/run.py @@ -1,4 +1,4 @@ from flaskblog import app if __name__ == '__main__': - app.run(debug=True) + app.run(debug=False) diff --git a/Python/Flask_Blog/09-Pagination/run.py b/Python/Flask_Blog/09-Pagination/run.py index b1324e6b3..0aa8134c0 100644 --- a/Python/Flask_Blog/09-Pagination/run.py +++ b/Python/Flask_Blog/09-Pagination/run.py @@ -1,4 +1,4 @@ from flaskblog import app if __name__ == '__main__': - app.run(debug=True) + app.run(debug=False) diff --git a/Python/Flask_Blog/10-Password-Reset-Email/run.py b/Python/Flask_Blog/10-Password-Reset-Email/run.py index b1324e6b3..0aa8134c0 100644 --- a/Python/Flask_Blog/10-Password-Reset-Email/run.py +++ b/Python/Flask_Blog/10-Password-Reset-Email/run.py @@ -1,4 +1,4 @@ from flaskblog import app if __name__ == '__main__': - app.run(debug=True) + app.run(debug=False) diff --git a/Python/Flask_Blog/11-Blueprints/bandit_report.html b/Python/Flask_Blog/11-Blueprints/bandit_report.html new file mode 100644 index 000000000..36dbf4aa6 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/bandit_report.html @@ -0,0 +1,57567 @@ + + + + + + + + + Bandit Report + + + + + + + +
+
+
+ Metrics:
+
+ Total lines of code: 624789
+ Total lines skipped (#nosec): 2 +
+
+ + + + +
+
+ +
+
+ flask_debug_true: A Flask app appears to be run with debug=False, which exposes the Werkzeug debugger and allows the execution of arbitrary code.
+ Test ID: B201
+ Severity: HIGH
+ Confidence: MEDIUM
+ CWE: CWE-94
+ File: ./run.py
+ Line number: 6
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b201_flask_debug_true.html
+ +
+
+5	if __name__ == '__main__':
+6	    app.run(debug=False)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/AvifImagePlugin.py
+ Line number: 81
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+80	
+81	        assert self.fp is not None
+82	        self._decoder = _avif.AvifDecoder(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/BlpImagePlugin.py
+ Line number: 261
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+260	    def _open(self) -> None:
+261	        assert self.fp is not None
+262	        self.magic = self.fp.read(4)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/BlpImagePlugin.py
+ Line number: 316
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+315	    def _safe_read(self, length: int) -> bytes:
+316	        assert self.fd is not None
+317	        return ImageFile._safe_read(self.fd, length)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/BlpImagePlugin.py
+ Line number: 371
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+370	        jpeg_header = self._safe_read(jpeg_header_size)
+371	        assert self.fd is not None
+372	        self._safe_read(self._offsets[0] - self.fd.tell())  # What IS this?
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/BlpImagePlugin.py
+ Line number: 379
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+378	            args = image.tile[0].args
+379	            assert isinstance(args, tuple)
+380	            image.tile = [image.tile[0]._replace(args=(args[0], "CMYK"))]
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/BlpImagePlugin.py
+ Line number: 390
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+389	
+390	        assert self.fd is not None
+391	        self.fd.seek(self._offsets[0])
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/BlpImagePlugin.py
+ Line number: 437
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+436	        data = b""
+437	        assert self.im is not None
+438	        palette = self.im.getpalette("RGBA", "RGBA")
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/BlpImagePlugin.py
+ Line number: 452
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+451	
+452	        assert self.im is not None
+453	        w, h = self.im.size
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/BlpImagePlugin.py
+ Line number: 473
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+472	
+473	    assert im.palette is not None
+474	    fp.write(struct.pack("<i", 1))  # Uncompressed or DirectX compression
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/BmpImagePlugin.py
+ Line number: 79
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+78	        """Read relevant info about the BMP"""
+79	        assert self.fp is not None
+80	        read, seek = self.fp.read, self.fp.seek
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/BmpImagePlugin.py
+ Line number: 91
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+90	        # read the rest of the bmp header, without its size
+91	        assert isinstance(file_info["header_size"], int)
+92	        header_data = ImageFile._safe_read(self.fp, file_info["header_size"] - 4)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/BmpImagePlugin.py
+ Line number: 132
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+131	            file_info["palette_padding"] = 4
+132	            assert isinstance(file_info["pixels_per_meter"], tuple)
+133	            self.info["dpi"] = tuple(x / 39.3701 for x in file_info["pixels_per_meter"])
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/BmpImagePlugin.py
+ Line number: 155
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+154	                        file_info[mask] = i32(read(4))
+155	                assert isinstance(file_info["r_mask"], int)
+156	                assert isinstance(file_info["g_mask"], int)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/BmpImagePlugin.py
+ Line number: 156
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+155	                assert isinstance(file_info["r_mask"], int)
+156	                assert isinstance(file_info["g_mask"], int)
+157	                assert isinstance(file_info["b_mask"], int)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/BmpImagePlugin.py
+ Line number: 157
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+156	                assert isinstance(file_info["g_mask"], int)
+157	                assert isinstance(file_info["b_mask"], int)
+158	                assert isinstance(file_info["a_mask"], int)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/BmpImagePlugin.py
+ Line number: 158
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+157	                assert isinstance(file_info["b_mask"], int)
+158	                assert isinstance(file_info["a_mask"], int)
+159	                file_info["rgb_mask"] = (
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/BmpImagePlugin.py
+ Line number: 176
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+175	        # ---------------------- is shorter than real size for bpp >= 16
+176	        assert isinstance(file_info["width"], int)
+177	        assert isinstance(file_info["height"], int)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/BmpImagePlugin.py
+ Line number: 177
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+176	        assert isinstance(file_info["width"], int)
+177	        assert isinstance(file_info["height"], int)
+178	        self._size = file_info["width"], file_info["height"]
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/BmpImagePlugin.py
+ Line number: 181
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+180	        # ------- If color count was not found in the header, compute from bits
+181	        assert isinstance(file_info["bits"], int)
+182	        if not file_info.get("colors", 0):
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/BmpImagePlugin.py
+ Line number: 184
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+183	            file_info["colors"] = 1 << file_info["bits"]
+184	        assert isinstance(file_info["palette_padding"], int)
+185	        assert isinstance(file_info["colors"], int)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/BmpImagePlugin.py
+ Line number: 185
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+184	        assert isinstance(file_info["palette_padding"], int)
+185	        assert isinstance(file_info["colors"], int)
+186	        if offset == 14 + file_info["header_size"] and file_info["bits"] <= 8:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/BmpImagePlugin.py
+ Line number: 230
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+229	                ):
+230	                    assert isinstance(file_info["rgba_mask"], tuple)
+231	                    raw_mode = MASK_MODES[(file_info["bits"], file_info["rgba_mask"])]
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/BmpImagePlugin.py
+ Line number: 237
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+236	                ):
+237	                    assert isinstance(file_info["rgb_mask"], tuple)
+238	                    raw_mode = MASK_MODES[(file_info["bits"], file_info["rgb_mask"])]
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/BmpImagePlugin.py
+ Line number: 297
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+296	        else:
+297	            assert isinstance(file_info["width"], int)
+298	            args.append(((file_info["width"] * file_info["bits"] + 31) >> 3) & (~3))
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/BmpImagePlugin.py
+ Line number: 312
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+311	        # read 14 bytes: magic number, filesize, reserved, header final offset
+312	        assert self.fp is not None
+313	        head_data = self.fp.read(14)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/BmpImagePlugin.py
+ Line number: 328
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+327	    def decode(self, buffer: bytes | Image.SupportsArrayInterface) -> tuple[int, int]:
+328	        assert self.fd is not None
+329	        rle4 = self.args[1]
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/BufrStubImagePlugin.py
+ Line number: 44
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+43	    def _open(self) -> None:
+44	        assert self.fp is not None
+45	        if not _accept(self.fp.read(4)):
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/CurImagePlugin.py
+ Line number: 41
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+40	    def _open(self) -> None:
+41	        assert self.fp is not None
+42	        offset = self.fp.tell()
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/DcxImagePlugin.py
+ Line number: 48
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+47	        # Header
+48	        assert self.fp is not None
+49	        s = self.fp.read(4)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/DdsImagePlugin.py
+ Line number: 273
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+272	for item in DDSD:
+273	    assert item.name is not None
+274	    setattr(module, f"DDSD_{item.name}", item.value)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/DdsImagePlugin.py
+ Line number: 276
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+275	for item1 in DDSCAPS:
+276	    assert item1.name is not None
+277	    setattr(module, f"DDSCAPS_{item1.name}", item1.value)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/DdsImagePlugin.py
+ Line number: 279
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+278	for item2 in DDSCAPS2:
+279	    assert item2.name is not None
+280	    setattr(module, f"DDSCAPS2_{item2.name}", item2.value)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/DdsImagePlugin.py
+ Line number: 282
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+281	for item3 in DDPF:
+282	    assert item3.name is not None
+283	    setattr(module, f"DDPF_{item3.name}", item3.value)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/DdsImagePlugin.py
+ Line number: 335
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+334	    def _open(self) -> None:
+335	        assert self.fp is not None
+336	        if not _accept(self.fp.read(4)):
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/DdsImagePlugin.py
+ Line number: 492
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+491	    def decode(self, buffer: bytes | Image.SupportsArrayInterface) -> tuple[int, int]:
+492	        assert self.fd is not None
+493	        bitcount, masks = self.args
+
+
+ + +
+
+ +
+
+ blacklist: Consider possible security implications associated with the subprocess module.
+ Test ID: B404
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/PIL/EpsImagePlugin.py
+ Line number: 27
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_imports.html#b404-import-subprocess
+ +
+
+26	import re
+27	import subprocess
+28	import sys
+
+
+ + +
+
+ +
+
+ start_process_with_partial_path: Starting a process with a partial executable path
+ Test ID: B607
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/PIL/EpsImagePlugin.py
+ Line number: 61
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b607_start_process_with_partial_path.html
+ +
+
+60	            try:
+61	                subprocess.check_call(["gs", "--version"], stdout=subprocess.DEVNULL)
+62	                gs_binary = "gs"
+
+
+ + +
+
+ +
+
+ subprocess_without_shell_equals_true: subprocess call - check for execution of untrusted input.
+ Test ID: B603
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/PIL/EpsImagePlugin.py
+ Line number: 61
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b603_subprocess_without_shell_equals_true.html
+ +
+
+60	            try:
+61	                subprocess.check_call(["gs", "--version"], stdout=subprocess.DEVNULL)
+62	                gs_binary = "gs"
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/EpsImagePlugin.py
+ Line number: 80
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+79	        raise OSError(msg)
+80	    assert isinstance(gs_binary, str)
+81	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/EpsImagePlugin.py
+ Line number: 84
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+83	    args = tile[0].args
+84	    assert isinstance(args, tuple)
+85	    length, bbox = args
+
+
+ + +
+
+ +
+
+ subprocess_without_shell_equals_true: subprocess call - check for execution of untrusted input.
+ Test ID: B603
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/PIL/EpsImagePlugin.py
+ Line number: 159
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b603_subprocess_without_shell_equals_true.html
+ +
+
+158	            startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
+159	        subprocess.check_call(command, startupinfo=startupinfo)
+160	        with Image.open(outfile) as out_im:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/EpsImagePlugin.py
+ Line number: 192
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+191	    def _open(self) -> None:
+192	        assert self.fp is not None
+193	        length, offset = self._find_offset(self.fp)
+
+
+ + +
+
+ +
+
+ try_except_pass: Try, Except, Pass detected.
+ Test ID: B110
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/EpsImagePlugin.py
+ Line number: 247
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b110_try_except_pass.html
+ +
+
+246	                        bounding_box = [int(float(i)) for i in v.split()]
+247	                    except Exception:
+248	                        pass
+249	            return True
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/EpsImagePlugin.py
+ Line number: 407
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+406	        if self.tile:
+407	            assert self.fp is not None
+408	            self.im = Ghostscript(self.tile, self.size, self.fp, scale, transparency)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/FitsImagePlugin.py
+ Line number: 28
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+27	    def _open(self) -> None:
+28	        assert self.fp is not None
+29	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/FitsImagePlugin.py
+ Line number: 130
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+129	    def decode(self, buffer: bytes | Image.SupportsArrayInterface) -> tuple[int, int]:
+130	        assert self.fd is not None
+131	        with gzip.open(self.fd) as fp:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/FliImagePlugin.py
+ Line number: 51
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+50	        # HEAD
+51	        assert self.fp is not None
+52	        s = self.fp.read(128)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/FliImagePlugin.py
+ Line number: 119
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+118	        i = 0
+119	        assert self.fp is not None
+120	        for e in range(i16(self.fp.read(2))):
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/FpxImagePlugin.py
+ Line number: 61
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+60	
+61	        assert self.fp is not None
+62	        try:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/FpxImagePlugin.py
+ Line number: 85
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+84	
+85	        assert isinstance(prop[0x1000002], int)
+86	        assert isinstance(prop[0x1000003], int)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/FpxImagePlugin.py
+ Line number: 86
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+85	        assert isinstance(prop[0x1000002], int)
+86	        assert isinstance(prop[0x1000003], int)
+87	        self._size = prop[0x1000002], prop[0x1000003]
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/FpxImagePlugin.py
+ Line number: 232
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+231	
+232	        assert self.fp is not None
+233	        self.stream = stream
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/FtexImagePlugin.py
+ Line number: 75
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+74	    def _open(self) -> None:
+75	        assert self.fp is not None
+76	        if not _accept(self.fp.read(4)):
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/FtexImagePlugin.py
+ Line number: 85
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+84	        # I don't know of any multi-format file.
+85	        assert format_count == 1
+86	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/GbrImagePlugin.py
+ Line number: 45
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+44	    def _open(self) -> None:
+45	        assert self.fp is not None
+46	        header_size = i32(self.fp.read(4))
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/GbrImagePlugin.py
+ Line number: 92
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+91	        if self._im is None:
+92	            assert self.fp is not None
+93	            self.im = Image.core.new(self.mode, self.size)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/GdImageFile.py
+ Line number: 52
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+51	        # Header
+52	        assert self.fp is not None
+53	
+
+
+ + +
+
+ +
+
+ blacklist: Consider possible security implications associated with the subprocess module.
+ Test ID: B404
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/PIL/GifImagePlugin.py
+ Line number: 31
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_imports.html#b404-import-subprocess
+ +
+
+30	import os
+31	import subprocess
+32	from enum import IntEnum
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/GifImagePlugin.py
+ Line number: 90
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+89	    def data(self) -> bytes | None:
+90	        assert self.fp is not None
+91	        s = self.fp.read(1)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/GifImagePlugin.py
+ Line number: 104
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+103	        # Screen
+104	        assert self.fp is not None
+105	        s = self.fp.read(13)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/GifImagePlugin.py
+ Line number: 485
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+484	            self._prev_im = expanded_im
+485	            assert self._prev_im is not None
+486	        if self._frame_transparency is not None:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/GifImagePlugin.py
+ Line number: 495
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+494	
+495	        assert self.dispose_extent is not None
+496	        frame_im = self._crop(frame_im, self.dispose_extent)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/GifImagePlugin.py
+ Line number: 532
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+531	        im = im.convert("P", palette=Image.Palette.ADAPTIVE)
+532	        assert im.palette is not None
+533	        if im.palette.mode == "RGBA":
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/GifImagePlugin.py
+ Line number: 570
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+569	            im_palette = im.getpalette(None)
+570	            assert im_palette is not None
+571	            source_palette = bytearray(im_palette)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/GifImagePlugin.py
+ Line number: 576
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+575	        im.palette = ImagePalette.ImagePalette("RGB", palette=source_palette)
+576	    assert source_palette is not None
+577	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/GifImagePlugin.py
+ Line number: 580
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+579	        used_palette_colors: list[int | None] = []
+580	        assert im.palette is not None
+581	        for i in range(0, len(source_palette), 3):
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/GifImagePlugin.py
+ Line number: 595
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+594	        for index in used_palette_colors:
+595	            assert index is not None
+596	            dest_map.append(index)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/GifImagePlugin.py
+ Line number: 611
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+610	
+611	    assert im.palette is not None
+612	    im.palette.palette = source_palette
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/GifImagePlugin.py
+ Line number: 716
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+715	                            first_palette = im_frames[0].im.palette
+716	                            assert first_palette is not None
+717	                            background_im.putpalette(first_palette, first_palette.mode)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/GifImagePlugin.py
+ Line number: 723
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+722	                    if "transparency" not in encoderinfo:
+723	                        assert im_frame.palette is not None
+724	                        try:
+
+
+ + +
+
+ +
+
+ start_process_with_partial_path: Starting a process with a partial executable path
+ Test ID: B607
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/PIL/GifImagePlugin.py
+ Line number: 888
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b607_start_process_with_partial_path.html
+ +
+
+887	            if im.mode != "RGB":
+888	                subprocess.check_call(
+889	                    ["ppmtogif", tempfile], stdout=f, stderr=subprocess.DEVNULL
+890	                )
+891	            else:
+
+
+ + +
+
+ +
+
+ subprocess_without_shell_equals_true: subprocess call - check for execution of untrusted input.
+ Test ID: B603
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/PIL/GifImagePlugin.py
+ Line number: 888
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b603_subprocess_without_shell_equals_true.html
+ +
+
+887	            if im.mode != "RGB":
+888	                subprocess.check_call(
+889	                    ["ppmtogif", tempfile], stdout=f, stderr=subprocess.DEVNULL
+890	                )
+891	            else:
+
+
+ + +
+
+ +
+
+ subprocess_without_shell_equals_true: subprocess call - check for execution of untrusted input.
+ Test ID: B603
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/PIL/GifImagePlugin.py
+ Line number: 896
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b603_subprocess_without_shell_equals_true.html
+ +
+
+895	                togif_cmd = ["ppmtogif"]
+896	                quant_proc = subprocess.Popen(
+897	                    quant_cmd, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL
+898	                )
+899	                togif_proc = subprocess.Popen(
+
+
+ + +
+
+ +
+
+ subprocess_without_shell_equals_true: subprocess call - check for execution of untrusted input.
+ Test ID: B603
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/PIL/GifImagePlugin.py
+ Line number: 899
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b603_subprocess_without_shell_equals_true.html
+ +
+
+898	                )
+899	                togif_proc = subprocess.Popen(
+900	                    togif_cmd,
+901	                    stdin=quant_proc.stdout,
+902	                    stdout=f,
+903	                    stderr=subprocess.DEVNULL,
+904	                )
+905	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/GifImagePlugin.py
+ Line number: 907
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+906	                # Allow ppmquant to receive SIGPIPE if ppmtogif exits
+907	                assert quant_proc.stdout is not None
+908	                quant_proc.stdout.close()
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/GifImagePlugin.py
+ Line number: 968
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+967	
+968	            assert im.palette is not None
+969	            num_palette_colors = len(im.palette.palette) // Image.getmodebands(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/GifImagePlugin.py
+ Line number: 1037
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1036	            # info["background"] - a global color table index
+1037	            assert im.palette is not None
+1038	            try:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/GimpGradientFile.py
+ Line number: 88
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+87	    def getpalette(self, entries: int = 256) -> tuple[bytes, str]:
+88	        assert self.gradient is not None
+89	        palette = []
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/GribStubImagePlugin.py
+ Line number: 44
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+43	    def _open(self) -> None:
+44	        assert self.fp is not None
+45	        if not _accept(self.fp.read(8)):
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/Hdf5StubImagePlugin.py
+ Line number: 44
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+43	    def _open(self) -> None:
+44	        assert self.fp is not None
+45	        if not _accept(self.fp.read(8)):
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/IcnsImagePlugin.py
+ Line number: 267
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+266	    def _open(self) -> None:
+267	        assert self.fp is not None
+268	        self.icns = IcnsFile(self.fp)
+
+
+ + +
+
+ +
+
+ start_process_with_no_shell: Starting a process without a shell.
+ Test ID: B606
+ Severity: LOW
+ Confidence: MEDIUM
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/PIL/IcnsImagePlugin.py
+ Line number: 401
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b606_start_process_with_no_shell.html
+ +
+
+400	        if sys.platform == "windows":
+401	            os.startfile("out.png")
+
+
+ + +
+
+ +
+
+ start_process_with_partial_path: Starting a process with a partial executable path
+ Test ID: B607
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/PIL/IcnsImagePlugin.py
+ Line number: 401
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b607_start_process_with_partial_path.html
+ +
+
+400	        if sys.platform == "windows":
+401	            os.startfile("out.png")
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/IcoImagePlugin.py
+ Line number: 343
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+342	    def _open(self) -> None:
+343	        assert self.fp is not None
+344	        self.ico = IcoFile(self.fp)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/ImImagePlugin.py
+ Line number: 128
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+127	
+128	        assert self.fp is not None
+129	        if b"\n" not in self.fp.read(100):
+
+
+ + +
+
+ +
+
+ blacklist: Using Element to parse untrusted XML data is known to be vulnerable to XML attacks. Replace Element with the equivalent defusedxml package, or make sure defusedxml.defuse_stdlib() is called.
+ Test ID: B405
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-20
+ File: ./venv/lib/python3.12/site-packages/PIL/Image.py
+ Line number: 206
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_imports.html#b405-import-xml-etree
+ +
+
+205	    import mmap
+206	    from xml.etree.ElementTree import Element
+207	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/Image.py
+ Line number: 443
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+442	
+443	        assert BmpImagePlugin
+444	    except ImportError:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/Image.py
+ Line number: 449
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+448	
+449	        assert GifImagePlugin
+450	    except ImportError:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/Image.py
+ Line number: 455
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+454	
+455	        assert JpegImagePlugin
+456	    except ImportError:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/Image.py
+ Line number: 461
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+460	
+461	        assert PpmImagePlugin
+462	    except ImportError:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/Image.py
+ Line number: 467
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+466	
+467	        assert PngImagePlugin
+468	    except ImportError:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/Image.py
+ Line number: 647
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+646	            raise self._im.ex
+647	        assert self._im is not None
+648	        return self._im
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/Image.py
+ Line number: 758
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+757	            return False
+758	        assert isinstance(other, Image)
+759	        return (
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/Image.py
+ Line number: 1147
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1146	                    if self.mode == "P":
+1147	                        assert self.palette is not None
+1148	                        trns_im.putpalette(self.palette, self.palette.mode)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/Image.py
+ Line number: 1151
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1150	                            err = "Couldn't allocate a palette color for transparency"
+1151	                            assert trns_im.palette is not None
+1152	                            try:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/Image.py
+ Line number: 1339
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1338	            new_im = self._new(im)
+1339	            assert palette.palette is not None
+1340	            new_im.palette = palette.palette.copy()
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/Image.py
+ Line number: 1641
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1640	
+1641	                assert isinstance(self, TiffImagePlugin.TiffImageFile)
+1642	                self._exif.bigtiff = self.tag_v2._bigtiff
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/Image.py
+ Line number: 1645
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1644	
+1645	                assert self.fp is not None
+1646	                self._exif.load_from_fp(self.fp, self.tag_v2._offset)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/Image.py
+ Line number: 1725
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1724	        if self.mode == "P":
+1725	            assert self.palette is not None
+1726	            return self.palette.mode.endswith("A")
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/Image.py
+ Line number: 1741
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1740	        palette = self.getpalette("RGBA")
+1741	        assert palette is not None
+1742	        transparency = self.info["transparency"]
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/Image.py
+ Line number: 2211
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2210	                value = value[:3]
+2211	            assert self.palette is not None
+2212	            palette_index = self.palette.getcolor(tuple(value), self)
+
+
+ + +
+
+ +
+
+ try_except_pass: Try, Except, Pass detected.
+ Test ID: B110
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/Image.py
+ Line number: 4095
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b110_try_except_pass.html
+ +
+
+4094	                return value[0]
+4095	        except Exception:
+4096	            pass
+4097	        return value
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/ImageColor.py
+ Line number: 48
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+47	        rgb_tuple = getrgb(rgb)
+48	        assert len(rgb_tuple) == 3
+49	        colormap[color] = rgb_tuple
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/ImageDraw.py
+ Line number: 578
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+577	            if ink is None:
+578	                assert fill_ink is not None
+579	                return fill_ink
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/ImageDraw.py
+ Line number: 859
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+858	    pixel = image.load()
+859	    assert pixel is not None
+860	    x, y = xy
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/ImageFile.py
+ Line number: 228
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+227	        if ifd1 and ifd1.get(ExifTags.Base.JpegIFOffset):
+228	            assert exif._info is not None
+229	            ifds.append((ifd1, exif._info.next))
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/ImageFile.py
+ Line number: 233
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+232	        for ifd, ifd_offset in ifds:
+233	            assert self.fp is not None
+234	            current_offset = self.fp.tell()
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/ImageFile.py
+ Line number: 246
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+245	                    length = ifd.get(ExifTags.Base.JpegIFByteCount)
+246	                    assert isinstance(length, int)
+247	                    data = self.fp.read(length)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/ImageFile.py
+ Line number: 262
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+261	        if offset is not None:
+262	            assert self.fp is not None
+263	            self.fp.seek(offset)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/ImageFile.py
+ Line number: 305
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+304	
+305	        assert self.fp is not None
+306	        readonly = 0
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/ImageFile.py
+ Line number: 498
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+497	        image = loader.load(self)
+498	        assert image is not None
+499	        # become the other object (!)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/ImageFile.py
+ Line number: 529
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+528	        """
+529	        assert self.data is None, "cannot reuse parsers"
+530	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/ImageFile.py
+ Line number: 699
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+698	                    # slight speedup: compress to real file object
+699	                    assert fh is not None
+700	                    errcode = encoder.encode_to_file(fh, bufsize)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/ImageFile.py
+ Line number: 867
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+866	        d = Image._getdecoder(self.mode, "raw", rawmode, extra)
+867	        assert self.im is not None
+868	        d.setimage(self.im, self.state.extents())
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/ImageFile.py
+ Line number: 917
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+916	        if data:
+917	            assert self.fd is not None
+918	            self.fd.write(data)
+
+
+ + +
+
+ +
+
+ try_except_pass: Try, Except, Pass detected.
+ Test ID: B110
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/ImageFont.py
+ Line number: 110
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b110_try_except_pass.html
+ +
+
+109	                    image = Image.open(fullname)
+110	                except Exception:
+111	                    pass
+112	                else:
+
+
+ + +
+
+ +
+
+ blacklist: Consider possible security implications associated with the subprocess module.
+ Test ID: B404
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/PIL/ImageGrab.py
+ Line number: 22
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_imports.html#b404-import-subprocess
+ +
+
+21	import shutil
+22	import subprocess
+23	import sys
+
+
+ + +
+
+ +
+
+ subprocess_without_shell_equals_true: subprocess call - check for execution of untrusted input.
+ Test ID: B603
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/PIL/ImageGrab.py
+ Line number: 52
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b603_subprocess_without_shell_equals_true.html
+ +
+
+51	            args += ["-x", filepath]
+52	            retcode = subprocess.call(args)
+53	            if retcode:
+
+
+ + +
+
+ +
+
+ subprocess_without_shell_equals_true: subprocess call - check for execution of untrusted input.
+ Test ID: B603
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/PIL/ImageGrab.py
+ Line number: 66
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b603_subprocess_without_shell_equals_true.html
+ +
+
+65	                    args = ["screencapture", "-l", str(window), "-o", "-x", filepath]
+66	                    retcode = subprocess.call(args)
+67	                    if retcode:
+
+
+ + +
+
+ +
+
+ subprocess_without_shell_equals_true: subprocess call - check for execution of untrusted input.
+ Test ID: B603
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/PIL/ImageGrab.py
+ Line number: 133
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b603_subprocess_without_shell_equals_true.html
+ +
+
+132	            args.append(filepath)
+133	            retcode = subprocess.call(args)
+134	            if retcode:
+
+
+ + +
+
+ +
+
+ start_process_with_partial_path: Starting a process with a partial executable path
+ Test ID: B607
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/PIL/ImageGrab.py
+ Line number: 155
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b607_start_process_with_partial_path.html
+ +
+
+154	    if sys.platform == "darwin":
+155	        p = subprocess.run(
+156	            ["osascript", "-e", "get the clipboard as «class PNGf»"],
+157	            capture_output=True,
+158	        )
+159	        if p.returncode != 0:
+
+
+ + +
+
+ +
+
+ subprocess_without_shell_equals_true: subprocess call - check for execution of untrusted input.
+ Test ID: B603
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/PIL/ImageGrab.py
+ Line number: 155
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b603_subprocess_without_shell_equals_true.html
+ +
+
+154	    if sys.platform == "darwin":
+155	        p = subprocess.run(
+156	            ["osascript", "-e", "get the clipboard as «class PNGf»"],
+157	            capture_output=True,
+158	        )
+159	        if p.returncode != 0:
+
+
+ + +
+
+ +
+
+ subprocess_without_shell_equals_true: subprocess call - check for execution of untrusted input.
+ Test ID: B603
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/PIL/ImageGrab.py
+ Line number: 204
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b603_subprocess_without_shell_equals_true.html
+ +
+
+203	
+204	        p = subprocess.run(args, capture_output=True)
+205	        if p.returncode != 0:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/ImageMorph.py
+ Line number: 127
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+126	        """
+127	        assert len(permutation) == 9
+128	        return "".join(pattern[p] for p in permutation)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/ImageMorph.py
+ Line number: 167
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+166	        self.build_default_lut()
+167	        assert self.lut is not None
+168	        patterns = []
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/ImageOps.py
+ Line number: 199
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+198	    # Initial asserts
+199	    assert image.mode == "L"
+200	    if mid is None:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/ImageOps.py
+ Line number: 201
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+200	    if mid is None:
+201	        assert 0 <= blackpoint <= whitepoint <= 255
+202	    else:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/ImageOps.py
+ Line number: 203
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+202	    else:
+203	        assert 0 <= blackpoint <= midpoint <= whitepoint <= 255
+204	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/ImagePalette.py
+ Line number: 169
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+168	                index = self._new_color_index(image, e)
+169	                assert isinstance(self._palette, bytearray)
+170	                self.colors[color] = index
+
+
+ + +
+
+ +
+
+ blacklist: Standard pseudo-random generators are not suitable for security/cryptographic purposes.
+ Test ID: B311
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-330
+ File: ./venv/lib/python3.12/site-packages/PIL/ImagePalette.py
+ Line number: 249
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b311-random
+ +
+
+248	
+249	    palette = [randint(0, 255) for _ in range(256 * len(mode))]
+250	    return ImagePalette(mode, palette)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/ImageQt.py
+ Line number: 144
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+143	        exclusive_fp = True
+144	    assert isinstance(im, Image.Image)
+145	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/ImageQt.py
+ Line number: 155
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+154	        palette = im.getpalette()
+155	        assert palette is not None
+156	        colortable = [rgb(*palette[i : i + 3]) for i in range(0, len(palette), 3)]
+
+
+ + +
+
+ +
+
+ blacklist: Consider possible security implications associated with the subprocess module.
+ Test ID: B404
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/PIL/ImageShow.py
+ Line number: 19
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_imports.html#b404-import-subprocess
+ +
+
+18	import shutil
+19	import subprocess
+20	import sys
+
+
+ + +
+
+ +
+
+ start_process_with_partial_path: Starting a process with a partial executable path
+ Test ID: B607
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/PIL/ImageShow.py
+ Line number: 177
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b607_start_process_with_partial_path.html
+ +
+
+176	            raise FileNotFoundError
+177	        subprocess.call(["open", "-a", "Preview.app", path])
+178	
+
+
+ + +
+
+ +
+
+ subprocess_without_shell_equals_true: subprocess call - check for execution of untrusted input.
+ Test ID: B603
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/PIL/ImageShow.py
+ Line number: 177
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b603_subprocess_without_shell_equals_true.html
+ +
+
+176	            raise FileNotFoundError
+177	        subprocess.call(["open", "-a", "Preview.app", path])
+178	
+
+
+ + +
+
+ +
+
+ subprocess_without_shell_equals_true: subprocess call - check for execution of untrusted input.
+ Test ID: B603
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/PIL/ImageShow.py
+ Line number: 182
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b603_subprocess_without_shell_equals_true.html
+ +
+
+181	        if executable:
+182	            subprocess.Popen(
+183	                [
+184	                    executable,
+185	                    "-c",
+186	                    "import os, sys, time; time.sleep(20); os.remove(sys.argv[1])",
+187	                    path,
+188	                ]
+189	            )
+190	        return 1
+
+
+ + +
+
+ +
+
+ start_process_with_partial_path: Starting a process with a partial executable path
+ Test ID: B607
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/PIL/ImageShow.py
+ Line number: 225
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b607_start_process_with_partial_path.html
+ +
+
+224	            raise FileNotFoundError
+225	        subprocess.Popen(["xdg-open", path])
+226	        return 1
+
+
+ + +
+
+ +
+
+ subprocess_without_shell_equals_true: subprocess call - check for execution of untrusted input.
+ Test ID: B603
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/PIL/ImageShow.py
+ Line number: 225
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b603_subprocess_without_shell_equals_true.html
+ +
+
+224	            raise FileNotFoundError
+225	        subprocess.Popen(["xdg-open", path])
+226	        return 1
+
+
+ + +
+
+ +
+
+ subprocess_without_shell_equals_true: subprocess call - check for execution of untrusted input.
+ Test ID: B603
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/PIL/ImageShow.py
+ Line number: 255
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b603_subprocess_without_shell_equals_true.html
+ +
+
+254	
+255	        subprocess.Popen(args)
+256	        return 1
+
+
+ + +
+
+ +
+
+ start_process_with_partial_path: Starting a process with a partial executable path
+ Test ID: B607
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/PIL/ImageShow.py
+ Line number: 273
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b607_start_process_with_partial_path.html
+ +
+
+272	            raise FileNotFoundError
+273	        subprocess.Popen(["gm", "display", path])
+274	        return 1
+
+
+ + +
+
+ +
+
+ subprocess_without_shell_equals_true: subprocess call - check for execution of untrusted input.
+ Test ID: B603
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/PIL/ImageShow.py
+ Line number: 273
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b603_subprocess_without_shell_equals_true.html
+ +
+
+272	            raise FileNotFoundError
+273	        subprocess.Popen(["gm", "display", path])
+274	        return 1
+
+
+ + +
+
+ +
+
+ start_process_with_partial_path: Starting a process with a partial executable path
+ Test ID: B607
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/PIL/ImageShow.py
+ Line number: 291
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b607_start_process_with_partial_path.html
+ +
+
+290	            raise FileNotFoundError
+291	        subprocess.Popen(["eog", "-n", path])
+292	        return 1
+
+
+ + +
+
+ +
+
+ subprocess_without_shell_equals_true: subprocess call - check for execution of untrusted input.
+ Test ID: B603
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/PIL/ImageShow.py
+ Line number: 291
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b603_subprocess_without_shell_equals_true.html
+ +
+
+290	            raise FileNotFoundError
+291	        subprocess.Popen(["eog", "-n", path])
+292	        return 1
+
+
+ + +
+
+ +
+
+ subprocess_without_shell_equals_true: subprocess call - check for execution of untrusted input.
+ Test ID: B603
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/PIL/ImageShow.py
+ Line number: 323
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b603_subprocess_without_shell_equals_true.html
+ +
+
+322	
+323	        subprocess.Popen(args)
+324	        return 1
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/ImageText.py
+ Line number: 507
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+506	
+507	        assert bbox is not None
+508	        return bbox
+
+
+ + +
+
+ +
+
+ try_except_pass: Try, Except, Pass detected.
+ Test ID: B110
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/ImageTk.py
+ Line number: 142
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b110_try_except_pass.html
+ +
+
+141	            self.__photo.tk.call("image", "delete", name)
+142	        except Exception:
+143	            pass  # ignore internal errors
+144	
+
+
+ + +
+
+ +
+
+ try_except_pass: Try, Except, Pass detected.
+ Test ID: B110
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/ImageTk.py
+ Line number: 230
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b110_try_except_pass.html
+ +
+
+229	            self.__photo.tk.call("image", "delete", name)
+230	        except Exception:
+231	            pass  # ignore internal errors
+232	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/ImageWin.py
+ Line number: 90
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+89	        if image:
+90	            assert not isinstance(image, str)
+91	            self.paste(image)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/ImtImagePlugin.py
+ Line number: 40
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+39	
+40	        assert self.fp is not None
+41	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/IptcImagePlugin.py
+ Line number: 52
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+51	        # get a IPTC field header
+52	        assert self.fp is not None
+53	        s = self.fp.read(5)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/IptcImagePlugin.py
+ Line number: 80
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+79	        # load descriptive fields
+80	        assert self.fp is not None
+81	        while True:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/IptcImagePlugin.py
+ Line number: 133
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+132	            args = self.tile[0].args
+133	            assert isinstance(args, tuple)
+134	            compression, band = args
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/IptcImagePlugin.py
+ Line number: 136
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+135	
+136	            assert self.fp is not None
+137	            self.fp.seek(self.tile[0].offset)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/Jpeg2KImagePlugin.py
+ Line number: 171
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+170	                mimetype = "image/jpx"
+171	    assert header is not None
+172	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/Jpeg2KImagePlugin.py
+ Line number: 186
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+185	            height, width, nc, bpc = header.read_fields(">IIHB")
+186	            assert isinstance(height, int)
+187	            assert isinstance(width, int)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/Jpeg2KImagePlugin.py
+ Line number: 187
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+186	            assert isinstance(height, int)
+187	            assert isinstance(width, int)
+188	            assert isinstance(bpc, int)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/Jpeg2KImagePlugin.py
+ Line number: 188
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+187	            assert isinstance(width, int)
+188	            assert isinstance(bpc, int)
+189	            size = (width, height)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/Jpeg2KImagePlugin.py
+ Line number: 213
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+212	            ne, npc = header.read_fields(">HB")
+213	            assert isinstance(ne, int)
+214	            assert isinstance(npc, int)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/Jpeg2KImagePlugin.py
+ Line number: 214
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+213	            assert isinstance(ne, int)
+214	            assert isinstance(npc, int)
+215	            max_bitdepth = 0
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/Jpeg2KImagePlugin.py
+ Line number: 217
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+216	            for bitdepth in header.read_fields(">" + ("B" * npc)):
+217	                assert isinstance(bitdepth, int)
+218	                if bitdepth > max_bitdepth:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/Jpeg2KImagePlugin.py
+ Line number: 229
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+228	                    for value in header.read_fields(">" + ("B" * npc)):
+229	                        assert isinstance(value, int)
+230	                        color.append(value)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/Jpeg2KImagePlugin.py
+ Line number: 239
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+238	                    vrcn, vrcd, hrcn, hrcd, vrce, hrce = res.read_fields(">HHHHBB")
+239	                    assert isinstance(vrcn, int)
+240	                    assert isinstance(vrcd, int)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/Jpeg2KImagePlugin.py
+ Line number: 240
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+239	                    assert isinstance(vrcn, int)
+240	                    assert isinstance(vrcd, int)
+241	                    assert isinstance(hrcn, int)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/Jpeg2KImagePlugin.py
+ Line number: 241
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+240	                    assert isinstance(vrcd, int)
+241	                    assert isinstance(hrcn, int)
+242	                    assert isinstance(hrcd, int)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/Jpeg2KImagePlugin.py
+ Line number: 242
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+241	                    assert isinstance(hrcn, int)
+242	                    assert isinstance(hrcd, int)
+243	                    assert isinstance(vrce, int)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/Jpeg2KImagePlugin.py
+ Line number: 243
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+242	                    assert isinstance(hrcd, int)
+243	                    assert isinstance(vrce, int)
+244	                    assert isinstance(hrce, int)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/Jpeg2KImagePlugin.py
+ Line number: 244
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+243	                    assert isinstance(vrce, int)
+244	                    assert isinstance(hrce, int)
+245	                    hres = _res_to_dpi(hrcn, hrcd, hrce)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/Jpeg2KImagePlugin.py
+ Line number: 267
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+266	    def _open(self) -> None:
+267	        assert self.fp is not None
+268	        sig = self.fp.read(4)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/Jpeg2KImagePlugin.py
+ Line number: 320
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+319	    def _parse_comment(self) -> None:
+320	        assert self.fp is not None
+321	        while True:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/Jpeg2KImagePlugin.py
+ Line number: 365
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+364	            t = self.tile[0]
+365	            assert isinstance(t[3], tuple)
+366	            t3 = (t[3][0], self._reduce, self.layers, t[3][3], t[3][4])
+
+
+ + +
+
+ +
+
+ blacklist: Consider possible security implications associated with the subprocess module.
+ Test ID: B404
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/PIL/JpegImagePlugin.py
+ Line number: 41
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_imports.html#b404-import-subprocess
+ +
+
+40	import struct
+41	import subprocess
+42	import sys
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/JpegImagePlugin.py
+ Line number: 64
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+63	def Skip(self: JpegImageFile, marker: int) -> None:
+64	    assert self.fp is not None
+65	    n = i16(self.fp.read(2)) - 2
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/JpegImagePlugin.py
+ Line number: 74
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+73	
+74	    assert self.fp is not None
+75	    n = i16(self.fp.read(2)) - 2
+
+
+ + +
+
+ +
+
+ try_except_pass: Try, Except, Pass detected.
+ Test ID: B110
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/JpegImagePlugin.py
+ Line number: 91
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b110_try_except_pass.html
+ +
+
+90	            jfif_density = i16(s, 8), i16(s, 10)
+91	        except Exception:
+92	            pass
+93	        else:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/JpegImagePlugin.py
+ Line number: 179
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+178	    # Comment marker.  Store these in the APP dictionary.
+179	    assert self.fp is not None
+180	    n = i16(self.fp.read(2)) - 2
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/JpegImagePlugin.py
+ Line number: 196
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+195	
+196	    assert self.fp is not None
+197	    n = i16(self.fp.read(2)) - 2
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/JpegImagePlugin.py
+ Line number: 247
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+246	
+247	    assert self.fp is not None
+248	    n = i16(self.fp.read(2)) - 2
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/JpegImagePlugin.py
+ Line number: 348
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+347	    def _open(self) -> None:
+348	        assert self.fp is not None
+349	        s = self.fp.read(3)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/JpegImagePlugin.py
+ Line number: 417
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+416	        """
+417	        assert self.fp is not None
+418	        s = self.fp.read(read_bytes)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/JpegImagePlugin.py
+ Line number: 442
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+441	
+442	        assert isinstance(a, tuple)
+443	        if a[0] == "RGB" and mode in ["L", "YCbCr"]:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/JpegImagePlugin.py
+ Line number: 452
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+451	                    break
+452	            assert e is not None
+453	            e = (
+
+
+ + +
+
+ +
+
+ start_process_with_partial_path: Starting a process with a partial executable path
+ Test ID: B607
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/PIL/JpegImagePlugin.py
+ Line number: 474
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b607_start_process_with_partial_path.html
+ +
+
+473	        if os.path.exists(self.filename):
+474	            subprocess.check_call(["djpeg", "-outfile", path, self.filename])
+475	        else:
+
+
+ + +
+
+ +
+
+ subprocess_without_shell_equals_true: subprocess call - check for execution of untrusted input.
+ Test ID: B603
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/PIL/JpegImagePlugin.py
+ Line number: 474
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b603_subprocess_without_shell_equals_true.html
+ +
+
+473	        if os.path.exists(self.filename):
+474	            subprocess.check_call(["djpeg", "-outfile", path, self.filename])
+475	        else:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/McIdasImagePlugin.py
+ Line number: 39
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+38	        # parse area file directory
+39	        assert self.fp is not None
+40	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/MicImagePlugin.py
+ Line number: 70
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+69	
+70	        assert self.fp is not None
+71	        self.__fp = self.fp
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/MpegImagePlugin.py
+ Line number: 66
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+65	    def _open(self) -> None:
+66	        assert self.fp is not None
+67	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/MpoImagePlugin.py
+ Line number: 108
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+107	    def _open(self) -> None:
+108	        assert self.fp is not None
+109	        self.fp.seek(0)  # prep the fp in order to pass the JPEG test
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/MpoImagePlugin.py
+ Line number: 125
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+124	        # gets broken within JpegImagePlugin.
+125	        assert self.n_frames == len(self.__mpoffsets)
+126	        del self.info["mpoffset"]  # no longer needed
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/MpoImagePlugin.py
+ Line number: 128
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+127	        self.is_animated = self.n_frames > 1
+128	        assert self.fp is not None
+129	        self._fp = self.fp  # FIXME: hack
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/MspImagePlugin.py
+ Line number: 54
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+53	        # Header
+54	        assert self.fp is not None
+55	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/MspImagePlugin.py
+ Line number: 116
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+115	    def decode(self, buffer: bytes | Image.SupportsArrayInterface) -> tuple[int, int]:
+116	        assert self.fd is not None
+117	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/PcdImagePlugin.py
+ Line number: 32
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+31	        # rough
+32	        assert self.fp is not None
+33	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/PcxImagePlugin.py
+ Line number: 55
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+54	        # header
+55	        assert self.fp is not None
+56	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/PcxImagePlugin.py
+ Line number: 204
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+203	
+204	    assert fp.tell() == 128
+205	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/PdfImagePlugin.py
+ Line number: 103
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+102	        palette = im.getpalette()
+103	        assert palette is not None
+104	        dict_obj["ColorSpace"] = [
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/PdfParser.py
+ Line number: 107
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+106	            return False
+107	        assert isinstance(other, IndirectReference)
+108	        return other.object_id == self.object_id and other.generation == self.generation
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/PdfParser.py
+ Line number: 446
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+445	    def seek_end(self) -> None:
+446	        assert self.f is not None
+447	        self.f.seek(0, os.SEEK_END)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/PdfParser.py
+ Line number: 450
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+449	    def write_header(self) -> None:
+450	        assert self.f is not None
+451	        self.f.write(b"%PDF-1.4\n")
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/PdfParser.py
+ Line number: 454
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+453	    def write_comment(self, s: str) -> None:
+454	        assert self.f is not None
+455	        self.f.write(f"% {s}\n".encode())
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/PdfParser.py
+ Line number: 458
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+457	    def write_catalog(self) -> IndirectReference:
+458	        assert self.f is not None
+459	        self.del_root()
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/PdfParser.py
+ Line number: 504
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+503	    ) -> None:
+504	        assert self.f is not None
+505	        if new_root_ref:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/PdfParser.py
+ Line number: 540
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+539	    ) -> IndirectReference:
+540	        assert self.f is not None
+541	        f = self.f
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/PdfParser.py
+ Line number: 580
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+579	    def read_pdf_info(self) -> None:
+580	        assert self.buf is not None
+581	        self.file_size_total = len(self.buf)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/PdfParser.py
+ Line number: 588
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+587	        self.root_ref = self.trailer_dict[b"Root"]
+588	        assert self.root_ref is not None
+589	        self.info_ref = self.trailer_dict.get(b"Info", None)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/PdfParser.py
+ Line number: 607
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+606	        self.pages_ref = self.root[b"Pages"]
+607	        assert self.pages_ref is not None
+608	        self.page_tree_root = self.read_indirect(self.pages_ref)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/PdfParser.py
+ Line number: 666
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+665	    def read_trailer(self) -> None:
+666	        assert self.buf is not None
+667	        search_start_offset = len(self.buf) - 16384
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/PdfParser.py
+ Line number: 679
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+678	            m = last_match
+679	        assert m is not None
+680	        trailer_data = m.group(1)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/PdfParser.py
+ Line number: 691
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+690	    ) -> None:
+691	        assert self.buf is not None
+692	        trailer_offset = self.read_xref_table(xref_section_offset=xref_section_offset)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/PdfParser.py
+ Line number: 697
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+696	        check_format_condition(m is not None, "previous trailer not found")
+697	        assert m is not None
+698	        trailer_data = m.group(1)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/PdfParser.py
+ Line number: 736
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+735	            key = cls.interpret_name(m.group(1))
+736	            assert isinstance(key, bytes)
+737	            value, value_offset = cls.get_value(trailer_data, m.end())
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/PdfParser.py
+ Line number: 854
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+853	            )
+854	            assert m is not None
+855	            return object, m.end()
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/PdfParser.py
+ Line number: 877
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+876	            while not m:
+877	                assert current_offset is not None
+878	                key, current_offset = cls.get_value(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/PdfParser.py
+ Line number: 900
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+899	                check_format_condition(m is not None, "stream end not found")
+900	                assert m is not None
+901	                current_offset = m.end()
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/PdfParser.py
+ Line number: 911
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+910	            while not m:
+911	                assert current_offset is not None
+912	                value, current_offset = cls.get_value(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/PdfParser.py
+ Line number: 1018
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1017	    def read_xref_table(self, xref_section_offset: int) -> int:
+1018	        assert self.buf is not None
+1019	        subsection_found = False
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/PdfParser.py
+ Line number: 1024
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1023	        check_format_condition(m is not None, "xref section start not found")
+1024	        assert m is not None
+1025	        offset = m.end()
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/PdfParser.py
+ Line number: 1040
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1039	                check_format_condition(m is not None, "xref entry not found")
+1040	                assert m is not None
+1041	                offset = m.end()
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/PdfParser.py
+ Line number: 1057
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1056	        )
+1057	        assert self.buf is not None
+1058	        value = self.get_value(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/PixarImagePlugin.py
+ Line number: 44
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+43	        # assuming a 4-byte magic label
+44	        assert self.fp is not None
+45	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/PngImagePlugin.py
+ Line number: 171
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+170	
+171	        assert self.fp is not None
+172	        if self.queue:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/PngImagePlugin.py
+ Line number: 198
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+197	    def push(self, cid: bytes, pos: int, length: int) -> None:
+198	        assert self.queue is not None
+199	        self.queue.append((cid, pos, length))
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/PngImagePlugin.py
+ Line number: 217
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+216	
+217	        assert self.fp is not None
+218	        try:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/PngImagePlugin.py
+ Line number: 231
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+230	
+231	        assert self.fp is not None
+232	        self.fp.read(4)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/PngImagePlugin.py
+ Line number: 240
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+239	
+240	        assert self.fp is not None
+241	        while True:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/PngImagePlugin.py
+ Line number: 426
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+425	        # ICC profile
+426	        assert self.fp is not None
+427	        s = ImageFile._safe_read(self.fp, length)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/PngImagePlugin.py
+ Line number: 454
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+453	        # image header
+454	        assert self.fp is not None
+455	        s = ImageFile._safe_read(self.fp, length)
+
+
+ + +
+
+ +
+
+ try_except_pass: Try, Except, Pass detected.
+ Test ID: B110
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/PngImagePlugin.py
+ Line number: 464
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b110_try_except_pass.html
+ +
+
+463	            self.im_mode, self.im_rawmode = _MODES[(s[8], s[9])]
+464	        except Exception:
+465	            pass
+466	        if s[12]:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/PngImagePlugin.py
+ Line number: 492
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+491	        # palette
+492	        assert self.fp is not None
+493	        s = ImageFile._safe_read(self.fp, length)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/PngImagePlugin.py
+ Line number: 500
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+499	        # transparency
+500	        assert self.fp is not None
+501	        s = ImageFile._safe_read(self.fp, length)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/PngImagePlugin.py
+ Line number: 523
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+522	        # gamma setting
+523	        assert self.fp is not None
+524	        s = ImageFile._safe_read(self.fp, length)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/PngImagePlugin.py
+ Line number: 532
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+531	
+532	        assert self.fp is not None
+533	        s = ImageFile._safe_read(self.fp, length)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/PngImagePlugin.py
+ Line number: 545
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+544	
+545	        assert self.fp is not None
+546	        s = ImageFile._safe_read(self.fp, length)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/PngImagePlugin.py
+ Line number: 557
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+556	        # pixels per unit
+557	        assert self.fp is not None
+558	        s = ImageFile._safe_read(self.fp, length)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/PngImagePlugin.py
+ Line number: 575
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+574	        # text
+575	        assert self.fp is not None
+576	        s = ImageFile._safe_read(self.fp, length)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/PngImagePlugin.py
+ Line number: 595
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+594	        # compressed text
+595	        assert self.fp is not None
+596	        s = ImageFile._safe_read(self.fp, length)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/PngImagePlugin.py
+ Line number: 630
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+629	        # international text
+630	        assert self.fp is not None
+631	        r = s = ImageFile._safe_read(self.fp, length)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/PngImagePlugin.py
+ Line number: 672
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+671	    def chunk_eXIf(self, pos: int, length: int) -> bytes:
+672	        assert self.fp is not None
+673	        s = ImageFile._safe_read(self.fp, length)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/PngImagePlugin.py
+ Line number: 679
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+678	    def chunk_acTL(self, pos: int, length: int) -> bytes:
+679	        assert self.fp is not None
+680	        s = ImageFile._safe_read(self.fp, length)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/PngImagePlugin.py
+ Line number: 700
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+699	    def chunk_fcTL(self, pos: int, length: int) -> bytes:
+700	        assert self.fp is not None
+701	        s = ImageFile._safe_read(self.fp, length)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/PngImagePlugin.py
+ Line number: 730
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+729	    def chunk_fdAT(self, pos: int, length: int) -> bytes:
+730	        assert self.fp is not None
+731	        if length < 4:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/PngImagePlugin.py
+ Line number: 763
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+762	    def _open(self) -> None:
+763	        assert self.fp is not None
+764	        if not _accept(self.fp.read(8)):
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/PngImagePlugin.py
+ Line number: 843
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+842	                self.seek(frame)
+843	        assert self._text is not None
+844	        return self._text
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/PngImagePlugin.py
+ Line number: 856
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+855	
+856	        assert self.png is not None
+857	        self.png.verify()
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/PngImagePlugin.py
+ Line number: 878
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+877	    def _seek(self, frame: int, rewind: bool = False) -> None:
+878	        assert self.png is not None
+879	        if isinstance(self._fp, DeferredError):
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/PngImagePlugin.py
+ Line number: 992
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+991	
+992	        assert self.png is not None
+993	        assert self.fp is not None
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/PngImagePlugin.py
+ Line number: 993
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+992	        assert self.png is not None
+993	        assert self.fp is not None
+994	        while self.__idat == 0:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/PngImagePlugin.py
+ Line number: 1026
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1025	        """internal: finished reading image data"""
+1026	        assert self.png is not None
+1027	        assert self.fp is not None
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/PngImagePlugin.py
+ Line number: 1027
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1026	        assert self.png is not None
+1027	        assert self.fp is not None
+1028	        if self.__idat != 0:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/PpmImagePlugin.py
+ Line number: 62
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+61	    def _read_magic(self) -> bytes:
+62	        assert self.fp is not None
+63	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/PpmImagePlugin.py
+ Line number: 74
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+73	    def _read_token(self) -> bytes:
+74	        assert self.fp is not None
+75	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/PpmImagePlugin.py
+ Line number: 102
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+101	    def _open(self) -> None:
+102	        assert self.fp is not None
+103	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/PpmImagePlugin.py
+ Line number: 168
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+167	    def _read_block(self) -> bytes:
+168	        assert self.fd is not None
+169	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/PpmImagePlugin.py
+ Line number: 304
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+303	    def decode(self, buffer: bytes | Image.SupportsArrayInterface) -> tuple[int, int]:
+304	        assert self.fd is not None
+305	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/PsdImagePlugin.py
+ Line number: 64
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+63	    def _open(self) -> None:
+64	        assert self.fp is not None
+65	        read = self.fp.read
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/QoiImagePlugin.py
+ Line number: 28
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+27	    def _open(self) -> None:
+28	        assert self.fp is not None
+29	        if not _accept(self.fp.read(4)):
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/QoiImagePlugin.py
+ Line number: 55
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+54	    def decode(self, buffer: bytes | Image.SupportsArrayInterface) -> tuple[int, int]:
+55	        assert self.fd is not None
+56	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/QoiImagePlugin.py
+ Line number: 155
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+154	    def encode(self, bufsize: int) -> tuple[int, int, bytes]:
+155	        assert self.im is not None
+156	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/SgiImagePlugin.py
+ Line number: 58
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+57	        # HEAD
+58	        assert self.fp is not None
+59	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/SgiImagePlugin.py
+ Line number: 202
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+201	    def decode(self, buffer: bytes | Image.SupportsArrayInterface) -> tuple[int, int]:
+202	        assert self.fd is not None
+203	        assert self.im is not None
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/SgiImagePlugin.py
+ Line number: 203
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+202	        assert self.fd is not None
+203	        assert self.im is not None
+204	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/SpiderImagePlugin.py
+ Line number: 107
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+106	        n = 27 * 4  # read 27 float values
+107	        assert self.fp is not None
+108	        f = self.fp.read(n)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/SpiderImagePlugin.py
+ Line number: 195
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+194	        extrema = self.getextrema()
+195	        assert isinstance(extrema[0], float)
+196	        minimum, maximum = cast(tuple[float, float], extrema)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/SpiderImagePlugin.py
+ Line number: 230
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+229	            with Image.open(img) as im:
+230	                assert isinstance(im, SpiderImageFile)
+231	                byte_im = im.convert2byte()
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/SunImagePlugin.py
+ Line number: 52
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+51	
+52	        assert self.fp is not None
+53	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/TgaImagePlugin.py
+ Line number: 57
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+56	        # process header
+57	        assert self.fp is not None
+58	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/TgaImagePlugin.py
+ Line number: 163
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+162	        if self.mode == "RGBA":
+163	            assert self.fp is not None
+164	            self.fp.seek(-26, os.SEEK_END)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/TiffImagePlugin.py
+ Line number: 400
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+399	
+400	        assert isinstance(self._val, Fraction)
+401	        f = self._val.limit_denominator(max_denominator)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/TiffImagePlugin.py
+ Line number: 424
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+423	        _val, _numerator, _denominator = state
+424	        assert isinstance(_val, (float, Fraction))
+425	        self._val = _val
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/TiffImagePlugin.py
+ Line number: 430
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+429	            self._numerator = _numerator
+430	        assert isinstance(_denominator, int)
+431	        self._denominator = _denominator
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/TiffImagePlugin.py
+ Line number: 689
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+688	                    for v in values:
+689	                        assert isinstance(v, IFDRational)
+690	                        if v < 0:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/TiffImagePlugin.py
+ Line number: 700
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+699	                    for v in values:
+700	                        assert isinstance(v, int)
+701	                        if short and not (0 <= v < 2**16):
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/TiffImagePlugin.py
+ Line number: 1181
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1180	        # Header
+1181	        assert self.fp is not None
+1182	        ifh = self.fp.read(8)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/TiffImagePlugin.py
+ Line number: 1211
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1210	            self.seek(current)
+1211	        assert self._n_frames is not None
+1212	        return self._n_frames
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/TiffImagePlugin.py
+ Line number: 1351
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1350	        # into a string in python.
+1351	        assert self.fp is not None
+1352	        try:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/TiffImagePlugin.py
+ Line number: 1365
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1364	        if fp:
+1365	            assert isinstance(args, tuple)
+1366	            args_list = list(args)
+
+
+ + +
+
+ +
+
+ try_except_pass: Try, Except, Pass detected.
+ Test ID: B110
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/TiffImagePlugin.py
+ Line number: 1763
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b110_try_except_pass.html
+ +
+
+1762	            ifd.tagtype[key] = info.tagtype[key]
+1763	        except Exception:
+1764	            pass  # might not be an IFD. Might not have populated type
+1765	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/TiffImagePlugin.py
+ Line number: 2110
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2109	        ifd_offset += self.offsetOfNewPage
+2110	        assert self.whereToWriteNewIFDOffset is not None
+2111	        self.f.seek(self.whereToWriteNewIFDOffset)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/WalImageFile.py
+ Line number: 43
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+42	        # read header fields
+43	        assert self.fp is not None
+44	        header = self.fp.read(32 + 24 + 32 + 12)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/WalImageFile.py
+ Line number: 59
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+58	        if self._im is None:
+59	            assert self.fp is not None
+60	            self.im = Image.core.new(self.mode, self.size)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/WebPImagePlugin.py
+ Line number: 48
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+47	        # and access muxed chunks like ICC/EXIF/XMP.
+48	        assert self.fp is not None
+49	        self._decoder = _webp.WebPAnimDecoder(self.fp.read())
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/WmfImagePlugin.py
+ Line number: 51
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+50	        def load(self, im: ImageFile.StubImageFile) -> Image.Image:
+51	            assert im.fp is not None
+52	            im.fp.seek(0)  # rewind
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/WmfImagePlugin.py
+ Line number: 84
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+83	        # check placeable header
+84	        assert self.fp is not None
+85	        s = self.fp.read(44)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/XVThumbImagePlugin.py
+ Line number: 50
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+49	        # check magic
+50	        assert self.fp is not None
+51	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/XbmImagePlugin.py
+ Line number: 53
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+52	    def _open(self) -> None:
+53	        assert self.fp is not None
+54	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/XpmImagePlugin.py
+ Line number: 40
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+39	    def _open(self) -> None:
+40	        assert self.fp is not None
+41	        if not _accept(self.fp.read(9)):
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/XpmImagePlugin.py
+ Line number: 112
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+111	
+112	        assert self.fp is not None
+113	        s = [self.fp.readline()[1 : xsize + 1].ljust(xsize) for i in range(ysize)]
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/XpmImagePlugin.py
+ Line number: 122
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+121	    def decode(self, buffer: bytes | Image.SupportsArrayInterface) -> tuple[int, int]:
+122	        assert self.fd is not None
+123	
+
+
+ + +
+
+ +
+
+ trojansource: A Python source file contains bidirectional control characters ('\u202e').
+ Test ID: B613
+ Severity: HIGH
+ Confidence: MEDIUM
+ CWE: CWE-838
+ File: ./venv/lib/python3.12/site-packages/bandit/plugins/trojansource.py
+ Line number: 22
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b613_trojansource.html
+ +
+
+21	     3  	access_level = "user"
+22	     4	    if access_level != 'none‮⁦': # Check if admin ⁩⁦' and access_level != 'user
+23	     5	        print("You are an admin.\n")
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/blinker/base.py
+ Line number: 420
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+419	        """
+420	        assert sender_id != ANY_ID
+421	
+
+
+ + +
+
+ +
+
+ try_except_pass: Try, Except, Pass detected.
+ Test ID: B110
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/click/_compat.py
+ Line number: 74
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b110_try_except_pass.html
+ +
+
+73	            self.detach()
+74	        except Exception:
+75	            pass
+76	
+
+
+ + +
+
+ +
+
+ try_except_pass: Try, Except, Pass detected.
+ Test ID: B110
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/click/_compat.py
+ Line number: 167
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b110_try_except_pass.html
+ +
+
+166	            return False
+167	        except Exception:
+168	            pass
+169	        return default
+
+
+ + +
+
+ +
+
+ blacklist: Standard pseudo-random generators are not suitable for security/cryptographic purposes.
+ Test ID: B311
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-330
+ File: ./venv/lib/python3.12/site-packages/click/_compat.py
+ Line number: 429
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b311-random
+ +
+
+428	            os.path.dirname(filename),
+429	            f".__atomic-write{random.randrange(1 << 32):08x}",
+430	        )
+
+
+ + +
+
+ +
+
+ try_except_pass: Try, Except, Pass detected.
+ Test ID: B110
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/click/_compat.py
+ Line number: 552
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b110_try_except_pass.html
+ +
+
+551	            _ansi_stream_wrappers[stream] = rv
+552	        except Exception:
+553	            pass
+554	
+
+
+ + +
+
+ +
+
+ try_except_pass: Try, Except, Pass detected.
+ Test ID: B110
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/click/_compat.py
+ Line number: 600
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b110_try_except_pass.html
+ +
+
+599	            cache[stream] = rv
+600	        except Exception:
+601	            pass
+602	        return rv
+
+
+ + +
+
+ +
+
+ blacklist: Consider possible security implications associated with the subprocess module.
+ Test ID: B404
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/click/_termui_impl.py
+ Line number: 439
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_imports.html#b404-import-subprocess
+ +
+
+438	
+439	    import subprocess
+440	
+
+
+ + +
+
+ +
+
+ subprocess_without_shell_equals_true: subprocess call - check for execution of untrusted input.
+ Test ID: B603
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/click/_termui_impl.py
+ Line number: 456
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b603_subprocess_without_shell_equals_true.html
+ +
+
+455	        [str(cmd_path)] + cmd_params,
+456	        shell=False,
+457	        stdin=subprocess.PIPE,
+458	        env=env,
+459	        errors="replace",
+460	        text=True,
+461	    )
+462	    assert c.stdin is not None
+463	    try:
+464	        for text in generator:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/click/_termui_impl.py
+ Line number: 462
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+461	    )
+462	    assert c.stdin is not None
+463	    try:
+
+
+ + +
+
+ +
+
+ blacklist: Consider possible security implications associated with the subprocess module.
+ Test ID: B404
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/click/_termui_impl.py
+ Line number: 531
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_imports.html#b404-import-subprocess
+ +
+
+530	
+531	    import subprocess
+532	    import tempfile
+
+
+ + +
+
+ +
+
+ subprocess_without_shell_equals_true: subprocess call - check for execution of untrusted input.
+ Test ID: B603
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/click/_termui_impl.py
+ Line number: 543
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b603_subprocess_without_shell_equals_true.html
+ +
+
+542	    try:
+543	        subprocess.call([str(cmd_path), filename])
+544	    except OSError:
+
+
+ + +
+
+ +
+
+ blacklist: Consider possible security implications associated with the subprocess module.
+ Test ID: B404
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/click/_termui_impl.py
+ Line number: 595
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_imports.html#b404-import-subprocess
+ +
+
+594	    def edit_files(self, filenames: cabc.Iterable[str]) -> None:
+595	        import subprocess
+596	
+
+
+ + +
+
+ +
+
+ blacklist: Consider possible security implications associated with the subprocess module.
+ Test ID: B404
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/click/_termui_impl.py
+ Line number: 677
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_imports.html#b404-import-subprocess
+ +
+
+676	def open_url(url: str, wait: bool = False, locate: bool = False) -> int:
+677	    import subprocess
+678	
+
+
+ + +
+
+ +
+
+ subprocess_without_shell_equals_true: subprocess call - check for execution of untrusted input.
+ Test ID: B603
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/click/_termui_impl.py
+ Line number: 696
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b603_subprocess_without_shell_equals_true.html
+ +
+
+695	        try:
+696	            return subprocess.Popen(args, stderr=null).wait()
+697	        finally:
+
+
+ + +
+
+ +
+
+ subprocess_without_shell_equals_true: subprocess call - check for execution of untrusted input.
+ Test ID: B603
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/click/_termui_impl.py
+ Line number: 710
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b603_subprocess_without_shell_equals_true.html
+ +
+
+709	        try:
+710	            return subprocess.call(args)
+711	        except OSError:
+
+
+ + +
+
+ +
+
+ subprocess_without_shell_equals_true: subprocess call - check for execution of untrusted input.
+ Test ID: B603
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/click/_termui_impl.py
+ Line number: 724
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b603_subprocess_without_shell_equals_true.html
+ +
+
+723	        try:
+724	            return subprocess.call(args)
+725	        except OSError:
+
+
+ + +
+
+ +
+
+ start_process_with_partial_path: Starting a process with a partial executable path
+ Test ID: B607
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/click/_termui_impl.py
+ Line number: 734
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b607_start_process_with_partial_path.html
+ +
+
+733	            url = _unquote_file(url)
+734	        c = subprocess.Popen(["xdg-open", url])
+735	        if wait:
+
+
+ + +
+
+ +
+
+ subprocess_without_shell_equals_true: subprocess call - check for execution of untrusted input.
+ Test ID: B603
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/click/_termui_impl.py
+ Line number: 734
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b603_subprocess_without_shell_equals_true.html
+ +
+
+733	            url = _unquote_file(url)
+734	        c = subprocess.Popen(["xdg-open", url])
+735	        if wait:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/click/_winconsole.py
+ Line number: 34
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+33	
+34	assert sys.platform == "win32"
+35	import msvcrt  # noqa: E402
+
+
+ + +
+
+ +
+
+ try_except_pass: Try, Except, Pass detected.
+ Test ID: B110
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/click/_winconsole.py
+ Line number: 208
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b110_try_except_pass.html
+ +
+
+207	            self.flush()
+208	        except Exception:
+209	            pass
+210	        return self.buffer.write(x)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/click/core.py
+ Line number: 1662
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1661	        if args and callable(args[0]):
+1662	            assert len(args) == 1 and not kwargs, (
+1663	                "Use 'command(**kwargs)(callable)' to provide arguments."
+1664	            )
+1665	            (func,) = args
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/click/core.py
+ Line number: 1711
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1710	        if args and callable(args[0]):
+1711	            assert len(args) == 1 and not kwargs, (
+1712	                "Use 'group(**kwargs)(callable)' to provide arguments."
+1713	            )
+1714	            (func,) = args
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/click/core.py
+ Line number: 1868
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1867	                cmd_name, cmd, args = self.resolve_command(ctx, args)
+1868	                assert cmd is not None
+1869	                ctx.invoked_subcommand = cmd_name
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/click/core.py
+ Line number: 1890
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1889	                cmd_name, cmd, args = self.resolve_command(ctx, args)
+1890	                assert cmd is not None
+1891	                sub_ctx = cmd.make_context(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/click/core.py
+ Line number: 2602
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2601	            # not to be exposed. We still assert it here to please the type checker.
+2602	            assert self.name is not None, (
+2603	                f"{self!r} parameter's name should not be None when exposing value."
+2604	            )
+2605	            ctx.params[self.name] = value
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/click/core.py
+ Line number: 3142
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+3141	        """
+3142	        assert self.prompt is not None
+3143	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/click/decorators.py
+ Line number: 211
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+210	        name = None
+211	        assert cls is None, "Use 'command(cls=cls)(callable)' to specify a class."
+212	        assert not attrs, "Use 'command(**kwargs)(callable)' to provide arguments."
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/click/decorators.py
+ Line number: 212
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+211	        assert cls is None, "Use 'command(cls=cls)(callable)' to specify a class."
+212	        assert not attrs, "Use 'command(**kwargs)(callable)' to provide arguments."
+213	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/click/decorators.py
+ Line number: 236
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+235	        if t.TYPE_CHECKING:
+236	            assert cls is not None
+237	            assert not callable(name)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/click/decorators.py
+ Line number: 237
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+236	            assert cls is not None
+237	            assert not callable(name)
+238	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/click/parser.py
+ Line number: 193
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+192	        if self.nargs > 1:
+193	            assert isinstance(value, cabc.Sequence)
+194	            holes = sum(1 for x in value if x is UNSET)
+
+
+ + +
+
+ +
+
+ blacklist: Consider possible security implications associated with the subprocess module.
+ Test ID: B404
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/click/shell_completion.py
+ Line number: 313
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_imports.html#b404-import-subprocess
+ +
+
+312	        import shutil
+313	        import subprocess
+314	
+
+
+ + +
+
+ +
+
+ subprocess_without_shell_equals_true: subprocess call - check for execution of untrusted input.
+ Test ID: B603
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/click/shell_completion.py
+ Line number: 320
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b603_subprocess_without_shell_equals_true.html
+ +
+
+319	        else:
+320	            output = subprocess.run(
+321	                [bash_exe, "--norc", "-c", 'echo "${BASH_VERSION}"'],
+322	                stdout=subprocess.PIPE,
+323	            )
+324	            match = re.search(r"^(\d+)\.(\d+)\.\d+", output.stdout.decode())
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/click/shell_completion.py
+ Line number: 514
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+513	
+514	    assert param.name is not None
+515	    # Will be None if expose_value is False.
+
+
+ + +
+
+ +
+
+ try_except_pass: Try, Except, Pass detected.
+ Test ID: B110
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/click/testing.py
+ Line number: 406
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b110_try_except_pass.html
+ +
+
+405	                        del os.environ[key]
+406	                    except Exception:
+407	                        pass
+408	                else:
+
+
+ + +
+
+ +
+
+ try_except_pass: Try, Except, Pass detected.
+ Test ID: B110
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/click/testing.py
+ Line number: 416
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b110_try_except_pass.html
+ +
+
+415	                        del os.environ[key]
+416	                    except Exception:
+417	                        pass
+418	                else:
+
+
+ + +
+
+ +
+
+ try_except_pass: Try, Except, Pass detected.
+ Test ID: B110
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/click/utils.py
+ Line number: 42
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b110_try_except_pass.html
+ +
+
+41	            return func(*args, **kwargs)
+42	        except Exception:
+43	            pass
+44	        return None
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/_asyncio_backend.py
+ Line number: 81
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+80	        try:
+81	            assert self.protocol.recvfrom is None
+82	            self.protocol.recvfrom = done
+
+
+ + +
+
+ +
+
+ try_except_pass: Try, Except, Pass detected.
+ Test ID: B110
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/_asyncio_backend.py
+ Line number: 179
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b110_try_except_pass.html
+ +
+
+178	                    return _CoreAnyIOStream(stream)
+179	                except Exception:
+180	                    pass
+181	            raise httpcore.ConnectError
+
+
+ + +
+
+ +
+
+ try_except_pass: Try, Except, Pass detected.
+ Test ID: B110
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/_ddr.py
+ Line number: 109
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b110_try_except_pass.html
+ +
+
+108	                nameservers.append(dns.nameserver.DoHNameserver(url, bootstrap_address))
+109	            except Exception:
+110	                # continue processing other ALPN types
+111	                pass
+112	        if b"dot" in alpns:
+
+
+ + +
+
+ +
+
+ try_except_pass: Try, Except, Pass detected.
+ Test ID: B110
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/_ddr.py
+ Line number: 138
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b110_try_except_pass.html
+ +
+
+137	                nameservers.extend(info.nameservers)
+138	        except Exception:
+139	            pass
+140	    return nameservers
+
+
+ + +
+
+ +
+
+ try_except_pass: Try, Except, Pass detected.
+ Test ID: B110
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/_ddr.py
+ Line number: 152
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b110_try_except_pass.html
+ +
+
+151	                nameservers.extend(info.nameservers)
+152	        except Exception:
+153	            pass
+154	    return nameservers
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/_trio_backend.py
+ Line number: 154
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+153	                    )
+154	                    assert isinstance(sock, StreamSocket)
+155	                    return _CoreTrioStream(sock.stream)
+
+
+ + +
+
+ +
+
+ try_except_continue: Try, Except, Continue detected.
+ Test ID: B112
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/_trio_backend.py
+ Line number: 156
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b112_try_except_continue.html
+ +
+
+155	                    return _CoreTrioStream(sock.stream)
+156	                except Exception:
+157	                    continue
+158	            raise httpcore.ConnectError
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/_trio_backend.py
+ Line number: 215
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+214	                with _maybe_timeout(timeout):
+215	                    assert destination is not None
+216	                    await s.connect(_lltuple(destination, af))
+
+
+ + +
+
+ +
+
+ hardcoded_bind_all_interfaces: Possible binding to all interfaces.
+ Test ID: B104
+ Severity: MEDIUM
+ Confidence: MEDIUM
+ CWE: CWE-605
+ File: ./venv/lib/python3.12/site-packages/dns/asyncquery.py
+ Line number: 72
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b104_hardcoded_bind_all_interfaces.html
+ +
+
+71	            if af == socket.AF_INET:
+72	                address = "0.0.0.0"
+73	            elif af == socket.AF_INET6:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/asyncquery.py
+ Line number: 589
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+588	            resolver = _maybe_get_resolver(resolver)
+589	            assert parsed.hostname is not None  # pyright: ignore
+590	            answers = await resolver.resolve_name(  # pyright: ignore
+
+
+ + +
+
+ +
+
+ blacklist: Standard pseudo-random generators are not suitable for security/cryptographic purposes.
+ Test ID: B311
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-330
+ File: ./venv/lib/python3.12/site-packages/dns/asyncquery.py
+ Line number: 593
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b311-random
+ +
+
+592	            )
+593	            bootstrap_address = random.choice(list(answers.addresses()))
+594	        if client and not isinstance(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/asyncquery.py
+ Line number: 598
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+597	            raise ValueError("client parameter must be a dns.quic.AsyncQuicConnection.")
+598	        assert client is None or isinstance(client, dns.quic.AsyncQuicConnection)
+599	        return await _http3(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/asyncquery.py
+ Line number: 726
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+725	    hostname = url_parts.hostname
+726	    assert hostname is not None
+727	    if url_parts.port is not None:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/asyncresolver.py
+ Line number: 86
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+85	                return answer
+86	            assert request is not None  # needed for type checking
+87	            done = False
+
+
+ + +
+
+ +
+
+ try_except_pass: Try, Except, Pass detected.
+ Test ID: B110
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/asyncresolver.py
+ Line number: 259
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b110_try_except_pass.html
+ +
+
+258	                self.nameservers = nameservers
+259	        except Exception:
+260	            pass
+261	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/asyncresolver.py
+ Line number: 270
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+269	        reset_default_resolver()
+270	    assert default_resolver is not None
+271	    return default_resolver
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/asyncresolver.py
+ Line number: 388
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+387	            )
+388	            assert answer.rrset is not None
+389	            if answer.rrset.name == name:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/btree.py
+ Line number: 61
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+60	    def __init__(self, t: int, creator: _Creator, is_leaf: bool):
+61	        assert t >= 3
+62	        self.t = t
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/btree.py
+ Line number: 70
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+69	        """Does this node have the maximal number of keys?"""
+70	        assert len(self.elts) <= _MAX(self.t)
+71	        return len(self.elts) == _MAX(self.t)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/btree.py
+ Line number: 75
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+74	        """Does this node have the minimal number of keys?"""
+75	        assert len(self.elts) >= _MIN(self.t)
+76	        return len(self.elts) == _MIN(self.t)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/btree.py
+ Line number: 108
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+107	    def maybe_cow_child(self, index: int) -> "_Node[KT, ET]":
+108	        assert not self.is_leaf
+109	        child = self.children[index]
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/btree.py
+ Line number: 162
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+161	    def insert_nonfull(self, element: ET, in_order: bool) -> ET | None:
+162	        assert not self.is_maximal()
+163	        while True:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/btree.py
+ Line number: 188
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+187	        """Split a maximal node into two minimal ones and a central element."""
+188	        assert self.is_maximal()
+189	        right = self.__class__(self.t, self.creator, self.is_leaf)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/btree.py
+ Line number: 211
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+210	                if not left.is_leaf:
+211	                    assert not self.is_leaf
+212	                    child = left.children.pop()
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/btree.py
+ Line number: 230
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+229	                if not right.is_leaf:
+230	                    assert not self.is_leaf
+231	                    child = right.children.pop(0)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/btree.py
+ Line number: 240
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+239	        then the left child must already be in the Node."""
+240	        assert not self.is_maximal()
+241	        assert not self.is_leaf
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/btree.py
+ Line number: 241
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+240	        assert not self.is_maximal()
+241	        assert not self.is_leaf
+242	        key = middle.key()
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/btree.py
+ Line number: 244
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+243	        i, equal = self.search_in_node(key)
+244	        assert not equal
+245	        self.elts.insert(i, middle)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/btree.py
+ Line number: 250
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+249	        else:
+250	            assert self.children[i] == left
+251	            self.children.insert(i + 1, right)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/btree.py
+ Line number: 279
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+278	        with one of them."""
+279	        assert not parent.is_leaf
+280	        if self.try_left_steal(parent, index):
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/btree.py
+ Line number: 300
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+299	        minimal unless it is the root."""
+300	        assert parent is None or not self.is_minimal()
+301	        i, equal = self.search_in_node(key)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/btree.py
+ Line number: 328
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+327	            i, equal = self.search_in_node(key)
+328	            assert not equal
+329	            child = self.children[i]
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/btree.py
+ Line number: 330
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+329	            child = self.children[i]
+330	            assert not child.is_minimal()
+331	        elt = child.delete(key, self, exact)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/btree.py
+ Line number: 334
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+333	            node, i = self._get_node(original_key)
+334	            assert node is not None
+335	            assert elt is not None
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/btree.py
+ Line number: 335
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+334	            assert node is not None
+335	            assert elt is not None
+336	            oelt = node.elts[i]
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/btree.py
+ Line number: 406
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+405	        # current node
+406	        assert self.current_node is not None
+407	        while not self.current_node.is_leaf:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/btree.py
+ Line number: 410
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+409	            self.current_node = self.current_node.children[self.current_index]
+410	            assert self.current_node is not None
+411	            self.current_index = 0
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/btree.py
+ Line number: 416
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+415	        # current node
+416	        assert self.current_node is not None
+417	        while not self.current_node.is_leaf:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/btree.py
+ Line number: 420
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+419	            self.current_node = self.current_node.children[self.current_index]
+420	            assert self.current_node is not None
+421	            self.current_index = len(self.current_node.elts)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/btree.py
+ Line number: 464
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+463	            else:
+464	                assert self.current_index == 1
+465	                # right boundary; seek to the actual boundary
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/btree.py
+ Line number: 504
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+503	            else:
+504	                assert self.current_index == 0
+505	                # left boundary; seek to the actual boundary
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/btree.py
+ Line number: 550
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+549	        self.current_node = self.btree.root
+550	        assert self.current_node is not None
+551	        self.recurse = False
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/btree.py
+ Line number: 568
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+567	            self.current_node = self.current_node.children[i]
+568	            assert self.current_node is not None
+569	        i, equal = self.current_node.search_in_node(key)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/btree.py
+ Line number: 707
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+706	                if not self.root.is_leaf:
+707	                    assert len(self.root.children) == 1
+708	                    self.root = self.root.children[0]
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/btree.py
+ Line number: 724
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+723	        delt = self._delete(element.key(), element)
+724	        assert delt is element
+725	        return delt
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/btreezone.py
+ Line number: 144
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+143	        if not replacement:
+144	            assert isinstance(zone, dns.versioned.Zone)
+145	            version = zone._versions[-1]
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/btreezone.py
+ Line number: 190
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+189	                node = new_node
+190	            assert isinstance(node, Node)
+191	            if is_glue:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/btreezone.py
+ Line number: 312
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+311	        """
+312	        assert self.origin is not None
+313	        # validate the origin because we may need to relativize
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/btreezone.py
+ Line number: 326
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+325	        left = c.prev()
+326	        assert left is not None
+327	        c.next()  # skip over left
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/dnssec.py
+ Line number: 117
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+116	    rdata = key.to_wire()
+117	    assert rdata is not None  # for mypy
+118	    if key.algorithm == Algorithm.RSAMD5:
+
+
+ + +
+
+ +
+
+ hashlib: Use of weak SHA1 hash for security. Consider usedforsecurity=False
+ Test ID: B324
+ Severity: HIGH
+ Confidence: HIGH
+ CWE: CWE-327
+ File: ./venv/lib/python3.12/site-packages/dns/dnssec.py
+ Line number: 234
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b324_hashlib.html
+ +
+
+233	    if algorithm == DSDigest.SHA1:
+234	        dshash = hashlib.sha1()
+235	    elif algorithm == DSDigest.SHA256:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/dnssec.py
+ Line number: 246
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+245	    kwire = key.to_wire(origin=origin)
+246	    assert wire is not None and kwire is not None  # for mypy
+247	    dshash.update(wire)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/dnssec.py
+ Line number: 639
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+638	    wire = rrsig.to_wire(origin=signer)
+639	    assert wire is not None  # for mypy
+640	    data += wire[:18]
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/dnssec.py
+ Line number: 792
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+791	    domain_encoded = domain.canonicalize().to_wire()
+792	    assert domain_encoded is not None
+793	
+
+
+ + +
+
+ +
+
+ hashlib: Use of weak SHA1 hash for security. Consider usedforsecurity=False
+ Test ID: B324
+ Severity: HIGH
+ Confidence: HIGH
+ CWE: CWE-327
+ File: ./venv/lib/python3.12/site-packages/dns/dnssec.py
+ Line number: 794
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b324_hashlib.html
+ +
+
+793	
+794	    digest = hashlib.sha1(domain_encoded + salt_encoded).digest()
+795	    for _ in range(iterations):
+
+
+ + +
+
+ +
+
+ hashlib: Use of weak SHA1 hash for security. Consider usedforsecurity=False
+ Test ID: B324
+ Severity: HIGH
+ Confidence: HIGH
+ CWE: CWE-327
+ File: ./venv/lib/python3.12/site-packages/dns/dnssec.py
+ Line number: 796
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b324_hashlib.html
+ +
+
+795	    for _ in range(iterations):
+796	        digest = hashlib.sha1(digest + salt_encoded).digest()
+797	
+
+
+ + +
+
+ +
+
+ blacklist: Use of insecure MD2, MD4, MD5, or SHA1 hash function.
+ Test ID: B303
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-327
+ File: ./venv/lib/python3.12/site-packages/dns/dnssecalgs/dsa.py
+ Line number: 16
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b303-md5
+ +
+
+15	    algorithm = Algorithm.DSA
+16	    chosen_hash = hashes.SHA1()
+17	
+
+
+ + +
+
+ +
+
+ blacklist: Use of insecure MD2, MD4, MD5, or SHA1 hash function.
+ Test ID: B303
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-327
+ File: ./venv/lib/python3.12/site-packages/dns/dnssecalgs/rsa.py
+ Line number: 86
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b303-md5
+ +
+
+85	    algorithm = Algorithm.RSAMD5
+86	    chosen_hash = hashes.MD5()
+87	
+
+
+ + +
+
+ +
+
+ blacklist: Use of insecure MD2, MD4, MD5, or SHA1 hash function.
+ Test ID: B303
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-327
+ File: ./venv/lib/python3.12/site-packages/dns/dnssecalgs/rsa.py
+ Line number: 95
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b303-md5
+ +
+
+94	    algorithm = Algorithm.RSASHA1
+95	    chosen_hash = hashes.SHA1()
+96	
+
+
+ + +
+
+ +
+
+ blacklist: Use of insecure MD2, MD4, MD5, or SHA1 hash function.
+ Test ID: B303
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-327
+ File: ./venv/lib/python3.12/site-packages/dns/dnssecalgs/rsa.py
+ Line number: 104
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b303-md5
+ +
+
+103	    algorithm = Algorithm.RSASHA1NSEC3SHA1
+104	    chosen_hash = hashes.SHA1()
+105	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/edns.py
+ Line number: 95
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+94	        wire = self.to_wire()
+95	        assert wire is not None  # for mypy
+96	        return GenericOption(self.otype, wire)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/edns.py
+ Line number: 227
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+226	
+227	        assert srclen is not None
+228	        self.address = address
+
+
+ + +
+
+ +
+
+ hashlib: Use of weak SHA1 hash for security. Consider usedforsecurity=False
+ Test ID: B324
+ Severity: HIGH
+ Confidence: HIGH
+ CWE: CWE-327
+ File: ./venv/lib/python3.12/site-packages/dns/entropy.py
+ Line number: 37
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b324_hashlib.html
+ +
+
+36	        self.lock = threading.Lock()
+37	        self.hash = hashlib.sha1()
+38	        self.hash_len = 20
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/exception.py
+ Line number: 76
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+75	        if args or kwargs:
+76	            assert bool(args) != bool(
+77	                kwargs
+78	            ), "keyword arguments are mutually exclusive with positional args"
+79	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/exception.py
+ Line number: 82
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+81	        if kwargs:
+82	            assert (
+83	                set(kwargs.keys()) == self.supp_kwargs
+84	            ), f"following set of keyword args is required: {self.supp_kwargs}"
+85	        return kwargs
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/grange.py
+ Line number: 64
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+63	    else:
+64	        assert state == 2
+65	        step = int(cur)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/grange.py
+ Line number: 67
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+66	
+67	    assert step >= 1
+68	    assert start >= 0
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/grange.py
+ Line number: 68
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+67	    assert step >= 1
+68	    assert start >= 0
+69	    if start > stop:
+
+
+ + +
+
+ +
+
+ hardcoded_bind_all_interfaces: Possible binding to all interfaces.
+ Test ID: B104
+ Severity: MEDIUM
+ Confidence: MEDIUM
+ CWE: CWE-605
+ File: ./venv/lib/python3.12/site-packages/dns/inet.py
+ Line number: 175
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b104_hardcoded_bind_all_interfaces.html
+ +
+
+174	    if af == socket.AF_INET:
+175	        return "0.0.0.0"
+176	    elif af == socket.AF_INET6:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/message.py
+ Line number: 1154
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1153	        """
+1154	        assert self.message is not None
+1155	        section = self.message.sections[section_number]
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/message.py
+ Line number: 1176
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1175	        """
+1176	        assert self.message is not None
+1177	        section = self.message.sections[section_number]
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/message.py
+ Line number: 1499
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1498	
+1499	        assert self.message is not None
+1500	        section = self.message.sections[section_number]
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/message.py
+ Line number: 1537
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1536	
+1537	        assert self.message is not None
+1538	        section = self.message.sections[section_number]
+
+
+ + +
+
+ +
+
+ try_except_pass: Try, Except, Pass detected.
+ Test ID: B110
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/message.py
+ Line number: 1654
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b110_try_except_pass.html
+ +
+
+1653	                        line_method = self._rr_line
+1654	                except Exception:
+1655	                    # It's just a comment.
+1656	                    pass
+1657	                self.tok.get_eol()
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/message.py
+ Line number: 1746
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1745	        return from_text(f, idna_codec, one_rr_per_rrset)
+1746	    assert False  # for mypy  lgtm[py/unreachable-statement]
+1747	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/message.py
+ Line number: 1932
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1931	    if query.had_tsig and query.keyring:
+1932	        assert query.mac is not None
+1933	        assert query.keyalgorithm is not None
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/message.py
+ Line number: 1933
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1932	        assert query.mac is not None
+1933	        assert query.keyalgorithm is not None
+1934	        response.use_tsig(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/name.py
+ Line number: 647
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+646	        digest = self.to_wire(origin=origin, canonicalize=True)
+647	        assert digest is not None
+648	        return digest
+
+
+ + +
+
+ +
+
+ hardcoded_bind_all_interfaces: Possible binding to all interfaces.
+ Test ID: B104
+ Severity: MEDIUM
+ Confidence: MEDIUM
+ CWE: CWE-605
+ File: ./venv/lib/python3.12/site-packages/dns/query.py
+ Line number: 106
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b104_hardcoded_bind_all_interfaces.html
+ +
+
+105	                    if local_address is None:
+106	                        local_address = "0.0.0.0"
+107	                    source = dns.inet.low_level_address_tuple(
+
+
+ + +
+
+ +
+
+ try_except_pass: Try, Except, Pass detected.
+ Test ID: B110
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/query.py
+ Line number: 121
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b110_try_except_pass.html
+ +
+
+120	                    return _CoreSyncStream(sock)
+121	                except Exception:
+122	                    pass
+123	            raise httpcore.ConnectError
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/query.py
+ Line number: 542
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+541	            resolver = _maybe_get_resolver(resolver)
+542	            assert parsed.hostname is not None  # pyright: ignore
+543	            answers = resolver.resolve_name(parsed.hostname, family)  # pyright: ignore
+
+
+ + +
+
+ +
+
+ blacklist: Standard pseudo-random generators are not suitable for security/cryptographic purposes.
+ Test ID: B311
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-330
+ File: ./venv/lib/python3.12/site-packages/dns/query.py
+ Line number: 544
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b311-random
+ +
+
+543	            answers = resolver.resolve_name(parsed.hostname, family)  # pyright: ignore
+544	            bootstrap_address = random.choice(list(answers.addresses()))
+545	        if session and not isinstance(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/query.py
+ Line number: 604
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+603	        # GET and POST examples
+604	        assert session is not None
+605	        if post:
+
+
+ + +
+
+ +
+
+ try_except_pass: Try, Except, Pass detected.
+ Test ID: B110
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/query.py
+ Line number: 671
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b110_try_except_pass.html
+ +
+
+670	                error = ": " + wire.decode()
+671	            except Exception:
+672	                pass
+673	        raise ValueError(f"{peer} responded with status code {status}{error}")
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/query.py
+ Line number: 695
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+694	    hostname = url_parts.hostname
+695	    assert hostname is not None
+696	    if url_parts.port is not None:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/query.py
+ Line number: 963
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+962	    else:
+963	        assert af is not None
+964	        cm = make_socket(af, socket.SOCK_DGRAM, source)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/query.py
+ Line number: 986
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+985	        return r
+986	    assert (
+987	        False  # help mypy figure out we can't get here  lgtm[py/unreachable-statement]
+988	    )
+989	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/query.py
+ Line number: 1255
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1254	        )
+1255	        assert af is not None
+1256	        cm = make_socket(af, socket.SOCK_STREAM, source)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/query.py
+ Line number: 1269
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1268	        return r
+1269	    assert (
+1270	        False  # help mypy figure out we can't get here  lgtm[py/unreachable-statement]
+1271	    )
+1272	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/query.py
+ Line number: 1407
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1406	    )
+1407	    assert af is not None  # where must be an address
+1408	    if ssl_context is None:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/query.py
+ Line number: 1428
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1427	        return r
+1428	    assert (
+1429	        False  # help mypy figure out we can't get here  lgtm[py/unreachable-statement]
+1430	    )
+1431	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/query.py
+ Line number: 1702
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1701	    )
+1702	    assert af is not None
+1703	    (_, expiration) = _compute_times(lifetime)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/query.py
+ Line number: 1768
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1767	    )
+1768	    assert af is not None
+1769	    (_, expiration) = _compute_times(lifetime)
+
+
+ + +
+
+ +
+
+ try_except_pass: Try, Except, Pass detected.
+ Test ID: B110
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/quic/_asyncio.py
+ Line number: 125
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b110_try_except_pass.html
+ +
+
+124	                    await self._wakeup()
+125	        except Exception:
+126	            pass
+127	        finally:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/quic/_asyncio.py
+ Line number: 148
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+147	            for datagram, address in datagrams:
+148	                assert address == self._peer
+149	                assert self._socket is not None
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/quic/_asyncio.py
+ Line number: 149
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+148	                assert address == self._peer
+149	                assert self._socket is not None
+150	                await self._socket.sendto(datagram, self._peer, None)
+
+
+ + +
+
+ +
+
+ try_except_pass: Try, Except, Pass detected.
+ Test ID: B110
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/quic/_asyncio.py
+ Line number: 154
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b110_try_except_pass.html
+ +
+
+153	                await asyncio.wait_for(self._wait_for_wake_timer(), interval)
+154	            except Exception:
+155	                pass
+156	            self._handle_timer(expiration)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/quic/_asyncio.py
+ Line number: 167
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+166	                if self.is_h3():
+167	                    assert self._h3_conn is not None
+168	                    h3_events = self._h3_conn.handle_event(event)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/quic/_common.py
+ Line number: 53
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+52	    def get(self, amount):
+53	        assert self.have(amount)
+54	        data = self._buffer[:amount]
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/quic/_common.py
+ Line number: 59
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+58	    def get_all(self):
+59	        assert self.seen_end()
+60	        data = self._buffer
+
+
+ + +
+
+ +
+
+ hardcoded_bind_all_interfaces: Possible binding to all interfaces.
+ Test ID: B104
+ Severity: MEDIUM
+ Confidence: MEDIUM
+ CWE: CWE-605
+ File: ./venv/lib/python3.12/site-packages/dns/quic/_common.py
+ Line number: 176
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b104_hardcoded_bind_all_interfaces.html
+ +
+
+175	            if self._af == socket.AF_INET:
+176	                source = "0.0.0.0"
+177	            elif self._af == socket.AF_INET6:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/quic/_common.py
+ Line number: 193
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+192	    def send_headers(self, stream_id, headers, is_end=False):
+193	        assert self._h3_conn is not None
+194	        self._h3_conn.send_headers(stream_id, headers, is_end)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/quic/_common.py
+ Line number: 197
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+196	    def send_data(self, stream_id, data, is_end=False):
+197	        assert self._h3_conn is not None
+198	        self._h3_conn.send_data(stream_id, data, is_end)
+
+
+ + +
+
+ +
+
+ try_except_pass: Try, Except, Pass detected.
+ Test ID: B110
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/quic/_sync.py
+ Line number: 157
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b110_try_except_pass.html
+ +
+
+156	                            pass
+157	        except Exception:
+158	            # Eat all exceptions as we have no way to pass them back to the
+159	            # caller currently.  It might be nice to fix this in the future.
+160	            pass
+161	        finally:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/quic/_sync.py
+ Line number: 176
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+175	                if self.is_h3():
+176	                    assert self._h3_conn is not None
+177	                    h3_events = self._h3_conn.handle_event(event)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/quic/_trio.py
+ Line number: 142
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+141	                if self.is_h3():
+142	                    assert self._h3_conn is not None
+143	                    h3_events = self._h3_conn.handle_event(event)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/rdata.py
+ Line number: 255
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+254	        wire = self.to_wire(origin=origin)
+255	        assert wire is not None  # for type checkers
+256	        return GenericRdata(self.rdclass, self.rdtype, wire)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/rdata.py
+ Line number: 265
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+264	        wire = self.to_wire(origin=origin, canonicalize=True)
+265	        assert wire is not None  # for mypy
+266	        return wire
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/rdata.py
+ Line number: 776
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+775	    cls = get_rdata_class(rdclass, rdtype)
+776	    assert cls is not None  # for type checkers
+777	    with dns.exception.ExceptionWrapper(dns.exception.SyntaxError):
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/rdata.py
+ Line number: 849
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+848	    cls = get_rdata_class(rdclass, rdtype)
+849	    assert cls is not None  # for type checkers
+850	    with dns.exception.ExceptionWrapper(dns.exception.FormError):
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/rdataset.py
+ Line number: 497
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+496	        r.add(rd)
+497	    assert r is not None
+498	    return r
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/rdtypes/ANY/CAA.py
+ Line number: 57
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+56	        l = len(self.tag)
+57	        assert l < 256
+58	        file.write(struct.pack("!B", l))
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/rdtypes/ANY/GPOS.py
+ Line number: 94
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+93	        l = len(self.latitude)
+94	        assert l < 256
+95	        file.write(struct.pack("!B", l))
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/rdtypes/ANY/GPOS.py
+ Line number: 98
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+97	        l = len(self.longitude)
+98	        assert l < 256
+99	        file.write(struct.pack("!B", l))
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/rdtypes/ANY/GPOS.py
+ Line number: 102
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+101	        l = len(self.altitude)
+102	        assert l < 256
+103	        file.write(struct.pack("!B", l))
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/rdtypes/ANY/HINFO.py
+ Line number: 52
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+51	        l = len(self.cpu)
+52	        assert l < 256
+53	        file.write(struct.pack("!B", l))
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/rdtypes/ANY/HINFO.py
+ Line number: 56
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+55	        l = len(self.os)
+56	        assert l < 256
+57	        file.write(struct.pack("!B", l))
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/rdtypes/ANY/ISDN.py
+ Line number: 62
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+61	        l = len(self.address)
+62	        assert l < 256
+63	        file.write(struct.pack("!B", l))
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/rdtypes/ANY/ISDN.py
+ Line number: 67
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+66	        if l > 0:
+67	            assert l < 256
+68	            file.write(struct.pack("!B", l))
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/rdtypes/ANY/X25.py
+ Line number: 50
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+49	        l = len(self.address)
+50	        assert l < 256
+51	        file.write(struct.pack("!B", l))
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/rdtypes/IN/APL.py
+ Line number: 72
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+71	        l = len(address)
+72	        assert l < 128
+73	        if self.negation:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/rdtypes/IN/NAPTR.py
+ Line number: 29
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+28	    l = len(s)
+29	    assert l < 256
+30	    file.write(struct.pack("!B", l))
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/rdtypes/util.py
+ Line number: 54
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+53	            # check that it's OK
+54	            assert isinstance(self.gateway, str)
+55	            dns.ipv4.inet_aton(self.gateway)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/rdtypes/util.py
+ Line number: 58
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+57	            # check that it's OK
+58	            assert isinstance(self.gateway, str)
+59	            dns.ipv6.inet_aton(self.gateway)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/rdtypes/util.py
+ Line number: 72
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+71	        elif self.type == 3:
+72	            assert isinstance(self.gateway, dns.name.Name)
+73	            return str(self.gateway.choose_relativity(origin, relativize))
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/rdtypes/util.py
+ Line number: 96
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+95	        elif self.type == 1:
+96	            assert isinstance(self.gateway, str)
+97	            file.write(dns.ipv4.inet_aton(self.gateway))
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/rdtypes/util.py
+ Line number: 99
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+98	        elif self.type == 2:
+99	            assert isinstance(self.gateway, str)
+100	            file.write(dns.ipv6.inet_aton(self.gateway))
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/rdtypes/util.py
+ Line number: 102
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+101	        elif self.type == 3:
+102	            assert isinstance(self.gateway, dns.name.Name)
+103	            self.gateway.to_wire(file, None, origin, False)
+
+
+ + +
+
+ +
+
+ blacklist: Standard pseudo-random generators are not suitable for security/cryptographic purposes.
+ Test ID: B311
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-330
+ File: ./venv/lib/python3.12/site-packages/dns/rdtypes/util.py
+ Line number: 244
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b311-random
+ +
+
+243	        while len(rdatas) > 1:
+244	            r = random.uniform(0, total)
+245	            for n, rdata in enumerate(rdatas):  # noqa: B007
+
+
+ + +
+
+ +
+
+ blacklist: Standard pseudo-random generators are not suitable for security/cryptographic purposes.
+ Test ID: B311
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-330
+ File: ./venv/lib/python3.12/site-packages/dns/renderer.py
+ Line number: 108
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b311-random
+ +
+
+107	        if id is None:
+108	            self.id = random.randint(0, 65535)
+109	        else:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/renderer.py
+ Line number: 212
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+211	            ttl = opt.ttl
+212	            assert opt_size >= 11
+213	            opt_rdata = opt[0]
+
+
+ + +
+
+ +
+
+ try_except_pass: Try, Except, Pass detected.
+ Test ID: B110
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/resolver.py
+ Line number: 101
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b110_try_except_pass.html
+ +
+
+100	                    return cname
+101	            except Exception:  # pragma: no cover
+102	                # We can just eat this exception as it means there was
+103	                # something wrong with the response.
+104	                pass
+105	        return self.kwargs["qnames"][0]
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/resolver.py
+ Line number: 762
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+761	        if self.retry_with_tcp:
+762	            assert self.nameserver is not None
+763	            assert not self.nameserver.is_always_max_size()
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/resolver.py
+ Line number: 763
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+762	            assert self.nameserver is not None
+763	            assert not self.nameserver.is_always_max_size()
+764	            self.tcp_attempt = True
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/resolver.py
+ Line number: 787
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+786	        #
+787	        assert self.nameserver is not None
+788	        if ex:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/resolver.py
+ Line number: 790
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+789	            # Exception during I/O or from_wire()
+790	            assert response is None
+791	            self.errors.append(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/resolver.py
+ Line number: 816
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+815	        # We got an answer!
+816	        assert response is not None
+817	        assert isinstance(response, dns.message.QueryMessage)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/resolver.py
+ Line number: 817
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+816	        assert response is not None
+817	        assert isinstance(response, dns.message.QueryMessage)
+818	        rcode = response.rcode()
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/resolver.py
+ Line number: 1322
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1321	                return answer
+1322	            assert request is not None  # needed for type checking
+1323	            done = False
+
+
+ + +
+
+ +
+
+ try_except_pass: Try, Except, Pass detected.
+ Test ID: B110
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/resolver.py
+ Line number: 1525
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b110_try_except_pass.html
+ +
+
+1524	                self.nameservers = nameservers
+1525	        except Exception:  # pragma: no cover
+1526	            pass
+1527	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/resolver.py
+ Line number: 1537
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1536	        reset_default_resolver()
+1537	    assert default_resolver is not None
+1538	    return default_resolver
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/resolver.py
+ Line number: 1716
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1715	            )
+1716	            assert answer.rrset is not None
+1717	            if answer.rrset.name == name:
+
+
+ + +
+
+ +
+
+ try_except_pass: Try, Except, Pass detected.
+ Test ID: B110
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/resolver.py
+ Line number: 1877
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b110_try_except_pass.html
+ +
+
+1876	        return _original_getaddrinfo(host, service, family, socktype, proto, flags)
+1877	    except Exception:
+1878	        pass
+1879	    # Something needs resolution!
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/resolver.py
+ Line number: 1881
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1880	    try:
+1881	        assert _resolver is not None
+1882	        answers = _resolver.resolve_name(host, family)
+
+
+ + +
+
+ +
+
+ try_except_pass: Try, Except, Pass detected.
+ Test ID: B110
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/resolver.py
+ Line number: 1903
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b110_try_except_pass.html
+ +
+
+1902	                port = socket.getservbyname(service)  # pyright: ignore
+1903	            except Exception:
+1904	                pass
+1905	    if port is None:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/resolver.py
+ Line number: 1944
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1943	        pname = "tcp"
+1944	    assert isinstance(addr, str)
+1945	    qname = dns.reversename.from_address(addr)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/resolver.py
+ Line number: 1948
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1947	        try:
+1948	            assert _resolver is not None
+1949	            answer = _resolver.resolve(qname, "PTR")
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/resolver.py
+ Line number: 1950
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1949	            answer = _resolver.resolve(qname, "PTR")
+1950	            assert answer.rrset is not None
+1951	            rdata = cast(dns.rdtypes.ANY.PTR.PTR, answer.rrset[0])
+
+
+ + +
+
+ +
+
+ try_except_pass: Try, Except, Pass detected.
+ Test ID: B110
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/resolver.py
+ Line number: 1977
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b110_try_except_pass.html
+ +
+
+1976	        # ignores them, so we do so here as well.
+1977	    except Exception:  # pragma: no cover
+1978	        pass
+1979	    return name
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/resolver.py
+ Line number: 2024
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2023	        addr = item[4][0]
+2024	        assert isinstance(addr, str)
+2025	        bin_addr = dns.inet.inet_pton(family, addr)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/rrset.py
+ Line number: 276
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+275	        r.add(rd)
+276	    assert r is not None
+277	    return r
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/tokenizer.py
+ Line number: 273
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+272	        self.line_number = 1
+273	        assert filename is not None
+274	        self.filename = filename
+
+
+ + +
+
+ +
+
+ hardcoded_password_string: Possible hardcoded password: ''
+ Test ID: B105
+ Severity: LOW
+ Confidence: MEDIUM
+ CWE: CWE-259
+ File: ./venv/lib/python3.12/site-packages/dns/tokenizer.py
+ Line number: 372
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b105_hardcoded_password_string.html
+ +
+
+371	            return Token(WHITESPACE, " ")
+372	        token = ""
+373	        ttype = IDENTIFIER
+
+
+ + +
+
+ +
+
+ hardcoded_password_string: Possible hardcoded password: ''
+ Test ID: B105
+ Severity: LOW
+ Confidence: MEDIUM
+ CWE: CWE-259
+ File: ./venv/lib/python3.12/site-packages/dns/tokenizer.py
+ Line number: 380
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b105_hardcoded_password_string.html
+ +
+
+379	                    raise dns.exception.UnexpectedEnd
+380	                if token == "" and ttype != QUOTED_STRING:
+381	                    if c == "(":
+
+
+ + +
+
+ +
+
+ hardcoded_password_string: Possible hardcoded password: ''
+ Test ID: B105
+ Severity: LOW
+ Confidence: MEDIUM
+ CWE: CWE-259
+ File: ./venv/lib/python3.12/site-packages/dns/tokenizer.py
+ Line number: 421
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b105_hardcoded_password_string.html
+ +
+
+420	                            self.skip_whitespace()
+421	                            token = ""
+422	                            continue
+
+
+ + +
+
+ +
+
+ hardcoded_password_string: Possible hardcoded password: ''
+ Test ID: B105
+ Severity: LOW
+ Confidence: MEDIUM
+ CWE: CWE-259
+ File: ./venv/lib/python3.12/site-packages/dns/tokenizer.py
+ Line number: 447
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b105_hardcoded_password_string.html
+ +
+
+446	            token += c
+447	        if token == "" and ttype != QUOTED_STRING:
+448	            if self.multiline:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/transaction.py
+ Line number: 442
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+441	                )
+442	            assert rdataset is not None  # for type checkers
+443	            if rdataset.rdclass != self.manager.get_class():
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/tsig.py
+ Line number: 225
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+224	            ctx.update(request_mac)
+225	    assert ctx is not None  # for type checkers
+226	    ctx.update(struct.pack("!H", rdata.original_id))
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/versioned.py
+ Line number: 100
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+99	                else:
+100	                    assert self.origin is not None
+101	                    oname = self.origin
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/versioned.py
+ Line number: 182
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+181	    def _prune_versions_unlocked(self):
+182	        assert len(self._versions) > 0
+183	        # Don't ever prune a version greater than or equal to one that
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/versioned.py
+ Line number: 243
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+242	    def _end_write_unlocked(self, txn):
+243	        assert self._write_txn == txn
+244	        self._write_txn = None
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/wire.py
+ Line number: 33
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+32	    def get_bytes(self, size: int) -> bytes:
+33	        assert size >= 0
+34	        if size > self.remaining():
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/wire.py
+ Line number: 78
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+77	    def restrict_to(self, size: int) -> Iterator:
+78	        assert size >= 0
+79	        if size > self.remaining():
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/xfr.py
+ Line number: 139
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+138	            if self.incremental:
+139	                assert self.soa_rdataset is not None
+140	                soa = cast(dns.rdtypes.ANY.SOA.SOA, self.soa_rdataset[0])
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/xfr.py
+ Line number: 170
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+169	                raise dns.exception.FormError("answers after final SOA")
+170	            assert self.txn is not None  # for mypy
+171	            if rdataset.rdtype == dns.rdatatype.SOA and name == self.origin:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/zone.py
+ Line number: 684
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+683	            if want_origin:
+684	                assert self.origin is not None
+685	                l = "$ORIGIN " + self.origin.to_text()
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/zone.py
+ Line number: 766
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+765	        else:
+766	            assert self.origin is not None
+767	            name = self.origin
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/zone.py
+ Line number: 815
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+814	        else:
+815	            assert self.origin is not None
+816	            origin_name = self.origin
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/zone.py
+ Line number: 853
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+852	        else:
+853	            assert self.origin is not None
+854	            rds = self.get_rdataset(self.origin, dns.rdatatype.ZONEMD)
+
+
+ + +
+
+ +
+
+ try_except_pass: Try, Except, Pass detected.
+ Test ID: B110
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/zone.py
+ Line number: 863
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b110_try_except_pass.html
+ +
+
+862	                    return
+863	            except Exception:
+864	                pass
+865	        raise DigestVerificationFailure
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/zone.py
+ Line number: 1120
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1119	    def _setup_version(self):
+1120	        assert self.version is None
+1121	        factory = self.manager.writable_version_factory  # pyright: ignore
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/zone.py
+ Line number: 1127
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1126	    def _get_rdataset(self, name, rdtype, covers):
+1127	        assert self.version is not None
+1128	        return self.version.get_rdataset(name, rdtype, covers)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/zone.py
+ Line number: 1131
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1130	    def _put_rdataset(self, name, rdataset):
+1131	        assert not self.read_only
+1132	        assert self.version is not None
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/zone.py
+ Line number: 1132
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1131	        assert not self.read_only
+1132	        assert self.version is not None
+1133	        self.version.put_rdataset(name, rdataset)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/zone.py
+ Line number: 1136
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1135	    def _delete_name(self, name):
+1136	        assert not self.read_only
+1137	        assert self.version is not None
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/zone.py
+ Line number: 1137
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1136	        assert not self.read_only
+1137	        assert self.version is not None
+1138	        self.version.delete_node(name)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/zone.py
+ Line number: 1141
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1140	    def _delete_rdataset(self, name, rdtype, covers):
+1141	        assert not self.read_only
+1142	        assert self.version is not None
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/zone.py
+ Line number: 1142
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1141	        assert not self.read_only
+1142	        assert self.version is not None
+1143	        self.version.delete_rdataset(name, rdtype, covers)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/zone.py
+ Line number: 1146
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1145	    def _name_exists(self, name):
+1146	        assert self.version is not None
+1147	        return self.version.get_node(name) is not None
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/zone.py
+ Line number: 1153
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1152	        else:
+1153	            assert self.version is not None
+1154	            return len(self.version.changed) > 0
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/zone.py
+ Line number: 1157
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1156	    def _end_transaction(self, commit):
+1157	        assert self.zone is not None
+1158	        assert self.version is not None
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/zone.py
+ Line number: 1158
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1157	        assert self.zone is not None
+1158	        assert self.version is not None
+1159	        if self.read_only:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/zone.py
+ Line number: 1178
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1177	    def _set_origin(self, origin):
+1178	        assert self.version is not None
+1179	        if self.version.origin is None:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/zone.py
+ Line number: 1183
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1182	    def _iterate_rdatasets(self):
+1183	        assert self.version is not None
+1184	        for name, node in self.version.items():
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/zone.py
+ Line number: 1189
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1188	    def _iterate_names(self):
+1189	        assert self.version is not None
+1190	        return self.version.keys()
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/zone.py
+ Line number: 1193
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1192	    def _get_node(self, name):
+1193	        assert self.version is not None
+1194	        return self.version.get_node(name)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/zone.py
+ Line number: 1197
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1196	    def _origin_information(self):
+1197	        assert self.version is not None
+1198	        (absolute, relativize, effective) = self.manager.origin_information()
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/zone.py
+ Line number: 1406
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1405	        )
+1406	    assert False  # make mypy happy  lgtm[py/unreachable-statement]
+1407	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/zonefile.py
+ Line number: 174
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+173	                raise dns.exception.SyntaxError("the last used name is undefined")
+174	            assert self.zone_origin is not None
+175	            if not name.is_subdomain(self.zone_origin):
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/zonefile.py
+ Line number: 430
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+429	            name = self.last_name
+430	            assert self.zone_origin is not None
+431	            if not name.is_subdomain(self.zone_origin):
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/zonefile.py
+ Line number: 563
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+562	    def __init__(self, manager, replacement, read_only):
+563	        assert not read_only
+564	        super().__init__(manager, replacement, read_only)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/zonefile.py
+ Line number: 646
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+645	    def writer(self, replacement=False):
+646	        assert replacement is True
+647	        return RRsetsReaderTransaction(self, True, False)
+
+
+ + +
+
+ +
+
+ hardcoded_password_string: Possible hardcoded password: 'None'
+ Test ID: B105
+ Severity: LOW
+ Confidence: MEDIUM
+ CWE: CWE-259
+ File: ./venv/lib/python3.12/site-packages/flask/app.py
+ Line number: 183
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b105_hardcoded_password_string.html
+ +
+
+182	            "PROPAGATE_EXCEPTIONS": None,
+183	            "SECRET_KEY": None,
+184	            "SECRET_KEY_FALLBACKS": None,
+185	            "PERMANENT_SESSION_LIFETIME": timedelta(days=31),
+186	            "USE_X_SENDFILE": False,
+187	            "TRUSTED_HOSTS": None,
+188	            "SERVER_NAME": None,
+189	            "APPLICATION_ROOT": "/",
+190	            "SESSION_COOKIE_NAME": "session",
+191	            "SESSION_COOKIE_DOMAIN": None,
+192	            "SESSION_COOKIE_PATH": None,
+193	            "SESSION_COOKIE_HTTPONLY": True,
+194	            "SESSION_COOKIE_SECURE": False,
+195	            "SESSION_COOKIE_PARTITIONED": False,
+196	            "SESSION_COOKIE_SAMESITE": None,
+197	            "SESSION_REFRESH_EACH_REQUEST": True,
+198	            "MAX_CONTENT_LENGTH": None,
+199	            "MAX_FORM_MEMORY_SIZE": 500_000,
+200	            "MAX_FORM_PARTS": 1_000,
+201	            "SEND_FILE_MAX_AGE_DEFAULT": None,
+202	            "TRAP_BAD_REQUEST_ERRORS": None,
+203	            "TRAP_HTTP_EXCEPTIONS": False,
+204	            "EXPLAIN_TEMPLATE_LOADING": False,
+205	            "PREFERRED_URL_SCHEME": "http",
+206	            "TEMPLATES_AUTO_RELOAD": None,
+207	            "MAX_COOKIE_SIZE": 4093,
+208	            "PROVIDE_AUTOMATIC_OPTIONS": True,
+209	        }
+210	    )
+211	
+212	    #: The class that is used for request objects.  See :class:`~flask.Request`
+213	    #: for more information.
+214	    request_class: type[Request] = Request
+
+
+ + +
+
+ +
+
+ hardcoded_password_string: Possible hardcoded password: 'None'
+ Test ID: B105
+ Severity: LOW
+ Confidence: MEDIUM
+ CWE: CWE-259
+ File: ./venv/lib/python3.12/site-packages/flask/app.py
+ Line number: 184
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b105_hardcoded_password_string.html
+ +
+
+183	            "SECRET_KEY": None,
+184	            "SECRET_KEY_FALLBACKS": None,
+185	            "PERMANENT_SESSION_LIFETIME": timedelta(days=31),
+186	            "USE_X_SENDFILE": False,
+187	            "TRUSTED_HOSTS": None,
+188	            "SERVER_NAME": None,
+189	            "APPLICATION_ROOT": "/",
+190	            "SESSION_COOKIE_NAME": "session",
+191	            "SESSION_COOKIE_DOMAIN": None,
+192	            "SESSION_COOKIE_PATH": None,
+193	            "SESSION_COOKIE_HTTPONLY": True,
+194	            "SESSION_COOKIE_SECURE": False,
+195	            "SESSION_COOKIE_PARTITIONED": False,
+196	            "SESSION_COOKIE_SAMESITE": None,
+197	            "SESSION_REFRESH_EACH_REQUEST": True,
+198	            "MAX_CONTENT_LENGTH": None,
+199	            "MAX_FORM_MEMORY_SIZE": 500_000,
+200	            "MAX_FORM_PARTS": 1_000,
+201	            "SEND_FILE_MAX_AGE_DEFAULT": None,
+202	            "TRAP_BAD_REQUEST_ERRORS": None,
+203	            "TRAP_HTTP_EXCEPTIONS": False,
+204	            "EXPLAIN_TEMPLATE_LOADING": False,
+205	            "PREFERRED_URL_SCHEME": "http",
+206	            "TEMPLATES_AUTO_RELOAD": None,
+207	            "MAX_COOKIE_SIZE": 4093,
+208	            "PROVIDE_AUTOMATIC_OPTIONS": True,
+209	        }
+210	    )
+211	
+212	    #: The class that is used for request objects.  See :class:`~flask.Request`
+213	    #: for more information.
+214	    request_class: type[Request] = Request
+215	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/flask/app.py
+ Line number: 268
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+267	        if self.has_static_folder:
+268	            assert bool(static_host) == host_matching, (
+269	                "Invalid static_host/host_matching combination"
+270	            )
+271	            # Use a weakref to avoid creating a reference cycle between the app
+
+
+ + +
+
+ +
+
+ blacklist: Use of possibly insecure function - consider using safer ast.literal_eval.
+ Test ID: B307
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/flask/cli.py
+ Line number: 1031
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b307-eval
+ +
+
+1030	        with open(startup) as f:
+1031	            eval(compile(f.read(), startup, "exec"), ctx)
+1032	
+
+
+ + +
+
+ +
+
+ try_except_pass: Try, Except, Pass detected.
+ Test ID: B110
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/flask/config.py
+ Line number: 163
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b110_try_except_pass.html
+ +
+
+162	                value = loads(value)
+163	            except Exception:
+164	                # Keep the value as a string if loading failed.
+165	                pass
+166	
+
+
+ + +
+
+ +
+
+ exec_used: Use of exec detected.
+ Test ID: B102
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/flask/config.py
+ Line number: 209
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b102_exec_used.html
+ +
+
+208	            with open(filename, mode="rb") as config_file:
+209	                exec(compile(config_file.read(), filename, "exec"), d.__dict__)
+210	        except OSError as e:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/flask/ctx.py
+ Line number: 373
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+372	        """
+373	        assert self._session is not None, "The session has not yet been opened."
+374	        self._session.accessed = True
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/flask/debughelpers.py
+ Line number: 59
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+58	        exc = request.routing_exception
+59	        assert isinstance(exc, RequestRedirect)
+60	        buf = [
+
+
+ + +
+
+ +
+
+ markupsafe_markup_xss: Potential XSS with ``markupsafe.Markup`` detected. Do not use ``Markup`` on untrusted data.
+ Test ID: B704
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-79
+ File: ./venv/lib/python3.12/site-packages/flask/json/tag.py
+ Line number: 188
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b704_markupsafe_markup_xss.html
+ +
+
+187	    def to_python(self, value: t.Any) -> t.Any:
+188	        return Markup(value)
+189	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/flask/sansio/scaffold.py
+ Line number: 705
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+704	    """
+705	    assert view_func is not None, "expected view func if endpoint is not provided."
+706	    return view_func.__name__
+
+
+ + +
+
+ +
+
+ hashlib: Use of weak SHA1 hash for security. Consider usedforsecurity=False
+ Test ID: B324
+ Severity: HIGH
+ Confidence: HIGH
+ CWE: CWE-327
+ File: ./venv/lib/python3.12/site-packages/flask/sessions.py
+ Line number: 281
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b324_hashlib.html
+ +
+
+280	    """
+281	    return hashlib.sha1(string)
+282	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/flask/testing.py
+ Line number: 59
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+58	    ) -> None:
+59	        assert not (base_url or subdomain or url_scheme) or (
+60	            base_url is not None
+61	        ) != bool(subdomain or url_scheme), (
+62	            'Cannot pass "subdomain" or "url_scheme" with "base_url".'
+63	        )
+64	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/flask/views.py
+ Line number: 190
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+189	
+190	        assert meth is not None, f"Unimplemented method {request.method!r}"
+191	        return current_app.ensure_sync(meth)(**kwargs)  # type: ignore[no-any-return]
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/flask_mail/__init__.py
+ Line number: 164
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+163	        """
+164	        assert message.send_to, "No recipients have been added"
+165	        assert message.sender, (
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/flask_mail/__init__.py
+ Line number: 165
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+164	        assert message.send_to, "No recipients have been added"
+165	        assert message.sender, (
+166	            "The message does not specify a sender and a default sender "
+167	            "has not been configured"
+168	        )
+169	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/flask_sqlalchemy/model.py
+ Line number: 58
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+57	        state = sa.inspect(self)
+58	        assert state is not None
+59	
+
+
+ + +
+
+ +
+
+ hashlib: Use of weak SHA1 hash for security. Consider usedforsecurity=False
+ Test ID: B324
+ Severity: HIGH
+ Confidence: HIGH
+ CWE: CWE-327
+ File: ./venv/lib/python3.12/site-packages/flask_wtf/csrf.py
+ Line number: 53
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b324_hashlib.html
+ +
+
+52	        if field_name not in session:
+53	            session[field_name] = hashlib.sha1(os.urandom(64)).hexdigest()
+54	
+
+
+ + +
+
+ +
+
+ hashlib: Use of weak SHA1 hash for security. Consider usedforsecurity=False
+ Test ID: B324
+ Severity: HIGH
+ Confidence: HIGH
+ CWE: CWE-327
+ File: ./venv/lib/python3.12/site-packages/flask_wtf/csrf.py
+ Line number: 58
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b324_hashlib.html
+ +
+
+57	        except TypeError:
+58	            session[field_name] = hashlib.sha1(os.urandom(64)).hexdigest()
+59	            token = s.dumps(session[field_name])
+
+
+ + +
+
+ +
+
+ markupsafe_markup_xss: Potential XSS with ``markupsafe.Markup`` detected. Do not use ``Markup`` on untrusted data.
+ Test ID: B704
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-79
+ File: ./venv/lib/python3.12/site-packages/flask_wtf/form.py
+ Line number: 119
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b704_markupsafe_markup_xss.html
+ +
+
+118	
+119	        return Markup("\n".join(str(f) for f in hidden_fields(fields or self)))
+120	
+
+
+ + +
+
+ +
+
+ blacklist: Audit url open for permitted schemes. Allowing use of file:/ or custom schemes is often unexpected.
+ Test ID: B310
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-22
+ File: ./venv/lib/python3.12/site-packages/flask_wtf/recaptcha/validators.py
+ Line number: 61
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b310-urllib-urlopen
+ +
+
+60	
+61	        http_response = http.urlopen(verify_server, data.encode("utf-8"))
+62	
+
+
+ + +
+
+ +
+
+ markupsafe_markup_xss: Potential XSS with ``markupsafe.Markup`` detected. Do not use ``Markup`` on untrusted data.
+ Test ID: B704
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-79
+ File: ./venv/lib/python3.12/site-packages/flask_wtf/recaptcha/widgets.py
+ Line number: 20
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b704_markupsafe_markup_xss.html
+ +
+
+19	        if html:
+20	            return Markup(html)
+21	        params = current_app.config.get("RECAPTCHA_PARAMETERS")
+
+
+ + +
+
+ +
+
+ markupsafe_markup_xss: Potential XSS with ``markupsafe.Markup`` detected. Do not use ``Markup`` on untrusted data.
+ Test ID: B704
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-79
+ File: ./venv/lib/python3.12/site-packages/flask_wtf/recaptcha/widgets.py
+ Line number: 33
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b704_markupsafe_markup_xss.html
+ +
+
+32	            div_class = RECAPTCHA_DIV_CLASS_DEFAULT
+33	        return Markup(RECAPTCHA_TEMPLATE % (script, div_class, snippet))
+34	
+
+
+ + +
+
+ +
+
+ blacklist: Consider possible security implications associated with the subprocess module.
+ Test ID: B404
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/greenlet/tests/__init__.py
+ Line number: 217
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_imports.html#b404-import-subprocess
+ +
+
+216	    def run_script(self, script_name, show_output=True):
+217	        import subprocess
+218	        script = os.path.join(
+
+
+ + +
+
+ +
+
+ subprocess_without_shell_equals_true: subprocess call - check for execution of untrusted input.
+ Test ID: B603
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/greenlet/tests/__init__.py
+ Line number: 224
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b603_subprocess_without_shell_equals_true.html
+ +
+
+223	        try:
+224	            return subprocess.check_output([sys.executable, script],
+225	                                           encoding='utf-8',
+226	                                           stderr=subprocess.STDOUT)
+227	        except subprocess.CalledProcessError as ex:
+
+
+ + +
+
+ +
+
+ blacklist: Consider possible security implications associated with the subprocess module.
+ Test ID: B404
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/greenlet/tests/__init__.py
+ Line number: 238
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_imports.html#b404-import-subprocess
+ +
+
+237	    def assertScriptRaises(self, script_name, exitcodes=None):
+238	        import subprocess
+239	        with self.assertRaises(subprocess.CalledProcessError) as exc:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/greenlet/tests/fail_initialstub_already_started.py
+ Line number: 34
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+33	        if name == 'run' and not self.doing_it:
+34	            assert greenlet.getcurrent() is c
+35	            self.doing_it = True
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/greenlet/tests/fail_initialstub_already_started.py
+ Line number: 69
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+68	# A and B should both be dead now.
+69	assert a.dead
+70	assert b.dead
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/greenlet/tests/fail_initialstub_already_started.py
+ Line number: 70
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+69	assert a.dead
+70	assert b.dead
+71	assert not c.dead
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/greenlet/tests/fail_initialstub_already_started.py
+ Line number: 71
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+70	assert b.dead
+71	assert not c.dead
+72	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/greenlet/tests/fail_initialstub_already_started.py
+ Line number: 76
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+75	# Now C is dead
+76	assert c.dead
+77	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/greenlet/tests/fail_slp_switch.py
+ Line number: 23
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+22	g.switch()
+23	assert runs == [1]
+24	g.switch()
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/greenlet/tests/fail_slp_switch.py
+ Line number: 25
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+24	g.switch()
+25	assert runs == [1, 2]
+26	g.force_slp_switch_error = True
+
+
+ + +
+
+ +
+
+ blacklist: Consider possible security implications associated with the subprocess module.
+ Test ID: B404
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/greenlet/tests/test_cpp.py
+ Line number: 2
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_imports.html#b404-import-subprocess
+ +
+
+1	import gc
+2	import subprocess
+3	import unittest
+
+
+ + +
+
+ +
+
+ subprocess_without_shell_equals_true: subprocess call - check for execution of untrusted input.
+ Test ID: B603
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/greenlet/tests/test_cpp.py
+ Line number: 33
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b603_subprocess_without_shell_equals_true.html
+ +
+
+32	        with self.assertRaises(subprocess.CalledProcessError) as exc:
+33	            subprocess.check_output(
+34	                args,
+35	                encoding='utf-8',
+36	                stderr=subprocess.STDOUT
+37	            )
+38	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/greenlet/tests/test_gc.py
+ Line number: 12
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+11	# which is no longer optional.
+12	assert greenlet.GREENLET_USE_GC
+13	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/greenlet/tests/test_generator_nested.py
+ Line number: 106
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+105	            x = [Yield([e] + p) for p in perms([x for x in l if x != e])]
+106	            assert x
+107	    else:
+
+
+ + +
+
+ +
+
+ try_except_pass: Try, Except, Pass detected.
+ Test ID: B110
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/greenlet/tests/test_greenlet.py
+ Line number: 503
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b110_try_except_pass.html
+ +
+
+502	                    raise Exception # pylint:disable=broad-exception-raised
+503	                except: # pylint:disable=bare-except
+504	                    pass
+505	                return RawGreenlet.__getattribute__(self, name)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/greenlet/tests/test_greenlet.py
+ Line number: 1289
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1288	        # implementation detail
+1289	        assert 'main' in repr(greenlet.getcurrent())
+1290	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/greenlet/tests/test_greenlet.py
+ Line number: 1292
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1291	        t = type(greenlet.getcurrent())
+1292	        assert 'main' not in repr(t)
+1293	        return t
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/greenlet/tests/test_greenlet_trash.py
+ Line number: 48
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+47	            # what we want it to.
+48	            assert sys.version_info[:2] >= (3, 13)
+49	            def get_tstate_trash_delete_nesting():
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/greenlet/tests/test_greenlet_trash.py
+ Line number: 62
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+61	
+62	        assert get_tstate_trash_delete_nesting() == 0
+63	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/greenlet/tests/test_greenlet_trash.py
+ Line number: 118
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+117	                    x = other.switch()
+118	                    assert x == 42
+119	                    # It's important that we don't switch back to the greenlet,
+
+
+ + +
+
+ +
+
+ blacklist: Consider possible security implications associated with the subprocess module.
+ Test ID: B404
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/greenlet/tests/test_interpreter_shutdown.py
+ Line number: 32
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_imports.html#b404-import-subprocess
+ +
+
+31	import sys
+32	import subprocess
+33	import unittest
+
+
+ + +
+
+ +
+
+ subprocess_without_shell_equals_true: subprocess call - check for execution of untrusted input.
+ Test ID: B603
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/greenlet/tests/test_interpreter_shutdown.py
+ Line number: 47
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b603_subprocess_without_shell_equals_true.html
+ +
+
+46	        full_script = textwrap.dedent(script_body)
+47	        result = subprocess.run(
+48	            [sys.executable, '-c', full_script],
+49	            capture_output=True,
+50	            text=True,
+51	            timeout=30,
+52	            check=False,
+53	        )
+54	        return result.returncode, result.stdout, result.stderr
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/greenlet/tests/test_leaks.py
+ Line number: 25
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+24	
+25	assert greenlet.GREENLET_USE_GC # Option to disable this was removed in 1.0
+26	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/greenlet/tests/test_leaks.py
+ Line number: 153
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+152	
+153	        assert gc.is_tracked([])
+154	        HasFinalizerTracksInstances.reset()
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/greenlet/tests/test_leaks.py
+ Line number: 212
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+211	
+212	        assert len(background_greenlets) == 1
+213	        self.assertFalse(background_greenlets[0].dead)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/greenlet/tests/test_leaks.py
+ Line number: 322
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+321	        # resolved, so we are actually running this on 3.8+
+322	        assert sys.version_info[0] >= 3
+323	        if RUNNING_ON_MANYLINUX:
+
+
+ + +
+
+ +
+
+ start_process_with_a_shell: Starting a process with a shell, possible injection detected, security issue.
+ Test ID: B605
+ Severity: HIGH
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/greenlet/tests/test_version.py
+ Line number: 36
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b605_start_process_with_a_shell.html
+ +
+
+35	        invoke_setup = "%s %s --version" % (sys.executable, setup_py)
+36	        with os.popen(invoke_setup) as f:
+37	            sversion = f.read().strip()
+
+
+ + +
+
+ +
+
+ try_except_pass: Try, Except, Pass detected.
+ Test ID: B110
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/itsdangerous/timed.py
+ Line number: 120
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b110_try_except_pass.html
+ +
+
+119	            ts_int = bytes_to_int(base64_decode(ts_bytes))
+120	        except Exception:
+121	            pass
+122	
+
+
+ + +
+
+ +
+
+ blacklist: Consider possible security implications associated with pickle module.
+ Test ID: B403
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-502
+ File: ./venv/lib/python3.12/site-packages/jinja2/bccache.py
+ Line number: 13
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_imports.html#b403-import-pickle
+ +
+
+12	import os
+13	import pickle
+14	import stat
+
+
+ + +
+
+ +
+
+ blacklist: Pickle and modules that wrap it can be unsafe when used to deserialize untrusted data, possible security issue.
+ Test ID: B301
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-502
+ File: ./venv/lib/python3.12/site-packages/jinja2/bccache.py
+ Line number: 73
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b301-pickle
+ +
+
+72	        # the source code of the file changed, we need to reload
+73	        checksum = pickle.load(f)
+74	        if self.checksum != checksum:
+
+
+ + +
+
+ +
+
+ blacklist: Deserialization with the marshal module is possibly dangerous.
+ Test ID: B302
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-502
+ File: ./venv/lib/python3.12/site-packages/jinja2/bccache.py
+ Line number: 79
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b302-marshal
+ +
+
+78	        try:
+79	            self.code = marshal.load(f)
+80	        except (EOFError, ValueError, TypeError):
+
+
+ + +
+
+ +
+
+ hashlib: Use of weak SHA1 hash for security. Consider usedforsecurity=False
+ Test ID: B324
+ Severity: HIGH
+ Confidence: HIGH
+ CWE: CWE-327
+ File: ./venv/lib/python3.12/site-packages/jinja2/bccache.py
+ Line number: 156
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b324_hashlib.html
+ +
+
+155	        """Returns the unique hash key for this template name."""
+156	        hash = sha1(name.encode("utf-8"))
+157	
+
+
+ + +
+
+ +
+
+ hashlib: Use of weak SHA1 hash for security. Consider usedforsecurity=False
+ Test ID: B324
+ Severity: HIGH
+ Confidence: HIGH
+ CWE: CWE-327
+ File: ./venv/lib/python3.12/site-packages/jinja2/bccache.py
+ Line number: 165
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b324_hashlib.html
+ +
+
+164	        """Returns a checksum for the source."""
+165	        return sha1(source.encode("utf-8")).hexdigest()
+166	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/jinja2/compiler.py
+ Line number: 832
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+831	    ) -> None:
+832	        assert frame is None, "no root frame allowed"
+833	        eval_ctx = EvalContext(self.environment, self.name)
+
+
+ + +
+
+ +
+
+ hardcoded_password_string: Possible hardcoded password: 'environment'
+ Test ID: B105
+ Severity: LOW
+ Confidence: MEDIUM
+ CWE: CWE-259
+ File: ./venv/lib/python3.12/site-packages/jinja2/compiler.py
+ Line number: 1440
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b105_hardcoded_password_string.html
+ +
+
+1439	
+1440	                if pass_arg == "environment":
+1441	
+
+
+ + +
+
+ +
+
+ exec_used: Use of exec detected.
+ Test ID: B102
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/jinja2/debug.py
+ Line number: 145
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b102_exec_used.html
+ +
+
+144	    try:
+145	        exec(code, globals, locals)
+146	    except BaseException:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/jinja2/environment.py
+ Line number: 128
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+127	    """Perform a sanity check on the environment."""
+128	    assert issubclass(
+129	        environment.undefined, Undefined
+130	    ), "'undefined' must be a subclass of 'jinja2.Undefined'."
+131	    assert (
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/jinja2/environment.py
+ Line number: 131
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+130	    ), "'undefined' must be a subclass of 'jinja2.Undefined'."
+131	    assert (
+132	        environment.block_start_string
+133	        != environment.variable_start_string
+134	        != environment.comment_start_string
+135	    ), "block, variable and comment start strings must be different."
+136	    assert environment.newline_sequence in {
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/jinja2/environment.py
+ Line number: 136
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+135	    ), "block, variable and comment start strings must be different."
+136	    assert environment.newline_sequence in {
+137	        "\r",
+138	        "\r\n",
+139	        "\n",
+140	    }, "'newline_sequence' must be one of '\\n', '\\r\\n', or '\\r'."
+141	    return environment
+
+
+ + +
+
+ +
+
+ try_except_pass: Try, Except, Pass detected.
+ Test ID: B110
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/jinja2/environment.py
+ Line number: 476
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b110_try_except_pass.html
+ +
+
+475	                    attr = str(argument)
+476	                except Exception:
+477	                    pass
+478	                else:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/jinja2/environment.py
+ Line number: 851
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+850	
+851	        assert log_function is not None
+852	        assert self.loader is not None, "No loader configured."
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/jinja2/environment.py
+ Line number: 852
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+851	        assert log_function is not None
+852	        assert self.loader is not None, "No loader configured."
+853	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/jinja2/environment.py
+ Line number: 919
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+918	        """
+919	        assert self.loader is not None, "No loader configured."
+920	        names = self.loader.list_templates()
+
+
+ + +
+
+ +
+
+ exec_used: Use of exec detected.
+ Test ID: B102
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/jinja2/environment.py
+ Line number: 1228
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b102_exec_used.html
+ +
+
+1227	        namespace = {"environment": environment, "__file__": code.co_filename}
+1228	        exec(code, namespace)
+1229	        rv = cls._from_namespace(environment, namespace, globals)
+
+
+ + +
+
+ +
+
+ markupsafe_markup_xss: Potential XSS with ``markupsafe.Markup`` detected. Do not use ``Markup`` on untrusted data.
+ Test ID: B704
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-79
+ File: ./venv/lib/python3.12/site-packages/jinja2/environment.py
+ Line number: 1544
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b704_markupsafe_markup_xss.html
+ +
+
+1543	    def __html__(self) -> Markup:
+1544	        return Markup(concat(self._body_stream))
+1545	
+
+
+ + +
+
+ +
+
+ markupsafe_markup_xss: Potential XSS with ``markupsafe.Markup`` detected. Do not use ``Markup`` on untrusted data.
+ Test ID: B704
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-79
+ File: ./venv/lib/python3.12/site-packages/jinja2/ext.py
+ Line number: 176
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b704_markupsafe_markup_xss.html
+ +
+
+175	        if __context.eval_ctx.autoescape:
+176	            rv = Markup(rv)
+177	        # Always treat as a format string, even if there are no
+
+
+ + +
+
+ +
+
+ markupsafe_markup_xss: Potential XSS with ``markupsafe.Markup`` detected. Do not use ``Markup`` on untrusted data.
+ Test ID: B704
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-79
+ File: ./venv/lib/python3.12/site-packages/jinja2/ext.py
+ Line number: 197
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b704_markupsafe_markup_xss.html
+ +
+
+196	        if __context.eval_ctx.autoescape:
+197	            rv = Markup(rv)
+198	        # Always treat as a format string, see gettext comment above.
+
+
+ + +
+
+ +
+
+ markupsafe_markup_xss: Potential XSS with ``markupsafe.Markup`` detected. Do not use ``Markup`` on untrusted data.
+ Test ID: B704
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-79
+ File: ./venv/lib/python3.12/site-packages/jinja2/ext.py
+ Line number: 213
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b704_markupsafe_markup_xss.html
+ +
+
+212	        if __context.eval_ctx.autoescape:
+213	            rv = Markup(rv)
+214	
+
+
+ + +
+
+ +
+
+ markupsafe_markup_xss: Potential XSS with ``markupsafe.Markup`` detected. Do not use ``Markup`` on untrusted data.
+ Test ID: B704
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-79
+ File: ./venv/lib/python3.12/site-packages/jinja2/ext.py
+ Line number: 238
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b704_markupsafe_markup_xss.html
+ +
+
+237	        if __context.eval_ctx.autoescape:
+238	            rv = Markup(rv)
+239	
+
+
+ + +
+
+ +
+
+ markupsafe_markup_xss: Potential XSS with ``markupsafe.Markup`` detected. Do not use ``Markup`` on untrusted data.
+ Test ID: B704
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-79
+ File: ./venv/lib/python3.12/site-packages/jinja2/filters.py
+ Line number: 316
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b704_markupsafe_markup_xss.html
+ +
+
+315	    if eval_ctx.autoescape:
+316	        rv = Markup(rv)
+317	
+
+
+ + +
+
+ +
+
+ blacklist: Standard pseudo-random generators are not suitable for security/cryptographic purposes.
+ Test ID: B311
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-330
+ File: ./venv/lib/python3.12/site-packages/jinja2/filters.py
+ Line number: 699
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b311-random
+ +
+
+698	    try:
+699	        return random.choice(seq)
+700	    except IndexError:
+
+
+ + +
+
+ +
+
+ markupsafe_markup_xss: Potential XSS with ``markupsafe.Markup`` detected. Do not use ``Markup`` on untrusted data.
+ Test ID: B704
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-79
+ File: ./venv/lib/python3.12/site-packages/jinja2/filters.py
+ Line number: 820
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b704_markupsafe_markup_xss.html
+ +
+
+819	    if eval_ctx.autoescape:
+820	        rv = Markup(rv)
+821	
+
+
+ + +
+
+ +
+
+ markupsafe_markup_xss: Potential XSS with ``markupsafe.Markup`` detected. Do not use ``Markup`` on untrusted data.
+ Test ID: B704
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-79
+ File: ./venv/lib/python3.12/site-packages/jinja2/filters.py
+ Line number: 851
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b704_markupsafe_markup_xss.html
+ +
+
+850	    if isinstance(s, Markup):
+851	        indention = Markup(indention)
+852	        newline = Markup(newline)
+
+
+ + +
+
+ +
+
+ markupsafe_markup_xss: Potential XSS with ``markupsafe.Markup`` detected. Do not use ``Markup`` on untrusted data.
+ Test ID: B704
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-79
+ File: ./venv/lib/python3.12/site-packages/jinja2/filters.py
+ Line number: 852
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b704_markupsafe_markup_xss.html
+ +
+
+851	        indention = Markup(indention)
+852	        newline = Markup(newline)
+853	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/jinja2/filters.py
+ Line number: 908
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+907	
+908	    assert length >= len(end), f"expected length >= {len(end)}, got {length}"
+909	    assert leeway >= 0, f"expected leeway >= 0, got {leeway}"
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/jinja2/filters.py
+ Line number: 909
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+908	    assert length >= len(end), f"expected length >= {len(end)}, got {length}"
+909	    assert leeway >= 0, f"expected leeway >= 0, got {leeway}"
+910	
+
+
+ + +
+
+ +
+
+ markupsafe_markup_xss: Potential XSS with ``markupsafe.Markup`` detected. Do not use ``Markup`` on untrusted data.
+ Test ID: B704
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-79
+ File: ./venv/lib/python3.12/site-packages/jinja2/filters.py
+ Line number: 1056
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b704_markupsafe_markup_xss.html
+ +
+
+1055	
+1056	    return Markup(str(value)).striptags()
+1057	
+
+
+ + +
+
+ +
+
+ markupsafe_markup_xss: Potential XSS with ``markupsafe.Markup`` detected. Do not use ``Markup`` on untrusted data.
+ Test ID: B704
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-79
+ File: ./venv/lib/python3.12/site-packages/jinja2/filters.py
+ Line number: 1377
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b704_markupsafe_markup_xss.html
+ +
+
+1376	    """
+1377	    return Markup(value)
+1378	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/jinja2/idtracking.py
+ Line number: 138
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+137	            target = self.find_ref(name)
+138	            assert target is not None, "should not happen"
+139	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/jinja2/lexer.py
+ Line number: 144
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+143	reverse_operators = {v: k for k, v in operators.items()}
+144	assert len(operators) == len(reverse_operators), "operators dropped"
+145	operator_re = re.compile(
+
+
+ + +
+
+ +
+
+ hardcoded_password_string: Possible hardcoded password: 'keyword'
+ Test ID: B105
+ Severity: LOW
+ Confidence: MEDIUM
+ CWE: CWE-259
+ File: ./venv/lib/python3.12/site-packages/jinja2/lexer.py
+ Line number: 639
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b105_hardcoded_password_string.html
+ +
+
+638	                value = self._normalize_newlines(value_str)
+639	            elif token == "keyword":
+640	                token = value_str
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/jinja2/lexer.py
+ Line number: 694
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+693	        if state is not None and state != "root":
+694	            assert state in ("variable", "block"), "invalid state"
+695	            stack.append(state + "_begin")
+
+
+ + +
+
+ +
+
+ hardcoded_password_string: Possible hardcoded password: '#bygroup'
+ Test ID: B105
+ Severity: LOW
+ Confidence: MEDIUM
+ CWE: CWE-259
+ File: ./venv/lib/python3.12/site-packages/jinja2/lexer.py
+ Line number: 765
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b105_hardcoded_password_string.html
+ +
+
+764	                        # group that matched
+765	                        elif token == "#bygroup":
+766	                            for key, value in m.groupdict().items():
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/jinja2/loaders.py
+ Line number: 325
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+324	        spec = importlib.util.find_spec(package_name)
+325	        assert spec is not None, "An import spec was not found for the package."
+326	        loader = spec.loader
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/jinja2/loaders.py
+ Line number: 327
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+326	        loader = spec.loader
+327	        assert loader is not None, "A loader was not found for the package."
+328	        self._loader = loader
+
+
+ + +
+
+ +
+
+ hashlib: Use of weak SHA1 hash for security. Consider usedforsecurity=False
+ Test ID: B324
+ Severity: HIGH
+ Confidence: HIGH
+ CWE: CWE-327
+ File: ./venv/lib/python3.12/site-packages/jinja2/loaders.py
+ Line number: 661
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b324_hashlib.html
+ +
+
+660	    def get_template_key(name: str) -> str:
+661	        return "tmpl_" + sha1(name.encode("utf-8")).hexdigest()
+662	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/jinja2/nodes.py
+ Line number: 64
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+63	            storage.extend(d.get(attr, ()))
+64	            assert len(bases) <= 1, "multiple inheritance not allowed"
+65	            assert len(storage) == len(set(storage)), "layout conflict"
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/jinja2/nodes.py
+ Line number: 65
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+64	            assert len(bases) <= 1, "multiple inheritance not allowed"
+65	            assert len(storage) == len(set(storage)), "layout conflict"
+66	            d[attr] = tuple(storage)
+
+
+ + +
+
+ +
+
+ markupsafe_markup_xss: Potential XSS with ``markupsafe.Markup`` detected. Do not use ``Markup`` on untrusted data.
+ Test ID: B704
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-79
+ File: ./venv/lib/python3.12/site-packages/jinja2/nodes.py
+ Line number: 619
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b704_markupsafe_markup_xss.html
+ +
+
+618	        if eval_ctx.autoescape:
+619	            return Markup(self.data)
+620	        return self.data
+
+
+ + +
+
+ +
+
+ markupsafe_markup_xss: Potential XSS with ``markupsafe.Markup`` detected. Do not use ``Markup`` on untrusted data.
+ Test ID: B704
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-79
+ File: ./venv/lib/python3.12/site-packages/jinja2/nodes.py
+ Line number: 1091
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b704_markupsafe_markup_xss.html
+ +
+
+1090	        eval_ctx = get_eval_context(self, eval_ctx)
+1091	        return Markup(self.expr.as_const(eval_ctx))
+1092	
+
+
+ + +
+
+ +
+
+ markupsafe_markup_xss: Potential XSS with ``markupsafe.Markup`` detected. Do not use ``Markup`` on untrusted data.
+ Test ID: B704
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-79
+ File: ./venv/lib/python3.12/site-packages/jinja2/nodes.py
+ Line number: 1112
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b704_markupsafe_markup_xss.html
+ +
+
+1111	        if eval_ctx.autoescape:
+1112	            return Markup(expr)
+1113	        return expr
+
+
+ + +
+
+ +
+
+ hardcoded_password_string: Possible hardcoded password: 'sub'
+ Test ID: B105
+ Severity: LOW
+ Confidence: MEDIUM
+ CWE: CWE-259
+ File: ./venv/lib/python3.12/site-packages/jinja2/parser.py
+ Line number: 630
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b105_hardcoded_password_string.html
+ +
+
+629	
+630	        if token_type == "sub":
+631	            next(self.stream)
+
+
+ + +
+
+ +
+
+ hardcoded_password_string: Possible hardcoded password: 'add'
+ Test ID: B105
+ Severity: LOW
+ Confidence: MEDIUM
+ CWE: CWE-259
+ File: ./venv/lib/python3.12/site-packages/jinja2/parser.py
+ Line number: 633
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b105_hardcoded_password_string.html
+ +
+
+632	            node = nodes.Neg(self.parse_unary(False), lineno=lineno)
+633	        elif token_type == "add":
+634	            next(self.stream)
+
+
+ + +
+
+ +
+
+ hardcoded_password_string: Possible hardcoded password: 'dot'
+ Test ID: B105
+ Severity: LOW
+ Confidence: MEDIUM
+ CWE: CWE-259
+ File: ./venv/lib/python3.12/site-packages/jinja2/parser.py
+ Line number: 784
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b105_hardcoded_password_string.html
+ +
+
+783	            token_type = self.stream.current.type
+784	            if token_type == "dot" or token_type == "lbracket":
+785	                node = self.parse_subscript(node)
+
+
+ + +
+
+ +
+
+ hardcoded_password_string: Possible hardcoded password: 'lbracket'
+ Test ID: B105
+ Severity: LOW
+ Confidence: MEDIUM
+ CWE: CWE-259
+ File: ./venv/lib/python3.12/site-packages/jinja2/parser.py
+ Line number: 784
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b105_hardcoded_password_string.html
+ +
+
+783	            token_type = self.stream.current.type
+784	            if token_type == "dot" or token_type == "lbracket":
+785	                node = self.parse_subscript(node)
+
+
+ + +
+
+ +
+
+ hardcoded_password_string: Possible hardcoded password: 'lparen'
+ Test ID: B105
+ Severity: LOW
+ Confidence: MEDIUM
+ CWE: CWE-259
+ File: ./venv/lib/python3.12/site-packages/jinja2/parser.py
+ Line number: 788
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b105_hardcoded_password_string.html
+ +
+
+787	            # and getitem) as well as filters and tests
+788	            elif token_type == "lparen":
+789	                node = self.parse_call(node)
+
+
+ + +
+
+ +
+
+ hardcoded_password_string: Possible hardcoded password: 'pipe'
+ Test ID: B105
+ Severity: LOW
+ Confidence: MEDIUM
+ CWE: CWE-259
+ File: ./venv/lib/python3.12/site-packages/jinja2/parser.py
+ Line number: 797
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b105_hardcoded_password_string.html
+ +
+
+796	            token_type = self.stream.current.type
+797	            if token_type == "pipe":
+798	                node = self.parse_filter(node)  # type: ignore
+
+
+ + +
+
+ +
+
+ hardcoded_password_string: Possible hardcoded password: 'name'
+ Test ID: B105
+ Severity: LOW
+ Confidence: MEDIUM
+ CWE: CWE-259
+ File: ./venv/lib/python3.12/site-packages/jinja2/parser.py
+ Line number: 799
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b105_hardcoded_password_string.html
+ +
+
+798	                node = self.parse_filter(node)  # type: ignore
+799	            elif token_type == "name" and self.stream.current.value == "is":
+800	                node = self.parse_test(node)
+
+
+ + +
+
+ +
+
+ hardcoded_password_string: Possible hardcoded password: 'lparen'
+ Test ID: B105
+ Severity: LOW
+ Confidence: MEDIUM
+ CWE: CWE-259
+ File: ./venv/lib/python3.12/site-packages/jinja2/parser.py
+ Line number: 803
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b105_hardcoded_password_string.html
+ +
+
+802	            # and getitem) as well as filters and tests
+803	            elif token_type == "lparen":
+804	                node = self.parse_call(node)
+
+
+ + +
+
+ +
+
+ markupsafe_markup_xss: Potential XSS with ``markupsafe.Markup`` detected. Do not use ``Markup`` on untrusted data.
+ Test ID: B704
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-79
+ File: ./venv/lib/python3.12/site-packages/jinja2/runtime.py
+ Line number: 375
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b704_markupsafe_markup_xss.html
+ +
+
+374	        if self._context.eval_ctx.autoescape:
+375	            return Markup(rv)
+376	
+
+
+ + +
+
+ +
+
+ markupsafe_markup_xss: Potential XSS with ``markupsafe.Markup`` detected. Do not use ``Markup`` on untrusted data.
+ Test ID: B704
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-79
+ File: ./venv/lib/python3.12/site-packages/jinja2/runtime.py
+ Line number: 389
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b704_markupsafe_markup_xss.html
+ +
+
+388	        if self._context.eval_ctx.autoescape:
+389	            return Markup(rv)
+390	
+
+
+ + +
+
+ +
+
+ markupsafe_markup_xss: Potential XSS with ``markupsafe.Markup`` detected. Do not use ``Markup`` on untrusted data.
+ Test ID: B704
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-79
+ File: ./venv/lib/python3.12/site-packages/jinja2/runtime.py
+ Line number: 776
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b704_markupsafe_markup_xss.html
+ +
+
+775	        if autoescape:
+776	            return Markup(rv)
+777	
+
+
+ + +
+
+ +
+
+ markupsafe_markup_xss: Potential XSS with ``markupsafe.Markup`` detected. Do not use ``Markup`` on untrusted data.
+ Test ID: B704
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-79
+ File: ./venv/lib/python3.12/site-packages/jinja2/runtime.py
+ Line number: 787
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b704_markupsafe_markup_xss.html
+ +
+
+786	        if autoescape:
+787	            rv = Markup(rv)
+788	
+
+
+ + +
+
+ +
+
+ try_except_pass: Try, Except, Pass detected.
+ Test ID: B110
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/jinja2/sandbox.py
+ Line number: 298
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b110_try_except_pass.html
+ +
+
+297	                    attr = str(argument)
+298	                except Exception:
+299	                    pass
+300	                else:
+
+
+ + +
+
+ +
+
+ blacklist: Standard pseudo-random generators are not suitable for security/cryptographic purposes.
+ Test ID: B311
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-330
+ File: ./venv/lib/python3.12/site-packages/jinja2/utils.py
+ Line number: 370
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b311-random
+ +
+
+369	        # each paragraph contains out of 20 to 100 words.
+370	        for idx, _ in enumerate(range(randrange(min, max))):
+371	            while True:
+
+
+ + +
+
+ +
+
+ blacklist: Standard pseudo-random generators are not suitable for security/cryptographic purposes.
+ Test ID: B311
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-330
+ File: ./venv/lib/python3.12/site-packages/jinja2/utils.py
+ Line number: 372
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b311-random
+ +
+
+371	            while True:
+372	                word = choice(words)
+373	                if word != last:
+
+
+ + +
+
+ +
+
+ blacklist: Standard pseudo-random generators are not suitable for security/cryptographic purposes.
+ Test ID: B311
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-330
+ File: ./venv/lib/python3.12/site-packages/jinja2/utils.py
+ Line number: 380
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b311-random
+ +
+
+379	            # add commas
+380	            if idx - randrange(3, 8) > last_comma:
+381	                last_comma = idx
+
+
+ + +
+
+ +
+
+ blacklist: Standard pseudo-random generators are not suitable for security/cryptographic purposes.
+ Test ID: B311
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-330
+ File: ./venv/lib/python3.12/site-packages/jinja2/utils.py
+ Line number: 385
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b311-random
+ +
+
+384	            # add end of sentences
+385	            if idx - randrange(10, 20) > last_fullstop:
+386	                last_comma = last_fullstop = idx
+
+
+ + +
+
+ +
+
+ markupsafe_markup_xss: Potential XSS with ``markupsafe.Markup`` detected. Do not use ``Markup`` on untrusted data.
+ Test ID: B704
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-79
+ File: ./venv/lib/python3.12/site-packages/jinja2/utils.py
+ Line number: 403
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b704_markupsafe_markup_xss.html
+ +
+
+402	        return "\n\n".join(result)
+403	    return markupsafe.Markup(
+404	        "\n".join(f"<p>{markupsafe.escape(x)}</p>" for x in result)
+405	    )
+406	
+
+
+ + +
+
+ +
+
+ markupsafe_markup_xss: Potential XSS with ``markupsafe.Markup`` detected. Do not use ``Markup`` on untrusted data.
+ Test ID: B704
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-79
+ File: ./venv/lib/python3.12/site-packages/jinja2/utils.py
+ Line number: 668
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b704_markupsafe_markup_xss.html
+ +
+
+667	
+668	    return markupsafe.Markup(
+669	        dumps(obj, **kwargs)
+670	        .replace("<", "\\u003c")
+671	        .replace(">", "\\u003e")
+672	        .replace("&", "\\u0026")
+673	        .replace("'", "\\u0027")
+674	    )
+675	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/markdown_it/ruler.py
+ Line number: 265
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+264	            self.__compile__()
+265	            assert self.__cache__ is not None
+266	        # Chain can be empty, if rules disabled. But we still have to return Array.
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/markdown_it/rules_core/linkify.py
+ Line number: 35
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+34	        # Use reversed logic in links start/end match
+35	        assert tokens is not None
+36	        i = len(tokens)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/markdown_it/rules_core/linkify.py
+ Line number: 39
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+38	            i -= 1
+39	            assert isinstance(tokens, list)
+40	            currentToken = tokens[i]
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/markdown_it/rules_core/smartquotes.py
+ Line number: 20
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+19	    # But basically, the index will not be negative.
+20	    assert index >= 0
+21	    return string[:index] + ch + string[index + 1 :]
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/markdown_it/tree.py
+ Line number: 100
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+99	            else:
+100	                assert node.nester_tokens
+101	                token_list.append(node.nester_tokens.opening)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/markdown_it/tree.py
+ Line number: 164
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+163	            return self.token.type
+164	        assert self.nester_tokens
+165	        return self.nester_tokens.opening.type.removesuffix("_open")
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/__pip-runner__.py
+ Line number: 43
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+42	        spec = PathFinder.find_spec(fullname, [PIP_SOURCES_ROOT], target)
+43	        assert spec, (PIP_SOURCES_ROOT, fullname)
+44	        return spec
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/__pip-runner__.py
+ Line number: 49
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+48	
+49	assert __name__ == "__main__", "Cannot run __pip-runner__.py as a non-main module"
+50	runpy.run_module("pip", run_name="__main__", alter_sys=True)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/build_env.py
+ Line number: 213
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+212	        prefix = self._prefixes[prefix_as_string]
+213	        assert not prefix.setup
+214	        prefix.setup = True
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/cache.py
+ Line number: 40
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+39	        super().__init__()
+40	        assert not cache_dir or os.path.isabs(cache_dir)
+41	        self.cache_dir = cache_dir or None
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/cache.py
+ Line number: 124
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+123	        parts = self._get_cache_path_parts(link)
+124	        assert self.cache_dir
+125	        # Store wheels within the root cache_dir
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/cli/base_command.py
+ Line number: 89
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+88	        # are present.
+89	        assert not hasattr(options, "no_index")
+90	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/cli/base_command.py
+ Line number: 181
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+180	                    status = run_func(*args)
+181	                    assert isinstance(status, int)
+182	                    return status
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/cli/command_context.py
+ Line number: 15
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+14	    def main_context(self) -> Generator[None, None, None]:
+15	        assert not self._in_main_context
+16	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/cli/command_context.py
+ Line number: 25
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+24	    def enter_context(self, context_provider: ContextManager[_T]) -> _T:
+25	        assert self._in_main_context
+26	
+
+
+ + +
+
+ +
+
+ blacklist: Consider possible security implications associated with the subprocess module.
+ Test ID: B404
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/cli/main_parser.py
+ Line number: 5
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_imports.html#b404-import-subprocess
+ +
+
+4	import os
+5	import subprocess
+6	import sys
+
+
+ + +
+
+ +
+
+ subprocess_without_shell_equals_true: subprocess call - check for execution of untrusted input.
+ Test ID: B603
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/cli/main_parser.py
+ Line number: 101
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b603_subprocess_without_shell_equals_true.html
+ +
+
+100	        try:
+101	            proc = subprocess.run(pip_cmd)
+102	            returncode = proc.returncode
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/cli/parser.py
+ Line number: 51
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+50	        if option.takes_value():
+51	            assert option.dest is not None
+52	            metavar = option.metavar or option.dest.lower()
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/cli/parser.py
+ Line number: 112
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+111	        if self.parser is not None:
+112	            assert isinstance(self.parser, ConfigOptionParser)
+113	            self.parser._update_defaults(self.parser.defaults)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/cli/parser.py
+ Line number: 114
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+113	            self.parser._update_defaults(self.parser.defaults)
+114	            assert option.dest is not None
+115	            default_values = self.parser.defaults.get(option.dest)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/cli/parser.py
+ Line number: 168
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+167	
+168	        assert self.name
+169	        super().__init__(*args, **kwargs)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/cli/parser.py
+ Line number: 225
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+224	
+225	            assert option.dest is not None
+226	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/cli/parser.py
+ Line number: 252
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+251	            elif option.action == "callback":
+252	                assert option.callback is not None
+253	                late_eval.add(option.dest)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/cli/parser.py
+ Line number: 285
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+284	        for option in self._get_all_options():
+285	            assert option.dest is not None
+286	            default = defaults.get(option.dest)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/cli/progress_bars.py
+ Line number: 28
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+27	) -> Generator[bytes, None, None]:
+28	    assert bar_type == "on", "This should only be used in the default mode."
+29	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/cli/req_command.py
+ Line number: 99
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+98	            # then https://github.com/python/mypy/issues/7696 kicks in
+99	            assert self._session is not None
+100	        return self._session
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/cli/req_command.py
+ Line number: 110
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+109	        cache_dir = options.cache_dir
+110	        assert not cache_dir or os.path.isabs(cache_dir)
+111	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/cli/req_command.py
+ Line number: 171
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+170	        # Make sure the index_group options are present.
+171	        assert hasattr(options, "no_index")
+172	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/cli/req_command.py
+ Line number: 240
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+239	    ) -> Optional[int]:
+240	        assert self.tempdir_registry is not None
+241	        if options.no_clean:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/cli/req_command.py
+ Line number: 286
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+285	        temp_build_dir_path = temp_build_dir.path
+286	        assert temp_build_dir_path is not None
+287	        legacy_resolver = False
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/cli/spinners.py
+ Line number: 44
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+43	    def _write(self, status: str) -> None:
+44	        assert not self._finished
+45	        # Erase what we wrote before by backspacing to the beginning, writing
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/cli/spinners.py
+ Line number: 83
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+82	    def _update(self, status: str) -> None:
+83	        assert not self._finished
+84	        self._rate_limiter.reset()
+
+
+ + +
+
+ +
+
+ any_other_function_with_shell_equals_true: Function call with shell=True parameter identified, possible security issue.
+ Test ID: B604
+ Severity: MEDIUM
+ Confidence: LOW
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/commands/completion.py
+ Line number: 124
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b604_any_other_function_with_shell_equals_true.html
+ +
+
+123	            )
+124	            print(BASE_COMPLETION.format(script=script, shell=options.shell))
+125	            return SUCCESS
+
+
+ + +
+
+ +
+
+ blacklist: Consider possible security implications associated with the subprocess module.
+ Test ID: B404
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/commands/configuration.py
+ Line number: 3
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_imports.html#b404-import-subprocess
+ +
+
+2	import os
+3	import subprocess
+4	from optparse import Values
+
+
+ + +
+
+ +
+
+ subprocess_popen_with_shell_equals_true: subprocess call with shell=True identified, security issue.
+ Test ID: B602
+ Severity: HIGH
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/commands/configuration.py
+ Line number: 239
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b602_subprocess_popen_with_shell_equals_true.html
+ +
+
+238	        try:
+239	            subprocess.check_call(f'{editor} "{fname}"', shell=True)
+240	        except FileNotFoundError as e:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/commands/debug.py
+ Line number: 73
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+72	        # Try to find version in debundled module info.
+73	        assert module.__file__ is not None
+74	        env = get_environment([os.path.dirname(module.__file__)])
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/commands/download.py
+ Line number: 137
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+136	            if req.satisfied_by is None:
+137	                assert req.name is not None
+138	                preparer.save_linked_requirement(req)
+
+
+ + +
+
+ +
+
+ try_except_pass: Try, Except, Pass detected.
+ Test ID: B110
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/commands/install.py
+ Line number: 480
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b110_try_except_pass.html
+ +
+
+479	                        item = f"{item}-{installed_dist.version}"
+480	                except Exception:
+481	                    pass
+482	                items.append(item)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/commands/install.py
+ Line number: 509
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+508	        if options.target_dir:
+509	            assert target_temp_dir
+510	            self._handle_target_dir(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/commands/install.py
+ Line number: 598
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+597	        else:
+598	            assert resolver_variant == "resolvelib"
+599	            parts.append(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/commands/install.py
+ Line number: 695
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+694	    # If we are here, user installs have not been explicitly requested/avoided
+695	    assert use_user_site is None
+696	
+
+
+ + +
+
+ +
+
+ blacklist: Using xmlrpc.client to parse untrusted XML data is known to be vulnerable to XML attacks. Use defusedxml.xmlrpc.monkey_patch() function to monkey-patch xmlrpclib and mitigate XML vulnerabilities.
+ Test ID: B411
+ Severity: HIGH
+ Confidence: HIGH
+ CWE: CWE-20
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/commands/search.py
+ Line number: 5
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_imports.html#b411-import-xmlrpclib
+ +
+
+4	import textwrap
+5	import xmlrpc.client
+6	from collections import OrderedDict
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/commands/search.py
+ Line number: 84
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+83	            raise CommandError(message)
+84	        assert isinstance(hits, list)
+85	        return hits
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/commands/wheel.py
+ Line number: 168
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+167	        for req in build_successes:
+168	            assert req.link and req.link.is_wheel
+169	            assert req.local_file_path
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/commands/wheel.py
+ Line number: 169
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+168	            assert req.link and req.link.is_wheel
+169	            assert req.local_file_path
+170	            # copy from cache to target directory
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/configuration.py
+ Line number: 130
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+129	        """Returns the file with highest priority in configuration"""
+130	        assert self.load_only is not None, "Need to be specified a file to be editing"
+131	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/configuration.py
+ Line number: 160
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+159	
+160	        assert self.load_only
+161	        fname, parser = self._get_parser_to_modify()
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/configuration.py
+ Line number: 180
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+179	
+180	        assert self.load_only
+181	        if key not in self._config[self.load_only]:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/configuration.py
+ Line number: 365
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+364	        # Determine which parser to modify
+365	        assert self.load_only
+366	        parsers = self._parsers[self.load_only]
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/distributions/installed.py
+ Line number: 20
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+19	    def get_metadata_distribution(self) -> BaseDistribution:
+20	        assert self.req.satisfied_by is not None, "not actually installed"
+21	        return self.req.satisfied_by
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/distributions/sdist.py
+ Line number: 24
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+23	        """Identify this requirement uniquely by its link."""
+24	        assert self.req.link
+25	        return self.req.link.url_without_fragment
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/distributions/sdist.py
+ Line number: 59
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+58	            pyproject_requires = self.req.pyproject_requires
+59	            assert pyproject_requires is not None
+60	            conflicting, missing = self.req.build_env.check_requirements(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/distributions/sdist.py
+ Line number: 73
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+72	        pyproject_requires = self.req.pyproject_requires
+73	        assert pyproject_requires is not None
+74	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/distributions/sdist.py
+ Line number: 99
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+98	            backend = self.req.pep517_backend
+99	            assert backend is not None
+100	            with backend.subprocess_runner(runner):
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/distributions/sdist.py
+ Line number: 109
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+108	            backend = self.req.pep517_backend
+109	            assert backend is not None
+110	            with backend.subprocess_runner(runner):
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/distributions/wheel.py
+ Line number: 29
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+28	        """
+29	        assert self.req.local_file_path, "Set as part of preparation during download"
+30	        assert self.req.name, "Wheels are never unnamed"
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/distributions/wheel.py
+ Line number: 30
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+29	        assert self.req.local_file_path, "Set as part of preparation during download"
+30	        assert self.req.name, "Wheels are never unnamed"
+31	        wheel = FilesystemWheel(self.req.local_file_path)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/exceptions.py
+ Line number: 87
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+86	        if reference is None:
+87	            assert hasattr(self, "reference"), "error reference not provided!"
+88	            reference = self.reference
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/exceptions.py
+ Line number: 89
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+88	            reference = self.reference
+89	        assert _is_kebab_case(reference), "error reference must be kebab-case!"
+90	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/exceptions.py
+ Line number: 646
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+645	        else:
+646	            assert self.error is not None
+647	            message_part = f".\n{self.error}\n"
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/index/collector.py
+ Line number: 193
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+192	    def __init__(self, page: "IndexContent") -> None:
+193	        assert page.cache_link_parsing
+194	        self.page = page
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/index/package_finder.py
+ Line number: 364
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+363	        """
+364	        assert set(applicable_candidates) <= set(candidates)
+365	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/index/package_finder.py
+ Line number: 367
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+366	        if best_candidate is None:
+367	            assert not applicable_candidates
+368	        else:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/index/package_finder.py
+ Line number: 369
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+368	        else:
+369	            assert best_candidate in applicable_candidates
+370	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/index/package_finder.py
+ Line number: 543
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+542	                match = re.match(r"^(\d+)(.*)$", wheel.build_tag)
+543	                assert match is not None, "guaranteed by filename validation"
+544	                build_tag_groups = match.groups()
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/index/package_finder.py
+ Line number: 847
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+846	            for candidate in file_candidates:
+847	                assert candidate.link.url  # we need to have a URL
+848	                try:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/locations/_distutils.py
+ Line number: 66
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+65	    obj = d.get_command_obj("install", create=True)
+66	    assert obj is not None
+67	    i = cast(distutils_install_command, obj)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/locations/_distutils.py
+ Line number: 71
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+70	    # ideally, we'd prefer a scheme class that has no side-effects.
+71	    assert not (user and prefix), f"user={user} prefix={prefix}"
+72	    assert not (home and prefix), f"home={home} prefix={prefix}"
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/locations/_distutils.py
+ Line number: 72
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+71	    assert not (user and prefix), f"user={user} prefix={prefix}"
+72	    assert not (home and prefix), f"home={home} prefix={prefix}"
+73	    i.user = user or i.user
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/metadata/pkg_resources.py
+ Line number: 92
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+91	        else:
+92	            assert dist_dir.endswith(".dist-info")
+93	            dist_cls = pkg_resources.DistInfoDistribution
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/models/direct_url.py
+ Line number: 58
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+57	        )
+58	    assert infos[0] is not None
+59	    return infos[0]
+
+
+ + +
+
+ +
+
+ hardcoded_password_string: Possible hardcoded password: 'git'
+ Test ID: B105
+ Severity: LOW
+ Confidence: MEDIUM
+ CWE: CWE-259
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/models/direct_url.py
+ Line number: 182
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b105_hardcoded_password_string.html
+ +
+
+181	            and self.info.vcs == "git"
+182	            and user_pass == "git"
+183	        ):
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/models/installation_report.py
+ Line number: 15
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+14	    def _install_req_to_dict(cls, ireq: InstallRequirement) -> Dict[str, Any]:
+15	        assert ireq.download_info, f"No download_info for {ireq}"
+16	        res = {
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/models/link.py
+ Line number: 70
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+69	    def __post_init__(self) -> None:
+70	        assert self.name in _SUPPORTED_HASHES
+71	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/models/link.py
+ Line number: 106
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+105	        if self.hashes is not None:
+106	            assert all(name in _SUPPORTED_HASHES for name in self.hashes)
+107	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/models/link.py
+ Line number: 393
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+392	        name = urllib.parse.unquote(name)
+393	        assert name, f"URL {self._url!r} produced no filename"
+394	        return name
+
+
+ + +
+
+ +
+
+ blacklist: Consider possible security implications associated with the subprocess module.
+ Test ID: B404
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/network/auth.py
+ Line number: 9
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_imports.html#b404-import-subprocess
+ +
+
+8	import shutil
+9	import subprocess
+10	import sysconfig
+
+
+ + +
+
+ +
+
+ subprocess_without_shell_equals_true: subprocess call - check for execution of untrusted input.
+ Test ID: B603
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/network/auth.py
+ Line number: 136
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b603_subprocess_without_shell_equals_true.html
+ +
+
+135	        env["PYTHONIOENCODING"] = "utf-8"
+136	        res = subprocess.run(
+137	            cmd,
+138	            stdin=subprocess.DEVNULL,
+139	            stdout=subprocess.PIPE,
+140	            env=env,
+141	        )
+142	        if res.returncode:
+
+
+ + +
+
+ +
+
+ subprocess_without_shell_equals_true: subprocess call - check for execution of untrusted input.
+ Test ID: B603
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/network/auth.py
+ Line number: 152
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b603_subprocess_without_shell_equals_true.html
+ +
+
+151	        env["PYTHONIOENCODING"] = "utf-8"
+152	        subprocess.run(
+153	            [self.keyring, "set", service_name, username],
+154	            input=f"{password}{os.linesep}".encode("utf-8"),
+155	            env=env,
+156	            check=True,
+157	        )
+158	        return None
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/network/auth.py
+ Line number: 426
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+425	
+426	        assert (
+427	            # Credentials were found
+428	            (username is not None and password is not None)
+429	            # Credentials were not found
+430	            or (username is None and password is None)
+431	        ), f"Could not load credentials from url: {original_url}"
+432	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/network/auth.py
+ Line number: 548
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+547	        """Response callback to save credentials on success."""
+548	        assert (
+549	            self.keyring_provider.has_keyring
+550	        ), "should never reach here without keyring"
+551	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/network/cache.py
+ Line number: 51
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+50	    def __init__(self, directory: str) -> None:
+51	        assert directory is not None, "Cache directory must not be None."
+52	        super().__init__()
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/network/download.py
+ Line number: 136
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+135	        except NetworkConnectionError as e:
+136	            assert e.response is not None
+137	            logger.critical(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/network/download.py
+ Line number: 170
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+169	            except NetworkConnectionError as e:
+170	                assert e.response is not None
+171	                logger.critical(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/network/lazy_wheel.py
+ Line number: 54
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+53	        raise_for_status(head)
+54	        assert head.status_code == 200
+55	        self._session, self._url, self._chunk_size = session, url, chunk_size
+
+
+ + +
+
+ +
+
+ blacklist: Consider possible security implications associated with the subprocess module.
+ Test ID: B404
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/network/session.py
+ Line number: 14
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_imports.html#b404-import-subprocess
+ +
+
+13	import shutil
+14	import subprocess
+15	import sys
+
+
+ + +
+
+ +
+
+ start_process_with_partial_path: Starting a process with a partial executable path
+ Test ID: B607
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/network/session.py
+ Line number: 182
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b607_start_process_with_partial_path.html
+ +
+
+181	        try:
+182	            rustc_output = subprocess.check_output(
+183	                ["rustc", "--version"], stderr=subprocess.STDOUT, timeout=0.5
+184	            )
+185	        except Exception:
+
+
+ + +
+
+ +
+
+ subprocess_without_shell_equals_true: subprocess call - check for execution of untrusted input.
+ Test ID: B603
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/network/session.py
+ Line number: 182
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b603_subprocess_without_shell_equals_true.html
+ +
+
+181	        try:
+182	            rustc_output = subprocess.check_output(
+183	                ["rustc", "--version"], stderr=subprocess.STDOUT, timeout=0.5
+184	            )
+185	        except Exception:
+
+
+ + +
+
+ +
+
+ try_except_pass: Try, Except, Pass detected.
+ Test ID: B110
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/network/session.py
+ Line number: 185
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b110_try_except_pass.html
+ +
+
+184	            )
+185	        except Exception:
+186	            pass
+187	        else:
+
+
+ + +
+
+ +
+
+ blacklist: Using xmlrpc.client to parse untrusted XML data is known to be vulnerable to XML attacks. Use defusedxml.xmlrpc.monkey_patch() function to monkey-patch xmlrpclib and mitigate XML vulnerabilities.
+ Test ID: B411
+ Severity: HIGH
+ Confidence: HIGH
+ CWE: CWE-20
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/network/xmlrpc.py
+ Line number: 6
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_imports.html#b411-import-xmlrpclib
+ +
+
+5	import urllib.parse
+6	import xmlrpc.client
+7	from typing import TYPE_CHECKING, Tuple
+
+
+ + +
+
+ +
+
+ blacklist: Using _HostType to parse untrusted XML data is known to be vulnerable to XML attacks. Use defusedxml.xmlrpc.monkey_patch() function to monkey-patch xmlrpclib and mitigate XML vulnerabilities.
+ Test ID: B411
+ Severity: HIGH
+ Confidence: HIGH
+ CWE: CWE-20
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/network/xmlrpc.py
+ Line number: 14
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_imports.html#b411-import-xmlrpclib
+ +
+
+13	if TYPE_CHECKING:
+14	    from xmlrpc.client import _HostType, _Marshallable
+15	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/network/xmlrpc.py
+ Line number: 41
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+40	    ) -> Tuple["_Marshallable", ...]:
+41	        assert isinstance(host, str)
+42	        parts = (self._scheme, host, handler, None, None, None)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/network/xmlrpc.py
+ Line number: 56
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+55	        except NetworkConnectionError as exc:
+56	            assert exc.response
+57	            logger.critical(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/operations/build/build_tracker.py
+ Line number: 37
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+36	            else:
+37	                assert isinstance(original_value, str)  # for mypy
+38	                target[name] = original_value
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/operations/build/build_tracker.py
+ Line number: 106
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+105	        # If we're here, req should really not be building already.
+106	        assert key not in self._entries
+107	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/operations/build/wheel.py
+ Line number: 22
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+21	    """
+22	    assert metadata_directory is not None
+23	    try:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/operations/build/wheel_editable.py
+ Line number: 22
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+21	    """
+22	    assert metadata_directory is not None
+23	    try:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/operations/freeze.py
+ Line number: 160
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+159	    editable_project_location = dist.editable_project_location
+160	    assert editable_project_location
+161	    location = os.path.normcase(os.path.abspath(editable_project_location))
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/operations/install/wheel.py
+ Line number: 99
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+98	    # XXX RECORD hashes will need to be updated
+99	    assert os.path.isfile(path)
+100	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/operations/install/wheel.py
+ Line number: 614
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+613	                        pyc_path = pyc_output_path(path)
+614	                        assert os.path.exists(pyc_path)
+615	                        pyc_record_path = cast(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/operations/prepare.py
+ Line number: 79
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+78	    vcs_backend = vcs.get_backend_for_scheme(link.scheme)
+79	    assert vcs_backend is not None
+80	    vcs_backend.unpack(location, url=hide_url(link.url), verbosity=verbosity)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/operations/prepare.py
+ Line number: 160
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+159	
+160	    assert not link.is_existing_dir()
+161	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/operations/prepare.py
+ Line number: 310
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+309	            return
+310	        assert req.source_dir is None
+311	        if req.link.is_existing_dir():
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/operations/prepare.py
+ Line number: 384
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+383	            return None
+384	        assert req.req is not None
+385	        logger.verbose(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/operations/prepare.py
+ Line number: 460
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+459	        for req in partially_downloaded_reqs:
+460	            assert req.link
+461	            links_to_fully_download[req.link] = req
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/operations/prepare.py
+ Line number: 493
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+492	        """Prepare a requirement to be obtained from req.link."""
+493	        assert req.link
+494	        self._log_preparing_link(req)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/operations/prepare.py
+ Line number: 560
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+559	    ) -> BaseDistribution:
+560	        assert req.link
+561	        link = req.link
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/operations/prepare.py
+ Line number: 566
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+565	        if hashes and req.is_wheel_from_cache:
+566	            assert req.download_info is not None
+567	            assert link.is_wheel
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/operations/prepare.py
+ Line number: 567
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+566	            assert req.download_info is not None
+567	            assert link.is_wheel
+568	            assert link.is_file
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/operations/prepare.py
+ Line number: 568
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+567	            assert link.is_wheel
+568	            assert link.is_file
+569	            # We need to verify hashes, and we have found the requirement in the cache
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/operations/prepare.py
+ Line number: 619
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+618	            # prepare_editable_requirement).
+619	            assert not req.editable
+620	            req.download_info = direct_url_from_link(link, req.source_dir)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/operations/prepare.py
+ Line number: 650
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+649	    def save_linked_requirement(self, req: InstallRequirement) -> None:
+650	        assert self.download_dir is not None
+651	        assert req.link is not None
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/operations/prepare.py
+ Line number: 651
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+650	        assert self.download_dir is not None
+651	        assert req.link is not None
+652	        link = req.link
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/operations/prepare.py
+ Line number: 680
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+679	        """Prepare an editable requirement."""
+680	        assert req.editable, "cannot prepare a non-editable req as editable"
+681	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/operations/prepare.py
+ Line number: 693
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+692	            req.update_editable()
+693	            assert req.source_dir
+694	            req.download_info = direct_url_for_editable(req.unpacked_source_directory)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/operations/prepare.py
+ Line number: 714
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+713	        """Prepare an already-installed requirement."""
+714	        assert req.satisfied_by, "req should have been satisfied but isn't"
+715	        assert skip_reason is not None, (
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/operations/prepare.py
+ Line number: 715
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+714	        assert req.satisfied_by, "req should have been satisfied but isn't"
+715	        assert skip_reason is not None, (
+716	            "did not get skip reason skipped but req.satisfied_by "
+717	            f"is set to {req.satisfied_by}"
+718	        )
+719	        logger.info(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/pyproject.py
+ Line number: 109
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+108	    # At this point, we know whether we're going to use PEP 517.
+109	    assert use_pep517 is not None
+110	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/pyproject.py
+ Line number: 134
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+133	    # specified a backend, though.
+134	    assert build_system is not None
+135	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/req/__init__.py
+ Line number: 33
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+32	    for req in requirements:
+33	        assert req.name, f"invalid to-be-installed requirement: {req}"
+34	        yield req.name, req
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/req/constructors.py
+ Line number: 74
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+73	    # ireq.req is a valid requirement so the regex should always match
+74	    assert (
+75	        match is not None
+76	    ), f"regex match on requirement {req} failed, this should never happen"
+77	    pre: Optional[str] = match.group(1)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/req/constructors.py
+ Line number: 79
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+78	    post: Optional[str] = match.group(3)
+79	    assert (
+80	        pre is not None and post is not None
+81	    ), f"regex group selection for requirement {req} failed, this should never happen"
+82	    extras: str = "[%s]" % ",".join(sorted(new_extras)) if new_extras else ""
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/req/req_file.py
+ Line number: 187
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+186	
+187	    assert line.is_requirement
+188	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/req/req_file.py
+ Line number: 476
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+475	                new_line.append(line)
+476	                assert primary_line_number is not None
+477	                yield primary_line_number, "".join(new_line)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/req/req_file.py
+ Line number: 488
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+487	    if new_line:
+488	        assert primary_line_number is not None
+489	        yield primary_line_number, "".join(new_line)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/req/req_install.py
+ Line number: 90
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+89	    ) -> None:
+90	        assert req is None or isinstance(req, Requirement), req
+91	        self.req = req
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/req/req_install.py
+ Line number: 104
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+103	        if self.editable:
+104	            assert link
+105	            if link.is_file:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/req/req_install.py
+ Line number: 251
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+250	            return False
+251	        assert self.pep517_backend
+252	        with self.build_env:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/req/req_install.py
+ Line number: 261
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+260	    def specifier(self) -> SpecifierSet:
+261	        assert self.req is not None
+262	        return self.req.specifier
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/req/req_install.py
+ Line number: 275
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+274	        """
+275	        assert self.req is not None
+276	        specifiers = self.req.specifier
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/req/req_install.py
+ Line number: 329
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+328	        if link and link.hash:
+329	            assert link.hash_name is not None
+330	            good_hashes.setdefault(link.hash_name, []).append(link.hash)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/req/req_install.py
+ Line number: 351
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+350	    ) -> str:
+351	        assert build_dir is not None
+352	        if self._temp_build_dir is not None:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/req/req_install.py
+ Line number: 353
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+352	        if self._temp_build_dir is not None:
+353	            assert self._temp_build_dir.path
+354	            return self._temp_build_dir.path
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/req/req_install.py
+ Line number: 393
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+392	        """Set requirement after generating metadata."""
+393	        assert self.req is None
+394	        assert self.metadata is not None
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/req/req_install.py
+ Line number: 394
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+393	        assert self.req is None
+394	        assert self.metadata is not None
+395	        assert self.source_dir is not None
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/req/req_install.py
+ Line number: 395
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+394	        assert self.metadata is not None
+395	        assert self.source_dir is not None
+396	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/req/req_install.py
+ Line number: 414
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+413	    def warn_on_mismatching_name(self) -> None:
+414	        assert self.req is not None
+415	        metadata_name = canonicalize_name(self.metadata["Name"])
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/req/req_install.py
+ Line number: 484
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+483	    def unpacked_source_directory(self) -> str:
+484	        assert self.source_dir, f"No source dir for {self}"
+485	        return os.path.join(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/req/req_install.py
+ Line number: 491
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+490	    def setup_py_path(self) -> str:
+491	        assert self.source_dir, f"No source dir for {self}"
+492	        setup_py = os.path.join(self.unpacked_source_directory, "setup.py")
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/req/req_install.py
+ Line number: 498
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+497	    def setup_cfg_path(self) -> str:
+498	        assert self.source_dir, f"No source dir for {self}"
+499	        setup_cfg = os.path.join(self.unpacked_source_directory, "setup.cfg")
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/req/req_install.py
+ Line number: 505
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+504	    def pyproject_toml_path(self) -> str:
+505	        assert self.source_dir, f"No source dir for {self}"
+506	        return make_pyproject_path(self.unpacked_source_directory)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/req/req_install.py
+ Line number: 521
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+520	        if pyproject_toml_data is None:
+521	            assert not self.config_settings
+522	            self.use_pep517 = False
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/req/req_install.py
+ Line number: 563
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+562	        """
+563	        assert self.source_dir, f"No source dir for {self}"
+564	        details = self.name or f"from {self.link}"
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/req/req_install.py
+ Line number: 567
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+566	        if self.use_pep517:
+567	            assert self.pep517_backend is not None
+568	            if (
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/req/req_install.py
+ Line number: 612
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+611	        elif self.local_file_path and self.is_wheel:
+612	            assert self.req is not None
+613	            return get_wheel_distribution(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/req/req_install.py
+ Line number: 623
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+622	    def assert_source_matches_version(self) -> None:
+623	        assert self.source_dir, f"No source dir for {self}"
+624	        version = self.metadata["version"]
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/req/req_install.py
+ Line number: 663
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+662	    def needs_unpacked_archive(self, archive_source: Path) -> None:
+663	        assert self._archive_source is None
+664	        self._archive_source = archive_source
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/req/req_install.py
+ Line number: 668
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+667	        """Ensure the source directory has not yet been built in."""
+668	        assert self.source_dir is not None
+669	        if self._archive_source is not None:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/req/req_install.py
+ Line number: 691
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+690	            return
+691	        assert self.editable
+692	        assert self.source_dir
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/req/req_install.py
+ Line number: 692
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+691	        assert self.editable
+692	        assert self.source_dir
+693	        if self.link.scheme == "file":
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/req/req_install.py
+ Line number: 699
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+698	        # So here, if it's neither a path nor a valid VCS URL, it's a bug.
+699	        assert vcs_backend, f"Unsupported VCS URL {self.link.url}"
+700	        hidden_url = hide_url(self.link.url)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/req/req_install.py
+ Line number: 719
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+718	        """
+719	        assert self.req
+720	        dist = get_default_environment().get_distribution(self.req.name)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/req/req_install.py
+ Line number: 732
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+731	        def _clean_zip_name(name: str, prefix: str) -> str:
+732	            assert name.startswith(
+733	                prefix + os.path.sep
+734	            ), f"name {name!r} doesn't start with prefix {prefix!r}"
+735	            name = name[len(prefix) + 1 :]
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/req/req_install.py
+ Line number: 739
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+738	
+739	        assert self.req is not None
+740	        path = os.path.join(parentdir, path)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/req/req_install.py
+ Line number: 749
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+748	        """
+749	        assert self.source_dir
+750	        if build_dir is None:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/req/req_install.py
+ Line number: 821
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+820	    ) -> None:
+821	        assert self.req is not None
+822	        scheme = get_scheme(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/req/req_install.py
+ Line number: 853
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+852	
+853	        assert self.is_wheel
+854	        assert self.local_file_path
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/req/req_install.py
+ Line number: 854
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+853	        assert self.is_wheel
+854	        assert self.local_file_path
+855	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/req/req_set.py
+ Line number: 45
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+44	    def add_unnamed_requirement(self, install_req: InstallRequirement) -> None:
+45	        assert not install_req.name
+46	        self.unnamed_requirements.append(install_req)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/req/req_set.py
+ Line number: 49
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+48	    def add_named_requirement(self, install_req: InstallRequirement) -> None:
+49	        assert install_req.name
+50	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/req/req_uninstall.py
+ Line number: 70
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+69	    location = dist.location
+70	    assert location is not None, "not installed"
+71	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/req/req_uninstall.py
+ Line number: 544
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+543	                )
+544	            assert os.path.samefile(
+545	                normalized_link_pointer, normalized_dist_location
+546	            ), (
+547	                f"Egg-link {develop_egg_link} (to {link_pointer}) does not match "
+548	                f"installed location of {dist.raw_name} (at {dist_location})"
+549	            )
+550	            paths_to_remove.add(develop_egg_link)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/resolution/legacy/resolver.py
+ Line number: 135
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+134	        super().__init__()
+135	        assert upgrade_strategy in self._allowed_strategies
+136	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/resolution/legacy/resolver.py
+ Line number: 238
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+237	        # This next bit is really a sanity check.
+238	        assert (
+239	            not install_req.user_supplied or parent_req_name is None
+240	        ), "a user supplied req shouldn't have a parent"
+241	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/resolution/legacy/resolver.py
+ Line number: 317
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+316	        else:
+317	            assert self.upgrade_strategy == "only-if-needed"
+318	            return req.user_supplied or req.constraint
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/resolution/legacy/resolver.py
+ Line number: 452
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+451	        # so it must be None here.
+452	        assert req.satisfied_by is None
+453	        skip_reason = self._check_skip_installed(req)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/resolution/legacy/resolver.py
+ Line number: 541
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+540	                # provided by the user.
+541	                assert req_to_install.user_supplied
+542	                self._add_requirement_to_set(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/resolution/resolvelib/candidates.py
+ Line number: 56
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+55	) -> InstallRequirement:
+56	    assert not template.editable, "template is editable"
+57	    if template.req:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/resolution/resolvelib/candidates.py
+ Line number: 81
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+80	) -> InstallRequirement:
+81	    assert template.editable, "template not editable"
+82	    ireq = install_req_from_editable(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/resolution/resolvelib/candidates.py
+ Line number: 264
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+263	        ireq = make_install_req_from_link(link, template)
+264	        assert ireq.link == link
+265	        if ireq.link.is_wheel and not ireq.link.is_file:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/resolution/resolvelib/candidates.py
+ Line number: 268
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+267	            wheel_name = canonicalize_name(wheel.name)
+268	            assert name == wheel_name, f"{name!r} != {wheel_name!r} for wheel"
+269	            # Version may not be present for PEP 508 direct URLs
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/resolution/resolvelib/candidates.py
+ Line number: 272
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+271	                wheel_version = Version(wheel.version)
+272	                assert version == wheel_version, "{!r} != {!r} for wheel {}".format(
+273	                    version, wheel_version, name
+274	                )
+275	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/resolution/resolvelib/candidates.py
+ Line number: 277
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+276	        if cache_entry is not None:
+277	            assert ireq.link.is_wheel
+278	            assert ireq.link.is_file
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/resolution/resolvelib/candidates.py
+ Line number: 278
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+277	            assert ireq.link.is_wheel
+278	            assert ireq.link.is_file
+279	            if cache_entry.persistent and template.link is template.original_link:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/resolution/resolvelib/factory.py
+ Line number: 262
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+261	        template = ireqs[0]
+262	        assert template.req, "Candidates found on index must be PEP 508"
+263	        name = canonicalize_name(template.req.name)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/resolution/resolvelib/factory.py
+ Line number: 267
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+266	        for ireq in ireqs:
+267	            assert ireq.req, "Candidates found on index must be PEP 508"
+268	            specifier &= ireq.req.specifier
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/resolution/resolvelib/factory.py
+ Line number: 362
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+361	            base_cand = as_base_candidate(lookup_cand)
+362	            assert base_cand is not None, "no extras here"
+363	            yield self._make_extras_candidate(base_cand, extras)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/resolution/resolvelib/factory.py
+ Line number: 527
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+526	                    continue
+527	                assert ireq.name, "Constraint must be named"
+528	                name = canonicalize_name(ireq.name)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/resolution/resolvelib/factory.py
+ Line number: 641
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+640	    ) -> UnsupportedPythonVersion:
+641	        assert causes, "Requires-Python error reported with no cause"
+642	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/resolution/resolvelib/factory.py
+ Line number: 717
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+716	    ) -> InstallationError:
+717	        assert e.causes, "Installation error reported with no cause"
+718	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/resolution/resolvelib/requirements.py
+ Line number: 42
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+41	    def __init__(self, ireq: InstallRequirement) -> None:
+42	        assert ireq.link is None, "This is a link, not a specifier"
+43	        self._ireq = ireq
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/resolution/resolvelib/requirements.py
+ Line number: 54
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+53	    def project_name(self) -> NormalizedName:
+54	        assert self._ireq.req, "Specifier-backed ireq is always PEP 508"
+55	        return canonicalize_name(self._ireq.req.name)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/resolution/resolvelib/requirements.py
+ Line number: 78
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+77	    def is_satisfied_by(self, candidate: Candidate) -> bool:
+78	        assert candidate.name == self.name, (
+79	            f"Internal issue: Candidate is not for this requirement "
+80	            f"{candidate.name} vs {self.name}"
+81	        )
+82	        # We can safely always allow prereleases here since PackageFinder
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/resolution/resolvelib/requirements.py
+ Line number: 85
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+84	        # prerelease candidates if the user does not expect them.
+85	        assert self._ireq.req, "Specifier-backed ireq is always PEP 508"
+86	        spec = self._ireq.req.specifier
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/resolution/resolvelib/requirements.py
+ Line number: 97
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+96	    def __init__(self, ireq: InstallRequirement) -> None:
+97	        assert ireq.link is None, "This is a link, not a specifier"
+98	        self._ireq = install_req_drop_extras(ireq)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/resolution/resolvelib/requirements.py
+ Line number: 132
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+131	    def is_satisfied_by(self, candidate: Candidate) -> bool:
+132	        assert candidate.name == self._candidate.name, "Not Python candidate"
+133	        # We can safely always allow prereleases here since PackageFinder
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/resolution/resolvelib/resolver.py
+ Line number: 56
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+55	        super().__init__()
+56	        assert upgrade_strategy in self._allowed_strategies
+57	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/resolution/resolvelib/resolver.py
+ Line number: 200
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+199	        """
+200	        assert self._result is not None, "must call resolve() first"
+201	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/resolution/resolvelib/resolver.py
+ Line number: 301
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+300	    difference = set(weights.keys()).difference(requirement_keys)
+301	    assert not difference, difference
+302	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/utils/direct_url_helpers.py
+ Line number: 23
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+22	    else:
+23	        assert isinstance(direct_url.info, DirInfo)
+24	        requirement += direct_url.url
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/utils/direct_url_helpers.py
+ Line number: 44
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+43	        vcs_backend = vcs.get_backend_for_scheme(link.scheme)
+44	        assert vcs_backend
+45	        url, requested_revision, _ = vcs_backend.get_url_rev_and_auth(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/utils/direct_url_helpers.py
+ Line number: 55
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+54	            # with the VCS checkout.
+55	            assert requested_revision
+56	            commit_id = requested_revision
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/utils/direct_url_helpers.py
+ Line number: 61
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+60	            # which we can inspect to find out the commit id.
+61	            assert source_dir
+62	            commit_id = vcs_backend.get_revision(source_dir)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/utils/encoding.py
+ Line number: 31
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+30	            result = ENCODING_RE.search(line)
+31	            assert result is not None
+32	            encoding = result.groups()[0].decode("ascii")
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/utils/filesystem.py
+ Line number: 22
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+21	
+22	    assert os.path.isabs(path)
+23	
+
+
+ + +
+
+ +
+
+ blacklist: Standard pseudo-random generators are not suitable for security/cryptographic purposes.
+ Test ID: B311
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-330
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/utils/filesystem.py
+ Line number: 100
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b311-random
+ +
+
+99	    for _ in range(10):
+100	        name = basename + "".join(random.choice(alphabet) for _ in range(6))
+101	        file = os.path.join(path, name)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/utils/logging.py
+ Line number: 157
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+156	        # If we are given a diagnostic error to present, present it with indentation.
+157	        assert isinstance(record.args, tuple)
+158	        if getattr(record, "rich", False):
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/utils/logging.py
+ Line number: 160
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+159	            (rich_renderable,) = record.args
+160	            assert isinstance(
+161	                rich_renderable, (ConsoleRenderable, RichCast, str)
+162	            ), f"{rich_renderable} is not rich-console-renderable"
+163	
+
+
+ + +
+
+ +
+
+ hardcoded_password_string: Possible hardcoded password: ''
+ Test ID: B105
+ Severity: LOW
+ Confidence: MEDIUM
+ CWE: CWE-259
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/utils/misc.py
+ Line number: 517
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b105_hardcoded_password_string.html
+ +
+
+516	        user = "****"
+517	        password = ""
+518	    else:
+
+
+ + +
+
+ +
+
+ hardcoded_password_string: Possible hardcoded password: ':****'
+ Test ID: B105
+ Severity: LOW
+ Confidence: MEDIUM
+ CWE: CWE-259
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/utils/misc.py
+ Line number: 520
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b105_hardcoded_password_string.html
+ +
+
+519	        user = urllib.parse.quote(user)
+520	        password = ":****"
+521	    return f"{user}{password}@{netloc}"
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/utils/setuptools_build.py
+ Line number: 113
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+112	) -> List[str]:
+113	    assert not (use_user_site and prefix)
+114	
+
+
+ + +
+
+ +
+
+ blacklist: Consider possible security implications associated with the subprocess module.
+ Test ID: B404
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/utils/subprocess.py
+ Line number: 4
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_imports.html#b404-import-subprocess
+ +
+
+3	import shlex
+4	import subprocess
+5	from typing import (
+
+
+ + +
+
+ +
+
+ subprocess_without_shell_equals_true: subprocess call - check for execution of untrusted input.
+ Test ID: B603
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/utils/subprocess.py
+ Line number: 141
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b603_subprocess_without_shell_equals_true.html
+ +
+
+140	    try:
+141	        proc = subprocess.Popen(
+142	            # Convert HiddenText objects to the underlying str.
+143	            reveal_command_args(cmd),
+144	            stdin=subprocess.PIPE,
+145	            stdout=subprocess.PIPE,
+146	            stderr=subprocess.STDOUT if not stdout_only else subprocess.PIPE,
+147	            cwd=cwd,
+148	            env=env,
+149	            errors="backslashreplace",
+150	        )
+151	    except Exception as exc:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/utils/subprocess.py
+ Line number: 161
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+160	    if not stdout_only:
+161	        assert proc.stdout
+162	        assert proc.stdin
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/utils/subprocess.py
+ Line number: 162
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+161	        assert proc.stdout
+162	        assert proc.stdin
+163	        proc.stdin.close()
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/utils/subprocess.py
+ Line number: 176
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+175	            if use_spinner:
+176	                assert spinner
+177	                spinner.spin()
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/utils/subprocess.py
+ Line number: 199
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+198	    if use_spinner:
+199	        assert spinner
+200	        if proc_had_error:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/utils/temp_dir.py
+ Line number: 146
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+145	        if globally_managed:
+146	            assert _tempdir_manager is not None
+147	            _tempdir_manager.enter_context(self)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/utils/temp_dir.py
+ Line number: 151
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+150	    def path(self) -> str:
+151	        assert not self._deleted, f"Attempted to access deleted path: {self._path}"
+152	        return self._path
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/utils/unpacking.py
+ Line number: 216
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+215	                ensure_dir(os.path.dirname(path))
+216	                assert fp is not None
+217	                with open(path, "wb") as destfp:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/utils/urls.py
+ Line number: 30
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+29	    """
+30	    assert url.startswith(
+31	        "file:"
+32	    ), f"You can only turn file: urls into filenames (not {url!r})"
+33	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/vcs/git.py
+ Line number: 214
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+213	        # rev return value is always non-None.
+214	        assert rev is not None
+215	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/vcs/git.py
+ Line number: 477
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+476	        if "://" not in url:
+477	            assert "file:" not in url
+478	            url = url.replace("git+", "git+ssh://")
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/vcs/subversion.py
+ Line number: 65
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+64	            if base == location:
+65	                assert dirurl is not None
+66	                base = dirurl + "/"  # save the root url
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/vcs/subversion.py
+ Line number: 169
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+168	                match = _svn_info_xml_url_re.search(xml)
+169	                assert match is not None
+170	                url = match.group(1)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/wheel_builder.py
+ Line number: 105
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+104	        # unless it points to an immutable commit hash.
+105	        assert not req.editable
+106	        assert req.source_dir
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/wheel_builder.py
+ Line number: 106
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+105	        assert not req.editable
+106	        assert req.source_dir
+107	        vcs_backend = vcs.get_backend_for_scheme(req.link.scheme)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/wheel_builder.py
+ Line number: 108
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+107	        vcs_backend = vcs.get_backend_for_scheme(req.link.scheme)
+108	        assert vcs_backend
+109	        if vcs_backend.is_immutable_rev_checkout(req.link.url, req.source_dir):
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/wheel_builder.py
+ Line number: 113
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+112	
+113	    assert req.link
+114	    base, ext = req.link.splitext()
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/wheel_builder.py
+ Line number: 130
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+129	    cache_available = bool(wheel_cache.cache_dir)
+130	    assert req.link
+131	    if cache_available and _should_cache(req):
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/wheel_builder.py
+ Line number: 213
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+212	    with TempDirectory(kind="wheel") as temp_dir:
+213	        assert req.name
+214	        if req.use_pep517:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/wheel_builder.py
+ Line number: 215
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+214	        if req.use_pep517:
+215	            assert req.metadata_directory
+216	            assert req.pep517_backend
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/wheel_builder.py
+ Line number: 216
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+215	            assert req.metadata_directory
+216	            assert req.pep517_backend
+217	            if global_options:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/wheel_builder.py
+ Line number: 317
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+316	        for req in requirements:
+317	            assert req.name
+318	            cache_dir = _get_cache_dir(req, wheel_cache)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/wheel_builder.py
+ Line number: 337
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+336	                req.local_file_path = req.link.file_path
+337	                assert req.link.is_wheel
+338	                build_successes.append(req)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/cachecontrol/adapter.py
+ Line number: 150
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+149	        if request.method in self.invalidating_methods and resp.ok:
+150	            assert request.url is not None
+151	            cache_url = self.controller.cache_url(request.url)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/cachecontrol/controller.py
+ Line number: 43
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+42	    match = URI.match(uri)
+43	    assert match is not None
+44	    groups = match.groups()
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/cachecontrol/controller.py
+ Line number: 146
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+145	        cache_url = request.url
+146	        assert cache_url is not None
+147	        cache_data = self.cache.get(cache_url)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/cachecontrol/controller.py
+ Line number: 167
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+166	        """
+167	        assert request.url is not None
+168	        cache_url = self.cache_url(request.url)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/cachecontrol/controller.py
+ Line number: 215
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+214	        time_tuple = parsedate_tz(headers["date"])
+215	        assert time_tuple is not None
+216	        date = calendar.timegm(time_tuple[:6])
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/cachecontrol/controller.py
+ Line number: 344
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+343	            time_tuple = parsedate_tz(response_headers["date"])
+344	            assert time_tuple is not None
+345	            date = calendar.timegm(time_tuple[:6])
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/cachecontrol/controller.py
+ Line number: 364
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+363	
+364	        assert request.url is not None
+365	        cache_url = self.cache_url(request.url)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/cachecontrol/controller.py
+ Line number: 416
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+415	            time_tuple = parsedate_tz(response_headers["date"])
+416	            assert time_tuple is not None
+417	            date = calendar.timegm(time_tuple[:6])
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/cachecontrol/controller.py
+ Line number: 463
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+462	        """
+463	        assert request.url is not None
+464	        cache_url = self.cache_url(request.url)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/cachecontrol/heuristics.py
+ Line number: 137
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+136	        time_tuple = parsedate_tz(headers["date"])
+137	        assert time_tuple is not None
+138	        date = calendar.timegm(time_tuple[:6])
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/chardet/eucjpprober.py
+ Line number: 59
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+58	    def feed(self, byte_str: Union[bytes, bytearray]) -> ProbingState:
+59	        assert self.coding_sm is not None
+60	        assert self.distribution_analyzer is not None
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/chardet/eucjpprober.py
+ Line number: 60
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+59	        assert self.coding_sm is not None
+60	        assert self.distribution_analyzer is not None
+61	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/chardet/eucjpprober.py
+ Line number: 98
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+97	    def get_confidence(self) -> float:
+98	        assert self.distribution_analyzer is not None
+99	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/chardet/hebrewprober.py
+ Line number: 273
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+272	    def charset_name(self) -> str:
+273	        assert self._logical_prober is not None
+274	        assert self._visual_prober is not None
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/chardet/hebrewprober.py
+ Line number: 274
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+273	        assert self._logical_prober is not None
+274	        assert self._visual_prober is not None
+275	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/chardet/hebrewprober.py
+ Line number: 308
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+307	    def state(self) -> ProbingState:
+308	        assert self._logical_prober is not None
+309	        assert self._visual_prober is not None
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/chardet/hebrewprober.py
+ Line number: 309
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+308	        assert self._logical_prober is not None
+309	        assert self._visual_prober is not None
+310	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/chardet/mbcharsetprober.py
+ Line number: 58
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+57	    def feed(self, byte_str: Union[bytes, bytearray]) -> ProbingState:
+58	        assert self.coding_sm is not None
+59	        assert self.distribution_analyzer is not None
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/chardet/mbcharsetprober.py
+ Line number: 59
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+58	        assert self.coding_sm is not None
+59	        assert self.distribution_analyzer is not None
+60	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/chardet/mbcharsetprober.py
+ Line number: 94
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+93	    def get_confidence(self) -> float:
+94	        assert self.distribution_analyzer is not None
+95	        return self.distribution_analyzer.get_confidence()
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/chardet/sjisprober.py
+ Line number: 59
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+58	    def feed(self, byte_str: Union[bytes, bytearray]) -> ProbingState:
+59	        assert self.coding_sm is not None
+60	        assert self.distribution_analyzer is not None
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/chardet/sjisprober.py
+ Line number: 60
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+59	        assert self.coding_sm is not None
+60	        assert self.distribution_analyzer is not None
+61	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/chardet/sjisprober.py
+ Line number: 101
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+100	    def get_confidence(self) -> float:
+101	        assert self.distribution_analyzer is not None
+102	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/chardet/universaldetector.py
+ Line number: 319
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+318	                charset_name = max_prober.charset_name
+319	                assert charset_name is not None
+320	                lower_charset_name = charset_name.lower()
+
+
+ + +
+
+ +
+
+ blacklist: Using xmlrpclib to parse untrusted XML data is known to be vulnerable to XML attacks. Use defusedxml.xmlrpc.monkey_patch() function to monkey-patch xmlrpclib and mitigate XML vulnerabilities.
+ Test ID: B411
+ Severity: HIGH
+ Confidence: HIGH
+ CWE: CWE-20
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/distlib/compat.py
+ Line number: 42
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_imports.html#b411-import-xmlrpclib
+ +
+
+41	    import httplib
+42	    import xmlrpclib
+43	    import Queue as queue
+
+
+ + +
+
+ +
+
+ blacklist: Using xmlrpc.client to parse untrusted XML data is known to be vulnerable to XML attacks. Use defusedxml.xmlrpc.monkey_patch() function to monkey-patch xmlrpclib and mitigate XML vulnerabilities.
+ Test ID: B411
+ Severity: HIGH
+ Confidence: HIGH
+ CWE: CWE-20
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/distlib/compat.py
+ Line number: 81
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_imports.html#b411-import-xmlrpclib
+ +
+
+80	    import urllib.request as urllib2
+81	    import xmlrpc.client as xmlrpclib
+82	    import queue
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/distlib/compat.py
+ Line number: 634
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+633	    def cache_from_source(path, debug_override=None):
+634	        assert path.endswith('.py')
+635	        if debug_override is None:
+
+
+ + +
+
+ +
+
+ hashlib: Use of weak MD5 hash for security. Consider usedforsecurity=False
+ Test ID: B324
+ Severity: HIGH
+ Confidence: HIGH
+ CWE: CWE-327
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/distlib/database.py
+ Line number: 1032
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b324_hashlib.html
+ +
+
+1031	                f.close()
+1032	            return hashlib.md5(content).hexdigest()
+1033	
+
+
+ + +
+
+ +
+
+ blacklist: Consider possible security implications associated with the subprocess module.
+ Test ID: B404
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/distlib/index.py
+ Line number: 11
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_imports.html#b404-import-subprocess
+ +
+
+10	import shutil
+11	import subprocess
+12	import tempfile
+
+
+ + +
+
+ +
+
+ subprocess_without_shell_equals_true: subprocess call - check for execution of untrusted input.
+ Test ID: B603
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/distlib/index.py
+ Line number: 58
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b603_subprocess_without_shell_equals_true.html
+ +
+
+57	                try:
+58	                    rc = subprocess.check_call([s, '--version'], stdout=sink,
+59	                                               stderr=sink)
+60	                    if rc == 0:
+
+
+ + +
+
+ +
+
+ subprocess_without_shell_equals_true: subprocess call - check for execution of untrusted input.
+ Test ID: B603
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/distlib/index.py
+ Line number: 193
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b603_subprocess_without_shell_equals_true.html
+ +
+
+192	        stderr = []
+193	        p = subprocess.Popen(cmd, **kwargs)
+194	        # We don't use communicate() here because we may need to
+
+
+ + +
+
+ +
+
+ hashlib: Use of weak MD5 hash for security. Consider usedforsecurity=False
+ Test ID: B324
+ Severity: HIGH
+ Confidence: HIGH
+ CWE: CWE-327
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/distlib/index.py
+ Line number: 269
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b324_hashlib.html
+ +
+
+268	            file_data = f.read()
+269	        md5_digest = hashlib.md5(file_data).hexdigest()
+270	        sha256_digest = hashlib.sha256(file_data).hexdigest()
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/distlib/locators.py
+ Line number: 953
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+952	        super(DistPathLocator, self).__init__(**kwargs)
+953	        assert isinstance(distpath, DistributionPath)
+954	        self.distpath = distpath
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/distlib/manifest.py
+ Line number: 115
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+114	                parent, _ = os.path.split(d)
+115	                assert parent not in ('', '/')
+116	                add_dir(dirs, parent)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/distlib/manifest.py
+ Line number: 330
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+329	            if _PYTHON_VERSION > (3, 2):
+330	                assert pattern_re.startswith(start) and pattern_re.endswith(end)
+331	        else:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/distlib/manifest.py
+ Line number: 342
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+341	                prefix_re = self._glob_to_re(prefix)
+342	                assert prefix_re.startswith(start) and prefix_re.endswith(end)
+343	                prefix_re = prefix_re[len(start): len(prefix_re) - len(end)]
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/distlib/markers.py
+ Line number: 78
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+77	        else:
+78	            assert isinstance(expr, dict)
+79	            op = expr['op']
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/distlib/metadata.py
+ Line number: 930
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+929	    def _from_legacy(self):
+930	        assert self._legacy and not self._data
+931	        result = {
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/distlib/metadata.py
+ Line number: 993
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+992	
+993	        assert self._data and not self._legacy
+994	        result = LegacyMetadata()
+
+
+ + +
+
+ +
+
+ try_except_pass: Try, Except, Pass detected.
+ Test ID: B110
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/distlib/scripts.py
+ Line number: 297
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b110_try_except_pass.html
+ +
+
+296	                        os.remove(dfname)
+297	                    except Exception:
+298	                        pass  # still in use - ignore error
+299	            else:
+
+
+ + +
+
+ +
+
+ blacklist: Consider possible security implications associated with the subprocess module.
+ Test ID: B404
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/distlib/util.py
+ Line number: 21
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_imports.html#b404-import-subprocess
+ +
+
+20	    ssl = None
+21	import subprocess
+22	import sys
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/distlib/util.py
+ Line number: 287
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+286	        path = path.replace(os.path.sep, '/')
+287	        assert path.startswith(root)
+288	        return path[len(root):].lstrip('/')
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/distlib/util.py
+ Line number: 374
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+373	                entry = get_export_entry(s)
+374	                assert entry is not None
+375	                entries[k] = entry
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/distlib/util.py
+ Line number: 401
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+400	            entry = get_export_entry(s)
+401	            assert entry is not None
+402	            # entry.dist = self
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/distlib/util.py
+ Line number: 552
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+551	    def copy_stream(self, instream, outfile, encoding=None):
+552	        assert not os.path.isdir(outfile)
+553	        self.ensure_dir(os.path.dirname(outfile))
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/distlib/util.py
+ Line number: 617
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+616	                else:
+617	                    assert path.startswith(prefix)
+618	                    diagpath = path[len(prefix):]
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/distlib/util.py
+ Line number: 667
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+666	        """
+667	        assert self.record
+668	        result = self.files_written, self.dirs_created
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/distlib/util.py
+ Line number: 684
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+683	                if flist:
+684	                    assert flist == ['__pycache__']
+685	                    sd = os.path.join(d, flist[0])
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/distlib/util.py
+ Line number: 864
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+863	            break
+864	    assert i is not None
+865	    return result
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/distlib/util.py
+ Line number: 1130
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1129	    def add(self, pred, succ):
+1130	        assert pred != succ
+1131	        self._preds.setdefault(succ, set()).add(pred)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/distlib/util.py
+ Line number: 1135
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1134	    def remove(self, pred, succ):
+1135	        assert pred != succ
+1136	        try:
+
+
+ + +
+
+ +
+
+ tarfile_unsafe_members: tarfile.extractall used without any validation. Please check and discard dangerous members.
+ Test ID: B202
+ Severity: HIGH
+ Confidence: HIGH
+ CWE: CWE-22
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/distlib/util.py
+ Line number: 1310
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b202_tarfile_unsafe_members.html
+ +
+
+1309	
+1310	        archive.extractall(dest_dir)
+1311	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/distlib/util.py
+ Line number: 1342
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1341	    def __init__(self, minval=0, maxval=100):
+1342	        assert maxval is None or maxval >= minval
+1343	        self.min = self.cur = minval
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/distlib/util.py
+ Line number: 1350
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1349	    def update(self, curval):
+1350	        assert self.min <= curval
+1351	        assert self.max is None or curval <= self.max
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/distlib/util.py
+ Line number: 1351
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1350	        assert self.min <= curval
+1351	        assert self.max is None or curval <= self.max
+1352	        self.cur = curval
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/distlib/util.py
+ Line number: 1360
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1359	    def increment(self, incr):
+1360	        assert incr >= 0
+1361	        self.update(self.cur + incr)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/distlib/util.py
+ Line number: 1451
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1450	    if len(rich_path_glob) > 1:
+1451	        assert len(rich_path_glob) == 3, rich_path_glob
+1452	        prefix, set, suffix = rich_path_glob
+
+
+ + +
+
+ +
+
+ subprocess_without_shell_equals_true: subprocess call - check for execution of untrusted input.
+ Test ID: B603
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/distlib/util.py
+ Line number: 1792
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b603_subprocess_without_shell_equals_true.html
+ +
+
+1791	    def run_command(self, cmd, **kwargs):
+1792	        p = subprocess.Popen(cmd,
+1793	                             stdout=subprocess.PIPE,
+1794	                             stderr=subprocess.PIPE,
+1795	                             **kwargs)
+1796	        t1 = threading.Thread(target=self.reader, args=(p.stdout, 'stdout'))
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/distlib/version.py
+ Line number: 34
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+33	        self._parts = parts = self.parse(s)
+34	        assert isinstance(parts, tuple)
+35	        assert len(parts) > 0
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/distlib/version.py
+ Line number: 35
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+34	        assert isinstance(parts, tuple)
+35	        assert len(parts) > 0
+36	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/distlib/wheel.py
+ Line number: 437
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+436	                        break
+437	                assert distinfo, '.dist-info directory expected, not found'
+438	
+
+
+ + +
+
+ +
+
+ blacklist: Consider possible security implications associated with the subprocess module.
+ Test ID: B404
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/distro/distro.py
+ Line number: 37
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_imports.html#b404-import-subprocess
+ +
+
+36	import shlex
+37	import subprocess
+38	import sys
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/distro/distro.py
+ Line number: 640
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+639	        def __get__(self, obj: Any, owner: Type[Any]) -> Any:
+640	            assert obj is not None, f"call {self._fname} on an instance"
+641	            ret = obj.__dict__[self._fname] = self._f(obj)
+
+
+ + +
+
+ +
+
+ subprocess_without_shell_equals_true: subprocess call - check for execution of untrusted input.
+ Test ID: B603
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/distro/distro.py
+ Line number: 1161
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b603_subprocess_without_shell_equals_true.html
+ +
+
+1160	            cmd = ("lsb_release", "-a")
+1161	            stdout = subprocess.check_output(cmd, stderr=subprocess.DEVNULL)
+1162	        # Command not found or lsb_release returned error
+
+
+ + +
+
+ +
+
+ subprocess_without_shell_equals_true: subprocess call - check for execution of untrusted input.
+ Test ID: B603
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/distro/distro.py
+ Line number: 1198
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b603_subprocess_without_shell_equals_true.html
+ +
+
+1197	            cmd = ("uname", "-rs")
+1198	            stdout = subprocess.check_output(cmd, stderr=subprocess.DEVNULL)
+1199	        except OSError:
+
+
+ + +
+
+ +
+
+ start_process_with_partial_path: Starting a process with a partial executable path
+ Test ID: B607
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/distro/distro.py
+ Line number: 1209
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b607_start_process_with_partial_path.html
+ +
+
+1208	        try:
+1209	            stdout = subprocess.check_output("oslevel", stderr=subprocess.DEVNULL)
+1210	        except (OSError, subprocess.CalledProcessError):
+
+
+ + +
+
+ +
+
+ subprocess_without_shell_equals_true: subprocess call - check for execution of untrusted input.
+ Test ID: B603
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/distro/distro.py
+ Line number: 1209
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b603_subprocess_without_shell_equals_true.html
+ +
+
+1208	        try:
+1209	            stdout = subprocess.check_output("oslevel", stderr=subprocess.DEVNULL)
+1210	        except (OSError, subprocess.CalledProcessError):
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/msgpack/fallback.py
+ Line number: 369
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+368	    def feed(self, next_bytes):
+369	        assert self._feeding
+370	        view = _get_data_from_buffer(next_bytes)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/msgpack/fallback.py
+ Line number: 433
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+432	                break
+433	            assert isinstance(read_data, bytes)
+434	            self._buffer += read_data
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/msgpack/fallback.py
+ Line number: 617
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+616	                return self._ext_hook(n, bytes(obj))
+617	        assert typ == TYPE_IMMEDIATE
+618	        return obj
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/msgpack/fallback.py
+ Line number: 833
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+832	                    data = obj.data
+833	                assert isinstance(code, int)
+834	                assert isinstance(data, bytes)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/msgpack/fallback.py
+ Line number: 834
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+833	                assert isinstance(code, int)
+834	                assert isinstance(data, bytes)
+835	                L = len(data)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/packaging/_manylinux.py
+ Line number: 146
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+145	        version_string = os.confstr("CS_GNU_LIBC_VERSION")
+146	        assert version_string is not None
+147	        _, version = version_string.split()
+
+
+ + +
+
+ +
+
+ blacklist: Consider possible security implications associated with the subprocess module.
+ Test ID: B404
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/packaging/_musllinux.py
+ Line number: 13
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_imports.html#b404-import-subprocess
+ +
+
+12	import struct
+13	import subprocess
+14	import sys
+
+
+ + +
+
+ +
+
+ subprocess_without_shell_equals_true: subprocess call - check for execution of untrusted input.
+ Test ID: B603
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/packaging/_musllinux.py
+ Line number: 106
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b603_subprocess_without_shell_equals_true.html
+ +
+
+105	        return None
+106	    proc = subprocess.run([ld], stderr=subprocess.PIPE, universal_newlines=True)
+107	    return _parse_musl_version(proc.stderr)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/packaging/_musllinux.py
+ Line number: 130
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+129	    plat = sysconfig.get_platform()
+130	    assert plat.startswith("linux-"), "not linux"
+131	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/packaging/markers.py
+ Line number: 152
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+151	
+152	    assert isinstance(marker, (list, tuple, str))
+153	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/packaging/markers.py
+ Line number: 226
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+225	    for marker in markers:
+226	        assert isinstance(marker, (list, tuple, str))
+227	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/packaging/markers.py
+ Line number: 242
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+241	        else:
+242	            assert marker in ["and", "or"]
+243	            if marker == "or":
+
+
+ + +
+
+ +
+
+ exec_used: Use of exec detected.
+ Test ID: B102
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/pkg_resources/__init__.py
+ Line number: 1561
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b102_exec_used.html
+ +
+
+1560	            code = compile(source, script_filename, 'exec')
+1561	            exec(code, namespace, namespace)
+1562	        else:
+
+
+ + +
+
+ +
+
+ exec_used: Use of exec detected.
+ Test ID: B102
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/pkg_resources/__init__.py
+ Line number: 1572
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b102_exec_used.html
+ +
+
+1571	            script_code = compile(script_text, script_filename, 'exec')
+1572	            exec(script_code, namespace, namespace)
+1573	
+
+
+ + +
+
+ +
+
+ hardcoded_tmp_directory: Probable insecure usage of temp file/directory.
+ Test ID: B108
+ Severity: MEDIUM
+ Confidence: MEDIUM
+ CWE: CWE-377
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/platformdirs/unix.py
+ Line number: 103
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b108_hardcoded_tmp_directory.html
+ +
+
+102	        """:return: cache directory shared by users, e.g. ``/var/tmp/$appname/$version``"""
+103	        return self._append_app_name_and_version("/var/tmp")  # noqa: S108
+104	
+
+
+ + +
+
+ +
+
+ hardcoded_tmp_directory: Probable insecure usage of temp file/directory.
+ Test ID: B108
+ Severity: MEDIUM
+ Confidence: MEDIUM
+ CWE: CWE-377
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/platformdirs/unix.py
+ Line number: 164
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b108_hardcoded_tmp_directory.html
+ +
+
+163	                if not Path(path).exists():
+164	                    path = f"/tmp/runtime-{getuid()}"  # noqa: S108
+165	            else:
+
+
+ + +
+
+ +
+
+ try_except_pass: Try, Except, Pass detected.
+ Test ID: B110
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/pygments/cmdline.py
+ Line number: 522
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b110_try_except_pass.html
+ +
+
+521	                width = shutil.get_terminal_size().columns - 2
+522	            except Exception:
+523	                pass
+524	        argparse.HelpFormatter.__init__(self, prog, indent_increment,
+
+
+ + +
+
+ +
+
+ exec_used: Use of exec detected.
+ Test ID: B102
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/pygments/formatters/__init__.py
+ Line number: 103
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b102_exec_used.html
+ +
+
+102	        with open(filename, 'rb') as f:
+103	            exec(f.read(), custom_namespace)
+104	        # Retrieve the class `formattername` from that namespace
+
+
+ + +
+
+ +
+
+ blacklist: Consider possible security implications associated with the subprocess module.
+ Test ID: B404
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/pygments/formatters/img.py
+ Line number: 18
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_imports.html#b404-import-subprocess
+ +
+
+17	
+18	import subprocess
+19	
+
+
+ + +
+
+ +
+
+ start_process_with_partial_path: Starting a process with a partial executable path
+ Test ID: B607
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/pygments/formatters/img.py
+ Line number: 85
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b607_start_process_with_partial_path.html
+ +
+
+84	    def _get_nix_font_path(self, name, style):
+85	        proc = subprocess.Popen(['fc-list', "%s:style=%s" % (name, style), 'file'],
+86	                                stdout=subprocess.PIPE, stderr=None)
+87	        stdout, _ = proc.communicate()
+
+
+ + +
+
+ +
+
+ subprocess_without_shell_equals_true: subprocess call - check for execution of untrusted input.
+ Test ID: B603
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/pygments/formatters/img.py
+ Line number: 85
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b603_subprocess_without_shell_equals_true.html
+ +
+
+84	    def _get_nix_font_path(self, name, style):
+85	        proc = subprocess.Popen(['fc-list', "%s:style=%s" % (name, style), 'file'],
+86	                                stdout=subprocess.PIPE, stderr=None)
+87	        stdout, _ = proc.communicate()
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/pygments/lexer.py
+ Line number: 492
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+491	        """Preprocess the token component of a token definition."""
+492	        assert type(token) is _TokenType or callable(token), \
+493	            'token type must be simple type or callable, not %r' % (token,)
+494	        return token
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/pygments/lexer.py
+ Line number: 509
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+508	            else:
+509	                assert False, 'unknown new state %r' % new_state
+510	        elif isinstance(new_state, combined):
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/pygments/lexer.py
+ Line number: 516
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+515	            for istate in new_state:
+516	                assert istate != new_state, 'circular state ref %r' % istate
+517	                itokens.extend(cls._process_state(unprocessed,
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/pygments/lexer.py
+ Line number: 524
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+523	            for istate in new_state:
+524	                assert (istate in unprocessed or
+525	                        istate in ('#pop', '#push')), \
+526	                    'unknown new state ' + istate
+527	            return new_state
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/pygments/lexer.py
+ Line number: 529
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+528	        else:
+529	            assert False, 'unknown new state def %r' % new_state
+530	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/pygments/lexer.py
+ Line number: 533
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+532	        """Preprocess a single state definition."""
+533	        assert type(state) is str, "wrong state name %r" % state
+534	        assert state[0] != '#', "invalid state name %r" % state
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/pygments/lexer.py
+ Line number: 534
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+533	        assert type(state) is str, "wrong state name %r" % state
+534	        assert state[0] != '#', "invalid state name %r" % state
+535	        if state in processed:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/pygments/lexer.py
+ Line number: 542
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+541	                # it's a state reference
+542	                assert tdef != state, "circular state reference %r" % state
+543	                tokens.extend(cls._process_state(unprocessed, processed,
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/pygments/lexer.py
+ Line number: 556
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+555	
+556	            assert type(tdef) is tuple, "wrong rule def %r" % tdef
+557	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/pygments/lexer.py
+ Line number: 723
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+722	                        else:
+723	                            assert False, "wrong state def: %r" % new_state
+724	                        statetokens = tokendefs[statestack[-1]]
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/pygments/lexer.py
+ Line number: 811
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+810	                        else:
+811	                            assert False, "wrong state def: %r" % new_state
+812	                        statetokens = tokendefs[ctx.stack[-1]]
+
+
+ + +
+
+ +
+
+ exec_used: Use of exec detected.
+ Test ID: B102
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/pygments/lexers/__init__.py
+ Line number: 153
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b102_exec_used.html
+ +
+
+152	        with open(filename, 'rb') as f:
+153	            exec(f.read(), custom_namespace)
+154	        # Retrieve the class `lexername` from that namespace
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/pygments/style.py
+ Line number: 79
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+78	                return text
+79	            assert False, "wrong color format %r" % text
+80	
+
+
+ + +
+
+ +
+
+ blacklist: Consider possible security implications associated with the subprocess module.
+ Test ID: B404
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/pyproject_hooks/_impl.py
+ Line number: 8
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_imports.html#b404-import-subprocess
+ +
+
+7	from os.path import join as pjoin
+8	from subprocess import STDOUT, check_call, check_output
+9	
+
+
+ + +
+
+ +
+
+ subprocess_without_shell_equals_true: subprocess call - check for execution of untrusted input.
+ Test ID: B603
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/pyproject_hooks/_impl.py
+ Line number: 59
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b603_subprocess_without_shell_equals_true.html
+ +
+
+58	
+59	    check_call(cmd, cwd=cwd, env=env)
+60	
+
+
+ + +
+
+ +
+
+ subprocess_without_shell_equals_true: subprocess call - check for execution of untrusted input.
+ Test ID: B603
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/pyproject_hooks/_impl.py
+ Line number: 71
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b603_subprocess_without_shell_equals_true.html
+ +
+
+70	
+71	    check_output(cmd, cwd=cwd, env=env, stderr=STDOUT)
+72	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/requests/__init__.py
+ Line number: 57
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+56	    urllib3_version = urllib3_version.split(".")
+57	    assert urllib3_version != ["dev"]  # Verify urllib3 isn't installed from git.
+58	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/requests/__init__.py
+ Line number: 67
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+66	    # urllib3 >= 1.21.1
+67	    assert major >= 1
+68	    if major == 1:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/requests/__init__.py
+ Line number: 69
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+68	    if major == 1:
+69	        assert minor >= 21
+70	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/requests/__init__.py
+ Line number: 76
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+75	        # chardet_version >= 3.0.2, < 6.0.0
+76	        assert (3, 0, 2) <= (major, minor, patch) < (6, 0, 0)
+77	    elif charset_normalizer_version:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/requests/__init__.py
+ Line number: 81
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+80	        # charset_normalizer >= 2.0.0 < 4.0.0
+81	        assert (2, 0, 0) <= (major, minor, patch) < (4, 0, 0)
+82	    else:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/requests/_internal_utils.py
+ Line number: 45
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+44	    """
+45	    assert isinstance(u_string, str)
+46	    try:
+
+
+ + +
+
+ +
+
+ hashlib: Use of weak MD5 hash for security. Consider usedforsecurity=False
+ Test ID: B324
+ Severity: HIGH
+ Confidence: HIGH
+ CWE: CWE-327
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/requests/auth.py
+ Line number: 148
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b324_hashlib.html
+ +
+
+147	                    x = x.encode("utf-8")
+148	                return hashlib.md5(x).hexdigest()
+149	
+
+
+ + +
+
+ +
+
+ hashlib: Use of weak SHA1 hash for security. Consider usedforsecurity=False
+ Test ID: B324
+ Severity: HIGH
+ Confidence: HIGH
+ CWE: CWE-327
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/requests/auth.py
+ Line number: 156
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b324_hashlib.html
+ +
+
+155	                    x = x.encode("utf-8")
+156	                return hashlib.sha1(x).hexdigest()
+157	
+
+
+ + +
+
+ +
+
+ hashlib: Use of weak SHA1 hash for security. Consider usedforsecurity=False
+ Test ID: B324
+ Severity: HIGH
+ Confidence: HIGH
+ CWE: CWE-327
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/requests/auth.py
+ Line number: 205
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b324_hashlib.html
+ +
+
+204	
+205	        cnonce = hashlib.sha1(s).hexdigest()[:16]
+206	        if _algorithm == "MD5-SESS":
+
+
+ + +
+
+ +
+
+ hardcoded_password_string: Possible hardcoded password: '㊙'
+ Test ID: B105
+ Severity: LOW
+ Confidence: MEDIUM
+ CWE: CWE-259
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/rich/_emoji_codes.py
+ Line number: 156
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b105_hardcoded_password_string.html
+ +
+
+155	    "japanese_reserved_button": "🈯",
+156	    "japanese_secret_button": "㊙",
+157	    "japanese_service_charge_button": "🈂",
+158	    "japanese_symbol_for_beginner": "🔰",
+159	    "japanese_vacancy_button": "🈳",
+160	    "jersey": "🇯🇪",
+161	    "jordan": "🇯🇴",
+162	    "kazakhstan": "🇰🇿",
+163	    "kenya": "🇰🇪",
+164	    "kiribati": "🇰🇮",
+165	    "kosovo": "🇽🇰",
+166	    "kuwait": "🇰🇼",
+167	    "kyrgyzstan": "🇰🇬",
+168	    "laos": "🇱🇦",
+169	    "latvia": "🇱🇻",
+170	    "lebanon": "🇱🇧",
+171	    "leo": "♌",
+172	    "lesotho": "🇱🇸",
+173	    "liberia": "🇱🇷",
+174	    "libra": "♎",
+175	    "libya": "🇱🇾",
+176	    "liechtenstein": "🇱🇮",
+177	    "lithuania": "🇱🇹",
+178	    "luxembourg": "🇱🇺",
+179	    "macau_sar_china": "🇲🇴",
+180	    "macedonia": "🇲🇰",
+181	    "madagascar": "🇲🇬",
+182	    "malawi": "🇲🇼",
+183	    "malaysia": "🇲🇾",
+184	    "maldives": "🇲🇻",
+185	    "mali": "🇲🇱",
+186	    "malta": "🇲🇹",
+187	    "marshall_islands": "🇲🇭",
+188	    "martinique": "🇲🇶",
+189	    "mauritania": "🇲🇷",
+190	    "mauritius": "🇲🇺",
+191	    "mayotte": "🇾🇹",
+192	    "mexico": "🇲🇽",
+193	    "micronesia": "🇫🇲",
+194	    "moldova": "🇲🇩",
+195	    "monaco": "🇲🇨",
+196	    "mongolia": "🇲🇳",
+197	    "montenegro": "🇲🇪",
+198	    "montserrat": "🇲🇸",
+199	    "morocco": "🇲🇦",
+200	    "mozambique": "🇲🇿",
+201	    "mrs._claus": "🤶",
+202	    "mrs._claus_dark_skin_tone": "🤶🏿",
+203	    "mrs._claus_light_skin_tone": "🤶🏻",
+204	    "mrs._claus_medium-dark_skin_tone": "🤶🏾",
+205	    "mrs._claus_medium-light_skin_tone": "🤶🏼",
+206	    "mrs._claus_medium_skin_tone": "🤶🏽",
+207	    "myanmar_(burma)": "🇲🇲",
+208	    "new_button": "🆕",
+209	    "ng_button": "🆖",
+210	    "namibia": "🇳🇦",
+211	    "nauru": "🇳🇷",
+212	    "nepal": "🇳🇵",
+213	    "netherlands": "🇳🇱",
+214	    "new_caledonia": "🇳🇨",
+215	    "new_zealand": "🇳🇿",
+216	    "nicaragua": "🇳🇮",
+217	    "niger": "🇳🇪",
+218	    "nigeria": "🇳🇬",
+219	    "niue": "🇳🇺",
+220	    "norfolk_island": "🇳🇫",
+221	    "north_korea": "🇰🇵",
+222	    "northern_mariana_islands": "🇲🇵",
+223	    "norway": "🇳🇴",
+224	    "ok_button": "🆗",
+225	    "ok_hand": "👌",
+226	    "ok_hand_dark_skin_tone": "👌🏿",
+227	    "ok_hand_light_skin_tone": "👌🏻",
+228	    "ok_hand_medium-dark_skin_tone": "👌🏾",
+229	    "ok_hand_medium-light_skin_tone": "👌🏼",
+230	    "ok_hand_medium_skin_tone": "👌🏽",
+231	    "on!_arrow": "🔛",
+232	    "o_button_(blood_type)": "🅾",
+233	    "oman": "🇴🇲",
+234	    "ophiuchus": "⛎",
+235	    "p_button": "🅿",
+236	    "pakistan": "🇵🇰",
+237	    "palau": "🇵🇼",
+238	    "palestinian_territories": "🇵🇸",
+239	    "panama": "🇵🇦",
+240	    "papua_new_guinea": "🇵🇬",
+241	    "paraguay": "🇵🇾",
+242	    "peru": "🇵🇪",
+243	    "philippines": "🇵🇭",
+244	    "pisces": "♓",
+245	    "pitcairn_islands": "🇵🇳",
+246	    "poland": "🇵🇱",
+247	    "portugal": "🇵🇹",
+248	    "puerto_rico": "🇵🇷",
+249	    "qatar": "🇶🇦",
+250	    "romania": "🇷🇴",
+251	    "russia": "🇷🇺",
+252	    "rwanda": "🇷🇼",
+253	    "réunion": "🇷🇪",
+254	    "soon_arrow": "🔜",
+255	    "sos_button": "🆘",
+256	    "sagittarius": "♐",
+257	    "samoa": "🇼🇸",
+258	    "san_marino": "🇸🇲",
+259	    "santa_claus": "🎅",
+260	    "santa_claus_dark_skin_tone": "🎅🏿",
+261	    "santa_claus_light_skin_tone": "🎅🏻",
+262	    "santa_claus_medium-dark_skin_tone": "🎅🏾",
+263	    "santa_claus_medium-light_skin_tone": "🎅🏼",
+264	    "santa_claus_medium_skin_tone": "🎅🏽",
+265	    "saudi_arabia": "🇸🇦",
+266	    "scorpio": "♏",
+267	    "scotland": "🏴\U000e0067\U000e0062\U000e0073\U000e0063\U000e0074\U000e007f",
+268	    "senegal": "🇸🇳",
+269	    "serbia": "🇷🇸",
+270	    "seychelles": "🇸🇨",
+271	    "sierra_leone": "🇸🇱",
+272	    "singapore": "🇸🇬",
+273	    "sint_maarten": "🇸🇽",
+274	    "slovakia": "🇸🇰",
+275	    "slovenia": "🇸🇮",
+276	    "solomon_islands": "🇸🇧",
+277	    "somalia": "🇸🇴",
+278	    "south_africa": "🇿🇦",
+279	    "south_georgia_&_south_sandwich_islands": "🇬🇸",
+280	    "south_korea": "🇰🇷",
+281	    "south_sudan": "🇸🇸",
+282	    "spain": "🇪🇸",
+283	    "sri_lanka": "🇱🇰",
+284	    "st._barthélemy": "🇧🇱",
+285	    "st._helena": "🇸🇭",
+286	    "st._kitts_&_nevis": "🇰🇳",
+287	    "st._lucia": "🇱🇨",
+288	    "st._martin": "🇲🇫",
+289	    "st._pierre_&_miquelon": "🇵🇲",
+290	    "st._vincent_&_grenadines": "🇻🇨",
+291	    "statue_of_liberty": "🗽",
+292	    "sudan": "🇸🇩",
+293	    "suriname": "🇸🇷",
+294	    "svalbard_&_jan_mayen": "🇸🇯",
+295	    "swaziland": "🇸🇿",
+296	    "sweden": "🇸🇪",
+297	    "switzerland": "🇨🇭",
+298	    "syria": "🇸🇾",
+299	    "são_tomé_&_príncipe": "🇸🇹",
+300	    "t-rex": "🦖",
+301	    "top_arrow": "🔝",
+302	    "taiwan": "🇹🇼",
+303	    "tajikistan": "🇹🇯",
+304	    "tanzania": "🇹🇿",
+305	    "taurus": "♉",
+306	    "thailand": "🇹🇭",
+307	    "timor-leste": "🇹🇱",
+308	    "togo": "🇹🇬",
+309	    "tokelau": "🇹🇰",
+310	    "tokyo_tower": "🗼",
+311	    "tonga": "🇹🇴",
+312	    "trinidad_&_tobago": "🇹🇹",
+313	    "tristan_da_cunha": "🇹🇦",
+314	    "tunisia": "🇹🇳",
+315	    "turkey": "🦃",
+316	    "turkmenistan": "🇹🇲",
+317	    "turks_&_caicos_islands": "🇹🇨",
+318	    "tuvalu": "🇹🇻",
+319	    "u.s._outlying_islands": "🇺🇲",
+320	    "u.s._virgin_islands": "🇻🇮",
+321	    "up!_button": "🆙",
+322	    "uganda": "🇺🇬",
+323	    "ukraine": "🇺🇦",
+324	    "united_arab_emirates": "🇦🇪",
+325	    "united_kingdom": "🇬🇧",
+326	    "united_nations": "🇺🇳",
+327	    "united_states": "🇺🇸",
+328	    "uruguay": "🇺🇾",
+329	    "uzbekistan": "🇺🇿",
+330	    "vs_button": "🆚",
+331	    "vanuatu": "🇻🇺",
+332	    "vatican_city": "🇻🇦",
+333	    "venezuela": "🇻🇪",
+334	    "vietnam": "🇻🇳",
+335	    "virgo": "♍",
+336	    "wales": "🏴\U000e0067\U000e0062\U000e0077\U000e006c\U000e0073\U000e007f",
+337	    "wallis_&_futuna": "🇼🇫",
+338	    "western_sahara": "🇪🇭",
+339	    "yemen": "🇾🇪",
+340	    "zambia": "🇿🇲",
+341	    "zimbabwe": "🇿🇼",
+342	    "abacus": "🧮",
+343	    "adhesive_bandage": "🩹",
+344	    "admission_tickets": "🎟",
+345	    "adult": "🧑",
+346	    "adult_dark_skin_tone": "🧑🏿",
+347	    "adult_light_skin_tone": "🧑🏻",
+348	    "adult_medium-dark_skin_tone": "🧑🏾",
+349	    "adult_medium-light_skin_tone": "🧑🏼",
+350	    "adult_medium_skin_tone": "🧑🏽",
+351	    "aerial_tramway": "🚡",
+352	    "airplane": "✈",
+353	    "airplane_arrival": "🛬",
+354	    "airplane_departure": "🛫",
+355	    "alarm_clock": "⏰",
+356	    "alembic": "⚗",
+357	    "alien": "👽",
+358	    "alien_monster": "👾",
+359	    "ambulance": "🚑",
+360	    "american_football": "🏈",
+361	    "amphora": "🏺",
+362	    "anchor": "⚓",
+363	    "anger_symbol": "💢",
+364	    "angry_face": "😠",
+365	    "angry_face_with_horns": "👿",
+366	    "anguished_face": "😧",
+367	    "ant": "🐜",
+368	    "antenna_bars": "📶",
+369	    "anxious_face_with_sweat": "😰",
+370	    "articulated_lorry": "🚛",
+371	    "artist_palette": "🎨",
+372	    "astonished_face": "😲",
+373	    "atom_symbol": "⚛",
+374	    "auto_rickshaw": "🛺",
+375	    "automobile": "🚗",
+376	    "avocado": "🥑",
+377	    "axe": "🪓",
+378	    "baby": "👶",
+379	    "baby_angel": "👼",
+380	    "baby_angel_dark_skin_tone": "👼🏿",
+381	    "baby_angel_light_skin_tone": "👼🏻",
+382	    "baby_angel_medium-dark_skin_tone": "👼🏾",
+383	    "baby_angel_medium-light_skin_tone": "👼🏼",
+384	    "baby_angel_medium_skin_tone": "👼🏽",
+385	    "baby_bottle": "🍼",
+386	    "baby_chick": "🐤",
+387	    "baby_dark_skin_tone": "👶🏿",
+388	    "baby_light_skin_tone": "👶🏻",
+389	    "baby_medium-dark_skin_tone": "👶🏾",
+390	    "baby_medium-light_skin_tone": "👶🏼",
+391	    "baby_medium_skin_tone": "👶🏽",
+392	    "baby_symbol": "🚼",
+393	    "backhand_index_pointing_down": "👇",
+394	    "backhand_index_pointing_down_dark_skin_tone": "👇🏿",
+395	    "backhand_index_pointing_down_light_skin_tone": "👇🏻",
+396	    "backhand_index_pointing_down_medium-dark_skin_tone": "👇🏾",
+397	    "backhand_index_pointing_down_medium-light_skin_tone": "👇🏼",
+398	    "backhand_index_pointing_down_medium_skin_tone": "👇🏽",
+399	    "backhand_index_pointing_left": "👈",
+400	    "backhand_index_pointing_left_dark_skin_tone": "👈🏿",
+401	    "backhand_index_pointing_left_light_skin_tone": "👈🏻",
+402	    "backhand_index_pointing_left_medium-dark_skin_tone": "👈🏾",
+403	    "backhand_index_pointing_left_medium-light_skin_tone": "👈🏼",
+404	    "backhand_index_pointing_left_medium_skin_tone": "👈🏽",
+405	    "backhand_index_pointing_right": "👉",
+406	    "backhand_index_pointing_right_dark_skin_tone": "👉🏿",
+407	    "backhand_index_pointing_right_light_skin_tone": "👉🏻",
+408	    "backhand_index_pointing_right_medium-dark_skin_tone": "👉🏾",
+409	    "backhand_index_pointing_right_medium-light_skin_tone": "👉🏼",
+410	    "backhand_index_pointing_right_medium_skin_tone": "👉🏽",
+411	    "backhand_index_pointing_up": "👆",
+412	    "backhand_index_pointing_up_dark_skin_tone": "👆🏿",
+413	    "backhand_index_pointing_up_light_skin_tone": "👆🏻",
+414	    "backhand_index_pointing_up_medium-dark_skin_tone": "👆🏾",
+415	    "backhand_index_pointing_up_medium-light_skin_tone": "👆🏼",
+416	    "backhand_index_pointing_up_medium_skin_tone": "👆🏽",
+417	    "bacon": "🥓",
+418	    "badger": "🦡",
+419	    "badminton": "🏸",
+420	    "bagel": "🥯",
+421	    "baggage_claim": "🛄",
+422	    "baguette_bread": "🥖",
+423	    "balance_scale": "⚖",
+424	    "bald": "🦲",
+425	    "bald_man": "👨\u200d🦲",
+426	    "bald_woman": "👩\u200d🦲",
+427	    "ballet_shoes": "🩰",
+428	    "balloon": "🎈",
+429	    "ballot_box_with_ballot": "🗳",
+430	    "ballot_box_with_check": "☑",
+431	    "banana": "🍌",
+432	    "banjo": "🪕",
+433	    "bank": "🏦",
+434	    "bar_chart": "📊",
+435	    "barber_pole": "💈",
+436	    "baseball": "⚾",
+437	    "basket": "🧺",
+438	    "basketball": "🏀",
+439	    "bat": "🦇",
+440	    "bathtub": "🛁",
+441	    "battery": "🔋",
+442	    "beach_with_umbrella": "🏖",
+443	    "beaming_face_with_smiling_eyes": "😁",
+444	    "bear_face": "🐻",
+445	    "bearded_person": "🧔",
+446	    "bearded_person_dark_skin_tone": "🧔🏿",
+447	    "bearded_person_light_skin_tone": "🧔🏻",
+448	    "bearded_person_medium-dark_skin_tone": "🧔🏾",
+449	    "bearded_person_medium-light_skin_tone": "🧔🏼",
+450	    "bearded_person_medium_skin_tone": "🧔🏽",
+451	    "beating_heart": "💓",
+452	    "bed": "🛏",
+453	    "beer_mug": "🍺",
+454	    "bell": "🔔",
+455	    "bell_with_slash": "🔕",
+456	    "bellhop_bell": "🛎",
+457	    "bento_box": "🍱",
+458	    "beverage_box": "🧃",
+459	    "bicycle": "🚲",
+460	    "bikini": "👙",
+461	    "billed_cap": "🧢",
+462	    "biohazard": "☣",
+463	    "bird": "🐦",
+464	    "birthday_cake": "🎂",
+465	    "black_circle": "⚫",
+466	    "black_flag": "🏴",
+467	    "black_heart": "🖤",
+468	    "black_large_square": "⬛",
+469	    "black_medium-small_square": "◾",
+470	    "black_medium_square": "◼",
+471	    "black_nib": "✒",
+472	    "black_small_square": "▪",
+473	    "black_square_button": "🔲",
+474	    "blond-haired_man": "👱\u200d♂️",
+475	    "blond-haired_man_dark_skin_tone": "👱🏿\u200d♂️",
+476	    "blond-haired_man_light_skin_tone": "👱🏻\u200d♂️",
+477	    "blond-haired_man_medium-dark_skin_tone": "👱🏾\u200d♂️",
+478	    "blond-haired_man_medium-light_skin_tone": "👱🏼\u200d♂️",
+479	    "blond-haired_man_medium_skin_tone": "👱🏽\u200d♂️",
+480	    "blond-haired_person": "👱",
+481	    "blond-haired_person_dark_skin_tone": "👱🏿",
+482	    "blond-haired_person_light_skin_tone": "👱🏻",
+483	    "blond-haired_person_medium-dark_skin_tone": "👱🏾",
+484	    "blond-haired_person_medium-light_skin_tone": "👱🏼",
+485	    "blond-haired_person_medium_skin_tone": "👱🏽",
+486	    "blond-haired_woman": "👱\u200d♀️",
+487	    "blond-haired_woman_dark_skin_tone": "👱🏿\u200d♀️",
+488	    "blond-haired_woman_light_skin_tone": "👱🏻\u200d♀️",
+489	    "blond-haired_woman_medium-dark_skin_tone": "👱🏾\u200d♀️",
+490	    "blond-haired_woman_medium-light_skin_tone": "👱🏼\u200d♀️",
+491	    "blond-haired_woman_medium_skin_tone": "👱🏽\u200d♀️",
+492	    "blossom": "🌼",
+493	    "blowfish": "🐡",
+494	    "blue_book": "📘",
+495	    "blue_circle": "🔵",
+496	    "blue_heart": "💙",
+497	    "blue_square": "🟦",
+498	    "boar": "🐗",
+499	    "bomb": "💣",
+500	    "bone": "🦴",
+501	    "bookmark": "🔖",
+502	    "bookmark_tabs": "📑",
+503	    "books": "📚",
+504	    "bottle_with_popping_cork": "🍾",
+505	    "bouquet": "💐",
+506	    "bow_and_arrow": "🏹",
+507	    "bowl_with_spoon": "🥣",
+508	    "bowling": "🎳",
+509	    "boxing_glove": "🥊",
+510	    "boy": "👦",
+511	    "boy_dark_skin_tone": "👦🏿",
+512	    "boy_light_skin_tone": "👦🏻",
+513	    "boy_medium-dark_skin_tone": "👦🏾",
+514	    "boy_medium-light_skin_tone": "👦🏼",
+515	    "boy_medium_skin_tone": "👦🏽",
+516	    "brain": "🧠",
+517	    "bread": "🍞",
+518	    "breast-feeding": "🤱",
+519	    "breast-feeding_dark_skin_tone": "🤱🏿",
+520	    "breast-feeding_light_skin_tone": "🤱🏻",
+521	    "breast-feeding_medium-dark_skin_tone": "🤱🏾",
+522	    "breast-feeding_medium-light_skin_tone": "🤱🏼",
+523	    "breast-feeding_medium_skin_tone": "🤱🏽",
+524	    "brick": "🧱",
+525	    "bride_with_veil": "👰",
+526	    "bride_with_veil_dark_skin_tone": "👰🏿",
+527	    "bride_with_veil_light_skin_tone": "👰🏻",
+528	    "bride_with_veil_medium-dark_skin_tone": "👰🏾",
+529	    "bride_with_veil_medium-light_skin_tone": "👰🏼",
+530	    "bride_with_veil_medium_skin_tone": "👰🏽",
+531	    "bridge_at_night": "🌉",
+532	    "briefcase": "💼",
+533	    "briefs": "🩲",
+534	    "bright_button": "🔆",
+535	    "broccoli": "🥦",
+536	    "broken_heart": "💔",
+537	    "broom": "🧹",
+538	    "brown_circle": "🟤",
+539	    "brown_heart": "🤎",
+540	    "brown_square": "🟫",
+541	    "bug": "🐛",
+542	    "building_construction": "🏗",
+543	    "bullet_train": "🚅",
+544	    "burrito": "🌯",
+545	    "bus": "🚌",
+546	    "bus_stop": "🚏",
+547	    "bust_in_silhouette": "👤",
+548	    "busts_in_silhouette": "👥",
+549	    "butter": "🧈",
+550	    "butterfly": "🦋",
+551	    "cactus": "🌵",
+552	    "calendar": "📆",
+553	    "call_me_hand": "🤙",
+554	    "call_me_hand_dark_skin_tone": "🤙🏿",
+555	    "call_me_hand_light_skin_tone": "🤙🏻",
+556	    "call_me_hand_medium-dark_skin_tone": "🤙🏾",
+557	    "call_me_hand_medium-light_skin_tone": "🤙🏼",
+558	    "call_me_hand_medium_skin_tone": "🤙🏽",
+559	    "camel": "🐫",
+560	    "camera": "📷",
+561	    "camera_with_flash": "📸",
+562	    "camping": "🏕",
+563	    "candle": "🕯",
+564	    "candy": "🍬",
+565	    "canned_food": "🥫",
+566	    "canoe": "🛶",
+567	    "card_file_box": "🗃",
+568	    "card_index": "📇",
+569	    "card_index_dividers": "🗂",
+570	    "carousel_horse": "🎠",
+571	    "carp_streamer": "🎏",
+572	    "carrot": "🥕",
+573	    "castle": "🏰",
+574	    "cat": "🐱",
+575	    "cat_face": "🐱",
+576	    "cat_face_with_tears_of_joy": "😹",
+577	    "cat_face_with_wry_smile": "😼",
+578	    "chains": "⛓",
+579	    "chair": "🪑",
+580	    "chart_decreasing": "📉",
+581	    "chart_increasing": "📈",
+582	    "chart_increasing_with_yen": "💹",
+583	    "cheese_wedge": "🧀",
+584	    "chequered_flag": "🏁",
+585	    "cherries": "🍒",
+586	    "cherry_blossom": "🌸",
+587	    "chess_pawn": "♟",
+588	    "chestnut": "🌰",
+589	    "chicken": "🐔",
+590	    "child": "🧒",
+591	    "child_dark_skin_tone": "🧒🏿",
+592	    "child_light_skin_tone": "🧒🏻",
+593	    "child_medium-dark_skin_tone": "🧒🏾",
+594	    "child_medium-light_skin_tone": "🧒🏼",
+595	    "child_medium_skin_tone": "🧒🏽",
+596	    "children_crossing": "🚸",
+597	    "chipmunk": "🐿",
+598	    "chocolate_bar": "🍫",
+599	    "chopsticks": "🥢",
+600	    "church": "⛪",
+601	    "cigarette": "🚬",
+602	    "cinema": "🎦",
+603	    "circled_m": "Ⓜ",
+604	    "circus_tent": "🎪",
+605	    "cityscape": "🏙",
+606	    "cityscape_at_dusk": "🌆",
+607	    "clamp": "🗜",
+608	    "clapper_board": "🎬",
+609	    "clapping_hands": "👏",
+610	    "clapping_hands_dark_skin_tone": "👏🏿",
+611	    "clapping_hands_light_skin_tone": "👏🏻",
+612	    "clapping_hands_medium-dark_skin_tone": "👏🏾",
+613	    "clapping_hands_medium-light_skin_tone": "👏🏼",
+614	    "clapping_hands_medium_skin_tone": "👏🏽",
+615	    "classical_building": "🏛",
+616	    "clinking_beer_mugs": "🍻",
+617	    "clinking_glasses": "🥂",
+618	    "clipboard": "📋",
+619	    "clockwise_vertical_arrows": "🔃",
+620	    "closed_book": "📕",
+621	    "closed_mailbox_with_lowered_flag": "📪",
+622	    "closed_mailbox_with_raised_flag": "📫",
+623	    "closed_umbrella": "🌂",
+624	    "cloud": "☁",
+625	    "cloud_with_lightning": "🌩",
+626	    "cloud_with_lightning_and_rain": "⛈",
+627	    "cloud_with_rain": "🌧",
+628	    "cloud_with_snow": "🌨",
+629	    "clown_face": "🤡",
+630	    "club_suit": "♣",
+631	    "clutch_bag": "👝",
+632	    "coat": "🧥",
+633	    "cocktail_glass": "🍸",
+634	    "coconut": "🥥",
+635	    "coffin": "⚰",
+636	    "cold_face": "🥶",
+637	    "collision": "💥",
+638	    "comet": "☄",
+639	    "compass": "🧭",
+640	    "computer_disk": "💽",
+641	    "computer_mouse": "🖱",
+642	    "confetti_ball": "🎊",
+643	    "confounded_face": "😖",
+644	    "confused_face": "😕",
+645	    "construction": "🚧",
+646	    "construction_worker": "👷",
+647	    "construction_worker_dark_skin_tone": "👷🏿",
+648	    "construction_worker_light_skin_tone": "👷🏻",
+649	    "construction_worker_medium-dark_skin_tone": "👷🏾",
+650	    "construction_worker_medium-light_skin_tone": "👷🏼",
+651	    "construction_worker_medium_skin_tone": "👷🏽",
+652	    "control_knobs": "🎛",
+653	    "convenience_store": "🏪",
+654	    "cooked_rice": "🍚",
+655	    "cookie": "🍪",
+656	    "cooking": "🍳",
+657	    "copyright": "©",
+658	    "couch_and_lamp": "🛋",
+659	    "counterclockwise_arrows_button": "🔄",
+660	    "couple_with_heart": "💑",
+661	    "couple_with_heart_man_man": "👨\u200d❤️\u200d👨",
+662	    "couple_with_heart_woman_man": "👩\u200d❤️\u200d👨",
+663	    "couple_with_heart_woman_woman": "👩\u200d❤️\u200d👩",
+664	    "cow": "🐮",
+665	    "cow_face": "🐮",
+666	    "cowboy_hat_face": "🤠",
+667	    "crab": "🦀",
+668	    "crayon": "🖍",
+669	    "credit_card": "💳",
+670	    "crescent_moon": "🌙",
+671	    "cricket": "🦗",
+672	    "cricket_game": "🏏",
+673	    "crocodile": "🐊",
+674	    "croissant": "🥐",
+675	    "cross_mark": "❌",
+676	    "cross_mark_button": "❎",
+677	    "crossed_fingers": "🤞",
+678	    "crossed_fingers_dark_skin_tone": "🤞🏿",
+679	    "crossed_fingers_light_skin_tone": "🤞🏻",
+680	    "crossed_fingers_medium-dark_skin_tone": "🤞🏾",
+681	    "crossed_fingers_medium-light_skin_tone": "🤞🏼",
+682	    "crossed_fingers_medium_skin_tone": "🤞🏽",
+683	    "crossed_flags": "🎌",
+684	    "crossed_swords": "⚔",
+685	    "crown": "👑",
+686	    "crying_cat_face": "😿",
+687	    "crying_face": "😢",
+688	    "crystal_ball": "🔮",
+689	    "cucumber": "🥒",
+690	    "cupcake": "🧁",
+691	    "cup_with_straw": "🥤",
+692	    "curling_stone": "🥌",
+693	    "curly_hair": "🦱",
+694	    "curly-haired_man": "👨\u200d🦱",
+695	    "curly-haired_woman": "👩\u200d🦱",
+696	    "curly_loop": "➰",
+697	    "currency_exchange": "💱",
+698	    "curry_rice": "🍛",
+699	    "custard": "🍮",
+700	    "customs": "🛃",
+701	    "cut_of_meat": "🥩",
+702	    "cyclone": "🌀",
+703	    "dagger": "🗡",
+704	    "dango": "🍡",
+705	    "dashing_away": "💨",
+706	    "deaf_person": "🧏",
+707	    "deciduous_tree": "🌳",
+708	    "deer": "🦌",
+709	    "delivery_truck": "🚚",
+710	    "department_store": "🏬",
+711	    "derelict_house": "🏚",
+712	    "desert": "🏜",
+713	    "desert_island": "🏝",
+714	    "desktop_computer": "🖥",
+715	    "detective": "🕵",
+716	    "detective_dark_skin_tone": "🕵🏿",
+717	    "detective_light_skin_tone": "🕵🏻",
+718	    "detective_medium-dark_skin_tone": "🕵🏾",
+719	    "detective_medium-light_skin_tone": "🕵🏼",
+720	    "detective_medium_skin_tone": "🕵🏽",
+721	    "diamond_suit": "♦",
+722	    "diamond_with_a_dot": "💠",
+723	    "dim_button": "🔅",
+724	    "direct_hit": "🎯",
+725	    "disappointed_face": "😞",
+726	    "diving_mask": "🤿",
+727	    "diya_lamp": "🪔",
+728	    "dizzy": "💫",
+729	    "dizzy_face": "😵",
+730	    "dna": "🧬",
+731	    "dog": "🐶",
+732	    "dog_face": "🐶",
+733	    "dollar_banknote": "💵",
+734	    "dolphin": "🐬",
+735	    "door": "🚪",
+736	    "dotted_six-pointed_star": "🔯",
+737	    "double_curly_loop": "➿",
+738	    "double_exclamation_mark": "‼",
+739	    "doughnut": "🍩",
+740	    "dove": "🕊",
+741	    "down-left_arrow": "↙",
+742	    "down-right_arrow": "↘",
+743	    "down_arrow": "⬇",
+744	    "downcast_face_with_sweat": "😓",
+745	    "downwards_button": "🔽",
+746	    "dragon": "🐉",
+747	    "dragon_face": "🐲",
+748	    "dress": "👗",
+749	    "drooling_face": "🤤",
+750	    "drop_of_blood": "🩸",
+751	    "droplet": "💧",
+752	    "drum": "🥁",
+753	    "duck": "🦆",
+754	    "dumpling": "🥟",
+755	    "dvd": "📀",
+756	    "e-mail": "📧",
+757	    "eagle": "🦅",
+758	    "ear": "👂",
+759	    "ear_dark_skin_tone": "👂🏿",
+760	    "ear_light_skin_tone": "👂🏻",
+761	    "ear_medium-dark_skin_tone": "👂🏾",
+762	    "ear_medium-light_skin_tone": "👂🏼",
+763	    "ear_medium_skin_tone": "👂🏽",
+764	    "ear_of_corn": "🌽",
+765	    "ear_with_hearing_aid": "🦻",
+766	    "egg": "🍳",
+767	    "eggplant": "🍆",
+768	    "eight-pointed_star": "✴",
+769	    "eight-spoked_asterisk": "✳",
+770	    "eight-thirty": "🕣",
+771	    "eight_o’clock": "🕗",
+772	    "eject_button": "⏏",
+773	    "electric_plug": "🔌",
+774	    "elephant": "🐘",
+775	    "eleven-thirty": "🕦",
+776	    "eleven_o’clock": "🕚",
+777	    "elf": "🧝",
+778	    "elf_dark_skin_tone": "🧝🏿",
+779	    "elf_light_skin_tone": "🧝🏻",
+780	    "elf_medium-dark_skin_tone": "🧝🏾",
+781	    "elf_medium-light_skin_tone": "🧝🏼",
+782	    "elf_medium_skin_tone": "🧝🏽",
+783	    "envelope": "✉",
+784	    "envelope_with_arrow": "📩",
+785	    "euro_banknote": "💶",
+786	    "evergreen_tree": "🌲",
+787	    "ewe": "🐑",
+788	    "exclamation_mark": "❗",
+789	    "exclamation_question_mark": "⁉",
+790	    "exploding_head": "🤯",
+791	    "expressionless_face": "😑",
+792	    "eye": "👁",
+793	    "eye_in_speech_bubble": "👁️\u200d🗨️",
+794	    "eyes": "👀",
+795	    "face_blowing_a_kiss": "😘",
+796	    "face_savoring_food": "😋",
+797	    "face_screaming_in_fear": "😱",
+798	    "face_vomiting": "🤮",
+799	    "face_with_hand_over_mouth": "🤭",
+800	    "face_with_head-bandage": "🤕",
+801	    "face_with_medical_mask": "😷",
+802	    "face_with_monocle": "🧐",
+803	    "face_with_open_mouth": "😮",
+804	    "face_with_raised_eyebrow": "🤨",
+805	    "face_with_rolling_eyes": "🙄",
+806	    "face_with_steam_from_nose": "😤",
+807	    "face_with_symbols_on_mouth": "🤬",
+808	    "face_with_tears_of_joy": "😂",
+809	    "face_with_thermometer": "🤒",
+810	    "face_with_tongue": "😛",
+811	    "face_without_mouth": "😶",
+812	    "factory": "🏭",
+813	    "fairy": "🧚",
+814	    "fairy_dark_skin_tone": "🧚🏿",
+815	    "fairy_light_skin_tone": "🧚🏻",
+816	    "fairy_medium-dark_skin_tone": "🧚🏾",
+817	    "fairy_medium-light_skin_tone": "🧚🏼",
+818	    "fairy_medium_skin_tone": "🧚🏽",
+819	    "falafel": "🧆",
+820	    "fallen_leaf": "🍂",
+821	    "family": "👪",
+822	    "family_man_boy": "👨\u200d👦",
+823	    "family_man_boy_boy": "👨\u200d👦\u200d👦",
+824	    "family_man_girl": "👨\u200d👧",
+825	    "family_man_girl_boy": "👨\u200d👧\u200d👦",
+826	    "family_man_girl_girl": "👨\u200d👧\u200d👧",
+827	    "family_man_man_boy": "👨\u200d👨\u200d👦",
+828	    "family_man_man_boy_boy": "👨\u200d👨\u200d👦\u200d👦",
+829	    "family_man_man_girl": "👨\u200d👨\u200d👧",
+830	    "family_man_man_girl_boy": "👨\u200d👨\u200d👧\u200d👦",
+831	    "family_man_man_girl_girl": "👨\u200d👨\u200d👧\u200d👧",
+832	    "family_man_woman_boy": "👨\u200d👩\u200d👦",
+833	    "family_man_woman_boy_boy": "👨\u200d👩\u200d👦\u200d👦",
+834	    "family_man_woman_girl": "👨\u200d👩\u200d👧",
+835	    "family_man_woman_girl_boy": "👨\u200d👩\u200d👧\u200d👦",
+836	    "family_man_woman_girl_girl": "👨\u200d👩\u200d👧\u200d👧",
+837	    "family_woman_boy": "👩\u200d👦",
+838	    "family_woman_boy_boy": "👩\u200d👦\u200d👦",
+839	    "family_woman_girl": "👩\u200d👧",
+840	    "family_woman_girl_boy": "👩\u200d👧\u200d👦",
+841	    "family_woman_girl_girl": "👩\u200d👧\u200d👧",
+842	    "family_woman_woman_boy": "👩\u200d👩\u200d👦",
+843	    "family_woman_woman_boy_boy": "👩\u200d👩\u200d👦\u200d👦",
+844	    "family_woman_woman_girl": "👩\u200d👩\u200d👧",
+845	    "family_woman_woman_girl_boy": "👩\u200d👩\u200d👧\u200d👦",
+846	    "family_woman_woman_girl_girl": "👩\u200d👩\u200d👧\u200d👧",
+847	    "fast-forward_button": "⏩",
+848	    "fast_down_button": "⏬",
+849	    "fast_reverse_button": "⏪",
+850	    "fast_up_button": "⏫",
+851	    "fax_machine": "📠",
+852	    "fearful_face": "😨",
+853	    "female_sign": "♀",
+854	    "ferris_wheel": "🎡",
+855	    "ferry": "⛴",
+856	    "field_hockey": "🏑",
+857	    "file_cabinet": "🗄",
+858	    "file_folder": "📁",
+859	    "film_frames": "🎞",
+860	    "film_projector": "📽",
+861	    "fire": "🔥",
+862	    "fire_extinguisher": "🧯",
+863	    "firecracker": "🧨",
+864	    "fire_engine": "🚒",
+865	    "fireworks": "🎆",
+866	    "first_quarter_moon": "🌓",
+867	    "first_quarter_moon_face": "🌛",
+868	    "fish": "🐟",
+869	    "fish_cake_with_swirl": "🍥",
+870	    "fishing_pole": "🎣",
+871	    "five-thirty": "🕠",
+872	    "five_o’clock": "🕔",
+873	    "flag_in_hole": "⛳",
+874	    "flamingo": "🦩",
+875	    "flashlight": "🔦",
+876	    "flat_shoe": "🥿",
+877	    "fleur-de-lis": "⚜",
+878	    "flexed_biceps": "💪",
+879	    "flexed_biceps_dark_skin_tone": "💪🏿",
+880	    "flexed_biceps_light_skin_tone": "💪🏻",
+881	    "flexed_biceps_medium-dark_skin_tone": "💪🏾",
+882	    "flexed_biceps_medium-light_skin_tone": "💪🏼",
+883	    "flexed_biceps_medium_skin_tone": "💪🏽",
+884	    "floppy_disk": "💾",
+885	    "flower_playing_cards": "🎴",
+886	    "flushed_face": "😳",
+887	    "flying_disc": "🥏",
+888	    "flying_saucer": "🛸",
+889	    "fog": "🌫",
+890	    "foggy": "🌁",
+891	    "folded_hands": "🙏",
+892	    "folded_hands_dark_skin_tone": "🙏🏿",
+893	    "folded_hands_light_skin_tone": "🙏🏻",
+894	    "folded_hands_medium-dark_skin_tone": "🙏🏾",
+895	    "folded_hands_medium-light_skin_tone": "🙏🏼",
+896	    "folded_hands_medium_skin_tone": "🙏🏽",
+897	    "foot": "🦶",
+898	    "footprints": "👣",
+899	    "fork_and_knife": "🍴",
+900	    "fork_and_knife_with_plate": "🍽",
+901	    "fortune_cookie": "🥠",
+902	    "fountain": "⛲",
+903	    "fountain_pen": "🖋",
+904	    "four-thirty": "🕟",
+905	    "four_leaf_clover": "🍀",
+906	    "four_o’clock": "🕓",
+907	    "fox_face": "🦊",
+908	    "framed_picture": "🖼",
+909	    "french_fries": "🍟",
+910	    "fried_shrimp": "🍤",
+911	    "frog_face": "🐸",
+912	    "front-facing_baby_chick": "🐥",
+913	    "frowning_face": "☹",
+914	    "frowning_face_with_open_mouth": "😦",
+915	    "fuel_pump": "⛽",
+916	    "full_moon": "🌕",
+917	    "full_moon_face": "🌝",
+918	    "funeral_urn": "⚱",
+919	    "game_die": "🎲",
+920	    "garlic": "🧄",
+921	    "gear": "⚙",
+922	    "gem_stone": "💎",
+923	    "genie": "🧞",
+924	    "ghost": "👻",
+925	    "giraffe": "🦒",
+926	    "girl": "👧",
+927	    "girl_dark_skin_tone": "👧🏿",
+928	    "girl_light_skin_tone": "👧🏻",
+929	    "girl_medium-dark_skin_tone": "👧🏾",
+930	    "girl_medium-light_skin_tone": "👧🏼",
+931	    "girl_medium_skin_tone": "👧🏽",
+932	    "glass_of_milk": "🥛",
+933	    "glasses": "👓",
+934	    "globe_showing_americas": "🌎",
+935	    "globe_showing_asia-australia": "🌏",
+936	    "globe_showing_europe-africa": "🌍",
+937	    "globe_with_meridians": "🌐",
+938	    "gloves": "🧤",
+939	    "glowing_star": "🌟",
+940	    "goal_net": "🥅",
+941	    "goat": "🐐",
+942	    "goblin": "👺",
+943	    "goggles": "🥽",
+944	    "gorilla": "🦍",
+945	    "graduation_cap": "🎓",
+946	    "grapes": "🍇",
+947	    "green_apple": "🍏",
+948	    "green_book": "📗",
+949	    "green_circle": "🟢",
+950	    "green_heart": "💚",
+951	    "green_salad": "🥗",
+952	    "green_square": "🟩",
+953	    "grimacing_face": "😬",
+954	    "grinning_cat_face": "😺",
+955	    "grinning_cat_face_with_smiling_eyes": "😸",
+956	    "grinning_face": "😀",
+957	    "grinning_face_with_big_eyes": "😃",
+958	    "grinning_face_with_smiling_eyes": "😄",
+959	    "grinning_face_with_sweat": "😅",
+960	    "grinning_squinting_face": "😆",
+961	    "growing_heart": "💗",
+962	    "guard": "💂",
+963	    "guard_dark_skin_tone": "💂🏿",
+964	    "guard_light_skin_tone": "💂🏻",
+965	    "guard_medium-dark_skin_tone": "💂🏾",
+966	    "guard_medium-light_skin_tone": "💂🏼",
+967	    "guard_medium_skin_tone": "💂🏽",
+968	    "guide_dog": "🦮",
+969	    "guitar": "🎸",
+970	    "hamburger": "🍔",
+971	    "hammer": "🔨",
+972	    "hammer_and_pick": "⚒",
+973	    "hammer_and_wrench": "🛠",
+974	    "hamster_face": "🐹",
+975	    "hand_with_fingers_splayed": "🖐",
+976	    "hand_with_fingers_splayed_dark_skin_tone": "🖐🏿",
+977	    "hand_with_fingers_splayed_light_skin_tone": "🖐🏻",
+978	    "hand_with_fingers_splayed_medium-dark_skin_tone": "🖐🏾",
+979	    "hand_with_fingers_splayed_medium-light_skin_tone": "🖐🏼",
+980	    "hand_with_fingers_splayed_medium_skin_tone": "🖐🏽",
+981	    "handbag": "👜",
+982	    "handshake": "🤝",
+983	    "hatching_chick": "🐣",
+984	    "headphone": "🎧",
+985	    "hear-no-evil_monkey": "🙉",
+986	    "heart_decoration": "💟",
+987	    "heart_suit": "♥",
+988	    "heart_with_arrow": "💘",
+989	    "heart_with_ribbon": "💝",
+990	    "heavy_check_mark": "✔",
+991	    "heavy_division_sign": "➗",
+992	    "heavy_dollar_sign": "💲",
+993	    "heavy_heart_exclamation": "❣",
+994	    "heavy_large_circle": "⭕",
+995	    "heavy_minus_sign": "➖",
+996	    "heavy_multiplication_x": "✖",
+997	    "heavy_plus_sign": "➕",
+998	    "hedgehog": "🦔",
+999	    "helicopter": "🚁",
+1000	    "herb": "🌿",
+1001	    "hibiscus": "🌺",
+1002	    "high-heeled_shoe": "👠",
+1003	    "high-speed_train": "🚄",
+1004	    "high_voltage": "⚡",
+1005	    "hiking_boot": "🥾",
+1006	    "hindu_temple": "🛕",
+1007	    "hippopotamus": "🦛",
+1008	    "hole": "🕳",
+1009	    "honey_pot": "🍯",
+1010	    "honeybee": "🐝",
+1011	    "horizontal_traffic_light": "🚥",
+1012	    "horse": "🐴",
+1013	    "horse_face": "🐴",
+1014	    "horse_racing": "🏇",
+1015	    "horse_racing_dark_skin_tone": "🏇🏿",
+1016	    "horse_racing_light_skin_tone": "🏇🏻",
+1017	    "horse_racing_medium-dark_skin_tone": "🏇🏾",
+1018	    "horse_racing_medium-light_skin_tone": "🏇🏼",
+1019	    "horse_racing_medium_skin_tone": "🏇🏽",
+1020	    "hospital": "🏥",
+1021	    "hot_beverage": "☕",
+1022	    "hot_dog": "🌭",
+1023	    "hot_face": "🥵",
+1024	    "hot_pepper": "🌶",
+1025	    "hot_springs": "♨",
+1026	    "hotel": "🏨",
+1027	    "hourglass_done": "⌛",
+1028	    "hourglass_not_done": "⏳",
+1029	    "house": "🏠",
+1030	    "house_with_garden": "🏡",
+1031	    "houses": "🏘",
+1032	    "hugging_face": "🤗",
+1033	    "hundred_points": "💯",
+1034	    "hushed_face": "😯",
+1035	    "ice": "🧊",
+1036	    "ice_cream": "🍨",
+1037	    "ice_hockey": "🏒",
+1038	    "ice_skate": "⛸",
+1039	    "inbox_tray": "📥",
+1040	    "incoming_envelope": "📨",
+1041	    "index_pointing_up": "☝",
+1042	    "index_pointing_up_dark_skin_tone": "☝🏿",
+1043	    "index_pointing_up_light_skin_tone": "☝🏻",
+1044	    "index_pointing_up_medium-dark_skin_tone": "☝🏾",
+1045	    "index_pointing_up_medium-light_skin_tone": "☝🏼",
+1046	    "index_pointing_up_medium_skin_tone": "☝🏽",
+1047	    "infinity": "♾",
+1048	    "information": "ℹ",
+1049	    "input_latin_letters": "🔤",
+1050	    "input_latin_lowercase": "🔡",
+1051	    "input_latin_uppercase": "🔠",
+1052	    "input_numbers": "🔢",
+1053	    "input_symbols": "🔣",
+1054	    "jack-o-lantern": "🎃",
+1055	    "jeans": "👖",
+1056	    "jigsaw": "🧩",
+1057	    "joker": "🃏",
+1058	    "joystick": "🕹",
+1059	    "kaaba": "🕋",
+1060	    "kangaroo": "🦘",
+1061	    "key": "🔑",
+1062	    "keyboard": "⌨",
+1063	    "keycap_#": "#️⃣",
+1064	    "keycap_*": "*️⃣",
+1065	    "keycap_0": "0️⃣",
+1066	    "keycap_1": "1️⃣",
+1067	    "keycap_10": "🔟",
+1068	    "keycap_2": "2️⃣",
+1069	    "keycap_3": "3️⃣",
+1070	    "keycap_4": "4️⃣",
+1071	    "keycap_5": "5️⃣",
+1072	    "keycap_6": "6️⃣",
+1073	    "keycap_7": "7️⃣",
+1074	    "keycap_8": "8️⃣",
+1075	    "keycap_9": "9️⃣",
+1076	    "kick_scooter": "🛴",
+1077	    "kimono": "👘",
+1078	    "kiss": "💋",
+1079	    "kiss_man_man": "👨\u200d❤️\u200d💋\u200d👨",
+1080	    "kiss_mark": "💋",
+1081	    "kiss_woman_man": "👩\u200d❤️\u200d💋\u200d👨",
+1082	    "kiss_woman_woman": "👩\u200d❤️\u200d💋\u200d👩",
+1083	    "kissing_cat_face": "😽",
+1084	    "kissing_face": "😗",
+1085	    "kissing_face_with_closed_eyes": "😚",
+1086	    "kissing_face_with_smiling_eyes": "😙",
+1087	    "kitchen_knife": "🔪",
+1088	    "kite": "🪁",
+1089	    "kiwi_fruit": "🥝",
+1090	    "koala": "🐨",
+1091	    "lab_coat": "🥼",
+1092	    "label": "🏷",
+1093	    "lacrosse": "🥍",
+1094	    "lady_beetle": "🐞",
+1095	    "laptop_computer": "💻",
+1096	    "large_blue_diamond": "🔷",
+1097	    "large_orange_diamond": "🔶",
+1098	    "last_quarter_moon": "🌗",
+1099	    "last_quarter_moon_face": "🌜",
+1100	    "last_track_button": "⏮",
+1101	    "latin_cross": "✝",
+1102	    "leaf_fluttering_in_wind": "🍃",
+1103	    "leafy_green": "🥬",
+1104	    "ledger": "📒",
+1105	    "left-facing_fist": "🤛",
+1106	    "left-facing_fist_dark_skin_tone": "🤛🏿",
+1107	    "left-facing_fist_light_skin_tone": "🤛🏻",
+1108	    "left-facing_fist_medium-dark_skin_tone": "🤛🏾",
+1109	    "left-facing_fist_medium-light_skin_tone": "🤛🏼",
+1110	    "left-facing_fist_medium_skin_tone": "🤛🏽",
+1111	    "left-right_arrow": "↔",
+1112	    "left_arrow": "⬅",
+1113	    "left_arrow_curving_right": "↪",
+1114	    "left_luggage": "🛅",
+1115	    "left_speech_bubble": "🗨",
+1116	    "leg": "🦵",
+1117	    "lemon": "🍋",
+1118	    "leopard": "🐆",
+1119	    "level_slider": "🎚",
+1120	    "light_bulb": "💡",
+1121	    "light_rail": "🚈",
+1122	    "link": "🔗",
+1123	    "linked_paperclips": "🖇",
+1124	    "lion_face": "🦁",
+1125	    "lipstick": "💄",
+1126	    "litter_in_bin_sign": "🚮",
+1127	    "lizard": "🦎",
+1128	    "llama": "🦙",
+1129	    "lobster": "🦞",
+1130	    "locked": "🔒",
+1131	    "locked_with_key": "🔐",
+1132	    "locked_with_pen": "🔏",
+1133	    "locomotive": "🚂",
+1134	    "lollipop": "🍭",
+1135	    "lotion_bottle": "🧴",
+1136	    "loudly_crying_face": "😭",
+1137	    "loudspeaker": "📢",
+1138	    "love-you_gesture": "🤟",
+1139	    "love-you_gesture_dark_skin_tone": "🤟🏿",
+1140	    "love-you_gesture_light_skin_tone": "🤟🏻",
+1141	    "love-you_gesture_medium-dark_skin_tone": "🤟🏾",
+1142	    "love-you_gesture_medium-light_skin_tone": "🤟🏼",
+1143	    "love-you_gesture_medium_skin_tone": "🤟🏽",
+1144	    "love_hotel": "🏩",
+1145	    "love_letter": "💌",
+1146	    "luggage": "🧳",
+1147	    "lying_face": "🤥",
+1148	    "mage": "🧙",
+1149	    "mage_dark_skin_tone": "🧙🏿",
+1150	    "mage_light_skin_tone": "🧙🏻",
+1151	    "mage_medium-dark_skin_tone": "🧙🏾",
+1152	    "mage_medium-light_skin_tone": "🧙🏼",
+1153	    "mage_medium_skin_tone": "🧙🏽",
+1154	    "magnet": "🧲",
+1155	    "magnifying_glass_tilted_left": "🔍",
+1156	    "magnifying_glass_tilted_right": "🔎",
+1157	    "mahjong_red_dragon": "🀄",
+1158	    "male_sign": "♂",
+1159	    "man": "👨",
+1160	    "man_and_woman_holding_hands": "👫",
+1161	    "man_artist": "👨\u200d🎨",
+1162	    "man_artist_dark_skin_tone": "👨🏿\u200d🎨",
+1163	    "man_artist_light_skin_tone": "👨🏻\u200d🎨",
+1164	    "man_artist_medium-dark_skin_tone": "👨🏾\u200d🎨",
+1165	    "man_artist_medium-light_skin_tone": "👨🏼\u200d🎨",
+1166	    "man_artist_medium_skin_tone": "👨🏽\u200d🎨",
+1167	    "man_astronaut": "👨\u200d🚀",
+1168	    "man_astronaut_dark_skin_tone": "👨🏿\u200d🚀",
+1169	    "man_astronaut_light_skin_tone": "👨🏻\u200d🚀",
+1170	    "man_astronaut_medium-dark_skin_tone": "👨🏾\u200d🚀",
+1171	    "man_astronaut_medium-light_skin_tone": "👨🏼\u200d🚀",
+1172	    "man_astronaut_medium_skin_tone": "👨🏽\u200d🚀",
+1173	    "man_biking": "🚴\u200d♂️",
+1174	    "man_biking_dark_skin_tone": "🚴🏿\u200d♂️",
+1175	    "man_biking_light_skin_tone": "🚴🏻\u200d♂️",
+1176	    "man_biking_medium-dark_skin_tone": "🚴🏾\u200d♂️",
+1177	    "man_biking_medium-light_skin_tone": "🚴🏼\u200d♂️",
+1178	    "man_biking_medium_skin_tone": "🚴🏽\u200d♂️",
+1179	    "man_bouncing_ball": "⛹️\u200d♂️",
+1180	    "man_bouncing_ball_dark_skin_tone": "⛹🏿\u200d♂️",
+1181	    "man_bouncing_ball_light_skin_tone": "⛹🏻\u200d♂️",
+1182	    "man_bouncing_ball_medium-dark_skin_tone": "⛹🏾\u200d♂️",
+1183	    "man_bouncing_ball_medium-light_skin_tone": "⛹🏼\u200d♂️",
+1184	    "man_bouncing_ball_medium_skin_tone": "⛹🏽\u200d♂️",
+1185	    "man_bowing": "🙇\u200d♂️",
+1186	    "man_bowing_dark_skin_tone": "🙇🏿\u200d♂️",
+1187	    "man_bowing_light_skin_tone": "🙇🏻\u200d♂️",
+1188	    "man_bowing_medium-dark_skin_tone": "🙇🏾\u200d♂️",
+1189	    "man_bowing_medium-light_skin_tone": "🙇🏼\u200d♂️",
+1190	    "man_bowing_medium_skin_tone": "🙇🏽\u200d♂️",
+1191	    "man_cartwheeling": "🤸\u200d♂️",
+1192	    "man_cartwheeling_dark_skin_tone": "🤸🏿\u200d♂️",
+1193	    "man_cartwheeling_light_skin_tone": "🤸🏻\u200d♂️",
+1194	    "man_cartwheeling_medium-dark_skin_tone": "🤸🏾\u200d♂️",
+1195	    "man_cartwheeling_medium-light_skin_tone": "🤸🏼\u200d♂️",
+1196	    "man_cartwheeling_medium_skin_tone": "🤸🏽\u200d♂️",
+1197	    "man_climbing": "🧗\u200d♂️",
+1198	    "man_climbing_dark_skin_tone": "🧗🏿\u200d♂️",
+1199	    "man_climbing_light_skin_tone": "🧗🏻\u200d♂️",
+1200	    "man_climbing_medium-dark_skin_tone": "🧗🏾\u200d♂️",
+1201	    "man_climbing_medium-light_skin_tone": "🧗🏼\u200d♂️",
+1202	    "man_climbing_medium_skin_tone": "🧗🏽\u200d♂️",
+1203	    "man_construction_worker": "👷\u200d♂️",
+1204	    "man_construction_worker_dark_skin_tone": "👷🏿\u200d♂️",
+1205	    "man_construction_worker_light_skin_tone": "👷🏻\u200d♂️",
+1206	    "man_construction_worker_medium-dark_skin_tone": "👷🏾\u200d♂️",
+1207	    "man_construction_worker_medium-light_skin_tone": "👷🏼\u200d♂️",
+1208	    "man_construction_worker_medium_skin_tone": "👷🏽\u200d♂️",
+1209	    "man_cook": "👨\u200d🍳",
+1210	    "man_cook_dark_skin_tone": "👨🏿\u200d🍳",
+1211	    "man_cook_light_skin_tone": "👨🏻\u200d🍳",
+1212	    "man_cook_medium-dark_skin_tone": "👨🏾\u200d🍳",
+1213	    "man_cook_medium-light_skin_tone": "👨🏼\u200d🍳",
+1214	    "man_cook_medium_skin_tone": "👨🏽\u200d🍳",
+1215	    "man_dancing": "🕺",
+1216	    "man_dancing_dark_skin_tone": "🕺🏿",
+1217	    "man_dancing_light_skin_tone": "🕺🏻",
+1218	    "man_dancing_medium-dark_skin_tone": "🕺🏾",
+1219	    "man_dancing_medium-light_skin_tone": "🕺🏼",
+1220	    "man_dancing_medium_skin_tone": "🕺🏽",
+1221	    "man_dark_skin_tone": "👨🏿",
+1222	    "man_detective": "🕵️\u200d♂️",
+1223	    "man_detective_dark_skin_tone": "🕵🏿\u200d♂️",
+1224	    "man_detective_light_skin_tone": "🕵🏻\u200d♂️",
+1225	    "man_detective_medium-dark_skin_tone": "🕵🏾\u200d♂️",
+1226	    "man_detective_medium-light_skin_tone": "🕵🏼\u200d♂️",
+1227	    "man_detective_medium_skin_tone": "🕵🏽\u200d♂️",
+1228	    "man_elf": "🧝\u200d♂️",
+1229	    "man_elf_dark_skin_tone": "🧝🏿\u200d♂️",
+1230	    "man_elf_light_skin_tone": "🧝🏻\u200d♂️",
+1231	    "man_elf_medium-dark_skin_tone": "🧝🏾\u200d♂️",
+1232	    "man_elf_medium-light_skin_tone": "🧝🏼\u200d♂️",
+1233	    "man_elf_medium_skin_tone": "🧝🏽\u200d♂️",
+1234	    "man_facepalming": "🤦\u200d♂️",
+1235	    "man_facepalming_dark_skin_tone": "🤦🏿\u200d♂️",
+1236	    "man_facepalming_light_skin_tone": "🤦🏻\u200d♂️",
+1237	    "man_facepalming_medium-dark_skin_tone": "🤦🏾\u200d♂️",
+1238	    "man_facepalming_medium-light_skin_tone": "🤦🏼\u200d♂️",
+1239	    "man_facepalming_medium_skin_tone": "🤦🏽\u200d♂️",
+1240	    "man_factory_worker": "👨\u200d🏭",
+1241	    "man_factory_worker_dark_skin_tone": "👨🏿\u200d🏭",
+1242	    "man_factory_worker_light_skin_tone": "👨🏻\u200d🏭",
+1243	    "man_factory_worker_medium-dark_skin_tone": "👨🏾\u200d🏭",
+1244	    "man_factory_worker_medium-light_skin_tone": "👨🏼\u200d🏭",
+1245	    "man_factory_worker_medium_skin_tone": "👨🏽\u200d🏭",
+1246	    "man_fairy": "🧚\u200d♂️",
+1247	    "man_fairy_dark_skin_tone": "🧚🏿\u200d♂️",
+1248	    "man_fairy_light_skin_tone": "🧚🏻\u200d♂️",
+1249	    "man_fairy_medium-dark_skin_tone": "🧚🏾\u200d♂️",
+1250	    "man_fairy_medium-light_skin_tone": "🧚🏼\u200d♂️",
+1251	    "man_fairy_medium_skin_tone": "🧚🏽\u200d♂️",
+1252	    "man_farmer": "👨\u200d🌾",
+1253	    "man_farmer_dark_skin_tone": "👨🏿\u200d🌾",
+1254	    "man_farmer_light_skin_tone": "👨🏻\u200d🌾",
+1255	    "man_farmer_medium-dark_skin_tone": "👨🏾\u200d🌾",
+1256	    "man_farmer_medium-light_skin_tone": "👨🏼\u200d🌾",
+1257	    "man_farmer_medium_skin_tone": "👨🏽\u200d🌾",
+1258	    "man_firefighter": "👨\u200d🚒",
+1259	    "man_firefighter_dark_skin_tone": "👨🏿\u200d🚒",
+1260	    "man_firefighter_light_skin_tone": "👨🏻\u200d🚒",
+1261	    "man_firefighter_medium-dark_skin_tone": "👨🏾\u200d🚒",
+1262	    "man_firefighter_medium-light_skin_tone": "👨🏼\u200d🚒",
+1263	    "man_firefighter_medium_skin_tone": "👨🏽\u200d🚒",
+1264	    "man_frowning": "🙍\u200d♂️",
+1265	    "man_frowning_dark_skin_tone": "🙍🏿\u200d♂️",
+1266	    "man_frowning_light_skin_tone": "🙍🏻\u200d♂️",
+1267	    "man_frowning_medium-dark_skin_tone": "🙍🏾\u200d♂️",
+1268	    "man_frowning_medium-light_skin_tone": "🙍🏼\u200d♂️",
+1269	    "man_frowning_medium_skin_tone": "🙍🏽\u200d♂️",
+1270	    "man_genie": "🧞\u200d♂️",
+1271	    "man_gesturing_no": "🙅\u200d♂️",
+1272	    "man_gesturing_no_dark_skin_tone": "🙅🏿\u200d♂️",
+1273	    "man_gesturing_no_light_skin_tone": "🙅🏻\u200d♂️",
+1274	    "man_gesturing_no_medium-dark_skin_tone": "🙅🏾\u200d♂️",
+1275	    "man_gesturing_no_medium-light_skin_tone": "🙅🏼\u200d♂️",
+1276	    "man_gesturing_no_medium_skin_tone": "🙅🏽\u200d♂️",
+1277	    "man_gesturing_ok": "🙆\u200d♂️",
+1278	    "man_gesturing_ok_dark_skin_tone": "🙆🏿\u200d♂️",
+1279	    "man_gesturing_ok_light_skin_tone": "🙆🏻\u200d♂️",
+1280	    "man_gesturing_ok_medium-dark_skin_tone": "🙆🏾\u200d♂️",
+1281	    "man_gesturing_ok_medium-light_skin_tone": "🙆🏼\u200d♂️",
+1282	    "man_gesturing_ok_medium_skin_tone": "🙆🏽\u200d♂️",
+1283	    "man_getting_haircut": "💇\u200d♂️",
+1284	    "man_getting_haircut_dark_skin_tone": "💇🏿\u200d♂️",
+1285	    "man_getting_haircut_light_skin_tone": "💇🏻\u200d♂️",
+1286	    "man_getting_haircut_medium-dark_skin_tone": "💇🏾\u200d♂️",
+1287	    "man_getting_haircut_medium-light_skin_tone": "💇🏼\u200d♂️",
+1288	    "man_getting_haircut_medium_skin_tone": "💇🏽\u200d♂️",
+1289	    "man_getting_massage": "💆\u200d♂️",
+1290	    "man_getting_massage_dark_skin_tone": "💆🏿\u200d♂️",
+1291	    "man_getting_massage_light_skin_tone": "💆🏻\u200d♂️",
+1292	    "man_getting_massage_medium-dark_skin_tone": "💆🏾\u200d♂️",
+1293	    "man_getting_massage_medium-light_skin_tone": "💆🏼\u200d♂️",
+1294	    "man_getting_massage_medium_skin_tone": "💆🏽\u200d♂️",
+1295	    "man_golfing": "🏌️\u200d♂️",
+1296	    "man_golfing_dark_skin_tone": "🏌🏿\u200d♂️",
+1297	    "man_golfing_light_skin_tone": "🏌🏻\u200d♂️",
+1298	    "man_golfing_medium-dark_skin_tone": "🏌🏾\u200d♂️",
+1299	    "man_golfing_medium-light_skin_tone": "🏌🏼\u200d♂️",
+1300	    "man_golfing_medium_skin_tone": "🏌🏽\u200d♂️",
+1301	    "man_guard": "💂\u200d♂️",
+1302	    "man_guard_dark_skin_tone": "💂🏿\u200d♂️",
+1303	    "man_guard_light_skin_tone": "💂🏻\u200d♂️",
+1304	    "man_guard_medium-dark_skin_tone": "💂🏾\u200d♂️",
+1305	    "man_guard_medium-light_skin_tone": "💂🏼\u200d♂️",
+1306	    "man_guard_medium_skin_tone": "💂🏽\u200d♂️",
+1307	    "man_health_worker": "👨\u200d⚕️",
+1308	    "man_health_worker_dark_skin_tone": "👨🏿\u200d⚕️",
+1309	    "man_health_worker_light_skin_tone": "👨🏻\u200d⚕️",
+1310	    "man_health_worker_medium-dark_skin_tone": "👨🏾\u200d⚕️",
+1311	    "man_health_worker_medium-light_skin_tone": "👨🏼\u200d⚕️",
+1312	    "man_health_worker_medium_skin_tone": "👨🏽\u200d⚕️",
+1313	    "man_in_lotus_position": "🧘\u200d♂️",
+1314	    "man_in_lotus_position_dark_skin_tone": "🧘🏿\u200d♂️",
+1315	    "man_in_lotus_position_light_skin_tone": "🧘🏻\u200d♂️",
+1316	    "man_in_lotus_position_medium-dark_skin_tone": "🧘🏾\u200d♂️",
+1317	    "man_in_lotus_position_medium-light_skin_tone": "🧘🏼\u200d♂️",
+1318	    "man_in_lotus_position_medium_skin_tone": "🧘🏽\u200d♂️",
+1319	    "man_in_manual_wheelchair": "👨\u200d🦽",
+1320	    "man_in_motorized_wheelchair": "👨\u200d🦼",
+1321	    "man_in_steamy_room": "🧖\u200d♂️",
+1322	    "man_in_steamy_room_dark_skin_tone": "🧖🏿\u200d♂️",
+1323	    "man_in_steamy_room_light_skin_tone": "🧖🏻\u200d♂️",
+1324	    "man_in_steamy_room_medium-dark_skin_tone": "🧖🏾\u200d♂️",
+1325	    "man_in_steamy_room_medium-light_skin_tone": "🧖🏼\u200d♂️",
+1326	    "man_in_steamy_room_medium_skin_tone": "🧖🏽\u200d♂️",
+1327	    "man_in_suit_levitating": "🕴",
+1328	    "man_in_suit_levitating_dark_skin_tone": "🕴🏿",
+1329	    "man_in_suit_levitating_light_skin_tone": "🕴🏻",
+1330	    "man_in_suit_levitating_medium-dark_skin_tone": "🕴🏾",
+1331	    "man_in_suit_levitating_medium-light_skin_tone": "🕴🏼",
+1332	    "man_in_suit_levitating_medium_skin_tone": "🕴🏽",
+1333	    "man_in_tuxedo": "🤵",
+1334	    "man_in_tuxedo_dark_skin_tone": "🤵🏿",
+1335	    "man_in_tuxedo_light_skin_tone": "🤵🏻",
+1336	    "man_in_tuxedo_medium-dark_skin_tone": "🤵🏾",
+1337	    "man_in_tuxedo_medium-light_skin_tone": "🤵🏼",
+1338	    "man_in_tuxedo_medium_skin_tone": "🤵🏽",
+1339	    "man_judge": "👨\u200d⚖️",
+1340	    "man_judge_dark_skin_tone": "👨🏿\u200d⚖️",
+1341	    "man_judge_light_skin_tone": "👨🏻\u200d⚖️",
+1342	    "man_judge_medium-dark_skin_tone": "👨🏾\u200d⚖️",
+1343	    "man_judge_medium-light_skin_tone": "👨🏼\u200d⚖️",
+1344	    "man_judge_medium_skin_tone": "👨🏽\u200d⚖️",
+1345	    "man_juggling": "🤹\u200d♂️",
+1346	    "man_juggling_dark_skin_tone": "🤹🏿\u200d♂️",
+1347	    "man_juggling_light_skin_tone": "🤹🏻\u200d♂️",
+1348	    "man_juggling_medium-dark_skin_tone": "🤹🏾\u200d♂️",
+1349	    "man_juggling_medium-light_skin_tone": "🤹🏼\u200d♂️",
+1350	    "man_juggling_medium_skin_tone": "🤹🏽\u200d♂️",
+1351	    "man_lifting_weights": "🏋️\u200d♂️",
+1352	    "man_lifting_weights_dark_skin_tone": "🏋🏿\u200d♂️",
+1353	    "man_lifting_weights_light_skin_tone": "🏋🏻\u200d♂️",
+1354	    "man_lifting_weights_medium-dark_skin_tone": "🏋🏾\u200d♂️",
+1355	    "man_lifting_weights_medium-light_skin_tone": "🏋🏼\u200d♂️",
+1356	    "man_lifting_weights_medium_skin_tone": "🏋🏽\u200d♂️",
+1357	    "man_light_skin_tone": "👨🏻",
+1358	    "man_mage": "🧙\u200d♂️",
+1359	    "man_mage_dark_skin_tone": "🧙🏿\u200d♂️",
+1360	    "man_mage_light_skin_tone": "🧙🏻\u200d♂️",
+1361	    "man_mage_medium-dark_skin_tone": "🧙🏾\u200d♂️",
+1362	    "man_mage_medium-light_skin_tone": "🧙🏼\u200d♂️",
+1363	    "man_mage_medium_skin_tone": "🧙🏽\u200d♂️",
+1364	    "man_mechanic": "👨\u200d🔧",
+1365	    "man_mechanic_dark_skin_tone": "👨🏿\u200d🔧",
+1366	    "man_mechanic_light_skin_tone": "👨🏻\u200d🔧",
+1367	    "man_mechanic_medium-dark_skin_tone": "👨🏾\u200d🔧",
+1368	    "man_mechanic_medium-light_skin_tone": "👨🏼\u200d🔧",
+1369	    "man_mechanic_medium_skin_tone": "👨🏽\u200d🔧",
+1370	    "man_medium-dark_skin_tone": "👨🏾",
+1371	    "man_medium-light_skin_tone": "👨🏼",
+1372	    "man_medium_skin_tone": "👨🏽",
+1373	    "man_mountain_biking": "🚵\u200d♂️",
+1374	    "man_mountain_biking_dark_skin_tone": "🚵🏿\u200d♂️",
+1375	    "man_mountain_biking_light_skin_tone": "🚵🏻\u200d♂️",
+1376	    "man_mountain_biking_medium-dark_skin_tone": "🚵🏾\u200d♂️",
+1377	    "man_mountain_biking_medium-light_skin_tone": "🚵🏼\u200d♂️",
+1378	    "man_mountain_biking_medium_skin_tone": "🚵🏽\u200d♂️",
+1379	    "man_office_worker": "👨\u200d💼",
+1380	    "man_office_worker_dark_skin_tone": "👨🏿\u200d💼",
+1381	    "man_office_worker_light_skin_tone": "👨🏻\u200d💼",
+1382	    "man_office_worker_medium-dark_skin_tone": "👨🏾\u200d💼",
+1383	    "man_office_worker_medium-light_skin_tone": "👨🏼\u200d💼",
+1384	    "man_office_worker_medium_skin_tone": "👨🏽\u200d💼",
+1385	    "man_pilot": "👨\u200d✈️",
+1386	    "man_pilot_dark_skin_tone": "👨🏿\u200d✈️",
+1387	    "man_pilot_light_skin_tone": "👨🏻\u200d✈️",
+1388	    "man_pilot_medium-dark_skin_tone": "👨🏾\u200d✈️",
+1389	    "man_pilot_medium-light_skin_tone": "👨🏼\u200d✈️",
+1390	    "man_pilot_medium_skin_tone": "👨🏽\u200d✈️",
+1391	    "man_playing_handball": "🤾\u200d♂️",
+1392	    "man_playing_handball_dark_skin_tone": "🤾🏿\u200d♂️",
+1393	    "man_playing_handball_light_skin_tone": "🤾🏻\u200d♂️",
+1394	    "man_playing_handball_medium-dark_skin_tone": "🤾🏾\u200d♂️",
+1395	    "man_playing_handball_medium-light_skin_tone": "🤾🏼\u200d♂️",
+1396	    "man_playing_handball_medium_skin_tone": "🤾🏽\u200d♂️",
+1397	    "man_playing_water_polo": "🤽\u200d♂️",
+1398	    "man_playing_water_polo_dark_skin_tone": "🤽🏿\u200d♂️",
+1399	    "man_playing_water_polo_light_skin_tone": "🤽🏻\u200d♂️",
+1400	    "man_playing_water_polo_medium-dark_skin_tone": "🤽🏾\u200d♂️",
+1401	    "man_playing_water_polo_medium-light_skin_tone": "🤽🏼\u200d♂️",
+1402	    "man_playing_water_polo_medium_skin_tone": "🤽🏽\u200d♂️",
+1403	    "man_police_officer": "👮\u200d♂️",
+1404	    "man_police_officer_dark_skin_tone": "👮🏿\u200d♂️",
+1405	    "man_police_officer_light_skin_tone": "👮🏻\u200d♂️",
+1406	    "man_police_officer_medium-dark_skin_tone": "👮🏾\u200d♂️",
+1407	    "man_police_officer_medium-light_skin_tone": "👮🏼\u200d♂️",
+1408	    "man_police_officer_medium_skin_tone": "👮🏽\u200d♂️",
+1409	    "man_pouting": "🙎\u200d♂️",
+1410	    "man_pouting_dark_skin_tone": "🙎🏿\u200d♂️",
+1411	    "man_pouting_light_skin_tone": "🙎🏻\u200d♂️",
+1412	    "man_pouting_medium-dark_skin_tone": "🙎🏾\u200d♂️",
+1413	    "man_pouting_medium-light_skin_tone": "🙎🏼\u200d♂️",
+1414	    "man_pouting_medium_skin_tone": "🙎🏽\u200d♂️",
+1415	    "man_raising_hand": "🙋\u200d♂️",
+1416	    "man_raising_hand_dark_skin_tone": "🙋🏿\u200d♂️",
+1417	    "man_raising_hand_light_skin_tone": "🙋🏻\u200d♂️",
+1418	    "man_raising_hand_medium-dark_skin_tone": "🙋🏾\u200d♂️",
+1419	    "man_raising_hand_medium-light_skin_tone": "🙋🏼\u200d♂️",
+1420	    "man_raising_hand_medium_skin_tone": "🙋🏽\u200d♂️",
+1421	    "man_rowing_boat": "🚣\u200d♂️",
+1422	    "man_rowing_boat_dark_skin_tone": "🚣🏿\u200d♂️",
+1423	    "man_rowing_boat_light_skin_tone": "🚣🏻\u200d♂️",
+1424	    "man_rowing_boat_medium-dark_skin_tone": "🚣🏾\u200d♂️",
+1425	    "man_rowing_boat_medium-light_skin_tone": "🚣🏼\u200d♂️",
+1426	    "man_rowing_boat_medium_skin_tone": "🚣🏽\u200d♂️",
+1427	    "man_running": "🏃\u200d♂️",
+1428	    "man_running_dark_skin_tone": "🏃🏿\u200d♂️",
+1429	    "man_running_light_skin_tone": "🏃🏻\u200d♂️",
+1430	    "man_running_medium-dark_skin_tone": "🏃🏾\u200d♂️",
+1431	    "man_running_medium-light_skin_tone": "🏃🏼\u200d♂️",
+1432	    "man_running_medium_skin_tone": "🏃🏽\u200d♂️",
+1433	    "man_scientist": "👨\u200d🔬",
+1434	    "man_scientist_dark_skin_tone": "👨🏿\u200d🔬",
+1435	    "man_scientist_light_skin_tone": "👨🏻\u200d🔬",
+1436	    "man_scientist_medium-dark_skin_tone": "👨🏾\u200d🔬",
+1437	    "man_scientist_medium-light_skin_tone": "👨🏼\u200d🔬",
+1438	    "man_scientist_medium_skin_tone": "👨🏽\u200d🔬",
+1439	    "man_shrugging": "🤷\u200d♂️",
+1440	    "man_shrugging_dark_skin_tone": "🤷🏿\u200d♂️",
+1441	    "man_shrugging_light_skin_tone": "🤷🏻\u200d♂️",
+1442	    "man_shrugging_medium-dark_skin_tone": "🤷🏾\u200d♂️",
+1443	    "man_shrugging_medium-light_skin_tone": "🤷🏼\u200d♂️",
+1444	    "man_shrugging_medium_skin_tone": "🤷🏽\u200d♂️",
+1445	    "man_singer": "👨\u200d🎤",
+1446	    "man_singer_dark_skin_tone": "👨🏿\u200d🎤",
+1447	    "man_singer_light_skin_tone": "👨🏻\u200d🎤",
+1448	    "man_singer_medium-dark_skin_tone": "👨🏾\u200d🎤",
+1449	    "man_singer_medium-light_skin_tone": "👨🏼\u200d🎤",
+1450	    "man_singer_medium_skin_tone": "👨🏽\u200d🎤",
+1451	    "man_student": "👨\u200d🎓",
+1452	    "man_student_dark_skin_tone": "👨🏿\u200d🎓",
+1453	    "man_student_light_skin_tone": "👨🏻\u200d🎓",
+1454	    "man_student_medium-dark_skin_tone": "👨🏾\u200d🎓",
+1455	    "man_student_medium-light_skin_tone": "👨🏼\u200d🎓",
+1456	    "man_student_medium_skin_tone": "👨🏽\u200d🎓",
+1457	    "man_surfing": "🏄\u200d♂️",
+1458	    "man_surfing_dark_skin_tone": "🏄🏿\u200d♂️",
+1459	    "man_surfing_light_skin_tone": "🏄🏻\u200d♂️",
+1460	    "man_surfing_medium-dark_skin_tone": "🏄🏾\u200d♂️",
+1461	    "man_surfing_medium-light_skin_tone": "🏄🏼\u200d♂️",
+1462	    "man_surfing_medium_skin_tone": "🏄🏽\u200d♂️",
+1463	    "man_swimming": "🏊\u200d♂️",
+1464	    "man_swimming_dark_skin_tone": "🏊🏿\u200d♂️",
+1465	    "man_swimming_light_skin_tone": "🏊🏻\u200d♂️",
+1466	    "man_swimming_medium-dark_skin_tone": "🏊🏾\u200d♂️",
+1467	    "man_swimming_medium-light_skin_tone": "🏊🏼\u200d♂️",
+1468	    "man_swimming_medium_skin_tone": "🏊🏽\u200d♂️",
+1469	    "man_teacher": "👨\u200d🏫",
+1470	    "man_teacher_dark_skin_tone": "👨🏿\u200d🏫",
+1471	    "man_teacher_light_skin_tone": "👨🏻\u200d🏫",
+1472	    "man_teacher_medium-dark_skin_tone": "👨🏾\u200d🏫",
+1473	    "man_teacher_medium-light_skin_tone": "👨🏼\u200d🏫",
+1474	    "man_teacher_medium_skin_tone": "👨🏽\u200d🏫",
+1475	    "man_technologist": "👨\u200d💻",
+1476	    "man_technologist_dark_skin_tone": "👨🏿\u200d💻",
+1477	    "man_technologist_light_skin_tone": "👨🏻\u200d💻",
+1478	    "man_technologist_medium-dark_skin_tone": "👨🏾\u200d💻",
+1479	    "man_technologist_medium-light_skin_tone": "👨🏼\u200d💻",
+1480	    "man_technologist_medium_skin_tone": "👨🏽\u200d💻",
+1481	    "man_tipping_hand": "💁\u200d♂️",
+1482	    "man_tipping_hand_dark_skin_tone": "💁🏿\u200d♂️",
+1483	    "man_tipping_hand_light_skin_tone": "💁🏻\u200d♂️",
+1484	    "man_tipping_hand_medium-dark_skin_tone": "💁🏾\u200d♂️",
+1485	    "man_tipping_hand_medium-light_skin_tone": "💁🏼\u200d♂️",
+1486	    "man_tipping_hand_medium_skin_tone": "💁🏽\u200d♂️",
+1487	    "man_vampire": "🧛\u200d♂️",
+1488	    "man_vampire_dark_skin_tone": "🧛🏿\u200d♂️",
+1489	    "man_vampire_light_skin_tone": "🧛🏻\u200d♂️",
+1490	    "man_vampire_medium-dark_skin_tone": "🧛🏾\u200d♂️",
+1491	    "man_vampire_medium-light_skin_tone": "🧛🏼\u200d♂️",
+1492	    "man_vampire_medium_skin_tone": "🧛🏽\u200d♂️",
+1493	    "man_walking": "🚶\u200d♂️",
+1494	    "man_walking_dark_skin_tone": "🚶🏿\u200d♂️",
+1495	    "man_walking_light_skin_tone": "🚶🏻\u200d♂️",
+1496	    "man_walking_medium-dark_skin_tone": "🚶🏾\u200d♂️",
+1497	    "man_walking_medium-light_skin_tone": "🚶🏼\u200d♂️",
+1498	    "man_walking_medium_skin_tone": "🚶🏽\u200d♂️",
+1499	    "man_wearing_turban": "👳\u200d♂️",
+1500	    "man_wearing_turban_dark_skin_tone": "👳🏿\u200d♂️",
+1501	    "man_wearing_turban_light_skin_tone": "👳🏻\u200d♂️",
+1502	    "man_wearing_turban_medium-dark_skin_tone": "👳🏾\u200d♂️",
+1503	    "man_wearing_turban_medium-light_skin_tone": "👳🏼\u200d♂️",
+1504	    "man_wearing_turban_medium_skin_tone": "👳🏽\u200d♂️",
+1505	    "man_with_probing_cane": "👨\u200d🦯",
+1506	    "man_with_chinese_cap": "👲",
+1507	    "man_with_chinese_cap_dark_skin_tone": "👲🏿",
+1508	    "man_with_chinese_cap_light_skin_tone": "👲🏻",
+1509	    "man_with_chinese_cap_medium-dark_skin_tone": "👲🏾",
+1510	    "man_with_chinese_cap_medium-light_skin_tone": "👲🏼",
+1511	    "man_with_chinese_cap_medium_skin_tone": "👲🏽",
+1512	    "man_zombie": "🧟\u200d♂️",
+1513	    "mango": "🥭",
+1514	    "mantelpiece_clock": "🕰",
+1515	    "manual_wheelchair": "🦽",
+1516	    "man’s_shoe": "👞",
+1517	    "map_of_japan": "🗾",
+1518	    "maple_leaf": "🍁",
+1519	    "martial_arts_uniform": "🥋",
+1520	    "mate": "🧉",
+1521	    "meat_on_bone": "🍖",
+1522	    "mechanical_arm": "🦾",
+1523	    "mechanical_leg": "🦿",
+1524	    "medical_symbol": "⚕",
+1525	    "megaphone": "📣",
+1526	    "melon": "🍈",
+1527	    "memo": "📝",
+1528	    "men_with_bunny_ears": "👯\u200d♂️",
+1529	    "men_wrestling": "🤼\u200d♂️",
+1530	    "menorah": "🕎",
+1531	    "men’s_room": "🚹",
+1532	    "mermaid": "🧜\u200d♀️",
+1533	    "mermaid_dark_skin_tone": "🧜🏿\u200d♀️",
+1534	    "mermaid_light_skin_tone": "🧜🏻\u200d♀️",
+1535	    "mermaid_medium-dark_skin_tone": "🧜🏾\u200d♀️",
+1536	    "mermaid_medium-light_skin_tone": "🧜🏼\u200d♀️",
+1537	    "mermaid_medium_skin_tone": "🧜🏽\u200d♀️",
+1538	    "merman": "🧜\u200d♂️",
+1539	    "merman_dark_skin_tone": "🧜🏿\u200d♂️",
+1540	    "merman_light_skin_tone": "🧜🏻\u200d♂️",
+1541	    "merman_medium-dark_skin_tone": "🧜🏾\u200d♂️",
+1542	    "merman_medium-light_skin_tone": "🧜🏼\u200d♂️",
+1543	    "merman_medium_skin_tone": "🧜🏽\u200d♂️",
+1544	    "merperson": "🧜",
+1545	    "merperson_dark_skin_tone": "🧜🏿",
+1546	    "merperson_light_skin_tone": "🧜🏻",
+1547	    "merperson_medium-dark_skin_tone": "🧜🏾",
+1548	    "merperson_medium-light_skin_tone": "🧜🏼",
+1549	    "merperson_medium_skin_tone": "🧜🏽",
+1550	    "metro": "🚇",
+1551	    "microbe": "🦠",
+1552	    "microphone": "🎤",
+1553	    "microscope": "🔬",
+1554	    "middle_finger": "🖕",
+1555	    "middle_finger_dark_skin_tone": "🖕🏿",
+1556	    "middle_finger_light_skin_tone": "🖕🏻",
+1557	    "middle_finger_medium-dark_skin_tone": "🖕🏾",
+1558	    "middle_finger_medium-light_skin_tone": "🖕🏼",
+1559	    "middle_finger_medium_skin_tone": "🖕🏽",
+1560	    "military_medal": "🎖",
+1561	    "milky_way": "🌌",
+1562	    "minibus": "🚐",
+1563	    "moai": "🗿",
+1564	    "mobile_phone": "📱",
+1565	    "mobile_phone_off": "📴",
+1566	    "mobile_phone_with_arrow": "📲",
+1567	    "money-mouth_face": "🤑",
+1568	    "money_bag": "💰",
+1569	    "money_with_wings": "💸",
+1570	    "monkey": "🐒",
+1571	    "monkey_face": "🐵",
+1572	    "monorail": "🚝",
+1573	    "moon_cake": "🥮",
+1574	    "moon_viewing_ceremony": "🎑",
+1575	    "mosque": "🕌",
+1576	    "mosquito": "🦟",
+1577	    "motor_boat": "🛥",
+1578	    "motor_scooter": "🛵",
+1579	    "motorcycle": "🏍",
+1580	    "motorized_wheelchair": "🦼",
+1581	    "motorway": "🛣",
+1582	    "mount_fuji": "🗻",
+1583	    "mountain": "⛰",
+1584	    "mountain_cableway": "🚠",
+1585	    "mountain_railway": "🚞",
+1586	    "mouse": "🐭",
+1587	    "mouse_face": "🐭",
+1588	    "mouth": "👄",
+1589	    "movie_camera": "🎥",
+1590	    "mushroom": "🍄",
+1591	    "musical_keyboard": "🎹",
+1592	    "musical_note": "🎵",
+1593	    "musical_notes": "🎶",
+1594	    "musical_score": "🎼",
+1595	    "muted_speaker": "🔇",
+1596	    "nail_polish": "💅",
+1597	    "nail_polish_dark_skin_tone": "💅🏿",
+1598	    "nail_polish_light_skin_tone": "💅🏻",
+1599	    "nail_polish_medium-dark_skin_tone": "💅🏾",
+1600	    "nail_polish_medium-light_skin_tone": "💅🏼",
+1601	    "nail_polish_medium_skin_tone": "💅🏽",
+1602	    "name_badge": "📛",
+1603	    "national_park": "🏞",
+1604	    "nauseated_face": "🤢",
+1605	    "nazar_amulet": "🧿",
+1606	    "necktie": "👔",
+1607	    "nerd_face": "🤓",
+1608	    "neutral_face": "😐",
+1609	    "new_moon": "🌑",
+1610	    "new_moon_face": "🌚",
+1611	    "newspaper": "📰",
+1612	    "next_track_button": "⏭",
+1613	    "night_with_stars": "🌃",
+1614	    "nine-thirty": "🕤",
+1615	    "nine_o’clock": "🕘",
+1616	    "no_bicycles": "🚳",
+1617	    "no_entry": "⛔",
+1618	    "no_littering": "🚯",
+1619	    "no_mobile_phones": "📵",
+1620	    "no_one_under_eighteen": "🔞",
+1621	    "no_pedestrians": "🚷",
+1622	    "no_smoking": "🚭",
+1623	    "non-potable_water": "🚱",
+1624	    "nose": "👃",
+1625	    "nose_dark_skin_tone": "👃🏿",
+1626	    "nose_light_skin_tone": "👃🏻",
+1627	    "nose_medium-dark_skin_tone": "👃🏾",
+1628	    "nose_medium-light_skin_tone": "👃🏼",
+1629	    "nose_medium_skin_tone": "👃🏽",
+1630	    "notebook": "📓",
+1631	    "notebook_with_decorative_cover": "📔",
+1632	    "nut_and_bolt": "🔩",
+1633	    "octopus": "🐙",
+1634	    "oden": "🍢",
+1635	    "office_building": "🏢",
+1636	    "ogre": "👹",
+1637	    "oil_drum": "🛢",
+1638	    "old_key": "🗝",
+1639	    "old_man": "👴",
+1640	    "old_man_dark_skin_tone": "👴🏿",
+1641	    "old_man_light_skin_tone": "👴🏻",
+1642	    "old_man_medium-dark_skin_tone": "👴🏾",
+1643	    "old_man_medium-light_skin_tone": "👴🏼",
+1644	    "old_man_medium_skin_tone": "👴🏽",
+1645	    "old_woman": "👵",
+1646	    "old_woman_dark_skin_tone": "👵🏿",
+1647	    "old_woman_light_skin_tone": "👵🏻",
+1648	    "old_woman_medium-dark_skin_tone": "👵🏾",
+1649	    "old_woman_medium-light_skin_tone": "👵🏼",
+1650	    "old_woman_medium_skin_tone": "👵🏽",
+1651	    "older_adult": "🧓",
+1652	    "older_adult_dark_skin_tone": "🧓🏿",
+1653	    "older_adult_light_skin_tone": "🧓🏻",
+1654	    "older_adult_medium-dark_skin_tone": "🧓🏾",
+1655	    "older_adult_medium-light_skin_tone": "🧓🏼",
+1656	    "older_adult_medium_skin_tone": "🧓🏽",
+1657	    "om": "🕉",
+1658	    "oncoming_automobile": "🚘",
+1659	    "oncoming_bus": "🚍",
+1660	    "oncoming_fist": "👊",
+1661	    "oncoming_fist_dark_skin_tone": "👊🏿",
+1662	    "oncoming_fist_light_skin_tone": "👊🏻",
+1663	    "oncoming_fist_medium-dark_skin_tone": "👊🏾",
+1664	    "oncoming_fist_medium-light_skin_tone": "👊🏼",
+1665	    "oncoming_fist_medium_skin_tone": "👊🏽",
+1666	    "oncoming_police_car": "🚔",
+1667	    "oncoming_taxi": "🚖",
+1668	    "one-piece_swimsuit": "🩱",
+1669	    "one-thirty": "🕜",
+1670	    "one_o’clock": "🕐",
+1671	    "onion": "🧅",
+1672	    "open_book": "📖",
+1673	    "open_file_folder": "📂",
+1674	    "open_hands": "👐",
+1675	    "open_hands_dark_skin_tone": "👐🏿",
+1676	    "open_hands_light_skin_tone": "👐🏻",
+1677	    "open_hands_medium-dark_skin_tone": "👐🏾",
+1678	    "open_hands_medium-light_skin_tone": "👐🏼",
+1679	    "open_hands_medium_skin_tone": "👐🏽",
+1680	    "open_mailbox_with_lowered_flag": "📭",
+1681	    "open_mailbox_with_raised_flag": "📬",
+1682	    "optical_disk": "💿",
+1683	    "orange_book": "📙",
+1684	    "orange_circle": "🟠",
+1685	    "orange_heart": "🧡",
+1686	    "orange_square": "🟧",
+1687	    "orangutan": "🦧",
+1688	    "orthodox_cross": "☦",
+1689	    "otter": "🦦",
+1690	    "outbox_tray": "📤",
+1691	    "owl": "🦉",
+1692	    "ox": "🐂",
+1693	    "oyster": "🦪",
+1694	    "package": "📦",
+1695	    "page_facing_up": "📄",
+1696	    "page_with_curl": "📃",
+1697	    "pager": "📟",
+1698	    "paintbrush": "🖌",
+1699	    "palm_tree": "🌴",
+1700	    "palms_up_together": "🤲",
+1701	    "palms_up_together_dark_skin_tone": "🤲🏿",
+1702	    "palms_up_together_light_skin_tone": "🤲🏻",
+1703	    "palms_up_together_medium-dark_skin_tone": "🤲🏾",
+1704	    "palms_up_together_medium-light_skin_tone": "🤲🏼",
+1705	    "palms_up_together_medium_skin_tone": "🤲🏽",
+1706	    "pancakes": "🥞",
+1707	    "panda_face": "🐼",
+1708	    "paperclip": "📎",
+1709	    "parrot": "🦜",
+1710	    "part_alternation_mark": "〽",
+1711	    "party_popper": "🎉",
+1712	    "partying_face": "🥳",
+1713	    "passenger_ship": "🛳",
+1714	    "passport_control": "🛂",
+1715	    "pause_button": "⏸",
+1716	    "paw_prints": "🐾",
+1717	    "peace_symbol": "☮",
+1718	    "peach": "🍑",
+1719	    "peacock": "🦚",
+1720	    "peanuts": "🥜",
+1721	    "pear": "🍐",
+1722	    "pen": "🖊",
+1723	    "pencil": "📝",
+1724	    "penguin": "🐧",
+1725	    "pensive_face": "😔",
+1726	    "people_holding_hands": "🧑\u200d🤝\u200d🧑",
+1727	    "people_with_bunny_ears": "👯",
+1728	    "people_wrestling": "🤼",
+1729	    "performing_arts": "🎭",
+1730	    "persevering_face": "😣",
+1731	    "person_biking": "🚴",
+1732	    "person_biking_dark_skin_tone": "🚴🏿",
+1733	    "person_biking_light_skin_tone": "🚴🏻",
+1734	    "person_biking_medium-dark_skin_tone": "🚴🏾",
+1735	    "person_biking_medium-light_skin_tone": "🚴🏼",
+1736	    "person_biking_medium_skin_tone": "🚴🏽",
+1737	    "person_bouncing_ball": "⛹",
+1738	    "person_bouncing_ball_dark_skin_tone": "⛹🏿",
+1739	    "person_bouncing_ball_light_skin_tone": "⛹🏻",
+1740	    "person_bouncing_ball_medium-dark_skin_tone": "⛹🏾",
+1741	    "person_bouncing_ball_medium-light_skin_tone": "⛹🏼",
+1742	    "person_bouncing_ball_medium_skin_tone": "⛹🏽",
+1743	    "person_bowing": "🙇",
+1744	    "person_bowing_dark_skin_tone": "🙇🏿",
+1745	    "person_bowing_light_skin_tone": "🙇🏻",
+1746	    "person_bowing_medium-dark_skin_tone": "🙇🏾",
+1747	    "person_bowing_medium-light_skin_tone": "🙇🏼",
+1748	    "person_bowing_medium_skin_tone": "🙇🏽",
+1749	    "person_cartwheeling": "🤸",
+1750	    "person_cartwheeling_dark_skin_tone": "🤸🏿",
+1751	    "person_cartwheeling_light_skin_tone": "🤸🏻",
+1752	    "person_cartwheeling_medium-dark_skin_tone": "🤸🏾",
+1753	    "person_cartwheeling_medium-light_skin_tone": "🤸🏼",
+1754	    "person_cartwheeling_medium_skin_tone": "🤸🏽",
+1755	    "person_climbing": "🧗",
+1756	    "person_climbing_dark_skin_tone": "🧗🏿",
+1757	    "person_climbing_light_skin_tone": "🧗🏻",
+1758	    "person_climbing_medium-dark_skin_tone": "🧗🏾",
+1759	    "person_climbing_medium-light_skin_tone": "🧗🏼",
+1760	    "person_climbing_medium_skin_tone": "🧗🏽",
+1761	    "person_facepalming": "🤦",
+1762	    "person_facepalming_dark_skin_tone": "🤦🏿",
+1763	    "person_facepalming_light_skin_tone": "🤦🏻",
+1764	    "person_facepalming_medium-dark_skin_tone": "🤦🏾",
+1765	    "person_facepalming_medium-light_skin_tone": "🤦🏼",
+1766	    "person_facepalming_medium_skin_tone": "🤦🏽",
+1767	    "person_fencing": "🤺",
+1768	    "person_frowning": "🙍",
+1769	    "person_frowning_dark_skin_tone": "🙍🏿",
+1770	    "person_frowning_light_skin_tone": "🙍🏻",
+1771	    "person_frowning_medium-dark_skin_tone": "🙍🏾",
+1772	    "person_frowning_medium-light_skin_tone": "🙍🏼",
+1773	    "person_frowning_medium_skin_tone": "🙍🏽",
+1774	    "person_gesturing_no": "🙅",
+1775	    "person_gesturing_no_dark_skin_tone": "🙅🏿",
+1776	    "person_gesturing_no_light_skin_tone": "🙅🏻",
+1777	    "person_gesturing_no_medium-dark_skin_tone": "🙅🏾",
+1778	    "person_gesturing_no_medium-light_skin_tone": "🙅🏼",
+1779	    "person_gesturing_no_medium_skin_tone": "🙅🏽",
+1780	    "person_gesturing_ok": "🙆",
+1781	    "person_gesturing_ok_dark_skin_tone": "🙆🏿",
+1782	    "person_gesturing_ok_light_skin_tone": "🙆🏻",
+1783	    "person_gesturing_ok_medium-dark_skin_tone": "🙆🏾",
+1784	    "person_gesturing_ok_medium-light_skin_tone": "🙆🏼",
+1785	    "person_gesturing_ok_medium_skin_tone": "🙆🏽",
+1786	    "person_getting_haircut": "💇",
+1787	    "person_getting_haircut_dark_skin_tone": "💇🏿",
+1788	    "person_getting_haircut_light_skin_tone": "💇🏻",
+1789	    "person_getting_haircut_medium-dark_skin_tone": "💇🏾",
+1790	    "person_getting_haircut_medium-light_skin_tone": "💇🏼",
+1791	    "person_getting_haircut_medium_skin_tone": "💇🏽",
+1792	    "person_getting_massage": "💆",
+1793	    "person_getting_massage_dark_skin_tone": "💆🏿",
+1794	    "person_getting_massage_light_skin_tone": "💆🏻",
+1795	    "person_getting_massage_medium-dark_skin_tone": "💆🏾",
+1796	    "person_getting_massage_medium-light_skin_tone": "💆🏼",
+1797	    "person_getting_massage_medium_skin_tone": "💆🏽",
+1798	    "person_golfing": "🏌",
+1799	    "person_golfing_dark_skin_tone": "🏌🏿",
+1800	    "person_golfing_light_skin_tone": "🏌🏻",
+1801	    "person_golfing_medium-dark_skin_tone": "🏌🏾",
+1802	    "person_golfing_medium-light_skin_tone": "🏌🏼",
+1803	    "person_golfing_medium_skin_tone": "🏌🏽",
+1804	    "person_in_bed": "🛌",
+1805	    "person_in_bed_dark_skin_tone": "🛌🏿",
+1806	    "person_in_bed_light_skin_tone": "🛌🏻",
+1807	    "person_in_bed_medium-dark_skin_tone": "🛌🏾",
+1808	    "person_in_bed_medium-light_skin_tone": "🛌🏼",
+1809	    "person_in_bed_medium_skin_tone": "🛌🏽",
+1810	    "person_in_lotus_position": "🧘",
+1811	    "person_in_lotus_position_dark_skin_tone": "🧘🏿",
+1812	    "person_in_lotus_position_light_skin_tone": "🧘🏻",
+1813	    "person_in_lotus_position_medium-dark_skin_tone": "🧘🏾",
+1814	    "person_in_lotus_position_medium-light_skin_tone": "🧘🏼",
+1815	    "person_in_lotus_position_medium_skin_tone": "🧘🏽",
+1816	    "person_in_steamy_room": "🧖",
+1817	    "person_in_steamy_room_dark_skin_tone": "🧖🏿",
+1818	    "person_in_steamy_room_light_skin_tone": "🧖🏻",
+1819	    "person_in_steamy_room_medium-dark_skin_tone": "🧖🏾",
+1820	    "person_in_steamy_room_medium-light_skin_tone": "🧖🏼",
+1821	    "person_in_steamy_room_medium_skin_tone": "🧖🏽",
+1822	    "person_juggling": "🤹",
+1823	    "person_juggling_dark_skin_tone": "🤹🏿",
+1824	    "person_juggling_light_skin_tone": "🤹🏻",
+1825	    "person_juggling_medium-dark_skin_tone": "🤹🏾",
+1826	    "person_juggling_medium-light_skin_tone": "🤹🏼",
+1827	    "person_juggling_medium_skin_tone": "🤹🏽",
+1828	    "person_kneeling": "🧎",
+1829	    "person_lifting_weights": "🏋",
+1830	    "person_lifting_weights_dark_skin_tone": "🏋🏿",
+1831	    "person_lifting_weights_light_skin_tone": "🏋🏻",
+1832	    "person_lifting_weights_medium-dark_skin_tone": "🏋🏾",
+1833	    "person_lifting_weights_medium-light_skin_tone": "🏋🏼",
+1834	    "person_lifting_weights_medium_skin_tone": "🏋🏽",
+1835	    "person_mountain_biking": "🚵",
+1836	    "person_mountain_biking_dark_skin_tone": "🚵🏿",
+1837	    "person_mountain_biking_light_skin_tone": "🚵🏻",
+1838	    "person_mountain_biking_medium-dark_skin_tone": "🚵🏾",
+1839	    "person_mountain_biking_medium-light_skin_tone": "🚵🏼",
+1840	    "person_mountain_biking_medium_skin_tone": "🚵🏽",
+1841	    "person_playing_handball": "🤾",
+1842	    "person_playing_handball_dark_skin_tone": "🤾🏿",
+1843	    "person_playing_handball_light_skin_tone": "🤾🏻",
+1844	    "person_playing_handball_medium-dark_skin_tone": "🤾🏾",
+1845	    "person_playing_handball_medium-light_skin_tone": "🤾🏼",
+1846	    "person_playing_handball_medium_skin_tone": "🤾🏽",
+1847	    "person_playing_water_polo": "🤽",
+1848	    "person_playing_water_polo_dark_skin_tone": "🤽🏿",
+1849	    "person_playing_water_polo_light_skin_tone": "🤽🏻",
+1850	    "person_playing_water_polo_medium-dark_skin_tone": "🤽🏾",
+1851	    "person_playing_water_polo_medium-light_skin_tone": "🤽🏼",
+1852	    "person_playing_water_polo_medium_skin_tone": "🤽🏽",
+1853	    "person_pouting": "🙎",
+1854	    "person_pouting_dark_skin_tone": "🙎🏿",
+1855	    "person_pouting_light_skin_tone": "🙎🏻",
+1856	    "person_pouting_medium-dark_skin_tone": "🙎🏾",
+1857	    "person_pouting_medium-light_skin_tone": "🙎🏼",
+1858	    "person_pouting_medium_skin_tone": "🙎🏽",
+1859	    "person_raising_hand": "🙋",
+1860	    "person_raising_hand_dark_skin_tone": "🙋🏿",
+1861	    "person_raising_hand_light_skin_tone": "🙋🏻",
+1862	    "person_raising_hand_medium-dark_skin_tone": "🙋🏾",
+1863	    "person_raising_hand_medium-light_skin_tone": "🙋🏼",
+1864	    "person_raising_hand_medium_skin_tone": "🙋🏽",
+1865	    "person_rowing_boat": "🚣",
+1866	    "person_rowing_boat_dark_skin_tone": "🚣🏿",
+1867	    "person_rowing_boat_light_skin_tone": "🚣🏻",
+1868	    "person_rowing_boat_medium-dark_skin_tone": "🚣🏾",
+1869	    "person_rowing_boat_medium-light_skin_tone": "🚣🏼",
+1870	    "person_rowing_boat_medium_skin_tone": "🚣🏽",
+1871	    "person_running": "🏃",
+1872	    "person_running_dark_skin_tone": "🏃🏿",
+1873	    "person_running_light_skin_tone": "🏃🏻",
+1874	    "person_running_medium-dark_skin_tone": "🏃🏾",
+1875	    "person_running_medium-light_skin_tone": "🏃🏼",
+1876	    "person_running_medium_skin_tone": "🏃🏽",
+1877	    "person_shrugging": "🤷",
+1878	    "person_shrugging_dark_skin_tone": "🤷🏿",
+1879	    "person_shrugging_light_skin_tone": "🤷🏻",
+1880	    "person_shrugging_medium-dark_skin_tone": "🤷🏾",
+1881	    "person_shrugging_medium-light_skin_tone": "🤷🏼",
+1882	    "person_shrugging_medium_skin_tone": "🤷🏽",
+1883	    "person_standing": "🧍",
+1884	    "person_surfing": "🏄",
+1885	    "person_surfing_dark_skin_tone": "🏄🏿",
+1886	    "person_surfing_light_skin_tone": "🏄🏻",
+1887	    "person_surfing_medium-dark_skin_tone": "🏄🏾",
+1888	    "person_surfing_medium-light_skin_tone": "🏄🏼",
+1889	    "person_surfing_medium_skin_tone": "🏄🏽",
+1890	    "person_swimming": "🏊",
+1891	    "person_swimming_dark_skin_tone": "🏊🏿",
+1892	    "person_swimming_light_skin_tone": "🏊🏻",
+1893	    "person_swimming_medium-dark_skin_tone": "🏊🏾",
+1894	    "person_swimming_medium-light_skin_tone": "🏊🏼",
+1895	    "person_swimming_medium_skin_tone": "🏊🏽",
+1896	    "person_taking_bath": "🛀",
+1897	    "person_taking_bath_dark_skin_tone": "🛀🏿",
+1898	    "person_taking_bath_light_skin_tone": "🛀🏻",
+1899	    "person_taking_bath_medium-dark_skin_tone": "🛀🏾",
+1900	    "person_taking_bath_medium-light_skin_tone": "🛀🏼",
+1901	    "person_taking_bath_medium_skin_tone": "🛀🏽",
+1902	    "person_tipping_hand": "💁",
+1903	    "person_tipping_hand_dark_skin_tone": "💁🏿",
+1904	    "person_tipping_hand_light_skin_tone": "💁🏻",
+1905	    "person_tipping_hand_medium-dark_skin_tone": "💁🏾",
+1906	    "person_tipping_hand_medium-light_skin_tone": "💁🏼",
+1907	    "person_tipping_hand_medium_skin_tone": "💁🏽",
+1908	    "person_walking": "🚶",
+1909	    "person_walking_dark_skin_tone": "🚶🏿",
+1910	    "person_walking_light_skin_tone": "🚶🏻",
+1911	    "person_walking_medium-dark_skin_tone": "🚶🏾",
+1912	    "person_walking_medium-light_skin_tone": "🚶🏼",
+1913	    "person_walking_medium_skin_tone": "🚶🏽",
+1914	    "person_wearing_turban": "👳",
+1915	    "person_wearing_turban_dark_skin_tone": "👳🏿",
+1916	    "person_wearing_turban_light_skin_tone": "👳🏻",
+1917	    "person_wearing_turban_medium-dark_skin_tone": "👳🏾",
+1918	    "person_wearing_turban_medium-light_skin_tone": "👳🏼",
+1919	    "person_wearing_turban_medium_skin_tone": "👳🏽",
+1920	    "petri_dish": "🧫",
+1921	    "pick": "⛏",
+1922	    "pie": "🥧",
+1923	    "pig": "🐷",
+1924	    "pig_face": "🐷",
+1925	    "pig_nose": "🐽",
+1926	    "pile_of_poo": "💩",
+1927	    "pill": "💊",
+1928	    "pinching_hand": "🤏",
+1929	    "pine_decoration": "🎍",
+1930	    "pineapple": "🍍",
+1931	    "ping_pong": "🏓",
+1932	    "pirate_flag": "🏴\u200d☠️",
+1933	    "pistol": "🔫",
+1934	    "pizza": "🍕",
+1935	    "place_of_worship": "🛐",
+1936	    "play_button": "▶",
+1937	    "play_or_pause_button": "⏯",
+1938	    "pleading_face": "🥺",
+1939	    "police_car": "🚓",
+1940	    "police_car_light": "🚨",
+1941	    "police_officer": "👮",
+1942	    "police_officer_dark_skin_tone": "👮🏿",
+1943	    "police_officer_light_skin_tone": "👮🏻",
+1944	    "police_officer_medium-dark_skin_tone": "👮🏾",
+1945	    "police_officer_medium-light_skin_tone": "👮🏼",
+1946	    "police_officer_medium_skin_tone": "👮🏽",
+1947	    "poodle": "🐩",
+1948	    "pool_8_ball": "🎱",
+1949	    "popcorn": "🍿",
+1950	    "post_office": "🏣",
+1951	    "postal_horn": "📯",
+1952	    "postbox": "📮",
+1953	    "pot_of_food": "🍲",
+1954	    "potable_water": "🚰",
+1955	    "potato": "🥔",
+1956	    "poultry_leg": "🍗",
+1957	    "pound_banknote": "💷",
+1958	    "pouting_cat_face": "😾",
+1959	    "pouting_face": "😡",
+1960	    "prayer_beads": "📿",
+1961	    "pregnant_woman": "🤰",
+1962	    "pregnant_woman_dark_skin_tone": "🤰🏿",
+1963	    "pregnant_woman_light_skin_tone": "🤰🏻",
+1964	    "pregnant_woman_medium-dark_skin_tone": "🤰🏾",
+1965	    "pregnant_woman_medium-light_skin_tone": "🤰🏼",
+1966	    "pregnant_woman_medium_skin_tone": "🤰🏽",
+1967	    "pretzel": "🥨",
+1968	    "probing_cane": "🦯",
+1969	    "prince": "🤴",
+1970	    "prince_dark_skin_tone": "🤴🏿",
+1971	    "prince_light_skin_tone": "🤴🏻",
+1972	    "prince_medium-dark_skin_tone": "🤴🏾",
+1973	    "prince_medium-light_skin_tone": "🤴🏼",
+1974	    "prince_medium_skin_tone": "🤴🏽",
+1975	    "princess": "👸",
+1976	    "princess_dark_skin_tone": "👸🏿",
+1977	    "princess_light_skin_tone": "👸🏻",
+1978	    "princess_medium-dark_skin_tone": "👸🏾",
+1979	    "princess_medium-light_skin_tone": "👸🏼",
+1980	    "princess_medium_skin_tone": "👸🏽",
+1981	    "printer": "🖨",
+1982	    "prohibited": "🚫",
+1983	    "purple_circle": "🟣",
+1984	    "purple_heart": "💜",
+1985	    "purple_square": "🟪",
+1986	    "purse": "👛",
+1987	    "pushpin": "📌",
+1988	    "question_mark": "❓",
+1989	    "rabbit": "🐰",
+1990	    "rabbit_face": "🐰",
+1991	    "raccoon": "🦝",
+1992	    "racing_car": "🏎",
+1993	    "radio": "📻",
+1994	    "radio_button": "🔘",
+1995	    "radioactive": "☢",
+1996	    "railway_car": "🚃",
+1997	    "railway_track": "🛤",
+1998	    "rainbow": "🌈",
+1999	    "rainbow_flag": "🏳️\u200d🌈",
+2000	    "raised_back_of_hand": "🤚",
+2001	    "raised_back_of_hand_dark_skin_tone": "🤚🏿",
+2002	    "raised_back_of_hand_light_skin_tone": "🤚🏻",
+2003	    "raised_back_of_hand_medium-dark_skin_tone": "🤚🏾",
+2004	    "raised_back_of_hand_medium-light_skin_tone": "🤚🏼",
+2005	    "raised_back_of_hand_medium_skin_tone": "🤚🏽",
+2006	    "raised_fist": "✊",
+2007	    "raised_fist_dark_skin_tone": "✊🏿",
+2008	    "raised_fist_light_skin_tone": "✊🏻",
+2009	    "raised_fist_medium-dark_skin_tone": "✊🏾",
+2010	    "raised_fist_medium-light_skin_tone": "✊🏼",
+2011	    "raised_fist_medium_skin_tone": "✊🏽",
+2012	    "raised_hand": "✋",
+2013	    "raised_hand_dark_skin_tone": "✋🏿",
+2014	    "raised_hand_light_skin_tone": "✋🏻",
+2015	    "raised_hand_medium-dark_skin_tone": "✋🏾",
+2016	    "raised_hand_medium-light_skin_tone": "✋🏼",
+2017	    "raised_hand_medium_skin_tone": "✋🏽",
+2018	    "raising_hands": "🙌",
+2019	    "raising_hands_dark_skin_tone": "🙌🏿",
+2020	    "raising_hands_light_skin_tone": "🙌🏻",
+2021	    "raising_hands_medium-dark_skin_tone": "🙌🏾",
+2022	    "raising_hands_medium-light_skin_tone": "🙌🏼",
+2023	    "raising_hands_medium_skin_tone": "🙌🏽",
+2024	    "ram": "🐏",
+2025	    "rat": "🐀",
+2026	    "razor": "🪒",
+2027	    "ringed_planet": "🪐",
+2028	    "receipt": "🧾",
+2029	    "record_button": "⏺",
+2030	    "recycling_symbol": "♻",
+2031	    "red_apple": "🍎",
+2032	    "red_circle": "🔴",
+2033	    "red_envelope": "🧧",
+2034	    "red_hair": "🦰",
+2035	    "red-haired_man": "👨\u200d🦰",
+2036	    "red-haired_woman": "👩\u200d🦰",
+2037	    "red_heart": "❤",
+2038	    "red_paper_lantern": "🏮",
+2039	    "red_square": "🟥",
+2040	    "red_triangle_pointed_down": "🔻",
+2041	    "red_triangle_pointed_up": "🔺",
+2042	    "registered": "®",
+2043	    "relieved_face": "😌",
+2044	    "reminder_ribbon": "🎗",
+2045	    "repeat_button": "🔁",
+2046	    "repeat_single_button": "🔂",
+2047	    "rescue_worker’s_helmet": "⛑",
+2048	    "restroom": "🚻",
+2049	    "reverse_button": "◀",
+2050	    "revolving_hearts": "💞",
+2051	    "rhinoceros": "🦏",
+2052	    "ribbon": "🎀",
+2053	    "rice_ball": "🍙",
+2054	    "rice_cracker": "🍘",
+2055	    "right-facing_fist": "🤜",
+2056	    "right-facing_fist_dark_skin_tone": "🤜🏿",
+2057	    "right-facing_fist_light_skin_tone": "🤜🏻",
+2058	    "right-facing_fist_medium-dark_skin_tone": "🤜🏾",
+2059	    "right-facing_fist_medium-light_skin_tone": "🤜🏼",
+2060	    "right-facing_fist_medium_skin_tone": "🤜🏽",
+2061	    "right_anger_bubble": "🗯",
+2062	    "right_arrow": "➡",
+2063	    "right_arrow_curving_down": "⤵",
+2064	    "right_arrow_curving_left": "↩",
+2065	    "right_arrow_curving_up": "⤴",
+2066	    "ring": "💍",
+2067	    "roasted_sweet_potato": "🍠",
+2068	    "robot_face": "🤖",
+2069	    "rocket": "🚀",
+2070	    "roll_of_paper": "🧻",
+2071	    "rolled-up_newspaper": "🗞",
+2072	    "roller_coaster": "🎢",
+2073	    "rolling_on_the_floor_laughing": "🤣",
+2074	    "rooster": "🐓",
+2075	    "rose": "🌹",
+2076	    "rosette": "🏵",
+2077	    "round_pushpin": "📍",
+2078	    "rugby_football": "🏉",
+2079	    "running_shirt": "🎽",
+2080	    "running_shoe": "👟",
+2081	    "sad_but_relieved_face": "😥",
+2082	    "safety_pin": "🧷",
+2083	    "safety_vest": "🦺",
+2084	    "salt": "🧂",
+2085	    "sailboat": "⛵",
+2086	    "sake": "🍶",
+2087	    "sandwich": "🥪",
+2088	    "sari": "🥻",
+2089	    "satellite": "📡",
+2090	    "satellite_antenna": "📡",
+2091	    "sauropod": "🦕",
+2092	    "saxophone": "🎷",
+2093	    "scarf": "🧣",
+2094	    "school": "🏫",
+2095	    "school_backpack": "🎒",
+2096	    "scissors": "✂",
+2097	    "scorpion": "🦂",
+2098	    "scroll": "📜",
+2099	    "seat": "💺",
+2100	    "see-no-evil_monkey": "🙈",
+2101	    "seedling": "🌱",
+2102	    "selfie": "🤳",
+2103	    "selfie_dark_skin_tone": "🤳🏿",
+2104	    "selfie_light_skin_tone": "🤳🏻",
+2105	    "selfie_medium-dark_skin_tone": "🤳🏾",
+2106	    "selfie_medium-light_skin_tone": "🤳🏼",
+2107	    "selfie_medium_skin_tone": "🤳🏽",
+2108	    "service_dog": "🐕\u200d🦺",
+2109	    "seven-thirty": "🕢",
+2110	    "seven_o’clock": "🕖",
+2111	    "shallow_pan_of_food": "🥘",
+2112	    "shamrock": "☘",
+2113	    "shark": "🦈",
+2114	    "shaved_ice": "🍧",
+2115	    "sheaf_of_rice": "🌾",
+2116	    "shield": "🛡",
+2117	    "shinto_shrine": "⛩",
+2118	    "ship": "🚢",
+2119	    "shooting_star": "🌠",
+2120	    "shopping_bags": "🛍",
+2121	    "shopping_cart": "🛒",
+2122	    "shortcake": "🍰",
+2123	    "shorts": "🩳",
+2124	    "shower": "🚿",
+2125	    "shrimp": "🦐",
+2126	    "shuffle_tracks_button": "🔀",
+2127	    "shushing_face": "🤫",
+2128	    "sign_of_the_horns": "🤘",
+2129	    "sign_of_the_horns_dark_skin_tone": "🤘🏿",
+2130	    "sign_of_the_horns_light_skin_tone": "🤘🏻",
+2131	    "sign_of_the_horns_medium-dark_skin_tone": "🤘🏾",
+2132	    "sign_of_the_horns_medium-light_skin_tone": "🤘🏼",
+2133	    "sign_of_the_horns_medium_skin_tone": "🤘🏽",
+2134	    "six-thirty": "🕡",
+2135	    "six_o’clock": "🕕",
+2136	    "skateboard": "🛹",
+2137	    "skier": "⛷",
+2138	    "skis": "🎿",
+2139	    "skull": "💀",
+2140	    "skull_and_crossbones": "☠",
+2141	    "skunk": "🦨",
+2142	    "sled": "🛷",
+2143	    "sleeping_face": "😴",
+2144	    "sleepy_face": "😪",
+2145	    "slightly_frowning_face": "🙁",
+2146	    "slightly_smiling_face": "🙂",
+2147	    "slot_machine": "🎰",
+2148	    "sloth": "🦥",
+2149	    "small_airplane": "🛩",
+2150	    "small_blue_diamond": "🔹",
+2151	    "small_orange_diamond": "🔸",
+2152	    "smiling_cat_face_with_heart-eyes": "😻",
+2153	    "smiling_face": "☺",
+2154	    "smiling_face_with_halo": "😇",
+2155	    "smiling_face_with_3_hearts": "🥰",
+2156	    "smiling_face_with_heart-eyes": "😍",
+2157	    "smiling_face_with_horns": "😈",
+2158	    "smiling_face_with_smiling_eyes": "😊",
+2159	    "smiling_face_with_sunglasses": "😎",
+2160	    "smirking_face": "😏",
+2161	    "snail": "🐌",
+2162	    "snake": "🐍",
+2163	    "sneezing_face": "🤧",
+2164	    "snow-capped_mountain": "🏔",
+2165	    "snowboarder": "🏂",
+2166	    "snowboarder_dark_skin_tone": "🏂🏿",
+2167	    "snowboarder_light_skin_tone": "🏂🏻",
+2168	    "snowboarder_medium-dark_skin_tone": "🏂🏾",
+2169	    "snowboarder_medium-light_skin_tone": "🏂🏼",
+2170	    "snowboarder_medium_skin_tone": "🏂🏽",
+2171	    "snowflake": "❄",
+2172	    "snowman": "☃",
+2173	    "snowman_without_snow": "⛄",
+2174	    "soap": "🧼",
+2175	    "soccer_ball": "⚽",
+2176	    "socks": "🧦",
+2177	    "softball": "🥎",
+2178	    "soft_ice_cream": "🍦",
+2179	    "spade_suit": "♠",
+2180	    "spaghetti": "🍝",
+2181	    "sparkle": "❇",
+2182	    "sparkler": "🎇",
+2183	    "sparkles": "✨",
+2184	    "sparkling_heart": "💖",
+2185	    "speak-no-evil_monkey": "🙊",
+2186	    "speaker_high_volume": "🔊",
+2187	    "speaker_low_volume": "🔈",
+2188	    "speaker_medium_volume": "🔉",
+2189	    "speaking_head": "🗣",
+2190	    "speech_balloon": "💬",
+2191	    "speedboat": "🚤",
+2192	    "spider": "🕷",
+2193	    "spider_web": "🕸",
+2194	    "spiral_calendar": "🗓",
+2195	    "spiral_notepad": "🗒",
+2196	    "spiral_shell": "🐚",
+2197	    "spoon": "🥄",
+2198	    "sponge": "🧽",
+2199	    "sport_utility_vehicle": "🚙",
+2200	    "sports_medal": "🏅",
+2201	    "spouting_whale": "🐳",
+2202	    "squid": "🦑",
+2203	    "squinting_face_with_tongue": "😝",
+2204	    "stadium": "🏟",
+2205	    "star-struck": "🤩",
+2206	    "star_and_crescent": "☪",
+2207	    "star_of_david": "✡",
+2208	    "station": "🚉",
+2209	    "steaming_bowl": "🍜",
+2210	    "stethoscope": "🩺",
+2211	    "stop_button": "⏹",
+2212	    "stop_sign": "🛑",
+2213	    "stopwatch": "⏱",
+2214	    "straight_ruler": "📏",
+2215	    "strawberry": "🍓",
+2216	    "studio_microphone": "🎙",
+2217	    "stuffed_flatbread": "🥙",
+2218	    "sun": "☀",
+2219	    "sun_behind_cloud": "⛅",
+2220	    "sun_behind_large_cloud": "🌥",
+2221	    "sun_behind_rain_cloud": "🌦",
+2222	    "sun_behind_small_cloud": "🌤",
+2223	    "sun_with_face": "🌞",
+2224	    "sunflower": "🌻",
+2225	    "sunglasses": "😎",
+2226	    "sunrise": "🌅",
+2227	    "sunrise_over_mountains": "🌄",
+2228	    "sunset": "🌇",
+2229	    "superhero": "🦸",
+2230	    "supervillain": "🦹",
+2231	    "sushi": "🍣",
+2232	    "suspension_railway": "🚟",
+2233	    "swan": "🦢",
+2234	    "sweat_droplets": "💦",
+2235	    "synagogue": "🕍",
+2236	    "syringe": "💉",
+2237	    "t-shirt": "👕",
+2238	    "taco": "🌮",
+2239	    "takeout_box": "🥡",
+2240	    "tanabata_tree": "🎋",
+2241	    "tangerine": "🍊",
+2242	    "taxi": "🚕",
+2243	    "teacup_without_handle": "🍵",
+2244	    "tear-off_calendar": "📆",
+2245	    "teddy_bear": "🧸",
+2246	    "telephone": "☎",
+2247	    "telephone_receiver": "📞",
+2248	    "telescope": "🔭",
+2249	    "television": "📺",
+2250	    "ten-thirty": "🕥",
+2251	    "ten_o’clock": "🕙",
+2252	    "tennis": "🎾",
+2253	    "tent": "⛺",
+2254	    "test_tube": "🧪",
+2255	    "thermometer": "🌡",
+2256	    "thinking_face": "🤔",
+2257	    "thought_balloon": "💭",
+2258	    "thread": "🧵",
+2259	    "three-thirty": "🕞",
+2260	    "three_o’clock": "🕒",
+2261	    "thumbs_down": "👎",
+2262	    "thumbs_down_dark_skin_tone": "👎🏿",
+2263	    "thumbs_down_light_skin_tone": "👎🏻",
+2264	    "thumbs_down_medium-dark_skin_tone": "👎🏾",
+2265	    "thumbs_down_medium-light_skin_tone": "👎🏼",
+2266	    "thumbs_down_medium_skin_tone": "👎🏽",
+2267	    "thumbs_up": "👍",
+2268	    "thumbs_up_dark_skin_tone": "👍🏿",
+2269	    "thumbs_up_light_skin_tone": "👍🏻",
+2270	    "thumbs_up_medium-dark_skin_tone": "👍🏾",
+2271	    "thumbs_up_medium-light_skin_tone": "👍🏼",
+2272	    "thumbs_up_medium_skin_tone": "👍🏽",
+2273	    "ticket": "🎫",
+2274	    "tiger": "🐯",
+2275	    "tiger_face": "🐯",
+2276	    "timer_clock": "⏲",
+2277	    "tired_face": "😫",
+2278	    "toolbox": "🧰",
+2279	    "toilet": "🚽",
+2280	    "tomato": "🍅",
+2281	    "tongue": "👅",
+2282	    "tooth": "🦷",
+2283	    "top_hat": "🎩",
+2284	    "tornado": "🌪",
+2285	    "trackball": "🖲",
+2286	    "tractor": "🚜",
+2287	    "trade_mark": "™",
+2288	    "train": "🚋",
+2289	    "tram": "🚊",
+2290	    "tram_car": "🚋",
+2291	    "triangular_flag": "🚩",
+2292	    "triangular_ruler": "📐",
+2293	    "trident_emblem": "🔱",
+2294	    "trolleybus": "🚎",
+2295	    "trophy": "🏆",
+2296	    "tropical_drink": "🍹",
+2297	    "tropical_fish": "🐠",
+2298	    "trumpet": "🎺",
+2299	    "tulip": "🌷",
+2300	    "tumbler_glass": "🥃",
+2301	    "turtle": "🐢",
+2302	    "twelve-thirty": "🕧",
+2303	    "twelve_o’clock": "🕛",
+2304	    "two-hump_camel": "🐫",
+2305	    "two-thirty": "🕝",
+2306	    "two_hearts": "💕",
+2307	    "two_men_holding_hands": "👬",
+2308	    "two_o’clock": "🕑",
+2309	    "two_women_holding_hands": "👭",
+2310	    "umbrella": "☂",
+2311	    "umbrella_on_ground": "⛱",
+2312	    "umbrella_with_rain_drops": "☔",
+2313	    "unamused_face": "😒",
+2314	    "unicorn_face": "🦄",
+2315	    "unlocked": "🔓",
+2316	    "up-down_arrow": "↕",
+2317	    "up-left_arrow": "↖",
+2318	    "up-right_arrow": "↗",
+2319	    "up_arrow": "⬆",
+2320	    "upside-down_face": "🙃",
+2321	    "upwards_button": "🔼",
+2322	    "vampire": "🧛",
+2323	    "vampire_dark_skin_tone": "🧛🏿",
+2324	    "vampire_light_skin_tone": "🧛🏻",
+2325	    "vampire_medium-dark_skin_tone": "🧛🏾",
+2326	    "vampire_medium-light_skin_tone": "🧛🏼",
+2327	    "vampire_medium_skin_tone": "🧛🏽",
+2328	    "vertical_traffic_light": "🚦",
+2329	    "vibration_mode": "📳",
+2330	    "victory_hand": "✌",
+2331	    "victory_hand_dark_skin_tone": "✌🏿",
+2332	    "victory_hand_light_skin_tone": "✌🏻",
+2333	    "victory_hand_medium-dark_skin_tone": "✌🏾",
+2334	    "victory_hand_medium-light_skin_tone": "✌🏼",
+2335	    "victory_hand_medium_skin_tone": "✌🏽",
+2336	    "video_camera": "📹",
+2337	    "video_game": "🎮",
+2338	    "videocassette": "📼",
+2339	    "violin": "🎻",
+2340	    "volcano": "🌋",
+2341	    "volleyball": "🏐",
+2342	    "vulcan_salute": "🖖",
+2343	    "vulcan_salute_dark_skin_tone": "🖖🏿",
+2344	    "vulcan_salute_light_skin_tone": "🖖🏻",
+2345	    "vulcan_salute_medium-dark_skin_tone": "🖖🏾",
+2346	    "vulcan_salute_medium-light_skin_tone": "🖖🏼",
+2347	    "vulcan_salute_medium_skin_tone": "🖖🏽",
+2348	    "waffle": "🧇",
+2349	    "waning_crescent_moon": "🌘",
+2350	    "waning_gibbous_moon": "🌖",
+2351	    "warning": "⚠",
+2352	    "wastebasket": "🗑",
+2353	    "watch": "⌚",
+2354	    "water_buffalo": "🐃",
+2355	    "water_closet": "🚾",
+2356	    "water_wave": "🌊",
+2357	    "watermelon": "🍉",
+2358	    "waving_hand": "👋",
+2359	    "waving_hand_dark_skin_tone": "👋🏿",
+2360	    "waving_hand_light_skin_tone": "👋🏻",
+2361	    "waving_hand_medium-dark_skin_tone": "👋🏾",
+2362	    "waving_hand_medium-light_skin_tone": "👋🏼",
+2363	    "waving_hand_medium_skin_tone": "👋🏽",
+2364	    "wavy_dash": "〰",
+2365	    "waxing_crescent_moon": "🌒",
+2366	    "waxing_gibbous_moon": "🌔",
+2367	    "weary_cat_face": "🙀",
+2368	    "weary_face": "😩",
+2369	    "wedding": "💒",
+2370	    "whale": "🐳",
+2371	    "wheel_of_dharma": "☸",
+2372	    "wheelchair_symbol": "♿",
+2373	    "white_circle": "⚪",
+2374	    "white_exclamation_mark": "❕",
+2375	    "white_flag": "🏳",
+2376	    "white_flower": "💮",
+2377	    "white_hair": "🦳",
+2378	    "white-haired_man": "👨\u200d🦳",
+2379	    "white-haired_woman": "👩\u200d🦳",
+2380	    "white_heart": "🤍",
+2381	    "white_heavy_check_mark": "✅",
+2382	    "white_large_square": "⬜",
+2383	    "white_medium-small_square": "◽",
+2384	    "white_medium_square": "◻",
+2385	    "white_medium_star": "⭐",
+2386	    "white_question_mark": "❔",
+2387	    "white_small_square": "▫",
+2388	    "white_square_button": "🔳",
+2389	    "wilted_flower": "🥀",
+2390	    "wind_chime": "🎐",
+2391	    "wind_face": "🌬",
+2392	    "wine_glass": "🍷",
+2393	    "winking_face": "😉",
+2394	    "winking_face_with_tongue": "😜",
+2395	    "wolf_face": "🐺",
+2396	    "woman": "👩",
+2397	    "woman_artist": "👩\u200d🎨",
+2398	    "woman_artist_dark_skin_tone": "👩🏿\u200d🎨",
+2399	    "woman_artist_light_skin_tone": "👩🏻\u200d🎨",
+2400	    "woman_artist_medium-dark_skin_tone": "👩🏾\u200d🎨",
+2401	    "woman_artist_medium-light_skin_tone": "👩🏼\u200d🎨",
+2402	    "woman_artist_medium_skin_tone": "👩🏽\u200d🎨",
+2403	    "woman_astronaut": "👩\u200d🚀",
+2404	    "woman_astronaut_dark_skin_tone": "👩🏿\u200d🚀",
+2405	    "woman_astronaut_light_skin_tone": "👩🏻\u200d🚀",
+2406	    "woman_astronaut_medium-dark_skin_tone": "👩🏾\u200d🚀",
+2407	    "woman_astronaut_medium-light_skin_tone": "👩🏼\u200d🚀",
+2408	    "woman_astronaut_medium_skin_tone": "👩🏽\u200d🚀",
+2409	    "woman_biking": "🚴\u200d♀️",
+2410	    "woman_biking_dark_skin_tone": "🚴🏿\u200d♀️",
+2411	    "woman_biking_light_skin_tone": "🚴🏻\u200d♀️",
+2412	    "woman_biking_medium-dark_skin_tone": "🚴🏾\u200d♀️",
+2413	    "woman_biking_medium-light_skin_tone": "🚴🏼\u200d♀️",
+2414	    "woman_biking_medium_skin_tone": "🚴🏽\u200d♀️",
+2415	    "woman_bouncing_ball": "⛹️\u200d♀️",
+2416	    "woman_bouncing_ball_dark_skin_tone": "⛹🏿\u200d♀️",
+2417	    "woman_bouncing_ball_light_skin_tone": "⛹🏻\u200d♀️",
+2418	    "woman_bouncing_ball_medium-dark_skin_tone": "⛹🏾\u200d♀️",
+2419	    "woman_bouncing_ball_medium-light_skin_tone": "⛹🏼\u200d♀️",
+2420	    "woman_bouncing_ball_medium_skin_tone": "⛹🏽\u200d♀️",
+2421	    "woman_bowing": "🙇\u200d♀️",
+2422	    "woman_bowing_dark_skin_tone": "🙇🏿\u200d♀️",
+2423	    "woman_bowing_light_skin_tone": "🙇🏻\u200d♀️",
+2424	    "woman_bowing_medium-dark_skin_tone": "🙇🏾\u200d♀️",
+2425	    "woman_bowing_medium-light_skin_tone": "🙇🏼\u200d♀️",
+2426	    "woman_bowing_medium_skin_tone": "🙇🏽\u200d♀️",
+2427	    "woman_cartwheeling": "🤸\u200d♀️",
+2428	    "woman_cartwheeling_dark_skin_tone": "🤸🏿\u200d♀️",
+2429	    "woman_cartwheeling_light_skin_tone": "🤸🏻\u200d♀️",
+2430	    "woman_cartwheeling_medium-dark_skin_tone": "🤸🏾\u200d♀️",
+2431	    "woman_cartwheeling_medium-light_skin_tone": "🤸🏼\u200d♀️",
+2432	    "woman_cartwheeling_medium_skin_tone": "🤸🏽\u200d♀️",
+2433	    "woman_climbing": "🧗\u200d♀️",
+2434	    "woman_climbing_dark_skin_tone": "🧗🏿\u200d♀️",
+2435	    "woman_climbing_light_skin_tone": "🧗🏻\u200d♀️",
+2436	    "woman_climbing_medium-dark_skin_tone": "🧗🏾\u200d♀️",
+2437	    "woman_climbing_medium-light_skin_tone": "🧗🏼\u200d♀️",
+2438	    "woman_climbing_medium_skin_tone": "🧗🏽\u200d♀️",
+2439	    "woman_construction_worker": "👷\u200d♀️",
+2440	    "woman_construction_worker_dark_skin_tone": "👷🏿\u200d♀️",
+2441	    "woman_construction_worker_light_skin_tone": "👷🏻\u200d♀️",
+2442	    "woman_construction_worker_medium-dark_skin_tone": "👷🏾\u200d♀️",
+2443	    "woman_construction_worker_medium-light_skin_tone": "👷🏼\u200d♀️",
+2444	    "woman_construction_worker_medium_skin_tone": "👷🏽\u200d♀️",
+2445	    "woman_cook": "👩\u200d🍳",
+2446	    "woman_cook_dark_skin_tone": "👩🏿\u200d🍳",
+2447	    "woman_cook_light_skin_tone": "👩🏻\u200d🍳",
+2448	    "woman_cook_medium-dark_skin_tone": "👩🏾\u200d🍳",
+2449	    "woman_cook_medium-light_skin_tone": "👩🏼\u200d🍳",
+2450	    "woman_cook_medium_skin_tone": "👩🏽\u200d🍳",
+2451	    "woman_dancing": "💃",
+2452	    "woman_dancing_dark_skin_tone": "💃🏿",
+2453	    "woman_dancing_light_skin_tone": "💃🏻",
+2454	    "woman_dancing_medium-dark_skin_tone": "💃🏾",
+2455	    "woman_dancing_medium-light_skin_tone": "💃🏼",
+2456	    "woman_dancing_medium_skin_tone": "💃🏽",
+2457	    "woman_dark_skin_tone": "👩🏿",
+2458	    "woman_detective": "🕵️\u200d♀️",
+2459	    "woman_detective_dark_skin_tone": "🕵🏿\u200d♀️",
+2460	    "woman_detective_light_skin_tone": "🕵🏻\u200d♀️",
+2461	    "woman_detective_medium-dark_skin_tone": "🕵🏾\u200d♀️",
+2462	    "woman_detective_medium-light_skin_tone": "🕵🏼\u200d♀️",
+2463	    "woman_detective_medium_skin_tone": "🕵🏽\u200d♀️",
+2464	    "woman_elf": "🧝\u200d♀️",
+2465	    "woman_elf_dark_skin_tone": "🧝🏿\u200d♀️",
+2466	    "woman_elf_light_skin_tone": "🧝🏻\u200d♀️",
+2467	    "woman_elf_medium-dark_skin_tone": "🧝🏾\u200d♀️",
+2468	    "woman_elf_medium-light_skin_tone": "🧝🏼\u200d♀️",
+2469	    "woman_elf_medium_skin_tone": "🧝🏽\u200d♀️",
+2470	    "woman_facepalming": "🤦\u200d♀️",
+2471	    "woman_facepalming_dark_skin_tone": "🤦🏿\u200d♀️",
+2472	    "woman_facepalming_light_skin_tone": "🤦🏻\u200d♀️",
+2473	    "woman_facepalming_medium-dark_skin_tone": "🤦🏾\u200d♀️",
+2474	    "woman_facepalming_medium-light_skin_tone": "🤦🏼\u200d♀️",
+2475	    "woman_facepalming_medium_skin_tone": "🤦🏽\u200d♀️",
+2476	    "woman_factory_worker": "👩\u200d🏭",
+2477	    "woman_factory_worker_dark_skin_tone": "👩🏿\u200d🏭",
+2478	    "woman_factory_worker_light_skin_tone": "👩🏻\u200d🏭",
+2479	    "woman_factory_worker_medium-dark_skin_tone": "👩🏾\u200d🏭",
+2480	    "woman_factory_worker_medium-light_skin_tone": "👩🏼\u200d🏭",
+2481	    "woman_factory_worker_medium_skin_tone": "👩🏽\u200d🏭",
+2482	    "woman_fairy": "🧚\u200d♀️",
+2483	    "woman_fairy_dark_skin_tone": "🧚🏿\u200d♀️",
+2484	    "woman_fairy_light_skin_tone": "🧚🏻\u200d♀️",
+2485	    "woman_fairy_medium-dark_skin_tone": "🧚🏾\u200d♀️",
+2486	    "woman_fairy_medium-light_skin_tone": "🧚🏼\u200d♀️",
+2487	    "woman_fairy_medium_skin_tone": "🧚🏽\u200d♀️",
+2488	    "woman_farmer": "👩\u200d🌾",
+2489	    "woman_farmer_dark_skin_tone": "👩🏿\u200d🌾",
+2490	    "woman_farmer_light_skin_tone": "👩🏻\u200d🌾",
+2491	    "woman_farmer_medium-dark_skin_tone": "👩🏾\u200d🌾",
+2492	    "woman_farmer_medium-light_skin_tone": "👩🏼\u200d🌾",
+2493	    "woman_farmer_medium_skin_tone": "👩🏽\u200d🌾",
+2494	    "woman_firefighter": "👩\u200d🚒",
+2495	    "woman_firefighter_dark_skin_tone": "👩🏿\u200d🚒",
+2496	    "woman_firefighter_light_skin_tone": "👩🏻\u200d🚒",
+2497	    "woman_firefighter_medium-dark_skin_tone": "👩🏾\u200d🚒",
+2498	    "woman_firefighter_medium-light_skin_tone": "👩🏼\u200d🚒",
+2499	    "woman_firefighter_medium_skin_tone": "👩🏽\u200d🚒",
+2500	    "woman_frowning": "🙍\u200d♀️",
+2501	    "woman_frowning_dark_skin_tone": "🙍🏿\u200d♀️",
+2502	    "woman_frowning_light_skin_tone": "🙍🏻\u200d♀️",
+2503	    "woman_frowning_medium-dark_skin_tone": "🙍🏾\u200d♀️",
+2504	    "woman_frowning_medium-light_skin_tone": "🙍🏼\u200d♀️",
+2505	    "woman_frowning_medium_skin_tone": "🙍🏽\u200d♀️",
+2506	    "woman_genie": "🧞\u200d♀️",
+2507	    "woman_gesturing_no": "🙅\u200d♀️",
+2508	    "woman_gesturing_no_dark_skin_tone": "🙅🏿\u200d♀️",
+2509	    "woman_gesturing_no_light_skin_tone": "🙅🏻\u200d♀️",
+2510	    "woman_gesturing_no_medium-dark_skin_tone": "🙅🏾\u200d♀️",
+2511	    "woman_gesturing_no_medium-light_skin_tone": "🙅🏼\u200d♀️",
+2512	    "woman_gesturing_no_medium_skin_tone": "🙅🏽\u200d♀️",
+2513	    "woman_gesturing_ok": "🙆\u200d♀️",
+2514	    "woman_gesturing_ok_dark_skin_tone": "🙆🏿\u200d♀️",
+2515	    "woman_gesturing_ok_light_skin_tone": "🙆🏻\u200d♀️",
+2516	    "woman_gesturing_ok_medium-dark_skin_tone": "🙆🏾\u200d♀️",
+2517	    "woman_gesturing_ok_medium-light_skin_tone": "🙆🏼\u200d♀️",
+2518	    "woman_gesturing_ok_medium_skin_tone": "🙆🏽\u200d♀️",
+2519	    "woman_getting_haircut": "💇\u200d♀️",
+2520	    "woman_getting_haircut_dark_skin_tone": "💇🏿\u200d♀️",
+2521	    "woman_getting_haircut_light_skin_tone": "💇🏻\u200d♀️",
+2522	    "woman_getting_haircut_medium-dark_skin_tone": "💇🏾\u200d♀️",
+2523	    "woman_getting_haircut_medium-light_skin_tone": "💇🏼\u200d♀️",
+2524	    "woman_getting_haircut_medium_skin_tone": "💇🏽\u200d♀️",
+2525	    "woman_getting_massage": "💆\u200d♀️",
+2526	    "woman_getting_massage_dark_skin_tone": "💆🏿\u200d♀️",
+2527	    "woman_getting_massage_light_skin_tone": "💆🏻\u200d♀️",
+2528	    "woman_getting_massage_medium-dark_skin_tone": "💆🏾\u200d♀️",
+2529	    "woman_getting_massage_medium-light_skin_tone": "💆🏼\u200d♀️",
+2530	    "woman_getting_massage_medium_skin_tone": "💆🏽\u200d♀️",
+2531	    "woman_golfing": "🏌️\u200d♀️",
+2532	    "woman_golfing_dark_skin_tone": "🏌🏿\u200d♀️",
+2533	    "woman_golfing_light_skin_tone": "🏌🏻\u200d♀️",
+2534	    "woman_golfing_medium-dark_skin_tone": "🏌🏾\u200d♀️",
+2535	    "woman_golfing_medium-light_skin_tone": "🏌🏼\u200d♀️",
+2536	    "woman_golfing_medium_skin_tone": "🏌🏽\u200d♀️",
+2537	    "woman_guard": "💂\u200d♀️",
+2538	    "woman_guard_dark_skin_tone": "💂🏿\u200d♀️",
+2539	    "woman_guard_light_skin_tone": "💂🏻\u200d♀️",
+2540	    "woman_guard_medium-dark_skin_tone": "💂🏾\u200d♀️",
+2541	    "woman_guard_medium-light_skin_tone": "💂🏼\u200d♀️",
+2542	    "woman_guard_medium_skin_tone": "💂🏽\u200d♀️",
+2543	    "woman_health_worker": "👩\u200d⚕️",
+2544	    "woman_health_worker_dark_skin_tone": "👩🏿\u200d⚕️",
+2545	    "woman_health_worker_light_skin_tone": "👩🏻\u200d⚕️",
+2546	    "woman_health_worker_medium-dark_skin_tone": "👩🏾\u200d⚕️",
+2547	    "woman_health_worker_medium-light_skin_tone": "👩🏼\u200d⚕️",
+2548	    "woman_health_worker_medium_skin_tone": "👩🏽\u200d⚕️",
+2549	    "woman_in_lotus_position": "🧘\u200d♀️",
+2550	    "woman_in_lotus_position_dark_skin_tone": "🧘🏿\u200d♀️",
+2551	    "woman_in_lotus_position_light_skin_tone": "🧘🏻\u200d♀️",
+2552	    "woman_in_lotus_position_medium-dark_skin_tone": "🧘🏾\u200d♀️",
+2553	    "woman_in_lotus_position_medium-light_skin_tone": "🧘🏼\u200d♀️",
+2554	    "woman_in_lotus_position_medium_skin_tone": "🧘🏽\u200d♀️",
+2555	    "woman_in_manual_wheelchair": "👩\u200d🦽",
+2556	    "woman_in_motorized_wheelchair": "👩\u200d🦼",
+2557	    "woman_in_steamy_room": "🧖\u200d♀️",
+2558	    "woman_in_steamy_room_dark_skin_tone": "🧖🏿\u200d♀️",
+2559	    "woman_in_steamy_room_light_skin_tone": "🧖🏻\u200d♀️",
+2560	    "woman_in_steamy_room_medium-dark_skin_tone": "🧖🏾\u200d♀️",
+2561	    "woman_in_steamy_room_medium-light_skin_tone": "🧖🏼\u200d♀️",
+2562	    "woman_in_steamy_room_medium_skin_tone": "🧖🏽\u200d♀️",
+2563	    "woman_judge": "👩\u200d⚖️",
+2564	    "woman_judge_dark_skin_tone": "👩🏿\u200d⚖️",
+2565	    "woman_judge_light_skin_tone": "👩🏻\u200d⚖️",
+2566	    "woman_judge_medium-dark_skin_tone": "👩🏾\u200d⚖️",
+2567	    "woman_judge_medium-light_skin_tone": "👩🏼\u200d⚖️",
+2568	    "woman_judge_medium_skin_tone": "👩🏽\u200d⚖️",
+2569	    "woman_juggling": "🤹\u200d♀️",
+2570	    "woman_juggling_dark_skin_tone": "🤹🏿\u200d♀️",
+2571	    "woman_juggling_light_skin_tone": "🤹🏻\u200d♀️",
+2572	    "woman_juggling_medium-dark_skin_tone": "🤹🏾\u200d♀️",
+2573	    "woman_juggling_medium-light_skin_tone": "🤹🏼\u200d♀️",
+2574	    "woman_juggling_medium_skin_tone": "🤹🏽\u200d♀️",
+2575	    "woman_lifting_weights": "🏋️\u200d♀️",
+2576	    "woman_lifting_weights_dark_skin_tone": "🏋🏿\u200d♀️",
+2577	    "woman_lifting_weights_light_skin_tone": "🏋🏻\u200d♀️",
+2578	    "woman_lifting_weights_medium-dark_skin_tone": "🏋🏾\u200d♀️",
+2579	    "woman_lifting_weights_medium-light_skin_tone": "🏋🏼\u200d♀️",
+2580	    "woman_lifting_weights_medium_skin_tone": "🏋🏽\u200d♀️",
+2581	    "woman_light_skin_tone": "👩🏻",
+2582	    "woman_mage": "🧙\u200d♀️",
+2583	    "woman_mage_dark_skin_tone": "🧙🏿\u200d♀️",
+2584	    "woman_mage_light_skin_tone": "🧙🏻\u200d♀️",
+2585	    "woman_mage_medium-dark_skin_tone": "🧙🏾\u200d♀️",
+2586	    "woman_mage_medium-light_skin_tone": "🧙🏼\u200d♀️",
+2587	    "woman_mage_medium_skin_tone": "🧙🏽\u200d♀️",
+2588	    "woman_mechanic": "👩\u200d🔧",
+2589	    "woman_mechanic_dark_skin_tone": "👩🏿\u200d🔧",
+2590	    "woman_mechanic_light_skin_tone": "👩🏻\u200d🔧",
+2591	    "woman_mechanic_medium-dark_skin_tone": "👩🏾\u200d🔧",
+2592	    "woman_mechanic_medium-light_skin_tone": "👩🏼\u200d🔧",
+2593	    "woman_mechanic_medium_skin_tone": "👩🏽\u200d🔧",
+2594	    "woman_medium-dark_skin_tone": "👩🏾",
+2595	    "woman_medium-light_skin_tone": "👩🏼",
+2596	    "woman_medium_skin_tone": "👩🏽",
+2597	    "woman_mountain_biking": "🚵\u200d♀️",
+2598	    "woman_mountain_biking_dark_skin_tone": "🚵🏿\u200d♀️",
+2599	    "woman_mountain_biking_light_skin_tone": "🚵🏻\u200d♀️",
+2600	    "woman_mountain_biking_medium-dark_skin_tone": "🚵🏾\u200d♀️",
+2601	    "woman_mountain_biking_medium-light_skin_tone": "🚵🏼\u200d♀️",
+2602	    "woman_mountain_biking_medium_skin_tone": "🚵🏽\u200d♀️",
+2603	    "woman_office_worker": "👩\u200d💼",
+2604	    "woman_office_worker_dark_skin_tone": "👩🏿\u200d💼",
+2605	    "woman_office_worker_light_skin_tone": "👩🏻\u200d💼",
+2606	    "woman_office_worker_medium-dark_skin_tone": "👩🏾\u200d💼",
+2607	    "woman_office_worker_medium-light_skin_tone": "👩🏼\u200d💼",
+2608	    "woman_office_worker_medium_skin_tone": "👩🏽\u200d💼",
+2609	    "woman_pilot": "👩\u200d✈️",
+2610	    "woman_pilot_dark_skin_tone": "👩🏿\u200d✈️",
+2611	    "woman_pilot_light_skin_tone": "👩🏻\u200d✈️",
+2612	    "woman_pilot_medium-dark_skin_tone": "👩🏾\u200d✈️",
+2613	    "woman_pilot_medium-light_skin_tone": "👩🏼\u200d✈️",
+2614	    "woman_pilot_medium_skin_tone": "👩🏽\u200d✈️",
+2615	    "woman_playing_handball": "🤾\u200d♀️",
+2616	    "woman_playing_handball_dark_skin_tone": "🤾🏿\u200d♀️",
+2617	    "woman_playing_handball_light_skin_tone": "🤾🏻\u200d♀️",
+2618	    "woman_playing_handball_medium-dark_skin_tone": "🤾🏾\u200d♀️",
+2619	    "woman_playing_handball_medium-light_skin_tone": "🤾🏼\u200d♀️",
+2620	    "woman_playing_handball_medium_skin_tone": "🤾🏽\u200d♀️",
+2621	    "woman_playing_water_polo": "🤽\u200d♀️",
+2622	    "woman_playing_water_polo_dark_skin_tone": "🤽🏿\u200d♀️",
+2623	    "woman_playing_water_polo_light_skin_tone": "🤽🏻\u200d♀️",
+2624	    "woman_playing_water_polo_medium-dark_skin_tone": "🤽🏾\u200d♀️",
+2625	    "woman_playing_water_polo_medium-light_skin_tone": "🤽🏼\u200d♀️",
+2626	    "woman_playing_water_polo_medium_skin_tone": "🤽🏽\u200d♀️",
+2627	    "woman_police_officer": "👮\u200d♀️",
+2628	    "woman_police_officer_dark_skin_tone": "👮🏿\u200d♀️",
+2629	    "woman_police_officer_light_skin_tone": "👮🏻\u200d♀️",
+2630	    "woman_police_officer_medium-dark_skin_tone": "👮🏾\u200d♀️",
+2631	    "woman_police_officer_medium-light_skin_tone": "👮🏼\u200d♀️",
+2632	    "woman_police_officer_medium_skin_tone": "👮🏽\u200d♀️",
+2633	    "woman_pouting": "🙎\u200d♀️",
+2634	    "woman_pouting_dark_skin_tone": "🙎🏿\u200d♀️",
+2635	    "woman_pouting_light_skin_tone": "🙎🏻\u200d♀️",
+2636	    "woman_pouting_medium-dark_skin_tone": "🙎🏾\u200d♀️",
+2637	    "woman_pouting_medium-light_skin_tone": "🙎🏼\u200d♀️",
+2638	    "woman_pouting_medium_skin_tone": "🙎🏽\u200d♀️",
+2639	    "woman_raising_hand": "🙋\u200d♀️",
+2640	    "woman_raising_hand_dark_skin_tone": "🙋🏿\u200d♀️",
+2641	    "woman_raising_hand_light_skin_tone": "🙋🏻\u200d♀️",
+2642	    "woman_raising_hand_medium-dark_skin_tone": "🙋🏾\u200d♀️",
+2643	    "woman_raising_hand_medium-light_skin_tone": "🙋🏼\u200d♀️",
+2644	    "woman_raising_hand_medium_skin_tone": "🙋🏽\u200d♀️",
+2645	    "woman_rowing_boat": "🚣\u200d♀️",
+2646	    "woman_rowing_boat_dark_skin_tone": "🚣🏿\u200d♀️",
+2647	    "woman_rowing_boat_light_skin_tone": "🚣🏻\u200d♀️",
+2648	    "woman_rowing_boat_medium-dark_skin_tone": "🚣🏾\u200d♀️",
+2649	    "woman_rowing_boat_medium-light_skin_tone": "🚣🏼\u200d♀️",
+2650	    "woman_rowing_boat_medium_skin_tone": "🚣🏽\u200d♀️",
+2651	    "woman_running": "🏃\u200d♀️",
+2652	    "woman_running_dark_skin_tone": "🏃🏿\u200d♀️",
+2653	    "woman_running_light_skin_tone": "🏃🏻\u200d♀️",
+2654	    "woman_running_medium-dark_skin_tone": "🏃🏾\u200d♀️",
+2655	    "woman_running_medium-light_skin_tone": "🏃🏼\u200d♀️",
+2656	    "woman_running_medium_skin_tone": "🏃🏽\u200d♀️",
+2657	    "woman_scientist": "👩\u200d🔬",
+2658	    "woman_scientist_dark_skin_tone": "👩🏿\u200d🔬",
+2659	    "woman_scientist_light_skin_tone": "👩🏻\u200d🔬",
+2660	    "woman_scientist_medium-dark_skin_tone": "👩🏾\u200d🔬",
+2661	    "woman_scientist_medium-light_skin_tone": "👩🏼\u200d🔬",
+2662	    "woman_scientist_medium_skin_tone": "👩🏽\u200d🔬",
+2663	    "woman_shrugging": "🤷\u200d♀️",
+2664	    "woman_shrugging_dark_skin_tone": "🤷🏿\u200d♀️",
+2665	    "woman_shrugging_light_skin_tone": "🤷🏻\u200d♀️",
+2666	    "woman_shrugging_medium-dark_skin_tone": "🤷🏾\u200d♀️",
+2667	    "woman_shrugging_medium-light_skin_tone": "🤷🏼\u200d♀️",
+2668	    "woman_shrugging_medium_skin_tone": "🤷🏽\u200d♀️",
+2669	    "woman_singer": "👩\u200d🎤",
+2670	    "woman_singer_dark_skin_tone": "👩🏿\u200d🎤",
+2671	    "woman_singer_light_skin_tone": "👩🏻\u200d🎤",
+2672	    "woman_singer_medium-dark_skin_tone": "👩🏾\u200d🎤",
+2673	    "woman_singer_medium-light_skin_tone": "👩🏼\u200d🎤",
+2674	    "woman_singer_medium_skin_tone": "👩🏽\u200d🎤",
+2675	    "woman_student": "👩\u200d🎓",
+2676	    "woman_student_dark_skin_tone": "👩🏿\u200d🎓",
+2677	    "woman_student_light_skin_tone": "👩🏻\u200d🎓",
+2678	    "woman_student_medium-dark_skin_tone": "👩🏾\u200d🎓",
+2679	    "woman_student_medium-light_skin_tone": "👩🏼\u200d🎓",
+2680	    "woman_student_medium_skin_tone": "👩🏽\u200d🎓",
+2681	    "woman_surfing": "🏄\u200d♀️",
+2682	    "woman_surfing_dark_skin_tone": "🏄🏿\u200d♀️",
+2683	    "woman_surfing_light_skin_tone": "🏄🏻\u200d♀️",
+2684	    "woman_surfing_medium-dark_skin_tone": "🏄🏾\u200d♀️",
+2685	    "woman_surfing_medium-light_skin_tone": "🏄🏼\u200d♀️",
+2686	    "woman_surfing_medium_skin_tone": "🏄🏽\u200d♀️",
+2687	    "woman_swimming": "🏊\u200d♀️",
+2688	    "woman_swimming_dark_skin_tone": "🏊🏿\u200d♀️",
+2689	    "woman_swimming_light_skin_tone": "🏊🏻\u200d♀️",
+2690	    "woman_swimming_medium-dark_skin_tone": "🏊🏾\u200d♀️",
+2691	    "woman_swimming_medium-light_skin_tone": "🏊🏼\u200d♀️",
+2692	    "woman_swimming_medium_skin_tone": "🏊🏽\u200d♀️",
+2693	    "woman_teacher": "👩\u200d🏫",
+2694	    "woman_teacher_dark_skin_tone": "👩🏿\u200d🏫",
+2695	    "woman_teacher_light_skin_tone": "👩🏻\u200d🏫",
+2696	    "woman_teacher_medium-dark_skin_tone": "👩🏾\u200d🏫",
+2697	    "woman_teacher_medium-light_skin_tone": "👩🏼\u200d🏫",
+2698	    "woman_teacher_medium_skin_tone": "👩🏽\u200d🏫",
+2699	    "woman_technologist": "👩\u200d💻",
+2700	    "woman_technologist_dark_skin_tone": "👩🏿\u200d💻",
+2701	    "woman_technologist_light_skin_tone": "👩🏻\u200d💻",
+2702	    "woman_technologist_medium-dark_skin_tone": "👩🏾\u200d💻",
+2703	    "woman_technologist_medium-light_skin_tone": "👩🏼\u200d💻",
+2704	    "woman_technologist_medium_skin_tone": "👩🏽\u200d💻",
+2705	    "woman_tipping_hand": "💁\u200d♀️",
+2706	    "woman_tipping_hand_dark_skin_tone": "💁🏿\u200d♀️",
+2707	    "woman_tipping_hand_light_skin_tone": "💁🏻\u200d♀️",
+2708	    "woman_tipping_hand_medium-dark_skin_tone": "💁🏾\u200d♀️",
+2709	    "woman_tipping_hand_medium-light_skin_tone": "💁🏼\u200d♀️",
+2710	    "woman_tipping_hand_medium_skin_tone": "💁🏽\u200d♀️",
+2711	    "woman_vampire": "🧛\u200d♀️",
+2712	    "woman_vampire_dark_skin_tone": "🧛🏿\u200d♀️",
+2713	    "woman_vampire_light_skin_tone": "🧛🏻\u200d♀️",
+2714	    "woman_vampire_medium-dark_skin_tone": "🧛🏾\u200d♀️",
+2715	    "woman_vampire_medium-light_skin_tone": "🧛🏼\u200d♀️",
+2716	    "woman_vampire_medium_skin_tone": "🧛🏽\u200d♀️",
+2717	    "woman_walking": "🚶\u200d♀️",
+2718	    "woman_walking_dark_skin_tone": "🚶🏿\u200d♀️",
+2719	    "woman_walking_light_skin_tone": "🚶🏻\u200d♀️",
+2720	    "woman_walking_medium-dark_skin_tone": "🚶🏾\u200d♀️",
+2721	    "woman_walking_medium-light_skin_tone": "🚶🏼\u200d♀️",
+2722	    "woman_walking_medium_skin_tone": "🚶🏽\u200d♀️",
+2723	    "woman_wearing_turban": "👳\u200d♀️",
+2724	    "woman_wearing_turban_dark_skin_tone": "👳🏿\u200d♀️",
+2725	    "woman_wearing_turban_light_skin_tone": "👳🏻\u200d♀️",
+2726	    "woman_wearing_turban_medium-dark_skin_tone": "👳🏾\u200d♀️",
+2727	    "woman_wearing_turban_medium-light_skin_tone": "👳🏼\u200d♀️",
+2728	    "woman_wearing_turban_medium_skin_tone": "👳🏽\u200d♀️",
+2729	    "woman_with_headscarf": "🧕",
+2730	    "woman_with_headscarf_dark_skin_tone": "🧕🏿",
+2731	    "woman_with_headscarf_light_skin_tone": "🧕🏻",
+2732	    "woman_with_headscarf_medium-dark_skin_tone": "🧕🏾",
+2733	    "woman_with_headscarf_medium-light_skin_tone": "🧕🏼",
+2734	    "woman_with_headscarf_medium_skin_tone": "🧕🏽",
+2735	    "woman_with_probing_cane": "👩\u200d🦯",
+2736	    "woman_zombie": "🧟\u200d♀️",
+2737	    "woman’s_boot": "👢",
+2738	    "woman’s_clothes": "👚",
+2739	    "woman’s_hat": "👒",
+2740	    "woman’s_sandal": "👡",
+2741	    "women_with_bunny_ears": "👯\u200d♀️",
+2742	    "women_wrestling": "🤼\u200d♀️",
+2743	    "women’s_room": "🚺",
+2744	    "woozy_face": "🥴",
+2745	    "world_map": "🗺",
+2746	    "worried_face": "😟",
+2747	    "wrapped_gift": "🎁",
+2748	    "wrench": "🔧",
+2749	    "writing_hand": "✍",
+2750	    "writing_hand_dark_skin_tone": "✍🏿",
+2751	    "writing_hand_light_skin_tone": "✍🏻",
+2752	    "writing_hand_medium-dark_skin_tone": "✍🏾",
+2753	    "writing_hand_medium-light_skin_tone": "✍🏼",
+2754	    "writing_hand_medium_skin_tone": "✍🏽",
+2755	    "yarn": "🧶",
+2756	    "yawning_face": "🥱",
+2757	    "yellow_circle": "🟡",
+2758	    "yellow_heart": "💛",
+2759	    "yellow_square": "🟨",
+2760	    "yen_banknote": "💴",
+2761	    "yo-yo": "🪀",
+2762	    "yin_yang": "☯",
+2763	    "zany_face": "🤪",
+2764	    "zebra": "🦓",
+2765	    "zipper-mouth_face": "🤐",
+2766	    "zombie": "🧟",
+2767	    "zzz": "💤",
+2768	    "åland_islands": "🇦🇽",
+2769	    "keycap_asterisk": "*⃣",
+2770	    "keycap_digit_eight": "8⃣",
+2771	    "keycap_digit_five": "5⃣",
+2772	    "keycap_digit_four": "4⃣",
+2773	    "keycap_digit_nine": "9⃣",
+2774	    "keycap_digit_one": "1⃣",
+2775	    "keycap_digit_seven": "7⃣",
+2776	    "keycap_digit_six": "6⃣",
+2777	    "keycap_digit_three": "3⃣",
+2778	    "keycap_digit_two": "2⃣",
+2779	    "keycap_digit_zero": "0⃣",
+2780	    "keycap_number_sign": "#⃣",
+2781	    "light_skin_tone": "🏻",
+2782	    "medium_light_skin_tone": "🏼",
+2783	    "medium_skin_tone": "🏽",
+2784	    "medium_dark_skin_tone": "🏾",
+2785	    "dark_skin_tone": "🏿",
+2786	    "regional_indicator_symbol_letter_a": "🇦",
+2787	    "regional_indicator_symbol_letter_b": "🇧",
+2788	    "regional_indicator_symbol_letter_c": "🇨",
+2789	    "regional_indicator_symbol_letter_d": "🇩",
+2790	    "regional_indicator_symbol_letter_e": "🇪",
+2791	    "regional_indicator_symbol_letter_f": "🇫",
+2792	    "regional_indicator_symbol_letter_g": "🇬",
+2793	    "regional_indicator_symbol_letter_h": "🇭",
+2794	    "regional_indicator_symbol_letter_i": "🇮",
+2795	    "regional_indicator_symbol_letter_j": "🇯",
+2796	    "regional_indicator_symbol_letter_k": "🇰",
+2797	    "regional_indicator_symbol_letter_l": "🇱",
+2798	    "regional_indicator_symbol_letter_m": "🇲",
+2799	    "regional_indicator_symbol_letter_n": "🇳",
+2800	    "regional_indicator_symbol_letter_o": "🇴",
+2801	    "regional_indicator_symbol_letter_p": "🇵",
+2802	    "regional_indicator_symbol_letter_q": "🇶",
+2803	    "regional_indicator_symbol_letter_r": "🇷",
+2804	    "regional_indicator_symbol_letter_s": "🇸",
+2805	    "regional_indicator_symbol_letter_t": "🇹",
+2806	    "regional_indicator_symbol_letter_u": "🇺",
+2807	    "regional_indicator_symbol_letter_v": "🇻",
+2808	    "regional_indicator_symbol_letter_w": "🇼",
+2809	    "regional_indicator_symbol_letter_x": "🇽",
+2810	    "regional_indicator_symbol_letter_y": "🇾",
+2811	    "regional_indicator_symbol_letter_z": "🇿",
+2812	    "airplane_arriving": "🛬",
+2813	    "space_invader": "👾",
+2814	    "football": "🏈",
+2815	    "anger": "💢",
+2816	    "angry": "😠",
+2817	    "anguished": "😧",
+2818	    "signal_strength": "📶",
+2819	    "arrows_counterclockwise": "🔄",
+2820	    "arrow_heading_down": "⤵",
+2821	    "arrow_heading_up": "⤴",
+2822	    "art": "🎨",
+2823	    "astonished": "😲",
+2824	    "athletic_shoe": "👟",
+2825	    "atm": "🏧",
+2826	    "car": "🚗",
+2827	    "red_car": "🚗",
+2828	    "angel": "👼",
+2829	    "back": "🔙",
+2830	    "badminton_racquet_and_shuttlecock": "🏸",
+2831	    "dollar": "💵",
+2832	    "euro": "💶",
+2833	    "pound": "💷",
+2834	    "yen": "💴",
+2835	    "barber": "💈",
+2836	    "bath": "🛀",
+2837	    "bear": "🐻",
+2838	    "heartbeat": "💓",
+2839	    "beer": "🍺",
+2840	    "no_bell": "🔕",
+2841	    "bento": "🍱",
+2842	    "bike": "🚲",
+2843	    "bicyclist": "🚴",
+2844	    "8ball": "🎱",
+2845	    "biohazard_sign": "☣",
+2846	    "birthday": "🎂",
+2847	    "black_circle_for_record": "⏺",
+2848	    "clubs": "♣",
+2849	    "diamonds": "♦",
+2850	    "arrow_double_down": "⏬",
+2851	    "hearts": "♥",
+2852	    "rewind": "⏪",
+2853	    "black_left__pointing_double_triangle_with_vertical_bar": "⏮",
+2854	    "arrow_backward": "◀",
+2855	    "black_medium_small_square": "◾",
+2856	    "question": "❓",
+2857	    "fast_forward": "⏩",
+2858	    "black_right__pointing_double_triangle_with_vertical_bar": "⏭",
+2859	    "arrow_forward": "▶",
+2860	    "black_right__pointing_triangle_with_double_vertical_bar": "⏯",
+2861	    "arrow_right": "➡",
+2862	    "spades": "♠",
+2863	    "black_square_for_stop": "⏹",
+2864	    "sunny": "☀",
+2865	    "phone": "☎",
+2866	    "recycle": "♻",
+2867	    "arrow_double_up": "⏫",
+2868	    "busstop": "🚏",
+2869	    "date": "📅",
+2870	    "flags": "🎏",
+2871	    "cat2": "🐈",
+2872	    "joy_cat": "😹",
+2873	    "smirk_cat": "😼",
+2874	    "chart_with_downwards_trend": "📉",
+2875	    "chart_with_upwards_trend": "📈",
+2876	    "chart": "💹",
+2877	    "mega": "📣",
+2878	    "checkered_flag": "🏁",
+2879	    "accept": "🉑",
+2880	    "ideograph_advantage": "🉐",
+2881	    "congratulations": "㊗",
+2882	    "secret": "㊙",
+2883	    "m": "Ⓜ",
+2884	    "city_sunset": "🌆",
+2885	    "clapper": "🎬",
+2886	    "clap": "👏",
+2887	    "beers": "🍻",
+2888	    "clock830": "🕣",
+2889	    "clock8": "🕗",
+2890	    "clock1130": "🕦",
+2891	    "clock11": "🕚",
+2892	    "clock530": "🕠",
+2893	    "clock5": "🕔",
+2894	    "clock430": "🕟",
+2895	    "clock4": "🕓",
+2896	    "clock930": "🕤",
+2897	    "clock9": "🕘",
+2898	    "clock130": "🕜",
+2899	    "clock1": "🕐",
+2900	    "clock730": "🕢",
+2901	    "clock7": "🕖",
+2902	    "clock630": "🕡",
+2903	    "clock6": "🕕",
+2904	    "clock1030": "🕥",
+2905	    "clock10": "🕙",
+2906	    "clock330": "🕞",
+2907	    "clock3": "🕒",
+2908	    "clock1230": "🕧",
+2909	    "clock12": "🕛",
+2910	    "clock230": "🕝",
+2911	    "clock2": "🕑",
+2912	    "arrows_clockwise": "🔃",
+2913	    "repeat": "🔁",
+2914	    "repeat_one": "🔂",
+2915	    "closed_lock_with_key": "🔐",
+2916	    "mailbox_closed": "📪",
+2917	    "mailbox": "📫",
+2918	    "cloud_with_tornado": "🌪",
+2919	    "cocktail": "🍸",
+2920	    "boom": "💥",
+2921	    "compression": "🗜",
+2922	    "confounded": "😖",
+2923	    "confused": "😕",
+2924	    "rice": "🍚",
+2925	    "cow2": "🐄",
+2926	    "cricket_bat_and_ball": "🏏",
+2927	    "x": "❌",
+2928	    "cry": "😢",
+2929	    "curry": "🍛",
+2930	    "dagger_knife": "🗡",
+2931	    "dancer": "💃",
+2932	    "dark_sunglasses": "🕶",
+2933	    "dash": "💨",
+2934	    "truck": "🚚",
+2935	    "derelict_house_building": "🏚",
+2936	    "diamond_shape_with_a_dot_inside": "💠",
+2937	    "dart": "🎯",
+2938	    "disappointed_relieved": "😥",
+2939	    "disappointed": "😞",
+2940	    "do_not_litter": "🚯",
+2941	    "dog2": "🐕",
+2942	    "flipper": "🐬",
+2943	    "loop": "➿",
+2944	    "bangbang": "‼",
+2945	    "double_vertical_bar": "⏸",
+2946	    "dove_of_peace": "🕊",
+2947	    "small_red_triangle_down": "🔻",
+2948	    "arrow_down_small": "🔽",
+2949	    "arrow_down": "⬇",
+2950	    "dromedary_camel": "🐪",
+2951	    "e__mail": "📧",
+2952	    "corn": "🌽",
+2953	    "ear_of_rice": "🌾",
+2954	    "earth_americas": "🌎",
+2955	    "earth_asia": "🌏",
+2956	    "earth_africa": "🌍",
+2957	    "eight_pointed_black_star": "✴",
+2958	    "eight_spoked_asterisk": "✳",
+2959	    "eject_symbol": "⏏",
+2960	    "bulb": "💡",
+2961	    "emoji_modifier_fitzpatrick_type__1__2": "🏻",
+2962	    "emoji_modifier_fitzpatrick_type__3": "🏼",
+2963	    "emoji_modifier_fitzpatrick_type__4": "🏽",
+2964	    "emoji_modifier_fitzpatrick_type__5": "🏾",
+2965	    "emoji_modifier_fitzpatrick_type__6": "🏿",
+2966	    "end": "🔚",
+2967	    "email": "✉",
+2968	    "european_castle": "🏰",
+2969	    "european_post_office": "🏤",
+2970	    "interrobang": "⁉",
+2971	    "expressionless": "😑",
+2972	    "eyeglasses": "👓",
+2973	    "massage": "💆",
+2974	    "yum": "😋",
+2975	    "scream": "😱",
+2976	    "kissing_heart": "😘",
+2977	    "sweat": "😓",
+2978	    "face_with_head__bandage": "🤕",
+2979	    "triumph": "😤",
+2980	    "mask": "😷",
+2981	    "no_good": "🙅",
+2982	    "ok_woman": "🙆",
+2983	    "open_mouth": "😮",
+2984	    "cold_sweat": "😰",
+2985	    "stuck_out_tongue": "😛",
+2986	    "stuck_out_tongue_closed_eyes": "😝",
+2987	    "stuck_out_tongue_winking_eye": "😜",
+2988	    "joy": "😂",
+2989	    "no_mouth": "😶",
+2990	    "santa": "🎅",
+2991	    "fax": "📠",
+2992	    "fearful": "😨",
+2993	    "field_hockey_stick_and_ball": "🏑",
+2994	    "first_quarter_moon_with_face": "🌛",
+2995	    "fish_cake": "🍥",
+2996	    "fishing_pole_and_fish": "🎣",
+2997	    "facepunch": "👊",
+2998	    "punch": "👊",
+2999	    "flag_for_afghanistan": "🇦🇫",
+3000	    "flag_for_albania": "🇦🇱",
+3001	    "flag_for_algeria": "🇩🇿",
+3002	    "flag_for_american_samoa": "🇦🇸",
+3003	    "flag_for_andorra": "🇦🇩",
+3004	    "flag_for_angola": "🇦🇴",
+3005	    "flag_for_anguilla": "🇦🇮",
+3006	    "flag_for_antarctica": "🇦🇶",
+3007	    "flag_for_antigua_&_barbuda": "🇦🇬",
+3008	    "flag_for_argentina": "🇦🇷",
+3009	    "flag_for_armenia": "🇦🇲",
+3010	    "flag_for_aruba": "🇦🇼",
+3011	    "flag_for_ascension_island": "🇦🇨",
+3012	    "flag_for_australia": "🇦🇺",
+3013	    "flag_for_austria": "🇦🇹",
+3014	    "flag_for_azerbaijan": "🇦🇿",
+3015	    "flag_for_bahamas": "🇧🇸",
+3016	    "flag_for_bahrain": "🇧🇭",
+3017	    "flag_for_bangladesh": "🇧🇩",
+3018	    "flag_for_barbados": "🇧🇧",
+3019	    "flag_for_belarus": "🇧🇾",
+3020	    "flag_for_belgium": "🇧🇪",
+3021	    "flag_for_belize": "🇧🇿",
+3022	    "flag_for_benin": "🇧🇯",
+3023	    "flag_for_bermuda": "🇧🇲",
+3024	    "flag_for_bhutan": "🇧🇹",
+3025	    "flag_for_bolivia": "🇧🇴",
+3026	    "flag_for_bosnia_&_herzegovina": "🇧🇦",
+3027	    "flag_for_botswana": "🇧🇼",
+3028	    "flag_for_bouvet_island": "🇧🇻",
+3029	    "flag_for_brazil": "🇧🇷",
+3030	    "flag_for_british_indian_ocean_territory": "🇮🇴",
+3031	    "flag_for_british_virgin_islands": "🇻🇬",
+3032	    "flag_for_brunei": "🇧🇳",
+3033	    "flag_for_bulgaria": "🇧🇬",
+3034	    "flag_for_burkina_faso": "🇧🇫",
+3035	    "flag_for_burundi": "🇧🇮",
+3036	    "flag_for_cambodia": "🇰🇭",
+3037	    "flag_for_cameroon": "🇨🇲",
+3038	    "flag_for_canada": "🇨🇦",
+3039	    "flag_for_canary_islands": "🇮🇨",
+3040	    "flag_for_cape_verde": "🇨🇻",
+3041	    "flag_for_caribbean_netherlands": "🇧🇶",
+3042	    "flag_for_cayman_islands": "🇰🇾",
+3043	    "flag_for_central_african_republic": "🇨🇫",
+3044	    "flag_for_ceuta_&_melilla": "🇪🇦",
+3045	    "flag_for_chad": "🇹🇩",
+3046	    "flag_for_chile": "🇨🇱",
+3047	    "flag_for_china": "🇨🇳",
+3048	    "flag_for_christmas_island": "🇨🇽",
+3049	    "flag_for_clipperton_island": "🇨🇵",
+3050	    "flag_for_cocos__islands": "🇨🇨",
+3051	    "flag_for_colombia": "🇨🇴",
+3052	    "flag_for_comoros": "🇰🇲",
+3053	    "flag_for_congo____brazzaville": "🇨🇬",
+3054	    "flag_for_congo____kinshasa": "🇨🇩",
+3055	    "flag_for_cook_islands": "🇨🇰",
+3056	    "flag_for_costa_rica": "🇨🇷",
+3057	    "flag_for_croatia": "🇭🇷",
+3058	    "flag_for_cuba": "🇨🇺",
+3059	    "flag_for_curaçao": "🇨🇼",
+3060	    "flag_for_cyprus": "🇨🇾",
+3061	    "flag_for_czech_republic": "🇨🇿",
+3062	    "flag_for_côte_d’ivoire": "🇨🇮",
+3063	    "flag_for_denmark": "🇩🇰",
+3064	    "flag_for_diego_garcia": "🇩🇬",
+3065	    "flag_for_djibouti": "🇩🇯",
+3066	    "flag_for_dominica": "🇩🇲",
+3067	    "flag_for_dominican_republic": "🇩🇴",
+3068	    "flag_for_ecuador": "🇪🇨",
+3069	    "flag_for_egypt": "🇪🇬",
+3070	    "flag_for_el_salvador": "🇸🇻",
+3071	    "flag_for_equatorial_guinea": "🇬🇶",
+3072	    "flag_for_eritrea": "🇪🇷",
+3073	    "flag_for_estonia": "🇪🇪",
+3074	    "flag_for_ethiopia": "🇪🇹",
+3075	    "flag_for_european_union": "🇪🇺",
+3076	    "flag_for_falkland_islands": "🇫🇰",
+3077	    "flag_for_faroe_islands": "🇫🇴",
+3078	    "flag_for_fiji": "🇫🇯",
+3079	    "flag_for_finland": "🇫🇮",
+3080	    "flag_for_france": "🇫🇷",
+3081	    "flag_for_french_guiana": "🇬🇫",
+3082	    "flag_for_french_polynesia": "🇵🇫",
+3083	    "flag_for_french_southern_territories": "🇹🇫",
+3084	    "flag_for_gabon": "🇬🇦",
+3085	    "flag_for_gambia": "🇬🇲",
+3086	    "flag_for_georgia": "🇬🇪",
+3087	    "flag_for_germany": "🇩🇪",
+3088	    "flag_for_ghana": "🇬🇭",
+3089	    "flag_for_gibraltar": "🇬🇮",
+3090	    "flag_for_greece": "🇬🇷",
+3091	    "flag_for_greenland": "🇬🇱",
+3092	    "flag_for_grenada": "🇬🇩",
+3093	    "flag_for_guadeloupe": "🇬🇵",
+3094	    "flag_for_guam": "🇬🇺",
+3095	    "flag_for_guatemala": "🇬🇹",
+3096	    "flag_for_guernsey": "🇬🇬",
+3097	    "flag_for_guinea": "🇬🇳",
+3098	    "flag_for_guinea__bissau": "🇬🇼",
+3099	    "flag_for_guyana": "🇬🇾",
+3100	    "flag_for_haiti": "🇭🇹",
+3101	    "flag_for_heard_&_mcdonald_islands": "🇭🇲",
+3102	    "flag_for_honduras": "🇭🇳",
+3103	    "flag_for_hong_kong": "🇭🇰",
+3104	    "flag_for_hungary": "🇭🇺",
+3105	    "flag_for_iceland": "🇮🇸",
+3106	    "flag_for_india": "🇮🇳",
+3107	    "flag_for_indonesia": "🇮🇩",
+3108	    "flag_for_iran": "🇮🇷",
+3109	    "flag_for_iraq": "🇮🇶",
+3110	    "flag_for_ireland": "🇮🇪",
+3111	    "flag_for_isle_of_man": "🇮🇲",
+3112	    "flag_for_israel": "🇮🇱",
+3113	    "flag_for_italy": "🇮🇹",
+3114	    "flag_for_jamaica": "🇯🇲",
+3115	    "flag_for_japan": "🇯🇵",
+3116	    "flag_for_jersey": "🇯🇪",
+3117	    "flag_for_jordan": "🇯🇴",
+3118	    "flag_for_kazakhstan": "🇰🇿",
+3119	    "flag_for_kenya": "🇰🇪",
+3120	    "flag_for_kiribati": "🇰🇮",
+3121	    "flag_for_kosovo": "🇽🇰",
+3122	    "flag_for_kuwait": "🇰🇼",
+3123	    "flag_for_kyrgyzstan": "🇰🇬",
+3124	    "flag_for_laos": "🇱🇦",
+3125	    "flag_for_latvia": "🇱🇻",
+3126	    "flag_for_lebanon": "🇱🇧",
+3127	    "flag_for_lesotho": "🇱🇸",
+3128	    "flag_for_liberia": "🇱🇷",
+3129	    "flag_for_libya": "🇱🇾",
+3130	    "flag_for_liechtenstein": "🇱🇮",
+3131	    "flag_for_lithuania": "🇱🇹",
+3132	    "flag_for_luxembourg": "🇱🇺",
+3133	    "flag_for_macau": "🇲🇴",
+3134	    "flag_for_macedonia": "🇲🇰",
+3135	    "flag_for_madagascar": "🇲🇬",
+3136	    "flag_for_malawi": "🇲🇼",
+3137	    "flag_for_malaysia": "🇲🇾",
+3138	    "flag_for_maldives": "🇲🇻",
+3139	    "flag_for_mali": "🇲🇱",
+3140	    "flag_for_malta": "🇲🇹",
+3141	    "flag_for_marshall_islands": "🇲🇭",
+3142	    "flag_for_martinique": "🇲🇶",
+3143	    "flag_for_mauritania": "🇲🇷",
+3144	    "flag_for_mauritius": "🇲🇺",
+3145	    "flag_for_mayotte": "🇾🇹",
+3146	    "flag_for_mexico": "🇲🇽",
+3147	    "flag_for_micronesia": "🇫🇲",
+3148	    "flag_for_moldova": "🇲🇩",
+3149	    "flag_for_monaco": "🇲🇨",
+3150	    "flag_for_mongolia": "🇲🇳",
+3151	    "flag_for_montenegro": "🇲🇪",
+3152	    "flag_for_montserrat": "🇲🇸",
+3153	    "flag_for_morocco": "🇲🇦",
+3154	    "flag_for_mozambique": "🇲🇿",
+3155	    "flag_for_myanmar": "🇲🇲",
+3156	    "flag_for_namibia": "🇳🇦",
+3157	    "flag_for_nauru": "🇳🇷",
+3158	    "flag_for_nepal": "🇳🇵",
+3159	    "flag_for_netherlands": "🇳🇱",
+3160	    "flag_for_new_caledonia": "🇳🇨",
+3161	    "flag_for_new_zealand": "🇳🇿",
+3162	    "flag_for_nicaragua": "🇳🇮",
+3163	    "flag_for_niger": "🇳🇪",
+3164	    "flag_for_nigeria": "🇳🇬",
+3165	    "flag_for_niue": "🇳🇺",
+3166	    "flag_for_norfolk_island": "🇳🇫",
+3167	    "flag_for_north_korea": "🇰🇵",
+3168	    "flag_for_northern_mariana_islands": "🇲🇵",
+3169	    "flag_for_norway": "🇳🇴",
+3170	    "flag_for_oman": "🇴🇲",
+3171	    "flag_for_pakistan": "🇵🇰",
+3172	    "flag_for_palau": "🇵🇼",
+3173	    "flag_for_palestinian_territories": "🇵🇸",
+3174	    "flag_for_panama": "🇵🇦",
+3175	    "flag_for_papua_new_guinea": "🇵🇬",
+3176	    "flag_for_paraguay": "🇵🇾",
+3177	    "flag_for_peru": "🇵🇪",
+3178	    "flag_for_philippines": "🇵🇭",
+3179	    "flag_for_pitcairn_islands": "🇵🇳",
+3180	    "flag_for_poland": "🇵🇱",
+3181	    "flag_for_portugal": "🇵🇹",
+3182	    "flag_for_puerto_rico": "🇵🇷",
+3183	    "flag_for_qatar": "🇶🇦",
+3184	    "flag_for_romania": "🇷🇴",
+3185	    "flag_for_russia": "🇷🇺",
+3186	    "flag_for_rwanda": "🇷🇼",
+3187	    "flag_for_réunion": "🇷🇪",
+3188	    "flag_for_samoa": "🇼🇸",
+3189	    "flag_for_san_marino": "🇸🇲",
+3190	    "flag_for_saudi_arabia": "🇸🇦",
+3191	    "flag_for_senegal": "🇸🇳",
+3192	    "flag_for_serbia": "🇷🇸",
+3193	    "flag_for_seychelles": "🇸🇨",
+3194	    "flag_for_sierra_leone": "🇸🇱",
+3195	    "flag_for_singapore": "🇸🇬",
+3196	    "flag_for_sint_maarten": "🇸🇽",
+3197	    "flag_for_slovakia": "🇸🇰",
+3198	    "flag_for_slovenia": "🇸🇮",
+3199	    "flag_for_solomon_islands": "🇸🇧",
+3200	    "flag_for_somalia": "🇸🇴",
+3201	    "flag_for_south_africa": "🇿🇦",
+3202	    "flag_for_south_georgia_&_south_sandwich_islands": "🇬🇸",
+3203	    "flag_for_south_korea": "🇰🇷",
+3204	    "flag_for_south_sudan": "🇸🇸",
+3205	    "flag_for_spain": "🇪🇸",
+3206	    "flag_for_sri_lanka": "🇱🇰",
+3207	    "flag_for_st._barthélemy": "🇧🇱",
+3208	    "flag_for_st._helena": "🇸🇭",
+3209	    "flag_for_st._kitts_&_nevis": "🇰🇳",
+3210	    "flag_for_st._lucia": "🇱🇨",
+3211	    "flag_for_st._martin": "🇲🇫",
+3212	    "flag_for_st._pierre_&_miquelon": "🇵🇲",
+3213	    "flag_for_st._vincent_&_grenadines": "🇻🇨",
+3214	    "flag_for_sudan": "🇸🇩",
+3215	    "flag_for_suriname": "🇸🇷",
+3216	    "flag_for_svalbard_&_jan_mayen": "🇸🇯",
+3217	    "flag_for_swaziland": "🇸🇿",
+3218	    "flag_for_sweden": "🇸🇪",
+3219	    "flag_for_switzerland": "🇨🇭",
+3220	    "flag_for_syria": "🇸🇾",
+3221	    "flag_for_são_tomé_&_príncipe": "🇸🇹",
+3222	    "flag_for_taiwan": "🇹🇼",
+3223	    "flag_for_tajikistan": "🇹🇯",
+3224	    "flag_for_tanzania": "🇹🇿",
+3225	    "flag_for_thailand": "🇹🇭",
+3226	    "flag_for_timor__leste": "🇹🇱",
+3227	    "flag_for_togo": "🇹🇬",
+3228	    "flag_for_tokelau": "🇹🇰",
+3229	    "flag_for_tonga": "🇹🇴",
+3230	    "flag_for_trinidad_&_tobago": "🇹🇹",
+3231	    "flag_for_tristan_da_cunha": "🇹🇦",
+3232	    "flag_for_tunisia": "🇹🇳",
+3233	    "flag_for_turkey": "🇹🇷",
+3234	    "flag_for_turkmenistan": "🇹🇲",
+3235	    "flag_for_turks_&_caicos_islands": "🇹🇨",
+3236	    "flag_for_tuvalu": "🇹🇻",
+3237	    "flag_for_u.s._outlying_islands": "🇺🇲",
+3238	    "flag_for_u.s._virgin_islands": "🇻🇮",
+3239	    "flag_for_uganda": "🇺🇬",
+3240	    "flag_for_ukraine": "🇺🇦",
+3241	    "flag_for_united_arab_emirates": "🇦🇪",
+3242	    "flag_for_united_kingdom": "🇬🇧",
+3243	    "flag_for_united_states": "🇺🇸",
+3244	    "flag_for_uruguay": "🇺🇾",
+3245	    "flag_for_uzbekistan": "🇺🇿",
+3246	    "flag_for_vanuatu": "🇻🇺",
+3247	    "flag_for_vatican_city": "🇻🇦",
+3248	    "flag_for_venezuela": "🇻🇪",
+3249	    "flag_for_vietnam": "🇻🇳",
+3250	    "flag_for_wallis_&_futuna": "🇼🇫",
+3251	    "flag_for_western_sahara": "🇪🇭",
+3252	    "flag_for_yemen": "🇾🇪",
+3253	    "flag_for_zambia": "🇿🇲",
+3254	    "flag_for_zimbabwe": "🇿🇼",
+3255	    "flag_for_åland_islands": "🇦🇽",
+3256	    "golf": "⛳",
+3257	    "fleur__de__lis": "⚜",
+3258	    "muscle": "💪",
+3259	    "flushed": "😳",
+3260	    "frame_with_picture": "🖼",
+3261	    "fries": "🍟",
+3262	    "frog": "🐸",
+3263	    "hatched_chick": "🐥",
+3264	    "frowning": "😦",
+3265	    "fuelpump": "⛽",
+3266	    "full_moon_with_face": "🌝",
+3267	    "gem": "💎",
+3268	    "star2": "🌟",
+3269	    "golfer": "🏌",
+3270	    "mortar_board": "🎓",
+3271	    "grimacing": "😬",
+3272	    "smile_cat": "😸",
+3273	    "grinning": "😀",
+3274	    "grin": "😁",
+3275	    "heartpulse": "💗",
+3276	    "guardsman": "💂",
+3277	    "haircut": "💇",
+3278	    "hamster": "🐹",
+3279	    "raising_hand": "🙋",
+3280	    "headphones": "🎧",
+3281	    "hear_no_evil": "🙉",
+3282	    "cupid": "💘",
+3283	    "gift_heart": "💝",
+3284	    "heart": "❤",
+3285	    "exclamation": "❗",
+3286	    "heavy_exclamation_mark": "❗",
+3287	    "heavy_heart_exclamation_mark_ornament": "❣",
+3288	    "o": "⭕",
+3289	    "helm_symbol": "⎈",
+3290	    "helmet_with_white_cross": "⛑",
+3291	    "high_heel": "👠",
+3292	    "bullettrain_side": "🚄",
+3293	    "bullettrain_front": "🚅",
+3294	    "high_brightness": "🔆",
+3295	    "zap": "⚡",
+3296	    "hocho": "🔪",
+3297	    "knife": "🔪",
+3298	    "bee": "🐝",
+3299	    "traffic_light": "🚥",
+3300	    "racehorse": "🐎",
+3301	    "coffee": "☕",
+3302	    "hotsprings": "♨",
+3303	    "hourglass": "⌛",
+3304	    "hourglass_flowing_sand": "⏳",
+3305	    "house_buildings": "🏘",
+3306	    "100": "💯",
+3307	    "hushed": "😯",
+3308	    "ice_hockey_stick_and_puck": "🏒",
+3309	    "imp": "👿",
+3310	    "information_desk_person": "💁",
+3311	    "information_source": "ℹ",
+3312	    "capital_abcd": "🔠",
+3313	    "abc": "🔤",
+3314	    "abcd": "🔡",
+3315	    "1234": "🔢",
+3316	    "symbols": "🔣",
+3317	    "izakaya_lantern": "🏮",
+3318	    "lantern": "🏮",
+3319	    "jack_o_lantern": "🎃",
+3320	    "dolls": "🎎",
+3321	    "japanese_goblin": "👺",
+3322	    "japanese_ogre": "👹",
+3323	    "beginner": "🔰",
+3324	    "zero": "0️⃣",
+3325	    "one": "1️⃣",
+3326	    "ten": "🔟",
+3327	    "two": "2️⃣",
+3328	    "three": "3️⃣",
+3329	    "four": "4️⃣",
+3330	    "five": "5️⃣",
+3331	    "six": "6️⃣",
+3332	    "seven": "7️⃣",
+3333	    "eight": "8️⃣",
+3334	    "nine": "9️⃣",
+3335	    "couplekiss": "💏",
+3336	    "kissing_cat": "😽",
+3337	    "kissing": "😗",
+3338	    "kissing_closed_eyes": "😚",
+3339	    "kissing_smiling_eyes": "😙",
+3340	    "beetle": "🐞",
+3341	    "large_blue_circle": "🔵",
+3342	    "last_quarter_moon_with_face": "🌜",
+3343	    "leaves": "🍃",
+3344	    "mag": "🔍",
+3345	    "left_right_arrow": "↔",
+3346	    "leftwards_arrow_with_hook": "↩",
+3347	    "arrow_left": "⬅",
+3348	    "lock": "🔒",
+3349	    "lock_with_ink_pen": "🔏",
+3350	    "sob": "😭",
+3351	    "low_brightness": "🔅",
+3352	    "lower_left_ballpoint_pen": "🖊",
+3353	    "lower_left_crayon": "🖍",
+3354	    "lower_left_fountain_pen": "🖋",
+3355	    "lower_left_paintbrush": "🖌",
+3356	    "mahjong": "🀄",
+3357	    "couple": "👫",
+3358	    "man_in_business_suit_levitating": "🕴",
+3359	    "man_with_gua_pi_mao": "👲",
+3360	    "man_with_turban": "👳",
+3361	    "mans_shoe": "👞",
+3362	    "shoe": "👞",
+3363	    "menorah_with_nine_branches": "🕎",
+3364	    "mens": "🚹",
+3365	    "minidisc": "💽",
+3366	    "iphone": "📱",
+3367	    "calling": "📲",
+3368	    "money__mouth_face": "🤑",
+3369	    "moneybag": "💰",
+3370	    "rice_scene": "🎑",
+3371	    "mountain_bicyclist": "🚵",
+3372	    "mouse2": "🐁",
+3373	    "lips": "👄",
+3374	    "moyai": "🗿",
+3375	    "notes": "🎶",
+3376	    "nail_care": "💅",
+3377	    "ab": "🆎",
+3378	    "negative_squared_cross_mark": "❎",
+3379	    "a": "🅰",
+3380	    "b": "🅱",
+3381	    "o2": "🅾",
+3382	    "parking": "🅿",
+3383	    "new_moon_with_face": "🌚",
+3384	    "no_entry_sign": "🚫",
+3385	    "underage": "🔞",
+3386	    "non__potable_water": "🚱",
+3387	    "arrow_upper_right": "↗",
+3388	    "arrow_upper_left": "↖",
+3389	    "office": "🏢",
+3390	    "older_man": "👴",
+3391	    "older_woman": "👵",
+3392	    "om_symbol": "🕉",
+3393	    "on": "🔛",
+3394	    "book": "📖",
+3395	    "unlock": "🔓",
+3396	    "mailbox_with_no_mail": "📭",
+3397	    "mailbox_with_mail": "📬",
+3398	    "cd": "💿",
+3399	    "tada": "🎉",
+3400	    "feet": "🐾",
+3401	    "walking": "🚶",
+3402	    "pencil2": "✏",
+3403	    "pensive": "😔",
+3404	    "persevere": "😣",
+3405	    "bow": "🙇",
+3406	    "raised_hands": "🙌",
+3407	    "person_with_ball": "⛹",
+3408	    "person_with_blond_hair": "👱",
+3409	    "pray": "🙏",
+3410	    "person_with_pouting_face": "🙎",
+3411	    "computer": "💻",
+3412	    "pig2": "🐖",
+3413	    "hankey": "💩",
+3414	    "poop": "💩",
+3415	    "shit": "💩",
+3416	    "bamboo": "🎍",
+3417	    "gun": "🔫",
+3418	    "black_joker": "🃏",
+3419	    "rotating_light": "🚨",
+3420	    "cop": "👮",
+3421	    "stew": "🍲",
+3422	    "pouch": "👝",
+3423	    "pouting_cat": "😾",
+3424	    "rage": "😡",
+3425	    "put_litter_in_its_place": "🚮",
+3426	    "rabbit2": "🐇",
+3427	    "racing_motorcycle": "🏍",
+3428	    "radioactive_sign": "☢",
+3429	    "fist": "✊",
+3430	    "hand": "✋",
+3431	    "raised_hand_with_fingers_splayed": "🖐",
+3432	    "raised_hand_with_part_between_middle_and_ring_fingers": "🖖",
+3433	    "blue_car": "🚙",
+3434	    "apple": "🍎",
+3435	    "relieved": "😌",
+3436	    "reversed_hand_with_middle_finger_extended": "🖕",
+3437	    "mag_right": "🔎",
+3438	    "arrow_right_hook": "↪",
+3439	    "sweet_potato": "🍠",
+3440	    "robot": "🤖",
+3441	    "rolled__up_newspaper": "🗞",
+3442	    "rowboat": "🚣",
+3443	    "runner": "🏃",
+3444	    "running": "🏃",
+3445	    "running_shirt_with_sash": "🎽",
+3446	    "boat": "⛵",
+3447	    "scales": "⚖",
+3448	    "school_satchel": "🎒",
+3449	    "scorpius": "♏",
+3450	    "see_no_evil": "🙈",
+3451	    "sheep": "🐑",
+3452	    "stars": "🌠",
+3453	    "cake": "🍰",
+3454	    "six_pointed_star": "🔯",
+3455	    "ski": "🎿",
+3456	    "sleeping_accommodation": "🛌",
+3457	    "sleeping": "😴",
+3458	    "sleepy": "😪",
+3459	    "sleuth_or_spy": "🕵",
+3460	    "heart_eyes_cat": "😻",
+3461	    "smiley_cat": "😺",
+3462	    "innocent": "😇",
+3463	    "heart_eyes": "😍",
+3464	    "smiling_imp": "😈",
+3465	    "smiley": "😃",
+3466	    "sweat_smile": "😅",
+3467	    "smile": "😄",
+3468	    "laughing": "😆",
+3469	    "satisfied": "😆",
+3470	    "blush": "😊",
+3471	    "smirk": "😏",
+3472	    "smoking": "🚬",
+3473	    "snow_capped_mountain": "🏔",
+3474	    "soccer": "⚽",
+3475	    "icecream": "🍦",
+3476	    "soon": "🔜",
+3477	    "arrow_lower_right": "↘",
+3478	    "arrow_lower_left": "↙",
+3479	    "speak_no_evil": "🙊",
+3480	    "speaker": "🔈",
+3481	    "mute": "🔇",
+3482	    "sound": "🔉",
+3483	    "loud_sound": "🔊",
+3484	    "speaking_head_in_silhouette": "🗣",
+3485	    "spiral_calendar_pad": "🗓",
+3486	    "spiral_note_pad": "🗒",
+3487	    "shell": "🐚",
+3488	    "sweat_drops": "💦",
+3489	    "u5272": "🈹",
+3490	    "u5408": "🈴",
+3491	    "u55b6": "🈺",
+3492	    "u6307": "🈯",
+3493	    "u6708": "🈷",
+3494	    "u6709": "🈶",
+3495	    "u6e80": "🈵",
+3496	    "u7121": "🈚",
+3497	    "u7533": "🈸",
+3498	    "u7981": "🈲",
+3499	    "u7a7a": "🈳",
+3500	    "cl": "🆑",
+3501	    "cool": "🆒",
+3502	    "free": "🆓",
+3503	    "id": "🆔",
+3504	    "koko": "🈁",
+3505	    "sa": "🈂",
+3506	    "new": "🆕",
+3507	    "ng": "🆖",
+3508	    "ok": "🆗",
+3509	    "sos": "🆘",
+3510	    "up": "🆙",
+3511	    "vs": "🆚",
+3512	    "steam_locomotive": "🚂",
+3513	    "ramen": "🍜",
+3514	    "partly_sunny": "⛅",
+3515	    "city_sunrise": "🌇",
+3516	    "surfer": "🏄",
+3517	    "swimmer": "🏊",
+3518	    "shirt": "👕",
+3519	    "tshirt": "👕",
+3520	    "table_tennis_paddle_and_ball": "🏓",
+3521	    "tea": "🍵",
+3522	    "tv": "📺",
+3523	    "three_button_mouse": "🖱",
+3524	    "+1": "👍",
+3525	    "thumbsup": "👍",
+3526	    "__1": "👎",
+3527	    "-1": "👎",
+3528	    "thumbsdown": "👎",
+3529	    "thunder_cloud_and_rain": "⛈",
+3530	    "tiger2": "🐅",
+3531	    "tophat": "🎩",
+3532	    "top": "🔝",
+3533	    "tm": "™",
+3534	    "train2": "🚆",
+3535	    "triangular_flag_on_post": "🚩",
+3536	    "trident": "🔱",
+3537	    "twisted_rightwards_arrows": "🔀",
+3538	    "unamused": "😒",
+3539	    "small_red_triangle": "🔺",
+3540	    "arrow_up_small": "🔼",
+3541	    "arrow_up_down": "↕",
+3542	    "upside__down_face": "🙃",
+3543	    "arrow_up": "⬆",
+3544	    "v": "✌",
+3545	    "vhs": "📼",
+3546	    "wc": "🚾",
+3547	    "ocean": "🌊",
+3548	    "waving_black_flag": "🏴",
+3549	    "wave": "👋",
+3550	    "waving_white_flag": "🏳",
+3551	    "moon": "🌔",
+3552	    "scream_cat": "🙀",
+3553	    "weary": "😩",
+3554	    "weight_lifter": "🏋",
+3555	    "whale2": "🐋",
+3556	    "wheelchair": "♿",
+3557	    "point_down": "👇",
+3558	    "grey_exclamation": "❕",
+3559	    "white_frowning_face": "☹",
+3560	    "white_check_mark": "✅",
+3561	    "point_left": "👈",
+3562	    "white_medium_small_square": "◽",
+3563	    "star": "⭐",
+3564	    "grey_question": "❔",
+3565	    "point_right": "👉",
+3566	    "relaxed": "☺",
+3567	    "white_sun_behind_cloud": "🌥",
+3568	    "white_sun_behind_cloud_with_rain": "🌦",
+3569	    "white_sun_with_small_cloud": "🌤",
+3570	    "point_up_2": "👆",
+3571	    "point_up": "☝",
+3572	    "wind_blowing_face": "🌬",
+3573	    "wink": "😉",
+3574	    "wolf": "🐺",
+3575	    "dancers": "👯",
+3576	    "boot": "👢",
+3577	    "womans_clothes": "👚",
+3578	    "womans_hat": "👒",
+3579	    "sandal": "👡",
+3580	    "womens": "🚺",
+3581	    "worried": "😟",
+3582	    "gift": "🎁",
+3583	    "zipper__mouth_face": "🤐",
+3584	    "regional_indicator_a": "🇦",
+3585	    "regional_indicator_b": "🇧",
+3586	    "regional_indicator_c": "🇨",
+3587	    "regional_indicator_d": "🇩",
+3588	    "regional_indicator_e": "🇪",
+3589	    "regional_indicator_f": "🇫",
+3590	    "regional_indicator_g": "🇬",
+3591	    "regional_indicator_h": "🇭",
+3592	    "regional_indicator_i": "🇮",
+3593	    "regional_indicator_j": "🇯",
+3594	    "regional_indicator_k": "🇰",
+3595	    "regional_indicator_l": "🇱",
+3596	    "regional_indicator_m": "🇲",
+3597	    "regional_indicator_n": "🇳",
+3598	    "regional_indicator_o": "🇴",
+3599	    "regional_indicator_p": "🇵",
+3600	    "regional_indicator_q": "🇶",
+3601	    "regional_indicator_r": "🇷",
+3602	    "regional_indicator_s": "🇸",
+3603	    "regional_indicator_t": "🇹",
+3604	    "regional_indicator_u": "🇺",
+3605	    "regional_indicator_v": "🇻",
+3606	    "regional_indicator_w": "🇼",
+3607	    "regional_indicator_x": "🇽",
+3608	    "regional_indicator_y": "🇾",
+3609	    "regional_indicator_z": "🇿",
+3610	}
+
+
+ + +
+
+ +
+
+ hardcoded_password_string: Possible hardcoded password: '㊙'
+ Test ID: B105
+ Severity: LOW
+ Confidence: MEDIUM
+ CWE: CWE-259
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/rich/_emoji_codes.py
+ Line number: 2882
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b105_hardcoded_password_string.html
+ +
+
+2881	    "congratulations": "㊗",
+2882	    "secret": "㊙",
+2883	    "m": "Ⓜ",
+2884	    "city_sunset": "🌆",
+2885	    "clapper": "🎬",
+2886	    "clap": "👏",
+2887	    "beers": "🍻",
+2888	    "clock830": "🕣",
+2889	    "clock8": "🕗",
+2890	    "clock1130": "🕦",
+2891	    "clock11": "🕚",
+2892	    "clock530": "🕠",
+2893	    "clock5": "🕔",
+2894	    "clock430": "🕟",
+2895	    "clock4": "🕓",
+2896	    "clock930": "🕤",
+2897	    "clock9": "🕘",
+2898	    "clock130": "🕜",
+2899	    "clock1": "🕐",
+2900	    "clock730": "🕢",
+2901	    "clock7": "🕖",
+2902	    "clock630": "🕡",
+2903	    "clock6": "🕕",
+2904	    "clock1030": "🕥",
+2905	    "clock10": "🕙",
+2906	    "clock330": "🕞",
+2907	    "clock3": "🕒",
+2908	    "clock1230": "🕧",
+2909	    "clock12": "🕛",
+2910	    "clock230": "🕝",
+2911	    "clock2": "🕑",
+2912	    "arrows_clockwise": "🔃",
+2913	    "repeat": "🔁",
+2914	    "repeat_one": "🔂",
+2915	    "closed_lock_with_key": "🔐",
+2916	    "mailbox_closed": "📪",
+2917	    "mailbox": "📫",
+2918	    "cloud_with_tornado": "🌪",
+2919	    "cocktail": "🍸",
+2920	    "boom": "💥",
+2921	    "compression": "🗜",
+2922	    "confounded": "😖",
+2923	    "confused": "😕",
+2924	    "rice": "🍚",
+2925	    "cow2": "🐄",
+2926	    "cricket_bat_and_ball": "🏏",
+2927	    "x": "❌",
+2928	    "cry": "😢",
+2929	    "curry": "🍛",
+2930	    "dagger_knife": "🗡",
+2931	    "dancer": "💃",
+2932	    "dark_sunglasses": "🕶",
+2933	    "dash": "💨",
+2934	    "truck": "🚚",
+2935	    "derelict_house_building": "🏚",
+2936	    "diamond_shape_with_a_dot_inside": "💠",
+2937	    "dart": "🎯",
+2938	    "disappointed_relieved": "😥",
+2939	    "disappointed": "😞",
+2940	    "do_not_litter": "🚯",
+2941	    "dog2": "🐕",
+2942	    "flipper": "🐬",
+2943	    "loop": "➿",
+2944	    "bangbang": "‼",
+2945	    "double_vertical_bar": "⏸",
+2946	    "dove_of_peace": "🕊",
+2947	    "small_red_triangle_down": "🔻",
+2948	    "arrow_down_small": "🔽",
+2949	    "arrow_down": "⬇",
+2950	    "dromedary_camel": "🐪",
+2951	    "e__mail": "📧",
+2952	    "corn": "🌽",
+2953	    "ear_of_rice": "🌾",
+2954	    "earth_americas": "🌎",
+2955	    "earth_asia": "🌏",
+2956	    "earth_africa": "🌍",
+2957	    "eight_pointed_black_star": "✴",
+2958	    "eight_spoked_asterisk": "✳",
+2959	    "eject_symbol": "⏏",
+2960	    "bulb": "💡",
+2961	    "emoji_modifier_fitzpatrick_type__1__2": "🏻",
+2962	    "emoji_modifier_fitzpatrick_type__3": "🏼",
+2963	    "emoji_modifier_fitzpatrick_type__4": "🏽",
+2964	    "emoji_modifier_fitzpatrick_type__5": "🏾",
+2965	    "emoji_modifier_fitzpatrick_type__6": "🏿",
+2966	    "end": "🔚",
+2967	    "email": "✉",
+2968	    "european_castle": "🏰",
+2969	    "european_post_office": "🏤",
+2970	    "interrobang": "⁉",
+2971	    "expressionless": "😑",
+2972	    "eyeglasses": "👓",
+2973	    "massage": "💆",
+2974	    "yum": "😋",
+2975	    "scream": "😱",
+2976	    "kissing_heart": "😘",
+2977	    "sweat": "😓",
+2978	    "face_with_head__bandage": "🤕",
+2979	    "triumph": "😤",
+2980	    "mask": "😷",
+2981	    "no_good": "🙅",
+2982	    "ok_woman": "🙆",
+2983	    "open_mouth": "😮",
+2984	    "cold_sweat": "😰",
+2985	    "stuck_out_tongue": "😛",
+2986	    "stuck_out_tongue_closed_eyes": "😝",
+2987	    "stuck_out_tongue_winking_eye": "😜",
+2988	    "joy": "😂",
+2989	    "no_mouth": "😶",
+2990	    "santa": "🎅",
+2991	    "fax": "📠",
+2992	    "fearful": "😨",
+2993	    "field_hockey_stick_and_ball": "🏑",
+2994	    "first_quarter_moon_with_face": "🌛",
+2995	    "fish_cake": "🍥",
+2996	    "fishing_pole_and_fish": "🎣",
+2997	    "facepunch": "👊",
+2998	    "punch": "👊",
+2999	    "flag_for_afghanistan": "🇦🇫",
+3000	    "flag_for_albania": "🇦🇱",
+3001	    "flag_for_algeria": "🇩🇿",
+3002	    "flag_for_american_samoa": "🇦🇸",
+3003	    "flag_for_andorra": "🇦🇩",
+3004	    "flag_for_angola": "🇦🇴",
+3005	    "flag_for_anguilla": "🇦🇮",
+3006	    "flag_for_antarctica": "🇦🇶",
+3007	    "flag_for_antigua_&_barbuda": "🇦🇬",
+3008	    "flag_for_argentina": "🇦🇷",
+3009	    "flag_for_armenia": "🇦🇲",
+3010	    "flag_for_aruba": "🇦🇼",
+3011	    "flag_for_ascension_island": "🇦🇨",
+3012	    "flag_for_australia": "🇦🇺",
+3013	    "flag_for_austria": "🇦🇹",
+3014	    "flag_for_azerbaijan": "🇦🇿",
+3015	    "flag_for_bahamas": "🇧🇸",
+3016	    "flag_for_bahrain": "🇧🇭",
+3017	    "flag_for_bangladesh": "🇧🇩",
+3018	    "flag_for_barbados": "🇧🇧",
+3019	    "flag_for_belarus": "🇧🇾",
+3020	    "flag_for_belgium": "🇧🇪",
+3021	    "flag_for_belize": "🇧🇿",
+3022	    "flag_for_benin": "🇧🇯",
+3023	    "flag_for_bermuda": "🇧🇲",
+3024	    "flag_for_bhutan": "🇧🇹",
+3025	    "flag_for_bolivia": "🇧🇴",
+3026	    "flag_for_bosnia_&_herzegovina": "🇧🇦",
+3027	    "flag_for_botswana": "🇧🇼",
+3028	    "flag_for_bouvet_island": "🇧🇻",
+3029	    "flag_for_brazil": "🇧🇷",
+3030	    "flag_for_british_indian_ocean_territory": "🇮🇴",
+3031	    "flag_for_british_virgin_islands": "🇻🇬",
+3032	    "flag_for_brunei": "🇧🇳",
+3033	    "flag_for_bulgaria": "🇧🇬",
+3034	    "flag_for_burkina_faso": "🇧🇫",
+3035	    "flag_for_burundi": "🇧🇮",
+3036	    "flag_for_cambodia": "🇰🇭",
+3037	    "flag_for_cameroon": "🇨🇲",
+3038	    "flag_for_canada": "🇨🇦",
+3039	    "flag_for_canary_islands": "🇮🇨",
+3040	    "flag_for_cape_verde": "🇨🇻",
+3041	    "flag_for_caribbean_netherlands": "🇧🇶",
+3042	    "flag_for_cayman_islands": "🇰🇾",
+3043	    "flag_for_central_african_republic": "🇨🇫",
+3044	    "flag_for_ceuta_&_melilla": "🇪🇦",
+3045	    "flag_for_chad": "🇹🇩",
+3046	    "flag_for_chile": "🇨🇱",
+3047	    "flag_for_china": "🇨🇳",
+3048	    "flag_for_christmas_island": "🇨🇽",
+3049	    "flag_for_clipperton_island": "🇨🇵",
+3050	    "flag_for_cocos__islands": "🇨🇨",
+3051	    "flag_for_colombia": "🇨🇴",
+3052	    "flag_for_comoros": "🇰🇲",
+3053	    "flag_for_congo____brazzaville": "🇨🇬",
+3054	    "flag_for_congo____kinshasa": "🇨🇩",
+3055	    "flag_for_cook_islands": "🇨🇰",
+3056	    "flag_for_costa_rica": "🇨🇷",
+3057	    "flag_for_croatia": "🇭🇷",
+3058	    "flag_for_cuba": "🇨🇺",
+3059	    "flag_for_curaçao": "🇨🇼",
+3060	    "flag_for_cyprus": "🇨🇾",
+3061	    "flag_for_czech_republic": "🇨🇿",
+3062	    "flag_for_côte_d’ivoire": "🇨🇮",
+3063	    "flag_for_denmark": "🇩🇰",
+3064	    "flag_for_diego_garcia": "🇩🇬",
+3065	    "flag_for_djibouti": "🇩🇯",
+3066	    "flag_for_dominica": "🇩🇲",
+3067	    "flag_for_dominican_republic": "🇩🇴",
+3068	    "flag_for_ecuador": "🇪🇨",
+3069	    "flag_for_egypt": "🇪🇬",
+3070	    "flag_for_el_salvador": "🇸🇻",
+3071	    "flag_for_equatorial_guinea": "🇬🇶",
+3072	    "flag_for_eritrea": "🇪🇷",
+3073	    "flag_for_estonia": "🇪🇪",
+3074	    "flag_for_ethiopia": "🇪🇹",
+3075	    "flag_for_european_union": "🇪🇺",
+3076	    "flag_for_falkland_islands": "🇫🇰",
+3077	    "flag_for_faroe_islands": "🇫🇴",
+3078	    "flag_for_fiji": "🇫🇯",
+3079	    "flag_for_finland": "🇫🇮",
+3080	    "flag_for_france": "🇫🇷",
+3081	    "flag_for_french_guiana": "🇬🇫",
+3082	    "flag_for_french_polynesia": "🇵🇫",
+3083	    "flag_for_french_southern_territories": "🇹🇫",
+3084	    "flag_for_gabon": "🇬🇦",
+3085	    "flag_for_gambia": "🇬🇲",
+3086	    "flag_for_georgia": "🇬🇪",
+3087	    "flag_for_germany": "🇩🇪",
+3088	    "flag_for_ghana": "🇬🇭",
+3089	    "flag_for_gibraltar": "🇬🇮",
+3090	    "flag_for_greece": "🇬🇷",
+3091	    "flag_for_greenland": "🇬🇱",
+3092	    "flag_for_grenada": "🇬🇩",
+3093	    "flag_for_guadeloupe": "🇬🇵",
+3094	    "flag_for_guam": "🇬🇺",
+3095	    "flag_for_guatemala": "🇬🇹",
+3096	    "flag_for_guernsey": "🇬🇬",
+3097	    "flag_for_guinea": "🇬🇳",
+3098	    "flag_for_guinea__bissau": "🇬🇼",
+3099	    "flag_for_guyana": "🇬🇾",
+3100	    "flag_for_haiti": "🇭🇹",
+3101	    "flag_for_heard_&_mcdonald_islands": "🇭🇲",
+3102	    "flag_for_honduras": "🇭🇳",
+3103	    "flag_for_hong_kong": "🇭🇰",
+3104	    "flag_for_hungary": "🇭🇺",
+3105	    "flag_for_iceland": "🇮🇸",
+3106	    "flag_for_india": "🇮🇳",
+3107	    "flag_for_indonesia": "🇮🇩",
+3108	    "flag_for_iran": "🇮🇷",
+3109	    "flag_for_iraq": "🇮🇶",
+3110	    "flag_for_ireland": "🇮🇪",
+3111	    "flag_for_isle_of_man": "🇮🇲",
+3112	    "flag_for_israel": "🇮🇱",
+3113	    "flag_for_italy": "🇮🇹",
+3114	    "flag_for_jamaica": "🇯🇲",
+3115	    "flag_for_japan": "🇯🇵",
+3116	    "flag_for_jersey": "🇯🇪",
+3117	    "flag_for_jordan": "🇯🇴",
+3118	    "flag_for_kazakhstan": "🇰🇿",
+3119	    "flag_for_kenya": "🇰🇪",
+3120	    "flag_for_kiribati": "🇰🇮",
+3121	    "flag_for_kosovo": "🇽🇰",
+3122	    "flag_for_kuwait": "🇰🇼",
+3123	    "flag_for_kyrgyzstan": "🇰🇬",
+3124	    "flag_for_laos": "🇱🇦",
+3125	    "flag_for_latvia": "🇱🇻",
+3126	    "flag_for_lebanon": "🇱🇧",
+3127	    "flag_for_lesotho": "🇱🇸",
+3128	    "flag_for_liberia": "🇱🇷",
+3129	    "flag_for_libya": "🇱🇾",
+3130	    "flag_for_liechtenstein": "🇱🇮",
+3131	    "flag_for_lithuania": "🇱🇹",
+3132	    "flag_for_luxembourg": "🇱🇺",
+3133	    "flag_for_macau": "🇲🇴",
+3134	    "flag_for_macedonia": "🇲🇰",
+3135	    "flag_for_madagascar": "🇲🇬",
+3136	    "flag_for_malawi": "🇲🇼",
+3137	    "flag_for_malaysia": "🇲🇾",
+3138	    "flag_for_maldives": "🇲🇻",
+3139	    "flag_for_mali": "🇲🇱",
+3140	    "flag_for_malta": "🇲🇹",
+3141	    "flag_for_marshall_islands": "🇲🇭",
+3142	    "flag_for_martinique": "🇲🇶",
+3143	    "flag_for_mauritania": "🇲🇷",
+3144	    "flag_for_mauritius": "🇲🇺",
+3145	    "flag_for_mayotte": "🇾🇹",
+3146	    "flag_for_mexico": "🇲🇽",
+3147	    "flag_for_micronesia": "🇫🇲",
+3148	    "flag_for_moldova": "🇲🇩",
+3149	    "flag_for_monaco": "🇲🇨",
+3150	    "flag_for_mongolia": "🇲🇳",
+3151	    "flag_for_montenegro": "🇲🇪",
+3152	    "flag_for_montserrat": "🇲🇸",
+3153	    "flag_for_morocco": "🇲🇦",
+3154	    "flag_for_mozambique": "🇲🇿",
+3155	    "flag_for_myanmar": "🇲🇲",
+3156	    "flag_for_namibia": "🇳🇦",
+3157	    "flag_for_nauru": "🇳🇷",
+3158	    "flag_for_nepal": "🇳🇵",
+3159	    "flag_for_netherlands": "🇳🇱",
+3160	    "flag_for_new_caledonia": "🇳🇨",
+3161	    "flag_for_new_zealand": "🇳🇿",
+3162	    "flag_for_nicaragua": "🇳🇮",
+3163	    "flag_for_niger": "🇳🇪",
+3164	    "flag_for_nigeria": "🇳🇬",
+3165	    "flag_for_niue": "🇳🇺",
+3166	    "flag_for_norfolk_island": "🇳🇫",
+3167	    "flag_for_north_korea": "🇰🇵",
+3168	    "flag_for_northern_mariana_islands": "🇲🇵",
+3169	    "flag_for_norway": "🇳🇴",
+3170	    "flag_for_oman": "🇴🇲",
+3171	    "flag_for_pakistan": "🇵🇰",
+3172	    "flag_for_palau": "🇵🇼",
+3173	    "flag_for_palestinian_territories": "🇵🇸",
+3174	    "flag_for_panama": "🇵🇦",
+3175	    "flag_for_papua_new_guinea": "🇵🇬",
+3176	    "flag_for_paraguay": "🇵🇾",
+3177	    "flag_for_peru": "🇵🇪",
+3178	    "flag_for_philippines": "🇵🇭",
+3179	    "flag_for_pitcairn_islands": "🇵🇳",
+3180	    "flag_for_poland": "🇵🇱",
+3181	    "flag_for_portugal": "🇵🇹",
+3182	    "flag_for_puerto_rico": "🇵🇷",
+3183	    "flag_for_qatar": "🇶🇦",
+3184	    "flag_for_romania": "🇷🇴",
+3185	    "flag_for_russia": "🇷🇺",
+3186	    "flag_for_rwanda": "🇷🇼",
+3187	    "flag_for_réunion": "🇷🇪",
+3188	    "flag_for_samoa": "🇼🇸",
+3189	    "flag_for_san_marino": "🇸🇲",
+3190	    "flag_for_saudi_arabia": "🇸🇦",
+3191	    "flag_for_senegal": "🇸🇳",
+3192	    "flag_for_serbia": "🇷🇸",
+3193	    "flag_for_seychelles": "🇸🇨",
+3194	    "flag_for_sierra_leone": "🇸🇱",
+3195	    "flag_for_singapore": "🇸🇬",
+3196	    "flag_for_sint_maarten": "🇸🇽",
+3197	    "flag_for_slovakia": "🇸🇰",
+3198	    "flag_for_slovenia": "🇸🇮",
+3199	    "flag_for_solomon_islands": "🇸🇧",
+3200	    "flag_for_somalia": "🇸🇴",
+3201	    "flag_for_south_africa": "🇿🇦",
+3202	    "flag_for_south_georgia_&_south_sandwich_islands": "🇬🇸",
+3203	    "flag_for_south_korea": "🇰🇷",
+3204	    "flag_for_south_sudan": "🇸🇸",
+3205	    "flag_for_spain": "🇪🇸",
+3206	    "flag_for_sri_lanka": "🇱🇰",
+3207	    "flag_for_st._barthélemy": "🇧🇱",
+3208	    "flag_for_st._helena": "🇸🇭",
+3209	    "flag_for_st._kitts_&_nevis": "🇰🇳",
+3210	    "flag_for_st._lucia": "🇱🇨",
+3211	    "flag_for_st._martin": "🇲🇫",
+3212	    "flag_for_st._pierre_&_miquelon": "🇵🇲",
+3213	    "flag_for_st._vincent_&_grenadines": "🇻🇨",
+3214	    "flag_for_sudan": "🇸🇩",
+3215	    "flag_for_suriname": "🇸🇷",
+3216	    "flag_for_svalbard_&_jan_mayen": "🇸🇯",
+3217	    "flag_for_swaziland": "🇸🇿",
+3218	    "flag_for_sweden": "🇸🇪",
+3219	    "flag_for_switzerland": "🇨🇭",
+3220	    "flag_for_syria": "🇸🇾",
+3221	    "flag_for_são_tomé_&_príncipe": "🇸🇹",
+3222	    "flag_for_taiwan": "🇹🇼",
+3223	    "flag_for_tajikistan": "🇹🇯",
+3224	    "flag_for_tanzania": "🇹🇿",
+3225	    "flag_for_thailand": "🇹🇭",
+3226	    "flag_for_timor__leste": "🇹🇱",
+3227	    "flag_for_togo": "🇹🇬",
+3228	    "flag_for_tokelau": "🇹🇰",
+3229	    "flag_for_tonga": "🇹🇴",
+3230	    "flag_for_trinidad_&_tobago": "🇹🇹",
+3231	    "flag_for_tristan_da_cunha": "🇹🇦",
+3232	    "flag_for_tunisia": "🇹🇳",
+3233	    "flag_for_turkey": "🇹🇷",
+3234	    "flag_for_turkmenistan": "🇹🇲",
+3235	    "flag_for_turks_&_caicos_islands": "🇹🇨",
+3236	    "flag_for_tuvalu": "🇹🇻",
+3237	    "flag_for_u.s._outlying_islands": "🇺🇲",
+3238	    "flag_for_u.s._virgin_islands": "🇻🇮",
+3239	    "flag_for_uganda": "🇺🇬",
+3240	    "flag_for_ukraine": "🇺🇦",
+3241	    "flag_for_united_arab_emirates": "🇦🇪",
+3242	    "flag_for_united_kingdom": "🇬🇧",
+3243	    "flag_for_united_states": "🇺🇸",
+3244	    "flag_for_uruguay": "🇺🇾",
+3245	    "flag_for_uzbekistan": "🇺🇿",
+3246	    "flag_for_vanuatu": "🇻🇺",
+3247	    "flag_for_vatican_city": "🇻🇦",
+3248	    "flag_for_venezuela": "🇻🇪",
+3249	    "flag_for_vietnam": "🇻🇳",
+3250	    "flag_for_wallis_&_futuna": "🇼🇫",
+3251	    "flag_for_western_sahara": "🇪🇭",
+3252	    "flag_for_yemen": "🇾🇪",
+3253	    "flag_for_zambia": "🇿🇲",
+3254	    "flag_for_zimbabwe": "🇿🇼",
+3255	    "flag_for_åland_islands": "🇦🇽",
+3256	    "golf": "⛳",
+3257	    "fleur__de__lis": "⚜",
+3258	    "muscle": "💪",
+3259	    "flushed": "😳",
+3260	    "frame_with_picture": "🖼",
+3261	    "fries": "🍟",
+3262	    "frog": "🐸",
+3263	    "hatched_chick": "🐥",
+3264	    "frowning": "😦",
+3265	    "fuelpump": "⛽",
+3266	    "full_moon_with_face": "🌝",
+3267	    "gem": "💎",
+3268	    "star2": "🌟",
+3269	    "golfer": "🏌",
+3270	    "mortar_board": "🎓",
+3271	    "grimacing": "😬",
+3272	    "smile_cat": "😸",
+3273	    "grinning": "😀",
+3274	    "grin": "😁",
+3275	    "heartpulse": "💗",
+3276	    "guardsman": "💂",
+3277	    "haircut": "💇",
+3278	    "hamster": "🐹",
+3279	    "raising_hand": "🙋",
+3280	    "headphones": "🎧",
+3281	    "hear_no_evil": "🙉",
+3282	    "cupid": "💘",
+3283	    "gift_heart": "💝",
+3284	    "heart": "❤",
+3285	    "exclamation": "❗",
+3286	    "heavy_exclamation_mark": "❗",
+3287	    "heavy_heart_exclamation_mark_ornament": "❣",
+3288	    "o": "⭕",
+3289	    "helm_symbol": "⎈",
+3290	    "helmet_with_white_cross": "⛑",
+3291	    "high_heel": "👠",
+3292	    "bullettrain_side": "🚄",
+3293	    "bullettrain_front": "🚅",
+3294	    "high_brightness": "🔆",
+3295	    "zap": "⚡",
+3296	    "hocho": "🔪",
+3297	    "knife": "🔪",
+3298	    "bee": "🐝",
+3299	    "traffic_light": "🚥",
+3300	    "racehorse": "🐎",
+3301	    "coffee": "☕",
+3302	    "hotsprings": "♨",
+3303	    "hourglass": "⌛",
+3304	    "hourglass_flowing_sand": "⏳",
+3305	    "house_buildings": "🏘",
+3306	    "100": "💯",
+3307	    "hushed": "😯",
+3308	    "ice_hockey_stick_and_puck": "🏒",
+3309	    "imp": "👿",
+3310	    "information_desk_person": "💁",
+3311	    "information_source": "ℹ",
+3312	    "capital_abcd": "🔠",
+3313	    "abc": "🔤",
+3314	    "abcd": "🔡",
+3315	    "1234": "🔢",
+3316	    "symbols": "🔣",
+3317	    "izakaya_lantern": "🏮",
+3318	    "lantern": "🏮",
+3319	    "jack_o_lantern": "🎃",
+3320	    "dolls": "🎎",
+3321	    "japanese_goblin": "👺",
+3322	    "japanese_ogre": "👹",
+3323	    "beginner": "🔰",
+3324	    "zero": "0️⃣",
+3325	    "one": "1️⃣",
+3326	    "ten": "🔟",
+3327	    "two": "2️⃣",
+3328	    "three": "3️⃣",
+3329	    "four": "4️⃣",
+3330	    "five": "5️⃣",
+3331	    "six": "6️⃣",
+3332	    "seven": "7️⃣",
+3333	    "eight": "8️⃣",
+3334	    "nine": "9️⃣",
+3335	    "couplekiss": "💏",
+3336	    "kissing_cat": "😽",
+3337	    "kissing": "😗",
+3338	    "kissing_closed_eyes": "😚",
+3339	    "kissing_smiling_eyes": "😙",
+3340	    "beetle": "🐞",
+3341	    "large_blue_circle": "🔵",
+3342	    "last_quarter_moon_with_face": "🌜",
+3343	    "leaves": "🍃",
+3344	    "mag": "🔍",
+3345	    "left_right_arrow": "↔",
+3346	    "leftwards_arrow_with_hook": "↩",
+3347	    "arrow_left": "⬅",
+3348	    "lock": "🔒",
+3349	    "lock_with_ink_pen": "🔏",
+3350	    "sob": "😭",
+3351	    "low_brightness": "🔅",
+3352	    "lower_left_ballpoint_pen": "🖊",
+3353	    "lower_left_crayon": "🖍",
+3354	    "lower_left_fountain_pen": "🖋",
+3355	    "lower_left_paintbrush": "🖌",
+3356	    "mahjong": "🀄",
+3357	    "couple": "👫",
+3358	    "man_in_business_suit_levitating": "🕴",
+3359	    "man_with_gua_pi_mao": "👲",
+3360	    "man_with_turban": "👳",
+3361	    "mans_shoe": "👞",
+3362	    "shoe": "👞",
+3363	    "menorah_with_nine_branches": "🕎",
+3364	    "mens": "🚹",
+3365	    "minidisc": "💽",
+3366	    "iphone": "📱",
+3367	    "calling": "📲",
+3368	    "money__mouth_face": "🤑",
+3369	    "moneybag": "💰",
+3370	    "rice_scene": "🎑",
+3371	    "mountain_bicyclist": "🚵",
+3372	    "mouse2": "🐁",
+3373	    "lips": "👄",
+3374	    "moyai": "🗿",
+3375	    "notes": "🎶",
+3376	    "nail_care": "💅",
+3377	    "ab": "🆎",
+3378	    "negative_squared_cross_mark": "❎",
+3379	    "a": "🅰",
+3380	    "b": "🅱",
+3381	    "o2": "🅾",
+3382	    "parking": "🅿",
+3383	    "new_moon_with_face": "🌚",
+3384	    "no_entry_sign": "🚫",
+3385	    "underage": "🔞",
+3386	    "non__potable_water": "🚱",
+3387	    "arrow_upper_right": "↗",
+3388	    "arrow_upper_left": "↖",
+3389	    "office": "🏢",
+3390	    "older_man": "👴",
+3391	    "older_woman": "👵",
+3392	    "om_symbol": "🕉",
+3393	    "on": "🔛",
+3394	    "book": "📖",
+3395	    "unlock": "🔓",
+3396	    "mailbox_with_no_mail": "📭",
+3397	    "mailbox_with_mail": "📬",
+3398	    "cd": "💿",
+3399	    "tada": "🎉",
+3400	    "feet": "🐾",
+3401	    "walking": "🚶",
+3402	    "pencil2": "✏",
+3403	    "pensive": "😔",
+3404	    "persevere": "😣",
+3405	    "bow": "🙇",
+3406	    "raised_hands": "🙌",
+3407	    "person_with_ball": "⛹",
+3408	    "person_with_blond_hair": "👱",
+3409	    "pray": "🙏",
+3410	    "person_with_pouting_face": "🙎",
+3411	    "computer": "💻",
+3412	    "pig2": "🐖",
+3413	    "hankey": "💩",
+3414	    "poop": "💩",
+3415	    "shit": "💩",
+3416	    "bamboo": "🎍",
+3417	    "gun": "🔫",
+3418	    "black_joker": "🃏",
+3419	    "rotating_light": "🚨",
+3420	    "cop": "👮",
+3421	    "stew": "🍲",
+3422	    "pouch": "👝",
+3423	    "pouting_cat": "😾",
+3424	    "rage": "😡",
+3425	    "put_litter_in_its_place": "🚮",
+3426	    "rabbit2": "🐇",
+3427	    "racing_motorcycle": "🏍",
+3428	    "radioactive_sign": "☢",
+3429	    "fist": "✊",
+3430	    "hand": "✋",
+3431	    "raised_hand_with_fingers_splayed": "🖐",
+3432	    "raised_hand_with_part_between_middle_and_ring_fingers": "🖖",
+3433	    "blue_car": "🚙",
+3434	    "apple": "🍎",
+3435	    "relieved": "😌",
+3436	    "reversed_hand_with_middle_finger_extended": "🖕",
+3437	    "mag_right": "🔎",
+3438	    "arrow_right_hook": "↪",
+3439	    "sweet_potato": "🍠",
+3440	    "robot": "🤖",
+3441	    "rolled__up_newspaper": "🗞",
+3442	    "rowboat": "🚣",
+3443	    "runner": "🏃",
+3444	    "running": "🏃",
+3445	    "running_shirt_with_sash": "🎽",
+3446	    "boat": "⛵",
+3447	    "scales": "⚖",
+3448	    "school_satchel": "🎒",
+3449	    "scorpius": "♏",
+3450	    "see_no_evil": "🙈",
+3451	    "sheep": "🐑",
+3452	    "stars": "🌠",
+3453	    "cake": "🍰",
+3454	    "six_pointed_star": "🔯",
+3455	    "ski": "🎿",
+3456	    "sleeping_accommodation": "🛌",
+3457	    "sleeping": "😴",
+3458	    "sleepy": "😪",
+3459	    "sleuth_or_spy": "🕵",
+3460	    "heart_eyes_cat": "😻",
+3461	    "smiley_cat": "😺",
+3462	    "innocent": "😇",
+3463	    "heart_eyes": "😍",
+3464	    "smiling_imp": "😈",
+3465	    "smiley": "😃",
+3466	    "sweat_smile": "😅",
+3467	    "smile": "😄",
+3468	    "laughing": "😆",
+3469	    "satisfied": "😆",
+3470	    "blush": "😊",
+3471	    "smirk": "😏",
+3472	    "smoking": "🚬",
+3473	    "snow_capped_mountain": "🏔",
+3474	    "soccer": "⚽",
+3475	    "icecream": "🍦",
+3476	    "soon": "🔜",
+3477	    "arrow_lower_right": "↘",
+3478	    "arrow_lower_left": "↙",
+3479	    "speak_no_evil": "🙊",
+3480	    "speaker": "🔈",
+3481	    "mute": "🔇",
+3482	    "sound": "🔉",
+3483	    "loud_sound": "🔊",
+3484	    "speaking_head_in_silhouette": "🗣",
+3485	    "spiral_calendar_pad": "🗓",
+3486	    "spiral_note_pad": "🗒",
+3487	    "shell": "🐚",
+3488	    "sweat_drops": "💦",
+3489	    "u5272": "🈹",
+3490	    "u5408": "🈴",
+3491	    "u55b6": "🈺",
+3492	    "u6307": "🈯",
+3493	    "u6708": "🈷",
+3494	    "u6709": "🈶",
+3495	    "u6e80": "🈵",
+3496	    "u7121": "🈚",
+3497	    "u7533": "🈸",
+3498	    "u7981": "🈲",
+3499	    "u7a7a": "🈳",
+3500	    "cl": "🆑",
+3501	    "cool": "🆒",
+3502	    "free": "🆓",
+3503	    "id": "🆔",
+3504	    "koko": "🈁",
+3505	    "sa": "🈂",
+3506	    "new": "🆕",
+3507	    "ng": "🆖",
+3508	    "ok": "🆗",
+3509	    "sos": "🆘",
+3510	    "up": "🆙",
+3511	    "vs": "🆚",
+3512	    "steam_locomotive": "🚂",
+3513	    "ramen": "🍜",
+3514	    "partly_sunny": "⛅",
+3515	    "city_sunrise": "🌇",
+3516	    "surfer": "🏄",
+3517	    "swimmer": "🏊",
+3518	    "shirt": "👕",
+3519	    "tshirt": "👕",
+3520	    "table_tennis_paddle_and_ball": "🏓",
+3521	    "tea": "🍵",
+3522	    "tv": "📺",
+3523	    "three_button_mouse": "🖱",
+3524	    "+1": "👍",
+3525	    "thumbsup": "👍",
+3526	    "__1": "👎",
+3527	    "-1": "👎",
+3528	    "thumbsdown": "👎",
+3529	    "thunder_cloud_and_rain": "⛈",
+3530	    "tiger2": "🐅",
+3531	    "tophat": "🎩",
+3532	    "top": "🔝",
+3533	    "tm": "™",
+3534	    "train2": "🚆",
+3535	    "triangular_flag_on_post": "🚩",
+3536	    "trident": "🔱",
+3537	    "twisted_rightwards_arrows": "🔀",
+3538	    "unamused": "😒",
+3539	    "small_red_triangle": "🔺",
+3540	    "arrow_up_small": "🔼",
+3541	    "arrow_up_down": "↕",
+3542	    "upside__down_face": "🙃",
+3543	    "arrow_up": "⬆",
+3544	    "v": "✌",
+3545	    "vhs": "📼",
+3546	    "wc": "🚾",
+3547	    "ocean": "🌊",
+3548	    "waving_black_flag": "🏴",
+3549	    "wave": "👋",
+3550	    "waving_white_flag": "🏳",
+3551	    "moon": "🌔",
+3552	    "scream_cat": "🙀",
+3553	    "weary": "😩",
+3554	    "weight_lifter": "🏋",
+3555	    "whale2": "🐋",
+3556	    "wheelchair": "♿",
+3557	    "point_down": "👇",
+3558	    "grey_exclamation": "❕",
+3559	    "white_frowning_face": "☹",
+3560	    "white_check_mark": "✅",
+3561	    "point_left": "👈",
+3562	    "white_medium_small_square": "◽",
+3563	    "star": "⭐",
+3564	    "grey_question": "❔",
+3565	    "point_right": "👉",
+3566	    "relaxed": "☺",
+3567	    "white_sun_behind_cloud": "🌥",
+3568	    "white_sun_behind_cloud_with_rain": "🌦",
+3569	    "white_sun_with_small_cloud": "🌤",
+3570	    "point_up_2": "👆",
+3571	    "point_up": "☝",
+3572	    "wind_blowing_face": "🌬",
+3573	    "wink": "😉",
+3574	    "wolf": "🐺",
+3575	    "dancers": "👯",
+3576	    "boot": "👢",
+3577	    "womans_clothes": "👚",
+3578	    "womans_hat": "👒",
+3579	    "sandal": "👡",
+3580	    "womens": "🚺",
+3581	    "worried": "😟",
+3582	    "gift": "🎁",
+3583	    "zipper__mouth_face": "🤐",
+3584	    "regional_indicator_a": "🇦",
+3585	    "regional_indicator_b": "🇧",
+3586	    "regional_indicator_c": "🇨",
+3587	    "regional_indicator_d": "🇩",
+3588	    "regional_indicator_e": "🇪",
+3589	    "regional_indicator_f": "🇫",
+3590	    "regional_indicator_g": "🇬",
+3591	    "regional_indicator_h": "🇭",
+3592	    "regional_indicator_i": "🇮",
+3593	    "regional_indicator_j": "🇯",
+3594	    "regional_indicator_k": "🇰",
+3595	    "regional_indicator_l": "🇱",
+3596	    "regional_indicator_m": "🇲",
+3597	    "regional_indicator_n": "🇳",
+3598	    "regional_indicator_o": "🇴",
+3599	    "regional_indicator_p": "🇵",
+3600	    "regional_indicator_q": "🇶",
+3601	    "regional_indicator_r": "🇷",
+3602	    "regional_indicator_s": "🇸",
+3603	    "regional_indicator_t": "🇹",
+3604	    "regional_indicator_u": "🇺",
+3605	    "regional_indicator_v": "🇻",
+3606	    "regional_indicator_w": "🇼",
+3607	    "regional_indicator_x": "🇽",
+3608	    "regional_indicator_y": "🇾",
+3609	    "regional_indicator_z": "🇿",
+3610	}
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/rich/_pick.py
+ Line number: 13
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+12	    """
+13	    assert values, "1 or more values required"
+14	    for value in values:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/rich/_ratio.py
+ Line number: 129
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+128	    total_ratio = sum(ratios)
+129	    assert total_ratio > 0, "Sum of ratios must be > 0"
+130	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/rich/_win32_console.py
+ Line number: 436
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+435	
+436	        assert fore is not None
+437	        assert back is not None
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/rich/_win32_console.py
+ Line number: 437
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+436	        assert fore is not None
+437	        assert back is not None
+438	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/rich/_win32_console.py
+ Line number: 566
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+565	        """
+566	        assert len(title) < 255, "Console title must be less than 255 characters"
+567	        SetConsoleTitle(title)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/rich/color.py
+ Line number: 365
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+364	        if self.type == ColorType.TRUECOLOR:
+365	            assert self.triplet is not None
+366	            return self.triplet
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/rich/color.py
+ Line number: 368
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+367	        elif self.type == ColorType.EIGHT_BIT:
+368	            assert self.number is not None
+369	            return EIGHT_BIT_PALETTE[self.number]
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/rich/color.py
+ Line number: 371
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+370	        elif self.type == ColorType.STANDARD:
+371	            assert self.number is not None
+372	            return theme.ansi_colors[self.number]
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/rich/color.py
+ Line number: 374
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+373	        elif self.type == ColorType.WINDOWS:
+374	            assert self.number is not None
+375	            return WINDOWS_PALETTE[self.number]
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/rich/color.py
+ Line number: 377
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+376	        else:  # self.type == ColorType.DEFAULT:
+377	            assert self.number is None
+378	            return theme.foreground_color if foreground else theme.background_color
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/rich/color.py
+ Line number: 493
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+492	            number = self.number
+493	            assert number is not None
+494	            fore, back = (30, 40) if number < 8 else (82, 92)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/rich/color.py
+ Line number: 499
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+498	            number = self.number
+499	            assert number is not None
+500	            fore, back = (30, 40) if number < 8 else (82, 92)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/rich/color.py
+ Line number: 504
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+503	        elif _type == ColorType.EIGHT_BIT:
+504	            assert self.number is not None
+505	            return ("38" if foreground else "48", "5", str(self.number))
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/rich/color.py
+ Line number: 508
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+507	        else:  # self.standard == ColorStandard.TRUECOLOR:
+508	            assert self.triplet is not None
+509	            red, green, blue = self.triplet
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/rich/color.py
+ Line number: 520
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+519	        if system == ColorSystem.EIGHT_BIT and self.system == ColorSystem.TRUECOLOR:
+520	            assert self.triplet is not None
+521	            _h, l, s = rgb_to_hls(*self.triplet.normalized)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/rich/color.py
+ Line number: 546
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+545	            if self.system == ColorSystem.TRUECOLOR:
+546	                assert self.triplet is not None
+547	                triplet = self.triplet
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/rich/color.py
+ Line number: 549
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+548	            else:  # self.system == ColorSystem.EIGHT_BIT
+549	                assert self.number is not None
+550	                triplet = ColorTriplet(*EIGHT_BIT_PALETTE[self.number])
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/rich/color.py
+ Line number: 557
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+556	            if self.system == ColorSystem.TRUECOLOR:
+557	                assert self.triplet is not None
+558	                triplet = self.triplet
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/rich/color.py
+ Line number: 560
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+559	            else:  # self.system == ColorSystem.EIGHT_BIT
+560	                assert self.number is not None
+561	                if self.number < 16:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/rich/color.py
+ Line number: 573
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+572	    """Parse six hex characters in to RGB triplet."""
+573	    assert len(hex_color) == 6, "must be 6 characters"
+574	    color = ColorTriplet(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/rich/console.py
+ Line number: 1135
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1134	
+1135	        assert count >= 0, "count must be >= 0"
+1136	        self.print(NewLine(count))
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/rich/console.py
+ Line number: 1900
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1899	                offset -= 1
+1900	            assert frame is not None
+1901	            return frame.f_code.co_filename, frame.f_lineno, frame.f_locals
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/rich/console.py
+ Line number: 2138
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2137	        """
+2138	        assert (
+2139	            self.record
+2140	        ), "To export console contents set record=True in the constructor or instance"
+2141	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/rich/console.py
+ Line number: 2194
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2193	        """
+2194	        assert (
+2195	            self.record
+2196	        ), "To export console contents set record=True in the constructor or instance"
+2197	        fragments: List[str] = []
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/rich/live.py
+ Line number: 65
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+64	    ) -> None:
+65	        assert refresh_per_second > 0, "refresh_per_second must be > 0"
+66	        self._renderable = renderable
+
+
+ + +
+
+ +
+
+ blacklist: Standard pseudo-random generators are not suitable for security/cryptographic purposes.
+ Test ID: B311
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-330
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/rich/live.py
+ Line number: 352
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b311-random
+ +
+
+351	                time.sleep(0.4)
+352	                if random.randint(0, 10) < 1:
+353	                    console.log(next(examples))
+
+
+ + +
+
+ +
+
+ blacklist: Standard pseudo-random generators are not suitable for security/cryptographic purposes.
+ Test ID: B311
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-330
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/rich/live.py
+ Line number: 355
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b311-random
+ +
+
+354	                exchange_rate_dict[(select_exchange, exchange)] = 200 / (
+355	                    (random.random() * 320) + 1
+356	                )
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/rich/logging.py
+ Line number: 136
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+135	            exc_type, exc_value, exc_traceback = record.exc_info
+136	            assert exc_type is not None
+137	            assert exc_value is not None
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/rich/logging.py
+ Line number: 137
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+136	            assert exc_type is not None
+137	            assert exc_value is not None
+138	            traceback = Traceback.from_exception(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/rich/pretty.py
+ Line number: 191
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+190	    console = console or get_console()
+191	    assert console is not None
+192	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/rich/pretty.py
+ Line number: 196
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+195	        if value is not None:
+196	            assert console is not None
+197	            builtins._ = None  # type: ignore[attr-defined]
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/rich/pretty.py
+ Line number: 496
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+495	        )
+496	        assert self.node is not None
+497	        return self.node.check_length(start_length, max_length)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/rich/pretty.py
+ Line number: 502
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+501	        node = self.node
+502	        assert node is not None
+503	        whitespace = self.whitespace
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/rich/pretty.py
+ Line number: 504
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+503	        whitespace = self.whitespace
+504	        assert node.children
+505	        if node.key_repr:
+
+
+ + +
+
+ +
+
+ try_except_pass: Try, Except, Pass detected.
+ Test ID: B110
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/rich/pretty.py
+ Line number: 641
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b110_try_except_pass.html
+ +
+
+640	                    rich_repr_result = obj.__rich_repr__()
+641	            except Exception:
+642	                pass
+643	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/rich/progress.py
+ Line number: 1080
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1079	    ) -> None:
+1080	        assert refresh_per_second > 0, "refresh_per_second must be > 0"
+1081	        self._lock = RLock()
+
+
+ + +
+
+ +
+
+ blacklist: Standard pseudo-random generators are not suitable for security/cryptographic purposes.
+ Test ID: B311
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-330
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/rich/progress.py
+ Line number: 1701
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b311-random
+ +
+
+1700	            time.sleep(0.01)
+1701	            if random.randint(0, 100) < 1:
+1702	                progress.log(next(examples))
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/rich/prompt.py
+ Line number: 214
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+213	        """
+214	        assert self.choices is not None
+215	        return value.strip() in self.choices
+
+
+ + +
+
+ +
+
+ blacklist: Standard pseudo-random generators are not suitable for security/cryptographic purposes.
+ Test ID: B311
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-330
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/rich/style.py
+ Line number: 193
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b311-random
+ +
+
+192	        self._link_id = (
+193	            f"{randint(0, 999999)}{hash(self._meta)}" if (link or meta) else ""
+194	        )
+
+
+ + +
+
+ +
+
+ blacklist: Standard pseudo-random generators are not suitable for security/cryptographic purposes.
+ Test ID: B311
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-330
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/rich/style.py
+ Line number: 243
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b311-random
+ +
+
+242	        style._meta = dumps(meta)
+243	        style._link_id = f"{randint(0, 999999)}{hash(style._meta)}"
+244	        style._hash = None
+
+
+ + +
+
+ +
+
+ blacklist: Deserialization with the marshal module is possibly dangerous.
+ Test ID: B302
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-502
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/rich/style.py
+ Line number: 475
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b302-marshal
+ +
+
+474	        """Get meta information (can not be changed after construction)."""
+475	        return {} if self._meta is None else cast(Dict[str, Any], loads(self._meta))
+476	
+
+
+ + +
+
+ +
+
+ blacklist: Standard pseudo-random generators are not suitable for security/cryptographic purposes.
+ Test ID: B311
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-330
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/rich/style.py
+ Line number: 490
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b311-random
+ +
+
+489	        style._link = self._link
+490	        style._link_id = f"{randint(0, 999999)}" if self._link else ""
+491	        style._null = False
+
+
+ + +
+
+ +
+
+ blacklist: Standard pseudo-random generators are not suitable for security/cryptographic purposes.
+ Test ID: B311
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-330
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/rich/style.py
+ Line number: 642
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b311-random
+ +
+
+641	        style._link = self._link
+642	        style._link_id = f"{randint(0, 999999)}" if self._link else ""
+643	        style._hash = self._hash
+
+
+ + +
+
+ +
+
+ blacklist: Standard pseudo-random generators are not suitable for security/cryptographic purposes.
+ Test ID: B311
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-330
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/rich/style.py
+ Line number: 688
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b311-random
+ +
+
+687	        style._link = link
+688	        style._link_id = f"{randint(0, 999999)}" if link else ""
+689	        style._hash = None
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/rich/syntax.py
+ Line number: 482
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+481	                    """Split tokens to one per line."""
+482	                    assert lexer  # required to make MyPy happy - we know lexer is not None at this point
+483	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/rich/text.py
+ Line number: 787
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+786	            tab_size = self.tab_size
+787	        assert tab_size is not None
+788	        result = self.blank_copy()
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/rich/text.py
+ Line number: 856
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+855	        """
+856	        assert len(character) == 1, "Character must be a string of length 1"
+857	        if count:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/rich/text.py
+ Line number: 873
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+872	        """
+873	        assert len(character) == 1, "Character must be a string of length 1"
+874	        if count:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/rich/text.py
+ Line number: 889
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+888	        """
+889	        assert len(character) == 1, "Character must be a string of length 1"
+890	        if count:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/rich/text.py
+ Line number: 1024
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1023	        """
+1024	        assert separator, "separator must not be empty"
+1025	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/rich/traceback.py
+ Line number: 282
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+281	            if not isinstance(suppress_entity, str):
+282	                assert (
+283	                    suppress_entity.__file__ is not None
+284	                ), f"{suppress_entity!r} must be a module with '__file__' attribute"
+285	                path = os.path.dirname(suppress_entity.__file__)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/rich/traceback.py
+ Line number: 645
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+644	            if excluded:
+645	                assert exclude_frames is not None
+646	                yield Text(
+
+
+ + +
+
+ +
+
+ exec_used: Use of exec detected.
+ Test ID: B102
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/six.py
+ Line number: 735
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b102_exec_used.html
+ +
+
+734	            _locs_ = _globs_
+735	        exec("""exec _code_ in _globs_, _locs_""")
+736	
+
+
+ + +
+
+ +
+
+ blacklist: Standard pseudo-random generators are not suitable for security/cryptographic purposes.
+ Test ID: B311
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-330
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/tenacity/wait.py
+ Line number: 72
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b311-random
+ +
+
+71	    def __call__(self, retry_state: "RetryCallState") -> float:
+72	        return self.wait_random_min + (random.random() * (self.wait_random_max - self.wait_random_min))
+73	
+
+
+ + +
+
+ +
+
+ blacklist: Standard pseudo-random generators are not suitable for security/cryptographic purposes.
+ Test ID: B311
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-330
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/tenacity/wait.py
+ Line number: 194
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b311-random
+ +
+
+193	        high = super().__call__(retry_state=retry_state)
+194	        return random.uniform(0, high)
+195	
+
+
+ + +
+
+ +
+
+ blacklist: Standard pseudo-random generators are not suitable for security/cryptographic purposes.
+ Test ID: B311
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-330
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/tenacity/wait.py
+ Line number: 222
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b311-random
+ +
+
+221	    def __call__(self, retry_state: "RetryCallState") -> float:
+222	        jitter = random.uniform(0, self.jitter)
+223	        try:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/typing_extensions.py
+ Line number: 374
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+373	                            deduped_pairs.remove(pair)
+374	                    assert not deduped_pairs, deduped_pairs
+375	                    parameters = tuple(new_parameters)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/typing_extensions.py
+ Line number: 1300
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1299	        def copy_with(self, params):
+1300	            assert len(params) == 1
+1301	            new_type = params[0]
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/typing_extensions.py
+ Line number: 2613
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2612	        def __new__(cls, typename, bases, ns):
+2613	            assert _NamedTuple in bases
+2614	            for base in bases:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/typing_extensions.py
+ Line number: 2654
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2653	    def _namedtuple_mro_entries(bases):
+2654	        assert NamedTuple in bases
+2655	        return (_NamedTuple,)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/urllib3/contrib/securetransport.py
+ Line number: 719
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+718	            leaf = Security.SecTrustGetCertificateAtIndex(trust, 0)
+719	            assert leaf
+720	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/urllib3/contrib/securetransport.py
+ Line number: 723
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+722	            certdata = Security.SecCertificateCopyData(leaf)
+723	            assert certdata
+724	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/urllib3/contrib/securetransport.py
+ Line number: 901
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+900	        # See PEP 543 for the real deal.
+901	        assert not server_side
+902	        assert do_handshake_on_connect
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/urllib3/contrib/securetransport.py
+ Line number: 902
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+901	        assert not server_side
+902	        assert do_handshake_on_connect
+903	        assert suppress_ragged_eofs
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/urllib3/contrib/securetransport.py
+ Line number: 903
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+902	        assert do_handshake_on_connect
+903	        assert suppress_ragged_eofs
+904	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/urllib3/packages/backports/makefile.py
+ Line number: 23
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+22	    reading = "r" in mode or not writing
+23	    assert reading or writing
+24	    binary = "b" in mode
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/urllib3/packages/backports/makefile.py
+ Line number: 45
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+44	    else:
+45	        assert writing
+46	        buffer = io.BufferedWriter(raw, buffering)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/urllib3/packages/backports/weakref_finalize.py
+ Line number: 150
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+149	                        sys.excepthook(*sys.exc_info())
+150	                    assert f not in cls._registry
+151	        finally:
+
+
+ + +
+
+ +
+
+ exec_used: Use of exec detected.
+ Test ID: B102
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/urllib3/packages/six.py
+ Line number: 787
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b102_exec_used.html
+ +
+
+786	            _locs_ = _globs_
+787	        exec ("""exec _code_ in _globs_, _locs_""")
+788	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/urllib3/response.py
+ Line number: 495
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+494	        """
+495	        assert self._fp
+496	        c_int_max = 2 ** 31 - 1
+
+
+ + +
+
+ +
+
+ try_except_pass: Try, Except, Pass detected.
+ Test ID: B110
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/urllib3/util/connection.py
+ Line number: 141
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b110_try_except_pass.html
+ +
+
+140	            has_ipv6 = True
+141	        except Exception:
+142	            pass
+143	
+
+
+ + +
+
+ +
+
+ ssl_with_no_version: ssl.wrap_socket call with no SSL/TLS protocol version specified, the default SSLv23 could be insecure, possible security issue.
+ Test ID: B504
+ Severity: LOW
+ Confidence: MEDIUM
+ CWE: CWE-327
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/urllib3/util/ssl_.py
+ Line number: 179
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b504_ssl_with_no_version.html
+ +
+
+178	            }
+179	            return wrap_socket(socket, ciphers=self.ciphers, **kwargs)
+180	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/urllib3/util/ssltransport.py
+ Line number: 120
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+119	        reading = "r" in mode or not writing
+120	        assert reading or writing
+121	        binary = "b" in mode
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/urllib3/util/ssltransport.py
+ Line number: 142
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+141	        else:
+142	            assert writing
+143	            buffer = io.BufferedWriter(raw, buffering)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/__init__.py
+ Line number: 224
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+223	        if output:
+224	            assert decoder.encoding is not None
+225	            yield decoder.encoding
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/__init__.py
+ Line number: 231
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+230	        output = decode(b'', final=True)
+231	        assert decoder.encoding is not None
+232	        yield decoder.encoding
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/mklabels.py
+ Line number: 21
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+20	def assert_lower(string):
+21	    assert string == string.lower()
+22	    return string
+
+
+ + +
+
+ +
+
+ blacklist: Audit url open for permitted schemes. Allowing use of file:/ or custom schemes is often unexpected.
+ Test ID: B310
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-22
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/mklabels.py
+ Line number: 47
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b310-urllib-urlopen
+ +
+
+46	         repr(encoding['name']).lstrip('u'))
+47	        for category in json.loads(urlopen(url).read().decode('ascii'))
+48	        for encoding in category['encodings']
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 30
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+29	def test_labels():
+30	    assert lookup('utf-8').name == 'utf-8'
+31	    assert lookup('Utf-8').name == 'utf-8'
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 31
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+30	    assert lookup('utf-8').name == 'utf-8'
+31	    assert lookup('Utf-8').name == 'utf-8'
+32	    assert lookup('UTF-8').name == 'utf-8'
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 32
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+31	    assert lookup('Utf-8').name == 'utf-8'
+32	    assert lookup('UTF-8').name == 'utf-8'
+33	    assert lookup('utf8').name == 'utf-8'
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 33
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+32	    assert lookup('UTF-8').name == 'utf-8'
+33	    assert lookup('utf8').name == 'utf-8'
+34	    assert lookup('utf8').name == 'utf-8'
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 34
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+33	    assert lookup('utf8').name == 'utf-8'
+34	    assert lookup('utf8').name == 'utf-8'
+35	    assert lookup('utf8 ').name == 'utf-8'
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 35
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+34	    assert lookup('utf8').name == 'utf-8'
+35	    assert lookup('utf8 ').name == 'utf-8'
+36	    assert lookup(' \r\nutf8\t').name == 'utf-8'
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 36
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+35	    assert lookup('utf8 ').name == 'utf-8'
+36	    assert lookup(' \r\nutf8\t').name == 'utf-8'
+37	    assert lookup('u8') is None  # Python label.
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 37
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+36	    assert lookup(' \r\nutf8\t').name == 'utf-8'
+37	    assert lookup('u8') is None  # Python label.
+38	    assert lookup('utf-8 ') is None  # Non-ASCII white space.
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 38
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+37	    assert lookup('u8') is None  # Python label.
+38	    assert lookup('utf-8 ') is None  # Non-ASCII white space.
+39	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 40
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+39	
+40	    assert lookup('US-ASCII').name == 'windows-1252'
+41	    assert lookup('iso-8859-1').name == 'windows-1252'
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 41
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+40	    assert lookup('US-ASCII').name == 'windows-1252'
+41	    assert lookup('iso-8859-1').name == 'windows-1252'
+42	    assert lookup('latin1').name == 'windows-1252'
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 42
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+41	    assert lookup('iso-8859-1').name == 'windows-1252'
+42	    assert lookup('latin1').name == 'windows-1252'
+43	    assert lookup('LATIN1').name == 'windows-1252'
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 43
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+42	    assert lookup('latin1').name == 'windows-1252'
+43	    assert lookup('LATIN1').name == 'windows-1252'
+44	    assert lookup('latin-1') is None
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 44
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+43	    assert lookup('LATIN1').name == 'windows-1252'
+44	    assert lookup('latin-1') is None
+45	    assert lookup('LATİN1') is None  # ASCII-only case insensitivity.
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 45
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+44	    assert lookup('latin-1') is None
+45	    assert lookup('LATİN1') is None  # ASCII-only case insensitivity.
+46	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 50
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+49	    for label in LABELS:
+50	        assert decode(b'', label) == ('', lookup(label))
+51	        assert encode('', label) == b''
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 51
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+50	        assert decode(b'', label) == ('', lookup(label))
+51	        assert encode('', label) == b''
+52	        for repeat in [0, 1, 12]:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 54
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+53	            output, _ = iter_decode([b''] * repeat, label)
+54	            assert list(output) == []
+55	            assert list(iter_encode([''] * repeat, label)) == []
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 55
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+54	            assert list(output) == []
+55	            assert list(iter_encode([''] * repeat, label)) == []
+56	        decoder = IncrementalDecoder(label)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 57
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+56	        decoder = IncrementalDecoder(label)
+57	        assert decoder.decode(b'') == ''
+58	        assert decoder.decode(b'', final=True) == ''
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 58
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+57	        assert decoder.decode(b'') == ''
+58	        assert decoder.decode(b'', final=True) == ''
+59	        encoder = IncrementalEncoder(label)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 60
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+59	        encoder = IncrementalEncoder(label)
+60	        assert encoder.encode('') == b''
+61	        assert encoder.encode('', final=True) == b''
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 61
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+60	        assert encoder.encode('') == b''
+61	        assert encoder.encode('', final=True) == b''
+62	    # All encoding names are valid labels too:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 64
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+63	    for name in set(LABELS.values()):
+64	        assert lookup(name).name == name
+65	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 77
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+76	def test_decode():
+77	    assert decode(b'\x80', 'latin1') == ('€', lookup('latin1'))
+78	    assert decode(b'\x80', lookup('latin1')) == ('€', lookup('latin1'))
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 78
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+77	    assert decode(b'\x80', 'latin1') == ('€', lookup('latin1'))
+78	    assert decode(b'\x80', lookup('latin1')) == ('€', lookup('latin1'))
+79	    assert decode(b'\xc3\xa9', 'utf8') == ('é', lookup('utf8'))
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 79
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+78	    assert decode(b'\x80', lookup('latin1')) == ('€', lookup('latin1'))
+79	    assert decode(b'\xc3\xa9', 'utf8') == ('é', lookup('utf8'))
+80	    assert decode(b'\xc3\xa9', UTF8) == ('é', lookup('utf8'))
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 80
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+79	    assert decode(b'\xc3\xa9', 'utf8') == ('é', lookup('utf8'))
+80	    assert decode(b'\xc3\xa9', UTF8) == ('é', lookup('utf8'))
+81	    assert decode(b'\xc3\xa9', 'ascii') == ('é', lookup('ascii'))
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 81
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+80	    assert decode(b'\xc3\xa9', UTF8) == ('é', lookup('utf8'))
+81	    assert decode(b'\xc3\xa9', 'ascii') == ('é', lookup('ascii'))
+82	    assert decode(b'\xEF\xBB\xBF\xc3\xa9', 'ascii') == ('é', lookup('utf8'))  # UTF-8 with BOM
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 82
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+81	    assert decode(b'\xc3\xa9', 'ascii') == ('é', lookup('ascii'))
+82	    assert decode(b'\xEF\xBB\xBF\xc3\xa9', 'ascii') == ('é', lookup('utf8'))  # UTF-8 with BOM
+83	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 84
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+83	
+84	    assert decode(b'\xFE\xFF\x00\xe9', 'ascii') == ('é', lookup('utf-16be'))  # UTF-16-BE with BOM
+85	    assert decode(b'\xFF\xFE\xe9\x00', 'ascii') == ('é', lookup('utf-16le'))  # UTF-16-LE with BOM
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 85
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+84	    assert decode(b'\xFE\xFF\x00\xe9', 'ascii') == ('é', lookup('utf-16be'))  # UTF-16-BE with BOM
+85	    assert decode(b'\xFF\xFE\xe9\x00', 'ascii') == ('é', lookup('utf-16le'))  # UTF-16-LE with BOM
+86	    assert decode(b'\xFE\xFF\xe9\x00', 'ascii') == ('\ue900', lookup('utf-16be'))
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 86
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+85	    assert decode(b'\xFF\xFE\xe9\x00', 'ascii') == ('é', lookup('utf-16le'))  # UTF-16-LE with BOM
+86	    assert decode(b'\xFE\xFF\xe9\x00', 'ascii') == ('\ue900', lookup('utf-16be'))
+87	    assert decode(b'\xFF\xFE\x00\xe9', 'ascii') == ('\ue900', lookup('utf-16le'))
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 87
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+86	    assert decode(b'\xFE\xFF\xe9\x00', 'ascii') == ('\ue900', lookup('utf-16be'))
+87	    assert decode(b'\xFF\xFE\x00\xe9', 'ascii') == ('\ue900', lookup('utf-16le'))
+88	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 89
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+88	
+89	    assert decode(b'\x00\xe9', 'UTF-16BE') == ('é', lookup('utf-16be'))
+90	    assert decode(b'\xe9\x00', 'UTF-16LE') == ('é', lookup('utf-16le'))
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 90
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+89	    assert decode(b'\x00\xe9', 'UTF-16BE') == ('é', lookup('utf-16be'))
+90	    assert decode(b'\xe9\x00', 'UTF-16LE') == ('é', lookup('utf-16le'))
+91	    assert decode(b'\xe9\x00', 'UTF-16') == ('é', lookup('utf-16le'))
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 91
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+90	    assert decode(b'\xe9\x00', 'UTF-16LE') == ('é', lookup('utf-16le'))
+91	    assert decode(b'\xe9\x00', 'UTF-16') == ('é', lookup('utf-16le'))
+92	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 93
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+92	
+93	    assert decode(b'\xe9\x00', 'UTF-16BE') == ('\ue900', lookup('utf-16be'))
+94	    assert decode(b'\x00\xe9', 'UTF-16LE') == ('\ue900', lookup('utf-16le'))
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 94
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+93	    assert decode(b'\xe9\x00', 'UTF-16BE') == ('\ue900', lookup('utf-16be'))
+94	    assert decode(b'\x00\xe9', 'UTF-16LE') == ('\ue900', lookup('utf-16le'))
+95	    assert decode(b'\x00\xe9', 'UTF-16') == ('\ue900', lookup('utf-16le'))
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 95
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+94	    assert decode(b'\x00\xe9', 'UTF-16LE') == ('\ue900', lookup('utf-16le'))
+95	    assert decode(b'\x00\xe9', 'UTF-16') == ('\ue900', lookup('utf-16le'))
+96	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 99
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+98	def test_encode():
+99	    assert encode('é', 'latin1') == b'\xe9'
+100	    assert encode('é', 'utf8') == b'\xc3\xa9'
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 100
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+99	    assert encode('é', 'latin1') == b'\xe9'
+100	    assert encode('é', 'utf8') == b'\xc3\xa9'
+101	    assert encode('é', 'utf8') == b'\xc3\xa9'
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 101
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+100	    assert encode('é', 'utf8') == b'\xc3\xa9'
+101	    assert encode('é', 'utf8') == b'\xc3\xa9'
+102	    assert encode('é', 'utf-16') == b'\xe9\x00'
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 102
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+101	    assert encode('é', 'utf8') == b'\xc3\xa9'
+102	    assert encode('é', 'utf-16') == b'\xe9\x00'
+103	    assert encode('é', 'utf-16le') == b'\xe9\x00'
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 103
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+102	    assert encode('é', 'utf-16') == b'\xe9\x00'
+103	    assert encode('é', 'utf-16le') == b'\xe9\x00'
+104	    assert encode('é', 'utf-16be') == b'\x00\xe9'
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 104
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+103	    assert encode('é', 'utf-16le') == b'\xe9\x00'
+104	    assert encode('é', 'utf-16be') == b'\x00\xe9'
+105	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 111
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+110	        return ''.join(output)
+111	    assert iter_decode_to_string([], 'latin1') == ''
+112	    assert iter_decode_to_string([b''], 'latin1') == ''
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 112
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+111	    assert iter_decode_to_string([], 'latin1') == ''
+112	    assert iter_decode_to_string([b''], 'latin1') == ''
+113	    assert iter_decode_to_string([b'\xe9'], 'latin1') == 'é'
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 113
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+112	    assert iter_decode_to_string([b''], 'latin1') == ''
+113	    assert iter_decode_to_string([b'\xe9'], 'latin1') == 'é'
+114	    assert iter_decode_to_string([b'hello'], 'latin1') == 'hello'
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 114
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+113	    assert iter_decode_to_string([b'\xe9'], 'latin1') == 'é'
+114	    assert iter_decode_to_string([b'hello'], 'latin1') == 'hello'
+115	    assert iter_decode_to_string([b'he', b'llo'], 'latin1') == 'hello'
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 115
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+114	    assert iter_decode_to_string([b'hello'], 'latin1') == 'hello'
+115	    assert iter_decode_to_string([b'he', b'llo'], 'latin1') == 'hello'
+116	    assert iter_decode_to_string([b'hell', b'o'], 'latin1') == 'hello'
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 116
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+115	    assert iter_decode_to_string([b'he', b'llo'], 'latin1') == 'hello'
+116	    assert iter_decode_to_string([b'hell', b'o'], 'latin1') == 'hello'
+117	    assert iter_decode_to_string([b'\xc3\xa9'], 'latin1') == 'é'
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 117
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+116	    assert iter_decode_to_string([b'hell', b'o'], 'latin1') == 'hello'
+117	    assert iter_decode_to_string([b'\xc3\xa9'], 'latin1') == 'é'
+118	    assert iter_decode_to_string([b'\xEF\xBB\xBF\xc3\xa9'], 'latin1') == 'é'
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 118
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+117	    assert iter_decode_to_string([b'\xc3\xa9'], 'latin1') == 'é'
+118	    assert iter_decode_to_string([b'\xEF\xBB\xBF\xc3\xa9'], 'latin1') == 'é'
+119	    assert iter_decode_to_string([
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 119
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+118	    assert iter_decode_to_string([b'\xEF\xBB\xBF\xc3\xa9'], 'latin1') == 'é'
+119	    assert iter_decode_to_string([
+120	        b'\xEF\xBB\xBF', b'\xc3', b'\xa9'], 'latin1') == 'é'
+121	    assert iter_decode_to_string([
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 121
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+120	        b'\xEF\xBB\xBF', b'\xc3', b'\xa9'], 'latin1') == 'é'
+121	    assert iter_decode_to_string([
+122	        b'\xEF\xBB\xBF', b'a', b'\xc3'], 'latin1') == 'a\uFFFD'
+123	    assert iter_decode_to_string([
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 123
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+122	        b'\xEF\xBB\xBF', b'a', b'\xc3'], 'latin1') == 'a\uFFFD'
+123	    assert iter_decode_to_string([
+124	        b'', b'\xEF', b'', b'', b'\xBB\xBF\xc3', b'\xa9'], 'latin1') == 'é'
+125	    assert iter_decode_to_string([b'\xEF\xBB\xBF'], 'latin1') == ''
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 125
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+124	        b'', b'\xEF', b'', b'', b'\xBB\xBF\xc3', b'\xa9'], 'latin1') == 'é'
+125	    assert iter_decode_to_string([b'\xEF\xBB\xBF'], 'latin1') == ''
+126	    assert iter_decode_to_string([b'\xEF\xBB'], 'latin1') == 'ï»'
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 126
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+125	    assert iter_decode_to_string([b'\xEF\xBB\xBF'], 'latin1') == ''
+126	    assert iter_decode_to_string([b'\xEF\xBB'], 'latin1') == 'ï»'
+127	    assert iter_decode_to_string([b'\xFE\xFF\x00\xe9'], 'latin1') == 'é'
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 127
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+126	    assert iter_decode_to_string([b'\xEF\xBB'], 'latin1') == 'ï»'
+127	    assert iter_decode_to_string([b'\xFE\xFF\x00\xe9'], 'latin1') == 'é'
+128	    assert iter_decode_to_string([b'\xFF\xFE\xe9\x00'], 'latin1') == 'é'
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 128
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+127	    assert iter_decode_to_string([b'\xFE\xFF\x00\xe9'], 'latin1') == 'é'
+128	    assert iter_decode_to_string([b'\xFF\xFE\xe9\x00'], 'latin1') == 'é'
+129	    assert iter_decode_to_string([
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 129
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+128	    assert iter_decode_to_string([b'\xFF\xFE\xe9\x00'], 'latin1') == 'é'
+129	    assert iter_decode_to_string([
+130	        b'', b'\xFF', b'', b'', b'\xFE\xe9', b'\x00'], 'latin1') == 'é'
+131	    assert iter_decode_to_string([
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 131
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+130	        b'', b'\xFF', b'', b'', b'\xFE\xe9', b'\x00'], 'latin1') == 'é'
+131	    assert iter_decode_to_string([
+132	        b'', b'h\xe9', b'llo'], 'x-user-defined') == 'h\uF7E9llo'
+133	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 136
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+135	def test_iter_encode():
+136	    assert b''.join(iter_encode([], 'latin1')) == b''
+137	    assert b''.join(iter_encode([''], 'latin1')) == b''
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 137
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+136	    assert b''.join(iter_encode([], 'latin1')) == b''
+137	    assert b''.join(iter_encode([''], 'latin1')) == b''
+138	    assert b''.join(iter_encode(['é'], 'latin1')) == b'\xe9'
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 138
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+137	    assert b''.join(iter_encode([''], 'latin1')) == b''
+138	    assert b''.join(iter_encode(['é'], 'latin1')) == b'\xe9'
+139	    assert b''.join(iter_encode(['', 'é', '', ''], 'latin1')) == b'\xe9'
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 139
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+138	    assert b''.join(iter_encode(['é'], 'latin1')) == b'\xe9'
+139	    assert b''.join(iter_encode(['', 'é', '', ''], 'latin1')) == b'\xe9'
+140	    assert b''.join(iter_encode(['', 'é', '', ''], 'utf-16')) == b'\xe9\x00'
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 140
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+139	    assert b''.join(iter_encode(['', 'é', '', ''], 'latin1')) == b'\xe9'
+140	    assert b''.join(iter_encode(['', 'é', '', ''], 'utf-16')) == b'\xe9\x00'
+141	    assert b''.join(iter_encode(['', 'é', '', ''], 'utf-16le')) == b'\xe9\x00'
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 141
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+140	    assert b''.join(iter_encode(['', 'é', '', ''], 'utf-16')) == b'\xe9\x00'
+141	    assert b''.join(iter_encode(['', 'é', '', ''], 'utf-16le')) == b'\xe9\x00'
+142	    assert b''.join(iter_encode(['', 'é', '', ''], 'utf-16be')) == b'\x00\xe9'
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 142
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+141	    assert b''.join(iter_encode(['', 'é', '', ''], 'utf-16le')) == b'\xe9\x00'
+142	    assert b''.join(iter_encode(['', 'é', '', ''], 'utf-16be')) == b'\x00\xe9'
+143	    assert b''.join(iter_encode([
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 143
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+142	    assert b''.join(iter_encode(['', 'é', '', ''], 'utf-16be')) == b'\x00\xe9'
+143	    assert b''.join(iter_encode([
+144	        '', 'h\uF7E9', '', 'llo'], 'x-user-defined')) == b'h\xe9llo'
+145	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 152
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+151	    decoded = 'aa'
+152	    assert decode(encoded, 'x-user-defined') == (decoded, lookup('x-user-defined'))
+153	    assert encode(decoded, 'x-user-defined') == encoded
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 153
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+152	    assert decode(encoded, 'x-user-defined') == (decoded, lookup('x-user-defined'))
+153	    assert encode(decoded, 'x-user-defined') == encoded
+
+
+ + +
+
+ +
+
+ try_except_pass: Try, Except, Pass detected.
+ Test ID: B110
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pygments/cmdline.py
+ Line number: 522
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b110_try_except_pass.html
+ +
+
+521	                width = shutil.get_terminal_size().columns - 2
+522	            except Exception:
+523	                pass
+524	        argparse.HelpFormatter.__init__(self, prog, indent_increment,
+
+
+ + +
+
+ +
+
+ exec_used: Use of exec detected.
+ Test ID: B102
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/pygments/formatters/__init__.py
+ Line number: 103
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b102_exec_used.html
+ +
+
+102	        with open(filename, 'rb') as f:
+103	            exec(f.read(), custom_namespace)
+104	        # Retrieve the class `formattername` from that namespace
+
+
+ + +
+
+ +
+
+ blacklist: Consider possible security implications associated with the subprocess module.
+ Test ID: B404
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/pygments/formatters/img.py
+ Line number: 17
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_imports.html#b404-import-subprocess
+ +
+
+16	
+17	import subprocess
+18	
+
+
+ + +
+
+ +
+
+ start_process_with_partial_path: Starting a process with a partial executable path
+ Test ID: B607
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/pygments/formatters/img.py
+ Line number: 93
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b607_start_process_with_partial_path.html
+ +
+
+92	    def _get_nix_font_path(self, name, style):
+93	        proc = subprocess.Popen(['fc-list', f"{name}:style={style}", 'file'],
+94	                                stdout=subprocess.PIPE, stderr=None)
+95	        stdout, _ = proc.communicate()
+
+
+ + +
+
+ +
+
+ subprocess_without_shell_equals_true: subprocess call - check for execution of untrusted input.
+ Test ID: B603
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/pygments/formatters/img.py
+ Line number: 93
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b603_subprocess_without_shell_equals_true.html
+ +
+
+92	    def _get_nix_font_path(self, name, style):
+93	        proc = subprocess.Popen(['fc-list', f"{name}:style={style}", 'file'],
+94	                                stdout=subprocess.PIPE, stderr=None)
+95	        stdout, _ = proc.communicate()
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pygments/lexer.py
+ Line number: 514
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+513	        """Preprocess the token component of a token definition."""
+514	        assert type(token) is _TokenType or callable(token), \
+515	            f'token type must be simple type or callable, not {token!r}'
+516	        return token
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pygments/lexer.py
+ Line number: 531
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+530	            else:
+531	                assert False, f'unknown new state {new_state!r}'
+532	        elif isinstance(new_state, combined):
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pygments/lexer.py
+ Line number: 538
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+537	            for istate in new_state:
+538	                assert istate != new_state, f'circular state ref {istate!r}'
+539	                itokens.extend(cls._process_state(unprocessed,
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pygments/lexer.py
+ Line number: 546
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+545	            for istate in new_state:
+546	                assert (istate in unprocessed or
+547	                        istate in ('#pop', '#push')), \
+548	                    'unknown new state ' + istate
+549	            return new_state
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pygments/lexer.py
+ Line number: 551
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+550	        else:
+551	            assert False, f'unknown new state def {new_state!r}'
+552	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pygments/lexer.py
+ Line number: 555
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+554	        """Preprocess a single state definition."""
+555	        assert isinstance(state, str), f"wrong state name {state!r}"
+556	        assert state[0] != '#', f"invalid state name {state!r}"
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pygments/lexer.py
+ Line number: 556
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+555	        assert isinstance(state, str), f"wrong state name {state!r}"
+556	        assert state[0] != '#', f"invalid state name {state!r}"
+557	        if state in processed:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pygments/lexer.py
+ Line number: 564
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+563	                # it's a state reference
+564	                assert tdef != state, f"circular state reference {state!r}"
+565	                tokens.extend(cls._process_state(unprocessed, processed,
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pygments/lexer.py
+ Line number: 578
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+577	
+578	            assert type(tdef) is tuple, f"wrong rule def {tdef!r}"
+579	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pygments/lexer.py
+ Line number: 744
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+743	                        else:
+744	                            assert False, f"wrong state def: {new_state!r}"
+745	                        statetokens = tokendefs[statestack[-1]]
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pygments/lexer.py
+ Line number: 831
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+830	                        else:
+831	                            assert False, f"wrong state def: {new_state!r}"
+832	                        statetokens = tokendefs[ctx.stack[-1]]
+
+
+ + +
+
+ +
+
+ exec_used: Use of exec detected.
+ Test ID: B102
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/pygments/lexers/__init__.py
+ Line number: 154
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b102_exec_used.html
+ +
+
+153	        with open(filename, 'rb') as f:
+154	            exec(f.read(), custom_namespace)
+155	        # Retrieve the class `lexername` from that namespace
+
+
+ + +
+
+ +
+
+ blacklist: Audit url open for permitted schemes. Allowing use of file:/ or custom schemes is often unexpected.
+ Test ID: B310
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-22
+ File: ./venv/lib/python3.12/site-packages/pygments/lexers/_lua_builtins.py
+ Line number: 225
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b310-urllib-urlopen
+ +
+
+224	    def get_newest_version():
+225	        f = urlopen('http://www.lua.org/manual/')
+226	        r = re.compile(r'^<A HREF="(\d\.\d)/">(Lua )?\1</A>')
+
+
+ + +
+
+ +
+
+ blacklist: Audit url open for permitted schemes. Allowing use of file:/ or custom schemes is often unexpected.
+ Test ID: B310
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-22
+ File: ./venv/lib/python3.12/site-packages/pygments/lexers/_lua_builtins.py
+ Line number: 233
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b310-urllib-urlopen
+ +
+
+232	    def get_lua_functions(version):
+233	        f = urlopen(f'http://www.lua.org/manual/{version}/')
+234	        r = re.compile(r'^<A HREF="manual.html#pdf-(?!lua|LUA)([^:]+)">\1</A>')
+
+
+ + +
+
+ +
+
+ blacklist: Audit url open for permitted schemes. Allowing use of file:/ or custom schemes is often unexpected.
+ Test ID: B310
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-22
+ File: ./venv/lib/python3.12/site-packages/pygments/lexers/_mysql_builtins.py
+ Line number: 1297
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b310-urllib-urlopen
+ +
+
+1296	        # Pull content from lex.h.
+1297	        lex_file = urlopen(LEX_URL).read().decode('utf8', errors='ignore')
+1298	        keywords = parse_lex_keywords(lex_file)
+
+
+ + +
+
+ +
+
+ blacklist: Audit url open for permitted schemes. Allowing use of file:/ or custom schemes is often unexpected.
+ Test ID: B310
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-22
+ File: ./venv/lib/python3.12/site-packages/pygments/lexers/_mysql_builtins.py
+ Line number: 1303
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b310-urllib-urlopen
+ +
+
+1302	        # Parse content in item_create.cc.
+1303	        item_create_file = urlopen(ITEM_CREATE_URL).read().decode('utf8', errors='ignore')
+1304	        functions.update(parse_item_create_functions(item_create_file))
+
+
+ + +
+
+ +
+
+ blacklist: Audit url open for permitted schemes. Allowing use of file:/ or custom schemes is often unexpected.
+ Test ID: B310
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-22
+ File: ./venv/lib/python3.12/site-packages/pygments/lexers/_php_builtins.py
+ Line number: 3299
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b310-urllib-urlopen
+ +
+
+3298	    def get_php_references():
+3299	        download = urlretrieve(PHP_MANUAL_URL)
+3300	        with tarfile.open(download[0]) as tar:
+
+
+ + +
+
+ +
+
+ tarfile_unsafe_members: tarfile.extractall used without any validation. Please check and discard dangerous members.
+ Test ID: B202
+ Severity: HIGH
+ Confidence: HIGH
+ CWE: CWE-22
+ File: ./venv/lib/python3.12/site-packages/pygments/lexers/_php_builtins.py
+ Line number: 3304
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b202_tarfile_unsafe_members.html
+ +
+
+3303	            else:
+3304	                tar.extractall()
+3305	        yield from glob.glob(f"{PHP_MANUAL_DIR}{PHP_REFERENCE_GLOB}")
+
+
+ + +
+
+ +
+
+ blacklist: Audit url open for permitted schemes. Allowing use of file:/ or custom schemes is often unexpected.
+ Test ID: B310
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-22
+ File: ./venv/lib/python3.12/site-packages/pygments/lexers/_postgres_builtins.py
+ Line number: 642
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b310-urllib-urlopen
+ +
+
+641	    def update_myself():
+642	        content = urlopen(DATATYPES_URL).read().decode('utf-8', errors='ignore')
+643	        data_file = list(content.splitlines())
+
+
+ + +
+
+ +
+
+ blacklist: Audit url open for permitted schemes. Allowing use of file:/ or custom schemes is often unexpected.
+ Test ID: B310
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-22
+ File: ./venv/lib/python3.12/site-packages/pygments/lexers/_postgres_builtins.py
+ Line number: 647
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b310-urllib-urlopen
+ +
+
+646	
+647	        content = urlopen(KEYWORDS_URL).read().decode('utf-8', errors='ignore')
+648	        keywords = parse_keywords(content)
+
+
+ + +
+
+ +
+
+ blacklist: Consider possible security implications associated with the subprocess module.
+ Test ID: B404
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/pygments/lexers/_scilab_builtins.py
+ Line number: 3055
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_imports.html#b404-import-subprocess
+ +
+
+3054	if __name__ == '__main__':  # pragma: no cover
+3055	    import subprocess
+3056	    from pygments.util import format_lines, duplicates_removed
+
+
+ + +
+
+ +
+
+ start_process_with_partial_path: Starting a process with a partial executable path
+ Test ID: B607
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/pygments/lexers/_scilab_builtins.py
+ Line number: 3061
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b607_start_process_with_partial_path.html
+ +
+
+3060	    def extract_completion(var_type):
+3061	        s = subprocess.Popen(['scilab', '-nwni'], stdin=subprocess.PIPE,
+3062	                             stdout=subprocess.PIPE, stderr=subprocess.PIPE)
+3063	        output = s.communicate(f'''\
+
+
+ + +
+
+ +
+
+ subprocess_without_shell_equals_true: subprocess call - check for execution of untrusted input.
+ Test ID: B603
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/pygments/lexers/_scilab_builtins.py
+ Line number: 3061
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b603_subprocess_without_shell_equals_true.html
+ +
+
+3060	    def extract_completion(var_type):
+3061	        s = subprocess.Popen(['scilab', '-nwni'], stdin=subprocess.PIPE,
+3062	                             stdout=subprocess.PIPE, stderr=subprocess.PIPE)
+3063	        output = s.communicate(f'''\
+
+
+ + +
+
+ +
+
+ hardcoded_password_string: Possible hardcoded password: 'root'
+ Test ID: B105
+ Severity: LOW
+ Confidence: MEDIUM
+ CWE: CWE-259
+ File: ./venv/lib/python3.12/site-packages/pygments/lexers/int_fiction.py
+ Line number: 728
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b105_hardcoded_password_string.html
+ +
+
+727	        for token in Inform6Lexer.tokens:
+728	            if token == 'root':
+729	                continue
+
+
+ + +
+
+ +
+
+ hardcoded_password_string: Possible hardcoded password: '[^\W\d]\w*'
+ Test ID: B105
+ Severity: LOW
+ Confidence: MEDIUM
+ CWE: CWE-259
+ File: ./venv/lib/python3.12/site-packages/pygments/lexers/jsonnet.py
+ Line number: 17
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b105_hardcoded_password_string.html
+ +
+
+16	
+17	jsonnet_token = r'[^\W\d]\w*'
+18	jsonnet_function_token = jsonnet_token + r'(?=\()'
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pygments/lexers/lilypond.py
+ Line number: 43
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+42	    else:
+43	        assert backslash == "disallowed"
+44	    return words(names, prefix, suffix)
+
+
+ + +
+
+ +
+
+ hardcoded_password_string: Possible hardcoded password: ' + (?= + \s # whitespace + | ; # comment + | \#[;|!] # fancy comments + | [)\]] # end delimiters + | $ # end of file + ) + '
+ Test ID: B105
+ Severity: LOW
+ Confidence: MEDIUM
+ CWE: CWE-259
+ File: ./venv/lib/python3.12/site-packages/pygments/lexers/lisp.py
+ Line number: 50
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b105_hardcoded_password_string.html
+ +
+
+49	    # Use within verbose regexes
+50	    token_end = r'''
+51	      (?=
+52	        \s         # whitespace
+53	        | ;        # comment
+54	        | \#[;|!] # fancy comments
+55	        | [)\]]    # end delimiters
+56	        | $        # end of file
+57	      )
+58	    '''
+59	
+
+
+ + +
+
+ +
+
+ hardcoded_password_string: Possible hardcoded password: '(?=\s|#|[)\]]|$)'
+ Test ID: B105
+ Severity: LOW
+ Confidence: MEDIUM
+ CWE: CWE-259
+ File: ./venv/lib/python3.12/site-packages/pygments/lexers/lisp.py
+ Line number: 3047
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b105_hardcoded_password_string.html
+ +
+
+3046	    # ...so, express it like this
+3047	    _token_end = r'(?=\s|#|[)\]]|$)'
+3048	
+
+
+ + +
+
+ +
+
+ hardcoded_password_string: Possible hardcoded password: '[A-Z]\w*'
+ Test ID: B105
+ Severity: LOW
+ Confidence: MEDIUM
+ CWE: CWE-259
+ File: ./venv/lib/python3.12/site-packages/pygments/lexers/parsers.py
+ Line number: 334
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b105_hardcoded_password_string.html
+ +
+
+333	    _id = r'[A-Za-z]\w*'
+334	    _TOKEN_REF = r'[A-Z]\w*'
+335	    _RULE_REF = r'[a-z]\w*'
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pygments/lexers/scripting.py
+ Line number: 1499
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1498	                        result += 0.01
+1499	        assert 0.0 <= result <= 1.0
+1500	        return result
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pygments/lexers/scripting.py
+ Line number: 1583
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1582	                result = 1.0
+1583	        assert 0.0 <= result <= 1.0
+1584	        return result
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pygments/lexers/sql.py
+ Line number: 236
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+235	    else:
+236	        assert 0, "SQL keywords not found"
+237	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pygments/style.py
+ Line number: 79
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+78	                return text
+79	            assert False, f"wrong color format {text!r}"
+80	
+
+
+ + +
+
+ +
+
+ hardcoded_password_string: Possible hardcoded password: '㊙'
+ Test ID: B105
+ Severity: LOW
+ Confidence: MEDIUM
+ CWE: CWE-259
+ File: ./venv/lib/python3.12/site-packages/rich/_emoji_codes.py
+ Line number: 156
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b105_hardcoded_password_string.html
+ +
+
+155	    "japanese_reserved_button": "🈯",
+156	    "japanese_secret_button": "㊙",
+157	    "japanese_service_charge_button": "🈂",
+158	    "japanese_symbol_for_beginner": "🔰",
+159	    "japanese_vacancy_button": "🈳",
+160	    "jersey": "🇯🇪",
+161	    "jordan": "🇯🇴",
+162	    "kazakhstan": "🇰🇿",
+163	    "kenya": "🇰🇪",
+164	    "kiribati": "🇰🇮",
+165	    "kosovo": "🇽🇰",
+166	    "kuwait": "🇰🇼",
+167	    "kyrgyzstan": "🇰🇬",
+168	    "laos": "🇱🇦",
+169	    "latvia": "🇱🇻",
+170	    "lebanon": "🇱🇧",
+171	    "leo": "♌",
+172	    "lesotho": "🇱🇸",
+173	    "liberia": "🇱🇷",
+174	    "libra": "♎",
+175	    "libya": "🇱🇾",
+176	    "liechtenstein": "🇱🇮",
+177	    "lithuania": "🇱🇹",
+178	    "luxembourg": "🇱🇺",
+179	    "macau_sar_china": "🇲🇴",
+180	    "macedonia": "🇲🇰",
+181	    "madagascar": "🇲🇬",
+182	    "malawi": "🇲🇼",
+183	    "malaysia": "🇲🇾",
+184	    "maldives": "🇲🇻",
+185	    "mali": "🇲🇱",
+186	    "malta": "🇲🇹",
+187	    "marshall_islands": "🇲🇭",
+188	    "martinique": "🇲🇶",
+189	    "mauritania": "🇲🇷",
+190	    "mauritius": "🇲🇺",
+191	    "mayotte": "🇾🇹",
+192	    "mexico": "🇲🇽",
+193	    "micronesia": "🇫🇲",
+194	    "moldova": "🇲🇩",
+195	    "monaco": "🇲🇨",
+196	    "mongolia": "🇲🇳",
+197	    "montenegro": "🇲🇪",
+198	    "montserrat": "🇲🇸",
+199	    "morocco": "🇲🇦",
+200	    "mozambique": "🇲🇿",
+201	    "mrs._claus": "🤶",
+202	    "mrs._claus_dark_skin_tone": "🤶🏿",
+203	    "mrs._claus_light_skin_tone": "🤶🏻",
+204	    "mrs._claus_medium-dark_skin_tone": "🤶🏾",
+205	    "mrs._claus_medium-light_skin_tone": "🤶🏼",
+206	    "mrs._claus_medium_skin_tone": "🤶🏽",
+207	    "myanmar_(burma)": "🇲🇲",
+208	    "new_button": "🆕",
+209	    "ng_button": "🆖",
+210	    "namibia": "🇳🇦",
+211	    "nauru": "🇳🇷",
+212	    "nepal": "🇳🇵",
+213	    "netherlands": "🇳🇱",
+214	    "new_caledonia": "🇳🇨",
+215	    "new_zealand": "🇳🇿",
+216	    "nicaragua": "🇳🇮",
+217	    "niger": "🇳🇪",
+218	    "nigeria": "🇳🇬",
+219	    "niue": "🇳🇺",
+220	    "norfolk_island": "🇳🇫",
+221	    "north_korea": "🇰🇵",
+222	    "northern_mariana_islands": "🇲🇵",
+223	    "norway": "🇳🇴",
+224	    "ok_button": "🆗",
+225	    "ok_hand": "👌",
+226	    "ok_hand_dark_skin_tone": "👌🏿",
+227	    "ok_hand_light_skin_tone": "👌🏻",
+228	    "ok_hand_medium-dark_skin_tone": "👌🏾",
+229	    "ok_hand_medium-light_skin_tone": "👌🏼",
+230	    "ok_hand_medium_skin_tone": "👌🏽",
+231	    "on!_arrow": "🔛",
+232	    "o_button_(blood_type)": "🅾",
+233	    "oman": "🇴🇲",
+234	    "ophiuchus": "⛎",
+235	    "p_button": "🅿",
+236	    "pakistan": "🇵🇰",
+237	    "palau": "🇵🇼",
+238	    "palestinian_territories": "🇵🇸",
+239	    "panama": "🇵🇦",
+240	    "papua_new_guinea": "🇵🇬",
+241	    "paraguay": "🇵🇾",
+242	    "peru": "🇵🇪",
+243	    "philippines": "🇵🇭",
+244	    "pisces": "♓",
+245	    "pitcairn_islands": "🇵🇳",
+246	    "poland": "🇵🇱",
+247	    "portugal": "🇵🇹",
+248	    "puerto_rico": "🇵🇷",
+249	    "qatar": "🇶🇦",
+250	    "romania": "🇷🇴",
+251	    "russia": "🇷🇺",
+252	    "rwanda": "🇷🇼",
+253	    "réunion": "🇷🇪",
+254	    "soon_arrow": "🔜",
+255	    "sos_button": "🆘",
+256	    "sagittarius": "♐",
+257	    "samoa": "🇼🇸",
+258	    "san_marino": "🇸🇲",
+259	    "santa_claus": "🎅",
+260	    "santa_claus_dark_skin_tone": "🎅🏿",
+261	    "santa_claus_light_skin_tone": "🎅🏻",
+262	    "santa_claus_medium-dark_skin_tone": "🎅🏾",
+263	    "santa_claus_medium-light_skin_tone": "🎅🏼",
+264	    "santa_claus_medium_skin_tone": "🎅🏽",
+265	    "saudi_arabia": "🇸🇦",
+266	    "scorpio": "♏",
+267	    "scotland": "🏴\U000e0067\U000e0062\U000e0073\U000e0063\U000e0074\U000e007f",
+268	    "senegal": "🇸🇳",
+269	    "serbia": "🇷🇸",
+270	    "seychelles": "🇸🇨",
+271	    "sierra_leone": "🇸🇱",
+272	    "singapore": "🇸🇬",
+273	    "sint_maarten": "🇸🇽",
+274	    "slovakia": "🇸🇰",
+275	    "slovenia": "🇸🇮",
+276	    "solomon_islands": "🇸🇧",
+277	    "somalia": "🇸🇴",
+278	    "south_africa": "🇿🇦",
+279	    "south_georgia_&_south_sandwich_islands": "🇬🇸",
+280	    "south_korea": "🇰🇷",
+281	    "south_sudan": "🇸🇸",
+282	    "spain": "🇪🇸",
+283	    "sri_lanka": "🇱🇰",
+284	    "st._barthélemy": "🇧🇱",
+285	    "st._helena": "🇸🇭",
+286	    "st._kitts_&_nevis": "🇰🇳",
+287	    "st._lucia": "🇱🇨",
+288	    "st._martin": "🇲🇫",
+289	    "st._pierre_&_miquelon": "🇵🇲",
+290	    "st._vincent_&_grenadines": "🇻🇨",
+291	    "statue_of_liberty": "🗽",
+292	    "sudan": "🇸🇩",
+293	    "suriname": "🇸🇷",
+294	    "svalbard_&_jan_mayen": "🇸🇯",
+295	    "swaziland": "🇸🇿",
+296	    "sweden": "🇸🇪",
+297	    "switzerland": "🇨🇭",
+298	    "syria": "🇸🇾",
+299	    "são_tomé_&_príncipe": "🇸🇹",
+300	    "t-rex": "🦖",
+301	    "top_arrow": "🔝",
+302	    "taiwan": "🇹🇼",
+303	    "tajikistan": "🇹🇯",
+304	    "tanzania": "🇹🇿",
+305	    "taurus": "♉",
+306	    "thailand": "🇹🇭",
+307	    "timor-leste": "🇹🇱",
+308	    "togo": "🇹🇬",
+309	    "tokelau": "🇹🇰",
+310	    "tokyo_tower": "🗼",
+311	    "tonga": "🇹🇴",
+312	    "trinidad_&_tobago": "🇹🇹",
+313	    "tristan_da_cunha": "🇹🇦",
+314	    "tunisia": "🇹🇳",
+315	    "turkey": "🦃",
+316	    "turkmenistan": "🇹🇲",
+317	    "turks_&_caicos_islands": "🇹🇨",
+318	    "tuvalu": "🇹🇻",
+319	    "u.s._outlying_islands": "🇺🇲",
+320	    "u.s._virgin_islands": "🇻🇮",
+321	    "up!_button": "🆙",
+322	    "uganda": "🇺🇬",
+323	    "ukraine": "🇺🇦",
+324	    "united_arab_emirates": "🇦🇪",
+325	    "united_kingdom": "🇬🇧",
+326	    "united_nations": "🇺🇳",
+327	    "united_states": "🇺🇸",
+328	    "uruguay": "🇺🇾",
+329	    "uzbekistan": "🇺🇿",
+330	    "vs_button": "🆚",
+331	    "vanuatu": "🇻🇺",
+332	    "vatican_city": "🇻🇦",
+333	    "venezuela": "🇻🇪",
+334	    "vietnam": "🇻🇳",
+335	    "virgo": "♍",
+336	    "wales": "🏴\U000e0067\U000e0062\U000e0077\U000e006c\U000e0073\U000e007f",
+337	    "wallis_&_futuna": "🇼🇫",
+338	    "western_sahara": "🇪🇭",
+339	    "yemen": "🇾🇪",
+340	    "zambia": "🇿🇲",
+341	    "zimbabwe": "🇿🇼",
+342	    "abacus": "🧮",
+343	    "adhesive_bandage": "🩹",
+344	    "admission_tickets": "🎟",
+345	    "adult": "🧑",
+346	    "adult_dark_skin_tone": "🧑🏿",
+347	    "adult_light_skin_tone": "🧑🏻",
+348	    "adult_medium-dark_skin_tone": "🧑🏾",
+349	    "adult_medium-light_skin_tone": "🧑🏼",
+350	    "adult_medium_skin_tone": "🧑🏽",
+351	    "aerial_tramway": "🚡",
+352	    "airplane": "✈",
+353	    "airplane_arrival": "🛬",
+354	    "airplane_departure": "🛫",
+355	    "alarm_clock": "⏰",
+356	    "alembic": "⚗",
+357	    "alien": "👽",
+358	    "alien_monster": "👾",
+359	    "ambulance": "🚑",
+360	    "american_football": "🏈",
+361	    "amphora": "🏺",
+362	    "anchor": "⚓",
+363	    "anger_symbol": "💢",
+364	    "angry_face": "😠",
+365	    "angry_face_with_horns": "👿",
+366	    "anguished_face": "😧",
+367	    "ant": "🐜",
+368	    "antenna_bars": "📶",
+369	    "anxious_face_with_sweat": "😰",
+370	    "articulated_lorry": "🚛",
+371	    "artist_palette": "🎨",
+372	    "astonished_face": "😲",
+373	    "atom_symbol": "⚛",
+374	    "auto_rickshaw": "🛺",
+375	    "automobile": "🚗",
+376	    "avocado": "🥑",
+377	    "axe": "🪓",
+378	    "baby": "👶",
+379	    "baby_angel": "👼",
+380	    "baby_angel_dark_skin_tone": "👼🏿",
+381	    "baby_angel_light_skin_tone": "👼🏻",
+382	    "baby_angel_medium-dark_skin_tone": "👼🏾",
+383	    "baby_angel_medium-light_skin_tone": "👼🏼",
+384	    "baby_angel_medium_skin_tone": "👼🏽",
+385	    "baby_bottle": "🍼",
+386	    "baby_chick": "🐤",
+387	    "baby_dark_skin_tone": "👶🏿",
+388	    "baby_light_skin_tone": "👶🏻",
+389	    "baby_medium-dark_skin_tone": "👶🏾",
+390	    "baby_medium-light_skin_tone": "👶🏼",
+391	    "baby_medium_skin_tone": "👶🏽",
+392	    "baby_symbol": "🚼",
+393	    "backhand_index_pointing_down": "👇",
+394	    "backhand_index_pointing_down_dark_skin_tone": "👇🏿",
+395	    "backhand_index_pointing_down_light_skin_tone": "👇🏻",
+396	    "backhand_index_pointing_down_medium-dark_skin_tone": "👇🏾",
+397	    "backhand_index_pointing_down_medium-light_skin_tone": "👇🏼",
+398	    "backhand_index_pointing_down_medium_skin_tone": "👇🏽",
+399	    "backhand_index_pointing_left": "👈",
+400	    "backhand_index_pointing_left_dark_skin_tone": "👈🏿",
+401	    "backhand_index_pointing_left_light_skin_tone": "👈🏻",
+402	    "backhand_index_pointing_left_medium-dark_skin_tone": "👈🏾",
+403	    "backhand_index_pointing_left_medium-light_skin_tone": "👈🏼",
+404	    "backhand_index_pointing_left_medium_skin_tone": "👈🏽",
+405	    "backhand_index_pointing_right": "👉",
+406	    "backhand_index_pointing_right_dark_skin_tone": "👉🏿",
+407	    "backhand_index_pointing_right_light_skin_tone": "👉🏻",
+408	    "backhand_index_pointing_right_medium-dark_skin_tone": "👉🏾",
+409	    "backhand_index_pointing_right_medium-light_skin_tone": "👉🏼",
+410	    "backhand_index_pointing_right_medium_skin_tone": "👉🏽",
+411	    "backhand_index_pointing_up": "👆",
+412	    "backhand_index_pointing_up_dark_skin_tone": "👆🏿",
+413	    "backhand_index_pointing_up_light_skin_tone": "👆🏻",
+414	    "backhand_index_pointing_up_medium-dark_skin_tone": "👆🏾",
+415	    "backhand_index_pointing_up_medium-light_skin_tone": "👆🏼",
+416	    "backhand_index_pointing_up_medium_skin_tone": "👆🏽",
+417	    "bacon": "🥓",
+418	    "badger": "🦡",
+419	    "badminton": "🏸",
+420	    "bagel": "🥯",
+421	    "baggage_claim": "🛄",
+422	    "baguette_bread": "🥖",
+423	    "balance_scale": "⚖",
+424	    "bald": "🦲",
+425	    "bald_man": "👨\u200d🦲",
+426	    "bald_woman": "👩\u200d🦲",
+427	    "ballet_shoes": "🩰",
+428	    "balloon": "🎈",
+429	    "ballot_box_with_ballot": "🗳",
+430	    "ballot_box_with_check": "☑",
+431	    "banana": "🍌",
+432	    "banjo": "🪕",
+433	    "bank": "🏦",
+434	    "bar_chart": "📊",
+435	    "barber_pole": "💈",
+436	    "baseball": "⚾",
+437	    "basket": "🧺",
+438	    "basketball": "🏀",
+439	    "bat": "🦇",
+440	    "bathtub": "🛁",
+441	    "battery": "🔋",
+442	    "beach_with_umbrella": "🏖",
+443	    "beaming_face_with_smiling_eyes": "😁",
+444	    "bear_face": "🐻",
+445	    "bearded_person": "🧔",
+446	    "bearded_person_dark_skin_tone": "🧔🏿",
+447	    "bearded_person_light_skin_tone": "🧔🏻",
+448	    "bearded_person_medium-dark_skin_tone": "🧔🏾",
+449	    "bearded_person_medium-light_skin_tone": "🧔🏼",
+450	    "bearded_person_medium_skin_tone": "🧔🏽",
+451	    "beating_heart": "💓",
+452	    "bed": "🛏",
+453	    "beer_mug": "🍺",
+454	    "bell": "🔔",
+455	    "bell_with_slash": "🔕",
+456	    "bellhop_bell": "🛎",
+457	    "bento_box": "🍱",
+458	    "beverage_box": "🧃",
+459	    "bicycle": "🚲",
+460	    "bikini": "👙",
+461	    "billed_cap": "🧢",
+462	    "biohazard": "☣",
+463	    "bird": "🐦",
+464	    "birthday_cake": "🎂",
+465	    "black_circle": "⚫",
+466	    "black_flag": "🏴",
+467	    "black_heart": "🖤",
+468	    "black_large_square": "⬛",
+469	    "black_medium-small_square": "◾",
+470	    "black_medium_square": "◼",
+471	    "black_nib": "✒",
+472	    "black_small_square": "▪",
+473	    "black_square_button": "🔲",
+474	    "blond-haired_man": "👱\u200d♂️",
+475	    "blond-haired_man_dark_skin_tone": "👱🏿\u200d♂️",
+476	    "blond-haired_man_light_skin_tone": "👱🏻\u200d♂️",
+477	    "blond-haired_man_medium-dark_skin_tone": "👱🏾\u200d♂️",
+478	    "blond-haired_man_medium-light_skin_tone": "👱🏼\u200d♂️",
+479	    "blond-haired_man_medium_skin_tone": "👱🏽\u200d♂️",
+480	    "blond-haired_person": "👱",
+481	    "blond-haired_person_dark_skin_tone": "👱🏿",
+482	    "blond-haired_person_light_skin_tone": "👱🏻",
+483	    "blond-haired_person_medium-dark_skin_tone": "👱🏾",
+484	    "blond-haired_person_medium-light_skin_tone": "👱🏼",
+485	    "blond-haired_person_medium_skin_tone": "👱🏽",
+486	    "blond-haired_woman": "👱\u200d♀️",
+487	    "blond-haired_woman_dark_skin_tone": "👱🏿\u200d♀️",
+488	    "blond-haired_woman_light_skin_tone": "👱🏻\u200d♀️",
+489	    "blond-haired_woman_medium-dark_skin_tone": "👱🏾\u200d♀️",
+490	    "blond-haired_woman_medium-light_skin_tone": "👱🏼\u200d♀️",
+491	    "blond-haired_woman_medium_skin_tone": "👱🏽\u200d♀️",
+492	    "blossom": "🌼",
+493	    "blowfish": "🐡",
+494	    "blue_book": "📘",
+495	    "blue_circle": "🔵",
+496	    "blue_heart": "💙",
+497	    "blue_square": "🟦",
+498	    "boar": "🐗",
+499	    "bomb": "💣",
+500	    "bone": "🦴",
+501	    "bookmark": "🔖",
+502	    "bookmark_tabs": "📑",
+503	    "books": "📚",
+504	    "bottle_with_popping_cork": "🍾",
+505	    "bouquet": "💐",
+506	    "bow_and_arrow": "🏹",
+507	    "bowl_with_spoon": "🥣",
+508	    "bowling": "🎳",
+509	    "boxing_glove": "🥊",
+510	    "boy": "👦",
+511	    "boy_dark_skin_tone": "👦🏿",
+512	    "boy_light_skin_tone": "👦🏻",
+513	    "boy_medium-dark_skin_tone": "👦🏾",
+514	    "boy_medium-light_skin_tone": "👦🏼",
+515	    "boy_medium_skin_tone": "👦🏽",
+516	    "brain": "🧠",
+517	    "bread": "🍞",
+518	    "breast-feeding": "🤱",
+519	    "breast-feeding_dark_skin_tone": "🤱🏿",
+520	    "breast-feeding_light_skin_tone": "🤱🏻",
+521	    "breast-feeding_medium-dark_skin_tone": "🤱🏾",
+522	    "breast-feeding_medium-light_skin_tone": "🤱🏼",
+523	    "breast-feeding_medium_skin_tone": "🤱🏽",
+524	    "brick": "🧱",
+525	    "bride_with_veil": "👰",
+526	    "bride_with_veil_dark_skin_tone": "👰🏿",
+527	    "bride_with_veil_light_skin_tone": "👰🏻",
+528	    "bride_with_veil_medium-dark_skin_tone": "👰🏾",
+529	    "bride_with_veil_medium-light_skin_tone": "👰🏼",
+530	    "bride_with_veil_medium_skin_tone": "👰🏽",
+531	    "bridge_at_night": "🌉",
+532	    "briefcase": "💼",
+533	    "briefs": "🩲",
+534	    "bright_button": "🔆",
+535	    "broccoli": "🥦",
+536	    "broken_heart": "💔",
+537	    "broom": "🧹",
+538	    "brown_circle": "🟤",
+539	    "brown_heart": "🤎",
+540	    "brown_square": "🟫",
+541	    "bug": "🐛",
+542	    "building_construction": "🏗",
+543	    "bullet_train": "🚅",
+544	    "burrito": "🌯",
+545	    "bus": "🚌",
+546	    "bus_stop": "🚏",
+547	    "bust_in_silhouette": "👤",
+548	    "busts_in_silhouette": "👥",
+549	    "butter": "🧈",
+550	    "butterfly": "🦋",
+551	    "cactus": "🌵",
+552	    "calendar": "📆",
+553	    "call_me_hand": "🤙",
+554	    "call_me_hand_dark_skin_tone": "🤙🏿",
+555	    "call_me_hand_light_skin_tone": "🤙🏻",
+556	    "call_me_hand_medium-dark_skin_tone": "🤙🏾",
+557	    "call_me_hand_medium-light_skin_tone": "🤙🏼",
+558	    "call_me_hand_medium_skin_tone": "🤙🏽",
+559	    "camel": "🐫",
+560	    "camera": "📷",
+561	    "camera_with_flash": "📸",
+562	    "camping": "🏕",
+563	    "candle": "🕯",
+564	    "candy": "🍬",
+565	    "canned_food": "🥫",
+566	    "canoe": "🛶",
+567	    "card_file_box": "🗃",
+568	    "card_index": "📇",
+569	    "card_index_dividers": "🗂",
+570	    "carousel_horse": "🎠",
+571	    "carp_streamer": "🎏",
+572	    "carrot": "🥕",
+573	    "castle": "🏰",
+574	    "cat": "🐱",
+575	    "cat_face": "🐱",
+576	    "cat_face_with_tears_of_joy": "😹",
+577	    "cat_face_with_wry_smile": "😼",
+578	    "chains": "⛓",
+579	    "chair": "🪑",
+580	    "chart_decreasing": "📉",
+581	    "chart_increasing": "📈",
+582	    "chart_increasing_with_yen": "💹",
+583	    "cheese_wedge": "🧀",
+584	    "chequered_flag": "🏁",
+585	    "cherries": "🍒",
+586	    "cherry_blossom": "🌸",
+587	    "chess_pawn": "♟",
+588	    "chestnut": "🌰",
+589	    "chicken": "🐔",
+590	    "child": "🧒",
+591	    "child_dark_skin_tone": "🧒🏿",
+592	    "child_light_skin_tone": "🧒🏻",
+593	    "child_medium-dark_skin_tone": "🧒🏾",
+594	    "child_medium-light_skin_tone": "🧒🏼",
+595	    "child_medium_skin_tone": "🧒🏽",
+596	    "children_crossing": "🚸",
+597	    "chipmunk": "🐿",
+598	    "chocolate_bar": "🍫",
+599	    "chopsticks": "🥢",
+600	    "church": "⛪",
+601	    "cigarette": "🚬",
+602	    "cinema": "🎦",
+603	    "circled_m": "Ⓜ",
+604	    "circus_tent": "🎪",
+605	    "cityscape": "🏙",
+606	    "cityscape_at_dusk": "🌆",
+607	    "clamp": "🗜",
+608	    "clapper_board": "🎬",
+609	    "clapping_hands": "👏",
+610	    "clapping_hands_dark_skin_tone": "👏🏿",
+611	    "clapping_hands_light_skin_tone": "👏🏻",
+612	    "clapping_hands_medium-dark_skin_tone": "👏🏾",
+613	    "clapping_hands_medium-light_skin_tone": "👏🏼",
+614	    "clapping_hands_medium_skin_tone": "👏🏽",
+615	    "classical_building": "🏛",
+616	    "clinking_beer_mugs": "🍻",
+617	    "clinking_glasses": "🥂",
+618	    "clipboard": "📋",
+619	    "clockwise_vertical_arrows": "🔃",
+620	    "closed_book": "📕",
+621	    "closed_mailbox_with_lowered_flag": "📪",
+622	    "closed_mailbox_with_raised_flag": "📫",
+623	    "closed_umbrella": "🌂",
+624	    "cloud": "☁",
+625	    "cloud_with_lightning": "🌩",
+626	    "cloud_with_lightning_and_rain": "⛈",
+627	    "cloud_with_rain": "🌧",
+628	    "cloud_with_snow": "🌨",
+629	    "clown_face": "🤡",
+630	    "club_suit": "♣",
+631	    "clutch_bag": "👝",
+632	    "coat": "🧥",
+633	    "cocktail_glass": "🍸",
+634	    "coconut": "🥥",
+635	    "coffin": "⚰",
+636	    "cold_face": "🥶",
+637	    "collision": "💥",
+638	    "comet": "☄",
+639	    "compass": "🧭",
+640	    "computer_disk": "💽",
+641	    "computer_mouse": "🖱",
+642	    "confetti_ball": "🎊",
+643	    "confounded_face": "😖",
+644	    "confused_face": "😕",
+645	    "construction": "🚧",
+646	    "construction_worker": "👷",
+647	    "construction_worker_dark_skin_tone": "👷🏿",
+648	    "construction_worker_light_skin_tone": "👷🏻",
+649	    "construction_worker_medium-dark_skin_tone": "👷🏾",
+650	    "construction_worker_medium-light_skin_tone": "👷🏼",
+651	    "construction_worker_medium_skin_tone": "👷🏽",
+652	    "control_knobs": "🎛",
+653	    "convenience_store": "🏪",
+654	    "cooked_rice": "🍚",
+655	    "cookie": "🍪",
+656	    "cooking": "🍳",
+657	    "copyright": "©",
+658	    "couch_and_lamp": "🛋",
+659	    "counterclockwise_arrows_button": "🔄",
+660	    "couple_with_heart": "💑",
+661	    "couple_with_heart_man_man": "👨\u200d❤️\u200d👨",
+662	    "couple_with_heart_woman_man": "👩\u200d❤️\u200d👨",
+663	    "couple_with_heart_woman_woman": "👩\u200d❤️\u200d👩",
+664	    "cow": "🐮",
+665	    "cow_face": "🐮",
+666	    "cowboy_hat_face": "🤠",
+667	    "crab": "🦀",
+668	    "crayon": "🖍",
+669	    "credit_card": "💳",
+670	    "crescent_moon": "🌙",
+671	    "cricket": "🦗",
+672	    "cricket_game": "🏏",
+673	    "crocodile": "🐊",
+674	    "croissant": "🥐",
+675	    "cross_mark": "❌",
+676	    "cross_mark_button": "❎",
+677	    "crossed_fingers": "🤞",
+678	    "crossed_fingers_dark_skin_tone": "🤞🏿",
+679	    "crossed_fingers_light_skin_tone": "🤞🏻",
+680	    "crossed_fingers_medium-dark_skin_tone": "🤞🏾",
+681	    "crossed_fingers_medium-light_skin_tone": "🤞🏼",
+682	    "crossed_fingers_medium_skin_tone": "🤞🏽",
+683	    "crossed_flags": "🎌",
+684	    "crossed_swords": "⚔",
+685	    "crown": "👑",
+686	    "crying_cat_face": "😿",
+687	    "crying_face": "😢",
+688	    "crystal_ball": "🔮",
+689	    "cucumber": "🥒",
+690	    "cupcake": "🧁",
+691	    "cup_with_straw": "🥤",
+692	    "curling_stone": "🥌",
+693	    "curly_hair": "🦱",
+694	    "curly-haired_man": "👨\u200d🦱",
+695	    "curly-haired_woman": "👩\u200d🦱",
+696	    "curly_loop": "➰",
+697	    "currency_exchange": "💱",
+698	    "curry_rice": "🍛",
+699	    "custard": "🍮",
+700	    "customs": "🛃",
+701	    "cut_of_meat": "🥩",
+702	    "cyclone": "🌀",
+703	    "dagger": "🗡",
+704	    "dango": "🍡",
+705	    "dashing_away": "💨",
+706	    "deaf_person": "🧏",
+707	    "deciduous_tree": "🌳",
+708	    "deer": "🦌",
+709	    "delivery_truck": "🚚",
+710	    "department_store": "🏬",
+711	    "derelict_house": "🏚",
+712	    "desert": "🏜",
+713	    "desert_island": "🏝",
+714	    "desktop_computer": "🖥",
+715	    "detective": "🕵",
+716	    "detective_dark_skin_tone": "🕵🏿",
+717	    "detective_light_skin_tone": "🕵🏻",
+718	    "detective_medium-dark_skin_tone": "🕵🏾",
+719	    "detective_medium-light_skin_tone": "🕵🏼",
+720	    "detective_medium_skin_tone": "🕵🏽",
+721	    "diamond_suit": "♦",
+722	    "diamond_with_a_dot": "💠",
+723	    "dim_button": "🔅",
+724	    "direct_hit": "🎯",
+725	    "disappointed_face": "😞",
+726	    "diving_mask": "🤿",
+727	    "diya_lamp": "🪔",
+728	    "dizzy": "💫",
+729	    "dizzy_face": "😵",
+730	    "dna": "🧬",
+731	    "dog": "🐶",
+732	    "dog_face": "🐶",
+733	    "dollar_banknote": "💵",
+734	    "dolphin": "🐬",
+735	    "door": "🚪",
+736	    "dotted_six-pointed_star": "🔯",
+737	    "double_curly_loop": "➿",
+738	    "double_exclamation_mark": "‼",
+739	    "doughnut": "🍩",
+740	    "dove": "🕊",
+741	    "down-left_arrow": "↙",
+742	    "down-right_arrow": "↘",
+743	    "down_arrow": "⬇",
+744	    "downcast_face_with_sweat": "😓",
+745	    "downwards_button": "🔽",
+746	    "dragon": "🐉",
+747	    "dragon_face": "🐲",
+748	    "dress": "👗",
+749	    "drooling_face": "🤤",
+750	    "drop_of_blood": "🩸",
+751	    "droplet": "💧",
+752	    "drum": "🥁",
+753	    "duck": "🦆",
+754	    "dumpling": "🥟",
+755	    "dvd": "📀",
+756	    "e-mail": "📧",
+757	    "eagle": "🦅",
+758	    "ear": "👂",
+759	    "ear_dark_skin_tone": "👂🏿",
+760	    "ear_light_skin_tone": "👂🏻",
+761	    "ear_medium-dark_skin_tone": "👂🏾",
+762	    "ear_medium-light_skin_tone": "👂🏼",
+763	    "ear_medium_skin_tone": "👂🏽",
+764	    "ear_of_corn": "🌽",
+765	    "ear_with_hearing_aid": "🦻",
+766	    "egg": "🍳",
+767	    "eggplant": "🍆",
+768	    "eight-pointed_star": "✴",
+769	    "eight-spoked_asterisk": "✳",
+770	    "eight-thirty": "🕣",
+771	    "eight_o’clock": "🕗",
+772	    "eject_button": "⏏",
+773	    "electric_plug": "🔌",
+774	    "elephant": "🐘",
+775	    "eleven-thirty": "🕦",
+776	    "eleven_o’clock": "🕚",
+777	    "elf": "🧝",
+778	    "elf_dark_skin_tone": "🧝🏿",
+779	    "elf_light_skin_tone": "🧝🏻",
+780	    "elf_medium-dark_skin_tone": "🧝🏾",
+781	    "elf_medium-light_skin_tone": "🧝🏼",
+782	    "elf_medium_skin_tone": "🧝🏽",
+783	    "envelope": "✉",
+784	    "envelope_with_arrow": "📩",
+785	    "euro_banknote": "💶",
+786	    "evergreen_tree": "🌲",
+787	    "ewe": "🐑",
+788	    "exclamation_mark": "❗",
+789	    "exclamation_question_mark": "⁉",
+790	    "exploding_head": "🤯",
+791	    "expressionless_face": "😑",
+792	    "eye": "👁",
+793	    "eye_in_speech_bubble": "👁️\u200d🗨️",
+794	    "eyes": "👀",
+795	    "face_blowing_a_kiss": "😘",
+796	    "face_savoring_food": "😋",
+797	    "face_screaming_in_fear": "😱",
+798	    "face_vomiting": "🤮",
+799	    "face_with_hand_over_mouth": "🤭",
+800	    "face_with_head-bandage": "🤕",
+801	    "face_with_medical_mask": "😷",
+802	    "face_with_monocle": "🧐",
+803	    "face_with_open_mouth": "😮",
+804	    "face_with_raised_eyebrow": "🤨",
+805	    "face_with_rolling_eyes": "🙄",
+806	    "face_with_steam_from_nose": "😤",
+807	    "face_with_symbols_on_mouth": "🤬",
+808	    "face_with_tears_of_joy": "😂",
+809	    "face_with_thermometer": "🤒",
+810	    "face_with_tongue": "😛",
+811	    "face_without_mouth": "😶",
+812	    "factory": "🏭",
+813	    "fairy": "🧚",
+814	    "fairy_dark_skin_tone": "🧚🏿",
+815	    "fairy_light_skin_tone": "🧚🏻",
+816	    "fairy_medium-dark_skin_tone": "🧚🏾",
+817	    "fairy_medium-light_skin_tone": "🧚🏼",
+818	    "fairy_medium_skin_tone": "🧚🏽",
+819	    "falafel": "🧆",
+820	    "fallen_leaf": "🍂",
+821	    "family": "👪",
+822	    "family_man_boy": "👨\u200d👦",
+823	    "family_man_boy_boy": "👨\u200d👦\u200d👦",
+824	    "family_man_girl": "👨\u200d👧",
+825	    "family_man_girl_boy": "👨\u200d👧\u200d👦",
+826	    "family_man_girl_girl": "👨\u200d👧\u200d👧",
+827	    "family_man_man_boy": "👨\u200d👨\u200d👦",
+828	    "family_man_man_boy_boy": "👨\u200d👨\u200d👦\u200d👦",
+829	    "family_man_man_girl": "👨\u200d👨\u200d👧",
+830	    "family_man_man_girl_boy": "👨\u200d👨\u200d👧\u200d👦",
+831	    "family_man_man_girl_girl": "👨\u200d👨\u200d👧\u200d👧",
+832	    "family_man_woman_boy": "👨\u200d👩\u200d👦",
+833	    "family_man_woman_boy_boy": "👨\u200d👩\u200d👦\u200d👦",
+834	    "family_man_woman_girl": "👨\u200d👩\u200d👧",
+835	    "family_man_woman_girl_boy": "👨\u200d👩\u200d👧\u200d👦",
+836	    "family_man_woman_girl_girl": "👨\u200d👩\u200d👧\u200d👧",
+837	    "family_woman_boy": "👩\u200d👦",
+838	    "family_woman_boy_boy": "👩\u200d👦\u200d👦",
+839	    "family_woman_girl": "👩\u200d👧",
+840	    "family_woman_girl_boy": "👩\u200d👧\u200d👦",
+841	    "family_woman_girl_girl": "👩\u200d👧\u200d👧",
+842	    "family_woman_woman_boy": "👩\u200d👩\u200d👦",
+843	    "family_woman_woman_boy_boy": "👩\u200d👩\u200d👦\u200d👦",
+844	    "family_woman_woman_girl": "👩\u200d👩\u200d👧",
+845	    "family_woman_woman_girl_boy": "👩\u200d👩\u200d👧\u200d👦",
+846	    "family_woman_woman_girl_girl": "👩\u200d👩\u200d👧\u200d👧",
+847	    "fast-forward_button": "⏩",
+848	    "fast_down_button": "⏬",
+849	    "fast_reverse_button": "⏪",
+850	    "fast_up_button": "⏫",
+851	    "fax_machine": "📠",
+852	    "fearful_face": "😨",
+853	    "female_sign": "♀",
+854	    "ferris_wheel": "🎡",
+855	    "ferry": "⛴",
+856	    "field_hockey": "🏑",
+857	    "file_cabinet": "🗄",
+858	    "file_folder": "📁",
+859	    "film_frames": "🎞",
+860	    "film_projector": "📽",
+861	    "fire": "🔥",
+862	    "fire_extinguisher": "🧯",
+863	    "firecracker": "🧨",
+864	    "fire_engine": "🚒",
+865	    "fireworks": "🎆",
+866	    "first_quarter_moon": "🌓",
+867	    "first_quarter_moon_face": "🌛",
+868	    "fish": "🐟",
+869	    "fish_cake_with_swirl": "🍥",
+870	    "fishing_pole": "🎣",
+871	    "five-thirty": "🕠",
+872	    "five_o’clock": "🕔",
+873	    "flag_in_hole": "⛳",
+874	    "flamingo": "🦩",
+875	    "flashlight": "🔦",
+876	    "flat_shoe": "🥿",
+877	    "fleur-de-lis": "⚜",
+878	    "flexed_biceps": "💪",
+879	    "flexed_biceps_dark_skin_tone": "💪🏿",
+880	    "flexed_biceps_light_skin_tone": "💪🏻",
+881	    "flexed_biceps_medium-dark_skin_tone": "💪🏾",
+882	    "flexed_biceps_medium-light_skin_tone": "💪🏼",
+883	    "flexed_biceps_medium_skin_tone": "💪🏽",
+884	    "floppy_disk": "💾",
+885	    "flower_playing_cards": "🎴",
+886	    "flushed_face": "😳",
+887	    "flying_disc": "🥏",
+888	    "flying_saucer": "🛸",
+889	    "fog": "🌫",
+890	    "foggy": "🌁",
+891	    "folded_hands": "🙏",
+892	    "folded_hands_dark_skin_tone": "🙏🏿",
+893	    "folded_hands_light_skin_tone": "🙏🏻",
+894	    "folded_hands_medium-dark_skin_tone": "🙏🏾",
+895	    "folded_hands_medium-light_skin_tone": "🙏🏼",
+896	    "folded_hands_medium_skin_tone": "🙏🏽",
+897	    "foot": "🦶",
+898	    "footprints": "👣",
+899	    "fork_and_knife": "🍴",
+900	    "fork_and_knife_with_plate": "🍽",
+901	    "fortune_cookie": "🥠",
+902	    "fountain": "⛲",
+903	    "fountain_pen": "🖋",
+904	    "four-thirty": "🕟",
+905	    "four_leaf_clover": "🍀",
+906	    "four_o’clock": "🕓",
+907	    "fox_face": "🦊",
+908	    "framed_picture": "🖼",
+909	    "french_fries": "🍟",
+910	    "fried_shrimp": "🍤",
+911	    "frog_face": "🐸",
+912	    "front-facing_baby_chick": "🐥",
+913	    "frowning_face": "☹",
+914	    "frowning_face_with_open_mouth": "😦",
+915	    "fuel_pump": "⛽",
+916	    "full_moon": "🌕",
+917	    "full_moon_face": "🌝",
+918	    "funeral_urn": "⚱",
+919	    "game_die": "🎲",
+920	    "garlic": "🧄",
+921	    "gear": "⚙",
+922	    "gem_stone": "💎",
+923	    "genie": "🧞",
+924	    "ghost": "👻",
+925	    "giraffe": "🦒",
+926	    "girl": "👧",
+927	    "girl_dark_skin_tone": "👧🏿",
+928	    "girl_light_skin_tone": "👧🏻",
+929	    "girl_medium-dark_skin_tone": "👧🏾",
+930	    "girl_medium-light_skin_tone": "👧🏼",
+931	    "girl_medium_skin_tone": "👧🏽",
+932	    "glass_of_milk": "🥛",
+933	    "glasses": "👓",
+934	    "globe_showing_americas": "🌎",
+935	    "globe_showing_asia-australia": "🌏",
+936	    "globe_showing_europe-africa": "🌍",
+937	    "globe_with_meridians": "🌐",
+938	    "gloves": "🧤",
+939	    "glowing_star": "🌟",
+940	    "goal_net": "🥅",
+941	    "goat": "🐐",
+942	    "goblin": "👺",
+943	    "goggles": "🥽",
+944	    "gorilla": "🦍",
+945	    "graduation_cap": "🎓",
+946	    "grapes": "🍇",
+947	    "green_apple": "🍏",
+948	    "green_book": "📗",
+949	    "green_circle": "🟢",
+950	    "green_heart": "💚",
+951	    "green_salad": "🥗",
+952	    "green_square": "🟩",
+953	    "grimacing_face": "😬",
+954	    "grinning_cat_face": "😺",
+955	    "grinning_cat_face_with_smiling_eyes": "😸",
+956	    "grinning_face": "😀",
+957	    "grinning_face_with_big_eyes": "😃",
+958	    "grinning_face_with_smiling_eyes": "😄",
+959	    "grinning_face_with_sweat": "😅",
+960	    "grinning_squinting_face": "😆",
+961	    "growing_heart": "💗",
+962	    "guard": "💂",
+963	    "guard_dark_skin_tone": "💂🏿",
+964	    "guard_light_skin_tone": "💂🏻",
+965	    "guard_medium-dark_skin_tone": "💂🏾",
+966	    "guard_medium-light_skin_tone": "💂🏼",
+967	    "guard_medium_skin_tone": "💂🏽",
+968	    "guide_dog": "🦮",
+969	    "guitar": "🎸",
+970	    "hamburger": "🍔",
+971	    "hammer": "🔨",
+972	    "hammer_and_pick": "⚒",
+973	    "hammer_and_wrench": "🛠",
+974	    "hamster_face": "🐹",
+975	    "hand_with_fingers_splayed": "🖐",
+976	    "hand_with_fingers_splayed_dark_skin_tone": "🖐🏿",
+977	    "hand_with_fingers_splayed_light_skin_tone": "🖐🏻",
+978	    "hand_with_fingers_splayed_medium-dark_skin_tone": "🖐🏾",
+979	    "hand_with_fingers_splayed_medium-light_skin_tone": "🖐🏼",
+980	    "hand_with_fingers_splayed_medium_skin_tone": "🖐🏽",
+981	    "handbag": "👜",
+982	    "handshake": "🤝",
+983	    "hatching_chick": "🐣",
+984	    "headphone": "🎧",
+985	    "hear-no-evil_monkey": "🙉",
+986	    "heart_decoration": "💟",
+987	    "heart_suit": "♥",
+988	    "heart_with_arrow": "💘",
+989	    "heart_with_ribbon": "💝",
+990	    "heavy_check_mark": "✔",
+991	    "heavy_division_sign": "➗",
+992	    "heavy_dollar_sign": "💲",
+993	    "heavy_heart_exclamation": "❣",
+994	    "heavy_large_circle": "⭕",
+995	    "heavy_minus_sign": "➖",
+996	    "heavy_multiplication_x": "✖",
+997	    "heavy_plus_sign": "➕",
+998	    "hedgehog": "🦔",
+999	    "helicopter": "🚁",
+1000	    "herb": "🌿",
+1001	    "hibiscus": "🌺",
+1002	    "high-heeled_shoe": "👠",
+1003	    "high-speed_train": "🚄",
+1004	    "high_voltage": "⚡",
+1005	    "hiking_boot": "🥾",
+1006	    "hindu_temple": "🛕",
+1007	    "hippopotamus": "🦛",
+1008	    "hole": "🕳",
+1009	    "honey_pot": "🍯",
+1010	    "honeybee": "🐝",
+1011	    "horizontal_traffic_light": "🚥",
+1012	    "horse": "🐴",
+1013	    "horse_face": "🐴",
+1014	    "horse_racing": "🏇",
+1015	    "horse_racing_dark_skin_tone": "🏇🏿",
+1016	    "horse_racing_light_skin_tone": "🏇🏻",
+1017	    "horse_racing_medium-dark_skin_tone": "🏇🏾",
+1018	    "horse_racing_medium-light_skin_tone": "🏇🏼",
+1019	    "horse_racing_medium_skin_tone": "🏇🏽",
+1020	    "hospital": "🏥",
+1021	    "hot_beverage": "☕",
+1022	    "hot_dog": "🌭",
+1023	    "hot_face": "🥵",
+1024	    "hot_pepper": "🌶",
+1025	    "hot_springs": "♨",
+1026	    "hotel": "🏨",
+1027	    "hourglass_done": "⌛",
+1028	    "hourglass_not_done": "⏳",
+1029	    "house": "🏠",
+1030	    "house_with_garden": "🏡",
+1031	    "houses": "🏘",
+1032	    "hugging_face": "🤗",
+1033	    "hundred_points": "💯",
+1034	    "hushed_face": "😯",
+1035	    "ice": "🧊",
+1036	    "ice_cream": "🍨",
+1037	    "ice_hockey": "🏒",
+1038	    "ice_skate": "⛸",
+1039	    "inbox_tray": "📥",
+1040	    "incoming_envelope": "📨",
+1041	    "index_pointing_up": "☝",
+1042	    "index_pointing_up_dark_skin_tone": "☝🏿",
+1043	    "index_pointing_up_light_skin_tone": "☝🏻",
+1044	    "index_pointing_up_medium-dark_skin_tone": "☝🏾",
+1045	    "index_pointing_up_medium-light_skin_tone": "☝🏼",
+1046	    "index_pointing_up_medium_skin_tone": "☝🏽",
+1047	    "infinity": "♾",
+1048	    "information": "ℹ",
+1049	    "input_latin_letters": "🔤",
+1050	    "input_latin_lowercase": "🔡",
+1051	    "input_latin_uppercase": "🔠",
+1052	    "input_numbers": "🔢",
+1053	    "input_symbols": "🔣",
+1054	    "jack-o-lantern": "🎃",
+1055	    "jeans": "👖",
+1056	    "jigsaw": "🧩",
+1057	    "joker": "🃏",
+1058	    "joystick": "🕹",
+1059	    "kaaba": "🕋",
+1060	    "kangaroo": "🦘",
+1061	    "key": "🔑",
+1062	    "keyboard": "⌨",
+1063	    "keycap_#": "#️⃣",
+1064	    "keycap_*": "*️⃣",
+1065	    "keycap_0": "0️⃣",
+1066	    "keycap_1": "1️⃣",
+1067	    "keycap_10": "🔟",
+1068	    "keycap_2": "2️⃣",
+1069	    "keycap_3": "3️⃣",
+1070	    "keycap_4": "4️⃣",
+1071	    "keycap_5": "5️⃣",
+1072	    "keycap_6": "6️⃣",
+1073	    "keycap_7": "7️⃣",
+1074	    "keycap_8": "8️⃣",
+1075	    "keycap_9": "9️⃣",
+1076	    "kick_scooter": "🛴",
+1077	    "kimono": "👘",
+1078	    "kiss": "💋",
+1079	    "kiss_man_man": "👨\u200d❤️\u200d💋\u200d👨",
+1080	    "kiss_mark": "💋",
+1081	    "kiss_woman_man": "👩\u200d❤️\u200d💋\u200d👨",
+1082	    "kiss_woman_woman": "👩\u200d❤️\u200d💋\u200d👩",
+1083	    "kissing_cat_face": "😽",
+1084	    "kissing_face": "😗",
+1085	    "kissing_face_with_closed_eyes": "😚",
+1086	    "kissing_face_with_smiling_eyes": "😙",
+1087	    "kitchen_knife": "🔪",
+1088	    "kite": "🪁",
+1089	    "kiwi_fruit": "🥝",
+1090	    "koala": "🐨",
+1091	    "lab_coat": "🥼",
+1092	    "label": "🏷",
+1093	    "lacrosse": "🥍",
+1094	    "lady_beetle": "🐞",
+1095	    "laptop_computer": "💻",
+1096	    "large_blue_diamond": "🔷",
+1097	    "large_orange_diamond": "🔶",
+1098	    "last_quarter_moon": "🌗",
+1099	    "last_quarter_moon_face": "🌜",
+1100	    "last_track_button": "⏮",
+1101	    "latin_cross": "✝",
+1102	    "leaf_fluttering_in_wind": "🍃",
+1103	    "leafy_green": "🥬",
+1104	    "ledger": "📒",
+1105	    "left-facing_fist": "🤛",
+1106	    "left-facing_fist_dark_skin_tone": "🤛🏿",
+1107	    "left-facing_fist_light_skin_tone": "🤛🏻",
+1108	    "left-facing_fist_medium-dark_skin_tone": "🤛🏾",
+1109	    "left-facing_fist_medium-light_skin_tone": "🤛🏼",
+1110	    "left-facing_fist_medium_skin_tone": "🤛🏽",
+1111	    "left-right_arrow": "↔",
+1112	    "left_arrow": "⬅",
+1113	    "left_arrow_curving_right": "↪",
+1114	    "left_luggage": "🛅",
+1115	    "left_speech_bubble": "🗨",
+1116	    "leg": "🦵",
+1117	    "lemon": "🍋",
+1118	    "leopard": "🐆",
+1119	    "level_slider": "🎚",
+1120	    "light_bulb": "💡",
+1121	    "light_rail": "🚈",
+1122	    "link": "🔗",
+1123	    "linked_paperclips": "🖇",
+1124	    "lion_face": "🦁",
+1125	    "lipstick": "💄",
+1126	    "litter_in_bin_sign": "🚮",
+1127	    "lizard": "🦎",
+1128	    "llama": "🦙",
+1129	    "lobster": "🦞",
+1130	    "locked": "🔒",
+1131	    "locked_with_key": "🔐",
+1132	    "locked_with_pen": "🔏",
+1133	    "locomotive": "🚂",
+1134	    "lollipop": "🍭",
+1135	    "lotion_bottle": "🧴",
+1136	    "loudly_crying_face": "😭",
+1137	    "loudspeaker": "📢",
+1138	    "love-you_gesture": "🤟",
+1139	    "love-you_gesture_dark_skin_tone": "🤟🏿",
+1140	    "love-you_gesture_light_skin_tone": "🤟🏻",
+1141	    "love-you_gesture_medium-dark_skin_tone": "🤟🏾",
+1142	    "love-you_gesture_medium-light_skin_tone": "🤟🏼",
+1143	    "love-you_gesture_medium_skin_tone": "🤟🏽",
+1144	    "love_hotel": "🏩",
+1145	    "love_letter": "💌",
+1146	    "luggage": "🧳",
+1147	    "lying_face": "🤥",
+1148	    "mage": "🧙",
+1149	    "mage_dark_skin_tone": "🧙🏿",
+1150	    "mage_light_skin_tone": "🧙🏻",
+1151	    "mage_medium-dark_skin_tone": "🧙🏾",
+1152	    "mage_medium-light_skin_tone": "🧙🏼",
+1153	    "mage_medium_skin_tone": "🧙🏽",
+1154	    "magnet": "🧲",
+1155	    "magnifying_glass_tilted_left": "🔍",
+1156	    "magnifying_glass_tilted_right": "🔎",
+1157	    "mahjong_red_dragon": "🀄",
+1158	    "male_sign": "♂",
+1159	    "man": "👨",
+1160	    "man_and_woman_holding_hands": "👫",
+1161	    "man_artist": "👨\u200d🎨",
+1162	    "man_artist_dark_skin_tone": "👨🏿\u200d🎨",
+1163	    "man_artist_light_skin_tone": "👨🏻\u200d🎨",
+1164	    "man_artist_medium-dark_skin_tone": "👨🏾\u200d🎨",
+1165	    "man_artist_medium-light_skin_tone": "👨🏼\u200d🎨",
+1166	    "man_artist_medium_skin_tone": "👨🏽\u200d🎨",
+1167	    "man_astronaut": "👨\u200d🚀",
+1168	    "man_astronaut_dark_skin_tone": "👨🏿\u200d🚀",
+1169	    "man_astronaut_light_skin_tone": "👨🏻\u200d🚀",
+1170	    "man_astronaut_medium-dark_skin_tone": "👨🏾\u200d🚀",
+1171	    "man_astronaut_medium-light_skin_tone": "👨🏼\u200d🚀",
+1172	    "man_astronaut_medium_skin_tone": "👨🏽\u200d🚀",
+1173	    "man_biking": "🚴\u200d♂️",
+1174	    "man_biking_dark_skin_tone": "🚴🏿\u200d♂️",
+1175	    "man_biking_light_skin_tone": "🚴🏻\u200d♂️",
+1176	    "man_biking_medium-dark_skin_tone": "🚴🏾\u200d♂️",
+1177	    "man_biking_medium-light_skin_tone": "🚴🏼\u200d♂️",
+1178	    "man_biking_medium_skin_tone": "🚴🏽\u200d♂️",
+1179	    "man_bouncing_ball": "⛹️\u200d♂️",
+1180	    "man_bouncing_ball_dark_skin_tone": "⛹🏿\u200d♂️",
+1181	    "man_bouncing_ball_light_skin_tone": "⛹🏻\u200d♂️",
+1182	    "man_bouncing_ball_medium-dark_skin_tone": "⛹🏾\u200d♂️",
+1183	    "man_bouncing_ball_medium-light_skin_tone": "⛹🏼\u200d♂️",
+1184	    "man_bouncing_ball_medium_skin_tone": "⛹🏽\u200d♂️",
+1185	    "man_bowing": "🙇\u200d♂️",
+1186	    "man_bowing_dark_skin_tone": "🙇🏿\u200d♂️",
+1187	    "man_bowing_light_skin_tone": "🙇🏻\u200d♂️",
+1188	    "man_bowing_medium-dark_skin_tone": "🙇🏾\u200d♂️",
+1189	    "man_bowing_medium-light_skin_tone": "🙇🏼\u200d♂️",
+1190	    "man_bowing_medium_skin_tone": "🙇🏽\u200d♂️",
+1191	    "man_cartwheeling": "🤸\u200d♂️",
+1192	    "man_cartwheeling_dark_skin_tone": "🤸🏿\u200d♂️",
+1193	    "man_cartwheeling_light_skin_tone": "🤸🏻\u200d♂️",
+1194	    "man_cartwheeling_medium-dark_skin_tone": "🤸🏾\u200d♂️",
+1195	    "man_cartwheeling_medium-light_skin_tone": "🤸🏼\u200d♂️",
+1196	    "man_cartwheeling_medium_skin_tone": "🤸🏽\u200d♂️",
+1197	    "man_climbing": "🧗\u200d♂️",
+1198	    "man_climbing_dark_skin_tone": "🧗🏿\u200d♂️",
+1199	    "man_climbing_light_skin_tone": "🧗🏻\u200d♂️",
+1200	    "man_climbing_medium-dark_skin_tone": "🧗🏾\u200d♂️",
+1201	    "man_climbing_medium-light_skin_tone": "🧗🏼\u200d♂️",
+1202	    "man_climbing_medium_skin_tone": "🧗🏽\u200d♂️",
+1203	    "man_construction_worker": "👷\u200d♂️",
+1204	    "man_construction_worker_dark_skin_tone": "👷🏿\u200d♂️",
+1205	    "man_construction_worker_light_skin_tone": "👷🏻\u200d♂️",
+1206	    "man_construction_worker_medium-dark_skin_tone": "👷🏾\u200d♂️",
+1207	    "man_construction_worker_medium-light_skin_tone": "👷🏼\u200d♂️",
+1208	    "man_construction_worker_medium_skin_tone": "👷🏽\u200d♂️",
+1209	    "man_cook": "👨\u200d🍳",
+1210	    "man_cook_dark_skin_tone": "👨🏿\u200d🍳",
+1211	    "man_cook_light_skin_tone": "👨🏻\u200d🍳",
+1212	    "man_cook_medium-dark_skin_tone": "👨🏾\u200d🍳",
+1213	    "man_cook_medium-light_skin_tone": "👨🏼\u200d🍳",
+1214	    "man_cook_medium_skin_tone": "👨🏽\u200d🍳",
+1215	    "man_dancing": "🕺",
+1216	    "man_dancing_dark_skin_tone": "🕺🏿",
+1217	    "man_dancing_light_skin_tone": "🕺🏻",
+1218	    "man_dancing_medium-dark_skin_tone": "🕺🏾",
+1219	    "man_dancing_medium-light_skin_tone": "🕺🏼",
+1220	    "man_dancing_medium_skin_tone": "🕺🏽",
+1221	    "man_dark_skin_tone": "👨🏿",
+1222	    "man_detective": "🕵️\u200d♂️",
+1223	    "man_detective_dark_skin_tone": "🕵🏿\u200d♂️",
+1224	    "man_detective_light_skin_tone": "🕵🏻\u200d♂️",
+1225	    "man_detective_medium-dark_skin_tone": "🕵🏾\u200d♂️",
+1226	    "man_detective_medium-light_skin_tone": "🕵🏼\u200d♂️",
+1227	    "man_detective_medium_skin_tone": "🕵🏽\u200d♂️",
+1228	    "man_elf": "🧝\u200d♂️",
+1229	    "man_elf_dark_skin_tone": "🧝🏿\u200d♂️",
+1230	    "man_elf_light_skin_tone": "🧝🏻\u200d♂️",
+1231	    "man_elf_medium-dark_skin_tone": "🧝🏾\u200d♂️",
+1232	    "man_elf_medium-light_skin_tone": "🧝🏼\u200d♂️",
+1233	    "man_elf_medium_skin_tone": "🧝🏽\u200d♂️",
+1234	    "man_facepalming": "🤦\u200d♂️",
+1235	    "man_facepalming_dark_skin_tone": "🤦🏿\u200d♂️",
+1236	    "man_facepalming_light_skin_tone": "🤦🏻\u200d♂️",
+1237	    "man_facepalming_medium-dark_skin_tone": "🤦🏾\u200d♂️",
+1238	    "man_facepalming_medium-light_skin_tone": "🤦🏼\u200d♂️",
+1239	    "man_facepalming_medium_skin_tone": "🤦🏽\u200d♂️",
+1240	    "man_factory_worker": "👨\u200d🏭",
+1241	    "man_factory_worker_dark_skin_tone": "👨🏿\u200d🏭",
+1242	    "man_factory_worker_light_skin_tone": "👨🏻\u200d🏭",
+1243	    "man_factory_worker_medium-dark_skin_tone": "👨🏾\u200d🏭",
+1244	    "man_factory_worker_medium-light_skin_tone": "👨🏼\u200d🏭",
+1245	    "man_factory_worker_medium_skin_tone": "👨🏽\u200d🏭",
+1246	    "man_fairy": "🧚\u200d♂️",
+1247	    "man_fairy_dark_skin_tone": "🧚🏿\u200d♂️",
+1248	    "man_fairy_light_skin_tone": "🧚🏻\u200d♂️",
+1249	    "man_fairy_medium-dark_skin_tone": "🧚🏾\u200d♂️",
+1250	    "man_fairy_medium-light_skin_tone": "🧚🏼\u200d♂️",
+1251	    "man_fairy_medium_skin_tone": "🧚🏽\u200d♂️",
+1252	    "man_farmer": "👨\u200d🌾",
+1253	    "man_farmer_dark_skin_tone": "👨🏿\u200d🌾",
+1254	    "man_farmer_light_skin_tone": "👨🏻\u200d🌾",
+1255	    "man_farmer_medium-dark_skin_tone": "👨🏾\u200d🌾",
+1256	    "man_farmer_medium-light_skin_tone": "👨🏼\u200d🌾",
+1257	    "man_farmer_medium_skin_tone": "👨🏽\u200d🌾",
+1258	    "man_firefighter": "👨\u200d🚒",
+1259	    "man_firefighter_dark_skin_tone": "👨🏿\u200d🚒",
+1260	    "man_firefighter_light_skin_tone": "👨🏻\u200d🚒",
+1261	    "man_firefighter_medium-dark_skin_tone": "👨🏾\u200d🚒",
+1262	    "man_firefighter_medium-light_skin_tone": "👨🏼\u200d🚒",
+1263	    "man_firefighter_medium_skin_tone": "👨🏽\u200d🚒",
+1264	    "man_frowning": "🙍\u200d♂️",
+1265	    "man_frowning_dark_skin_tone": "🙍🏿\u200d♂️",
+1266	    "man_frowning_light_skin_tone": "🙍🏻\u200d♂️",
+1267	    "man_frowning_medium-dark_skin_tone": "🙍🏾\u200d♂️",
+1268	    "man_frowning_medium-light_skin_tone": "🙍🏼\u200d♂️",
+1269	    "man_frowning_medium_skin_tone": "🙍🏽\u200d♂️",
+1270	    "man_genie": "🧞\u200d♂️",
+1271	    "man_gesturing_no": "🙅\u200d♂️",
+1272	    "man_gesturing_no_dark_skin_tone": "🙅🏿\u200d♂️",
+1273	    "man_gesturing_no_light_skin_tone": "🙅🏻\u200d♂️",
+1274	    "man_gesturing_no_medium-dark_skin_tone": "🙅🏾\u200d♂️",
+1275	    "man_gesturing_no_medium-light_skin_tone": "🙅🏼\u200d♂️",
+1276	    "man_gesturing_no_medium_skin_tone": "🙅🏽\u200d♂️",
+1277	    "man_gesturing_ok": "🙆\u200d♂️",
+1278	    "man_gesturing_ok_dark_skin_tone": "🙆🏿\u200d♂️",
+1279	    "man_gesturing_ok_light_skin_tone": "🙆🏻\u200d♂️",
+1280	    "man_gesturing_ok_medium-dark_skin_tone": "🙆🏾\u200d♂️",
+1281	    "man_gesturing_ok_medium-light_skin_tone": "🙆🏼\u200d♂️",
+1282	    "man_gesturing_ok_medium_skin_tone": "🙆🏽\u200d♂️",
+1283	    "man_getting_haircut": "💇\u200d♂️",
+1284	    "man_getting_haircut_dark_skin_tone": "💇🏿\u200d♂️",
+1285	    "man_getting_haircut_light_skin_tone": "💇🏻\u200d♂️",
+1286	    "man_getting_haircut_medium-dark_skin_tone": "💇🏾\u200d♂️",
+1287	    "man_getting_haircut_medium-light_skin_tone": "💇🏼\u200d♂️",
+1288	    "man_getting_haircut_medium_skin_tone": "💇🏽\u200d♂️",
+1289	    "man_getting_massage": "💆\u200d♂️",
+1290	    "man_getting_massage_dark_skin_tone": "💆🏿\u200d♂️",
+1291	    "man_getting_massage_light_skin_tone": "💆🏻\u200d♂️",
+1292	    "man_getting_massage_medium-dark_skin_tone": "💆🏾\u200d♂️",
+1293	    "man_getting_massage_medium-light_skin_tone": "💆🏼\u200d♂️",
+1294	    "man_getting_massage_medium_skin_tone": "💆🏽\u200d♂️",
+1295	    "man_golfing": "🏌️\u200d♂️",
+1296	    "man_golfing_dark_skin_tone": "🏌🏿\u200d♂️",
+1297	    "man_golfing_light_skin_tone": "🏌🏻\u200d♂️",
+1298	    "man_golfing_medium-dark_skin_tone": "🏌🏾\u200d♂️",
+1299	    "man_golfing_medium-light_skin_tone": "🏌🏼\u200d♂️",
+1300	    "man_golfing_medium_skin_tone": "🏌🏽\u200d♂️",
+1301	    "man_guard": "💂\u200d♂️",
+1302	    "man_guard_dark_skin_tone": "💂🏿\u200d♂️",
+1303	    "man_guard_light_skin_tone": "💂🏻\u200d♂️",
+1304	    "man_guard_medium-dark_skin_tone": "💂🏾\u200d♂️",
+1305	    "man_guard_medium-light_skin_tone": "💂🏼\u200d♂️",
+1306	    "man_guard_medium_skin_tone": "💂🏽\u200d♂️",
+1307	    "man_health_worker": "👨\u200d⚕️",
+1308	    "man_health_worker_dark_skin_tone": "👨🏿\u200d⚕️",
+1309	    "man_health_worker_light_skin_tone": "👨🏻\u200d⚕️",
+1310	    "man_health_worker_medium-dark_skin_tone": "👨🏾\u200d⚕️",
+1311	    "man_health_worker_medium-light_skin_tone": "👨🏼\u200d⚕️",
+1312	    "man_health_worker_medium_skin_tone": "👨🏽\u200d⚕️",
+1313	    "man_in_lotus_position": "🧘\u200d♂️",
+1314	    "man_in_lotus_position_dark_skin_tone": "🧘🏿\u200d♂️",
+1315	    "man_in_lotus_position_light_skin_tone": "🧘🏻\u200d♂️",
+1316	    "man_in_lotus_position_medium-dark_skin_tone": "🧘🏾\u200d♂️",
+1317	    "man_in_lotus_position_medium-light_skin_tone": "🧘🏼\u200d♂️",
+1318	    "man_in_lotus_position_medium_skin_tone": "🧘🏽\u200d♂️",
+1319	    "man_in_manual_wheelchair": "👨\u200d🦽",
+1320	    "man_in_motorized_wheelchair": "👨\u200d🦼",
+1321	    "man_in_steamy_room": "🧖\u200d♂️",
+1322	    "man_in_steamy_room_dark_skin_tone": "🧖🏿\u200d♂️",
+1323	    "man_in_steamy_room_light_skin_tone": "🧖🏻\u200d♂️",
+1324	    "man_in_steamy_room_medium-dark_skin_tone": "🧖🏾\u200d♂️",
+1325	    "man_in_steamy_room_medium-light_skin_tone": "🧖🏼\u200d♂️",
+1326	    "man_in_steamy_room_medium_skin_tone": "🧖🏽\u200d♂️",
+1327	    "man_in_suit_levitating": "🕴",
+1328	    "man_in_suit_levitating_dark_skin_tone": "🕴🏿",
+1329	    "man_in_suit_levitating_light_skin_tone": "🕴🏻",
+1330	    "man_in_suit_levitating_medium-dark_skin_tone": "🕴🏾",
+1331	    "man_in_suit_levitating_medium-light_skin_tone": "🕴🏼",
+1332	    "man_in_suit_levitating_medium_skin_tone": "🕴🏽",
+1333	    "man_in_tuxedo": "🤵",
+1334	    "man_in_tuxedo_dark_skin_tone": "🤵🏿",
+1335	    "man_in_tuxedo_light_skin_tone": "🤵🏻",
+1336	    "man_in_tuxedo_medium-dark_skin_tone": "🤵🏾",
+1337	    "man_in_tuxedo_medium-light_skin_tone": "🤵🏼",
+1338	    "man_in_tuxedo_medium_skin_tone": "🤵🏽",
+1339	    "man_judge": "👨\u200d⚖️",
+1340	    "man_judge_dark_skin_tone": "👨🏿\u200d⚖️",
+1341	    "man_judge_light_skin_tone": "👨🏻\u200d⚖️",
+1342	    "man_judge_medium-dark_skin_tone": "👨🏾\u200d⚖️",
+1343	    "man_judge_medium-light_skin_tone": "👨🏼\u200d⚖️",
+1344	    "man_judge_medium_skin_tone": "👨🏽\u200d⚖️",
+1345	    "man_juggling": "🤹\u200d♂️",
+1346	    "man_juggling_dark_skin_tone": "🤹🏿\u200d♂️",
+1347	    "man_juggling_light_skin_tone": "🤹🏻\u200d♂️",
+1348	    "man_juggling_medium-dark_skin_tone": "🤹🏾\u200d♂️",
+1349	    "man_juggling_medium-light_skin_tone": "🤹🏼\u200d♂️",
+1350	    "man_juggling_medium_skin_tone": "🤹🏽\u200d♂️",
+1351	    "man_lifting_weights": "🏋️\u200d♂️",
+1352	    "man_lifting_weights_dark_skin_tone": "🏋🏿\u200d♂️",
+1353	    "man_lifting_weights_light_skin_tone": "🏋🏻\u200d♂️",
+1354	    "man_lifting_weights_medium-dark_skin_tone": "🏋🏾\u200d♂️",
+1355	    "man_lifting_weights_medium-light_skin_tone": "🏋🏼\u200d♂️",
+1356	    "man_lifting_weights_medium_skin_tone": "🏋🏽\u200d♂️",
+1357	    "man_light_skin_tone": "👨🏻",
+1358	    "man_mage": "🧙\u200d♂️",
+1359	    "man_mage_dark_skin_tone": "🧙🏿\u200d♂️",
+1360	    "man_mage_light_skin_tone": "🧙🏻\u200d♂️",
+1361	    "man_mage_medium-dark_skin_tone": "🧙🏾\u200d♂️",
+1362	    "man_mage_medium-light_skin_tone": "🧙🏼\u200d♂️",
+1363	    "man_mage_medium_skin_tone": "🧙🏽\u200d♂️",
+1364	    "man_mechanic": "👨\u200d🔧",
+1365	    "man_mechanic_dark_skin_tone": "👨🏿\u200d🔧",
+1366	    "man_mechanic_light_skin_tone": "👨🏻\u200d🔧",
+1367	    "man_mechanic_medium-dark_skin_tone": "👨🏾\u200d🔧",
+1368	    "man_mechanic_medium-light_skin_tone": "👨🏼\u200d🔧",
+1369	    "man_mechanic_medium_skin_tone": "👨🏽\u200d🔧",
+1370	    "man_medium-dark_skin_tone": "👨🏾",
+1371	    "man_medium-light_skin_tone": "👨🏼",
+1372	    "man_medium_skin_tone": "👨🏽",
+1373	    "man_mountain_biking": "🚵\u200d♂️",
+1374	    "man_mountain_biking_dark_skin_tone": "🚵🏿\u200d♂️",
+1375	    "man_mountain_biking_light_skin_tone": "🚵🏻\u200d♂️",
+1376	    "man_mountain_biking_medium-dark_skin_tone": "🚵🏾\u200d♂️",
+1377	    "man_mountain_biking_medium-light_skin_tone": "🚵🏼\u200d♂️",
+1378	    "man_mountain_biking_medium_skin_tone": "🚵🏽\u200d♂️",
+1379	    "man_office_worker": "👨\u200d💼",
+1380	    "man_office_worker_dark_skin_tone": "👨🏿\u200d💼",
+1381	    "man_office_worker_light_skin_tone": "👨🏻\u200d💼",
+1382	    "man_office_worker_medium-dark_skin_tone": "👨🏾\u200d💼",
+1383	    "man_office_worker_medium-light_skin_tone": "👨🏼\u200d💼",
+1384	    "man_office_worker_medium_skin_tone": "👨🏽\u200d💼",
+1385	    "man_pilot": "👨\u200d✈️",
+1386	    "man_pilot_dark_skin_tone": "👨🏿\u200d✈️",
+1387	    "man_pilot_light_skin_tone": "👨🏻\u200d✈️",
+1388	    "man_pilot_medium-dark_skin_tone": "👨🏾\u200d✈️",
+1389	    "man_pilot_medium-light_skin_tone": "👨🏼\u200d✈️",
+1390	    "man_pilot_medium_skin_tone": "👨🏽\u200d✈️",
+1391	    "man_playing_handball": "🤾\u200d♂️",
+1392	    "man_playing_handball_dark_skin_tone": "🤾🏿\u200d♂️",
+1393	    "man_playing_handball_light_skin_tone": "🤾🏻\u200d♂️",
+1394	    "man_playing_handball_medium-dark_skin_tone": "🤾🏾\u200d♂️",
+1395	    "man_playing_handball_medium-light_skin_tone": "🤾🏼\u200d♂️",
+1396	    "man_playing_handball_medium_skin_tone": "🤾🏽\u200d♂️",
+1397	    "man_playing_water_polo": "🤽\u200d♂️",
+1398	    "man_playing_water_polo_dark_skin_tone": "🤽🏿\u200d♂️",
+1399	    "man_playing_water_polo_light_skin_tone": "🤽🏻\u200d♂️",
+1400	    "man_playing_water_polo_medium-dark_skin_tone": "🤽🏾\u200d♂️",
+1401	    "man_playing_water_polo_medium-light_skin_tone": "🤽🏼\u200d♂️",
+1402	    "man_playing_water_polo_medium_skin_tone": "🤽🏽\u200d♂️",
+1403	    "man_police_officer": "👮\u200d♂️",
+1404	    "man_police_officer_dark_skin_tone": "👮🏿\u200d♂️",
+1405	    "man_police_officer_light_skin_tone": "👮🏻\u200d♂️",
+1406	    "man_police_officer_medium-dark_skin_tone": "👮🏾\u200d♂️",
+1407	    "man_police_officer_medium-light_skin_tone": "👮🏼\u200d♂️",
+1408	    "man_police_officer_medium_skin_tone": "👮🏽\u200d♂️",
+1409	    "man_pouting": "🙎\u200d♂️",
+1410	    "man_pouting_dark_skin_tone": "🙎🏿\u200d♂️",
+1411	    "man_pouting_light_skin_tone": "🙎🏻\u200d♂️",
+1412	    "man_pouting_medium-dark_skin_tone": "🙎🏾\u200d♂️",
+1413	    "man_pouting_medium-light_skin_tone": "🙎🏼\u200d♂️",
+1414	    "man_pouting_medium_skin_tone": "🙎🏽\u200d♂️",
+1415	    "man_raising_hand": "🙋\u200d♂️",
+1416	    "man_raising_hand_dark_skin_tone": "🙋🏿\u200d♂️",
+1417	    "man_raising_hand_light_skin_tone": "🙋🏻\u200d♂️",
+1418	    "man_raising_hand_medium-dark_skin_tone": "🙋🏾\u200d♂️",
+1419	    "man_raising_hand_medium-light_skin_tone": "🙋🏼\u200d♂️",
+1420	    "man_raising_hand_medium_skin_tone": "🙋🏽\u200d♂️",
+1421	    "man_rowing_boat": "🚣\u200d♂️",
+1422	    "man_rowing_boat_dark_skin_tone": "🚣🏿\u200d♂️",
+1423	    "man_rowing_boat_light_skin_tone": "🚣🏻\u200d♂️",
+1424	    "man_rowing_boat_medium-dark_skin_tone": "🚣🏾\u200d♂️",
+1425	    "man_rowing_boat_medium-light_skin_tone": "🚣🏼\u200d♂️",
+1426	    "man_rowing_boat_medium_skin_tone": "🚣🏽\u200d♂️",
+1427	    "man_running": "🏃\u200d♂️",
+1428	    "man_running_dark_skin_tone": "🏃🏿\u200d♂️",
+1429	    "man_running_light_skin_tone": "🏃🏻\u200d♂️",
+1430	    "man_running_medium-dark_skin_tone": "🏃🏾\u200d♂️",
+1431	    "man_running_medium-light_skin_tone": "🏃🏼\u200d♂️",
+1432	    "man_running_medium_skin_tone": "🏃🏽\u200d♂️",
+1433	    "man_scientist": "👨\u200d🔬",
+1434	    "man_scientist_dark_skin_tone": "👨🏿\u200d🔬",
+1435	    "man_scientist_light_skin_tone": "👨🏻\u200d🔬",
+1436	    "man_scientist_medium-dark_skin_tone": "👨🏾\u200d🔬",
+1437	    "man_scientist_medium-light_skin_tone": "👨🏼\u200d🔬",
+1438	    "man_scientist_medium_skin_tone": "👨🏽\u200d🔬",
+1439	    "man_shrugging": "🤷\u200d♂️",
+1440	    "man_shrugging_dark_skin_tone": "🤷🏿\u200d♂️",
+1441	    "man_shrugging_light_skin_tone": "🤷🏻\u200d♂️",
+1442	    "man_shrugging_medium-dark_skin_tone": "🤷🏾\u200d♂️",
+1443	    "man_shrugging_medium-light_skin_tone": "🤷🏼\u200d♂️",
+1444	    "man_shrugging_medium_skin_tone": "🤷🏽\u200d♂️",
+1445	    "man_singer": "👨\u200d🎤",
+1446	    "man_singer_dark_skin_tone": "👨🏿\u200d🎤",
+1447	    "man_singer_light_skin_tone": "👨🏻\u200d🎤",
+1448	    "man_singer_medium-dark_skin_tone": "👨🏾\u200d🎤",
+1449	    "man_singer_medium-light_skin_tone": "👨🏼\u200d🎤",
+1450	    "man_singer_medium_skin_tone": "👨🏽\u200d🎤",
+1451	    "man_student": "👨\u200d🎓",
+1452	    "man_student_dark_skin_tone": "👨🏿\u200d🎓",
+1453	    "man_student_light_skin_tone": "👨🏻\u200d🎓",
+1454	    "man_student_medium-dark_skin_tone": "👨🏾\u200d🎓",
+1455	    "man_student_medium-light_skin_tone": "👨🏼\u200d🎓",
+1456	    "man_student_medium_skin_tone": "👨🏽\u200d🎓",
+1457	    "man_surfing": "🏄\u200d♂️",
+1458	    "man_surfing_dark_skin_tone": "🏄🏿\u200d♂️",
+1459	    "man_surfing_light_skin_tone": "🏄🏻\u200d♂️",
+1460	    "man_surfing_medium-dark_skin_tone": "🏄🏾\u200d♂️",
+1461	    "man_surfing_medium-light_skin_tone": "🏄🏼\u200d♂️",
+1462	    "man_surfing_medium_skin_tone": "🏄🏽\u200d♂️",
+1463	    "man_swimming": "🏊\u200d♂️",
+1464	    "man_swimming_dark_skin_tone": "🏊🏿\u200d♂️",
+1465	    "man_swimming_light_skin_tone": "🏊🏻\u200d♂️",
+1466	    "man_swimming_medium-dark_skin_tone": "🏊🏾\u200d♂️",
+1467	    "man_swimming_medium-light_skin_tone": "🏊🏼\u200d♂️",
+1468	    "man_swimming_medium_skin_tone": "🏊🏽\u200d♂️",
+1469	    "man_teacher": "👨\u200d🏫",
+1470	    "man_teacher_dark_skin_tone": "👨🏿\u200d🏫",
+1471	    "man_teacher_light_skin_tone": "👨🏻\u200d🏫",
+1472	    "man_teacher_medium-dark_skin_tone": "👨🏾\u200d🏫",
+1473	    "man_teacher_medium-light_skin_tone": "👨🏼\u200d🏫",
+1474	    "man_teacher_medium_skin_tone": "👨🏽\u200d🏫",
+1475	    "man_technologist": "👨\u200d💻",
+1476	    "man_technologist_dark_skin_tone": "👨🏿\u200d💻",
+1477	    "man_technologist_light_skin_tone": "👨🏻\u200d💻",
+1478	    "man_technologist_medium-dark_skin_tone": "👨🏾\u200d💻",
+1479	    "man_technologist_medium-light_skin_tone": "👨🏼\u200d💻",
+1480	    "man_technologist_medium_skin_tone": "👨🏽\u200d💻",
+1481	    "man_tipping_hand": "💁\u200d♂️",
+1482	    "man_tipping_hand_dark_skin_tone": "💁🏿\u200d♂️",
+1483	    "man_tipping_hand_light_skin_tone": "💁🏻\u200d♂️",
+1484	    "man_tipping_hand_medium-dark_skin_tone": "💁🏾\u200d♂️",
+1485	    "man_tipping_hand_medium-light_skin_tone": "💁🏼\u200d♂️",
+1486	    "man_tipping_hand_medium_skin_tone": "💁🏽\u200d♂️",
+1487	    "man_vampire": "🧛\u200d♂️",
+1488	    "man_vampire_dark_skin_tone": "🧛🏿\u200d♂️",
+1489	    "man_vampire_light_skin_tone": "🧛🏻\u200d♂️",
+1490	    "man_vampire_medium-dark_skin_tone": "🧛🏾\u200d♂️",
+1491	    "man_vampire_medium-light_skin_tone": "🧛🏼\u200d♂️",
+1492	    "man_vampire_medium_skin_tone": "🧛🏽\u200d♂️",
+1493	    "man_walking": "🚶\u200d♂️",
+1494	    "man_walking_dark_skin_tone": "🚶🏿\u200d♂️",
+1495	    "man_walking_light_skin_tone": "🚶🏻\u200d♂️",
+1496	    "man_walking_medium-dark_skin_tone": "🚶🏾\u200d♂️",
+1497	    "man_walking_medium-light_skin_tone": "🚶🏼\u200d♂️",
+1498	    "man_walking_medium_skin_tone": "🚶🏽\u200d♂️",
+1499	    "man_wearing_turban": "👳\u200d♂️",
+1500	    "man_wearing_turban_dark_skin_tone": "👳🏿\u200d♂️",
+1501	    "man_wearing_turban_light_skin_tone": "👳🏻\u200d♂️",
+1502	    "man_wearing_turban_medium-dark_skin_tone": "👳🏾\u200d♂️",
+1503	    "man_wearing_turban_medium-light_skin_tone": "👳🏼\u200d♂️",
+1504	    "man_wearing_turban_medium_skin_tone": "👳🏽\u200d♂️",
+1505	    "man_with_probing_cane": "👨\u200d🦯",
+1506	    "man_with_chinese_cap": "👲",
+1507	    "man_with_chinese_cap_dark_skin_tone": "👲🏿",
+1508	    "man_with_chinese_cap_light_skin_tone": "👲🏻",
+1509	    "man_with_chinese_cap_medium-dark_skin_tone": "👲🏾",
+1510	    "man_with_chinese_cap_medium-light_skin_tone": "👲🏼",
+1511	    "man_with_chinese_cap_medium_skin_tone": "👲🏽",
+1512	    "man_zombie": "🧟\u200d♂️",
+1513	    "mango": "🥭",
+1514	    "mantelpiece_clock": "🕰",
+1515	    "manual_wheelchair": "🦽",
+1516	    "man’s_shoe": "👞",
+1517	    "map_of_japan": "🗾",
+1518	    "maple_leaf": "🍁",
+1519	    "martial_arts_uniform": "🥋",
+1520	    "mate": "🧉",
+1521	    "meat_on_bone": "🍖",
+1522	    "mechanical_arm": "🦾",
+1523	    "mechanical_leg": "🦿",
+1524	    "medical_symbol": "⚕",
+1525	    "megaphone": "📣",
+1526	    "melon": "🍈",
+1527	    "memo": "📝",
+1528	    "men_with_bunny_ears": "👯\u200d♂️",
+1529	    "men_wrestling": "🤼\u200d♂️",
+1530	    "menorah": "🕎",
+1531	    "men’s_room": "🚹",
+1532	    "mermaid": "🧜\u200d♀️",
+1533	    "mermaid_dark_skin_tone": "🧜🏿\u200d♀️",
+1534	    "mermaid_light_skin_tone": "🧜🏻\u200d♀️",
+1535	    "mermaid_medium-dark_skin_tone": "🧜🏾\u200d♀️",
+1536	    "mermaid_medium-light_skin_tone": "🧜🏼\u200d♀️",
+1537	    "mermaid_medium_skin_tone": "🧜🏽\u200d♀️",
+1538	    "merman": "🧜\u200d♂️",
+1539	    "merman_dark_skin_tone": "🧜🏿\u200d♂️",
+1540	    "merman_light_skin_tone": "🧜🏻\u200d♂️",
+1541	    "merman_medium-dark_skin_tone": "🧜🏾\u200d♂️",
+1542	    "merman_medium-light_skin_tone": "🧜🏼\u200d♂️",
+1543	    "merman_medium_skin_tone": "🧜🏽\u200d♂️",
+1544	    "merperson": "🧜",
+1545	    "merperson_dark_skin_tone": "🧜🏿",
+1546	    "merperson_light_skin_tone": "🧜🏻",
+1547	    "merperson_medium-dark_skin_tone": "🧜🏾",
+1548	    "merperson_medium-light_skin_tone": "🧜🏼",
+1549	    "merperson_medium_skin_tone": "🧜🏽",
+1550	    "metro": "🚇",
+1551	    "microbe": "🦠",
+1552	    "microphone": "🎤",
+1553	    "microscope": "🔬",
+1554	    "middle_finger": "🖕",
+1555	    "middle_finger_dark_skin_tone": "🖕🏿",
+1556	    "middle_finger_light_skin_tone": "🖕🏻",
+1557	    "middle_finger_medium-dark_skin_tone": "🖕🏾",
+1558	    "middle_finger_medium-light_skin_tone": "🖕🏼",
+1559	    "middle_finger_medium_skin_tone": "🖕🏽",
+1560	    "military_medal": "🎖",
+1561	    "milky_way": "🌌",
+1562	    "minibus": "🚐",
+1563	    "moai": "🗿",
+1564	    "mobile_phone": "📱",
+1565	    "mobile_phone_off": "📴",
+1566	    "mobile_phone_with_arrow": "📲",
+1567	    "money-mouth_face": "🤑",
+1568	    "money_bag": "💰",
+1569	    "money_with_wings": "💸",
+1570	    "monkey": "🐒",
+1571	    "monkey_face": "🐵",
+1572	    "monorail": "🚝",
+1573	    "moon_cake": "🥮",
+1574	    "moon_viewing_ceremony": "🎑",
+1575	    "mosque": "🕌",
+1576	    "mosquito": "🦟",
+1577	    "motor_boat": "🛥",
+1578	    "motor_scooter": "🛵",
+1579	    "motorcycle": "🏍",
+1580	    "motorized_wheelchair": "🦼",
+1581	    "motorway": "🛣",
+1582	    "mount_fuji": "🗻",
+1583	    "mountain": "⛰",
+1584	    "mountain_cableway": "🚠",
+1585	    "mountain_railway": "🚞",
+1586	    "mouse": "🐭",
+1587	    "mouse_face": "🐭",
+1588	    "mouth": "👄",
+1589	    "movie_camera": "🎥",
+1590	    "mushroom": "🍄",
+1591	    "musical_keyboard": "🎹",
+1592	    "musical_note": "🎵",
+1593	    "musical_notes": "🎶",
+1594	    "musical_score": "🎼",
+1595	    "muted_speaker": "🔇",
+1596	    "nail_polish": "💅",
+1597	    "nail_polish_dark_skin_tone": "💅🏿",
+1598	    "nail_polish_light_skin_tone": "💅🏻",
+1599	    "nail_polish_medium-dark_skin_tone": "💅🏾",
+1600	    "nail_polish_medium-light_skin_tone": "💅🏼",
+1601	    "nail_polish_medium_skin_tone": "💅🏽",
+1602	    "name_badge": "📛",
+1603	    "national_park": "🏞",
+1604	    "nauseated_face": "🤢",
+1605	    "nazar_amulet": "🧿",
+1606	    "necktie": "👔",
+1607	    "nerd_face": "🤓",
+1608	    "neutral_face": "😐",
+1609	    "new_moon": "🌑",
+1610	    "new_moon_face": "🌚",
+1611	    "newspaper": "📰",
+1612	    "next_track_button": "⏭",
+1613	    "night_with_stars": "🌃",
+1614	    "nine-thirty": "🕤",
+1615	    "nine_o’clock": "🕘",
+1616	    "no_bicycles": "🚳",
+1617	    "no_entry": "⛔",
+1618	    "no_littering": "🚯",
+1619	    "no_mobile_phones": "📵",
+1620	    "no_one_under_eighteen": "🔞",
+1621	    "no_pedestrians": "🚷",
+1622	    "no_smoking": "🚭",
+1623	    "non-potable_water": "🚱",
+1624	    "nose": "👃",
+1625	    "nose_dark_skin_tone": "👃🏿",
+1626	    "nose_light_skin_tone": "👃🏻",
+1627	    "nose_medium-dark_skin_tone": "👃🏾",
+1628	    "nose_medium-light_skin_tone": "👃🏼",
+1629	    "nose_medium_skin_tone": "👃🏽",
+1630	    "notebook": "📓",
+1631	    "notebook_with_decorative_cover": "📔",
+1632	    "nut_and_bolt": "🔩",
+1633	    "octopus": "🐙",
+1634	    "oden": "🍢",
+1635	    "office_building": "🏢",
+1636	    "ogre": "👹",
+1637	    "oil_drum": "🛢",
+1638	    "old_key": "🗝",
+1639	    "old_man": "👴",
+1640	    "old_man_dark_skin_tone": "👴🏿",
+1641	    "old_man_light_skin_tone": "👴🏻",
+1642	    "old_man_medium-dark_skin_tone": "👴🏾",
+1643	    "old_man_medium-light_skin_tone": "👴🏼",
+1644	    "old_man_medium_skin_tone": "👴🏽",
+1645	    "old_woman": "👵",
+1646	    "old_woman_dark_skin_tone": "👵🏿",
+1647	    "old_woman_light_skin_tone": "👵🏻",
+1648	    "old_woman_medium-dark_skin_tone": "👵🏾",
+1649	    "old_woman_medium-light_skin_tone": "👵🏼",
+1650	    "old_woman_medium_skin_tone": "👵🏽",
+1651	    "older_adult": "🧓",
+1652	    "older_adult_dark_skin_tone": "🧓🏿",
+1653	    "older_adult_light_skin_tone": "🧓🏻",
+1654	    "older_adult_medium-dark_skin_tone": "🧓🏾",
+1655	    "older_adult_medium-light_skin_tone": "🧓🏼",
+1656	    "older_adult_medium_skin_tone": "🧓🏽",
+1657	    "om": "🕉",
+1658	    "oncoming_automobile": "🚘",
+1659	    "oncoming_bus": "🚍",
+1660	    "oncoming_fist": "👊",
+1661	    "oncoming_fist_dark_skin_tone": "👊🏿",
+1662	    "oncoming_fist_light_skin_tone": "👊🏻",
+1663	    "oncoming_fist_medium-dark_skin_tone": "👊🏾",
+1664	    "oncoming_fist_medium-light_skin_tone": "👊🏼",
+1665	    "oncoming_fist_medium_skin_tone": "👊🏽",
+1666	    "oncoming_police_car": "🚔",
+1667	    "oncoming_taxi": "🚖",
+1668	    "one-piece_swimsuit": "🩱",
+1669	    "one-thirty": "🕜",
+1670	    "one_o’clock": "🕐",
+1671	    "onion": "🧅",
+1672	    "open_book": "📖",
+1673	    "open_file_folder": "📂",
+1674	    "open_hands": "👐",
+1675	    "open_hands_dark_skin_tone": "👐🏿",
+1676	    "open_hands_light_skin_tone": "👐🏻",
+1677	    "open_hands_medium-dark_skin_tone": "👐🏾",
+1678	    "open_hands_medium-light_skin_tone": "👐🏼",
+1679	    "open_hands_medium_skin_tone": "👐🏽",
+1680	    "open_mailbox_with_lowered_flag": "📭",
+1681	    "open_mailbox_with_raised_flag": "📬",
+1682	    "optical_disk": "💿",
+1683	    "orange_book": "📙",
+1684	    "orange_circle": "🟠",
+1685	    "orange_heart": "🧡",
+1686	    "orange_square": "🟧",
+1687	    "orangutan": "🦧",
+1688	    "orthodox_cross": "☦",
+1689	    "otter": "🦦",
+1690	    "outbox_tray": "📤",
+1691	    "owl": "🦉",
+1692	    "ox": "🐂",
+1693	    "oyster": "🦪",
+1694	    "package": "📦",
+1695	    "page_facing_up": "📄",
+1696	    "page_with_curl": "📃",
+1697	    "pager": "📟",
+1698	    "paintbrush": "🖌",
+1699	    "palm_tree": "🌴",
+1700	    "palms_up_together": "🤲",
+1701	    "palms_up_together_dark_skin_tone": "🤲🏿",
+1702	    "palms_up_together_light_skin_tone": "🤲🏻",
+1703	    "palms_up_together_medium-dark_skin_tone": "🤲🏾",
+1704	    "palms_up_together_medium-light_skin_tone": "🤲🏼",
+1705	    "palms_up_together_medium_skin_tone": "🤲🏽",
+1706	    "pancakes": "🥞",
+1707	    "panda_face": "🐼",
+1708	    "paperclip": "📎",
+1709	    "parrot": "🦜",
+1710	    "part_alternation_mark": "〽",
+1711	    "party_popper": "🎉",
+1712	    "partying_face": "🥳",
+1713	    "passenger_ship": "🛳",
+1714	    "passport_control": "🛂",
+1715	    "pause_button": "⏸",
+1716	    "paw_prints": "🐾",
+1717	    "peace_symbol": "☮",
+1718	    "peach": "🍑",
+1719	    "peacock": "🦚",
+1720	    "peanuts": "🥜",
+1721	    "pear": "🍐",
+1722	    "pen": "🖊",
+1723	    "pencil": "📝",
+1724	    "penguin": "🐧",
+1725	    "pensive_face": "😔",
+1726	    "people_holding_hands": "🧑\u200d🤝\u200d🧑",
+1727	    "people_with_bunny_ears": "👯",
+1728	    "people_wrestling": "🤼",
+1729	    "performing_arts": "🎭",
+1730	    "persevering_face": "😣",
+1731	    "person_biking": "🚴",
+1732	    "person_biking_dark_skin_tone": "🚴🏿",
+1733	    "person_biking_light_skin_tone": "🚴🏻",
+1734	    "person_biking_medium-dark_skin_tone": "🚴🏾",
+1735	    "person_biking_medium-light_skin_tone": "🚴🏼",
+1736	    "person_biking_medium_skin_tone": "🚴🏽",
+1737	    "person_bouncing_ball": "⛹",
+1738	    "person_bouncing_ball_dark_skin_tone": "⛹🏿",
+1739	    "person_bouncing_ball_light_skin_tone": "⛹🏻",
+1740	    "person_bouncing_ball_medium-dark_skin_tone": "⛹🏾",
+1741	    "person_bouncing_ball_medium-light_skin_tone": "⛹🏼",
+1742	    "person_bouncing_ball_medium_skin_tone": "⛹🏽",
+1743	    "person_bowing": "🙇",
+1744	    "person_bowing_dark_skin_tone": "🙇🏿",
+1745	    "person_bowing_light_skin_tone": "🙇🏻",
+1746	    "person_bowing_medium-dark_skin_tone": "🙇🏾",
+1747	    "person_bowing_medium-light_skin_tone": "🙇🏼",
+1748	    "person_bowing_medium_skin_tone": "🙇🏽",
+1749	    "person_cartwheeling": "🤸",
+1750	    "person_cartwheeling_dark_skin_tone": "🤸🏿",
+1751	    "person_cartwheeling_light_skin_tone": "🤸🏻",
+1752	    "person_cartwheeling_medium-dark_skin_tone": "🤸🏾",
+1753	    "person_cartwheeling_medium-light_skin_tone": "🤸🏼",
+1754	    "person_cartwheeling_medium_skin_tone": "🤸🏽",
+1755	    "person_climbing": "🧗",
+1756	    "person_climbing_dark_skin_tone": "🧗🏿",
+1757	    "person_climbing_light_skin_tone": "🧗🏻",
+1758	    "person_climbing_medium-dark_skin_tone": "🧗🏾",
+1759	    "person_climbing_medium-light_skin_tone": "🧗🏼",
+1760	    "person_climbing_medium_skin_tone": "🧗🏽",
+1761	    "person_facepalming": "🤦",
+1762	    "person_facepalming_dark_skin_tone": "🤦🏿",
+1763	    "person_facepalming_light_skin_tone": "🤦🏻",
+1764	    "person_facepalming_medium-dark_skin_tone": "🤦🏾",
+1765	    "person_facepalming_medium-light_skin_tone": "🤦🏼",
+1766	    "person_facepalming_medium_skin_tone": "🤦🏽",
+1767	    "person_fencing": "🤺",
+1768	    "person_frowning": "🙍",
+1769	    "person_frowning_dark_skin_tone": "🙍🏿",
+1770	    "person_frowning_light_skin_tone": "🙍🏻",
+1771	    "person_frowning_medium-dark_skin_tone": "🙍🏾",
+1772	    "person_frowning_medium-light_skin_tone": "🙍🏼",
+1773	    "person_frowning_medium_skin_tone": "🙍🏽",
+1774	    "person_gesturing_no": "🙅",
+1775	    "person_gesturing_no_dark_skin_tone": "🙅🏿",
+1776	    "person_gesturing_no_light_skin_tone": "🙅🏻",
+1777	    "person_gesturing_no_medium-dark_skin_tone": "🙅🏾",
+1778	    "person_gesturing_no_medium-light_skin_tone": "🙅🏼",
+1779	    "person_gesturing_no_medium_skin_tone": "🙅🏽",
+1780	    "person_gesturing_ok": "🙆",
+1781	    "person_gesturing_ok_dark_skin_tone": "🙆🏿",
+1782	    "person_gesturing_ok_light_skin_tone": "🙆🏻",
+1783	    "person_gesturing_ok_medium-dark_skin_tone": "🙆🏾",
+1784	    "person_gesturing_ok_medium-light_skin_tone": "🙆🏼",
+1785	    "person_gesturing_ok_medium_skin_tone": "🙆🏽",
+1786	    "person_getting_haircut": "💇",
+1787	    "person_getting_haircut_dark_skin_tone": "💇🏿",
+1788	    "person_getting_haircut_light_skin_tone": "💇🏻",
+1789	    "person_getting_haircut_medium-dark_skin_tone": "💇🏾",
+1790	    "person_getting_haircut_medium-light_skin_tone": "💇🏼",
+1791	    "person_getting_haircut_medium_skin_tone": "💇🏽",
+1792	    "person_getting_massage": "💆",
+1793	    "person_getting_massage_dark_skin_tone": "💆🏿",
+1794	    "person_getting_massage_light_skin_tone": "💆🏻",
+1795	    "person_getting_massage_medium-dark_skin_tone": "💆🏾",
+1796	    "person_getting_massage_medium-light_skin_tone": "💆🏼",
+1797	    "person_getting_massage_medium_skin_tone": "💆🏽",
+1798	    "person_golfing": "🏌",
+1799	    "person_golfing_dark_skin_tone": "🏌🏿",
+1800	    "person_golfing_light_skin_tone": "🏌🏻",
+1801	    "person_golfing_medium-dark_skin_tone": "🏌🏾",
+1802	    "person_golfing_medium-light_skin_tone": "🏌🏼",
+1803	    "person_golfing_medium_skin_tone": "🏌🏽",
+1804	    "person_in_bed": "🛌",
+1805	    "person_in_bed_dark_skin_tone": "🛌🏿",
+1806	    "person_in_bed_light_skin_tone": "🛌🏻",
+1807	    "person_in_bed_medium-dark_skin_tone": "🛌🏾",
+1808	    "person_in_bed_medium-light_skin_tone": "🛌🏼",
+1809	    "person_in_bed_medium_skin_tone": "🛌🏽",
+1810	    "person_in_lotus_position": "🧘",
+1811	    "person_in_lotus_position_dark_skin_tone": "🧘🏿",
+1812	    "person_in_lotus_position_light_skin_tone": "🧘🏻",
+1813	    "person_in_lotus_position_medium-dark_skin_tone": "🧘🏾",
+1814	    "person_in_lotus_position_medium-light_skin_tone": "🧘🏼",
+1815	    "person_in_lotus_position_medium_skin_tone": "🧘🏽",
+1816	    "person_in_steamy_room": "🧖",
+1817	    "person_in_steamy_room_dark_skin_tone": "🧖🏿",
+1818	    "person_in_steamy_room_light_skin_tone": "🧖🏻",
+1819	    "person_in_steamy_room_medium-dark_skin_tone": "🧖🏾",
+1820	    "person_in_steamy_room_medium-light_skin_tone": "🧖🏼",
+1821	    "person_in_steamy_room_medium_skin_tone": "🧖🏽",
+1822	    "person_juggling": "🤹",
+1823	    "person_juggling_dark_skin_tone": "🤹🏿",
+1824	    "person_juggling_light_skin_tone": "🤹🏻",
+1825	    "person_juggling_medium-dark_skin_tone": "🤹🏾",
+1826	    "person_juggling_medium-light_skin_tone": "🤹🏼",
+1827	    "person_juggling_medium_skin_tone": "🤹🏽",
+1828	    "person_kneeling": "🧎",
+1829	    "person_lifting_weights": "🏋",
+1830	    "person_lifting_weights_dark_skin_tone": "🏋🏿",
+1831	    "person_lifting_weights_light_skin_tone": "🏋🏻",
+1832	    "person_lifting_weights_medium-dark_skin_tone": "🏋🏾",
+1833	    "person_lifting_weights_medium-light_skin_tone": "🏋🏼",
+1834	    "person_lifting_weights_medium_skin_tone": "🏋🏽",
+1835	    "person_mountain_biking": "🚵",
+1836	    "person_mountain_biking_dark_skin_tone": "🚵🏿",
+1837	    "person_mountain_biking_light_skin_tone": "🚵🏻",
+1838	    "person_mountain_biking_medium-dark_skin_tone": "🚵🏾",
+1839	    "person_mountain_biking_medium-light_skin_tone": "🚵🏼",
+1840	    "person_mountain_biking_medium_skin_tone": "🚵🏽",
+1841	    "person_playing_handball": "🤾",
+1842	    "person_playing_handball_dark_skin_tone": "🤾🏿",
+1843	    "person_playing_handball_light_skin_tone": "🤾🏻",
+1844	    "person_playing_handball_medium-dark_skin_tone": "🤾🏾",
+1845	    "person_playing_handball_medium-light_skin_tone": "🤾🏼",
+1846	    "person_playing_handball_medium_skin_tone": "🤾🏽",
+1847	    "person_playing_water_polo": "🤽",
+1848	    "person_playing_water_polo_dark_skin_tone": "🤽🏿",
+1849	    "person_playing_water_polo_light_skin_tone": "🤽🏻",
+1850	    "person_playing_water_polo_medium-dark_skin_tone": "🤽🏾",
+1851	    "person_playing_water_polo_medium-light_skin_tone": "🤽🏼",
+1852	    "person_playing_water_polo_medium_skin_tone": "🤽🏽",
+1853	    "person_pouting": "🙎",
+1854	    "person_pouting_dark_skin_tone": "🙎🏿",
+1855	    "person_pouting_light_skin_tone": "🙎🏻",
+1856	    "person_pouting_medium-dark_skin_tone": "🙎🏾",
+1857	    "person_pouting_medium-light_skin_tone": "🙎🏼",
+1858	    "person_pouting_medium_skin_tone": "🙎🏽",
+1859	    "person_raising_hand": "🙋",
+1860	    "person_raising_hand_dark_skin_tone": "🙋🏿",
+1861	    "person_raising_hand_light_skin_tone": "🙋🏻",
+1862	    "person_raising_hand_medium-dark_skin_tone": "🙋🏾",
+1863	    "person_raising_hand_medium-light_skin_tone": "🙋🏼",
+1864	    "person_raising_hand_medium_skin_tone": "🙋🏽",
+1865	    "person_rowing_boat": "🚣",
+1866	    "person_rowing_boat_dark_skin_tone": "🚣🏿",
+1867	    "person_rowing_boat_light_skin_tone": "🚣🏻",
+1868	    "person_rowing_boat_medium-dark_skin_tone": "🚣🏾",
+1869	    "person_rowing_boat_medium-light_skin_tone": "🚣🏼",
+1870	    "person_rowing_boat_medium_skin_tone": "🚣🏽",
+1871	    "person_running": "🏃",
+1872	    "person_running_dark_skin_tone": "🏃🏿",
+1873	    "person_running_light_skin_tone": "🏃🏻",
+1874	    "person_running_medium-dark_skin_tone": "🏃🏾",
+1875	    "person_running_medium-light_skin_tone": "🏃🏼",
+1876	    "person_running_medium_skin_tone": "🏃🏽",
+1877	    "person_shrugging": "🤷",
+1878	    "person_shrugging_dark_skin_tone": "🤷🏿",
+1879	    "person_shrugging_light_skin_tone": "🤷🏻",
+1880	    "person_shrugging_medium-dark_skin_tone": "🤷🏾",
+1881	    "person_shrugging_medium-light_skin_tone": "🤷🏼",
+1882	    "person_shrugging_medium_skin_tone": "🤷🏽",
+1883	    "person_standing": "🧍",
+1884	    "person_surfing": "🏄",
+1885	    "person_surfing_dark_skin_tone": "🏄🏿",
+1886	    "person_surfing_light_skin_tone": "🏄🏻",
+1887	    "person_surfing_medium-dark_skin_tone": "🏄🏾",
+1888	    "person_surfing_medium-light_skin_tone": "🏄🏼",
+1889	    "person_surfing_medium_skin_tone": "🏄🏽",
+1890	    "person_swimming": "🏊",
+1891	    "person_swimming_dark_skin_tone": "🏊🏿",
+1892	    "person_swimming_light_skin_tone": "🏊🏻",
+1893	    "person_swimming_medium-dark_skin_tone": "🏊🏾",
+1894	    "person_swimming_medium-light_skin_tone": "🏊🏼",
+1895	    "person_swimming_medium_skin_tone": "🏊🏽",
+1896	    "person_taking_bath": "🛀",
+1897	    "person_taking_bath_dark_skin_tone": "🛀🏿",
+1898	    "person_taking_bath_light_skin_tone": "🛀🏻",
+1899	    "person_taking_bath_medium-dark_skin_tone": "🛀🏾",
+1900	    "person_taking_bath_medium-light_skin_tone": "🛀🏼",
+1901	    "person_taking_bath_medium_skin_tone": "🛀🏽",
+1902	    "person_tipping_hand": "💁",
+1903	    "person_tipping_hand_dark_skin_tone": "💁🏿",
+1904	    "person_tipping_hand_light_skin_tone": "💁🏻",
+1905	    "person_tipping_hand_medium-dark_skin_tone": "💁🏾",
+1906	    "person_tipping_hand_medium-light_skin_tone": "💁🏼",
+1907	    "person_tipping_hand_medium_skin_tone": "💁🏽",
+1908	    "person_walking": "🚶",
+1909	    "person_walking_dark_skin_tone": "🚶🏿",
+1910	    "person_walking_light_skin_tone": "🚶🏻",
+1911	    "person_walking_medium-dark_skin_tone": "🚶🏾",
+1912	    "person_walking_medium-light_skin_tone": "🚶🏼",
+1913	    "person_walking_medium_skin_tone": "🚶🏽",
+1914	    "person_wearing_turban": "👳",
+1915	    "person_wearing_turban_dark_skin_tone": "👳🏿",
+1916	    "person_wearing_turban_light_skin_tone": "👳🏻",
+1917	    "person_wearing_turban_medium-dark_skin_tone": "👳🏾",
+1918	    "person_wearing_turban_medium-light_skin_tone": "👳🏼",
+1919	    "person_wearing_turban_medium_skin_tone": "👳🏽",
+1920	    "petri_dish": "🧫",
+1921	    "pick": "⛏",
+1922	    "pie": "🥧",
+1923	    "pig": "🐷",
+1924	    "pig_face": "🐷",
+1925	    "pig_nose": "🐽",
+1926	    "pile_of_poo": "💩",
+1927	    "pill": "💊",
+1928	    "pinching_hand": "🤏",
+1929	    "pine_decoration": "🎍",
+1930	    "pineapple": "🍍",
+1931	    "ping_pong": "🏓",
+1932	    "pirate_flag": "🏴\u200d☠️",
+1933	    "pistol": "🔫",
+1934	    "pizza": "🍕",
+1935	    "place_of_worship": "🛐",
+1936	    "play_button": "▶",
+1937	    "play_or_pause_button": "⏯",
+1938	    "pleading_face": "🥺",
+1939	    "police_car": "🚓",
+1940	    "police_car_light": "🚨",
+1941	    "police_officer": "👮",
+1942	    "police_officer_dark_skin_tone": "👮🏿",
+1943	    "police_officer_light_skin_tone": "👮🏻",
+1944	    "police_officer_medium-dark_skin_tone": "👮🏾",
+1945	    "police_officer_medium-light_skin_tone": "👮🏼",
+1946	    "police_officer_medium_skin_tone": "👮🏽",
+1947	    "poodle": "🐩",
+1948	    "pool_8_ball": "🎱",
+1949	    "popcorn": "🍿",
+1950	    "post_office": "🏣",
+1951	    "postal_horn": "📯",
+1952	    "postbox": "📮",
+1953	    "pot_of_food": "🍲",
+1954	    "potable_water": "🚰",
+1955	    "potato": "🥔",
+1956	    "poultry_leg": "🍗",
+1957	    "pound_banknote": "💷",
+1958	    "pouting_cat_face": "😾",
+1959	    "pouting_face": "😡",
+1960	    "prayer_beads": "📿",
+1961	    "pregnant_woman": "🤰",
+1962	    "pregnant_woman_dark_skin_tone": "🤰🏿",
+1963	    "pregnant_woman_light_skin_tone": "🤰🏻",
+1964	    "pregnant_woman_medium-dark_skin_tone": "🤰🏾",
+1965	    "pregnant_woman_medium-light_skin_tone": "🤰🏼",
+1966	    "pregnant_woman_medium_skin_tone": "🤰🏽",
+1967	    "pretzel": "🥨",
+1968	    "probing_cane": "🦯",
+1969	    "prince": "🤴",
+1970	    "prince_dark_skin_tone": "🤴🏿",
+1971	    "prince_light_skin_tone": "🤴🏻",
+1972	    "prince_medium-dark_skin_tone": "🤴🏾",
+1973	    "prince_medium-light_skin_tone": "🤴🏼",
+1974	    "prince_medium_skin_tone": "🤴🏽",
+1975	    "princess": "👸",
+1976	    "princess_dark_skin_tone": "👸🏿",
+1977	    "princess_light_skin_tone": "👸🏻",
+1978	    "princess_medium-dark_skin_tone": "👸🏾",
+1979	    "princess_medium-light_skin_tone": "👸🏼",
+1980	    "princess_medium_skin_tone": "👸🏽",
+1981	    "printer": "🖨",
+1982	    "prohibited": "🚫",
+1983	    "purple_circle": "🟣",
+1984	    "purple_heart": "💜",
+1985	    "purple_square": "🟪",
+1986	    "purse": "👛",
+1987	    "pushpin": "📌",
+1988	    "question_mark": "❓",
+1989	    "rabbit": "🐰",
+1990	    "rabbit_face": "🐰",
+1991	    "raccoon": "🦝",
+1992	    "racing_car": "🏎",
+1993	    "radio": "📻",
+1994	    "radio_button": "🔘",
+1995	    "radioactive": "☢",
+1996	    "railway_car": "🚃",
+1997	    "railway_track": "🛤",
+1998	    "rainbow": "🌈",
+1999	    "rainbow_flag": "🏳️\u200d🌈",
+2000	    "raised_back_of_hand": "🤚",
+2001	    "raised_back_of_hand_dark_skin_tone": "🤚🏿",
+2002	    "raised_back_of_hand_light_skin_tone": "🤚🏻",
+2003	    "raised_back_of_hand_medium-dark_skin_tone": "🤚🏾",
+2004	    "raised_back_of_hand_medium-light_skin_tone": "🤚🏼",
+2005	    "raised_back_of_hand_medium_skin_tone": "🤚🏽",
+2006	    "raised_fist": "✊",
+2007	    "raised_fist_dark_skin_tone": "✊🏿",
+2008	    "raised_fist_light_skin_tone": "✊🏻",
+2009	    "raised_fist_medium-dark_skin_tone": "✊🏾",
+2010	    "raised_fist_medium-light_skin_tone": "✊🏼",
+2011	    "raised_fist_medium_skin_tone": "✊🏽",
+2012	    "raised_hand": "✋",
+2013	    "raised_hand_dark_skin_tone": "✋🏿",
+2014	    "raised_hand_light_skin_tone": "✋🏻",
+2015	    "raised_hand_medium-dark_skin_tone": "✋🏾",
+2016	    "raised_hand_medium-light_skin_tone": "✋🏼",
+2017	    "raised_hand_medium_skin_tone": "✋🏽",
+2018	    "raising_hands": "🙌",
+2019	    "raising_hands_dark_skin_tone": "🙌🏿",
+2020	    "raising_hands_light_skin_tone": "🙌🏻",
+2021	    "raising_hands_medium-dark_skin_tone": "🙌🏾",
+2022	    "raising_hands_medium-light_skin_tone": "🙌🏼",
+2023	    "raising_hands_medium_skin_tone": "🙌🏽",
+2024	    "ram": "🐏",
+2025	    "rat": "🐀",
+2026	    "razor": "🪒",
+2027	    "ringed_planet": "🪐",
+2028	    "receipt": "🧾",
+2029	    "record_button": "⏺",
+2030	    "recycling_symbol": "♻",
+2031	    "red_apple": "🍎",
+2032	    "red_circle": "🔴",
+2033	    "red_envelope": "🧧",
+2034	    "red_hair": "🦰",
+2035	    "red-haired_man": "👨\u200d🦰",
+2036	    "red-haired_woman": "👩\u200d🦰",
+2037	    "red_heart": "❤",
+2038	    "red_paper_lantern": "🏮",
+2039	    "red_square": "🟥",
+2040	    "red_triangle_pointed_down": "🔻",
+2041	    "red_triangle_pointed_up": "🔺",
+2042	    "registered": "®",
+2043	    "relieved_face": "😌",
+2044	    "reminder_ribbon": "🎗",
+2045	    "repeat_button": "🔁",
+2046	    "repeat_single_button": "🔂",
+2047	    "rescue_worker’s_helmet": "⛑",
+2048	    "restroom": "🚻",
+2049	    "reverse_button": "◀",
+2050	    "revolving_hearts": "💞",
+2051	    "rhinoceros": "🦏",
+2052	    "ribbon": "🎀",
+2053	    "rice_ball": "🍙",
+2054	    "rice_cracker": "🍘",
+2055	    "right-facing_fist": "🤜",
+2056	    "right-facing_fist_dark_skin_tone": "🤜🏿",
+2057	    "right-facing_fist_light_skin_tone": "🤜🏻",
+2058	    "right-facing_fist_medium-dark_skin_tone": "🤜🏾",
+2059	    "right-facing_fist_medium-light_skin_tone": "🤜🏼",
+2060	    "right-facing_fist_medium_skin_tone": "🤜🏽",
+2061	    "right_anger_bubble": "🗯",
+2062	    "right_arrow": "➡",
+2063	    "right_arrow_curving_down": "⤵",
+2064	    "right_arrow_curving_left": "↩",
+2065	    "right_arrow_curving_up": "⤴",
+2066	    "ring": "💍",
+2067	    "roasted_sweet_potato": "🍠",
+2068	    "robot_face": "🤖",
+2069	    "rocket": "🚀",
+2070	    "roll_of_paper": "🧻",
+2071	    "rolled-up_newspaper": "🗞",
+2072	    "roller_coaster": "🎢",
+2073	    "rolling_on_the_floor_laughing": "🤣",
+2074	    "rooster": "🐓",
+2075	    "rose": "🌹",
+2076	    "rosette": "🏵",
+2077	    "round_pushpin": "📍",
+2078	    "rugby_football": "🏉",
+2079	    "running_shirt": "🎽",
+2080	    "running_shoe": "👟",
+2081	    "sad_but_relieved_face": "😥",
+2082	    "safety_pin": "🧷",
+2083	    "safety_vest": "🦺",
+2084	    "salt": "🧂",
+2085	    "sailboat": "⛵",
+2086	    "sake": "🍶",
+2087	    "sandwich": "🥪",
+2088	    "sari": "🥻",
+2089	    "satellite": "📡",
+2090	    "satellite_antenna": "📡",
+2091	    "sauropod": "🦕",
+2092	    "saxophone": "🎷",
+2093	    "scarf": "🧣",
+2094	    "school": "🏫",
+2095	    "school_backpack": "🎒",
+2096	    "scissors": "✂",
+2097	    "scorpion": "🦂",
+2098	    "scroll": "📜",
+2099	    "seat": "💺",
+2100	    "see-no-evil_monkey": "🙈",
+2101	    "seedling": "🌱",
+2102	    "selfie": "🤳",
+2103	    "selfie_dark_skin_tone": "🤳🏿",
+2104	    "selfie_light_skin_tone": "🤳🏻",
+2105	    "selfie_medium-dark_skin_tone": "🤳🏾",
+2106	    "selfie_medium-light_skin_tone": "🤳🏼",
+2107	    "selfie_medium_skin_tone": "🤳🏽",
+2108	    "service_dog": "🐕\u200d🦺",
+2109	    "seven-thirty": "🕢",
+2110	    "seven_o’clock": "🕖",
+2111	    "shallow_pan_of_food": "🥘",
+2112	    "shamrock": "☘",
+2113	    "shark": "🦈",
+2114	    "shaved_ice": "🍧",
+2115	    "sheaf_of_rice": "🌾",
+2116	    "shield": "🛡",
+2117	    "shinto_shrine": "⛩",
+2118	    "ship": "🚢",
+2119	    "shooting_star": "🌠",
+2120	    "shopping_bags": "🛍",
+2121	    "shopping_cart": "🛒",
+2122	    "shortcake": "🍰",
+2123	    "shorts": "🩳",
+2124	    "shower": "🚿",
+2125	    "shrimp": "🦐",
+2126	    "shuffle_tracks_button": "🔀",
+2127	    "shushing_face": "🤫",
+2128	    "sign_of_the_horns": "🤘",
+2129	    "sign_of_the_horns_dark_skin_tone": "🤘🏿",
+2130	    "sign_of_the_horns_light_skin_tone": "🤘🏻",
+2131	    "sign_of_the_horns_medium-dark_skin_tone": "🤘🏾",
+2132	    "sign_of_the_horns_medium-light_skin_tone": "🤘🏼",
+2133	    "sign_of_the_horns_medium_skin_tone": "🤘🏽",
+2134	    "six-thirty": "🕡",
+2135	    "six_o’clock": "🕕",
+2136	    "skateboard": "🛹",
+2137	    "skier": "⛷",
+2138	    "skis": "🎿",
+2139	    "skull": "💀",
+2140	    "skull_and_crossbones": "☠",
+2141	    "skunk": "🦨",
+2142	    "sled": "🛷",
+2143	    "sleeping_face": "😴",
+2144	    "sleepy_face": "😪",
+2145	    "slightly_frowning_face": "🙁",
+2146	    "slightly_smiling_face": "🙂",
+2147	    "slot_machine": "🎰",
+2148	    "sloth": "🦥",
+2149	    "small_airplane": "🛩",
+2150	    "small_blue_diamond": "🔹",
+2151	    "small_orange_diamond": "🔸",
+2152	    "smiling_cat_face_with_heart-eyes": "😻",
+2153	    "smiling_face": "☺",
+2154	    "smiling_face_with_halo": "😇",
+2155	    "smiling_face_with_3_hearts": "🥰",
+2156	    "smiling_face_with_heart-eyes": "😍",
+2157	    "smiling_face_with_horns": "😈",
+2158	    "smiling_face_with_smiling_eyes": "😊",
+2159	    "smiling_face_with_sunglasses": "😎",
+2160	    "smirking_face": "😏",
+2161	    "snail": "🐌",
+2162	    "snake": "🐍",
+2163	    "sneezing_face": "🤧",
+2164	    "snow-capped_mountain": "🏔",
+2165	    "snowboarder": "🏂",
+2166	    "snowboarder_dark_skin_tone": "🏂🏿",
+2167	    "snowboarder_light_skin_tone": "🏂🏻",
+2168	    "snowboarder_medium-dark_skin_tone": "🏂🏾",
+2169	    "snowboarder_medium-light_skin_tone": "🏂🏼",
+2170	    "snowboarder_medium_skin_tone": "🏂🏽",
+2171	    "snowflake": "❄",
+2172	    "snowman": "☃",
+2173	    "snowman_without_snow": "⛄",
+2174	    "soap": "🧼",
+2175	    "soccer_ball": "⚽",
+2176	    "socks": "🧦",
+2177	    "softball": "🥎",
+2178	    "soft_ice_cream": "🍦",
+2179	    "spade_suit": "♠",
+2180	    "spaghetti": "🍝",
+2181	    "sparkle": "❇",
+2182	    "sparkler": "🎇",
+2183	    "sparkles": "✨",
+2184	    "sparkling_heart": "💖",
+2185	    "speak-no-evil_monkey": "🙊",
+2186	    "speaker_high_volume": "🔊",
+2187	    "speaker_low_volume": "🔈",
+2188	    "speaker_medium_volume": "🔉",
+2189	    "speaking_head": "🗣",
+2190	    "speech_balloon": "💬",
+2191	    "speedboat": "🚤",
+2192	    "spider": "🕷",
+2193	    "spider_web": "🕸",
+2194	    "spiral_calendar": "🗓",
+2195	    "spiral_notepad": "🗒",
+2196	    "spiral_shell": "🐚",
+2197	    "spoon": "🥄",
+2198	    "sponge": "🧽",
+2199	    "sport_utility_vehicle": "🚙",
+2200	    "sports_medal": "🏅",
+2201	    "spouting_whale": "🐳",
+2202	    "squid": "🦑",
+2203	    "squinting_face_with_tongue": "😝",
+2204	    "stadium": "🏟",
+2205	    "star-struck": "🤩",
+2206	    "star_and_crescent": "☪",
+2207	    "star_of_david": "✡",
+2208	    "station": "🚉",
+2209	    "steaming_bowl": "🍜",
+2210	    "stethoscope": "🩺",
+2211	    "stop_button": "⏹",
+2212	    "stop_sign": "🛑",
+2213	    "stopwatch": "⏱",
+2214	    "straight_ruler": "📏",
+2215	    "strawberry": "🍓",
+2216	    "studio_microphone": "🎙",
+2217	    "stuffed_flatbread": "🥙",
+2218	    "sun": "☀",
+2219	    "sun_behind_cloud": "⛅",
+2220	    "sun_behind_large_cloud": "🌥",
+2221	    "sun_behind_rain_cloud": "🌦",
+2222	    "sun_behind_small_cloud": "🌤",
+2223	    "sun_with_face": "🌞",
+2224	    "sunflower": "🌻",
+2225	    "sunglasses": "😎",
+2226	    "sunrise": "🌅",
+2227	    "sunrise_over_mountains": "🌄",
+2228	    "sunset": "🌇",
+2229	    "superhero": "🦸",
+2230	    "supervillain": "🦹",
+2231	    "sushi": "🍣",
+2232	    "suspension_railway": "🚟",
+2233	    "swan": "🦢",
+2234	    "sweat_droplets": "💦",
+2235	    "synagogue": "🕍",
+2236	    "syringe": "💉",
+2237	    "t-shirt": "👕",
+2238	    "taco": "🌮",
+2239	    "takeout_box": "🥡",
+2240	    "tanabata_tree": "🎋",
+2241	    "tangerine": "🍊",
+2242	    "taxi": "🚕",
+2243	    "teacup_without_handle": "🍵",
+2244	    "tear-off_calendar": "📆",
+2245	    "teddy_bear": "🧸",
+2246	    "telephone": "☎",
+2247	    "telephone_receiver": "📞",
+2248	    "telescope": "🔭",
+2249	    "television": "📺",
+2250	    "ten-thirty": "🕥",
+2251	    "ten_o’clock": "🕙",
+2252	    "tennis": "🎾",
+2253	    "tent": "⛺",
+2254	    "test_tube": "🧪",
+2255	    "thermometer": "🌡",
+2256	    "thinking_face": "🤔",
+2257	    "thought_balloon": "💭",
+2258	    "thread": "🧵",
+2259	    "three-thirty": "🕞",
+2260	    "three_o’clock": "🕒",
+2261	    "thumbs_down": "👎",
+2262	    "thumbs_down_dark_skin_tone": "👎🏿",
+2263	    "thumbs_down_light_skin_tone": "👎🏻",
+2264	    "thumbs_down_medium-dark_skin_tone": "👎🏾",
+2265	    "thumbs_down_medium-light_skin_tone": "👎🏼",
+2266	    "thumbs_down_medium_skin_tone": "👎🏽",
+2267	    "thumbs_up": "👍",
+2268	    "thumbs_up_dark_skin_tone": "👍🏿",
+2269	    "thumbs_up_light_skin_tone": "👍🏻",
+2270	    "thumbs_up_medium-dark_skin_tone": "👍🏾",
+2271	    "thumbs_up_medium-light_skin_tone": "👍🏼",
+2272	    "thumbs_up_medium_skin_tone": "👍🏽",
+2273	    "ticket": "🎫",
+2274	    "tiger": "🐯",
+2275	    "tiger_face": "🐯",
+2276	    "timer_clock": "⏲",
+2277	    "tired_face": "😫",
+2278	    "toolbox": "🧰",
+2279	    "toilet": "🚽",
+2280	    "tomato": "🍅",
+2281	    "tongue": "👅",
+2282	    "tooth": "🦷",
+2283	    "top_hat": "🎩",
+2284	    "tornado": "🌪",
+2285	    "trackball": "🖲",
+2286	    "tractor": "🚜",
+2287	    "trade_mark": "™",
+2288	    "train": "🚋",
+2289	    "tram": "🚊",
+2290	    "tram_car": "🚋",
+2291	    "triangular_flag": "🚩",
+2292	    "triangular_ruler": "📐",
+2293	    "trident_emblem": "🔱",
+2294	    "trolleybus": "🚎",
+2295	    "trophy": "🏆",
+2296	    "tropical_drink": "🍹",
+2297	    "tropical_fish": "🐠",
+2298	    "trumpet": "🎺",
+2299	    "tulip": "🌷",
+2300	    "tumbler_glass": "🥃",
+2301	    "turtle": "🐢",
+2302	    "twelve-thirty": "🕧",
+2303	    "twelve_o’clock": "🕛",
+2304	    "two-hump_camel": "🐫",
+2305	    "two-thirty": "🕝",
+2306	    "two_hearts": "💕",
+2307	    "two_men_holding_hands": "👬",
+2308	    "two_o’clock": "🕑",
+2309	    "two_women_holding_hands": "👭",
+2310	    "umbrella": "☂",
+2311	    "umbrella_on_ground": "⛱",
+2312	    "umbrella_with_rain_drops": "☔",
+2313	    "unamused_face": "😒",
+2314	    "unicorn_face": "🦄",
+2315	    "unlocked": "🔓",
+2316	    "up-down_arrow": "↕",
+2317	    "up-left_arrow": "↖",
+2318	    "up-right_arrow": "↗",
+2319	    "up_arrow": "⬆",
+2320	    "upside-down_face": "🙃",
+2321	    "upwards_button": "🔼",
+2322	    "vampire": "🧛",
+2323	    "vampire_dark_skin_tone": "🧛🏿",
+2324	    "vampire_light_skin_tone": "🧛🏻",
+2325	    "vampire_medium-dark_skin_tone": "🧛🏾",
+2326	    "vampire_medium-light_skin_tone": "🧛🏼",
+2327	    "vampire_medium_skin_tone": "🧛🏽",
+2328	    "vertical_traffic_light": "🚦",
+2329	    "vibration_mode": "📳",
+2330	    "victory_hand": "✌",
+2331	    "victory_hand_dark_skin_tone": "✌🏿",
+2332	    "victory_hand_light_skin_tone": "✌🏻",
+2333	    "victory_hand_medium-dark_skin_tone": "✌🏾",
+2334	    "victory_hand_medium-light_skin_tone": "✌🏼",
+2335	    "victory_hand_medium_skin_tone": "✌🏽",
+2336	    "video_camera": "📹",
+2337	    "video_game": "🎮",
+2338	    "videocassette": "📼",
+2339	    "violin": "🎻",
+2340	    "volcano": "🌋",
+2341	    "volleyball": "🏐",
+2342	    "vulcan_salute": "🖖",
+2343	    "vulcan_salute_dark_skin_tone": "🖖🏿",
+2344	    "vulcan_salute_light_skin_tone": "🖖🏻",
+2345	    "vulcan_salute_medium-dark_skin_tone": "🖖🏾",
+2346	    "vulcan_salute_medium-light_skin_tone": "🖖🏼",
+2347	    "vulcan_salute_medium_skin_tone": "🖖🏽",
+2348	    "waffle": "🧇",
+2349	    "waning_crescent_moon": "🌘",
+2350	    "waning_gibbous_moon": "🌖",
+2351	    "warning": "⚠",
+2352	    "wastebasket": "🗑",
+2353	    "watch": "⌚",
+2354	    "water_buffalo": "🐃",
+2355	    "water_closet": "🚾",
+2356	    "water_wave": "🌊",
+2357	    "watermelon": "🍉",
+2358	    "waving_hand": "👋",
+2359	    "waving_hand_dark_skin_tone": "👋🏿",
+2360	    "waving_hand_light_skin_tone": "👋🏻",
+2361	    "waving_hand_medium-dark_skin_tone": "👋🏾",
+2362	    "waving_hand_medium-light_skin_tone": "👋🏼",
+2363	    "waving_hand_medium_skin_tone": "👋🏽",
+2364	    "wavy_dash": "〰",
+2365	    "waxing_crescent_moon": "🌒",
+2366	    "waxing_gibbous_moon": "🌔",
+2367	    "weary_cat_face": "🙀",
+2368	    "weary_face": "😩",
+2369	    "wedding": "💒",
+2370	    "whale": "🐳",
+2371	    "wheel_of_dharma": "☸",
+2372	    "wheelchair_symbol": "♿",
+2373	    "white_circle": "⚪",
+2374	    "white_exclamation_mark": "❕",
+2375	    "white_flag": "🏳",
+2376	    "white_flower": "💮",
+2377	    "white_hair": "🦳",
+2378	    "white-haired_man": "👨\u200d🦳",
+2379	    "white-haired_woman": "👩\u200d🦳",
+2380	    "white_heart": "🤍",
+2381	    "white_heavy_check_mark": "✅",
+2382	    "white_large_square": "⬜",
+2383	    "white_medium-small_square": "◽",
+2384	    "white_medium_square": "◻",
+2385	    "white_medium_star": "⭐",
+2386	    "white_question_mark": "❔",
+2387	    "white_small_square": "▫",
+2388	    "white_square_button": "🔳",
+2389	    "wilted_flower": "🥀",
+2390	    "wind_chime": "🎐",
+2391	    "wind_face": "🌬",
+2392	    "wine_glass": "🍷",
+2393	    "winking_face": "😉",
+2394	    "winking_face_with_tongue": "😜",
+2395	    "wolf_face": "🐺",
+2396	    "woman": "👩",
+2397	    "woman_artist": "👩\u200d🎨",
+2398	    "woman_artist_dark_skin_tone": "👩🏿\u200d🎨",
+2399	    "woman_artist_light_skin_tone": "👩🏻\u200d🎨",
+2400	    "woman_artist_medium-dark_skin_tone": "👩🏾\u200d🎨",
+2401	    "woman_artist_medium-light_skin_tone": "👩🏼\u200d🎨",
+2402	    "woman_artist_medium_skin_tone": "👩🏽\u200d🎨",
+2403	    "woman_astronaut": "👩\u200d🚀",
+2404	    "woman_astronaut_dark_skin_tone": "👩🏿\u200d🚀",
+2405	    "woman_astronaut_light_skin_tone": "👩🏻\u200d🚀",
+2406	    "woman_astronaut_medium-dark_skin_tone": "👩🏾\u200d🚀",
+2407	    "woman_astronaut_medium-light_skin_tone": "👩🏼\u200d🚀",
+2408	    "woman_astronaut_medium_skin_tone": "👩🏽\u200d🚀",
+2409	    "woman_biking": "🚴\u200d♀️",
+2410	    "woman_biking_dark_skin_tone": "🚴🏿\u200d♀️",
+2411	    "woman_biking_light_skin_tone": "🚴🏻\u200d♀️",
+2412	    "woman_biking_medium-dark_skin_tone": "🚴🏾\u200d♀️",
+2413	    "woman_biking_medium-light_skin_tone": "🚴🏼\u200d♀️",
+2414	    "woman_biking_medium_skin_tone": "🚴🏽\u200d♀️",
+2415	    "woman_bouncing_ball": "⛹️\u200d♀️",
+2416	    "woman_bouncing_ball_dark_skin_tone": "⛹🏿\u200d♀️",
+2417	    "woman_bouncing_ball_light_skin_tone": "⛹🏻\u200d♀️",
+2418	    "woman_bouncing_ball_medium-dark_skin_tone": "⛹🏾\u200d♀️",
+2419	    "woman_bouncing_ball_medium-light_skin_tone": "⛹🏼\u200d♀️",
+2420	    "woman_bouncing_ball_medium_skin_tone": "⛹🏽\u200d♀️",
+2421	    "woman_bowing": "🙇\u200d♀️",
+2422	    "woman_bowing_dark_skin_tone": "🙇🏿\u200d♀️",
+2423	    "woman_bowing_light_skin_tone": "🙇🏻\u200d♀️",
+2424	    "woman_bowing_medium-dark_skin_tone": "🙇🏾\u200d♀️",
+2425	    "woman_bowing_medium-light_skin_tone": "🙇🏼\u200d♀️",
+2426	    "woman_bowing_medium_skin_tone": "🙇🏽\u200d♀️",
+2427	    "woman_cartwheeling": "🤸\u200d♀️",
+2428	    "woman_cartwheeling_dark_skin_tone": "🤸🏿\u200d♀️",
+2429	    "woman_cartwheeling_light_skin_tone": "🤸🏻\u200d♀️",
+2430	    "woman_cartwheeling_medium-dark_skin_tone": "🤸🏾\u200d♀️",
+2431	    "woman_cartwheeling_medium-light_skin_tone": "🤸🏼\u200d♀️",
+2432	    "woman_cartwheeling_medium_skin_tone": "🤸🏽\u200d♀️",
+2433	    "woman_climbing": "🧗\u200d♀️",
+2434	    "woman_climbing_dark_skin_tone": "🧗🏿\u200d♀️",
+2435	    "woman_climbing_light_skin_tone": "🧗🏻\u200d♀️",
+2436	    "woman_climbing_medium-dark_skin_tone": "🧗🏾\u200d♀️",
+2437	    "woman_climbing_medium-light_skin_tone": "🧗🏼\u200d♀️",
+2438	    "woman_climbing_medium_skin_tone": "🧗🏽\u200d♀️",
+2439	    "woman_construction_worker": "👷\u200d♀️",
+2440	    "woman_construction_worker_dark_skin_tone": "👷🏿\u200d♀️",
+2441	    "woman_construction_worker_light_skin_tone": "👷🏻\u200d♀️",
+2442	    "woman_construction_worker_medium-dark_skin_tone": "👷🏾\u200d♀️",
+2443	    "woman_construction_worker_medium-light_skin_tone": "👷🏼\u200d♀️",
+2444	    "woman_construction_worker_medium_skin_tone": "👷🏽\u200d♀️",
+2445	    "woman_cook": "👩\u200d🍳",
+2446	    "woman_cook_dark_skin_tone": "👩🏿\u200d🍳",
+2447	    "woman_cook_light_skin_tone": "👩🏻\u200d🍳",
+2448	    "woman_cook_medium-dark_skin_tone": "👩🏾\u200d🍳",
+2449	    "woman_cook_medium-light_skin_tone": "👩🏼\u200d🍳",
+2450	    "woman_cook_medium_skin_tone": "👩🏽\u200d🍳",
+2451	    "woman_dancing": "💃",
+2452	    "woman_dancing_dark_skin_tone": "💃🏿",
+2453	    "woman_dancing_light_skin_tone": "💃🏻",
+2454	    "woman_dancing_medium-dark_skin_tone": "💃🏾",
+2455	    "woman_dancing_medium-light_skin_tone": "💃🏼",
+2456	    "woman_dancing_medium_skin_tone": "💃🏽",
+2457	    "woman_dark_skin_tone": "👩🏿",
+2458	    "woman_detective": "🕵️\u200d♀️",
+2459	    "woman_detective_dark_skin_tone": "🕵🏿\u200d♀️",
+2460	    "woman_detective_light_skin_tone": "🕵🏻\u200d♀️",
+2461	    "woman_detective_medium-dark_skin_tone": "🕵🏾\u200d♀️",
+2462	    "woman_detective_medium-light_skin_tone": "🕵🏼\u200d♀️",
+2463	    "woman_detective_medium_skin_tone": "🕵🏽\u200d♀️",
+2464	    "woman_elf": "🧝\u200d♀️",
+2465	    "woman_elf_dark_skin_tone": "🧝🏿\u200d♀️",
+2466	    "woman_elf_light_skin_tone": "🧝🏻\u200d♀️",
+2467	    "woman_elf_medium-dark_skin_tone": "🧝🏾\u200d♀️",
+2468	    "woman_elf_medium-light_skin_tone": "🧝🏼\u200d♀️",
+2469	    "woman_elf_medium_skin_tone": "🧝🏽\u200d♀️",
+2470	    "woman_facepalming": "🤦\u200d♀️",
+2471	    "woman_facepalming_dark_skin_tone": "🤦🏿\u200d♀️",
+2472	    "woman_facepalming_light_skin_tone": "🤦🏻\u200d♀️",
+2473	    "woman_facepalming_medium-dark_skin_tone": "🤦🏾\u200d♀️",
+2474	    "woman_facepalming_medium-light_skin_tone": "🤦🏼\u200d♀️",
+2475	    "woman_facepalming_medium_skin_tone": "🤦🏽\u200d♀️",
+2476	    "woman_factory_worker": "👩\u200d🏭",
+2477	    "woman_factory_worker_dark_skin_tone": "👩🏿\u200d🏭",
+2478	    "woman_factory_worker_light_skin_tone": "👩🏻\u200d🏭",
+2479	    "woman_factory_worker_medium-dark_skin_tone": "👩🏾\u200d🏭",
+2480	    "woman_factory_worker_medium-light_skin_tone": "👩🏼\u200d🏭",
+2481	    "woman_factory_worker_medium_skin_tone": "👩🏽\u200d🏭",
+2482	    "woman_fairy": "🧚\u200d♀️",
+2483	    "woman_fairy_dark_skin_tone": "🧚🏿\u200d♀️",
+2484	    "woman_fairy_light_skin_tone": "🧚🏻\u200d♀️",
+2485	    "woman_fairy_medium-dark_skin_tone": "🧚🏾\u200d♀️",
+2486	    "woman_fairy_medium-light_skin_tone": "🧚🏼\u200d♀️",
+2487	    "woman_fairy_medium_skin_tone": "🧚🏽\u200d♀️",
+2488	    "woman_farmer": "👩\u200d🌾",
+2489	    "woman_farmer_dark_skin_tone": "👩🏿\u200d🌾",
+2490	    "woman_farmer_light_skin_tone": "👩🏻\u200d🌾",
+2491	    "woman_farmer_medium-dark_skin_tone": "👩🏾\u200d🌾",
+2492	    "woman_farmer_medium-light_skin_tone": "👩🏼\u200d🌾",
+2493	    "woman_farmer_medium_skin_tone": "👩🏽\u200d🌾",
+2494	    "woman_firefighter": "👩\u200d🚒",
+2495	    "woman_firefighter_dark_skin_tone": "👩🏿\u200d🚒",
+2496	    "woman_firefighter_light_skin_tone": "👩🏻\u200d🚒",
+2497	    "woman_firefighter_medium-dark_skin_tone": "👩🏾\u200d🚒",
+2498	    "woman_firefighter_medium-light_skin_tone": "👩🏼\u200d🚒",
+2499	    "woman_firefighter_medium_skin_tone": "👩🏽\u200d🚒",
+2500	    "woman_frowning": "🙍\u200d♀️",
+2501	    "woman_frowning_dark_skin_tone": "🙍🏿\u200d♀️",
+2502	    "woman_frowning_light_skin_tone": "🙍🏻\u200d♀️",
+2503	    "woman_frowning_medium-dark_skin_tone": "🙍🏾\u200d♀️",
+2504	    "woman_frowning_medium-light_skin_tone": "🙍🏼\u200d♀️",
+2505	    "woman_frowning_medium_skin_tone": "🙍🏽\u200d♀️",
+2506	    "woman_genie": "🧞\u200d♀️",
+2507	    "woman_gesturing_no": "🙅\u200d♀️",
+2508	    "woman_gesturing_no_dark_skin_tone": "🙅🏿\u200d♀️",
+2509	    "woman_gesturing_no_light_skin_tone": "🙅🏻\u200d♀️",
+2510	    "woman_gesturing_no_medium-dark_skin_tone": "🙅🏾\u200d♀️",
+2511	    "woman_gesturing_no_medium-light_skin_tone": "🙅🏼\u200d♀️",
+2512	    "woman_gesturing_no_medium_skin_tone": "🙅🏽\u200d♀️",
+2513	    "woman_gesturing_ok": "🙆\u200d♀️",
+2514	    "woman_gesturing_ok_dark_skin_tone": "🙆🏿\u200d♀️",
+2515	    "woman_gesturing_ok_light_skin_tone": "🙆🏻\u200d♀️",
+2516	    "woman_gesturing_ok_medium-dark_skin_tone": "🙆🏾\u200d♀️",
+2517	    "woman_gesturing_ok_medium-light_skin_tone": "🙆🏼\u200d♀️",
+2518	    "woman_gesturing_ok_medium_skin_tone": "🙆🏽\u200d♀️",
+2519	    "woman_getting_haircut": "💇\u200d♀️",
+2520	    "woman_getting_haircut_dark_skin_tone": "💇🏿\u200d♀️",
+2521	    "woman_getting_haircut_light_skin_tone": "💇🏻\u200d♀️",
+2522	    "woman_getting_haircut_medium-dark_skin_tone": "💇🏾\u200d♀️",
+2523	    "woman_getting_haircut_medium-light_skin_tone": "💇🏼\u200d♀️",
+2524	    "woman_getting_haircut_medium_skin_tone": "💇🏽\u200d♀️",
+2525	    "woman_getting_massage": "💆\u200d♀️",
+2526	    "woman_getting_massage_dark_skin_tone": "💆🏿\u200d♀️",
+2527	    "woman_getting_massage_light_skin_tone": "💆🏻\u200d♀️",
+2528	    "woman_getting_massage_medium-dark_skin_tone": "💆🏾\u200d♀️",
+2529	    "woman_getting_massage_medium-light_skin_tone": "💆🏼\u200d♀️",
+2530	    "woman_getting_massage_medium_skin_tone": "💆🏽\u200d♀️",
+2531	    "woman_golfing": "🏌️\u200d♀️",
+2532	    "woman_golfing_dark_skin_tone": "🏌🏿\u200d♀️",
+2533	    "woman_golfing_light_skin_tone": "🏌🏻\u200d♀️",
+2534	    "woman_golfing_medium-dark_skin_tone": "🏌🏾\u200d♀️",
+2535	    "woman_golfing_medium-light_skin_tone": "🏌🏼\u200d♀️",
+2536	    "woman_golfing_medium_skin_tone": "🏌🏽\u200d♀️",
+2537	    "woman_guard": "💂\u200d♀️",
+2538	    "woman_guard_dark_skin_tone": "💂🏿\u200d♀️",
+2539	    "woman_guard_light_skin_tone": "💂🏻\u200d♀️",
+2540	    "woman_guard_medium-dark_skin_tone": "💂🏾\u200d♀️",
+2541	    "woman_guard_medium-light_skin_tone": "💂🏼\u200d♀️",
+2542	    "woman_guard_medium_skin_tone": "💂🏽\u200d♀️",
+2543	    "woman_health_worker": "👩\u200d⚕️",
+2544	    "woman_health_worker_dark_skin_tone": "👩🏿\u200d⚕️",
+2545	    "woman_health_worker_light_skin_tone": "👩🏻\u200d⚕️",
+2546	    "woman_health_worker_medium-dark_skin_tone": "👩🏾\u200d⚕️",
+2547	    "woman_health_worker_medium-light_skin_tone": "👩🏼\u200d⚕️",
+2548	    "woman_health_worker_medium_skin_tone": "👩🏽\u200d⚕️",
+2549	    "woman_in_lotus_position": "🧘\u200d♀️",
+2550	    "woman_in_lotus_position_dark_skin_tone": "🧘🏿\u200d♀️",
+2551	    "woman_in_lotus_position_light_skin_tone": "🧘🏻\u200d♀️",
+2552	    "woman_in_lotus_position_medium-dark_skin_tone": "🧘🏾\u200d♀️",
+2553	    "woman_in_lotus_position_medium-light_skin_tone": "🧘🏼\u200d♀️",
+2554	    "woman_in_lotus_position_medium_skin_tone": "🧘🏽\u200d♀️",
+2555	    "woman_in_manual_wheelchair": "👩\u200d🦽",
+2556	    "woman_in_motorized_wheelchair": "👩\u200d🦼",
+2557	    "woman_in_steamy_room": "🧖\u200d♀️",
+2558	    "woman_in_steamy_room_dark_skin_tone": "🧖🏿\u200d♀️",
+2559	    "woman_in_steamy_room_light_skin_tone": "🧖🏻\u200d♀️",
+2560	    "woman_in_steamy_room_medium-dark_skin_tone": "🧖🏾\u200d♀️",
+2561	    "woman_in_steamy_room_medium-light_skin_tone": "🧖🏼\u200d♀️",
+2562	    "woman_in_steamy_room_medium_skin_tone": "🧖🏽\u200d♀️",
+2563	    "woman_judge": "👩\u200d⚖️",
+2564	    "woman_judge_dark_skin_tone": "👩🏿\u200d⚖️",
+2565	    "woman_judge_light_skin_tone": "👩🏻\u200d⚖️",
+2566	    "woman_judge_medium-dark_skin_tone": "👩🏾\u200d⚖️",
+2567	    "woman_judge_medium-light_skin_tone": "👩🏼\u200d⚖️",
+2568	    "woman_judge_medium_skin_tone": "👩🏽\u200d⚖️",
+2569	    "woman_juggling": "🤹\u200d♀️",
+2570	    "woman_juggling_dark_skin_tone": "🤹🏿\u200d♀️",
+2571	    "woman_juggling_light_skin_tone": "🤹🏻\u200d♀️",
+2572	    "woman_juggling_medium-dark_skin_tone": "🤹🏾\u200d♀️",
+2573	    "woman_juggling_medium-light_skin_tone": "🤹🏼\u200d♀️",
+2574	    "woman_juggling_medium_skin_tone": "🤹🏽\u200d♀️",
+2575	    "woman_lifting_weights": "🏋️\u200d♀️",
+2576	    "woman_lifting_weights_dark_skin_tone": "🏋🏿\u200d♀️",
+2577	    "woman_lifting_weights_light_skin_tone": "🏋🏻\u200d♀️",
+2578	    "woman_lifting_weights_medium-dark_skin_tone": "🏋🏾\u200d♀️",
+2579	    "woman_lifting_weights_medium-light_skin_tone": "🏋🏼\u200d♀️",
+2580	    "woman_lifting_weights_medium_skin_tone": "🏋🏽\u200d♀️",
+2581	    "woman_light_skin_tone": "👩🏻",
+2582	    "woman_mage": "🧙\u200d♀️",
+2583	    "woman_mage_dark_skin_tone": "🧙🏿\u200d♀️",
+2584	    "woman_mage_light_skin_tone": "🧙🏻\u200d♀️",
+2585	    "woman_mage_medium-dark_skin_tone": "🧙🏾\u200d♀️",
+2586	    "woman_mage_medium-light_skin_tone": "🧙🏼\u200d♀️",
+2587	    "woman_mage_medium_skin_tone": "🧙🏽\u200d♀️",
+2588	    "woman_mechanic": "👩\u200d🔧",
+2589	    "woman_mechanic_dark_skin_tone": "👩🏿\u200d🔧",
+2590	    "woman_mechanic_light_skin_tone": "👩🏻\u200d🔧",
+2591	    "woman_mechanic_medium-dark_skin_tone": "👩🏾\u200d🔧",
+2592	    "woman_mechanic_medium-light_skin_tone": "👩🏼\u200d🔧",
+2593	    "woman_mechanic_medium_skin_tone": "👩🏽\u200d🔧",
+2594	    "woman_medium-dark_skin_tone": "👩🏾",
+2595	    "woman_medium-light_skin_tone": "👩🏼",
+2596	    "woman_medium_skin_tone": "👩🏽",
+2597	    "woman_mountain_biking": "🚵\u200d♀️",
+2598	    "woman_mountain_biking_dark_skin_tone": "🚵🏿\u200d♀️",
+2599	    "woman_mountain_biking_light_skin_tone": "🚵🏻\u200d♀️",
+2600	    "woman_mountain_biking_medium-dark_skin_tone": "🚵🏾\u200d♀️",
+2601	    "woman_mountain_biking_medium-light_skin_tone": "🚵🏼\u200d♀️",
+2602	    "woman_mountain_biking_medium_skin_tone": "🚵🏽\u200d♀️",
+2603	    "woman_office_worker": "👩\u200d💼",
+2604	    "woman_office_worker_dark_skin_tone": "👩🏿\u200d💼",
+2605	    "woman_office_worker_light_skin_tone": "👩🏻\u200d💼",
+2606	    "woman_office_worker_medium-dark_skin_tone": "👩🏾\u200d💼",
+2607	    "woman_office_worker_medium-light_skin_tone": "👩🏼\u200d💼",
+2608	    "woman_office_worker_medium_skin_tone": "👩🏽\u200d💼",
+2609	    "woman_pilot": "👩\u200d✈️",
+2610	    "woman_pilot_dark_skin_tone": "👩🏿\u200d✈️",
+2611	    "woman_pilot_light_skin_tone": "👩🏻\u200d✈️",
+2612	    "woman_pilot_medium-dark_skin_tone": "👩🏾\u200d✈️",
+2613	    "woman_pilot_medium-light_skin_tone": "👩🏼\u200d✈️",
+2614	    "woman_pilot_medium_skin_tone": "👩🏽\u200d✈️",
+2615	    "woman_playing_handball": "🤾\u200d♀️",
+2616	    "woman_playing_handball_dark_skin_tone": "🤾🏿\u200d♀️",
+2617	    "woman_playing_handball_light_skin_tone": "🤾🏻\u200d♀️",
+2618	    "woman_playing_handball_medium-dark_skin_tone": "🤾🏾\u200d♀️",
+2619	    "woman_playing_handball_medium-light_skin_tone": "🤾🏼\u200d♀️",
+2620	    "woman_playing_handball_medium_skin_tone": "🤾🏽\u200d♀️",
+2621	    "woman_playing_water_polo": "🤽\u200d♀️",
+2622	    "woman_playing_water_polo_dark_skin_tone": "🤽🏿\u200d♀️",
+2623	    "woman_playing_water_polo_light_skin_tone": "🤽🏻\u200d♀️",
+2624	    "woman_playing_water_polo_medium-dark_skin_tone": "🤽🏾\u200d♀️",
+2625	    "woman_playing_water_polo_medium-light_skin_tone": "🤽🏼\u200d♀️",
+2626	    "woman_playing_water_polo_medium_skin_tone": "🤽🏽\u200d♀️",
+2627	    "woman_police_officer": "👮\u200d♀️",
+2628	    "woman_police_officer_dark_skin_tone": "👮🏿\u200d♀️",
+2629	    "woman_police_officer_light_skin_tone": "👮🏻\u200d♀️",
+2630	    "woman_police_officer_medium-dark_skin_tone": "👮🏾\u200d♀️",
+2631	    "woman_police_officer_medium-light_skin_tone": "👮🏼\u200d♀️",
+2632	    "woman_police_officer_medium_skin_tone": "👮🏽\u200d♀️",
+2633	    "woman_pouting": "🙎\u200d♀️",
+2634	    "woman_pouting_dark_skin_tone": "🙎🏿\u200d♀️",
+2635	    "woman_pouting_light_skin_tone": "🙎🏻\u200d♀️",
+2636	    "woman_pouting_medium-dark_skin_tone": "🙎🏾\u200d♀️",
+2637	    "woman_pouting_medium-light_skin_tone": "🙎🏼\u200d♀️",
+2638	    "woman_pouting_medium_skin_tone": "🙎🏽\u200d♀️",
+2639	    "woman_raising_hand": "🙋\u200d♀️",
+2640	    "woman_raising_hand_dark_skin_tone": "🙋🏿\u200d♀️",
+2641	    "woman_raising_hand_light_skin_tone": "🙋🏻\u200d♀️",
+2642	    "woman_raising_hand_medium-dark_skin_tone": "🙋🏾\u200d♀️",
+2643	    "woman_raising_hand_medium-light_skin_tone": "🙋🏼\u200d♀️",
+2644	    "woman_raising_hand_medium_skin_tone": "🙋🏽\u200d♀️",
+2645	    "woman_rowing_boat": "🚣\u200d♀️",
+2646	    "woman_rowing_boat_dark_skin_tone": "🚣🏿\u200d♀️",
+2647	    "woman_rowing_boat_light_skin_tone": "🚣🏻\u200d♀️",
+2648	    "woman_rowing_boat_medium-dark_skin_tone": "🚣🏾\u200d♀️",
+2649	    "woman_rowing_boat_medium-light_skin_tone": "🚣🏼\u200d♀️",
+2650	    "woman_rowing_boat_medium_skin_tone": "🚣🏽\u200d♀️",
+2651	    "woman_running": "🏃\u200d♀️",
+2652	    "woman_running_dark_skin_tone": "🏃🏿\u200d♀️",
+2653	    "woman_running_light_skin_tone": "🏃🏻\u200d♀️",
+2654	    "woman_running_medium-dark_skin_tone": "🏃🏾\u200d♀️",
+2655	    "woman_running_medium-light_skin_tone": "🏃🏼\u200d♀️",
+2656	    "woman_running_medium_skin_tone": "🏃🏽\u200d♀️",
+2657	    "woman_scientist": "👩\u200d🔬",
+2658	    "woman_scientist_dark_skin_tone": "👩🏿\u200d🔬",
+2659	    "woman_scientist_light_skin_tone": "👩🏻\u200d🔬",
+2660	    "woman_scientist_medium-dark_skin_tone": "👩🏾\u200d🔬",
+2661	    "woman_scientist_medium-light_skin_tone": "👩🏼\u200d🔬",
+2662	    "woman_scientist_medium_skin_tone": "👩🏽\u200d🔬",
+2663	    "woman_shrugging": "🤷\u200d♀️",
+2664	    "woman_shrugging_dark_skin_tone": "🤷🏿\u200d♀️",
+2665	    "woman_shrugging_light_skin_tone": "🤷🏻\u200d♀️",
+2666	    "woman_shrugging_medium-dark_skin_tone": "🤷🏾\u200d♀️",
+2667	    "woman_shrugging_medium-light_skin_tone": "🤷🏼\u200d♀️",
+2668	    "woman_shrugging_medium_skin_tone": "🤷🏽\u200d♀️",
+2669	    "woman_singer": "👩\u200d🎤",
+2670	    "woman_singer_dark_skin_tone": "👩🏿\u200d🎤",
+2671	    "woman_singer_light_skin_tone": "👩🏻\u200d🎤",
+2672	    "woman_singer_medium-dark_skin_tone": "👩🏾\u200d🎤",
+2673	    "woman_singer_medium-light_skin_tone": "👩🏼\u200d🎤",
+2674	    "woman_singer_medium_skin_tone": "👩🏽\u200d🎤",
+2675	    "woman_student": "👩\u200d🎓",
+2676	    "woman_student_dark_skin_tone": "👩🏿\u200d🎓",
+2677	    "woman_student_light_skin_tone": "👩🏻\u200d🎓",
+2678	    "woman_student_medium-dark_skin_tone": "👩🏾\u200d🎓",
+2679	    "woman_student_medium-light_skin_tone": "👩🏼\u200d🎓",
+2680	    "woman_student_medium_skin_tone": "👩🏽\u200d🎓",
+2681	    "woman_surfing": "🏄\u200d♀️",
+2682	    "woman_surfing_dark_skin_tone": "🏄🏿\u200d♀️",
+2683	    "woman_surfing_light_skin_tone": "🏄🏻\u200d♀️",
+2684	    "woman_surfing_medium-dark_skin_tone": "🏄🏾\u200d♀️",
+2685	    "woman_surfing_medium-light_skin_tone": "🏄🏼\u200d♀️",
+2686	    "woman_surfing_medium_skin_tone": "🏄🏽\u200d♀️",
+2687	    "woman_swimming": "🏊\u200d♀️",
+2688	    "woman_swimming_dark_skin_tone": "🏊🏿\u200d♀️",
+2689	    "woman_swimming_light_skin_tone": "🏊🏻\u200d♀️",
+2690	    "woman_swimming_medium-dark_skin_tone": "🏊🏾\u200d♀️",
+2691	    "woman_swimming_medium-light_skin_tone": "🏊🏼\u200d♀️",
+2692	    "woman_swimming_medium_skin_tone": "🏊🏽\u200d♀️",
+2693	    "woman_teacher": "👩\u200d🏫",
+2694	    "woman_teacher_dark_skin_tone": "👩🏿\u200d🏫",
+2695	    "woman_teacher_light_skin_tone": "👩🏻\u200d🏫",
+2696	    "woman_teacher_medium-dark_skin_tone": "👩🏾\u200d🏫",
+2697	    "woman_teacher_medium-light_skin_tone": "👩🏼\u200d🏫",
+2698	    "woman_teacher_medium_skin_tone": "👩🏽\u200d🏫",
+2699	    "woman_technologist": "👩\u200d💻",
+2700	    "woman_technologist_dark_skin_tone": "👩🏿\u200d💻",
+2701	    "woman_technologist_light_skin_tone": "👩🏻\u200d💻",
+2702	    "woman_technologist_medium-dark_skin_tone": "👩🏾\u200d💻",
+2703	    "woman_technologist_medium-light_skin_tone": "👩🏼\u200d💻",
+2704	    "woman_technologist_medium_skin_tone": "👩🏽\u200d💻",
+2705	    "woman_tipping_hand": "💁\u200d♀️",
+2706	    "woman_tipping_hand_dark_skin_tone": "💁🏿\u200d♀️",
+2707	    "woman_tipping_hand_light_skin_tone": "💁🏻\u200d♀️",
+2708	    "woman_tipping_hand_medium-dark_skin_tone": "💁🏾\u200d♀️",
+2709	    "woman_tipping_hand_medium-light_skin_tone": "💁🏼\u200d♀️",
+2710	    "woman_tipping_hand_medium_skin_tone": "💁🏽\u200d♀️",
+2711	    "woman_vampire": "🧛\u200d♀️",
+2712	    "woman_vampire_dark_skin_tone": "🧛🏿\u200d♀️",
+2713	    "woman_vampire_light_skin_tone": "🧛🏻\u200d♀️",
+2714	    "woman_vampire_medium-dark_skin_tone": "🧛🏾\u200d♀️",
+2715	    "woman_vampire_medium-light_skin_tone": "🧛🏼\u200d♀️",
+2716	    "woman_vampire_medium_skin_tone": "🧛🏽\u200d♀️",
+2717	    "woman_walking": "🚶\u200d♀️",
+2718	    "woman_walking_dark_skin_tone": "🚶🏿\u200d♀️",
+2719	    "woman_walking_light_skin_tone": "🚶🏻\u200d♀️",
+2720	    "woman_walking_medium-dark_skin_tone": "🚶🏾\u200d♀️",
+2721	    "woman_walking_medium-light_skin_tone": "🚶🏼\u200d♀️",
+2722	    "woman_walking_medium_skin_tone": "🚶🏽\u200d♀️",
+2723	    "woman_wearing_turban": "👳\u200d♀️",
+2724	    "woman_wearing_turban_dark_skin_tone": "👳🏿\u200d♀️",
+2725	    "woman_wearing_turban_light_skin_tone": "👳🏻\u200d♀️",
+2726	    "woman_wearing_turban_medium-dark_skin_tone": "👳🏾\u200d♀️",
+2727	    "woman_wearing_turban_medium-light_skin_tone": "👳🏼\u200d♀️",
+2728	    "woman_wearing_turban_medium_skin_tone": "👳🏽\u200d♀️",
+2729	    "woman_with_headscarf": "🧕",
+2730	    "woman_with_headscarf_dark_skin_tone": "🧕🏿",
+2731	    "woman_with_headscarf_light_skin_tone": "🧕🏻",
+2732	    "woman_with_headscarf_medium-dark_skin_tone": "🧕🏾",
+2733	    "woman_with_headscarf_medium-light_skin_tone": "🧕🏼",
+2734	    "woman_with_headscarf_medium_skin_tone": "🧕🏽",
+2735	    "woman_with_probing_cane": "👩\u200d🦯",
+2736	    "woman_zombie": "🧟\u200d♀️",
+2737	    "woman’s_boot": "👢",
+2738	    "woman’s_clothes": "👚",
+2739	    "woman’s_hat": "👒",
+2740	    "woman’s_sandal": "👡",
+2741	    "women_with_bunny_ears": "👯\u200d♀️",
+2742	    "women_wrestling": "🤼\u200d♀️",
+2743	    "women’s_room": "🚺",
+2744	    "woozy_face": "🥴",
+2745	    "world_map": "🗺",
+2746	    "worried_face": "😟",
+2747	    "wrapped_gift": "🎁",
+2748	    "wrench": "🔧",
+2749	    "writing_hand": "✍",
+2750	    "writing_hand_dark_skin_tone": "✍🏿",
+2751	    "writing_hand_light_skin_tone": "✍🏻",
+2752	    "writing_hand_medium-dark_skin_tone": "✍🏾",
+2753	    "writing_hand_medium-light_skin_tone": "✍🏼",
+2754	    "writing_hand_medium_skin_tone": "✍🏽",
+2755	    "yarn": "🧶",
+2756	    "yawning_face": "🥱",
+2757	    "yellow_circle": "🟡",
+2758	    "yellow_heart": "💛",
+2759	    "yellow_square": "🟨",
+2760	    "yen_banknote": "💴",
+2761	    "yo-yo": "🪀",
+2762	    "yin_yang": "☯",
+2763	    "zany_face": "🤪",
+2764	    "zebra": "🦓",
+2765	    "zipper-mouth_face": "🤐",
+2766	    "zombie": "🧟",
+2767	    "zzz": "💤",
+2768	    "åland_islands": "🇦🇽",
+2769	    "keycap_asterisk": "*⃣",
+2770	    "keycap_digit_eight": "8⃣",
+2771	    "keycap_digit_five": "5⃣",
+2772	    "keycap_digit_four": "4⃣",
+2773	    "keycap_digit_nine": "9⃣",
+2774	    "keycap_digit_one": "1⃣",
+2775	    "keycap_digit_seven": "7⃣",
+2776	    "keycap_digit_six": "6⃣",
+2777	    "keycap_digit_three": "3⃣",
+2778	    "keycap_digit_two": "2⃣",
+2779	    "keycap_digit_zero": "0⃣",
+2780	    "keycap_number_sign": "#⃣",
+2781	    "light_skin_tone": "🏻",
+2782	    "medium_light_skin_tone": "🏼",
+2783	    "medium_skin_tone": "🏽",
+2784	    "medium_dark_skin_tone": "🏾",
+2785	    "dark_skin_tone": "🏿",
+2786	    "regional_indicator_symbol_letter_a": "🇦",
+2787	    "regional_indicator_symbol_letter_b": "🇧",
+2788	    "regional_indicator_symbol_letter_c": "🇨",
+2789	    "regional_indicator_symbol_letter_d": "🇩",
+2790	    "regional_indicator_symbol_letter_e": "🇪",
+2791	    "regional_indicator_symbol_letter_f": "🇫",
+2792	    "regional_indicator_symbol_letter_g": "🇬",
+2793	    "regional_indicator_symbol_letter_h": "🇭",
+2794	    "regional_indicator_symbol_letter_i": "🇮",
+2795	    "regional_indicator_symbol_letter_j": "🇯",
+2796	    "regional_indicator_symbol_letter_k": "🇰",
+2797	    "regional_indicator_symbol_letter_l": "🇱",
+2798	    "regional_indicator_symbol_letter_m": "🇲",
+2799	    "regional_indicator_symbol_letter_n": "🇳",
+2800	    "regional_indicator_symbol_letter_o": "🇴",
+2801	    "regional_indicator_symbol_letter_p": "🇵",
+2802	    "regional_indicator_symbol_letter_q": "🇶",
+2803	    "regional_indicator_symbol_letter_r": "🇷",
+2804	    "regional_indicator_symbol_letter_s": "🇸",
+2805	    "regional_indicator_symbol_letter_t": "🇹",
+2806	    "regional_indicator_symbol_letter_u": "🇺",
+2807	    "regional_indicator_symbol_letter_v": "🇻",
+2808	    "regional_indicator_symbol_letter_w": "🇼",
+2809	    "regional_indicator_symbol_letter_x": "🇽",
+2810	    "regional_indicator_symbol_letter_y": "🇾",
+2811	    "regional_indicator_symbol_letter_z": "🇿",
+2812	    "airplane_arriving": "🛬",
+2813	    "space_invader": "👾",
+2814	    "football": "🏈",
+2815	    "anger": "💢",
+2816	    "angry": "😠",
+2817	    "anguished": "😧",
+2818	    "signal_strength": "📶",
+2819	    "arrows_counterclockwise": "🔄",
+2820	    "arrow_heading_down": "⤵",
+2821	    "arrow_heading_up": "⤴",
+2822	    "art": "🎨",
+2823	    "astonished": "😲",
+2824	    "athletic_shoe": "👟",
+2825	    "atm": "🏧",
+2826	    "car": "🚗",
+2827	    "red_car": "🚗",
+2828	    "angel": "👼",
+2829	    "back": "🔙",
+2830	    "badminton_racquet_and_shuttlecock": "🏸",
+2831	    "dollar": "💵",
+2832	    "euro": "💶",
+2833	    "pound": "💷",
+2834	    "yen": "💴",
+2835	    "barber": "💈",
+2836	    "bath": "🛀",
+2837	    "bear": "🐻",
+2838	    "heartbeat": "💓",
+2839	    "beer": "🍺",
+2840	    "no_bell": "🔕",
+2841	    "bento": "🍱",
+2842	    "bike": "🚲",
+2843	    "bicyclist": "🚴",
+2844	    "8ball": "🎱",
+2845	    "biohazard_sign": "☣",
+2846	    "birthday": "🎂",
+2847	    "black_circle_for_record": "⏺",
+2848	    "clubs": "♣",
+2849	    "diamonds": "♦",
+2850	    "arrow_double_down": "⏬",
+2851	    "hearts": "♥",
+2852	    "rewind": "⏪",
+2853	    "black_left__pointing_double_triangle_with_vertical_bar": "⏮",
+2854	    "arrow_backward": "◀",
+2855	    "black_medium_small_square": "◾",
+2856	    "question": "❓",
+2857	    "fast_forward": "⏩",
+2858	    "black_right__pointing_double_triangle_with_vertical_bar": "⏭",
+2859	    "arrow_forward": "▶",
+2860	    "black_right__pointing_triangle_with_double_vertical_bar": "⏯",
+2861	    "arrow_right": "➡",
+2862	    "spades": "♠",
+2863	    "black_square_for_stop": "⏹",
+2864	    "sunny": "☀",
+2865	    "phone": "☎",
+2866	    "recycle": "♻",
+2867	    "arrow_double_up": "⏫",
+2868	    "busstop": "🚏",
+2869	    "date": "📅",
+2870	    "flags": "🎏",
+2871	    "cat2": "🐈",
+2872	    "joy_cat": "😹",
+2873	    "smirk_cat": "😼",
+2874	    "chart_with_downwards_trend": "📉",
+2875	    "chart_with_upwards_trend": "📈",
+2876	    "chart": "💹",
+2877	    "mega": "📣",
+2878	    "checkered_flag": "🏁",
+2879	    "accept": "🉑",
+2880	    "ideograph_advantage": "🉐",
+2881	    "congratulations": "㊗",
+2882	    "secret": "㊙",
+2883	    "m": "Ⓜ",
+2884	    "city_sunset": "🌆",
+2885	    "clapper": "🎬",
+2886	    "clap": "👏",
+2887	    "beers": "🍻",
+2888	    "clock830": "🕣",
+2889	    "clock8": "🕗",
+2890	    "clock1130": "🕦",
+2891	    "clock11": "🕚",
+2892	    "clock530": "🕠",
+2893	    "clock5": "🕔",
+2894	    "clock430": "🕟",
+2895	    "clock4": "🕓",
+2896	    "clock930": "🕤",
+2897	    "clock9": "🕘",
+2898	    "clock130": "🕜",
+2899	    "clock1": "🕐",
+2900	    "clock730": "🕢",
+2901	    "clock7": "🕖",
+2902	    "clock630": "🕡",
+2903	    "clock6": "🕕",
+2904	    "clock1030": "🕥",
+2905	    "clock10": "🕙",
+2906	    "clock330": "🕞",
+2907	    "clock3": "🕒",
+2908	    "clock1230": "🕧",
+2909	    "clock12": "🕛",
+2910	    "clock230": "🕝",
+2911	    "clock2": "🕑",
+2912	    "arrows_clockwise": "🔃",
+2913	    "repeat": "🔁",
+2914	    "repeat_one": "🔂",
+2915	    "closed_lock_with_key": "🔐",
+2916	    "mailbox_closed": "📪",
+2917	    "mailbox": "📫",
+2918	    "cloud_with_tornado": "🌪",
+2919	    "cocktail": "🍸",
+2920	    "boom": "💥",
+2921	    "compression": "🗜",
+2922	    "confounded": "😖",
+2923	    "confused": "😕",
+2924	    "rice": "🍚",
+2925	    "cow2": "🐄",
+2926	    "cricket_bat_and_ball": "🏏",
+2927	    "x": "❌",
+2928	    "cry": "😢",
+2929	    "curry": "🍛",
+2930	    "dagger_knife": "🗡",
+2931	    "dancer": "💃",
+2932	    "dark_sunglasses": "🕶",
+2933	    "dash": "💨",
+2934	    "truck": "🚚",
+2935	    "derelict_house_building": "🏚",
+2936	    "diamond_shape_with_a_dot_inside": "💠",
+2937	    "dart": "🎯",
+2938	    "disappointed_relieved": "😥",
+2939	    "disappointed": "😞",
+2940	    "do_not_litter": "🚯",
+2941	    "dog2": "🐕",
+2942	    "flipper": "🐬",
+2943	    "loop": "➿",
+2944	    "bangbang": "‼",
+2945	    "double_vertical_bar": "⏸",
+2946	    "dove_of_peace": "🕊",
+2947	    "small_red_triangle_down": "🔻",
+2948	    "arrow_down_small": "🔽",
+2949	    "arrow_down": "⬇",
+2950	    "dromedary_camel": "🐪",
+2951	    "e__mail": "📧",
+2952	    "corn": "🌽",
+2953	    "ear_of_rice": "🌾",
+2954	    "earth_americas": "🌎",
+2955	    "earth_asia": "🌏",
+2956	    "earth_africa": "🌍",
+2957	    "eight_pointed_black_star": "✴",
+2958	    "eight_spoked_asterisk": "✳",
+2959	    "eject_symbol": "⏏",
+2960	    "bulb": "💡",
+2961	    "emoji_modifier_fitzpatrick_type__1__2": "🏻",
+2962	    "emoji_modifier_fitzpatrick_type__3": "🏼",
+2963	    "emoji_modifier_fitzpatrick_type__4": "🏽",
+2964	    "emoji_modifier_fitzpatrick_type__5": "🏾",
+2965	    "emoji_modifier_fitzpatrick_type__6": "🏿",
+2966	    "end": "🔚",
+2967	    "email": "✉",
+2968	    "european_castle": "🏰",
+2969	    "european_post_office": "🏤",
+2970	    "interrobang": "⁉",
+2971	    "expressionless": "😑",
+2972	    "eyeglasses": "👓",
+2973	    "massage": "💆",
+2974	    "yum": "😋",
+2975	    "scream": "😱",
+2976	    "kissing_heart": "😘",
+2977	    "sweat": "😓",
+2978	    "face_with_head__bandage": "🤕",
+2979	    "triumph": "😤",
+2980	    "mask": "😷",
+2981	    "no_good": "🙅",
+2982	    "ok_woman": "🙆",
+2983	    "open_mouth": "😮",
+2984	    "cold_sweat": "😰",
+2985	    "stuck_out_tongue": "😛",
+2986	    "stuck_out_tongue_closed_eyes": "😝",
+2987	    "stuck_out_tongue_winking_eye": "😜",
+2988	    "joy": "😂",
+2989	    "no_mouth": "😶",
+2990	    "santa": "🎅",
+2991	    "fax": "📠",
+2992	    "fearful": "😨",
+2993	    "field_hockey_stick_and_ball": "🏑",
+2994	    "first_quarter_moon_with_face": "🌛",
+2995	    "fish_cake": "🍥",
+2996	    "fishing_pole_and_fish": "🎣",
+2997	    "facepunch": "👊",
+2998	    "punch": "👊",
+2999	    "flag_for_afghanistan": "🇦🇫",
+3000	    "flag_for_albania": "🇦🇱",
+3001	    "flag_for_algeria": "🇩🇿",
+3002	    "flag_for_american_samoa": "🇦🇸",
+3003	    "flag_for_andorra": "🇦🇩",
+3004	    "flag_for_angola": "🇦🇴",
+3005	    "flag_for_anguilla": "🇦🇮",
+3006	    "flag_for_antarctica": "🇦🇶",
+3007	    "flag_for_antigua_&_barbuda": "🇦🇬",
+3008	    "flag_for_argentina": "🇦🇷",
+3009	    "flag_for_armenia": "🇦🇲",
+3010	    "flag_for_aruba": "🇦🇼",
+3011	    "flag_for_ascension_island": "🇦🇨",
+3012	    "flag_for_australia": "🇦🇺",
+3013	    "flag_for_austria": "🇦🇹",
+3014	    "flag_for_azerbaijan": "🇦🇿",
+3015	    "flag_for_bahamas": "🇧🇸",
+3016	    "flag_for_bahrain": "🇧🇭",
+3017	    "flag_for_bangladesh": "🇧🇩",
+3018	    "flag_for_barbados": "🇧🇧",
+3019	    "flag_for_belarus": "🇧🇾",
+3020	    "flag_for_belgium": "🇧🇪",
+3021	    "flag_for_belize": "🇧🇿",
+3022	    "flag_for_benin": "🇧🇯",
+3023	    "flag_for_bermuda": "🇧🇲",
+3024	    "flag_for_bhutan": "🇧🇹",
+3025	    "flag_for_bolivia": "🇧🇴",
+3026	    "flag_for_bosnia_&_herzegovina": "🇧🇦",
+3027	    "flag_for_botswana": "🇧🇼",
+3028	    "flag_for_bouvet_island": "🇧🇻",
+3029	    "flag_for_brazil": "🇧🇷",
+3030	    "flag_for_british_indian_ocean_territory": "🇮🇴",
+3031	    "flag_for_british_virgin_islands": "🇻🇬",
+3032	    "flag_for_brunei": "🇧🇳",
+3033	    "flag_for_bulgaria": "🇧🇬",
+3034	    "flag_for_burkina_faso": "🇧🇫",
+3035	    "flag_for_burundi": "🇧🇮",
+3036	    "flag_for_cambodia": "🇰🇭",
+3037	    "flag_for_cameroon": "🇨🇲",
+3038	    "flag_for_canada": "🇨🇦",
+3039	    "flag_for_canary_islands": "🇮🇨",
+3040	    "flag_for_cape_verde": "🇨🇻",
+3041	    "flag_for_caribbean_netherlands": "🇧🇶",
+3042	    "flag_for_cayman_islands": "🇰🇾",
+3043	    "flag_for_central_african_republic": "🇨🇫",
+3044	    "flag_for_ceuta_&_melilla": "🇪🇦",
+3045	    "flag_for_chad": "🇹🇩",
+3046	    "flag_for_chile": "🇨🇱",
+3047	    "flag_for_china": "🇨🇳",
+3048	    "flag_for_christmas_island": "🇨🇽",
+3049	    "flag_for_clipperton_island": "🇨🇵",
+3050	    "flag_for_cocos__islands": "🇨🇨",
+3051	    "flag_for_colombia": "🇨🇴",
+3052	    "flag_for_comoros": "🇰🇲",
+3053	    "flag_for_congo____brazzaville": "🇨🇬",
+3054	    "flag_for_congo____kinshasa": "🇨🇩",
+3055	    "flag_for_cook_islands": "🇨🇰",
+3056	    "flag_for_costa_rica": "🇨🇷",
+3057	    "flag_for_croatia": "🇭🇷",
+3058	    "flag_for_cuba": "🇨🇺",
+3059	    "flag_for_curaçao": "🇨🇼",
+3060	    "flag_for_cyprus": "🇨🇾",
+3061	    "flag_for_czech_republic": "🇨🇿",
+3062	    "flag_for_côte_d’ivoire": "🇨🇮",
+3063	    "flag_for_denmark": "🇩🇰",
+3064	    "flag_for_diego_garcia": "🇩🇬",
+3065	    "flag_for_djibouti": "🇩🇯",
+3066	    "flag_for_dominica": "🇩🇲",
+3067	    "flag_for_dominican_republic": "🇩🇴",
+3068	    "flag_for_ecuador": "🇪🇨",
+3069	    "flag_for_egypt": "🇪🇬",
+3070	    "flag_for_el_salvador": "🇸🇻",
+3071	    "flag_for_equatorial_guinea": "🇬🇶",
+3072	    "flag_for_eritrea": "🇪🇷",
+3073	    "flag_for_estonia": "🇪🇪",
+3074	    "flag_for_ethiopia": "🇪🇹",
+3075	    "flag_for_european_union": "🇪🇺",
+3076	    "flag_for_falkland_islands": "🇫🇰",
+3077	    "flag_for_faroe_islands": "🇫🇴",
+3078	    "flag_for_fiji": "🇫🇯",
+3079	    "flag_for_finland": "🇫🇮",
+3080	    "flag_for_france": "🇫🇷",
+3081	    "flag_for_french_guiana": "🇬🇫",
+3082	    "flag_for_french_polynesia": "🇵🇫",
+3083	    "flag_for_french_southern_territories": "🇹🇫",
+3084	    "flag_for_gabon": "🇬🇦",
+3085	    "flag_for_gambia": "🇬🇲",
+3086	    "flag_for_georgia": "🇬🇪",
+3087	    "flag_for_germany": "🇩🇪",
+3088	    "flag_for_ghana": "🇬🇭",
+3089	    "flag_for_gibraltar": "🇬🇮",
+3090	    "flag_for_greece": "🇬🇷",
+3091	    "flag_for_greenland": "🇬🇱",
+3092	    "flag_for_grenada": "🇬🇩",
+3093	    "flag_for_guadeloupe": "🇬🇵",
+3094	    "flag_for_guam": "🇬🇺",
+3095	    "flag_for_guatemala": "🇬🇹",
+3096	    "flag_for_guernsey": "🇬🇬",
+3097	    "flag_for_guinea": "🇬🇳",
+3098	    "flag_for_guinea__bissau": "🇬🇼",
+3099	    "flag_for_guyana": "🇬🇾",
+3100	    "flag_for_haiti": "🇭🇹",
+3101	    "flag_for_heard_&_mcdonald_islands": "🇭🇲",
+3102	    "flag_for_honduras": "🇭🇳",
+3103	    "flag_for_hong_kong": "🇭🇰",
+3104	    "flag_for_hungary": "🇭🇺",
+3105	    "flag_for_iceland": "🇮🇸",
+3106	    "flag_for_india": "🇮🇳",
+3107	    "flag_for_indonesia": "🇮🇩",
+3108	    "flag_for_iran": "🇮🇷",
+3109	    "flag_for_iraq": "🇮🇶",
+3110	    "flag_for_ireland": "🇮🇪",
+3111	    "flag_for_isle_of_man": "🇮🇲",
+3112	    "flag_for_israel": "🇮🇱",
+3113	    "flag_for_italy": "🇮🇹",
+3114	    "flag_for_jamaica": "🇯🇲",
+3115	    "flag_for_japan": "🇯🇵",
+3116	    "flag_for_jersey": "🇯🇪",
+3117	    "flag_for_jordan": "🇯🇴",
+3118	    "flag_for_kazakhstan": "🇰🇿",
+3119	    "flag_for_kenya": "🇰🇪",
+3120	    "flag_for_kiribati": "🇰🇮",
+3121	    "flag_for_kosovo": "🇽🇰",
+3122	    "flag_for_kuwait": "🇰🇼",
+3123	    "flag_for_kyrgyzstan": "🇰🇬",
+3124	    "flag_for_laos": "🇱🇦",
+3125	    "flag_for_latvia": "🇱🇻",
+3126	    "flag_for_lebanon": "🇱🇧",
+3127	    "flag_for_lesotho": "🇱🇸",
+3128	    "flag_for_liberia": "🇱🇷",
+3129	    "flag_for_libya": "🇱🇾",
+3130	    "flag_for_liechtenstein": "🇱🇮",
+3131	    "flag_for_lithuania": "🇱🇹",
+3132	    "flag_for_luxembourg": "🇱🇺",
+3133	    "flag_for_macau": "🇲🇴",
+3134	    "flag_for_macedonia": "🇲🇰",
+3135	    "flag_for_madagascar": "🇲🇬",
+3136	    "flag_for_malawi": "🇲🇼",
+3137	    "flag_for_malaysia": "🇲🇾",
+3138	    "flag_for_maldives": "🇲🇻",
+3139	    "flag_for_mali": "🇲🇱",
+3140	    "flag_for_malta": "🇲🇹",
+3141	    "flag_for_marshall_islands": "🇲🇭",
+3142	    "flag_for_martinique": "🇲🇶",
+3143	    "flag_for_mauritania": "🇲🇷",
+3144	    "flag_for_mauritius": "🇲🇺",
+3145	    "flag_for_mayotte": "🇾🇹",
+3146	    "flag_for_mexico": "🇲🇽",
+3147	    "flag_for_micronesia": "🇫🇲",
+3148	    "flag_for_moldova": "🇲🇩",
+3149	    "flag_for_monaco": "🇲🇨",
+3150	    "flag_for_mongolia": "🇲🇳",
+3151	    "flag_for_montenegro": "🇲🇪",
+3152	    "flag_for_montserrat": "🇲🇸",
+3153	    "flag_for_morocco": "🇲🇦",
+3154	    "flag_for_mozambique": "🇲🇿",
+3155	    "flag_for_myanmar": "🇲🇲",
+3156	    "flag_for_namibia": "🇳🇦",
+3157	    "flag_for_nauru": "🇳🇷",
+3158	    "flag_for_nepal": "🇳🇵",
+3159	    "flag_for_netherlands": "🇳🇱",
+3160	    "flag_for_new_caledonia": "🇳🇨",
+3161	    "flag_for_new_zealand": "🇳🇿",
+3162	    "flag_for_nicaragua": "🇳🇮",
+3163	    "flag_for_niger": "🇳🇪",
+3164	    "flag_for_nigeria": "🇳🇬",
+3165	    "flag_for_niue": "🇳🇺",
+3166	    "flag_for_norfolk_island": "🇳🇫",
+3167	    "flag_for_north_korea": "🇰🇵",
+3168	    "flag_for_northern_mariana_islands": "🇲🇵",
+3169	    "flag_for_norway": "🇳🇴",
+3170	    "flag_for_oman": "🇴🇲",
+3171	    "flag_for_pakistan": "🇵🇰",
+3172	    "flag_for_palau": "🇵🇼",
+3173	    "flag_for_palestinian_territories": "🇵🇸",
+3174	    "flag_for_panama": "🇵🇦",
+3175	    "flag_for_papua_new_guinea": "🇵🇬",
+3176	    "flag_for_paraguay": "🇵🇾",
+3177	    "flag_for_peru": "🇵🇪",
+3178	    "flag_for_philippines": "🇵🇭",
+3179	    "flag_for_pitcairn_islands": "🇵🇳",
+3180	    "flag_for_poland": "🇵🇱",
+3181	    "flag_for_portugal": "🇵🇹",
+3182	    "flag_for_puerto_rico": "🇵🇷",
+3183	    "flag_for_qatar": "🇶🇦",
+3184	    "flag_for_romania": "🇷🇴",
+3185	    "flag_for_russia": "🇷🇺",
+3186	    "flag_for_rwanda": "🇷🇼",
+3187	    "flag_for_réunion": "🇷🇪",
+3188	    "flag_for_samoa": "🇼🇸",
+3189	    "flag_for_san_marino": "🇸🇲",
+3190	    "flag_for_saudi_arabia": "🇸🇦",
+3191	    "flag_for_senegal": "🇸🇳",
+3192	    "flag_for_serbia": "🇷🇸",
+3193	    "flag_for_seychelles": "🇸🇨",
+3194	    "flag_for_sierra_leone": "🇸🇱",
+3195	    "flag_for_singapore": "🇸🇬",
+3196	    "flag_for_sint_maarten": "🇸🇽",
+3197	    "flag_for_slovakia": "🇸🇰",
+3198	    "flag_for_slovenia": "🇸🇮",
+3199	    "flag_for_solomon_islands": "🇸🇧",
+3200	    "flag_for_somalia": "🇸🇴",
+3201	    "flag_for_south_africa": "🇿🇦",
+3202	    "flag_for_south_georgia_&_south_sandwich_islands": "🇬🇸",
+3203	    "flag_for_south_korea": "🇰🇷",
+3204	    "flag_for_south_sudan": "🇸🇸",
+3205	    "flag_for_spain": "🇪🇸",
+3206	    "flag_for_sri_lanka": "🇱🇰",
+3207	    "flag_for_st._barthélemy": "🇧🇱",
+3208	    "flag_for_st._helena": "🇸🇭",
+3209	    "flag_for_st._kitts_&_nevis": "🇰🇳",
+3210	    "flag_for_st._lucia": "🇱🇨",
+3211	    "flag_for_st._martin": "🇲🇫",
+3212	    "flag_for_st._pierre_&_miquelon": "🇵🇲",
+3213	    "flag_for_st._vincent_&_grenadines": "🇻🇨",
+3214	    "flag_for_sudan": "🇸🇩",
+3215	    "flag_for_suriname": "🇸🇷",
+3216	    "flag_for_svalbard_&_jan_mayen": "🇸🇯",
+3217	    "flag_for_swaziland": "🇸🇿",
+3218	    "flag_for_sweden": "🇸🇪",
+3219	    "flag_for_switzerland": "🇨🇭",
+3220	    "flag_for_syria": "🇸🇾",
+3221	    "flag_for_são_tomé_&_príncipe": "🇸🇹",
+3222	    "flag_for_taiwan": "🇹🇼",
+3223	    "flag_for_tajikistan": "🇹🇯",
+3224	    "flag_for_tanzania": "🇹🇿",
+3225	    "flag_for_thailand": "🇹🇭",
+3226	    "flag_for_timor__leste": "🇹🇱",
+3227	    "flag_for_togo": "🇹🇬",
+3228	    "flag_for_tokelau": "🇹🇰",
+3229	    "flag_for_tonga": "🇹🇴",
+3230	    "flag_for_trinidad_&_tobago": "🇹🇹",
+3231	    "flag_for_tristan_da_cunha": "🇹🇦",
+3232	    "flag_for_tunisia": "🇹🇳",
+3233	    "flag_for_turkey": "🇹🇷",
+3234	    "flag_for_turkmenistan": "🇹🇲",
+3235	    "flag_for_turks_&_caicos_islands": "🇹🇨",
+3236	    "flag_for_tuvalu": "🇹🇻",
+3237	    "flag_for_u.s._outlying_islands": "🇺🇲",
+3238	    "flag_for_u.s._virgin_islands": "🇻🇮",
+3239	    "flag_for_uganda": "🇺🇬",
+3240	    "flag_for_ukraine": "🇺🇦",
+3241	    "flag_for_united_arab_emirates": "🇦🇪",
+3242	    "flag_for_united_kingdom": "🇬🇧",
+3243	    "flag_for_united_states": "🇺🇸",
+3244	    "flag_for_uruguay": "🇺🇾",
+3245	    "flag_for_uzbekistan": "🇺🇿",
+3246	    "flag_for_vanuatu": "🇻🇺",
+3247	    "flag_for_vatican_city": "🇻🇦",
+3248	    "flag_for_venezuela": "🇻🇪",
+3249	    "flag_for_vietnam": "🇻🇳",
+3250	    "flag_for_wallis_&_futuna": "🇼🇫",
+3251	    "flag_for_western_sahara": "🇪🇭",
+3252	    "flag_for_yemen": "🇾🇪",
+3253	    "flag_for_zambia": "🇿🇲",
+3254	    "flag_for_zimbabwe": "🇿🇼",
+3255	    "flag_for_åland_islands": "🇦🇽",
+3256	    "golf": "⛳",
+3257	    "fleur__de__lis": "⚜",
+3258	    "muscle": "💪",
+3259	    "flushed": "😳",
+3260	    "frame_with_picture": "🖼",
+3261	    "fries": "🍟",
+3262	    "frog": "🐸",
+3263	    "hatched_chick": "🐥",
+3264	    "frowning": "😦",
+3265	    "fuelpump": "⛽",
+3266	    "full_moon_with_face": "🌝",
+3267	    "gem": "💎",
+3268	    "star2": "🌟",
+3269	    "golfer": "🏌",
+3270	    "mortar_board": "🎓",
+3271	    "grimacing": "😬",
+3272	    "smile_cat": "😸",
+3273	    "grinning": "😀",
+3274	    "grin": "😁",
+3275	    "heartpulse": "💗",
+3276	    "guardsman": "💂",
+3277	    "haircut": "💇",
+3278	    "hamster": "🐹",
+3279	    "raising_hand": "🙋",
+3280	    "headphones": "🎧",
+3281	    "hear_no_evil": "🙉",
+3282	    "cupid": "💘",
+3283	    "gift_heart": "💝",
+3284	    "heart": "❤",
+3285	    "exclamation": "❗",
+3286	    "heavy_exclamation_mark": "❗",
+3287	    "heavy_heart_exclamation_mark_ornament": "❣",
+3288	    "o": "⭕",
+3289	    "helm_symbol": "⎈",
+3290	    "helmet_with_white_cross": "⛑",
+3291	    "high_heel": "👠",
+3292	    "bullettrain_side": "🚄",
+3293	    "bullettrain_front": "🚅",
+3294	    "high_brightness": "🔆",
+3295	    "zap": "⚡",
+3296	    "hocho": "🔪",
+3297	    "knife": "🔪",
+3298	    "bee": "🐝",
+3299	    "traffic_light": "🚥",
+3300	    "racehorse": "🐎",
+3301	    "coffee": "☕",
+3302	    "hotsprings": "♨",
+3303	    "hourglass": "⌛",
+3304	    "hourglass_flowing_sand": "⏳",
+3305	    "house_buildings": "🏘",
+3306	    "100": "💯",
+3307	    "hushed": "😯",
+3308	    "ice_hockey_stick_and_puck": "🏒",
+3309	    "imp": "👿",
+3310	    "information_desk_person": "💁",
+3311	    "information_source": "ℹ",
+3312	    "capital_abcd": "🔠",
+3313	    "abc": "🔤",
+3314	    "abcd": "🔡",
+3315	    "1234": "🔢",
+3316	    "symbols": "🔣",
+3317	    "izakaya_lantern": "🏮",
+3318	    "lantern": "🏮",
+3319	    "jack_o_lantern": "🎃",
+3320	    "dolls": "🎎",
+3321	    "japanese_goblin": "👺",
+3322	    "japanese_ogre": "👹",
+3323	    "beginner": "🔰",
+3324	    "zero": "0️⃣",
+3325	    "one": "1️⃣",
+3326	    "ten": "🔟",
+3327	    "two": "2️⃣",
+3328	    "three": "3️⃣",
+3329	    "four": "4️⃣",
+3330	    "five": "5️⃣",
+3331	    "six": "6️⃣",
+3332	    "seven": "7️⃣",
+3333	    "eight": "8️⃣",
+3334	    "nine": "9️⃣",
+3335	    "couplekiss": "💏",
+3336	    "kissing_cat": "😽",
+3337	    "kissing": "😗",
+3338	    "kissing_closed_eyes": "😚",
+3339	    "kissing_smiling_eyes": "😙",
+3340	    "beetle": "🐞",
+3341	    "large_blue_circle": "🔵",
+3342	    "last_quarter_moon_with_face": "🌜",
+3343	    "leaves": "🍃",
+3344	    "mag": "🔍",
+3345	    "left_right_arrow": "↔",
+3346	    "leftwards_arrow_with_hook": "↩",
+3347	    "arrow_left": "⬅",
+3348	    "lock": "🔒",
+3349	    "lock_with_ink_pen": "🔏",
+3350	    "sob": "😭",
+3351	    "low_brightness": "🔅",
+3352	    "lower_left_ballpoint_pen": "🖊",
+3353	    "lower_left_crayon": "🖍",
+3354	    "lower_left_fountain_pen": "🖋",
+3355	    "lower_left_paintbrush": "🖌",
+3356	    "mahjong": "🀄",
+3357	    "couple": "👫",
+3358	    "man_in_business_suit_levitating": "🕴",
+3359	    "man_with_gua_pi_mao": "👲",
+3360	    "man_with_turban": "👳",
+3361	    "mans_shoe": "👞",
+3362	    "shoe": "👞",
+3363	    "menorah_with_nine_branches": "🕎",
+3364	    "mens": "🚹",
+3365	    "minidisc": "💽",
+3366	    "iphone": "📱",
+3367	    "calling": "📲",
+3368	    "money__mouth_face": "🤑",
+3369	    "moneybag": "💰",
+3370	    "rice_scene": "🎑",
+3371	    "mountain_bicyclist": "🚵",
+3372	    "mouse2": "🐁",
+3373	    "lips": "👄",
+3374	    "moyai": "🗿",
+3375	    "notes": "🎶",
+3376	    "nail_care": "💅",
+3377	    "ab": "🆎",
+3378	    "negative_squared_cross_mark": "❎",
+3379	    "a": "🅰",
+3380	    "b": "🅱",
+3381	    "o2": "🅾",
+3382	    "parking": "🅿",
+3383	    "new_moon_with_face": "🌚",
+3384	    "no_entry_sign": "🚫",
+3385	    "underage": "🔞",
+3386	    "non__potable_water": "🚱",
+3387	    "arrow_upper_right": "↗",
+3388	    "arrow_upper_left": "↖",
+3389	    "office": "🏢",
+3390	    "older_man": "👴",
+3391	    "older_woman": "👵",
+3392	    "om_symbol": "🕉",
+3393	    "on": "🔛",
+3394	    "book": "📖",
+3395	    "unlock": "🔓",
+3396	    "mailbox_with_no_mail": "📭",
+3397	    "mailbox_with_mail": "📬",
+3398	    "cd": "💿",
+3399	    "tada": "🎉",
+3400	    "feet": "🐾",
+3401	    "walking": "🚶",
+3402	    "pencil2": "✏",
+3403	    "pensive": "😔",
+3404	    "persevere": "😣",
+3405	    "bow": "🙇",
+3406	    "raised_hands": "🙌",
+3407	    "person_with_ball": "⛹",
+3408	    "person_with_blond_hair": "👱",
+3409	    "pray": "🙏",
+3410	    "person_with_pouting_face": "🙎",
+3411	    "computer": "💻",
+3412	    "pig2": "🐖",
+3413	    "hankey": "💩",
+3414	    "poop": "💩",
+3415	    "shit": "💩",
+3416	    "bamboo": "🎍",
+3417	    "gun": "🔫",
+3418	    "black_joker": "🃏",
+3419	    "rotating_light": "🚨",
+3420	    "cop": "👮",
+3421	    "stew": "🍲",
+3422	    "pouch": "👝",
+3423	    "pouting_cat": "😾",
+3424	    "rage": "😡",
+3425	    "put_litter_in_its_place": "🚮",
+3426	    "rabbit2": "🐇",
+3427	    "racing_motorcycle": "🏍",
+3428	    "radioactive_sign": "☢",
+3429	    "fist": "✊",
+3430	    "hand": "✋",
+3431	    "raised_hand_with_fingers_splayed": "🖐",
+3432	    "raised_hand_with_part_between_middle_and_ring_fingers": "🖖",
+3433	    "blue_car": "🚙",
+3434	    "apple": "🍎",
+3435	    "relieved": "😌",
+3436	    "reversed_hand_with_middle_finger_extended": "🖕",
+3437	    "mag_right": "🔎",
+3438	    "arrow_right_hook": "↪",
+3439	    "sweet_potato": "🍠",
+3440	    "robot": "🤖",
+3441	    "rolled__up_newspaper": "🗞",
+3442	    "rowboat": "🚣",
+3443	    "runner": "🏃",
+3444	    "running": "🏃",
+3445	    "running_shirt_with_sash": "🎽",
+3446	    "boat": "⛵",
+3447	    "scales": "⚖",
+3448	    "school_satchel": "🎒",
+3449	    "scorpius": "♏",
+3450	    "see_no_evil": "🙈",
+3451	    "sheep": "🐑",
+3452	    "stars": "🌠",
+3453	    "cake": "🍰",
+3454	    "six_pointed_star": "🔯",
+3455	    "ski": "🎿",
+3456	    "sleeping_accommodation": "🛌",
+3457	    "sleeping": "😴",
+3458	    "sleepy": "😪",
+3459	    "sleuth_or_spy": "🕵",
+3460	    "heart_eyes_cat": "😻",
+3461	    "smiley_cat": "😺",
+3462	    "innocent": "😇",
+3463	    "heart_eyes": "😍",
+3464	    "smiling_imp": "😈",
+3465	    "smiley": "😃",
+3466	    "sweat_smile": "😅",
+3467	    "smile": "😄",
+3468	    "laughing": "😆",
+3469	    "satisfied": "😆",
+3470	    "blush": "😊",
+3471	    "smirk": "😏",
+3472	    "smoking": "🚬",
+3473	    "snow_capped_mountain": "🏔",
+3474	    "soccer": "⚽",
+3475	    "icecream": "🍦",
+3476	    "soon": "🔜",
+3477	    "arrow_lower_right": "↘",
+3478	    "arrow_lower_left": "↙",
+3479	    "speak_no_evil": "🙊",
+3480	    "speaker": "🔈",
+3481	    "mute": "🔇",
+3482	    "sound": "🔉",
+3483	    "loud_sound": "🔊",
+3484	    "speaking_head_in_silhouette": "🗣",
+3485	    "spiral_calendar_pad": "🗓",
+3486	    "spiral_note_pad": "🗒",
+3487	    "shell": "🐚",
+3488	    "sweat_drops": "💦",
+3489	    "u5272": "🈹",
+3490	    "u5408": "🈴",
+3491	    "u55b6": "🈺",
+3492	    "u6307": "🈯",
+3493	    "u6708": "🈷",
+3494	    "u6709": "🈶",
+3495	    "u6e80": "🈵",
+3496	    "u7121": "🈚",
+3497	    "u7533": "🈸",
+3498	    "u7981": "🈲",
+3499	    "u7a7a": "🈳",
+3500	    "cl": "🆑",
+3501	    "cool": "🆒",
+3502	    "free": "🆓",
+3503	    "id": "🆔",
+3504	    "koko": "🈁",
+3505	    "sa": "🈂",
+3506	    "new": "🆕",
+3507	    "ng": "🆖",
+3508	    "ok": "🆗",
+3509	    "sos": "🆘",
+3510	    "up": "🆙",
+3511	    "vs": "🆚",
+3512	    "steam_locomotive": "🚂",
+3513	    "ramen": "🍜",
+3514	    "partly_sunny": "⛅",
+3515	    "city_sunrise": "🌇",
+3516	    "surfer": "🏄",
+3517	    "swimmer": "🏊",
+3518	    "shirt": "👕",
+3519	    "tshirt": "👕",
+3520	    "table_tennis_paddle_and_ball": "🏓",
+3521	    "tea": "🍵",
+3522	    "tv": "📺",
+3523	    "three_button_mouse": "🖱",
+3524	    "+1": "👍",
+3525	    "thumbsup": "👍",
+3526	    "__1": "👎",
+3527	    "-1": "👎",
+3528	    "thumbsdown": "👎",
+3529	    "thunder_cloud_and_rain": "⛈",
+3530	    "tiger2": "🐅",
+3531	    "tophat": "🎩",
+3532	    "top": "🔝",
+3533	    "tm": "™",
+3534	    "train2": "🚆",
+3535	    "triangular_flag_on_post": "🚩",
+3536	    "trident": "🔱",
+3537	    "twisted_rightwards_arrows": "🔀",
+3538	    "unamused": "😒",
+3539	    "small_red_triangle": "🔺",
+3540	    "arrow_up_small": "🔼",
+3541	    "arrow_up_down": "↕",
+3542	    "upside__down_face": "🙃",
+3543	    "arrow_up": "⬆",
+3544	    "v": "✌",
+3545	    "vhs": "📼",
+3546	    "wc": "🚾",
+3547	    "ocean": "🌊",
+3548	    "waving_black_flag": "🏴",
+3549	    "wave": "👋",
+3550	    "waving_white_flag": "🏳",
+3551	    "moon": "🌔",
+3552	    "scream_cat": "🙀",
+3553	    "weary": "😩",
+3554	    "weight_lifter": "🏋",
+3555	    "whale2": "🐋",
+3556	    "wheelchair": "♿",
+3557	    "point_down": "👇",
+3558	    "grey_exclamation": "❕",
+3559	    "white_frowning_face": "☹",
+3560	    "white_check_mark": "✅",
+3561	    "point_left": "👈",
+3562	    "white_medium_small_square": "◽",
+3563	    "star": "⭐",
+3564	    "grey_question": "❔",
+3565	    "point_right": "👉",
+3566	    "relaxed": "☺",
+3567	    "white_sun_behind_cloud": "🌥",
+3568	    "white_sun_behind_cloud_with_rain": "🌦",
+3569	    "white_sun_with_small_cloud": "🌤",
+3570	    "point_up_2": "👆",
+3571	    "point_up": "☝",
+3572	    "wind_blowing_face": "🌬",
+3573	    "wink": "😉",
+3574	    "wolf": "🐺",
+3575	    "dancers": "👯",
+3576	    "boot": "👢",
+3577	    "womans_clothes": "👚",
+3578	    "womans_hat": "👒",
+3579	    "sandal": "👡",
+3580	    "womens": "🚺",
+3581	    "worried": "😟",
+3582	    "gift": "🎁",
+3583	    "zipper__mouth_face": "🤐",
+3584	    "regional_indicator_a": "🇦",
+3585	    "regional_indicator_b": "🇧",
+3586	    "regional_indicator_c": "🇨",
+3587	    "regional_indicator_d": "🇩",
+3588	    "regional_indicator_e": "🇪",
+3589	    "regional_indicator_f": "🇫",
+3590	    "regional_indicator_g": "🇬",
+3591	    "regional_indicator_h": "🇭",
+3592	    "regional_indicator_i": "🇮",
+3593	    "regional_indicator_j": "🇯",
+3594	    "regional_indicator_k": "🇰",
+3595	    "regional_indicator_l": "🇱",
+3596	    "regional_indicator_m": "🇲",
+3597	    "regional_indicator_n": "🇳",
+3598	    "regional_indicator_o": "🇴",
+3599	    "regional_indicator_p": "🇵",
+3600	    "regional_indicator_q": "🇶",
+3601	    "regional_indicator_r": "🇷",
+3602	    "regional_indicator_s": "🇸",
+3603	    "regional_indicator_t": "🇹",
+3604	    "regional_indicator_u": "🇺",
+3605	    "regional_indicator_v": "🇻",
+3606	    "regional_indicator_w": "🇼",
+3607	    "regional_indicator_x": "🇽",
+3608	    "regional_indicator_y": "🇾",
+3609	    "regional_indicator_z": "🇿",
+3610	}
+
+
+ + +
+
+ +
+
+ hardcoded_password_string: Possible hardcoded password: '㊙'
+ Test ID: B105
+ Severity: LOW
+ Confidence: MEDIUM
+ CWE: CWE-259
+ File: ./venv/lib/python3.12/site-packages/rich/_emoji_codes.py
+ Line number: 2882
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b105_hardcoded_password_string.html
+ +
+
+2881	    "congratulations": "㊗",
+2882	    "secret": "㊙",
+2883	    "m": "Ⓜ",
+2884	    "city_sunset": "🌆",
+2885	    "clapper": "🎬",
+2886	    "clap": "👏",
+2887	    "beers": "🍻",
+2888	    "clock830": "🕣",
+2889	    "clock8": "🕗",
+2890	    "clock1130": "🕦",
+2891	    "clock11": "🕚",
+2892	    "clock530": "🕠",
+2893	    "clock5": "🕔",
+2894	    "clock430": "🕟",
+2895	    "clock4": "🕓",
+2896	    "clock930": "🕤",
+2897	    "clock9": "🕘",
+2898	    "clock130": "🕜",
+2899	    "clock1": "🕐",
+2900	    "clock730": "🕢",
+2901	    "clock7": "🕖",
+2902	    "clock630": "🕡",
+2903	    "clock6": "🕕",
+2904	    "clock1030": "🕥",
+2905	    "clock10": "🕙",
+2906	    "clock330": "🕞",
+2907	    "clock3": "🕒",
+2908	    "clock1230": "🕧",
+2909	    "clock12": "🕛",
+2910	    "clock230": "🕝",
+2911	    "clock2": "🕑",
+2912	    "arrows_clockwise": "🔃",
+2913	    "repeat": "🔁",
+2914	    "repeat_one": "🔂",
+2915	    "closed_lock_with_key": "🔐",
+2916	    "mailbox_closed": "📪",
+2917	    "mailbox": "📫",
+2918	    "cloud_with_tornado": "🌪",
+2919	    "cocktail": "🍸",
+2920	    "boom": "💥",
+2921	    "compression": "🗜",
+2922	    "confounded": "😖",
+2923	    "confused": "😕",
+2924	    "rice": "🍚",
+2925	    "cow2": "🐄",
+2926	    "cricket_bat_and_ball": "🏏",
+2927	    "x": "❌",
+2928	    "cry": "😢",
+2929	    "curry": "🍛",
+2930	    "dagger_knife": "🗡",
+2931	    "dancer": "💃",
+2932	    "dark_sunglasses": "🕶",
+2933	    "dash": "💨",
+2934	    "truck": "🚚",
+2935	    "derelict_house_building": "🏚",
+2936	    "diamond_shape_with_a_dot_inside": "💠",
+2937	    "dart": "🎯",
+2938	    "disappointed_relieved": "😥",
+2939	    "disappointed": "😞",
+2940	    "do_not_litter": "🚯",
+2941	    "dog2": "🐕",
+2942	    "flipper": "🐬",
+2943	    "loop": "➿",
+2944	    "bangbang": "‼",
+2945	    "double_vertical_bar": "⏸",
+2946	    "dove_of_peace": "🕊",
+2947	    "small_red_triangle_down": "🔻",
+2948	    "arrow_down_small": "🔽",
+2949	    "arrow_down": "⬇",
+2950	    "dromedary_camel": "🐪",
+2951	    "e__mail": "📧",
+2952	    "corn": "🌽",
+2953	    "ear_of_rice": "🌾",
+2954	    "earth_americas": "🌎",
+2955	    "earth_asia": "🌏",
+2956	    "earth_africa": "🌍",
+2957	    "eight_pointed_black_star": "✴",
+2958	    "eight_spoked_asterisk": "✳",
+2959	    "eject_symbol": "⏏",
+2960	    "bulb": "💡",
+2961	    "emoji_modifier_fitzpatrick_type__1__2": "🏻",
+2962	    "emoji_modifier_fitzpatrick_type__3": "🏼",
+2963	    "emoji_modifier_fitzpatrick_type__4": "🏽",
+2964	    "emoji_modifier_fitzpatrick_type__5": "🏾",
+2965	    "emoji_modifier_fitzpatrick_type__6": "🏿",
+2966	    "end": "🔚",
+2967	    "email": "✉",
+2968	    "european_castle": "🏰",
+2969	    "european_post_office": "🏤",
+2970	    "interrobang": "⁉",
+2971	    "expressionless": "😑",
+2972	    "eyeglasses": "👓",
+2973	    "massage": "💆",
+2974	    "yum": "😋",
+2975	    "scream": "😱",
+2976	    "kissing_heart": "😘",
+2977	    "sweat": "😓",
+2978	    "face_with_head__bandage": "🤕",
+2979	    "triumph": "😤",
+2980	    "mask": "😷",
+2981	    "no_good": "🙅",
+2982	    "ok_woman": "🙆",
+2983	    "open_mouth": "😮",
+2984	    "cold_sweat": "😰",
+2985	    "stuck_out_tongue": "😛",
+2986	    "stuck_out_tongue_closed_eyes": "😝",
+2987	    "stuck_out_tongue_winking_eye": "😜",
+2988	    "joy": "😂",
+2989	    "no_mouth": "😶",
+2990	    "santa": "🎅",
+2991	    "fax": "📠",
+2992	    "fearful": "😨",
+2993	    "field_hockey_stick_and_ball": "🏑",
+2994	    "first_quarter_moon_with_face": "🌛",
+2995	    "fish_cake": "🍥",
+2996	    "fishing_pole_and_fish": "🎣",
+2997	    "facepunch": "👊",
+2998	    "punch": "👊",
+2999	    "flag_for_afghanistan": "🇦🇫",
+3000	    "flag_for_albania": "🇦🇱",
+3001	    "flag_for_algeria": "🇩🇿",
+3002	    "flag_for_american_samoa": "🇦🇸",
+3003	    "flag_for_andorra": "🇦🇩",
+3004	    "flag_for_angola": "🇦🇴",
+3005	    "flag_for_anguilla": "🇦🇮",
+3006	    "flag_for_antarctica": "🇦🇶",
+3007	    "flag_for_antigua_&_barbuda": "🇦🇬",
+3008	    "flag_for_argentina": "🇦🇷",
+3009	    "flag_for_armenia": "🇦🇲",
+3010	    "flag_for_aruba": "🇦🇼",
+3011	    "flag_for_ascension_island": "🇦🇨",
+3012	    "flag_for_australia": "🇦🇺",
+3013	    "flag_for_austria": "🇦🇹",
+3014	    "flag_for_azerbaijan": "🇦🇿",
+3015	    "flag_for_bahamas": "🇧🇸",
+3016	    "flag_for_bahrain": "🇧🇭",
+3017	    "flag_for_bangladesh": "🇧🇩",
+3018	    "flag_for_barbados": "🇧🇧",
+3019	    "flag_for_belarus": "🇧🇾",
+3020	    "flag_for_belgium": "🇧🇪",
+3021	    "flag_for_belize": "🇧🇿",
+3022	    "flag_for_benin": "🇧🇯",
+3023	    "flag_for_bermuda": "🇧🇲",
+3024	    "flag_for_bhutan": "🇧🇹",
+3025	    "flag_for_bolivia": "🇧🇴",
+3026	    "flag_for_bosnia_&_herzegovina": "🇧🇦",
+3027	    "flag_for_botswana": "🇧🇼",
+3028	    "flag_for_bouvet_island": "🇧🇻",
+3029	    "flag_for_brazil": "🇧🇷",
+3030	    "flag_for_british_indian_ocean_territory": "🇮🇴",
+3031	    "flag_for_british_virgin_islands": "🇻🇬",
+3032	    "flag_for_brunei": "🇧🇳",
+3033	    "flag_for_bulgaria": "🇧🇬",
+3034	    "flag_for_burkina_faso": "🇧🇫",
+3035	    "flag_for_burundi": "🇧🇮",
+3036	    "flag_for_cambodia": "🇰🇭",
+3037	    "flag_for_cameroon": "🇨🇲",
+3038	    "flag_for_canada": "🇨🇦",
+3039	    "flag_for_canary_islands": "🇮🇨",
+3040	    "flag_for_cape_verde": "🇨🇻",
+3041	    "flag_for_caribbean_netherlands": "🇧🇶",
+3042	    "flag_for_cayman_islands": "🇰🇾",
+3043	    "flag_for_central_african_republic": "🇨🇫",
+3044	    "flag_for_ceuta_&_melilla": "🇪🇦",
+3045	    "flag_for_chad": "🇹🇩",
+3046	    "flag_for_chile": "🇨🇱",
+3047	    "flag_for_china": "🇨🇳",
+3048	    "flag_for_christmas_island": "🇨🇽",
+3049	    "flag_for_clipperton_island": "🇨🇵",
+3050	    "flag_for_cocos__islands": "🇨🇨",
+3051	    "flag_for_colombia": "🇨🇴",
+3052	    "flag_for_comoros": "🇰🇲",
+3053	    "flag_for_congo____brazzaville": "🇨🇬",
+3054	    "flag_for_congo____kinshasa": "🇨🇩",
+3055	    "flag_for_cook_islands": "🇨🇰",
+3056	    "flag_for_costa_rica": "🇨🇷",
+3057	    "flag_for_croatia": "🇭🇷",
+3058	    "flag_for_cuba": "🇨🇺",
+3059	    "flag_for_curaçao": "🇨🇼",
+3060	    "flag_for_cyprus": "🇨🇾",
+3061	    "flag_for_czech_republic": "🇨🇿",
+3062	    "flag_for_côte_d’ivoire": "🇨🇮",
+3063	    "flag_for_denmark": "🇩🇰",
+3064	    "flag_for_diego_garcia": "🇩🇬",
+3065	    "flag_for_djibouti": "🇩🇯",
+3066	    "flag_for_dominica": "🇩🇲",
+3067	    "flag_for_dominican_republic": "🇩🇴",
+3068	    "flag_for_ecuador": "🇪🇨",
+3069	    "flag_for_egypt": "🇪🇬",
+3070	    "flag_for_el_salvador": "🇸🇻",
+3071	    "flag_for_equatorial_guinea": "🇬🇶",
+3072	    "flag_for_eritrea": "🇪🇷",
+3073	    "flag_for_estonia": "🇪🇪",
+3074	    "flag_for_ethiopia": "🇪🇹",
+3075	    "flag_for_european_union": "🇪🇺",
+3076	    "flag_for_falkland_islands": "🇫🇰",
+3077	    "flag_for_faroe_islands": "🇫🇴",
+3078	    "flag_for_fiji": "🇫🇯",
+3079	    "flag_for_finland": "🇫🇮",
+3080	    "flag_for_france": "🇫🇷",
+3081	    "flag_for_french_guiana": "🇬🇫",
+3082	    "flag_for_french_polynesia": "🇵🇫",
+3083	    "flag_for_french_southern_territories": "🇹🇫",
+3084	    "flag_for_gabon": "🇬🇦",
+3085	    "flag_for_gambia": "🇬🇲",
+3086	    "flag_for_georgia": "🇬🇪",
+3087	    "flag_for_germany": "🇩🇪",
+3088	    "flag_for_ghana": "🇬🇭",
+3089	    "flag_for_gibraltar": "🇬🇮",
+3090	    "flag_for_greece": "🇬🇷",
+3091	    "flag_for_greenland": "🇬🇱",
+3092	    "flag_for_grenada": "🇬🇩",
+3093	    "flag_for_guadeloupe": "🇬🇵",
+3094	    "flag_for_guam": "🇬🇺",
+3095	    "flag_for_guatemala": "🇬🇹",
+3096	    "flag_for_guernsey": "🇬🇬",
+3097	    "flag_for_guinea": "🇬🇳",
+3098	    "flag_for_guinea__bissau": "🇬🇼",
+3099	    "flag_for_guyana": "🇬🇾",
+3100	    "flag_for_haiti": "🇭🇹",
+3101	    "flag_for_heard_&_mcdonald_islands": "🇭🇲",
+3102	    "flag_for_honduras": "🇭🇳",
+3103	    "flag_for_hong_kong": "🇭🇰",
+3104	    "flag_for_hungary": "🇭🇺",
+3105	    "flag_for_iceland": "🇮🇸",
+3106	    "flag_for_india": "🇮🇳",
+3107	    "flag_for_indonesia": "🇮🇩",
+3108	    "flag_for_iran": "🇮🇷",
+3109	    "flag_for_iraq": "🇮🇶",
+3110	    "flag_for_ireland": "🇮🇪",
+3111	    "flag_for_isle_of_man": "🇮🇲",
+3112	    "flag_for_israel": "🇮🇱",
+3113	    "flag_for_italy": "🇮🇹",
+3114	    "flag_for_jamaica": "🇯🇲",
+3115	    "flag_for_japan": "🇯🇵",
+3116	    "flag_for_jersey": "🇯🇪",
+3117	    "flag_for_jordan": "🇯🇴",
+3118	    "flag_for_kazakhstan": "🇰🇿",
+3119	    "flag_for_kenya": "🇰🇪",
+3120	    "flag_for_kiribati": "🇰🇮",
+3121	    "flag_for_kosovo": "🇽🇰",
+3122	    "flag_for_kuwait": "🇰🇼",
+3123	    "flag_for_kyrgyzstan": "🇰🇬",
+3124	    "flag_for_laos": "🇱🇦",
+3125	    "flag_for_latvia": "🇱🇻",
+3126	    "flag_for_lebanon": "🇱🇧",
+3127	    "flag_for_lesotho": "🇱🇸",
+3128	    "flag_for_liberia": "🇱🇷",
+3129	    "flag_for_libya": "🇱🇾",
+3130	    "flag_for_liechtenstein": "🇱🇮",
+3131	    "flag_for_lithuania": "🇱🇹",
+3132	    "flag_for_luxembourg": "🇱🇺",
+3133	    "flag_for_macau": "🇲🇴",
+3134	    "flag_for_macedonia": "🇲🇰",
+3135	    "flag_for_madagascar": "🇲🇬",
+3136	    "flag_for_malawi": "🇲🇼",
+3137	    "flag_for_malaysia": "🇲🇾",
+3138	    "flag_for_maldives": "🇲🇻",
+3139	    "flag_for_mali": "🇲🇱",
+3140	    "flag_for_malta": "🇲🇹",
+3141	    "flag_for_marshall_islands": "🇲🇭",
+3142	    "flag_for_martinique": "🇲🇶",
+3143	    "flag_for_mauritania": "🇲🇷",
+3144	    "flag_for_mauritius": "🇲🇺",
+3145	    "flag_for_mayotte": "🇾🇹",
+3146	    "flag_for_mexico": "🇲🇽",
+3147	    "flag_for_micronesia": "🇫🇲",
+3148	    "flag_for_moldova": "🇲🇩",
+3149	    "flag_for_monaco": "🇲🇨",
+3150	    "flag_for_mongolia": "🇲🇳",
+3151	    "flag_for_montenegro": "🇲🇪",
+3152	    "flag_for_montserrat": "🇲🇸",
+3153	    "flag_for_morocco": "🇲🇦",
+3154	    "flag_for_mozambique": "🇲🇿",
+3155	    "flag_for_myanmar": "🇲🇲",
+3156	    "flag_for_namibia": "🇳🇦",
+3157	    "flag_for_nauru": "🇳🇷",
+3158	    "flag_for_nepal": "🇳🇵",
+3159	    "flag_for_netherlands": "🇳🇱",
+3160	    "flag_for_new_caledonia": "🇳🇨",
+3161	    "flag_for_new_zealand": "🇳🇿",
+3162	    "flag_for_nicaragua": "🇳🇮",
+3163	    "flag_for_niger": "🇳🇪",
+3164	    "flag_for_nigeria": "🇳🇬",
+3165	    "flag_for_niue": "🇳🇺",
+3166	    "flag_for_norfolk_island": "🇳🇫",
+3167	    "flag_for_north_korea": "🇰🇵",
+3168	    "flag_for_northern_mariana_islands": "🇲🇵",
+3169	    "flag_for_norway": "🇳🇴",
+3170	    "flag_for_oman": "🇴🇲",
+3171	    "flag_for_pakistan": "🇵🇰",
+3172	    "flag_for_palau": "🇵🇼",
+3173	    "flag_for_palestinian_territories": "🇵🇸",
+3174	    "flag_for_panama": "🇵🇦",
+3175	    "flag_for_papua_new_guinea": "🇵🇬",
+3176	    "flag_for_paraguay": "🇵🇾",
+3177	    "flag_for_peru": "🇵🇪",
+3178	    "flag_for_philippines": "🇵🇭",
+3179	    "flag_for_pitcairn_islands": "🇵🇳",
+3180	    "flag_for_poland": "🇵🇱",
+3181	    "flag_for_portugal": "🇵🇹",
+3182	    "flag_for_puerto_rico": "🇵🇷",
+3183	    "flag_for_qatar": "🇶🇦",
+3184	    "flag_for_romania": "🇷🇴",
+3185	    "flag_for_russia": "🇷🇺",
+3186	    "flag_for_rwanda": "🇷🇼",
+3187	    "flag_for_réunion": "🇷🇪",
+3188	    "flag_for_samoa": "🇼🇸",
+3189	    "flag_for_san_marino": "🇸🇲",
+3190	    "flag_for_saudi_arabia": "🇸🇦",
+3191	    "flag_for_senegal": "🇸🇳",
+3192	    "flag_for_serbia": "🇷🇸",
+3193	    "flag_for_seychelles": "🇸🇨",
+3194	    "flag_for_sierra_leone": "🇸🇱",
+3195	    "flag_for_singapore": "🇸🇬",
+3196	    "flag_for_sint_maarten": "🇸🇽",
+3197	    "flag_for_slovakia": "🇸🇰",
+3198	    "flag_for_slovenia": "🇸🇮",
+3199	    "flag_for_solomon_islands": "🇸🇧",
+3200	    "flag_for_somalia": "🇸🇴",
+3201	    "flag_for_south_africa": "🇿🇦",
+3202	    "flag_for_south_georgia_&_south_sandwich_islands": "🇬🇸",
+3203	    "flag_for_south_korea": "🇰🇷",
+3204	    "flag_for_south_sudan": "🇸🇸",
+3205	    "flag_for_spain": "🇪🇸",
+3206	    "flag_for_sri_lanka": "🇱🇰",
+3207	    "flag_for_st._barthélemy": "🇧🇱",
+3208	    "flag_for_st._helena": "🇸🇭",
+3209	    "flag_for_st._kitts_&_nevis": "🇰🇳",
+3210	    "flag_for_st._lucia": "🇱🇨",
+3211	    "flag_for_st._martin": "🇲🇫",
+3212	    "flag_for_st._pierre_&_miquelon": "🇵🇲",
+3213	    "flag_for_st._vincent_&_grenadines": "🇻🇨",
+3214	    "flag_for_sudan": "🇸🇩",
+3215	    "flag_for_suriname": "🇸🇷",
+3216	    "flag_for_svalbard_&_jan_mayen": "🇸🇯",
+3217	    "flag_for_swaziland": "🇸🇿",
+3218	    "flag_for_sweden": "🇸🇪",
+3219	    "flag_for_switzerland": "🇨🇭",
+3220	    "flag_for_syria": "🇸🇾",
+3221	    "flag_for_são_tomé_&_príncipe": "🇸🇹",
+3222	    "flag_for_taiwan": "🇹🇼",
+3223	    "flag_for_tajikistan": "🇹🇯",
+3224	    "flag_for_tanzania": "🇹🇿",
+3225	    "flag_for_thailand": "🇹🇭",
+3226	    "flag_for_timor__leste": "🇹🇱",
+3227	    "flag_for_togo": "🇹🇬",
+3228	    "flag_for_tokelau": "🇹🇰",
+3229	    "flag_for_tonga": "🇹🇴",
+3230	    "flag_for_trinidad_&_tobago": "🇹🇹",
+3231	    "flag_for_tristan_da_cunha": "🇹🇦",
+3232	    "flag_for_tunisia": "🇹🇳",
+3233	    "flag_for_turkey": "🇹🇷",
+3234	    "flag_for_turkmenistan": "🇹🇲",
+3235	    "flag_for_turks_&_caicos_islands": "🇹🇨",
+3236	    "flag_for_tuvalu": "🇹🇻",
+3237	    "flag_for_u.s._outlying_islands": "🇺🇲",
+3238	    "flag_for_u.s._virgin_islands": "🇻🇮",
+3239	    "flag_for_uganda": "🇺🇬",
+3240	    "flag_for_ukraine": "🇺🇦",
+3241	    "flag_for_united_arab_emirates": "🇦🇪",
+3242	    "flag_for_united_kingdom": "🇬🇧",
+3243	    "flag_for_united_states": "🇺🇸",
+3244	    "flag_for_uruguay": "🇺🇾",
+3245	    "flag_for_uzbekistan": "🇺🇿",
+3246	    "flag_for_vanuatu": "🇻🇺",
+3247	    "flag_for_vatican_city": "🇻🇦",
+3248	    "flag_for_venezuela": "🇻🇪",
+3249	    "flag_for_vietnam": "🇻🇳",
+3250	    "flag_for_wallis_&_futuna": "🇼🇫",
+3251	    "flag_for_western_sahara": "🇪🇭",
+3252	    "flag_for_yemen": "🇾🇪",
+3253	    "flag_for_zambia": "🇿🇲",
+3254	    "flag_for_zimbabwe": "🇿🇼",
+3255	    "flag_for_åland_islands": "🇦🇽",
+3256	    "golf": "⛳",
+3257	    "fleur__de__lis": "⚜",
+3258	    "muscle": "💪",
+3259	    "flushed": "😳",
+3260	    "frame_with_picture": "🖼",
+3261	    "fries": "🍟",
+3262	    "frog": "🐸",
+3263	    "hatched_chick": "🐥",
+3264	    "frowning": "😦",
+3265	    "fuelpump": "⛽",
+3266	    "full_moon_with_face": "🌝",
+3267	    "gem": "💎",
+3268	    "star2": "🌟",
+3269	    "golfer": "🏌",
+3270	    "mortar_board": "🎓",
+3271	    "grimacing": "😬",
+3272	    "smile_cat": "😸",
+3273	    "grinning": "😀",
+3274	    "grin": "😁",
+3275	    "heartpulse": "💗",
+3276	    "guardsman": "💂",
+3277	    "haircut": "💇",
+3278	    "hamster": "🐹",
+3279	    "raising_hand": "🙋",
+3280	    "headphones": "🎧",
+3281	    "hear_no_evil": "🙉",
+3282	    "cupid": "💘",
+3283	    "gift_heart": "💝",
+3284	    "heart": "❤",
+3285	    "exclamation": "❗",
+3286	    "heavy_exclamation_mark": "❗",
+3287	    "heavy_heart_exclamation_mark_ornament": "❣",
+3288	    "o": "⭕",
+3289	    "helm_symbol": "⎈",
+3290	    "helmet_with_white_cross": "⛑",
+3291	    "high_heel": "👠",
+3292	    "bullettrain_side": "🚄",
+3293	    "bullettrain_front": "🚅",
+3294	    "high_brightness": "🔆",
+3295	    "zap": "⚡",
+3296	    "hocho": "🔪",
+3297	    "knife": "🔪",
+3298	    "bee": "🐝",
+3299	    "traffic_light": "🚥",
+3300	    "racehorse": "🐎",
+3301	    "coffee": "☕",
+3302	    "hotsprings": "♨",
+3303	    "hourglass": "⌛",
+3304	    "hourglass_flowing_sand": "⏳",
+3305	    "house_buildings": "🏘",
+3306	    "100": "💯",
+3307	    "hushed": "😯",
+3308	    "ice_hockey_stick_and_puck": "🏒",
+3309	    "imp": "👿",
+3310	    "information_desk_person": "💁",
+3311	    "information_source": "ℹ",
+3312	    "capital_abcd": "🔠",
+3313	    "abc": "🔤",
+3314	    "abcd": "🔡",
+3315	    "1234": "🔢",
+3316	    "symbols": "🔣",
+3317	    "izakaya_lantern": "🏮",
+3318	    "lantern": "🏮",
+3319	    "jack_o_lantern": "🎃",
+3320	    "dolls": "🎎",
+3321	    "japanese_goblin": "👺",
+3322	    "japanese_ogre": "👹",
+3323	    "beginner": "🔰",
+3324	    "zero": "0️⃣",
+3325	    "one": "1️⃣",
+3326	    "ten": "🔟",
+3327	    "two": "2️⃣",
+3328	    "three": "3️⃣",
+3329	    "four": "4️⃣",
+3330	    "five": "5️⃣",
+3331	    "six": "6️⃣",
+3332	    "seven": "7️⃣",
+3333	    "eight": "8️⃣",
+3334	    "nine": "9️⃣",
+3335	    "couplekiss": "💏",
+3336	    "kissing_cat": "😽",
+3337	    "kissing": "😗",
+3338	    "kissing_closed_eyes": "😚",
+3339	    "kissing_smiling_eyes": "😙",
+3340	    "beetle": "🐞",
+3341	    "large_blue_circle": "🔵",
+3342	    "last_quarter_moon_with_face": "🌜",
+3343	    "leaves": "🍃",
+3344	    "mag": "🔍",
+3345	    "left_right_arrow": "↔",
+3346	    "leftwards_arrow_with_hook": "↩",
+3347	    "arrow_left": "⬅",
+3348	    "lock": "🔒",
+3349	    "lock_with_ink_pen": "🔏",
+3350	    "sob": "😭",
+3351	    "low_brightness": "🔅",
+3352	    "lower_left_ballpoint_pen": "🖊",
+3353	    "lower_left_crayon": "🖍",
+3354	    "lower_left_fountain_pen": "🖋",
+3355	    "lower_left_paintbrush": "🖌",
+3356	    "mahjong": "🀄",
+3357	    "couple": "👫",
+3358	    "man_in_business_suit_levitating": "🕴",
+3359	    "man_with_gua_pi_mao": "👲",
+3360	    "man_with_turban": "👳",
+3361	    "mans_shoe": "👞",
+3362	    "shoe": "👞",
+3363	    "menorah_with_nine_branches": "🕎",
+3364	    "mens": "🚹",
+3365	    "minidisc": "💽",
+3366	    "iphone": "📱",
+3367	    "calling": "📲",
+3368	    "money__mouth_face": "🤑",
+3369	    "moneybag": "💰",
+3370	    "rice_scene": "🎑",
+3371	    "mountain_bicyclist": "🚵",
+3372	    "mouse2": "🐁",
+3373	    "lips": "👄",
+3374	    "moyai": "🗿",
+3375	    "notes": "🎶",
+3376	    "nail_care": "💅",
+3377	    "ab": "🆎",
+3378	    "negative_squared_cross_mark": "❎",
+3379	    "a": "🅰",
+3380	    "b": "🅱",
+3381	    "o2": "🅾",
+3382	    "parking": "🅿",
+3383	    "new_moon_with_face": "🌚",
+3384	    "no_entry_sign": "🚫",
+3385	    "underage": "🔞",
+3386	    "non__potable_water": "🚱",
+3387	    "arrow_upper_right": "↗",
+3388	    "arrow_upper_left": "↖",
+3389	    "office": "🏢",
+3390	    "older_man": "👴",
+3391	    "older_woman": "👵",
+3392	    "om_symbol": "🕉",
+3393	    "on": "🔛",
+3394	    "book": "📖",
+3395	    "unlock": "🔓",
+3396	    "mailbox_with_no_mail": "📭",
+3397	    "mailbox_with_mail": "📬",
+3398	    "cd": "💿",
+3399	    "tada": "🎉",
+3400	    "feet": "🐾",
+3401	    "walking": "🚶",
+3402	    "pencil2": "✏",
+3403	    "pensive": "😔",
+3404	    "persevere": "😣",
+3405	    "bow": "🙇",
+3406	    "raised_hands": "🙌",
+3407	    "person_with_ball": "⛹",
+3408	    "person_with_blond_hair": "👱",
+3409	    "pray": "🙏",
+3410	    "person_with_pouting_face": "🙎",
+3411	    "computer": "💻",
+3412	    "pig2": "🐖",
+3413	    "hankey": "💩",
+3414	    "poop": "💩",
+3415	    "shit": "💩",
+3416	    "bamboo": "🎍",
+3417	    "gun": "🔫",
+3418	    "black_joker": "🃏",
+3419	    "rotating_light": "🚨",
+3420	    "cop": "👮",
+3421	    "stew": "🍲",
+3422	    "pouch": "👝",
+3423	    "pouting_cat": "😾",
+3424	    "rage": "😡",
+3425	    "put_litter_in_its_place": "🚮",
+3426	    "rabbit2": "🐇",
+3427	    "racing_motorcycle": "🏍",
+3428	    "radioactive_sign": "☢",
+3429	    "fist": "✊",
+3430	    "hand": "✋",
+3431	    "raised_hand_with_fingers_splayed": "🖐",
+3432	    "raised_hand_with_part_between_middle_and_ring_fingers": "🖖",
+3433	    "blue_car": "🚙",
+3434	    "apple": "🍎",
+3435	    "relieved": "😌",
+3436	    "reversed_hand_with_middle_finger_extended": "🖕",
+3437	    "mag_right": "🔎",
+3438	    "arrow_right_hook": "↪",
+3439	    "sweet_potato": "🍠",
+3440	    "robot": "🤖",
+3441	    "rolled__up_newspaper": "🗞",
+3442	    "rowboat": "🚣",
+3443	    "runner": "🏃",
+3444	    "running": "🏃",
+3445	    "running_shirt_with_sash": "🎽",
+3446	    "boat": "⛵",
+3447	    "scales": "⚖",
+3448	    "school_satchel": "🎒",
+3449	    "scorpius": "♏",
+3450	    "see_no_evil": "🙈",
+3451	    "sheep": "🐑",
+3452	    "stars": "🌠",
+3453	    "cake": "🍰",
+3454	    "six_pointed_star": "🔯",
+3455	    "ski": "🎿",
+3456	    "sleeping_accommodation": "🛌",
+3457	    "sleeping": "😴",
+3458	    "sleepy": "😪",
+3459	    "sleuth_or_spy": "🕵",
+3460	    "heart_eyes_cat": "😻",
+3461	    "smiley_cat": "😺",
+3462	    "innocent": "😇",
+3463	    "heart_eyes": "😍",
+3464	    "smiling_imp": "😈",
+3465	    "smiley": "😃",
+3466	    "sweat_smile": "😅",
+3467	    "smile": "😄",
+3468	    "laughing": "😆",
+3469	    "satisfied": "😆",
+3470	    "blush": "😊",
+3471	    "smirk": "😏",
+3472	    "smoking": "🚬",
+3473	    "snow_capped_mountain": "🏔",
+3474	    "soccer": "⚽",
+3475	    "icecream": "🍦",
+3476	    "soon": "🔜",
+3477	    "arrow_lower_right": "↘",
+3478	    "arrow_lower_left": "↙",
+3479	    "speak_no_evil": "🙊",
+3480	    "speaker": "🔈",
+3481	    "mute": "🔇",
+3482	    "sound": "🔉",
+3483	    "loud_sound": "🔊",
+3484	    "speaking_head_in_silhouette": "🗣",
+3485	    "spiral_calendar_pad": "🗓",
+3486	    "spiral_note_pad": "🗒",
+3487	    "shell": "🐚",
+3488	    "sweat_drops": "💦",
+3489	    "u5272": "🈹",
+3490	    "u5408": "🈴",
+3491	    "u55b6": "🈺",
+3492	    "u6307": "🈯",
+3493	    "u6708": "🈷",
+3494	    "u6709": "🈶",
+3495	    "u6e80": "🈵",
+3496	    "u7121": "🈚",
+3497	    "u7533": "🈸",
+3498	    "u7981": "🈲",
+3499	    "u7a7a": "🈳",
+3500	    "cl": "🆑",
+3501	    "cool": "🆒",
+3502	    "free": "🆓",
+3503	    "id": "🆔",
+3504	    "koko": "🈁",
+3505	    "sa": "🈂",
+3506	    "new": "🆕",
+3507	    "ng": "🆖",
+3508	    "ok": "🆗",
+3509	    "sos": "🆘",
+3510	    "up": "🆙",
+3511	    "vs": "🆚",
+3512	    "steam_locomotive": "🚂",
+3513	    "ramen": "🍜",
+3514	    "partly_sunny": "⛅",
+3515	    "city_sunrise": "🌇",
+3516	    "surfer": "🏄",
+3517	    "swimmer": "🏊",
+3518	    "shirt": "👕",
+3519	    "tshirt": "👕",
+3520	    "table_tennis_paddle_and_ball": "🏓",
+3521	    "tea": "🍵",
+3522	    "tv": "📺",
+3523	    "three_button_mouse": "🖱",
+3524	    "+1": "👍",
+3525	    "thumbsup": "👍",
+3526	    "__1": "👎",
+3527	    "-1": "👎",
+3528	    "thumbsdown": "👎",
+3529	    "thunder_cloud_and_rain": "⛈",
+3530	    "tiger2": "🐅",
+3531	    "tophat": "🎩",
+3532	    "top": "🔝",
+3533	    "tm": "™",
+3534	    "train2": "🚆",
+3535	    "triangular_flag_on_post": "🚩",
+3536	    "trident": "🔱",
+3537	    "twisted_rightwards_arrows": "🔀",
+3538	    "unamused": "😒",
+3539	    "small_red_triangle": "🔺",
+3540	    "arrow_up_small": "🔼",
+3541	    "arrow_up_down": "↕",
+3542	    "upside__down_face": "🙃",
+3543	    "arrow_up": "⬆",
+3544	    "v": "✌",
+3545	    "vhs": "📼",
+3546	    "wc": "🚾",
+3547	    "ocean": "🌊",
+3548	    "waving_black_flag": "🏴",
+3549	    "wave": "👋",
+3550	    "waving_white_flag": "🏳",
+3551	    "moon": "🌔",
+3552	    "scream_cat": "🙀",
+3553	    "weary": "😩",
+3554	    "weight_lifter": "🏋",
+3555	    "whale2": "🐋",
+3556	    "wheelchair": "♿",
+3557	    "point_down": "👇",
+3558	    "grey_exclamation": "❕",
+3559	    "white_frowning_face": "☹",
+3560	    "white_check_mark": "✅",
+3561	    "point_left": "👈",
+3562	    "white_medium_small_square": "◽",
+3563	    "star": "⭐",
+3564	    "grey_question": "❔",
+3565	    "point_right": "👉",
+3566	    "relaxed": "☺",
+3567	    "white_sun_behind_cloud": "🌥",
+3568	    "white_sun_behind_cloud_with_rain": "🌦",
+3569	    "white_sun_with_small_cloud": "🌤",
+3570	    "point_up_2": "👆",
+3571	    "point_up": "☝",
+3572	    "wind_blowing_face": "🌬",
+3573	    "wink": "😉",
+3574	    "wolf": "🐺",
+3575	    "dancers": "👯",
+3576	    "boot": "👢",
+3577	    "womans_clothes": "👚",
+3578	    "womans_hat": "👒",
+3579	    "sandal": "👡",
+3580	    "womens": "🚺",
+3581	    "worried": "😟",
+3582	    "gift": "🎁",
+3583	    "zipper__mouth_face": "🤐",
+3584	    "regional_indicator_a": "🇦",
+3585	    "regional_indicator_b": "🇧",
+3586	    "regional_indicator_c": "🇨",
+3587	    "regional_indicator_d": "🇩",
+3588	    "regional_indicator_e": "🇪",
+3589	    "regional_indicator_f": "🇫",
+3590	    "regional_indicator_g": "🇬",
+3591	    "regional_indicator_h": "🇭",
+3592	    "regional_indicator_i": "🇮",
+3593	    "regional_indicator_j": "🇯",
+3594	    "regional_indicator_k": "🇰",
+3595	    "regional_indicator_l": "🇱",
+3596	    "regional_indicator_m": "🇲",
+3597	    "regional_indicator_n": "🇳",
+3598	    "regional_indicator_o": "🇴",
+3599	    "regional_indicator_p": "🇵",
+3600	    "regional_indicator_q": "🇶",
+3601	    "regional_indicator_r": "🇷",
+3602	    "regional_indicator_s": "🇸",
+3603	    "regional_indicator_t": "🇹",
+3604	    "regional_indicator_u": "🇺",
+3605	    "regional_indicator_v": "🇻",
+3606	    "regional_indicator_w": "🇼",
+3607	    "regional_indicator_x": "🇽",
+3608	    "regional_indicator_y": "🇾",
+3609	    "regional_indicator_z": "🇿",
+3610	}
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/rich/_pick.py
+ Line number: 13
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+12	    """
+13	    assert values, "1 or more values required"
+14	    for value in values:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/rich/_ratio.py
+ Line number: 123
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+122	    total_ratio = sum(ratios)
+123	    assert total_ratio > 0, "Sum of ratios must be > 0"
+124	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/rich/_unicode_data/__init__.py
+ Line number: 92
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+91	    if TYPE_CHECKING:
+92	        assert isinstance(module.cell_table, CellTable)
+93	    return module.cell_table
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/rich/_win32_console.py
+ Line number: 435
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+434	
+435	        assert fore is not None
+436	        assert back is not None
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/rich/_win32_console.py
+ Line number: 436
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+435	        assert fore is not None
+436	        assert back is not None
+437	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/rich/_win32_console.py
+ Line number: 565
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+564	        """
+565	        assert len(title) < 255, "Console title must be less than 255 characters"
+566	        SetConsoleTitle(title)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/rich/color.py
+ Line number: 365
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+364	        if self.type == ColorType.TRUECOLOR:
+365	            assert self.triplet is not None
+366	            return self.triplet
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/rich/color.py
+ Line number: 368
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+367	        elif self.type == ColorType.EIGHT_BIT:
+368	            assert self.number is not None
+369	            return EIGHT_BIT_PALETTE[self.number]
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/rich/color.py
+ Line number: 371
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+370	        elif self.type == ColorType.STANDARD:
+371	            assert self.number is not None
+372	            return theme.ansi_colors[self.number]
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/rich/color.py
+ Line number: 374
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+373	        elif self.type == ColorType.WINDOWS:
+374	            assert self.number is not None
+375	            return WINDOWS_PALETTE[self.number]
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/rich/color.py
+ Line number: 377
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+376	        else:  # self.type == ColorType.DEFAULT:
+377	            assert self.number is None
+378	            return theme.foreground_color if foreground else theme.background_color
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/rich/color.py
+ Line number: 493
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+492	            number = self.number
+493	            assert number is not None
+494	            fore, back = (30, 40) if number < 8 else (82, 92)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/rich/color.py
+ Line number: 499
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+498	            number = self.number
+499	            assert number is not None
+500	            fore, back = (30, 40) if number < 8 else (82, 92)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/rich/color.py
+ Line number: 504
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+503	        elif _type == ColorType.EIGHT_BIT:
+504	            assert self.number is not None
+505	            return ("38" if foreground else "48", "5", str(self.number))
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/rich/color.py
+ Line number: 508
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+507	        else:  # self.standard == ColorStandard.TRUECOLOR:
+508	            assert self.triplet is not None
+509	            red, green, blue = self.triplet
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/rich/color.py
+ Line number: 520
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+519	        if system == ColorSystem.EIGHT_BIT and self.system == ColorSystem.TRUECOLOR:
+520	            assert self.triplet is not None
+521	            _h, l, s = rgb_to_hls(*self.triplet.normalized)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/rich/color.py
+ Line number: 546
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+545	            if self.system == ColorSystem.TRUECOLOR:
+546	                assert self.triplet is not None
+547	                triplet = self.triplet
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/rich/color.py
+ Line number: 549
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+548	            else:  # self.system == ColorSystem.EIGHT_BIT
+549	                assert self.number is not None
+550	                triplet = ColorTriplet(*EIGHT_BIT_PALETTE[self.number])
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/rich/color.py
+ Line number: 557
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+556	            if self.system == ColorSystem.TRUECOLOR:
+557	                assert self.triplet is not None
+558	                triplet = self.triplet
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/rich/color.py
+ Line number: 560
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+559	            else:  # self.system == ColorSystem.EIGHT_BIT
+560	                assert self.number is not None
+561	                if self.number < 16:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/rich/color.py
+ Line number: 573
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+572	    """Parse six hex characters in to RGB triplet."""
+573	    assert len(hex_color) == 6, "must be 6 characters"
+574	    color = ColorTriplet(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/rich/console.py
+ Line number: 1149
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1148	
+1149	        assert count >= 0, "count must be >= 0"
+1150	        self.print(NewLine(count))
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/rich/console.py
+ Line number: 1929
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1928	                offset -= 1
+1929	            assert frame is not None
+1930	            return frame.f_code.co_filename, frame.f_lineno, frame.f_locals
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/rich/console.py
+ Line number: 2189
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2188	        """
+2189	        assert (
+2190	            self.record
+2191	        ), "To export console contents set record=True in the constructor or instance"
+2192	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/rich/console.py
+ Line number: 2245
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2244	        """
+2245	        assert (
+2246	            self.record
+2247	        ), "To export console contents set record=True in the constructor or instance"
+2248	        fragments: List[str] = []
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/rich/live.py
+ Line number: 71
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+70	    ) -> None:
+71	        assert refresh_per_second > 0, "refresh_per_second must be > 0"
+72	        self._renderable = renderable
+
+
+ + +
+
+ +
+
+ blacklist: Standard pseudo-random generators are not suitable for security/cryptographic purposes.
+ Test ID: B311
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-330
+ File: ./venv/lib/python3.12/site-packages/rich/live.py
+ Line number: 381
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b311-random
+ +
+
+380	                time.sleep(0.4)
+381	                if random.randint(0, 10) < 1:
+382	                    console.log(next(examples))
+
+
+ + +
+
+ +
+
+ blacklist: Standard pseudo-random generators are not suitable for security/cryptographic purposes.
+ Test ID: B311
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-330
+ File: ./venv/lib/python3.12/site-packages/rich/live.py
+ Line number: 384
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b311-random
+ +
+
+383	                exchange_rate_dict[(select_exchange, exchange)] = 200 / (
+384	                    (random.random() * 320) + 1
+385	                )
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/rich/logging.py
+ Line number: 142
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+141	            exc_type, exc_value, exc_traceback = record.exc_info
+142	            assert exc_type is not None
+143	            assert exc_value is not None
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/rich/logging.py
+ Line number: 143
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+142	            assert exc_type is not None
+143	            assert exc_value is not None
+144	            traceback = Traceback.from_exception(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/rich/markdown.py
+ Line number: 279
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+278	    def on_child_close(self, context: MarkdownContext, child: MarkdownElement) -> bool:
+279	        assert isinstance(child, TableRowElement)
+280	        self.row = child
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/rich/markdown.py
+ Line number: 291
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+290	    def on_child_close(self, context: MarkdownContext, child: MarkdownElement) -> bool:
+291	        assert isinstance(child, TableRowElement)
+292	        self.rows.append(child)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/rich/markdown.py
+ Line number: 303
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+302	    def on_child_close(self, context: MarkdownContext, child: MarkdownElement) -> bool:
+303	        assert isinstance(child, TableDataElement)
+304	        self.cells.append(child)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/rich/markdown.py
+ Line number: 326
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+325	
+326	        assert justify in get_args(JustifyMethod)
+327	        return cls(justify=justify)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/rich/markdown.py
+ Line number: 352
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+351	    def on_child_close(self, context: MarkdownContext, child: MarkdownElement) -> bool:
+352	        assert isinstance(child, ListItem)
+353	        self.items.append(child)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/rich/markdown.py
+ Line number: 623
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+622	                    element = context.stack.pop()
+623	                    assert isinstance(element, Link)
+624	                    link_style = console.get_style("markdown.link", default="none")
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/rich/pretty.py
+ Line number: 198
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+197	    console = console or get_console()
+198	    assert console is not None
+199	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/rich/pretty.py
+ Line number: 203
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+202	        if value is not None:
+203	            assert console is not None
+204	            builtins._ = None  # type: ignore[attr-defined]
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/rich/pretty.py
+ Line number: 516
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+515	        )
+516	        assert self.node is not None
+517	        return self.node.check_length(start_length, max_length)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/rich/pretty.py
+ Line number: 522
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+521	        node = self.node
+522	        assert node is not None
+523	        whitespace = self.whitespace
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/rich/pretty.py
+ Line number: 524
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+523	        whitespace = self.whitespace
+524	        assert node.children
+525	        if node.key_repr:
+
+
+ + +
+
+ +
+
+ try_except_pass: Try, Except, Pass detected.
+ Test ID: B110
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/rich/pretty.py
+ Line number: 661
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b110_try_except_pass.html
+ +
+
+660	                    rich_repr_result = obj.__rich_repr__()
+661	            except Exception:
+662	                pass
+663	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/rich/progress.py
+ Line number: 1091
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1090	    ) -> None:
+1091	        assert refresh_per_second > 0, "refresh_per_second must be > 0"
+1092	        self._lock = RLock()
+
+
+ + +
+
+ +
+
+ blacklist: Standard pseudo-random generators are not suitable for security/cryptographic purposes.
+ Test ID: B311
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-330
+ File: ./venv/lib/python3.12/site-packages/rich/progress.py
+ Line number: 1715
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b311-random
+ +
+
+1714	            time.sleep(0.01)
+1715	            if random.randint(0, 100) < 1:
+1716	                progress.log(next(examples))
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/rich/prompt.py
+ Line number: 222
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+221	        """
+222	        assert self.choices is not None
+223	        if self.case_sensitive:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/rich/segment.py
+ Line number: 171
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+170	        text, style, control = self
+171	        assert cut >= 0
+172	
+
+
+ + +
+
+ +
+
+ blacklist: Consider possible security implications associated with dumps module.
+ Test ID: B403
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-502
+ File: ./venv/lib/python3.12/site-packages/rich/style.py
+ Line number: 4
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_imports.html#b403-import-pickle
+ +
+
+3	from operator import attrgetter
+4	from pickle import dumps, loads
+5	from random import randint
+
+
+ + +
+
+ +
+
+ blacklist: Standard pseudo-random generators are not suitable for security/cryptographic purposes.
+ Test ID: B311
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-330
+ File: ./venv/lib/python3.12/site-packages/rich/style.py
+ Line number: 198
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b311-random
+ +
+
+197	        self._link_id = (
+198	            f"{randint(0, 999999)}{hash(self._meta)}" if (link or meta) else ""
+199	        )
+
+
+ + +
+
+ +
+
+ blacklist: Standard pseudo-random generators are not suitable for security/cryptographic purposes.
+ Test ID: B311
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-330
+ File: ./venv/lib/python3.12/site-packages/rich/style.py
+ Line number: 248
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b311-random
+ +
+
+247	        style._meta = dumps(meta)
+248	        style._link_id = f"{randint(0, 999999)}{hash(style._meta)}"
+249	        style._hash = None
+
+
+ + +
+
+ +
+
+ blacklist: Pickle and modules that wrap it can be unsafe when used to deserialize untrusted data, possible security issue.
+ Test ID: B301
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-502
+ File: ./venv/lib/python3.12/site-packages/rich/style.py
+ Line number: 471
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b301-pickle
+ +
+
+470	        """Get meta information (can not be changed after construction)."""
+471	        return {} if self._meta is None else cast(Dict[str, Any], loads(self._meta))
+472	
+
+
+ + +
+
+ +
+
+ blacklist: Standard pseudo-random generators are not suitable for security/cryptographic purposes.
+ Test ID: B311
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-330
+ File: ./venv/lib/python3.12/site-packages/rich/style.py
+ Line number: 486
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b311-random
+ +
+
+485	        style._link = self._link
+486	        style._link_id = f"{randint(0, 999999)}" if self._link else ""
+487	        style._null = False
+
+
+ + +
+
+ +
+
+ blacklist: Standard pseudo-random generators are not suitable for security/cryptographic purposes.
+ Test ID: B311
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-330
+ File: ./venv/lib/python3.12/site-packages/rich/style.py
+ Line number: 638
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b311-random
+ +
+
+637	        style._link = self._link
+638	        style._link_id = f"{randint(0, 999999)}" if self._link else ""
+639	        style._hash = self._hash
+
+
+ + +
+
+ +
+
+ blacklist: Standard pseudo-random generators are not suitable for security/cryptographic purposes.
+ Test ID: B311
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-330
+ File: ./venv/lib/python3.12/site-packages/rich/style.py
+ Line number: 684
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b311-random
+ +
+
+683	        style._link = link
+684	        style._link_id = f"{randint(0, 999999)}" if link else ""
+685	        style._hash = None
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/rich/syntax.py
+ Line number: 507
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+506	                    """Split tokens to one per line."""
+507	                    assert lexer  # required to make MyPy happy - we know lexer is not None at this point
+508	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/rich/text.py
+ Line number: 907
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+906	        """
+907	        assert len(character) == 1, "Character must be a string of length 1"
+908	        if count:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/rich/text.py
+ Line number: 924
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+923	        """
+924	        assert len(character) == 1, "Character must be a string of length 1"
+925	        if count:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/rich/text.py
+ Line number: 940
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+939	        """
+940	        assert len(character) == 1, "Character must be a string of length 1"
+941	        if count:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/rich/text.py
+ Line number: 1079
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1078	        """
+1079	        assert separator, "separator must not be empty"
+1080	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/rich/traceback.py
+ Line number: 342
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+341	            if not isinstance(suppress_entity, str):
+342	                assert (
+343	                    suppress_entity.__file__ is not None
+344	                ), f"{suppress_entity!r} must be a module with '__file__' attribute"
+345	                path = os.path.dirname(suppress_entity.__file__)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/rich/traceback.py
+ Line number: 798
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+797	            if excluded:
+798	                assert exclude_frames is not None
+799	                yield Text(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/mssql/base.py
+ Line number: 1885
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1884	            if TYPE_CHECKING:
+1885	                assert is_sql_compiler(self.compiled)
+1886	                assert isinstance(self.compiled.compile_state, DMLState)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/mssql/base.py
+ Line number: 1886
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1885	                assert is_sql_compiler(self.compiled)
+1886	                assert isinstance(self.compiled.compile_state, DMLState)
+1887	                assert isinstance(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/mssql/base.py
+ Line number: 1887
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1886	                assert isinstance(self.compiled.compile_state, DMLState)
+1887	                assert isinstance(
+1888	                    self.compiled.compile_state.dml_table, TableClause
+1889	                )
+1890	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/mssql/base.py
+ Line number: 1969
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1968	            if TYPE_CHECKING:
+1969	                assert is_sql_compiler(self.compiled)
+1970	                assert isinstance(self.compiled.compile_state, DMLState)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/mssql/base.py
+ Line number: 1970
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1969	                assert is_sql_compiler(self.compiled)
+1970	                assert isinstance(self.compiled.compile_state, DMLState)
+1971	                assert isinstance(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/mssql/base.py
+ Line number: 1971
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1970	                assert isinstance(self.compiled.compile_state, DMLState)
+1971	                assert isinstance(
+1972	                    self.compiled.compile_state.dml_table, TableClause
+1973	                )
+1974	            conn._cursor_execute(
+
+
+ + +
+
+ +
+
+ try_except_pass: Try, Except, Pass detected.
+ Test ID: B110
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/mssql/base.py
+ Line number: 2000
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b110_try_except_pass.html
+ +
+
+1999	                )
+2000	            except Exception:
+2001	                pass
+2002	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/mssql/base.py
+ Line number: 2339
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2338	        else:
+2339	            assert False, "expected Insert, Update or Delete statement"
+2340	
+
+
+ + +
+
+ +
+
+ hardcoded_password_string: Possible hardcoded password: '['
+ Test ID: B105
+ Severity: LOW
+ Confidence: MEDIUM
+ CWE: CWE-259
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/mssql/base.py
+ Line number: 2973
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b105_hardcoded_password_string.html
+ +
+
+2972	            continue
+2973	        if token == "[":
+2974	            bracket = True
+
+
+ + +
+
+ +
+
+ hardcoded_password_string: Possible hardcoded password: ']'
+ Test ID: B105
+ Severity: LOW
+ Confidence: MEDIUM
+ CWE: CWE-259
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/mssql/base.py
+ Line number: 2976
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b105_hardcoded_password_string.html
+ +
+
+2975	            has_brackets = True
+2976	        elif token == "]":
+2977	            bracket = False
+
+
+ + +
+
+ +
+
+ hardcoded_password_string: Possible hardcoded password: '.'
+ Test ID: B105
+ Severity: LOW
+ Confidence: MEDIUM
+ CWE: CWE-259
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/mssql/base.py
+ Line number: 2978
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b105_hardcoded_password_string.html
+ +
+
+2977	            bracket = False
+2978	        elif not bracket and token == ".":
+2979	            if has_brackets:
+
+
+ + +
+
+ +
+
+ hardcoded_sql_expressions: Possible SQL injection vector through string-based query construction.
+ Test ID: B608
+ Severity: MEDIUM
+ Confidence: MEDIUM
+ CWE: CWE-89
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/mssql/base.py
+ Line number: 3210
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b608_hardcoded_sql_expressions.html
+ +
+
+3209	                (
+3210	                    "SELECT name FROM {} WHERE name IN "
+3211	                    "('dm_exec_sessions', 'dm_pdw_nodes_exec_sessions')"
+3212	                ).format(view_name)
+3213	            )
+3214	            row = cursor.fetchone()
+
+
+ + +
+
+ +
+
+ hardcoded_sql_expressions: Possible SQL injection vector through string-based query construction.
+ Test ID: B608
+ Severity: MEDIUM
+ Confidence: MEDIUM
+ CWE: CWE-89
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/mssql/base.py
+ Line number: 3224
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b608_hardcoded_sql_expressions.html
+ +
+
+3223	            cursor.execute(
+3224	                """
+3225	                    SELECT CASE transaction_isolation_level
+3226	                    WHEN 0 THEN NULL
+3227	                    WHEN 1 THEN 'READ UNCOMMITTED'
+3228	                    WHEN 2 THEN 'READ COMMITTED'
+3229	                    WHEN 3 THEN 'REPEATABLE READ'
+3230	                    WHEN 4 THEN 'SERIALIZABLE'
+3231	                    WHEN 5 THEN 'SNAPSHOT' END
+3232	                    AS TRANSACTION_ISOLATION_LEVEL
+3233	                    FROM {}
+3234	                    where session_id = @@SPID
+3235	                """.format(
+3236	                    view_name
+
+
+ + +
+
+ +
+
+ hardcoded_sql_expressions: Possible SQL injection vector through string-based query construction.
+ Test ID: B608
+ Severity: MEDIUM
+ Confidence: LOW
+ CWE: CWE-89
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/mssql/base.py
+ Line number: 3436
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b608_hardcoded_sql_expressions.html
+ +
+
+3435	            sql.text(
+3436	                f"""
+3437	select
+3438	    ind.index_id,
+3439	    ind.is_unique,
+3440	    ind.name,
+3441	    ind.type,
+3442	    {filter_definition}
+3443	from
+3444	    sys.indexes as ind
+3445	join sys.tables as tab on
+3446	    ind.object_id = tab.object_id
+3447	join sys.schemas as sch on
+3448	    sch.schema_id = tab.schema_id
+3449	where
+3450	    tab.name = :tabname
+3451	    and sch.name = :schname
+3452	    and ind.is_primary_key = 0
+3453	    and ind.type != 0
+3454	order by
+3455	    ind.name
+3456	                """
+3457	            )
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/mysql/aiomysql.py
+ Line number: 95
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+94	    def ping(self, reconnect: bool) -> None:
+95	        assert not reconnect
+96	        self.await_(self._connection.ping(reconnect))
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/mysql/asyncmy.py
+ Line number: 94
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+93	    def ping(self, reconnect: bool) -> None:
+94	        assert not reconnect
+95	        return self.await_(self._do_ping())
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/mysql/base.py
+ Line number: 1771
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1770	    ) -> str:
+1771	        assert select._for_update_arg is not None
+1772	        if select._for_update_arg.read:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/mysql/base.py
+ Line number: 1836
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1835	        else:
+1836	            assert limit_clause is not None
+1837	            # No offset provided, so just use the limit
+
+
+ + +
+
+ +
+
+ hardcoded_sql_expressions: Possible SQL injection vector through string-based query construction.
+ Test ID: B608
+ Severity: MEDIUM
+ Confidence: LOW
+ CWE: CWE-89
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/mysql/base.py
+ Line number: 1911
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b608_hardcoded_sql_expressions.html
+ +
+
+1910	        return (
+1911	            "SELECT %(outer)s FROM (SELECT %(inner)s) "
+1912	            "as _empty_set WHERE 1!=1"
+1913	            % {
+1914	                "inner": ", ".join(
+1915	                    "1 AS _in_%s" % idx
+1916	                    for idx, type_ in enumerate(element_types)
+1917	                ),
+1918	                "outer": ", ".join(
+1919	                    "_in_%s" % idx for idx, type_ in enumerate(element_types)
+1920	                ),
+1921	            }
+1922	        )
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/mysql/base.py
+ Line number: 1955
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1954	    ) -> str:
+1955	        assert binary.modifiers is not None
+1956	        flags = binary.modifiers["flags"]
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/mysql/base.py
+ Line number: 1989
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1988	    ) -> str:
+1989	        assert binary.modifiers is not None
+1990	        flags = binary.modifiers["flags"]
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/mysql/base.py
+ Line number: 3059
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+3058	
+3059	        assert schema is not None
+3060	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/mysql/base.py
+ Line number: 3210
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+3209	            mdb_version = self._mariadb_normalized_version_info
+3210	            assert mdb_version is not None
+3211	            if mdb_version > (10, 2) and mdb_version < (10, 2, 9):
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/mysql/base.py
+ Line number: 3297
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+3296	            schema = self.default_schema_name
+3297	        assert schema is not None
+3298	        charset = self._connection_charset
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/mysql/base.py
+ Line number: 3821
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+3820	        if full_name is None:
+3821	            assert table is not None
+3822	            full_name = self.identifier_preparer.format_table(table)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/mysql/base.py
+ Line number: 3867
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+3866	        if full_name is None:
+3867	            assert table is not None
+3868	            full_name = self.identifier_preparer.format_table(table)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/mysql/enumerated.py
+ Line number: 96
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+95	        if TYPE_CHECKING:
+96	            assert isinstance(impl, ENUM)
+97	        kw.setdefault("validate_strings", impl.validate_strings)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/mysql/enumerated.py
+ Line number: 221
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+220	                        value = super_convert(value)
+221	                        assert value is not None
+222	                    if TYPE_CHECKING:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/mysql/enumerated.py
+ Line number: 223
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+222	                    if TYPE_CHECKING:
+223	                        assert isinstance(value, str)
+224	                    return set(re.findall(r"[^,]+", value))
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/mysql/mariadbconnector.py
+ Line number: 109
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+108	        if TYPE_CHECKING:
+109	            assert isinstance(self.compiled, SQLCompiler)
+110	        if self.isinsert and self.compiled.postfetch_lastrowid:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/mysql/mariadbconnector.py
+ Line number: 115
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+114	        if TYPE_CHECKING:
+115	            assert self._lastrowid is not None
+116	        return self._lastrowid
+
+
+ + +
+
+ +
+
+ try_except_pass: Try, Except, Pass detected.
+ Test ID: B110
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/mysql/mysqlconnector.py
+ Line number: 215
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b110_try_except_pass.html
+ +
+
+214	                opts["client_flags"] = client_flags
+215	            except Exception:
+216	                pass
+217	
+
+
+ + +
+
+ +
+
+ hardcoded_password_funcarg: Possible hardcoded password: 'passwd'
+ Test ID: B106
+ Severity: LOW
+ Confidence: MEDIUM
+ CWE: CWE-259
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/mysql/mysqldb.py
+ Line number: 205
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b106_hardcoded_password_funcarg.html
+ +
+
+204	            _translate_args = dict(
+205	                database="db", username="user", password="passwd"
+206	            )
+207	
+208	        opts = url.translate_connect_args(**_translate_args)
+
+
+ + +
+
+ +
+
+ try_except_pass: Try, Except, Pass detected.
+ Test ID: B110
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/mysql/provision.py
+ Line number: 67
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b110_try_except_pass.html
+ +
+
+66	            _mysql_drop_db(cfg, conn, ident)
+67	        except Exception:
+68	            pass
+69	
+
+
+ + +
+
+ +
+
+ hardcoded_sql_expressions: Possible SQL injection vector through string-based query construction.
+ Test ID: B608
+ Severity: MEDIUM
+ Confidence: LOW
+ CWE: CWE-89
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/oracle/base.py
+ Line number: 1914
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b608_hardcoded_sql_expressions.html
+ +
+
+1913	        return self._execute_scalar(
+1914	            "SELECT "
+1915	            + self.identifier_preparer.format_sequence(seq)
+1916	            + ".nextval FROM DUAL",
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/oracle/base.py
+ Line number: 3264
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+3263	                if row_dict["descend"].lower() != "asc":
+3264	                    assert row_dict["descend"].lower() == "desc"
+3265	                    cs = index_dict.setdefault("column_sorting", {})
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/oracle/base.py
+ Line number: 3268
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+3267	            else:
+3268	                assert row_dict["descend"].lower() == "asc"
+3269	                cn = self.normalize_name(row_dict["column_name"])
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/oracle/base.py
+ Line number: 3481
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+3480	
+3481	            assert constraint_name is not None
+3482	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/oracle/base.py
+ Line number: 3633
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+3632	
+3633	            assert constraint_name is not None
+3634	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/oracle/base.py
+ Line number: 3684
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+3683	            if synonyms:
+3684	                assert len(synonyms) == 1
+3685	                row_dict = synonyms[0]
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/oracle/cx_oracle.py
+ Line number: 835
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+834	            out_parameters = self.out_parameters
+835	            assert out_parameters is not None
+836	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/oracle/cx_oracle.py
+ Line number: 854
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+853	
+854	                        assert cx_Oracle is not None
+855	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/oracle/cx_oracle.py
+ Line number: 1026
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1025	        # False.
+1026	        assert not self.compiled.returning
+1027	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/oracle/cx_oracle.py
+ Line number: 1270
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1269	            decimal_char = value.lstrip("0")[1]
+1270	            assert not decimal_char[0].isdigit()
+1271	
+
+
+ + +
+
+ +
+
+ blacklist: Standard pseudo-random generators are not suitable for security/cryptographic purposes.
+ Test ID: B311
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-330
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/oracle/cx_oracle.py
+ Line number: 1496
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b311-random
+ +
+
+1495	    def create_xid(self):
+1496	        id_ = random.randint(0, 2**128)
+1497	        return (0x1234, "%032x" % id_, "%032x" % 9)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/oracle/provision.py
+ Line number: 171
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+170	def _connect_with_retry(dialect, conn_rec, cargs, cparams):
+171	    assert dialect.driver == "cx_oracle"
+172	
+
+
+ + +
+
+ +
+
+ try_except_pass: Try, Except, Pass detected.
+ Test ID: B110
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/oracle/provision.py
+ Line number: 226
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b110_try_except_pass.html
+ +
+
+225	            sc = dbapi_connection.stmtcachesize
+226	        except:
+227	            # connection closed
+228	            pass
+229	        else:
+
+
+ + +
+
+ +
+
+ hardcoded_password_funcarg: Possible hardcoded password: 'xe'
+ Test ID: B106
+ Severity: LOW
+ Confidence: MEDIUM
+ CWE: CWE-259
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/oracle/provision.py
+ Line number: 270
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b106_hardcoded_password_funcarg.html
+ +
+
+269	    url = sa_url.make_url(url)
+270	    return url.set(username=ident, password="xe")
+271	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/postgresql/asyncpg.py
+ Line number: 633
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+632	    def _buffer_rows(self):
+633	        assert self._cursor is not None
+634	        new_rows = self._adapt_connection.await_(self._cursor.fetch(50))
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/postgresql/asyncpg.py
+ Line number: 663
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+662	
+663	        assert self._cursor is not None
+664	        rb = self._rowbuffer
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/postgresql/asyncpg.py
+ Line number: 1136
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1135	        if multihosts:
+1136	            assert multiports
+1137	            if len(multihosts) == 1:
+
+
+ + +
+
+ +
+
+ hardcoded_sql_expressions: Possible SQL injection vector through string-based query construction.
+ Test ID: B608
+ Severity: MEDIUM
+ Confidence: LOW
+ CWE: CWE-89
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/postgresql/base.py
+ Line number: 2291
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b608_hardcoded_sql_expressions.html
+ +
+
+2290	
+2291	        return "ON CONFLICT %s DO UPDATE SET %s" % (target_text, action_text)
+2292	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/postgresql/base.py
+ Line number: 3431
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+3430	                        if TYPE_CHECKING:
+3431	                            assert isinstance(h, str)
+3432	                            assert isinstance(p, str)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/postgresql/base.py
+ Line number: 3432
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+3431	                            assert isinstance(h, str)
+3432	                            assert isinstance(p, str)
+3433	                        hosts = (h,)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/postgresql/base.py
+ Line number: 4889
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+4888	                        # supported in included columns".
+4889	                        assert all(
+4890	                            not is_expr
+4891	                            for is_expr in all_elements_is_expr[indnkeyatts:]
+4892	                        )
+4893	                        idx_elements_opclass = all_elements_opclass[
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/postgresql/psycopg.py
+ Line number: 485
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+484	                # this one
+485	                assert self._psycopg_adapters_map
+486	                register_hstore(info, self._psycopg_adapters_map)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/postgresql/psycopg.py
+ Line number: 489
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+488	                # register the adapter for this connection
+489	                assert connection.connection
+490	                register_hstore(info, connection.connection.driver_connection)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/postgresql/ranges.py
+ Line number: 653
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+652	
+653	        assert False, f"Unhandled case computing {self} - {other}"
+654	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/postgresql/types.py
+ Line number: 61
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+60	        if TYPE_CHECKING:
+61	            assert isinstance(self, TypeEngine)
+62	        return self
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/sqlite/aiosqlite.py
+ Line number: 242
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+241	    def fetchone(self) -> Optional[Any]:
+242	        assert self._cursor is not None
+243	        return self.await_(self._cursor.fetchone())
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/sqlite/aiosqlite.py
+ Line number: 246
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+245	    def fetchmany(self, size: Optional[int] = None) -> Sequence[Any]:
+246	        assert self._cursor is not None
+247	        if size is None:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/sqlite/aiosqlite.py
+ Line number: 252
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+251	    def fetchall(self) -> Sequence[Any]:
+252	        assert self._cursor is not None
+253	        return self.await_(self._cursor.fetchall())
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/sqlite/base.py
+ Line number: 1163
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1162	        if truncate_microseconds:
+1163	            assert "storage_format" not in kwargs, (
+1164	                "You can specify only "
+1165	                "one of truncate_microseconds or storage_format."
+1166	            )
+1167	            assert "regexp" not in kwargs, (
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/sqlite/base.py
+ Line number: 1167
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1166	            )
+1167	            assert "regexp" not in kwargs, (
+1168	                "You can specify only one of "
+1169	                "truncate_microseconds or regexp."
+1170	            )
+1171	            self._storage_format = (
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/sqlite/base.py
+ Line number: 1357
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1356	        if truncate_microseconds:
+1357	            assert "storage_format" not in kwargs, (
+1358	                "You can specify only "
+1359	                "one of truncate_microseconds or storage_format."
+1360	            )
+1361	            assert "regexp" not in kwargs, (
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/sqlite/base.py
+ Line number: 1361
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1360	            )
+1361	            assert "regexp" not in kwargs, (
+1362	                "You can specify only one of "
+1363	                "truncate_microseconds or regexp."
+1364	            )
+1365	            self._storage_format = "%(hour)02d:%(minute)02d:%(second)02d"
+
+
+ + +
+
+ +
+
+ hardcoded_sql_expressions: Possible SQL injection vector through string-based query construction.
+ Test ID: B608
+ Severity: MEDIUM
+ Confidence: LOW
+ CWE: CWE-89
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/sqlite/base.py
+ Line number: 1573
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b608_hardcoded_sql_expressions.html
+ +
+
+1572	    def visit_empty_set_expr(self, element_types, **kw):
+1573	        return "SELECT %s FROM (SELECT %s) WHERE 1!=1" % (
+1574	            ", ".join("1" for type_ in element_types or [INTEGER()]),
+1575	            ", ".join("1" for type_ in element_types or [INTEGER()]),
+1576	        )
+1577	
+
+
+ + +
+
+ +
+
+ hardcoded_sql_expressions: Possible SQL injection vector through string-based query construction.
+ Test ID: B608
+ Severity: MEDIUM
+ Confidence: LOW
+ CWE: CWE-89
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/sqlite/base.py
+ Line number: 1691
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b608_hardcoded_sql_expressions.html
+ +
+
+1690	
+1691	        return "ON CONFLICT %s DO UPDATE SET %s" % (target_text, action_text)
+1692	
+
+
+ + +
+
+ +
+
+ hardcoded_password_string: Possible hardcoded password: 'NULL'
+ Test ID: B105
+ Severity: LOW
+ Confidence: MEDIUM
+ CWE: CWE-259
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/sqlite/base.py
+ Line number: 2104
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b105_hardcoded_password_string.html
+ +
+
+2103	
+2104	    default_metavalue_token = "NULL"
+2105	    """for INSERT... VALUES (DEFAULT) syntax, the token to put in the
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/sqlite/base.py
+ Line number: 2260
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2259	        else:
+2260	            assert False, "Unknown isolation level %s" % value
+2261	
+
+
+ + +
+
+ +
+
+ hardcoded_sql_expressions: Possible SQL injection vector through string-based query construction.
+ Test ID: B608
+ Severity: MEDIUM
+ Confidence: LOW
+ CWE: CWE-89
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/sqlite/base.py
+ Line number: 2290
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b608_hardcoded_sql_expressions.html
+ +
+
+2289	        query = (
+2290	            f"SELECT name FROM {main} "
+2291	            f"WHERE type='{type_}'{filter_table} "
+2292	            "ORDER BY name"
+2293	        )
+
+
+ + +
+
+ +
+
+ hardcoded_sql_expressions: Possible SQL injection vector through string-based query construction.
+ Test ID: B608
+ Severity: MEDIUM
+ Confidence: LOW
+ CWE: CWE-89
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/sqlite/base.py
+ Line number: 2358
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b608_hardcoded_sql_expressions.html
+ +
+
+2357	            master = f"{qschema}.sqlite_master"
+2358	            s = ("SELECT sql FROM %s WHERE name = ? AND type='view'") % (
+2359	                master,
+2360	            )
+2361	            rs = connection.exec_driver_sql(s, (view_name,))
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/sqlite/base.py
+ Line number: 2428
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2427	                )
+2428	                assert match, f"create table not found in {tablesql}"
+2429	                tablesql = match.group(1).strip()
+
+
+ + +
+
+ +
+
+ hardcoded_sql_expressions: Possible SQL injection vector through string-based query construction.
+ Test ID: B608
+ Severity: MEDIUM
+ Confidence: LOW
+ CWE: CWE-89
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/sqlite/base.py
+ Line number: 2946
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b608_hardcoded_sql_expressions.html
+ +
+
+2945	                s = (
+2946	                    "SELECT sql FROM %(schema)ssqlite_master "
+2947	                    "WHERE name = ? "
+2948	                    "AND type = 'index'" % {"schema": schema_expr}
+2949	                )
+
+
+ + +
+
+ +
+
+ hardcoded_sql_expressions: Possible SQL injection vector through string-based query construction.
+ Test ID: B608
+ Severity: MEDIUM
+ Confidence: LOW
+ CWE: CWE-89
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/sqlite/base.py
+ Line number: 3012
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b608_hardcoded_sql_expressions.html
+ +
+
+3011	            s = (
+3012	                "SELECT sql FROM "
+3013	                " (SELECT * FROM %(schema)ssqlite_master UNION ALL "
+3014	                "  SELECT * FROM %(schema)ssqlite_temp_master) "
+3015	                "WHERE name = ? "
+3016	                "AND type in ('table', 'view')" % {"schema": schema_expr}
+3017	            )
+
+
+ + +
+
+ +
+
+ hardcoded_sql_expressions: Possible SQL injection vector through string-based query construction.
+ Test ID: B608
+ Severity: MEDIUM
+ Confidence: LOW
+ CWE: CWE-89
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/sqlite/base.py
+ Line number: 3021
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b608_hardcoded_sql_expressions.html
+ +
+
+3020	            s = (
+3021	                "SELECT sql FROM %(schema)ssqlite_master "
+3022	                "WHERE name = ? "
+3023	                "AND type in ('table', 'view')" % {"schema": schema_expr}
+3024	            )
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/sqlite/provision.py
+ Line number: 54
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+53	    if filename and filename != ":memory:":
+54	        assert "test_schema" not in filename
+55	        tokens = re.split(r"[_\.]", filename)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/sqlite/provision.py
+ Line number: 67
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+66	
+67	        assert name_token, f"sqlite filename has no name token: {url.database}"
+68	
+
+
+ + +
+
+ +
+
+ hardcoded_password_funcarg: Possible hardcoded password: 'test'
+ Test ID: B106
+ Severity: LOW
+ Confidence: MEDIUM
+ CWE: CWE-259
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/sqlite/provision.py
+ Line number: 78
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b106_hardcoded_password_funcarg.html
+ +
+
+77	    if needs_enc:
+78	        url = url.set(password="test")
+79	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/sqlite/pysqlite.py
+ Line number: 674
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+673	                m = nis.search(sql)
+674	                assert not m, f"Found {nis.pattern!r} in {sql!r}"
+675	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/sqlite/pysqlite.py
+ Line number: 685
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+684	            if parameters:
+685	                assert isinstance(parameters, tuple)
+686	                return {
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/engine/base.py
+ Line number: 627
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+626	        dbapi_connection = self.connection.dbapi_connection
+627	        assert dbapi_connection is not None
+628	        try:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/engine/base.py
+ Line number: 746
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+745	            pool_proxied_connection = self._dbapi_connection
+746	            assert pool_proxied_connection is not None
+747	            pool_proxied_connection.invalidate(exception)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/engine/base.py
+ Line number: 1190
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1189	
+1190	        assert isinstance(self._transaction, TwoPhaseTransaction)
+1191	        try:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/engine/base.py
+ Line number: 1201
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1200	        if self._still_open_and_dbapi_connection_is_valid:
+1201	            assert isinstance(self._transaction, TwoPhaseTransaction)
+1202	            try:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/engine/base.py
+ Line number: 1213
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1212	
+1213	        assert isinstance(self._transaction, TwoPhaseTransaction)
+1214	        try:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/engine/base.py
+ Line number: 2362
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2361	            elif should_wrap:
+2362	                assert sqlalchemy_exception is not None
+2363	                raise sqlalchemy_exception.with_traceback(exc_info[2]) from e
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/engine/base.py
+ Line number: 2365
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2364	            else:
+2365	                assert exc_info[1] is not None
+2366	                raise exc_info[1].with_traceback(exc_info[2])
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/engine/base.py
+ Line number: 2373
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2372	                    dbapi_conn_wrapper = self._dbapi_connection
+2373	                    assert dbapi_conn_wrapper is not None
+2374	                    if invalidate_pool_on_disconnect:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/engine/base.py
+ Line number: 2447
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2446	        elif should_wrap:
+2447	            assert sqlalchemy_exception is not None
+2448	            raise sqlalchemy_exception.with_traceback(exc_info[2]) from e
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/engine/base.py
+ Line number: 2450
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2449	        else:
+2450	            assert exc_info[1] is not None
+2451	            raise exc_info[1].with_traceback(exc_info[2])
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/engine/base.py
+ Line number: 2599
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2598	        finally:
+2599	            assert not self.is_active
+2600	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/engine/base.py
+ Line number: 2621
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2620	        finally:
+2621	            assert not self.is_active
+2622	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/engine/base.py
+ Line number: 2642
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2641	        finally:
+2642	            assert not self.is_active
+2643	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/engine/base.py
+ Line number: 2688
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2687	    def __init__(self, connection: Connection):
+2688	        assert connection._transaction is None
+2689	        if connection._trans_context_manager:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/engine/base.py
+ Line number: 2699
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2698	        if self.is_active:
+2699	            assert self.connection._transaction is self
+2700	            self.is_active = False
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/engine/base.py
+ Line number: 2731
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2730	
+2731	        assert not self.is_active
+2732	        assert self.connection._transaction is not self
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/engine/base.py
+ Line number: 2732
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2731	        assert not self.is_active
+2732	        assert self.connection._transaction is not self
+2733	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/engine/base.py
+ Line number: 2742
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2741	        if self.is_active:
+2742	            assert self.connection._transaction is self
+2743	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/engine/base.py
+ Line number: 2765
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2764	
+2765	        assert not self.is_active
+2766	        assert self.connection._transaction is not self
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/engine/base.py
+ Line number: 2766
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2765	        assert not self.is_active
+2766	        assert self.connection._transaction is not self
+2767	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/engine/base.py
+ Line number: 2806
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2805	    def __init__(self, connection: Connection):
+2806	        assert connection._transaction is not None
+2807	        if connection._trans_context_manager:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/engine/base.py
+ Line number: 2852
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2851	
+2852	        assert not self.is_active
+2853	        if deactivate_from_connection:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/engine/base.py
+ Line number: 2854
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2853	        if deactivate_from_connection:
+2854	            assert self.connection._nested_transaction is not self
+2855	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/engine/create.py
+ Line number: 744
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+743	            ) -> None:
+744	                assert do_on_connect is not None
+745	                do_on_connect(dbapi_connection)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/engine/cursor.py
+ Line number: 218
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+217	    def _remove_processors(self) -> CursorResultMetaData:
+218	        assert not self._tuplefilter
+219	        return self._make_new_metadata(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/engine/cursor.py
+ Line number: 236
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+235	    ) -> CursorResultMetaData:
+236	        assert not self._tuplefilter
+237	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/engine/cursor.py
+ Line number: 313
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+312	        if TYPE_CHECKING:
+313	            assert isinstance(invoked_statement, elements.ClauseElement)
+314	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/engine/cursor.py
+ Line number: 318
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+317	
+318	        assert invoked_statement is not None
+319	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/engine/cursor.py
+ Line number: 338
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+337	
+338	        assert not self._tuplefilter
+339	        return self._make_new_metadata(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/engine/cursor.py
+ Line number: 874
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+873	            x = self._key_fallback(key, ke, raiseerr)
+874	            assert x is None
+875	            return None
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/engine/cursor.py
+ Line number: 1112
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1111	        # we only expect to have a _NoResultMetaData() here right now.
+1112	        assert not result._metadata.returns_rows
+1113	        result._metadata._we_dont_return_rows(err)  # type: ignore[union-attr]
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/engine/cursor.py
+ Line number: 1384
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1383	        else:
+1384	            assert dbapi_cursor is not None
+1385	            self._rowbuffer = collections.deque(dbapi_cursor.fetchall())
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/engine/cursor.py
+ Line number: 1589
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1588	        else:
+1589	            assert context._num_sentinel_cols == 0
+1590	            self._metadata = self._no_result_metadata
+
+
+ + +
+
+ +
+
+ hardcoded_password_string: Possible hardcoded password: 'DEFAULT'
+ Test ID: B105
+ Severity: LOW
+ Confidence: MEDIUM
+ CWE: CWE-259
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/engine/default.py
+ Line number: 226
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b105_hardcoded_password_string.html
+ +
+
+225	
+226	    default_metavalue_token = "DEFAULT"
+227	    """for INSERT... VALUES (DEFAULT) syntax, the token to put in the
+
+
+ + +
+
+ +
+
+ blacklist: Standard pseudo-random generators are not suitable for security/cryptographic purposes.
+ Test ID: B311
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-330
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/engine/default.py
+ Line number: 765
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b311-random
+ +
+
+764	
+765	        return "_sa_%032x" % random.randint(0, 2**128)
+766	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/engine/default.py
+ Line number: 797
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+796	        imv = compiled._insertmanyvalues
+797	        assert imv is not None
+798	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/engine/default.py
+ Line number: 848
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+847	                # would have assured this but pylance thinks not
+848	                assert result is not None
+849	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/engine/default.py
+ Line number: 855
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+854	                        # integer autoincrement, do a simple sort.
+855	                        assert not composite_sentinel
+856	                        result.extend(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/engine/default.py
+ Line number: 863
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+862	                    # with parameters
+863	                    assert imv.sentinel_param_keys
+864	                    assert imv.sentinel_columns
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/engine/default.py
+ Line number: 864
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+863	                    assert imv.sentinel_param_keys
+864	                    assert imv.sentinel_columns
+865	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/engine/default.py
+ Line number: 1006
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1005	        if self._on_connect_isolation_level is not None:
+1006	            assert (
+1007	                self._on_connect_isolation_level == "AUTOCOMMIT"
+1008	                or self._on_connect_isolation_level
+1009	                == self.default_isolation_level
+1010	            )
+1011	            self._assert_and_set_isolation_level(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/engine/default.py
+ Line number: 1015
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1014	        else:
+1015	            assert self.default_isolation_level is not None
+1016	            self._assert_and_set_isolation_level(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/engine/default.py
+ Line number: 1355
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1354	            if TYPE_CHECKING:
+1355	                assert isinstance(dml_statement, UpdateBase)
+1356	            self.is_crud = True
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/engine/default.py
+ Line number: 1365
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1364	            # dont mix implicit and explicit returning
+1365	            assert not (iir and ier)
+1366	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/engine/default.py
+ Line number: 1492
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1491	            core_positional_parameters: MutableSequence[Sequence[Any]] = []
+1492	            assert positiontup is not None
+1493	            for compiled_params in self.compiled_parameters:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/engine/default.py
+ Line number: 1614
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1613	        gen_time = self.compiled._gen_time
+1614	        assert gen_time is not None
+1615	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/engine/default.py
+ Line number: 1664
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1663	        if TYPE_CHECKING:
+1664	            assert isinstance(self.compiled, SQLCompiler)
+1665	        return self.compiled.postfetch
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/engine/default.py
+ Line number: 1670
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1669	        if TYPE_CHECKING:
+1670	            assert isinstance(self.compiled, SQLCompiler)
+1671	        if self.isinsert:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/engine/default.py
+ Line number: 1965
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1964	        elif self._num_sentinel_cols:
+1965	            assert self.execute_style is ExecuteStyle.INSERTMANYVALUES
+1966	            # strip out the sentinel columns from cursor description
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/engine/default.py
+ Line number: 1990
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1989	                # support is added here.
+1990	                assert result._metadata.returns_rows
+1991	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/engine/default.py
+ Line number: 2022
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2021	            # the rows have all been fetched however.
+2022	            assert result._metadata.returns_rows
+2023	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/engine/default.py
+ Line number: 2301
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2300	        else:
+2301	            assert column is not None
+2302	            assert parameters is not None
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/engine/default.py
+ Line number: 2302
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2301	            assert column is not None
+2302	            assert parameters is not None
+2303	        compile_state = cast(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/engine/default.py
+ Line number: 2306
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2305	        )
+2306	        assert compile_state is not None
+2307	        if (
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/engine/default.py
+ Line number: 2318
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2317	                index = 0
+2318	            assert compile_state._dict_parameters is not None
+2319	            keys = compile_state._dict_parameters.keys()
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/engine/reflection.py
+ Line number: 1672
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1671	            default_text = col_d["default"]
+1672	            assert default_text is not None
+1673	            if isinstance(default_text, TextClause):
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/engine/result.py
+ Line number: 149
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+148	    ) -> Optional[NoReturn]:
+149	        assert raiseerr
+150	        raise KeyError(key) from err
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/engine/result.py
+ Line number: 551
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+550	        make_row = self._row_getter
+551	        assert make_row is not None
+552	        rows = self._fetchall_impl()
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/engine/result.py
+ Line number: 691
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+690	                        num = len(rows)
+691	                        assert make_row is not None
+692	                        collect.extend(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/engine/result.py
+ Line number: 699
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+698	
+699	                assert num is not None
+700	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/engine/result.py
+ Line number: 808
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+807	                        if strategy:
+808	                            assert next_row is not _NO_ROW
+809	                            if existing_row_hash == strategy(next_row):
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/engine/result.py
+ Line number: 867
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+866	
+867	        assert self._generate_rows
+868	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/engine/result.py
+ Line number: 873
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+872	    def _unique_strategy(self) -> _UniqueFilterStateType:
+873	        assert self._unique_filter_state is not None
+874	        uniques, strategy = self._unique_filter_state
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/engine/util.py
+ Line number: 152
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+151	                if not out_of_band_exit:
+152	                    assert subject is not None
+153	                    subject._trans_context_manager = self._outer_trans_ctx
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/engine/util.py
+ Line number: 165
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+164	                if not out_of_band_exit:
+165	                    assert subject is not None
+166	                    subject._trans_context_manager = self._outer_trans_ctx
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/event/attr.py
+ Line number: 182
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+181	        target = event_key.dispatch_target
+182	        assert isinstance(
+183	            target, type
+184	        ), "Class-level Event targets must be classes."
+185	        if not getattr(target, "_sa_propagate_class_events", True):
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/event/attr.py
+ Line number: 345
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+344	
+345	        assert obj._instance_cls is not None
+346	        existing = getattr(obj, self.name)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/event/attr.py
+ Line number: 355
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+354	                # with freethreaded.
+355	                assert isinstance(existing, _ListenerCollection)
+356	                return existing
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/event/base.py
+ Line number: 146
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+145	        if instance_cls:
+146	            assert parent is not None
+147	            try:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/event/base.py
+ Line number: 194
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+193	        """
+194	        assert "_joined_dispatch_cls" in self.__class__.__dict__
+195	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/event/base.py
+ Line number: 317
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+316	            dispatch_target_cls = cls._dispatch_target
+317	            assert dispatch_target_cls is not None
+318	            if (
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/event/legacy.py
+ Line number: 102
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+101	            if conv is not None:
+102	                assert not has_kw
+103	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/event/legacy.py
+ Line number: 106
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+105	                    util.warn_deprecated(warning_txt, version=since)
+106	                    assert conv is not None
+107	                    return fn(*conv(*args))
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/event/legacy.py
+ Line number: 234
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+233	    if getattr(fn, "_omit_standard_example", False):
+234	        assert fn.__doc__
+235	        return fn.__doc__
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/event/registry.py
+ Line number: 193
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+192	        if newowner_ref in dispatch_reg:
+193	            assert dispatch_reg[newowner_ref] == listen_ref
+194	        else:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/ext/associationproxy.py
+ Line number: 453
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+452	
+453	        assert instance is None
+454	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/ext/associationproxy.py
+ Line number: 735
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+734	        attr = getattr(target_class, value_attr)
+735	        assert not isinstance(attr, AssociationProxy)
+736	        if isinstance(attr, AssociationProxyInstance):
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/ext/associationproxy.py
+ Line number: 900
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+899	                if id(obj) == creator_id and id(self) == self_id:
+900	                    assert self.collection_class is not None
+901	                    return proxy
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/ext/associationproxy.py
+ Line number: 933
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+932	            proxy = self.get(obj)
+933	            assert self.collection_class is not None
+934	            if proxy is not values:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/engine.py
+ Line number: 332
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+331	        """Begin a transaction prior to autobegin occurring."""
+332	        assert self._proxied
+333	        return AsyncTransaction(self)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/engine.py
+ Line number: 337
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+336	        """Begin a nested transaction and return a transaction handle."""
+337	        assert self._proxied
+338	        return AsyncTransaction(self, nested=True)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/engine.py
+ Line number: 443
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+442	        c2 = await greenlet_spawn(conn.execution_options, **opt)
+443	        assert c2 is conn
+444	        return self
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/engine.py
+ Line number: 593
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+592	        )
+593	        assert result.context._is_server_side
+594	        ar = AsyncResult(result)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/engine.py
+ Line number: 1360
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1359	        )
+1360	        assert async_connection is not None
+1361	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/ext/automap.py
+ Line number: 1232
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1231	        else:
+1232	            assert False, "Can't locate automap base in class hierarchy"
+1233	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/ext/automap.py
+ Line number: 1257
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1256	        if reflect:
+1257	            assert autoload_with
+1258	            opts = dict(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/ext/automap.py
+ Line number: 1294
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1293	                if lcl_m2m is not None:
+1294	                    assert rem_m2m is not None
+1295	                    assert m2m_const is not None
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/ext/automap.py
+ Line number: 1295
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1294	                    assert rem_m2m is not None
+1295	                    assert m2m_const is not None
+1296	                    many_to_many.append((lcl_m2m, rem_m2m, m2m_const, table))
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/ext/automap.py
+ Line number: 1330
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1329	                    )
+1330	                    assert map_config.cls.__name__ == newname
+1331	                    if new_module is None:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/ext/automap.py
+ Line number: 1345
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1344	                        # see test_cls_schema_name_conflict
+1345	                        assert isinstance(props, Properties)
+1346	                        by_module_properties = props
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/ext/baked.py
+ Line number: 204
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+203	                else:
+204	                    assert not ck[1], (
+205	                        "loader options with variable bound parameters "
+206	                        "not supported with baked queries.  Please "
+207	                        "use new-style select() statements for cached "
+208	                        "ORM queries."
+209	                    )
+210	                    key += ck[0]
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/ext/horizontal_shard.py
+ Line number: 113
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+112	        super().__init__(*args, **kwargs)
+113	        assert isinstance(self.session, ShardedSession)
+114	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/ext/horizontal_shard.py
+ Line number: 310
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+309	                token = state.key[2]
+310	                assert token is not None
+311	                return token
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/ext/horizontal_shard.py
+ Line number: 315
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+314	
+315	        assert isinstance(mapper, Mapper)
+316	        shard_id = self.shard_chooser(mapper, instance, **kw)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/ext/horizontal_shard.py
+ Line number: 338
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+337	            trans = self.get_transaction()
+338	            assert trans is not None
+339	            return trans.connection(mapper, shard_id=shard_id)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/ext/horizontal_shard.py
+ Line number: 348
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+347	            else:
+348	                assert isinstance(bind, Connection)
+349	                return bind
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/ext/horizontal_shard.py
+ Line number: 364
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+363	            )
+364	            assert shard_id is not None
+365	        return self.__shards[shard_id]
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/ext/horizontal_shard.py
+ Line number: 443
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+442	    session = orm_context.session
+443	    assert isinstance(session, ShardedSession)
+444	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/ext/hybrid.py
+ Line number: 1471
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1470	            if TYPE_CHECKING:
+1471	                assert isinstance(expr, ColumnElement)
+1472	            ret_expr = expr
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/ext/hybrid.py
+ Line number: 1478
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1477	            # true
+1478	            assert isinstance(ret_expr, ColumnElement)
+1479	        return ret_expr
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/ext/mutable.py
+ Line number: 525
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+524	                    val = cls.coerce(key, val)
+525	                    assert val is not None
+526	                    state.dict[key] = val
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/ext/mypy/apply.py
+ Line number: 79
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+78	    left_hand_explicit_type = get_proper_type(stmt.type)
+79	    assert isinstance(
+80	        left_hand_explicit_type, (Instance, UnionType, UnboundType)
+81	    )
+82	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/ext/mypy/apply.py
+ Line number: 174
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+173	            ):
+174	                assert python_type_for_type is not None
+175	                left_node.type = api.named_type(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/ext/mypy/apply.py
+ Line number: 213
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+212	    left_node = lvalue.node
+213	    assert isinstance(left_node, Var)
+214	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/ext/mypy/apply.py
+ Line number: 316
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+315	    if sym:
+316	        assert isinstance(sym.node, TypeInfo)
+317	        type_: ProperType = Instance(sym.node, [])
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/ext/mypy/decl_class.py
+ Line number: 191
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+190	    if left_hand_explicit_type is not None:
+191	        assert value.node is not None
+192	        attributes.append(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/ext/mypy/decl_class.py
+ Line number: 378
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+377	    # hook.
+378	    assert sym is not None
+379	    node = sym.node
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/ext/mypy/decl_class.py
+ Line number: 384
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+383	
+384	    assert node is lvalue.node
+385	    assert isinstance(node, Var)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/ext/mypy/decl_class.py
+ Line number: 385
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+384	    assert node is lvalue.node
+385	    assert isinstance(node, Var)
+386	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/ext/mypy/decl_class.py
+ Line number: 468
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+467	
+468	    assert python_type_for_type is not None
+469	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/ext/mypy/infer.py
+ Line number: 110
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+109	
+110	    assert isinstance(stmt.rvalue, CallExpr)
+111	    target_cls_arg = stmt.rvalue.args[0]
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/ext/mypy/infer.py
+ Line number: 230
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+229	        if type_is_a_collection:
+230	            assert isinstance(left_hand_explicit_type, Instance)
+231	            assert isinstance(python_type_for_type, Instance)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/ext/mypy/infer.py
+ Line number: 231
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+230	            assert isinstance(left_hand_explicit_type, Instance)
+231	            assert isinstance(python_type_for_type, Instance)
+232	            return _infer_collection_type_from_left_and_inferred_right(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/ext/mypy/infer.py
+ Line number: 254
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+253	
+254	    assert isinstance(stmt.rvalue, CallExpr)
+255	    target_cls_arg = stmt.rvalue.args[0]
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/ext/mypy/infer.py
+ Line number: 290
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+289	    """
+290	    assert isinstance(stmt.rvalue, CallExpr)
+291	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/ext/mypy/infer.py
+ Line number: 322
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+321	    """
+322	    assert isinstance(stmt.rvalue, CallExpr)
+323	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/ext/mypy/infer.py
+ Line number: 397
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+396	    """
+397	    assert isinstance(node, Var)
+398	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/ext/mypy/infer.py
+ Line number: 431
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+430	        else:
+431	            assert False
+432	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/ext/mypy/infer.py
+ Line number: 516
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+515	
+516	    assert isinstance(left_hand_arg, (Instance, UnionType))
+517	    assert isinstance(python_type_arg, (Instance, UnionType))
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/ext/mypy/infer.py
+ Line number: 517
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+516	    assert isinstance(left_hand_arg, (Instance, UnionType))
+517	    assert isinstance(python_type_arg, (Instance, UnionType))
+518	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/ext/mypy/infer.py
+ Line number: 575
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+574	
+575	    assert node.has_base("sqlalchemy.sql.type_api.TypeEngine"), (
+576	        "could not extract Python type from node: %s" % node
+577	    )
+578	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/ext/mypy/infer.py
+ Line number: 583
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+582	
+583	    assert type_engine_sym is not None and isinstance(
+584	        type_engine_sym.node, TypeInfo
+585	    )
+586	    type_engine = map_instance_to_supertype(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/ext/mypy/plugin.py
+ Line number: 235
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+234	    _add_globals(ctx)
+235	    assert isinstance(ctx.reason, nodes.MemberExpr)
+236	    expr = ctx.reason.expr
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/ext/mypy/plugin.py
+ Line number: 238
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+237	
+238	    assert isinstance(expr, nodes.RefExpr) and isinstance(expr.node, nodes.Var)
+239	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/ext/mypy/plugin.py
+ Line number: 242
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+241	
+242	    assert (
+243	        isinstance(node_type, Instance)
+244	        and names.type_id_for_named_node(node_type.type) is names.REGISTRY
+245	    )
+246	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/ext/mypy/plugin.py
+ Line number: 302
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+301	    )
+302	    assert sym is not None and isinstance(sym.node, TypeInfo)
+303	    info.declared_metaclass = info.metaclass_type = Instance(sym.node, [])
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/ext/mypy/util.py
+ Line number: 78
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+77	    def serialize(self) -> JsonDict:
+78	        assert self.type
+79	        return {
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/ext/mypy/util.py
+ Line number: 335
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+334	            return None
+335	        assert sym and isinstance(sym.node, TypeInfo)
+336	        return sym.node
+
+
+ + +
+
+ +
+
+ try_except_pass: Try, Except, Pass detected.
+ Test ID: B110
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/ext/mypy/util.py
+ Line number: 344
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b110_try_except_pass.html
+ +
+
+343	        return typ.serialize()
+344	    except Exception:
+345	        pass
+346	    if hasattr(typ, "args"):
+
+
+ + +
+
+ +
+
+ blacklist: Consider possible security implications associated with pickle module.
+ Test ID: B403
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-502
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/ext/serializer.py
+ Line number: 72
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_imports.html#b403-import-pickle
+ +
+
+71	from io import BytesIO
+72	import pickle
+73	import re
+
+
+ + +
+
+ +
+
+ blacklist: Pickle and modules that wrap it can be unsafe when used to deserialize untrusted data, possible security issue.
+ Test ID: B301
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-502
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/ext/serializer.py
+ Line number: 150
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b301-pickle
+ +
+
+149	                key, clsarg = args.split(":")
+150	                cls = pickle.loads(b64decode(clsarg))
+151	                return getattr(cls, key)
+
+
+ + +
+
+ +
+
+ blacklist: Pickle and modules that wrap it can be unsafe when used to deserialize untrusted data, possible security issue.
+ Test ID: B301
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-502
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/ext/serializer.py
+ Line number: 153
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b301-pickle
+ +
+
+152	            elif type_ == "mapper":
+153	                cls = pickle.loads(b64decode(args))
+154	                return class_mapper(cls)
+
+
+ + +
+
+ +
+
+ blacklist: Pickle and modules that wrap it can be unsafe when used to deserialize untrusted data, possible security issue.
+ Test ID: B301
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-502
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/ext/serializer.py
+ Line number: 156
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b301-pickle
+ +
+
+155	            elif type_ == "mapper_selectable":
+156	                cls = pickle.loads(b64decode(args))
+157	                return class_mapper(cls).__clause_element__()
+
+
+ + +
+
+ +
+
+ blacklist: Pickle and modules that wrap it can be unsafe when used to deserialize untrusted data, possible security issue.
+ Test ID: B301
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-502
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/ext/serializer.py
+ Line number: 160
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b301-pickle
+ +
+
+159	                mapper, keyname = args.split(":")
+160	                cls = pickle.loads(b64decode(mapper))
+161	                return class_mapper(cls).attrs[keyname]
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/attributes.py
+ Line number: 218
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+217	
+218	        assert comparator is not None
+219	        self.comparator = comparator
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/attributes.py
+ Line number: 336
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+335	        entity_namespace = self._entity_namespace
+336	        assert isinstance(entity_namespace, HasCacheKey)
+337	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/attributes.py
+ Line number: 350
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+349	            if TYPE_CHECKING:
+350	                assert isinstance(ce, ColumnElement)
+351	            anno = ce._annotate
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/attributes.py
+ Line number: 395
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+394	    def adapt_to_entity(self, adapt_to_entity: AliasedInsp[Any]) -> Self:
+395	        assert not self._of_type
+396	        return self.__class__(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/attributes.py
+ Line number: 419
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+418	        if TYPE_CHECKING:
+419	            assert isinstance(self.comparator, RelationshipProperty.Comparator)
+420	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/attributes.py
+ Line number: 975
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+974	        msg = "This AttributeImpl is not configured to track parents."
+975	        assert self.trackparent, msg
+976	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/attributes.py
+ Line number: 993
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+992	        msg = "This AttributeImpl is not configured to track parents."
+993	        assert self.trackparent, msg
+994	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/attributes.py
+ Line number: 1060
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1059	
+1060	        assert self.key not in dict_, (
+1061	            "_default_value should only be invoked for an "
+1062	            "uninitialized or expired attribute"
+1063	        )
+1064	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/attributes.py
+ Line number: 1704
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1703	                # pending mutations
+1704	                assert self.key not in state._pending_mutations
+1705	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/attributes.py
+ Line number: 1835
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1834	
+1835	        assert self.key not in dict_, (
+1836	            "_default_value should only be invoked for an "
+1837	            "uninitialized or expired attribute"
+1838	        )
+1839	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/attributes.py
+ Line number: 1873
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1872	            )
+1873	            assert (
+1874	                self.key not in dict_
+1875	            ), "Collection was loaded during event handling."
+1876	            state._get_pending_mutation(self.key).append(value)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/attributes.py
+ Line number: 1879
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1878	            if TYPE_CHECKING:
+1879	                assert isinstance(collection, CollectionAdapter)
+1880	            collection.append_with_event(value, initiator)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/attributes.py
+ Line number: 1895
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1894	            self.fire_remove_event(state, dict_, value, initiator, key=NO_KEY)
+1895	            assert (
+1896	                self.key not in dict_
+1897	            ), "Collection was loaded during event handling."
+1898	            state._get_pending_mutation(self.key).remove(value)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/attributes.py
+ Line number: 1901
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1900	            if TYPE_CHECKING:
+1901	                assert isinstance(collection, CollectionAdapter)
+1902	            collection.remove_with_event(value, initiator)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/attributes.py
+ Line number: 2704
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2703	    if TYPE_CHECKING:
+2704	        assert isinstance(attr, HasCollectionAdapter)
+2705	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/base.py
+ Line number: 443
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+442	    else:
+443	        assert isinstance(class_or_mapper, type)
+444	        raise exc.UnmappedClassError(class_or_mapper)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/bulk_persistence.py
+ Line number: 236
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+235	            elif result.returns_rows:
+236	                assert bookkeeping
+237	                return_result = return_result.splice_horizontally(result)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/bulk_persistence.py
+ Line number: 250
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+249	    if use_orm_insert_stmt is not None:
+250	        assert return_result is not None
+251	        return return_result
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/bulk_persistence.py
+ Line number: 480
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+479	    def _get_crud_kv_pairs(cls, statement, kv_iterator, needs_to_be_cacheable):
+480	        assert (
+481	            needs_to_be_cacheable
+482	        ), "no test coverage for needs_to_be_cacheable=False"
+483	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/bulk_persistence.py
+ Line number: 705
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+704	        except KeyError:
+705	            assert False, "statement had 'orm' plugin but no plugin_subject"
+706	        else:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/bulk_persistence.py
+ Line number: 1199
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1198	        except KeyError:
+1199	            assert False, "statement had 'orm' plugin but no plugin_subject"
+1200	        else:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/bulk_persistence.py
+ Line number: 1290
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1289	
+1290	            assert mapper is not None
+1291	            assert session._transaction is not None
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/bulk_persistence.py
+ Line number: 1291
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1290	            assert mapper is not None
+1291	            assert session._transaction is not None
+1292	            result = _bulk_insert(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/bulk_persistence.py
+ Line number: 1623
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1622	
+1623	            assert update_options._synchronize_session != "fetch"
+1624	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/bulk_persistence.py
+ Line number: 1637
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1636	            mapper = update_options._subject_mapper
+1637	            assert mapper is not None
+1638	            assert session._transaction is not None
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/bulk_persistence.py
+ Line number: 1638
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1637	            assert mapper is not None
+1638	            assert session._transaction is not None
+1639	            result = _bulk_update(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/clsregistry.py
+ Line number: 348
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+347	                else:
+348	                    assert isinstance(value, _MultipleClassMarker)
+349	                    return value.attempt_get(self.__parent.path, key)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/clsregistry.py
+ Line number: 375
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+374	            if desc.extension_type is interfaces.NotExtension.NOT_EXTENSION:
+375	                assert isinstance(desc, attributes.QueryableAttribute)
+376	                prop = desc.property
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/clsregistry.py
+ Line number: 452
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+451	        decl_base = manager.registry
+452	        assert decl_base is not None
+453	        decl_class_registry = decl_base._class_registry
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/clsregistry.py
+ Line number: 528
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+527	                if TYPE_CHECKING:
+528	                    assert isinstance(rval, (type, Table, _ModNS))
+529	                return rval
+
+
+ + +
+
+ +
+
+ blacklist: Use of possibly insecure function - consider using safer ast.literal_eval.
+ Test ID: B307
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/clsregistry.py
+ Line number: 533
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b307-eval
+ +
+
+532	        try:
+533	            x = eval(self.arg, globals(), self._dict)
+534	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/collections.py
+ Line number: 548
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+547	    def _set_empty(self, user_data):
+548	        assert (
+549	            not self.empty
+550	        ), "This collection adapter is already in the 'empty' state"
+551	        self.empty = True
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/collections.py
+ Line number: 555
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+554	    def _reset_empty(self) -> None:
+555	        assert (
+556	            self.empty
+557	        ), "This collection adapter is not in the 'empty' state"
+558	        self.empty = False
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/collections.py
+ Line number: 799
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+798	
+799	    assert isinstance(values, list)
+800	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/collections.py
+ Line number: 908
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+907	                role = method._sa_instrument_role
+908	                assert role in (
+909	                    "appender",
+910	                    "remover",
+911	                    "iterator",
+912	                    "converter",
+913	                )
+914	                roles.setdefault(role, name)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/collections.py
+ Line number: 923
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+922	                op, argument = method._sa_instrument_before
+923	                assert op in ("fire_append_event", "fire_remove_event")
+924	                before = op, argument
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/collections.py
+ Line number: 927
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+926	                op = method._sa_instrument_after
+927	                assert op in ("fire_append_event", "fire_remove_event")
+928	                after = op
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/collections.py
+ Line number: 945
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+944	    if collection_type in __interfaces:
+945	        assert collection_type is not None
+946	        canned_roles, decorators = __interfaces[collection_type]
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/context.py
+ Line number: 235
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+234	            self.global_attributes = {}
+235	            assert toplevel
+236	            return
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/context.py
+ Line number: 571
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+570	        except KeyError:
+571	            assert False, "statement had 'orm' plugin but no plugin_subject"
+572	        else:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/context.py
+ Line number: 783
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+782	
+783	        assert isinstance(statement_container, FromStatement)
+784	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/context.py
+ Line number: 1374
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1373	            if self.compile_options._only_load_props:
+1374	                assert False, "no columns were included in _only_load_props"
+1375	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/context.py
+ Line number: 1491
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1490	
+1491	        assert self.compile_options._set_base_alias
+1492	        assert len(query._from_obj) == 1
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/context.py
+ Line number: 1492
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1491	        assert self.compile_options._set_base_alias
+1492	        assert len(query._from_obj) == 1
+1493	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/context.py
+ Line number: 1518
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1517	            equivs = self._all_equivs()
+1518	            assert info is info.selectable
+1519	            return ORMStatementAdapter(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/context.py
+ Line number: 1952
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1951	            # entities
+1952	            assert prop is None
+1953	            (
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/context.py
+ Line number: 2013
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2012	                # might be distinct
+2013	                assert isinstance(
+2014	                    entities_collection[use_entity_index], _MapperEntity
+2015	                )
+2016	                left_clause = entities_collection[use_entity_index].selectable
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/context.py
+ Line number: 2342
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2341	            # a warning has been emitted.
+2342	            assert right_mapper
+2343	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/context.py
+ Line number: 3285
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+3284	            if column is None:
+3285	                assert compile_state.is_dml_returning
+3286	                self._fetch_column = self.column
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/decl_api.py
+ Line number: 299
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+298	        # assert that we are in fact in the declarative scan
+299	        assert declarative_scan is not None
+300	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/decl_api.py
+ Line number: 1309
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1308	                if res_after_fallback is not None:
+1309	                    assert kind is not None
+1310	                    if kind == "pep-695 type":
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/decl_api.py
+ Line number: 1425
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1424	            )
+1425	        assert manager.registry is None
+1426	        manager.registry = self
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/decl_base.py
+ Line number: 203
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+202	    # make sure we've moved it out.  transitional
+203	    assert attrname != "__abstract__"
+204	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/decl_base.py
+ Line number: 880
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+879	                        # _include_dunders
+880	                        assert False
+881	                elif class_mapped:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/decl_base.py
+ Line number: 910
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+909	                        # pylance, no luck
+910	                        assert obj is not None
+911	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/decl_base.py
+ Line number: 990
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+989	                        if not fixed_table:
+990	                            assert (
+991	                                name in collected_attributes
+992	                                or attribute_is_overridden(name, None)
+993	                            )
+994	                        continue
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/decl_base.py
+ Line number: 1012
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1011	
+1012	                    assert not attribute_is_overridden(name, obj)
+1013	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/decl_base.py
+ Line number: 1095
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1094	        manager = instrumentation.manager_of_class(self.cls)
+1095	        assert manager is not None
+1096	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/decl_base.py
+ Line number: 1165
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1164	            else:
+1165	                assert False
+1166	            annotations[name] = tp
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/decl_base.py
+ Line number: 1590
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1589	                        # by util._extract_mapped_subtype before we got here.
+1590	                        assert expect_annotations_wo_mapped
+1591	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/decl_base.py
+ Line number: 1689
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1688	                # ensure every column we get here has been named
+1689	                assert c.name is not None
+1690	                name_to_prop_key[c.name].add(key)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/decl_base.py
+ Line number: 1846
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1845	            inherited_mapper_or_config = _declared_mapping_info(self.inherits)
+1846	            assert inherited_mapper_or_config is not None
+1847	            inherited_table = inherited_mapper_or_config.local_table
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/decl_base.py
+ Line number: 1870
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1869	                for col in declared_columns:
+1870	                    assert inherited_table is not None
+1871	                    if col.name in inherited_table.c:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/decl_base.py
+ Line number: 1889
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1888	                    if TYPE_CHECKING:
+1889	                        assert isinstance(inherited_table, Table)
+1890	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/dependency.py
+ Line number: 136
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+135	            # this method a bit more.
+136	            assert child_deletes not in uow.cycles
+137	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/dependency.py
+ Line number: 916
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+915	    def process_deletes(self, uowcommit, states):
+916	        assert False
+917	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/dependency.py
+ Line number: 923
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+922	        # statements being emitted
+923	        assert self.passive_updates
+924	        self._process_key_switches(states, uowcommit)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/descriptor_props.py
+ Line number: 856
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+855	            if self._adapt_to_entity:
+856	                assert self.adapter is not None
+857	                comparisons = [self.adapter(x) for x in comparisons]
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/descriptor_props.py
+ Line number: 910
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+909	                break
+910	        assert comparator_callable is not None
+911	        return comparator_callable(p, mapper)  # type: ignore
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/exc.py
+ Line number: 195
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+194	        else:
+195	            assert applies_to is not None
+196	            sa_exc.InvalidRequestError.__init__(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/identity.py
+ Line number: 151
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+150	            if TYPE_CHECKING:
+151	                assert state.key is not None
+152	            try:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/identity.py
+ Line number: 162
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+161	    ) -> Optional[InstanceState[Any]]:
+162	        assert state.key is not None
+163	        if state.key in self._dict:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/identity.py
+ Line number: 183
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+182	        key = state.key
+183	        assert key is not None
+184	        # inline of self.__contains__
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/identity.py
+ Line number: 241
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+240	            key = state.key
+241	            assert key is not None
+242	            if value is not None:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/identity.py
+ Line number: 266
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+265	        key = state.key
+266	        assert key is not None
+267	        try:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/identity.py
+ Line number: 282
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+281	        if key in self._dict:
+282	            assert key is not None
+283	            try:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/instrumentation.py
+ Line number: 214
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+213	        if init_method:
+214	            assert not self._finalized, (
+215	                "class is already instrumented, "
+216	                "init_method %s can't be applied" % init_method
+217	            )
+218	            self.init_method = init_method
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/instrumentation.py
+ Line number: 483
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+482	        impl = self.get_impl(key)
+483	        assert _is_collection_attribute_impl(impl)
+484	        adapter = collections.CollectionAdapter(impl, state, user_data)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/instrumentation.py
+ Line number: 613
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+612	    def create_manager_for_cls(self, class_: Type[_O]) -> ClassManager[_O]:
+613	        assert class_ is not None
+614	        assert opt_manager_of_class(class_) is None
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/instrumentation.py
+ Line number: 614
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+613	        assert class_ is not None
+614	        assert opt_manager_of_class(class_) is None
+615	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/instrumentation.py
+ Line number: 624
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+623	        else:
+624	            assert manager is not None
+625	
+
+
+ + +
+
+ +
+
+ exec_used: Use of exec detected.
+ Test ID: B102
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/instrumentation.py
+ Line number: 744
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b102_exec_used.html
+ +
+
+743	    env["__name__"] = __name__
+744	    exec(func_text, env)
+745	    __init__ = env["__init__"]
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/interfaces.py
+ Line number: 296
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+295	
+296	            assert False, "Mapped[] received without a mapping declaration"
+297	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/interfaces.py
+ Line number: 1148
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1147	                if TYPE_CHECKING:
+1148	                    assert issubclass(prop_cls, MapperProperty)
+1149	                strategies = cls._all_strategies[prop_cls]
+
+
+ + +
+
+ +
+
+ try_except_pass: Try, Except, Pass detected.
+ Test ID: B110
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/loading.py
+ Line number: 148
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b110_try_except_pass.html
+ +
+
+147	                        return hash(obj)
+148	                    except:
+149	                        pass
+150	
+
+
+ + +
+
+ +
+
+ try_except_pass: Try, Except, Pass detected.
+ Test ID: B110
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/loading.py
+ Line number: 172
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b110_try_except_pass.html
+ +
+
+171	                        return hash(obj)
+172	                    except:
+173	                        pass
+174	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/loading.py
+ Line number: 548
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+547	
+548	    assert not q._is_lambda_element
+549	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/loading.py
+ Line number: 1012
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1011	            # loading does not apply
+1012	            assert only_load_props is None
+1013	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/mapper.py
+ Line number: 1241
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1240	                        except sa_exc.NoForeignKeysError as nfe:
+1241	                            assert self.inherits.local_table is not None
+1242	                            assert self.local_table is not None
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/mapper.py
+ Line number: 1242
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1241	                            assert self.inherits.local_table is not None
+1242	                            assert self.local_table is not None
+1243	                            raise sa_exc.NoForeignKeysError(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/mapper.py
+ Line number: 1261
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1260	                        except sa_exc.AmbiguousForeignKeysError as afe:
+1261	                            assert self.inherits.local_table is not None
+1262	                            assert self.local_table is not None
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/mapper.py
+ Line number: 1262
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1261	                            assert self.inherits.local_table is not None
+1262	                            assert self.local_table is not None
+1263	                            raise sa_exc.AmbiguousForeignKeysError(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/mapper.py
+ Line number: 1276
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1275	                            ) from afe
+1276	                    assert self.inherits.persist_selectable is not None
+1277	                    self.persist_selectable = sql.join(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/mapper.py
+ Line number: 1377
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1376	            self.base_mapper = self
+1377	            assert self.local_table is not None
+1378	            self.persist_selectable = self.local_table
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/mapper.py
+ Line number: 1433
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1432	        elif self.with_polymorphic[0] != "*":
+1433	            assert isinstance(self.with_polymorphic[0], tuple)
+1434	            self._set_with_polymorphic(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/mapper.py
+ Line number: 1443
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1442	
+1443	        assert self.concrete
+1444	        assert not self.inherits
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/mapper.py
+ Line number: 1444
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1443	        assert self.concrete
+1444	        assert not self.inherits
+1445	        assert isinstance(mapper, Mapper)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/mapper.py
+ Line number: 1445
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1444	        assert not self.inherits
+1445	        assert isinstance(mapper, Mapper)
+1446	        self.inherits = mapper
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/mapper.py
+ Line number: 1495
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1494	
+1495	            assert manager.registry is not None
+1496	            self.registry = manager.registry
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/mapper.py
+ Line number: 1530
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1529	
+1530	        assert manager.registry is not None
+1531	        self.registry = manager.registry
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/mapper.py
+ Line number: 2318
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2317	        if incoming_prop is None:
+2318	            assert single_column is not None
+2319	            incoming_column = single_column
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/mapper.py
+ Line number: 2322
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2321	        else:
+2322	            assert single_column is None
+2323	            incoming_column = incoming_prop.columns[0]
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/mapper.py
+ Line number: 2457
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2456	        )
+2457	        assert isinstance(prop, MapperProperty)
+2458	        self._init_properties[key] = prop
+
+
+ + +
+
+ +
+
+ hardcoded_password_string: Possible hardcoded password: 'True'
+ Test ID: B105
+ Severity: LOW
+ Confidence: MEDIUM
+ CWE: CWE-259
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/mapper.py
+ Line number: 2902
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b105_hardcoded_password_string.html
+ +
+
+2901	                    "parentmapper": self,
+2902	                    "identity_token": True,
+2903	                }
+2904	            )
+2905	            ._set_propagate_attrs(
+2906	                {"compile_state_plugin": "orm", "plugin_subject": self}
+2907	            )
+2908	        )
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/mapper.py
+ Line number: 3700
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+3699	            if start and not mapper.single:
+3700	                assert mapper.inherits
+3701	                assert not mapper.concrete
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/mapper.py
+ Line number: 3701
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+3700	                assert mapper.inherits
+3701	                assert not mapper.concrete
+3702	                assert mapper.inherit_condition is not None
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/mapper.py
+ Line number: 3702
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+3701	                assert not mapper.concrete
+3702	                assert mapper.inherit_condition is not None
+3703	                allconds.append(mapper.inherit_condition)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/mapper.py
+ Line number: 3790
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+3789	        # mappers or other objects.
+3790	        assert self.isa(super_mapper)
+3791	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/mapper.py
+ Line number: 3834
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+3833	
+3834	        assert self.inherits
+3835	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/mapper.py
+ Line number: 3902
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+3901	        if entity.is_aliased_class:
+3902	            assert entity.mapper is self
+3903	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/mapper.py
+ Line number: 3963
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+3962	
+3963	        assert state.mapper.isa(self)
+3964	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/mapper.py
+ Line number: 3990
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+3989	                    continue
+3990	                assert parent_state is not None
+3991	                assert parent_dict is not None
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/mapper.py
+ Line number: 3991
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+3990	                assert parent_state is not None
+3991	                assert parent_dict is not None
+3992	                queue = deque(
+
+
+ + +
+
+ +
+
+ hardcoded_password_string: Possible hardcoded password: '_sa_default'
+ Test ID: B105
+ Severity: LOW
+ Confidence: MEDIUM
+ CWE: CWE-259
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/path_registry.py
+ Line number: 83
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b105_hardcoded_password_string.html
+ +
+
+82	_WILDCARD_TOKEN: _LiteralStar = "*"
+83	_DEFAULT_TOKEN = "_sa_default"
+84	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/path_registry.py
+ Line number: 286
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+285	                mp = orm_base._inspect_mapped_class(mcls, configure=True)
+286	                assert mp is not None
+287	                return mp.attrs[key]
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/path_registry.py
+ Line number: 310
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+309	    def deserialize(cls, path: _SerializedPath) -> PathRegistry:
+310	        assert path is not None
+311	        p = cls._deserialize_path(path)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/path_registry.py
+ Line number: 388
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+387	            if TYPE_CHECKING:
+388	                assert isinstance(entity, _StrPathToken)
+389	            return TokenRegistry(self, PathToken._intern[entity])
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/path_registry.py
+ Line number: 459
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+458	        if TYPE_CHECKING:
+459	            assert isinstance(parent, AbstractEntityRegistry)
+460	        if not parent.is_aliased_class:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/path_registry.py
+ Line number: 487
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+486	        if TYPE_CHECKING:
+487	            assert isinstance(parent, AbstractEntityRegistry)
+488	        for mp_ent in parent.mapper.iterate_to_root():
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/path_registry.py
+ Line number: 614
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+613	            if TYPE_CHECKING:
+614	                assert isinstance(prop, RelationshipProperty)
+615	            self.entity = prop.entity
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/path_registry.py
+ Line number: 641
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+640	    def entity_path(self) -> AbstractEntityRegistry:
+641	        assert self.entity is not None
+642	        return self[self.entity]
+
+
+ + +
+
+ +
+
+ hardcoded_sql_expressions: Possible SQL injection vector through string-based query construction.
+ Test ID: B608
+ Severity: MEDIUM
+ Confidence: LOW
+ CWE: CWE-89
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/persistence.py
+ Line number: 715
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b608_hardcoded_sql_expressions.html
+ +
+
+714	                raise orm_exc.FlushError(
+715	                    "Can't delete from table %s "
+716	                    "using NULL for primary "
+717	                    "key value on column %s" % (table, col)
+718	                )
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/persistence.py
+ Line number: 1214
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1213	            else:
+1214	                assert not returning_is_required_anyway
+1215	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/properties.py
+ Line number: 762
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+761	        ):
+762	            assert originating_module is not None
+763	            argument = de_stringify_annotation(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/query.py
+ Line number: 648
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+647	        if TYPE_CHECKING:
+648	            assert isinstance(stmt, Select)
+649	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/query.py
+ Line number: 3344
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+3343	        stmt = self._statement_20(for_statement=for_statement, **kw)
+3344	        assert for_statement == stmt._compile_options._for_statement
+3345	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/relationships.py
+ Line number: 785
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+784	                )
+785	                assert info is not None
+786	                target_mapper, to_selectable, is_aliased_class = (
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/relationships.py
+ Line number: 1170
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1169	    ) -> ColumnElement[bool]:
+1170	        assert instance is not None
+1171	        adapt_source: Optional[_CoreAdapterProto] = None
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/relationships.py
+ Line number: 1174
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1173	            insp: Optional[_InternalEntityType[Any]] = inspect(from_entity)
+1174	            assert insp is not None
+1175	            if insp_is_aliased_class(insp):
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/relationships.py
+ Line number: 1311
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1310	        def _go() -> Any:
+1311	            assert lkv_fixed is not None
+1312	            last_known = to_return = lkv_fixed[prop.key]
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/relationships.py
+ Line number: 1409
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1408	
+1409	            assert is_has_collection_adapter(impl)
+1410	            instances_iterable = impl.get_collection(source_state, source_dict)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/relationships.py
+ Line number: 1415
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1414	            # True
+1415	            assert not instances_iterable.empty if impl.collection else True
+1416	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/relationships.py
+ Line number: 1450
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1449	                dest_impl = dest_state.get_impl(self.key)
+1450	                assert is_has_collection_adapter(dest_impl)
+1451	                dest_impl.set(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/relationships.py
+ Line number: 1544
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1543	
+1544	            assert instance_state is not None
+1545	            instance_dict = attributes.instance_dict(c)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/relationships.py
+ Line number: 1767
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1766	        argument = extracted_mapped_annotation
+1767	        assert originating_module is not None
+1768	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/relationships.py
+ Line number: 2322
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2321	        self._determine_joins()
+2322	        assert self.primaryjoin is not None
+2323	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/relationships.py
+ Line number: 2494
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2493	    def secondaryjoin_minus_local(self) -> ColumnElement[bool]:
+2494	        assert self.secondaryjoin is not None
+2495	        return _deep_deannotate(self.secondaryjoin, values=("local", "remote"))
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/relationships.py
+ Line number: 2687
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2686	
+2687	        assert self.secondary is not None
+2688	        fixed_secondary = self.secondary
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/relationships.py
+ Line number: 2699
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2698	
+2699	        assert self.secondaryjoin is not None
+2700	        self.secondaryjoin = visitors.replacement_traverse(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/session.py
+ Line number: 952
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+951	        elif origin is SessionTransactionOrigin.SUBTRANSACTION:
+952	            assert parent is not None
+953	        else:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/session.py
+ Line number: 954
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+953	        else:
+954	            assert parent is None
+955	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/session.py
+ Line number: 1075
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1074	            parent = self._parent
+1075	            assert parent is not None
+1076	            self._new = parent._new
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/session.py
+ Line number: 1100
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1099	        """
+1100	        assert self._is_transaction_boundary
+1101	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/session.py
+ Line number: 1120
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1119	
+1120	        assert not self.session._deleted
+1121	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/session.py
+ Line number: 1132
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1131	        """
+1132	        assert self._is_transaction_boundary
+1133	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/session.py
+ Line number: 1144
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1143	            parent = self._parent
+1144	            assert parent is not None
+1145	            parent._new.update(self._new)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/session.py
+ Line number: 1238
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1237	                    else:
+1238	                        assert False, join_transaction_mode
+1239	                else:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/session.py
+ Line number: 1277
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1276	        stx = self.session._transaction
+1277	        assert stx is not None
+1278	        if stx is not self:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/session.py
+ Line number: 1343
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1342	        stx = self.session._transaction
+1343	        assert stx is not None
+1344	        if stx is not self:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/session.py
+ Line number: 1887
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1886	            )
+1887	            assert self._transaction is trans
+1888	            return trans
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/session.py
+ Line number: 1934
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1933	
+1934	        assert trans is not None
+1935	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/session.py
+ Line number: 1938
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1937	            trans = trans._begin(nested=nested)
+1938	            assert self._transaction is trans
+1939	            self._nested_transaction = trans
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/session.py
+ Line number: 2162
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2161	            if TYPE_CHECKING:
+2162	                assert isinstance(
+2163	                    compile_state_cls, context.AbstractORMCompileState
+2164	                )
+2165	        else:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/session.py
+ Line number: 2606
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2605	            if TYPE_CHECKING:
+2606	                assert isinstance(insp, Inspectable)
+2607	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/session.py
+ Line number: 2817
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2816	                        if TYPE_CHECKING:
+2817	                            assert isinstance(obj, Table)
+2818	                        return self.__binds[obj]
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/session.py
+ Line number: 3362
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+3361	                    trans = self._transaction
+3362	                    assert trans is not None
+3363	                    if state in trans._key_switches:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/session.py
+ Line number: 3565
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+3564	            if TYPE_CHECKING:
+3565	                assert cascade_states is not None
+3566	            for o, m, st_, dct_ in cascade_states:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/session.py
+ Line number: 3841
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+3840	            # TODO: this was being tested before, but this is not possible
+3841	            assert instance is not LoaderCallableStatus.PASSIVE_CLASS_MISMATCH
+3842	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/session.py
+ Line number: 4408
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+4407	                )
+4408	                assert _reg, "Failed to add object to the flush context!"
+4409	                processed.add(state)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/session.py
+ Line number: 4418
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+4417	            _reg = flush_context.register_object(state, isdelete=True)
+4418	            assert _reg, "Failed to add object to the flush context!"
+4419	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/state.py
+ Line number: 527
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+526	        # so make sure this is not set
+527	        assert self._strong_obj is None
+528	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/state.py
+ Line number: 909
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+908	                    if TYPE_CHECKING:
+909	                        assert is_collection_impl(attr)
+910	                    if previous is NEVER_SET:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/state_changes.py
+ Line number: 83
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+82	        """
+83	        assert prerequisite_states, "no prerequisite states sent"
+84	        has_prerequisite_states = (
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/state_changes.py
+ Line number: 180
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+179	        """
+180	        assert self._next_state is _StateChangeStates.CHANGE_IN_PROGRESS, (
+181	            "Unexpected call to _expect_state outside of "
+182	            "state-changing method"
+183	        )
+184	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/strategies.py
+ Line number: 1810
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1809	            q = self.subq
+1810	            assert q.session is None
+1811	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/strategies.py
+ Line number: 2043
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2042	
+2043	        assert subq.session is None
+2044	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/strategies.py
+ Line number: 2397
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2396	
+2397	        assert clauses.is_aliased_class
+2398	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/strategies.py
+ Line number: 2519
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2518	
+2519	        assert clauses.is_aliased_class
+2520	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/strategies.py
+ Line number: 2609
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2608	
+2609	        assert entity_we_want_to_splice_onto is path[-2]
+2610	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/strategies.py
+ Line number: 2612
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2611	        if entity_inside_join_structure is False:
+2612	            assert isinstance(join_obj, orm_util._ORMJoin)
+2613	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/strategies.py
+ Line number: 2690
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2689	            if entity_inside_join_structure is False:
+2690	                assert (
+2691	                    False
+2692	                ), "assertion failed attempting to produce joined eager loads"
+2693	            return None
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/strategies.py
+ Line number: 2712
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2711	            # and entity_inside_join_structure=join_obj._right_memo.mapper
+2712	            assert detected_existing_path[-3] is entity_inside_join_structure
+2713	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/strategy_options.py
+ Line number: 148
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+147	        elif getattr(attr, "_of_type", None):
+148	            assert isinstance(attr, QueryableAttribute)
+149	            ot: Optional[_InternalEntityType[Any]] = inspect(attr._of_type)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/strategy_options.py
+ Line number: 150
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+149	            ot: Optional[_InternalEntityType[Any]] = inspect(attr._of_type)
+150	            assert ot is not None
+151	            coerced_alias = ot.selectable
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/strategy_options.py
+ Line number: 1071
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1070	        orig_cache_key = orig_query._generate_cache_key()
+1071	        assert orig_cache_key is not None
+1072	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/strategy_options.py
+ Line number: 1160
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1159	
+1160	        assert cloned.propagate_to_loaders == self.propagate_to_loaders
+1161	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/strategy_options.py
+ Line number: 1279
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1278	                self.context += (load_element,)
+1279	                assert opts is not None
+1280	                self.additional_source_entities += cast(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/strategy_options.py
+ Line number: 1374
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1373	    ):
+1374	        assert attrs is not None
+1375	        attr = attrs[0]
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/strategy_options.py
+ Line number: 1376
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1375	        attr = attrs[0]
+1376	        assert (
+1377	            wildcard_key
+1378	            and isinstance(attr, str)
+1379	            and attr in (_WILDCARD_TOKEN, _DEFAULT_TOKEN)
+1380	        )
+1381	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/strategy_options.py
+ Line number: 1389
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1388	
+1389	        assert extra_criteria is None
+1390	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/strategy_options.py
+ Line number: 1403
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1402	        """
+1403	        assert self.path
+1404	        attr = self.path[0]
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/strategy_options.py
+ Line number: 1410
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1409	
+1410	        assert effective_path.is_token
+1411	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/strategy_options.py
+ Line number: 1443
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1442	            # just returns it
+1443	            assert new_path == start_path
+1444	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/strategy_options.py
+ Line number: 1446
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1445	        # start_path is a single-token tuple
+1446	        assert start_path and len(start_path) == 1
+1447	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/strategy_options.py
+ Line number: 1449
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1448	        token = start_path[0]
+1449	        assert isinstance(token, str)
+1450	        entity = self._find_entity_basestring(entities, token, raiseerr)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/strategy_options.py
+ Line number: 1462
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1461	
+1462	        assert isinstance(token, str)
+1463	        loader = _TokenStrategyLoad.create(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/strategy_options.py
+ Line number: 1475
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1474	
+1475	        assert loader.path.is_token
+1476	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/strategy_options.py
+ Line number: 1771
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1770	
+1771	        assert opt.is_token_strategy == path.is_token
+1772	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/strategy_options.py
+ Line number: 1813
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1812	
+1813	        assert cloned.strategy == self.strategy
+1814	        assert cloned.local_opts == self.local_opts
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/strategy_options.py
+ Line number: 1814
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1813	        assert cloned.strategy == self.strategy
+1814	        assert cloned.local_opts == self.local_opts
+1815	        assert cloned.is_class_strategy == self.is_class_strategy
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/strategy_options.py
+ Line number: 1815
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1814	        assert cloned.local_opts == self.local_opts
+1815	        assert cloned.is_class_strategy == self.is_class_strategy
+1816	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/strategy_options.py
+ Line number: 1911
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1910	    ):
+1911	        assert attr is not None
+1912	        self._of_type = None
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/strategy_options.py
+ Line number: 1930
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1929	            # should not reach here;
+1930	            assert False
+1931	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/strategy_options.py
+ Line number: 1957
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1956	        if extra_criteria:
+1957	            assert not attr._extra_criteria
+1958	            self._extra_criteria = extra_criteria
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/strategy_options.py
+ Line number: 2009
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2008	
+2009	        assert (
+2010	            self._extra_criteria
+2011	        ), "this should only be called if _extra_criteria is present"
+2012	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/strategy_options.py
+ Line number: 2035
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2034	    def _set_of_type_info(self, context, current_path):
+2035	        assert self._path_with_polymorphic_path
+2036	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/strategy_options.py
+ Line number: 2038
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2037	        pwpi = self._of_type
+2038	        assert pwpi
+2039	        if not pwpi.is_aliased_class:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/strategy_options.py
+ Line number: 2080
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2079	        is_refresh = compile_state.compile_options._for_refresh_state
+2080	        assert not self.path.is_token
+2081	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/strategy_options.py
+ Line number: 2103
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2102	        if current_path:
+2103	            assert effective_path is not None
+2104	            effective_path = self._adjust_effective_path_for_current_path(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/strategy_options.py
+ Line number: 2132
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2131	            else:
+2132	                assert False, "unexpected object for _of_type"
+2133	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/strategy_options.py
+ Line number: 2203
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2202	
+2203	        assert self.path.is_token
+2204	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/strategy_options.py
+ Line number: 2357
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2356	
+2357	    assert lead_element
+2358	    return lead_element
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/unitofwork.py
+ Line number: 638
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+637	        self.sort_key = ("SaveUpdateAll", mapper._sort_key)
+638	        assert mapper is mapper.base_mapper
+639	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/unitofwork.py
+ Line number: 675
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+674	        self.sort_key = ("DeleteAll", mapper._sort_key)
+675	        assert mapper is mapper.base_mapper
+676	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/util.py
+ Line number: 727
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+726	
+727	        assert alias is not None
+728	        self._aliased_insp = AliasedInsp(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/util.py
+ Line number: 1004
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1003	            # supports "aliased class of aliased class" use case
+1004	            assert isinstance(inspected, AliasedInsp)
+1005	            self._adapter = inspected._adapter.wrap(self._adapter)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/util.py
+ Line number: 1065
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1064	        if aliased or flat:
+1065	            assert selectable is not None
+1066	            selectable = selectable._anonymous_fromclause(flat=flat)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/util.py
+ Line number: 1160
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1159	
+1160	        assert self.mapper is primary_mapper
+1161	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/util.py
+ Line number: 1187
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1186	    ) -> _ORMCOLEXPR:
+1187	        assert isinstance(expr, ColumnElement)
+1188	        d: Dict[str, Any] = {
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/util.py
+ Line number: 1230
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1229	        else:
+1230	            assert False, "mapper %s doesn't correspond to %s" % (mapper, self)
+1231	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/util.py
+ Line number: 1388
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1387	            else:
+1388	                assert entity is not None
+1389	                wrap_entity = entity.entity
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/util.py
+ Line number: 1435
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1434	        else:
+1435	            assert self.root_entity
+1436	            stack = list(self.root_entity.__subclasses__())
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/util.py
+ Line number: 1468
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1467	            crit = self.where_criteria  # type: ignore
+1468	        assert isinstance(crit, ColumnElement)
+1469	        return sql_util._deep_annotate(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/util.py
+ Line number: 1813
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1812	            if TYPE_CHECKING:
+1813	                assert isinstance(
+1814	                    onclause.comparator, RelationshipProperty.Comparator
+1815	                )
+1816	            on_selectable = onclause.comparator._source_selectable()
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/util.py
+ Line number: 1833
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1832	            else:
+1833	                assert isinstance(left_selectable, FromClause)
+1834	                adapt_from = left_selectable
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/util.py
+ Line number: 1886
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1885	
+1886	        assert self.onclause is not None
+1887	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/util.py
+ Line number: 1916
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1915	
+1916	        assert self.right is leftmost
+1917	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/util.py
+ Line number: 2081
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2080	
+2081	    assert insp_is_mapper(given)
+2082	    return entity.common_parent(given)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/writeonly.py
+ Line number: 503
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+502	        if TYPE_CHECKING:
+503	            assert instance
+504	        self.instance = instance
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/pool/base.py
+ Line number: 868
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+867	
+868	        assert self.dbapi_connection is not None
+869	        return self.dbapi_connection
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/pool/base.py
+ Line number: 882
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+881	            self.__pool.dispatch.close(self.dbapi_connection, self)
+882	        assert self.dbapi_connection is not None
+883	        self.__pool._close_connection(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/pool/base.py
+ Line number: 940
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+939	    if is_gc_cleanup:
+940	        assert ref is not None
+941	        _strong_ref_connection_records.pop(ref, None)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/pool/base.py
+ Line number: 942
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+941	        _strong_ref_connection_records.pop(ref, None)
+942	        assert connection_record is not None
+943	        if connection_record.fairy_ref is not ref:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/pool/base.py
+ Line number: 945
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+944	            return
+945	        assert dbapi_connection is None
+946	        dbapi_connection = connection_record.dbapi_connection
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/pool/base.py
+ Line number: 977
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+976	            if not fairy:
+977	                assert connection_record is not None
+978	                fairy = _ConnectionFairy(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/pool/base.py
+ Line number: 984
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+983	                )
+984	            assert fairy.dbapi_connection is dbapi_connection
+985	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/pool/base.py
+ Line number: 1277
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1276	
+1277	        assert (
+1278	            fairy._connection_record is not None
+1279	        ), "can't 'checkout' a detached connection fairy"
+1280	        assert (
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/pool/base.py
+ Line number: 1280
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1279	        ), "can't 'checkout' a detached connection fairy"
+1280	        assert (
+1281	            fairy.dbapi_connection is not None
+1282	        ), "can't 'checkout' an invalidated connection fairy"
+1283	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/pool/base.py
+ Line number: 1493
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1492	    def cursor(self, *args: Any, **kwargs: Any) -> DBAPICursor:
+1493	        assert self.dbapi_connection is not None
+1494	        return self.dbapi_connection.cursor(*args, **kwargs)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/pool/events.py
+ Line number: 78
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+77	            else:
+78	                assert issubclass(target, Pool)
+79	                return target
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/pool/impl.py
+ Line number: 392
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+391	        # losing the state of an existing SQLite :memory: connection
+392	        assert not hasattr(other_singleton_pool._fairy, "current")
+393	        self._conn = other_singleton_pool._conn
+
+
+ + +
+
+ +
+
+ try_except_pass: Try, Except, Pass detected.
+ Test ID: B110
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/pool/impl.py
+ Line number: 402
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b110_try_except_pass.html
+ +
+
+401	                conn.close()
+402	            except Exception:
+403	                # pysqlite won't even let you close a conn from a thread
+404	                # that didn't create it
+405	                pass
+406	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/pool/impl.py
+ Line number: 502
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+501	            conn = other_static_pool.connection.dbapi_connection
+502	            assert conn is not None
+503	            return conn
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/pool/impl.py
+ Line number: 552
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+551	        self._checked_out = False
+552	        assert record is self._conn
+553	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/_py_util.py
+ Line number: 63
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+62	            s_val = self[idself]
+63	            assert s_val is not True
+64	            return s_val, True
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/base.py
+ Line number: 286
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+285	        x = fn(self, *args, **kw)
+286	        assert x is self, "generative methods must return self"
+287	        return self
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/base.py
+ Line number: 1223
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1222	
+1223	        assert self._compile_options is not None
+1224	        self._compile_options += options
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/cache_key.py
+ Line number: 165
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+164	                try:
+165	                    assert issubclass(cls, HasTraverseInternals)
+166	                    _cache_key_traversal = cls._traverse_internals
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/cache_key.py
+ Line number: 171
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+170	
+171	            assert _cache_key_traversal is not NO_CACHE, (
+172	                f"class {cls} has _cache_key_traversal=NO_CACHE, "
+173	                "which conflicts with inherit_cache=True"
+174	            )
+175	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/cache_key.py
+ Line number: 386
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+385	        else:
+386	            assert key is not None
+387	            return CacheKey(key, bindparams)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/cache_key.py
+ Line number: 400
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+399	        else:
+400	            assert key is not None
+401	            return CacheKey(key, bindparams)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/coercions.py
+ Line number: 408
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+407	        if typing.TYPE_CHECKING:
+408	            assert isinstance(resolved, (SQLCoreOperations, ClauseElement))
+409	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/coercions.py
+ Line number: 454
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+453	        if isinstance(resolved, str):
+454	            assert isinstance(expr, str)
+455	            strname = resolved = expr
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/coercions.py
+ Line number: 706
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+705	        # never reached
+706	        assert False
+707	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/coercions.py
+ Line number: 887
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+886	        elif isinstance(element, elements.ClauseList):
+887	            assert not len(element.clauses) == 0
+888	            return element.self_group(against=operator)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/coercions.py
+ Line number: 1331
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1330	    def _post_coercion(self, element, *, flat=False, name=None, **kw):
+1331	        assert name is None
+1332	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/compiler.py
+ Line number: 899
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+898	                if TYPE_CHECKING:
+899	                    assert isinstance(statement, Executable)
+900	                self.execution_options = statement._execution_options
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/compiler.py
+ Line number: 904
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+903	            if render_schema_translate:
+904	                assert schema_translate_map is not None
+905	                self.string = self.preparer._render_schema_translates(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/compiler.py
+ Line number: 1465
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1464	            if TYPE_CHECKING:
+1465	                assert isinstance(statement, UpdateBase)
+1466	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/compiler.py
+ Line number: 1469
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1468	                if TYPE_CHECKING:
+1469	                    assert isinstance(statement, ValuesBase)
+1470	                if statement._inline:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/compiler.py
+ Line number: 1662
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1661	    def _process_positional(self):
+1662	        assert not self.positiontup
+1663	        assert self.state is CompilerState.STRING_APPLIED
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/compiler.py
+ Line number: 1663
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1662	        assert not self.positiontup
+1663	        assert self.state is CompilerState.STRING_APPLIED
+1664	        assert not self._numeric_binds
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/compiler.py
+ Line number: 1664
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1663	        assert self.state is CompilerState.STRING_APPLIED
+1664	        assert not self._numeric_binds
+1665	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/compiler.py
+ Line number: 1669
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1668	        else:
+1669	            assert self.dialect.paramstyle == "qmark"
+1670	            placeholder = "?"
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/compiler.py
+ Line number: 1690
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1689	            reverse_escape = {v: k for k, v in self.escaped_bind_names.items()}
+1690	            assert len(self.escaped_bind_names) == len(reverse_escape)
+1691	            self.positiontup = [
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/compiler.py
+ Line number: 1721
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1720	    def _process_numeric(self):
+1721	        assert self._numeric_binds
+1722	        assert self.state is CompilerState.STRING_APPLIED
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/compiler.py
+ Line number: 1722
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1721	        assert self._numeric_binds
+1722	        assert self.state is CompilerState.STRING_APPLIED
+1723	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/compiler.py
+ Line number: 1767
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1766	            }
+1767	            assert len(param_pos) == len_before
+1768	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/compiler.py
+ Line number: 1864
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1863	        if self._render_postcompile and not _no_postcompile:
+1864	            assert self._post_compile_expanded_state is not None
+1865	            if not params:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/compiler.py
+ Line number: 1893
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1892	            ckbm_tuple = self._cache_key_bind_match
+1893	            assert ckbm_tuple is not None
+1894	            ckbm, _ = ckbm_tuple
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/compiler.py
+ Line number: 2140
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2139	                    if parameter.type._is_tuple_type:
+2140	                        assert values is not None
+2141	                        new_processors.update(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/compiler.py
+ Line number: 2192
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2191	        if numeric_positiontup is not None:
+2192	            assert new_positiontup is not None
+2193	            param_pos = {
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/compiler.py
+ Line number: 2252
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2251	
+2252	        assert self.compile_state is not None
+2253	        statement = self.compile_state.statement
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/compiler.py
+ Line number: 2256
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2255	        if TYPE_CHECKING:
+2256	            assert isinstance(statement, Insert)
+2257	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/compiler.py
+ Line number: 2334
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2333	
+2334	        assert self.compile_state is not None
+2335	        statement = self.compile_state.statement
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/compiler.py
+ Line number: 2338
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2337	        if TYPE_CHECKING:
+2338	            assert isinstance(statement, Insert)
+2339	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/compiler.py
+ Line number: 2344
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2343	        returning = self.implicit_returning
+2344	        assert returning is not None
+2345	        ret = {col: idx for idx, col in enumerate(returning)}
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/compiler.py
+ Line number: 2648
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2647	            if TYPE_CHECKING:
+2648	                assert isinstance(table, NamedFromClause)
+2649	            tablename = table.name
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/compiler.py
+ Line number: 3291
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+3290	                m = post_compile_pattern.search(bind_expression_template)
+3291	                assert m and m.group(
+3292	                    2
+3293	                ), "unexpected format for expanding parameter"
+3294	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/compiler.py
+ Line number: 3361
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+3360	        ):
+3361	            assert not typ_dialect_impl._is_array
+3362	            to_update = [
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/compiler.py
+ Line number: 3725
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+3724	                    )
+3725	                    assert m, "unexpected format for expanding parameter"
+3726	                    wrapped = "(__[POSTCOMPILE_%s~~%s~~REPL~~%s~~])" % (
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/compiler.py
+ Line number: 4058
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+4057	        self_ctes = self._init_cte_state()
+4058	        assert self_ctes is self.ctes
+4059	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/compiler.py
+ Line number: 4079
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+4078	            ]
+4079	            assert _ == cte_name
+4080	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/compiler.py
+ Line number: 4128
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+4127	
+4128	                assert existing_cte_reference_cte is _reference_cte
+4129	                assert existing_cte_reference_cte is existing_cte
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/compiler.py
+ Line number: 4129
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+4128	                assert existing_cte_reference_cte is _reference_cte
+4129	                assert existing_cte_reference_cte is existing_cte
+4130	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/compiler.py
+ Line number: 4218
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+4217	
+4218	                assert kwargs.get("subquery", False) is False
+4219	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/compiler.py
+ Line number: 4291
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+4290	                # from visit_lateral() and we need to set enclosing_lateral.
+4291	                assert alias._is_lateral
+4292	                kwargs["enclosing_lateral"] = alias
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/compiler.py
+ Line number: 4473
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+4472	        # collection properly
+4473	        assert objects
+4474	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/compiler.py
+ Line number: 4568
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+4567	        # these assertions right now set up the current expected inputs
+4568	        assert within_columns_clause, (
+4569	            "_label_select_column is only relevant within "
+4570	            "the columns clause of a SELECT or RETURNING"
+4571	        )
+4572	        result_expr: Union[elements.Label[Any], _CompileLabel]
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/compiler.py
+ Line number: 4588
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+4587	
+4588	            assert (
+4589	                proxy_name is not None
+4590	            ), "proxy_name is required if 'name' is passed"
+4591	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/compiler.py
+ Line number: 4696
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+4695	                    # just-added _label_returning_column method
+4696	                    assert not column_is_repeated
+4697	                    fallback_label_name = column._anon_name_label
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/compiler.py
+ Line number: 4795
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+4794	    ):
+4795	        assert select_wraps_for is None, (
+4796	            "SQLAlchemy 1.4 requires use of "
+4797	            "the translate_select_structure hook for structural "
+4798	            "translations of SELECT objects"
+4799	        )
+4800	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/compiler.py
+ Line number: 5123
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+5122	        if warn_linting:
+5123	            assert from_linter is not None
+5124	            from_linter.warn()
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/compiler.py
+ Line number: 5541
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+5540	        imv = self._insertmanyvalues
+5541	        assert imv is not None
+5542	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/compiler.py
+ Line number: 5674
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+5673	        insert_crud_params = imv.insert_crud_params
+5674	        assert insert_crud_params is not None
+5675	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/compiler.py
+ Line number: 5745
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+5744	                positiontup = self.positiontup
+5745	                assert positiontup is not None
+5746	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/compiler.py
+ Line number: 5754
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+5753	                expand_pos_upper_index = max(all_expand_positions) + 1
+5754	                assert (
+5755	                    len(all_expand_positions)
+5756	                    == expand_pos_upper_index - expand_pos_lower_index
+5757	                )
+5758	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/compiler.py
+ Line number: 5833
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+5832	                    # parameters
+5833	                    assert not extra_params_right
+5834	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/compiler.py
+ Line number: 6033
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+6032	            if add_sentinel_cols is not None:
+6033	                assert use_insertmanyvalues
+6034	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/compiler.py
+ Line number: 6082
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+6081	                        # _get_sentinel_column_for_table.
+6082	                        assert not add_sentinel_cols[0]._insert_sentinel, (
+6083	                            "sentinel selection rules should have prevented "
+6084	                            "us from getting here for this dialect"
+6085	                        )
+6086	
+
+
+ + +
+
+ +
+
+ hardcoded_sql_expressions: Possible SQL injection vector through string-based query construction.
+ Test ID: B608
+ Severity: MEDIUM
+ Confidence: LOW
+ CWE: CWE-89
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/compiler.py
+ Line number: 6224
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b608_hardcoded_sql_expressions.html
+ +
+
+6223	                text += (
+6224	                    f" SELECT {colnames_w_cast} FROM "
+6225	                    f"(VALUES ({insert_single_values_expr})) "
+6226	                    f"AS imp_sen({colnames}, sen_counter) "
+6227	                    "ORDER BY sen_counter"
+6228	                )
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/compiler.py
+ Line number: 6332
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+6331	        if TYPE_CHECKING:
+6332	            assert isinstance(compile_state, UpdateDMLState)
+6333	        update_stmt = compile_state.statement  # type: ignore[assignment]
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/compiler.py
+ Line number: 6463
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+6462	        if warn_linting:
+6463	            assert from_linter is not None
+6464	            from_linter.warn(stmt_type="UPDATE")
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/compiler.py
+ Line number: 6615
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+6614	        if warn_linting:
+6615	            assert from_linter is not None
+6616	            from_linter.warn(stmt_type="DELETE")
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/compiler.py
+ Line number: 7869
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+7868	        if name is None:
+7869	            assert alias is not None
+7870	            return self.quote(alias.name)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/compiler.py
+ Line number: 7899
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+7898	
+7899	        assert name is not None
+7900	        if constraint.__visit_name__ == "index":
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/compiler.py
+ Line number: 7953
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+7952	        name = self.format_constraint(index)
+7953	        assert name is not None
+7954	        return name
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/compiler.py
+ Line number: 7965
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+7964	            if TYPE_CHECKING:
+7965	                assert isinstance(table, NamedFromClause)
+7966	            name = table.name
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/compiler.py
+ Line number: 8008
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+8007	            name = column.name
+8008	            assert name is not None
+8009	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/crud.py
+ Line number: 166
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+165	        kw.pop("accumulate_bind_names", None)
+166	    assert (
+167	        "accumulate_bind_names" not in kw
+168	    ), "Don't know how to handle insert within insert without a CTE"
+169	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/crud.py
+ Line number: 230
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+229	        mp = compile_state._multi_parameters
+230	        assert mp is not None
+231	        spd = mp[0]
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/crud.py
+ Line number: 237
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+236	        stmt_parameter_tuples = compile_state._ordered_values
+237	        assert spd is not None
+238	        spd_str_key = {_column_as_key(key) for key in spd}
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/crud.py
+ Line number: 251
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+250	    elif stmt_parameter_tuples:
+251	        assert spd_str_key is not None
+252	        parameters = {
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/crud.py
+ Line number: 296
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+295	
+296	        assert not compile_state._has_multi_parameters
+297	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/crud.py
+ Line number: 370
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+369	                elif multi_not_in_from:
+370	                    assert compiler.render_table_with_column_in_update_from
+371	                    raise exc.CompileError(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/crud.py
+ Line number: 393
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+392	        # is a multiparams, is not an insert from a select
+393	        assert not stmt._select_names
+394	        multi_extended_values = _extend_values_for_multiparams(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/crud.py
+ Line number: 559
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+558	                if TYPE_CHECKING:
+559	                    assert isinstance(col.table, TableClause)
+560	                return "%s_%s" % (col.table.name, col.key)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/crud.py
+ Line number: 588
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+587	
+588	    assert compiler.stack[-1]["selectable"] is stmt
+589	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/crud.py
+ Line number: 664
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+663	
+664	    assert compile_state.isupdate or compile_state.isinsert
+665	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/crud.py
+ Line number: 1392
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1391	        col = _multiparam_column(c, index)
+1392	        assert isinstance(stmt, dml.Insert)
+1393	        return _create_insert_prefetch_bind_param(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/crud.py
+ Line number: 1513
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1512	    mp = compile_state._multi_parameters
+1513	    assert mp is not None
+1514	    for i, row in enumerate(mp[1:]):
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/ddl.py
+ Line number: 126
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+125	        else:
+126	            assert False, "compiler or dialect is required"
+127	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/ddl.py
+ Line number: 443
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+442	    def stringify_dialect(self):  # type: ignore[override]
+443	        assert not isinstance(self.element, str)
+444	        return self.element.create_drop_stringify_dialect
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/ddl.py
+ Line number: 872
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+871	        self.connection = connection
+872	        assert not kw, f"Unexpected keywords: {kw.keys()}"
+873	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/dml.py
+ Line number: 235
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+234	    def _process_select_values(self, statement: ValuesBase) -> None:
+235	        assert statement._select_names is not None
+236	        parameters: MutableMapping[_DMLColumnElement, Any] = {
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/dml.py
+ Line number: 246
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+245	            # does not allow this construction to occur
+246	            assert False, "This statement already has parameters"
+247	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/dml.py
+ Line number: 330
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+329	            else:
+330	                assert self._multi_parameters
+331	                self._multi_parameters.extend(multi_parameters)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/dml.py
+ Line number: 364
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+363	            self._no_parameters = False
+364	            assert parameters is not None
+365	            self._dict_parameters = dict(parameters)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/dml.py
+ Line number: 1175
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1174	                    # case
+1175	                    assert isinstance(self, Insert)
+1176	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/elements.py
+ Line number: 323
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+322	        if TYPE_CHECKING:
+323	            assert isinstance(self, ClauseElement)
+324	        return dialect.statement_compiler(dialect, self, **kw)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/elements.py
+ Line number: 526
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+525	            if TYPE_CHECKING:
+526	                assert isinstance(self, Executable)
+527	            return connection._execute_clauseelement(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/elements.py
+ Line number: 702
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+701	            if TYPE_CHECKING:
+702	                assert compiled_cache is not None
+703	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/elements.py
+ Line number: 759
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+758	        grouped = self.self_group(against=operators.inv)
+759	        assert isinstance(grouped, ColumnElement)
+760	        return UnaryExpression(grouped, operator=operators.inv)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/elements.py
+ Line number: 1485
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1484	            grouped = self.self_group(against=operators.inv)
+1485	            assert isinstance(grouped, ColumnElement)
+1486	            return UnaryExpression(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/elements.py
+ Line number: 1682
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1681	
+1682	        assert key is not None
+1683	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/elements.py
+ Line number: 1747
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1746	            # 16 bits leftward.  fill extra add_hash on right
+1747	            assert add_hash < (2 << 15)
+1748	            assert seed
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/elements.py
+ Line number: 1748
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1747	            assert add_hash < (2 << 15)
+1748	            assert seed
+1749	            hash_value = (hash_value << 16) | add_hash
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/elements.py
+ Line number: 2883
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2882	        if operators.is_associative(op):
+2883	            assert (
+2884	                negate is None
+2885	            ), f"negate not supported for associative operator {op}"
+2886	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/elements.py
+ Line number: 3008
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+3007	        grouped = self.self_group(against=operators.inv)
+3008	        assert isinstance(grouped, ColumnElement)
+3009	        return UnaryExpression(grouped, operator=operators.inv)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/elements.py
+ Line number: 3120
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+3119	        else:
+3120	            assert lcc
+3121	            # just one element.  return it as a single boolean element,
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/elements.py
+ Line number: 3850
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+3849	        # comparison operators should never call reverse_operate
+3850	        assert not operators.is_comparison(op)
+3851	        raise exc.ArgumentError(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/elements.py
+ Line number: 4071
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+4070	    def self_group(self, against: Optional[OperatorType] = None) -> Self:
+4071	        assert against is operator.getitem
+4072	        return self
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/elements.py
+ Line number: 4121
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+4120	    def _ungroup(self) -> ColumnElement[_T]:
+4121	        assert isinstance(self.element, ColumnElement)
+4122	        return self.element._ungroup()
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/elements.py
+ Line number: 5074
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+5073	            else:
+5074	                assert not TYPE_CHECKING or isinstance(t, NamedFromClause)
+5075	                label = t.name + "_" + name
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/elements.py
+ Line number: 5086
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+5085	                # assert false on it for now
+5086	                assert not isinstance(label, quoted_name)
+5087	                label = quoted_name(label, t.name.quote)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/elements.py
+ Line number: 5314
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+5313	    def __new__(cls, value: str, quote: Optional[bool]) -> quoted_name:
+5314	        assert (
+5315	            value is not None
+5316	        ), "use quoted_name.construct() for None passthrough"
+5317	        if isinstance(value, cls) and (quote is None or value.quote == quote):
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/elements.py
+ Line number: 5445
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+5444	        if TYPE_CHECKING:
+5445	            assert isinstance(self._Annotated__element, Column)
+5446	        return self._Annotated__element.info
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/functions.py
+ Line number: 1600
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1599	    def __init__(self, seq: schema.Sequence, **kw: Any) -> None:
+1600	        assert isinstance(
+1601	            seq, schema.Sequence
+1602	        ), "next_value() accepts a Sequence object as input."
+1603	        self.sequence = seq
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/lambdas.py
+ Line number: 408
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+407	        while parent is not None:
+408	            assert parent.closure_cache_key is not CacheConst.NO_CACHE
+409	            parent_closure_cache_key: Tuple[Any, ...] = (
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/lambdas.py
+ Line number: 451
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+450	    def _resolve_with_args(self, *lambda_args: Any) -> ClauseElement:
+451	        assert isinstance(self._rec, AnalyzedFunction)
+452	        tracker_fn = self._rec.tracker_instrumented_fn
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/lambdas.py
+ Line number: 594
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+593	        if TYPE_CHECKING:
+594	            assert isinstance(self._rec.expected_expr, ClauseElement)
+595	        if self._rec.expected_expr.supports_execution:
+
+
+ + +
+
+ +
+
+ hardcoded_sql_expressions: Possible SQL injection vector through string-based query construction.
+ Test ID: B608
+ Severity: MEDIUM
+ Confidence: LOW
+ CWE: CWE-89
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/lambdas.py
+ Line number: 1045
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b608_hardcoded_sql_expressions.html
+ +
+
+1044	        raise exc.InvalidRequestError(
+1045	            "Closure variable named '%s' inside of lambda callable %s "
+1046	            "does not refer to a cacheable SQL element, and also does not "
+1047	            "appear to be serving as a SQL literal bound value based on "
+1048	            "the default "
+1049	            "SQL expression returned by the function.   This variable "
+1050	            "needs to remain outside the scope of a SQL-generating lambda "
+1051	            "so that a proper cache key may be generated from the "
+1052	            "lambda's state.  Evaluate this variable outside of the "
+1053	            "lambda, set track_on=[<elements>] to explicitly select "
+1054	            "closure elements to track, or set "
+1055	            "track_closure_variables=False to exclude "
+1056	            "closure variables from being part of the cache key."
+1057	            % (variable_name, fn.__code__),
+1058	        ) from from_
+
+
+ + +
+
+ +
+
+ exec_used: Use of exec detected.
+ Test ID: B102
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/lambdas.py
+ Line number: 1264
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b102_exec_used.html
+ +
+
+1263	        vars_ = {"o%d" % i: cell_values[i] for i in argrange}
+1264	        exec(code, vars_, vars_)
+1265	        closure = vars_["make_cells"]()
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/schema.py
+ Line number: 824
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+823	            quote_schema = quote_schema
+824	            assert isinstance(schema, str)
+825	            self.schema = quoted_name(schema, quote_schema)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/schema.py
+ Line number: 948
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+947	
+948	        assert extend_existing
+949	        assert not keep_existing
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/schema.py
+ Line number: 949
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+948	        assert extend_existing
+949	        assert not keep_existing
+950	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/schema.py
+ Line number: 1046
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1045	        if sentinel_is_explicit and explicit_sentinel_col is autoinc_col:
+1046	            assert autoinc_col is not None
+1047	            sentinel_is_autoinc = True
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/schema.py
+ Line number: 1125
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1124	        if the_sentinel is None and self.primary_key:
+1125	            assert autoinc_col is None
+1126	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/schema.py
+ Line number: 1272
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1271	        metadata = parent
+1272	        assert isinstance(metadata, MetaData)
+1273	        metadata._add_table(self.name, self.schema, self)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/schema.py
+ Line number: 2224
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2223	    def _set_type(self, type_: TypeEngine[Any]) -> None:
+2224	        assert self.type._isnull or type_ is self.type
+2225	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/schema.py
+ Line number: 2322
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2321	        table = parent
+2322	        assert isinstance(table, Table)
+2323	        if not self.name:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/schema.py
+ Line number: 3023
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+3022	        else:
+3023	            assert isinstance(self._colspec, str)
+3024	            return self._colspec
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/schema.py
+ Line number: 3121
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+3120	            if isinstance(c, Column):
+3121	                assert c.table is parenttable
+3122	                break
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/schema.py
+ Line number: 3124
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+3123	        else:
+3124	            assert False
+3125	        ######################
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/schema.py
+ Line number: 3147
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+3146	            parent = self.parent
+3147	            assert parent is not None
+3148	            key = parent.key
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/schema.py
+ Line number: 3172
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+3171	    def _set_target_column(self, column: Column[Any]) -> None:
+3172	        assert self.parent is not None
+3173	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/schema.py
+ Line number: 3250
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+3249	    def _set_parent(self, parent: SchemaEventTarget, **kw: Any) -> None:
+3250	        assert isinstance(parent, Column)
+3251	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/schema.py
+ Line number: 3264
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+3263	        self._set_target_column(_column)
+3264	        assert self.constraint is not None
+3265	        self.constraint._validate_dest_table(table)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/schema.py
+ Line number: 3278
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+3277	        # on the hosting Table when attached to the Table.
+3278	        assert isinstance(table, Table)
+3279	        if self.constraint is None:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/schema.py
+ Line number: 3370
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+3369	        if TYPE_CHECKING:
+3370	            assert isinstance(parent, Column)
+3371	        self.column = parent
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/schema.py
+ Line number: 3936
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+3935	        column = parent
+3936	        assert isinstance(column, Column)
+3937	        super()._set_parent(column)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/schema.py
+ Line number: 4035
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+4034	        column = parent
+4035	        assert isinstance(column, Column)
+4036	        self.column = column
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/schema.py
+ Line number: 4189
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+4188	    def _set_parent(self, parent: SchemaEventTarget, **kw: Any) -> None:
+4189	        assert isinstance(parent, (Table, Column))
+4190	        self.parent = parent
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/schema.py
+ Line number: 4245
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+4244	            # this is expected to be an empty list
+4245	            assert not processed_expressions
+4246	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/schema.py
+ Line number: 4276
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+4275	            # such that when all those cols are attached, we autoattach.
+4276	            assert not evt, "Should not reach here on event call"
+4277	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/schema.py
+ Line number: 4330
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+4329	            ]
+4330	            assert len(result) == len(self._pending_colargs)
+4331	            return result
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/schema.py
+ Line number: 4346
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+4345	    def _set_parent(self, parent: SchemaEventTarget, **kw: Any) -> None:
+4346	        assert isinstance(parent, (Table, Column))
+4347	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/schema.py
+ Line number: 4407
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+4406	    def _set_parent(self, parent: SchemaEventTarget, **kw: Any) -> None:
+4407	        assert isinstance(parent, (Column, Table))
+4408	        Constraint._set_parent(self, parent)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/schema.py
+ Line number: 4445
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+4444	
+4445	        assert isinstance(self.parent, Table)
+4446	        c = self.__class__(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/schema.py
+ Line number: 4753
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+4752	            if hasattr(self, "parent"):
+4753	                assert table is self.parent
+4754	            self._set_parent_with_dispatch(table)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/schema.py
+ Line number: 4836
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+4835	        table = parent
+4836	        assert isinstance(table, Table)
+4837	        Constraint._set_parent(self, table)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/schema.py
+ Line number: 4986
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+4985	        table = parent
+4986	        assert isinstance(table, Table)
+4987	        super()._set_parent(table)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/schema.py
+ Line number: 5298
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+5297	        table = parent
+5298	        assert isinstance(table, Table)
+5299	        ColumnCollectionMixin._set_parent(self, table)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/schema.py
+ Line number: 5312
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+5311	        col_expressions = self._col_expressions(table)
+5312	        assert len(expressions) == len(col_expressions)
+5313	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/schema.py
+ Line number: 5321
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+5320	            else:
+5321	                assert False
+5322	        self.expressions = self._table_bound_expressions = exprs
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/schema.py
+ Line number: 6032
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+6031	    def _set_parent(self, parent: SchemaEventTarget, **kw: Any) -> None:
+6032	        assert isinstance(parent, Column)
+6033	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/schema.py
+ Line number: 6178
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+6177	    def _set_parent(self, parent: SchemaEventTarget, **kw: Any) -> None:
+6178	        assert isinstance(parent, Column)
+6179	        if not isinstance(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/selectable.py
+ Line number: 919
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+918	            if "_columns" in self.__dict__:
+919	                assert "primary_key" in self.__dict__
+920	                assert "foreign_keys" in self.__dict__
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/selectable.py
+ Line number: 920
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+919	                assert "primary_key" in self.__dict__
+920	                assert "foreign_keys" in self.__dict__
+921	                return
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/selectable.py
+ Line number: 2106
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2105	    ) -> None:
+2106	        assert sampling is not None
+2107	        functions = util.preloaded.sql_functions
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/selectable.py
+ Line number: 2261
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2260	        """
+2261	        assert is_select_statement(
+2262	            self.element
+2263	        ), f"CTE element f{self.element} does not support union()"
+2264	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/selectable.py
+ Line number: 2293
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2292	
+2293	        assert is_select_statement(
+2294	            self.element
+2295	        ), f"CTE element f{self.element} does not support union_all()"
+2296	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/selectable.py
+ Line number: 2407
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2406	                if TYPE_CHECKING:
+2407	                    assert is_column_element(c)
+2408	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/selectable.py
+ Line number: 2413
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2412	                if TYPE_CHECKING:
+2413	                    assert is_column_element(c)
+2414	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/selectable.py
+ Line number: 2455
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2454	                if TYPE_CHECKING:
+2455	                    assert is_column_element(c)
+2456	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/selectable.py
+ Line number: 2479
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2478	                            # you need two levels of duplication to be here
+2479	                            assert hash(names[required_label_name]) == hash(c)
+2480	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/selectable.py
+ Line number: 4831
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+4830	            elif TYPE_CHECKING:
+4831	                assert is_column_element(c)
+4832	
+
+
+ + +
+
+ +
+
+ hardcoded_sql_expressions: Possible SQL injection vector through string-based query construction.
+ Test ID: B608
+ Severity: MEDIUM
+ Confidence: LOW
+ CWE: CWE-89
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/selectable.py
+ Line number: 4999
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b608_hardcoded_sql_expressions.html
+ +
+
+4998	                raise exc.InvalidRequestError(
+4999	                    "Select statement '%r"
+5000	                    "' returned no FROM clauses "
+5001	                    "due to auto-correlation; "
+5002	                    "specify correlate(<tables>) "
+5003	                    "to control correlation "
+5004	                    "manually." % self.statement
+5005	                )
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/selectable.py
+ Line number: 5053
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+5052	                if onclause is not None:
+5053	                    assert isinstance(onclause, ColumnElement)
+5054	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/selectable.py
+ Line number: 5076
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+5075	            if TYPE_CHECKING:
+5076	                assert isinstance(right, FromClause)
+5077	                if onclause is not None:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/selectable.py
+ Line number: 5078
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+5077	                if onclause is not None:
+5078	                    assert isinstance(onclause, ColumnElement)
+5079	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/selectable.py
+ Line number: 5099
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+5098	            else:
+5099	                assert left is not None
+5100	                self.from_clauses = self.from_clauses + (
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/selectable.py
+ Line number: 6249
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+6248	
+6249	        assert isinstance(self._where_criteria, tuple)
+6250	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/selectable.py
+ Line number: 6956
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+6955	
+6956	        assert isinstance(self.element, ScalarSelect)
+6957	        element = self.element.element
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/selectable.py
+ Line number: 7191
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+7190	        if TYPE_CHECKING:
+7191	            assert isinstance(fromclause, Subquery)
+7192	
+
+
+ + +
+
+ +
+
+ blacklist: Consider possible security implications associated with pickle module.
+ Test ID: B403
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-502
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/sqltypes.py
+ Line number: 17
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_imports.html#b403-import-pickle
+ +
+
+16	import json
+17	import pickle
+18	from typing import Any
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/sqltypes.py
+ Line number: 112
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+111	            if TYPE_CHECKING:
+112	                assert isinstance(self.type, HasExpressionLookup)
+113	            lookup = self.type._expression_adaptations.get(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/sqltypes.py
+ Line number: 724
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+723	    def _literal_processor_portion(self, dialect, _portion=None):
+724	        assert _portion in (None, 0, -1)
+725	        if _portion is not None:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/sqltypes.py
+ Line number: 1518
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1517	            self.enum_class = enums[0]  # type: ignore[assignment]
+1518	            assert self.enum_class is not None
+1519	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/sqltypes.py
+ Line number: 1549
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1548	        typ = self._resolve_for_python_type(tv, tv, tv)
+1549	        assert typ is not None
+1550	        return typ
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/sqltypes.py
+ Line number: 1764
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1763	        kw.setdefault("_create_events", False)
+1764	        assert "_enums" in kw
+1765	        return impltype(**kw)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/sqltypes.py
+ Line number: 1798
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1797	        )
+1798	        assert e.table is table
+1799	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/sqltypes.py
+ Line number: 2038
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2037	        )
+2038	        assert e.table is table
+2039	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/sqltypes.py
+ Line number: 2183
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2182	        if TYPE_CHECKING:
+2183	            assert isinstance(self.impl_instance, DateTime)
+2184	        impl_processor = self.impl_instance.bind_processor(dialect)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/sqltypes.py
+ Line number: 2215
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2214	        if TYPE_CHECKING:
+2215	            assert isinstance(self.impl_instance, DateTime)
+2216	        impl_processor = self.impl_instance.result_processor(dialect, coltype)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/traversals.py
+ Line number: 360
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+359	                # TODO: use abc classes
+360	                assert False
+361	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/traversals.py
+ Line number: 549
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+548	
+549	                assert left_visit_sym is not None
+550	                assert left_attrname is not None
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/traversals.py
+ Line number: 550
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+549	                assert left_visit_sym is not None
+550	                assert left_attrname is not None
+551	                assert right_attrname is not None
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/traversals.py
+ Line number: 551
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+550	                assert left_attrname is not None
+551	                assert right_attrname is not None
+552	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/traversals.py
+ Line number: 554
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+553	                dispatch = self.dispatch(left_visit_sym)
+554	                assert dispatch is not None, (
+555	                    f"{self.__class__} has no dispatch for "
+556	                    f"'{self._dispatch_lookup[left_visit_sym]}'"
+557	                )
+558	                left_child = operator.attrgetter(left_attrname)(left)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/type_api.py
+ Line number: 987
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+986	            # this can't be self, else we create a cycle
+987	            assert impl is not self
+988	            d: _TypeMemoDict = {"impl": impl, "result": {}}
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/type_api.py
+ Line number: 1745
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1744	            if TYPE_CHECKING:
+1745	                assert isinstance(self.expr.type, TypeDecorator)
+1746	            kwargs["_python_is_types"] = self.expr.type.coerce_to_is_types
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/type_api.py
+ Line number: 1753
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1752	            if TYPE_CHECKING:
+1753	                assert isinstance(self.expr.type, TypeDecorator)
+1754	            kwargs["_python_is_types"] = self.expr.type.coerce_to_is_types
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/util.py
+ Line number: 234
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+233	            if resolve_ambiguity:
+234	                assert cols_in_onclause is not None
+235	                if set(f.c).union(s.c).issuperset(cols_in_onclause):
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/util.py
+ Line number: 421
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+420	        elif isinstance(element, _textual_label_reference):
+421	            assert False, "can't unwrap a textual label reference"
+422	        return None
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/util.py
+ Line number: 695
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+694	            else:
+695	                assert False, "Unknown parameter type %s" % (
+696	                    type(multi_params[0])
+697	                )
+698	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/util.py
+ Line number: 863
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+862	        if prevright is not None:
+863	            assert right is not None
+864	            prevright.left = right
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/util.py
+ Line number: 1197
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1196	        if TYPE_CHECKING:
+1197	            assert isinstance(col, KeyedColumnElement)
+1198	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/util.py
+ Line number: 1207
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1206	        if TYPE_CHECKING:
+1207	            assert isinstance(col, KeyedColumnElement)
+1208	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/util.py
+ Line number: 1336
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1335	    def chain(self, visitor: ExternalTraversal) -> ColumnAdapter:
+1336	        assert isinstance(visitor, ColumnAdapter)
+1337	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/util.py
+ Line number: 1463
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1462	        else:
+1463	            assert offset_clause is not None
+1464	            offset_clause = _offset_or_limit_clause(offset_clause)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/visitors.py
+ Line number: 584
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+583	            sym_name = sym.value
+584	            assert sym_name not in lookup, sym_name
+585	            lookup[sym] = lookup[sym_name] = visit_key
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/assertions.py
+ Line number: 190
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+189	        # block will assert our messages
+190	        assert _SEEN is not None
+191	        assert _EXC_CLS is not None
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/assertions.py
+ Line number: 191
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+190	        assert _SEEN is not None
+191	        assert _EXC_CLS is not None
+192	        _FILTERS.extend(filters)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/assertions.py
+ Line number: 249
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+248	                if assert_:
+249	                    assert not seen, "Warnings were not seen: %s" % ", ".join(
+250	                        "%r" % (s.pattern if regex else s) for s in seen
+251	                    )
+252	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/assertions.py
+ Line number: 271
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+270	    deviance = int(expected * variance)
+271	    assert (
+272	        abs(received - expected) < deviance
+273	    ), "Given int value %s is not within %d%% of expected value %s" % (
+274	        received,
+275	        variance * 100,
+276	        expected,
+277	    )
+278	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/assertions.py
+ Line number: 281
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+280	def eq_regex(a, b, msg=None, flags=0):
+281	    assert re.match(b, a, flags), msg or "%r !~ %r" % (a, b)
+282	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/assertions.py
+ Line number: 286
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+285	    """Assert a == b, with repr messaging on failure."""
+286	    assert a == b, msg or "%r != %r" % (a, b)
+287	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/assertions.py
+ Line number: 291
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+290	    """Assert a != b, with repr messaging on failure."""
+291	    assert a != b, msg or "%r == %r" % (a, b)
+292	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/assertions.py
+ Line number: 296
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+295	    """Assert a <= b, with repr messaging on failure."""
+296	    assert a <= b, msg or "%r != %r" % (a, b)
+297	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/assertions.py
+ Line number: 300
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+299	def is_instance_of(a, b, msg=None):
+300	    assert isinstance(a, b), msg or "%r is not an instance of %r" % (a, b)
+301	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/assertions.py
+ Line number: 321
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+320	    """Assert a is b, with repr messaging on failure."""
+321	    assert a is b, msg or "%r is not %r" % (a, b)
+322	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/assertions.py
+ Line number: 326
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+325	    """Assert a is not b, with repr messaging on failure."""
+326	    assert a is not b, msg or "%r is %r" % (a, b)
+327	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/assertions.py
+ Line number: 335
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+334	    """Assert a in b, with repr messaging on failure."""
+335	    assert a in b, msg or "%r not in %r" % (a, b)
+336	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/assertions.py
+ Line number: 340
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+339	    """Assert a in not b, with repr messaging on failure."""
+340	    assert a not in b, msg or "%r is in %r" % (a, b)
+341	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/assertions.py
+ Line number: 349
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+348	    """Assert a.startswith(fragment), with repr messaging on failure."""
+349	    assert a.startswith(fragment), msg or "%r does not start with %r" % (
+350	        a,
+351	        fragment,
+352	    )
+353	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/assertions.py
+ Line number: 363
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+362	
+363	    assert a == b, msg or "%r != %r" % (a, b)
+364	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/assertions.py
+ Line number: 380
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+379	    ):
+380	        assert False, (
+381	            "Exception %r was correctly raised but did not set a cause, "
+382	            "within context %r as its cause."
+383	            % (exception, exception.__context__)
+384	        )
+385	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/assertions.py
+ Line number: 476
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+475	            error_as_string = str(err)
+476	            assert re.search(msg, error_as_string, re.UNICODE), "%r !~ %s" % (
+477	                msg,
+478	                error_as_string,
+479	            )
+480	        if check_context and not are_we_already_in_a_traceback:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/assertions.py
+ Line number: 492
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+491	    # assert outside the block so it works for AssertionError too !
+492	    assert success, "Callable did not raise an exception"
+493	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/assertions.py
+ Line number: 752
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+751	                    msg = "Expected to find bindparam %r in %r" % (v, stmt)
+752	                    assert False, msg
+753	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/assertions.py
+ Line number: 777
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+776	    ):
+777	        assert len(table.c) == len(reflected_table.c)
+778	        for c, reflected_c in zip(table.c, reflected_table.c):
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/assertions.py
+ Line number: 780
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+779	            eq_(c.name, reflected_c.name)
+780	            assert reflected_c is reflected_table.c[c.name]
+781	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/assertions.py
+ Line number: 788
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+787	                msg = "Type '%s' doesn't correspond to type '%s'"
+788	                assert isinstance(reflected_c.type, type(c.type)), msg % (
+789	                    reflected_c.type,
+790	                    c.type,
+791	                )
+792	            else:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/assertions.py
+ Line number: 804
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+803	            if c.server_default:
+804	                assert isinstance(
+805	                    reflected_c.server_default, schema.FetchedValue
+806	                )
+807	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/assertions.py
+ Line number: 809
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+808	        if strict_constraints:
+809	            assert len(table.primary_key) == len(reflected_table.primary_key)
+810	            for c in table.primary_key:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/assertions.py
+ Line number: 811
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+810	            for c in table.primary_key:
+811	                assert reflected_table.primary_key.columns[c.name] is not None
+812	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/assertions.py
+ Line number: 814
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+813	    def assert_types_base(self, c1, c2):
+814	        assert c1.type._compare_type_affinity(
+815	            c2.type
+816	        ), "On column %r, type '%s' doesn't correspond to type '%s'" % (
+817	            c1.name,
+818	            c1.type,
+819	            c2.type,
+820	        )
+821	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/assertsql.py
+ Line number: 32
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+31	    def no_more_statements(self):
+32	        assert False, (
+33	            "All statements are complete, but pending "
+34	            "assertion rules remain"
+35	        )
+36	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/assertsql.py
+ Line number: 103
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+102	                # to look like all the current RETURNING dialects
+103	                assert dialect.insert_executemany_returning
+104	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/assertsql.py
+ Line number: 351
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+350	        if self.count != self._statement_count:
+351	            assert False, "desired statement count %d does not match %d" % (
+352	                self.count,
+353	                self._statement_count,
+354	            )
+355	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/assertsql.py
+ Line number: 470
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+469	            elif rule.errormessage:
+470	                assert False, rule.errormessage
+471	        if observed:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/assertsql.py
+ Line number: 472
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+471	        if observed:
+472	            assert False, "Additional SQL statements remain:\n%s" % observed
+473	        elif not rule.is_consumed:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/config.py
+ Line number: 389
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+388	    def push_engine(cls, db, namespace):
+389	        assert _current, "Can't push without a default Config set up"
+390	        cls.push(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/engines.py
+ Line number: 61
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+60	
+61	        assert scope in ("class", "global", "function", "fixture")
+62	        self.testing_engines[scope].add(engine)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/engines.py
+ Line number: 170
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+169	                    # are not easily preventable
+170	                    assert (
+171	                        False
+172	                    ), "%d connection recs not cleared after test suite" % (ln)
+173	        if config.options and config.options.low_connections:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/engines.py
+ Line number: 186
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+185	            if rec.is_valid:
+186	                assert False
+187	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/engines.py
+ Line number: 259
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+258	            curs.execute("select 1")
+259	            assert False, "simulated connect failure didn't work"
+260	        else:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/engines.py
+ Line number: 420
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+419	        recv = [re.sub(r"[\n\t]", "", str(s)) for s in buffer]
+420	        assert recv == stmts, recv
+421	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/engines.py
+ Line number: 427
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+426	    engine = create_mock_engine(dialect_name + "://", executor)
+427	    assert not hasattr(engine, "mock")
+428	    engine.mock = buffer
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/exclusions.py
+ Line number: 242
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+241	        else:
+242	            assert False, "unknown predicate type: %s" % predicate
+243	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/exclusions.py
+ Line number: 310
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+309	        if self.op is not None:
+310	            assert driver is None, "DBAPI version specs not supported yet"
+311	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/exclusions.py
+ Line number: 473
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+472	def against(config, *queries):
+473	    assert queries, "no queries sent!"
+474	    return OrPredicate([Predicate.as_predicate(query) for query in queries])(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/fixtures/base.py
+ Line number: 50
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+49	    def assert_(self, val, msg=None):
+50	        assert val, msg
+51	
+
+
+ + +
+
+ +
+
+ try_except_pass: Try, Except, Pass detected.
+ Test ID: B110
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/fixtures/base.py
+ Line number: 101
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b110_try_except_pass.html
+ +
+
+100	                r.all()
+101	            except:
+102	                pass
+103	        for r in to_close:
+
+
+ + +
+
+ +
+
+ try_except_pass: Try, Except, Pass detected.
+ Test ID: B110
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/fixtures/base.py
+ Line number: 106
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b110_try_except_pass.html
+ +
+
+105	                r.close()
+106	            except:
+107	                pass
+108	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/fixtures/base.py
+ Line number: 230
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+229	            name = dialect_cls.name
+230	            assert name, "name is required"
+231	            registry.impls[name] = dialect_cls
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/fixtures/base.py
+ Line number: 236
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+235	
+236	        assert name is not None
+237	        del registry.impls[name]
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/fixtures/mypy.py
+ Line number: 324
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+323	                    print("Remaining messages:", extra, sep="\n")
+324	                assert False, "expected messages not found, see stdout"
+325	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/fixtures/mypy.py
+ Line number: 329
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+328	                print("\n".join(msg for _, msg in output))
+329	                assert False, "errors and/or notes remain, see stdout"
+330	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/fixtures/orm.py
+ Line number: 119
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+118	            def __init_subclass__(cls) -> None:
+119	                assert cls_registry is not None
+120	                cls_registry[cls.__name__] = cls
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/fixtures/orm.py
+ Line number: 175
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+174	            def __init_subclass__(cls, **kw) -> None:
+175	                assert cls_registry is not None
+176	                cls_registry[cls.__name__] = cls
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/fixtures/sql.py
+ Line number: 86
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+85	                cls.run_create_tables = "each"
+86	            assert cls.run_inserts in ("each", None)
+87	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/fixtures/sql.py
+ Line number: 328
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+327	        if a_key is None:
+328	            assert a._annotations.get("nocache")
+329	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/fixtures/sql.py
+ Line number: 330
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+329	
+330	            assert b_key is None
+331	        else:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/fixtures/sql.py
+ Line number: 336
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+335	            for a_param, b_param in zip(a_key.bindparams, b_key.bindparams):
+336	                assert a_param.compare(b_param, compare_values=compare_values)
+337	        return a_key, b_key
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/fixtures/sql.py
+ Line number: 358
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+357	                    if a_key is None:
+358	                        assert case_a[a]._annotations.get("nocache")
+359	                    if b_key is None:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/fixtures/sql.py
+ Line number: 360
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+359	                    if b_key is None:
+360	                        assert case_b[b]._annotations.get("nocache")
+361	                    continue
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/plugin/bootstrap.py
+ Line number: 39
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+38	    spec = importlib.util.spec_from_file_location(name, path)
+39	    assert spec is not None
+40	    assert spec.loader is not None
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/plugin/bootstrap.py
+ Line number: 40
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+39	    assert spec is not None
+40	    assert spec.loader is not None
+41	    mod = importlib.util.module_from_spec(spec)
+
+
+ + +
+
+ +
+
+ exec_used: Use of exec detected.
+ Test ID: B102
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/plugin/pytestplugin.py
+ Line number: 645
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b102_exec_used.html
+ +
+
+644	        # in format_argpsec_plus()
+645	        exec(code, env)
+646	        return env[fn_name]
+
+
+ + +
+
+ +
+
+ blacklist: Standard pseudo-random generators are not suitable for security/cryptographic purposes.
+ Test ID: B311
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-330
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_ddl.py
+ Line number: 214
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b311-random
+ +
+
+213	                "_".join(
+214	                    "".join(random.choice("abcdef") for j in range(20))
+215	                    for i in range(10)
+
+
+ + +
+
+ +
+
+ blacklist: Standard pseudo-random generators are not suitable for security/cryptographic purposes.
+ Test ID: B311
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-330
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_ddl.py
+ Line number: 259
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b311-random
+ +
+
+258	                "_".join(
+259	                    "".join(random.choice("abcdef") for j in range(30))
+260	                    for i in range(10)
+
+
+ + +
+
+ +
+
+ blacklist: Standard pseudo-random generators are not suitable for security/cryptographic purposes.
+ Test ID: B311
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-330
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_ddl.py
+ Line number: 287
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b311-random
+ +
+
+286	                "_".join(
+287	                    "".join(random.choice("abcdef") for j in range(30))
+288	                    for i in range(10)
+
+
+ + +
+
+ +
+
+ blacklist: Standard pseudo-random generators are not suitable for security/cryptographic purposes.
+ Test ID: B311
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-330
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_ddl.py
+ Line number: 315
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b311-random
+ +
+
+314	                "_".join(
+315	                    "".join(random.choice("abcdef") for j in range(30))
+316	                    for i in range(10)
+
+
+ + +
+
+ +
+
+ blacklist: Standard pseudo-random generators are not suitable for security/cryptographic purposes.
+ Test ID: B311
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-330
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_ddl.py
+ Line number: 343
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b311-random
+ +
+
+342	                "_".join(
+343	                    "".join(random.choice("abcdef") for j in range(30))
+344	                    for i in range(10)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_ddl.py
+ Line number: 379
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+378	
+379	        assert len(actual_name) > 255
+380	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_dialect.py
+ Line number: 143
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+142	                conn.execute(select(literal_column("méil")))
+143	                assert False
+144	            except exc.DBAPIError as err:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_dialect.py
+ Line number: 147
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+146	
+147	                assert str(err.orig) in str(err)
+148	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_dialect.py
+ Line number: 149
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+148	
+149	            assert isinstance(err_str, str)
+150	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_insert.py
+ Line number: 161
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+160	        r = connection.execute(stmt, data)
+161	        assert not r.returns_rows
+162	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_insert.py
+ Line number: 168
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+167	        )
+168	        assert r._soft_closed
+169	        assert not r.closed
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_insert.py
+ Line number: 169
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+168	        assert r._soft_closed
+169	        assert not r.closed
+170	        assert r.is_insert
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_insert.py
+ Line number: 170
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+169	        assert not r.closed
+170	        assert r.is_insert
+171	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_insert.py
+ Line number: 177
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+176	        # case, the row had to have been consumed at least.
+177	        assert not r.returns_rows or r.fetchone() is None
+178	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_insert.py
+ Line number: 188
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+187	        )
+188	        assert r._soft_closed
+189	        assert not r.closed
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_insert.py
+ Line number: 189
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+188	        assert r._soft_closed
+189	        assert not r.closed
+190	        assert r.is_insert
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_insert.py
+ Line number: 190
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+189	        assert not r.closed
+190	        assert r.is_insert
+191	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_insert.py
+ Line number: 196
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+195	        # "returns rows"
+196	        assert r.returns_rows
+197	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_insert.py
+ Line number: 210
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+209	        r = connection.execute(self.tables.autoinc_pk.insert())
+210	        assert r._soft_closed
+211	        assert not r.closed
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_insert.py
+ Line number: 211
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+210	        assert r._soft_closed
+211	        assert not r.closed
+212	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_insert.py
+ Line number: 223
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+222	        r = connection.execute(self.tables.autoinc_pk.insert(), [{}, {}, {}])
+223	        assert r._soft_closed
+224	        assert not r.closed
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_insert.py
+ Line number: 224
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+223	        assert r._soft_closed
+224	        assert not r.closed
+225	
+
+
+ + +
+
+ +
+
+ hardcoded_sql_expressions: Possible SQL injection vector through string-based query construction.
+ Test ID: B608
+ Severity: MEDIUM
+ Confidence: LOW
+ CWE: CWE-89
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_reflection.py
+ Line number: 111
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b608_hardcoded_sql_expressions.html
+ +
+
+110	            query = (
+111	                "CREATE VIEW %s.vv AS SELECT id, data FROM %s.test_table_s"
+112	                % (
+113	                    config.test_schema,
+114	                    config.test_schema,
+115	                )
+116	            )
+
+
+ + +
+
+ +
+
+ hardcoded_sql_expressions: Possible SQL injection vector through string-based query construction.
+ Test ID: B608
+ Severity: MEDIUM
+ Confidence: LOW
+ CWE: CWE-89
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_reflection.py
+ Line number: 149
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b608_hardcoded_sql_expressions.html
+ +
+
+148	                DDL(
+149	                    "create temporary view user_tmp_v as "
+150	                    "select * from user_tmp_%s" % config.ident
+151	                ),
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_reflection.py
+ Line number: 263
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+262	        meth = self._has_index(kind, connection)
+263	        assert meth("test_table", "my_idx")
+264	        assert not meth("test_table", "my_idx_s")
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_reflection.py
+ Line number: 264
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+263	        assert meth("test_table", "my_idx")
+264	        assert not meth("test_table", "my_idx_s")
+265	        assert not meth("nonexistent_table", "my_idx")
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_reflection.py
+ Line number: 265
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+264	        assert not meth("test_table", "my_idx_s")
+265	        assert not meth("nonexistent_table", "my_idx")
+266	        assert not meth("test_table", "nonexistent_idx")
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_reflection.py
+ Line number: 266
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+265	        assert not meth("nonexistent_table", "my_idx")
+266	        assert not meth("test_table", "nonexistent_idx")
+267	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_reflection.py
+ Line number: 268
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+267	
+268	        assert not meth("test_table", "my_idx_2")
+269	        assert not meth("test_table_2", "my_idx_3")
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_reflection.py
+ Line number: 269
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+268	        assert not meth("test_table", "my_idx_2")
+269	        assert not meth("test_table_2", "my_idx_3")
+270	        idx = Index("my_idx_2", self.tables.test_table.c.data2)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_reflection.py
+ Line number: 281
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+280	            if kind == "inspector":
+281	                assert not meth("test_table", "my_idx_2")
+282	                assert not meth("test_table_2", "my_idx_3")
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_reflection.py
+ Line number: 282
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+281	                assert not meth("test_table", "my_idx_2")
+282	                assert not meth("test_table_2", "my_idx_3")
+283	                meth.__self__.clear_cache()
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_reflection.py
+ Line number: 284
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+283	                meth.__self__.clear_cache()
+284	            assert meth("test_table", "my_idx_2") is True
+285	            assert meth("test_table_2", "my_idx_3") is True
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_reflection.py
+ Line number: 285
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+284	            assert meth("test_table", "my_idx_2") is True
+285	            assert meth("test_table_2", "my_idx_3") is True
+286	        finally:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_reflection.py
+ Line number: 294
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+293	        meth = self._has_index(kind, connection)
+294	        assert meth("test_table", "my_idx_s", schema=config.test_schema)
+295	        assert not meth("test_table", "my_idx", schema=config.test_schema)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_reflection.py
+ Line number: 295
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+294	        assert meth("test_table", "my_idx_s", schema=config.test_schema)
+295	        assert not meth("test_table", "my_idx", schema=config.test_schema)
+296	        assert not meth(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_reflection.py
+ Line number: 296
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+295	        assert not meth("test_table", "my_idx", schema=config.test_schema)
+296	        assert not meth(
+297	            "nonexistent_table", "my_idx_s", schema=config.test_schema
+298	        )
+299	        assert not meth(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_reflection.py
+ Line number: 299
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+298	        )
+299	        assert not meth(
+300	            "test_table", "nonexistent_idx_s", schema=config.test_schema
+301	        )
+302	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_reflection.py
+ Line number: 369
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+368	
+369	        assert o2.c.ref.references(t1.c[0])
+370	        if use_composite:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_reflection.py
+ Line number: 371
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+370	        if use_composite:
+371	            assert o2.c.ref2.references(t1.c[1])
+372	
+
+
+ + +
+
+ +
+
+ hardcoded_sql_expressions: Possible SQL injection vector through string-based query construction.
+ Test ID: B608
+ Severity: MEDIUM
+ Confidence: LOW
+ CWE: CWE-89
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_reflection.py
+ Line number: 513
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b608_hardcoded_sql_expressions.html
+ +
+
+512	            for name in names:
+513	                query = "CREATE VIEW %s AS SELECT * FROM %s" % (
+514	                    config.db.dialect.identifier_preparer.quote(
+515	                        "view %s" % name
+516	                    ),
+517	                    config.db.dialect.identifier_preparer.quote(name),
+518	                )
+519	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_reflection.py
+ Line number: 553
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+552	        insp = inspect(config.db)
+553	        assert insp.get_view_definition("view %s" % name)
+554	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_reflection.py
+ Line number: 558
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+557	        insp = inspect(config.db)
+558	        assert insp.get_columns(name)
+559	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_reflection.py
+ Line number: 563
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+562	        insp = inspect(config.db)
+563	        assert insp.get_pk_constraint(name)
+564	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_reflection.py
+ Line number: 569
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+568	        insp = inspect(config.db)
+569	        assert insp.get_foreign_keys(name)
+570	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_reflection.py
+ Line number: 575
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+574	        insp = inspect(config.db)
+575	        assert insp.get_indexes(name)
+576	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_reflection.py
+ Line number: 581
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+580	        insp = inspect(config.db)
+581	        assert insp.get_unique_constraints(name)
+582	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_reflection.py
+ Line number: 587
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+586	        insp = inspect(config.db)
+587	        assert insp.get_table_comment(name)
+588	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_reflection.py
+ Line number: 593
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+592	        insp = inspect(config.db)
+593	        assert insp.get_check_constraints(name)
+594	
+
+
+ + +
+
+ +
+
+ hardcoded_sql_expressions: Possible SQL injection vector through string-based query construction.
+ Test ID: B608
+ Severity: MEDIUM
+ Confidence: LOW
+ CWE: CWE-89
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_reflection.py
+ Line number: 845
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b608_hardcoded_sql_expressions.html
+ +
+
+844	                DDL(
+845	                    "create temporary view user_tmp_v as "
+846	                    "select * from user_tmp_%s" % config.ident
+847	                ),
+
+
+ + +
+
+ +
+
+ hardcoded_sql_expressions: Possible SQL injection vector through string-based query construction.
+ Test ID: B608
+ Severity: MEDIUM
+ Confidence: LOW
+ CWE: CWE-89
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_reflection.py
+ Line number: 864
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b608_hardcoded_sql_expressions.html
+ +
+
+863	            query = (
+864	                f"CREATE {prefix}VIEW {view_name} AS SELECT * FROM {fullname}"
+865	            )
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_reflection.py
+ Line number: 1573
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1572	        inspect(engine)
+1573	        assert hasattr(engine.dialect, "default_schema_name")
+1574	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_reflection.py
+ Line number: 1757
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1756	                if not col.primary_key:
+1757	                    assert cols[i]["default"] is None
+1758	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_reflection.py
+ Line number: 2057
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2056	        index_names = [idx["name"] for idx in indexes]
+2057	        assert idx_name in index_names, f"Expected {idx_name} in {index_names}"
+2058	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_reflection.py
+ Line number: 2174
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2173	
+2174	        assert not idx_names.intersection(uq_names)
+2175	        if names_that_duplicate_index:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_reflection.py
+ Line number: 2258
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2257	            id_ = {c["name"]: c for c in cols}[cname]
+2258	            assert id_.get("autoincrement", True)
+2259	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_reflection.py
+ Line number: 2697
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2696	        m.reflect(connection)
+2697	        assert set(m.tables).intersection(["empty"])
+2698	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_reflection.py
+ Line number: 3037
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+3036	        ):
+3037	            assert isinstance(typ, sql_types.Numeric)
+3038	            eq_(typ.precision, 18)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_reflection.py
+ Line number: 3053
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+3052	        if issubclass(type_, sql_types.VARCHAR):
+3053	            assert isinstance(typ, sql_types.VARCHAR)
+3054	        elif issubclass(type_, sql_types.CHAR):
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_reflection.py
+ Line number: 3055
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+3054	        elif issubclass(type_, sql_types.CHAR):
+3055	            assert isinstance(typ, sql_types.CHAR)
+3056	        else:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_reflection.py
+ Line number: 3057
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+3056	        else:
+3057	            assert isinstance(typ, sql_types.String)
+3058	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_reflection.py
+ Line number: 3060
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+3059	        eq_(typ.length, 52)
+3060	        assert isinstance(typ.length, int)
+3061	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_reflection.py
+ Line number: 3238
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+3237	        t1_ref = m2.tables["t1"]
+3238	        assert t2_ref.c.t1id.references(t1_ref.c.id)
+3239	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_reflection.py
+ Line number: 3244
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+3243	        )
+3244	        assert m3.tables["t2"].c.t1id.references(m3.tables["t1"].c.id)
+3245	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_results.py
+ Line number: 384
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+383	            ).exec_driver_sql(self.stringify("select 1"))
+384	            assert self._is_server_side(result.cursor)
+385	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_results.py
+ Line number: 408
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+407	            result = conn.execution_options(stream_results=False).execute(s)
+408	            assert not self._is_server_side(result.cursor)
+409	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_results.py
+ Line number: 421
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+420	            result = conn.execute(s1.select())
+421	            assert not self._is_server_side(result.cursor)
+422	            result.close()
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_results.py
+ Line number: 427
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+426	            result = conn.execute(s2)
+427	            assert not self._is_server_side(result.cursor)
+428	            result.close()
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_rowcount.py
+ Line number: 116
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+115	
+116	        assert r.rowcount in (-1, 3)
+117	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_rowcount.py
+ Line number: 127
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+126	        )
+127	        assert r.rowcount == 3
+128	
+
+
+ + +
+
+ +
+
+ hardcoded_sql_expressions: Possible SQL injection vector through string-based query construction.
+ Test ID: B608
+ Severity: MEDIUM
+ Confidence: LOW
+ CWE: CWE-89
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_select.py
+ Line number: 1067
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b608_hardcoded_sql_expressions.html
+ +
+
+1066	            CursorSQL(
+1067	                "SELECT some_table.id \nFROM some_table "
+1068	                "\nWHERE (some_table.x, some_table.y) "
+1069	                "IN (%s(5, 10), (12, 18))"
+1070	                % ("VALUES " if config.db.dialect.tuple_in_values else ""),
+1071	                () if config.db.dialect.positional else {},
+
+
+ + +
+
+ +
+
+ hardcoded_sql_expressions: Possible SQL injection vector through string-based query construction.
+ Test ID: B608
+ Severity: MEDIUM
+ Confidence: LOW
+ CWE: CWE-89
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_select.py
+ Line number: 1091
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b608_hardcoded_sql_expressions.html
+ +
+
+1090	            CursorSQL(
+1091	                "SELECT some_table.id \nFROM some_table "
+1092	                "\nWHERE (some_table.x, some_table.z) "
+1093	                "IN (%s(5, 'z1'), (12, 'z3'))"
+1094	                % ("VALUES " if config.db.dialect.tuple_in_values else ""),
+1095	                () if config.db.dialect.positional else {},
+
+
+ + +
+
+ +
+
+ hardcoded_sql_expressions: Possible SQL injection vector through string-based query construction.
+ Test ID: B608
+ Severity: MEDIUM
+ Confidence: LOW
+ CWE: CWE-89
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_sequence.py
+ Line number: 185
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b608_hardcoded_sql_expressions.html
+ +
+
+184	            stmt,
+185	            "INSERT INTO x (y, q) VALUES (%s, 5)" % (seq_nextval,),
+186	            literal_binds=True,
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_types.py
+ Line number: 127
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+126	            rows = connection.execute(stmt).all()
+127	            assert rows, "No rows returned"
+128	            for row in rows:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_types.py
+ Line number: 132
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+131	                    value = filter_(value)
+132	                assert value in output
+133	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_types.py
+ Line number: 175
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+174	        eq_(row, (self.data,))
+175	        assert isinstance(row[0], str)
+176	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_types.py
+ Line number: 190
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+189	        for row in rows:
+190	            assert isinstance(row[0], str)
+191	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_types.py
+ Line number: 601
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+600	        eq_(row, (compare,))
+601	        assert isinstance(row[0], type(compare))
+602	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_types.py
+ Line number: 616
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+615	        eq_(row, (compare,))
+616	        assert isinstance(row[0], type(compare))
+617	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_types.py
+ Line number: 857
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+856	
+857	            assert isinstance(row[0], int)
+858	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_types.py
+ Line number: 1249
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1248	        eq_(row, (True, False))
+1249	        assert isinstance(row[0], bool)
+1250	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_types.py
+ Line number: 1659
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1658	        else:
+1659	            assert False
+1660	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_types.py
+ Line number: 1716
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1715	        else:
+1716	            assert False
+1717	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_update_delete.py
+ Line number: 48
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+47	        )
+48	        assert not r.is_insert
+49	        assert not r.returns_rows
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_update_delete.py
+ Line number: 49
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+48	        assert not r.is_insert
+49	        assert not r.returns_rows
+50	        assert r.rowcount == 1
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_update_delete.py
+ Line number: 50
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+49	        assert not r.returns_rows
+50	        assert r.rowcount == 1
+51	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_update_delete.py
+ Line number: 60
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+59	        r = connection.execute(t.delete().where(t.c.id == 2))
+60	        assert not r.is_insert
+61	        assert not r.returns_rows
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_update_delete.py
+ Line number: 61
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+60	        assert not r.is_insert
+61	        assert not r.returns_rows
+62	        assert r.rowcount == 1
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_update_delete.py
+ Line number: 62
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+61	        assert not r.returns_rows
+62	        assert r.rowcount == 1
+63	        eq_(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_update_delete.py
+ Line number: 85
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+84	        r = connection.execute(stmt, dict(data="d2_new"))
+85	        assert not r.is_insert
+86	        assert r.returns_rows
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_update_delete.py
+ Line number: 86
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+85	        assert not r.is_insert
+86	        assert r.returns_rows
+87	        eq_(r.keys(), ["id", "data"])
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_update_delete.py
+ Line number: 120
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+119	        r = connection.execute(stmt)
+120	        assert not r.is_insert
+121	        assert r.returns_rows
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_update_delete.py
+ Line number: 121
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+120	        assert not r.is_insert
+121	        assert r.returns_rows
+122	        eq_(r.keys(), ["id", "data"])
+
+
+ + +
+
+ +
+
+ blacklist: Consider possible security implications associated with pickle module.
+ Test ID: B403
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-502
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/util.py
+ Line number: 18
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_imports.html#b403-import-pickle
+ +
+
+17	from itertools import chain
+18	import pickle
+19	import random
+
+
+ + +
+
+ +
+
+ blacklist: Standard pseudo-random generators are not suitable for security/cryptographic purposes.
+ Test ID: B311
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-330
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/util.py
+ Line number: 67
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b311-random
+ +
+
+66	def random_choices(population, k=1):
+67	    return random.choices(population, k=k)
+68	
+
+
+ + +
+
+ +
+
+ blacklist: Standard pseudo-random generators are not suitable for security/cryptographic purposes.
+ Test ID: B311
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-330
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/util.py
+ Line number: 87
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b311-random
+ +
+
+86	    def pop(self):
+87	        index = random.randint(0, len(self) - 1)
+88	        item = list(set.__iter__(self))[index]
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/util.py
+ Line number: 192
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+191	def fail(msg):
+192	    assert False, msg
+193	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/util.py
+ Line number: 407
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+406	    if schema is not None:
+407	        assert consider_schemas == (
+408	            None,
+409	        ), "consider_schemas and schema are mutually exclusive"
+410	        consider_schemas = (schema,)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/util/_concurrency_py3k.py
+ Line number: 276
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+275	            self._lazy_init()
+276	            assert self._loop
+277	            return self._loop
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/util/_concurrency_py3k.py
+ Line number: 281
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+280	            self._lazy_init()
+281	            assert self._loop
+282	            return self._loop.run_until_complete(coro)
+
+
+ + +
+
+ +
+
+ try_except_pass: Try, Except, Pass detected.
+ Test ID: B110
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/util/compat.py
+ Line number: 105
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b110_try_except_pass.html
+ +
+
+104	            ann = _get_dunder_annotations(obj)
+105	        except Exception:
+106	            pass
+107	        else:
+
+
+ + +
+
+ +
+
+ hashlib: Use of weak MD5 hash for security. Consider usedforsecurity=False
+ Test ID: B324
+ Severity: HIGH
+ Confidence: HIGH
+ CWE: CWE-327
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/util/compat.py
+ Line number: 222
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b324_hashlib.html
+ +
+
+221	    def md5_not_for_security() -> Any:
+222	        return hashlib.md5()
+223	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/util/deprecations.py
+ Line number: 139
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+138	    def decorate(fn: _F) -> _F:
+139	        assert message is not None
+140	        assert warning is not None
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/util/deprecations.py
+ Line number: 140
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+139	        assert message is not None
+140	        assert warning is not None
+141	        return _decorate_with_warning(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/util/deprecations.py
+ Line number: 184
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+183	        if not attribute_ok:
+184	            assert kw.get("enable_warnings") is False, (
+185	                "attribute %s will emit a warning on read access.  "
+186	                "If you *really* want this, "
+187	                "add warn_on_attribute_access=True.  Otherwise please add "
+188	                "enable_warnings=False." % api_name
+189	            )
+190	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/util/deprecations.py
+ Line number: 265
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+264	            ):
+265	                assert check_any_kw is not None
+266	                _warn_with_version(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/util/deprecations.py
+ Line number: 347
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+346	        if constructor is not None:
+347	            assert constructor_fn is not None
+348	            assert wtype is not None
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/util/deprecations.py
+ Line number: 348
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+347	            assert constructor_fn is not None
+348	            assert wtype is not None
+349	            setattr(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/util/langhelpers.py
+ Line number: 115
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+114	    ) -> NoReturn:
+115	        assert self._exc_info is not None
+116	        # see #2703 for notes
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/util/langhelpers.py
+ Line number: 119
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+118	            exc_type, exc_value, exc_tb = self._exc_info
+119	            assert exc_value is not None
+120	            self._exc_info = None  # remove potential circular references
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/util/langhelpers.py
+ Line number: 124
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+123	            self._exc_info = None  # remove potential circular references
+124	            assert value is not None
+125	            raise value.with_traceback(traceback)
+
+
+ + +
+
+ +
+
+ exec_used: Use of exec detected.
+ Test ID: B102
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/util/langhelpers.py
+ Line number: 316
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b102_exec_used.html
+ +
+
+315	) -> Callable[..., Any]:
+316	    exec(code, env)
+317	    return env[fn_name]  # type: ignore[no-any-return]
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/util/langhelpers.py
+ Line number: 422
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+421	        _set = set()
+422	    assert _set is not None
+423	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/util/langhelpers.py
+ Line number: 769
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+768	            if default_len:
+769	                assert spec.defaults
+770	                kw_args.update(
+
+
+ + +
+
+ +
+
+ try_except_pass: Try, Except, Pass detected.
+ Test ID: B110
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/util/langhelpers.py
+ Line number: 792
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b110_try_except_pass.html
+ +
+
+791	                output.append("%s=%r" % (arg, val))
+792	        except Exception:
+793	            pass
+794	
+
+
+ + +
+
+ +
+
+ try_except_pass: Try, Except, Pass detected.
+ Test ID: B110
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/util/langhelpers.py
+ Line number: 801
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b110_try_except_pass.html
+ +
+
+800	                    output.append("%s=%r" % (arg, val))
+801	            except Exception:
+802	                pass
+803	
+
+
+ + +
+
+ +
+
+ exec_used: Use of exec detected.
+ Test ID: B102
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/util/langhelpers.py
+ Line number: 950
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b102_exec_used.html
+ +
+
+949	        )
+950	        exec(py, env)
+951	        try:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/util/langhelpers.py
+ Line number: 1204
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1203	        for elem in self._memoized_keys:
+1204	            assert elem not in self.__dict__
+1205	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/util/langhelpers.py
+ Line number: 1484
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1483	            for key in dictlike.iterkeys():
+1484	                assert getter is not None
+1485	                yield key, getter(key)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/util/langhelpers.py
+ Line number: 1546
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1545	    def __set__(self, instance: Any, value: Any) -> None:
+1546	        assert self.setfn is not None
+1547	        self.setfn(instance, value)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/util/langhelpers.py
+ Line number: 1605
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1604	            if sym is None:
+1605	                assert isinstance(name, str)
+1606	                if canonical is None:
+
+
+ + +
+
+ +
+
+ exec_used: Use of exec detected.
+ Test ID: B102
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/util/langhelpers.py
+ Line number: 1944
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b102_exec_used.html
+ +
+
+1943	    env = locals().copy()
+1944	    exec(code, env)
+1945	    return env["set"]
+
+
+ + +
+
+ +
+
+ blacklist: Consider possible security implications associated with the subprocess module.
+ Test ID: B404
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/util/tool_support.py
+ Line number: 24
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_imports.html#b404-import-subprocess
+ +
+
+23	import shutil
+24	import subprocess
+25	import sys
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/util/tool_support.py
+ Line number: 46
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+45	        self.pyproject_toml_path = self.source_root / Path("pyproject.toml")
+46	        assert self.pyproject_toml_path.exists()
+47	
+
+
+ + +
+
+ +
+
+ subprocess_without_shell_equals_true: subprocess call - check for execution of untrusted input.
+ Test ID: B603
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/util/tool_support.py
+ Line number: 109
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b603_subprocess_without_shell_equals_true.html
+ +
+
+108	
+109	        subprocess.run(
+110	            [
+111	                sys.executable,
+112	                "-c",
+113	                "import %s; %s.%s()" % (impl.module, impl.module, impl.attr),
+114	            ]
+115	            + cmdline_options_list,
+116	            cwd=str(self.source_root),
+117	            **kw,
+118	        )
+119	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/util/tool_support.py
+ Line number: 166
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+165	        else:
+166	            assert False, "source or source_file is required"
+167	
+
+
+ + +
+
+ +
+
+ blacklist: Use of possibly insecure function - consider using safer ast.literal_eval.
+ Test ID: B307
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/util/typing.py
+ Line number: 274
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b307-eval
+ +
+
+273	
+274	            annotation = eval(expression, cls_namespace, locals_)
+275	        else:
+
+
+ + +
+
+ +
+
+ blacklist: Use of possibly insecure function - consider using safer ast.literal_eval.
+ Test ID: B307
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/util/typing.py
+ Line number: 276
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b307-eval
+ +
+
+275	        else:
+276	            annotation = eval(expression, base_globals, locals_)
+277	    except Exception as err:
+
+
+ + +
+
+ +
+
+ hardcoded_tmp_directory: Probable insecure usage of temp file/directory.
+ Test ID: B108
+ Severity: MEDIUM
+ Confidence: MEDIUM
+ CWE: CWE-377
+ File: ./venv/lib/python3.12/site-packages/stevedore/_cache.py
+ Line number: 153
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b108_hardcoded_tmp_directory.html
+ +
+
+152	                os.path.isfile(os.path.join(self._dir, '.disable')),
+153	                sys.executable[0:4] == '/tmp',  # noqa: S108,
+154	            ]
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/stevedore/example/load_as_driver.py
+ Line number: 42
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+41	    # okay because invoke_on_load is true
+42	    assert isinstance(mgr.driver, FormatterBase)
+43	    for chunk in mgr.driver.format(data):
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/stevedore/example/load_as_extension.py
+ Line number: 44
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+43	    ) -> tuple[str, Iterable[str]]:
+44	        assert ext.obj is not None
+45	        return (ext.name, ext.obj.format(data))
+
+
+ + +
+
+ +
+
+ hardcoded_tmp_directory: Probable insecure usage of temp file/directory.
+ Test ID: B108
+ Severity: MEDIUM
+ Confidence: MEDIUM
+ CWE: CWE-377
+ File: ./venv/lib/python3.12/site-packages/stevedore/tests/test_cache.py
+ Line number: 28
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b108_hardcoded_tmp_directory.html
+ +
+
+27	        """
+28	        with mock.patch.object(sys, 'executable', '/tmp/fake'):
+29	            sot = _cache.Cache()
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/stevedore/tests/test_extension.py
+ Line number: 86
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+85	        else:
+86	            assert False, 'Failed to raise KeyError'
+87	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/stevedore/tests/test_extension.py
+ Line number: 141
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+140	        for e in em.extensions:
+141	            assert e.obj is not None
+142	            self.assertEqual(e.obj.args, ('a',))
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/stevedore/tests/test_extension.py
+ Line number: 198
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+197	            em.map(mapped, 1, 2, a='A', b='B')
+198	            assert False
+199	        except RuntimeError:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/stevedore/tests/test_hook.py
+ Line number: 60
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+59	        else:
+60	            assert False, 'Failed to raise KeyError'
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/stevedore/tests/test_test_manager.py
+ Line number: 154
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+153	        # This will raise KeyError if the names don't match
+154	        assert em[test_extension.name]
+155	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/typing_extensions.py
+ Line number: 411
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+410	                            deduped_pairs.remove(pair)
+411	                    assert not deduped_pairs, deduped_pairs
+412	                    parameters = tuple(new_parameters)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/typing_extensions.py
+ Line number: 1815
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1814	                if len(params) == 1 and not typing._is_param_expr(args[0]):
+1815	                    assert i == 0
+1816	                    args = (args,)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/typing_extensions.py
+ Line number: 2020
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2019	                    if len(params) == 1 and not _is_param_expr(args[0]):
+2020	                        assert i == 0
+2021	                        args = (args,)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/typing_extensions.py
+ Line number: 2500
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2499	        def __typing_unpacked_tuple_args__(self):
+2500	            assert self.__origin__ is Unpack
+2501	            assert len(self.__args__) == 1
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/typing_extensions.py
+ Line number: 2501
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2500	            assert self.__origin__ is Unpack
+2501	            assert len(self.__args__) == 1
+2502	            arg, = self.__args__
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/typing_extensions.py
+ Line number: 2511
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2510	        def __typing_is_unpacked_typevartuple__(self):
+2511	            assert self.__origin__ is Unpack
+2512	            assert len(self.__args__) == 1
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/typing_extensions.py
+ Line number: 2512
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2511	            assert self.__origin__ is Unpack
+2512	            assert len(self.__args__) == 1
+2513	            return isinstance(self.__args__[0], TypeVarTuple)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/typing_extensions.py
+ Line number: 3310
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+3309	        def __new__(cls, typename, bases, ns):
+3310	            assert _NamedTuple in bases
+3311	            for base in bases:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/typing_extensions.py
+ Line number: 3382
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+3381	    def _namedtuple_mro_entries(bases):
+3382	        assert NamedTuple in bases
+3383	        return (_NamedTuple,)
+
+
+ + +
+
+ +
+
+ blacklist: Use of possibly insecure function - consider using safer ast.literal_eval.
+ Test ID: B307
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/typing_extensions.py
+ Line number: 4034
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b307-eval
+ +
+
+4033	        return_value = {key:
+4034	            value if not isinstance(value, str) else eval(value, globals, locals)
+4035	            for key, value in ann.items() }
+
+
+ + +
+
+ +
+
+ blacklist: Use of possibly insecure function - consider using safer ast.literal_eval.
+ Test ID: B307
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/typing_extensions.py
+ Line number: 4116
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b307-eval
+ +
+
+4115	            code = forward_ref.__forward_code__
+4116	            value = eval(code, globals, locals)
+4117	        forward_ref.__forward_evaluated__ = True
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/werkzeug/_internal.py
+ Line number: 39
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+38	    env = getattr(obj, "environ", obj)
+39	    assert isinstance(env, dict), (
+40	        f"{type(obj).__name__!r} is not a WSGI environment (has to be a dict)"
+41	    )
+42	    return env
+
+
+ + +
+
+ +
+
+ blacklist: Consider possible security implications associated with the subprocess module.
+ Test ID: B404
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/werkzeug/_reloader.py
+ Line number: 5
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_imports.html#b404-import-subprocess
+ +
+
+4	import os
+5	import subprocess
+6	import sys
+
+
+ + +
+
+ +
+
+ subprocess_without_shell_equals_true: subprocess call - check for execution of untrusted input.
+ Test ID: B603
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/werkzeug/_reloader.py
+ Line number: 275
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b603_subprocess_without_shell_equals_true.html
+ +
+
+274	            new_environ["WERKZEUG_RUN_MAIN"] = "true"
+275	            exit_code = subprocess.call(args, env=new_environ, close_fds=False)
+276	
+
+
+ + +
+
+ +
+
+ try_except_pass: Try, Except, Pass detected.
+ Test ID: B110
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/werkzeug/datastructures/file_storage.py
+ Line number: 142
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b110_try_except_pass.html
+ +
+
+141	            self.stream.close()
+142	        except Exception:
+143	            pass
+144	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/werkzeug/datastructures/range.py
+ Line number: 178
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+177	        """Simple method to update the ranges."""
+178	        assert http.is_byte_range_valid(start, stop, length), "Bad range provided"
+179	        self._units: str | None = units
+
+
+ + +
+
+ +
+
+ hashlib: Use of weak SHA1 hash for security. Consider usedforsecurity=False
+ Test ID: B324
+ Severity: HIGH
+ Confidence: HIGH
+ CWE: CWE-327
+ File: ./venv/lib/python3.12/site-packages/werkzeug/debug/__init__.py
+ Line number: 45
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b324_hashlib.html
+ +
+
+44	def hash_pin(pin: str) -> str:
+45	    return hashlib.sha1(f"{pin} added salt".encode("utf-8", "replace")).hexdigest()[:12]
+46	
+
+
+ + +
+
+ +
+
+ blacklist: Consider possible security implications associated with the subprocess module.
+ Test ID: B404
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/werkzeug/debug/__init__.py
+ Line number: 88
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_imports.html#b404-import-subprocess
+ +
+
+87	            # https://github.com/pallets/werkzeug/issues/925
+88	            from subprocess import PIPE
+89	            from subprocess import Popen
+
+
+ + +
+
+ +
+
+ blacklist: Consider possible security implications associated with the subprocess module.
+ Test ID: B404
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/werkzeug/debug/__init__.py
+ Line number: 89
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_imports.html#b404-import-subprocess
+ +
+
+88	            from subprocess import PIPE
+89	            from subprocess import Popen
+90	
+
+
+ + +
+
+ +
+
+ start_process_with_partial_path: Starting a process with a partial executable path
+ Test ID: B607
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/werkzeug/debug/__init__.py
+ Line number: 91
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b607_start_process_with_partial_path.html
+ +
+
+90	
+91	            dump = Popen(
+92	                ["ioreg", "-c", "IOPlatformExpertDevice", "-d", "2"], stdout=PIPE
+93	            ).communicate()[0]
+94	            match = re.search(b'"serial-number" = <([^>]+)', dump)
+
+
+ + +
+
+ +
+
+ subprocess_without_shell_equals_true: subprocess call - check for execution of untrusted input.
+ Test ID: B603
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/werkzeug/debug/__init__.py
+ Line number: 91
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b603_subprocess_without_shell_equals_true.html
+ +
+
+90	
+91	            dump = Popen(
+92	                ["ioreg", "-c", "IOPlatformExpertDevice", "-d", "2"], stdout=PIPE
+93	            ).communicate()[0]
+94	            match = re.search(b'"serial-number" = <([^>]+)', dump)
+
+
+ + +
+
+ +
+
+ hashlib: Use of weak SHA1 hash for security. Consider usedforsecurity=False
+ Test ID: B324
+ Severity: HIGH
+ Confidence: HIGH
+ CWE: CWE-327
+ File: ./venv/lib/python3.12/site-packages/werkzeug/debug/__init__.py
+ Line number: 196
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b324_hashlib.html
+ +
+
+195	
+196	    h = hashlib.sha1()
+197	    for bit in chain(probably_public_bits, private_bits):
+
+
+ + +
+
+ +
+
+ exec_used: Use of exec detected.
+ Test ID: B102
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/werkzeug/debug/console.py
+ Line number: 177
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b102_exec_used.html
+ +
+
+176	        try:
+177	            exec(code, self.locals)
+178	        except Exception:
+
+
+ + +
+
+ +
+
+ try_except_pass: Try, Except, Pass detected.
+ Test ID: B110
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/werkzeug/debug/repr.py
+ Line number: 260
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b110_try_except_pass.html
+ +
+
+259	                    items.append((key, self.repr(getattr(obj, key))))
+260	                except Exception:
+261	                    pass
+262	            title = "Details for"
+
+
+ + +
+
+ +
+
+ hashlib: Use of weak SHA1 hash for security. Consider usedforsecurity=False
+ Test ID: B324
+ Severity: HIGH
+ Confidence: HIGH
+ CWE: CWE-327
+ File: ./venv/lib/python3.12/site-packages/werkzeug/http.py
+ Line number: 1019
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b324_hashlib.html
+ +
+
+1018	    """
+1019	    return sha1(data).hexdigest()
+1020	
+
+
+ + +
+
+ +
+
+ try_except_pass: Try, Except, Pass detected.
+ Test ID: B110
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/werkzeug/middleware/lint.py
+ Line number: 223
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b110_try_except_pass.html
+ +
+
+222	                )
+223	            except Exception:
+224	                pass
+225	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/werkzeug/routing/map.py
+ Line number: 729
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+728	        """
+729	        assert self.map.redirect_defaults
+730	        for r in self.map._rules_by_endpoint[rule.endpoint]:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/werkzeug/routing/map.py
+ Line number: 784
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+783	            url += f"?{self.encode_query_args(query_args)}"
+784	        assert url != path, "detected invalid alias setting. No canonical URL found"
+785	        return url
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/werkzeug/routing/rules.py
+ Line number: 700
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+699	        """Compiles the regular expression and stores it."""
+700	        assert self.map is not None, "rule not bound"
+701	
+
+
+ + +
+
+ +
+
+ exec_used: Use of exec detected.
+ Test ID: B102
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/werkzeug/routing/rules.py
+ Line number: 736
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b102_exec_used.html
+ +
+
+735	        locs: dict[str, t.Any] = {}
+736	        exec(code, globs, locs)
+737	        return locs[name]  # type: ignore
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/werkzeug/serving.py
+ Line number: 262
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+261	            nonlocal status_sent, headers_sent, chunk_response
+262	            assert status_set is not None, "write() before start_response"
+263	            assert headers_set is not None, "write() before start_response"
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/werkzeug/serving.py
+ Line number: 263
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+262	            assert status_set is not None, "write() before start_response"
+263	            assert headers_set is not None, "write() before start_response"
+264	            if status_sent is None:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/werkzeug/serving.py
+ Line number: 303
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+302	
+303	            assert isinstance(data, bytes), "applications must write bytes"
+304	
+
+
+ + +
+
+ +
+
+ try_except_pass: Try, Except, Pass detected.
+ Test ID: B110
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/werkzeug/serving.py
+ Line number: 388
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b110_try_except_pass.html
+ +
+
+387	                execute(InternalServerError())
+388	            except Exception:
+389	                pass
+390	
+
+
+ + +
+
+ +
+
+ hardcoded_bind_all_interfaces: Possible binding to all interfaces.
+ Test ID: B104
+ Severity: MEDIUM
+ Confidence: MEDIUM
+ CWE: CWE-605
+ File: ./venv/lib/python3.12/site-packages/werkzeug/serving.py
+ Line number: 849
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b104_hardcoded_bind_all_interfaces.html
+ +
+
+848	
+849	            if self.host in {"0.0.0.0", "::"}:
+850	                messages.append(f" * Running on all addresses ({self.host})")
+
+
+ + +
+
+ +
+
+ hardcoded_bind_all_interfaces: Possible binding to all interfaces.
+ Test ID: B104
+ Severity: MEDIUM
+ Confidence: MEDIUM
+ CWE: CWE-605
+ File: ./venv/lib/python3.12/site-packages/werkzeug/serving.py
+ Line number: 852
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b104_hardcoded_bind_all_interfaces.html
+ +
+
+851	
+852	                if self.host == "0.0.0.0":
+853	                    localhost = "127.0.0.1"
+
+
+ + +
+
+ +
+
+ blacklist: Standard pseudo-random generators are not suitable for security/cryptographic purposes.
+ Test ID: B311
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-330
+ File: ./venv/lib/python3.12/site-packages/werkzeug/test.py
+ Line number: 68
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b311-random
+ +
+
+67	    if boundary is None:
+68	        boundary = f"---------------WerkzeugFormPart_{time()}{random()}"
+69	
+
+
+ + +
+
+ +
+
+ try_except_pass: Try, Except, Pass detected.
+ Test ID: B110
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/werkzeug/test.py
+ Line number: 646
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b110_try_except_pass.html
+ +
+
+645	            self.close()
+646	        except Exception:
+647	            pass
+648	
+
+
+ + +
+
+ +
+
+ try_except_pass: Try, Except, Pass detected.
+ Test ID: B110
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/werkzeug/test.py
+ Line number: 663
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b110_try_except_pass.html
+ +
+
+662	                f.close()
+663	            except Exception:
+664	                pass
+665	        self.closed = True
+
+
+ + +
+
+ +
+
+ hashlib: Use of weak SHA1 hash for security. Consider usedforsecurity=False
+ Test ID: B324
+ Severity: HIGH
+ Confidence: HIGH
+ CWE: CWE-327
+ File: ./venv/lib/python3.12/site-packages/wtforms/csrf/session.py
+ Line number: 47
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b324_hashlib.html
+ +
+
+46	        if "csrf" not in session:
+47	            session["csrf"] = sha1(os.urandom(64)).hexdigest()
+48	
+
+
+ + +
+
+ +
+
+ markupsafe_markup_xss: Potential XSS with ``markupsafe.Markup`` detected. Do not use ``Markup`` on untrusted data.
+ Test ID: B704
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-79
+ File: ./venv/lib/python3.12/site-packages/wtforms/fields/core.py
+ Line number: 445
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b704_markupsafe_markup_xss.html
+ +
+
+444	        text = escape(text or self.text)
+445	        return Markup(f"<label {attributes}>{text}</label>")
+446	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/wtforms/fields/list.py
+ Line number: 53
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+52	            )
+53	        assert isinstance(
+54	            unbound_field, UnboundField
+55	        ), "Field must be unbound, not a field class"
+56	        self.unbound_field = unbound_field
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/wtforms/fields/list.py
+ Line number: 156
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+155	    def _add_entry(self, formdata=None, data=unset_value, index=None):
+156	        assert (
+157	            not self.max_entries or len(self.entries) < self.max_entries
+158	        ), "You cannot have more than max_entries entries in this FieldList"
+159	        if index is None:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/wtforms/validators.py
+ Line number: 123
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+122	    def __init__(self, min=-1, max=-1, message=None):
+123	        assert (
+124	            min != -1 or max != -1
+125	        ), "At least one of `min` or `max` must be specified."
+126	        assert max == -1 or min <= max, "`min` cannot be more than `max`."
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/wtforms/validators.py
+ Line number: 126
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+125	        ), "At least one of `min` or `max` must be specified."
+126	        assert max == -1 or min <= max, "`min` cannot be more than `max`."
+127	        self.min = min
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/wtforms/widgets/core.py
+ Line number: 100
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+99	    def __init__(self, html_tag="ul", prefix_label=True):
+100	        assert html_tag in ("ol", "ul")
+101	        self.html_tag = html_tag
+
+
+ + +
+
+ +
+
+ markupsafe_markup_xss: Potential XSS with ``markupsafe.Markup`` detected. Do not use ``Markup`` on untrusted data.
+ Test ID: B704
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-79
+ File: ./venv/lib/python3.12/site-packages/wtforms/widgets/core.py
+ Line number: 113
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b704_markupsafe_markup_xss.html
+ +
+
+112	        html.append(f"</{self.html_tag}>")
+113	        return Markup("".join(html))
+114	
+
+
+ + +
+
+ +
+
+ markupsafe_markup_xss: Potential XSS with ``markupsafe.Markup`` detected. Do not use ``Markup`` on untrusted data.
+ Test ID: B704
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-79
+ File: ./venv/lib/python3.12/site-packages/wtforms/widgets/core.py
+ Line number: 150
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b704_markupsafe_markup_xss.html
+ +
+
+149	            html.append(hidden)
+150	        return Markup("".join(html))
+151	
+
+
+ + +
+
+ +
+
+ markupsafe_markup_xss: Potential XSS with ``markupsafe.Markup`` detected. Do not use ``Markup`` on untrusted data.
+ Test ID: B704
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-79
+ File: ./venv/lib/python3.12/site-packages/wtforms/widgets/core.py
+ Line number: 179
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b704_markupsafe_markup_xss.html
+ +
+
+178	        input_params = self.html_params(name=field.name, **kwargs)
+179	        return Markup(f"<input {input_params}>")
+180	
+
+
+ + +
+
+ +
+
+ markupsafe_markup_xss: Potential XSS with ``markupsafe.Markup`` detected. Do not use ``Markup`` on untrusted data.
+ Test ID: B704
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-79
+ File: ./venv/lib/python3.12/site-packages/wtforms/widgets/core.py
+ Line number: 328
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b704_markupsafe_markup_xss.html
+ +
+
+327	        textarea_innerhtml = escape(field._value())
+328	        return Markup(
+329	            f"<textarea {textarea_params}>\r\n{textarea_innerhtml}</textarea>"
+330	        )
+331	
+
+
+ + +
+
+ +
+
+ markupsafe_markup_xss: Potential XSS with ``markupsafe.Markup`` detected. Do not use ``Markup`` on untrusted data.
+ Test ID: B704
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-79
+ File: ./venv/lib/python3.12/site-packages/wtforms/widgets/core.py
+ Line number: 377
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b704_markupsafe_markup_xss.html
+ +
+
+376	        html.append("</select>")
+377	        return Markup("".join(html))
+378	
+
+
+ + +
+
+ +
+
+ markupsafe_markup_xss: Potential XSS with ``markupsafe.Markup`` detected. Do not use ``Markup`` on untrusted data.
+ Test ID: B704
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-79
+ File: ./venv/lib/python3.12/site-packages/wtforms/widgets/core.py
+ Line number: 388
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b704_markupsafe_markup_xss.html
+ +
+
+387	            options["selected"] = True
+388	        return Markup(f"<option {html_params(**options)}>{escape(label)}</option>")
+389	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/yaml/parser.py
+ Line number: 185
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+184	            event = StreamEndEvent(token.start_mark, token.end_mark)
+185	            assert not self.states
+186	            assert not self.marks
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/yaml/parser.py
+ Line number: 186
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+185	            assert not self.states
+186	            assert not self.marks
+187	            self.state = None
+
+
+ + +
+
+ +
+ + + diff --git a/Python/Flask_Blog/11-Blueprints/bandit_report_updated.html b/Python/Flask_Blog/11-Blueprints/bandit_report_updated.html new file mode 100644 index 000000000..b09a4d655 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/bandit_report_updated.html @@ -0,0 +1,57346 @@ + + + + + + + + + Bandit Report + + + + + + + +
+
+
+ Metrics:
+
+ Total lines of code: 624790
+ Total lines skipped (#nosec): 2 +
+
+ + + +
+
+
+Skipped files:

+./venv/lib/python3.12/site-packages/PIL/AvifImagePlugin.py reason: syntax error while parsing AST from file
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/BlpImagePlugin.py
+ Line number: 261
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+260	    def _open(self) -> None:
+261	        assert self.fp is not None
+262	        self.magic = self.fp.read(4)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/BlpImagePlugin.py
+ Line number: 316
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+315	    def _safe_read(self, length: int) -> bytes:
+316	        assert self.fd is not None
+317	        return ImageFile._safe_read(self.fd, length)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/BlpImagePlugin.py
+ Line number: 371
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+370	        jpeg_header = self._safe_read(jpeg_header_size)
+371	        assert self.fd is not None
+372	        self._safe_read(self._offsets[0] - self.fd.tell())  # What IS this?
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/BlpImagePlugin.py
+ Line number: 379
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+378	            args = image.tile[0].args
+379	            assert isinstance(args, tuple)
+380	            image.tile = [image.tile[0]._replace(args=(args[0], "CMYK"))]
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/BlpImagePlugin.py
+ Line number: 390
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+389	
+390	        assert self.fd is not None
+391	        self.fd.seek(self._offsets[0])
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/BlpImagePlugin.py
+ Line number: 437
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+436	        data = b""
+437	        assert self.im is not None
+438	        palette = self.im.getpalette("RGBA", "RGBA")
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/BlpImagePlugin.py
+ Line number: 452
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+451	
+452	        assert self.im is not None
+453	        w, h = self.im.size
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/BlpImagePlugin.py
+ Line number: 473
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+472	
+473	    assert im.palette is not None
+474	    fp.write(struct.pack("<i", 1))  # Uncompressed or DirectX compression
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/BmpImagePlugin.py
+ Line number: 79
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+78	        """Read relevant info about the BMP"""
+79	        assert self.fp is not None
+80	        read, seek = self.fp.read, self.fp.seek
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/BmpImagePlugin.py
+ Line number: 91
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+90	        # read the rest of the bmp header, without its size
+91	        assert isinstance(file_info["header_size"], int)
+92	        header_data = ImageFile._safe_read(self.fp, file_info["header_size"] - 4)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/BmpImagePlugin.py
+ Line number: 132
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+131	            file_info["palette_padding"] = 4
+132	            assert isinstance(file_info["pixels_per_meter"], tuple)
+133	            self.info["dpi"] = tuple(x / 39.3701 for x in file_info["pixels_per_meter"])
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/BmpImagePlugin.py
+ Line number: 155
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+154	                        file_info[mask] = i32(read(4))
+155	                assert isinstance(file_info["r_mask"], int)
+156	                assert isinstance(file_info["g_mask"], int)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/BmpImagePlugin.py
+ Line number: 156
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+155	                assert isinstance(file_info["r_mask"], int)
+156	                assert isinstance(file_info["g_mask"], int)
+157	                assert isinstance(file_info["b_mask"], int)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/BmpImagePlugin.py
+ Line number: 157
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+156	                assert isinstance(file_info["g_mask"], int)
+157	                assert isinstance(file_info["b_mask"], int)
+158	                assert isinstance(file_info["a_mask"], int)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/BmpImagePlugin.py
+ Line number: 158
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+157	                assert isinstance(file_info["b_mask"], int)
+158	                assert isinstance(file_info["a_mask"], int)
+159	                file_info["rgb_mask"] = (
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/BmpImagePlugin.py
+ Line number: 176
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+175	        # ---------------------- is shorter than real size for bpp >= 16
+176	        assert isinstance(file_info["width"], int)
+177	        assert isinstance(file_info["height"], int)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/BmpImagePlugin.py
+ Line number: 177
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+176	        assert isinstance(file_info["width"], int)
+177	        assert isinstance(file_info["height"], int)
+178	        self._size = file_info["width"], file_info["height"]
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/BmpImagePlugin.py
+ Line number: 181
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+180	        # ------- If color count was not found in the header, compute from bits
+181	        assert isinstance(file_info["bits"], int)
+182	        if not file_info.get("colors", 0):
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/BmpImagePlugin.py
+ Line number: 184
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+183	            file_info["colors"] = 1 << file_info["bits"]
+184	        assert isinstance(file_info["palette_padding"], int)
+185	        assert isinstance(file_info["colors"], int)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/BmpImagePlugin.py
+ Line number: 185
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+184	        assert isinstance(file_info["palette_padding"], int)
+185	        assert isinstance(file_info["colors"], int)
+186	        if offset == 14 + file_info["header_size"] and file_info["bits"] <= 8:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/BmpImagePlugin.py
+ Line number: 230
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+229	                ):
+230	                    assert isinstance(file_info["rgba_mask"], tuple)
+231	                    raw_mode = MASK_MODES[(file_info["bits"], file_info["rgba_mask"])]
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/BmpImagePlugin.py
+ Line number: 237
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+236	                ):
+237	                    assert isinstance(file_info["rgb_mask"], tuple)
+238	                    raw_mode = MASK_MODES[(file_info["bits"], file_info["rgb_mask"])]
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/BmpImagePlugin.py
+ Line number: 297
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+296	        else:
+297	            assert isinstance(file_info["width"], int)
+298	            args.append(((file_info["width"] * file_info["bits"] + 31) >> 3) & (~3))
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/BmpImagePlugin.py
+ Line number: 312
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+311	        # read 14 bytes: magic number, filesize, reserved, header final offset
+312	        assert self.fp is not None
+313	        head_data = self.fp.read(14)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/BmpImagePlugin.py
+ Line number: 328
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+327	    def decode(self, buffer: bytes | Image.SupportsArrayInterface) -> tuple[int, int]:
+328	        assert self.fd is not None
+329	        rle4 = self.args[1]
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/BufrStubImagePlugin.py
+ Line number: 44
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+43	    def _open(self) -> None:
+44	        assert self.fp is not None
+45	        if not _accept(self.fp.read(4)):
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/CurImagePlugin.py
+ Line number: 41
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+40	    def _open(self) -> None:
+41	        assert self.fp is not None
+42	        offset = self.fp.tell()
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/DcxImagePlugin.py
+ Line number: 48
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+47	        # Header
+48	        assert self.fp is not None
+49	        s = self.fp.read(4)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/DdsImagePlugin.py
+ Line number: 273
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+272	for item in DDSD:
+273	    assert item.name is not None
+274	    setattr(module, f"DDSD_{item.name}", item.value)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/DdsImagePlugin.py
+ Line number: 276
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+275	for item1 in DDSCAPS:
+276	    assert item1.name is not None
+277	    setattr(module, f"DDSCAPS_{item1.name}", item1.value)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/DdsImagePlugin.py
+ Line number: 279
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+278	for item2 in DDSCAPS2:
+279	    assert item2.name is not None
+280	    setattr(module, f"DDSCAPS2_{item2.name}", item2.value)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/DdsImagePlugin.py
+ Line number: 282
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+281	for item3 in DDPF:
+282	    assert item3.name is not None
+283	    setattr(module, f"DDPF_{item3.name}", item3.value)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/DdsImagePlugin.py
+ Line number: 335
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+334	    def _open(self) -> None:
+335	        assert self.fp is not None
+336	        if not _accept(self.fp.read(4)):
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/DdsImagePlugin.py
+ Line number: 492
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+491	    def decode(self, buffer: bytes | Image.SupportsArrayInterface) -> tuple[int, int]:
+492	        assert self.fd is not None
+493	        bitcount, masks = self.args
+
+
+ + +
+
+ +
+
+ blacklist: Consider possible security implications associated with the subprocess module.
+ Test ID: B404
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/PIL/EpsImagePlugin.py
+ Line number: 27
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_imports.html#b404-import-subprocess
+ +
+
+26	import re
+27	import subprocess
+28	import sys
+
+
+ + +
+
+ +
+
+ start_process_with_partial_path: Starting a process with a partial executable path
+ Test ID: B607
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/PIL/EpsImagePlugin.py
+ Line number: 61
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b607_start_process_with_partial_path.html
+ +
+
+60	            try:
+61	                subprocess.check_call(["gs", "--version"], stdout=subprocess.DEVNULL)
+62	                gs_binary = "gs"
+
+
+ + +
+
+ +
+
+ subprocess_without_shell_equals_true: subprocess call - check for execution of untrusted input.
+ Test ID: B603
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/PIL/EpsImagePlugin.py
+ Line number: 61
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b603_subprocess_without_shell_equals_true.html
+ +
+
+60	            try:
+61	                subprocess.check_call(["gs", "--version"], stdout=subprocess.DEVNULL)
+62	                gs_binary = "gs"
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/EpsImagePlugin.py
+ Line number: 80
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+79	        raise OSError(msg)
+80	    assert isinstance(gs_binary, str)
+81	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/EpsImagePlugin.py
+ Line number: 84
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+83	    args = tile[0].args
+84	    assert isinstance(args, tuple)
+85	    length, bbox = args
+
+
+ + +
+
+ +
+
+ subprocess_without_shell_equals_true: subprocess call - check for execution of untrusted input.
+ Test ID: B603
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/PIL/EpsImagePlugin.py
+ Line number: 159
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b603_subprocess_without_shell_equals_true.html
+ +
+
+158	            startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
+159	        subprocess.check_call(command, startupinfo=startupinfo)
+160	        with Image.open(outfile) as out_im:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/EpsImagePlugin.py
+ Line number: 192
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+191	    def _open(self) -> None:
+192	        assert self.fp is not None
+193	        length, offset = self._find_offset(self.fp)
+
+
+ + +
+
+ +
+
+ try_except_pass: Try, Except, Pass detected.
+ Test ID: B110
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/EpsImagePlugin.py
+ Line number: 247
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b110_try_except_pass.html
+ +
+
+246	                        bounding_box = [int(float(i)) for i in v.split()]
+247	                    except Exception:
+248	                        pass
+249	            return True
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/EpsImagePlugin.py
+ Line number: 407
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+406	        if self.tile:
+407	            assert self.fp is not None
+408	            self.im = Ghostscript(self.tile, self.size, self.fp, scale, transparency)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/FitsImagePlugin.py
+ Line number: 28
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+27	    def _open(self) -> None:
+28	        assert self.fp is not None
+29	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/FitsImagePlugin.py
+ Line number: 130
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+129	    def decode(self, buffer: bytes | Image.SupportsArrayInterface) -> tuple[int, int]:
+130	        assert self.fd is not None
+131	        with gzip.open(self.fd) as fp:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/FliImagePlugin.py
+ Line number: 51
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+50	        # HEAD
+51	        assert self.fp is not None
+52	        s = self.fp.read(128)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/FliImagePlugin.py
+ Line number: 119
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+118	        i = 0
+119	        assert self.fp is not None
+120	        for e in range(i16(self.fp.read(2))):
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/FpxImagePlugin.py
+ Line number: 61
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+60	
+61	        assert self.fp is not None
+62	        try:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/FpxImagePlugin.py
+ Line number: 85
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+84	
+85	        assert isinstance(prop[0x1000002], int)
+86	        assert isinstance(prop[0x1000003], int)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/FpxImagePlugin.py
+ Line number: 86
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+85	        assert isinstance(prop[0x1000002], int)
+86	        assert isinstance(prop[0x1000003], int)
+87	        self._size = prop[0x1000002], prop[0x1000003]
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/FpxImagePlugin.py
+ Line number: 232
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+231	
+232	        assert self.fp is not None
+233	        self.stream = stream
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/FtexImagePlugin.py
+ Line number: 75
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+74	    def _open(self) -> None:
+75	        assert self.fp is not None
+76	        if not _accept(self.fp.read(4)):
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/FtexImagePlugin.py
+ Line number: 85
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+84	        # I don't know of any multi-format file.
+85	        assert format_count == 1
+86	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/GbrImagePlugin.py
+ Line number: 45
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+44	    def _open(self) -> None:
+45	        assert self.fp is not None
+46	        header_size = i32(self.fp.read(4))
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/GbrImagePlugin.py
+ Line number: 92
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+91	        if self._im is None:
+92	            assert self.fp is not None
+93	            self.im = Image.core.new(self.mode, self.size)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/GdImageFile.py
+ Line number: 52
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+51	        # Header
+52	        assert self.fp is not None
+53	
+
+
+ + +
+
+ +
+
+ blacklist: Consider possible security implications associated with the subprocess module.
+ Test ID: B404
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/PIL/GifImagePlugin.py
+ Line number: 31
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_imports.html#b404-import-subprocess
+ +
+
+30	import os
+31	import subprocess
+32	from enum import IntEnum
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/GifImagePlugin.py
+ Line number: 90
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+89	    def data(self) -> bytes | None:
+90	        assert self.fp is not None
+91	        s = self.fp.read(1)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/GifImagePlugin.py
+ Line number: 104
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+103	        # Screen
+104	        assert self.fp is not None
+105	        s = self.fp.read(13)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/GifImagePlugin.py
+ Line number: 485
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+484	            self._prev_im = expanded_im
+485	            assert self._prev_im is not None
+486	        if self._frame_transparency is not None:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/GifImagePlugin.py
+ Line number: 495
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+494	
+495	        assert self.dispose_extent is not None
+496	        frame_im = self._crop(frame_im, self.dispose_extent)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/GifImagePlugin.py
+ Line number: 532
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+531	        im = im.convert("P", palette=Image.Palette.ADAPTIVE)
+532	        assert im.palette is not None
+533	        if im.palette.mode == "RGBA":
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/GifImagePlugin.py
+ Line number: 570
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+569	            im_palette = im.getpalette(None)
+570	            assert im_palette is not None
+571	            source_palette = bytearray(im_palette)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/GifImagePlugin.py
+ Line number: 576
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+575	        im.palette = ImagePalette.ImagePalette("RGB", palette=source_palette)
+576	    assert source_palette is not None
+577	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/GifImagePlugin.py
+ Line number: 580
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+579	        used_palette_colors: list[int | None] = []
+580	        assert im.palette is not None
+581	        for i in range(0, len(source_palette), 3):
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/GifImagePlugin.py
+ Line number: 595
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+594	        for index in used_palette_colors:
+595	            assert index is not None
+596	            dest_map.append(index)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/GifImagePlugin.py
+ Line number: 611
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+610	
+611	    assert im.palette is not None
+612	    im.palette.palette = source_palette
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/GifImagePlugin.py
+ Line number: 716
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+715	                            first_palette = im_frames[0].im.palette
+716	                            assert first_palette is not None
+717	                            background_im.putpalette(first_palette, first_palette.mode)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/GifImagePlugin.py
+ Line number: 723
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+722	                    if "transparency" not in encoderinfo:
+723	                        assert im_frame.palette is not None
+724	                        try:
+
+
+ + +
+
+ +
+
+ start_process_with_partial_path: Starting a process with a partial executable path
+ Test ID: B607
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/PIL/GifImagePlugin.py
+ Line number: 888
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b607_start_process_with_partial_path.html
+ +
+
+887	            if im.mode != "RGB":
+888	                subprocess.check_call(
+889	                    ["ppmtogif", tempfile], stdout=f, stderr=subprocess.DEVNULL
+890	                )
+891	            else:
+
+
+ + +
+
+ +
+
+ subprocess_without_shell_equals_true: subprocess call - check for execution of untrusted input.
+ Test ID: B603
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/PIL/GifImagePlugin.py
+ Line number: 888
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b603_subprocess_without_shell_equals_true.html
+ +
+
+887	            if im.mode != "RGB":
+888	                subprocess.check_call(
+889	                    ["ppmtogif", tempfile], stdout=f, stderr=subprocess.DEVNULL
+890	                )
+891	            else:
+
+
+ + +
+
+ +
+
+ subprocess_without_shell_equals_true: subprocess call - check for execution of untrusted input.
+ Test ID: B603
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/PIL/GifImagePlugin.py
+ Line number: 896
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b603_subprocess_without_shell_equals_true.html
+ +
+
+895	                togif_cmd = ["ppmtogif"]
+896	                quant_proc = subprocess.Popen(
+897	                    quant_cmd, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL
+898	                )
+899	                togif_proc = subprocess.Popen(
+
+
+ + +
+
+ +
+
+ subprocess_without_shell_equals_true: subprocess call - check for execution of untrusted input.
+ Test ID: B603
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/PIL/GifImagePlugin.py
+ Line number: 899
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b603_subprocess_without_shell_equals_true.html
+ +
+
+898	                )
+899	                togif_proc = subprocess.Popen(
+900	                    togif_cmd,
+901	                    stdin=quant_proc.stdout,
+902	                    stdout=f,
+903	                    stderr=subprocess.DEVNULL,
+904	                )
+905	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/GifImagePlugin.py
+ Line number: 907
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+906	                # Allow ppmquant to receive SIGPIPE if ppmtogif exits
+907	                assert quant_proc.stdout is not None
+908	                quant_proc.stdout.close()
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/GifImagePlugin.py
+ Line number: 968
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+967	
+968	            assert im.palette is not None
+969	            num_palette_colors = len(im.palette.palette) // Image.getmodebands(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/GifImagePlugin.py
+ Line number: 1037
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1036	            # info["background"] - a global color table index
+1037	            assert im.palette is not None
+1038	            try:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/GimpGradientFile.py
+ Line number: 88
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+87	    def getpalette(self, entries: int = 256) -> tuple[bytes, str]:
+88	        assert self.gradient is not None
+89	        palette = []
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/GribStubImagePlugin.py
+ Line number: 44
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+43	    def _open(self) -> None:
+44	        assert self.fp is not None
+45	        if not _accept(self.fp.read(8)):
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/Hdf5StubImagePlugin.py
+ Line number: 44
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+43	    def _open(self) -> None:
+44	        assert self.fp is not None
+45	        if not _accept(self.fp.read(8)):
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/IcnsImagePlugin.py
+ Line number: 267
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+266	    def _open(self) -> None:
+267	        assert self.fp is not None
+268	        self.icns = IcnsFile(self.fp)
+
+
+ + +
+
+ +
+
+ start_process_with_no_shell: Starting a process without a shell.
+ Test ID: B606
+ Severity: LOW
+ Confidence: MEDIUM
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/PIL/IcnsImagePlugin.py
+ Line number: 401
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b606_start_process_with_no_shell.html
+ +
+
+400	        if sys.platform == "windows":
+401	            os.startfile("out.png")
+
+
+ + +
+
+ +
+
+ start_process_with_partial_path: Starting a process with a partial executable path
+ Test ID: B607
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/PIL/IcnsImagePlugin.py
+ Line number: 401
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b607_start_process_with_partial_path.html
+ +
+
+400	        if sys.platform == "windows":
+401	            os.startfile("out.png")
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/IcoImagePlugin.py
+ Line number: 343
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+342	    def _open(self) -> None:
+343	        assert self.fp is not None
+344	        self.ico = IcoFile(self.fp)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/ImImagePlugin.py
+ Line number: 128
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+127	
+128	        assert self.fp is not None
+129	        if b"\n" not in self.fp.read(100):
+
+
+ + +
+
+ +
+
+ blacklist: Using Element to parse untrusted XML data is known to be vulnerable to XML attacks. Replace Element with the equivalent defusedxml package, or make sure defusedxml.defuse_stdlib() is called.
+ Test ID: B405
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-20
+ File: ./venv/lib/python3.12/site-packages/PIL/Image.py
+ Line number: 206
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_imports.html#b405-import-xml-etree
+ +
+
+205	    import mmap
+206	    from xml.etree.ElementTree import Element
+207	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/Image.py
+ Line number: 443
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+442	
+443	        assert BmpImagePlugin
+444	    except ImportError:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/Image.py
+ Line number: 449
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+448	
+449	        assert GifImagePlugin
+450	    except ImportError:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/Image.py
+ Line number: 455
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+454	
+455	        assert JpegImagePlugin
+456	    except ImportError:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/Image.py
+ Line number: 461
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+460	
+461	        assert PpmImagePlugin
+462	    except ImportError:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/Image.py
+ Line number: 467
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+466	
+467	        assert PngImagePlugin
+468	    except ImportError:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/Image.py
+ Line number: 647
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+646	            raise self._im.ex
+647	        assert self._im is not None
+648	        return self._im
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/Image.py
+ Line number: 758
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+757	            return False
+758	        assert isinstance(other, Image)
+759	        return (
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/Image.py
+ Line number: 1147
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1146	                    if self.mode == "P":
+1147	                        assert self.palette is not None
+1148	                        trns_im.putpalette(self.palette, self.palette.mode)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/Image.py
+ Line number: 1151
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1150	                            err = "Couldn't allocate a palette color for transparency"
+1151	                            assert trns_im.palette is not None
+1152	                            try:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/Image.py
+ Line number: 1339
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1338	            new_im = self._new(im)
+1339	            assert palette.palette is not None
+1340	            new_im.palette = palette.palette.copy()
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/Image.py
+ Line number: 1641
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1640	
+1641	                assert isinstance(self, TiffImagePlugin.TiffImageFile)
+1642	                self._exif.bigtiff = self.tag_v2._bigtiff
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/Image.py
+ Line number: 1645
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1644	
+1645	                assert self.fp is not None
+1646	                self._exif.load_from_fp(self.fp, self.tag_v2._offset)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/Image.py
+ Line number: 1725
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1724	        if self.mode == "P":
+1725	            assert self.palette is not None
+1726	            return self.palette.mode.endswith("A")
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/Image.py
+ Line number: 1741
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1740	        palette = self.getpalette("RGBA")
+1741	        assert palette is not None
+1742	        transparency = self.info["transparency"]
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/Image.py
+ Line number: 2211
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2210	                value = value[:3]
+2211	            assert self.palette is not None
+2212	            palette_index = self.palette.getcolor(tuple(value), self)
+
+
+ + +
+
+ +
+
+ try_except_pass: Try, Except, Pass detected.
+ Test ID: B110
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/Image.py
+ Line number: 4095
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b110_try_except_pass.html
+ +
+
+4094	                return value[0]
+4095	        except Exception:
+4096	            pass
+4097	        return value
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/ImageColor.py
+ Line number: 48
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+47	        rgb_tuple = getrgb(rgb)
+48	        assert len(rgb_tuple) == 3
+49	        colormap[color] = rgb_tuple
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/ImageDraw.py
+ Line number: 578
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+577	            if ink is None:
+578	                assert fill_ink is not None
+579	                return fill_ink
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/ImageDraw.py
+ Line number: 859
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+858	    pixel = image.load()
+859	    assert pixel is not None
+860	    x, y = xy
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/ImageFile.py
+ Line number: 228
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+227	        if ifd1 and ifd1.get(ExifTags.Base.JpegIFOffset):
+228	            assert exif._info is not None
+229	            ifds.append((ifd1, exif._info.next))
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/ImageFile.py
+ Line number: 233
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+232	        for ifd, ifd_offset in ifds:
+233	            assert self.fp is not None
+234	            current_offset = self.fp.tell()
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/ImageFile.py
+ Line number: 246
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+245	                    length = ifd.get(ExifTags.Base.JpegIFByteCount)
+246	                    assert isinstance(length, int)
+247	                    data = self.fp.read(length)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/ImageFile.py
+ Line number: 262
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+261	        if offset is not None:
+262	            assert self.fp is not None
+263	            self.fp.seek(offset)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/ImageFile.py
+ Line number: 305
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+304	
+305	        assert self.fp is not None
+306	        readonly = 0
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/ImageFile.py
+ Line number: 498
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+497	        image = loader.load(self)
+498	        assert image is not None
+499	        # become the other object (!)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/ImageFile.py
+ Line number: 529
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+528	        """
+529	        assert self.data is None, "cannot reuse parsers"
+530	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/ImageFile.py
+ Line number: 699
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+698	                    # slight speedup: compress to real file object
+699	                    assert fh is not None
+700	                    errcode = encoder.encode_to_file(fh, bufsize)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/ImageFile.py
+ Line number: 867
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+866	        d = Image._getdecoder(self.mode, "raw", rawmode, extra)
+867	        assert self.im is not None
+868	        d.setimage(self.im, self.state.extents())
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/ImageFile.py
+ Line number: 917
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+916	        if data:
+917	            assert self.fd is not None
+918	            self.fd.write(data)
+
+
+ + +
+
+ +
+
+ try_except_pass: Try, Except, Pass detected.
+ Test ID: B110
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/ImageFont.py
+ Line number: 110
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b110_try_except_pass.html
+ +
+
+109	                    image = Image.open(fullname)
+110	                except Exception:
+111	                    pass
+112	                else:
+
+
+ + +
+
+ +
+
+ blacklist: Consider possible security implications associated with the subprocess module.
+ Test ID: B404
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/PIL/ImageGrab.py
+ Line number: 22
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_imports.html#b404-import-subprocess
+ +
+
+21	import shutil
+22	import subprocess
+23	import sys
+
+
+ + +
+
+ +
+
+ subprocess_without_shell_equals_true: subprocess call - check for execution of untrusted input.
+ Test ID: B603
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/PIL/ImageGrab.py
+ Line number: 52
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b603_subprocess_without_shell_equals_true.html
+ +
+
+51	            args += ["-x", filepath]
+52	            retcode = subprocess.call(args)
+53	            if retcode:
+
+
+ + +
+
+ +
+
+ subprocess_without_shell_equals_true: subprocess call - check for execution of untrusted input.
+ Test ID: B603
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/PIL/ImageGrab.py
+ Line number: 66
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b603_subprocess_without_shell_equals_true.html
+ +
+
+65	                    args = ["screencapture", "-l", str(window), "-o", "-x", filepath]
+66	                    retcode = subprocess.call(args)
+67	                    if retcode:
+
+
+ + +
+
+ +
+
+ subprocess_without_shell_equals_true: subprocess call - check for execution of untrusted input.
+ Test ID: B603
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/PIL/ImageGrab.py
+ Line number: 133
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b603_subprocess_without_shell_equals_true.html
+ +
+
+132	            args.append(filepath)
+133	            retcode = subprocess.call(args)
+134	            if retcode:
+
+
+ + +
+
+ +
+
+ start_process_with_partial_path: Starting a process with a partial executable path
+ Test ID: B607
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/PIL/ImageGrab.py
+ Line number: 155
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b607_start_process_with_partial_path.html
+ +
+
+154	    if sys.platform == "darwin":
+155	        p = subprocess.run(
+156	            ["osascript", "-e", "get the clipboard as «class PNGf»"],
+157	            capture_output=True,
+158	        )
+159	        if p.returncode != 0:
+
+
+ + +
+
+ +
+
+ subprocess_without_shell_equals_true: subprocess call - check for execution of untrusted input.
+ Test ID: B603
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/PIL/ImageGrab.py
+ Line number: 155
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b603_subprocess_without_shell_equals_true.html
+ +
+
+154	    if sys.platform == "darwin":
+155	        p = subprocess.run(
+156	            ["osascript", "-e", "get the clipboard as «class PNGf»"],
+157	            capture_output=True,
+158	        )
+159	        if p.returncode != 0:
+
+
+ + +
+
+ +
+
+ subprocess_without_shell_equals_true: subprocess call - check for execution of untrusted input.
+ Test ID: B603
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/PIL/ImageGrab.py
+ Line number: 204
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b603_subprocess_without_shell_equals_true.html
+ +
+
+203	
+204	        p = subprocess.run(args, capture_output=True)
+205	        if p.returncode != 0:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/ImageMorph.py
+ Line number: 127
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+126	        """
+127	        assert len(permutation) == 9
+128	        return "".join(pattern[p] for p in permutation)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/ImageMorph.py
+ Line number: 167
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+166	        self.build_default_lut()
+167	        assert self.lut is not None
+168	        patterns = []
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/ImageOps.py
+ Line number: 199
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+198	    # Initial asserts
+199	    assert image.mode == "L"
+200	    if mid is None:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/ImageOps.py
+ Line number: 201
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+200	    if mid is None:
+201	        assert 0 <= blackpoint <= whitepoint <= 255
+202	    else:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/ImageOps.py
+ Line number: 203
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+202	    else:
+203	        assert 0 <= blackpoint <= midpoint <= whitepoint <= 255
+204	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/ImagePalette.py
+ Line number: 169
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+168	                index = self._new_color_index(image, e)
+169	                assert isinstance(self._palette, bytearray)
+170	                self.colors[color] = index
+
+
+ + +
+
+ +
+
+ blacklist: Standard pseudo-random generators are not suitable for security/cryptographic purposes.
+ Test ID: B311
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-330
+ File: ./venv/lib/python3.12/site-packages/PIL/ImagePalette.py
+ Line number: 249
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b311-random
+ +
+
+248	
+249	    palette = [randint(0, 255) for _ in range(256 * len(mode))]
+250	    return ImagePalette(mode, palette)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/ImageQt.py
+ Line number: 144
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+143	        exclusive_fp = True
+144	    assert isinstance(im, Image.Image)
+145	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/ImageQt.py
+ Line number: 155
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+154	        palette = im.getpalette()
+155	        assert palette is not None
+156	        colortable = [rgb(*palette[i : i + 3]) for i in range(0, len(palette), 3)]
+
+
+ + +
+
+ +
+
+ blacklist: Consider possible security implications associated with the subprocess module.
+ Test ID: B404
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/PIL/ImageShow.py
+ Line number: 19
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_imports.html#b404-import-subprocess
+ +
+
+18	import shutil
+19	import subprocess
+20	import sys
+
+
+ + +
+
+ +
+
+ start_process_with_partial_path: Starting a process with a partial executable path
+ Test ID: B607
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/PIL/ImageShow.py
+ Line number: 177
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b607_start_process_with_partial_path.html
+ +
+
+176	            raise FileNotFoundError
+177	        subprocess.call(["open", "-a", "Preview.app", path])
+178	
+
+
+ + +
+
+ +
+
+ subprocess_without_shell_equals_true: subprocess call - check for execution of untrusted input.
+ Test ID: B603
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/PIL/ImageShow.py
+ Line number: 177
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b603_subprocess_without_shell_equals_true.html
+ +
+
+176	            raise FileNotFoundError
+177	        subprocess.call(["open", "-a", "Preview.app", path])
+178	
+
+
+ + +
+
+ +
+
+ subprocess_without_shell_equals_true: subprocess call - check for execution of untrusted input.
+ Test ID: B603
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/PIL/ImageShow.py
+ Line number: 182
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b603_subprocess_without_shell_equals_true.html
+ +
+
+181	        if executable:
+182	            subprocess.Popen(
+183	                [
+184	                    executable,
+185	                    "-c",
+186	                    "import os, sys, time; time.sleep(20); os.remove(sys.argv[1])",
+187	                    path,
+188	                ]
+189	            )
+190	        return 1
+
+
+ + +
+
+ +
+
+ start_process_with_partial_path: Starting a process with a partial executable path
+ Test ID: B607
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/PIL/ImageShow.py
+ Line number: 225
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b607_start_process_with_partial_path.html
+ +
+
+224	            raise FileNotFoundError
+225	        subprocess.Popen(["xdg-open", path])
+226	        return 1
+
+
+ + +
+
+ +
+
+ subprocess_without_shell_equals_true: subprocess call - check for execution of untrusted input.
+ Test ID: B603
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/PIL/ImageShow.py
+ Line number: 225
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b603_subprocess_without_shell_equals_true.html
+ +
+
+224	            raise FileNotFoundError
+225	        subprocess.Popen(["xdg-open", path])
+226	        return 1
+
+
+ + +
+
+ +
+
+ subprocess_without_shell_equals_true: subprocess call - check for execution of untrusted input.
+ Test ID: B603
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/PIL/ImageShow.py
+ Line number: 255
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b603_subprocess_without_shell_equals_true.html
+ +
+
+254	
+255	        subprocess.Popen(args)
+256	        return 1
+
+
+ + +
+
+ +
+
+ start_process_with_partial_path: Starting a process with a partial executable path
+ Test ID: B607
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/PIL/ImageShow.py
+ Line number: 273
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b607_start_process_with_partial_path.html
+ +
+
+272	            raise FileNotFoundError
+273	        subprocess.Popen(["gm", "display", path])
+274	        return 1
+
+
+ + +
+
+ +
+
+ subprocess_without_shell_equals_true: subprocess call - check for execution of untrusted input.
+ Test ID: B603
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/PIL/ImageShow.py
+ Line number: 273
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b603_subprocess_without_shell_equals_true.html
+ +
+
+272	            raise FileNotFoundError
+273	        subprocess.Popen(["gm", "display", path])
+274	        return 1
+
+
+ + +
+
+ +
+
+ start_process_with_partial_path: Starting a process with a partial executable path
+ Test ID: B607
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/PIL/ImageShow.py
+ Line number: 291
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b607_start_process_with_partial_path.html
+ +
+
+290	            raise FileNotFoundError
+291	        subprocess.Popen(["eog", "-n", path])
+292	        return 1
+
+
+ + +
+
+ +
+
+ subprocess_without_shell_equals_true: subprocess call - check for execution of untrusted input.
+ Test ID: B603
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/PIL/ImageShow.py
+ Line number: 291
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b603_subprocess_without_shell_equals_true.html
+ +
+
+290	            raise FileNotFoundError
+291	        subprocess.Popen(["eog", "-n", path])
+292	        return 1
+
+
+ + +
+
+ +
+
+ subprocess_without_shell_equals_true: subprocess call - check for execution of untrusted input.
+ Test ID: B603
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/PIL/ImageShow.py
+ Line number: 323
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b603_subprocess_without_shell_equals_true.html
+ +
+
+322	
+323	        subprocess.Popen(args)
+324	        return 1
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/ImageText.py
+ Line number: 507
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+506	
+507	        assert bbox is not None
+508	        return bbox
+
+
+ + +
+
+ +
+
+ try_except_pass: Try, Except, Pass detected.
+ Test ID: B110
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/ImageTk.py
+ Line number: 142
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b110_try_except_pass.html
+ +
+
+141	            self.__photo.tk.call("image", "delete", name)
+142	        except Exception:
+143	            pass  # ignore internal errors
+144	
+
+
+ + +
+
+ +
+
+ try_except_pass: Try, Except, Pass detected.
+ Test ID: B110
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/ImageTk.py
+ Line number: 230
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b110_try_except_pass.html
+ +
+
+229	            self.__photo.tk.call("image", "delete", name)
+230	        except Exception:
+231	            pass  # ignore internal errors
+232	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/ImageWin.py
+ Line number: 90
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+89	        if image:
+90	            assert not isinstance(image, str)
+91	            self.paste(image)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/ImtImagePlugin.py
+ Line number: 40
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+39	
+40	        assert self.fp is not None
+41	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/IptcImagePlugin.py
+ Line number: 52
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+51	        # get a IPTC field header
+52	        assert self.fp is not None
+53	        s = self.fp.read(5)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/IptcImagePlugin.py
+ Line number: 80
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+79	        # load descriptive fields
+80	        assert self.fp is not None
+81	        while True:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/IptcImagePlugin.py
+ Line number: 133
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+132	            args = self.tile[0].args
+133	            assert isinstance(args, tuple)
+134	            compression, band = args
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/IptcImagePlugin.py
+ Line number: 136
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+135	
+136	            assert self.fp is not None
+137	            self.fp.seek(self.tile[0].offset)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/Jpeg2KImagePlugin.py
+ Line number: 171
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+170	                mimetype = "image/jpx"
+171	    assert header is not None
+172	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/Jpeg2KImagePlugin.py
+ Line number: 186
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+185	            height, width, nc, bpc = header.read_fields(">IIHB")
+186	            assert isinstance(height, int)
+187	            assert isinstance(width, int)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/Jpeg2KImagePlugin.py
+ Line number: 187
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+186	            assert isinstance(height, int)
+187	            assert isinstance(width, int)
+188	            assert isinstance(bpc, int)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/Jpeg2KImagePlugin.py
+ Line number: 188
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+187	            assert isinstance(width, int)
+188	            assert isinstance(bpc, int)
+189	            size = (width, height)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/Jpeg2KImagePlugin.py
+ Line number: 213
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+212	            ne, npc = header.read_fields(">HB")
+213	            assert isinstance(ne, int)
+214	            assert isinstance(npc, int)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/Jpeg2KImagePlugin.py
+ Line number: 214
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+213	            assert isinstance(ne, int)
+214	            assert isinstance(npc, int)
+215	            max_bitdepth = 0
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/Jpeg2KImagePlugin.py
+ Line number: 217
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+216	            for bitdepth in header.read_fields(">" + ("B" * npc)):
+217	                assert isinstance(bitdepth, int)
+218	                if bitdepth > max_bitdepth:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/Jpeg2KImagePlugin.py
+ Line number: 229
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+228	                    for value in header.read_fields(">" + ("B" * npc)):
+229	                        assert isinstance(value, int)
+230	                        color.append(value)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/Jpeg2KImagePlugin.py
+ Line number: 239
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+238	                    vrcn, vrcd, hrcn, hrcd, vrce, hrce = res.read_fields(">HHHHBB")
+239	                    assert isinstance(vrcn, int)
+240	                    assert isinstance(vrcd, int)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/Jpeg2KImagePlugin.py
+ Line number: 240
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+239	                    assert isinstance(vrcn, int)
+240	                    assert isinstance(vrcd, int)
+241	                    assert isinstance(hrcn, int)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/Jpeg2KImagePlugin.py
+ Line number: 241
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+240	                    assert isinstance(vrcd, int)
+241	                    assert isinstance(hrcn, int)
+242	                    assert isinstance(hrcd, int)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/Jpeg2KImagePlugin.py
+ Line number: 242
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+241	                    assert isinstance(hrcn, int)
+242	                    assert isinstance(hrcd, int)
+243	                    assert isinstance(vrce, int)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/Jpeg2KImagePlugin.py
+ Line number: 243
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+242	                    assert isinstance(hrcd, int)
+243	                    assert isinstance(vrce, int)
+244	                    assert isinstance(hrce, int)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/Jpeg2KImagePlugin.py
+ Line number: 244
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+243	                    assert isinstance(vrce, int)
+244	                    assert isinstance(hrce, int)
+245	                    hres = _res_to_dpi(hrcn, hrcd, hrce)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/Jpeg2KImagePlugin.py
+ Line number: 267
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+266	    def _open(self) -> None:
+267	        assert self.fp is not None
+268	        sig = self.fp.read(4)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/Jpeg2KImagePlugin.py
+ Line number: 320
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+319	    def _parse_comment(self) -> None:
+320	        assert self.fp is not None
+321	        while True:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/Jpeg2KImagePlugin.py
+ Line number: 365
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+364	            t = self.tile[0]
+365	            assert isinstance(t[3], tuple)
+366	            t3 = (t[3][0], self._reduce, self.layers, t[3][3], t[3][4])
+
+
+ + +
+
+ +
+
+ blacklist: Consider possible security implications associated with the subprocess module.
+ Test ID: B404
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/PIL/JpegImagePlugin.py
+ Line number: 41
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_imports.html#b404-import-subprocess
+ +
+
+40	import struct
+41	import subprocess
+42	import sys
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/JpegImagePlugin.py
+ Line number: 64
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+63	def Skip(self: JpegImageFile, marker: int) -> None:
+64	    assert self.fp is not None
+65	    n = i16(self.fp.read(2)) - 2
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/JpegImagePlugin.py
+ Line number: 74
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+73	
+74	    assert self.fp is not None
+75	    n = i16(self.fp.read(2)) - 2
+
+
+ + +
+
+ +
+
+ try_except_pass: Try, Except, Pass detected.
+ Test ID: B110
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/JpegImagePlugin.py
+ Line number: 91
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b110_try_except_pass.html
+ +
+
+90	            jfif_density = i16(s, 8), i16(s, 10)
+91	        except Exception:
+92	            pass
+93	        else:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/JpegImagePlugin.py
+ Line number: 179
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+178	    # Comment marker.  Store these in the APP dictionary.
+179	    assert self.fp is not None
+180	    n = i16(self.fp.read(2)) - 2
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/JpegImagePlugin.py
+ Line number: 196
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+195	
+196	    assert self.fp is not None
+197	    n = i16(self.fp.read(2)) - 2
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/JpegImagePlugin.py
+ Line number: 247
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+246	
+247	    assert self.fp is not None
+248	    n = i16(self.fp.read(2)) - 2
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/JpegImagePlugin.py
+ Line number: 348
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+347	    def _open(self) -> None:
+348	        assert self.fp is not None
+349	        s = self.fp.read(3)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/JpegImagePlugin.py
+ Line number: 417
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+416	        """
+417	        assert self.fp is not None
+418	        s = self.fp.read(read_bytes)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/JpegImagePlugin.py
+ Line number: 442
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+441	
+442	        assert isinstance(a, tuple)
+443	        if a[0] == "RGB" and mode in ["L", "YCbCr"]:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/JpegImagePlugin.py
+ Line number: 452
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+451	                    break
+452	            assert e is not None
+453	            e = (
+
+
+ + +
+
+ +
+
+ start_process_with_partial_path: Starting a process with a partial executable path
+ Test ID: B607
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/PIL/JpegImagePlugin.py
+ Line number: 474
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b607_start_process_with_partial_path.html
+ +
+
+473	        if os.path.exists(self.filename):
+474	            subprocess.check_call(["djpeg", "-outfile", path, self.filename])
+475	        else:
+
+
+ + +
+
+ +
+
+ subprocess_without_shell_equals_true: subprocess call - check for execution of untrusted input.
+ Test ID: B603
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/PIL/JpegImagePlugin.py
+ Line number: 474
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b603_subprocess_without_shell_equals_true.html
+ +
+
+473	        if os.path.exists(self.filename):
+474	            subprocess.check_call(["djpeg", "-outfile", path, self.filename])
+475	        else:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/McIdasImagePlugin.py
+ Line number: 39
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+38	        # parse area file directory
+39	        assert self.fp is not None
+40	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/MicImagePlugin.py
+ Line number: 70
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+69	
+70	        assert self.fp is not None
+71	        self.__fp = self.fp
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/MpegImagePlugin.py
+ Line number: 66
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+65	    def _open(self) -> None:
+66	        assert self.fp is not None
+67	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/MpoImagePlugin.py
+ Line number: 108
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+107	    def _open(self) -> None:
+108	        assert self.fp is not None
+109	        self.fp.seek(0)  # prep the fp in order to pass the JPEG test
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/MpoImagePlugin.py
+ Line number: 125
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+124	        # gets broken within JpegImagePlugin.
+125	        assert self.n_frames == len(self.__mpoffsets)
+126	        del self.info["mpoffset"]  # no longer needed
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/MpoImagePlugin.py
+ Line number: 128
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+127	        self.is_animated = self.n_frames > 1
+128	        assert self.fp is not None
+129	        self._fp = self.fp  # FIXME: hack
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/MspImagePlugin.py
+ Line number: 54
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+53	        # Header
+54	        assert self.fp is not None
+55	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/MspImagePlugin.py
+ Line number: 116
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+115	    def decode(self, buffer: bytes | Image.SupportsArrayInterface) -> tuple[int, int]:
+116	        assert self.fd is not None
+117	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/PcdImagePlugin.py
+ Line number: 32
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+31	        # rough
+32	        assert self.fp is not None
+33	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/PcxImagePlugin.py
+ Line number: 55
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+54	        # header
+55	        assert self.fp is not None
+56	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/PcxImagePlugin.py
+ Line number: 204
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+203	
+204	    assert fp.tell() == 128
+205	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/PdfImagePlugin.py
+ Line number: 103
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+102	        palette = im.getpalette()
+103	        assert palette is not None
+104	        dict_obj["ColorSpace"] = [
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/PdfParser.py
+ Line number: 107
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+106	            return False
+107	        assert isinstance(other, IndirectReference)
+108	        return other.object_id == self.object_id and other.generation == self.generation
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/PdfParser.py
+ Line number: 446
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+445	    def seek_end(self) -> None:
+446	        assert self.f is not None
+447	        self.f.seek(0, os.SEEK_END)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/PdfParser.py
+ Line number: 450
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+449	    def write_header(self) -> None:
+450	        assert self.f is not None
+451	        self.f.write(b"%PDF-1.4\n")
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/PdfParser.py
+ Line number: 454
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+453	    def write_comment(self, s: str) -> None:
+454	        assert self.f is not None
+455	        self.f.write(f"% {s}\n".encode())
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/PdfParser.py
+ Line number: 458
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+457	    def write_catalog(self) -> IndirectReference:
+458	        assert self.f is not None
+459	        self.del_root()
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/PdfParser.py
+ Line number: 504
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+503	    ) -> None:
+504	        assert self.f is not None
+505	        if new_root_ref:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/PdfParser.py
+ Line number: 540
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+539	    ) -> IndirectReference:
+540	        assert self.f is not None
+541	        f = self.f
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/PdfParser.py
+ Line number: 580
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+579	    def read_pdf_info(self) -> None:
+580	        assert self.buf is not None
+581	        self.file_size_total = len(self.buf)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/PdfParser.py
+ Line number: 588
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+587	        self.root_ref = self.trailer_dict[b"Root"]
+588	        assert self.root_ref is not None
+589	        self.info_ref = self.trailer_dict.get(b"Info", None)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/PdfParser.py
+ Line number: 607
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+606	        self.pages_ref = self.root[b"Pages"]
+607	        assert self.pages_ref is not None
+608	        self.page_tree_root = self.read_indirect(self.pages_ref)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/PdfParser.py
+ Line number: 666
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+665	    def read_trailer(self) -> None:
+666	        assert self.buf is not None
+667	        search_start_offset = len(self.buf) - 16384
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/PdfParser.py
+ Line number: 679
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+678	            m = last_match
+679	        assert m is not None
+680	        trailer_data = m.group(1)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/PdfParser.py
+ Line number: 691
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+690	    ) -> None:
+691	        assert self.buf is not None
+692	        trailer_offset = self.read_xref_table(xref_section_offset=xref_section_offset)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/PdfParser.py
+ Line number: 697
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+696	        check_format_condition(m is not None, "previous trailer not found")
+697	        assert m is not None
+698	        trailer_data = m.group(1)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/PdfParser.py
+ Line number: 736
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+735	            key = cls.interpret_name(m.group(1))
+736	            assert isinstance(key, bytes)
+737	            value, value_offset = cls.get_value(trailer_data, m.end())
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/PdfParser.py
+ Line number: 854
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+853	            )
+854	            assert m is not None
+855	            return object, m.end()
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/PdfParser.py
+ Line number: 877
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+876	            while not m:
+877	                assert current_offset is not None
+878	                key, current_offset = cls.get_value(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/PdfParser.py
+ Line number: 900
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+899	                check_format_condition(m is not None, "stream end not found")
+900	                assert m is not None
+901	                current_offset = m.end()
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/PdfParser.py
+ Line number: 911
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+910	            while not m:
+911	                assert current_offset is not None
+912	                value, current_offset = cls.get_value(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/PdfParser.py
+ Line number: 1018
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1017	    def read_xref_table(self, xref_section_offset: int) -> int:
+1018	        assert self.buf is not None
+1019	        subsection_found = False
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/PdfParser.py
+ Line number: 1024
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1023	        check_format_condition(m is not None, "xref section start not found")
+1024	        assert m is not None
+1025	        offset = m.end()
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/PdfParser.py
+ Line number: 1040
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1039	                check_format_condition(m is not None, "xref entry not found")
+1040	                assert m is not None
+1041	                offset = m.end()
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/PdfParser.py
+ Line number: 1057
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1056	        )
+1057	        assert self.buf is not None
+1058	        value = self.get_value(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/PixarImagePlugin.py
+ Line number: 44
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+43	        # assuming a 4-byte magic label
+44	        assert self.fp is not None
+45	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/PngImagePlugin.py
+ Line number: 171
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+170	
+171	        assert self.fp is not None
+172	        if self.queue:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/PngImagePlugin.py
+ Line number: 198
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+197	    def push(self, cid: bytes, pos: int, length: int) -> None:
+198	        assert self.queue is not None
+199	        self.queue.append((cid, pos, length))
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/PngImagePlugin.py
+ Line number: 217
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+216	
+217	        assert self.fp is not None
+218	        try:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/PngImagePlugin.py
+ Line number: 231
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+230	
+231	        assert self.fp is not None
+232	        self.fp.read(4)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/PngImagePlugin.py
+ Line number: 240
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+239	
+240	        assert self.fp is not None
+241	        while True:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/PngImagePlugin.py
+ Line number: 426
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+425	        # ICC profile
+426	        assert self.fp is not None
+427	        s = ImageFile._safe_read(self.fp, length)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/PngImagePlugin.py
+ Line number: 454
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+453	        # image header
+454	        assert self.fp is not None
+455	        s = ImageFile._safe_read(self.fp, length)
+
+
+ + +
+
+ +
+
+ try_except_pass: Try, Except, Pass detected.
+ Test ID: B110
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/PngImagePlugin.py
+ Line number: 464
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b110_try_except_pass.html
+ +
+
+463	            self.im_mode, self.im_rawmode = _MODES[(s[8], s[9])]
+464	        except Exception:
+465	            pass
+466	        if s[12]:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/PngImagePlugin.py
+ Line number: 492
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+491	        # palette
+492	        assert self.fp is not None
+493	        s = ImageFile._safe_read(self.fp, length)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/PngImagePlugin.py
+ Line number: 500
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+499	        # transparency
+500	        assert self.fp is not None
+501	        s = ImageFile._safe_read(self.fp, length)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/PngImagePlugin.py
+ Line number: 523
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+522	        # gamma setting
+523	        assert self.fp is not None
+524	        s = ImageFile._safe_read(self.fp, length)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/PngImagePlugin.py
+ Line number: 532
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+531	
+532	        assert self.fp is not None
+533	        s = ImageFile._safe_read(self.fp, length)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/PngImagePlugin.py
+ Line number: 545
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+544	
+545	        assert self.fp is not None
+546	        s = ImageFile._safe_read(self.fp, length)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/PngImagePlugin.py
+ Line number: 557
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+556	        # pixels per unit
+557	        assert self.fp is not None
+558	        s = ImageFile._safe_read(self.fp, length)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/PngImagePlugin.py
+ Line number: 575
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+574	        # text
+575	        assert self.fp is not None
+576	        s = ImageFile._safe_read(self.fp, length)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/PngImagePlugin.py
+ Line number: 595
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+594	        # compressed text
+595	        assert self.fp is not None
+596	        s = ImageFile._safe_read(self.fp, length)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/PngImagePlugin.py
+ Line number: 630
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+629	        # international text
+630	        assert self.fp is not None
+631	        r = s = ImageFile._safe_read(self.fp, length)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/PngImagePlugin.py
+ Line number: 672
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+671	    def chunk_eXIf(self, pos: int, length: int) -> bytes:
+672	        assert self.fp is not None
+673	        s = ImageFile._safe_read(self.fp, length)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/PngImagePlugin.py
+ Line number: 679
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+678	    def chunk_acTL(self, pos: int, length: int) -> bytes:
+679	        assert self.fp is not None
+680	        s = ImageFile._safe_read(self.fp, length)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/PngImagePlugin.py
+ Line number: 700
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+699	    def chunk_fcTL(self, pos: int, length: int) -> bytes:
+700	        assert self.fp is not None
+701	        s = ImageFile._safe_read(self.fp, length)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/PngImagePlugin.py
+ Line number: 730
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+729	    def chunk_fdAT(self, pos: int, length: int) -> bytes:
+730	        assert self.fp is not None
+731	        if length < 4:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/PngImagePlugin.py
+ Line number: 763
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+762	    def _open(self) -> None:
+763	        assert self.fp is not None
+764	        if not _accept(self.fp.read(8)):
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/PngImagePlugin.py
+ Line number: 843
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+842	                self.seek(frame)
+843	        assert self._text is not None
+844	        return self._text
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/PngImagePlugin.py
+ Line number: 856
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+855	
+856	        assert self.png is not None
+857	        self.png.verify()
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/PngImagePlugin.py
+ Line number: 878
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+877	    def _seek(self, frame: int, rewind: bool = False) -> None:
+878	        assert self.png is not None
+879	        if isinstance(self._fp, DeferredError):
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/PngImagePlugin.py
+ Line number: 992
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+991	
+992	        assert self.png is not None
+993	        assert self.fp is not None
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/PngImagePlugin.py
+ Line number: 993
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+992	        assert self.png is not None
+993	        assert self.fp is not None
+994	        while self.__idat == 0:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/PngImagePlugin.py
+ Line number: 1026
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1025	        """internal: finished reading image data"""
+1026	        assert self.png is not None
+1027	        assert self.fp is not None
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/PngImagePlugin.py
+ Line number: 1027
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1026	        assert self.png is not None
+1027	        assert self.fp is not None
+1028	        if self.__idat != 0:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/PpmImagePlugin.py
+ Line number: 62
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+61	    def _read_magic(self) -> bytes:
+62	        assert self.fp is not None
+63	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/PpmImagePlugin.py
+ Line number: 74
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+73	    def _read_token(self) -> bytes:
+74	        assert self.fp is not None
+75	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/PpmImagePlugin.py
+ Line number: 102
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+101	    def _open(self) -> None:
+102	        assert self.fp is not None
+103	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/PpmImagePlugin.py
+ Line number: 168
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+167	    def _read_block(self) -> bytes:
+168	        assert self.fd is not None
+169	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/PpmImagePlugin.py
+ Line number: 304
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+303	    def decode(self, buffer: bytes | Image.SupportsArrayInterface) -> tuple[int, int]:
+304	        assert self.fd is not None
+305	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/PsdImagePlugin.py
+ Line number: 64
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+63	    def _open(self) -> None:
+64	        assert self.fp is not None
+65	        read = self.fp.read
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/QoiImagePlugin.py
+ Line number: 28
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+27	    def _open(self) -> None:
+28	        assert self.fp is not None
+29	        if not _accept(self.fp.read(4)):
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/QoiImagePlugin.py
+ Line number: 55
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+54	    def decode(self, buffer: bytes | Image.SupportsArrayInterface) -> tuple[int, int]:
+55	        assert self.fd is not None
+56	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/QoiImagePlugin.py
+ Line number: 155
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+154	    def encode(self, bufsize: int) -> tuple[int, int, bytes]:
+155	        assert self.im is not None
+156	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/SgiImagePlugin.py
+ Line number: 58
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+57	        # HEAD
+58	        assert self.fp is not None
+59	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/SgiImagePlugin.py
+ Line number: 202
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+201	    def decode(self, buffer: bytes | Image.SupportsArrayInterface) -> tuple[int, int]:
+202	        assert self.fd is not None
+203	        assert self.im is not None
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/SgiImagePlugin.py
+ Line number: 203
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+202	        assert self.fd is not None
+203	        assert self.im is not None
+204	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/SpiderImagePlugin.py
+ Line number: 107
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+106	        n = 27 * 4  # read 27 float values
+107	        assert self.fp is not None
+108	        f = self.fp.read(n)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/SpiderImagePlugin.py
+ Line number: 195
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+194	        extrema = self.getextrema()
+195	        assert isinstance(extrema[0], float)
+196	        minimum, maximum = cast(tuple[float, float], extrema)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/SpiderImagePlugin.py
+ Line number: 230
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+229	            with Image.open(img) as im:
+230	                assert isinstance(im, SpiderImageFile)
+231	                byte_im = im.convert2byte()
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/SunImagePlugin.py
+ Line number: 52
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+51	
+52	        assert self.fp is not None
+53	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/TgaImagePlugin.py
+ Line number: 57
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+56	        # process header
+57	        assert self.fp is not None
+58	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/TgaImagePlugin.py
+ Line number: 163
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+162	        if self.mode == "RGBA":
+163	            assert self.fp is not None
+164	            self.fp.seek(-26, os.SEEK_END)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/TiffImagePlugin.py
+ Line number: 400
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+399	
+400	        assert isinstance(self._val, Fraction)
+401	        f = self._val.limit_denominator(max_denominator)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/TiffImagePlugin.py
+ Line number: 424
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+423	        _val, _numerator, _denominator = state
+424	        assert isinstance(_val, (float, Fraction))
+425	        self._val = _val
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/TiffImagePlugin.py
+ Line number: 430
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+429	            self._numerator = _numerator
+430	        assert isinstance(_denominator, int)
+431	        self._denominator = _denominator
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/TiffImagePlugin.py
+ Line number: 689
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+688	                    for v in values:
+689	                        assert isinstance(v, IFDRational)
+690	                        if v < 0:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/TiffImagePlugin.py
+ Line number: 700
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+699	                    for v in values:
+700	                        assert isinstance(v, int)
+701	                        if short and not (0 <= v < 2**16):
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/TiffImagePlugin.py
+ Line number: 1181
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1180	        # Header
+1181	        assert self.fp is not None
+1182	        ifh = self.fp.read(8)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/TiffImagePlugin.py
+ Line number: 1211
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1210	            self.seek(current)
+1211	        assert self._n_frames is not None
+1212	        return self._n_frames
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/TiffImagePlugin.py
+ Line number: 1351
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1350	        # into a string in python.
+1351	        assert self.fp is not None
+1352	        try:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/TiffImagePlugin.py
+ Line number: 1365
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1364	        if fp:
+1365	            assert isinstance(args, tuple)
+1366	            args_list = list(args)
+
+
+ + +
+
+ +
+
+ try_except_pass: Try, Except, Pass detected.
+ Test ID: B110
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/TiffImagePlugin.py
+ Line number: 1763
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b110_try_except_pass.html
+ +
+
+1762	            ifd.tagtype[key] = info.tagtype[key]
+1763	        except Exception:
+1764	            pass  # might not be an IFD. Might not have populated type
+1765	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/TiffImagePlugin.py
+ Line number: 2110
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2109	        ifd_offset += self.offsetOfNewPage
+2110	        assert self.whereToWriteNewIFDOffset is not None
+2111	        self.f.seek(self.whereToWriteNewIFDOffset)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/WalImageFile.py
+ Line number: 43
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+42	        # read header fields
+43	        assert self.fp is not None
+44	        header = self.fp.read(32 + 24 + 32 + 12)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/WalImageFile.py
+ Line number: 59
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+58	        if self._im is None:
+59	            assert self.fp is not None
+60	            self.im = Image.core.new(self.mode, self.size)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/WebPImagePlugin.py
+ Line number: 48
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+47	        # and access muxed chunks like ICC/EXIF/XMP.
+48	        assert self.fp is not None
+49	        self._decoder = _webp.WebPAnimDecoder(self.fp.read())
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/WmfImagePlugin.py
+ Line number: 51
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+50	        def load(self, im: ImageFile.StubImageFile) -> Image.Image:
+51	            assert im.fp is not None
+52	            im.fp.seek(0)  # rewind
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/WmfImagePlugin.py
+ Line number: 84
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+83	        # check placeable header
+84	        assert self.fp is not None
+85	        s = self.fp.read(44)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/XVThumbImagePlugin.py
+ Line number: 50
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+49	        # check magic
+50	        assert self.fp is not None
+51	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/XbmImagePlugin.py
+ Line number: 53
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+52	    def _open(self) -> None:
+53	        assert self.fp is not None
+54	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/XpmImagePlugin.py
+ Line number: 40
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+39	    def _open(self) -> None:
+40	        assert self.fp is not None
+41	        if not _accept(self.fp.read(9)):
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/XpmImagePlugin.py
+ Line number: 112
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+111	
+112	        assert self.fp is not None
+113	        s = [self.fp.readline()[1 : xsize + 1].ljust(xsize) for i in range(ysize)]
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/PIL/XpmImagePlugin.py
+ Line number: 122
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+121	    def decode(self, buffer: bytes | Image.SupportsArrayInterface) -> tuple[int, int]:
+122	        assert self.fd is not None
+123	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/blinker/base.py
+ Line number: 420
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+419	        """
+420	        assert sender_id != ANY_ID
+421	
+
+
+ + +
+
+ +
+
+ try_except_pass: Try, Except, Pass detected.
+ Test ID: B110
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/click/_compat.py
+ Line number: 74
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b110_try_except_pass.html
+ +
+
+73	            self.detach()
+74	        except Exception:
+75	            pass
+76	
+
+
+ + +
+
+ +
+
+ try_except_pass: Try, Except, Pass detected.
+ Test ID: B110
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/click/_compat.py
+ Line number: 167
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b110_try_except_pass.html
+ +
+
+166	            return False
+167	        except Exception:
+168	            pass
+169	        return default
+
+
+ + +
+
+ +
+
+ blacklist: Standard pseudo-random generators are not suitable for security/cryptographic purposes.
+ Test ID: B311
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-330
+ File: ./venv/lib/python3.12/site-packages/click/_compat.py
+ Line number: 429
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b311-random
+ +
+
+428	            os.path.dirname(filename),
+429	            f".__atomic-write{random.randrange(1 << 32):08x}",
+430	        )
+
+
+ + +
+
+ +
+
+ try_except_pass: Try, Except, Pass detected.
+ Test ID: B110
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/click/_compat.py
+ Line number: 552
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b110_try_except_pass.html
+ +
+
+551	            _ansi_stream_wrappers[stream] = rv
+552	        except Exception:
+553	            pass
+554	
+
+
+ + +
+
+ +
+
+ try_except_pass: Try, Except, Pass detected.
+ Test ID: B110
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/click/_compat.py
+ Line number: 600
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b110_try_except_pass.html
+ +
+
+599	            cache[stream] = rv
+600	        except Exception:
+601	            pass
+602	        return rv
+
+
+ + +
+
+ +
+
+ blacklist: Consider possible security implications associated with the subprocess module.
+ Test ID: B404
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/click/_termui_impl.py
+ Line number: 439
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_imports.html#b404-import-subprocess
+ +
+
+438	
+439	    import subprocess
+440	
+
+
+ + +
+
+ +
+
+ subprocess_without_shell_equals_true: subprocess call - check for execution of untrusted input.
+ Test ID: B603
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/click/_termui_impl.py
+ Line number: 456
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b603_subprocess_without_shell_equals_true.html
+ +
+
+455	        [str(cmd_path)] + cmd_params,
+456	        shell=False,
+457	        stdin=subprocess.PIPE,
+458	        env=env,
+459	        errors="replace",
+460	        text=True,
+461	    )
+462	    assert c.stdin is not None
+463	    try:
+464	        for text in generator:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/click/_termui_impl.py
+ Line number: 462
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+461	    )
+462	    assert c.stdin is not None
+463	    try:
+
+
+ + +
+
+ +
+
+ blacklist: Consider possible security implications associated with the subprocess module.
+ Test ID: B404
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/click/_termui_impl.py
+ Line number: 531
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_imports.html#b404-import-subprocess
+ +
+
+530	
+531	    import subprocess
+532	    import tempfile
+
+
+ + +
+
+ +
+
+ subprocess_without_shell_equals_true: subprocess call - check for execution of untrusted input.
+ Test ID: B603
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/click/_termui_impl.py
+ Line number: 543
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b603_subprocess_without_shell_equals_true.html
+ +
+
+542	    try:
+543	        subprocess.call([str(cmd_path), filename])
+544	    except OSError:
+
+
+ + +
+
+ +
+
+ blacklist: Consider possible security implications associated with the subprocess module.
+ Test ID: B404
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/click/_termui_impl.py
+ Line number: 595
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_imports.html#b404-import-subprocess
+ +
+
+594	    def edit_files(self, filenames: cabc.Iterable[str]) -> None:
+595	        import subprocess
+596	
+
+
+ + +
+
+ +
+
+ blacklist: Consider possible security implications associated with the subprocess module.
+ Test ID: B404
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/click/_termui_impl.py
+ Line number: 677
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_imports.html#b404-import-subprocess
+ +
+
+676	def open_url(url: str, wait: bool = False, locate: bool = False) -> int:
+677	    import subprocess
+678	
+
+
+ + +
+
+ +
+
+ subprocess_without_shell_equals_true: subprocess call - check for execution of untrusted input.
+ Test ID: B603
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/click/_termui_impl.py
+ Line number: 696
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b603_subprocess_without_shell_equals_true.html
+ +
+
+695	        try:
+696	            return subprocess.Popen(args, stderr=null).wait()
+697	        finally:
+
+
+ + +
+
+ +
+
+ subprocess_without_shell_equals_true: subprocess call - check for execution of untrusted input.
+ Test ID: B603
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/click/_termui_impl.py
+ Line number: 710
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b603_subprocess_without_shell_equals_true.html
+ +
+
+709	        try:
+710	            return subprocess.call(args)
+711	        except OSError:
+
+
+ + +
+
+ +
+
+ subprocess_without_shell_equals_true: subprocess call - check for execution of untrusted input.
+ Test ID: B603
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/click/_termui_impl.py
+ Line number: 724
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b603_subprocess_without_shell_equals_true.html
+ +
+
+723	        try:
+724	            return subprocess.call(args)
+725	        except OSError:
+
+
+ + +
+
+ +
+
+ start_process_with_partial_path: Starting a process with a partial executable path
+ Test ID: B607
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/click/_termui_impl.py
+ Line number: 734
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b607_start_process_with_partial_path.html
+ +
+
+733	            url = _unquote_file(url)
+734	        c = subprocess.Popen(["xdg-open", url])
+735	        if wait:
+
+
+ + +
+
+ +
+
+ subprocess_without_shell_equals_true: subprocess call - check for execution of untrusted input.
+ Test ID: B603
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/click/_termui_impl.py
+ Line number: 734
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b603_subprocess_without_shell_equals_true.html
+ +
+
+733	            url = _unquote_file(url)
+734	        c = subprocess.Popen(["xdg-open", url])
+735	        if wait:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/click/_winconsole.py
+ Line number: 34
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+33	
+34	assert sys.platform == "win32"
+35	import msvcrt  # noqa: E402
+
+
+ + +
+
+ +
+
+ try_except_pass: Try, Except, Pass detected.
+ Test ID: B110
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/click/_winconsole.py
+ Line number: 208
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b110_try_except_pass.html
+ +
+
+207	            self.flush()
+208	        except Exception:
+209	            pass
+210	        return self.buffer.write(x)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/click/core.py
+ Line number: 1662
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1661	        if args and callable(args[0]):
+1662	            assert len(args) == 1 and not kwargs, (
+1663	                "Use 'command(**kwargs)(callable)' to provide arguments."
+1664	            )
+1665	            (func,) = args
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/click/core.py
+ Line number: 1711
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1710	        if args and callable(args[0]):
+1711	            assert len(args) == 1 and not kwargs, (
+1712	                "Use 'group(**kwargs)(callable)' to provide arguments."
+1713	            )
+1714	            (func,) = args
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/click/core.py
+ Line number: 1868
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1867	                cmd_name, cmd, args = self.resolve_command(ctx, args)
+1868	                assert cmd is not None
+1869	                ctx.invoked_subcommand = cmd_name
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/click/core.py
+ Line number: 1890
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1889	                cmd_name, cmd, args = self.resolve_command(ctx, args)
+1890	                assert cmd is not None
+1891	                sub_ctx = cmd.make_context(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/click/core.py
+ Line number: 2602
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2601	            # not to be exposed. We still assert it here to please the type checker.
+2602	            assert self.name is not None, (
+2603	                f"{self!r} parameter's name should not be None when exposing value."
+2604	            )
+2605	            ctx.params[self.name] = value
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/click/core.py
+ Line number: 3142
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+3141	        """
+3142	        assert self.prompt is not None
+3143	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/click/decorators.py
+ Line number: 211
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+210	        name = None
+211	        assert cls is None, "Use 'command(cls=cls)(callable)' to specify a class."
+212	        assert not attrs, "Use 'command(**kwargs)(callable)' to provide arguments."
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/click/decorators.py
+ Line number: 212
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+211	        assert cls is None, "Use 'command(cls=cls)(callable)' to specify a class."
+212	        assert not attrs, "Use 'command(**kwargs)(callable)' to provide arguments."
+213	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/click/decorators.py
+ Line number: 236
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+235	        if t.TYPE_CHECKING:
+236	            assert cls is not None
+237	            assert not callable(name)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/click/decorators.py
+ Line number: 237
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+236	            assert cls is not None
+237	            assert not callable(name)
+238	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/click/parser.py
+ Line number: 193
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+192	        if self.nargs > 1:
+193	            assert isinstance(value, cabc.Sequence)
+194	            holes = sum(1 for x in value if x is UNSET)
+
+
+ + +
+
+ +
+
+ blacklist: Consider possible security implications associated with the subprocess module.
+ Test ID: B404
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/click/shell_completion.py
+ Line number: 313
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_imports.html#b404-import-subprocess
+ +
+
+312	        import shutil
+313	        import subprocess
+314	
+
+
+ + +
+
+ +
+
+ subprocess_without_shell_equals_true: subprocess call - check for execution of untrusted input.
+ Test ID: B603
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/click/shell_completion.py
+ Line number: 320
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b603_subprocess_without_shell_equals_true.html
+ +
+
+319	        else:
+320	            output = subprocess.run(
+321	                [bash_exe, "--norc", "-c", 'echo "${BASH_VERSION}"'],
+322	                stdout=subprocess.PIPE,
+323	            )
+324	            match = re.search(r"^(\d+)\.(\d+)\.\d+", output.stdout.decode())
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/click/shell_completion.py
+ Line number: 514
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+513	
+514	    assert param.name is not None
+515	    # Will be None if expose_value is False.
+
+
+ + +
+
+ +
+
+ try_except_pass: Try, Except, Pass detected.
+ Test ID: B110
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/click/testing.py
+ Line number: 406
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b110_try_except_pass.html
+ +
+
+405	                        del os.environ[key]
+406	                    except Exception:
+407	                        pass
+408	                else:
+
+
+ + +
+
+ +
+
+ try_except_pass: Try, Except, Pass detected.
+ Test ID: B110
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/click/testing.py
+ Line number: 416
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b110_try_except_pass.html
+ +
+
+415	                        del os.environ[key]
+416	                    except Exception:
+417	                        pass
+418	                else:
+
+
+ + +
+
+ +
+
+ try_except_pass: Try, Except, Pass detected.
+ Test ID: B110
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/click/utils.py
+ Line number: 42
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b110_try_except_pass.html
+ +
+
+41	            return func(*args, **kwargs)
+42	        except Exception:
+43	            pass
+44	        return None
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/_asyncio_backend.py
+ Line number: 81
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+80	        try:
+81	            assert self.protocol.recvfrom is None
+82	            self.protocol.recvfrom = done
+
+
+ + +
+
+ +
+
+ try_except_pass: Try, Except, Pass detected.
+ Test ID: B110
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/_asyncio_backend.py
+ Line number: 179
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b110_try_except_pass.html
+ +
+
+178	                    return _CoreAnyIOStream(stream)
+179	                except Exception:
+180	                    pass
+181	            raise httpcore.ConnectError
+
+
+ + +
+
+ +
+
+ try_except_pass: Try, Except, Pass detected.
+ Test ID: B110
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/_ddr.py
+ Line number: 109
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b110_try_except_pass.html
+ +
+
+108	                nameservers.append(dns.nameserver.DoHNameserver(url, bootstrap_address))
+109	            except Exception:
+110	                # continue processing other ALPN types
+111	                pass
+112	        if b"dot" in alpns:
+
+
+ + +
+
+ +
+
+ try_except_pass: Try, Except, Pass detected.
+ Test ID: B110
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/_ddr.py
+ Line number: 138
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b110_try_except_pass.html
+ +
+
+137	                nameservers.extend(info.nameservers)
+138	        except Exception:
+139	            pass
+140	    return nameservers
+
+
+ + +
+
+ +
+
+ try_except_pass: Try, Except, Pass detected.
+ Test ID: B110
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/_ddr.py
+ Line number: 152
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b110_try_except_pass.html
+ +
+
+151	                nameservers.extend(info.nameservers)
+152	        except Exception:
+153	            pass
+154	    return nameservers
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/_trio_backend.py
+ Line number: 154
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+153	                    )
+154	                    assert isinstance(sock, StreamSocket)
+155	                    return _CoreTrioStream(sock.stream)
+
+
+ + +
+
+ +
+
+ try_except_continue: Try, Except, Continue detected.
+ Test ID: B112
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/_trio_backend.py
+ Line number: 156
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b112_try_except_continue.html
+ +
+
+155	                    return _CoreTrioStream(sock.stream)
+156	                except Exception:
+157	                    continue
+158	            raise httpcore.ConnectError
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/_trio_backend.py
+ Line number: 215
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+214	                with _maybe_timeout(timeout):
+215	                    assert destination is not None
+216	                    await s.connect(_lltuple(destination, af))
+
+
+ + +
+
+ +
+
+ hardcoded_bind_all_interfaces: Possible binding to all interfaces.
+ Test ID: B104
+ Severity: MEDIUM
+ Confidence: MEDIUM
+ CWE: CWE-605
+ File: ./venv/lib/python3.12/site-packages/dns/asyncquery.py
+ Line number: 72
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b104_hardcoded_bind_all_interfaces.html
+ +
+
+71	            if af == socket.AF_INET:
+72	                address = "0.0.0.0"
+73	            elif af == socket.AF_INET6:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/asyncquery.py
+ Line number: 589
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+588	            resolver = _maybe_get_resolver(resolver)
+589	            assert parsed.hostname is not None  # pyright: ignore
+590	            answers = await resolver.resolve_name(  # pyright: ignore
+
+
+ + +
+
+ +
+
+ blacklist: Standard pseudo-random generators are not suitable for security/cryptographic purposes.
+ Test ID: B311
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-330
+ File: ./venv/lib/python3.12/site-packages/dns/asyncquery.py
+ Line number: 593
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b311-random
+ +
+
+592	            )
+593	            bootstrap_address = random.choice(list(answers.addresses()))
+594	        if client and not isinstance(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/asyncquery.py
+ Line number: 598
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+597	            raise ValueError("client parameter must be a dns.quic.AsyncQuicConnection.")
+598	        assert client is None or isinstance(client, dns.quic.AsyncQuicConnection)
+599	        return await _http3(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/asyncquery.py
+ Line number: 726
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+725	    hostname = url_parts.hostname
+726	    assert hostname is not None
+727	    if url_parts.port is not None:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/asyncresolver.py
+ Line number: 86
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+85	                return answer
+86	            assert request is not None  # needed for type checking
+87	            done = False
+
+
+ + +
+
+ +
+
+ try_except_pass: Try, Except, Pass detected.
+ Test ID: B110
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/asyncresolver.py
+ Line number: 259
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b110_try_except_pass.html
+ +
+
+258	                self.nameservers = nameservers
+259	        except Exception:
+260	            pass
+261	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/asyncresolver.py
+ Line number: 270
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+269	        reset_default_resolver()
+270	    assert default_resolver is not None
+271	    return default_resolver
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/asyncresolver.py
+ Line number: 388
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+387	            )
+388	            assert answer.rrset is not None
+389	            if answer.rrset.name == name:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/btree.py
+ Line number: 61
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+60	    def __init__(self, t: int, creator: _Creator, is_leaf: bool):
+61	        assert t >= 3
+62	        self.t = t
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/btree.py
+ Line number: 70
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+69	        """Does this node have the maximal number of keys?"""
+70	        assert len(self.elts) <= _MAX(self.t)
+71	        return len(self.elts) == _MAX(self.t)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/btree.py
+ Line number: 75
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+74	        """Does this node have the minimal number of keys?"""
+75	        assert len(self.elts) >= _MIN(self.t)
+76	        return len(self.elts) == _MIN(self.t)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/btree.py
+ Line number: 108
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+107	    def maybe_cow_child(self, index: int) -> "_Node[KT, ET]":
+108	        assert not self.is_leaf
+109	        child = self.children[index]
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/btree.py
+ Line number: 162
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+161	    def insert_nonfull(self, element: ET, in_order: bool) -> ET | None:
+162	        assert not self.is_maximal()
+163	        while True:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/btree.py
+ Line number: 188
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+187	        """Split a maximal node into two minimal ones and a central element."""
+188	        assert self.is_maximal()
+189	        right = self.__class__(self.t, self.creator, self.is_leaf)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/btree.py
+ Line number: 211
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+210	                if not left.is_leaf:
+211	                    assert not self.is_leaf
+212	                    child = left.children.pop()
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/btree.py
+ Line number: 230
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+229	                if not right.is_leaf:
+230	                    assert not self.is_leaf
+231	                    child = right.children.pop(0)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/btree.py
+ Line number: 240
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+239	        then the left child must already be in the Node."""
+240	        assert not self.is_maximal()
+241	        assert not self.is_leaf
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/btree.py
+ Line number: 241
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+240	        assert not self.is_maximal()
+241	        assert not self.is_leaf
+242	        key = middle.key()
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/btree.py
+ Line number: 244
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+243	        i, equal = self.search_in_node(key)
+244	        assert not equal
+245	        self.elts.insert(i, middle)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/btree.py
+ Line number: 250
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+249	        else:
+250	            assert self.children[i] == left
+251	            self.children.insert(i + 1, right)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/btree.py
+ Line number: 279
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+278	        with one of them."""
+279	        assert not parent.is_leaf
+280	        if self.try_left_steal(parent, index):
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/btree.py
+ Line number: 300
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+299	        minimal unless it is the root."""
+300	        assert parent is None or not self.is_minimal()
+301	        i, equal = self.search_in_node(key)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/btree.py
+ Line number: 328
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+327	            i, equal = self.search_in_node(key)
+328	            assert not equal
+329	            child = self.children[i]
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/btree.py
+ Line number: 330
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+329	            child = self.children[i]
+330	            assert not child.is_minimal()
+331	        elt = child.delete(key, self, exact)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/btree.py
+ Line number: 334
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+333	            node, i = self._get_node(original_key)
+334	            assert node is not None
+335	            assert elt is not None
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/btree.py
+ Line number: 335
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+334	            assert node is not None
+335	            assert elt is not None
+336	            oelt = node.elts[i]
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/btree.py
+ Line number: 406
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+405	        # current node
+406	        assert self.current_node is not None
+407	        while not self.current_node.is_leaf:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/btree.py
+ Line number: 410
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+409	            self.current_node = self.current_node.children[self.current_index]
+410	            assert self.current_node is not None
+411	            self.current_index = 0
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/btree.py
+ Line number: 416
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+415	        # current node
+416	        assert self.current_node is not None
+417	        while not self.current_node.is_leaf:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/btree.py
+ Line number: 420
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+419	            self.current_node = self.current_node.children[self.current_index]
+420	            assert self.current_node is not None
+421	            self.current_index = len(self.current_node.elts)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/btree.py
+ Line number: 464
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+463	            else:
+464	                assert self.current_index == 1
+465	                # right boundary; seek to the actual boundary
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/btree.py
+ Line number: 504
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+503	            else:
+504	                assert self.current_index == 0
+505	                # left boundary; seek to the actual boundary
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/btree.py
+ Line number: 550
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+549	        self.current_node = self.btree.root
+550	        assert self.current_node is not None
+551	        self.recurse = False
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/btree.py
+ Line number: 568
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+567	            self.current_node = self.current_node.children[i]
+568	            assert self.current_node is not None
+569	        i, equal = self.current_node.search_in_node(key)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/btree.py
+ Line number: 707
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+706	                if not self.root.is_leaf:
+707	                    assert len(self.root.children) == 1
+708	                    self.root = self.root.children[0]
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/btree.py
+ Line number: 724
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+723	        delt = self._delete(element.key(), element)
+724	        assert delt is element
+725	        return delt
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/btreezone.py
+ Line number: 144
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+143	        if not replacement:
+144	            assert isinstance(zone, dns.versioned.Zone)
+145	            version = zone._versions[-1]
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/btreezone.py
+ Line number: 190
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+189	                node = new_node
+190	            assert isinstance(node, Node)
+191	            if is_glue:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/btreezone.py
+ Line number: 312
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+311	        """
+312	        assert self.origin is not None
+313	        # validate the origin because we may need to relativize
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/btreezone.py
+ Line number: 326
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+325	        left = c.prev()
+326	        assert left is not None
+327	        c.next()  # skip over left
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/dnssec.py
+ Line number: 117
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+116	    rdata = key.to_wire()
+117	    assert rdata is not None  # for mypy
+118	    if key.algorithm == Algorithm.RSAMD5:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/dnssec.py
+ Line number: 246
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+245	    kwire = key.to_wire(origin=origin)
+246	    assert wire is not None and kwire is not None  # for mypy
+247	    dshash.update(wire)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/dnssec.py
+ Line number: 639
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+638	    wire = rrsig.to_wire(origin=signer)
+639	    assert wire is not None  # for mypy
+640	    data += wire[:18]
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/dnssec.py
+ Line number: 792
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+791	    domain_encoded = domain.canonicalize().to_wire()
+792	    assert domain_encoded is not None
+793	
+
+
+ + +
+
+ +
+
+ blacklist: Use of insecure MD2, MD4, MD5, or SHA1 hash function.
+ Test ID: B303
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-327
+ File: ./venv/lib/python3.12/site-packages/dns/dnssecalgs/rsa.py
+ Line number: 95
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b303-md5
+ +
+
+94	    algorithm = Algorithm.RSASHA1
+95	    chosen_hash = hashes.SHA1()
+96	
+
+
+ + +
+
+ +
+
+ blacklist: Use of insecure MD2, MD4, MD5, or SHA1 hash function.
+ Test ID: B303
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-327
+ File: ./venv/lib/python3.12/site-packages/dns/dnssecalgs/rsa.py
+ Line number: 104
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b303-md5
+ +
+
+103	    algorithm = Algorithm.RSASHA1NSEC3SHA1
+104	    chosen_hash = hashes.SHA1()
+105	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/edns.py
+ Line number: 95
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+94	        wire = self.to_wire()
+95	        assert wire is not None  # for mypy
+96	        return GenericOption(self.otype, wire)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/edns.py
+ Line number: 227
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+226	
+227	        assert srclen is not None
+228	        self.address = address
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/exception.py
+ Line number: 76
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+75	        if args or kwargs:
+76	            assert bool(args) != bool(
+77	                kwargs
+78	            ), "keyword arguments are mutually exclusive with positional args"
+79	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/exception.py
+ Line number: 82
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+81	        if kwargs:
+82	            assert (
+83	                set(kwargs.keys()) == self.supp_kwargs
+84	            ), f"following set of keyword args is required: {self.supp_kwargs}"
+85	        return kwargs
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/grange.py
+ Line number: 64
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+63	    else:
+64	        assert state == 2
+65	        step = int(cur)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/grange.py
+ Line number: 67
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+66	
+67	    assert step >= 1
+68	    assert start >= 0
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/grange.py
+ Line number: 68
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+67	    assert step >= 1
+68	    assert start >= 0
+69	    if start > stop:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/message.py
+ Line number: 1154
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1153	        """
+1154	        assert self.message is not None
+1155	        section = self.message.sections[section_number]
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/message.py
+ Line number: 1176
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1175	        """
+1176	        assert self.message is not None
+1177	        section = self.message.sections[section_number]
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/message.py
+ Line number: 1499
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1498	
+1499	        assert self.message is not None
+1500	        section = self.message.sections[section_number]
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/message.py
+ Line number: 1537
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1536	
+1537	        assert self.message is not None
+1538	        section = self.message.sections[section_number]
+
+
+ + +
+
+ +
+
+ try_except_pass: Try, Except, Pass detected.
+ Test ID: B110
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/message.py
+ Line number: 1654
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b110_try_except_pass.html
+ +
+
+1653	                        line_method = self._rr_line
+1654	                except Exception:
+1655	                    # It's just a comment.
+1656	                    pass
+1657	                self.tok.get_eol()
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/message.py
+ Line number: 1746
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1745	        return from_text(f, idna_codec, one_rr_per_rrset)
+1746	    assert False  # for mypy  lgtm[py/unreachable-statement]
+1747	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/message.py
+ Line number: 1932
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1931	    if query.had_tsig and query.keyring:
+1932	        assert query.mac is not None
+1933	        assert query.keyalgorithm is not None
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/message.py
+ Line number: 1933
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1932	        assert query.mac is not None
+1933	        assert query.keyalgorithm is not None
+1934	        response.use_tsig(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/name.py
+ Line number: 647
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+646	        digest = self.to_wire(origin=origin, canonicalize=True)
+647	        assert digest is not None
+648	        return digest
+
+
+ + +
+
+ +
+
+ hardcoded_bind_all_interfaces: Possible binding to all interfaces.
+ Test ID: B104
+ Severity: MEDIUM
+ Confidence: MEDIUM
+ CWE: CWE-605
+ File: ./venv/lib/python3.12/site-packages/dns/query.py
+ Line number: 106
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b104_hardcoded_bind_all_interfaces.html
+ +
+
+105	                    if local_address is None:
+106	                        local_address = "0.0.0.0"
+107	                    source = dns.inet.low_level_address_tuple(
+
+
+ + +
+
+ +
+
+ try_except_pass: Try, Except, Pass detected.
+ Test ID: B110
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/query.py
+ Line number: 121
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b110_try_except_pass.html
+ +
+
+120	                    return _CoreSyncStream(sock)
+121	                except Exception:
+122	                    pass
+123	            raise httpcore.ConnectError
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/query.py
+ Line number: 542
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+541	            resolver = _maybe_get_resolver(resolver)
+542	            assert parsed.hostname is not None  # pyright: ignore
+543	            answers = resolver.resolve_name(parsed.hostname, family)  # pyright: ignore
+
+
+ + +
+
+ +
+
+ blacklist: Standard pseudo-random generators are not suitable for security/cryptographic purposes.
+ Test ID: B311
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-330
+ File: ./venv/lib/python3.12/site-packages/dns/query.py
+ Line number: 544
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b311-random
+ +
+
+543	            answers = resolver.resolve_name(parsed.hostname, family)  # pyright: ignore
+544	            bootstrap_address = random.choice(list(answers.addresses()))
+545	        if session and not isinstance(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/query.py
+ Line number: 604
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+603	        # GET and POST examples
+604	        assert session is not None
+605	        if post:
+
+
+ + +
+
+ +
+
+ try_except_pass: Try, Except, Pass detected.
+ Test ID: B110
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/query.py
+ Line number: 671
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b110_try_except_pass.html
+ +
+
+670	                error = ": " + wire.decode()
+671	            except Exception:
+672	                pass
+673	        raise ValueError(f"{peer} responded with status code {status}{error}")
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/query.py
+ Line number: 695
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+694	    hostname = url_parts.hostname
+695	    assert hostname is not None
+696	    if url_parts.port is not None:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/query.py
+ Line number: 963
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+962	    else:
+963	        assert af is not None
+964	        cm = make_socket(af, socket.SOCK_DGRAM, source)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/query.py
+ Line number: 986
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+985	        return r
+986	    assert (
+987	        False  # help mypy figure out we can't get here  lgtm[py/unreachable-statement]
+988	    )
+989	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/query.py
+ Line number: 1255
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1254	        )
+1255	        assert af is not None
+1256	        cm = make_socket(af, socket.SOCK_STREAM, source)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/query.py
+ Line number: 1269
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1268	        return r
+1269	    assert (
+1270	        False  # help mypy figure out we can't get here  lgtm[py/unreachable-statement]
+1271	    )
+1272	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/query.py
+ Line number: 1407
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1406	    )
+1407	    assert af is not None  # where must be an address
+1408	    if ssl_context is None:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/query.py
+ Line number: 1428
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1427	        return r
+1428	    assert (
+1429	        False  # help mypy figure out we can't get here  lgtm[py/unreachable-statement]
+1430	    )
+1431	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/query.py
+ Line number: 1702
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1701	    )
+1702	    assert af is not None
+1703	    (_, expiration) = _compute_times(lifetime)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/query.py
+ Line number: 1768
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1767	    )
+1768	    assert af is not None
+1769	    (_, expiration) = _compute_times(lifetime)
+
+
+ + +
+
+ +
+
+ try_except_pass: Try, Except, Pass detected.
+ Test ID: B110
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/quic/_asyncio.py
+ Line number: 125
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b110_try_except_pass.html
+ +
+
+124	                    await self._wakeup()
+125	        except Exception:
+126	            pass
+127	        finally:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/quic/_asyncio.py
+ Line number: 148
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+147	            for datagram, address in datagrams:
+148	                assert address == self._peer
+149	                assert self._socket is not None
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/quic/_asyncio.py
+ Line number: 149
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+148	                assert address == self._peer
+149	                assert self._socket is not None
+150	                await self._socket.sendto(datagram, self._peer, None)
+
+
+ + +
+
+ +
+
+ try_except_pass: Try, Except, Pass detected.
+ Test ID: B110
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/quic/_asyncio.py
+ Line number: 154
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b110_try_except_pass.html
+ +
+
+153	                await asyncio.wait_for(self._wait_for_wake_timer(), interval)
+154	            except Exception:
+155	                pass
+156	            self._handle_timer(expiration)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/quic/_asyncio.py
+ Line number: 167
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+166	                if self.is_h3():
+167	                    assert self._h3_conn is not None
+168	                    h3_events = self._h3_conn.handle_event(event)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/quic/_common.py
+ Line number: 53
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+52	    def get(self, amount):
+53	        assert self.have(amount)
+54	        data = self._buffer[:amount]
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/quic/_common.py
+ Line number: 59
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+58	    def get_all(self):
+59	        assert self.seen_end()
+60	        data = self._buffer
+
+
+ + +
+
+ +
+
+ hardcoded_bind_all_interfaces: Possible binding to all interfaces.
+ Test ID: B104
+ Severity: MEDIUM
+ Confidence: MEDIUM
+ CWE: CWE-605
+ File: ./venv/lib/python3.12/site-packages/dns/quic/_common.py
+ Line number: 176
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b104_hardcoded_bind_all_interfaces.html
+ +
+
+175	            if self._af == socket.AF_INET:
+176	                source = "0.0.0.0"
+177	            elif self._af == socket.AF_INET6:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/quic/_common.py
+ Line number: 193
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+192	    def send_headers(self, stream_id, headers, is_end=False):
+193	        assert self._h3_conn is not None
+194	        self._h3_conn.send_headers(stream_id, headers, is_end)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/quic/_common.py
+ Line number: 197
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+196	    def send_data(self, stream_id, data, is_end=False):
+197	        assert self._h3_conn is not None
+198	        self._h3_conn.send_data(stream_id, data, is_end)
+
+
+ + +
+
+ +
+
+ try_except_pass: Try, Except, Pass detected.
+ Test ID: B110
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/quic/_sync.py
+ Line number: 157
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b110_try_except_pass.html
+ +
+
+156	                            pass
+157	        except Exception:
+158	            # Eat all exceptions as we have no way to pass them back to the
+159	            # caller currently.  It might be nice to fix this in the future.
+160	            pass
+161	        finally:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/quic/_sync.py
+ Line number: 176
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+175	                if self.is_h3():
+176	                    assert self._h3_conn is not None
+177	                    h3_events = self._h3_conn.handle_event(event)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/quic/_trio.py
+ Line number: 142
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+141	                if self.is_h3():
+142	                    assert self._h3_conn is not None
+143	                    h3_events = self._h3_conn.handle_event(event)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/rdata.py
+ Line number: 255
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+254	        wire = self.to_wire(origin=origin)
+255	        assert wire is not None  # for type checkers
+256	        return GenericRdata(self.rdclass, self.rdtype, wire)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/rdata.py
+ Line number: 265
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+264	        wire = self.to_wire(origin=origin, canonicalize=True)
+265	        assert wire is not None  # for mypy
+266	        return wire
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/rdata.py
+ Line number: 776
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+775	    cls = get_rdata_class(rdclass, rdtype)
+776	    assert cls is not None  # for type checkers
+777	    with dns.exception.ExceptionWrapper(dns.exception.SyntaxError):
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/rdata.py
+ Line number: 849
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+848	    cls = get_rdata_class(rdclass, rdtype)
+849	    assert cls is not None  # for type checkers
+850	    with dns.exception.ExceptionWrapper(dns.exception.FormError):
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/rdataset.py
+ Line number: 497
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+496	        r.add(rd)
+497	    assert r is not None
+498	    return r
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/rdtypes/ANY/CAA.py
+ Line number: 57
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+56	        l = len(self.tag)
+57	        assert l < 256
+58	        file.write(struct.pack("!B", l))
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/rdtypes/ANY/GPOS.py
+ Line number: 94
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+93	        l = len(self.latitude)
+94	        assert l < 256
+95	        file.write(struct.pack("!B", l))
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/rdtypes/ANY/GPOS.py
+ Line number: 98
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+97	        l = len(self.longitude)
+98	        assert l < 256
+99	        file.write(struct.pack("!B", l))
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/rdtypes/ANY/GPOS.py
+ Line number: 102
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+101	        l = len(self.altitude)
+102	        assert l < 256
+103	        file.write(struct.pack("!B", l))
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/rdtypes/ANY/HINFO.py
+ Line number: 52
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+51	        l = len(self.cpu)
+52	        assert l < 256
+53	        file.write(struct.pack("!B", l))
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/rdtypes/ANY/HINFO.py
+ Line number: 56
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+55	        l = len(self.os)
+56	        assert l < 256
+57	        file.write(struct.pack("!B", l))
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/rdtypes/ANY/ISDN.py
+ Line number: 62
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+61	        l = len(self.address)
+62	        assert l < 256
+63	        file.write(struct.pack("!B", l))
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/rdtypes/ANY/ISDN.py
+ Line number: 67
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+66	        if l > 0:
+67	            assert l < 256
+68	            file.write(struct.pack("!B", l))
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/rdtypes/ANY/X25.py
+ Line number: 50
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+49	        l = len(self.address)
+50	        assert l < 256
+51	        file.write(struct.pack("!B", l))
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/rdtypes/IN/APL.py
+ Line number: 72
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+71	        l = len(address)
+72	        assert l < 128
+73	        if self.negation:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/rdtypes/IN/NAPTR.py
+ Line number: 29
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+28	    l = len(s)
+29	    assert l < 256
+30	    file.write(struct.pack("!B", l))
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/rdtypes/util.py
+ Line number: 54
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+53	            # check that it's OK
+54	            assert isinstance(self.gateway, str)
+55	            dns.ipv4.inet_aton(self.gateway)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/rdtypes/util.py
+ Line number: 58
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+57	            # check that it's OK
+58	            assert isinstance(self.gateway, str)
+59	            dns.ipv6.inet_aton(self.gateway)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/rdtypes/util.py
+ Line number: 72
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+71	        elif self.type == 3:
+72	            assert isinstance(self.gateway, dns.name.Name)
+73	            return str(self.gateway.choose_relativity(origin, relativize))
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/rdtypes/util.py
+ Line number: 96
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+95	        elif self.type == 1:
+96	            assert isinstance(self.gateway, str)
+97	            file.write(dns.ipv4.inet_aton(self.gateway))
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/rdtypes/util.py
+ Line number: 99
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+98	        elif self.type == 2:
+99	            assert isinstance(self.gateway, str)
+100	            file.write(dns.ipv6.inet_aton(self.gateway))
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/rdtypes/util.py
+ Line number: 102
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+101	        elif self.type == 3:
+102	            assert isinstance(self.gateway, dns.name.Name)
+103	            self.gateway.to_wire(file, None, origin, False)
+
+
+ + +
+
+ +
+
+ blacklist: Standard pseudo-random generators are not suitable for security/cryptographic purposes.
+ Test ID: B311
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-330
+ File: ./venv/lib/python3.12/site-packages/dns/rdtypes/util.py
+ Line number: 244
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b311-random
+ +
+
+243	        while len(rdatas) > 1:
+244	            r = random.uniform(0, total)
+245	            for n, rdata in enumerate(rdatas):  # noqa: B007
+
+
+ + +
+
+ +
+
+ blacklist: Standard pseudo-random generators are not suitable for security/cryptographic purposes.
+ Test ID: B311
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-330
+ File: ./venv/lib/python3.12/site-packages/dns/renderer.py
+ Line number: 108
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b311-random
+ +
+
+107	        if id is None:
+108	            self.id = random.randint(0, 65535)
+109	        else:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/renderer.py
+ Line number: 212
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+211	            ttl = opt.ttl
+212	            assert opt_size >= 11
+213	            opt_rdata = opt[0]
+
+
+ + +
+
+ +
+
+ try_except_pass: Try, Except, Pass detected.
+ Test ID: B110
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/resolver.py
+ Line number: 101
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b110_try_except_pass.html
+ +
+
+100	                    return cname
+101	            except Exception:  # pragma: no cover
+102	                # We can just eat this exception as it means there was
+103	                # something wrong with the response.
+104	                pass
+105	        return self.kwargs["qnames"][0]
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/resolver.py
+ Line number: 762
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+761	        if self.retry_with_tcp:
+762	            assert self.nameserver is not None
+763	            assert not self.nameserver.is_always_max_size()
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/resolver.py
+ Line number: 763
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+762	            assert self.nameserver is not None
+763	            assert not self.nameserver.is_always_max_size()
+764	            self.tcp_attempt = True
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/resolver.py
+ Line number: 787
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+786	        #
+787	        assert self.nameserver is not None
+788	        if ex:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/resolver.py
+ Line number: 790
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+789	            # Exception during I/O or from_wire()
+790	            assert response is None
+791	            self.errors.append(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/resolver.py
+ Line number: 816
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+815	        # We got an answer!
+816	        assert response is not None
+817	        assert isinstance(response, dns.message.QueryMessage)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/resolver.py
+ Line number: 817
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+816	        assert response is not None
+817	        assert isinstance(response, dns.message.QueryMessage)
+818	        rcode = response.rcode()
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/resolver.py
+ Line number: 1322
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1321	                return answer
+1322	            assert request is not None  # needed for type checking
+1323	            done = False
+
+
+ + +
+
+ +
+
+ try_except_pass: Try, Except, Pass detected.
+ Test ID: B110
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/resolver.py
+ Line number: 1525
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b110_try_except_pass.html
+ +
+
+1524	                self.nameservers = nameservers
+1525	        except Exception:  # pragma: no cover
+1526	            pass
+1527	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/resolver.py
+ Line number: 1537
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1536	        reset_default_resolver()
+1537	    assert default_resolver is not None
+1538	    return default_resolver
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/resolver.py
+ Line number: 1716
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1715	            )
+1716	            assert answer.rrset is not None
+1717	            if answer.rrset.name == name:
+
+
+ + +
+
+ +
+
+ try_except_pass: Try, Except, Pass detected.
+ Test ID: B110
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/resolver.py
+ Line number: 1877
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b110_try_except_pass.html
+ +
+
+1876	        return _original_getaddrinfo(host, service, family, socktype, proto, flags)
+1877	    except Exception:
+1878	        pass
+1879	    # Something needs resolution!
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/resolver.py
+ Line number: 1881
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1880	    try:
+1881	        assert _resolver is not None
+1882	        answers = _resolver.resolve_name(host, family)
+
+
+ + +
+
+ +
+
+ try_except_pass: Try, Except, Pass detected.
+ Test ID: B110
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/resolver.py
+ Line number: 1903
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b110_try_except_pass.html
+ +
+
+1902	                port = socket.getservbyname(service)  # pyright: ignore
+1903	            except Exception:
+1904	                pass
+1905	    if port is None:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/resolver.py
+ Line number: 1944
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1943	        pname = "tcp"
+1944	    assert isinstance(addr, str)
+1945	    qname = dns.reversename.from_address(addr)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/resolver.py
+ Line number: 1948
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1947	        try:
+1948	            assert _resolver is not None
+1949	            answer = _resolver.resolve(qname, "PTR")
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/resolver.py
+ Line number: 1950
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1949	            answer = _resolver.resolve(qname, "PTR")
+1950	            assert answer.rrset is not None
+1951	            rdata = cast(dns.rdtypes.ANY.PTR.PTR, answer.rrset[0])
+
+
+ + +
+
+ +
+
+ try_except_pass: Try, Except, Pass detected.
+ Test ID: B110
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/resolver.py
+ Line number: 1977
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b110_try_except_pass.html
+ +
+
+1976	        # ignores them, so we do so here as well.
+1977	    except Exception:  # pragma: no cover
+1978	        pass
+1979	    return name
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/resolver.py
+ Line number: 2024
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2023	        addr = item[4][0]
+2024	        assert isinstance(addr, str)
+2025	        bin_addr = dns.inet.inet_pton(family, addr)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/rrset.py
+ Line number: 276
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+275	        r.add(rd)
+276	    assert r is not None
+277	    return r
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/tokenizer.py
+ Line number: 273
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+272	        self.line_number = 1
+273	        assert filename is not None
+274	        self.filename = filename
+
+
+ + +
+
+ +
+
+ hardcoded_password_string: Possible hardcoded password: ''
+ Test ID: B105
+ Severity: LOW
+ Confidence: MEDIUM
+ CWE: CWE-259
+ File: ./venv/lib/python3.12/site-packages/dns/tokenizer.py
+ Line number: 372
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b105_hardcoded_password_string.html
+ +
+
+371	            return Token(WHITESPACE, " ")
+372	        token = ""
+373	        ttype = IDENTIFIER
+
+
+ + +
+
+ +
+
+ hardcoded_password_string: Possible hardcoded password: ''
+ Test ID: B105
+ Severity: LOW
+ Confidence: MEDIUM
+ CWE: CWE-259
+ File: ./venv/lib/python3.12/site-packages/dns/tokenizer.py
+ Line number: 380
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b105_hardcoded_password_string.html
+ +
+
+379	                    raise dns.exception.UnexpectedEnd
+380	                if token == "" and ttype != QUOTED_STRING:
+381	                    if c == "(":
+
+
+ + +
+
+ +
+
+ hardcoded_password_string: Possible hardcoded password: ''
+ Test ID: B105
+ Severity: LOW
+ Confidence: MEDIUM
+ CWE: CWE-259
+ File: ./venv/lib/python3.12/site-packages/dns/tokenizer.py
+ Line number: 421
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b105_hardcoded_password_string.html
+ +
+
+420	                            self.skip_whitespace()
+421	                            token = ""
+422	                            continue
+
+
+ + +
+
+ +
+
+ hardcoded_password_string: Possible hardcoded password: ''
+ Test ID: B105
+ Severity: LOW
+ Confidence: MEDIUM
+ CWE: CWE-259
+ File: ./venv/lib/python3.12/site-packages/dns/tokenizer.py
+ Line number: 447
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b105_hardcoded_password_string.html
+ +
+
+446	            token += c
+447	        if token == "" and ttype != QUOTED_STRING:
+448	            if self.multiline:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/transaction.py
+ Line number: 442
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+441	                )
+442	            assert rdataset is not None  # for type checkers
+443	            if rdataset.rdclass != self.manager.get_class():
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/tsig.py
+ Line number: 225
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+224	            ctx.update(request_mac)
+225	    assert ctx is not None  # for type checkers
+226	    ctx.update(struct.pack("!H", rdata.original_id))
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/versioned.py
+ Line number: 100
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+99	                else:
+100	                    assert self.origin is not None
+101	                    oname = self.origin
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/versioned.py
+ Line number: 182
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+181	    def _prune_versions_unlocked(self):
+182	        assert len(self._versions) > 0
+183	        # Don't ever prune a version greater than or equal to one that
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/versioned.py
+ Line number: 243
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+242	    def _end_write_unlocked(self, txn):
+243	        assert self._write_txn == txn
+244	        self._write_txn = None
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/wire.py
+ Line number: 33
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+32	    def get_bytes(self, size: int) -> bytes:
+33	        assert size >= 0
+34	        if size > self.remaining():
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/wire.py
+ Line number: 78
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+77	    def restrict_to(self, size: int) -> Iterator:
+78	        assert size >= 0
+79	        if size > self.remaining():
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/xfr.py
+ Line number: 139
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+138	            if self.incremental:
+139	                assert self.soa_rdataset is not None
+140	                soa = cast(dns.rdtypes.ANY.SOA.SOA, self.soa_rdataset[0])
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/xfr.py
+ Line number: 170
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+169	                raise dns.exception.FormError("answers after final SOA")
+170	            assert self.txn is not None  # for mypy
+171	            if rdataset.rdtype == dns.rdatatype.SOA and name == self.origin:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/zone.py
+ Line number: 684
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+683	            if want_origin:
+684	                assert self.origin is not None
+685	                l = "$ORIGIN " + self.origin.to_text()
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/zone.py
+ Line number: 766
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+765	        else:
+766	            assert self.origin is not None
+767	            name = self.origin
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/zone.py
+ Line number: 815
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+814	        else:
+815	            assert self.origin is not None
+816	            origin_name = self.origin
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/zone.py
+ Line number: 853
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+852	        else:
+853	            assert self.origin is not None
+854	            rds = self.get_rdataset(self.origin, dns.rdatatype.ZONEMD)
+
+
+ + +
+
+ +
+
+ try_except_pass: Try, Except, Pass detected.
+ Test ID: B110
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/zone.py
+ Line number: 863
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b110_try_except_pass.html
+ +
+
+862	                    return
+863	            except Exception:
+864	                pass
+865	        raise DigestVerificationFailure
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/zone.py
+ Line number: 1120
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1119	    def _setup_version(self):
+1120	        assert self.version is None
+1121	        factory = self.manager.writable_version_factory  # pyright: ignore
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/zone.py
+ Line number: 1127
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1126	    def _get_rdataset(self, name, rdtype, covers):
+1127	        assert self.version is not None
+1128	        return self.version.get_rdataset(name, rdtype, covers)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/zone.py
+ Line number: 1131
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1130	    def _put_rdataset(self, name, rdataset):
+1131	        assert not self.read_only
+1132	        assert self.version is not None
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/zone.py
+ Line number: 1132
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1131	        assert not self.read_only
+1132	        assert self.version is not None
+1133	        self.version.put_rdataset(name, rdataset)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/zone.py
+ Line number: 1136
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1135	    def _delete_name(self, name):
+1136	        assert not self.read_only
+1137	        assert self.version is not None
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/zone.py
+ Line number: 1137
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1136	        assert not self.read_only
+1137	        assert self.version is not None
+1138	        self.version.delete_node(name)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/zone.py
+ Line number: 1141
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1140	    def _delete_rdataset(self, name, rdtype, covers):
+1141	        assert not self.read_only
+1142	        assert self.version is not None
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/zone.py
+ Line number: 1142
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1141	        assert not self.read_only
+1142	        assert self.version is not None
+1143	        self.version.delete_rdataset(name, rdtype, covers)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/zone.py
+ Line number: 1146
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1145	    def _name_exists(self, name):
+1146	        assert self.version is not None
+1147	        return self.version.get_node(name) is not None
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/zone.py
+ Line number: 1153
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1152	        else:
+1153	            assert self.version is not None
+1154	            return len(self.version.changed) > 0
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/zone.py
+ Line number: 1157
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1156	    def _end_transaction(self, commit):
+1157	        assert self.zone is not None
+1158	        assert self.version is not None
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/zone.py
+ Line number: 1158
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1157	        assert self.zone is not None
+1158	        assert self.version is not None
+1159	        if self.read_only:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/zone.py
+ Line number: 1178
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1177	    def _set_origin(self, origin):
+1178	        assert self.version is not None
+1179	        if self.version.origin is None:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/zone.py
+ Line number: 1183
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1182	    def _iterate_rdatasets(self):
+1183	        assert self.version is not None
+1184	        for name, node in self.version.items():
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/zone.py
+ Line number: 1189
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1188	    def _iterate_names(self):
+1189	        assert self.version is not None
+1190	        return self.version.keys()
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/zone.py
+ Line number: 1193
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1192	    def _get_node(self, name):
+1193	        assert self.version is not None
+1194	        return self.version.get_node(name)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/zone.py
+ Line number: 1197
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1196	    def _origin_information(self):
+1197	        assert self.version is not None
+1198	        (absolute, relativize, effective) = self.manager.origin_information()
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/zone.py
+ Line number: 1406
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1405	        )
+1406	    assert False  # make mypy happy  lgtm[py/unreachable-statement]
+1407	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/zonefile.py
+ Line number: 174
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+173	                raise dns.exception.SyntaxError("the last used name is undefined")
+174	            assert self.zone_origin is not None
+175	            if not name.is_subdomain(self.zone_origin):
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/zonefile.py
+ Line number: 430
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+429	            name = self.last_name
+430	            assert self.zone_origin is not None
+431	            if not name.is_subdomain(self.zone_origin):
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/zonefile.py
+ Line number: 563
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+562	    def __init__(self, manager, replacement, read_only):
+563	        assert not read_only
+564	        super().__init__(manager, replacement, read_only)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/dns/zonefile.py
+ Line number: 646
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+645	    def writer(self, replacement=False):
+646	        assert replacement is True
+647	        return RRsetsReaderTransaction(self, True, False)
+
+
+ + +
+
+ +
+
+ hardcoded_password_string: Possible hardcoded password: 'None'
+ Test ID: B105
+ Severity: LOW
+ Confidence: MEDIUM
+ CWE: CWE-259
+ File: ./venv/lib/python3.12/site-packages/flask/app.py
+ Line number: 183
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b105_hardcoded_password_string.html
+ +
+
+182	            "PROPAGATE_EXCEPTIONS": None,
+183	            "SECRET_KEY": None,
+184	            "SECRET_KEY_FALLBACKS": None,
+185	            "PERMANENT_SESSION_LIFETIME": timedelta(days=31),
+186	            "USE_X_SENDFILE": False,
+187	            "TRUSTED_HOSTS": None,
+188	            "SERVER_NAME": None,
+189	            "APPLICATION_ROOT": "/",
+190	            "SESSION_COOKIE_NAME": "session",
+191	            "SESSION_COOKIE_DOMAIN": None,
+192	            "SESSION_COOKIE_PATH": None,
+193	            "SESSION_COOKIE_HTTPONLY": True,
+194	            "SESSION_COOKIE_SECURE": False,
+195	            "SESSION_COOKIE_PARTITIONED": False,
+196	            "SESSION_COOKIE_SAMESITE": None,
+197	            "SESSION_REFRESH_EACH_REQUEST": True,
+198	            "MAX_CONTENT_LENGTH": None,
+199	            "MAX_FORM_MEMORY_SIZE": 500_000,
+200	            "MAX_FORM_PARTS": 1_000,
+201	            "SEND_FILE_MAX_AGE_DEFAULT": None,
+202	            "TRAP_BAD_REQUEST_ERRORS": None,
+203	            "TRAP_HTTP_EXCEPTIONS": False,
+204	            "EXPLAIN_TEMPLATE_LOADING": False,
+205	            "PREFERRED_URL_SCHEME": "http",
+206	            "TEMPLATES_AUTO_RELOAD": None,
+207	            "MAX_COOKIE_SIZE": 4093,
+208	            "PROVIDE_AUTOMATIC_OPTIONS": True,
+209	        }
+210	    )
+211	
+212	    #: The class that is used for request objects.  See :class:`~flask.Request`
+213	    #: for more information.
+214	    request_class: type[Request] = Request
+
+
+ + +
+
+ +
+
+ hardcoded_password_string: Possible hardcoded password: 'None'
+ Test ID: B105
+ Severity: LOW
+ Confidence: MEDIUM
+ CWE: CWE-259
+ File: ./venv/lib/python3.12/site-packages/flask/app.py
+ Line number: 184
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b105_hardcoded_password_string.html
+ +
+
+183	            "SECRET_KEY": None,
+184	            "SECRET_KEY_FALLBACKS": None,
+185	            "PERMANENT_SESSION_LIFETIME": timedelta(days=31),
+186	            "USE_X_SENDFILE": False,
+187	            "TRUSTED_HOSTS": None,
+188	            "SERVER_NAME": None,
+189	            "APPLICATION_ROOT": "/",
+190	            "SESSION_COOKIE_NAME": "session",
+191	            "SESSION_COOKIE_DOMAIN": None,
+192	            "SESSION_COOKIE_PATH": None,
+193	            "SESSION_COOKIE_HTTPONLY": True,
+194	            "SESSION_COOKIE_SECURE": False,
+195	            "SESSION_COOKIE_PARTITIONED": False,
+196	            "SESSION_COOKIE_SAMESITE": None,
+197	            "SESSION_REFRESH_EACH_REQUEST": True,
+198	            "MAX_CONTENT_LENGTH": None,
+199	            "MAX_FORM_MEMORY_SIZE": 500_000,
+200	            "MAX_FORM_PARTS": 1_000,
+201	            "SEND_FILE_MAX_AGE_DEFAULT": None,
+202	            "TRAP_BAD_REQUEST_ERRORS": None,
+203	            "TRAP_HTTP_EXCEPTIONS": False,
+204	            "EXPLAIN_TEMPLATE_LOADING": False,
+205	            "PREFERRED_URL_SCHEME": "http",
+206	            "TEMPLATES_AUTO_RELOAD": None,
+207	            "MAX_COOKIE_SIZE": 4093,
+208	            "PROVIDE_AUTOMATIC_OPTIONS": True,
+209	        }
+210	    )
+211	
+212	    #: The class that is used for request objects.  See :class:`~flask.Request`
+213	    #: for more information.
+214	    request_class: type[Request] = Request
+215	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/flask/app.py
+ Line number: 268
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+267	        if self.has_static_folder:
+268	            assert bool(static_host) == host_matching, (
+269	                "Invalid static_host/host_matching combination"
+270	            )
+271	            # Use a weakref to avoid creating a reference cycle between the app
+
+
+ + +
+
+ +
+
+ blacklist: Use of possibly insecure function - consider using safer ast.literal_eval.
+ Test ID: B307
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/flask/cli.py
+ Line number: 1031
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b307-eval
+ +
+
+1030	        with open(startup) as f:
+1031	            eval(compile(f.read(), startup, "exec"), ctx)
+1032	
+
+
+ + +
+
+ +
+
+ try_except_pass: Try, Except, Pass detected.
+ Test ID: B110
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/flask/config.py
+ Line number: 163
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b110_try_except_pass.html
+ +
+
+162	                value = loads(value)
+163	            except Exception:
+164	                # Keep the value as a string if loading failed.
+165	                pass
+166	
+
+
+ + +
+
+ +
+
+ exec_used: Use of exec detected.
+ Test ID: B102
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/flask/config.py
+ Line number: 209
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b102_exec_used.html
+ +
+
+208	            with open(filename, mode="rb") as config_file:
+209	                exec(compile(config_file.read(), filename, "exec"), d.__dict__)
+210	        except OSError as e:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/flask/ctx.py
+ Line number: 373
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+372	        """
+373	        assert self._session is not None, "The session has not yet been opened."
+374	        self._session.accessed = True
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/flask/debughelpers.py
+ Line number: 59
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+58	        exc = request.routing_exception
+59	        assert isinstance(exc, RequestRedirect)
+60	        buf = [
+
+
+ + +
+
+ +
+
+ markupsafe_markup_xss: Potential XSS with ``markupsafe.Markup`` detected. Do not use ``Markup`` on untrusted data.
+ Test ID: B704
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-79
+ File: ./venv/lib/python3.12/site-packages/flask/json/tag.py
+ Line number: 188
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b704_markupsafe_markup_xss.html
+ +
+
+187	    def to_python(self, value: t.Any) -> t.Any:
+188	        return Markup(value)
+189	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/flask/sansio/scaffold.py
+ Line number: 705
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+704	    """
+705	    assert view_func is not None, "expected view func if endpoint is not provided."
+706	    return view_func.__name__
+
+
+ + +
+
+ +
+
+ hashlib: Use of weak SHA1 hash for security. Consider usedforsecurity=False
+ Test ID: B324
+ Severity: HIGH
+ Confidence: HIGH
+ CWE: CWE-327
+ File: ./venv/lib/python3.12/site-packages/flask/sessions.py
+ Line number: 281
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b324_hashlib.html
+ +
+
+280	    """
+281	    return hashlib.sha1(string)
+282	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/flask/testing.py
+ Line number: 59
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+58	    ) -> None:
+59	        assert not (base_url or subdomain or url_scheme) or (
+60	            base_url is not None
+61	        ) != bool(subdomain or url_scheme), (
+62	            'Cannot pass "subdomain" or "url_scheme" with "base_url".'
+63	        )
+64	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/flask/views.py
+ Line number: 190
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+189	
+190	        assert meth is not None, f"Unimplemented method {request.method!r}"
+191	        return current_app.ensure_sync(meth)(**kwargs)  # type: ignore[no-any-return]
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/flask_mail/__init__.py
+ Line number: 164
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+163	        """
+164	        assert message.send_to, "No recipients have been added"
+165	        assert message.sender, (
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/flask_mail/__init__.py
+ Line number: 165
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+164	        assert message.send_to, "No recipients have been added"
+165	        assert message.sender, (
+166	            "The message does not specify a sender and a default sender "
+167	            "has not been configured"
+168	        )
+169	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/flask_sqlalchemy/model.py
+ Line number: 58
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+57	        state = sa.inspect(self)
+58	        assert state is not None
+59	
+
+
+ + +
+
+ +
+
+ hashlib: Use of weak SHA1 hash for security. Consider usedforsecurity=False
+ Test ID: B324
+ Severity: HIGH
+ Confidence: HIGH
+ CWE: CWE-327
+ File: ./venv/lib/python3.12/site-packages/flask_wtf/csrf.py
+ Line number: 53
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b324_hashlib.html
+ +
+
+52	        if field_name not in session:
+53	            session[field_name] = hashlib.sha1(os.urandom(64)).hexdigest()
+54	
+
+
+ + +
+
+ +
+
+ hashlib: Use of weak SHA1 hash for security. Consider usedforsecurity=False
+ Test ID: B324
+ Severity: HIGH
+ Confidence: HIGH
+ CWE: CWE-327
+ File: ./venv/lib/python3.12/site-packages/flask_wtf/csrf.py
+ Line number: 58
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b324_hashlib.html
+ +
+
+57	        except TypeError:
+58	            session[field_name] = hashlib.sha1(os.urandom(64)).hexdigest()
+59	            token = s.dumps(session[field_name])
+
+
+ + +
+
+ +
+
+ markupsafe_markup_xss: Potential XSS with ``markupsafe.Markup`` detected. Do not use ``Markup`` on untrusted data.
+ Test ID: B704
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-79
+ File: ./venv/lib/python3.12/site-packages/flask_wtf/form.py
+ Line number: 119
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b704_markupsafe_markup_xss.html
+ +
+
+118	
+119	        return Markup("\n".join(str(f) for f in hidden_fields(fields or self)))
+120	
+
+
+ + +
+
+ +
+
+ blacklist: Audit url open for permitted schemes. Allowing use of file:/ or custom schemes is often unexpected.
+ Test ID: B310
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-22
+ File: ./venv/lib/python3.12/site-packages/flask_wtf/recaptcha/validators.py
+ Line number: 61
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b310-urllib-urlopen
+ +
+
+60	
+61	        http_response = http.urlopen(verify_server, data.encode("utf-8"))
+62	
+
+
+ + +
+
+ +
+
+ markupsafe_markup_xss: Potential XSS with ``markupsafe.Markup`` detected. Do not use ``Markup`` on untrusted data.
+ Test ID: B704
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-79
+ File: ./venv/lib/python3.12/site-packages/flask_wtf/recaptcha/widgets.py
+ Line number: 20
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b704_markupsafe_markup_xss.html
+ +
+
+19	        if html:
+20	            return Markup(html)
+21	        params = current_app.config.get("RECAPTCHA_PARAMETERS")
+
+
+ + +
+
+ +
+
+ markupsafe_markup_xss: Potential XSS with ``markupsafe.Markup`` detected. Do not use ``Markup`` on untrusted data.
+ Test ID: B704
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-79
+ File: ./venv/lib/python3.12/site-packages/flask_wtf/recaptcha/widgets.py
+ Line number: 33
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b704_markupsafe_markup_xss.html
+ +
+
+32	            div_class = RECAPTCHA_DIV_CLASS_DEFAULT
+33	        return Markup(RECAPTCHA_TEMPLATE % (script, div_class, snippet))
+34	
+
+
+ + +
+
+ +
+
+ blacklist: Consider possible security implications associated with the subprocess module.
+ Test ID: B404
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/greenlet/tests/__init__.py
+ Line number: 217
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_imports.html#b404-import-subprocess
+ +
+
+216	    def run_script(self, script_name, show_output=True):
+217	        import subprocess
+218	        script = os.path.join(
+
+
+ + +
+
+ +
+
+ subprocess_without_shell_equals_true: subprocess call - check for execution of untrusted input.
+ Test ID: B603
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/greenlet/tests/__init__.py
+ Line number: 224
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b603_subprocess_without_shell_equals_true.html
+ +
+
+223	        try:
+224	            return subprocess.check_output([sys.executable, script],
+225	                                           encoding='utf-8',
+226	                                           stderr=subprocess.STDOUT)
+227	        except subprocess.CalledProcessError as ex:
+
+
+ + +
+
+ +
+
+ blacklist: Consider possible security implications associated with the subprocess module.
+ Test ID: B404
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/greenlet/tests/__init__.py
+ Line number: 238
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_imports.html#b404-import-subprocess
+ +
+
+237	    def assertScriptRaises(self, script_name, exitcodes=None):
+238	        import subprocess
+239	        with self.assertRaises(subprocess.CalledProcessError) as exc:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/greenlet/tests/fail_initialstub_already_started.py
+ Line number: 34
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+33	        if name == 'run' and not self.doing_it:
+34	            assert greenlet.getcurrent() is c
+35	            self.doing_it = True
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/greenlet/tests/fail_initialstub_already_started.py
+ Line number: 69
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+68	# A and B should both be dead now.
+69	assert a.dead
+70	assert b.dead
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/greenlet/tests/fail_initialstub_already_started.py
+ Line number: 70
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+69	assert a.dead
+70	assert b.dead
+71	assert not c.dead
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/greenlet/tests/fail_initialstub_already_started.py
+ Line number: 71
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+70	assert b.dead
+71	assert not c.dead
+72	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/greenlet/tests/fail_initialstub_already_started.py
+ Line number: 76
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+75	# Now C is dead
+76	assert c.dead
+77	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/greenlet/tests/fail_slp_switch.py
+ Line number: 23
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+22	g.switch()
+23	assert runs == [1]
+24	g.switch()
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/greenlet/tests/fail_slp_switch.py
+ Line number: 25
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+24	g.switch()
+25	assert runs == [1, 2]
+26	g.force_slp_switch_error = True
+
+
+ + +
+
+ +
+
+ blacklist: Consider possible security implications associated with the subprocess module.
+ Test ID: B404
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/greenlet/tests/test_cpp.py
+ Line number: 2
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_imports.html#b404-import-subprocess
+ +
+
+1	import gc
+2	import subprocess
+3	import unittest
+
+
+ + +
+
+ +
+
+ subprocess_without_shell_equals_true: subprocess call - check for execution of untrusted input.
+ Test ID: B603
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/greenlet/tests/test_cpp.py
+ Line number: 33
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b603_subprocess_without_shell_equals_true.html
+ +
+
+32	        with self.assertRaises(subprocess.CalledProcessError) as exc:
+33	            subprocess.check_output(
+34	                args,
+35	                encoding='utf-8',
+36	                stderr=subprocess.STDOUT
+37	            )
+38	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/greenlet/tests/test_gc.py
+ Line number: 12
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+11	# which is no longer optional.
+12	assert greenlet.GREENLET_USE_GC
+13	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/greenlet/tests/test_generator_nested.py
+ Line number: 106
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+105	            x = [Yield([e] + p) for p in perms([x for x in l if x != e])]
+106	            assert x
+107	    else:
+
+
+ + +
+
+ +
+
+ try_except_pass: Try, Except, Pass detected.
+ Test ID: B110
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/greenlet/tests/test_greenlet.py
+ Line number: 503
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b110_try_except_pass.html
+ +
+
+502	                    raise Exception # pylint:disable=broad-exception-raised
+503	                except: # pylint:disable=bare-except
+504	                    pass
+505	                return RawGreenlet.__getattribute__(self, name)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/greenlet/tests/test_greenlet.py
+ Line number: 1289
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1288	        # implementation detail
+1289	        assert 'main' in repr(greenlet.getcurrent())
+1290	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/greenlet/tests/test_greenlet.py
+ Line number: 1292
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1291	        t = type(greenlet.getcurrent())
+1292	        assert 'main' not in repr(t)
+1293	        return t
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/greenlet/tests/test_greenlet_trash.py
+ Line number: 48
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+47	            # what we want it to.
+48	            assert sys.version_info[:2] >= (3, 13)
+49	            def get_tstate_trash_delete_nesting():
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/greenlet/tests/test_greenlet_trash.py
+ Line number: 62
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+61	
+62	        assert get_tstate_trash_delete_nesting() == 0
+63	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/greenlet/tests/test_greenlet_trash.py
+ Line number: 118
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+117	                    x = other.switch()
+118	                    assert x == 42
+119	                    # It's important that we don't switch back to the greenlet,
+
+
+ + +
+
+ +
+
+ blacklist: Consider possible security implications associated with the subprocess module.
+ Test ID: B404
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/greenlet/tests/test_interpreter_shutdown.py
+ Line number: 32
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_imports.html#b404-import-subprocess
+ +
+
+31	import sys
+32	import subprocess
+33	import unittest
+
+
+ + +
+
+ +
+
+ subprocess_without_shell_equals_true: subprocess call - check for execution of untrusted input.
+ Test ID: B603
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/greenlet/tests/test_interpreter_shutdown.py
+ Line number: 47
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b603_subprocess_without_shell_equals_true.html
+ +
+
+46	        full_script = textwrap.dedent(script_body)
+47	        result = subprocess.run(
+48	            [sys.executable, '-c', full_script],
+49	            capture_output=True,
+50	            text=True,
+51	            timeout=30,
+52	            check=False,
+53	        )
+54	        return result.returncode, result.stdout, result.stderr
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/greenlet/tests/test_leaks.py
+ Line number: 25
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+24	
+25	assert greenlet.GREENLET_USE_GC # Option to disable this was removed in 1.0
+26	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/greenlet/tests/test_leaks.py
+ Line number: 153
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+152	
+153	        assert gc.is_tracked([])
+154	        HasFinalizerTracksInstances.reset()
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/greenlet/tests/test_leaks.py
+ Line number: 212
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+211	
+212	        assert len(background_greenlets) == 1
+213	        self.assertFalse(background_greenlets[0].dead)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/greenlet/tests/test_leaks.py
+ Line number: 322
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+321	        # resolved, so we are actually running this on 3.8+
+322	        assert sys.version_info[0] >= 3
+323	        if RUNNING_ON_MANYLINUX:
+
+
+ + +
+
+ +
+
+ start_process_with_a_shell: Starting a process with a shell, possible injection detected, security issue.
+ Test ID: B605
+ Severity: HIGH
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/greenlet/tests/test_version.py
+ Line number: 36
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b605_start_process_with_a_shell.html
+ +
+
+35	        invoke_setup = "%s %s --version" % (sys.executable, setup_py)
+36	        with os.popen(invoke_setup) as f:
+37	            sversion = f.read().strip()
+
+
+ + +
+
+ +
+
+ try_except_pass: Try, Except, Pass detected.
+ Test ID: B110
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/itsdangerous/timed.py
+ Line number: 120
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b110_try_except_pass.html
+ +
+
+119	            ts_int = bytes_to_int(base64_decode(ts_bytes))
+120	        except Exception:
+121	            pass
+122	
+
+
+ + +
+
+ +
+
+ blacklist: Consider possible security implications associated with pickle module.
+ Test ID: B403
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-502
+ File: ./venv/lib/python3.12/site-packages/jinja2/bccache.py
+ Line number: 13
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_imports.html#b403-import-pickle
+ +
+
+12	import os
+13	import pickle
+14	import stat
+
+
+ + +
+
+ +
+
+ blacklist: Pickle and modules that wrap it can be unsafe when used to deserialize untrusted data, possible security issue.
+ Test ID: B301
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-502
+ File: ./venv/lib/python3.12/site-packages/jinja2/bccache.py
+ Line number: 73
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b301-pickle
+ +
+
+72	        # the source code of the file changed, we need to reload
+73	        checksum = pickle.load(f)
+74	        if self.checksum != checksum:
+
+
+ + +
+
+ +
+
+ blacklist: Deserialization with the marshal module is possibly dangerous.
+ Test ID: B302
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-502
+ File: ./venv/lib/python3.12/site-packages/jinja2/bccache.py
+ Line number: 79
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b302-marshal
+ +
+
+78	        try:
+79	            self.code = marshal.load(f)
+80	        except (EOFError, ValueError, TypeError):
+
+
+ + +
+
+ +
+
+ hashlib: Use of weak SHA1 hash for security. Consider usedforsecurity=False
+ Test ID: B324
+ Severity: HIGH
+ Confidence: HIGH
+ CWE: CWE-327
+ File: ./venv/lib/python3.12/site-packages/jinja2/bccache.py
+ Line number: 156
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b324_hashlib.html
+ +
+
+155	        """Returns the unique hash key for this template name."""
+156	        hash = sha1(name.encode("utf-8"))
+157	
+
+
+ + +
+
+ +
+
+ hashlib: Use of weak SHA1 hash for security. Consider usedforsecurity=False
+ Test ID: B324
+ Severity: HIGH
+ Confidence: HIGH
+ CWE: CWE-327
+ File: ./venv/lib/python3.12/site-packages/jinja2/bccache.py
+ Line number: 165
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b324_hashlib.html
+ +
+
+164	        """Returns a checksum for the source."""
+165	        return sha1(source.encode("utf-8")).hexdigest()
+166	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/jinja2/compiler.py
+ Line number: 832
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+831	    ) -> None:
+832	        assert frame is None, "no root frame allowed"
+833	        eval_ctx = EvalContext(self.environment, self.name)
+
+
+ + +
+
+ +
+
+ hardcoded_password_string: Possible hardcoded password: 'environment'
+ Test ID: B105
+ Severity: LOW
+ Confidence: MEDIUM
+ CWE: CWE-259
+ File: ./venv/lib/python3.12/site-packages/jinja2/compiler.py
+ Line number: 1440
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b105_hardcoded_password_string.html
+ +
+
+1439	
+1440	                if pass_arg == "environment":
+1441	
+
+
+ + +
+
+ +
+
+ exec_used: Use of exec detected.
+ Test ID: B102
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/jinja2/debug.py
+ Line number: 145
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b102_exec_used.html
+ +
+
+144	    try:
+145	        exec(code, globals, locals)
+146	    except BaseException:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/jinja2/environment.py
+ Line number: 128
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+127	    """Perform a sanity check on the environment."""
+128	    assert issubclass(
+129	        environment.undefined, Undefined
+130	    ), "'undefined' must be a subclass of 'jinja2.Undefined'."
+131	    assert (
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/jinja2/environment.py
+ Line number: 131
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+130	    ), "'undefined' must be a subclass of 'jinja2.Undefined'."
+131	    assert (
+132	        environment.block_start_string
+133	        != environment.variable_start_string
+134	        != environment.comment_start_string
+135	    ), "block, variable and comment start strings must be different."
+136	    assert environment.newline_sequence in {
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/jinja2/environment.py
+ Line number: 136
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+135	    ), "block, variable and comment start strings must be different."
+136	    assert environment.newline_sequence in {
+137	        "\r",
+138	        "\r\n",
+139	        "\n",
+140	    }, "'newline_sequence' must be one of '\\n', '\\r\\n', or '\\r'."
+141	    return environment
+
+
+ + +
+
+ +
+
+ try_except_pass: Try, Except, Pass detected.
+ Test ID: B110
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/jinja2/environment.py
+ Line number: 476
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b110_try_except_pass.html
+ +
+
+475	                    attr = str(argument)
+476	                except Exception:
+477	                    pass
+478	                else:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/jinja2/environment.py
+ Line number: 851
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+850	
+851	        assert log_function is not None
+852	        assert self.loader is not None, "No loader configured."
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/jinja2/environment.py
+ Line number: 852
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+851	        assert log_function is not None
+852	        assert self.loader is not None, "No loader configured."
+853	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/jinja2/environment.py
+ Line number: 919
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+918	        """
+919	        assert self.loader is not None, "No loader configured."
+920	        names = self.loader.list_templates()
+
+
+ + +
+
+ +
+
+ exec_used: Use of exec detected.
+ Test ID: B102
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/jinja2/environment.py
+ Line number: 1228
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b102_exec_used.html
+ +
+
+1227	        namespace = {"environment": environment, "__file__": code.co_filename}
+1228	        exec(code, namespace)
+1229	        rv = cls._from_namespace(environment, namespace, globals)
+
+
+ + +
+
+ +
+
+ markupsafe_markup_xss: Potential XSS with ``markupsafe.Markup`` detected. Do not use ``Markup`` on untrusted data.
+ Test ID: B704
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-79
+ File: ./venv/lib/python3.12/site-packages/jinja2/environment.py
+ Line number: 1544
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b704_markupsafe_markup_xss.html
+ +
+
+1543	    def __html__(self) -> Markup:
+1544	        return Markup(concat(self._body_stream))
+1545	
+
+
+ + +
+
+ +
+
+ markupsafe_markup_xss: Potential XSS with ``markupsafe.Markup`` detected. Do not use ``Markup`` on untrusted data.
+ Test ID: B704
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-79
+ File: ./venv/lib/python3.12/site-packages/jinja2/ext.py
+ Line number: 176
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b704_markupsafe_markup_xss.html
+ +
+
+175	        if __context.eval_ctx.autoescape:
+176	            rv = Markup(rv)
+177	        # Always treat as a format string, even if there are no
+
+
+ + +
+
+ +
+
+ markupsafe_markup_xss: Potential XSS with ``markupsafe.Markup`` detected. Do not use ``Markup`` on untrusted data.
+ Test ID: B704
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-79
+ File: ./venv/lib/python3.12/site-packages/jinja2/ext.py
+ Line number: 197
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b704_markupsafe_markup_xss.html
+ +
+
+196	        if __context.eval_ctx.autoescape:
+197	            rv = Markup(rv)
+198	        # Always treat as a format string, see gettext comment above.
+
+
+ + +
+
+ +
+
+ markupsafe_markup_xss: Potential XSS with ``markupsafe.Markup`` detected. Do not use ``Markup`` on untrusted data.
+ Test ID: B704
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-79
+ File: ./venv/lib/python3.12/site-packages/jinja2/ext.py
+ Line number: 213
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b704_markupsafe_markup_xss.html
+ +
+
+212	        if __context.eval_ctx.autoescape:
+213	            rv = Markup(rv)
+214	
+
+
+ + +
+
+ +
+
+ markupsafe_markup_xss: Potential XSS with ``markupsafe.Markup`` detected. Do not use ``Markup`` on untrusted data.
+ Test ID: B704
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-79
+ File: ./venv/lib/python3.12/site-packages/jinja2/ext.py
+ Line number: 238
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b704_markupsafe_markup_xss.html
+ +
+
+237	        if __context.eval_ctx.autoescape:
+238	            rv = Markup(rv)
+239	
+
+
+ + +
+
+ +
+
+ markupsafe_markup_xss: Potential XSS with ``markupsafe.Markup`` detected. Do not use ``Markup`` on untrusted data.
+ Test ID: B704
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-79
+ File: ./venv/lib/python3.12/site-packages/jinja2/filters.py
+ Line number: 316
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b704_markupsafe_markup_xss.html
+ +
+
+315	    if eval_ctx.autoescape:
+316	        rv = Markup(rv)
+317	
+
+
+ + +
+
+ +
+
+ blacklist: Standard pseudo-random generators are not suitable for security/cryptographic purposes.
+ Test ID: B311
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-330
+ File: ./venv/lib/python3.12/site-packages/jinja2/filters.py
+ Line number: 699
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b311-random
+ +
+
+698	    try:
+699	        return random.choice(seq)
+700	    except IndexError:
+
+
+ + +
+
+ +
+
+ markupsafe_markup_xss: Potential XSS with ``markupsafe.Markup`` detected. Do not use ``Markup`` on untrusted data.
+ Test ID: B704
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-79
+ File: ./venv/lib/python3.12/site-packages/jinja2/filters.py
+ Line number: 820
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b704_markupsafe_markup_xss.html
+ +
+
+819	    if eval_ctx.autoescape:
+820	        rv = Markup(rv)
+821	
+
+
+ + +
+
+ +
+
+ markupsafe_markup_xss: Potential XSS with ``markupsafe.Markup`` detected. Do not use ``Markup`` on untrusted data.
+ Test ID: B704
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-79
+ File: ./venv/lib/python3.12/site-packages/jinja2/filters.py
+ Line number: 851
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b704_markupsafe_markup_xss.html
+ +
+
+850	    if isinstance(s, Markup):
+851	        indention = Markup(indention)
+852	        newline = Markup(newline)
+
+
+ + +
+
+ +
+
+ markupsafe_markup_xss: Potential XSS with ``markupsafe.Markup`` detected. Do not use ``Markup`` on untrusted data.
+ Test ID: B704
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-79
+ File: ./venv/lib/python3.12/site-packages/jinja2/filters.py
+ Line number: 852
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b704_markupsafe_markup_xss.html
+ +
+
+851	        indention = Markup(indention)
+852	        newline = Markup(newline)
+853	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/jinja2/filters.py
+ Line number: 908
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+907	
+908	    assert length >= len(end), f"expected length >= {len(end)}, got {length}"
+909	    assert leeway >= 0, f"expected leeway >= 0, got {leeway}"
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/jinja2/filters.py
+ Line number: 909
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+908	    assert length >= len(end), f"expected length >= {len(end)}, got {length}"
+909	    assert leeway >= 0, f"expected leeway >= 0, got {leeway}"
+910	
+
+
+ + +
+
+ +
+
+ markupsafe_markup_xss: Potential XSS with ``markupsafe.Markup`` detected. Do not use ``Markup`` on untrusted data.
+ Test ID: B704
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-79
+ File: ./venv/lib/python3.12/site-packages/jinja2/filters.py
+ Line number: 1056
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b704_markupsafe_markup_xss.html
+ +
+
+1055	
+1056	    return Markup(str(value)).striptags()
+1057	
+
+
+ + +
+
+ +
+
+ markupsafe_markup_xss: Potential XSS with ``markupsafe.Markup`` detected. Do not use ``Markup`` on untrusted data.
+ Test ID: B704
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-79
+ File: ./venv/lib/python3.12/site-packages/jinja2/filters.py
+ Line number: 1377
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b704_markupsafe_markup_xss.html
+ +
+
+1376	    """
+1377	    return Markup(value)
+1378	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/jinja2/idtracking.py
+ Line number: 138
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+137	            target = self.find_ref(name)
+138	            assert target is not None, "should not happen"
+139	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/jinja2/lexer.py
+ Line number: 144
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+143	reverse_operators = {v: k for k, v in operators.items()}
+144	assert len(operators) == len(reverse_operators), "operators dropped"
+145	operator_re = re.compile(
+
+
+ + +
+
+ +
+
+ hardcoded_password_string: Possible hardcoded password: 'keyword'
+ Test ID: B105
+ Severity: LOW
+ Confidence: MEDIUM
+ CWE: CWE-259
+ File: ./venv/lib/python3.12/site-packages/jinja2/lexer.py
+ Line number: 639
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b105_hardcoded_password_string.html
+ +
+
+638	                value = self._normalize_newlines(value_str)
+639	            elif token == "keyword":
+640	                token = value_str
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/jinja2/lexer.py
+ Line number: 694
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+693	        if state is not None and state != "root":
+694	            assert state in ("variable", "block"), "invalid state"
+695	            stack.append(state + "_begin")
+
+
+ + +
+
+ +
+
+ hardcoded_password_string: Possible hardcoded password: '#bygroup'
+ Test ID: B105
+ Severity: LOW
+ Confidence: MEDIUM
+ CWE: CWE-259
+ File: ./venv/lib/python3.12/site-packages/jinja2/lexer.py
+ Line number: 765
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b105_hardcoded_password_string.html
+ +
+
+764	                        # group that matched
+765	                        elif token == "#bygroup":
+766	                            for key, value in m.groupdict().items():
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/jinja2/loaders.py
+ Line number: 325
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+324	        spec = importlib.util.find_spec(package_name)
+325	        assert spec is not None, "An import spec was not found for the package."
+326	        loader = spec.loader
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/jinja2/loaders.py
+ Line number: 327
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+326	        loader = spec.loader
+327	        assert loader is not None, "A loader was not found for the package."
+328	        self._loader = loader
+
+
+ + +
+
+ +
+
+ hashlib: Use of weak SHA1 hash for security. Consider usedforsecurity=False
+ Test ID: B324
+ Severity: HIGH
+ Confidence: HIGH
+ CWE: CWE-327
+ File: ./venv/lib/python3.12/site-packages/jinja2/loaders.py
+ Line number: 661
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b324_hashlib.html
+ +
+
+660	    def get_template_key(name: str) -> str:
+661	        return "tmpl_" + sha1(name.encode("utf-8")).hexdigest()
+662	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/jinja2/nodes.py
+ Line number: 64
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+63	            storage.extend(d.get(attr, ()))
+64	            assert len(bases) <= 1, "multiple inheritance not allowed"
+65	            assert len(storage) == len(set(storage)), "layout conflict"
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/jinja2/nodes.py
+ Line number: 65
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+64	            assert len(bases) <= 1, "multiple inheritance not allowed"
+65	            assert len(storage) == len(set(storage)), "layout conflict"
+66	            d[attr] = tuple(storage)
+
+
+ + +
+
+ +
+
+ markupsafe_markup_xss: Potential XSS with ``markupsafe.Markup`` detected. Do not use ``Markup`` on untrusted data.
+ Test ID: B704
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-79
+ File: ./venv/lib/python3.12/site-packages/jinja2/nodes.py
+ Line number: 619
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b704_markupsafe_markup_xss.html
+ +
+
+618	        if eval_ctx.autoescape:
+619	            return Markup(self.data)
+620	        return self.data
+
+
+ + +
+
+ +
+
+ markupsafe_markup_xss: Potential XSS with ``markupsafe.Markup`` detected. Do not use ``Markup`` on untrusted data.
+ Test ID: B704
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-79
+ File: ./venv/lib/python3.12/site-packages/jinja2/nodes.py
+ Line number: 1091
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b704_markupsafe_markup_xss.html
+ +
+
+1090	        eval_ctx = get_eval_context(self, eval_ctx)
+1091	        return Markup(self.expr.as_const(eval_ctx))
+1092	
+
+
+ + +
+
+ +
+
+ markupsafe_markup_xss: Potential XSS with ``markupsafe.Markup`` detected. Do not use ``Markup`` on untrusted data.
+ Test ID: B704
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-79
+ File: ./venv/lib/python3.12/site-packages/jinja2/nodes.py
+ Line number: 1112
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b704_markupsafe_markup_xss.html
+ +
+
+1111	        if eval_ctx.autoescape:
+1112	            return Markup(expr)
+1113	        return expr
+
+
+ + +
+
+ +
+
+ hardcoded_password_string: Possible hardcoded password: 'sub'
+ Test ID: B105
+ Severity: LOW
+ Confidence: MEDIUM
+ CWE: CWE-259
+ File: ./venv/lib/python3.12/site-packages/jinja2/parser.py
+ Line number: 630
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b105_hardcoded_password_string.html
+ +
+
+629	
+630	        if token_type == "sub":
+631	            next(self.stream)
+
+
+ + +
+
+ +
+
+ hardcoded_password_string: Possible hardcoded password: 'add'
+ Test ID: B105
+ Severity: LOW
+ Confidence: MEDIUM
+ CWE: CWE-259
+ File: ./venv/lib/python3.12/site-packages/jinja2/parser.py
+ Line number: 633
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b105_hardcoded_password_string.html
+ +
+
+632	            node = nodes.Neg(self.parse_unary(False), lineno=lineno)
+633	        elif token_type == "add":
+634	            next(self.stream)
+
+
+ + +
+
+ +
+
+ hardcoded_password_string: Possible hardcoded password: 'dot'
+ Test ID: B105
+ Severity: LOW
+ Confidence: MEDIUM
+ CWE: CWE-259
+ File: ./venv/lib/python3.12/site-packages/jinja2/parser.py
+ Line number: 784
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b105_hardcoded_password_string.html
+ +
+
+783	            token_type = self.stream.current.type
+784	            if token_type == "dot" or token_type == "lbracket":
+785	                node = self.parse_subscript(node)
+
+
+ + +
+
+ +
+
+ hardcoded_password_string: Possible hardcoded password: 'lbracket'
+ Test ID: B105
+ Severity: LOW
+ Confidence: MEDIUM
+ CWE: CWE-259
+ File: ./venv/lib/python3.12/site-packages/jinja2/parser.py
+ Line number: 784
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b105_hardcoded_password_string.html
+ +
+
+783	            token_type = self.stream.current.type
+784	            if token_type == "dot" or token_type == "lbracket":
+785	                node = self.parse_subscript(node)
+
+
+ + +
+
+ +
+
+ hardcoded_password_string: Possible hardcoded password: 'lparen'
+ Test ID: B105
+ Severity: LOW
+ Confidence: MEDIUM
+ CWE: CWE-259
+ File: ./venv/lib/python3.12/site-packages/jinja2/parser.py
+ Line number: 788
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b105_hardcoded_password_string.html
+ +
+
+787	            # and getitem) as well as filters and tests
+788	            elif token_type == "lparen":
+789	                node = self.parse_call(node)
+
+
+ + +
+
+ +
+
+ hardcoded_password_string: Possible hardcoded password: 'pipe'
+ Test ID: B105
+ Severity: LOW
+ Confidence: MEDIUM
+ CWE: CWE-259
+ File: ./venv/lib/python3.12/site-packages/jinja2/parser.py
+ Line number: 797
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b105_hardcoded_password_string.html
+ +
+
+796	            token_type = self.stream.current.type
+797	            if token_type == "pipe":
+798	                node = self.parse_filter(node)  # type: ignore
+
+
+ + +
+
+ +
+
+ hardcoded_password_string: Possible hardcoded password: 'name'
+ Test ID: B105
+ Severity: LOW
+ Confidence: MEDIUM
+ CWE: CWE-259
+ File: ./venv/lib/python3.12/site-packages/jinja2/parser.py
+ Line number: 799
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b105_hardcoded_password_string.html
+ +
+
+798	                node = self.parse_filter(node)  # type: ignore
+799	            elif token_type == "name" and self.stream.current.value == "is":
+800	                node = self.parse_test(node)
+
+
+ + +
+
+ +
+
+ hardcoded_password_string: Possible hardcoded password: 'lparen'
+ Test ID: B105
+ Severity: LOW
+ Confidence: MEDIUM
+ CWE: CWE-259
+ File: ./venv/lib/python3.12/site-packages/jinja2/parser.py
+ Line number: 803
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b105_hardcoded_password_string.html
+ +
+
+802	            # and getitem) as well as filters and tests
+803	            elif token_type == "lparen":
+804	                node = self.parse_call(node)
+
+
+ + +
+
+ +
+
+ markupsafe_markup_xss: Potential XSS with ``markupsafe.Markup`` detected. Do not use ``Markup`` on untrusted data.
+ Test ID: B704
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-79
+ File: ./venv/lib/python3.12/site-packages/jinja2/runtime.py
+ Line number: 375
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b704_markupsafe_markup_xss.html
+ +
+
+374	        if self._context.eval_ctx.autoescape:
+375	            return Markup(rv)
+376	
+
+
+ + +
+
+ +
+
+ markupsafe_markup_xss: Potential XSS with ``markupsafe.Markup`` detected. Do not use ``Markup`` on untrusted data.
+ Test ID: B704
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-79
+ File: ./venv/lib/python3.12/site-packages/jinja2/runtime.py
+ Line number: 389
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b704_markupsafe_markup_xss.html
+ +
+
+388	        if self._context.eval_ctx.autoescape:
+389	            return Markup(rv)
+390	
+
+
+ + +
+
+ +
+
+ markupsafe_markup_xss: Potential XSS with ``markupsafe.Markup`` detected. Do not use ``Markup`` on untrusted data.
+ Test ID: B704
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-79
+ File: ./venv/lib/python3.12/site-packages/jinja2/runtime.py
+ Line number: 776
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b704_markupsafe_markup_xss.html
+ +
+
+775	        if autoescape:
+776	            return Markup(rv)
+777	
+
+
+ + +
+
+ +
+
+ markupsafe_markup_xss: Potential XSS with ``markupsafe.Markup`` detected. Do not use ``Markup`` on untrusted data.
+ Test ID: B704
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-79
+ File: ./venv/lib/python3.12/site-packages/jinja2/runtime.py
+ Line number: 787
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b704_markupsafe_markup_xss.html
+ +
+
+786	        if autoescape:
+787	            rv = Markup(rv)
+788	
+
+
+ + +
+
+ +
+
+ try_except_pass: Try, Except, Pass detected.
+ Test ID: B110
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/jinja2/sandbox.py
+ Line number: 298
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b110_try_except_pass.html
+ +
+
+297	                    attr = str(argument)
+298	                except Exception:
+299	                    pass
+300	                else:
+
+
+ + +
+
+ +
+
+ blacklist: Standard pseudo-random generators are not suitable for security/cryptographic purposes.
+ Test ID: B311
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-330
+ File: ./venv/lib/python3.12/site-packages/jinja2/utils.py
+ Line number: 370
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b311-random
+ +
+
+369	        # each paragraph contains out of 20 to 100 words.
+370	        for idx, _ in enumerate(range(randrange(min, max))):
+371	            while True:
+
+
+ + +
+
+ +
+
+ blacklist: Standard pseudo-random generators are not suitable for security/cryptographic purposes.
+ Test ID: B311
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-330
+ File: ./venv/lib/python3.12/site-packages/jinja2/utils.py
+ Line number: 372
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b311-random
+ +
+
+371	            while True:
+372	                word = choice(words)
+373	                if word != last:
+
+
+ + +
+
+ +
+
+ blacklist: Standard pseudo-random generators are not suitable for security/cryptographic purposes.
+ Test ID: B311
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-330
+ File: ./venv/lib/python3.12/site-packages/jinja2/utils.py
+ Line number: 380
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b311-random
+ +
+
+379	            # add commas
+380	            if idx - randrange(3, 8) > last_comma:
+381	                last_comma = idx
+
+
+ + +
+
+ +
+
+ blacklist: Standard pseudo-random generators are not suitable for security/cryptographic purposes.
+ Test ID: B311
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-330
+ File: ./venv/lib/python3.12/site-packages/jinja2/utils.py
+ Line number: 385
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b311-random
+ +
+
+384	            # add end of sentences
+385	            if idx - randrange(10, 20) > last_fullstop:
+386	                last_comma = last_fullstop = idx
+
+
+ + +
+
+ +
+
+ markupsafe_markup_xss: Potential XSS with ``markupsafe.Markup`` detected. Do not use ``Markup`` on untrusted data.
+ Test ID: B704
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-79
+ File: ./venv/lib/python3.12/site-packages/jinja2/utils.py
+ Line number: 403
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b704_markupsafe_markup_xss.html
+ +
+
+402	        return "\n\n".join(result)
+403	    return markupsafe.Markup(
+404	        "\n".join(f"<p>{markupsafe.escape(x)}</p>" for x in result)
+405	    )
+406	
+
+
+ + +
+
+ +
+
+ markupsafe_markup_xss: Potential XSS with ``markupsafe.Markup`` detected. Do not use ``Markup`` on untrusted data.
+ Test ID: B704
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-79
+ File: ./venv/lib/python3.12/site-packages/jinja2/utils.py
+ Line number: 668
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b704_markupsafe_markup_xss.html
+ +
+
+667	
+668	    return markupsafe.Markup(
+669	        dumps(obj, **kwargs)
+670	        .replace("<", "\\u003c")
+671	        .replace(">", "\\u003e")
+672	        .replace("&", "\\u0026")
+673	        .replace("'", "\\u0027")
+674	    )
+675	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/markdown_it/ruler.py
+ Line number: 265
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+264	            self.__compile__()
+265	            assert self.__cache__ is not None
+266	        # Chain can be empty, if rules disabled. But we still have to return Array.
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/markdown_it/rules_core/linkify.py
+ Line number: 35
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+34	        # Use reversed logic in links start/end match
+35	        assert tokens is not None
+36	        i = len(tokens)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/markdown_it/rules_core/linkify.py
+ Line number: 39
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+38	            i -= 1
+39	            assert isinstance(tokens, list)
+40	            currentToken = tokens[i]
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/markdown_it/rules_core/smartquotes.py
+ Line number: 20
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+19	    # But basically, the index will not be negative.
+20	    assert index >= 0
+21	    return string[:index] + ch + string[index + 1 :]
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/markdown_it/tree.py
+ Line number: 100
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+99	            else:
+100	                assert node.nester_tokens
+101	                token_list.append(node.nester_tokens.opening)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/markdown_it/tree.py
+ Line number: 164
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+163	            return self.token.type
+164	        assert self.nester_tokens
+165	        return self.nester_tokens.opening.type.removesuffix("_open")
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/__pip-runner__.py
+ Line number: 43
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+42	        spec = PathFinder.find_spec(fullname, [PIP_SOURCES_ROOT], target)
+43	        assert spec, (PIP_SOURCES_ROOT, fullname)
+44	        return spec
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/__pip-runner__.py
+ Line number: 49
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+48	
+49	assert __name__ == "__main__", "Cannot run __pip-runner__.py as a non-main module"
+50	runpy.run_module("pip", run_name="__main__", alter_sys=True)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/build_env.py
+ Line number: 213
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+212	        prefix = self._prefixes[prefix_as_string]
+213	        assert not prefix.setup
+214	        prefix.setup = True
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/cache.py
+ Line number: 40
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+39	        super().__init__()
+40	        assert not cache_dir or os.path.isabs(cache_dir)
+41	        self.cache_dir = cache_dir or None
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/cache.py
+ Line number: 124
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+123	        parts = self._get_cache_path_parts(link)
+124	        assert self.cache_dir
+125	        # Store wheels within the root cache_dir
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/cli/base_command.py
+ Line number: 89
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+88	        # are present.
+89	        assert not hasattr(options, "no_index")
+90	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/cli/base_command.py
+ Line number: 181
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+180	                    status = run_func(*args)
+181	                    assert isinstance(status, int)
+182	                    return status
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/cli/command_context.py
+ Line number: 15
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+14	    def main_context(self) -> Generator[None, None, None]:
+15	        assert not self._in_main_context
+16	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/cli/command_context.py
+ Line number: 25
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+24	    def enter_context(self, context_provider: ContextManager[_T]) -> _T:
+25	        assert self._in_main_context
+26	
+
+
+ + +
+
+ +
+
+ blacklist: Consider possible security implications associated with the subprocess module.
+ Test ID: B404
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/cli/main_parser.py
+ Line number: 5
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_imports.html#b404-import-subprocess
+ +
+
+4	import os
+5	import subprocess
+6	import sys
+
+
+ + +
+
+ +
+
+ subprocess_without_shell_equals_true: subprocess call - check for execution of untrusted input.
+ Test ID: B603
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/cli/main_parser.py
+ Line number: 101
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b603_subprocess_without_shell_equals_true.html
+ +
+
+100	        try:
+101	            proc = subprocess.run(pip_cmd)
+102	            returncode = proc.returncode
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/cli/parser.py
+ Line number: 51
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+50	        if option.takes_value():
+51	            assert option.dest is not None
+52	            metavar = option.metavar or option.dest.lower()
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/cli/parser.py
+ Line number: 112
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+111	        if self.parser is not None:
+112	            assert isinstance(self.parser, ConfigOptionParser)
+113	            self.parser._update_defaults(self.parser.defaults)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/cli/parser.py
+ Line number: 114
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+113	            self.parser._update_defaults(self.parser.defaults)
+114	            assert option.dest is not None
+115	            default_values = self.parser.defaults.get(option.dest)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/cli/parser.py
+ Line number: 168
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+167	
+168	        assert self.name
+169	        super().__init__(*args, **kwargs)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/cli/parser.py
+ Line number: 225
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+224	
+225	            assert option.dest is not None
+226	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/cli/parser.py
+ Line number: 252
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+251	            elif option.action == "callback":
+252	                assert option.callback is not None
+253	                late_eval.add(option.dest)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/cli/parser.py
+ Line number: 285
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+284	        for option in self._get_all_options():
+285	            assert option.dest is not None
+286	            default = defaults.get(option.dest)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/cli/progress_bars.py
+ Line number: 28
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+27	) -> Generator[bytes, None, None]:
+28	    assert bar_type == "on", "This should only be used in the default mode."
+29	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/cli/req_command.py
+ Line number: 99
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+98	            # then https://github.com/python/mypy/issues/7696 kicks in
+99	            assert self._session is not None
+100	        return self._session
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/cli/req_command.py
+ Line number: 110
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+109	        cache_dir = options.cache_dir
+110	        assert not cache_dir or os.path.isabs(cache_dir)
+111	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/cli/req_command.py
+ Line number: 171
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+170	        # Make sure the index_group options are present.
+171	        assert hasattr(options, "no_index")
+172	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/cli/req_command.py
+ Line number: 240
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+239	    ) -> Optional[int]:
+240	        assert self.tempdir_registry is not None
+241	        if options.no_clean:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/cli/req_command.py
+ Line number: 286
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+285	        temp_build_dir_path = temp_build_dir.path
+286	        assert temp_build_dir_path is not None
+287	        legacy_resolver = False
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/cli/spinners.py
+ Line number: 44
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+43	    def _write(self, status: str) -> None:
+44	        assert not self._finished
+45	        # Erase what we wrote before by backspacing to the beginning, writing
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/cli/spinners.py
+ Line number: 83
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+82	    def _update(self, status: str) -> None:
+83	        assert not self._finished
+84	        self._rate_limiter.reset()
+
+
+ + +
+
+ +
+
+ any_other_function_with_shell_equals_true: Function call with shell=True parameter identified, possible security issue.
+ Test ID: B604
+ Severity: MEDIUM
+ Confidence: LOW
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/commands/completion.py
+ Line number: 124
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b604_any_other_function_with_shell_equals_true.html
+ +
+
+123	            )
+124	            print(BASE_COMPLETION.format(script=script, shell=options.shell))
+125	            return SUCCESS
+
+
+ + +
+
+ +
+
+ blacklist: Consider possible security implications associated with the subprocess module.
+ Test ID: B404
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/commands/configuration.py
+ Line number: 3
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_imports.html#b404-import-subprocess
+ +
+
+2	import os
+3	import subprocess
+4	from optparse import Values
+
+
+ + +
+
+ +
+
+ subprocess_popen_with_shell_equals_true: subprocess call with shell=True identified, security issue.
+ Test ID: B602
+ Severity: HIGH
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/commands/configuration.py
+ Line number: 239
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b602_subprocess_popen_with_shell_equals_true.html
+ +
+
+238	        try:
+239	            subprocess.check_call(f'{editor} "{fname}"', shell=True)
+240	        except FileNotFoundError as e:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/commands/debug.py
+ Line number: 73
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+72	        # Try to find version in debundled module info.
+73	        assert module.__file__ is not None
+74	        env = get_environment([os.path.dirname(module.__file__)])
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/commands/download.py
+ Line number: 137
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+136	            if req.satisfied_by is None:
+137	                assert req.name is not None
+138	                preparer.save_linked_requirement(req)
+
+
+ + +
+
+ +
+
+ try_except_pass: Try, Except, Pass detected.
+ Test ID: B110
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/commands/install.py
+ Line number: 480
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b110_try_except_pass.html
+ +
+
+479	                        item = f"{item}-{installed_dist.version}"
+480	                except Exception:
+481	                    pass
+482	                items.append(item)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/commands/install.py
+ Line number: 509
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+508	        if options.target_dir:
+509	            assert target_temp_dir
+510	            self._handle_target_dir(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/commands/install.py
+ Line number: 598
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+597	        else:
+598	            assert resolver_variant == "resolvelib"
+599	            parts.append(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/commands/install.py
+ Line number: 695
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+694	    # If we are here, user installs have not been explicitly requested/avoided
+695	    assert use_user_site is None
+696	
+
+
+ + +
+
+ +
+
+ blacklist: Using xmlrpc.client to parse untrusted XML data is known to be vulnerable to XML attacks. Use defusedxml.xmlrpc.monkey_patch() function to monkey-patch xmlrpclib and mitigate XML vulnerabilities.
+ Test ID: B411
+ Severity: HIGH
+ Confidence: HIGH
+ CWE: CWE-20
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/commands/search.py
+ Line number: 5
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_imports.html#b411-import-xmlrpclib
+ +
+
+4	import textwrap
+5	import xmlrpc.client
+6	from collections import OrderedDict
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/commands/search.py
+ Line number: 84
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+83	            raise CommandError(message)
+84	        assert isinstance(hits, list)
+85	        return hits
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/commands/wheel.py
+ Line number: 168
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+167	        for req in build_successes:
+168	            assert req.link and req.link.is_wheel
+169	            assert req.local_file_path
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/commands/wheel.py
+ Line number: 169
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+168	            assert req.link and req.link.is_wheel
+169	            assert req.local_file_path
+170	            # copy from cache to target directory
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/configuration.py
+ Line number: 130
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+129	        """Returns the file with highest priority in configuration"""
+130	        assert self.load_only is not None, "Need to be specified a file to be editing"
+131	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/configuration.py
+ Line number: 160
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+159	
+160	        assert self.load_only
+161	        fname, parser = self._get_parser_to_modify()
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/configuration.py
+ Line number: 180
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+179	
+180	        assert self.load_only
+181	        if key not in self._config[self.load_only]:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/configuration.py
+ Line number: 365
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+364	        # Determine which parser to modify
+365	        assert self.load_only
+366	        parsers = self._parsers[self.load_only]
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/distributions/installed.py
+ Line number: 20
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+19	    def get_metadata_distribution(self) -> BaseDistribution:
+20	        assert self.req.satisfied_by is not None, "not actually installed"
+21	        return self.req.satisfied_by
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/distributions/sdist.py
+ Line number: 24
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+23	        """Identify this requirement uniquely by its link."""
+24	        assert self.req.link
+25	        return self.req.link.url_without_fragment
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/distributions/sdist.py
+ Line number: 59
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+58	            pyproject_requires = self.req.pyproject_requires
+59	            assert pyproject_requires is not None
+60	            conflicting, missing = self.req.build_env.check_requirements(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/distributions/sdist.py
+ Line number: 73
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+72	        pyproject_requires = self.req.pyproject_requires
+73	        assert pyproject_requires is not None
+74	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/distributions/sdist.py
+ Line number: 99
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+98	            backend = self.req.pep517_backend
+99	            assert backend is not None
+100	            with backend.subprocess_runner(runner):
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/distributions/sdist.py
+ Line number: 109
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+108	            backend = self.req.pep517_backend
+109	            assert backend is not None
+110	            with backend.subprocess_runner(runner):
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/distributions/wheel.py
+ Line number: 29
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+28	        """
+29	        assert self.req.local_file_path, "Set as part of preparation during download"
+30	        assert self.req.name, "Wheels are never unnamed"
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/distributions/wheel.py
+ Line number: 30
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+29	        assert self.req.local_file_path, "Set as part of preparation during download"
+30	        assert self.req.name, "Wheels are never unnamed"
+31	        wheel = FilesystemWheel(self.req.local_file_path)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/exceptions.py
+ Line number: 87
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+86	        if reference is None:
+87	            assert hasattr(self, "reference"), "error reference not provided!"
+88	            reference = self.reference
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/exceptions.py
+ Line number: 89
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+88	            reference = self.reference
+89	        assert _is_kebab_case(reference), "error reference must be kebab-case!"
+90	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/exceptions.py
+ Line number: 646
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+645	        else:
+646	            assert self.error is not None
+647	            message_part = f".\n{self.error}\n"
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/index/collector.py
+ Line number: 193
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+192	    def __init__(self, page: "IndexContent") -> None:
+193	        assert page.cache_link_parsing
+194	        self.page = page
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/index/package_finder.py
+ Line number: 364
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+363	        """
+364	        assert set(applicable_candidates) <= set(candidates)
+365	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/index/package_finder.py
+ Line number: 367
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+366	        if best_candidate is None:
+367	            assert not applicable_candidates
+368	        else:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/index/package_finder.py
+ Line number: 369
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+368	        else:
+369	            assert best_candidate in applicable_candidates
+370	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/index/package_finder.py
+ Line number: 543
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+542	                match = re.match(r"^(\d+)(.*)$", wheel.build_tag)
+543	                assert match is not None, "guaranteed by filename validation"
+544	                build_tag_groups = match.groups()
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/index/package_finder.py
+ Line number: 847
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+846	            for candidate in file_candidates:
+847	                assert candidate.link.url  # we need to have a URL
+848	                try:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/locations/_distutils.py
+ Line number: 66
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+65	    obj = d.get_command_obj("install", create=True)
+66	    assert obj is not None
+67	    i = cast(distutils_install_command, obj)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/locations/_distutils.py
+ Line number: 71
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+70	    # ideally, we'd prefer a scheme class that has no side-effects.
+71	    assert not (user and prefix), f"user={user} prefix={prefix}"
+72	    assert not (home and prefix), f"home={home} prefix={prefix}"
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/locations/_distutils.py
+ Line number: 72
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+71	    assert not (user and prefix), f"user={user} prefix={prefix}"
+72	    assert not (home and prefix), f"home={home} prefix={prefix}"
+73	    i.user = user or i.user
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/metadata/pkg_resources.py
+ Line number: 92
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+91	        else:
+92	            assert dist_dir.endswith(".dist-info")
+93	            dist_cls = pkg_resources.DistInfoDistribution
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/models/direct_url.py
+ Line number: 58
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+57	        )
+58	    assert infos[0] is not None
+59	    return infos[0]
+
+
+ + +
+
+ +
+
+ hardcoded_password_string: Possible hardcoded password: 'git'
+ Test ID: B105
+ Severity: LOW
+ Confidence: MEDIUM
+ CWE: CWE-259
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/models/direct_url.py
+ Line number: 182
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b105_hardcoded_password_string.html
+ +
+
+181	            and self.info.vcs == "git"
+182	            and user_pass == "git"
+183	        ):
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/models/installation_report.py
+ Line number: 15
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+14	    def _install_req_to_dict(cls, ireq: InstallRequirement) -> Dict[str, Any]:
+15	        assert ireq.download_info, f"No download_info for {ireq}"
+16	        res = {
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/models/link.py
+ Line number: 70
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+69	    def __post_init__(self) -> None:
+70	        assert self.name in _SUPPORTED_HASHES
+71	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/models/link.py
+ Line number: 106
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+105	        if self.hashes is not None:
+106	            assert all(name in _SUPPORTED_HASHES for name in self.hashes)
+107	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/models/link.py
+ Line number: 393
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+392	        name = urllib.parse.unquote(name)
+393	        assert name, f"URL {self._url!r} produced no filename"
+394	        return name
+
+
+ + +
+
+ +
+
+ blacklist: Consider possible security implications associated with the subprocess module.
+ Test ID: B404
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/network/auth.py
+ Line number: 9
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_imports.html#b404-import-subprocess
+ +
+
+8	import shutil
+9	import subprocess
+10	import sysconfig
+
+
+ + +
+
+ +
+
+ subprocess_without_shell_equals_true: subprocess call - check for execution of untrusted input.
+ Test ID: B603
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/network/auth.py
+ Line number: 136
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b603_subprocess_without_shell_equals_true.html
+ +
+
+135	        env["PYTHONIOENCODING"] = "utf-8"
+136	        res = subprocess.run(
+137	            cmd,
+138	            stdin=subprocess.DEVNULL,
+139	            stdout=subprocess.PIPE,
+140	            env=env,
+141	        )
+142	        if res.returncode:
+
+
+ + +
+
+ +
+
+ subprocess_without_shell_equals_true: subprocess call - check for execution of untrusted input.
+ Test ID: B603
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/network/auth.py
+ Line number: 152
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b603_subprocess_without_shell_equals_true.html
+ +
+
+151	        env["PYTHONIOENCODING"] = "utf-8"
+152	        subprocess.run(
+153	            [self.keyring, "set", service_name, username],
+154	            input=f"{password}{os.linesep}".encode("utf-8"),
+155	            env=env,
+156	            check=True,
+157	        )
+158	        return None
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/network/auth.py
+ Line number: 426
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+425	
+426	        assert (
+427	            # Credentials were found
+428	            (username is not None and password is not None)
+429	            # Credentials were not found
+430	            or (username is None and password is None)
+431	        ), f"Could not load credentials from url: {original_url}"
+432	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/network/auth.py
+ Line number: 548
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+547	        """Response callback to save credentials on success."""
+548	        assert (
+549	            self.keyring_provider.has_keyring
+550	        ), "should never reach here without keyring"
+551	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/network/cache.py
+ Line number: 51
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+50	    def __init__(self, directory: str) -> None:
+51	        assert directory is not None, "Cache directory must not be None."
+52	        super().__init__()
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/network/download.py
+ Line number: 136
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+135	        except NetworkConnectionError as e:
+136	            assert e.response is not None
+137	            logger.critical(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/network/download.py
+ Line number: 170
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+169	            except NetworkConnectionError as e:
+170	                assert e.response is not None
+171	                logger.critical(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/network/lazy_wheel.py
+ Line number: 54
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+53	        raise_for_status(head)
+54	        assert head.status_code == 200
+55	        self._session, self._url, self._chunk_size = session, url, chunk_size
+
+
+ + +
+
+ +
+
+ blacklist: Consider possible security implications associated with the subprocess module.
+ Test ID: B404
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/network/session.py
+ Line number: 14
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_imports.html#b404-import-subprocess
+ +
+
+13	import shutil
+14	import subprocess
+15	import sys
+
+
+ + +
+
+ +
+
+ start_process_with_partial_path: Starting a process with a partial executable path
+ Test ID: B607
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/network/session.py
+ Line number: 182
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b607_start_process_with_partial_path.html
+ +
+
+181	        try:
+182	            rustc_output = subprocess.check_output(
+183	                ["rustc", "--version"], stderr=subprocess.STDOUT, timeout=0.5
+184	            )
+185	        except Exception:
+
+
+ + +
+
+ +
+
+ subprocess_without_shell_equals_true: subprocess call - check for execution of untrusted input.
+ Test ID: B603
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/network/session.py
+ Line number: 182
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b603_subprocess_without_shell_equals_true.html
+ +
+
+181	        try:
+182	            rustc_output = subprocess.check_output(
+183	                ["rustc", "--version"], stderr=subprocess.STDOUT, timeout=0.5
+184	            )
+185	        except Exception:
+
+
+ + +
+
+ +
+
+ try_except_pass: Try, Except, Pass detected.
+ Test ID: B110
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/network/session.py
+ Line number: 185
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b110_try_except_pass.html
+ +
+
+184	            )
+185	        except Exception:
+186	            pass
+187	        else:
+
+
+ + +
+
+ +
+
+ blacklist: Using xmlrpc.client to parse untrusted XML data is known to be vulnerable to XML attacks. Use defusedxml.xmlrpc.monkey_patch() function to monkey-patch xmlrpclib and mitigate XML vulnerabilities.
+ Test ID: B411
+ Severity: HIGH
+ Confidence: HIGH
+ CWE: CWE-20
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/network/xmlrpc.py
+ Line number: 6
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_imports.html#b411-import-xmlrpclib
+ +
+
+5	import urllib.parse
+6	import xmlrpc.client
+7	from typing import TYPE_CHECKING, Tuple
+
+
+ + +
+
+ +
+
+ blacklist: Using _HostType to parse untrusted XML data is known to be vulnerable to XML attacks. Use defusedxml.xmlrpc.monkey_patch() function to monkey-patch xmlrpclib and mitigate XML vulnerabilities.
+ Test ID: B411
+ Severity: HIGH
+ Confidence: HIGH
+ CWE: CWE-20
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/network/xmlrpc.py
+ Line number: 14
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_imports.html#b411-import-xmlrpclib
+ +
+
+13	if TYPE_CHECKING:
+14	    from xmlrpc.client import _HostType, _Marshallable
+15	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/network/xmlrpc.py
+ Line number: 41
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+40	    ) -> Tuple["_Marshallable", ...]:
+41	        assert isinstance(host, str)
+42	        parts = (self._scheme, host, handler, None, None, None)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/network/xmlrpc.py
+ Line number: 56
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+55	        except NetworkConnectionError as exc:
+56	            assert exc.response
+57	            logger.critical(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/operations/build/build_tracker.py
+ Line number: 37
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+36	            else:
+37	                assert isinstance(original_value, str)  # for mypy
+38	                target[name] = original_value
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/operations/build/build_tracker.py
+ Line number: 106
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+105	        # If we're here, req should really not be building already.
+106	        assert key not in self._entries
+107	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/operations/build/wheel.py
+ Line number: 22
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+21	    """
+22	    assert metadata_directory is not None
+23	    try:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/operations/build/wheel_editable.py
+ Line number: 22
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+21	    """
+22	    assert metadata_directory is not None
+23	    try:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/operations/freeze.py
+ Line number: 160
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+159	    editable_project_location = dist.editable_project_location
+160	    assert editable_project_location
+161	    location = os.path.normcase(os.path.abspath(editable_project_location))
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/operations/install/wheel.py
+ Line number: 99
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+98	    # XXX RECORD hashes will need to be updated
+99	    assert os.path.isfile(path)
+100	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/operations/install/wheel.py
+ Line number: 614
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+613	                        pyc_path = pyc_output_path(path)
+614	                        assert os.path.exists(pyc_path)
+615	                        pyc_record_path = cast(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/operations/prepare.py
+ Line number: 79
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+78	    vcs_backend = vcs.get_backend_for_scheme(link.scheme)
+79	    assert vcs_backend is not None
+80	    vcs_backend.unpack(location, url=hide_url(link.url), verbosity=verbosity)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/operations/prepare.py
+ Line number: 160
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+159	
+160	    assert not link.is_existing_dir()
+161	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/operations/prepare.py
+ Line number: 310
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+309	            return
+310	        assert req.source_dir is None
+311	        if req.link.is_existing_dir():
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/operations/prepare.py
+ Line number: 384
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+383	            return None
+384	        assert req.req is not None
+385	        logger.verbose(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/operations/prepare.py
+ Line number: 460
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+459	        for req in partially_downloaded_reqs:
+460	            assert req.link
+461	            links_to_fully_download[req.link] = req
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/operations/prepare.py
+ Line number: 493
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+492	        """Prepare a requirement to be obtained from req.link."""
+493	        assert req.link
+494	        self._log_preparing_link(req)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/operations/prepare.py
+ Line number: 560
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+559	    ) -> BaseDistribution:
+560	        assert req.link
+561	        link = req.link
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/operations/prepare.py
+ Line number: 566
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+565	        if hashes and req.is_wheel_from_cache:
+566	            assert req.download_info is not None
+567	            assert link.is_wheel
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/operations/prepare.py
+ Line number: 567
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+566	            assert req.download_info is not None
+567	            assert link.is_wheel
+568	            assert link.is_file
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/operations/prepare.py
+ Line number: 568
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+567	            assert link.is_wheel
+568	            assert link.is_file
+569	            # We need to verify hashes, and we have found the requirement in the cache
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/operations/prepare.py
+ Line number: 619
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+618	            # prepare_editable_requirement).
+619	            assert not req.editable
+620	            req.download_info = direct_url_from_link(link, req.source_dir)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/operations/prepare.py
+ Line number: 650
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+649	    def save_linked_requirement(self, req: InstallRequirement) -> None:
+650	        assert self.download_dir is not None
+651	        assert req.link is not None
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/operations/prepare.py
+ Line number: 651
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+650	        assert self.download_dir is not None
+651	        assert req.link is not None
+652	        link = req.link
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/operations/prepare.py
+ Line number: 680
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+679	        """Prepare an editable requirement."""
+680	        assert req.editable, "cannot prepare a non-editable req as editable"
+681	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/operations/prepare.py
+ Line number: 693
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+692	            req.update_editable()
+693	            assert req.source_dir
+694	            req.download_info = direct_url_for_editable(req.unpacked_source_directory)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/operations/prepare.py
+ Line number: 714
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+713	        """Prepare an already-installed requirement."""
+714	        assert req.satisfied_by, "req should have been satisfied but isn't"
+715	        assert skip_reason is not None, (
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/operations/prepare.py
+ Line number: 715
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+714	        assert req.satisfied_by, "req should have been satisfied but isn't"
+715	        assert skip_reason is not None, (
+716	            "did not get skip reason skipped but req.satisfied_by "
+717	            f"is set to {req.satisfied_by}"
+718	        )
+719	        logger.info(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/pyproject.py
+ Line number: 109
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+108	    # At this point, we know whether we're going to use PEP 517.
+109	    assert use_pep517 is not None
+110	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/pyproject.py
+ Line number: 134
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+133	    # specified a backend, though.
+134	    assert build_system is not None
+135	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/req/__init__.py
+ Line number: 33
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+32	    for req in requirements:
+33	        assert req.name, f"invalid to-be-installed requirement: {req}"
+34	        yield req.name, req
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/req/constructors.py
+ Line number: 74
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+73	    # ireq.req is a valid requirement so the regex should always match
+74	    assert (
+75	        match is not None
+76	    ), f"regex match on requirement {req} failed, this should never happen"
+77	    pre: Optional[str] = match.group(1)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/req/constructors.py
+ Line number: 79
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+78	    post: Optional[str] = match.group(3)
+79	    assert (
+80	        pre is not None and post is not None
+81	    ), f"regex group selection for requirement {req} failed, this should never happen"
+82	    extras: str = "[%s]" % ",".join(sorted(new_extras)) if new_extras else ""
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/req/req_file.py
+ Line number: 187
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+186	
+187	    assert line.is_requirement
+188	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/req/req_file.py
+ Line number: 476
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+475	                new_line.append(line)
+476	                assert primary_line_number is not None
+477	                yield primary_line_number, "".join(new_line)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/req/req_file.py
+ Line number: 488
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+487	    if new_line:
+488	        assert primary_line_number is not None
+489	        yield primary_line_number, "".join(new_line)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/req/req_install.py
+ Line number: 90
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+89	    ) -> None:
+90	        assert req is None or isinstance(req, Requirement), req
+91	        self.req = req
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/req/req_install.py
+ Line number: 104
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+103	        if self.editable:
+104	            assert link
+105	            if link.is_file:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/req/req_install.py
+ Line number: 251
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+250	            return False
+251	        assert self.pep517_backend
+252	        with self.build_env:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/req/req_install.py
+ Line number: 261
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+260	    def specifier(self) -> SpecifierSet:
+261	        assert self.req is not None
+262	        return self.req.specifier
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/req/req_install.py
+ Line number: 275
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+274	        """
+275	        assert self.req is not None
+276	        specifiers = self.req.specifier
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/req/req_install.py
+ Line number: 329
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+328	        if link and link.hash:
+329	            assert link.hash_name is not None
+330	            good_hashes.setdefault(link.hash_name, []).append(link.hash)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/req/req_install.py
+ Line number: 351
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+350	    ) -> str:
+351	        assert build_dir is not None
+352	        if self._temp_build_dir is not None:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/req/req_install.py
+ Line number: 353
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+352	        if self._temp_build_dir is not None:
+353	            assert self._temp_build_dir.path
+354	            return self._temp_build_dir.path
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/req/req_install.py
+ Line number: 393
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+392	        """Set requirement after generating metadata."""
+393	        assert self.req is None
+394	        assert self.metadata is not None
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/req/req_install.py
+ Line number: 394
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+393	        assert self.req is None
+394	        assert self.metadata is not None
+395	        assert self.source_dir is not None
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/req/req_install.py
+ Line number: 395
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+394	        assert self.metadata is not None
+395	        assert self.source_dir is not None
+396	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/req/req_install.py
+ Line number: 414
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+413	    def warn_on_mismatching_name(self) -> None:
+414	        assert self.req is not None
+415	        metadata_name = canonicalize_name(self.metadata["Name"])
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/req/req_install.py
+ Line number: 484
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+483	    def unpacked_source_directory(self) -> str:
+484	        assert self.source_dir, f"No source dir for {self}"
+485	        return os.path.join(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/req/req_install.py
+ Line number: 491
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+490	    def setup_py_path(self) -> str:
+491	        assert self.source_dir, f"No source dir for {self}"
+492	        setup_py = os.path.join(self.unpacked_source_directory, "setup.py")
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/req/req_install.py
+ Line number: 498
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+497	    def setup_cfg_path(self) -> str:
+498	        assert self.source_dir, f"No source dir for {self}"
+499	        setup_cfg = os.path.join(self.unpacked_source_directory, "setup.cfg")
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/req/req_install.py
+ Line number: 505
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+504	    def pyproject_toml_path(self) -> str:
+505	        assert self.source_dir, f"No source dir for {self}"
+506	        return make_pyproject_path(self.unpacked_source_directory)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/req/req_install.py
+ Line number: 521
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+520	        if pyproject_toml_data is None:
+521	            assert not self.config_settings
+522	            self.use_pep517 = False
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/req/req_install.py
+ Line number: 563
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+562	        """
+563	        assert self.source_dir, f"No source dir for {self}"
+564	        details = self.name or f"from {self.link}"
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/req/req_install.py
+ Line number: 567
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+566	        if self.use_pep517:
+567	            assert self.pep517_backend is not None
+568	            if (
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/req/req_install.py
+ Line number: 612
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+611	        elif self.local_file_path and self.is_wheel:
+612	            assert self.req is not None
+613	            return get_wheel_distribution(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/req/req_install.py
+ Line number: 623
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+622	    def assert_source_matches_version(self) -> None:
+623	        assert self.source_dir, f"No source dir for {self}"
+624	        version = self.metadata["version"]
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/req/req_install.py
+ Line number: 663
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+662	    def needs_unpacked_archive(self, archive_source: Path) -> None:
+663	        assert self._archive_source is None
+664	        self._archive_source = archive_source
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/req/req_install.py
+ Line number: 668
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+667	        """Ensure the source directory has not yet been built in."""
+668	        assert self.source_dir is not None
+669	        if self._archive_source is not None:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/req/req_install.py
+ Line number: 691
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+690	            return
+691	        assert self.editable
+692	        assert self.source_dir
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/req/req_install.py
+ Line number: 692
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+691	        assert self.editable
+692	        assert self.source_dir
+693	        if self.link.scheme == "file":
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/req/req_install.py
+ Line number: 699
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+698	        # So here, if it's neither a path nor a valid VCS URL, it's a bug.
+699	        assert vcs_backend, f"Unsupported VCS URL {self.link.url}"
+700	        hidden_url = hide_url(self.link.url)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/req/req_install.py
+ Line number: 719
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+718	        """
+719	        assert self.req
+720	        dist = get_default_environment().get_distribution(self.req.name)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/req/req_install.py
+ Line number: 732
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+731	        def _clean_zip_name(name: str, prefix: str) -> str:
+732	            assert name.startswith(
+733	                prefix + os.path.sep
+734	            ), f"name {name!r} doesn't start with prefix {prefix!r}"
+735	            name = name[len(prefix) + 1 :]
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/req/req_install.py
+ Line number: 739
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+738	
+739	        assert self.req is not None
+740	        path = os.path.join(parentdir, path)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/req/req_install.py
+ Line number: 749
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+748	        """
+749	        assert self.source_dir
+750	        if build_dir is None:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/req/req_install.py
+ Line number: 821
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+820	    ) -> None:
+821	        assert self.req is not None
+822	        scheme = get_scheme(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/req/req_install.py
+ Line number: 853
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+852	
+853	        assert self.is_wheel
+854	        assert self.local_file_path
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/req/req_install.py
+ Line number: 854
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+853	        assert self.is_wheel
+854	        assert self.local_file_path
+855	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/req/req_set.py
+ Line number: 45
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+44	    def add_unnamed_requirement(self, install_req: InstallRequirement) -> None:
+45	        assert not install_req.name
+46	        self.unnamed_requirements.append(install_req)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/req/req_set.py
+ Line number: 49
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+48	    def add_named_requirement(self, install_req: InstallRequirement) -> None:
+49	        assert install_req.name
+50	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/req/req_uninstall.py
+ Line number: 70
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+69	    location = dist.location
+70	    assert location is not None, "not installed"
+71	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/req/req_uninstall.py
+ Line number: 544
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+543	                )
+544	            assert os.path.samefile(
+545	                normalized_link_pointer, normalized_dist_location
+546	            ), (
+547	                f"Egg-link {develop_egg_link} (to {link_pointer}) does not match "
+548	                f"installed location of {dist.raw_name} (at {dist_location})"
+549	            )
+550	            paths_to_remove.add(develop_egg_link)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/resolution/legacy/resolver.py
+ Line number: 135
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+134	        super().__init__()
+135	        assert upgrade_strategy in self._allowed_strategies
+136	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/resolution/legacy/resolver.py
+ Line number: 238
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+237	        # This next bit is really a sanity check.
+238	        assert (
+239	            not install_req.user_supplied or parent_req_name is None
+240	        ), "a user supplied req shouldn't have a parent"
+241	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/resolution/legacy/resolver.py
+ Line number: 317
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+316	        else:
+317	            assert self.upgrade_strategy == "only-if-needed"
+318	            return req.user_supplied or req.constraint
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/resolution/legacy/resolver.py
+ Line number: 452
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+451	        # so it must be None here.
+452	        assert req.satisfied_by is None
+453	        skip_reason = self._check_skip_installed(req)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/resolution/legacy/resolver.py
+ Line number: 541
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+540	                # provided by the user.
+541	                assert req_to_install.user_supplied
+542	                self._add_requirement_to_set(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/resolution/resolvelib/candidates.py
+ Line number: 56
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+55	) -> InstallRequirement:
+56	    assert not template.editable, "template is editable"
+57	    if template.req:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/resolution/resolvelib/candidates.py
+ Line number: 81
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+80	) -> InstallRequirement:
+81	    assert template.editable, "template not editable"
+82	    ireq = install_req_from_editable(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/resolution/resolvelib/candidates.py
+ Line number: 264
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+263	        ireq = make_install_req_from_link(link, template)
+264	        assert ireq.link == link
+265	        if ireq.link.is_wheel and not ireq.link.is_file:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/resolution/resolvelib/candidates.py
+ Line number: 268
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+267	            wheel_name = canonicalize_name(wheel.name)
+268	            assert name == wheel_name, f"{name!r} != {wheel_name!r} for wheel"
+269	            # Version may not be present for PEP 508 direct URLs
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/resolution/resolvelib/candidates.py
+ Line number: 272
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+271	                wheel_version = Version(wheel.version)
+272	                assert version == wheel_version, "{!r} != {!r} for wheel {}".format(
+273	                    version, wheel_version, name
+274	                )
+275	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/resolution/resolvelib/candidates.py
+ Line number: 277
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+276	        if cache_entry is not None:
+277	            assert ireq.link.is_wheel
+278	            assert ireq.link.is_file
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/resolution/resolvelib/candidates.py
+ Line number: 278
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+277	            assert ireq.link.is_wheel
+278	            assert ireq.link.is_file
+279	            if cache_entry.persistent and template.link is template.original_link:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/resolution/resolvelib/factory.py
+ Line number: 262
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+261	        template = ireqs[0]
+262	        assert template.req, "Candidates found on index must be PEP 508"
+263	        name = canonicalize_name(template.req.name)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/resolution/resolvelib/factory.py
+ Line number: 267
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+266	        for ireq in ireqs:
+267	            assert ireq.req, "Candidates found on index must be PEP 508"
+268	            specifier &= ireq.req.specifier
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/resolution/resolvelib/factory.py
+ Line number: 362
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+361	            base_cand = as_base_candidate(lookup_cand)
+362	            assert base_cand is not None, "no extras here"
+363	            yield self._make_extras_candidate(base_cand, extras)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/resolution/resolvelib/factory.py
+ Line number: 527
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+526	                    continue
+527	                assert ireq.name, "Constraint must be named"
+528	                name = canonicalize_name(ireq.name)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/resolution/resolvelib/factory.py
+ Line number: 641
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+640	    ) -> UnsupportedPythonVersion:
+641	        assert causes, "Requires-Python error reported with no cause"
+642	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/resolution/resolvelib/factory.py
+ Line number: 717
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+716	    ) -> InstallationError:
+717	        assert e.causes, "Installation error reported with no cause"
+718	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/resolution/resolvelib/requirements.py
+ Line number: 42
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+41	    def __init__(self, ireq: InstallRequirement) -> None:
+42	        assert ireq.link is None, "This is a link, not a specifier"
+43	        self._ireq = ireq
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/resolution/resolvelib/requirements.py
+ Line number: 54
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+53	    def project_name(self) -> NormalizedName:
+54	        assert self._ireq.req, "Specifier-backed ireq is always PEP 508"
+55	        return canonicalize_name(self._ireq.req.name)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/resolution/resolvelib/requirements.py
+ Line number: 78
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+77	    def is_satisfied_by(self, candidate: Candidate) -> bool:
+78	        assert candidate.name == self.name, (
+79	            f"Internal issue: Candidate is not for this requirement "
+80	            f"{candidate.name} vs {self.name}"
+81	        )
+82	        # We can safely always allow prereleases here since PackageFinder
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/resolution/resolvelib/requirements.py
+ Line number: 85
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+84	        # prerelease candidates if the user does not expect them.
+85	        assert self._ireq.req, "Specifier-backed ireq is always PEP 508"
+86	        spec = self._ireq.req.specifier
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/resolution/resolvelib/requirements.py
+ Line number: 97
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+96	    def __init__(self, ireq: InstallRequirement) -> None:
+97	        assert ireq.link is None, "This is a link, not a specifier"
+98	        self._ireq = install_req_drop_extras(ireq)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/resolution/resolvelib/requirements.py
+ Line number: 132
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+131	    def is_satisfied_by(self, candidate: Candidate) -> bool:
+132	        assert candidate.name == self._candidate.name, "Not Python candidate"
+133	        # We can safely always allow prereleases here since PackageFinder
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/resolution/resolvelib/resolver.py
+ Line number: 56
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+55	        super().__init__()
+56	        assert upgrade_strategy in self._allowed_strategies
+57	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/resolution/resolvelib/resolver.py
+ Line number: 200
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+199	        """
+200	        assert self._result is not None, "must call resolve() first"
+201	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/resolution/resolvelib/resolver.py
+ Line number: 301
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+300	    difference = set(weights.keys()).difference(requirement_keys)
+301	    assert not difference, difference
+302	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/utils/direct_url_helpers.py
+ Line number: 23
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+22	    else:
+23	        assert isinstance(direct_url.info, DirInfo)
+24	        requirement += direct_url.url
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/utils/direct_url_helpers.py
+ Line number: 44
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+43	        vcs_backend = vcs.get_backend_for_scheme(link.scheme)
+44	        assert vcs_backend
+45	        url, requested_revision, _ = vcs_backend.get_url_rev_and_auth(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/utils/direct_url_helpers.py
+ Line number: 55
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+54	            # with the VCS checkout.
+55	            assert requested_revision
+56	            commit_id = requested_revision
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/utils/direct_url_helpers.py
+ Line number: 61
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+60	            # which we can inspect to find out the commit id.
+61	            assert source_dir
+62	            commit_id = vcs_backend.get_revision(source_dir)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/utils/encoding.py
+ Line number: 31
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+30	            result = ENCODING_RE.search(line)
+31	            assert result is not None
+32	            encoding = result.groups()[0].decode("ascii")
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/utils/filesystem.py
+ Line number: 22
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+21	
+22	    assert os.path.isabs(path)
+23	
+
+
+ + +
+
+ +
+
+ blacklist: Standard pseudo-random generators are not suitable for security/cryptographic purposes.
+ Test ID: B311
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-330
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/utils/filesystem.py
+ Line number: 100
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b311-random
+ +
+
+99	    for _ in range(10):
+100	        name = basename + "".join(random.choice(alphabet) for _ in range(6))
+101	        file = os.path.join(path, name)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/utils/logging.py
+ Line number: 157
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+156	        # If we are given a diagnostic error to present, present it with indentation.
+157	        assert isinstance(record.args, tuple)
+158	        if getattr(record, "rich", False):
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/utils/logging.py
+ Line number: 160
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+159	            (rich_renderable,) = record.args
+160	            assert isinstance(
+161	                rich_renderable, (ConsoleRenderable, RichCast, str)
+162	            ), f"{rich_renderable} is not rich-console-renderable"
+163	
+
+
+ + +
+
+ +
+
+ hardcoded_password_string: Possible hardcoded password: ''
+ Test ID: B105
+ Severity: LOW
+ Confidence: MEDIUM
+ CWE: CWE-259
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/utils/misc.py
+ Line number: 517
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b105_hardcoded_password_string.html
+ +
+
+516	        user = "****"
+517	        password = ""
+518	    else:
+
+
+ + +
+
+ +
+
+ hardcoded_password_string: Possible hardcoded password: ':****'
+ Test ID: B105
+ Severity: LOW
+ Confidence: MEDIUM
+ CWE: CWE-259
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/utils/misc.py
+ Line number: 520
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b105_hardcoded_password_string.html
+ +
+
+519	        user = urllib.parse.quote(user)
+520	        password = ":****"
+521	    return f"{user}{password}@{netloc}"
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/utils/setuptools_build.py
+ Line number: 113
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+112	) -> List[str]:
+113	    assert not (use_user_site and prefix)
+114	
+
+
+ + +
+
+ +
+
+ blacklist: Consider possible security implications associated with the subprocess module.
+ Test ID: B404
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/utils/subprocess.py
+ Line number: 4
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_imports.html#b404-import-subprocess
+ +
+
+3	import shlex
+4	import subprocess
+5	from typing import (
+
+
+ + +
+
+ +
+
+ subprocess_without_shell_equals_true: subprocess call - check for execution of untrusted input.
+ Test ID: B603
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/utils/subprocess.py
+ Line number: 141
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b603_subprocess_without_shell_equals_true.html
+ +
+
+140	    try:
+141	        proc = subprocess.Popen(
+142	            # Convert HiddenText objects to the underlying str.
+143	            reveal_command_args(cmd),
+144	            stdin=subprocess.PIPE,
+145	            stdout=subprocess.PIPE,
+146	            stderr=subprocess.STDOUT if not stdout_only else subprocess.PIPE,
+147	            cwd=cwd,
+148	            env=env,
+149	            errors="backslashreplace",
+150	        )
+151	    except Exception as exc:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/utils/subprocess.py
+ Line number: 161
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+160	    if not stdout_only:
+161	        assert proc.stdout
+162	        assert proc.stdin
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/utils/subprocess.py
+ Line number: 162
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+161	        assert proc.stdout
+162	        assert proc.stdin
+163	        proc.stdin.close()
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/utils/subprocess.py
+ Line number: 176
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+175	            if use_spinner:
+176	                assert spinner
+177	                spinner.spin()
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/utils/subprocess.py
+ Line number: 199
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+198	    if use_spinner:
+199	        assert spinner
+200	        if proc_had_error:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/utils/temp_dir.py
+ Line number: 146
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+145	        if globally_managed:
+146	            assert _tempdir_manager is not None
+147	            _tempdir_manager.enter_context(self)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/utils/temp_dir.py
+ Line number: 151
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+150	    def path(self) -> str:
+151	        assert not self._deleted, f"Attempted to access deleted path: {self._path}"
+152	        return self._path
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/utils/unpacking.py
+ Line number: 216
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+215	                ensure_dir(os.path.dirname(path))
+216	                assert fp is not None
+217	                with open(path, "wb") as destfp:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/utils/urls.py
+ Line number: 30
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+29	    """
+30	    assert url.startswith(
+31	        "file:"
+32	    ), f"You can only turn file: urls into filenames (not {url!r})"
+33	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/vcs/git.py
+ Line number: 214
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+213	        # rev return value is always non-None.
+214	        assert rev is not None
+215	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/vcs/git.py
+ Line number: 477
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+476	        if "://" not in url:
+477	            assert "file:" not in url
+478	            url = url.replace("git+", "git+ssh://")
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/vcs/subversion.py
+ Line number: 65
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+64	            if base == location:
+65	                assert dirurl is not None
+66	                base = dirurl + "/"  # save the root url
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/vcs/subversion.py
+ Line number: 169
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+168	                match = _svn_info_xml_url_re.search(xml)
+169	                assert match is not None
+170	                url = match.group(1)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/wheel_builder.py
+ Line number: 105
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+104	        # unless it points to an immutable commit hash.
+105	        assert not req.editable
+106	        assert req.source_dir
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/wheel_builder.py
+ Line number: 106
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+105	        assert not req.editable
+106	        assert req.source_dir
+107	        vcs_backend = vcs.get_backend_for_scheme(req.link.scheme)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/wheel_builder.py
+ Line number: 108
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+107	        vcs_backend = vcs.get_backend_for_scheme(req.link.scheme)
+108	        assert vcs_backend
+109	        if vcs_backend.is_immutable_rev_checkout(req.link.url, req.source_dir):
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/wheel_builder.py
+ Line number: 113
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+112	
+113	    assert req.link
+114	    base, ext = req.link.splitext()
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/wheel_builder.py
+ Line number: 130
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+129	    cache_available = bool(wheel_cache.cache_dir)
+130	    assert req.link
+131	    if cache_available and _should_cache(req):
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/wheel_builder.py
+ Line number: 213
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+212	    with TempDirectory(kind="wheel") as temp_dir:
+213	        assert req.name
+214	        if req.use_pep517:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/wheel_builder.py
+ Line number: 215
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+214	        if req.use_pep517:
+215	            assert req.metadata_directory
+216	            assert req.pep517_backend
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/wheel_builder.py
+ Line number: 216
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+215	            assert req.metadata_directory
+216	            assert req.pep517_backend
+217	            if global_options:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/wheel_builder.py
+ Line number: 317
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+316	        for req in requirements:
+317	            assert req.name
+318	            cache_dir = _get_cache_dir(req, wheel_cache)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_internal/wheel_builder.py
+ Line number: 337
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+336	                req.local_file_path = req.link.file_path
+337	                assert req.link.is_wheel
+338	                build_successes.append(req)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/cachecontrol/adapter.py
+ Line number: 150
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+149	        if request.method in self.invalidating_methods and resp.ok:
+150	            assert request.url is not None
+151	            cache_url = self.controller.cache_url(request.url)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/cachecontrol/controller.py
+ Line number: 43
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+42	    match = URI.match(uri)
+43	    assert match is not None
+44	    groups = match.groups()
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/cachecontrol/controller.py
+ Line number: 146
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+145	        cache_url = request.url
+146	        assert cache_url is not None
+147	        cache_data = self.cache.get(cache_url)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/cachecontrol/controller.py
+ Line number: 167
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+166	        """
+167	        assert request.url is not None
+168	        cache_url = self.cache_url(request.url)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/cachecontrol/controller.py
+ Line number: 215
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+214	        time_tuple = parsedate_tz(headers["date"])
+215	        assert time_tuple is not None
+216	        date = calendar.timegm(time_tuple[:6])
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/cachecontrol/controller.py
+ Line number: 344
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+343	            time_tuple = parsedate_tz(response_headers["date"])
+344	            assert time_tuple is not None
+345	            date = calendar.timegm(time_tuple[:6])
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/cachecontrol/controller.py
+ Line number: 364
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+363	
+364	        assert request.url is not None
+365	        cache_url = self.cache_url(request.url)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/cachecontrol/controller.py
+ Line number: 416
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+415	            time_tuple = parsedate_tz(response_headers["date"])
+416	            assert time_tuple is not None
+417	            date = calendar.timegm(time_tuple[:6])
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/cachecontrol/controller.py
+ Line number: 463
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+462	        """
+463	        assert request.url is not None
+464	        cache_url = self.cache_url(request.url)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/cachecontrol/heuristics.py
+ Line number: 137
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+136	        time_tuple = parsedate_tz(headers["date"])
+137	        assert time_tuple is not None
+138	        date = calendar.timegm(time_tuple[:6])
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/chardet/eucjpprober.py
+ Line number: 59
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+58	    def feed(self, byte_str: Union[bytes, bytearray]) -> ProbingState:
+59	        assert self.coding_sm is not None
+60	        assert self.distribution_analyzer is not None
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/chardet/eucjpprober.py
+ Line number: 60
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+59	        assert self.coding_sm is not None
+60	        assert self.distribution_analyzer is not None
+61	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/chardet/eucjpprober.py
+ Line number: 98
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+97	    def get_confidence(self) -> float:
+98	        assert self.distribution_analyzer is not None
+99	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/chardet/hebrewprober.py
+ Line number: 273
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+272	    def charset_name(self) -> str:
+273	        assert self._logical_prober is not None
+274	        assert self._visual_prober is not None
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/chardet/hebrewprober.py
+ Line number: 274
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+273	        assert self._logical_prober is not None
+274	        assert self._visual_prober is not None
+275	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/chardet/hebrewprober.py
+ Line number: 308
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+307	    def state(self) -> ProbingState:
+308	        assert self._logical_prober is not None
+309	        assert self._visual_prober is not None
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/chardet/hebrewprober.py
+ Line number: 309
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+308	        assert self._logical_prober is not None
+309	        assert self._visual_prober is not None
+310	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/chardet/mbcharsetprober.py
+ Line number: 58
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+57	    def feed(self, byte_str: Union[bytes, bytearray]) -> ProbingState:
+58	        assert self.coding_sm is not None
+59	        assert self.distribution_analyzer is not None
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/chardet/mbcharsetprober.py
+ Line number: 59
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+58	        assert self.coding_sm is not None
+59	        assert self.distribution_analyzer is not None
+60	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/chardet/mbcharsetprober.py
+ Line number: 94
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+93	    def get_confidence(self) -> float:
+94	        assert self.distribution_analyzer is not None
+95	        return self.distribution_analyzer.get_confidence()
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/chardet/sjisprober.py
+ Line number: 59
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+58	    def feed(self, byte_str: Union[bytes, bytearray]) -> ProbingState:
+59	        assert self.coding_sm is not None
+60	        assert self.distribution_analyzer is not None
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/chardet/sjisprober.py
+ Line number: 60
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+59	        assert self.coding_sm is not None
+60	        assert self.distribution_analyzer is not None
+61	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/chardet/sjisprober.py
+ Line number: 101
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+100	    def get_confidence(self) -> float:
+101	        assert self.distribution_analyzer is not None
+102	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/chardet/universaldetector.py
+ Line number: 319
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+318	                charset_name = max_prober.charset_name
+319	                assert charset_name is not None
+320	                lower_charset_name = charset_name.lower()
+
+
+ + +
+
+ +
+
+ blacklist: Using xmlrpclib to parse untrusted XML data is known to be vulnerable to XML attacks. Use defusedxml.xmlrpc.monkey_patch() function to monkey-patch xmlrpclib and mitigate XML vulnerabilities.
+ Test ID: B411
+ Severity: HIGH
+ Confidence: HIGH
+ CWE: CWE-20
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/distlib/compat.py
+ Line number: 42
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_imports.html#b411-import-xmlrpclib
+ +
+
+41	    import httplib
+42	    import xmlrpclib
+43	    import Queue as queue
+
+
+ + +
+
+ +
+
+ blacklist: Using xmlrpc.client to parse untrusted XML data is known to be vulnerable to XML attacks. Use defusedxml.xmlrpc.monkey_patch() function to monkey-patch xmlrpclib and mitigate XML vulnerabilities.
+ Test ID: B411
+ Severity: HIGH
+ Confidence: HIGH
+ CWE: CWE-20
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/distlib/compat.py
+ Line number: 81
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_imports.html#b411-import-xmlrpclib
+ +
+
+80	    import urllib.request as urllib2
+81	    import xmlrpc.client as xmlrpclib
+82	    import queue
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/distlib/compat.py
+ Line number: 634
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+633	    def cache_from_source(path, debug_override=None):
+634	        assert path.endswith('.py')
+635	        if debug_override is None:
+
+
+ + +
+
+ +
+
+ hashlib: Use of weak MD5 hash for security. Consider usedforsecurity=False
+ Test ID: B324
+ Severity: HIGH
+ Confidence: HIGH
+ CWE: CWE-327
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/distlib/database.py
+ Line number: 1032
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b324_hashlib.html
+ +
+
+1031	                f.close()
+1032	            return hashlib.md5(content).hexdigest()
+1033	
+
+
+ + +
+
+ +
+
+ blacklist: Consider possible security implications associated with the subprocess module.
+ Test ID: B404
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/distlib/index.py
+ Line number: 11
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_imports.html#b404-import-subprocess
+ +
+
+10	import shutil
+11	import subprocess
+12	import tempfile
+
+
+ + +
+
+ +
+
+ subprocess_without_shell_equals_true: subprocess call - check for execution of untrusted input.
+ Test ID: B603
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/distlib/index.py
+ Line number: 58
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b603_subprocess_without_shell_equals_true.html
+ +
+
+57	                try:
+58	                    rc = subprocess.check_call([s, '--version'], stdout=sink,
+59	                                               stderr=sink)
+60	                    if rc == 0:
+
+
+ + +
+
+ +
+
+ subprocess_without_shell_equals_true: subprocess call - check for execution of untrusted input.
+ Test ID: B603
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/distlib/index.py
+ Line number: 193
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b603_subprocess_without_shell_equals_true.html
+ +
+
+192	        stderr = []
+193	        p = subprocess.Popen(cmd, **kwargs)
+194	        # We don't use communicate() here because we may need to
+
+
+ + +
+
+ +
+
+ hashlib: Use of weak MD5 hash for security. Consider usedforsecurity=False
+ Test ID: B324
+ Severity: HIGH
+ Confidence: HIGH
+ CWE: CWE-327
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/distlib/index.py
+ Line number: 269
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b324_hashlib.html
+ +
+
+268	            file_data = f.read()
+269	        md5_digest = hashlib.md5(file_data).hexdigest()
+270	        sha256_digest = hashlib.sha256(file_data).hexdigest()
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/distlib/locators.py
+ Line number: 953
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+952	        super(DistPathLocator, self).__init__(**kwargs)
+953	        assert isinstance(distpath, DistributionPath)
+954	        self.distpath = distpath
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/distlib/manifest.py
+ Line number: 115
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+114	                parent, _ = os.path.split(d)
+115	                assert parent not in ('', '/')
+116	                add_dir(dirs, parent)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/distlib/manifest.py
+ Line number: 330
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+329	            if _PYTHON_VERSION > (3, 2):
+330	                assert pattern_re.startswith(start) and pattern_re.endswith(end)
+331	        else:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/distlib/manifest.py
+ Line number: 342
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+341	                prefix_re = self._glob_to_re(prefix)
+342	                assert prefix_re.startswith(start) and prefix_re.endswith(end)
+343	                prefix_re = prefix_re[len(start): len(prefix_re) - len(end)]
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/distlib/markers.py
+ Line number: 78
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+77	        else:
+78	            assert isinstance(expr, dict)
+79	            op = expr['op']
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/distlib/metadata.py
+ Line number: 930
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+929	    def _from_legacy(self):
+930	        assert self._legacy and not self._data
+931	        result = {
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/distlib/metadata.py
+ Line number: 993
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+992	
+993	        assert self._data and not self._legacy
+994	        result = LegacyMetadata()
+
+
+ + +
+
+ +
+
+ try_except_pass: Try, Except, Pass detected.
+ Test ID: B110
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/distlib/scripts.py
+ Line number: 297
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b110_try_except_pass.html
+ +
+
+296	                        os.remove(dfname)
+297	                    except Exception:
+298	                        pass  # still in use - ignore error
+299	            else:
+
+
+ + +
+
+ +
+
+ blacklist: Consider possible security implications associated with the subprocess module.
+ Test ID: B404
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/distlib/util.py
+ Line number: 21
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_imports.html#b404-import-subprocess
+ +
+
+20	    ssl = None
+21	import subprocess
+22	import sys
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/distlib/util.py
+ Line number: 287
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+286	        path = path.replace(os.path.sep, '/')
+287	        assert path.startswith(root)
+288	        return path[len(root):].lstrip('/')
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/distlib/util.py
+ Line number: 374
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+373	                entry = get_export_entry(s)
+374	                assert entry is not None
+375	                entries[k] = entry
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/distlib/util.py
+ Line number: 401
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+400	            entry = get_export_entry(s)
+401	            assert entry is not None
+402	            # entry.dist = self
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/distlib/util.py
+ Line number: 552
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+551	    def copy_stream(self, instream, outfile, encoding=None):
+552	        assert not os.path.isdir(outfile)
+553	        self.ensure_dir(os.path.dirname(outfile))
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/distlib/util.py
+ Line number: 617
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+616	                else:
+617	                    assert path.startswith(prefix)
+618	                    diagpath = path[len(prefix):]
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/distlib/util.py
+ Line number: 667
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+666	        """
+667	        assert self.record
+668	        result = self.files_written, self.dirs_created
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/distlib/util.py
+ Line number: 684
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+683	                if flist:
+684	                    assert flist == ['__pycache__']
+685	                    sd = os.path.join(d, flist[0])
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/distlib/util.py
+ Line number: 864
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+863	            break
+864	    assert i is not None
+865	    return result
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/distlib/util.py
+ Line number: 1130
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1129	    def add(self, pred, succ):
+1130	        assert pred != succ
+1131	        self._preds.setdefault(succ, set()).add(pred)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/distlib/util.py
+ Line number: 1135
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1134	    def remove(self, pred, succ):
+1135	        assert pred != succ
+1136	        try:
+
+
+ + +
+
+ +
+
+ tarfile_unsafe_members: tarfile.extractall used without any validation. Please check and discard dangerous members.
+ Test ID: B202
+ Severity: HIGH
+ Confidence: HIGH
+ CWE: CWE-22
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/distlib/util.py
+ Line number: 1310
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b202_tarfile_unsafe_members.html
+ +
+
+1309	
+1310	        archive.extractall(dest_dir)
+1311	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/distlib/util.py
+ Line number: 1342
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1341	    def __init__(self, minval=0, maxval=100):
+1342	        assert maxval is None or maxval >= minval
+1343	        self.min = self.cur = minval
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/distlib/util.py
+ Line number: 1350
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1349	    def update(self, curval):
+1350	        assert self.min <= curval
+1351	        assert self.max is None or curval <= self.max
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/distlib/util.py
+ Line number: 1351
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1350	        assert self.min <= curval
+1351	        assert self.max is None or curval <= self.max
+1352	        self.cur = curval
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/distlib/util.py
+ Line number: 1360
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1359	    def increment(self, incr):
+1360	        assert incr >= 0
+1361	        self.update(self.cur + incr)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/distlib/util.py
+ Line number: 1451
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1450	    if len(rich_path_glob) > 1:
+1451	        assert len(rich_path_glob) == 3, rich_path_glob
+1452	        prefix, set, suffix = rich_path_glob
+
+
+ + +
+
+ +
+
+ subprocess_without_shell_equals_true: subprocess call - check for execution of untrusted input.
+ Test ID: B603
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/distlib/util.py
+ Line number: 1792
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b603_subprocess_without_shell_equals_true.html
+ +
+
+1791	    def run_command(self, cmd, **kwargs):
+1792	        p = subprocess.Popen(cmd,
+1793	                             stdout=subprocess.PIPE,
+1794	                             stderr=subprocess.PIPE,
+1795	                             **kwargs)
+1796	        t1 = threading.Thread(target=self.reader, args=(p.stdout, 'stdout'))
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/distlib/version.py
+ Line number: 34
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+33	        self._parts = parts = self.parse(s)
+34	        assert isinstance(parts, tuple)
+35	        assert len(parts) > 0
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/distlib/version.py
+ Line number: 35
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+34	        assert isinstance(parts, tuple)
+35	        assert len(parts) > 0
+36	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/distlib/wheel.py
+ Line number: 437
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+436	                        break
+437	                assert distinfo, '.dist-info directory expected, not found'
+438	
+
+
+ + +
+
+ +
+
+ blacklist: Consider possible security implications associated with the subprocess module.
+ Test ID: B404
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/distro/distro.py
+ Line number: 37
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_imports.html#b404-import-subprocess
+ +
+
+36	import shlex
+37	import subprocess
+38	import sys
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/distro/distro.py
+ Line number: 640
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+639	        def __get__(self, obj: Any, owner: Type[Any]) -> Any:
+640	            assert obj is not None, f"call {self._fname} on an instance"
+641	            ret = obj.__dict__[self._fname] = self._f(obj)
+
+
+ + +
+
+ +
+
+ subprocess_without_shell_equals_true: subprocess call - check for execution of untrusted input.
+ Test ID: B603
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/distro/distro.py
+ Line number: 1161
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b603_subprocess_without_shell_equals_true.html
+ +
+
+1160	            cmd = ("lsb_release", "-a")
+1161	            stdout = subprocess.check_output(cmd, stderr=subprocess.DEVNULL)
+1162	        # Command not found or lsb_release returned error
+
+
+ + +
+
+ +
+
+ subprocess_without_shell_equals_true: subprocess call - check for execution of untrusted input.
+ Test ID: B603
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/distro/distro.py
+ Line number: 1198
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b603_subprocess_without_shell_equals_true.html
+ +
+
+1197	            cmd = ("uname", "-rs")
+1198	            stdout = subprocess.check_output(cmd, stderr=subprocess.DEVNULL)
+1199	        except OSError:
+
+
+ + +
+
+ +
+
+ start_process_with_partial_path: Starting a process with a partial executable path
+ Test ID: B607
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/distro/distro.py
+ Line number: 1209
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b607_start_process_with_partial_path.html
+ +
+
+1208	        try:
+1209	            stdout = subprocess.check_output("oslevel", stderr=subprocess.DEVNULL)
+1210	        except (OSError, subprocess.CalledProcessError):
+
+
+ + +
+
+ +
+
+ subprocess_without_shell_equals_true: subprocess call - check for execution of untrusted input.
+ Test ID: B603
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/distro/distro.py
+ Line number: 1209
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b603_subprocess_without_shell_equals_true.html
+ +
+
+1208	        try:
+1209	            stdout = subprocess.check_output("oslevel", stderr=subprocess.DEVNULL)
+1210	        except (OSError, subprocess.CalledProcessError):
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/msgpack/fallback.py
+ Line number: 369
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+368	    def feed(self, next_bytes):
+369	        assert self._feeding
+370	        view = _get_data_from_buffer(next_bytes)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/msgpack/fallback.py
+ Line number: 433
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+432	                break
+433	            assert isinstance(read_data, bytes)
+434	            self._buffer += read_data
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/msgpack/fallback.py
+ Line number: 617
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+616	                return self._ext_hook(n, bytes(obj))
+617	        assert typ == TYPE_IMMEDIATE
+618	        return obj
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/msgpack/fallback.py
+ Line number: 833
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+832	                    data = obj.data
+833	                assert isinstance(code, int)
+834	                assert isinstance(data, bytes)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/msgpack/fallback.py
+ Line number: 834
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+833	                assert isinstance(code, int)
+834	                assert isinstance(data, bytes)
+835	                L = len(data)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/packaging/_manylinux.py
+ Line number: 146
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+145	        version_string = os.confstr("CS_GNU_LIBC_VERSION")
+146	        assert version_string is not None
+147	        _, version = version_string.split()
+
+
+ + +
+
+ +
+
+ blacklist: Consider possible security implications associated with the subprocess module.
+ Test ID: B404
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/packaging/_musllinux.py
+ Line number: 13
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_imports.html#b404-import-subprocess
+ +
+
+12	import struct
+13	import subprocess
+14	import sys
+
+
+ + +
+
+ +
+
+ subprocess_without_shell_equals_true: subprocess call - check for execution of untrusted input.
+ Test ID: B603
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/packaging/_musllinux.py
+ Line number: 106
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b603_subprocess_without_shell_equals_true.html
+ +
+
+105	        return None
+106	    proc = subprocess.run([ld], stderr=subprocess.PIPE, universal_newlines=True)
+107	    return _parse_musl_version(proc.stderr)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/packaging/_musllinux.py
+ Line number: 130
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+129	    plat = sysconfig.get_platform()
+130	    assert plat.startswith("linux-"), "not linux"
+131	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/packaging/markers.py
+ Line number: 152
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+151	
+152	    assert isinstance(marker, (list, tuple, str))
+153	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/packaging/markers.py
+ Line number: 226
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+225	    for marker in markers:
+226	        assert isinstance(marker, (list, tuple, str))
+227	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/packaging/markers.py
+ Line number: 242
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+241	        else:
+242	            assert marker in ["and", "or"]
+243	            if marker == "or":
+
+
+ + +
+
+ +
+
+ exec_used: Use of exec detected.
+ Test ID: B102
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/pkg_resources/__init__.py
+ Line number: 1561
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b102_exec_used.html
+ +
+
+1560	            code = compile(source, script_filename, 'exec')
+1561	            exec(code, namespace, namespace)
+1562	        else:
+
+
+ + +
+
+ +
+
+ exec_used: Use of exec detected.
+ Test ID: B102
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/pkg_resources/__init__.py
+ Line number: 1572
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b102_exec_used.html
+ +
+
+1571	            script_code = compile(script_text, script_filename, 'exec')
+1572	            exec(script_code, namespace, namespace)
+1573	
+
+
+ + +
+
+ +
+
+ hardcoded_tmp_directory: Probable insecure usage of temp file/directory.
+ Test ID: B108
+ Severity: MEDIUM
+ Confidence: MEDIUM
+ CWE: CWE-377
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/platformdirs/unix.py
+ Line number: 103
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b108_hardcoded_tmp_directory.html
+ +
+
+102	        """:return: cache directory shared by users, e.g. ``/var/tmp/$appname/$version``"""
+103	        return self._append_app_name_and_version("/var/tmp")  # noqa: S108
+104	
+
+
+ + +
+
+ +
+
+ hardcoded_tmp_directory: Probable insecure usage of temp file/directory.
+ Test ID: B108
+ Severity: MEDIUM
+ Confidence: MEDIUM
+ CWE: CWE-377
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/platformdirs/unix.py
+ Line number: 164
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b108_hardcoded_tmp_directory.html
+ +
+
+163	                if not Path(path).exists():
+164	                    path = f"/tmp/runtime-{getuid()}"  # noqa: S108
+165	            else:
+
+
+ + +
+
+ +
+
+ try_except_pass: Try, Except, Pass detected.
+ Test ID: B110
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/pygments/cmdline.py
+ Line number: 522
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b110_try_except_pass.html
+ +
+
+521	                width = shutil.get_terminal_size().columns - 2
+522	            except Exception:
+523	                pass
+524	        argparse.HelpFormatter.__init__(self, prog, indent_increment,
+
+
+ + +
+
+ +
+
+ exec_used: Use of exec detected.
+ Test ID: B102
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/pygments/formatters/__init__.py
+ Line number: 103
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b102_exec_used.html
+ +
+
+102	        with open(filename, 'rb') as f:
+103	            exec(f.read(), custom_namespace)
+104	        # Retrieve the class `formattername` from that namespace
+
+
+ + +
+
+ +
+
+ blacklist: Consider possible security implications associated with the subprocess module.
+ Test ID: B404
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/pygments/formatters/img.py
+ Line number: 18
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_imports.html#b404-import-subprocess
+ +
+
+17	
+18	import subprocess
+19	
+
+
+ + +
+
+ +
+
+ start_process_with_partial_path: Starting a process with a partial executable path
+ Test ID: B607
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/pygments/formatters/img.py
+ Line number: 85
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b607_start_process_with_partial_path.html
+ +
+
+84	    def _get_nix_font_path(self, name, style):
+85	        proc = subprocess.Popen(['fc-list', "%s:style=%s" % (name, style), 'file'],
+86	                                stdout=subprocess.PIPE, stderr=None)
+87	        stdout, _ = proc.communicate()
+
+
+ + +
+
+ +
+
+ subprocess_without_shell_equals_true: subprocess call - check for execution of untrusted input.
+ Test ID: B603
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/pygments/formatters/img.py
+ Line number: 85
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b603_subprocess_without_shell_equals_true.html
+ +
+
+84	    def _get_nix_font_path(self, name, style):
+85	        proc = subprocess.Popen(['fc-list', "%s:style=%s" % (name, style), 'file'],
+86	                                stdout=subprocess.PIPE, stderr=None)
+87	        stdout, _ = proc.communicate()
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/pygments/lexer.py
+ Line number: 492
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+491	        """Preprocess the token component of a token definition."""
+492	        assert type(token) is _TokenType or callable(token), \
+493	            'token type must be simple type or callable, not %r' % (token,)
+494	        return token
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/pygments/lexer.py
+ Line number: 509
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+508	            else:
+509	                assert False, 'unknown new state %r' % new_state
+510	        elif isinstance(new_state, combined):
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/pygments/lexer.py
+ Line number: 516
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+515	            for istate in new_state:
+516	                assert istate != new_state, 'circular state ref %r' % istate
+517	                itokens.extend(cls._process_state(unprocessed,
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/pygments/lexer.py
+ Line number: 524
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+523	            for istate in new_state:
+524	                assert (istate in unprocessed or
+525	                        istate in ('#pop', '#push')), \
+526	                    'unknown new state ' + istate
+527	            return new_state
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/pygments/lexer.py
+ Line number: 529
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+528	        else:
+529	            assert False, 'unknown new state def %r' % new_state
+530	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/pygments/lexer.py
+ Line number: 533
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+532	        """Preprocess a single state definition."""
+533	        assert type(state) is str, "wrong state name %r" % state
+534	        assert state[0] != '#', "invalid state name %r" % state
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/pygments/lexer.py
+ Line number: 534
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+533	        assert type(state) is str, "wrong state name %r" % state
+534	        assert state[0] != '#', "invalid state name %r" % state
+535	        if state in processed:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/pygments/lexer.py
+ Line number: 542
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+541	                # it's a state reference
+542	                assert tdef != state, "circular state reference %r" % state
+543	                tokens.extend(cls._process_state(unprocessed, processed,
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/pygments/lexer.py
+ Line number: 556
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+555	
+556	            assert type(tdef) is tuple, "wrong rule def %r" % tdef
+557	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/pygments/lexer.py
+ Line number: 723
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+722	                        else:
+723	                            assert False, "wrong state def: %r" % new_state
+724	                        statetokens = tokendefs[statestack[-1]]
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/pygments/lexer.py
+ Line number: 811
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+810	                        else:
+811	                            assert False, "wrong state def: %r" % new_state
+812	                        statetokens = tokendefs[ctx.stack[-1]]
+
+
+ + +
+
+ +
+
+ exec_used: Use of exec detected.
+ Test ID: B102
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/pygments/lexers/__init__.py
+ Line number: 153
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b102_exec_used.html
+ +
+
+152	        with open(filename, 'rb') as f:
+153	            exec(f.read(), custom_namespace)
+154	        # Retrieve the class `lexername` from that namespace
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/pygments/style.py
+ Line number: 79
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+78	                return text
+79	            assert False, "wrong color format %r" % text
+80	
+
+
+ + +
+
+ +
+
+ blacklist: Consider possible security implications associated with the subprocess module.
+ Test ID: B404
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/pyproject_hooks/_impl.py
+ Line number: 8
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_imports.html#b404-import-subprocess
+ +
+
+7	from os.path import join as pjoin
+8	from subprocess import STDOUT, check_call, check_output
+9	
+
+
+ + +
+
+ +
+
+ subprocess_without_shell_equals_true: subprocess call - check for execution of untrusted input.
+ Test ID: B603
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/pyproject_hooks/_impl.py
+ Line number: 59
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b603_subprocess_without_shell_equals_true.html
+ +
+
+58	
+59	    check_call(cmd, cwd=cwd, env=env)
+60	
+
+
+ + +
+
+ +
+
+ subprocess_without_shell_equals_true: subprocess call - check for execution of untrusted input.
+ Test ID: B603
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/pyproject_hooks/_impl.py
+ Line number: 71
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b603_subprocess_without_shell_equals_true.html
+ +
+
+70	
+71	    check_output(cmd, cwd=cwd, env=env, stderr=STDOUT)
+72	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/requests/__init__.py
+ Line number: 57
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+56	    urllib3_version = urllib3_version.split(".")
+57	    assert urllib3_version != ["dev"]  # Verify urllib3 isn't installed from git.
+58	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/requests/__init__.py
+ Line number: 67
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+66	    # urllib3 >= 1.21.1
+67	    assert major >= 1
+68	    if major == 1:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/requests/__init__.py
+ Line number: 69
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+68	    if major == 1:
+69	        assert minor >= 21
+70	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/requests/__init__.py
+ Line number: 76
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+75	        # chardet_version >= 3.0.2, < 6.0.0
+76	        assert (3, 0, 2) <= (major, minor, patch) < (6, 0, 0)
+77	    elif charset_normalizer_version:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/requests/__init__.py
+ Line number: 81
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+80	        # charset_normalizer >= 2.0.0 < 4.0.0
+81	        assert (2, 0, 0) <= (major, minor, patch) < (4, 0, 0)
+82	    else:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/requests/_internal_utils.py
+ Line number: 45
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+44	    """
+45	    assert isinstance(u_string, str)
+46	    try:
+
+
+ + +
+
+ +
+
+ hashlib: Use of weak MD5 hash for security. Consider usedforsecurity=False
+ Test ID: B324
+ Severity: HIGH
+ Confidence: HIGH
+ CWE: CWE-327
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/requests/auth.py
+ Line number: 148
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b324_hashlib.html
+ +
+
+147	                    x = x.encode("utf-8")
+148	                return hashlib.md5(x).hexdigest()
+149	
+
+
+ + +
+
+ +
+
+ hashlib: Use of weak SHA1 hash for security. Consider usedforsecurity=False
+ Test ID: B324
+ Severity: HIGH
+ Confidence: HIGH
+ CWE: CWE-327
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/requests/auth.py
+ Line number: 156
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b324_hashlib.html
+ +
+
+155	                    x = x.encode("utf-8")
+156	                return hashlib.sha1(x).hexdigest()
+157	
+
+
+ + +
+
+ +
+
+ hashlib: Use of weak SHA1 hash for security. Consider usedforsecurity=False
+ Test ID: B324
+ Severity: HIGH
+ Confidence: HIGH
+ CWE: CWE-327
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/requests/auth.py
+ Line number: 205
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b324_hashlib.html
+ +
+
+204	
+205	        cnonce = hashlib.sha1(s).hexdigest()[:16]
+206	        if _algorithm == "MD5-SESS":
+
+
+ + +
+
+ +
+
+ hardcoded_password_string: Possible hardcoded password: '㊙'
+ Test ID: B105
+ Severity: LOW
+ Confidence: MEDIUM
+ CWE: CWE-259
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/rich/_emoji_codes.py
+ Line number: 156
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b105_hardcoded_password_string.html
+ +
+
+155	    "japanese_reserved_button": "🈯",
+156	    "japanese_secret_button": "㊙",
+157	    "japanese_service_charge_button": "🈂",
+158	    "japanese_symbol_for_beginner": "🔰",
+159	    "japanese_vacancy_button": "🈳",
+160	    "jersey": "🇯🇪",
+161	    "jordan": "🇯🇴",
+162	    "kazakhstan": "🇰🇿",
+163	    "kenya": "🇰🇪",
+164	    "kiribati": "🇰🇮",
+165	    "kosovo": "🇽🇰",
+166	    "kuwait": "🇰🇼",
+167	    "kyrgyzstan": "🇰🇬",
+168	    "laos": "🇱🇦",
+169	    "latvia": "🇱🇻",
+170	    "lebanon": "🇱🇧",
+171	    "leo": "♌",
+172	    "lesotho": "🇱🇸",
+173	    "liberia": "🇱🇷",
+174	    "libra": "♎",
+175	    "libya": "🇱🇾",
+176	    "liechtenstein": "🇱🇮",
+177	    "lithuania": "🇱🇹",
+178	    "luxembourg": "🇱🇺",
+179	    "macau_sar_china": "🇲🇴",
+180	    "macedonia": "🇲🇰",
+181	    "madagascar": "🇲🇬",
+182	    "malawi": "🇲🇼",
+183	    "malaysia": "🇲🇾",
+184	    "maldives": "🇲🇻",
+185	    "mali": "🇲🇱",
+186	    "malta": "🇲🇹",
+187	    "marshall_islands": "🇲🇭",
+188	    "martinique": "🇲🇶",
+189	    "mauritania": "🇲🇷",
+190	    "mauritius": "🇲🇺",
+191	    "mayotte": "🇾🇹",
+192	    "mexico": "🇲🇽",
+193	    "micronesia": "🇫🇲",
+194	    "moldova": "🇲🇩",
+195	    "monaco": "🇲🇨",
+196	    "mongolia": "🇲🇳",
+197	    "montenegro": "🇲🇪",
+198	    "montserrat": "🇲🇸",
+199	    "morocco": "🇲🇦",
+200	    "mozambique": "🇲🇿",
+201	    "mrs._claus": "🤶",
+202	    "mrs._claus_dark_skin_tone": "🤶🏿",
+203	    "mrs._claus_light_skin_tone": "🤶🏻",
+204	    "mrs._claus_medium-dark_skin_tone": "🤶🏾",
+205	    "mrs._claus_medium-light_skin_tone": "🤶🏼",
+206	    "mrs._claus_medium_skin_tone": "🤶🏽",
+207	    "myanmar_(burma)": "🇲🇲",
+208	    "new_button": "🆕",
+209	    "ng_button": "🆖",
+210	    "namibia": "🇳🇦",
+211	    "nauru": "🇳🇷",
+212	    "nepal": "🇳🇵",
+213	    "netherlands": "🇳🇱",
+214	    "new_caledonia": "🇳🇨",
+215	    "new_zealand": "🇳🇿",
+216	    "nicaragua": "🇳🇮",
+217	    "niger": "🇳🇪",
+218	    "nigeria": "🇳🇬",
+219	    "niue": "🇳🇺",
+220	    "norfolk_island": "🇳🇫",
+221	    "north_korea": "🇰🇵",
+222	    "northern_mariana_islands": "🇲🇵",
+223	    "norway": "🇳🇴",
+224	    "ok_button": "🆗",
+225	    "ok_hand": "👌",
+226	    "ok_hand_dark_skin_tone": "👌🏿",
+227	    "ok_hand_light_skin_tone": "👌🏻",
+228	    "ok_hand_medium-dark_skin_tone": "👌🏾",
+229	    "ok_hand_medium-light_skin_tone": "👌🏼",
+230	    "ok_hand_medium_skin_tone": "👌🏽",
+231	    "on!_arrow": "🔛",
+232	    "o_button_(blood_type)": "🅾",
+233	    "oman": "🇴🇲",
+234	    "ophiuchus": "⛎",
+235	    "p_button": "🅿",
+236	    "pakistan": "🇵🇰",
+237	    "palau": "🇵🇼",
+238	    "palestinian_territories": "🇵🇸",
+239	    "panama": "🇵🇦",
+240	    "papua_new_guinea": "🇵🇬",
+241	    "paraguay": "🇵🇾",
+242	    "peru": "🇵🇪",
+243	    "philippines": "🇵🇭",
+244	    "pisces": "♓",
+245	    "pitcairn_islands": "🇵🇳",
+246	    "poland": "🇵🇱",
+247	    "portugal": "🇵🇹",
+248	    "puerto_rico": "🇵🇷",
+249	    "qatar": "🇶🇦",
+250	    "romania": "🇷🇴",
+251	    "russia": "🇷🇺",
+252	    "rwanda": "🇷🇼",
+253	    "réunion": "🇷🇪",
+254	    "soon_arrow": "🔜",
+255	    "sos_button": "🆘",
+256	    "sagittarius": "♐",
+257	    "samoa": "🇼🇸",
+258	    "san_marino": "🇸🇲",
+259	    "santa_claus": "🎅",
+260	    "santa_claus_dark_skin_tone": "🎅🏿",
+261	    "santa_claus_light_skin_tone": "🎅🏻",
+262	    "santa_claus_medium-dark_skin_tone": "🎅🏾",
+263	    "santa_claus_medium-light_skin_tone": "🎅🏼",
+264	    "santa_claus_medium_skin_tone": "🎅🏽",
+265	    "saudi_arabia": "🇸🇦",
+266	    "scorpio": "♏",
+267	    "scotland": "🏴\U000e0067\U000e0062\U000e0073\U000e0063\U000e0074\U000e007f",
+268	    "senegal": "🇸🇳",
+269	    "serbia": "🇷🇸",
+270	    "seychelles": "🇸🇨",
+271	    "sierra_leone": "🇸🇱",
+272	    "singapore": "🇸🇬",
+273	    "sint_maarten": "🇸🇽",
+274	    "slovakia": "🇸🇰",
+275	    "slovenia": "🇸🇮",
+276	    "solomon_islands": "🇸🇧",
+277	    "somalia": "🇸🇴",
+278	    "south_africa": "🇿🇦",
+279	    "south_georgia_&_south_sandwich_islands": "🇬🇸",
+280	    "south_korea": "🇰🇷",
+281	    "south_sudan": "🇸🇸",
+282	    "spain": "🇪🇸",
+283	    "sri_lanka": "🇱🇰",
+284	    "st._barthélemy": "🇧🇱",
+285	    "st._helena": "🇸🇭",
+286	    "st._kitts_&_nevis": "🇰🇳",
+287	    "st._lucia": "🇱🇨",
+288	    "st._martin": "🇲🇫",
+289	    "st._pierre_&_miquelon": "🇵🇲",
+290	    "st._vincent_&_grenadines": "🇻🇨",
+291	    "statue_of_liberty": "🗽",
+292	    "sudan": "🇸🇩",
+293	    "suriname": "🇸🇷",
+294	    "svalbard_&_jan_mayen": "🇸🇯",
+295	    "swaziland": "🇸🇿",
+296	    "sweden": "🇸🇪",
+297	    "switzerland": "🇨🇭",
+298	    "syria": "🇸🇾",
+299	    "são_tomé_&_príncipe": "🇸🇹",
+300	    "t-rex": "🦖",
+301	    "top_arrow": "🔝",
+302	    "taiwan": "🇹🇼",
+303	    "tajikistan": "🇹🇯",
+304	    "tanzania": "🇹🇿",
+305	    "taurus": "♉",
+306	    "thailand": "🇹🇭",
+307	    "timor-leste": "🇹🇱",
+308	    "togo": "🇹🇬",
+309	    "tokelau": "🇹🇰",
+310	    "tokyo_tower": "🗼",
+311	    "tonga": "🇹🇴",
+312	    "trinidad_&_tobago": "🇹🇹",
+313	    "tristan_da_cunha": "🇹🇦",
+314	    "tunisia": "🇹🇳",
+315	    "turkey": "🦃",
+316	    "turkmenistan": "🇹🇲",
+317	    "turks_&_caicos_islands": "🇹🇨",
+318	    "tuvalu": "🇹🇻",
+319	    "u.s._outlying_islands": "🇺🇲",
+320	    "u.s._virgin_islands": "🇻🇮",
+321	    "up!_button": "🆙",
+322	    "uganda": "🇺🇬",
+323	    "ukraine": "🇺🇦",
+324	    "united_arab_emirates": "🇦🇪",
+325	    "united_kingdom": "🇬🇧",
+326	    "united_nations": "🇺🇳",
+327	    "united_states": "🇺🇸",
+328	    "uruguay": "🇺🇾",
+329	    "uzbekistan": "🇺🇿",
+330	    "vs_button": "🆚",
+331	    "vanuatu": "🇻🇺",
+332	    "vatican_city": "🇻🇦",
+333	    "venezuela": "🇻🇪",
+334	    "vietnam": "🇻🇳",
+335	    "virgo": "♍",
+336	    "wales": "🏴\U000e0067\U000e0062\U000e0077\U000e006c\U000e0073\U000e007f",
+337	    "wallis_&_futuna": "🇼🇫",
+338	    "western_sahara": "🇪🇭",
+339	    "yemen": "🇾🇪",
+340	    "zambia": "🇿🇲",
+341	    "zimbabwe": "🇿🇼",
+342	    "abacus": "🧮",
+343	    "adhesive_bandage": "🩹",
+344	    "admission_tickets": "🎟",
+345	    "adult": "🧑",
+346	    "adult_dark_skin_tone": "🧑🏿",
+347	    "adult_light_skin_tone": "🧑🏻",
+348	    "adult_medium-dark_skin_tone": "🧑🏾",
+349	    "adult_medium-light_skin_tone": "🧑🏼",
+350	    "adult_medium_skin_tone": "🧑🏽",
+351	    "aerial_tramway": "🚡",
+352	    "airplane": "✈",
+353	    "airplane_arrival": "🛬",
+354	    "airplane_departure": "🛫",
+355	    "alarm_clock": "⏰",
+356	    "alembic": "⚗",
+357	    "alien": "👽",
+358	    "alien_monster": "👾",
+359	    "ambulance": "🚑",
+360	    "american_football": "🏈",
+361	    "amphora": "🏺",
+362	    "anchor": "⚓",
+363	    "anger_symbol": "💢",
+364	    "angry_face": "😠",
+365	    "angry_face_with_horns": "👿",
+366	    "anguished_face": "😧",
+367	    "ant": "🐜",
+368	    "antenna_bars": "📶",
+369	    "anxious_face_with_sweat": "😰",
+370	    "articulated_lorry": "🚛",
+371	    "artist_palette": "🎨",
+372	    "astonished_face": "😲",
+373	    "atom_symbol": "⚛",
+374	    "auto_rickshaw": "🛺",
+375	    "automobile": "🚗",
+376	    "avocado": "🥑",
+377	    "axe": "🪓",
+378	    "baby": "👶",
+379	    "baby_angel": "👼",
+380	    "baby_angel_dark_skin_tone": "👼🏿",
+381	    "baby_angel_light_skin_tone": "👼🏻",
+382	    "baby_angel_medium-dark_skin_tone": "👼🏾",
+383	    "baby_angel_medium-light_skin_tone": "👼🏼",
+384	    "baby_angel_medium_skin_tone": "👼🏽",
+385	    "baby_bottle": "🍼",
+386	    "baby_chick": "🐤",
+387	    "baby_dark_skin_tone": "👶🏿",
+388	    "baby_light_skin_tone": "👶🏻",
+389	    "baby_medium-dark_skin_tone": "👶🏾",
+390	    "baby_medium-light_skin_tone": "👶🏼",
+391	    "baby_medium_skin_tone": "👶🏽",
+392	    "baby_symbol": "🚼",
+393	    "backhand_index_pointing_down": "👇",
+394	    "backhand_index_pointing_down_dark_skin_tone": "👇🏿",
+395	    "backhand_index_pointing_down_light_skin_tone": "👇🏻",
+396	    "backhand_index_pointing_down_medium-dark_skin_tone": "👇🏾",
+397	    "backhand_index_pointing_down_medium-light_skin_tone": "👇🏼",
+398	    "backhand_index_pointing_down_medium_skin_tone": "👇🏽",
+399	    "backhand_index_pointing_left": "👈",
+400	    "backhand_index_pointing_left_dark_skin_tone": "👈🏿",
+401	    "backhand_index_pointing_left_light_skin_tone": "👈🏻",
+402	    "backhand_index_pointing_left_medium-dark_skin_tone": "👈🏾",
+403	    "backhand_index_pointing_left_medium-light_skin_tone": "👈🏼",
+404	    "backhand_index_pointing_left_medium_skin_tone": "👈🏽",
+405	    "backhand_index_pointing_right": "👉",
+406	    "backhand_index_pointing_right_dark_skin_tone": "👉🏿",
+407	    "backhand_index_pointing_right_light_skin_tone": "👉🏻",
+408	    "backhand_index_pointing_right_medium-dark_skin_tone": "👉🏾",
+409	    "backhand_index_pointing_right_medium-light_skin_tone": "👉🏼",
+410	    "backhand_index_pointing_right_medium_skin_tone": "👉🏽",
+411	    "backhand_index_pointing_up": "👆",
+412	    "backhand_index_pointing_up_dark_skin_tone": "👆🏿",
+413	    "backhand_index_pointing_up_light_skin_tone": "👆🏻",
+414	    "backhand_index_pointing_up_medium-dark_skin_tone": "👆🏾",
+415	    "backhand_index_pointing_up_medium-light_skin_tone": "👆🏼",
+416	    "backhand_index_pointing_up_medium_skin_tone": "👆🏽",
+417	    "bacon": "🥓",
+418	    "badger": "🦡",
+419	    "badminton": "🏸",
+420	    "bagel": "🥯",
+421	    "baggage_claim": "🛄",
+422	    "baguette_bread": "🥖",
+423	    "balance_scale": "⚖",
+424	    "bald": "🦲",
+425	    "bald_man": "👨\u200d🦲",
+426	    "bald_woman": "👩\u200d🦲",
+427	    "ballet_shoes": "🩰",
+428	    "balloon": "🎈",
+429	    "ballot_box_with_ballot": "🗳",
+430	    "ballot_box_with_check": "☑",
+431	    "banana": "🍌",
+432	    "banjo": "🪕",
+433	    "bank": "🏦",
+434	    "bar_chart": "📊",
+435	    "barber_pole": "💈",
+436	    "baseball": "⚾",
+437	    "basket": "🧺",
+438	    "basketball": "🏀",
+439	    "bat": "🦇",
+440	    "bathtub": "🛁",
+441	    "battery": "🔋",
+442	    "beach_with_umbrella": "🏖",
+443	    "beaming_face_with_smiling_eyes": "😁",
+444	    "bear_face": "🐻",
+445	    "bearded_person": "🧔",
+446	    "bearded_person_dark_skin_tone": "🧔🏿",
+447	    "bearded_person_light_skin_tone": "🧔🏻",
+448	    "bearded_person_medium-dark_skin_tone": "🧔🏾",
+449	    "bearded_person_medium-light_skin_tone": "🧔🏼",
+450	    "bearded_person_medium_skin_tone": "🧔🏽",
+451	    "beating_heart": "💓",
+452	    "bed": "🛏",
+453	    "beer_mug": "🍺",
+454	    "bell": "🔔",
+455	    "bell_with_slash": "🔕",
+456	    "bellhop_bell": "🛎",
+457	    "bento_box": "🍱",
+458	    "beverage_box": "🧃",
+459	    "bicycle": "🚲",
+460	    "bikini": "👙",
+461	    "billed_cap": "🧢",
+462	    "biohazard": "☣",
+463	    "bird": "🐦",
+464	    "birthday_cake": "🎂",
+465	    "black_circle": "⚫",
+466	    "black_flag": "🏴",
+467	    "black_heart": "🖤",
+468	    "black_large_square": "⬛",
+469	    "black_medium-small_square": "◾",
+470	    "black_medium_square": "◼",
+471	    "black_nib": "✒",
+472	    "black_small_square": "▪",
+473	    "black_square_button": "🔲",
+474	    "blond-haired_man": "👱\u200d♂️",
+475	    "blond-haired_man_dark_skin_tone": "👱🏿\u200d♂️",
+476	    "blond-haired_man_light_skin_tone": "👱🏻\u200d♂️",
+477	    "blond-haired_man_medium-dark_skin_tone": "👱🏾\u200d♂️",
+478	    "blond-haired_man_medium-light_skin_tone": "👱🏼\u200d♂️",
+479	    "blond-haired_man_medium_skin_tone": "👱🏽\u200d♂️",
+480	    "blond-haired_person": "👱",
+481	    "blond-haired_person_dark_skin_tone": "👱🏿",
+482	    "blond-haired_person_light_skin_tone": "👱🏻",
+483	    "blond-haired_person_medium-dark_skin_tone": "👱🏾",
+484	    "blond-haired_person_medium-light_skin_tone": "👱🏼",
+485	    "blond-haired_person_medium_skin_tone": "👱🏽",
+486	    "blond-haired_woman": "👱\u200d♀️",
+487	    "blond-haired_woman_dark_skin_tone": "👱🏿\u200d♀️",
+488	    "blond-haired_woman_light_skin_tone": "👱🏻\u200d♀️",
+489	    "blond-haired_woman_medium-dark_skin_tone": "👱🏾\u200d♀️",
+490	    "blond-haired_woman_medium-light_skin_tone": "👱🏼\u200d♀️",
+491	    "blond-haired_woman_medium_skin_tone": "👱🏽\u200d♀️",
+492	    "blossom": "🌼",
+493	    "blowfish": "🐡",
+494	    "blue_book": "📘",
+495	    "blue_circle": "🔵",
+496	    "blue_heart": "💙",
+497	    "blue_square": "🟦",
+498	    "boar": "🐗",
+499	    "bomb": "💣",
+500	    "bone": "🦴",
+501	    "bookmark": "🔖",
+502	    "bookmark_tabs": "📑",
+503	    "books": "📚",
+504	    "bottle_with_popping_cork": "🍾",
+505	    "bouquet": "💐",
+506	    "bow_and_arrow": "🏹",
+507	    "bowl_with_spoon": "🥣",
+508	    "bowling": "🎳",
+509	    "boxing_glove": "🥊",
+510	    "boy": "👦",
+511	    "boy_dark_skin_tone": "👦🏿",
+512	    "boy_light_skin_tone": "👦🏻",
+513	    "boy_medium-dark_skin_tone": "👦🏾",
+514	    "boy_medium-light_skin_tone": "👦🏼",
+515	    "boy_medium_skin_tone": "👦🏽",
+516	    "brain": "🧠",
+517	    "bread": "🍞",
+518	    "breast-feeding": "🤱",
+519	    "breast-feeding_dark_skin_tone": "🤱🏿",
+520	    "breast-feeding_light_skin_tone": "🤱🏻",
+521	    "breast-feeding_medium-dark_skin_tone": "🤱🏾",
+522	    "breast-feeding_medium-light_skin_tone": "🤱🏼",
+523	    "breast-feeding_medium_skin_tone": "🤱🏽",
+524	    "brick": "🧱",
+525	    "bride_with_veil": "👰",
+526	    "bride_with_veil_dark_skin_tone": "👰🏿",
+527	    "bride_with_veil_light_skin_tone": "👰🏻",
+528	    "bride_with_veil_medium-dark_skin_tone": "👰🏾",
+529	    "bride_with_veil_medium-light_skin_tone": "👰🏼",
+530	    "bride_with_veil_medium_skin_tone": "👰🏽",
+531	    "bridge_at_night": "🌉",
+532	    "briefcase": "💼",
+533	    "briefs": "🩲",
+534	    "bright_button": "🔆",
+535	    "broccoli": "🥦",
+536	    "broken_heart": "💔",
+537	    "broom": "🧹",
+538	    "brown_circle": "🟤",
+539	    "brown_heart": "🤎",
+540	    "brown_square": "🟫",
+541	    "bug": "🐛",
+542	    "building_construction": "🏗",
+543	    "bullet_train": "🚅",
+544	    "burrito": "🌯",
+545	    "bus": "🚌",
+546	    "bus_stop": "🚏",
+547	    "bust_in_silhouette": "👤",
+548	    "busts_in_silhouette": "👥",
+549	    "butter": "🧈",
+550	    "butterfly": "🦋",
+551	    "cactus": "🌵",
+552	    "calendar": "📆",
+553	    "call_me_hand": "🤙",
+554	    "call_me_hand_dark_skin_tone": "🤙🏿",
+555	    "call_me_hand_light_skin_tone": "🤙🏻",
+556	    "call_me_hand_medium-dark_skin_tone": "🤙🏾",
+557	    "call_me_hand_medium-light_skin_tone": "🤙🏼",
+558	    "call_me_hand_medium_skin_tone": "🤙🏽",
+559	    "camel": "🐫",
+560	    "camera": "📷",
+561	    "camera_with_flash": "📸",
+562	    "camping": "🏕",
+563	    "candle": "🕯",
+564	    "candy": "🍬",
+565	    "canned_food": "🥫",
+566	    "canoe": "🛶",
+567	    "card_file_box": "🗃",
+568	    "card_index": "📇",
+569	    "card_index_dividers": "🗂",
+570	    "carousel_horse": "🎠",
+571	    "carp_streamer": "🎏",
+572	    "carrot": "🥕",
+573	    "castle": "🏰",
+574	    "cat": "🐱",
+575	    "cat_face": "🐱",
+576	    "cat_face_with_tears_of_joy": "😹",
+577	    "cat_face_with_wry_smile": "😼",
+578	    "chains": "⛓",
+579	    "chair": "🪑",
+580	    "chart_decreasing": "📉",
+581	    "chart_increasing": "📈",
+582	    "chart_increasing_with_yen": "💹",
+583	    "cheese_wedge": "🧀",
+584	    "chequered_flag": "🏁",
+585	    "cherries": "🍒",
+586	    "cherry_blossom": "🌸",
+587	    "chess_pawn": "♟",
+588	    "chestnut": "🌰",
+589	    "chicken": "🐔",
+590	    "child": "🧒",
+591	    "child_dark_skin_tone": "🧒🏿",
+592	    "child_light_skin_tone": "🧒🏻",
+593	    "child_medium-dark_skin_tone": "🧒🏾",
+594	    "child_medium-light_skin_tone": "🧒🏼",
+595	    "child_medium_skin_tone": "🧒🏽",
+596	    "children_crossing": "🚸",
+597	    "chipmunk": "🐿",
+598	    "chocolate_bar": "🍫",
+599	    "chopsticks": "🥢",
+600	    "church": "⛪",
+601	    "cigarette": "🚬",
+602	    "cinema": "🎦",
+603	    "circled_m": "Ⓜ",
+604	    "circus_tent": "🎪",
+605	    "cityscape": "🏙",
+606	    "cityscape_at_dusk": "🌆",
+607	    "clamp": "🗜",
+608	    "clapper_board": "🎬",
+609	    "clapping_hands": "👏",
+610	    "clapping_hands_dark_skin_tone": "👏🏿",
+611	    "clapping_hands_light_skin_tone": "👏🏻",
+612	    "clapping_hands_medium-dark_skin_tone": "👏🏾",
+613	    "clapping_hands_medium-light_skin_tone": "👏🏼",
+614	    "clapping_hands_medium_skin_tone": "👏🏽",
+615	    "classical_building": "🏛",
+616	    "clinking_beer_mugs": "🍻",
+617	    "clinking_glasses": "🥂",
+618	    "clipboard": "📋",
+619	    "clockwise_vertical_arrows": "🔃",
+620	    "closed_book": "📕",
+621	    "closed_mailbox_with_lowered_flag": "📪",
+622	    "closed_mailbox_with_raised_flag": "📫",
+623	    "closed_umbrella": "🌂",
+624	    "cloud": "☁",
+625	    "cloud_with_lightning": "🌩",
+626	    "cloud_with_lightning_and_rain": "⛈",
+627	    "cloud_with_rain": "🌧",
+628	    "cloud_with_snow": "🌨",
+629	    "clown_face": "🤡",
+630	    "club_suit": "♣",
+631	    "clutch_bag": "👝",
+632	    "coat": "🧥",
+633	    "cocktail_glass": "🍸",
+634	    "coconut": "🥥",
+635	    "coffin": "⚰",
+636	    "cold_face": "🥶",
+637	    "collision": "💥",
+638	    "comet": "☄",
+639	    "compass": "🧭",
+640	    "computer_disk": "💽",
+641	    "computer_mouse": "🖱",
+642	    "confetti_ball": "🎊",
+643	    "confounded_face": "😖",
+644	    "confused_face": "😕",
+645	    "construction": "🚧",
+646	    "construction_worker": "👷",
+647	    "construction_worker_dark_skin_tone": "👷🏿",
+648	    "construction_worker_light_skin_tone": "👷🏻",
+649	    "construction_worker_medium-dark_skin_tone": "👷🏾",
+650	    "construction_worker_medium-light_skin_tone": "👷🏼",
+651	    "construction_worker_medium_skin_tone": "👷🏽",
+652	    "control_knobs": "🎛",
+653	    "convenience_store": "🏪",
+654	    "cooked_rice": "🍚",
+655	    "cookie": "🍪",
+656	    "cooking": "🍳",
+657	    "copyright": "©",
+658	    "couch_and_lamp": "🛋",
+659	    "counterclockwise_arrows_button": "🔄",
+660	    "couple_with_heart": "💑",
+661	    "couple_with_heart_man_man": "👨\u200d❤️\u200d👨",
+662	    "couple_with_heart_woman_man": "👩\u200d❤️\u200d👨",
+663	    "couple_with_heart_woman_woman": "👩\u200d❤️\u200d👩",
+664	    "cow": "🐮",
+665	    "cow_face": "🐮",
+666	    "cowboy_hat_face": "🤠",
+667	    "crab": "🦀",
+668	    "crayon": "🖍",
+669	    "credit_card": "💳",
+670	    "crescent_moon": "🌙",
+671	    "cricket": "🦗",
+672	    "cricket_game": "🏏",
+673	    "crocodile": "🐊",
+674	    "croissant": "🥐",
+675	    "cross_mark": "❌",
+676	    "cross_mark_button": "❎",
+677	    "crossed_fingers": "🤞",
+678	    "crossed_fingers_dark_skin_tone": "🤞🏿",
+679	    "crossed_fingers_light_skin_tone": "🤞🏻",
+680	    "crossed_fingers_medium-dark_skin_tone": "🤞🏾",
+681	    "crossed_fingers_medium-light_skin_tone": "🤞🏼",
+682	    "crossed_fingers_medium_skin_tone": "🤞🏽",
+683	    "crossed_flags": "🎌",
+684	    "crossed_swords": "⚔",
+685	    "crown": "👑",
+686	    "crying_cat_face": "😿",
+687	    "crying_face": "😢",
+688	    "crystal_ball": "🔮",
+689	    "cucumber": "🥒",
+690	    "cupcake": "🧁",
+691	    "cup_with_straw": "🥤",
+692	    "curling_stone": "🥌",
+693	    "curly_hair": "🦱",
+694	    "curly-haired_man": "👨\u200d🦱",
+695	    "curly-haired_woman": "👩\u200d🦱",
+696	    "curly_loop": "➰",
+697	    "currency_exchange": "💱",
+698	    "curry_rice": "🍛",
+699	    "custard": "🍮",
+700	    "customs": "🛃",
+701	    "cut_of_meat": "🥩",
+702	    "cyclone": "🌀",
+703	    "dagger": "🗡",
+704	    "dango": "🍡",
+705	    "dashing_away": "💨",
+706	    "deaf_person": "🧏",
+707	    "deciduous_tree": "🌳",
+708	    "deer": "🦌",
+709	    "delivery_truck": "🚚",
+710	    "department_store": "🏬",
+711	    "derelict_house": "🏚",
+712	    "desert": "🏜",
+713	    "desert_island": "🏝",
+714	    "desktop_computer": "🖥",
+715	    "detective": "🕵",
+716	    "detective_dark_skin_tone": "🕵🏿",
+717	    "detective_light_skin_tone": "🕵🏻",
+718	    "detective_medium-dark_skin_tone": "🕵🏾",
+719	    "detective_medium-light_skin_tone": "🕵🏼",
+720	    "detective_medium_skin_tone": "🕵🏽",
+721	    "diamond_suit": "♦",
+722	    "diamond_with_a_dot": "💠",
+723	    "dim_button": "🔅",
+724	    "direct_hit": "🎯",
+725	    "disappointed_face": "😞",
+726	    "diving_mask": "🤿",
+727	    "diya_lamp": "🪔",
+728	    "dizzy": "💫",
+729	    "dizzy_face": "😵",
+730	    "dna": "🧬",
+731	    "dog": "🐶",
+732	    "dog_face": "🐶",
+733	    "dollar_banknote": "💵",
+734	    "dolphin": "🐬",
+735	    "door": "🚪",
+736	    "dotted_six-pointed_star": "🔯",
+737	    "double_curly_loop": "➿",
+738	    "double_exclamation_mark": "‼",
+739	    "doughnut": "🍩",
+740	    "dove": "🕊",
+741	    "down-left_arrow": "↙",
+742	    "down-right_arrow": "↘",
+743	    "down_arrow": "⬇",
+744	    "downcast_face_with_sweat": "😓",
+745	    "downwards_button": "🔽",
+746	    "dragon": "🐉",
+747	    "dragon_face": "🐲",
+748	    "dress": "👗",
+749	    "drooling_face": "🤤",
+750	    "drop_of_blood": "🩸",
+751	    "droplet": "💧",
+752	    "drum": "🥁",
+753	    "duck": "🦆",
+754	    "dumpling": "🥟",
+755	    "dvd": "📀",
+756	    "e-mail": "📧",
+757	    "eagle": "🦅",
+758	    "ear": "👂",
+759	    "ear_dark_skin_tone": "👂🏿",
+760	    "ear_light_skin_tone": "👂🏻",
+761	    "ear_medium-dark_skin_tone": "👂🏾",
+762	    "ear_medium-light_skin_tone": "👂🏼",
+763	    "ear_medium_skin_tone": "👂🏽",
+764	    "ear_of_corn": "🌽",
+765	    "ear_with_hearing_aid": "🦻",
+766	    "egg": "🍳",
+767	    "eggplant": "🍆",
+768	    "eight-pointed_star": "✴",
+769	    "eight-spoked_asterisk": "✳",
+770	    "eight-thirty": "🕣",
+771	    "eight_o’clock": "🕗",
+772	    "eject_button": "⏏",
+773	    "electric_plug": "🔌",
+774	    "elephant": "🐘",
+775	    "eleven-thirty": "🕦",
+776	    "eleven_o’clock": "🕚",
+777	    "elf": "🧝",
+778	    "elf_dark_skin_tone": "🧝🏿",
+779	    "elf_light_skin_tone": "🧝🏻",
+780	    "elf_medium-dark_skin_tone": "🧝🏾",
+781	    "elf_medium-light_skin_tone": "🧝🏼",
+782	    "elf_medium_skin_tone": "🧝🏽",
+783	    "envelope": "✉",
+784	    "envelope_with_arrow": "📩",
+785	    "euro_banknote": "💶",
+786	    "evergreen_tree": "🌲",
+787	    "ewe": "🐑",
+788	    "exclamation_mark": "❗",
+789	    "exclamation_question_mark": "⁉",
+790	    "exploding_head": "🤯",
+791	    "expressionless_face": "😑",
+792	    "eye": "👁",
+793	    "eye_in_speech_bubble": "👁️\u200d🗨️",
+794	    "eyes": "👀",
+795	    "face_blowing_a_kiss": "😘",
+796	    "face_savoring_food": "😋",
+797	    "face_screaming_in_fear": "😱",
+798	    "face_vomiting": "🤮",
+799	    "face_with_hand_over_mouth": "🤭",
+800	    "face_with_head-bandage": "🤕",
+801	    "face_with_medical_mask": "😷",
+802	    "face_with_monocle": "🧐",
+803	    "face_with_open_mouth": "😮",
+804	    "face_with_raised_eyebrow": "🤨",
+805	    "face_with_rolling_eyes": "🙄",
+806	    "face_with_steam_from_nose": "😤",
+807	    "face_with_symbols_on_mouth": "🤬",
+808	    "face_with_tears_of_joy": "😂",
+809	    "face_with_thermometer": "🤒",
+810	    "face_with_tongue": "😛",
+811	    "face_without_mouth": "😶",
+812	    "factory": "🏭",
+813	    "fairy": "🧚",
+814	    "fairy_dark_skin_tone": "🧚🏿",
+815	    "fairy_light_skin_tone": "🧚🏻",
+816	    "fairy_medium-dark_skin_tone": "🧚🏾",
+817	    "fairy_medium-light_skin_tone": "🧚🏼",
+818	    "fairy_medium_skin_tone": "🧚🏽",
+819	    "falafel": "🧆",
+820	    "fallen_leaf": "🍂",
+821	    "family": "👪",
+822	    "family_man_boy": "👨\u200d👦",
+823	    "family_man_boy_boy": "👨\u200d👦\u200d👦",
+824	    "family_man_girl": "👨\u200d👧",
+825	    "family_man_girl_boy": "👨\u200d👧\u200d👦",
+826	    "family_man_girl_girl": "👨\u200d👧\u200d👧",
+827	    "family_man_man_boy": "👨\u200d👨\u200d👦",
+828	    "family_man_man_boy_boy": "👨\u200d👨\u200d👦\u200d👦",
+829	    "family_man_man_girl": "👨\u200d👨\u200d👧",
+830	    "family_man_man_girl_boy": "👨\u200d👨\u200d👧\u200d👦",
+831	    "family_man_man_girl_girl": "👨\u200d👨\u200d👧\u200d👧",
+832	    "family_man_woman_boy": "👨\u200d👩\u200d👦",
+833	    "family_man_woman_boy_boy": "👨\u200d👩\u200d👦\u200d👦",
+834	    "family_man_woman_girl": "👨\u200d👩\u200d👧",
+835	    "family_man_woman_girl_boy": "👨\u200d👩\u200d👧\u200d👦",
+836	    "family_man_woman_girl_girl": "👨\u200d👩\u200d👧\u200d👧",
+837	    "family_woman_boy": "👩\u200d👦",
+838	    "family_woman_boy_boy": "👩\u200d👦\u200d👦",
+839	    "family_woman_girl": "👩\u200d👧",
+840	    "family_woman_girl_boy": "👩\u200d👧\u200d👦",
+841	    "family_woman_girl_girl": "👩\u200d👧\u200d👧",
+842	    "family_woman_woman_boy": "👩\u200d👩\u200d👦",
+843	    "family_woman_woman_boy_boy": "👩\u200d👩\u200d👦\u200d👦",
+844	    "family_woman_woman_girl": "👩\u200d👩\u200d👧",
+845	    "family_woman_woman_girl_boy": "👩\u200d👩\u200d👧\u200d👦",
+846	    "family_woman_woman_girl_girl": "👩\u200d👩\u200d👧\u200d👧",
+847	    "fast-forward_button": "⏩",
+848	    "fast_down_button": "⏬",
+849	    "fast_reverse_button": "⏪",
+850	    "fast_up_button": "⏫",
+851	    "fax_machine": "📠",
+852	    "fearful_face": "😨",
+853	    "female_sign": "♀",
+854	    "ferris_wheel": "🎡",
+855	    "ferry": "⛴",
+856	    "field_hockey": "🏑",
+857	    "file_cabinet": "🗄",
+858	    "file_folder": "📁",
+859	    "film_frames": "🎞",
+860	    "film_projector": "📽",
+861	    "fire": "🔥",
+862	    "fire_extinguisher": "🧯",
+863	    "firecracker": "🧨",
+864	    "fire_engine": "🚒",
+865	    "fireworks": "🎆",
+866	    "first_quarter_moon": "🌓",
+867	    "first_quarter_moon_face": "🌛",
+868	    "fish": "🐟",
+869	    "fish_cake_with_swirl": "🍥",
+870	    "fishing_pole": "🎣",
+871	    "five-thirty": "🕠",
+872	    "five_o’clock": "🕔",
+873	    "flag_in_hole": "⛳",
+874	    "flamingo": "🦩",
+875	    "flashlight": "🔦",
+876	    "flat_shoe": "🥿",
+877	    "fleur-de-lis": "⚜",
+878	    "flexed_biceps": "💪",
+879	    "flexed_biceps_dark_skin_tone": "💪🏿",
+880	    "flexed_biceps_light_skin_tone": "💪🏻",
+881	    "flexed_biceps_medium-dark_skin_tone": "💪🏾",
+882	    "flexed_biceps_medium-light_skin_tone": "💪🏼",
+883	    "flexed_biceps_medium_skin_tone": "💪🏽",
+884	    "floppy_disk": "💾",
+885	    "flower_playing_cards": "🎴",
+886	    "flushed_face": "😳",
+887	    "flying_disc": "🥏",
+888	    "flying_saucer": "🛸",
+889	    "fog": "🌫",
+890	    "foggy": "🌁",
+891	    "folded_hands": "🙏",
+892	    "folded_hands_dark_skin_tone": "🙏🏿",
+893	    "folded_hands_light_skin_tone": "🙏🏻",
+894	    "folded_hands_medium-dark_skin_tone": "🙏🏾",
+895	    "folded_hands_medium-light_skin_tone": "🙏🏼",
+896	    "folded_hands_medium_skin_tone": "🙏🏽",
+897	    "foot": "🦶",
+898	    "footprints": "👣",
+899	    "fork_and_knife": "🍴",
+900	    "fork_and_knife_with_plate": "🍽",
+901	    "fortune_cookie": "🥠",
+902	    "fountain": "⛲",
+903	    "fountain_pen": "🖋",
+904	    "four-thirty": "🕟",
+905	    "four_leaf_clover": "🍀",
+906	    "four_o’clock": "🕓",
+907	    "fox_face": "🦊",
+908	    "framed_picture": "🖼",
+909	    "french_fries": "🍟",
+910	    "fried_shrimp": "🍤",
+911	    "frog_face": "🐸",
+912	    "front-facing_baby_chick": "🐥",
+913	    "frowning_face": "☹",
+914	    "frowning_face_with_open_mouth": "😦",
+915	    "fuel_pump": "⛽",
+916	    "full_moon": "🌕",
+917	    "full_moon_face": "🌝",
+918	    "funeral_urn": "⚱",
+919	    "game_die": "🎲",
+920	    "garlic": "🧄",
+921	    "gear": "⚙",
+922	    "gem_stone": "💎",
+923	    "genie": "🧞",
+924	    "ghost": "👻",
+925	    "giraffe": "🦒",
+926	    "girl": "👧",
+927	    "girl_dark_skin_tone": "👧🏿",
+928	    "girl_light_skin_tone": "👧🏻",
+929	    "girl_medium-dark_skin_tone": "👧🏾",
+930	    "girl_medium-light_skin_tone": "👧🏼",
+931	    "girl_medium_skin_tone": "👧🏽",
+932	    "glass_of_milk": "🥛",
+933	    "glasses": "👓",
+934	    "globe_showing_americas": "🌎",
+935	    "globe_showing_asia-australia": "🌏",
+936	    "globe_showing_europe-africa": "🌍",
+937	    "globe_with_meridians": "🌐",
+938	    "gloves": "🧤",
+939	    "glowing_star": "🌟",
+940	    "goal_net": "🥅",
+941	    "goat": "🐐",
+942	    "goblin": "👺",
+943	    "goggles": "🥽",
+944	    "gorilla": "🦍",
+945	    "graduation_cap": "🎓",
+946	    "grapes": "🍇",
+947	    "green_apple": "🍏",
+948	    "green_book": "📗",
+949	    "green_circle": "🟢",
+950	    "green_heart": "💚",
+951	    "green_salad": "🥗",
+952	    "green_square": "🟩",
+953	    "grimacing_face": "😬",
+954	    "grinning_cat_face": "😺",
+955	    "grinning_cat_face_with_smiling_eyes": "😸",
+956	    "grinning_face": "😀",
+957	    "grinning_face_with_big_eyes": "😃",
+958	    "grinning_face_with_smiling_eyes": "😄",
+959	    "grinning_face_with_sweat": "😅",
+960	    "grinning_squinting_face": "😆",
+961	    "growing_heart": "💗",
+962	    "guard": "💂",
+963	    "guard_dark_skin_tone": "💂🏿",
+964	    "guard_light_skin_tone": "💂🏻",
+965	    "guard_medium-dark_skin_tone": "💂🏾",
+966	    "guard_medium-light_skin_tone": "💂🏼",
+967	    "guard_medium_skin_tone": "💂🏽",
+968	    "guide_dog": "🦮",
+969	    "guitar": "🎸",
+970	    "hamburger": "🍔",
+971	    "hammer": "🔨",
+972	    "hammer_and_pick": "⚒",
+973	    "hammer_and_wrench": "🛠",
+974	    "hamster_face": "🐹",
+975	    "hand_with_fingers_splayed": "🖐",
+976	    "hand_with_fingers_splayed_dark_skin_tone": "🖐🏿",
+977	    "hand_with_fingers_splayed_light_skin_tone": "🖐🏻",
+978	    "hand_with_fingers_splayed_medium-dark_skin_tone": "🖐🏾",
+979	    "hand_with_fingers_splayed_medium-light_skin_tone": "🖐🏼",
+980	    "hand_with_fingers_splayed_medium_skin_tone": "🖐🏽",
+981	    "handbag": "👜",
+982	    "handshake": "🤝",
+983	    "hatching_chick": "🐣",
+984	    "headphone": "🎧",
+985	    "hear-no-evil_monkey": "🙉",
+986	    "heart_decoration": "💟",
+987	    "heart_suit": "♥",
+988	    "heart_with_arrow": "💘",
+989	    "heart_with_ribbon": "💝",
+990	    "heavy_check_mark": "✔",
+991	    "heavy_division_sign": "➗",
+992	    "heavy_dollar_sign": "💲",
+993	    "heavy_heart_exclamation": "❣",
+994	    "heavy_large_circle": "⭕",
+995	    "heavy_minus_sign": "➖",
+996	    "heavy_multiplication_x": "✖",
+997	    "heavy_plus_sign": "➕",
+998	    "hedgehog": "🦔",
+999	    "helicopter": "🚁",
+1000	    "herb": "🌿",
+1001	    "hibiscus": "🌺",
+1002	    "high-heeled_shoe": "👠",
+1003	    "high-speed_train": "🚄",
+1004	    "high_voltage": "⚡",
+1005	    "hiking_boot": "🥾",
+1006	    "hindu_temple": "🛕",
+1007	    "hippopotamus": "🦛",
+1008	    "hole": "🕳",
+1009	    "honey_pot": "🍯",
+1010	    "honeybee": "🐝",
+1011	    "horizontal_traffic_light": "🚥",
+1012	    "horse": "🐴",
+1013	    "horse_face": "🐴",
+1014	    "horse_racing": "🏇",
+1015	    "horse_racing_dark_skin_tone": "🏇🏿",
+1016	    "horse_racing_light_skin_tone": "🏇🏻",
+1017	    "horse_racing_medium-dark_skin_tone": "🏇🏾",
+1018	    "horse_racing_medium-light_skin_tone": "🏇🏼",
+1019	    "horse_racing_medium_skin_tone": "🏇🏽",
+1020	    "hospital": "🏥",
+1021	    "hot_beverage": "☕",
+1022	    "hot_dog": "🌭",
+1023	    "hot_face": "🥵",
+1024	    "hot_pepper": "🌶",
+1025	    "hot_springs": "♨",
+1026	    "hotel": "🏨",
+1027	    "hourglass_done": "⌛",
+1028	    "hourglass_not_done": "⏳",
+1029	    "house": "🏠",
+1030	    "house_with_garden": "🏡",
+1031	    "houses": "🏘",
+1032	    "hugging_face": "🤗",
+1033	    "hundred_points": "💯",
+1034	    "hushed_face": "😯",
+1035	    "ice": "🧊",
+1036	    "ice_cream": "🍨",
+1037	    "ice_hockey": "🏒",
+1038	    "ice_skate": "⛸",
+1039	    "inbox_tray": "📥",
+1040	    "incoming_envelope": "📨",
+1041	    "index_pointing_up": "☝",
+1042	    "index_pointing_up_dark_skin_tone": "☝🏿",
+1043	    "index_pointing_up_light_skin_tone": "☝🏻",
+1044	    "index_pointing_up_medium-dark_skin_tone": "☝🏾",
+1045	    "index_pointing_up_medium-light_skin_tone": "☝🏼",
+1046	    "index_pointing_up_medium_skin_tone": "☝🏽",
+1047	    "infinity": "♾",
+1048	    "information": "ℹ",
+1049	    "input_latin_letters": "🔤",
+1050	    "input_latin_lowercase": "🔡",
+1051	    "input_latin_uppercase": "🔠",
+1052	    "input_numbers": "🔢",
+1053	    "input_symbols": "🔣",
+1054	    "jack-o-lantern": "🎃",
+1055	    "jeans": "👖",
+1056	    "jigsaw": "🧩",
+1057	    "joker": "🃏",
+1058	    "joystick": "🕹",
+1059	    "kaaba": "🕋",
+1060	    "kangaroo": "🦘",
+1061	    "key": "🔑",
+1062	    "keyboard": "⌨",
+1063	    "keycap_#": "#️⃣",
+1064	    "keycap_*": "*️⃣",
+1065	    "keycap_0": "0️⃣",
+1066	    "keycap_1": "1️⃣",
+1067	    "keycap_10": "🔟",
+1068	    "keycap_2": "2️⃣",
+1069	    "keycap_3": "3️⃣",
+1070	    "keycap_4": "4️⃣",
+1071	    "keycap_5": "5️⃣",
+1072	    "keycap_6": "6️⃣",
+1073	    "keycap_7": "7️⃣",
+1074	    "keycap_8": "8️⃣",
+1075	    "keycap_9": "9️⃣",
+1076	    "kick_scooter": "🛴",
+1077	    "kimono": "👘",
+1078	    "kiss": "💋",
+1079	    "kiss_man_man": "👨\u200d❤️\u200d💋\u200d👨",
+1080	    "kiss_mark": "💋",
+1081	    "kiss_woman_man": "👩\u200d❤️\u200d💋\u200d👨",
+1082	    "kiss_woman_woman": "👩\u200d❤️\u200d💋\u200d👩",
+1083	    "kissing_cat_face": "😽",
+1084	    "kissing_face": "😗",
+1085	    "kissing_face_with_closed_eyes": "😚",
+1086	    "kissing_face_with_smiling_eyes": "😙",
+1087	    "kitchen_knife": "🔪",
+1088	    "kite": "🪁",
+1089	    "kiwi_fruit": "🥝",
+1090	    "koala": "🐨",
+1091	    "lab_coat": "🥼",
+1092	    "label": "🏷",
+1093	    "lacrosse": "🥍",
+1094	    "lady_beetle": "🐞",
+1095	    "laptop_computer": "💻",
+1096	    "large_blue_diamond": "🔷",
+1097	    "large_orange_diamond": "🔶",
+1098	    "last_quarter_moon": "🌗",
+1099	    "last_quarter_moon_face": "🌜",
+1100	    "last_track_button": "⏮",
+1101	    "latin_cross": "✝",
+1102	    "leaf_fluttering_in_wind": "🍃",
+1103	    "leafy_green": "🥬",
+1104	    "ledger": "📒",
+1105	    "left-facing_fist": "🤛",
+1106	    "left-facing_fist_dark_skin_tone": "🤛🏿",
+1107	    "left-facing_fist_light_skin_tone": "🤛🏻",
+1108	    "left-facing_fist_medium-dark_skin_tone": "🤛🏾",
+1109	    "left-facing_fist_medium-light_skin_tone": "🤛🏼",
+1110	    "left-facing_fist_medium_skin_tone": "🤛🏽",
+1111	    "left-right_arrow": "↔",
+1112	    "left_arrow": "⬅",
+1113	    "left_arrow_curving_right": "↪",
+1114	    "left_luggage": "🛅",
+1115	    "left_speech_bubble": "🗨",
+1116	    "leg": "🦵",
+1117	    "lemon": "🍋",
+1118	    "leopard": "🐆",
+1119	    "level_slider": "🎚",
+1120	    "light_bulb": "💡",
+1121	    "light_rail": "🚈",
+1122	    "link": "🔗",
+1123	    "linked_paperclips": "🖇",
+1124	    "lion_face": "🦁",
+1125	    "lipstick": "💄",
+1126	    "litter_in_bin_sign": "🚮",
+1127	    "lizard": "🦎",
+1128	    "llama": "🦙",
+1129	    "lobster": "🦞",
+1130	    "locked": "🔒",
+1131	    "locked_with_key": "🔐",
+1132	    "locked_with_pen": "🔏",
+1133	    "locomotive": "🚂",
+1134	    "lollipop": "🍭",
+1135	    "lotion_bottle": "🧴",
+1136	    "loudly_crying_face": "😭",
+1137	    "loudspeaker": "📢",
+1138	    "love-you_gesture": "🤟",
+1139	    "love-you_gesture_dark_skin_tone": "🤟🏿",
+1140	    "love-you_gesture_light_skin_tone": "🤟🏻",
+1141	    "love-you_gesture_medium-dark_skin_tone": "🤟🏾",
+1142	    "love-you_gesture_medium-light_skin_tone": "🤟🏼",
+1143	    "love-you_gesture_medium_skin_tone": "🤟🏽",
+1144	    "love_hotel": "🏩",
+1145	    "love_letter": "💌",
+1146	    "luggage": "🧳",
+1147	    "lying_face": "🤥",
+1148	    "mage": "🧙",
+1149	    "mage_dark_skin_tone": "🧙🏿",
+1150	    "mage_light_skin_tone": "🧙🏻",
+1151	    "mage_medium-dark_skin_tone": "🧙🏾",
+1152	    "mage_medium-light_skin_tone": "🧙🏼",
+1153	    "mage_medium_skin_tone": "🧙🏽",
+1154	    "magnet": "🧲",
+1155	    "magnifying_glass_tilted_left": "🔍",
+1156	    "magnifying_glass_tilted_right": "🔎",
+1157	    "mahjong_red_dragon": "🀄",
+1158	    "male_sign": "♂",
+1159	    "man": "👨",
+1160	    "man_and_woman_holding_hands": "👫",
+1161	    "man_artist": "👨\u200d🎨",
+1162	    "man_artist_dark_skin_tone": "👨🏿\u200d🎨",
+1163	    "man_artist_light_skin_tone": "👨🏻\u200d🎨",
+1164	    "man_artist_medium-dark_skin_tone": "👨🏾\u200d🎨",
+1165	    "man_artist_medium-light_skin_tone": "👨🏼\u200d🎨",
+1166	    "man_artist_medium_skin_tone": "👨🏽\u200d🎨",
+1167	    "man_astronaut": "👨\u200d🚀",
+1168	    "man_astronaut_dark_skin_tone": "👨🏿\u200d🚀",
+1169	    "man_astronaut_light_skin_tone": "👨🏻\u200d🚀",
+1170	    "man_astronaut_medium-dark_skin_tone": "👨🏾\u200d🚀",
+1171	    "man_astronaut_medium-light_skin_tone": "👨🏼\u200d🚀",
+1172	    "man_astronaut_medium_skin_tone": "👨🏽\u200d🚀",
+1173	    "man_biking": "🚴\u200d♂️",
+1174	    "man_biking_dark_skin_tone": "🚴🏿\u200d♂️",
+1175	    "man_biking_light_skin_tone": "🚴🏻\u200d♂️",
+1176	    "man_biking_medium-dark_skin_tone": "🚴🏾\u200d♂️",
+1177	    "man_biking_medium-light_skin_tone": "🚴🏼\u200d♂️",
+1178	    "man_biking_medium_skin_tone": "🚴🏽\u200d♂️",
+1179	    "man_bouncing_ball": "⛹️\u200d♂️",
+1180	    "man_bouncing_ball_dark_skin_tone": "⛹🏿\u200d♂️",
+1181	    "man_bouncing_ball_light_skin_tone": "⛹🏻\u200d♂️",
+1182	    "man_bouncing_ball_medium-dark_skin_tone": "⛹🏾\u200d♂️",
+1183	    "man_bouncing_ball_medium-light_skin_tone": "⛹🏼\u200d♂️",
+1184	    "man_bouncing_ball_medium_skin_tone": "⛹🏽\u200d♂️",
+1185	    "man_bowing": "🙇\u200d♂️",
+1186	    "man_bowing_dark_skin_tone": "🙇🏿\u200d♂️",
+1187	    "man_bowing_light_skin_tone": "🙇🏻\u200d♂️",
+1188	    "man_bowing_medium-dark_skin_tone": "🙇🏾\u200d♂️",
+1189	    "man_bowing_medium-light_skin_tone": "🙇🏼\u200d♂️",
+1190	    "man_bowing_medium_skin_tone": "🙇🏽\u200d♂️",
+1191	    "man_cartwheeling": "🤸\u200d♂️",
+1192	    "man_cartwheeling_dark_skin_tone": "🤸🏿\u200d♂️",
+1193	    "man_cartwheeling_light_skin_tone": "🤸🏻\u200d♂️",
+1194	    "man_cartwheeling_medium-dark_skin_tone": "🤸🏾\u200d♂️",
+1195	    "man_cartwheeling_medium-light_skin_tone": "🤸🏼\u200d♂️",
+1196	    "man_cartwheeling_medium_skin_tone": "🤸🏽\u200d♂️",
+1197	    "man_climbing": "🧗\u200d♂️",
+1198	    "man_climbing_dark_skin_tone": "🧗🏿\u200d♂️",
+1199	    "man_climbing_light_skin_tone": "🧗🏻\u200d♂️",
+1200	    "man_climbing_medium-dark_skin_tone": "🧗🏾\u200d♂️",
+1201	    "man_climbing_medium-light_skin_tone": "🧗🏼\u200d♂️",
+1202	    "man_climbing_medium_skin_tone": "🧗🏽\u200d♂️",
+1203	    "man_construction_worker": "👷\u200d♂️",
+1204	    "man_construction_worker_dark_skin_tone": "👷🏿\u200d♂️",
+1205	    "man_construction_worker_light_skin_tone": "👷🏻\u200d♂️",
+1206	    "man_construction_worker_medium-dark_skin_tone": "👷🏾\u200d♂️",
+1207	    "man_construction_worker_medium-light_skin_tone": "👷🏼\u200d♂️",
+1208	    "man_construction_worker_medium_skin_tone": "👷🏽\u200d♂️",
+1209	    "man_cook": "👨\u200d🍳",
+1210	    "man_cook_dark_skin_tone": "👨🏿\u200d🍳",
+1211	    "man_cook_light_skin_tone": "👨🏻\u200d🍳",
+1212	    "man_cook_medium-dark_skin_tone": "👨🏾\u200d🍳",
+1213	    "man_cook_medium-light_skin_tone": "👨🏼\u200d🍳",
+1214	    "man_cook_medium_skin_tone": "👨🏽\u200d🍳",
+1215	    "man_dancing": "🕺",
+1216	    "man_dancing_dark_skin_tone": "🕺🏿",
+1217	    "man_dancing_light_skin_tone": "🕺🏻",
+1218	    "man_dancing_medium-dark_skin_tone": "🕺🏾",
+1219	    "man_dancing_medium-light_skin_tone": "🕺🏼",
+1220	    "man_dancing_medium_skin_tone": "🕺🏽",
+1221	    "man_dark_skin_tone": "👨🏿",
+1222	    "man_detective": "🕵️\u200d♂️",
+1223	    "man_detective_dark_skin_tone": "🕵🏿\u200d♂️",
+1224	    "man_detective_light_skin_tone": "🕵🏻\u200d♂️",
+1225	    "man_detective_medium-dark_skin_tone": "🕵🏾\u200d♂️",
+1226	    "man_detective_medium-light_skin_tone": "🕵🏼\u200d♂️",
+1227	    "man_detective_medium_skin_tone": "🕵🏽\u200d♂️",
+1228	    "man_elf": "🧝\u200d♂️",
+1229	    "man_elf_dark_skin_tone": "🧝🏿\u200d♂️",
+1230	    "man_elf_light_skin_tone": "🧝🏻\u200d♂️",
+1231	    "man_elf_medium-dark_skin_tone": "🧝🏾\u200d♂️",
+1232	    "man_elf_medium-light_skin_tone": "🧝🏼\u200d♂️",
+1233	    "man_elf_medium_skin_tone": "🧝🏽\u200d♂️",
+1234	    "man_facepalming": "🤦\u200d♂️",
+1235	    "man_facepalming_dark_skin_tone": "🤦🏿\u200d♂️",
+1236	    "man_facepalming_light_skin_tone": "🤦🏻\u200d♂️",
+1237	    "man_facepalming_medium-dark_skin_tone": "🤦🏾\u200d♂️",
+1238	    "man_facepalming_medium-light_skin_tone": "🤦🏼\u200d♂️",
+1239	    "man_facepalming_medium_skin_tone": "🤦🏽\u200d♂️",
+1240	    "man_factory_worker": "👨\u200d🏭",
+1241	    "man_factory_worker_dark_skin_tone": "👨🏿\u200d🏭",
+1242	    "man_factory_worker_light_skin_tone": "👨🏻\u200d🏭",
+1243	    "man_factory_worker_medium-dark_skin_tone": "👨🏾\u200d🏭",
+1244	    "man_factory_worker_medium-light_skin_tone": "👨🏼\u200d🏭",
+1245	    "man_factory_worker_medium_skin_tone": "👨🏽\u200d🏭",
+1246	    "man_fairy": "🧚\u200d♂️",
+1247	    "man_fairy_dark_skin_tone": "🧚🏿\u200d♂️",
+1248	    "man_fairy_light_skin_tone": "🧚🏻\u200d♂️",
+1249	    "man_fairy_medium-dark_skin_tone": "🧚🏾\u200d♂️",
+1250	    "man_fairy_medium-light_skin_tone": "🧚🏼\u200d♂️",
+1251	    "man_fairy_medium_skin_tone": "🧚🏽\u200d♂️",
+1252	    "man_farmer": "👨\u200d🌾",
+1253	    "man_farmer_dark_skin_tone": "👨🏿\u200d🌾",
+1254	    "man_farmer_light_skin_tone": "👨🏻\u200d🌾",
+1255	    "man_farmer_medium-dark_skin_tone": "👨🏾\u200d🌾",
+1256	    "man_farmer_medium-light_skin_tone": "👨🏼\u200d🌾",
+1257	    "man_farmer_medium_skin_tone": "👨🏽\u200d🌾",
+1258	    "man_firefighter": "👨\u200d🚒",
+1259	    "man_firefighter_dark_skin_tone": "👨🏿\u200d🚒",
+1260	    "man_firefighter_light_skin_tone": "👨🏻\u200d🚒",
+1261	    "man_firefighter_medium-dark_skin_tone": "👨🏾\u200d🚒",
+1262	    "man_firefighter_medium-light_skin_tone": "👨🏼\u200d🚒",
+1263	    "man_firefighter_medium_skin_tone": "👨🏽\u200d🚒",
+1264	    "man_frowning": "🙍\u200d♂️",
+1265	    "man_frowning_dark_skin_tone": "🙍🏿\u200d♂️",
+1266	    "man_frowning_light_skin_tone": "🙍🏻\u200d♂️",
+1267	    "man_frowning_medium-dark_skin_tone": "🙍🏾\u200d♂️",
+1268	    "man_frowning_medium-light_skin_tone": "🙍🏼\u200d♂️",
+1269	    "man_frowning_medium_skin_tone": "🙍🏽\u200d♂️",
+1270	    "man_genie": "🧞\u200d♂️",
+1271	    "man_gesturing_no": "🙅\u200d♂️",
+1272	    "man_gesturing_no_dark_skin_tone": "🙅🏿\u200d♂️",
+1273	    "man_gesturing_no_light_skin_tone": "🙅🏻\u200d♂️",
+1274	    "man_gesturing_no_medium-dark_skin_tone": "🙅🏾\u200d♂️",
+1275	    "man_gesturing_no_medium-light_skin_tone": "🙅🏼\u200d♂️",
+1276	    "man_gesturing_no_medium_skin_tone": "🙅🏽\u200d♂️",
+1277	    "man_gesturing_ok": "🙆\u200d♂️",
+1278	    "man_gesturing_ok_dark_skin_tone": "🙆🏿\u200d♂️",
+1279	    "man_gesturing_ok_light_skin_tone": "🙆🏻\u200d♂️",
+1280	    "man_gesturing_ok_medium-dark_skin_tone": "🙆🏾\u200d♂️",
+1281	    "man_gesturing_ok_medium-light_skin_tone": "🙆🏼\u200d♂️",
+1282	    "man_gesturing_ok_medium_skin_tone": "🙆🏽\u200d♂️",
+1283	    "man_getting_haircut": "💇\u200d♂️",
+1284	    "man_getting_haircut_dark_skin_tone": "💇🏿\u200d♂️",
+1285	    "man_getting_haircut_light_skin_tone": "💇🏻\u200d♂️",
+1286	    "man_getting_haircut_medium-dark_skin_tone": "💇🏾\u200d♂️",
+1287	    "man_getting_haircut_medium-light_skin_tone": "💇🏼\u200d♂️",
+1288	    "man_getting_haircut_medium_skin_tone": "💇🏽\u200d♂️",
+1289	    "man_getting_massage": "💆\u200d♂️",
+1290	    "man_getting_massage_dark_skin_tone": "💆🏿\u200d♂️",
+1291	    "man_getting_massage_light_skin_tone": "💆🏻\u200d♂️",
+1292	    "man_getting_massage_medium-dark_skin_tone": "💆🏾\u200d♂️",
+1293	    "man_getting_massage_medium-light_skin_tone": "💆🏼\u200d♂️",
+1294	    "man_getting_massage_medium_skin_tone": "💆🏽\u200d♂️",
+1295	    "man_golfing": "🏌️\u200d♂️",
+1296	    "man_golfing_dark_skin_tone": "🏌🏿\u200d♂️",
+1297	    "man_golfing_light_skin_tone": "🏌🏻\u200d♂️",
+1298	    "man_golfing_medium-dark_skin_tone": "🏌🏾\u200d♂️",
+1299	    "man_golfing_medium-light_skin_tone": "🏌🏼\u200d♂️",
+1300	    "man_golfing_medium_skin_tone": "🏌🏽\u200d♂️",
+1301	    "man_guard": "💂\u200d♂️",
+1302	    "man_guard_dark_skin_tone": "💂🏿\u200d♂️",
+1303	    "man_guard_light_skin_tone": "💂🏻\u200d♂️",
+1304	    "man_guard_medium-dark_skin_tone": "💂🏾\u200d♂️",
+1305	    "man_guard_medium-light_skin_tone": "💂🏼\u200d♂️",
+1306	    "man_guard_medium_skin_tone": "💂🏽\u200d♂️",
+1307	    "man_health_worker": "👨\u200d⚕️",
+1308	    "man_health_worker_dark_skin_tone": "👨🏿\u200d⚕️",
+1309	    "man_health_worker_light_skin_tone": "👨🏻\u200d⚕️",
+1310	    "man_health_worker_medium-dark_skin_tone": "👨🏾\u200d⚕️",
+1311	    "man_health_worker_medium-light_skin_tone": "👨🏼\u200d⚕️",
+1312	    "man_health_worker_medium_skin_tone": "👨🏽\u200d⚕️",
+1313	    "man_in_lotus_position": "🧘\u200d♂️",
+1314	    "man_in_lotus_position_dark_skin_tone": "🧘🏿\u200d♂️",
+1315	    "man_in_lotus_position_light_skin_tone": "🧘🏻\u200d♂️",
+1316	    "man_in_lotus_position_medium-dark_skin_tone": "🧘🏾\u200d♂️",
+1317	    "man_in_lotus_position_medium-light_skin_tone": "🧘🏼\u200d♂️",
+1318	    "man_in_lotus_position_medium_skin_tone": "🧘🏽\u200d♂️",
+1319	    "man_in_manual_wheelchair": "👨\u200d🦽",
+1320	    "man_in_motorized_wheelchair": "👨\u200d🦼",
+1321	    "man_in_steamy_room": "🧖\u200d♂️",
+1322	    "man_in_steamy_room_dark_skin_tone": "🧖🏿\u200d♂️",
+1323	    "man_in_steamy_room_light_skin_tone": "🧖🏻\u200d♂️",
+1324	    "man_in_steamy_room_medium-dark_skin_tone": "🧖🏾\u200d♂️",
+1325	    "man_in_steamy_room_medium-light_skin_tone": "🧖🏼\u200d♂️",
+1326	    "man_in_steamy_room_medium_skin_tone": "🧖🏽\u200d♂️",
+1327	    "man_in_suit_levitating": "🕴",
+1328	    "man_in_suit_levitating_dark_skin_tone": "🕴🏿",
+1329	    "man_in_suit_levitating_light_skin_tone": "🕴🏻",
+1330	    "man_in_suit_levitating_medium-dark_skin_tone": "🕴🏾",
+1331	    "man_in_suit_levitating_medium-light_skin_tone": "🕴🏼",
+1332	    "man_in_suit_levitating_medium_skin_tone": "🕴🏽",
+1333	    "man_in_tuxedo": "🤵",
+1334	    "man_in_tuxedo_dark_skin_tone": "🤵🏿",
+1335	    "man_in_tuxedo_light_skin_tone": "🤵🏻",
+1336	    "man_in_tuxedo_medium-dark_skin_tone": "🤵🏾",
+1337	    "man_in_tuxedo_medium-light_skin_tone": "🤵🏼",
+1338	    "man_in_tuxedo_medium_skin_tone": "🤵🏽",
+1339	    "man_judge": "👨\u200d⚖️",
+1340	    "man_judge_dark_skin_tone": "👨🏿\u200d⚖️",
+1341	    "man_judge_light_skin_tone": "👨🏻\u200d⚖️",
+1342	    "man_judge_medium-dark_skin_tone": "👨🏾\u200d⚖️",
+1343	    "man_judge_medium-light_skin_tone": "👨🏼\u200d⚖️",
+1344	    "man_judge_medium_skin_tone": "👨🏽\u200d⚖️",
+1345	    "man_juggling": "🤹\u200d♂️",
+1346	    "man_juggling_dark_skin_tone": "🤹🏿\u200d♂️",
+1347	    "man_juggling_light_skin_tone": "🤹🏻\u200d♂️",
+1348	    "man_juggling_medium-dark_skin_tone": "🤹🏾\u200d♂️",
+1349	    "man_juggling_medium-light_skin_tone": "🤹🏼\u200d♂️",
+1350	    "man_juggling_medium_skin_tone": "🤹🏽\u200d♂️",
+1351	    "man_lifting_weights": "🏋️\u200d♂️",
+1352	    "man_lifting_weights_dark_skin_tone": "🏋🏿\u200d♂️",
+1353	    "man_lifting_weights_light_skin_tone": "🏋🏻\u200d♂️",
+1354	    "man_lifting_weights_medium-dark_skin_tone": "🏋🏾\u200d♂️",
+1355	    "man_lifting_weights_medium-light_skin_tone": "🏋🏼\u200d♂️",
+1356	    "man_lifting_weights_medium_skin_tone": "🏋🏽\u200d♂️",
+1357	    "man_light_skin_tone": "👨🏻",
+1358	    "man_mage": "🧙\u200d♂️",
+1359	    "man_mage_dark_skin_tone": "🧙🏿\u200d♂️",
+1360	    "man_mage_light_skin_tone": "🧙🏻\u200d♂️",
+1361	    "man_mage_medium-dark_skin_tone": "🧙🏾\u200d♂️",
+1362	    "man_mage_medium-light_skin_tone": "🧙🏼\u200d♂️",
+1363	    "man_mage_medium_skin_tone": "🧙🏽\u200d♂️",
+1364	    "man_mechanic": "👨\u200d🔧",
+1365	    "man_mechanic_dark_skin_tone": "👨🏿\u200d🔧",
+1366	    "man_mechanic_light_skin_tone": "👨🏻\u200d🔧",
+1367	    "man_mechanic_medium-dark_skin_tone": "👨🏾\u200d🔧",
+1368	    "man_mechanic_medium-light_skin_tone": "👨🏼\u200d🔧",
+1369	    "man_mechanic_medium_skin_tone": "👨🏽\u200d🔧",
+1370	    "man_medium-dark_skin_tone": "👨🏾",
+1371	    "man_medium-light_skin_tone": "👨🏼",
+1372	    "man_medium_skin_tone": "👨🏽",
+1373	    "man_mountain_biking": "🚵\u200d♂️",
+1374	    "man_mountain_biking_dark_skin_tone": "🚵🏿\u200d♂️",
+1375	    "man_mountain_biking_light_skin_tone": "🚵🏻\u200d♂️",
+1376	    "man_mountain_biking_medium-dark_skin_tone": "🚵🏾\u200d♂️",
+1377	    "man_mountain_biking_medium-light_skin_tone": "🚵🏼\u200d♂️",
+1378	    "man_mountain_biking_medium_skin_tone": "🚵🏽\u200d♂️",
+1379	    "man_office_worker": "👨\u200d💼",
+1380	    "man_office_worker_dark_skin_tone": "👨🏿\u200d💼",
+1381	    "man_office_worker_light_skin_tone": "👨🏻\u200d💼",
+1382	    "man_office_worker_medium-dark_skin_tone": "👨🏾\u200d💼",
+1383	    "man_office_worker_medium-light_skin_tone": "👨🏼\u200d💼",
+1384	    "man_office_worker_medium_skin_tone": "👨🏽\u200d💼",
+1385	    "man_pilot": "👨\u200d✈️",
+1386	    "man_pilot_dark_skin_tone": "👨🏿\u200d✈️",
+1387	    "man_pilot_light_skin_tone": "👨🏻\u200d✈️",
+1388	    "man_pilot_medium-dark_skin_tone": "👨🏾\u200d✈️",
+1389	    "man_pilot_medium-light_skin_tone": "👨🏼\u200d✈️",
+1390	    "man_pilot_medium_skin_tone": "👨🏽\u200d✈️",
+1391	    "man_playing_handball": "🤾\u200d♂️",
+1392	    "man_playing_handball_dark_skin_tone": "🤾🏿\u200d♂️",
+1393	    "man_playing_handball_light_skin_tone": "🤾🏻\u200d♂️",
+1394	    "man_playing_handball_medium-dark_skin_tone": "🤾🏾\u200d♂️",
+1395	    "man_playing_handball_medium-light_skin_tone": "🤾🏼\u200d♂️",
+1396	    "man_playing_handball_medium_skin_tone": "🤾🏽\u200d♂️",
+1397	    "man_playing_water_polo": "🤽\u200d♂️",
+1398	    "man_playing_water_polo_dark_skin_tone": "🤽🏿\u200d♂️",
+1399	    "man_playing_water_polo_light_skin_tone": "🤽🏻\u200d♂️",
+1400	    "man_playing_water_polo_medium-dark_skin_tone": "🤽🏾\u200d♂️",
+1401	    "man_playing_water_polo_medium-light_skin_tone": "🤽🏼\u200d♂️",
+1402	    "man_playing_water_polo_medium_skin_tone": "🤽🏽\u200d♂️",
+1403	    "man_police_officer": "👮\u200d♂️",
+1404	    "man_police_officer_dark_skin_tone": "👮🏿\u200d♂️",
+1405	    "man_police_officer_light_skin_tone": "👮🏻\u200d♂️",
+1406	    "man_police_officer_medium-dark_skin_tone": "👮🏾\u200d♂️",
+1407	    "man_police_officer_medium-light_skin_tone": "👮🏼\u200d♂️",
+1408	    "man_police_officer_medium_skin_tone": "👮🏽\u200d♂️",
+1409	    "man_pouting": "🙎\u200d♂️",
+1410	    "man_pouting_dark_skin_tone": "🙎🏿\u200d♂️",
+1411	    "man_pouting_light_skin_tone": "🙎🏻\u200d♂️",
+1412	    "man_pouting_medium-dark_skin_tone": "🙎🏾\u200d♂️",
+1413	    "man_pouting_medium-light_skin_tone": "🙎🏼\u200d♂️",
+1414	    "man_pouting_medium_skin_tone": "🙎🏽\u200d♂️",
+1415	    "man_raising_hand": "🙋\u200d♂️",
+1416	    "man_raising_hand_dark_skin_tone": "🙋🏿\u200d♂️",
+1417	    "man_raising_hand_light_skin_tone": "🙋🏻\u200d♂️",
+1418	    "man_raising_hand_medium-dark_skin_tone": "🙋🏾\u200d♂️",
+1419	    "man_raising_hand_medium-light_skin_tone": "🙋🏼\u200d♂️",
+1420	    "man_raising_hand_medium_skin_tone": "🙋🏽\u200d♂️",
+1421	    "man_rowing_boat": "🚣\u200d♂️",
+1422	    "man_rowing_boat_dark_skin_tone": "🚣🏿\u200d♂️",
+1423	    "man_rowing_boat_light_skin_tone": "🚣🏻\u200d♂️",
+1424	    "man_rowing_boat_medium-dark_skin_tone": "🚣🏾\u200d♂️",
+1425	    "man_rowing_boat_medium-light_skin_tone": "🚣🏼\u200d♂️",
+1426	    "man_rowing_boat_medium_skin_tone": "🚣🏽\u200d♂️",
+1427	    "man_running": "🏃\u200d♂️",
+1428	    "man_running_dark_skin_tone": "🏃🏿\u200d♂️",
+1429	    "man_running_light_skin_tone": "🏃🏻\u200d♂️",
+1430	    "man_running_medium-dark_skin_tone": "🏃🏾\u200d♂️",
+1431	    "man_running_medium-light_skin_tone": "🏃🏼\u200d♂️",
+1432	    "man_running_medium_skin_tone": "🏃🏽\u200d♂️",
+1433	    "man_scientist": "👨\u200d🔬",
+1434	    "man_scientist_dark_skin_tone": "👨🏿\u200d🔬",
+1435	    "man_scientist_light_skin_tone": "👨🏻\u200d🔬",
+1436	    "man_scientist_medium-dark_skin_tone": "👨🏾\u200d🔬",
+1437	    "man_scientist_medium-light_skin_tone": "👨🏼\u200d🔬",
+1438	    "man_scientist_medium_skin_tone": "👨🏽\u200d🔬",
+1439	    "man_shrugging": "🤷\u200d♂️",
+1440	    "man_shrugging_dark_skin_tone": "🤷🏿\u200d♂️",
+1441	    "man_shrugging_light_skin_tone": "🤷🏻\u200d♂️",
+1442	    "man_shrugging_medium-dark_skin_tone": "🤷🏾\u200d♂️",
+1443	    "man_shrugging_medium-light_skin_tone": "🤷🏼\u200d♂️",
+1444	    "man_shrugging_medium_skin_tone": "🤷🏽\u200d♂️",
+1445	    "man_singer": "👨\u200d🎤",
+1446	    "man_singer_dark_skin_tone": "👨🏿\u200d🎤",
+1447	    "man_singer_light_skin_tone": "👨🏻\u200d🎤",
+1448	    "man_singer_medium-dark_skin_tone": "👨🏾\u200d🎤",
+1449	    "man_singer_medium-light_skin_tone": "👨🏼\u200d🎤",
+1450	    "man_singer_medium_skin_tone": "👨🏽\u200d🎤",
+1451	    "man_student": "👨\u200d🎓",
+1452	    "man_student_dark_skin_tone": "👨🏿\u200d🎓",
+1453	    "man_student_light_skin_tone": "👨🏻\u200d🎓",
+1454	    "man_student_medium-dark_skin_tone": "👨🏾\u200d🎓",
+1455	    "man_student_medium-light_skin_tone": "👨🏼\u200d🎓",
+1456	    "man_student_medium_skin_tone": "👨🏽\u200d🎓",
+1457	    "man_surfing": "🏄\u200d♂️",
+1458	    "man_surfing_dark_skin_tone": "🏄🏿\u200d♂️",
+1459	    "man_surfing_light_skin_tone": "🏄🏻\u200d♂️",
+1460	    "man_surfing_medium-dark_skin_tone": "🏄🏾\u200d♂️",
+1461	    "man_surfing_medium-light_skin_tone": "🏄🏼\u200d♂️",
+1462	    "man_surfing_medium_skin_tone": "🏄🏽\u200d♂️",
+1463	    "man_swimming": "🏊\u200d♂️",
+1464	    "man_swimming_dark_skin_tone": "🏊🏿\u200d♂️",
+1465	    "man_swimming_light_skin_tone": "🏊🏻\u200d♂️",
+1466	    "man_swimming_medium-dark_skin_tone": "🏊🏾\u200d♂️",
+1467	    "man_swimming_medium-light_skin_tone": "🏊🏼\u200d♂️",
+1468	    "man_swimming_medium_skin_tone": "🏊🏽\u200d♂️",
+1469	    "man_teacher": "👨\u200d🏫",
+1470	    "man_teacher_dark_skin_tone": "👨🏿\u200d🏫",
+1471	    "man_teacher_light_skin_tone": "👨🏻\u200d🏫",
+1472	    "man_teacher_medium-dark_skin_tone": "👨🏾\u200d🏫",
+1473	    "man_teacher_medium-light_skin_tone": "👨🏼\u200d🏫",
+1474	    "man_teacher_medium_skin_tone": "👨🏽\u200d🏫",
+1475	    "man_technologist": "👨\u200d💻",
+1476	    "man_technologist_dark_skin_tone": "👨🏿\u200d💻",
+1477	    "man_technologist_light_skin_tone": "👨🏻\u200d💻",
+1478	    "man_technologist_medium-dark_skin_tone": "👨🏾\u200d💻",
+1479	    "man_technologist_medium-light_skin_tone": "👨🏼\u200d💻",
+1480	    "man_technologist_medium_skin_tone": "👨🏽\u200d💻",
+1481	    "man_tipping_hand": "💁\u200d♂️",
+1482	    "man_tipping_hand_dark_skin_tone": "💁🏿\u200d♂️",
+1483	    "man_tipping_hand_light_skin_tone": "💁🏻\u200d♂️",
+1484	    "man_tipping_hand_medium-dark_skin_tone": "💁🏾\u200d♂️",
+1485	    "man_tipping_hand_medium-light_skin_tone": "💁🏼\u200d♂️",
+1486	    "man_tipping_hand_medium_skin_tone": "💁🏽\u200d♂️",
+1487	    "man_vampire": "🧛\u200d♂️",
+1488	    "man_vampire_dark_skin_tone": "🧛🏿\u200d♂️",
+1489	    "man_vampire_light_skin_tone": "🧛🏻\u200d♂️",
+1490	    "man_vampire_medium-dark_skin_tone": "🧛🏾\u200d♂️",
+1491	    "man_vampire_medium-light_skin_tone": "🧛🏼\u200d♂️",
+1492	    "man_vampire_medium_skin_tone": "🧛🏽\u200d♂️",
+1493	    "man_walking": "🚶\u200d♂️",
+1494	    "man_walking_dark_skin_tone": "🚶🏿\u200d♂️",
+1495	    "man_walking_light_skin_tone": "🚶🏻\u200d♂️",
+1496	    "man_walking_medium-dark_skin_tone": "🚶🏾\u200d♂️",
+1497	    "man_walking_medium-light_skin_tone": "🚶🏼\u200d♂️",
+1498	    "man_walking_medium_skin_tone": "🚶🏽\u200d♂️",
+1499	    "man_wearing_turban": "👳\u200d♂️",
+1500	    "man_wearing_turban_dark_skin_tone": "👳🏿\u200d♂️",
+1501	    "man_wearing_turban_light_skin_tone": "👳🏻\u200d♂️",
+1502	    "man_wearing_turban_medium-dark_skin_tone": "👳🏾\u200d♂️",
+1503	    "man_wearing_turban_medium-light_skin_tone": "👳🏼\u200d♂️",
+1504	    "man_wearing_turban_medium_skin_tone": "👳🏽\u200d♂️",
+1505	    "man_with_probing_cane": "👨\u200d🦯",
+1506	    "man_with_chinese_cap": "👲",
+1507	    "man_with_chinese_cap_dark_skin_tone": "👲🏿",
+1508	    "man_with_chinese_cap_light_skin_tone": "👲🏻",
+1509	    "man_with_chinese_cap_medium-dark_skin_tone": "👲🏾",
+1510	    "man_with_chinese_cap_medium-light_skin_tone": "👲🏼",
+1511	    "man_with_chinese_cap_medium_skin_tone": "👲🏽",
+1512	    "man_zombie": "🧟\u200d♂️",
+1513	    "mango": "🥭",
+1514	    "mantelpiece_clock": "🕰",
+1515	    "manual_wheelchair": "🦽",
+1516	    "man’s_shoe": "👞",
+1517	    "map_of_japan": "🗾",
+1518	    "maple_leaf": "🍁",
+1519	    "martial_arts_uniform": "🥋",
+1520	    "mate": "🧉",
+1521	    "meat_on_bone": "🍖",
+1522	    "mechanical_arm": "🦾",
+1523	    "mechanical_leg": "🦿",
+1524	    "medical_symbol": "⚕",
+1525	    "megaphone": "📣",
+1526	    "melon": "🍈",
+1527	    "memo": "📝",
+1528	    "men_with_bunny_ears": "👯\u200d♂️",
+1529	    "men_wrestling": "🤼\u200d♂️",
+1530	    "menorah": "🕎",
+1531	    "men’s_room": "🚹",
+1532	    "mermaid": "🧜\u200d♀️",
+1533	    "mermaid_dark_skin_tone": "🧜🏿\u200d♀️",
+1534	    "mermaid_light_skin_tone": "🧜🏻\u200d♀️",
+1535	    "mermaid_medium-dark_skin_tone": "🧜🏾\u200d♀️",
+1536	    "mermaid_medium-light_skin_tone": "🧜🏼\u200d♀️",
+1537	    "mermaid_medium_skin_tone": "🧜🏽\u200d♀️",
+1538	    "merman": "🧜\u200d♂️",
+1539	    "merman_dark_skin_tone": "🧜🏿\u200d♂️",
+1540	    "merman_light_skin_tone": "🧜🏻\u200d♂️",
+1541	    "merman_medium-dark_skin_tone": "🧜🏾\u200d♂️",
+1542	    "merman_medium-light_skin_tone": "🧜🏼\u200d♂️",
+1543	    "merman_medium_skin_tone": "🧜🏽\u200d♂️",
+1544	    "merperson": "🧜",
+1545	    "merperson_dark_skin_tone": "🧜🏿",
+1546	    "merperson_light_skin_tone": "🧜🏻",
+1547	    "merperson_medium-dark_skin_tone": "🧜🏾",
+1548	    "merperson_medium-light_skin_tone": "🧜🏼",
+1549	    "merperson_medium_skin_tone": "🧜🏽",
+1550	    "metro": "🚇",
+1551	    "microbe": "🦠",
+1552	    "microphone": "🎤",
+1553	    "microscope": "🔬",
+1554	    "middle_finger": "🖕",
+1555	    "middle_finger_dark_skin_tone": "🖕🏿",
+1556	    "middle_finger_light_skin_tone": "🖕🏻",
+1557	    "middle_finger_medium-dark_skin_tone": "🖕🏾",
+1558	    "middle_finger_medium-light_skin_tone": "🖕🏼",
+1559	    "middle_finger_medium_skin_tone": "🖕🏽",
+1560	    "military_medal": "🎖",
+1561	    "milky_way": "🌌",
+1562	    "minibus": "🚐",
+1563	    "moai": "🗿",
+1564	    "mobile_phone": "📱",
+1565	    "mobile_phone_off": "📴",
+1566	    "mobile_phone_with_arrow": "📲",
+1567	    "money-mouth_face": "🤑",
+1568	    "money_bag": "💰",
+1569	    "money_with_wings": "💸",
+1570	    "monkey": "🐒",
+1571	    "monkey_face": "🐵",
+1572	    "monorail": "🚝",
+1573	    "moon_cake": "🥮",
+1574	    "moon_viewing_ceremony": "🎑",
+1575	    "mosque": "🕌",
+1576	    "mosquito": "🦟",
+1577	    "motor_boat": "🛥",
+1578	    "motor_scooter": "🛵",
+1579	    "motorcycle": "🏍",
+1580	    "motorized_wheelchair": "🦼",
+1581	    "motorway": "🛣",
+1582	    "mount_fuji": "🗻",
+1583	    "mountain": "⛰",
+1584	    "mountain_cableway": "🚠",
+1585	    "mountain_railway": "🚞",
+1586	    "mouse": "🐭",
+1587	    "mouse_face": "🐭",
+1588	    "mouth": "👄",
+1589	    "movie_camera": "🎥",
+1590	    "mushroom": "🍄",
+1591	    "musical_keyboard": "🎹",
+1592	    "musical_note": "🎵",
+1593	    "musical_notes": "🎶",
+1594	    "musical_score": "🎼",
+1595	    "muted_speaker": "🔇",
+1596	    "nail_polish": "💅",
+1597	    "nail_polish_dark_skin_tone": "💅🏿",
+1598	    "nail_polish_light_skin_tone": "💅🏻",
+1599	    "nail_polish_medium-dark_skin_tone": "💅🏾",
+1600	    "nail_polish_medium-light_skin_tone": "💅🏼",
+1601	    "nail_polish_medium_skin_tone": "💅🏽",
+1602	    "name_badge": "📛",
+1603	    "national_park": "🏞",
+1604	    "nauseated_face": "🤢",
+1605	    "nazar_amulet": "🧿",
+1606	    "necktie": "👔",
+1607	    "nerd_face": "🤓",
+1608	    "neutral_face": "😐",
+1609	    "new_moon": "🌑",
+1610	    "new_moon_face": "🌚",
+1611	    "newspaper": "📰",
+1612	    "next_track_button": "⏭",
+1613	    "night_with_stars": "🌃",
+1614	    "nine-thirty": "🕤",
+1615	    "nine_o’clock": "🕘",
+1616	    "no_bicycles": "🚳",
+1617	    "no_entry": "⛔",
+1618	    "no_littering": "🚯",
+1619	    "no_mobile_phones": "📵",
+1620	    "no_one_under_eighteen": "🔞",
+1621	    "no_pedestrians": "🚷",
+1622	    "no_smoking": "🚭",
+1623	    "non-potable_water": "🚱",
+1624	    "nose": "👃",
+1625	    "nose_dark_skin_tone": "👃🏿",
+1626	    "nose_light_skin_tone": "👃🏻",
+1627	    "nose_medium-dark_skin_tone": "👃🏾",
+1628	    "nose_medium-light_skin_tone": "👃🏼",
+1629	    "nose_medium_skin_tone": "👃🏽",
+1630	    "notebook": "📓",
+1631	    "notebook_with_decorative_cover": "📔",
+1632	    "nut_and_bolt": "🔩",
+1633	    "octopus": "🐙",
+1634	    "oden": "🍢",
+1635	    "office_building": "🏢",
+1636	    "ogre": "👹",
+1637	    "oil_drum": "🛢",
+1638	    "old_key": "🗝",
+1639	    "old_man": "👴",
+1640	    "old_man_dark_skin_tone": "👴🏿",
+1641	    "old_man_light_skin_tone": "👴🏻",
+1642	    "old_man_medium-dark_skin_tone": "👴🏾",
+1643	    "old_man_medium-light_skin_tone": "👴🏼",
+1644	    "old_man_medium_skin_tone": "👴🏽",
+1645	    "old_woman": "👵",
+1646	    "old_woman_dark_skin_tone": "👵🏿",
+1647	    "old_woman_light_skin_tone": "👵🏻",
+1648	    "old_woman_medium-dark_skin_tone": "👵🏾",
+1649	    "old_woman_medium-light_skin_tone": "👵🏼",
+1650	    "old_woman_medium_skin_tone": "👵🏽",
+1651	    "older_adult": "🧓",
+1652	    "older_adult_dark_skin_tone": "🧓🏿",
+1653	    "older_adult_light_skin_tone": "🧓🏻",
+1654	    "older_adult_medium-dark_skin_tone": "🧓🏾",
+1655	    "older_adult_medium-light_skin_tone": "🧓🏼",
+1656	    "older_adult_medium_skin_tone": "🧓🏽",
+1657	    "om": "🕉",
+1658	    "oncoming_automobile": "🚘",
+1659	    "oncoming_bus": "🚍",
+1660	    "oncoming_fist": "👊",
+1661	    "oncoming_fist_dark_skin_tone": "👊🏿",
+1662	    "oncoming_fist_light_skin_tone": "👊🏻",
+1663	    "oncoming_fist_medium-dark_skin_tone": "👊🏾",
+1664	    "oncoming_fist_medium-light_skin_tone": "👊🏼",
+1665	    "oncoming_fist_medium_skin_tone": "👊🏽",
+1666	    "oncoming_police_car": "🚔",
+1667	    "oncoming_taxi": "🚖",
+1668	    "one-piece_swimsuit": "🩱",
+1669	    "one-thirty": "🕜",
+1670	    "one_o’clock": "🕐",
+1671	    "onion": "🧅",
+1672	    "open_book": "📖",
+1673	    "open_file_folder": "📂",
+1674	    "open_hands": "👐",
+1675	    "open_hands_dark_skin_tone": "👐🏿",
+1676	    "open_hands_light_skin_tone": "👐🏻",
+1677	    "open_hands_medium-dark_skin_tone": "👐🏾",
+1678	    "open_hands_medium-light_skin_tone": "👐🏼",
+1679	    "open_hands_medium_skin_tone": "👐🏽",
+1680	    "open_mailbox_with_lowered_flag": "📭",
+1681	    "open_mailbox_with_raised_flag": "📬",
+1682	    "optical_disk": "💿",
+1683	    "orange_book": "📙",
+1684	    "orange_circle": "🟠",
+1685	    "orange_heart": "🧡",
+1686	    "orange_square": "🟧",
+1687	    "orangutan": "🦧",
+1688	    "orthodox_cross": "☦",
+1689	    "otter": "🦦",
+1690	    "outbox_tray": "📤",
+1691	    "owl": "🦉",
+1692	    "ox": "🐂",
+1693	    "oyster": "🦪",
+1694	    "package": "📦",
+1695	    "page_facing_up": "📄",
+1696	    "page_with_curl": "📃",
+1697	    "pager": "📟",
+1698	    "paintbrush": "🖌",
+1699	    "palm_tree": "🌴",
+1700	    "palms_up_together": "🤲",
+1701	    "palms_up_together_dark_skin_tone": "🤲🏿",
+1702	    "palms_up_together_light_skin_tone": "🤲🏻",
+1703	    "palms_up_together_medium-dark_skin_tone": "🤲🏾",
+1704	    "palms_up_together_medium-light_skin_tone": "🤲🏼",
+1705	    "palms_up_together_medium_skin_tone": "🤲🏽",
+1706	    "pancakes": "🥞",
+1707	    "panda_face": "🐼",
+1708	    "paperclip": "📎",
+1709	    "parrot": "🦜",
+1710	    "part_alternation_mark": "〽",
+1711	    "party_popper": "🎉",
+1712	    "partying_face": "🥳",
+1713	    "passenger_ship": "🛳",
+1714	    "passport_control": "🛂",
+1715	    "pause_button": "⏸",
+1716	    "paw_prints": "🐾",
+1717	    "peace_symbol": "☮",
+1718	    "peach": "🍑",
+1719	    "peacock": "🦚",
+1720	    "peanuts": "🥜",
+1721	    "pear": "🍐",
+1722	    "pen": "🖊",
+1723	    "pencil": "📝",
+1724	    "penguin": "🐧",
+1725	    "pensive_face": "😔",
+1726	    "people_holding_hands": "🧑\u200d🤝\u200d🧑",
+1727	    "people_with_bunny_ears": "👯",
+1728	    "people_wrestling": "🤼",
+1729	    "performing_arts": "🎭",
+1730	    "persevering_face": "😣",
+1731	    "person_biking": "🚴",
+1732	    "person_biking_dark_skin_tone": "🚴🏿",
+1733	    "person_biking_light_skin_tone": "🚴🏻",
+1734	    "person_biking_medium-dark_skin_tone": "🚴🏾",
+1735	    "person_biking_medium-light_skin_tone": "🚴🏼",
+1736	    "person_biking_medium_skin_tone": "🚴🏽",
+1737	    "person_bouncing_ball": "⛹",
+1738	    "person_bouncing_ball_dark_skin_tone": "⛹🏿",
+1739	    "person_bouncing_ball_light_skin_tone": "⛹🏻",
+1740	    "person_bouncing_ball_medium-dark_skin_tone": "⛹🏾",
+1741	    "person_bouncing_ball_medium-light_skin_tone": "⛹🏼",
+1742	    "person_bouncing_ball_medium_skin_tone": "⛹🏽",
+1743	    "person_bowing": "🙇",
+1744	    "person_bowing_dark_skin_tone": "🙇🏿",
+1745	    "person_bowing_light_skin_tone": "🙇🏻",
+1746	    "person_bowing_medium-dark_skin_tone": "🙇🏾",
+1747	    "person_bowing_medium-light_skin_tone": "🙇🏼",
+1748	    "person_bowing_medium_skin_tone": "🙇🏽",
+1749	    "person_cartwheeling": "🤸",
+1750	    "person_cartwheeling_dark_skin_tone": "🤸🏿",
+1751	    "person_cartwheeling_light_skin_tone": "🤸🏻",
+1752	    "person_cartwheeling_medium-dark_skin_tone": "🤸🏾",
+1753	    "person_cartwheeling_medium-light_skin_tone": "🤸🏼",
+1754	    "person_cartwheeling_medium_skin_tone": "🤸🏽",
+1755	    "person_climbing": "🧗",
+1756	    "person_climbing_dark_skin_tone": "🧗🏿",
+1757	    "person_climbing_light_skin_tone": "🧗🏻",
+1758	    "person_climbing_medium-dark_skin_tone": "🧗🏾",
+1759	    "person_climbing_medium-light_skin_tone": "🧗🏼",
+1760	    "person_climbing_medium_skin_tone": "🧗🏽",
+1761	    "person_facepalming": "🤦",
+1762	    "person_facepalming_dark_skin_tone": "🤦🏿",
+1763	    "person_facepalming_light_skin_tone": "🤦🏻",
+1764	    "person_facepalming_medium-dark_skin_tone": "🤦🏾",
+1765	    "person_facepalming_medium-light_skin_tone": "🤦🏼",
+1766	    "person_facepalming_medium_skin_tone": "🤦🏽",
+1767	    "person_fencing": "🤺",
+1768	    "person_frowning": "🙍",
+1769	    "person_frowning_dark_skin_tone": "🙍🏿",
+1770	    "person_frowning_light_skin_tone": "🙍🏻",
+1771	    "person_frowning_medium-dark_skin_tone": "🙍🏾",
+1772	    "person_frowning_medium-light_skin_tone": "🙍🏼",
+1773	    "person_frowning_medium_skin_tone": "🙍🏽",
+1774	    "person_gesturing_no": "🙅",
+1775	    "person_gesturing_no_dark_skin_tone": "🙅🏿",
+1776	    "person_gesturing_no_light_skin_tone": "🙅🏻",
+1777	    "person_gesturing_no_medium-dark_skin_tone": "🙅🏾",
+1778	    "person_gesturing_no_medium-light_skin_tone": "🙅🏼",
+1779	    "person_gesturing_no_medium_skin_tone": "🙅🏽",
+1780	    "person_gesturing_ok": "🙆",
+1781	    "person_gesturing_ok_dark_skin_tone": "🙆🏿",
+1782	    "person_gesturing_ok_light_skin_tone": "🙆🏻",
+1783	    "person_gesturing_ok_medium-dark_skin_tone": "🙆🏾",
+1784	    "person_gesturing_ok_medium-light_skin_tone": "🙆🏼",
+1785	    "person_gesturing_ok_medium_skin_tone": "🙆🏽",
+1786	    "person_getting_haircut": "💇",
+1787	    "person_getting_haircut_dark_skin_tone": "💇🏿",
+1788	    "person_getting_haircut_light_skin_tone": "💇🏻",
+1789	    "person_getting_haircut_medium-dark_skin_tone": "💇🏾",
+1790	    "person_getting_haircut_medium-light_skin_tone": "💇🏼",
+1791	    "person_getting_haircut_medium_skin_tone": "💇🏽",
+1792	    "person_getting_massage": "💆",
+1793	    "person_getting_massage_dark_skin_tone": "💆🏿",
+1794	    "person_getting_massage_light_skin_tone": "💆🏻",
+1795	    "person_getting_massage_medium-dark_skin_tone": "💆🏾",
+1796	    "person_getting_massage_medium-light_skin_tone": "💆🏼",
+1797	    "person_getting_massage_medium_skin_tone": "💆🏽",
+1798	    "person_golfing": "🏌",
+1799	    "person_golfing_dark_skin_tone": "🏌🏿",
+1800	    "person_golfing_light_skin_tone": "🏌🏻",
+1801	    "person_golfing_medium-dark_skin_tone": "🏌🏾",
+1802	    "person_golfing_medium-light_skin_tone": "🏌🏼",
+1803	    "person_golfing_medium_skin_tone": "🏌🏽",
+1804	    "person_in_bed": "🛌",
+1805	    "person_in_bed_dark_skin_tone": "🛌🏿",
+1806	    "person_in_bed_light_skin_tone": "🛌🏻",
+1807	    "person_in_bed_medium-dark_skin_tone": "🛌🏾",
+1808	    "person_in_bed_medium-light_skin_tone": "🛌🏼",
+1809	    "person_in_bed_medium_skin_tone": "🛌🏽",
+1810	    "person_in_lotus_position": "🧘",
+1811	    "person_in_lotus_position_dark_skin_tone": "🧘🏿",
+1812	    "person_in_lotus_position_light_skin_tone": "🧘🏻",
+1813	    "person_in_lotus_position_medium-dark_skin_tone": "🧘🏾",
+1814	    "person_in_lotus_position_medium-light_skin_tone": "🧘🏼",
+1815	    "person_in_lotus_position_medium_skin_tone": "🧘🏽",
+1816	    "person_in_steamy_room": "🧖",
+1817	    "person_in_steamy_room_dark_skin_tone": "🧖🏿",
+1818	    "person_in_steamy_room_light_skin_tone": "🧖🏻",
+1819	    "person_in_steamy_room_medium-dark_skin_tone": "🧖🏾",
+1820	    "person_in_steamy_room_medium-light_skin_tone": "🧖🏼",
+1821	    "person_in_steamy_room_medium_skin_tone": "🧖🏽",
+1822	    "person_juggling": "🤹",
+1823	    "person_juggling_dark_skin_tone": "🤹🏿",
+1824	    "person_juggling_light_skin_tone": "🤹🏻",
+1825	    "person_juggling_medium-dark_skin_tone": "🤹🏾",
+1826	    "person_juggling_medium-light_skin_tone": "🤹🏼",
+1827	    "person_juggling_medium_skin_tone": "🤹🏽",
+1828	    "person_kneeling": "🧎",
+1829	    "person_lifting_weights": "🏋",
+1830	    "person_lifting_weights_dark_skin_tone": "🏋🏿",
+1831	    "person_lifting_weights_light_skin_tone": "🏋🏻",
+1832	    "person_lifting_weights_medium-dark_skin_tone": "🏋🏾",
+1833	    "person_lifting_weights_medium-light_skin_tone": "🏋🏼",
+1834	    "person_lifting_weights_medium_skin_tone": "🏋🏽",
+1835	    "person_mountain_biking": "🚵",
+1836	    "person_mountain_biking_dark_skin_tone": "🚵🏿",
+1837	    "person_mountain_biking_light_skin_tone": "🚵🏻",
+1838	    "person_mountain_biking_medium-dark_skin_tone": "🚵🏾",
+1839	    "person_mountain_biking_medium-light_skin_tone": "🚵🏼",
+1840	    "person_mountain_biking_medium_skin_tone": "🚵🏽",
+1841	    "person_playing_handball": "🤾",
+1842	    "person_playing_handball_dark_skin_tone": "🤾🏿",
+1843	    "person_playing_handball_light_skin_tone": "🤾🏻",
+1844	    "person_playing_handball_medium-dark_skin_tone": "🤾🏾",
+1845	    "person_playing_handball_medium-light_skin_tone": "🤾🏼",
+1846	    "person_playing_handball_medium_skin_tone": "🤾🏽",
+1847	    "person_playing_water_polo": "🤽",
+1848	    "person_playing_water_polo_dark_skin_tone": "🤽🏿",
+1849	    "person_playing_water_polo_light_skin_tone": "🤽🏻",
+1850	    "person_playing_water_polo_medium-dark_skin_tone": "🤽🏾",
+1851	    "person_playing_water_polo_medium-light_skin_tone": "🤽🏼",
+1852	    "person_playing_water_polo_medium_skin_tone": "🤽🏽",
+1853	    "person_pouting": "🙎",
+1854	    "person_pouting_dark_skin_tone": "🙎🏿",
+1855	    "person_pouting_light_skin_tone": "🙎🏻",
+1856	    "person_pouting_medium-dark_skin_tone": "🙎🏾",
+1857	    "person_pouting_medium-light_skin_tone": "🙎🏼",
+1858	    "person_pouting_medium_skin_tone": "🙎🏽",
+1859	    "person_raising_hand": "🙋",
+1860	    "person_raising_hand_dark_skin_tone": "🙋🏿",
+1861	    "person_raising_hand_light_skin_tone": "🙋🏻",
+1862	    "person_raising_hand_medium-dark_skin_tone": "🙋🏾",
+1863	    "person_raising_hand_medium-light_skin_tone": "🙋🏼",
+1864	    "person_raising_hand_medium_skin_tone": "🙋🏽",
+1865	    "person_rowing_boat": "🚣",
+1866	    "person_rowing_boat_dark_skin_tone": "🚣🏿",
+1867	    "person_rowing_boat_light_skin_tone": "🚣🏻",
+1868	    "person_rowing_boat_medium-dark_skin_tone": "🚣🏾",
+1869	    "person_rowing_boat_medium-light_skin_tone": "🚣🏼",
+1870	    "person_rowing_boat_medium_skin_tone": "🚣🏽",
+1871	    "person_running": "🏃",
+1872	    "person_running_dark_skin_tone": "🏃🏿",
+1873	    "person_running_light_skin_tone": "🏃🏻",
+1874	    "person_running_medium-dark_skin_tone": "🏃🏾",
+1875	    "person_running_medium-light_skin_tone": "🏃🏼",
+1876	    "person_running_medium_skin_tone": "🏃🏽",
+1877	    "person_shrugging": "🤷",
+1878	    "person_shrugging_dark_skin_tone": "🤷🏿",
+1879	    "person_shrugging_light_skin_tone": "🤷🏻",
+1880	    "person_shrugging_medium-dark_skin_tone": "🤷🏾",
+1881	    "person_shrugging_medium-light_skin_tone": "🤷🏼",
+1882	    "person_shrugging_medium_skin_tone": "🤷🏽",
+1883	    "person_standing": "🧍",
+1884	    "person_surfing": "🏄",
+1885	    "person_surfing_dark_skin_tone": "🏄🏿",
+1886	    "person_surfing_light_skin_tone": "🏄🏻",
+1887	    "person_surfing_medium-dark_skin_tone": "🏄🏾",
+1888	    "person_surfing_medium-light_skin_tone": "🏄🏼",
+1889	    "person_surfing_medium_skin_tone": "🏄🏽",
+1890	    "person_swimming": "🏊",
+1891	    "person_swimming_dark_skin_tone": "🏊🏿",
+1892	    "person_swimming_light_skin_tone": "🏊🏻",
+1893	    "person_swimming_medium-dark_skin_tone": "🏊🏾",
+1894	    "person_swimming_medium-light_skin_tone": "🏊🏼",
+1895	    "person_swimming_medium_skin_tone": "🏊🏽",
+1896	    "person_taking_bath": "🛀",
+1897	    "person_taking_bath_dark_skin_tone": "🛀🏿",
+1898	    "person_taking_bath_light_skin_tone": "🛀🏻",
+1899	    "person_taking_bath_medium-dark_skin_tone": "🛀🏾",
+1900	    "person_taking_bath_medium-light_skin_tone": "🛀🏼",
+1901	    "person_taking_bath_medium_skin_tone": "🛀🏽",
+1902	    "person_tipping_hand": "💁",
+1903	    "person_tipping_hand_dark_skin_tone": "💁🏿",
+1904	    "person_tipping_hand_light_skin_tone": "💁🏻",
+1905	    "person_tipping_hand_medium-dark_skin_tone": "💁🏾",
+1906	    "person_tipping_hand_medium-light_skin_tone": "💁🏼",
+1907	    "person_tipping_hand_medium_skin_tone": "💁🏽",
+1908	    "person_walking": "🚶",
+1909	    "person_walking_dark_skin_tone": "🚶🏿",
+1910	    "person_walking_light_skin_tone": "🚶🏻",
+1911	    "person_walking_medium-dark_skin_tone": "🚶🏾",
+1912	    "person_walking_medium-light_skin_tone": "🚶🏼",
+1913	    "person_walking_medium_skin_tone": "🚶🏽",
+1914	    "person_wearing_turban": "👳",
+1915	    "person_wearing_turban_dark_skin_tone": "👳🏿",
+1916	    "person_wearing_turban_light_skin_tone": "👳🏻",
+1917	    "person_wearing_turban_medium-dark_skin_tone": "👳🏾",
+1918	    "person_wearing_turban_medium-light_skin_tone": "👳🏼",
+1919	    "person_wearing_turban_medium_skin_tone": "👳🏽",
+1920	    "petri_dish": "🧫",
+1921	    "pick": "⛏",
+1922	    "pie": "🥧",
+1923	    "pig": "🐷",
+1924	    "pig_face": "🐷",
+1925	    "pig_nose": "🐽",
+1926	    "pile_of_poo": "💩",
+1927	    "pill": "💊",
+1928	    "pinching_hand": "🤏",
+1929	    "pine_decoration": "🎍",
+1930	    "pineapple": "🍍",
+1931	    "ping_pong": "🏓",
+1932	    "pirate_flag": "🏴\u200d☠️",
+1933	    "pistol": "🔫",
+1934	    "pizza": "🍕",
+1935	    "place_of_worship": "🛐",
+1936	    "play_button": "▶",
+1937	    "play_or_pause_button": "⏯",
+1938	    "pleading_face": "🥺",
+1939	    "police_car": "🚓",
+1940	    "police_car_light": "🚨",
+1941	    "police_officer": "👮",
+1942	    "police_officer_dark_skin_tone": "👮🏿",
+1943	    "police_officer_light_skin_tone": "👮🏻",
+1944	    "police_officer_medium-dark_skin_tone": "👮🏾",
+1945	    "police_officer_medium-light_skin_tone": "👮🏼",
+1946	    "police_officer_medium_skin_tone": "👮🏽",
+1947	    "poodle": "🐩",
+1948	    "pool_8_ball": "🎱",
+1949	    "popcorn": "🍿",
+1950	    "post_office": "🏣",
+1951	    "postal_horn": "📯",
+1952	    "postbox": "📮",
+1953	    "pot_of_food": "🍲",
+1954	    "potable_water": "🚰",
+1955	    "potato": "🥔",
+1956	    "poultry_leg": "🍗",
+1957	    "pound_banknote": "💷",
+1958	    "pouting_cat_face": "😾",
+1959	    "pouting_face": "😡",
+1960	    "prayer_beads": "📿",
+1961	    "pregnant_woman": "🤰",
+1962	    "pregnant_woman_dark_skin_tone": "🤰🏿",
+1963	    "pregnant_woman_light_skin_tone": "🤰🏻",
+1964	    "pregnant_woman_medium-dark_skin_tone": "🤰🏾",
+1965	    "pregnant_woman_medium-light_skin_tone": "🤰🏼",
+1966	    "pregnant_woman_medium_skin_tone": "🤰🏽",
+1967	    "pretzel": "🥨",
+1968	    "probing_cane": "🦯",
+1969	    "prince": "🤴",
+1970	    "prince_dark_skin_tone": "🤴🏿",
+1971	    "prince_light_skin_tone": "🤴🏻",
+1972	    "prince_medium-dark_skin_tone": "🤴🏾",
+1973	    "prince_medium-light_skin_tone": "🤴🏼",
+1974	    "prince_medium_skin_tone": "🤴🏽",
+1975	    "princess": "👸",
+1976	    "princess_dark_skin_tone": "👸🏿",
+1977	    "princess_light_skin_tone": "👸🏻",
+1978	    "princess_medium-dark_skin_tone": "👸🏾",
+1979	    "princess_medium-light_skin_tone": "👸🏼",
+1980	    "princess_medium_skin_tone": "👸🏽",
+1981	    "printer": "🖨",
+1982	    "prohibited": "🚫",
+1983	    "purple_circle": "🟣",
+1984	    "purple_heart": "💜",
+1985	    "purple_square": "🟪",
+1986	    "purse": "👛",
+1987	    "pushpin": "📌",
+1988	    "question_mark": "❓",
+1989	    "rabbit": "🐰",
+1990	    "rabbit_face": "🐰",
+1991	    "raccoon": "🦝",
+1992	    "racing_car": "🏎",
+1993	    "radio": "📻",
+1994	    "radio_button": "🔘",
+1995	    "radioactive": "☢",
+1996	    "railway_car": "🚃",
+1997	    "railway_track": "🛤",
+1998	    "rainbow": "🌈",
+1999	    "rainbow_flag": "🏳️\u200d🌈",
+2000	    "raised_back_of_hand": "🤚",
+2001	    "raised_back_of_hand_dark_skin_tone": "🤚🏿",
+2002	    "raised_back_of_hand_light_skin_tone": "🤚🏻",
+2003	    "raised_back_of_hand_medium-dark_skin_tone": "🤚🏾",
+2004	    "raised_back_of_hand_medium-light_skin_tone": "🤚🏼",
+2005	    "raised_back_of_hand_medium_skin_tone": "🤚🏽",
+2006	    "raised_fist": "✊",
+2007	    "raised_fist_dark_skin_tone": "✊🏿",
+2008	    "raised_fist_light_skin_tone": "✊🏻",
+2009	    "raised_fist_medium-dark_skin_tone": "✊🏾",
+2010	    "raised_fist_medium-light_skin_tone": "✊🏼",
+2011	    "raised_fist_medium_skin_tone": "✊🏽",
+2012	    "raised_hand": "✋",
+2013	    "raised_hand_dark_skin_tone": "✋🏿",
+2014	    "raised_hand_light_skin_tone": "✋🏻",
+2015	    "raised_hand_medium-dark_skin_tone": "✋🏾",
+2016	    "raised_hand_medium-light_skin_tone": "✋🏼",
+2017	    "raised_hand_medium_skin_tone": "✋🏽",
+2018	    "raising_hands": "🙌",
+2019	    "raising_hands_dark_skin_tone": "🙌🏿",
+2020	    "raising_hands_light_skin_tone": "🙌🏻",
+2021	    "raising_hands_medium-dark_skin_tone": "🙌🏾",
+2022	    "raising_hands_medium-light_skin_tone": "🙌🏼",
+2023	    "raising_hands_medium_skin_tone": "🙌🏽",
+2024	    "ram": "🐏",
+2025	    "rat": "🐀",
+2026	    "razor": "🪒",
+2027	    "ringed_planet": "🪐",
+2028	    "receipt": "🧾",
+2029	    "record_button": "⏺",
+2030	    "recycling_symbol": "♻",
+2031	    "red_apple": "🍎",
+2032	    "red_circle": "🔴",
+2033	    "red_envelope": "🧧",
+2034	    "red_hair": "🦰",
+2035	    "red-haired_man": "👨\u200d🦰",
+2036	    "red-haired_woman": "👩\u200d🦰",
+2037	    "red_heart": "❤",
+2038	    "red_paper_lantern": "🏮",
+2039	    "red_square": "🟥",
+2040	    "red_triangle_pointed_down": "🔻",
+2041	    "red_triangle_pointed_up": "🔺",
+2042	    "registered": "®",
+2043	    "relieved_face": "😌",
+2044	    "reminder_ribbon": "🎗",
+2045	    "repeat_button": "🔁",
+2046	    "repeat_single_button": "🔂",
+2047	    "rescue_worker’s_helmet": "⛑",
+2048	    "restroom": "🚻",
+2049	    "reverse_button": "◀",
+2050	    "revolving_hearts": "💞",
+2051	    "rhinoceros": "🦏",
+2052	    "ribbon": "🎀",
+2053	    "rice_ball": "🍙",
+2054	    "rice_cracker": "🍘",
+2055	    "right-facing_fist": "🤜",
+2056	    "right-facing_fist_dark_skin_tone": "🤜🏿",
+2057	    "right-facing_fist_light_skin_tone": "🤜🏻",
+2058	    "right-facing_fist_medium-dark_skin_tone": "🤜🏾",
+2059	    "right-facing_fist_medium-light_skin_tone": "🤜🏼",
+2060	    "right-facing_fist_medium_skin_tone": "🤜🏽",
+2061	    "right_anger_bubble": "🗯",
+2062	    "right_arrow": "➡",
+2063	    "right_arrow_curving_down": "⤵",
+2064	    "right_arrow_curving_left": "↩",
+2065	    "right_arrow_curving_up": "⤴",
+2066	    "ring": "💍",
+2067	    "roasted_sweet_potato": "🍠",
+2068	    "robot_face": "🤖",
+2069	    "rocket": "🚀",
+2070	    "roll_of_paper": "🧻",
+2071	    "rolled-up_newspaper": "🗞",
+2072	    "roller_coaster": "🎢",
+2073	    "rolling_on_the_floor_laughing": "🤣",
+2074	    "rooster": "🐓",
+2075	    "rose": "🌹",
+2076	    "rosette": "🏵",
+2077	    "round_pushpin": "📍",
+2078	    "rugby_football": "🏉",
+2079	    "running_shirt": "🎽",
+2080	    "running_shoe": "👟",
+2081	    "sad_but_relieved_face": "😥",
+2082	    "safety_pin": "🧷",
+2083	    "safety_vest": "🦺",
+2084	    "salt": "🧂",
+2085	    "sailboat": "⛵",
+2086	    "sake": "🍶",
+2087	    "sandwich": "🥪",
+2088	    "sari": "🥻",
+2089	    "satellite": "📡",
+2090	    "satellite_antenna": "📡",
+2091	    "sauropod": "🦕",
+2092	    "saxophone": "🎷",
+2093	    "scarf": "🧣",
+2094	    "school": "🏫",
+2095	    "school_backpack": "🎒",
+2096	    "scissors": "✂",
+2097	    "scorpion": "🦂",
+2098	    "scroll": "📜",
+2099	    "seat": "💺",
+2100	    "see-no-evil_monkey": "🙈",
+2101	    "seedling": "🌱",
+2102	    "selfie": "🤳",
+2103	    "selfie_dark_skin_tone": "🤳🏿",
+2104	    "selfie_light_skin_tone": "🤳🏻",
+2105	    "selfie_medium-dark_skin_tone": "🤳🏾",
+2106	    "selfie_medium-light_skin_tone": "🤳🏼",
+2107	    "selfie_medium_skin_tone": "🤳🏽",
+2108	    "service_dog": "🐕\u200d🦺",
+2109	    "seven-thirty": "🕢",
+2110	    "seven_o’clock": "🕖",
+2111	    "shallow_pan_of_food": "🥘",
+2112	    "shamrock": "☘",
+2113	    "shark": "🦈",
+2114	    "shaved_ice": "🍧",
+2115	    "sheaf_of_rice": "🌾",
+2116	    "shield": "🛡",
+2117	    "shinto_shrine": "⛩",
+2118	    "ship": "🚢",
+2119	    "shooting_star": "🌠",
+2120	    "shopping_bags": "🛍",
+2121	    "shopping_cart": "🛒",
+2122	    "shortcake": "🍰",
+2123	    "shorts": "🩳",
+2124	    "shower": "🚿",
+2125	    "shrimp": "🦐",
+2126	    "shuffle_tracks_button": "🔀",
+2127	    "shushing_face": "🤫",
+2128	    "sign_of_the_horns": "🤘",
+2129	    "sign_of_the_horns_dark_skin_tone": "🤘🏿",
+2130	    "sign_of_the_horns_light_skin_tone": "🤘🏻",
+2131	    "sign_of_the_horns_medium-dark_skin_tone": "🤘🏾",
+2132	    "sign_of_the_horns_medium-light_skin_tone": "🤘🏼",
+2133	    "sign_of_the_horns_medium_skin_tone": "🤘🏽",
+2134	    "six-thirty": "🕡",
+2135	    "six_o’clock": "🕕",
+2136	    "skateboard": "🛹",
+2137	    "skier": "⛷",
+2138	    "skis": "🎿",
+2139	    "skull": "💀",
+2140	    "skull_and_crossbones": "☠",
+2141	    "skunk": "🦨",
+2142	    "sled": "🛷",
+2143	    "sleeping_face": "😴",
+2144	    "sleepy_face": "😪",
+2145	    "slightly_frowning_face": "🙁",
+2146	    "slightly_smiling_face": "🙂",
+2147	    "slot_machine": "🎰",
+2148	    "sloth": "🦥",
+2149	    "small_airplane": "🛩",
+2150	    "small_blue_diamond": "🔹",
+2151	    "small_orange_diamond": "🔸",
+2152	    "smiling_cat_face_with_heart-eyes": "😻",
+2153	    "smiling_face": "☺",
+2154	    "smiling_face_with_halo": "😇",
+2155	    "smiling_face_with_3_hearts": "🥰",
+2156	    "smiling_face_with_heart-eyes": "😍",
+2157	    "smiling_face_with_horns": "😈",
+2158	    "smiling_face_with_smiling_eyes": "😊",
+2159	    "smiling_face_with_sunglasses": "😎",
+2160	    "smirking_face": "😏",
+2161	    "snail": "🐌",
+2162	    "snake": "🐍",
+2163	    "sneezing_face": "🤧",
+2164	    "snow-capped_mountain": "🏔",
+2165	    "snowboarder": "🏂",
+2166	    "snowboarder_dark_skin_tone": "🏂🏿",
+2167	    "snowboarder_light_skin_tone": "🏂🏻",
+2168	    "snowboarder_medium-dark_skin_tone": "🏂🏾",
+2169	    "snowboarder_medium-light_skin_tone": "🏂🏼",
+2170	    "snowboarder_medium_skin_tone": "🏂🏽",
+2171	    "snowflake": "❄",
+2172	    "snowman": "☃",
+2173	    "snowman_without_snow": "⛄",
+2174	    "soap": "🧼",
+2175	    "soccer_ball": "⚽",
+2176	    "socks": "🧦",
+2177	    "softball": "🥎",
+2178	    "soft_ice_cream": "🍦",
+2179	    "spade_suit": "♠",
+2180	    "spaghetti": "🍝",
+2181	    "sparkle": "❇",
+2182	    "sparkler": "🎇",
+2183	    "sparkles": "✨",
+2184	    "sparkling_heart": "💖",
+2185	    "speak-no-evil_monkey": "🙊",
+2186	    "speaker_high_volume": "🔊",
+2187	    "speaker_low_volume": "🔈",
+2188	    "speaker_medium_volume": "🔉",
+2189	    "speaking_head": "🗣",
+2190	    "speech_balloon": "💬",
+2191	    "speedboat": "🚤",
+2192	    "spider": "🕷",
+2193	    "spider_web": "🕸",
+2194	    "spiral_calendar": "🗓",
+2195	    "spiral_notepad": "🗒",
+2196	    "spiral_shell": "🐚",
+2197	    "spoon": "🥄",
+2198	    "sponge": "🧽",
+2199	    "sport_utility_vehicle": "🚙",
+2200	    "sports_medal": "🏅",
+2201	    "spouting_whale": "🐳",
+2202	    "squid": "🦑",
+2203	    "squinting_face_with_tongue": "😝",
+2204	    "stadium": "🏟",
+2205	    "star-struck": "🤩",
+2206	    "star_and_crescent": "☪",
+2207	    "star_of_david": "✡",
+2208	    "station": "🚉",
+2209	    "steaming_bowl": "🍜",
+2210	    "stethoscope": "🩺",
+2211	    "stop_button": "⏹",
+2212	    "stop_sign": "🛑",
+2213	    "stopwatch": "⏱",
+2214	    "straight_ruler": "📏",
+2215	    "strawberry": "🍓",
+2216	    "studio_microphone": "🎙",
+2217	    "stuffed_flatbread": "🥙",
+2218	    "sun": "☀",
+2219	    "sun_behind_cloud": "⛅",
+2220	    "sun_behind_large_cloud": "🌥",
+2221	    "sun_behind_rain_cloud": "🌦",
+2222	    "sun_behind_small_cloud": "🌤",
+2223	    "sun_with_face": "🌞",
+2224	    "sunflower": "🌻",
+2225	    "sunglasses": "😎",
+2226	    "sunrise": "🌅",
+2227	    "sunrise_over_mountains": "🌄",
+2228	    "sunset": "🌇",
+2229	    "superhero": "🦸",
+2230	    "supervillain": "🦹",
+2231	    "sushi": "🍣",
+2232	    "suspension_railway": "🚟",
+2233	    "swan": "🦢",
+2234	    "sweat_droplets": "💦",
+2235	    "synagogue": "🕍",
+2236	    "syringe": "💉",
+2237	    "t-shirt": "👕",
+2238	    "taco": "🌮",
+2239	    "takeout_box": "🥡",
+2240	    "tanabata_tree": "🎋",
+2241	    "tangerine": "🍊",
+2242	    "taxi": "🚕",
+2243	    "teacup_without_handle": "🍵",
+2244	    "tear-off_calendar": "📆",
+2245	    "teddy_bear": "🧸",
+2246	    "telephone": "☎",
+2247	    "telephone_receiver": "📞",
+2248	    "telescope": "🔭",
+2249	    "television": "📺",
+2250	    "ten-thirty": "🕥",
+2251	    "ten_o’clock": "🕙",
+2252	    "tennis": "🎾",
+2253	    "tent": "⛺",
+2254	    "test_tube": "🧪",
+2255	    "thermometer": "🌡",
+2256	    "thinking_face": "🤔",
+2257	    "thought_balloon": "💭",
+2258	    "thread": "🧵",
+2259	    "three-thirty": "🕞",
+2260	    "three_o’clock": "🕒",
+2261	    "thumbs_down": "👎",
+2262	    "thumbs_down_dark_skin_tone": "👎🏿",
+2263	    "thumbs_down_light_skin_tone": "👎🏻",
+2264	    "thumbs_down_medium-dark_skin_tone": "👎🏾",
+2265	    "thumbs_down_medium-light_skin_tone": "👎🏼",
+2266	    "thumbs_down_medium_skin_tone": "👎🏽",
+2267	    "thumbs_up": "👍",
+2268	    "thumbs_up_dark_skin_tone": "👍🏿",
+2269	    "thumbs_up_light_skin_tone": "👍🏻",
+2270	    "thumbs_up_medium-dark_skin_tone": "👍🏾",
+2271	    "thumbs_up_medium-light_skin_tone": "👍🏼",
+2272	    "thumbs_up_medium_skin_tone": "👍🏽",
+2273	    "ticket": "🎫",
+2274	    "tiger": "🐯",
+2275	    "tiger_face": "🐯",
+2276	    "timer_clock": "⏲",
+2277	    "tired_face": "😫",
+2278	    "toolbox": "🧰",
+2279	    "toilet": "🚽",
+2280	    "tomato": "🍅",
+2281	    "tongue": "👅",
+2282	    "tooth": "🦷",
+2283	    "top_hat": "🎩",
+2284	    "tornado": "🌪",
+2285	    "trackball": "🖲",
+2286	    "tractor": "🚜",
+2287	    "trade_mark": "™",
+2288	    "train": "🚋",
+2289	    "tram": "🚊",
+2290	    "tram_car": "🚋",
+2291	    "triangular_flag": "🚩",
+2292	    "triangular_ruler": "📐",
+2293	    "trident_emblem": "🔱",
+2294	    "trolleybus": "🚎",
+2295	    "trophy": "🏆",
+2296	    "tropical_drink": "🍹",
+2297	    "tropical_fish": "🐠",
+2298	    "trumpet": "🎺",
+2299	    "tulip": "🌷",
+2300	    "tumbler_glass": "🥃",
+2301	    "turtle": "🐢",
+2302	    "twelve-thirty": "🕧",
+2303	    "twelve_o’clock": "🕛",
+2304	    "two-hump_camel": "🐫",
+2305	    "two-thirty": "🕝",
+2306	    "two_hearts": "💕",
+2307	    "two_men_holding_hands": "👬",
+2308	    "two_o’clock": "🕑",
+2309	    "two_women_holding_hands": "👭",
+2310	    "umbrella": "☂",
+2311	    "umbrella_on_ground": "⛱",
+2312	    "umbrella_with_rain_drops": "☔",
+2313	    "unamused_face": "😒",
+2314	    "unicorn_face": "🦄",
+2315	    "unlocked": "🔓",
+2316	    "up-down_arrow": "↕",
+2317	    "up-left_arrow": "↖",
+2318	    "up-right_arrow": "↗",
+2319	    "up_arrow": "⬆",
+2320	    "upside-down_face": "🙃",
+2321	    "upwards_button": "🔼",
+2322	    "vampire": "🧛",
+2323	    "vampire_dark_skin_tone": "🧛🏿",
+2324	    "vampire_light_skin_tone": "🧛🏻",
+2325	    "vampire_medium-dark_skin_tone": "🧛🏾",
+2326	    "vampire_medium-light_skin_tone": "🧛🏼",
+2327	    "vampire_medium_skin_tone": "🧛🏽",
+2328	    "vertical_traffic_light": "🚦",
+2329	    "vibration_mode": "📳",
+2330	    "victory_hand": "✌",
+2331	    "victory_hand_dark_skin_tone": "✌🏿",
+2332	    "victory_hand_light_skin_tone": "✌🏻",
+2333	    "victory_hand_medium-dark_skin_tone": "✌🏾",
+2334	    "victory_hand_medium-light_skin_tone": "✌🏼",
+2335	    "victory_hand_medium_skin_tone": "✌🏽",
+2336	    "video_camera": "📹",
+2337	    "video_game": "🎮",
+2338	    "videocassette": "📼",
+2339	    "violin": "🎻",
+2340	    "volcano": "🌋",
+2341	    "volleyball": "🏐",
+2342	    "vulcan_salute": "🖖",
+2343	    "vulcan_salute_dark_skin_tone": "🖖🏿",
+2344	    "vulcan_salute_light_skin_tone": "🖖🏻",
+2345	    "vulcan_salute_medium-dark_skin_tone": "🖖🏾",
+2346	    "vulcan_salute_medium-light_skin_tone": "🖖🏼",
+2347	    "vulcan_salute_medium_skin_tone": "🖖🏽",
+2348	    "waffle": "🧇",
+2349	    "waning_crescent_moon": "🌘",
+2350	    "waning_gibbous_moon": "🌖",
+2351	    "warning": "⚠",
+2352	    "wastebasket": "🗑",
+2353	    "watch": "⌚",
+2354	    "water_buffalo": "🐃",
+2355	    "water_closet": "🚾",
+2356	    "water_wave": "🌊",
+2357	    "watermelon": "🍉",
+2358	    "waving_hand": "👋",
+2359	    "waving_hand_dark_skin_tone": "👋🏿",
+2360	    "waving_hand_light_skin_tone": "👋🏻",
+2361	    "waving_hand_medium-dark_skin_tone": "👋🏾",
+2362	    "waving_hand_medium-light_skin_tone": "👋🏼",
+2363	    "waving_hand_medium_skin_tone": "👋🏽",
+2364	    "wavy_dash": "〰",
+2365	    "waxing_crescent_moon": "🌒",
+2366	    "waxing_gibbous_moon": "🌔",
+2367	    "weary_cat_face": "🙀",
+2368	    "weary_face": "😩",
+2369	    "wedding": "💒",
+2370	    "whale": "🐳",
+2371	    "wheel_of_dharma": "☸",
+2372	    "wheelchair_symbol": "♿",
+2373	    "white_circle": "⚪",
+2374	    "white_exclamation_mark": "❕",
+2375	    "white_flag": "🏳",
+2376	    "white_flower": "💮",
+2377	    "white_hair": "🦳",
+2378	    "white-haired_man": "👨\u200d🦳",
+2379	    "white-haired_woman": "👩\u200d🦳",
+2380	    "white_heart": "🤍",
+2381	    "white_heavy_check_mark": "✅",
+2382	    "white_large_square": "⬜",
+2383	    "white_medium-small_square": "◽",
+2384	    "white_medium_square": "◻",
+2385	    "white_medium_star": "⭐",
+2386	    "white_question_mark": "❔",
+2387	    "white_small_square": "▫",
+2388	    "white_square_button": "🔳",
+2389	    "wilted_flower": "🥀",
+2390	    "wind_chime": "🎐",
+2391	    "wind_face": "🌬",
+2392	    "wine_glass": "🍷",
+2393	    "winking_face": "😉",
+2394	    "winking_face_with_tongue": "😜",
+2395	    "wolf_face": "🐺",
+2396	    "woman": "👩",
+2397	    "woman_artist": "👩\u200d🎨",
+2398	    "woman_artist_dark_skin_tone": "👩🏿\u200d🎨",
+2399	    "woman_artist_light_skin_tone": "👩🏻\u200d🎨",
+2400	    "woman_artist_medium-dark_skin_tone": "👩🏾\u200d🎨",
+2401	    "woman_artist_medium-light_skin_tone": "👩🏼\u200d🎨",
+2402	    "woman_artist_medium_skin_tone": "👩🏽\u200d🎨",
+2403	    "woman_astronaut": "👩\u200d🚀",
+2404	    "woman_astronaut_dark_skin_tone": "👩🏿\u200d🚀",
+2405	    "woman_astronaut_light_skin_tone": "👩🏻\u200d🚀",
+2406	    "woman_astronaut_medium-dark_skin_tone": "👩🏾\u200d🚀",
+2407	    "woman_astronaut_medium-light_skin_tone": "👩🏼\u200d🚀",
+2408	    "woman_astronaut_medium_skin_tone": "👩🏽\u200d🚀",
+2409	    "woman_biking": "🚴\u200d♀️",
+2410	    "woman_biking_dark_skin_tone": "🚴🏿\u200d♀️",
+2411	    "woman_biking_light_skin_tone": "🚴🏻\u200d♀️",
+2412	    "woman_biking_medium-dark_skin_tone": "🚴🏾\u200d♀️",
+2413	    "woman_biking_medium-light_skin_tone": "🚴🏼\u200d♀️",
+2414	    "woman_biking_medium_skin_tone": "🚴🏽\u200d♀️",
+2415	    "woman_bouncing_ball": "⛹️\u200d♀️",
+2416	    "woman_bouncing_ball_dark_skin_tone": "⛹🏿\u200d♀️",
+2417	    "woman_bouncing_ball_light_skin_tone": "⛹🏻\u200d♀️",
+2418	    "woman_bouncing_ball_medium-dark_skin_tone": "⛹🏾\u200d♀️",
+2419	    "woman_bouncing_ball_medium-light_skin_tone": "⛹🏼\u200d♀️",
+2420	    "woman_bouncing_ball_medium_skin_tone": "⛹🏽\u200d♀️",
+2421	    "woman_bowing": "🙇\u200d♀️",
+2422	    "woman_bowing_dark_skin_tone": "🙇🏿\u200d♀️",
+2423	    "woman_bowing_light_skin_tone": "🙇🏻\u200d♀️",
+2424	    "woman_bowing_medium-dark_skin_tone": "🙇🏾\u200d♀️",
+2425	    "woman_bowing_medium-light_skin_tone": "🙇🏼\u200d♀️",
+2426	    "woman_bowing_medium_skin_tone": "🙇🏽\u200d♀️",
+2427	    "woman_cartwheeling": "🤸\u200d♀️",
+2428	    "woman_cartwheeling_dark_skin_tone": "🤸🏿\u200d♀️",
+2429	    "woman_cartwheeling_light_skin_tone": "🤸🏻\u200d♀️",
+2430	    "woman_cartwheeling_medium-dark_skin_tone": "🤸🏾\u200d♀️",
+2431	    "woman_cartwheeling_medium-light_skin_tone": "🤸🏼\u200d♀️",
+2432	    "woman_cartwheeling_medium_skin_tone": "🤸🏽\u200d♀️",
+2433	    "woman_climbing": "🧗\u200d♀️",
+2434	    "woman_climbing_dark_skin_tone": "🧗🏿\u200d♀️",
+2435	    "woman_climbing_light_skin_tone": "🧗🏻\u200d♀️",
+2436	    "woman_climbing_medium-dark_skin_tone": "🧗🏾\u200d♀️",
+2437	    "woman_climbing_medium-light_skin_tone": "🧗🏼\u200d♀️",
+2438	    "woman_climbing_medium_skin_tone": "🧗🏽\u200d♀️",
+2439	    "woman_construction_worker": "👷\u200d♀️",
+2440	    "woman_construction_worker_dark_skin_tone": "👷🏿\u200d♀️",
+2441	    "woman_construction_worker_light_skin_tone": "👷🏻\u200d♀️",
+2442	    "woman_construction_worker_medium-dark_skin_tone": "👷🏾\u200d♀️",
+2443	    "woman_construction_worker_medium-light_skin_tone": "👷🏼\u200d♀️",
+2444	    "woman_construction_worker_medium_skin_tone": "👷🏽\u200d♀️",
+2445	    "woman_cook": "👩\u200d🍳",
+2446	    "woman_cook_dark_skin_tone": "👩🏿\u200d🍳",
+2447	    "woman_cook_light_skin_tone": "👩🏻\u200d🍳",
+2448	    "woman_cook_medium-dark_skin_tone": "👩🏾\u200d🍳",
+2449	    "woman_cook_medium-light_skin_tone": "👩🏼\u200d🍳",
+2450	    "woman_cook_medium_skin_tone": "👩🏽\u200d🍳",
+2451	    "woman_dancing": "💃",
+2452	    "woman_dancing_dark_skin_tone": "💃🏿",
+2453	    "woman_dancing_light_skin_tone": "💃🏻",
+2454	    "woman_dancing_medium-dark_skin_tone": "💃🏾",
+2455	    "woman_dancing_medium-light_skin_tone": "💃🏼",
+2456	    "woman_dancing_medium_skin_tone": "💃🏽",
+2457	    "woman_dark_skin_tone": "👩🏿",
+2458	    "woman_detective": "🕵️\u200d♀️",
+2459	    "woman_detective_dark_skin_tone": "🕵🏿\u200d♀️",
+2460	    "woman_detective_light_skin_tone": "🕵🏻\u200d♀️",
+2461	    "woman_detective_medium-dark_skin_tone": "🕵🏾\u200d♀️",
+2462	    "woman_detective_medium-light_skin_tone": "🕵🏼\u200d♀️",
+2463	    "woman_detective_medium_skin_tone": "🕵🏽\u200d♀️",
+2464	    "woman_elf": "🧝\u200d♀️",
+2465	    "woman_elf_dark_skin_tone": "🧝🏿\u200d♀️",
+2466	    "woman_elf_light_skin_tone": "🧝🏻\u200d♀️",
+2467	    "woman_elf_medium-dark_skin_tone": "🧝🏾\u200d♀️",
+2468	    "woman_elf_medium-light_skin_tone": "🧝🏼\u200d♀️",
+2469	    "woman_elf_medium_skin_tone": "🧝🏽\u200d♀️",
+2470	    "woman_facepalming": "🤦\u200d♀️",
+2471	    "woman_facepalming_dark_skin_tone": "🤦🏿\u200d♀️",
+2472	    "woman_facepalming_light_skin_tone": "🤦🏻\u200d♀️",
+2473	    "woman_facepalming_medium-dark_skin_tone": "🤦🏾\u200d♀️",
+2474	    "woman_facepalming_medium-light_skin_tone": "🤦🏼\u200d♀️",
+2475	    "woman_facepalming_medium_skin_tone": "🤦🏽\u200d♀️",
+2476	    "woman_factory_worker": "👩\u200d🏭",
+2477	    "woman_factory_worker_dark_skin_tone": "👩🏿\u200d🏭",
+2478	    "woman_factory_worker_light_skin_tone": "👩🏻\u200d🏭",
+2479	    "woman_factory_worker_medium-dark_skin_tone": "👩🏾\u200d🏭",
+2480	    "woman_factory_worker_medium-light_skin_tone": "👩🏼\u200d🏭",
+2481	    "woman_factory_worker_medium_skin_tone": "👩🏽\u200d🏭",
+2482	    "woman_fairy": "🧚\u200d♀️",
+2483	    "woman_fairy_dark_skin_tone": "🧚🏿\u200d♀️",
+2484	    "woman_fairy_light_skin_tone": "🧚🏻\u200d♀️",
+2485	    "woman_fairy_medium-dark_skin_tone": "🧚🏾\u200d♀️",
+2486	    "woman_fairy_medium-light_skin_tone": "🧚🏼\u200d♀️",
+2487	    "woman_fairy_medium_skin_tone": "🧚🏽\u200d♀️",
+2488	    "woman_farmer": "👩\u200d🌾",
+2489	    "woman_farmer_dark_skin_tone": "👩🏿\u200d🌾",
+2490	    "woman_farmer_light_skin_tone": "👩🏻\u200d🌾",
+2491	    "woman_farmer_medium-dark_skin_tone": "👩🏾\u200d🌾",
+2492	    "woman_farmer_medium-light_skin_tone": "👩🏼\u200d🌾",
+2493	    "woman_farmer_medium_skin_tone": "👩🏽\u200d🌾",
+2494	    "woman_firefighter": "👩\u200d🚒",
+2495	    "woman_firefighter_dark_skin_tone": "👩🏿\u200d🚒",
+2496	    "woman_firefighter_light_skin_tone": "👩🏻\u200d🚒",
+2497	    "woman_firefighter_medium-dark_skin_tone": "👩🏾\u200d🚒",
+2498	    "woman_firefighter_medium-light_skin_tone": "👩🏼\u200d🚒",
+2499	    "woman_firefighter_medium_skin_tone": "👩🏽\u200d🚒",
+2500	    "woman_frowning": "🙍\u200d♀️",
+2501	    "woman_frowning_dark_skin_tone": "🙍🏿\u200d♀️",
+2502	    "woman_frowning_light_skin_tone": "🙍🏻\u200d♀️",
+2503	    "woman_frowning_medium-dark_skin_tone": "🙍🏾\u200d♀️",
+2504	    "woman_frowning_medium-light_skin_tone": "🙍🏼\u200d♀️",
+2505	    "woman_frowning_medium_skin_tone": "🙍🏽\u200d♀️",
+2506	    "woman_genie": "🧞\u200d♀️",
+2507	    "woman_gesturing_no": "🙅\u200d♀️",
+2508	    "woman_gesturing_no_dark_skin_tone": "🙅🏿\u200d♀️",
+2509	    "woman_gesturing_no_light_skin_tone": "🙅🏻\u200d♀️",
+2510	    "woman_gesturing_no_medium-dark_skin_tone": "🙅🏾\u200d♀️",
+2511	    "woman_gesturing_no_medium-light_skin_tone": "🙅🏼\u200d♀️",
+2512	    "woman_gesturing_no_medium_skin_tone": "🙅🏽\u200d♀️",
+2513	    "woman_gesturing_ok": "🙆\u200d♀️",
+2514	    "woman_gesturing_ok_dark_skin_tone": "🙆🏿\u200d♀️",
+2515	    "woman_gesturing_ok_light_skin_tone": "🙆🏻\u200d♀️",
+2516	    "woman_gesturing_ok_medium-dark_skin_tone": "🙆🏾\u200d♀️",
+2517	    "woman_gesturing_ok_medium-light_skin_tone": "🙆🏼\u200d♀️",
+2518	    "woman_gesturing_ok_medium_skin_tone": "🙆🏽\u200d♀️",
+2519	    "woman_getting_haircut": "💇\u200d♀️",
+2520	    "woman_getting_haircut_dark_skin_tone": "💇🏿\u200d♀️",
+2521	    "woman_getting_haircut_light_skin_tone": "💇🏻\u200d♀️",
+2522	    "woman_getting_haircut_medium-dark_skin_tone": "💇🏾\u200d♀️",
+2523	    "woman_getting_haircut_medium-light_skin_tone": "💇🏼\u200d♀️",
+2524	    "woman_getting_haircut_medium_skin_tone": "💇🏽\u200d♀️",
+2525	    "woman_getting_massage": "💆\u200d♀️",
+2526	    "woman_getting_massage_dark_skin_tone": "💆🏿\u200d♀️",
+2527	    "woman_getting_massage_light_skin_tone": "💆🏻\u200d♀️",
+2528	    "woman_getting_massage_medium-dark_skin_tone": "💆🏾\u200d♀️",
+2529	    "woman_getting_massage_medium-light_skin_tone": "💆🏼\u200d♀️",
+2530	    "woman_getting_massage_medium_skin_tone": "💆🏽\u200d♀️",
+2531	    "woman_golfing": "🏌️\u200d♀️",
+2532	    "woman_golfing_dark_skin_tone": "🏌🏿\u200d♀️",
+2533	    "woman_golfing_light_skin_tone": "🏌🏻\u200d♀️",
+2534	    "woman_golfing_medium-dark_skin_tone": "🏌🏾\u200d♀️",
+2535	    "woman_golfing_medium-light_skin_tone": "🏌🏼\u200d♀️",
+2536	    "woman_golfing_medium_skin_tone": "🏌🏽\u200d♀️",
+2537	    "woman_guard": "💂\u200d♀️",
+2538	    "woman_guard_dark_skin_tone": "💂🏿\u200d♀️",
+2539	    "woman_guard_light_skin_tone": "💂🏻\u200d♀️",
+2540	    "woman_guard_medium-dark_skin_tone": "💂🏾\u200d♀️",
+2541	    "woman_guard_medium-light_skin_tone": "💂🏼\u200d♀️",
+2542	    "woman_guard_medium_skin_tone": "💂🏽\u200d♀️",
+2543	    "woman_health_worker": "👩\u200d⚕️",
+2544	    "woman_health_worker_dark_skin_tone": "👩🏿\u200d⚕️",
+2545	    "woman_health_worker_light_skin_tone": "👩🏻\u200d⚕️",
+2546	    "woman_health_worker_medium-dark_skin_tone": "👩🏾\u200d⚕️",
+2547	    "woman_health_worker_medium-light_skin_tone": "👩🏼\u200d⚕️",
+2548	    "woman_health_worker_medium_skin_tone": "👩🏽\u200d⚕️",
+2549	    "woman_in_lotus_position": "🧘\u200d♀️",
+2550	    "woman_in_lotus_position_dark_skin_tone": "🧘🏿\u200d♀️",
+2551	    "woman_in_lotus_position_light_skin_tone": "🧘🏻\u200d♀️",
+2552	    "woman_in_lotus_position_medium-dark_skin_tone": "🧘🏾\u200d♀️",
+2553	    "woman_in_lotus_position_medium-light_skin_tone": "🧘🏼\u200d♀️",
+2554	    "woman_in_lotus_position_medium_skin_tone": "🧘🏽\u200d♀️",
+2555	    "woman_in_manual_wheelchair": "👩\u200d🦽",
+2556	    "woman_in_motorized_wheelchair": "👩\u200d🦼",
+2557	    "woman_in_steamy_room": "🧖\u200d♀️",
+2558	    "woman_in_steamy_room_dark_skin_tone": "🧖🏿\u200d♀️",
+2559	    "woman_in_steamy_room_light_skin_tone": "🧖🏻\u200d♀️",
+2560	    "woman_in_steamy_room_medium-dark_skin_tone": "🧖🏾\u200d♀️",
+2561	    "woman_in_steamy_room_medium-light_skin_tone": "🧖🏼\u200d♀️",
+2562	    "woman_in_steamy_room_medium_skin_tone": "🧖🏽\u200d♀️",
+2563	    "woman_judge": "👩\u200d⚖️",
+2564	    "woman_judge_dark_skin_tone": "👩🏿\u200d⚖️",
+2565	    "woman_judge_light_skin_tone": "👩🏻\u200d⚖️",
+2566	    "woman_judge_medium-dark_skin_tone": "👩🏾\u200d⚖️",
+2567	    "woman_judge_medium-light_skin_tone": "👩🏼\u200d⚖️",
+2568	    "woman_judge_medium_skin_tone": "👩🏽\u200d⚖️",
+2569	    "woman_juggling": "🤹\u200d♀️",
+2570	    "woman_juggling_dark_skin_tone": "🤹🏿\u200d♀️",
+2571	    "woman_juggling_light_skin_tone": "🤹🏻\u200d♀️",
+2572	    "woman_juggling_medium-dark_skin_tone": "🤹🏾\u200d♀️",
+2573	    "woman_juggling_medium-light_skin_tone": "🤹🏼\u200d♀️",
+2574	    "woman_juggling_medium_skin_tone": "🤹🏽\u200d♀️",
+2575	    "woman_lifting_weights": "🏋️\u200d♀️",
+2576	    "woman_lifting_weights_dark_skin_tone": "🏋🏿\u200d♀️",
+2577	    "woman_lifting_weights_light_skin_tone": "🏋🏻\u200d♀️",
+2578	    "woman_lifting_weights_medium-dark_skin_tone": "🏋🏾\u200d♀️",
+2579	    "woman_lifting_weights_medium-light_skin_tone": "🏋🏼\u200d♀️",
+2580	    "woman_lifting_weights_medium_skin_tone": "🏋🏽\u200d♀️",
+2581	    "woman_light_skin_tone": "👩🏻",
+2582	    "woman_mage": "🧙\u200d♀️",
+2583	    "woman_mage_dark_skin_tone": "🧙🏿\u200d♀️",
+2584	    "woman_mage_light_skin_tone": "🧙🏻\u200d♀️",
+2585	    "woman_mage_medium-dark_skin_tone": "🧙🏾\u200d♀️",
+2586	    "woman_mage_medium-light_skin_tone": "🧙🏼\u200d♀️",
+2587	    "woman_mage_medium_skin_tone": "🧙🏽\u200d♀️",
+2588	    "woman_mechanic": "👩\u200d🔧",
+2589	    "woman_mechanic_dark_skin_tone": "👩🏿\u200d🔧",
+2590	    "woman_mechanic_light_skin_tone": "👩🏻\u200d🔧",
+2591	    "woman_mechanic_medium-dark_skin_tone": "👩🏾\u200d🔧",
+2592	    "woman_mechanic_medium-light_skin_tone": "👩🏼\u200d🔧",
+2593	    "woman_mechanic_medium_skin_tone": "👩🏽\u200d🔧",
+2594	    "woman_medium-dark_skin_tone": "👩🏾",
+2595	    "woman_medium-light_skin_tone": "👩🏼",
+2596	    "woman_medium_skin_tone": "👩🏽",
+2597	    "woman_mountain_biking": "🚵\u200d♀️",
+2598	    "woman_mountain_biking_dark_skin_tone": "🚵🏿\u200d♀️",
+2599	    "woman_mountain_biking_light_skin_tone": "🚵🏻\u200d♀️",
+2600	    "woman_mountain_biking_medium-dark_skin_tone": "🚵🏾\u200d♀️",
+2601	    "woman_mountain_biking_medium-light_skin_tone": "🚵🏼\u200d♀️",
+2602	    "woman_mountain_biking_medium_skin_tone": "🚵🏽\u200d♀️",
+2603	    "woman_office_worker": "👩\u200d💼",
+2604	    "woman_office_worker_dark_skin_tone": "👩🏿\u200d💼",
+2605	    "woman_office_worker_light_skin_tone": "👩🏻\u200d💼",
+2606	    "woman_office_worker_medium-dark_skin_tone": "👩🏾\u200d💼",
+2607	    "woman_office_worker_medium-light_skin_tone": "👩🏼\u200d💼",
+2608	    "woman_office_worker_medium_skin_tone": "👩🏽\u200d💼",
+2609	    "woman_pilot": "👩\u200d✈️",
+2610	    "woman_pilot_dark_skin_tone": "👩🏿\u200d✈️",
+2611	    "woman_pilot_light_skin_tone": "👩🏻\u200d✈️",
+2612	    "woman_pilot_medium-dark_skin_tone": "👩🏾\u200d✈️",
+2613	    "woman_pilot_medium-light_skin_tone": "👩🏼\u200d✈️",
+2614	    "woman_pilot_medium_skin_tone": "👩🏽\u200d✈️",
+2615	    "woman_playing_handball": "🤾\u200d♀️",
+2616	    "woman_playing_handball_dark_skin_tone": "🤾🏿\u200d♀️",
+2617	    "woman_playing_handball_light_skin_tone": "🤾🏻\u200d♀️",
+2618	    "woman_playing_handball_medium-dark_skin_tone": "🤾🏾\u200d♀️",
+2619	    "woman_playing_handball_medium-light_skin_tone": "🤾🏼\u200d♀️",
+2620	    "woman_playing_handball_medium_skin_tone": "🤾🏽\u200d♀️",
+2621	    "woman_playing_water_polo": "🤽\u200d♀️",
+2622	    "woman_playing_water_polo_dark_skin_tone": "🤽🏿\u200d♀️",
+2623	    "woman_playing_water_polo_light_skin_tone": "🤽🏻\u200d♀️",
+2624	    "woman_playing_water_polo_medium-dark_skin_tone": "🤽🏾\u200d♀️",
+2625	    "woman_playing_water_polo_medium-light_skin_tone": "🤽🏼\u200d♀️",
+2626	    "woman_playing_water_polo_medium_skin_tone": "🤽🏽\u200d♀️",
+2627	    "woman_police_officer": "👮\u200d♀️",
+2628	    "woman_police_officer_dark_skin_tone": "👮🏿\u200d♀️",
+2629	    "woman_police_officer_light_skin_tone": "👮🏻\u200d♀️",
+2630	    "woman_police_officer_medium-dark_skin_tone": "👮🏾\u200d♀️",
+2631	    "woman_police_officer_medium-light_skin_tone": "👮🏼\u200d♀️",
+2632	    "woman_police_officer_medium_skin_tone": "👮🏽\u200d♀️",
+2633	    "woman_pouting": "🙎\u200d♀️",
+2634	    "woman_pouting_dark_skin_tone": "🙎🏿\u200d♀️",
+2635	    "woman_pouting_light_skin_tone": "🙎🏻\u200d♀️",
+2636	    "woman_pouting_medium-dark_skin_tone": "🙎🏾\u200d♀️",
+2637	    "woman_pouting_medium-light_skin_tone": "🙎🏼\u200d♀️",
+2638	    "woman_pouting_medium_skin_tone": "🙎🏽\u200d♀️",
+2639	    "woman_raising_hand": "🙋\u200d♀️",
+2640	    "woman_raising_hand_dark_skin_tone": "🙋🏿\u200d♀️",
+2641	    "woman_raising_hand_light_skin_tone": "🙋🏻\u200d♀️",
+2642	    "woman_raising_hand_medium-dark_skin_tone": "🙋🏾\u200d♀️",
+2643	    "woman_raising_hand_medium-light_skin_tone": "🙋🏼\u200d♀️",
+2644	    "woman_raising_hand_medium_skin_tone": "🙋🏽\u200d♀️",
+2645	    "woman_rowing_boat": "🚣\u200d♀️",
+2646	    "woman_rowing_boat_dark_skin_tone": "🚣🏿\u200d♀️",
+2647	    "woman_rowing_boat_light_skin_tone": "🚣🏻\u200d♀️",
+2648	    "woman_rowing_boat_medium-dark_skin_tone": "🚣🏾\u200d♀️",
+2649	    "woman_rowing_boat_medium-light_skin_tone": "🚣🏼\u200d♀️",
+2650	    "woman_rowing_boat_medium_skin_tone": "🚣🏽\u200d♀️",
+2651	    "woman_running": "🏃\u200d♀️",
+2652	    "woman_running_dark_skin_tone": "🏃🏿\u200d♀️",
+2653	    "woman_running_light_skin_tone": "🏃🏻\u200d♀️",
+2654	    "woman_running_medium-dark_skin_tone": "🏃🏾\u200d♀️",
+2655	    "woman_running_medium-light_skin_tone": "🏃🏼\u200d♀️",
+2656	    "woman_running_medium_skin_tone": "🏃🏽\u200d♀️",
+2657	    "woman_scientist": "👩\u200d🔬",
+2658	    "woman_scientist_dark_skin_tone": "👩🏿\u200d🔬",
+2659	    "woman_scientist_light_skin_tone": "👩🏻\u200d🔬",
+2660	    "woman_scientist_medium-dark_skin_tone": "👩🏾\u200d🔬",
+2661	    "woman_scientist_medium-light_skin_tone": "👩🏼\u200d🔬",
+2662	    "woman_scientist_medium_skin_tone": "👩🏽\u200d🔬",
+2663	    "woman_shrugging": "🤷\u200d♀️",
+2664	    "woman_shrugging_dark_skin_tone": "🤷🏿\u200d♀️",
+2665	    "woman_shrugging_light_skin_tone": "🤷🏻\u200d♀️",
+2666	    "woman_shrugging_medium-dark_skin_tone": "🤷🏾\u200d♀️",
+2667	    "woman_shrugging_medium-light_skin_tone": "🤷🏼\u200d♀️",
+2668	    "woman_shrugging_medium_skin_tone": "🤷🏽\u200d♀️",
+2669	    "woman_singer": "👩\u200d🎤",
+2670	    "woman_singer_dark_skin_tone": "👩🏿\u200d🎤",
+2671	    "woman_singer_light_skin_tone": "👩🏻\u200d🎤",
+2672	    "woman_singer_medium-dark_skin_tone": "👩🏾\u200d🎤",
+2673	    "woman_singer_medium-light_skin_tone": "👩🏼\u200d🎤",
+2674	    "woman_singer_medium_skin_tone": "👩🏽\u200d🎤",
+2675	    "woman_student": "👩\u200d🎓",
+2676	    "woman_student_dark_skin_tone": "👩🏿\u200d🎓",
+2677	    "woman_student_light_skin_tone": "👩🏻\u200d🎓",
+2678	    "woman_student_medium-dark_skin_tone": "👩🏾\u200d🎓",
+2679	    "woman_student_medium-light_skin_tone": "👩🏼\u200d🎓",
+2680	    "woman_student_medium_skin_tone": "👩🏽\u200d🎓",
+2681	    "woman_surfing": "🏄\u200d♀️",
+2682	    "woman_surfing_dark_skin_tone": "🏄🏿\u200d♀️",
+2683	    "woman_surfing_light_skin_tone": "🏄🏻\u200d♀️",
+2684	    "woman_surfing_medium-dark_skin_tone": "🏄🏾\u200d♀️",
+2685	    "woman_surfing_medium-light_skin_tone": "🏄🏼\u200d♀️",
+2686	    "woman_surfing_medium_skin_tone": "🏄🏽\u200d♀️",
+2687	    "woman_swimming": "🏊\u200d♀️",
+2688	    "woman_swimming_dark_skin_tone": "🏊🏿\u200d♀️",
+2689	    "woman_swimming_light_skin_tone": "🏊🏻\u200d♀️",
+2690	    "woman_swimming_medium-dark_skin_tone": "🏊🏾\u200d♀️",
+2691	    "woman_swimming_medium-light_skin_tone": "🏊🏼\u200d♀️",
+2692	    "woman_swimming_medium_skin_tone": "🏊🏽\u200d♀️",
+2693	    "woman_teacher": "👩\u200d🏫",
+2694	    "woman_teacher_dark_skin_tone": "👩🏿\u200d🏫",
+2695	    "woman_teacher_light_skin_tone": "👩🏻\u200d🏫",
+2696	    "woman_teacher_medium-dark_skin_tone": "👩🏾\u200d🏫",
+2697	    "woman_teacher_medium-light_skin_tone": "👩🏼\u200d🏫",
+2698	    "woman_teacher_medium_skin_tone": "👩🏽\u200d🏫",
+2699	    "woman_technologist": "👩\u200d💻",
+2700	    "woman_technologist_dark_skin_tone": "👩🏿\u200d💻",
+2701	    "woman_technologist_light_skin_tone": "👩🏻\u200d💻",
+2702	    "woman_technologist_medium-dark_skin_tone": "👩🏾\u200d💻",
+2703	    "woman_technologist_medium-light_skin_tone": "👩🏼\u200d💻",
+2704	    "woman_technologist_medium_skin_tone": "👩🏽\u200d💻",
+2705	    "woman_tipping_hand": "💁\u200d♀️",
+2706	    "woman_tipping_hand_dark_skin_tone": "💁🏿\u200d♀️",
+2707	    "woman_tipping_hand_light_skin_tone": "💁🏻\u200d♀️",
+2708	    "woman_tipping_hand_medium-dark_skin_tone": "💁🏾\u200d♀️",
+2709	    "woman_tipping_hand_medium-light_skin_tone": "💁🏼\u200d♀️",
+2710	    "woman_tipping_hand_medium_skin_tone": "💁🏽\u200d♀️",
+2711	    "woman_vampire": "🧛\u200d♀️",
+2712	    "woman_vampire_dark_skin_tone": "🧛🏿\u200d♀️",
+2713	    "woman_vampire_light_skin_tone": "🧛🏻\u200d♀️",
+2714	    "woman_vampire_medium-dark_skin_tone": "🧛🏾\u200d♀️",
+2715	    "woman_vampire_medium-light_skin_tone": "🧛🏼\u200d♀️",
+2716	    "woman_vampire_medium_skin_tone": "🧛🏽\u200d♀️",
+2717	    "woman_walking": "🚶\u200d♀️",
+2718	    "woman_walking_dark_skin_tone": "🚶🏿\u200d♀️",
+2719	    "woman_walking_light_skin_tone": "🚶🏻\u200d♀️",
+2720	    "woman_walking_medium-dark_skin_tone": "🚶🏾\u200d♀️",
+2721	    "woman_walking_medium-light_skin_tone": "🚶🏼\u200d♀️",
+2722	    "woman_walking_medium_skin_tone": "🚶🏽\u200d♀️",
+2723	    "woman_wearing_turban": "👳\u200d♀️",
+2724	    "woman_wearing_turban_dark_skin_tone": "👳🏿\u200d♀️",
+2725	    "woman_wearing_turban_light_skin_tone": "👳🏻\u200d♀️",
+2726	    "woman_wearing_turban_medium-dark_skin_tone": "👳🏾\u200d♀️",
+2727	    "woman_wearing_turban_medium-light_skin_tone": "👳🏼\u200d♀️",
+2728	    "woman_wearing_turban_medium_skin_tone": "👳🏽\u200d♀️",
+2729	    "woman_with_headscarf": "🧕",
+2730	    "woman_with_headscarf_dark_skin_tone": "🧕🏿",
+2731	    "woman_with_headscarf_light_skin_tone": "🧕🏻",
+2732	    "woman_with_headscarf_medium-dark_skin_tone": "🧕🏾",
+2733	    "woman_with_headscarf_medium-light_skin_tone": "🧕🏼",
+2734	    "woman_with_headscarf_medium_skin_tone": "🧕🏽",
+2735	    "woman_with_probing_cane": "👩\u200d🦯",
+2736	    "woman_zombie": "🧟\u200d♀️",
+2737	    "woman’s_boot": "👢",
+2738	    "woman’s_clothes": "👚",
+2739	    "woman’s_hat": "👒",
+2740	    "woman’s_sandal": "👡",
+2741	    "women_with_bunny_ears": "👯\u200d♀️",
+2742	    "women_wrestling": "🤼\u200d♀️",
+2743	    "women’s_room": "🚺",
+2744	    "woozy_face": "🥴",
+2745	    "world_map": "🗺",
+2746	    "worried_face": "😟",
+2747	    "wrapped_gift": "🎁",
+2748	    "wrench": "🔧",
+2749	    "writing_hand": "✍",
+2750	    "writing_hand_dark_skin_tone": "✍🏿",
+2751	    "writing_hand_light_skin_tone": "✍🏻",
+2752	    "writing_hand_medium-dark_skin_tone": "✍🏾",
+2753	    "writing_hand_medium-light_skin_tone": "✍🏼",
+2754	    "writing_hand_medium_skin_tone": "✍🏽",
+2755	    "yarn": "🧶",
+2756	    "yawning_face": "🥱",
+2757	    "yellow_circle": "🟡",
+2758	    "yellow_heart": "💛",
+2759	    "yellow_square": "🟨",
+2760	    "yen_banknote": "💴",
+2761	    "yo-yo": "🪀",
+2762	    "yin_yang": "☯",
+2763	    "zany_face": "🤪",
+2764	    "zebra": "🦓",
+2765	    "zipper-mouth_face": "🤐",
+2766	    "zombie": "🧟",
+2767	    "zzz": "💤",
+2768	    "åland_islands": "🇦🇽",
+2769	    "keycap_asterisk": "*⃣",
+2770	    "keycap_digit_eight": "8⃣",
+2771	    "keycap_digit_five": "5⃣",
+2772	    "keycap_digit_four": "4⃣",
+2773	    "keycap_digit_nine": "9⃣",
+2774	    "keycap_digit_one": "1⃣",
+2775	    "keycap_digit_seven": "7⃣",
+2776	    "keycap_digit_six": "6⃣",
+2777	    "keycap_digit_three": "3⃣",
+2778	    "keycap_digit_two": "2⃣",
+2779	    "keycap_digit_zero": "0⃣",
+2780	    "keycap_number_sign": "#⃣",
+2781	    "light_skin_tone": "🏻",
+2782	    "medium_light_skin_tone": "🏼",
+2783	    "medium_skin_tone": "🏽",
+2784	    "medium_dark_skin_tone": "🏾",
+2785	    "dark_skin_tone": "🏿",
+2786	    "regional_indicator_symbol_letter_a": "🇦",
+2787	    "regional_indicator_symbol_letter_b": "🇧",
+2788	    "regional_indicator_symbol_letter_c": "🇨",
+2789	    "regional_indicator_symbol_letter_d": "🇩",
+2790	    "regional_indicator_symbol_letter_e": "🇪",
+2791	    "regional_indicator_symbol_letter_f": "🇫",
+2792	    "regional_indicator_symbol_letter_g": "🇬",
+2793	    "regional_indicator_symbol_letter_h": "🇭",
+2794	    "regional_indicator_symbol_letter_i": "🇮",
+2795	    "regional_indicator_symbol_letter_j": "🇯",
+2796	    "regional_indicator_symbol_letter_k": "🇰",
+2797	    "regional_indicator_symbol_letter_l": "🇱",
+2798	    "regional_indicator_symbol_letter_m": "🇲",
+2799	    "regional_indicator_symbol_letter_n": "🇳",
+2800	    "regional_indicator_symbol_letter_o": "🇴",
+2801	    "regional_indicator_symbol_letter_p": "🇵",
+2802	    "regional_indicator_symbol_letter_q": "🇶",
+2803	    "regional_indicator_symbol_letter_r": "🇷",
+2804	    "regional_indicator_symbol_letter_s": "🇸",
+2805	    "regional_indicator_symbol_letter_t": "🇹",
+2806	    "regional_indicator_symbol_letter_u": "🇺",
+2807	    "regional_indicator_symbol_letter_v": "🇻",
+2808	    "regional_indicator_symbol_letter_w": "🇼",
+2809	    "regional_indicator_symbol_letter_x": "🇽",
+2810	    "regional_indicator_symbol_letter_y": "🇾",
+2811	    "regional_indicator_symbol_letter_z": "🇿",
+2812	    "airplane_arriving": "🛬",
+2813	    "space_invader": "👾",
+2814	    "football": "🏈",
+2815	    "anger": "💢",
+2816	    "angry": "😠",
+2817	    "anguished": "😧",
+2818	    "signal_strength": "📶",
+2819	    "arrows_counterclockwise": "🔄",
+2820	    "arrow_heading_down": "⤵",
+2821	    "arrow_heading_up": "⤴",
+2822	    "art": "🎨",
+2823	    "astonished": "😲",
+2824	    "athletic_shoe": "👟",
+2825	    "atm": "🏧",
+2826	    "car": "🚗",
+2827	    "red_car": "🚗",
+2828	    "angel": "👼",
+2829	    "back": "🔙",
+2830	    "badminton_racquet_and_shuttlecock": "🏸",
+2831	    "dollar": "💵",
+2832	    "euro": "💶",
+2833	    "pound": "💷",
+2834	    "yen": "💴",
+2835	    "barber": "💈",
+2836	    "bath": "🛀",
+2837	    "bear": "🐻",
+2838	    "heartbeat": "💓",
+2839	    "beer": "🍺",
+2840	    "no_bell": "🔕",
+2841	    "bento": "🍱",
+2842	    "bike": "🚲",
+2843	    "bicyclist": "🚴",
+2844	    "8ball": "🎱",
+2845	    "biohazard_sign": "☣",
+2846	    "birthday": "🎂",
+2847	    "black_circle_for_record": "⏺",
+2848	    "clubs": "♣",
+2849	    "diamonds": "♦",
+2850	    "arrow_double_down": "⏬",
+2851	    "hearts": "♥",
+2852	    "rewind": "⏪",
+2853	    "black_left__pointing_double_triangle_with_vertical_bar": "⏮",
+2854	    "arrow_backward": "◀",
+2855	    "black_medium_small_square": "◾",
+2856	    "question": "❓",
+2857	    "fast_forward": "⏩",
+2858	    "black_right__pointing_double_triangle_with_vertical_bar": "⏭",
+2859	    "arrow_forward": "▶",
+2860	    "black_right__pointing_triangle_with_double_vertical_bar": "⏯",
+2861	    "arrow_right": "➡",
+2862	    "spades": "♠",
+2863	    "black_square_for_stop": "⏹",
+2864	    "sunny": "☀",
+2865	    "phone": "☎",
+2866	    "recycle": "♻",
+2867	    "arrow_double_up": "⏫",
+2868	    "busstop": "🚏",
+2869	    "date": "📅",
+2870	    "flags": "🎏",
+2871	    "cat2": "🐈",
+2872	    "joy_cat": "😹",
+2873	    "smirk_cat": "😼",
+2874	    "chart_with_downwards_trend": "📉",
+2875	    "chart_with_upwards_trend": "📈",
+2876	    "chart": "💹",
+2877	    "mega": "📣",
+2878	    "checkered_flag": "🏁",
+2879	    "accept": "🉑",
+2880	    "ideograph_advantage": "🉐",
+2881	    "congratulations": "㊗",
+2882	    "secret": "㊙",
+2883	    "m": "Ⓜ",
+2884	    "city_sunset": "🌆",
+2885	    "clapper": "🎬",
+2886	    "clap": "👏",
+2887	    "beers": "🍻",
+2888	    "clock830": "🕣",
+2889	    "clock8": "🕗",
+2890	    "clock1130": "🕦",
+2891	    "clock11": "🕚",
+2892	    "clock530": "🕠",
+2893	    "clock5": "🕔",
+2894	    "clock430": "🕟",
+2895	    "clock4": "🕓",
+2896	    "clock930": "🕤",
+2897	    "clock9": "🕘",
+2898	    "clock130": "🕜",
+2899	    "clock1": "🕐",
+2900	    "clock730": "🕢",
+2901	    "clock7": "🕖",
+2902	    "clock630": "🕡",
+2903	    "clock6": "🕕",
+2904	    "clock1030": "🕥",
+2905	    "clock10": "🕙",
+2906	    "clock330": "🕞",
+2907	    "clock3": "🕒",
+2908	    "clock1230": "🕧",
+2909	    "clock12": "🕛",
+2910	    "clock230": "🕝",
+2911	    "clock2": "🕑",
+2912	    "arrows_clockwise": "🔃",
+2913	    "repeat": "🔁",
+2914	    "repeat_one": "🔂",
+2915	    "closed_lock_with_key": "🔐",
+2916	    "mailbox_closed": "📪",
+2917	    "mailbox": "📫",
+2918	    "cloud_with_tornado": "🌪",
+2919	    "cocktail": "🍸",
+2920	    "boom": "💥",
+2921	    "compression": "🗜",
+2922	    "confounded": "😖",
+2923	    "confused": "😕",
+2924	    "rice": "🍚",
+2925	    "cow2": "🐄",
+2926	    "cricket_bat_and_ball": "🏏",
+2927	    "x": "❌",
+2928	    "cry": "😢",
+2929	    "curry": "🍛",
+2930	    "dagger_knife": "🗡",
+2931	    "dancer": "💃",
+2932	    "dark_sunglasses": "🕶",
+2933	    "dash": "💨",
+2934	    "truck": "🚚",
+2935	    "derelict_house_building": "🏚",
+2936	    "diamond_shape_with_a_dot_inside": "💠",
+2937	    "dart": "🎯",
+2938	    "disappointed_relieved": "😥",
+2939	    "disappointed": "😞",
+2940	    "do_not_litter": "🚯",
+2941	    "dog2": "🐕",
+2942	    "flipper": "🐬",
+2943	    "loop": "➿",
+2944	    "bangbang": "‼",
+2945	    "double_vertical_bar": "⏸",
+2946	    "dove_of_peace": "🕊",
+2947	    "small_red_triangle_down": "🔻",
+2948	    "arrow_down_small": "🔽",
+2949	    "arrow_down": "⬇",
+2950	    "dromedary_camel": "🐪",
+2951	    "e__mail": "📧",
+2952	    "corn": "🌽",
+2953	    "ear_of_rice": "🌾",
+2954	    "earth_americas": "🌎",
+2955	    "earth_asia": "🌏",
+2956	    "earth_africa": "🌍",
+2957	    "eight_pointed_black_star": "✴",
+2958	    "eight_spoked_asterisk": "✳",
+2959	    "eject_symbol": "⏏",
+2960	    "bulb": "💡",
+2961	    "emoji_modifier_fitzpatrick_type__1__2": "🏻",
+2962	    "emoji_modifier_fitzpatrick_type__3": "🏼",
+2963	    "emoji_modifier_fitzpatrick_type__4": "🏽",
+2964	    "emoji_modifier_fitzpatrick_type__5": "🏾",
+2965	    "emoji_modifier_fitzpatrick_type__6": "🏿",
+2966	    "end": "🔚",
+2967	    "email": "✉",
+2968	    "european_castle": "🏰",
+2969	    "european_post_office": "🏤",
+2970	    "interrobang": "⁉",
+2971	    "expressionless": "😑",
+2972	    "eyeglasses": "👓",
+2973	    "massage": "💆",
+2974	    "yum": "😋",
+2975	    "scream": "😱",
+2976	    "kissing_heart": "😘",
+2977	    "sweat": "😓",
+2978	    "face_with_head__bandage": "🤕",
+2979	    "triumph": "😤",
+2980	    "mask": "😷",
+2981	    "no_good": "🙅",
+2982	    "ok_woman": "🙆",
+2983	    "open_mouth": "😮",
+2984	    "cold_sweat": "😰",
+2985	    "stuck_out_tongue": "😛",
+2986	    "stuck_out_tongue_closed_eyes": "😝",
+2987	    "stuck_out_tongue_winking_eye": "😜",
+2988	    "joy": "😂",
+2989	    "no_mouth": "😶",
+2990	    "santa": "🎅",
+2991	    "fax": "📠",
+2992	    "fearful": "😨",
+2993	    "field_hockey_stick_and_ball": "🏑",
+2994	    "first_quarter_moon_with_face": "🌛",
+2995	    "fish_cake": "🍥",
+2996	    "fishing_pole_and_fish": "🎣",
+2997	    "facepunch": "👊",
+2998	    "punch": "👊",
+2999	    "flag_for_afghanistan": "🇦🇫",
+3000	    "flag_for_albania": "🇦🇱",
+3001	    "flag_for_algeria": "🇩🇿",
+3002	    "flag_for_american_samoa": "🇦🇸",
+3003	    "flag_for_andorra": "🇦🇩",
+3004	    "flag_for_angola": "🇦🇴",
+3005	    "flag_for_anguilla": "🇦🇮",
+3006	    "flag_for_antarctica": "🇦🇶",
+3007	    "flag_for_antigua_&_barbuda": "🇦🇬",
+3008	    "flag_for_argentina": "🇦🇷",
+3009	    "flag_for_armenia": "🇦🇲",
+3010	    "flag_for_aruba": "🇦🇼",
+3011	    "flag_for_ascension_island": "🇦🇨",
+3012	    "flag_for_australia": "🇦🇺",
+3013	    "flag_for_austria": "🇦🇹",
+3014	    "flag_for_azerbaijan": "🇦🇿",
+3015	    "flag_for_bahamas": "🇧🇸",
+3016	    "flag_for_bahrain": "🇧🇭",
+3017	    "flag_for_bangladesh": "🇧🇩",
+3018	    "flag_for_barbados": "🇧🇧",
+3019	    "flag_for_belarus": "🇧🇾",
+3020	    "flag_for_belgium": "🇧🇪",
+3021	    "flag_for_belize": "🇧🇿",
+3022	    "flag_for_benin": "🇧🇯",
+3023	    "flag_for_bermuda": "🇧🇲",
+3024	    "flag_for_bhutan": "🇧🇹",
+3025	    "flag_for_bolivia": "🇧🇴",
+3026	    "flag_for_bosnia_&_herzegovina": "🇧🇦",
+3027	    "flag_for_botswana": "🇧🇼",
+3028	    "flag_for_bouvet_island": "🇧🇻",
+3029	    "flag_for_brazil": "🇧🇷",
+3030	    "flag_for_british_indian_ocean_territory": "🇮🇴",
+3031	    "flag_for_british_virgin_islands": "🇻🇬",
+3032	    "flag_for_brunei": "🇧🇳",
+3033	    "flag_for_bulgaria": "🇧🇬",
+3034	    "flag_for_burkina_faso": "🇧🇫",
+3035	    "flag_for_burundi": "🇧🇮",
+3036	    "flag_for_cambodia": "🇰🇭",
+3037	    "flag_for_cameroon": "🇨🇲",
+3038	    "flag_for_canada": "🇨🇦",
+3039	    "flag_for_canary_islands": "🇮🇨",
+3040	    "flag_for_cape_verde": "🇨🇻",
+3041	    "flag_for_caribbean_netherlands": "🇧🇶",
+3042	    "flag_for_cayman_islands": "🇰🇾",
+3043	    "flag_for_central_african_republic": "🇨🇫",
+3044	    "flag_for_ceuta_&_melilla": "🇪🇦",
+3045	    "flag_for_chad": "🇹🇩",
+3046	    "flag_for_chile": "🇨🇱",
+3047	    "flag_for_china": "🇨🇳",
+3048	    "flag_for_christmas_island": "🇨🇽",
+3049	    "flag_for_clipperton_island": "🇨🇵",
+3050	    "flag_for_cocos__islands": "🇨🇨",
+3051	    "flag_for_colombia": "🇨🇴",
+3052	    "flag_for_comoros": "🇰🇲",
+3053	    "flag_for_congo____brazzaville": "🇨🇬",
+3054	    "flag_for_congo____kinshasa": "🇨🇩",
+3055	    "flag_for_cook_islands": "🇨🇰",
+3056	    "flag_for_costa_rica": "🇨🇷",
+3057	    "flag_for_croatia": "🇭🇷",
+3058	    "flag_for_cuba": "🇨🇺",
+3059	    "flag_for_curaçao": "🇨🇼",
+3060	    "flag_for_cyprus": "🇨🇾",
+3061	    "flag_for_czech_republic": "🇨🇿",
+3062	    "flag_for_côte_d’ivoire": "🇨🇮",
+3063	    "flag_for_denmark": "🇩🇰",
+3064	    "flag_for_diego_garcia": "🇩🇬",
+3065	    "flag_for_djibouti": "🇩🇯",
+3066	    "flag_for_dominica": "🇩🇲",
+3067	    "flag_for_dominican_republic": "🇩🇴",
+3068	    "flag_for_ecuador": "🇪🇨",
+3069	    "flag_for_egypt": "🇪🇬",
+3070	    "flag_for_el_salvador": "🇸🇻",
+3071	    "flag_for_equatorial_guinea": "🇬🇶",
+3072	    "flag_for_eritrea": "🇪🇷",
+3073	    "flag_for_estonia": "🇪🇪",
+3074	    "flag_for_ethiopia": "🇪🇹",
+3075	    "flag_for_european_union": "🇪🇺",
+3076	    "flag_for_falkland_islands": "🇫🇰",
+3077	    "flag_for_faroe_islands": "🇫🇴",
+3078	    "flag_for_fiji": "🇫🇯",
+3079	    "flag_for_finland": "🇫🇮",
+3080	    "flag_for_france": "🇫🇷",
+3081	    "flag_for_french_guiana": "🇬🇫",
+3082	    "flag_for_french_polynesia": "🇵🇫",
+3083	    "flag_for_french_southern_territories": "🇹🇫",
+3084	    "flag_for_gabon": "🇬🇦",
+3085	    "flag_for_gambia": "🇬🇲",
+3086	    "flag_for_georgia": "🇬🇪",
+3087	    "flag_for_germany": "🇩🇪",
+3088	    "flag_for_ghana": "🇬🇭",
+3089	    "flag_for_gibraltar": "🇬🇮",
+3090	    "flag_for_greece": "🇬🇷",
+3091	    "flag_for_greenland": "🇬🇱",
+3092	    "flag_for_grenada": "🇬🇩",
+3093	    "flag_for_guadeloupe": "🇬🇵",
+3094	    "flag_for_guam": "🇬🇺",
+3095	    "flag_for_guatemala": "🇬🇹",
+3096	    "flag_for_guernsey": "🇬🇬",
+3097	    "flag_for_guinea": "🇬🇳",
+3098	    "flag_for_guinea__bissau": "🇬🇼",
+3099	    "flag_for_guyana": "🇬🇾",
+3100	    "flag_for_haiti": "🇭🇹",
+3101	    "flag_for_heard_&_mcdonald_islands": "🇭🇲",
+3102	    "flag_for_honduras": "🇭🇳",
+3103	    "flag_for_hong_kong": "🇭🇰",
+3104	    "flag_for_hungary": "🇭🇺",
+3105	    "flag_for_iceland": "🇮🇸",
+3106	    "flag_for_india": "🇮🇳",
+3107	    "flag_for_indonesia": "🇮🇩",
+3108	    "flag_for_iran": "🇮🇷",
+3109	    "flag_for_iraq": "🇮🇶",
+3110	    "flag_for_ireland": "🇮🇪",
+3111	    "flag_for_isle_of_man": "🇮🇲",
+3112	    "flag_for_israel": "🇮🇱",
+3113	    "flag_for_italy": "🇮🇹",
+3114	    "flag_for_jamaica": "🇯🇲",
+3115	    "flag_for_japan": "🇯🇵",
+3116	    "flag_for_jersey": "🇯🇪",
+3117	    "flag_for_jordan": "🇯🇴",
+3118	    "flag_for_kazakhstan": "🇰🇿",
+3119	    "flag_for_kenya": "🇰🇪",
+3120	    "flag_for_kiribati": "🇰🇮",
+3121	    "flag_for_kosovo": "🇽🇰",
+3122	    "flag_for_kuwait": "🇰🇼",
+3123	    "flag_for_kyrgyzstan": "🇰🇬",
+3124	    "flag_for_laos": "🇱🇦",
+3125	    "flag_for_latvia": "🇱🇻",
+3126	    "flag_for_lebanon": "🇱🇧",
+3127	    "flag_for_lesotho": "🇱🇸",
+3128	    "flag_for_liberia": "🇱🇷",
+3129	    "flag_for_libya": "🇱🇾",
+3130	    "flag_for_liechtenstein": "🇱🇮",
+3131	    "flag_for_lithuania": "🇱🇹",
+3132	    "flag_for_luxembourg": "🇱🇺",
+3133	    "flag_for_macau": "🇲🇴",
+3134	    "flag_for_macedonia": "🇲🇰",
+3135	    "flag_for_madagascar": "🇲🇬",
+3136	    "flag_for_malawi": "🇲🇼",
+3137	    "flag_for_malaysia": "🇲🇾",
+3138	    "flag_for_maldives": "🇲🇻",
+3139	    "flag_for_mali": "🇲🇱",
+3140	    "flag_for_malta": "🇲🇹",
+3141	    "flag_for_marshall_islands": "🇲🇭",
+3142	    "flag_for_martinique": "🇲🇶",
+3143	    "flag_for_mauritania": "🇲🇷",
+3144	    "flag_for_mauritius": "🇲🇺",
+3145	    "flag_for_mayotte": "🇾🇹",
+3146	    "flag_for_mexico": "🇲🇽",
+3147	    "flag_for_micronesia": "🇫🇲",
+3148	    "flag_for_moldova": "🇲🇩",
+3149	    "flag_for_monaco": "🇲🇨",
+3150	    "flag_for_mongolia": "🇲🇳",
+3151	    "flag_for_montenegro": "🇲🇪",
+3152	    "flag_for_montserrat": "🇲🇸",
+3153	    "flag_for_morocco": "🇲🇦",
+3154	    "flag_for_mozambique": "🇲🇿",
+3155	    "flag_for_myanmar": "🇲🇲",
+3156	    "flag_for_namibia": "🇳🇦",
+3157	    "flag_for_nauru": "🇳🇷",
+3158	    "flag_for_nepal": "🇳🇵",
+3159	    "flag_for_netherlands": "🇳🇱",
+3160	    "flag_for_new_caledonia": "🇳🇨",
+3161	    "flag_for_new_zealand": "🇳🇿",
+3162	    "flag_for_nicaragua": "🇳🇮",
+3163	    "flag_for_niger": "🇳🇪",
+3164	    "flag_for_nigeria": "🇳🇬",
+3165	    "flag_for_niue": "🇳🇺",
+3166	    "flag_for_norfolk_island": "🇳🇫",
+3167	    "flag_for_north_korea": "🇰🇵",
+3168	    "flag_for_northern_mariana_islands": "🇲🇵",
+3169	    "flag_for_norway": "🇳🇴",
+3170	    "flag_for_oman": "🇴🇲",
+3171	    "flag_for_pakistan": "🇵🇰",
+3172	    "flag_for_palau": "🇵🇼",
+3173	    "flag_for_palestinian_territories": "🇵🇸",
+3174	    "flag_for_panama": "🇵🇦",
+3175	    "flag_for_papua_new_guinea": "🇵🇬",
+3176	    "flag_for_paraguay": "🇵🇾",
+3177	    "flag_for_peru": "🇵🇪",
+3178	    "flag_for_philippines": "🇵🇭",
+3179	    "flag_for_pitcairn_islands": "🇵🇳",
+3180	    "flag_for_poland": "🇵🇱",
+3181	    "flag_for_portugal": "🇵🇹",
+3182	    "flag_for_puerto_rico": "🇵🇷",
+3183	    "flag_for_qatar": "🇶🇦",
+3184	    "flag_for_romania": "🇷🇴",
+3185	    "flag_for_russia": "🇷🇺",
+3186	    "flag_for_rwanda": "🇷🇼",
+3187	    "flag_for_réunion": "🇷🇪",
+3188	    "flag_for_samoa": "🇼🇸",
+3189	    "flag_for_san_marino": "🇸🇲",
+3190	    "flag_for_saudi_arabia": "🇸🇦",
+3191	    "flag_for_senegal": "🇸🇳",
+3192	    "flag_for_serbia": "🇷🇸",
+3193	    "flag_for_seychelles": "🇸🇨",
+3194	    "flag_for_sierra_leone": "🇸🇱",
+3195	    "flag_for_singapore": "🇸🇬",
+3196	    "flag_for_sint_maarten": "🇸🇽",
+3197	    "flag_for_slovakia": "🇸🇰",
+3198	    "flag_for_slovenia": "🇸🇮",
+3199	    "flag_for_solomon_islands": "🇸🇧",
+3200	    "flag_for_somalia": "🇸🇴",
+3201	    "flag_for_south_africa": "🇿🇦",
+3202	    "flag_for_south_georgia_&_south_sandwich_islands": "🇬🇸",
+3203	    "flag_for_south_korea": "🇰🇷",
+3204	    "flag_for_south_sudan": "🇸🇸",
+3205	    "flag_for_spain": "🇪🇸",
+3206	    "flag_for_sri_lanka": "🇱🇰",
+3207	    "flag_for_st._barthélemy": "🇧🇱",
+3208	    "flag_for_st._helena": "🇸🇭",
+3209	    "flag_for_st._kitts_&_nevis": "🇰🇳",
+3210	    "flag_for_st._lucia": "🇱🇨",
+3211	    "flag_for_st._martin": "🇲🇫",
+3212	    "flag_for_st._pierre_&_miquelon": "🇵🇲",
+3213	    "flag_for_st._vincent_&_grenadines": "🇻🇨",
+3214	    "flag_for_sudan": "🇸🇩",
+3215	    "flag_for_suriname": "🇸🇷",
+3216	    "flag_for_svalbard_&_jan_mayen": "🇸🇯",
+3217	    "flag_for_swaziland": "🇸🇿",
+3218	    "flag_for_sweden": "🇸🇪",
+3219	    "flag_for_switzerland": "🇨🇭",
+3220	    "flag_for_syria": "🇸🇾",
+3221	    "flag_for_são_tomé_&_príncipe": "🇸🇹",
+3222	    "flag_for_taiwan": "🇹🇼",
+3223	    "flag_for_tajikistan": "🇹🇯",
+3224	    "flag_for_tanzania": "🇹🇿",
+3225	    "flag_for_thailand": "🇹🇭",
+3226	    "flag_for_timor__leste": "🇹🇱",
+3227	    "flag_for_togo": "🇹🇬",
+3228	    "flag_for_tokelau": "🇹🇰",
+3229	    "flag_for_tonga": "🇹🇴",
+3230	    "flag_for_trinidad_&_tobago": "🇹🇹",
+3231	    "flag_for_tristan_da_cunha": "🇹🇦",
+3232	    "flag_for_tunisia": "🇹🇳",
+3233	    "flag_for_turkey": "🇹🇷",
+3234	    "flag_for_turkmenistan": "🇹🇲",
+3235	    "flag_for_turks_&_caicos_islands": "🇹🇨",
+3236	    "flag_for_tuvalu": "🇹🇻",
+3237	    "flag_for_u.s._outlying_islands": "🇺🇲",
+3238	    "flag_for_u.s._virgin_islands": "🇻🇮",
+3239	    "flag_for_uganda": "🇺🇬",
+3240	    "flag_for_ukraine": "🇺🇦",
+3241	    "flag_for_united_arab_emirates": "🇦🇪",
+3242	    "flag_for_united_kingdom": "🇬🇧",
+3243	    "flag_for_united_states": "🇺🇸",
+3244	    "flag_for_uruguay": "🇺🇾",
+3245	    "flag_for_uzbekistan": "🇺🇿",
+3246	    "flag_for_vanuatu": "🇻🇺",
+3247	    "flag_for_vatican_city": "🇻🇦",
+3248	    "flag_for_venezuela": "🇻🇪",
+3249	    "flag_for_vietnam": "🇻🇳",
+3250	    "flag_for_wallis_&_futuna": "🇼🇫",
+3251	    "flag_for_western_sahara": "🇪🇭",
+3252	    "flag_for_yemen": "🇾🇪",
+3253	    "flag_for_zambia": "🇿🇲",
+3254	    "flag_for_zimbabwe": "🇿🇼",
+3255	    "flag_for_åland_islands": "🇦🇽",
+3256	    "golf": "⛳",
+3257	    "fleur__de__lis": "⚜",
+3258	    "muscle": "💪",
+3259	    "flushed": "😳",
+3260	    "frame_with_picture": "🖼",
+3261	    "fries": "🍟",
+3262	    "frog": "🐸",
+3263	    "hatched_chick": "🐥",
+3264	    "frowning": "😦",
+3265	    "fuelpump": "⛽",
+3266	    "full_moon_with_face": "🌝",
+3267	    "gem": "💎",
+3268	    "star2": "🌟",
+3269	    "golfer": "🏌",
+3270	    "mortar_board": "🎓",
+3271	    "grimacing": "😬",
+3272	    "smile_cat": "😸",
+3273	    "grinning": "😀",
+3274	    "grin": "😁",
+3275	    "heartpulse": "💗",
+3276	    "guardsman": "💂",
+3277	    "haircut": "💇",
+3278	    "hamster": "🐹",
+3279	    "raising_hand": "🙋",
+3280	    "headphones": "🎧",
+3281	    "hear_no_evil": "🙉",
+3282	    "cupid": "💘",
+3283	    "gift_heart": "💝",
+3284	    "heart": "❤",
+3285	    "exclamation": "❗",
+3286	    "heavy_exclamation_mark": "❗",
+3287	    "heavy_heart_exclamation_mark_ornament": "❣",
+3288	    "o": "⭕",
+3289	    "helm_symbol": "⎈",
+3290	    "helmet_with_white_cross": "⛑",
+3291	    "high_heel": "👠",
+3292	    "bullettrain_side": "🚄",
+3293	    "bullettrain_front": "🚅",
+3294	    "high_brightness": "🔆",
+3295	    "zap": "⚡",
+3296	    "hocho": "🔪",
+3297	    "knife": "🔪",
+3298	    "bee": "🐝",
+3299	    "traffic_light": "🚥",
+3300	    "racehorse": "🐎",
+3301	    "coffee": "☕",
+3302	    "hotsprings": "♨",
+3303	    "hourglass": "⌛",
+3304	    "hourglass_flowing_sand": "⏳",
+3305	    "house_buildings": "🏘",
+3306	    "100": "💯",
+3307	    "hushed": "😯",
+3308	    "ice_hockey_stick_and_puck": "🏒",
+3309	    "imp": "👿",
+3310	    "information_desk_person": "💁",
+3311	    "information_source": "ℹ",
+3312	    "capital_abcd": "🔠",
+3313	    "abc": "🔤",
+3314	    "abcd": "🔡",
+3315	    "1234": "🔢",
+3316	    "symbols": "🔣",
+3317	    "izakaya_lantern": "🏮",
+3318	    "lantern": "🏮",
+3319	    "jack_o_lantern": "🎃",
+3320	    "dolls": "🎎",
+3321	    "japanese_goblin": "👺",
+3322	    "japanese_ogre": "👹",
+3323	    "beginner": "🔰",
+3324	    "zero": "0️⃣",
+3325	    "one": "1️⃣",
+3326	    "ten": "🔟",
+3327	    "two": "2️⃣",
+3328	    "three": "3️⃣",
+3329	    "four": "4️⃣",
+3330	    "five": "5️⃣",
+3331	    "six": "6️⃣",
+3332	    "seven": "7️⃣",
+3333	    "eight": "8️⃣",
+3334	    "nine": "9️⃣",
+3335	    "couplekiss": "💏",
+3336	    "kissing_cat": "😽",
+3337	    "kissing": "😗",
+3338	    "kissing_closed_eyes": "😚",
+3339	    "kissing_smiling_eyes": "😙",
+3340	    "beetle": "🐞",
+3341	    "large_blue_circle": "🔵",
+3342	    "last_quarter_moon_with_face": "🌜",
+3343	    "leaves": "🍃",
+3344	    "mag": "🔍",
+3345	    "left_right_arrow": "↔",
+3346	    "leftwards_arrow_with_hook": "↩",
+3347	    "arrow_left": "⬅",
+3348	    "lock": "🔒",
+3349	    "lock_with_ink_pen": "🔏",
+3350	    "sob": "😭",
+3351	    "low_brightness": "🔅",
+3352	    "lower_left_ballpoint_pen": "🖊",
+3353	    "lower_left_crayon": "🖍",
+3354	    "lower_left_fountain_pen": "🖋",
+3355	    "lower_left_paintbrush": "🖌",
+3356	    "mahjong": "🀄",
+3357	    "couple": "👫",
+3358	    "man_in_business_suit_levitating": "🕴",
+3359	    "man_with_gua_pi_mao": "👲",
+3360	    "man_with_turban": "👳",
+3361	    "mans_shoe": "👞",
+3362	    "shoe": "👞",
+3363	    "menorah_with_nine_branches": "🕎",
+3364	    "mens": "🚹",
+3365	    "minidisc": "💽",
+3366	    "iphone": "📱",
+3367	    "calling": "📲",
+3368	    "money__mouth_face": "🤑",
+3369	    "moneybag": "💰",
+3370	    "rice_scene": "🎑",
+3371	    "mountain_bicyclist": "🚵",
+3372	    "mouse2": "🐁",
+3373	    "lips": "👄",
+3374	    "moyai": "🗿",
+3375	    "notes": "🎶",
+3376	    "nail_care": "💅",
+3377	    "ab": "🆎",
+3378	    "negative_squared_cross_mark": "❎",
+3379	    "a": "🅰",
+3380	    "b": "🅱",
+3381	    "o2": "🅾",
+3382	    "parking": "🅿",
+3383	    "new_moon_with_face": "🌚",
+3384	    "no_entry_sign": "🚫",
+3385	    "underage": "🔞",
+3386	    "non__potable_water": "🚱",
+3387	    "arrow_upper_right": "↗",
+3388	    "arrow_upper_left": "↖",
+3389	    "office": "🏢",
+3390	    "older_man": "👴",
+3391	    "older_woman": "👵",
+3392	    "om_symbol": "🕉",
+3393	    "on": "🔛",
+3394	    "book": "📖",
+3395	    "unlock": "🔓",
+3396	    "mailbox_with_no_mail": "📭",
+3397	    "mailbox_with_mail": "📬",
+3398	    "cd": "💿",
+3399	    "tada": "🎉",
+3400	    "feet": "🐾",
+3401	    "walking": "🚶",
+3402	    "pencil2": "✏",
+3403	    "pensive": "😔",
+3404	    "persevere": "😣",
+3405	    "bow": "🙇",
+3406	    "raised_hands": "🙌",
+3407	    "person_with_ball": "⛹",
+3408	    "person_with_blond_hair": "👱",
+3409	    "pray": "🙏",
+3410	    "person_with_pouting_face": "🙎",
+3411	    "computer": "💻",
+3412	    "pig2": "🐖",
+3413	    "hankey": "💩",
+3414	    "poop": "💩",
+3415	    "shit": "💩",
+3416	    "bamboo": "🎍",
+3417	    "gun": "🔫",
+3418	    "black_joker": "🃏",
+3419	    "rotating_light": "🚨",
+3420	    "cop": "👮",
+3421	    "stew": "🍲",
+3422	    "pouch": "👝",
+3423	    "pouting_cat": "😾",
+3424	    "rage": "😡",
+3425	    "put_litter_in_its_place": "🚮",
+3426	    "rabbit2": "🐇",
+3427	    "racing_motorcycle": "🏍",
+3428	    "radioactive_sign": "☢",
+3429	    "fist": "✊",
+3430	    "hand": "✋",
+3431	    "raised_hand_with_fingers_splayed": "🖐",
+3432	    "raised_hand_with_part_between_middle_and_ring_fingers": "🖖",
+3433	    "blue_car": "🚙",
+3434	    "apple": "🍎",
+3435	    "relieved": "😌",
+3436	    "reversed_hand_with_middle_finger_extended": "🖕",
+3437	    "mag_right": "🔎",
+3438	    "arrow_right_hook": "↪",
+3439	    "sweet_potato": "🍠",
+3440	    "robot": "🤖",
+3441	    "rolled__up_newspaper": "🗞",
+3442	    "rowboat": "🚣",
+3443	    "runner": "🏃",
+3444	    "running": "🏃",
+3445	    "running_shirt_with_sash": "🎽",
+3446	    "boat": "⛵",
+3447	    "scales": "⚖",
+3448	    "school_satchel": "🎒",
+3449	    "scorpius": "♏",
+3450	    "see_no_evil": "🙈",
+3451	    "sheep": "🐑",
+3452	    "stars": "🌠",
+3453	    "cake": "🍰",
+3454	    "six_pointed_star": "🔯",
+3455	    "ski": "🎿",
+3456	    "sleeping_accommodation": "🛌",
+3457	    "sleeping": "😴",
+3458	    "sleepy": "😪",
+3459	    "sleuth_or_spy": "🕵",
+3460	    "heart_eyes_cat": "😻",
+3461	    "smiley_cat": "😺",
+3462	    "innocent": "😇",
+3463	    "heart_eyes": "😍",
+3464	    "smiling_imp": "😈",
+3465	    "smiley": "😃",
+3466	    "sweat_smile": "😅",
+3467	    "smile": "😄",
+3468	    "laughing": "😆",
+3469	    "satisfied": "😆",
+3470	    "blush": "😊",
+3471	    "smirk": "😏",
+3472	    "smoking": "🚬",
+3473	    "snow_capped_mountain": "🏔",
+3474	    "soccer": "⚽",
+3475	    "icecream": "🍦",
+3476	    "soon": "🔜",
+3477	    "arrow_lower_right": "↘",
+3478	    "arrow_lower_left": "↙",
+3479	    "speak_no_evil": "🙊",
+3480	    "speaker": "🔈",
+3481	    "mute": "🔇",
+3482	    "sound": "🔉",
+3483	    "loud_sound": "🔊",
+3484	    "speaking_head_in_silhouette": "🗣",
+3485	    "spiral_calendar_pad": "🗓",
+3486	    "spiral_note_pad": "🗒",
+3487	    "shell": "🐚",
+3488	    "sweat_drops": "💦",
+3489	    "u5272": "🈹",
+3490	    "u5408": "🈴",
+3491	    "u55b6": "🈺",
+3492	    "u6307": "🈯",
+3493	    "u6708": "🈷",
+3494	    "u6709": "🈶",
+3495	    "u6e80": "🈵",
+3496	    "u7121": "🈚",
+3497	    "u7533": "🈸",
+3498	    "u7981": "🈲",
+3499	    "u7a7a": "🈳",
+3500	    "cl": "🆑",
+3501	    "cool": "🆒",
+3502	    "free": "🆓",
+3503	    "id": "🆔",
+3504	    "koko": "🈁",
+3505	    "sa": "🈂",
+3506	    "new": "🆕",
+3507	    "ng": "🆖",
+3508	    "ok": "🆗",
+3509	    "sos": "🆘",
+3510	    "up": "🆙",
+3511	    "vs": "🆚",
+3512	    "steam_locomotive": "🚂",
+3513	    "ramen": "🍜",
+3514	    "partly_sunny": "⛅",
+3515	    "city_sunrise": "🌇",
+3516	    "surfer": "🏄",
+3517	    "swimmer": "🏊",
+3518	    "shirt": "👕",
+3519	    "tshirt": "👕",
+3520	    "table_tennis_paddle_and_ball": "🏓",
+3521	    "tea": "🍵",
+3522	    "tv": "📺",
+3523	    "three_button_mouse": "🖱",
+3524	    "+1": "👍",
+3525	    "thumbsup": "👍",
+3526	    "__1": "👎",
+3527	    "-1": "👎",
+3528	    "thumbsdown": "👎",
+3529	    "thunder_cloud_and_rain": "⛈",
+3530	    "tiger2": "🐅",
+3531	    "tophat": "🎩",
+3532	    "top": "🔝",
+3533	    "tm": "™",
+3534	    "train2": "🚆",
+3535	    "triangular_flag_on_post": "🚩",
+3536	    "trident": "🔱",
+3537	    "twisted_rightwards_arrows": "🔀",
+3538	    "unamused": "😒",
+3539	    "small_red_triangle": "🔺",
+3540	    "arrow_up_small": "🔼",
+3541	    "arrow_up_down": "↕",
+3542	    "upside__down_face": "🙃",
+3543	    "arrow_up": "⬆",
+3544	    "v": "✌",
+3545	    "vhs": "📼",
+3546	    "wc": "🚾",
+3547	    "ocean": "🌊",
+3548	    "waving_black_flag": "🏴",
+3549	    "wave": "👋",
+3550	    "waving_white_flag": "🏳",
+3551	    "moon": "🌔",
+3552	    "scream_cat": "🙀",
+3553	    "weary": "😩",
+3554	    "weight_lifter": "🏋",
+3555	    "whale2": "🐋",
+3556	    "wheelchair": "♿",
+3557	    "point_down": "👇",
+3558	    "grey_exclamation": "❕",
+3559	    "white_frowning_face": "☹",
+3560	    "white_check_mark": "✅",
+3561	    "point_left": "👈",
+3562	    "white_medium_small_square": "◽",
+3563	    "star": "⭐",
+3564	    "grey_question": "❔",
+3565	    "point_right": "👉",
+3566	    "relaxed": "☺",
+3567	    "white_sun_behind_cloud": "🌥",
+3568	    "white_sun_behind_cloud_with_rain": "🌦",
+3569	    "white_sun_with_small_cloud": "🌤",
+3570	    "point_up_2": "👆",
+3571	    "point_up": "☝",
+3572	    "wind_blowing_face": "🌬",
+3573	    "wink": "😉",
+3574	    "wolf": "🐺",
+3575	    "dancers": "👯",
+3576	    "boot": "👢",
+3577	    "womans_clothes": "👚",
+3578	    "womans_hat": "👒",
+3579	    "sandal": "👡",
+3580	    "womens": "🚺",
+3581	    "worried": "😟",
+3582	    "gift": "🎁",
+3583	    "zipper__mouth_face": "🤐",
+3584	    "regional_indicator_a": "🇦",
+3585	    "regional_indicator_b": "🇧",
+3586	    "regional_indicator_c": "🇨",
+3587	    "regional_indicator_d": "🇩",
+3588	    "regional_indicator_e": "🇪",
+3589	    "regional_indicator_f": "🇫",
+3590	    "regional_indicator_g": "🇬",
+3591	    "regional_indicator_h": "🇭",
+3592	    "regional_indicator_i": "🇮",
+3593	    "regional_indicator_j": "🇯",
+3594	    "regional_indicator_k": "🇰",
+3595	    "regional_indicator_l": "🇱",
+3596	    "regional_indicator_m": "🇲",
+3597	    "regional_indicator_n": "🇳",
+3598	    "regional_indicator_o": "🇴",
+3599	    "regional_indicator_p": "🇵",
+3600	    "regional_indicator_q": "🇶",
+3601	    "regional_indicator_r": "🇷",
+3602	    "regional_indicator_s": "🇸",
+3603	    "regional_indicator_t": "🇹",
+3604	    "regional_indicator_u": "🇺",
+3605	    "regional_indicator_v": "🇻",
+3606	    "regional_indicator_w": "🇼",
+3607	    "regional_indicator_x": "🇽",
+3608	    "regional_indicator_y": "🇾",
+3609	    "regional_indicator_z": "🇿",
+3610	}
+
+
+ + +
+
+ +
+
+ hardcoded_password_string: Possible hardcoded password: '㊙'
+ Test ID: B105
+ Severity: LOW
+ Confidence: MEDIUM
+ CWE: CWE-259
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/rich/_emoji_codes.py
+ Line number: 2882
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b105_hardcoded_password_string.html
+ +
+
+2881	    "congratulations": "㊗",
+2882	    "secret": "㊙",
+2883	    "m": "Ⓜ",
+2884	    "city_sunset": "🌆",
+2885	    "clapper": "🎬",
+2886	    "clap": "👏",
+2887	    "beers": "🍻",
+2888	    "clock830": "🕣",
+2889	    "clock8": "🕗",
+2890	    "clock1130": "🕦",
+2891	    "clock11": "🕚",
+2892	    "clock530": "🕠",
+2893	    "clock5": "🕔",
+2894	    "clock430": "🕟",
+2895	    "clock4": "🕓",
+2896	    "clock930": "🕤",
+2897	    "clock9": "🕘",
+2898	    "clock130": "🕜",
+2899	    "clock1": "🕐",
+2900	    "clock730": "🕢",
+2901	    "clock7": "🕖",
+2902	    "clock630": "🕡",
+2903	    "clock6": "🕕",
+2904	    "clock1030": "🕥",
+2905	    "clock10": "🕙",
+2906	    "clock330": "🕞",
+2907	    "clock3": "🕒",
+2908	    "clock1230": "🕧",
+2909	    "clock12": "🕛",
+2910	    "clock230": "🕝",
+2911	    "clock2": "🕑",
+2912	    "arrows_clockwise": "🔃",
+2913	    "repeat": "🔁",
+2914	    "repeat_one": "🔂",
+2915	    "closed_lock_with_key": "🔐",
+2916	    "mailbox_closed": "📪",
+2917	    "mailbox": "📫",
+2918	    "cloud_with_tornado": "🌪",
+2919	    "cocktail": "🍸",
+2920	    "boom": "💥",
+2921	    "compression": "🗜",
+2922	    "confounded": "😖",
+2923	    "confused": "😕",
+2924	    "rice": "🍚",
+2925	    "cow2": "🐄",
+2926	    "cricket_bat_and_ball": "🏏",
+2927	    "x": "❌",
+2928	    "cry": "😢",
+2929	    "curry": "🍛",
+2930	    "dagger_knife": "🗡",
+2931	    "dancer": "💃",
+2932	    "dark_sunglasses": "🕶",
+2933	    "dash": "💨",
+2934	    "truck": "🚚",
+2935	    "derelict_house_building": "🏚",
+2936	    "diamond_shape_with_a_dot_inside": "💠",
+2937	    "dart": "🎯",
+2938	    "disappointed_relieved": "😥",
+2939	    "disappointed": "😞",
+2940	    "do_not_litter": "🚯",
+2941	    "dog2": "🐕",
+2942	    "flipper": "🐬",
+2943	    "loop": "➿",
+2944	    "bangbang": "‼",
+2945	    "double_vertical_bar": "⏸",
+2946	    "dove_of_peace": "🕊",
+2947	    "small_red_triangle_down": "🔻",
+2948	    "arrow_down_small": "🔽",
+2949	    "arrow_down": "⬇",
+2950	    "dromedary_camel": "🐪",
+2951	    "e__mail": "📧",
+2952	    "corn": "🌽",
+2953	    "ear_of_rice": "🌾",
+2954	    "earth_americas": "🌎",
+2955	    "earth_asia": "🌏",
+2956	    "earth_africa": "🌍",
+2957	    "eight_pointed_black_star": "✴",
+2958	    "eight_spoked_asterisk": "✳",
+2959	    "eject_symbol": "⏏",
+2960	    "bulb": "💡",
+2961	    "emoji_modifier_fitzpatrick_type__1__2": "🏻",
+2962	    "emoji_modifier_fitzpatrick_type__3": "🏼",
+2963	    "emoji_modifier_fitzpatrick_type__4": "🏽",
+2964	    "emoji_modifier_fitzpatrick_type__5": "🏾",
+2965	    "emoji_modifier_fitzpatrick_type__6": "🏿",
+2966	    "end": "🔚",
+2967	    "email": "✉",
+2968	    "european_castle": "🏰",
+2969	    "european_post_office": "🏤",
+2970	    "interrobang": "⁉",
+2971	    "expressionless": "😑",
+2972	    "eyeglasses": "👓",
+2973	    "massage": "💆",
+2974	    "yum": "😋",
+2975	    "scream": "😱",
+2976	    "kissing_heart": "😘",
+2977	    "sweat": "😓",
+2978	    "face_with_head__bandage": "🤕",
+2979	    "triumph": "😤",
+2980	    "mask": "😷",
+2981	    "no_good": "🙅",
+2982	    "ok_woman": "🙆",
+2983	    "open_mouth": "😮",
+2984	    "cold_sweat": "😰",
+2985	    "stuck_out_tongue": "😛",
+2986	    "stuck_out_tongue_closed_eyes": "😝",
+2987	    "stuck_out_tongue_winking_eye": "😜",
+2988	    "joy": "😂",
+2989	    "no_mouth": "😶",
+2990	    "santa": "🎅",
+2991	    "fax": "📠",
+2992	    "fearful": "😨",
+2993	    "field_hockey_stick_and_ball": "🏑",
+2994	    "first_quarter_moon_with_face": "🌛",
+2995	    "fish_cake": "🍥",
+2996	    "fishing_pole_and_fish": "🎣",
+2997	    "facepunch": "👊",
+2998	    "punch": "👊",
+2999	    "flag_for_afghanistan": "🇦🇫",
+3000	    "flag_for_albania": "🇦🇱",
+3001	    "flag_for_algeria": "🇩🇿",
+3002	    "flag_for_american_samoa": "🇦🇸",
+3003	    "flag_for_andorra": "🇦🇩",
+3004	    "flag_for_angola": "🇦🇴",
+3005	    "flag_for_anguilla": "🇦🇮",
+3006	    "flag_for_antarctica": "🇦🇶",
+3007	    "flag_for_antigua_&_barbuda": "🇦🇬",
+3008	    "flag_for_argentina": "🇦🇷",
+3009	    "flag_for_armenia": "🇦🇲",
+3010	    "flag_for_aruba": "🇦🇼",
+3011	    "flag_for_ascension_island": "🇦🇨",
+3012	    "flag_for_australia": "🇦🇺",
+3013	    "flag_for_austria": "🇦🇹",
+3014	    "flag_for_azerbaijan": "🇦🇿",
+3015	    "flag_for_bahamas": "🇧🇸",
+3016	    "flag_for_bahrain": "🇧🇭",
+3017	    "flag_for_bangladesh": "🇧🇩",
+3018	    "flag_for_barbados": "🇧🇧",
+3019	    "flag_for_belarus": "🇧🇾",
+3020	    "flag_for_belgium": "🇧🇪",
+3021	    "flag_for_belize": "🇧🇿",
+3022	    "flag_for_benin": "🇧🇯",
+3023	    "flag_for_bermuda": "🇧🇲",
+3024	    "flag_for_bhutan": "🇧🇹",
+3025	    "flag_for_bolivia": "🇧🇴",
+3026	    "flag_for_bosnia_&_herzegovina": "🇧🇦",
+3027	    "flag_for_botswana": "🇧🇼",
+3028	    "flag_for_bouvet_island": "🇧🇻",
+3029	    "flag_for_brazil": "🇧🇷",
+3030	    "flag_for_british_indian_ocean_territory": "🇮🇴",
+3031	    "flag_for_british_virgin_islands": "🇻🇬",
+3032	    "flag_for_brunei": "🇧🇳",
+3033	    "flag_for_bulgaria": "🇧🇬",
+3034	    "flag_for_burkina_faso": "🇧🇫",
+3035	    "flag_for_burundi": "🇧🇮",
+3036	    "flag_for_cambodia": "🇰🇭",
+3037	    "flag_for_cameroon": "🇨🇲",
+3038	    "flag_for_canada": "🇨🇦",
+3039	    "flag_for_canary_islands": "🇮🇨",
+3040	    "flag_for_cape_verde": "🇨🇻",
+3041	    "flag_for_caribbean_netherlands": "🇧🇶",
+3042	    "flag_for_cayman_islands": "🇰🇾",
+3043	    "flag_for_central_african_republic": "🇨🇫",
+3044	    "flag_for_ceuta_&_melilla": "🇪🇦",
+3045	    "flag_for_chad": "🇹🇩",
+3046	    "flag_for_chile": "🇨🇱",
+3047	    "flag_for_china": "🇨🇳",
+3048	    "flag_for_christmas_island": "🇨🇽",
+3049	    "flag_for_clipperton_island": "🇨🇵",
+3050	    "flag_for_cocos__islands": "🇨🇨",
+3051	    "flag_for_colombia": "🇨🇴",
+3052	    "flag_for_comoros": "🇰🇲",
+3053	    "flag_for_congo____brazzaville": "🇨🇬",
+3054	    "flag_for_congo____kinshasa": "🇨🇩",
+3055	    "flag_for_cook_islands": "🇨🇰",
+3056	    "flag_for_costa_rica": "🇨🇷",
+3057	    "flag_for_croatia": "🇭🇷",
+3058	    "flag_for_cuba": "🇨🇺",
+3059	    "flag_for_curaçao": "🇨🇼",
+3060	    "flag_for_cyprus": "🇨🇾",
+3061	    "flag_for_czech_republic": "🇨🇿",
+3062	    "flag_for_côte_d’ivoire": "🇨🇮",
+3063	    "flag_for_denmark": "🇩🇰",
+3064	    "flag_for_diego_garcia": "🇩🇬",
+3065	    "flag_for_djibouti": "🇩🇯",
+3066	    "flag_for_dominica": "🇩🇲",
+3067	    "flag_for_dominican_republic": "🇩🇴",
+3068	    "flag_for_ecuador": "🇪🇨",
+3069	    "flag_for_egypt": "🇪🇬",
+3070	    "flag_for_el_salvador": "🇸🇻",
+3071	    "flag_for_equatorial_guinea": "🇬🇶",
+3072	    "flag_for_eritrea": "🇪🇷",
+3073	    "flag_for_estonia": "🇪🇪",
+3074	    "flag_for_ethiopia": "🇪🇹",
+3075	    "flag_for_european_union": "🇪🇺",
+3076	    "flag_for_falkland_islands": "🇫🇰",
+3077	    "flag_for_faroe_islands": "🇫🇴",
+3078	    "flag_for_fiji": "🇫🇯",
+3079	    "flag_for_finland": "🇫🇮",
+3080	    "flag_for_france": "🇫🇷",
+3081	    "flag_for_french_guiana": "🇬🇫",
+3082	    "flag_for_french_polynesia": "🇵🇫",
+3083	    "flag_for_french_southern_territories": "🇹🇫",
+3084	    "flag_for_gabon": "🇬🇦",
+3085	    "flag_for_gambia": "🇬🇲",
+3086	    "flag_for_georgia": "🇬🇪",
+3087	    "flag_for_germany": "🇩🇪",
+3088	    "flag_for_ghana": "🇬🇭",
+3089	    "flag_for_gibraltar": "🇬🇮",
+3090	    "flag_for_greece": "🇬🇷",
+3091	    "flag_for_greenland": "🇬🇱",
+3092	    "flag_for_grenada": "🇬🇩",
+3093	    "flag_for_guadeloupe": "🇬🇵",
+3094	    "flag_for_guam": "🇬🇺",
+3095	    "flag_for_guatemala": "🇬🇹",
+3096	    "flag_for_guernsey": "🇬🇬",
+3097	    "flag_for_guinea": "🇬🇳",
+3098	    "flag_for_guinea__bissau": "🇬🇼",
+3099	    "flag_for_guyana": "🇬🇾",
+3100	    "flag_for_haiti": "🇭🇹",
+3101	    "flag_for_heard_&_mcdonald_islands": "🇭🇲",
+3102	    "flag_for_honduras": "🇭🇳",
+3103	    "flag_for_hong_kong": "🇭🇰",
+3104	    "flag_for_hungary": "🇭🇺",
+3105	    "flag_for_iceland": "🇮🇸",
+3106	    "flag_for_india": "🇮🇳",
+3107	    "flag_for_indonesia": "🇮🇩",
+3108	    "flag_for_iran": "🇮🇷",
+3109	    "flag_for_iraq": "🇮🇶",
+3110	    "flag_for_ireland": "🇮🇪",
+3111	    "flag_for_isle_of_man": "🇮🇲",
+3112	    "flag_for_israel": "🇮🇱",
+3113	    "flag_for_italy": "🇮🇹",
+3114	    "flag_for_jamaica": "🇯🇲",
+3115	    "flag_for_japan": "🇯🇵",
+3116	    "flag_for_jersey": "🇯🇪",
+3117	    "flag_for_jordan": "🇯🇴",
+3118	    "flag_for_kazakhstan": "🇰🇿",
+3119	    "flag_for_kenya": "🇰🇪",
+3120	    "flag_for_kiribati": "🇰🇮",
+3121	    "flag_for_kosovo": "🇽🇰",
+3122	    "flag_for_kuwait": "🇰🇼",
+3123	    "flag_for_kyrgyzstan": "🇰🇬",
+3124	    "flag_for_laos": "🇱🇦",
+3125	    "flag_for_latvia": "🇱🇻",
+3126	    "flag_for_lebanon": "🇱🇧",
+3127	    "flag_for_lesotho": "🇱🇸",
+3128	    "flag_for_liberia": "🇱🇷",
+3129	    "flag_for_libya": "🇱🇾",
+3130	    "flag_for_liechtenstein": "🇱🇮",
+3131	    "flag_for_lithuania": "🇱🇹",
+3132	    "flag_for_luxembourg": "🇱🇺",
+3133	    "flag_for_macau": "🇲🇴",
+3134	    "flag_for_macedonia": "🇲🇰",
+3135	    "flag_for_madagascar": "🇲🇬",
+3136	    "flag_for_malawi": "🇲🇼",
+3137	    "flag_for_malaysia": "🇲🇾",
+3138	    "flag_for_maldives": "🇲🇻",
+3139	    "flag_for_mali": "🇲🇱",
+3140	    "flag_for_malta": "🇲🇹",
+3141	    "flag_for_marshall_islands": "🇲🇭",
+3142	    "flag_for_martinique": "🇲🇶",
+3143	    "flag_for_mauritania": "🇲🇷",
+3144	    "flag_for_mauritius": "🇲🇺",
+3145	    "flag_for_mayotte": "🇾🇹",
+3146	    "flag_for_mexico": "🇲🇽",
+3147	    "flag_for_micronesia": "🇫🇲",
+3148	    "flag_for_moldova": "🇲🇩",
+3149	    "flag_for_monaco": "🇲🇨",
+3150	    "flag_for_mongolia": "🇲🇳",
+3151	    "flag_for_montenegro": "🇲🇪",
+3152	    "flag_for_montserrat": "🇲🇸",
+3153	    "flag_for_morocco": "🇲🇦",
+3154	    "flag_for_mozambique": "🇲🇿",
+3155	    "flag_for_myanmar": "🇲🇲",
+3156	    "flag_for_namibia": "🇳🇦",
+3157	    "flag_for_nauru": "🇳🇷",
+3158	    "flag_for_nepal": "🇳🇵",
+3159	    "flag_for_netherlands": "🇳🇱",
+3160	    "flag_for_new_caledonia": "🇳🇨",
+3161	    "flag_for_new_zealand": "🇳🇿",
+3162	    "flag_for_nicaragua": "🇳🇮",
+3163	    "flag_for_niger": "🇳🇪",
+3164	    "flag_for_nigeria": "🇳🇬",
+3165	    "flag_for_niue": "🇳🇺",
+3166	    "flag_for_norfolk_island": "🇳🇫",
+3167	    "flag_for_north_korea": "🇰🇵",
+3168	    "flag_for_northern_mariana_islands": "🇲🇵",
+3169	    "flag_for_norway": "🇳🇴",
+3170	    "flag_for_oman": "🇴🇲",
+3171	    "flag_for_pakistan": "🇵🇰",
+3172	    "flag_for_palau": "🇵🇼",
+3173	    "flag_for_palestinian_territories": "🇵🇸",
+3174	    "flag_for_panama": "🇵🇦",
+3175	    "flag_for_papua_new_guinea": "🇵🇬",
+3176	    "flag_for_paraguay": "🇵🇾",
+3177	    "flag_for_peru": "🇵🇪",
+3178	    "flag_for_philippines": "🇵🇭",
+3179	    "flag_for_pitcairn_islands": "🇵🇳",
+3180	    "flag_for_poland": "🇵🇱",
+3181	    "flag_for_portugal": "🇵🇹",
+3182	    "flag_for_puerto_rico": "🇵🇷",
+3183	    "flag_for_qatar": "🇶🇦",
+3184	    "flag_for_romania": "🇷🇴",
+3185	    "flag_for_russia": "🇷🇺",
+3186	    "flag_for_rwanda": "🇷🇼",
+3187	    "flag_for_réunion": "🇷🇪",
+3188	    "flag_for_samoa": "🇼🇸",
+3189	    "flag_for_san_marino": "🇸🇲",
+3190	    "flag_for_saudi_arabia": "🇸🇦",
+3191	    "flag_for_senegal": "🇸🇳",
+3192	    "flag_for_serbia": "🇷🇸",
+3193	    "flag_for_seychelles": "🇸🇨",
+3194	    "flag_for_sierra_leone": "🇸🇱",
+3195	    "flag_for_singapore": "🇸🇬",
+3196	    "flag_for_sint_maarten": "🇸🇽",
+3197	    "flag_for_slovakia": "🇸🇰",
+3198	    "flag_for_slovenia": "🇸🇮",
+3199	    "flag_for_solomon_islands": "🇸🇧",
+3200	    "flag_for_somalia": "🇸🇴",
+3201	    "flag_for_south_africa": "🇿🇦",
+3202	    "flag_for_south_georgia_&_south_sandwich_islands": "🇬🇸",
+3203	    "flag_for_south_korea": "🇰🇷",
+3204	    "flag_for_south_sudan": "🇸🇸",
+3205	    "flag_for_spain": "🇪🇸",
+3206	    "flag_for_sri_lanka": "🇱🇰",
+3207	    "flag_for_st._barthélemy": "🇧🇱",
+3208	    "flag_for_st._helena": "🇸🇭",
+3209	    "flag_for_st._kitts_&_nevis": "🇰🇳",
+3210	    "flag_for_st._lucia": "🇱🇨",
+3211	    "flag_for_st._martin": "🇲🇫",
+3212	    "flag_for_st._pierre_&_miquelon": "🇵🇲",
+3213	    "flag_for_st._vincent_&_grenadines": "🇻🇨",
+3214	    "flag_for_sudan": "🇸🇩",
+3215	    "flag_for_suriname": "🇸🇷",
+3216	    "flag_for_svalbard_&_jan_mayen": "🇸🇯",
+3217	    "flag_for_swaziland": "🇸🇿",
+3218	    "flag_for_sweden": "🇸🇪",
+3219	    "flag_for_switzerland": "🇨🇭",
+3220	    "flag_for_syria": "🇸🇾",
+3221	    "flag_for_são_tomé_&_príncipe": "🇸🇹",
+3222	    "flag_for_taiwan": "🇹🇼",
+3223	    "flag_for_tajikistan": "🇹🇯",
+3224	    "flag_for_tanzania": "🇹🇿",
+3225	    "flag_for_thailand": "🇹🇭",
+3226	    "flag_for_timor__leste": "🇹🇱",
+3227	    "flag_for_togo": "🇹🇬",
+3228	    "flag_for_tokelau": "🇹🇰",
+3229	    "flag_for_tonga": "🇹🇴",
+3230	    "flag_for_trinidad_&_tobago": "🇹🇹",
+3231	    "flag_for_tristan_da_cunha": "🇹🇦",
+3232	    "flag_for_tunisia": "🇹🇳",
+3233	    "flag_for_turkey": "🇹🇷",
+3234	    "flag_for_turkmenistan": "🇹🇲",
+3235	    "flag_for_turks_&_caicos_islands": "🇹🇨",
+3236	    "flag_for_tuvalu": "🇹🇻",
+3237	    "flag_for_u.s._outlying_islands": "🇺🇲",
+3238	    "flag_for_u.s._virgin_islands": "🇻🇮",
+3239	    "flag_for_uganda": "🇺🇬",
+3240	    "flag_for_ukraine": "🇺🇦",
+3241	    "flag_for_united_arab_emirates": "🇦🇪",
+3242	    "flag_for_united_kingdom": "🇬🇧",
+3243	    "flag_for_united_states": "🇺🇸",
+3244	    "flag_for_uruguay": "🇺🇾",
+3245	    "flag_for_uzbekistan": "🇺🇿",
+3246	    "flag_for_vanuatu": "🇻🇺",
+3247	    "flag_for_vatican_city": "🇻🇦",
+3248	    "flag_for_venezuela": "🇻🇪",
+3249	    "flag_for_vietnam": "🇻🇳",
+3250	    "flag_for_wallis_&_futuna": "🇼🇫",
+3251	    "flag_for_western_sahara": "🇪🇭",
+3252	    "flag_for_yemen": "🇾🇪",
+3253	    "flag_for_zambia": "🇿🇲",
+3254	    "flag_for_zimbabwe": "🇿🇼",
+3255	    "flag_for_åland_islands": "🇦🇽",
+3256	    "golf": "⛳",
+3257	    "fleur__de__lis": "⚜",
+3258	    "muscle": "💪",
+3259	    "flushed": "😳",
+3260	    "frame_with_picture": "🖼",
+3261	    "fries": "🍟",
+3262	    "frog": "🐸",
+3263	    "hatched_chick": "🐥",
+3264	    "frowning": "😦",
+3265	    "fuelpump": "⛽",
+3266	    "full_moon_with_face": "🌝",
+3267	    "gem": "💎",
+3268	    "star2": "🌟",
+3269	    "golfer": "🏌",
+3270	    "mortar_board": "🎓",
+3271	    "grimacing": "😬",
+3272	    "smile_cat": "😸",
+3273	    "grinning": "😀",
+3274	    "grin": "😁",
+3275	    "heartpulse": "💗",
+3276	    "guardsman": "💂",
+3277	    "haircut": "💇",
+3278	    "hamster": "🐹",
+3279	    "raising_hand": "🙋",
+3280	    "headphones": "🎧",
+3281	    "hear_no_evil": "🙉",
+3282	    "cupid": "💘",
+3283	    "gift_heart": "💝",
+3284	    "heart": "❤",
+3285	    "exclamation": "❗",
+3286	    "heavy_exclamation_mark": "❗",
+3287	    "heavy_heart_exclamation_mark_ornament": "❣",
+3288	    "o": "⭕",
+3289	    "helm_symbol": "⎈",
+3290	    "helmet_with_white_cross": "⛑",
+3291	    "high_heel": "👠",
+3292	    "bullettrain_side": "🚄",
+3293	    "bullettrain_front": "🚅",
+3294	    "high_brightness": "🔆",
+3295	    "zap": "⚡",
+3296	    "hocho": "🔪",
+3297	    "knife": "🔪",
+3298	    "bee": "🐝",
+3299	    "traffic_light": "🚥",
+3300	    "racehorse": "🐎",
+3301	    "coffee": "☕",
+3302	    "hotsprings": "♨",
+3303	    "hourglass": "⌛",
+3304	    "hourglass_flowing_sand": "⏳",
+3305	    "house_buildings": "🏘",
+3306	    "100": "💯",
+3307	    "hushed": "😯",
+3308	    "ice_hockey_stick_and_puck": "🏒",
+3309	    "imp": "👿",
+3310	    "information_desk_person": "💁",
+3311	    "information_source": "ℹ",
+3312	    "capital_abcd": "🔠",
+3313	    "abc": "🔤",
+3314	    "abcd": "🔡",
+3315	    "1234": "🔢",
+3316	    "symbols": "🔣",
+3317	    "izakaya_lantern": "🏮",
+3318	    "lantern": "🏮",
+3319	    "jack_o_lantern": "🎃",
+3320	    "dolls": "🎎",
+3321	    "japanese_goblin": "👺",
+3322	    "japanese_ogre": "👹",
+3323	    "beginner": "🔰",
+3324	    "zero": "0️⃣",
+3325	    "one": "1️⃣",
+3326	    "ten": "🔟",
+3327	    "two": "2️⃣",
+3328	    "three": "3️⃣",
+3329	    "four": "4️⃣",
+3330	    "five": "5️⃣",
+3331	    "six": "6️⃣",
+3332	    "seven": "7️⃣",
+3333	    "eight": "8️⃣",
+3334	    "nine": "9️⃣",
+3335	    "couplekiss": "💏",
+3336	    "kissing_cat": "😽",
+3337	    "kissing": "😗",
+3338	    "kissing_closed_eyes": "😚",
+3339	    "kissing_smiling_eyes": "😙",
+3340	    "beetle": "🐞",
+3341	    "large_blue_circle": "🔵",
+3342	    "last_quarter_moon_with_face": "🌜",
+3343	    "leaves": "🍃",
+3344	    "mag": "🔍",
+3345	    "left_right_arrow": "↔",
+3346	    "leftwards_arrow_with_hook": "↩",
+3347	    "arrow_left": "⬅",
+3348	    "lock": "🔒",
+3349	    "lock_with_ink_pen": "🔏",
+3350	    "sob": "😭",
+3351	    "low_brightness": "🔅",
+3352	    "lower_left_ballpoint_pen": "🖊",
+3353	    "lower_left_crayon": "🖍",
+3354	    "lower_left_fountain_pen": "🖋",
+3355	    "lower_left_paintbrush": "🖌",
+3356	    "mahjong": "🀄",
+3357	    "couple": "👫",
+3358	    "man_in_business_suit_levitating": "🕴",
+3359	    "man_with_gua_pi_mao": "👲",
+3360	    "man_with_turban": "👳",
+3361	    "mans_shoe": "👞",
+3362	    "shoe": "👞",
+3363	    "menorah_with_nine_branches": "🕎",
+3364	    "mens": "🚹",
+3365	    "minidisc": "💽",
+3366	    "iphone": "📱",
+3367	    "calling": "📲",
+3368	    "money__mouth_face": "🤑",
+3369	    "moneybag": "💰",
+3370	    "rice_scene": "🎑",
+3371	    "mountain_bicyclist": "🚵",
+3372	    "mouse2": "🐁",
+3373	    "lips": "👄",
+3374	    "moyai": "🗿",
+3375	    "notes": "🎶",
+3376	    "nail_care": "💅",
+3377	    "ab": "🆎",
+3378	    "negative_squared_cross_mark": "❎",
+3379	    "a": "🅰",
+3380	    "b": "🅱",
+3381	    "o2": "🅾",
+3382	    "parking": "🅿",
+3383	    "new_moon_with_face": "🌚",
+3384	    "no_entry_sign": "🚫",
+3385	    "underage": "🔞",
+3386	    "non__potable_water": "🚱",
+3387	    "arrow_upper_right": "↗",
+3388	    "arrow_upper_left": "↖",
+3389	    "office": "🏢",
+3390	    "older_man": "👴",
+3391	    "older_woman": "👵",
+3392	    "om_symbol": "🕉",
+3393	    "on": "🔛",
+3394	    "book": "📖",
+3395	    "unlock": "🔓",
+3396	    "mailbox_with_no_mail": "📭",
+3397	    "mailbox_with_mail": "📬",
+3398	    "cd": "💿",
+3399	    "tada": "🎉",
+3400	    "feet": "🐾",
+3401	    "walking": "🚶",
+3402	    "pencil2": "✏",
+3403	    "pensive": "😔",
+3404	    "persevere": "😣",
+3405	    "bow": "🙇",
+3406	    "raised_hands": "🙌",
+3407	    "person_with_ball": "⛹",
+3408	    "person_with_blond_hair": "👱",
+3409	    "pray": "🙏",
+3410	    "person_with_pouting_face": "🙎",
+3411	    "computer": "💻",
+3412	    "pig2": "🐖",
+3413	    "hankey": "💩",
+3414	    "poop": "💩",
+3415	    "shit": "💩",
+3416	    "bamboo": "🎍",
+3417	    "gun": "🔫",
+3418	    "black_joker": "🃏",
+3419	    "rotating_light": "🚨",
+3420	    "cop": "👮",
+3421	    "stew": "🍲",
+3422	    "pouch": "👝",
+3423	    "pouting_cat": "😾",
+3424	    "rage": "😡",
+3425	    "put_litter_in_its_place": "🚮",
+3426	    "rabbit2": "🐇",
+3427	    "racing_motorcycle": "🏍",
+3428	    "radioactive_sign": "☢",
+3429	    "fist": "✊",
+3430	    "hand": "✋",
+3431	    "raised_hand_with_fingers_splayed": "🖐",
+3432	    "raised_hand_with_part_between_middle_and_ring_fingers": "🖖",
+3433	    "blue_car": "🚙",
+3434	    "apple": "🍎",
+3435	    "relieved": "😌",
+3436	    "reversed_hand_with_middle_finger_extended": "🖕",
+3437	    "mag_right": "🔎",
+3438	    "arrow_right_hook": "↪",
+3439	    "sweet_potato": "🍠",
+3440	    "robot": "🤖",
+3441	    "rolled__up_newspaper": "🗞",
+3442	    "rowboat": "🚣",
+3443	    "runner": "🏃",
+3444	    "running": "🏃",
+3445	    "running_shirt_with_sash": "🎽",
+3446	    "boat": "⛵",
+3447	    "scales": "⚖",
+3448	    "school_satchel": "🎒",
+3449	    "scorpius": "♏",
+3450	    "see_no_evil": "🙈",
+3451	    "sheep": "🐑",
+3452	    "stars": "🌠",
+3453	    "cake": "🍰",
+3454	    "six_pointed_star": "🔯",
+3455	    "ski": "🎿",
+3456	    "sleeping_accommodation": "🛌",
+3457	    "sleeping": "😴",
+3458	    "sleepy": "😪",
+3459	    "sleuth_or_spy": "🕵",
+3460	    "heart_eyes_cat": "😻",
+3461	    "smiley_cat": "😺",
+3462	    "innocent": "😇",
+3463	    "heart_eyes": "😍",
+3464	    "smiling_imp": "😈",
+3465	    "smiley": "😃",
+3466	    "sweat_smile": "😅",
+3467	    "smile": "😄",
+3468	    "laughing": "😆",
+3469	    "satisfied": "😆",
+3470	    "blush": "😊",
+3471	    "smirk": "😏",
+3472	    "smoking": "🚬",
+3473	    "snow_capped_mountain": "🏔",
+3474	    "soccer": "⚽",
+3475	    "icecream": "🍦",
+3476	    "soon": "🔜",
+3477	    "arrow_lower_right": "↘",
+3478	    "arrow_lower_left": "↙",
+3479	    "speak_no_evil": "🙊",
+3480	    "speaker": "🔈",
+3481	    "mute": "🔇",
+3482	    "sound": "🔉",
+3483	    "loud_sound": "🔊",
+3484	    "speaking_head_in_silhouette": "🗣",
+3485	    "spiral_calendar_pad": "🗓",
+3486	    "spiral_note_pad": "🗒",
+3487	    "shell": "🐚",
+3488	    "sweat_drops": "💦",
+3489	    "u5272": "🈹",
+3490	    "u5408": "🈴",
+3491	    "u55b6": "🈺",
+3492	    "u6307": "🈯",
+3493	    "u6708": "🈷",
+3494	    "u6709": "🈶",
+3495	    "u6e80": "🈵",
+3496	    "u7121": "🈚",
+3497	    "u7533": "🈸",
+3498	    "u7981": "🈲",
+3499	    "u7a7a": "🈳",
+3500	    "cl": "🆑",
+3501	    "cool": "🆒",
+3502	    "free": "🆓",
+3503	    "id": "🆔",
+3504	    "koko": "🈁",
+3505	    "sa": "🈂",
+3506	    "new": "🆕",
+3507	    "ng": "🆖",
+3508	    "ok": "🆗",
+3509	    "sos": "🆘",
+3510	    "up": "🆙",
+3511	    "vs": "🆚",
+3512	    "steam_locomotive": "🚂",
+3513	    "ramen": "🍜",
+3514	    "partly_sunny": "⛅",
+3515	    "city_sunrise": "🌇",
+3516	    "surfer": "🏄",
+3517	    "swimmer": "🏊",
+3518	    "shirt": "👕",
+3519	    "tshirt": "👕",
+3520	    "table_tennis_paddle_and_ball": "🏓",
+3521	    "tea": "🍵",
+3522	    "tv": "📺",
+3523	    "three_button_mouse": "🖱",
+3524	    "+1": "👍",
+3525	    "thumbsup": "👍",
+3526	    "__1": "👎",
+3527	    "-1": "👎",
+3528	    "thumbsdown": "👎",
+3529	    "thunder_cloud_and_rain": "⛈",
+3530	    "tiger2": "🐅",
+3531	    "tophat": "🎩",
+3532	    "top": "🔝",
+3533	    "tm": "™",
+3534	    "train2": "🚆",
+3535	    "triangular_flag_on_post": "🚩",
+3536	    "trident": "🔱",
+3537	    "twisted_rightwards_arrows": "🔀",
+3538	    "unamused": "😒",
+3539	    "small_red_triangle": "🔺",
+3540	    "arrow_up_small": "🔼",
+3541	    "arrow_up_down": "↕",
+3542	    "upside__down_face": "🙃",
+3543	    "arrow_up": "⬆",
+3544	    "v": "✌",
+3545	    "vhs": "📼",
+3546	    "wc": "🚾",
+3547	    "ocean": "🌊",
+3548	    "waving_black_flag": "🏴",
+3549	    "wave": "👋",
+3550	    "waving_white_flag": "🏳",
+3551	    "moon": "🌔",
+3552	    "scream_cat": "🙀",
+3553	    "weary": "😩",
+3554	    "weight_lifter": "🏋",
+3555	    "whale2": "🐋",
+3556	    "wheelchair": "♿",
+3557	    "point_down": "👇",
+3558	    "grey_exclamation": "❕",
+3559	    "white_frowning_face": "☹",
+3560	    "white_check_mark": "✅",
+3561	    "point_left": "👈",
+3562	    "white_medium_small_square": "◽",
+3563	    "star": "⭐",
+3564	    "grey_question": "❔",
+3565	    "point_right": "👉",
+3566	    "relaxed": "☺",
+3567	    "white_sun_behind_cloud": "🌥",
+3568	    "white_sun_behind_cloud_with_rain": "🌦",
+3569	    "white_sun_with_small_cloud": "🌤",
+3570	    "point_up_2": "👆",
+3571	    "point_up": "☝",
+3572	    "wind_blowing_face": "🌬",
+3573	    "wink": "😉",
+3574	    "wolf": "🐺",
+3575	    "dancers": "👯",
+3576	    "boot": "👢",
+3577	    "womans_clothes": "👚",
+3578	    "womans_hat": "👒",
+3579	    "sandal": "👡",
+3580	    "womens": "🚺",
+3581	    "worried": "😟",
+3582	    "gift": "🎁",
+3583	    "zipper__mouth_face": "🤐",
+3584	    "regional_indicator_a": "🇦",
+3585	    "regional_indicator_b": "🇧",
+3586	    "regional_indicator_c": "🇨",
+3587	    "regional_indicator_d": "🇩",
+3588	    "regional_indicator_e": "🇪",
+3589	    "regional_indicator_f": "🇫",
+3590	    "regional_indicator_g": "🇬",
+3591	    "regional_indicator_h": "🇭",
+3592	    "regional_indicator_i": "🇮",
+3593	    "regional_indicator_j": "🇯",
+3594	    "regional_indicator_k": "🇰",
+3595	    "regional_indicator_l": "🇱",
+3596	    "regional_indicator_m": "🇲",
+3597	    "regional_indicator_n": "🇳",
+3598	    "regional_indicator_o": "🇴",
+3599	    "regional_indicator_p": "🇵",
+3600	    "regional_indicator_q": "🇶",
+3601	    "regional_indicator_r": "🇷",
+3602	    "regional_indicator_s": "🇸",
+3603	    "regional_indicator_t": "🇹",
+3604	    "regional_indicator_u": "🇺",
+3605	    "regional_indicator_v": "🇻",
+3606	    "regional_indicator_w": "🇼",
+3607	    "regional_indicator_x": "🇽",
+3608	    "regional_indicator_y": "🇾",
+3609	    "regional_indicator_z": "🇿",
+3610	}
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/rich/_pick.py
+ Line number: 13
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+12	    """
+13	    assert values, "1 or more values required"
+14	    for value in values:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/rich/_ratio.py
+ Line number: 129
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+128	    total_ratio = sum(ratios)
+129	    assert total_ratio > 0, "Sum of ratios must be > 0"
+130	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/rich/_win32_console.py
+ Line number: 436
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+435	
+436	        assert fore is not None
+437	        assert back is not None
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/rich/_win32_console.py
+ Line number: 437
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+436	        assert fore is not None
+437	        assert back is not None
+438	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/rich/_win32_console.py
+ Line number: 566
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+565	        """
+566	        assert len(title) < 255, "Console title must be less than 255 characters"
+567	        SetConsoleTitle(title)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/rich/color.py
+ Line number: 365
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+364	        if self.type == ColorType.TRUECOLOR:
+365	            assert self.triplet is not None
+366	            return self.triplet
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/rich/color.py
+ Line number: 368
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+367	        elif self.type == ColorType.EIGHT_BIT:
+368	            assert self.number is not None
+369	            return EIGHT_BIT_PALETTE[self.number]
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/rich/color.py
+ Line number: 371
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+370	        elif self.type == ColorType.STANDARD:
+371	            assert self.number is not None
+372	            return theme.ansi_colors[self.number]
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/rich/color.py
+ Line number: 374
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+373	        elif self.type == ColorType.WINDOWS:
+374	            assert self.number is not None
+375	            return WINDOWS_PALETTE[self.number]
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/rich/color.py
+ Line number: 377
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+376	        else:  # self.type == ColorType.DEFAULT:
+377	            assert self.number is None
+378	            return theme.foreground_color if foreground else theme.background_color
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/rich/color.py
+ Line number: 493
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+492	            number = self.number
+493	            assert number is not None
+494	            fore, back = (30, 40) if number < 8 else (82, 92)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/rich/color.py
+ Line number: 499
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+498	            number = self.number
+499	            assert number is not None
+500	            fore, back = (30, 40) if number < 8 else (82, 92)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/rich/color.py
+ Line number: 504
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+503	        elif _type == ColorType.EIGHT_BIT:
+504	            assert self.number is not None
+505	            return ("38" if foreground else "48", "5", str(self.number))
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/rich/color.py
+ Line number: 508
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+507	        else:  # self.standard == ColorStandard.TRUECOLOR:
+508	            assert self.triplet is not None
+509	            red, green, blue = self.triplet
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/rich/color.py
+ Line number: 520
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+519	        if system == ColorSystem.EIGHT_BIT and self.system == ColorSystem.TRUECOLOR:
+520	            assert self.triplet is not None
+521	            _h, l, s = rgb_to_hls(*self.triplet.normalized)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/rich/color.py
+ Line number: 546
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+545	            if self.system == ColorSystem.TRUECOLOR:
+546	                assert self.triplet is not None
+547	                triplet = self.triplet
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/rich/color.py
+ Line number: 549
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+548	            else:  # self.system == ColorSystem.EIGHT_BIT
+549	                assert self.number is not None
+550	                triplet = ColorTriplet(*EIGHT_BIT_PALETTE[self.number])
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/rich/color.py
+ Line number: 557
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+556	            if self.system == ColorSystem.TRUECOLOR:
+557	                assert self.triplet is not None
+558	                triplet = self.triplet
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/rich/color.py
+ Line number: 560
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+559	            else:  # self.system == ColorSystem.EIGHT_BIT
+560	                assert self.number is not None
+561	                if self.number < 16:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/rich/color.py
+ Line number: 573
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+572	    """Parse six hex characters in to RGB triplet."""
+573	    assert len(hex_color) == 6, "must be 6 characters"
+574	    color = ColorTriplet(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/rich/console.py
+ Line number: 1135
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1134	
+1135	        assert count >= 0, "count must be >= 0"
+1136	        self.print(NewLine(count))
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/rich/console.py
+ Line number: 1900
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1899	                offset -= 1
+1900	            assert frame is not None
+1901	            return frame.f_code.co_filename, frame.f_lineno, frame.f_locals
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/rich/console.py
+ Line number: 2138
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2137	        """
+2138	        assert (
+2139	            self.record
+2140	        ), "To export console contents set record=True in the constructor or instance"
+2141	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/rich/console.py
+ Line number: 2194
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2193	        """
+2194	        assert (
+2195	            self.record
+2196	        ), "To export console contents set record=True in the constructor or instance"
+2197	        fragments: List[str] = []
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/rich/live.py
+ Line number: 65
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+64	    ) -> None:
+65	        assert refresh_per_second > 0, "refresh_per_second must be > 0"
+66	        self._renderable = renderable
+
+
+ + +
+
+ +
+
+ blacklist: Standard pseudo-random generators are not suitable for security/cryptographic purposes.
+ Test ID: B311
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-330
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/rich/live.py
+ Line number: 352
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b311-random
+ +
+
+351	                time.sleep(0.4)
+352	                if random.randint(0, 10) < 1:
+353	                    console.log(next(examples))
+
+
+ + +
+
+ +
+
+ blacklist: Standard pseudo-random generators are not suitable for security/cryptographic purposes.
+ Test ID: B311
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-330
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/rich/live.py
+ Line number: 355
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b311-random
+ +
+
+354	                exchange_rate_dict[(select_exchange, exchange)] = 200 / (
+355	                    (random.random() * 320) + 1
+356	                )
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/rich/logging.py
+ Line number: 136
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+135	            exc_type, exc_value, exc_traceback = record.exc_info
+136	            assert exc_type is not None
+137	            assert exc_value is not None
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/rich/logging.py
+ Line number: 137
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+136	            assert exc_type is not None
+137	            assert exc_value is not None
+138	            traceback = Traceback.from_exception(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/rich/pretty.py
+ Line number: 191
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+190	    console = console or get_console()
+191	    assert console is not None
+192	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/rich/pretty.py
+ Line number: 196
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+195	        if value is not None:
+196	            assert console is not None
+197	            builtins._ = None  # type: ignore[attr-defined]
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/rich/pretty.py
+ Line number: 496
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+495	        )
+496	        assert self.node is not None
+497	        return self.node.check_length(start_length, max_length)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/rich/pretty.py
+ Line number: 502
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+501	        node = self.node
+502	        assert node is not None
+503	        whitespace = self.whitespace
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/rich/pretty.py
+ Line number: 504
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+503	        whitespace = self.whitespace
+504	        assert node.children
+505	        if node.key_repr:
+
+
+ + +
+
+ +
+
+ try_except_pass: Try, Except, Pass detected.
+ Test ID: B110
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/rich/pretty.py
+ Line number: 641
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b110_try_except_pass.html
+ +
+
+640	                    rich_repr_result = obj.__rich_repr__()
+641	            except Exception:
+642	                pass
+643	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/rich/progress.py
+ Line number: 1080
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1079	    ) -> None:
+1080	        assert refresh_per_second > 0, "refresh_per_second must be > 0"
+1081	        self._lock = RLock()
+
+
+ + +
+
+ +
+
+ blacklist: Standard pseudo-random generators are not suitable for security/cryptographic purposes.
+ Test ID: B311
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-330
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/rich/progress.py
+ Line number: 1701
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b311-random
+ +
+
+1700	            time.sleep(0.01)
+1701	            if random.randint(0, 100) < 1:
+1702	                progress.log(next(examples))
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/rich/prompt.py
+ Line number: 214
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+213	        """
+214	        assert self.choices is not None
+215	        return value.strip() in self.choices
+
+
+ + +
+
+ +
+
+ blacklist: Standard pseudo-random generators are not suitable for security/cryptographic purposes.
+ Test ID: B311
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-330
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/rich/style.py
+ Line number: 193
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b311-random
+ +
+
+192	        self._link_id = (
+193	            f"{randint(0, 999999)}{hash(self._meta)}" if (link or meta) else ""
+194	        )
+
+
+ + +
+
+ +
+
+ blacklist: Standard pseudo-random generators are not suitable for security/cryptographic purposes.
+ Test ID: B311
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-330
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/rich/style.py
+ Line number: 243
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b311-random
+ +
+
+242	        style._meta = dumps(meta)
+243	        style._link_id = f"{randint(0, 999999)}{hash(style._meta)}"
+244	        style._hash = None
+
+
+ + +
+
+ +
+
+ blacklist: Deserialization with the marshal module is possibly dangerous.
+ Test ID: B302
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-502
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/rich/style.py
+ Line number: 475
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b302-marshal
+ +
+
+474	        """Get meta information (can not be changed after construction)."""
+475	        return {} if self._meta is None else cast(Dict[str, Any], loads(self._meta))
+476	
+
+
+ + +
+
+ +
+
+ blacklist: Standard pseudo-random generators are not suitable for security/cryptographic purposes.
+ Test ID: B311
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-330
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/rich/style.py
+ Line number: 490
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b311-random
+ +
+
+489	        style._link = self._link
+490	        style._link_id = f"{randint(0, 999999)}" if self._link else ""
+491	        style._null = False
+
+
+ + +
+
+ +
+
+ blacklist: Standard pseudo-random generators are not suitable for security/cryptographic purposes.
+ Test ID: B311
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-330
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/rich/style.py
+ Line number: 642
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b311-random
+ +
+
+641	        style._link = self._link
+642	        style._link_id = f"{randint(0, 999999)}" if self._link else ""
+643	        style._hash = self._hash
+
+
+ + +
+
+ +
+
+ blacklist: Standard pseudo-random generators are not suitable for security/cryptographic purposes.
+ Test ID: B311
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-330
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/rich/style.py
+ Line number: 688
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b311-random
+ +
+
+687	        style._link = link
+688	        style._link_id = f"{randint(0, 999999)}" if link else ""
+689	        style._hash = None
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/rich/syntax.py
+ Line number: 482
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+481	                    """Split tokens to one per line."""
+482	                    assert lexer  # required to make MyPy happy - we know lexer is not None at this point
+483	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/rich/text.py
+ Line number: 787
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+786	            tab_size = self.tab_size
+787	        assert tab_size is not None
+788	        result = self.blank_copy()
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/rich/text.py
+ Line number: 856
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+855	        """
+856	        assert len(character) == 1, "Character must be a string of length 1"
+857	        if count:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/rich/text.py
+ Line number: 873
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+872	        """
+873	        assert len(character) == 1, "Character must be a string of length 1"
+874	        if count:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/rich/text.py
+ Line number: 889
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+888	        """
+889	        assert len(character) == 1, "Character must be a string of length 1"
+890	        if count:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/rich/text.py
+ Line number: 1024
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1023	        """
+1024	        assert separator, "separator must not be empty"
+1025	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/rich/traceback.py
+ Line number: 282
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+281	            if not isinstance(suppress_entity, str):
+282	                assert (
+283	                    suppress_entity.__file__ is not None
+284	                ), f"{suppress_entity!r} must be a module with '__file__' attribute"
+285	                path = os.path.dirname(suppress_entity.__file__)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/rich/traceback.py
+ Line number: 645
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+644	            if excluded:
+645	                assert exclude_frames is not None
+646	                yield Text(
+
+
+ + +
+
+ +
+
+ exec_used: Use of exec detected.
+ Test ID: B102
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/six.py
+ Line number: 735
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b102_exec_used.html
+ +
+
+734	            _locs_ = _globs_
+735	        exec("""exec _code_ in _globs_, _locs_""")
+736	
+
+
+ + +
+
+ +
+
+ blacklist: Standard pseudo-random generators are not suitable for security/cryptographic purposes.
+ Test ID: B311
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-330
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/tenacity/wait.py
+ Line number: 72
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b311-random
+ +
+
+71	    def __call__(self, retry_state: "RetryCallState") -> float:
+72	        return self.wait_random_min + (random.random() * (self.wait_random_max - self.wait_random_min))
+73	
+
+
+ + +
+
+ +
+
+ blacklist: Standard pseudo-random generators are not suitable for security/cryptographic purposes.
+ Test ID: B311
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-330
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/tenacity/wait.py
+ Line number: 194
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b311-random
+ +
+
+193	        high = super().__call__(retry_state=retry_state)
+194	        return random.uniform(0, high)
+195	
+
+
+ + +
+
+ +
+
+ blacklist: Standard pseudo-random generators are not suitable for security/cryptographic purposes.
+ Test ID: B311
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-330
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/tenacity/wait.py
+ Line number: 222
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b311-random
+ +
+
+221	    def __call__(self, retry_state: "RetryCallState") -> float:
+222	        jitter = random.uniform(0, self.jitter)
+223	        try:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/typing_extensions.py
+ Line number: 374
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+373	                            deduped_pairs.remove(pair)
+374	                    assert not deduped_pairs, deduped_pairs
+375	                    parameters = tuple(new_parameters)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/typing_extensions.py
+ Line number: 1300
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1299	        def copy_with(self, params):
+1300	            assert len(params) == 1
+1301	            new_type = params[0]
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/typing_extensions.py
+ Line number: 2613
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2612	        def __new__(cls, typename, bases, ns):
+2613	            assert _NamedTuple in bases
+2614	            for base in bases:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/typing_extensions.py
+ Line number: 2654
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2653	    def _namedtuple_mro_entries(bases):
+2654	        assert NamedTuple in bases
+2655	        return (_NamedTuple,)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/urllib3/contrib/securetransport.py
+ Line number: 719
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+718	            leaf = Security.SecTrustGetCertificateAtIndex(trust, 0)
+719	            assert leaf
+720	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/urllib3/contrib/securetransport.py
+ Line number: 723
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+722	            certdata = Security.SecCertificateCopyData(leaf)
+723	            assert certdata
+724	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/urllib3/contrib/securetransport.py
+ Line number: 901
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+900	        # See PEP 543 for the real deal.
+901	        assert not server_side
+902	        assert do_handshake_on_connect
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/urllib3/contrib/securetransport.py
+ Line number: 902
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+901	        assert not server_side
+902	        assert do_handshake_on_connect
+903	        assert suppress_ragged_eofs
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/urllib3/contrib/securetransport.py
+ Line number: 903
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+902	        assert do_handshake_on_connect
+903	        assert suppress_ragged_eofs
+904	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/urllib3/packages/backports/makefile.py
+ Line number: 23
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+22	    reading = "r" in mode or not writing
+23	    assert reading or writing
+24	    binary = "b" in mode
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/urllib3/packages/backports/makefile.py
+ Line number: 45
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+44	    else:
+45	        assert writing
+46	        buffer = io.BufferedWriter(raw, buffering)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/urllib3/packages/backports/weakref_finalize.py
+ Line number: 150
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+149	                        sys.excepthook(*sys.exc_info())
+150	                    assert f not in cls._registry
+151	        finally:
+
+
+ + +
+
+ +
+
+ exec_used: Use of exec detected.
+ Test ID: B102
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/urllib3/packages/six.py
+ Line number: 787
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b102_exec_used.html
+ +
+
+786	            _locs_ = _globs_
+787	        exec ("""exec _code_ in _globs_, _locs_""")
+788	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/urllib3/response.py
+ Line number: 495
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+494	        """
+495	        assert self._fp
+496	        c_int_max = 2 ** 31 - 1
+
+
+ + +
+
+ +
+
+ try_except_pass: Try, Except, Pass detected.
+ Test ID: B110
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/urllib3/util/connection.py
+ Line number: 141
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b110_try_except_pass.html
+ +
+
+140	            has_ipv6 = True
+141	        except Exception:
+142	            pass
+143	
+
+
+ + +
+
+ +
+
+ ssl_with_no_version: ssl.wrap_socket call with no SSL/TLS protocol version specified, the default SSLv23 could be insecure, possible security issue.
+ Test ID: B504
+ Severity: LOW
+ Confidence: MEDIUM
+ CWE: CWE-327
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/urllib3/util/ssl_.py
+ Line number: 179
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b504_ssl_with_no_version.html
+ +
+
+178	            }
+179	            return wrap_socket(socket, ciphers=self.ciphers, **kwargs)
+180	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/urllib3/util/ssltransport.py
+ Line number: 120
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+119	        reading = "r" in mode or not writing
+120	        assert reading or writing
+121	        binary = "b" in mode
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/urllib3/util/ssltransport.py
+ Line number: 142
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+141	        else:
+142	            assert writing
+143	            buffer = io.BufferedWriter(raw, buffering)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/__init__.py
+ Line number: 224
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+223	        if output:
+224	            assert decoder.encoding is not None
+225	            yield decoder.encoding
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/__init__.py
+ Line number: 231
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+230	        output = decode(b'', final=True)
+231	        assert decoder.encoding is not None
+232	        yield decoder.encoding
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/mklabels.py
+ Line number: 21
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+20	def assert_lower(string):
+21	    assert string == string.lower()
+22	    return string
+
+
+ + +
+
+ +
+
+ blacklist: Audit url open for permitted schemes. Allowing use of file:/ or custom schemes is often unexpected.
+ Test ID: B310
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-22
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/mklabels.py
+ Line number: 47
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b310-urllib-urlopen
+ +
+
+46	         repr(encoding['name']).lstrip('u'))
+47	        for category in json.loads(urlopen(url).read().decode('ascii'))
+48	        for encoding in category['encodings']
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 30
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+29	def test_labels():
+30	    assert lookup('utf-8').name == 'utf-8'
+31	    assert lookup('Utf-8').name == 'utf-8'
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 31
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+30	    assert lookup('utf-8').name == 'utf-8'
+31	    assert lookup('Utf-8').name == 'utf-8'
+32	    assert lookup('UTF-8').name == 'utf-8'
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 32
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+31	    assert lookup('Utf-8').name == 'utf-8'
+32	    assert lookup('UTF-8').name == 'utf-8'
+33	    assert lookup('utf8').name == 'utf-8'
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 33
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+32	    assert lookup('UTF-8').name == 'utf-8'
+33	    assert lookup('utf8').name == 'utf-8'
+34	    assert lookup('utf8').name == 'utf-8'
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 34
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+33	    assert lookup('utf8').name == 'utf-8'
+34	    assert lookup('utf8').name == 'utf-8'
+35	    assert lookup('utf8 ').name == 'utf-8'
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 35
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+34	    assert lookup('utf8').name == 'utf-8'
+35	    assert lookup('utf8 ').name == 'utf-8'
+36	    assert lookup(' \r\nutf8\t').name == 'utf-8'
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 36
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+35	    assert lookup('utf8 ').name == 'utf-8'
+36	    assert lookup(' \r\nutf8\t').name == 'utf-8'
+37	    assert lookup('u8') is None  # Python label.
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 37
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+36	    assert lookup(' \r\nutf8\t').name == 'utf-8'
+37	    assert lookup('u8') is None  # Python label.
+38	    assert lookup('utf-8 ') is None  # Non-ASCII white space.
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 38
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+37	    assert lookup('u8') is None  # Python label.
+38	    assert lookup('utf-8 ') is None  # Non-ASCII white space.
+39	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 40
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+39	
+40	    assert lookup('US-ASCII').name == 'windows-1252'
+41	    assert lookup('iso-8859-1').name == 'windows-1252'
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 41
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+40	    assert lookup('US-ASCII').name == 'windows-1252'
+41	    assert lookup('iso-8859-1').name == 'windows-1252'
+42	    assert lookup('latin1').name == 'windows-1252'
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 42
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+41	    assert lookup('iso-8859-1').name == 'windows-1252'
+42	    assert lookup('latin1').name == 'windows-1252'
+43	    assert lookup('LATIN1').name == 'windows-1252'
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 43
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+42	    assert lookup('latin1').name == 'windows-1252'
+43	    assert lookup('LATIN1').name == 'windows-1252'
+44	    assert lookup('latin-1') is None
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 44
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+43	    assert lookup('LATIN1').name == 'windows-1252'
+44	    assert lookup('latin-1') is None
+45	    assert lookup('LATİN1') is None  # ASCII-only case insensitivity.
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 45
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+44	    assert lookup('latin-1') is None
+45	    assert lookup('LATİN1') is None  # ASCII-only case insensitivity.
+46	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 50
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+49	    for label in LABELS:
+50	        assert decode(b'', label) == ('', lookup(label))
+51	        assert encode('', label) == b''
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 51
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+50	        assert decode(b'', label) == ('', lookup(label))
+51	        assert encode('', label) == b''
+52	        for repeat in [0, 1, 12]:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 54
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+53	            output, _ = iter_decode([b''] * repeat, label)
+54	            assert list(output) == []
+55	            assert list(iter_encode([''] * repeat, label)) == []
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 55
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+54	            assert list(output) == []
+55	            assert list(iter_encode([''] * repeat, label)) == []
+56	        decoder = IncrementalDecoder(label)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 57
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+56	        decoder = IncrementalDecoder(label)
+57	        assert decoder.decode(b'') == ''
+58	        assert decoder.decode(b'', final=True) == ''
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 58
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+57	        assert decoder.decode(b'') == ''
+58	        assert decoder.decode(b'', final=True) == ''
+59	        encoder = IncrementalEncoder(label)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 60
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+59	        encoder = IncrementalEncoder(label)
+60	        assert encoder.encode('') == b''
+61	        assert encoder.encode('', final=True) == b''
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 61
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+60	        assert encoder.encode('') == b''
+61	        assert encoder.encode('', final=True) == b''
+62	    # All encoding names are valid labels too:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 64
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+63	    for name in set(LABELS.values()):
+64	        assert lookup(name).name == name
+65	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 77
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+76	def test_decode():
+77	    assert decode(b'\x80', 'latin1') == ('€', lookup('latin1'))
+78	    assert decode(b'\x80', lookup('latin1')) == ('€', lookup('latin1'))
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 78
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+77	    assert decode(b'\x80', 'latin1') == ('€', lookup('latin1'))
+78	    assert decode(b'\x80', lookup('latin1')) == ('€', lookup('latin1'))
+79	    assert decode(b'\xc3\xa9', 'utf8') == ('é', lookup('utf8'))
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 79
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+78	    assert decode(b'\x80', lookup('latin1')) == ('€', lookup('latin1'))
+79	    assert decode(b'\xc3\xa9', 'utf8') == ('é', lookup('utf8'))
+80	    assert decode(b'\xc3\xa9', UTF8) == ('é', lookup('utf8'))
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 80
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+79	    assert decode(b'\xc3\xa9', 'utf8') == ('é', lookup('utf8'))
+80	    assert decode(b'\xc3\xa9', UTF8) == ('é', lookup('utf8'))
+81	    assert decode(b'\xc3\xa9', 'ascii') == ('é', lookup('ascii'))
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 81
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+80	    assert decode(b'\xc3\xa9', UTF8) == ('é', lookup('utf8'))
+81	    assert decode(b'\xc3\xa9', 'ascii') == ('é', lookup('ascii'))
+82	    assert decode(b'\xEF\xBB\xBF\xc3\xa9', 'ascii') == ('é', lookup('utf8'))  # UTF-8 with BOM
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 82
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+81	    assert decode(b'\xc3\xa9', 'ascii') == ('é', lookup('ascii'))
+82	    assert decode(b'\xEF\xBB\xBF\xc3\xa9', 'ascii') == ('é', lookup('utf8'))  # UTF-8 with BOM
+83	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 84
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+83	
+84	    assert decode(b'\xFE\xFF\x00\xe9', 'ascii') == ('é', lookup('utf-16be'))  # UTF-16-BE with BOM
+85	    assert decode(b'\xFF\xFE\xe9\x00', 'ascii') == ('é', lookup('utf-16le'))  # UTF-16-LE with BOM
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 85
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+84	    assert decode(b'\xFE\xFF\x00\xe9', 'ascii') == ('é', lookup('utf-16be'))  # UTF-16-BE with BOM
+85	    assert decode(b'\xFF\xFE\xe9\x00', 'ascii') == ('é', lookup('utf-16le'))  # UTF-16-LE with BOM
+86	    assert decode(b'\xFE\xFF\xe9\x00', 'ascii') == ('\ue900', lookup('utf-16be'))
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 86
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+85	    assert decode(b'\xFF\xFE\xe9\x00', 'ascii') == ('é', lookup('utf-16le'))  # UTF-16-LE with BOM
+86	    assert decode(b'\xFE\xFF\xe9\x00', 'ascii') == ('\ue900', lookup('utf-16be'))
+87	    assert decode(b'\xFF\xFE\x00\xe9', 'ascii') == ('\ue900', lookup('utf-16le'))
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 87
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+86	    assert decode(b'\xFE\xFF\xe9\x00', 'ascii') == ('\ue900', lookup('utf-16be'))
+87	    assert decode(b'\xFF\xFE\x00\xe9', 'ascii') == ('\ue900', lookup('utf-16le'))
+88	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 89
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+88	
+89	    assert decode(b'\x00\xe9', 'UTF-16BE') == ('é', lookup('utf-16be'))
+90	    assert decode(b'\xe9\x00', 'UTF-16LE') == ('é', lookup('utf-16le'))
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 90
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+89	    assert decode(b'\x00\xe9', 'UTF-16BE') == ('é', lookup('utf-16be'))
+90	    assert decode(b'\xe9\x00', 'UTF-16LE') == ('é', lookup('utf-16le'))
+91	    assert decode(b'\xe9\x00', 'UTF-16') == ('é', lookup('utf-16le'))
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 91
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+90	    assert decode(b'\xe9\x00', 'UTF-16LE') == ('é', lookup('utf-16le'))
+91	    assert decode(b'\xe9\x00', 'UTF-16') == ('é', lookup('utf-16le'))
+92	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 93
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+92	
+93	    assert decode(b'\xe9\x00', 'UTF-16BE') == ('\ue900', lookup('utf-16be'))
+94	    assert decode(b'\x00\xe9', 'UTF-16LE') == ('\ue900', lookup('utf-16le'))
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 94
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+93	    assert decode(b'\xe9\x00', 'UTF-16BE') == ('\ue900', lookup('utf-16be'))
+94	    assert decode(b'\x00\xe9', 'UTF-16LE') == ('\ue900', lookup('utf-16le'))
+95	    assert decode(b'\x00\xe9', 'UTF-16') == ('\ue900', lookup('utf-16le'))
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 95
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+94	    assert decode(b'\x00\xe9', 'UTF-16LE') == ('\ue900', lookup('utf-16le'))
+95	    assert decode(b'\x00\xe9', 'UTF-16') == ('\ue900', lookup('utf-16le'))
+96	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 99
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+98	def test_encode():
+99	    assert encode('é', 'latin1') == b'\xe9'
+100	    assert encode('é', 'utf8') == b'\xc3\xa9'
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 100
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+99	    assert encode('é', 'latin1') == b'\xe9'
+100	    assert encode('é', 'utf8') == b'\xc3\xa9'
+101	    assert encode('é', 'utf8') == b'\xc3\xa9'
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 101
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+100	    assert encode('é', 'utf8') == b'\xc3\xa9'
+101	    assert encode('é', 'utf8') == b'\xc3\xa9'
+102	    assert encode('é', 'utf-16') == b'\xe9\x00'
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 102
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+101	    assert encode('é', 'utf8') == b'\xc3\xa9'
+102	    assert encode('é', 'utf-16') == b'\xe9\x00'
+103	    assert encode('é', 'utf-16le') == b'\xe9\x00'
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 103
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+102	    assert encode('é', 'utf-16') == b'\xe9\x00'
+103	    assert encode('é', 'utf-16le') == b'\xe9\x00'
+104	    assert encode('é', 'utf-16be') == b'\x00\xe9'
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 104
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+103	    assert encode('é', 'utf-16le') == b'\xe9\x00'
+104	    assert encode('é', 'utf-16be') == b'\x00\xe9'
+105	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 111
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+110	        return ''.join(output)
+111	    assert iter_decode_to_string([], 'latin1') == ''
+112	    assert iter_decode_to_string([b''], 'latin1') == ''
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 112
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+111	    assert iter_decode_to_string([], 'latin1') == ''
+112	    assert iter_decode_to_string([b''], 'latin1') == ''
+113	    assert iter_decode_to_string([b'\xe9'], 'latin1') == 'é'
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 113
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+112	    assert iter_decode_to_string([b''], 'latin1') == ''
+113	    assert iter_decode_to_string([b'\xe9'], 'latin1') == 'é'
+114	    assert iter_decode_to_string([b'hello'], 'latin1') == 'hello'
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 114
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+113	    assert iter_decode_to_string([b'\xe9'], 'latin1') == 'é'
+114	    assert iter_decode_to_string([b'hello'], 'latin1') == 'hello'
+115	    assert iter_decode_to_string([b'he', b'llo'], 'latin1') == 'hello'
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 115
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+114	    assert iter_decode_to_string([b'hello'], 'latin1') == 'hello'
+115	    assert iter_decode_to_string([b'he', b'llo'], 'latin1') == 'hello'
+116	    assert iter_decode_to_string([b'hell', b'o'], 'latin1') == 'hello'
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 116
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+115	    assert iter_decode_to_string([b'he', b'llo'], 'latin1') == 'hello'
+116	    assert iter_decode_to_string([b'hell', b'o'], 'latin1') == 'hello'
+117	    assert iter_decode_to_string([b'\xc3\xa9'], 'latin1') == 'é'
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 117
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+116	    assert iter_decode_to_string([b'hell', b'o'], 'latin1') == 'hello'
+117	    assert iter_decode_to_string([b'\xc3\xa9'], 'latin1') == 'é'
+118	    assert iter_decode_to_string([b'\xEF\xBB\xBF\xc3\xa9'], 'latin1') == 'é'
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 118
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+117	    assert iter_decode_to_string([b'\xc3\xa9'], 'latin1') == 'é'
+118	    assert iter_decode_to_string([b'\xEF\xBB\xBF\xc3\xa9'], 'latin1') == 'é'
+119	    assert iter_decode_to_string([
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 119
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+118	    assert iter_decode_to_string([b'\xEF\xBB\xBF\xc3\xa9'], 'latin1') == 'é'
+119	    assert iter_decode_to_string([
+120	        b'\xEF\xBB\xBF', b'\xc3', b'\xa9'], 'latin1') == 'é'
+121	    assert iter_decode_to_string([
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 121
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+120	        b'\xEF\xBB\xBF', b'\xc3', b'\xa9'], 'latin1') == 'é'
+121	    assert iter_decode_to_string([
+122	        b'\xEF\xBB\xBF', b'a', b'\xc3'], 'latin1') == 'a\uFFFD'
+123	    assert iter_decode_to_string([
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 123
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+122	        b'\xEF\xBB\xBF', b'a', b'\xc3'], 'latin1') == 'a\uFFFD'
+123	    assert iter_decode_to_string([
+124	        b'', b'\xEF', b'', b'', b'\xBB\xBF\xc3', b'\xa9'], 'latin1') == 'é'
+125	    assert iter_decode_to_string([b'\xEF\xBB\xBF'], 'latin1') == ''
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 125
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+124	        b'', b'\xEF', b'', b'', b'\xBB\xBF\xc3', b'\xa9'], 'latin1') == 'é'
+125	    assert iter_decode_to_string([b'\xEF\xBB\xBF'], 'latin1') == ''
+126	    assert iter_decode_to_string([b'\xEF\xBB'], 'latin1') == 'ï»'
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 126
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+125	    assert iter_decode_to_string([b'\xEF\xBB\xBF'], 'latin1') == ''
+126	    assert iter_decode_to_string([b'\xEF\xBB'], 'latin1') == 'ï»'
+127	    assert iter_decode_to_string([b'\xFE\xFF\x00\xe9'], 'latin1') == 'é'
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 127
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+126	    assert iter_decode_to_string([b'\xEF\xBB'], 'latin1') == 'ï»'
+127	    assert iter_decode_to_string([b'\xFE\xFF\x00\xe9'], 'latin1') == 'é'
+128	    assert iter_decode_to_string([b'\xFF\xFE\xe9\x00'], 'latin1') == 'é'
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 128
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+127	    assert iter_decode_to_string([b'\xFE\xFF\x00\xe9'], 'latin1') == 'é'
+128	    assert iter_decode_to_string([b'\xFF\xFE\xe9\x00'], 'latin1') == 'é'
+129	    assert iter_decode_to_string([
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 129
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+128	    assert iter_decode_to_string([b'\xFF\xFE\xe9\x00'], 'latin1') == 'é'
+129	    assert iter_decode_to_string([
+130	        b'', b'\xFF', b'', b'', b'\xFE\xe9', b'\x00'], 'latin1') == 'é'
+131	    assert iter_decode_to_string([
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 131
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+130	        b'', b'\xFF', b'', b'', b'\xFE\xe9', b'\x00'], 'latin1') == 'é'
+131	    assert iter_decode_to_string([
+132	        b'', b'h\xe9', b'llo'], 'x-user-defined') == 'h\uF7E9llo'
+133	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 136
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+135	def test_iter_encode():
+136	    assert b''.join(iter_encode([], 'latin1')) == b''
+137	    assert b''.join(iter_encode([''], 'latin1')) == b''
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 137
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+136	    assert b''.join(iter_encode([], 'latin1')) == b''
+137	    assert b''.join(iter_encode([''], 'latin1')) == b''
+138	    assert b''.join(iter_encode(['é'], 'latin1')) == b'\xe9'
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 138
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+137	    assert b''.join(iter_encode([''], 'latin1')) == b''
+138	    assert b''.join(iter_encode(['é'], 'latin1')) == b'\xe9'
+139	    assert b''.join(iter_encode(['', 'é', '', ''], 'latin1')) == b'\xe9'
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 139
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+138	    assert b''.join(iter_encode(['é'], 'latin1')) == b'\xe9'
+139	    assert b''.join(iter_encode(['', 'é', '', ''], 'latin1')) == b'\xe9'
+140	    assert b''.join(iter_encode(['', 'é', '', ''], 'utf-16')) == b'\xe9\x00'
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 140
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+139	    assert b''.join(iter_encode(['', 'é', '', ''], 'latin1')) == b'\xe9'
+140	    assert b''.join(iter_encode(['', 'é', '', ''], 'utf-16')) == b'\xe9\x00'
+141	    assert b''.join(iter_encode(['', 'é', '', ''], 'utf-16le')) == b'\xe9\x00'
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 141
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+140	    assert b''.join(iter_encode(['', 'é', '', ''], 'utf-16')) == b'\xe9\x00'
+141	    assert b''.join(iter_encode(['', 'é', '', ''], 'utf-16le')) == b'\xe9\x00'
+142	    assert b''.join(iter_encode(['', 'é', '', ''], 'utf-16be')) == b'\x00\xe9'
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 142
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+141	    assert b''.join(iter_encode(['', 'é', '', ''], 'utf-16le')) == b'\xe9\x00'
+142	    assert b''.join(iter_encode(['', 'é', '', ''], 'utf-16be')) == b'\x00\xe9'
+143	    assert b''.join(iter_encode([
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 143
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+142	    assert b''.join(iter_encode(['', 'é', '', ''], 'utf-16be')) == b'\x00\xe9'
+143	    assert b''.join(iter_encode([
+144	        '', 'h\uF7E9', '', 'llo'], 'x-user-defined')) == b'h\xe9llo'
+145	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 152
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+151	    decoded = 'aa'
+152	    assert decode(encoded, 'x-user-defined') == (decoded, lookup('x-user-defined'))
+153	    assert encode(decoded, 'x-user-defined') == encoded
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pip/_vendor/webencodings/tests.py
+ Line number: 153
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+152	    assert decode(encoded, 'x-user-defined') == (decoded, lookup('x-user-defined'))
+153	    assert encode(decoded, 'x-user-defined') == encoded
+
+
+ + +
+
+ +
+
+ try_except_pass: Try, Except, Pass detected.
+ Test ID: B110
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pygments/cmdline.py
+ Line number: 522
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b110_try_except_pass.html
+ +
+
+521	                width = shutil.get_terminal_size().columns - 2
+522	            except Exception:
+523	                pass
+524	        argparse.HelpFormatter.__init__(self, prog, indent_increment,
+
+
+ + +
+
+ +
+
+ exec_used: Use of exec detected.
+ Test ID: B102
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/pygments/formatters/__init__.py
+ Line number: 103
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b102_exec_used.html
+ +
+
+102	        with open(filename, 'rb') as f:
+103	            exec(f.read(), custom_namespace)
+104	        # Retrieve the class `formattername` from that namespace
+
+
+ + +
+
+ +
+
+ blacklist: Consider possible security implications associated with the subprocess module.
+ Test ID: B404
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/pygments/formatters/img.py
+ Line number: 17
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_imports.html#b404-import-subprocess
+ +
+
+16	
+17	import subprocess
+18	
+
+
+ + +
+
+ +
+
+ start_process_with_partial_path: Starting a process with a partial executable path
+ Test ID: B607
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/pygments/formatters/img.py
+ Line number: 93
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b607_start_process_with_partial_path.html
+ +
+
+92	    def _get_nix_font_path(self, name, style):
+93	        proc = subprocess.Popen(['fc-list', f"{name}:style={style}", 'file'],
+94	                                stdout=subprocess.PIPE, stderr=None)
+95	        stdout, _ = proc.communicate()
+
+
+ + +
+
+ +
+
+ subprocess_without_shell_equals_true: subprocess call - check for execution of untrusted input.
+ Test ID: B603
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/pygments/formatters/img.py
+ Line number: 93
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b603_subprocess_without_shell_equals_true.html
+ +
+
+92	    def _get_nix_font_path(self, name, style):
+93	        proc = subprocess.Popen(['fc-list', f"{name}:style={style}", 'file'],
+94	                                stdout=subprocess.PIPE, stderr=None)
+95	        stdout, _ = proc.communicate()
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pygments/lexer.py
+ Line number: 514
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+513	        """Preprocess the token component of a token definition."""
+514	        assert type(token) is _TokenType or callable(token), \
+515	            f'token type must be simple type or callable, not {token!r}'
+516	        return token
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pygments/lexer.py
+ Line number: 531
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+530	            else:
+531	                assert False, f'unknown new state {new_state!r}'
+532	        elif isinstance(new_state, combined):
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pygments/lexer.py
+ Line number: 538
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+537	            for istate in new_state:
+538	                assert istate != new_state, f'circular state ref {istate!r}'
+539	                itokens.extend(cls._process_state(unprocessed,
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pygments/lexer.py
+ Line number: 546
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+545	            for istate in new_state:
+546	                assert (istate in unprocessed or
+547	                        istate in ('#pop', '#push')), \
+548	                    'unknown new state ' + istate
+549	            return new_state
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pygments/lexer.py
+ Line number: 551
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+550	        else:
+551	            assert False, f'unknown new state def {new_state!r}'
+552	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pygments/lexer.py
+ Line number: 555
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+554	        """Preprocess a single state definition."""
+555	        assert isinstance(state, str), f"wrong state name {state!r}"
+556	        assert state[0] != '#', f"invalid state name {state!r}"
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pygments/lexer.py
+ Line number: 556
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+555	        assert isinstance(state, str), f"wrong state name {state!r}"
+556	        assert state[0] != '#', f"invalid state name {state!r}"
+557	        if state in processed:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pygments/lexer.py
+ Line number: 564
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+563	                # it's a state reference
+564	                assert tdef != state, f"circular state reference {state!r}"
+565	                tokens.extend(cls._process_state(unprocessed, processed,
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pygments/lexer.py
+ Line number: 578
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+577	
+578	            assert type(tdef) is tuple, f"wrong rule def {tdef!r}"
+579	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pygments/lexer.py
+ Line number: 744
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+743	                        else:
+744	                            assert False, f"wrong state def: {new_state!r}"
+745	                        statetokens = tokendefs[statestack[-1]]
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pygments/lexer.py
+ Line number: 831
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+830	                        else:
+831	                            assert False, f"wrong state def: {new_state!r}"
+832	                        statetokens = tokendefs[ctx.stack[-1]]
+
+
+ + +
+
+ +
+
+ exec_used: Use of exec detected.
+ Test ID: B102
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/pygments/lexers/__init__.py
+ Line number: 154
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b102_exec_used.html
+ +
+
+153	        with open(filename, 'rb') as f:
+154	            exec(f.read(), custom_namespace)
+155	        # Retrieve the class `lexername` from that namespace
+
+
+ + +
+
+ +
+
+ blacklist: Audit url open for permitted schemes. Allowing use of file:/ or custom schemes is often unexpected.
+ Test ID: B310
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-22
+ File: ./venv/lib/python3.12/site-packages/pygments/lexers/_lua_builtins.py
+ Line number: 225
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b310-urllib-urlopen
+ +
+
+224	    def get_newest_version():
+225	        f = urlopen('http://www.lua.org/manual/')
+226	        r = re.compile(r'^<A HREF="(\d\.\d)/">(Lua )?\1</A>')
+
+
+ + +
+
+ +
+
+ blacklist: Audit url open for permitted schemes. Allowing use of file:/ or custom schemes is often unexpected.
+ Test ID: B310
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-22
+ File: ./venv/lib/python3.12/site-packages/pygments/lexers/_lua_builtins.py
+ Line number: 233
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b310-urllib-urlopen
+ +
+
+232	    def get_lua_functions(version):
+233	        f = urlopen(f'http://www.lua.org/manual/{version}/')
+234	        r = re.compile(r'^<A HREF="manual.html#pdf-(?!lua|LUA)([^:]+)">\1</A>')
+
+
+ + +
+
+ +
+
+ blacklist: Audit url open for permitted schemes. Allowing use of file:/ or custom schemes is often unexpected.
+ Test ID: B310
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-22
+ File: ./venv/lib/python3.12/site-packages/pygments/lexers/_mysql_builtins.py
+ Line number: 1297
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b310-urllib-urlopen
+ +
+
+1296	        # Pull content from lex.h.
+1297	        lex_file = urlopen(LEX_URL).read().decode('utf8', errors='ignore')
+1298	        keywords = parse_lex_keywords(lex_file)
+
+
+ + +
+
+ +
+
+ blacklist: Audit url open for permitted schemes. Allowing use of file:/ or custom schemes is often unexpected.
+ Test ID: B310
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-22
+ File: ./venv/lib/python3.12/site-packages/pygments/lexers/_mysql_builtins.py
+ Line number: 1303
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b310-urllib-urlopen
+ +
+
+1302	        # Parse content in item_create.cc.
+1303	        item_create_file = urlopen(ITEM_CREATE_URL).read().decode('utf8', errors='ignore')
+1304	        functions.update(parse_item_create_functions(item_create_file))
+
+
+ + +
+
+ +
+
+ blacklist: Audit url open for permitted schemes. Allowing use of file:/ or custom schemes is often unexpected.
+ Test ID: B310
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-22
+ File: ./venv/lib/python3.12/site-packages/pygments/lexers/_php_builtins.py
+ Line number: 3299
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b310-urllib-urlopen
+ +
+
+3298	    def get_php_references():
+3299	        download = urlretrieve(PHP_MANUAL_URL)
+3300	        with tarfile.open(download[0]) as tar:
+
+
+ + +
+
+ +
+
+ tarfile_unsafe_members: tarfile.extractall used without any validation. Please check and discard dangerous members.
+ Test ID: B202
+ Severity: HIGH
+ Confidence: HIGH
+ CWE: CWE-22
+ File: ./venv/lib/python3.12/site-packages/pygments/lexers/_php_builtins.py
+ Line number: 3304
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b202_tarfile_unsafe_members.html
+ +
+
+3303	            else:
+3304	                tar.extractall()
+3305	        yield from glob.glob(f"{PHP_MANUAL_DIR}{PHP_REFERENCE_GLOB}")
+
+
+ + +
+
+ +
+
+ blacklist: Audit url open for permitted schemes. Allowing use of file:/ or custom schemes is often unexpected.
+ Test ID: B310
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-22
+ File: ./venv/lib/python3.12/site-packages/pygments/lexers/_postgres_builtins.py
+ Line number: 642
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b310-urllib-urlopen
+ +
+
+641	    def update_myself():
+642	        content = urlopen(DATATYPES_URL).read().decode('utf-8', errors='ignore')
+643	        data_file = list(content.splitlines())
+
+
+ + +
+
+ +
+
+ blacklist: Audit url open for permitted schemes. Allowing use of file:/ or custom schemes is often unexpected.
+ Test ID: B310
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-22
+ File: ./venv/lib/python3.12/site-packages/pygments/lexers/_postgres_builtins.py
+ Line number: 647
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b310-urllib-urlopen
+ +
+
+646	
+647	        content = urlopen(KEYWORDS_URL).read().decode('utf-8', errors='ignore')
+648	        keywords = parse_keywords(content)
+
+
+ + +
+
+ +
+
+ blacklist: Consider possible security implications associated with the subprocess module.
+ Test ID: B404
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/pygments/lexers/_scilab_builtins.py
+ Line number: 3055
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_imports.html#b404-import-subprocess
+ +
+
+3054	if __name__ == '__main__':  # pragma: no cover
+3055	    import subprocess
+3056	    from pygments.util import format_lines, duplicates_removed
+
+
+ + +
+
+ +
+
+ start_process_with_partial_path: Starting a process with a partial executable path
+ Test ID: B607
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/pygments/lexers/_scilab_builtins.py
+ Line number: 3061
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b607_start_process_with_partial_path.html
+ +
+
+3060	    def extract_completion(var_type):
+3061	        s = subprocess.Popen(['scilab', '-nwni'], stdin=subprocess.PIPE,
+3062	                             stdout=subprocess.PIPE, stderr=subprocess.PIPE)
+3063	        output = s.communicate(f'''\
+
+
+ + +
+
+ +
+
+ subprocess_without_shell_equals_true: subprocess call - check for execution of untrusted input.
+ Test ID: B603
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/pygments/lexers/_scilab_builtins.py
+ Line number: 3061
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b603_subprocess_without_shell_equals_true.html
+ +
+
+3060	    def extract_completion(var_type):
+3061	        s = subprocess.Popen(['scilab', '-nwni'], stdin=subprocess.PIPE,
+3062	                             stdout=subprocess.PIPE, stderr=subprocess.PIPE)
+3063	        output = s.communicate(f'''\
+
+
+ + +
+
+ +
+
+ hardcoded_password_string: Possible hardcoded password: 'root'
+ Test ID: B105
+ Severity: LOW
+ Confidence: MEDIUM
+ CWE: CWE-259
+ File: ./venv/lib/python3.12/site-packages/pygments/lexers/int_fiction.py
+ Line number: 728
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b105_hardcoded_password_string.html
+ +
+
+727	        for token in Inform6Lexer.tokens:
+728	            if token == 'root':
+729	                continue
+
+
+ + +
+
+ +
+
+ hardcoded_password_string: Possible hardcoded password: '[^\W\d]\w*'
+ Test ID: B105
+ Severity: LOW
+ Confidence: MEDIUM
+ CWE: CWE-259
+ File: ./venv/lib/python3.12/site-packages/pygments/lexers/jsonnet.py
+ Line number: 17
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b105_hardcoded_password_string.html
+ +
+
+16	
+17	jsonnet_token = r'[^\W\d]\w*'
+18	jsonnet_function_token = jsonnet_token + r'(?=\()'
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pygments/lexers/lilypond.py
+ Line number: 43
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+42	    else:
+43	        assert backslash == "disallowed"
+44	    return words(names, prefix, suffix)
+
+
+ + +
+
+ +
+
+ hardcoded_password_string: Possible hardcoded password: ' + (?= + \s # whitespace + | ; # comment + | \#[;|!] # fancy comments + | [)\]] # end delimiters + | $ # end of file + ) + '
+ Test ID: B105
+ Severity: LOW
+ Confidence: MEDIUM
+ CWE: CWE-259
+ File: ./venv/lib/python3.12/site-packages/pygments/lexers/lisp.py
+ Line number: 50
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b105_hardcoded_password_string.html
+ +
+
+49	    # Use within verbose regexes
+50	    token_end = r'''
+51	      (?=
+52	        \s         # whitespace
+53	        | ;        # comment
+54	        | \#[;|!] # fancy comments
+55	        | [)\]]    # end delimiters
+56	        | $        # end of file
+57	      )
+58	    '''
+59	
+
+
+ + +
+
+ +
+
+ hardcoded_password_string: Possible hardcoded password: '(?=\s|#|[)\]]|$)'
+ Test ID: B105
+ Severity: LOW
+ Confidence: MEDIUM
+ CWE: CWE-259
+ File: ./venv/lib/python3.12/site-packages/pygments/lexers/lisp.py
+ Line number: 3047
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b105_hardcoded_password_string.html
+ +
+
+3046	    # ...so, express it like this
+3047	    _token_end = r'(?=\s|#|[)\]]|$)'
+3048	
+
+
+ + +
+
+ +
+
+ hardcoded_password_string: Possible hardcoded password: '[A-Z]\w*'
+ Test ID: B105
+ Severity: LOW
+ Confidence: MEDIUM
+ CWE: CWE-259
+ File: ./venv/lib/python3.12/site-packages/pygments/lexers/parsers.py
+ Line number: 334
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b105_hardcoded_password_string.html
+ +
+
+333	    _id = r'[A-Za-z]\w*'
+334	    _TOKEN_REF = r'[A-Z]\w*'
+335	    _RULE_REF = r'[a-z]\w*'
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pygments/lexers/scripting.py
+ Line number: 1499
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1498	                        result += 0.01
+1499	        assert 0.0 <= result <= 1.0
+1500	        return result
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pygments/lexers/scripting.py
+ Line number: 1583
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1582	                result = 1.0
+1583	        assert 0.0 <= result <= 1.0
+1584	        return result
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pygments/lexers/sql.py
+ Line number: 236
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+235	    else:
+236	        assert 0, "SQL keywords not found"
+237	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/pygments/style.py
+ Line number: 79
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+78	                return text
+79	            assert False, f"wrong color format {text!r}"
+80	
+
+
+ + +
+
+ +
+
+ hardcoded_password_string: Possible hardcoded password: '㊙'
+ Test ID: B105
+ Severity: LOW
+ Confidence: MEDIUM
+ CWE: CWE-259
+ File: ./venv/lib/python3.12/site-packages/rich/_emoji_codes.py
+ Line number: 156
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b105_hardcoded_password_string.html
+ +
+
+155	    "japanese_reserved_button": "🈯",
+156	    "japanese_secret_button": "㊙",
+157	    "japanese_service_charge_button": "🈂",
+158	    "japanese_symbol_for_beginner": "🔰",
+159	    "japanese_vacancy_button": "🈳",
+160	    "jersey": "🇯🇪",
+161	    "jordan": "🇯🇴",
+162	    "kazakhstan": "🇰🇿",
+163	    "kenya": "🇰🇪",
+164	    "kiribati": "🇰🇮",
+165	    "kosovo": "🇽🇰",
+166	    "kuwait": "🇰🇼",
+167	    "kyrgyzstan": "🇰🇬",
+168	    "laos": "🇱🇦",
+169	    "latvia": "🇱🇻",
+170	    "lebanon": "🇱🇧",
+171	    "leo": "♌",
+172	    "lesotho": "🇱🇸",
+173	    "liberia": "🇱🇷",
+174	    "libra": "♎",
+175	    "libya": "🇱🇾",
+176	    "liechtenstein": "🇱🇮",
+177	    "lithuania": "🇱🇹",
+178	    "luxembourg": "🇱🇺",
+179	    "macau_sar_china": "🇲🇴",
+180	    "macedonia": "🇲🇰",
+181	    "madagascar": "🇲🇬",
+182	    "malawi": "🇲🇼",
+183	    "malaysia": "🇲🇾",
+184	    "maldives": "🇲🇻",
+185	    "mali": "🇲🇱",
+186	    "malta": "🇲🇹",
+187	    "marshall_islands": "🇲🇭",
+188	    "martinique": "🇲🇶",
+189	    "mauritania": "🇲🇷",
+190	    "mauritius": "🇲🇺",
+191	    "mayotte": "🇾🇹",
+192	    "mexico": "🇲🇽",
+193	    "micronesia": "🇫🇲",
+194	    "moldova": "🇲🇩",
+195	    "monaco": "🇲🇨",
+196	    "mongolia": "🇲🇳",
+197	    "montenegro": "🇲🇪",
+198	    "montserrat": "🇲🇸",
+199	    "morocco": "🇲🇦",
+200	    "mozambique": "🇲🇿",
+201	    "mrs._claus": "🤶",
+202	    "mrs._claus_dark_skin_tone": "🤶🏿",
+203	    "mrs._claus_light_skin_tone": "🤶🏻",
+204	    "mrs._claus_medium-dark_skin_tone": "🤶🏾",
+205	    "mrs._claus_medium-light_skin_tone": "🤶🏼",
+206	    "mrs._claus_medium_skin_tone": "🤶🏽",
+207	    "myanmar_(burma)": "🇲🇲",
+208	    "new_button": "🆕",
+209	    "ng_button": "🆖",
+210	    "namibia": "🇳🇦",
+211	    "nauru": "🇳🇷",
+212	    "nepal": "🇳🇵",
+213	    "netherlands": "🇳🇱",
+214	    "new_caledonia": "🇳🇨",
+215	    "new_zealand": "🇳🇿",
+216	    "nicaragua": "🇳🇮",
+217	    "niger": "🇳🇪",
+218	    "nigeria": "🇳🇬",
+219	    "niue": "🇳🇺",
+220	    "norfolk_island": "🇳🇫",
+221	    "north_korea": "🇰🇵",
+222	    "northern_mariana_islands": "🇲🇵",
+223	    "norway": "🇳🇴",
+224	    "ok_button": "🆗",
+225	    "ok_hand": "👌",
+226	    "ok_hand_dark_skin_tone": "👌🏿",
+227	    "ok_hand_light_skin_tone": "👌🏻",
+228	    "ok_hand_medium-dark_skin_tone": "👌🏾",
+229	    "ok_hand_medium-light_skin_tone": "👌🏼",
+230	    "ok_hand_medium_skin_tone": "👌🏽",
+231	    "on!_arrow": "🔛",
+232	    "o_button_(blood_type)": "🅾",
+233	    "oman": "🇴🇲",
+234	    "ophiuchus": "⛎",
+235	    "p_button": "🅿",
+236	    "pakistan": "🇵🇰",
+237	    "palau": "🇵🇼",
+238	    "palestinian_territories": "🇵🇸",
+239	    "panama": "🇵🇦",
+240	    "papua_new_guinea": "🇵🇬",
+241	    "paraguay": "🇵🇾",
+242	    "peru": "🇵🇪",
+243	    "philippines": "🇵🇭",
+244	    "pisces": "♓",
+245	    "pitcairn_islands": "🇵🇳",
+246	    "poland": "🇵🇱",
+247	    "portugal": "🇵🇹",
+248	    "puerto_rico": "🇵🇷",
+249	    "qatar": "🇶🇦",
+250	    "romania": "🇷🇴",
+251	    "russia": "🇷🇺",
+252	    "rwanda": "🇷🇼",
+253	    "réunion": "🇷🇪",
+254	    "soon_arrow": "🔜",
+255	    "sos_button": "🆘",
+256	    "sagittarius": "♐",
+257	    "samoa": "🇼🇸",
+258	    "san_marino": "🇸🇲",
+259	    "santa_claus": "🎅",
+260	    "santa_claus_dark_skin_tone": "🎅🏿",
+261	    "santa_claus_light_skin_tone": "🎅🏻",
+262	    "santa_claus_medium-dark_skin_tone": "🎅🏾",
+263	    "santa_claus_medium-light_skin_tone": "🎅🏼",
+264	    "santa_claus_medium_skin_tone": "🎅🏽",
+265	    "saudi_arabia": "🇸🇦",
+266	    "scorpio": "♏",
+267	    "scotland": "🏴\U000e0067\U000e0062\U000e0073\U000e0063\U000e0074\U000e007f",
+268	    "senegal": "🇸🇳",
+269	    "serbia": "🇷🇸",
+270	    "seychelles": "🇸🇨",
+271	    "sierra_leone": "🇸🇱",
+272	    "singapore": "🇸🇬",
+273	    "sint_maarten": "🇸🇽",
+274	    "slovakia": "🇸🇰",
+275	    "slovenia": "🇸🇮",
+276	    "solomon_islands": "🇸🇧",
+277	    "somalia": "🇸🇴",
+278	    "south_africa": "🇿🇦",
+279	    "south_georgia_&_south_sandwich_islands": "🇬🇸",
+280	    "south_korea": "🇰🇷",
+281	    "south_sudan": "🇸🇸",
+282	    "spain": "🇪🇸",
+283	    "sri_lanka": "🇱🇰",
+284	    "st._barthélemy": "🇧🇱",
+285	    "st._helena": "🇸🇭",
+286	    "st._kitts_&_nevis": "🇰🇳",
+287	    "st._lucia": "🇱🇨",
+288	    "st._martin": "🇲🇫",
+289	    "st._pierre_&_miquelon": "🇵🇲",
+290	    "st._vincent_&_grenadines": "🇻🇨",
+291	    "statue_of_liberty": "🗽",
+292	    "sudan": "🇸🇩",
+293	    "suriname": "🇸🇷",
+294	    "svalbard_&_jan_mayen": "🇸🇯",
+295	    "swaziland": "🇸🇿",
+296	    "sweden": "🇸🇪",
+297	    "switzerland": "🇨🇭",
+298	    "syria": "🇸🇾",
+299	    "são_tomé_&_príncipe": "🇸🇹",
+300	    "t-rex": "🦖",
+301	    "top_arrow": "🔝",
+302	    "taiwan": "🇹🇼",
+303	    "tajikistan": "🇹🇯",
+304	    "tanzania": "🇹🇿",
+305	    "taurus": "♉",
+306	    "thailand": "🇹🇭",
+307	    "timor-leste": "🇹🇱",
+308	    "togo": "🇹🇬",
+309	    "tokelau": "🇹🇰",
+310	    "tokyo_tower": "🗼",
+311	    "tonga": "🇹🇴",
+312	    "trinidad_&_tobago": "🇹🇹",
+313	    "tristan_da_cunha": "🇹🇦",
+314	    "tunisia": "🇹🇳",
+315	    "turkey": "🦃",
+316	    "turkmenistan": "🇹🇲",
+317	    "turks_&_caicos_islands": "🇹🇨",
+318	    "tuvalu": "🇹🇻",
+319	    "u.s._outlying_islands": "🇺🇲",
+320	    "u.s._virgin_islands": "🇻🇮",
+321	    "up!_button": "🆙",
+322	    "uganda": "🇺🇬",
+323	    "ukraine": "🇺🇦",
+324	    "united_arab_emirates": "🇦🇪",
+325	    "united_kingdom": "🇬🇧",
+326	    "united_nations": "🇺🇳",
+327	    "united_states": "🇺🇸",
+328	    "uruguay": "🇺🇾",
+329	    "uzbekistan": "🇺🇿",
+330	    "vs_button": "🆚",
+331	    "vanuatu": "🇻🇺",
+332	    "vatican_city": "🇻🇦",
+333	    "venezuela": "🇻🇪",
+334	    "vietnam": "🇻🇳",
+335	    "virgo": "♍",
+336	    "wales": "🏴\U000e0067\U000e0062\U000e0077\U000e006c\U000e0073\U000e007f",
+337	    "wallis_&_futuna": "🇼🇫",
+338	    "western_sahara": "🇪🇭",
+339	    "yemen": "🇾🇪",
+340	    "zambia": "🇿🇲",
+341	    "zimbabwe": "🇿🇼",
+342	    "abacus": "🧮",
+343	    "adhesive_bandage": "🩹",
+344	    "admission_tickets": "🎟",
+345	    "adult": "🧑",
+346	    "adult_dark_skin_tone": "🧑🏿",
+347	    "adult_light_skin_tone": "🧑🏻",
+348	    "adult_medium-dark_skin_tone": "🧑🏾",
+349	    "adult_medium-light_skin_tone": "🧑🏼",
+350	    "adult_medium_skin_tone": "🧑🏽",
+351	    "aerial_tramway": "🚡",
+352	    "airplane": "✈",
+353	    "airplane_arrival": "🛬",
+354	    "airplane_departure": "🛫",
+355	    "alarm_clock": "⏰",
+356	    "alembic": "⚗",
+357	    "alien": "👽",
+358	    "alien_monster": "👾",
+359	    "ambulance": "🚑",
+360	    "american_football": "🏈",
+361	    "amphora": "🏺",
+362	    "anchor": "⚓",
+363	    "anger_symbol": "💢",
+364	    "angry_face": "😠",
+365	    "angry_face_with_horns": "👿",
+366	    "anguished_face": "😧",
+367	    "ant": "🐜",
+368	    "antenna_bars": "📶",
+369	    "anxious_face_with_sweat": "😰",
+370	    "articulated_lorry": "🚛",
+371	    "artist_palette": "🎨",
+372	    "astonished_face": "😲",
+373	    "atom_symbol": "⚛",
+374	    "auto_rickshaw": "🛺",
+375	    "automobile": "🚗",
+376	    "avocado": "🥑",
+377	    "axe": "🪓",
+378	    "baby": "👶",
+379	    "baby_angel": "👼",
+380	    "baby_angel_dark_skin_tone": "👼🏿",
+381	    "baby_angel_light_skin_tone": "👼🏻",
+382	    "baby_angel_medium-dark_skin_tone": "👼🏾",
+383	    "baby_angel_medium-light_skin_tone": "👼🏼",
+384	    "baby_angel_medium_skin_tone": "👼🏽",
+385	    "baby_bottle": "🍼",
+386	    "baby_chick": "🐤",
+387	    "baby_dark_skin_tone": "👶🏿",
+388	    "baby_light_skin_tone": "👶🏻",
+389	    "baby_medium-dark_skin_tone": "👶🏾",
+390	    "baby_medium-light_skin_tone": "👶🏼",
+391	    "baby_medium_skin_tone": "👶🏽",
+392	    "baby_symbol": "🚼",
+393	    "backhand_index_pointing_down": "👇",
+394	    "backhand_index_pointing_down_dark_skin_tone": "👇🏿",
+395	    "backhand_index_pointing_down_light_skin_tone": "👇🏻",
+396	    "backhand_index_pointing_down_medium-dark_skin_tone": "👇🏾",
+397	    "backhand_index_pointing_down_medium-light_skin_tone": "👇🏼",
+398	    "backhand_index_pointing_down_medium_skin_tone": "👇🏽",
+399	    "backhand_index_pointing_left": "👈",
+400	    "backhand_index_pointing_left_dark_skin_tone": "👈🏿",
+401	    "backhand_index_pointing_left_light_skin_tone": "👈🏻",
+402	    "backhand_index_pointing_left_medium-dark_skin_tone": "👈🏾",
+403	    "backhand_index_pointing_left_medium-light_skin_tone": "👈🏼",
+404	    "backhand_index_pointing_left_medium_skin_tone": "👈🏽",
+405	    "backhand_index_pointing_right": "👉",
+406	    "backhand_index_pointing_right_dark_skin_tone": "👉🏿",
+407	    "backhand_index_pointing_right_light_skin_tone": "👉🏻",
+408	    "backhand_index_pointing_right_medium-dark_skin_tone": "👉🏾",
+409	    "backhand_index_pointing_right_medium-light_skin_tone": "👉🏼",
+410	    "backhand_index_pointing_right_medium_skin_tone": "👉🏽",
+411	    "backhand_index_pointing_up": "👆",
+412	    "backhand_index_pointing_up_dark_skin_tone": "👆🏿",
+413	    "backhand_index_pointing_up_light_skin_tone": "👆🏻",
+414	    "backhand_index_pointing_up_medium-dark_skin_tone": "👆🏾",
+415	    "backhand_index_pointing_up_medium-light_skin_tone": "👆🏼",
+416	    "backhand_index_pointing_up_medium_skin_tone": "👆🏽",
+417	    "bacon": "🥓",
+418	    "badger": "🦡",
+419	    "badminton": "🏸",
+420	    "bagel": "🥯",
+421	    "baggage_claim": "🛄",
+422	    "baguette_bread": "🥖",
+423	    "balance_scale": "⚖",
+424	    "bald": "🦲",
+425	    "bald_man": "👨\u200d🦲",
+426	    "bald_woman": "👩\u200d🦲",
+427	    "ballet_shoes": "🩰",
+428	    "balloon": "🎈",
+429	    "ballot_box_with_ballot": "🗳",
+430	    "ballot_box_with_check": "☑",
+431	    "banana": "🍌",
+432	    "banjo": "🪕",
+433	    "bank": "🏦",
+434	    "bar_chart": "📊",
+435	    "barber_pole": "💈",
+436	    "baseball": "⚾",
+437	    "basket": "🧺",
+438	    "basketball": "🏀",
+439	    "bat": "🦇",
+440	    "bathtub": "🛁",
+441	    "battery": "🔋",
+442	    "beach_with_umbrella": "🏖",
+443	    "beaming_face_with_smiling_eyes": "😁",
+444	    "bear_face": "🐻",
+445	    "bearded_person": "🧔",
+446	    "bearded_person_dark_skin_tone": "🧔🏿",
+447	    "bearded_person_light_skin_tone": "🧔🏻",
+448	    "bearded_person_medium-dark_skin_tone": "🧔🏾",
+449	    "bearded_person_medium-light_skin_tone": "🧔🏼",
+450	    "bearded_person_medium_skin_tone": "🧔🏽",
+451	    "beating_heart": "💓",
+452	    "bed": "🛏",
+453	    "beer_mug": "🍺",
+454	    "bell": "🔔",
+455	    "bell_with_slash": "🔕",
+456	    "bellhop_bell": "🛎",
+457	    "bento_box": "🍱",
+458	    "beverage_box": "🧃",
+459	    "bicycle": "🚲",
+460	    "bikini": "👙",
+461	    "billed_cap": "🧢",
+462	    "biohazard": "☣",
+463	    "bird": "🐦",
+464	    "birthday_cake": "🎂",
+465	    "black_circle": "⚫",
+466	    "black_flag": "🏴",
+467	    "black_heart": "🖤",
+468	    "black_large_square": "⬛",
+469	    "black_medium-small_square": "◾",
+470	    "black_medium_square": "◼",
+471	    "black_nib": "✒",
+472	    "black_small_square": "▪",
+473	    "black_square_button": "🔲",
+474	    "blond-haired_man": "👱\u200d♂️",
+475	    "blond-haired_man_dark_skin_tone": "👱🏿\u200d♂️",
+476	    "blond-haired_man_light_skin_tone": "👱🏻\u200d♂️",
+477	    "blond-haired_man_medium-dark_skin_tone": "👱🏾\u200d♂️",
+478	    "blond-haired_man_medium-light_skin_tone": "👱🏼\u200d♂️",
+479	    "blond-haired_man_medium_skin_tone": "👱🏽\u200d♂️",
+480	    "blond-haired_person": "👱",
+481	    "blond-haired_person_dark_skin_tone": "👱🏿",
+482	    "blond-haired_person_light_skin_tone": "👱🏻",
+483	    "blond-haired_person_medium-dark_skin_tone": "👱🏾",
+484	    "blond-haired_person_medium-light_skin_tone": "👱🏼",
+485	    "blond-haired_person_medium_skin_tone": "👱🏽",
+486	    "blond-haired_woman": "👱\u200d♀️",
+487	    "blond-haired_woman_dark_skin_tone": "👱🏿\u200d♀️",
+488	    "blond-haired_woman_light_skin_tone": "👱🏻\u200d♀️",
+489	    "blond-haired_woman_medium-dark_skin_tone": "👱🏾\u200d♀️",
+490	    "blond-haired_woman_medium-light_skin_tone": "👱🏼\u200d♀️",
+491	    "blond-haired_woman_medium_skin_tone": "👱🏽\u200d♀️",
+492	    "blossom": "🌼",
+493	    "blowfish": "🐡",
+494	    "blue_book": "📘",
+495	    "blue_circle": "🔵",
+496	    "blue_heart": "💙",
+497	    "blue_square": "🟦",
+498	    "boar": "🐗",
+499	    "bomb": "💣",
+500	    "bone": "🦴",
+501	    "bookmark": "🔖",
+502	    "bookmark_tabs": "📑",
+503	    "books": "📚",
+504	    "bottle_with_popping_cork": "🍾",
+505	    "bouquet": "💐",
+506	    "bow_and_arrow": "🏹",
+507	    "bowl_with_spoon": "🥣",
+508	    "bowling": "🎳",
+509	    "boxing_glove": "🥊",
+510	    "boy": "👦",
+511	    "boy_dark_skin_tone": "👦🏿",
+512	    "boy_light_skin_tone": "👦🏻",
+513	    "boy_medium-dark_skin_tone": "👦🏾",
+514	    "boy_medium-light_skin_tone": "👦🏼",
+515	    "boy_medium_skin_tone": "👦🏽",
+516	    "brain": "🧠",
+517	    "bread": "🍞",
+518	    "breast-feeding": "🤱",
+519	    "breast-feeding_dark_skin_tone": "🤱🏿",
+520	    "breast-feeding_light_skin_tone": "🤱🏻",
+521	    "breast-feeding_medium-dark_skin_tone": "🤱🏾",
+522	    "breast-feeding_medium-light_skin_tone": "🤱🏼",
+523	    "breast-feeding_medium_skin_tone": "🤱🏽",
+524	    "brick": "🧱",
+525	    "bride_with_veil": "👰",
+526	    "bride_with_veil_dark_skin_tone": "👰🏿",
+527	    "bride_with_veil_light_skin_tone": "👰🏻",
+528	    "bride_with_veil_medium-dark_skin_tone": "👰🏾",
+529	    "bride_with_veil_medium-light_skin_tone": "👰🏼",
+530	    "bride_with_veil_medium_skin_tone": "👰🏽",
+531	    "bridge_at_night": "🌉",
+532	    "briefcase": "💼",
+533	    "briefs": "🩲",
+534	    "bright_button": "🔆",
+535	    "broccoli": "🥦",
+536	    "broken_heart": "💔",
+537	    "broom": "🧹",
+538	    "brown_circle": "🟤",
+539	    "brown_heart": "🤎",
+540	    "brown_square": "🟫",
+541	    "bug": "🐛",
+542	    "building_construction": "🏗",
+543	    "bullet_train": "🚅",
+544	    "burrito": "🌯",
+545	    "bus": "🚌",
+546	    "bus_stop": "🚏",
+547	    "bust_in_silhouette": "👤",
+548	    "busts_in_silhouette": "👥",
+549	    "butter": "🧈",
+550	    "butterfly": "🦋",
+551	    "cactus": "🌵",
+552	    "calendar": "📆",
+553	    "call_me_hand": "🤙",
+554	    "call_me_hand_dark_skin_tone": "🤙🏿",
+555	    "call_me_hand_light_skin_tone": "🤙🏻",
+556	    "call_me_hand_medium-dark_skin_tone": "🤙🏾",
+557	    "call_me_hand_medium-light_skin_tone": "🤙🏼",
+558	    "call_me_hand_medium_skin_tone": "🤙🏽",
+559	    "camel": "🐫",
+560	    "camera": "📷",
+561	    "camera_with_flash": "📸",
+562	    "camping": "🏕",
+563	    "candle": "🕯",
+564	    "candy": "🍬",
+565	    "canned_food": "🥫",
+566	    "canoe": "🛶",
+567	    "card_file_box": "🗃",
+568	    "card_index": "📇",
+569	    "card_index_dividers": "🗂",
+570	    "carousel_horse": "🎠",
+571	    "carp_streamer": "🎏",
+572	    "carrot": "🥕",
+573	    "castle": "🏰",
+574	    "cat": "🐱",
+575	    "cat_face": "🐱",
+576	    "cat_face_with_tears_of_joy": "😹",
+577	    "cat_face_with_wry_smile": "😼",
+578	    "chains": "⛓",
+579	    "chair": "🪑",
+580	    "chart_decreasing": "📉",
+581	    "chart_increasing": "📈",
+582	    "chart_increasing_with_yen": "💹",
+583	    "cheese_wedge": "🧀",
+584	    "chequered_flag": "🏁",
+585	    "cherries": "🍒",
+586	    "cherry_blossom": "🌸",
+587	    "chess_pawn": "♟",
+588	    "chestnut": "🌰",
+589	    "chicken": "🐔",
+590	    "child": "🧒",
+591	    "child_dark_skin_tone": "🧒🏿",
+592	    "child_light_skin_tone": "🧒🏻",
+593	    "child_medium-dark_skin_tone": "🧒🏾",
+594	    "child_medium-light_skin_tone": "🧒🏼",
+595	    "child_medium_skin_tone": "🧒🏽",
+596	    "children_crossing": "🚸",
+597	    "chipmunk": "🐿",
+598	    "chocolate_bar": "🍫",
+599	    "chopsticks": "🥢",
+600	    "church": "⛪",
+601	    "cigarette": "🚬",
+602	    "cinema": "🎦",
+603	    "circled_m": "Ⓜ",
+604	    "circus_tent": "🎪",
+605	    "cityscape": "🏙",
+606	    "cityscape_at_dusk": "🌆",
+607	    "clamp": "🗜",
+608	    "clapper_board": "🎬",
+609	    "clapping_hands": "👏",
+610	    "clapping_hands_dark_skin_tone": "👏🏿",
+611	    "clapping_hands_light_skin_tone": "👏🏻",
+612	    "clapping_hands_medium-dark_skin_tone": "👏🏾",
+613	    "clapping_hands_medium-light_skin_tone": "👏🏼",
+614	    "clapping_hands_medium_skin_tone": "👏🏽",
+615	    "classical_building": "🏛",
+616	    "clinking_beer_mugs": "🍻",
+617	    "clinking_glasses": "🥂",
+618	    "clipboard": "📋",
+619	    "clockwise_vertical_arrows": "🔃",
+620	    "closed_book": "📕",
+621	    "closed_mailbox_with_lowered_flag": "📪",
+622	    "closed_mailbox_with_raised_flag": "📫",
+623	    "closed_umbrella": "🌂",
+624	    "cloud": "☁",
+625	    "cloud_with_lightning": "🌩",
+626	    "cloud_with_lightning_and_rain": "⛈",
+627	    "cloud_with_rain": "🌧",
+628	    "cloud_with_snow": "🌨",
+629	    "clown_face": "🤡",
+630	    "club_suit": "♣",
+631	    "clutch_bag": "👝",
+632	    "coat": "🧥",
+633	    "cocktail_glass": "🍸",
+634	    "coconut": "🥥",
+635	    "coffin": "⚰",
+636	    "cold_face": "🥶",
+637	    "collision": "💥",
+638	    "comet": "☄",
+639	    "compass": "🧭",
+640	    "computer_disk": "💽",
+641	    "computer_mouse": "🖱",
+642	    "confetti_ball": "🎊",
+643	    "confounded_face": "😖",
+644	    "confused_face": "😕",
+645	    "construction": "🚧",
+646	    "construction_worker": "👷",
+647	    "construction_worker_dark_skin_tone": "👷🏿",
+648	    "construction_worker_light_skin_tone": "👷🏻",
+649	    "construction_worker_medium-dark_skin_tone": "👷🏾",
+650	    "construction_worker_medium-light_skin_tone": "👷🏼",
+651	    "construction_worker_medium_skin_tone": "👷🏽",
+652	    "control_knobs": "🎛",
+653	    "convenience_store": "🏪",
+654	    "cooked_rice": "🍚",
+655	    "cookie": "🍪",
+656	    "cooking": "🍳",
+657	    "copyright": "©",
+658	    "couch_and_lamp": "🛋",
+659	    "counterclockwise_arrows_button": "🔄",
+660	    "couple_with_heart": "💑",
+661	    "couple_with_heart_man_man": "👨\u200d❤️\u200d👨",
+662	    "couple_with_heart_woman_man": "👩\u200d❤️\u200d👨",
+663	    "couple_with_heart_woman_woman": "👩\u200d❤️\u200d👩",
+664	    "cow": "🐮",
+665	    "cow_face": "🐮",
+666	    "cowboy_hat_face": "🤠",
+667	    "crab": "🦀",
+668	    "crayon": "🖍",
+669	    "credit_card": "💳",
+670	    "crescent_moon": "🌙",
+671	    "cricket": "🦗",
+672	    "cricket_game": "🏏",
+673	    "crocodile": "🐊",
+674	    "croissant": "🥐",
+675	    "cross_mark": "❌",
+676	    "cross_mark_button": "❎",
+677	    "crossed_fingers": "🤞",
+678	    "crossed_fingers_dark_skin_tone": "🤞🏿",
+679	    "crossed_fingers_light_skin_tone": "🤞🏻",
+680	    "crossed_fingers_medium-dark_skin_tone": "🤞🏾",
+681	    "crossed_fingers_medium-light_skin_tone": "🤞🏼",
+682	    "crossed_fingers_medium_skin_tone": "🤞🏽",
+683	    "crossed_flags": "🎌",
+684	    "crossed_swords": "⚔",
+685	    "crown": "👑",
+686	    "crying_cat_face": "😿",
+687	    "crying_face": "😢",
+688	    "crystal_ball": "🔮",
+689	    "cucumber": "🥒",
+690	    "cupcake": "🧁",
+691	    "cup_with_straw": "🥤",
+692	    "curling_stone": "🥌",
+693	    "curly_hair": "🦱",
+694	    "curly-haired_man": "👨\u200d🦱",
+695	    "curly-haired_woman": "👩\u200d🦱",
+696	    "curly_loop": "➰",
+697	    "currency_exchange": "💱",
+698	    "curry_rice": "🍛",
+699	    "custard": "🍮",
+700	    "customs": "🛃",
+701	    "cut_of_meat": "🥩",
+702	    "cyclone": "🌀",
+703	    "dagger": "🗡",
+704	    "dango": "🍡",
+705	    "dashing_away": "💨",
+706	    "deaf_person": "🧏",
+707	    "deciduous_tree": "🌳",
+708	    "deer": "🦌",
+709	    "delivery_truck": "🚚",
+710	    "department_store": "🏬",
+711	    "derelict_house": "🏚",
+712	    "desert": "🏜",
+713	    "desert_island": "🏝",
+714	    "desktop_computer": "🖥",
+715	    "detective": "🕵",
+716	    "detective_dark_skin_tone": "🕵🏿",
+717	    "detective_light_skin_tone": "🕵🏻",
+718	    "detective_medium-dark_skin_tone": "🕵🏾",
+719	    "detective_medium-light_skin_tone": "🕵🏼",
+720	    "detective_medium_skin_tone": "🕵🏽",
+721	    "diamond_suit": "♦",
+722	    "diamond_with_a_dot": "💠",
+723	    "dim_button": "🔅",
+724	    "direct_hit": "🎯",
+725	    "disappointed_face": "😞",
+726	    "diving_mask": "🤿",
+727	    "diya_lamp": "🪔",
+728	    "dizzy": "💫",
+729	    "dizzy_face": "😵",
+730	    "dna": "🧬",
+731	    "dog": "🐶",
+732	    "dog_face": "🐶",
+733	    "dollar_banknote": "💵",
+734	    "dolphin": "🐬",
+735	    "door": "🚪",
+736	    "dotted_six-pointed_star": "🔯",
+737	    "double_curly_loop": "➿",
+738	    "double_exclamation_mark": "‼",
+739	    "doughnut": "🍩",
+740	    "dove": "🕊",
+741	    "down-left_arrow": "↙",
+742	    "down-right_arrow": "↘",
+743	    "down_arrow": "⬇",
+744	    "downcast_face_with_sweat": "😓",
+745	    "downwards_button": "🔽",
+746	    "dragon": "🐉",
+747	    "dragon_face": "🐲",
+748	    "dress": "👗",
+749	    "drooling_face": "🤤",
+750	    "drop_of_blood": "🩸",
+751	    "droplet": "💧",
+752	    "drum": "🥁",
+753	    "duck": "🦆",
+754	    "dumpling": "🥟",
+755	    "dvd": "📀",
+756	    "e-mail": "📧",
+757	    "eagle": "🦅",
+758	    "ear": "👂",
+759	    "ear_dark_skin_tone": "👂🏿",
+760	    "ear_light_skin_tone": "👂🏻",
+761	    "ear_medium-dark_skin_tone": "👂🏾",
+762	    "ear_medium-light_skin_tone": "👂🏼",
+763	    "ear_medium_skin_tone": "👂🏽",
+764	    "ear_of_corn": "🌽",
+765	    "ear_with_hearing_aid": "🦻",
+766	    "egg": "🍳",
+767	    "eggplant": "🍆",
+768	    "eight-pointed_star": "✴",
+769	    "eight-spoked_asterisk": "✳",
+770	    "eight-thirty": "🕣",
+771	    "eight_o’clock": "🕗",
+772	    "eject_button": "⏏",
+773	    "electric_plug": "🔌",
+774	    "elephant": "🐘",
+775	    "eleven-thirty": "🕦",
+776	    "eleven_o’clock": "🕚",
+777	    "elf": "🧝",
+778	    "elf_dark_skin_tone": "🧝🏿",
+779	    "elf_light_skin_tone": "🧝🏻",
+780	    "elf_medium-dark_skin_tone": "🧝🏾",
+781	    "elf_medium-light_skin_tone": "🧝🏼",
+782	    "elf_medium_skin_tone": "🧝🏽",
+783	    "envelope": "✉",
+784	    "envelope_with_arrow": "📩",
+785	    "euro_banknote": "💶",
+786	    "evergreen_tree": "🌲",
+787	    "ewe": "🐑",
+788	    "exclamation_mark": "❗",
+789	    "exclamation_question_mark": "⁉",
+790	    "exploding_head": "🤯",
+791	    "expressionless_face": "😑",
+792	    "eye": "👁",
+793	    "eye_in_speech_bubble": "👁️\u200d🗨️",
+794	    "eyes": "👀",
+795	    "face_blowing_a_kiss": "😘",
+796	    "face_savoring_food": "😋",
+797	    "face_screaming_in_fear": "😱",
+798	    "face_vomiting": "🤮",
+799	    "face_with_hand_over_mouth": "🤭",
+800	    "face_with_head-bandage": "🤕",
+801	    "face_with_medical_mask": "😷",
+802	    "face_with_monocle": "🧐",
+803	    "face_with_open_mouth": "😮",
+804	    "face_with_raised_eyebrow": "🤨",
+805	    "face_with_rolling_eyes": "🙄",
+806	    "face_with_steam_from_nose": "😤",
+807	    "face_with_symbols_on_mouth": "🤬",
+808	    "face_with_tears_of_joy": "😂",
+809	    "face_with_thermometer": "🤒",
+810	    "face_with_tongue": "😛",
+811	    "face_without_mouth": "😶",
+812	    "factory": "🏭",
+813	    "fairy": "🧚",
+814	    "fairy_dark_skin_tone": "🧚🏿",
+815	    "fairy_light_skin_tone": "🧚🏻",
+816	    "fairy_medium-dark_skin_tone": "🧚🏾",
+817	    "fairy_medium-light_skin_tone": "🧚🏼",
+818	    "fairy_medium_skin_tone": "🧚🏽",
+819	    "falafel": "🧆",
+820	    "fallen_leaf": "🍂",
+821	    "family": "👪",
+822	    "family_man_boy": "👨\u200d👦",
+823	    "family_man_boy_boy": "👨\u200d👦\u200d👦",
+824	    "family_man_girl": "👨\u200d👧",
+825	    "family_man_girl_boy": "👨\u200d👧\u200d👦",
+826	    "family_man_girl_girl": "👨\u200d👧\u200d👧",
+827	    "family_man_man_boy": "👨\u200d👨\u200d👦",
+828	    "family_man_man_boy_boy": "👨\u200d👨\u200d👦\u200d👦",
+829	    "family_man_man_girl": "👨\u200d👨\u200d👧",
+830	    "family_man_man_girl_boy": "👨\u200d👨\u200d👧\u200d👦",
+831	    "family_man_man_girl_girl": "👨\u200d👨\u200d👧\u200d👧",
+832	    "family_man_woman_boy": "👨\u200d👩\u200d👦",
+833	    "family_man_woman_boy_boy": "👨\u200d👩\u200d👦\u200d👦",
+834	    "family_man_woman_girl": "👨\u200d👩\u200d👧",
+835	    "family_man_woman_girl_boy": "👨\u200d👩\u200d👧\u200d👦",
+836	    "family_man_woman_girl_girl": "👨\u200d👩\u200d👧\u200d👧",
+837	    "family_woman_boy": "👩\u200d👦",
+838	    "family_woman_boy_boy": "👩\u200d👦\u200d👦",
+839	    "family_woman_girl": "👩\u200d👧",
+840	    "family_woman_girl_boy": "👩\u200d👧\u200d👦",
+841	    "family_woman_girl_girl": "👩\u200d👧\u200d👧",
+842	    "family_woman_woman_boy": "👩\u200d👩\u200d👦",
+843	    "family_woman_woman_boy_boy": "👩\u200d👩\u200d👦\u200d👦",
+844	    "family_woman_woman_girl": "👩\u200d👩\u200d👧",
+845	    "family_woman_woman_girl_boy": "👩\u200d👩\u200d👧\u200d👦",
+846	    "family_woman_woman_girl_girl": "👩\u200d👩\u200d👧\u200d👧",
+847	    "fast-forward_button": "⏩",
+848	    "fast_down_button": "⏬",
+849	    "fast_reverse_button": "⏪",
+850	    "fast_up_button": "⏫",
+851	    "fax_machine": "📠",
+852	    "fearful_face": "😨",
+853	    "female_sign": "♀",
+854	    "ferris_wheel": "🎡",
+855	    "ferry": "⛴",
+856	    "field_hockey": "🏑",
+857	    "file_cabinet": "🗄",
+858	    "file_folder": "📁",
+859	    "film_frames": "🎞",
+860	    "film_projector": "📽",
+861	    "fire": "🔥",
+862	    "fire_extinguisher": "🧯",
+863	    "firecracker": "🧨",
+864	    "fire_engine": "🚒",
+865	    "fireworks": "🎆",
+866	    "first_quarter_moon": "🌓",
+867	    "first_quarter_moon_face": "🌛",
+868	    "fish": "🐟",
+869	    "fish_cake_with_swirl": "🍥",
+870	    "fishing_pole": "🎣",
+871	    "five-thirty": "🕠",
+872	    "five_o’clock": "🕔",
+873	    "flag_in_hole": "⛳",
+874	    "flamingo": "🦩",
+875	    "flashlight": "🔦",
+876	    "flat_shoe": "🥿",
+877	    "fleur-de-lis": "⚜",
+878	    "flexed_biceps": "💪",
+879	    "flexed_biceps_dark_skin_tone": "💪🏿",
+880	    "flexed_biceps_light_skin_tone": "💪🏻",
+881	    "flexed_biceps_medium-dark_skin_tone": "💪🏾",
+882	    "flexed_biceps_medium-light_skin_tone": "💪🏼",
+883	    "flexed_biceps_medium_skin_tone": "💪🏽",
+884	    "floppy_disk": "💾",
+885	    "flower_playing_cards": "🎴",
+886	    "flushed_face": "😳",
+887	    "flying_disc": "🥏",
+888	    "flying_saucer": "🛸",
+889	    "fog": "🌫",
+890	    "foggy": "🌁",
+891	    "folded_hands": "🙏",
+892	    "folded_hands_dark_skin_tone": "🙏🏿",
+893	    "folded_hands_light_skin_tone": "🙏🏻",
+894	    "folded_hands_medium-dark_skin_tone": "🙏🏾",
+895	    "folded_hands_medium-light_skin_tone": "🙏🏼",
+896	    "folded_hands_medium_skin_tone": "🙏🏽",
+897	    "foot": "🦶",
+898	    "footprints": "👣",
+899	    "fork_and_knife": "🍴",
+900	    "fork_and_knife_with_plate": "🍽",
+901	    "fortune_cookie": "🥠",
+902	    "fountain": "⛲",
+903	    "fountain_pen": "🖋",
+904	    "four-thirty": "🕟",
+905	    "four_leaf_clover": "🍀",
+906	    "four_o’clock": "🕓",
+907	    "fox_face": "🦊",
+908	    "framed_picture": "🖼",
+909	    "french_fries": "🍟",
+910	    "fried_shrimp": "🍤",
+911	    "frog_face": "🐸",
+912	    "front-facing_baby_chick": "🐥",
+913	    "frowning_face": "☹",
+914	    "frowning_face_with_open_mouth": "😦",
+915	    "fuel_pump": "⛽",
+916	    "full_moon": "🌕",
+917	    "full_moon_face": "🌝",
+918	    "funeral_urn": "⚱",
+919	    "game_die": "🎲",
+920	    "garlic": "🧄",
+921	    "gear": "⚙",
+922	    "gem_stone": "💎",
+923	    "genie": "🧞",
+924	    "ghost": "👻",
+925	    "giraffe": "🦒",
+926	    "girl": "👧",
+927	    "girl_dark_skin_tone": "👧🏿",
+928	    "girl_light_skin_tone": "👧🏻",
+929	    "girl_medium-dark_skin_tone": "👧🏾",
+930	    "girl_medium-light_skin_tone": "👧🏼",
+931	    "girl_medium_skin_tone": "👧🏽",
+932	    "glass_of_milk": "🥛",
+933	    "glasses": "👓",
+934	    "globe_showing_americas": "🌎",
+935	    "globe_showing_asia-australia": "🌏",
+936	    "globe_showing_europe-africa": "🌍",
+937	    "globe_with_meridians": "🌐",
+938	    "gloves": "🧤",
+939	    "glowing_star": "🌟",
+940	    "goal_net": "🥅",
+941	    "goat": "🐐",
+942	    "goblin": "👺",
+943	    "goggles": "🥽",
+944	    "gorilla": "🦍",
+945	    "graduation_cap": "🎓",
+946	    "grapes": "🍇",
+947	    "green_apple": "🍏",
+948	    "green_book": "📗",
+949	    "green_circle": "🟢",
+950	    "green_heart": "💚",
+951	    "green_salad": "🥗",
+952	    "green_square": "🟩",
+953	    "grimacing_face": "😬",
+954	    "grinning_cat_face": "😺",
+955	    "grinning_cat_face_with_smiling_eyes": "😸",
+956	    "grinning_face": "😀",
+957	    "grinning_face_with_big_eyes": "😃",
+958	    "grinning_face_with_smiling_eyes": "😄",
+959	    "grinning_face_with_sweat": "😅",
+960	    "grinning_squinting_face": "😆",
+961	    "growing_heart": "💗",
+962	    "guard": "💂",
+963	    "guard_dark_skin_tone": "💂🏿",
+964	    "guard_light_skin_tone": "💂🏻",
+965	    "guard_medium-dark_skin_tone": "💂🏾",
+966	    "guard_medium-light_skin_tone": "💂🏼",
+967	    "guard_medium_skin_tone": "💂🏽",
+968	    "guide_dog": "🦮",
+969	    "guitar": "🎸",
+970	    "hamburger": "🍔",
+971	    "hammer": "🔨",
+972	    "hammer_and_pick": "⚒",
+973	    "hammer_and_wrench": "🛠",
+974	    "hamster_face": "🐹",
+975	    "hand_with_fingers_splayed": "🖐",
+976	    "hand_with_fingers_splayed_dark_skin_tone": "🖐🏿",
+977	    "hand_with_fingers_splayed_light_skin_tone": "🖐🏻",
+978	    "hand_with_fingers_splayed_medium-dark_skin_tone": "🖐🏾",
+979	    "hand_with_fingers_splayed_medium-light_skin_tone": "🖐🏼",
+980	    "hand_with_fingers_splayed_medium_skin_tone": "🖐🏽",
+981	    "handbag": "👜",
+982	    "handshake": "🤝",
+983	    "hatching_chick": "🐣",
+984	    "headphone": "🎧",
+985	    "hear-no-evil_monkey": "🙉",
+986	    "heart_decoration": "💟",
+987	    "heart_suit": "♥",
+988	    "heart_with_arrow": "💘",
+989	    "heart_with_ribbon": "💝",
+990	    "heavy_check_mark": "✔",
+991	    "heavy_division_sign": "➗",
+992	    "heavy_dollar_sign": "💲",
+993	    "heavy_heart_exclamation": "❣",
+994	    "heavy_large_circle": "⭕",
+995	    "heavy_minus_sign": "➖",
+996	    "heavy_multiplication_x": "✖",
+997	    "heavy_plus_sign": "➕",
+998	    "hedgehog": "🦔",
+999	    "helicopter": "🚁",
+1000	    "herb": "🌿",
+1001	    "hibiscus": "🌺",
+1002	    "high-heeled_shoe": "👠",
+1003	    "high-speed_train": "🚄",
+1004	    "high_voltage": "⚡",
+1005	    "hiking_boot": "🥾",
+1006	    "hindu_temple": "🛕",
+1007	    "hippopotamus": "🦛",
+1008	    "hole": "🕳",
+1009	    "honey_pot": "🍯",
+1010	    "honeybee": "🐝",
+1011	    "horizontal_traffic_light": "🚥",
+1012	    "horse": "🐴",
+1013	    "horse_face": "🐴",
+1014	    "horse_racing": "🏇",
+1015	    "horse_racing_dark_skin_tone": "🏇🏿",
+1016	    "horse_racing_light_skin_tone": "🏇🏻",
+1017	    "horse_racing_medium-dark_skin_tone": "🏇🏾",
+1018	    "horse_racing_medium-light_skin_tone": "🏇🏼",
+1019	    "horse_racing_medium_skin_tone": "🏇🏽",
+1020	    "hospital": "🏥",
+1021	    "hot_beverage": "☕",
+1022	    "hot_dog": "🌭",
+1023	    "hot_face": "🥵",
+1024	    "hot_pepper": "🌶",
+1025	    "hot_springs": "♨",
+1026	    "hotel": "🏨",
+1027	    "hourglass_done": "⌛",
+1028	    "hourglass_not_done": "⏳",
+1029	    "house": "🏠",
+1030	    "house_with_garden": "🏡",
+1031	    "houses": "🏘",
+1032	    "hugging_face": "🤗",
+1033	    "hundred_points": "💯",
+1034	    "hushed_face": "😯",
+1035	    "ice": "🧊",
+1036	    "ice_cream": "🍨",
+1037	    "ice_hockey": "🏒",
+1038	    "ice_skate": "⛸",
+1039	    "inbox_tray": "📥",
+1040	    "incoming_envelope": "📨",
+1041	    "index_pointing_up": "☝",
+1042	    "index_pointing_up_dark_skin_tone": "☝🏿",
+1043	    "index_pointing_up_light_skin_tone": "☝🏻",
+1044	    "index_pointing_up_medium-dark_skin_tone": "☝🏾",
+1045	    "index_pointing_up_medium-light_skin_tone": "☝🏼",
+1046	    "index_pointing_up_medium_skin_tone": "☝🏽",
+1047	    "infinity": "♾",
+1048	    "information": "ℹ",
+1049	    "input_latin_letters": "🔤",
+1050	    "input_latin_lowercase": "🔡",
+1051	    "input_latin_uppercase": "🔠",
+1052	    "input_numbers": "🔢",
+1053	    "input_symbols": "🔣",
+1054	    "jack-o-lantern": "🎃",
+1055	    "jeans": "👖",
+1056	    "jigsaw": "🧩",
+1057	    "joker": "🃏",
+1058	    "joystick": "🕹",
+1059	    "kaaba": "🕋",
+1060	    "kangaroo": "🦘",
+1061	    "key": "🔑",
+1062	    "keyboard": "⌨",
+1063	    "keycap_#": "#️⃣",
+1064	    "keycap_*": "*️⃣",
+1065	    "keycap_0": "0️⃣",
+1066	    "keycap_1": "1️⃣",
+1067	    "keycap_10": "🔟",
+1068	    "keycap_2": "2️⃣",
+1069	    "keycap_3": "3️⃣",
+1070	    "keycap_4": "4️⃣",
+1071	    "keycap_5": "5️⃣",
+1072	    "keycap_6": "6️⃣",
+1073	    "keycap_7": "7️⃣",
+1074	    "keycap_8": "8️⃣",
+1075	    "keycap_9": "9️⃣",
+1076	    "kick_scooter": "🛴",
+1077	    "kimono": "👘",
+1078	    "kiss": "💋",
+1079	    "kiss_man_man": "👨\u200d❤️\u200d💋\u200d👨",
+1080	    "kiss_mark": "💋",
+1081	    "kiss_woman_man": "👩\u200d❤️\u200d💋\u200d👨",
+1082	    "kiss_woman_woman": "👩\u200d❤️\u200d💋\u200d👩",
+1083	    "kissing_cat_face": "😽",
+1084	    "kissing_face": "😗",
+1085	    "kissing_face_with_closed_eyes": "😚",
+1086	    "kissing_face_with_smiling_eyes": "😙",
+1087	    "kitchen_knife": "🔪",
+1088	    "kite": "🪁",
+1089	    "kiwi_fruit": "🥝",
+1090	    "koala": "🐨",
+1091	    "lab_coat": "🥼",
+1092	    "label": "🏷",
+1093	    "lacrosse": "🥍",
+1094	    "lady_beetle": "🐞",
+1095	    "laptop_computer": "💻",
+1096	    "large_blue_diamond": "🔷",
+1097	    "large_orange_diamond": "🔶",
+1098	    "last_quarter_moon": "🌗",
+1099	    "last_quarter_moon_face": "🌜",
+1100	    "last_track_button": "⏮",
+1101	    "latin_cross": "✝",
+1102	    "leaf_fluttering_in_wind": "🍃",
+1103	    "leafy_green": "🥬",
+1104	    "ledger": "📒",
+1105	    "left-facing_fist": "🤛",
+1106	    "left-facing_fist_dark_skin_tone": "🤛🏿",
+1107	    "left-facing_fist_light_skin_tone": "🤛🏻",
+1108	    "left-facing_fist_medium-dark_skin_tone": "🤛🏾",
+1109	    "left-facing_fist_medium-light_skin_tone": "🤛🏼",
+1110	    "left-facing_fist_medium_skin_tone": "🤛🏽",
+1111	    "left-right_arrow": "↔",
+1112	    "left_arrow": "⬅",
+1113	    "left_arrow_curving_right": "↪",
+1114	    "left_luggage": "🛅",
+1115	    "left_speech_bubble": "🗨",
+1116	    "leg": "🦵",
+1117	    "lemon": "🍋",
+1118	    "leopard": "🐆",
+1119	    "level_slider": "🎚",
+1120	    "light_bulb": "💡",
+1121	    "light_rail": "🚈",
+1122	    "link": "🔗",
+1123	    "linked_paperclips": "🖇",
+1124	    "lion_face": "🦁",
+1125	    "lipstick": "💄",
+1126	    "litter_in_bin_sign": "🚮",
+1127	    "lizard": "🦎",
+1128	    "llama": "🦙",
+1129	    "lobster": "🦞",
+1130	    "locked": "🔒",
+1131	    "locked_with_key": "🔐",
+1132	    "locked_with_pen": "🔏",
+1133	    "locomotive": "🚂",
+1134	    "lollipop": "🍭",
+1135	    "lotion_bottle": "🧴",
+1136	    "loudly_crying_face": "😭",
+1137	    "loudspeaker": "📢",
+1138	    "love-you_gesture": "🤟",
+1139	    "love-you_gesture_dark_skin_tone": "🤟🏿",
+1140	    "love-you_gesture_light_skin_tone": "🤟🏻",
+1141	    "love-you_gesture_medium-dark_skin_tone": "🤟🏾",
+1142	    "love-you_gesture_medium-light_skin_tone": "🤟🏼",
+1143	    "love-you_gesture_medium_skin_tone": "🤟🏽",
+1144	    "love_hotel": "🏩",
+1145	    "love_letter": "💌",
+1146	    "luggage": "🧳",
+1147	    "lying_face": "🤥",
+1148	    "mage": "🧙",
+1149	    "mage_dark_skin_tone": "🧙🏿",
+1150	    "mage_light_skin_tone": "🧙🏻",
+1151	    "mage_medium-dark_skin_tone": "🧙🏾",
+1152	    "mage_medium-light_skin_tone": "🧙🏼",
+1153	    "mage_medium_skin_tone": "🧙🏽",
+1154	    "magnet": "🧲",
+1155	    "magnifying_glass_tilted_left": "🔍",
+1156	    "magnifying_glass_tilted_right": "🔎",
+1157	    "mahjong_red_dragon": "🀄",
+1158	    "male_sign": "♂",
+1159	    "man": "👨",
+1160	    "man_and_woman_holding_hands": "👫",
+1161	    "man_artist": "👨\u200d🎨",
+1162	    "man_artist_dark_skin_tone": "👨🏿\u200d🎨",
+1163	    "man_artist_light_skin_tone": "👨🏻\u200d🎨",
+1164	    "man_artist_medium-dark_skin_tone": "👨🏾\u200d🎨",
+1165	    "man_artist_medium-light_skin_tone": "👨🏼\u200d🎨",
+1166	    "man_artist_medium_skin_tone": "👨🏽\u200d🎨",
+1167	    "man_astronaut": "👨\u200d🚀",
+1168	    "man_astronaut_dark_skin_tone": "👨🏿\u200d🚀",
+1169	    "man_astronaut_light_skin_tone": "👨🏻\u200d🚀",
+1170	    "man_astronaut_medium-dark_skin_tone": "👨🏾\u200d🚀",
+1171	    "man_astronaut_medium-light_skin_tone": "👨🏼\u200d🚀",
+1172	    "man_astronaut_medium_skin_tone": "👨🏽\u200d🚀",
+1173	    "man_biking": "🚴\u200d♂️",
+1174	    "man_biking_dark_skin_tone": "🚴🏿\u200d♂️",
+1175	    "man_biking_light_skin_tone": "🚴🏻\u200d♂️",
+1176	    "man_biking_medium-dark_skin_tone": "🚴🏾\u200d♂️",
+1177	    "man_biking_medium-light_skin_tone": "🚴🏼\u200d♂️",
+1178	    "man_biking_medium_skin_tone": "🚴🏽\u200d♂️",
+1179	    "man_bouncing_ball": "⛹️\u200d♂️",
+1180	    "man_bouncing_ball_dark_skin_tone": "⛹🏿\u200d♂️",
+1181	    "man_bouncing_ball_light_skin_tone": "⛹🏻\u200d♂️",
+1182	    "man_bouncing_ball_medium-dark_skin_tone": "⛹🏾\u200d♂️",
+1183	    "man_bouncing_ball_medium-light_skin_tone": "⛹🏼\u200d♂️",
+1184	    "man_bouncing_ball_medium_skin_tone": "⛹🏽\u200d♂️",
+1185	    "man_bowing": "🙇\u200d♂️",
+1186	    "man_bowing_dark_skin_tone": "🙇🏿\u200d♂️",
+1187	    "man_bowing_light_skin_tone": "🙇🏻\u200d♂️",
+1188	    "man_bowing_medium-dark_skin_tone": "🙇🏾\u200d♂️",
+1189	    "man_bowing_medium-light_skin_tone": "🙇🏼\u200d♂️",
+1190	    "man_bowing_medium_skin_tone": "🙇🏽\u200d♂️",
+1191	    "man_cartwheeling": "🤸\u200d♂️",
+1192	    "man_cartwheeling_dark_skin_tone": "🤸🏿\u200d♂️",
+1193	    "man_cartwheeling_light_skin_tone": "🤸🏻\u200d♂️",
+1194	    "man_cartwheeling_medium-dark_skin_tone": "🤸🏾\u200d♂️",
+1195	    "man_cartwheeling_medium-light_skin_tone": "🤸🏼\u200d♂️",
+1196	    "man_cartwheeling_medium_skin_tone": "🤸🏽\u200d♂️",
+1197	    "man_climbing": "🧗\u200d♂️",
+1198	    "man_climbing_dark_skin_tone": "🧗🏿\u200d♂️",
+1199	    "man_climbing_light_skin_tone": "🧗🏻\u200d♂️",
+1200	    "man_climbing_medium-dark_skin_tone": "🧗🏾\u200d♂️",
+1201	    "man_climbing_medium-light_skin_tone": "🧗🏼\u200d♂️",
+1202	    "man_climbing_medium_skin_tone": "🧗🏽\u200d♂️",
+1203	    "man_construction_worker": "👷\u200d♂️",
+1204	    "man_construction_worker_dark_skin_tone": "👷🏿\u200d♂️",
+1205	    "man_construction_worker_light_skin_tone": "👷🏻\u200d♂️",
+1206	    "man_construction_worker_medium-dark_skin_tone": "👷🏾\u200d♂️",
+1207	    "man_construction_worker_medium-light_skin_tone": "👷🏼\u200d♂️",
+1208	    "man_construction_worker_medium_skin_tone": "👷🏽\u200d♂️",
+1209	    "man_cook": "👨\u200d🍳",
+1210	    "man_cook_dark_skin_tone": "👨🏿\u200d🍳",
+1211	    "man_cook_light_skin_tone": "👨🏻\u200d🍳",
+1212	    "man_cook_medium-dark_skin_tone": "👨🏾\u200d🍳",
+1213	    "man_cook_medium-light_skin_tone": "👨🏼\u200d🍳",
+1214	    "man_cook_medium_skin_tone": "👨🏽\u200d🍳",
+1215	    "man_dancing": "🕺",
+1216	    "man_dancing_dark_skin_tone": "🕺🏿",
+1217	    "man_dancing_light_skin_tone": "🕺🏻",
+1218	    "man_dancing_medium-dark_skin_tone": "🕺🏾",
+1219	    "man_dancing_medium-light_skin_tone": "🕺🏼",
+1220	    "man_dancing_medium_skin_tone": "🕺🏽",
+1221	    "man_dark_skin_tone": "👨🏿",
+1222	    "man_detective": "🕵️\u200d♂️",
+1223	    "man_detective_dark_skin_tone": "🕵🏿\u200d♂️",
+1224	    "man_detective_light_skin_tone": "🕵🏻\u200d♂️",
+1225	    "man_detective_medium-dark_skin_tone": "🕵🏾\u200d♂️",
+1226	    "man_detective_medium-light_skin_tone": "🕵🏼\u200d♂️",
+1227	    "man_detective_medium_skin_tone": "🕵🏽\u200d♂️",
+1228	    "man_elf": "🧝\u200d♂️",
+1229	    "man_elf_dark_skin_tone": "🧝🏿\u200d♂️",
+1230	    "man_elf_light_skin_tone": "🧝🏻\u200d♂️",
+1231	    "man_elf_medium-dark_skin_tone": "🧝🏾\u200d♂️",
+1232	    "man_elf_medium-light_skin_tone": "🧝🏼\u200d♂️",
+1233	    "man_elf_medium_skin_tone": "🧝🏽\u200d♂️",
+1234	    "man_facepalming": "🤦\u200d♂️",
+1235	    "man_facepalming_dark_skin_tone": "🤦🏿\u200d♂️",
+1236	    "man_facepalming_light_skin_tone": "🤦🏻\u200d♂️",
+1237	    "man_facepalming_medium-dark_skin_tone": "🤦🏾\u200d♂️",
+1238	    "man_facepalming_medium-light_skin_tone": "🤦🏼\u200d♂️",
+1239	    "man_facepalming_medium_skin_tone": "🤦🏽\u200d♂️",
+1240	    "man_factory_worker": "👨\u200d🏭",
+1241	    "man_factory_worker_dark_skin_tone": "👨🏿\u200d🏭",
+1242	    "man_factory_worker_light_skin_tone": "👨🏻\u200d🏭",
+1243	    "man_factory_worker_medium-dark_skin_tone": "👨🏾\u200d🏭",
+1244	    "man_factory_worker_medium-light_skin_tone": "👨🏼\u200d🏭",
+1245	    "man_factory_worker_medium_skin_tone": "👨🏽\u200d🏭",
+1246	    "man_fairy": "🧚\u200d♂️",
+1247	    "man_fairy_dark_skin_tone": "🧚🏿\u200d♂️",
+1248	    "man_fairy_light_skin_tone": "🧚🏻\u200d♂️",
+1249	    "man_fairy_medium-dark_skin_tone": "🧚🏾\u200d♂️",
+1250	    "man_fairy_medium-light_skin_tone": "🧚🏼\u200d♂️",
+1251	    "man_fairy_medium_skin_tone": "🧚🏽\u200d♂️",
+1252	    "man_farmer": "👨\u200d🌾",
+1253	    "man_farmer_dark_skin_tone": "👨🏿\u200d🌾",
+1254	    "man_farmer_light_skin_tone": "👨🏻\u200d🌾",
+1255	    "man_farmer_medium-dark_skin_tone": "👨🏾\u200d🌾",
+1256	    "man_farmer_medium-light_skin_tone": "👨🏼\u200d🌾",
+1257	    "man_farmer_medium_skin_tone": "👨🏽\u200d🌾",
+1258	    "man_firefighter": "👨\u200d🚒",
+1259	    "man_firefighter_dark_skin_tone": "👨🏿\u200d🚒",
+1260	    "man_firefighter_light_skin_tone": "👨🏻\u200d🚒",
+1261	    "man_firefighter_medium-dark_skin_tone": "👨🏾\u200d🚒",
+1262	    "man_firefighter_medium-light_skin_tone": "👨🏼\u200d🚒",
+1263	    "man_firefighter_medium_skin_tone": "👨🏽\u200d🚒",
+1264	    "man_frowning": "🙍\u200d♂️",
+1265	    "man_frowning_dark_skin_tone": "🙍🏿\u200d♂️",
+1266	    "man_frowning_light_skin_tone": "🙍🏻\u200d♂️",
+1267	    "man_frowning_medium-dark_skin_tone": "🙍🏾\u200d♂️",
+1268	    "man_frowning_medium-light_skin_tone": "🙍🏼\u200d♂️",
+1269	    "man_frowning_medium_skin_tone": "🙍🏽\u200d♂️",
+1270	    "man_genie": "🧞\u200d♂️",
+1271	    "man_gesturing_no": "🙅\u200d♂️",
+1272	    "man_gesturing_no_dark_skin_tone": "🙅🏿\u200d♂️",
+1273	    "man_gesturing_no_light_skin_tone": "🙅🏻\u200d♂️",
+1274	    "man_gesturing_no_medium-dark_skin_tone": "🙅🏾\u200d♂️",
+1275	    "man_gesturing_no_medium-light_skin_tone": "🙅🏼\u200d♂️",
+1276	    "man_gesturing_no_medium_skin_tone": "🙅🏽\u200d♂️",
+1277	    "man_gesturing_ok": "🙆\u200d♂️",
+1278	    "man_gesturing_ok_dark_skin_tone": "🙆🏿\u200d♂️",
+1279	    "man_gesturing_ok_light_skin_tone": "🙆🏻\u200d♂️",
+1280	    "man_gesturing_ok_medium-dark_skin_tone": "🙆🏾\u200d♂️",
+1281	    "man_gesturing_ok_medium-light_skin_tone": "🙆🏼\u200d♂️",
+1282	    "man_gesturing_ok_medium_skin_tone": "🙆🏽\u200d♂️",
+1283	    "man_getting_haircut": "💇\u200d♂️",
+1284	    "man_getting_haircut_dark_skin_tone": "💇🏿\u200d♂️",
+1285	    "man_getting_haircut_light_skin_tone": "💇🏻\u200d♂️",
+1286	    "man_getting_haircut_medium-dark_skin_tone": "💇🏾\u200d♂️",
+1287	    "man_getting_haircut_medium-light_skin_tone": "💇🏼\u200d♂️",
+1288	    "man_getting_haircut_medium_skin_tone": "💇🏽\u200d♂️",
+1289	    "man_getting_massage": "💆\u200d♂️",
+1290	    "man_getting_massage_dark_skin_tone": "💆🏿\u200d♂️",
+1291	    "man_getting_massage_light_skin_tone": "💆🏻\u200d♂️",
+1292	    "man_getting_massage_medium-dark_skin_tone": "💆🏾\u200d♂️",
+1293	    "man_getting_massage_medium-light_skin_tone": "💆🏼\u200d♂️",
+1294	    "man_getting_massage_medium_skin_tone": "💆🏽\u200d♂️",
+1295	    "man_golfing": "🏌️\u200d♂️",
+1296	    "man_golfing_dark_skin_tone": "🏌🏿\u200d♂️",
+1297	    "man_golfing_light_skin_tone": "🏌🏻\u200d♂️",
+1298	    "man_golfing_medium-dark_skin_tone": "🏌🏾\u200d♂️",
+1299	    "man_golfing_medium-light_skin_tone": "🏌🏼\u200d♂️",
+1300	    "man_golfing_medium_skin_tone": "🏌🏽\u200d♂️",
+1301	    "man_guard": "💂\u200d♂️",
+1302	    "man_guard_dark_skin_tone": "💂🏿\u200d♂️",
+1303	    "man_guard_light_skin_tone": "💂🏻\u200d♂️",
+1304	    "man_guard_medium-dark_skin_tone": "💂🏾\u200d♂️",
+1305	    "man_guard_medium-light_skin_tone": "💂🏼\u200d♂️",
+1306	    "man_guard_medium_skin_tone": "💂🏽\u200d♂️",
+1307	    "man_health_worker": "👨\u200d⚕️",
+1308	    "man_health_worker_dark_skin_tone": "👨🏿\u200d⚕️",
+1309	    "man_health_worker_light_skin_tone": "👨🏻\u200d⚕️",
+1310	    "man_health_worker_medium-dark_skin_tone": "👨🏾\u200d⚕️",
+1311	    "man_health_worker_medium-light_skin_tone": "👨🏼\u200d⚕️",
+1312	    "man_health_worker_medium_skin_tone": "👨🏽\u200d⚕️",
+1313	    "man_in_lotus_position": "🧘\u200d♂️",
+1314	    "man_in_lotus_position_dark_skin_tone": "🧘🏿\u200d♂️",
+1315	    "man_in_lotus_position_light_skin_tone": "🧘🏻\u200d♂️",
+1316	    "man_in_lotus_position_medium-dark_skin_tone": "🧘🏾\u200d♂️",
+1317	    "man_in_lotus_position_medium-light_skin_tone": "🧘🏼\u200d♂️",
+1318	    "man_in_lotus_position_medium_skin_tone": "🧘🏽\u200d♂️",
+1319	    "man_in_manual_wheelchair": "👨\u200d🦽",
+1320	    "man_in_motorized_wheelchair": "👨\u200d🦼",
+1321	    "man_in_steamy_room": "🧖\u200d♂️",
+1322	    "man_in_steamy_room_dark_skin_tone": "🧖🏿\u200d♂️",
+1323	    "man_in_steamy_room_light_skin_tone": "🧖🏻\u200d♂️",
+1324	    "man_in_steamy_room_medium-dark_skin_tone": "🧖🏾\u200d♂️",
+1325	    "man_in_steamy_room_medium-light_skin_tone": "🧖🏼\u200d♂️",
+1326	    "man_in_steamy_room_medium_skin_tone": "🧖🏽\u200d♂️",
+1327	    "man_in_suit_levitating": "🕴",
+1328	    "man_in_suit_levitating_dark_skin_tone": "🕴🏿",
+1329	    "man_in_suit_levitating_light_skin_tone": "🕴🏻",
+1330	    "man_in_suit_levitating_medium-dark_skin_tone": "🕴🏾",
+1331	    "man_in_suit_levitating_medium-light_skin_tone": "🕴🏼",
+1332	    "man_in_suit_levitating_medium_skin_tone": "🕴🏽",
+1333	    "man_in_tuxedo": "🤵",
+1334	    "man_in_tuxedo_dark_skin_tone": "🤵🏿",
+1335	    "man_in_tuxedo_light_skin_tone": "🤵🏻",
+1336	    "man_in_tuxedo_medium-dark_skin_tone": "🤵🏾",
+1337	    "man_in_tuxedo_medium-light_skin_tone": "🤵🏼",
+1338	    "man_in_tuxedo_medium_skin_tone": "🤵🏽",
+1339	    "man_judge": "👨\u200d⚖️",
+1340	    "man_judge_dark_skin_tone": "👨🏿\u200d⚖️",
+1341	    "man_judge_light_skin_tone": "👨🏻\u200d⚖️",
+1342	    "man_judge_medium-dark_skin_tone": "👨🏾\u200d⚖️",
+1343	    "man_judge_medium-light_skin_tone": "👨🏼\u200d⚖️",
+1344	    "man_judge_medium_skin_tone": "👨🏽\u200d⚖️",
+1345	    "man_juggling": "🤹\u200d♂️",
+1346	    "man_juggling_dark_skin_tone": "🤹🏿\u200d♂️",
+1347	    "man_juggling_light_skin_tone": "🤹🏻\u200d♂️",
+1348	    "man_juggling_medium-dark_skin_tone": "🤹🏾\u200d♂️",
+1349	    "man_juggling_medium-light_skin_tone": "🤹🏼\u200d♂️",
+1350	    "man_juggling_medium_skin_tone": "🤹🏽\u200d♂️",
+1351	    "man_lifting_weights": "🏋️\u200d♂️",
+1352	    "man_lifting_weights_dark_skin_tone": "🏋🏿\u200d♂️",
+1353	    "man_lifting_weights_light_skin_tone": "🏋🏻\u200d♂️",
+1354	    "man_lifting_weights_medium-dark_skin_tone": "🏋🏾\u200d♂️",
+1355	    "man_lifting_weights_medium-light_skin_tone": "🏋🏼\u200d♂️",
+1356	    "man_lifting_weights_medium_skin_tone": "🏋🏽\u200d♂️",
+1357	    "man_light_skin_tone": "👨🏻",
+1358	    "man_mage": "🧙\u200d♂️",
+1359	    "man_mage_dark_skin_tone": "🧙🏿\u200d♂️",
+1360	    "man_mage_light_skin_tone": "🧙🏻\u200d♂️",
+1361	    "man_mage_medium-dark_skin_tone": "🧙🏾\u200d♂️",
+1362	    "man_mage_medium-light_skin_tone": "🧙🏼\u200d♂️",
+1363	    "man_mage_medium_skin_tone": "🧙🏽\u200d♂️",
+1364	    "man_mechanic": "👨\u200d🔧",
+1365	    "man_mechanic_dark_skin_tone": "👨🏿\u200d🔧",
+1366	    "man_mechanic_light_skin_tone": "👨🏻\u200d🔧",
+1367	    "man_mechanic_medium-dark_skin_tone": "👨🏾\u200d🔧",
+1368	    "man_mechanic_medium-light_skin_tone": "👨🏼\u200d🔧",
+1369	    "man_mechanic_medium_skin_tone": "👨🏽\u200d🔧",
+1370	    "man_medium-dark_skin_tone": "👨🏾",
+1371	    "man_medium-light_skin_tone": "👨🏼",
+1372	    "man_medium_skin_tone": "👨🏽",
+1373	    "man_mountain_biking": "🚵\u200d♂️",
+1374	    "man_mountain_biking_dark_skin_tone": "🚵🏿\u200d♂️",
+1375	    "man_mountain_biking_light_skin_tone": "🚵🏻\u200d♂️",
+1376	    "man_mountain_biking_medium-dark_skin_tone": "🚵🏾\u200d♂️",
+1377	    "man_mountain_biking_medium-light_skin_tone": "🚵🏼\u200d♂️",
+1378	    "man_mountain_biking_medium_skin_tone": "🚵🏽\u200d♂️",
+1379	    "man_office_worker": "👨\u200d💼",
+1380	    "man_office_worker_dark_skin_tone": "👨🏿\u200d💼",
+1381	    "man_office_worker_light_skin_tone": "👨🏻\u200d💼",
+1382	    "man_office_worker_medium-dark_skin_tone": "👨🏾\u200d💼",
+1383	    "man_office_worker_medium-light_skin_tone": "👨🏼\u200d💼",
+1384	    "man_office_worker_medium_skin_tone": "👨🏽\u200d💼",
+1385	    "man_pilot": "👨\u200d✈️",
+1386	    "man_pilot_dark_skin_tone": "👨🏿\u200d✈️",
+1387	    "man_pilot_light_skin_tone": "👨🏻\u200d✈️",
+1388	    "man_pilot_medium-dark_skin_tone": "👨🏾\u200d✈️",
+1389	    "man_pilot_medium-light_skin_tone": "👨🏼\u200d✈️",
+1390	    "man_pilot_medium_skin_tone": "👨🏽\u200d✈️",
+1391	    "man_playing_handball": "🤾\u200d♂️",
+1392	    "man_playing_handball_dark_skin_tone": "🤾🏿\u200d♂️",
+1393	    "man_playing_handball_light_skin_tone": "🤾🏻\u200d♂️",
+1394	    "man_playing_handball_medium-dark_skin_tone": "🤾🏾\u200d♂️",
+1395	    "man_playing_handball_medium-light_skin_tone": "🤾🏼\u200d♂️",
+1396	    "man_playing_handball_medium_skin_tone": "🤾🏽\u200d♂️",
+1397	    "man_playing_water_polo": "🤽\u200d♂️",
+1398	    "man_playing_water_polo_dark_skin_tone": "🤽🏿\u200d♂️",
+1399	    "man_playing_water_polo_light_skin_tone": "🤽🏻\u200d♂️",
+1400	    "man_playing_water_polo_medium-dark_skin_tone": "🤽🏾\u200d♂️",
+1401	    "man_playing_water_polo_medium-light_skin_tone": "🤽🏼\u200d♂️",
+1402	    "man_playing_water_polo_medium_skin_tone": "🤽🏽\u200d♂️",
+1403	    "man_police_officer": "👮\u200d♂️",
+1404	    "man_police_officer_dark_skin_tone": "👮🏿\u200d♂️",
+1405	    "man_police_officer_light_skin_tone": "👮🏻\u200d♂️",
+1406	    "man_police_officer_medium-dark_skin_tone": "👮🏾\u200d♂️",
+1407	    "man_police_officer_medium-light_skin_tone": "👮🏼\u200d♂️",
+1408	    "man_police_officer_medium_skin_tone": "👮🏽\u200d♂️",
+1409	    "man_pouting": "🙎\u200d♂️",
+1410	    "man_pouting_dark_skin_tone": "🙎🏿\u200d♂️",
+1411	    "man_pouting_light_skin_tone": "🙎🏻\u200d♂️",
+1412	    "man_pouting_medium-dark_skin_tone": "🙎🏾\u200d♂️",
+1413	    "man_pouting_medium-light_skin_tone": "🙎🏼\u200d♂️",
+1414	    "man_pouting_medium_skin_tone": "🙎🏽\u200d♂️",
+1415	    "man_raising_hand": "🙋\u200d♂️",
+1416	    "man_raising_hand_dark_skin_tone": "🙋🏿\u200d♂️",
+1417	    "man_raising_hand_light_skin_tone": "🙋🏻\u200d♂️",
+1418	    "man_raising_hand_medium-dark_skin_tone": "🙋🏾\u200d♂️",
+1419	    "man_raising_hand_medium-light_skin_tone": "🙋🏼\u200d♂️",
+1420	    "man_raising_hand_medium_skin_tone": "🙋🏽\u200d♂️",
+1421	    "man_rowing_boat": "🚣\u200d♂️",
+1422	    "man_rowing_boat_dark_skin_tone": "🚣🏿\u200d♂️",
+1423	    "man_rowing_boat_light_skin_tone": "🚣🏻\u200d♂️",
+1424	    "man_rowing_boat_medium-dark_skin_tone": "🚣🏾\u200d♂️",
+1425	    "man_rowing_boat_medium-light_skin_tone": "🚣🏼\u200d♂️",
+1426	    "man_rowing_boat_medium_skin_tone": "🚣🏽\u200d♂️",
+1427	    "man_running": "🏃\u200d♂️",
+1428	    "man_running_dark_skin_tone": "🏃🏿\u200d♂️",
+1429	    "man_running_light_skin_tone": "🏃🏻\u200d♂️",
+1430	    "man_running_medium-dark_skin_tone": "🏃🏾\u200d♂️",
+1431	    "man_running_medium-light_skin_tone": "🏃🏼\u200d♂️",
+1432	    "man_running_medium_skin_tone": "🏃🏽\u200d♂️",
+1433	    "man_scientist": "👨\u200d🔬",
+1434	    "man_scientist_dark_skin_tone": "👨🏿\u200d🔬",
+1435	    "man_scientist_light_skin_tone": "👨🏻\u200d🔬",
+1436	    "man_scientist_medium-dark_skin_tone": "👨🏾\u200d🔬",
+1437	    "man_scientist_medium-light_skin_tone": "👨🏼\u200d🔬",
+1438	    "man_scientist_medium_skin_tone": "👨🏽\u200d🔬",
+1439	    "man_shrugging": "🤷\u200d♂️",
+1440	    "man_shrugging_dark_skin_tone": "🤷🏿\u200d♂️",
+1441	    "man_shrugging_light_skin_tone": "🤷🏻\u200d♂️",
+1442	    "man_shrugging_medium-dark_skin_tone": "🤷🏾\u200d♂️",
+1443	    "man_shrugging_medium-light_skin_tone": "🤷🏼\u200d♂️",
+1444	    "man_shrugging_medium_skin_tone": "🤷🏽\u200d♂️",
+1445	    "man_singer": "👨\u200d🎤",
+1446	    "man_singer_dark_skin_tone": "👨🏿\u200d🎤",
+1447	    "man_singer_light_skin_tone": "👨🏻\u200d🎤",
+1448	    "man_singer_medium-dark_skin_tone": "👨🏾\u200d🎤",
+1449	    "man_singer_medium-light_skin_tone": "👨🏼\u200d🎤",
+1450	    "man_singer_medium_skin_tone": "👨🏽\u200d🎤",
+1451	    "man_student": "👨\u200d🎓",
+1452	    "man_student_dark_skin_tone": "👨🏿\u200d🎓",
+1453	    "man_student_light_skin_tone": "👨🏻\u200d🎓",
+1454	    "man_student_medium-dark_skin_tone": "👨🏾\u200d🎓",
+1455	    "man_student_medium-light_skin_tone": "👨🏼\u200d🎓",
+1456	    "man_student_medium_skin_tone": "👨🏽\u200d🎓",
+1457	    "man_surfing": "🏄\u200d♂️",
+1458	    "man_surfing_dark_skin_tone": "🏄🏿\u200d♂️",
+1459	    "man_surfing_light_skin_tone": "🏄🏻\u200d♂️",
+1460	    "man_surfing_medium-dark_skin_tone": "🏄🏾\u200d♂️",
+1461	    "man_surfing_medium-light_skin_tone": "🏄🏼\u200d♂️",
+1462	    "man_surfing_medium_skin_tone": "🏄🏽\u200d♂️",
+1463	    "man_swimming": "🏊\u200d♂️",
+1464	    "man_swimming_dark_skin_tone": "🏊🏿\u200d♂️",
+1465	    "man_swimming_light_skin_tone": "🏊🏻\u200d♂️",
+1466	    "man_swimming_medium-dark_skin_tone": "🏊🏾\u200d♂️",
+1467	    "man_swimming_medium-light_skin_tone": "🏊🏼\u200d♂️",
+1468	    "man_swimming_medium_skin_tone": "🏊🏽\u200d♂️",
+1469	    "man_teacher": "👨\u200d🏫",
+1470	    "man_teacher_dark_skin_tone": "👨🏿\u200d🏫",
+1471	    "man_teacher_light_skin_tone": "👨🏻\u200d🏫",
+1472	    "man_teacher_medium-dark_skin_tone": "👨🏾\u200d🏫",
+1473	    "man_teacher_medium-light_skin_tone": "👨🏼\u200d🏫",
+1474	    "man_teacher_medium_skin_tone": "👨🏽\u200d🏫",
+1475	    "man_technologist": "👨\u200d💻",
+1476	    "man_technologist_dark_skin_tone": "👨🏿\u200d💻",
+1477	    "man_technologist_light_skin_tone": "👨🏻\u200d💻",
+1478	    "man_technologist_medium-dark_skin_tone": "👨🏾\u200d💻",
+1479	    "man_technologist_medium-light_skin_tone": "👨🏼\u200d💻",
+1480	    "man_technologist_medium_skin_tone": "👨🏽\u200d💻",
+1481	    "man_tipping_hand": "💁\u200d♂️",
+1482	    "man_tipping_hand_dark_skin_tone": "💁🏿\u200d♂️",
+1483	    "man_tipping_hand_light_skin_tone": "💁🏻\u200d♂️",
+1484	    "man_tipping_hand_medium-dark_skin_tone": "💁🏾\u200d♂️",
+1485	    "man_tipping_hand_medium-light_skin_tone": "💁🏼\u200d♂️",
+1486	    "man_tipping_hand_medium_skin_tone": "💁🏽\u200d♂️",
+1487	    "man_vampire": "🧛\u200d♂️",
+1488	    "man_vampire_dark_skin_tone": "🧛🏿\u200d♂️",
+1489	    "man_vampire_light_skin_tone": "🧛🏻\u200d♂️",
+1490	    "man_vampire_medium-dark_skin_tone": "🧛🏾\u200d♂️",
+1491	    "man_vampire_medium-light_skin_tone": "🧛🏼\u200d♂️",
+1492	    "man_vampire_medium_skin_tone": "🧛🏽\u200d♂️",
+1493	    "man_walking": "🚶\u200d♂️",
+1494	    "man_walking_dark_skin_tone": "🚶🏿\u200d♂️",
+1495	    "man_walking_light_skin_tone": "🚶🏻\u200d♂️",
+1496	    "man_walking_medium-dark_skin_tone": "🚶🏾\u200d♂️",
+1497	    "man_walking_medium-light_skin_tone": "🚶🏼\u200d♂️",
+1498	    "man_walking_medium_skin_tone": "🚶🏽\u200d♂️",
+1499	    "man_wearing_turban": "👳\u200d♂️",
+1500	    "man_wearing_turban_dark_skin_tone": "👳🏿\u200d♂️",
+1501	    "man_wearing_turban_light_skin_tone": "👳🏻\u200d♂️",
+1502	    "man_wearing_turban_medium-dark_skin_tone": "👳🏾\u200d♂️",
+1503	    "man_wearing_turban_medium-light_skin_tone": "👳🏼\u200d♂️",
+1504	    "man_wearing_turban_medium_skin_tone": "👳🏽\u200d♂️",
+1505	    "man_with_probing_cane": "👨\u200d🦯",
+1506	    "man_with_chinese_cap": "👲",
+1507	    "man_with_chinese_cap_dark_skin_tone": "👲🏿",
+1508	    "man_with_chinese_cap_light_skin_tone": "👲🏻",
+1509	    "man_with_chinese_cap_medium-dark_skin_tone": "👲🏾",
+1510	    "man_with_chinese_cap_medium-light_skin_tone": "👲🏼",
+1511	    "man_with_chinese_cap_medium_skin_tone": "👲🏽",
+1512	    "man_zombie": "🧟\u200d♂️",
+1513	    "mango": "🥭",
+1514	    "mantelpiece_clock": "🕰",
+1515	    "manual_wheelchair": "🦽",
+1516	    "man’s_shoe": "👞",
+1517	    "map_of_japan": "🗾",
+1518	    "maple_leaf": "🍁",
+1519	    "martial_arts_uniform": "🥋",
+1520	    "mate": "🧉",
+1521	    "meat_on_bone": "🍖",
+1522	    "mechanical_arm": "🦾",
+1523	    "mechanical_leg": "🦿",
+1524	    "medical_symbol": "⚕",
+1525	    "megaphone": "📣",
+1526	    "melon": "🍈",
+1527	    "memo": "📝",
+1528	    "men_with_bunny_ears": "👯\u200d♂️",
+1529	    "men_wrestling": "🤼\u200d♂️",
+1530	    "menorah": "🕎",
+1531	    "men’s_room": "🚹",
+1532	    "mermaid": "🧜\u200d♀️",
+1533	    "mermaid_dark_skin_tone": "🧜🏿\u200d♀️",
+1534	    "mermaid_light_skin_tone": "🧜🏻\u200d♀️",
+1535	    "mermaid_medium-dark_skin_tone": "🧜🏾\u200d♀️",
+1536	    "mermaid_medium-light_skin_tone": "🧜🏼\u200d♀️",
+1537	    "mermaid_medium_skin_tone": "🧜🏽\u200d♀️",
+1538	    "merman": "🧜\u200d♂️",
+1539	    "merman_dark_skin_tone": "🧜🏿\u200d♂️",
+1540	    "merman_light_skin_tone": "🧜🏻\u200d♂️",
+1541	    "merman_medium-dark_skin_tone": "🧜🏾\u200d♂️",
+1542	    "merman_medium-light_skin_tone": "🧜🏼\u200d♂️",
+1543	    "merman_medium_skin_tone": "🧜🏽\u200d♂️",
+1544	    "merperson": "🧜",
+1545	    "merperson_dark_skin_tone": "🧜🏿",
+1546	    "merperson_light_skin_tone": "🧜🏻",
+1547	    "merperson_medium-dark_skin_tone": "🧜🏾",
+1548	    "merperson_medium-light_skin_tone": "🧜🏼",
+1549	    "merperson_medium_skin_tone": "🧜🏽",
+1550	    "metro": "🚇",
+1551	    "microbe": "🦠",
+1552	    "microphone": "🎤",
+1553	    "microscope": "🔬",
+1554	    "middle_finger": "🖕",
+1555	    "middle_finger_dark_skin_tone": "🖕🏿",
+1556	    "middle_finger_light_skin_tone": "🖕🏻",
+1557	    "middle_finger_medium-dark_skin_tone": "🖕🏾",
+1558	    "middle_finger_medium-light_skin_tone": "🖕🏼",
+1559	    "middle_finger_medium_skin_tone": "🖕🏽",
+1560	    "military_medal": "🎖",
+1561	    "milky_way": "🌌",
+1562	    "minibus": "🚐",
+1563	    "moai": "🗿",
+1564	    "mobile_phone": "📱",
+1565	    "mobile_phone_off": "📴",
+1566	    "mobile_phone_with_arrow": "📲",
+1567	    "money-mouth_face": "🤑",
+1568	    "money_bag": "💰",
+1569	    "money_with_wings": "💸",
+1570	    "monkey": "🐒",
+1571	    "monkey_face": "🐵",
+1572	    "monorail": "🚝",
+1573	    "moon_cake": "🥮",
+1574	    "moon_viewing_ceremony": "🎑",
+1575	    "mosque": "🕌",
+1576	    "mosquito": "🦟",
+1577	    "motor_boat": "🛥",
+1578	    "motor_scooter": "🛵",
+1579	    "motorcycle": "🏍",
+1580	    "motorized_wheelchair": "🦼",
+1581	    "motorway": "🛣",
+1582	    "mount_fuji": "🗻",
+1583	    "mountain": "⛰",
+1584	    "mountain_cableway": "🚠",
+1585	    "mountain_railway": "🚞",
+1586	    "mouse": "🐭",
+1587	    "mouse_face": "🐭",
+1588	    "mouth": "👄",
+1589	    "movie_camera": "🎥",
+1590	    "mushroom": "🍄",
+1591	    "musical_keyboard": "🎹",
+1592	    "musical_note": "🎵",
+1593	    "musical_notes": "🎶",
+1594	    "musical_score": "🎼",
+1595	    "muted_speaker": "🔇",
+1596	    "nail_polish": "💅",
+1597	    "nail_polish_dark_skin_tone": "💅🏿",
+1598	    "nail_polish_light_skin_tone": "💅🏻",
+1599	    "nail_polish_medium-dark_skin_tone": "💅🏾",
+1600	    "nail_polish_medium-light_skin_tone": "💅🏼",
+1601	    "nail_polish_medium_skin_tone": "💅🏽",
+1602	    "name_badge": "📛",
+1603	    "national_park": "🏞",
+1604	    "nauseated_face": "🤢",
+1605	    "nazar_amulet": "🧿",
+1606	    "necktie": "👔",
+1607	    "nerd_face": "🤓",
+1608	    "neutral_face": "😐",
+1609	    "new_moon": "🌑",
+1610	    "new_moon_face": "🌚",
+1611	    "newspaper": "📰",
+1612	    "next_track_button": "⏭",
+1613	    "night_with_stars": "🌃",
+1614	    "nine-thirty": "🕤",
+1615	    "nine_o’clock": "🕘",
+1616	    "no_bicycles": "🚳",
+1617	    "no_entry": "⛔",
+1618	    "no_littering": "🚯",
+1619	    "no_mobile_phones": "📵",
+1620	    "no_one_under_eighteen": "🔞",
+1621	    "no_pedestrians": "🚷",
+1622	    "no_smoking": "🚭",
+1623	    "non-potable_water": "🚱",
+1624	    "nose": "👃",
+1625	    "nose_dark_skin_tone": "👃🏿",
+1626	    "nose_light_skin_tone": "👃🏻",
+1627	    "nose_medium-dark_skin_tone": "👃🏾",
+1628	    "nose_medium-light_skin_tone": "👃🏼",
+1629	    "nose_medium_skin_tone": "👃🏽",
+1630	    "notebook": "📓",
+1631	    "notebook_with_decorative_cover": "📔",
+1632	    "nut_and_bolt": "🔩",
+1633	    "octopus": "🐙",
+1634	    "oden": "🍢",
+1635	    "office_building": "🏢",
+1636	    "ogre": "👹",
+1637	    "oil_drum": "🛢",
+1638	    "old_key": "🗝",
+1639	    "old_man": "👴",
+1640	    "old_man_dark_skin_tone": "👴🏿",
+1641	    "old_man_light_skin_tone": "👴🏻",
+1642	    "old_man_medium-dark_skin_tone": "👴🏾",
+1643	    "old_man_medium-light_skin_tone": "👴🏼",
+1644	    "old_man_medium_skin_tone": "👴🏽",
+1645	    "old_woman": "👵",
+1646	    "old_woman_dark_skin_tone": "👵🏿",
+1647	    "old_woman_light_skin_tone": "👵🏻",
+1648	    "old_woman_medium-dark_skin_tone": "👵🏾",
+1649	    "old_woman_medium-light_skin_tone": "👵🏼",
+1650	    "old_woman_medium_skin_tone": "👵🏽",
+1651	    "older_adult": "🧓",
+1652	    "older_adult_dark_skin_tone": "🧓🏿",
+1653	    "older_adult_light_skin_tone": "🧓🏻",
+1654	    "older_adult_medium-dark_skin_tone": "🧓🏾",
+1655	    "older_adult_medium-light_skin_tone": "🧓🏼",
+1656	    "older_adult_medium_skin_tone": "🧓🏽",
+1657	    "om": "🕉",
+1658	    "oncoming_automobile": "🚘",
+1659	    "oncoming_bus": "🚍",
+1660	    "oncoming_fist": "👊",
+1661	    "oncoming_fist_dark_skin_tone": "👊🏿",
+1662	    "oncoming_fist_light_skin_tone": "👊🏻",
+1663	    "oncoming_fist_medium-dark_skin_tone": "👊🏾",
+1664	    "oncoming_fist_medium-light_skin_tone": "👊🏼",
+1665	    "oncoming_fist_medium_skin_tone": "👊🏽",
+1666	    "oncoming_police_car": "🚔",
+1667	    "oncoming_taxi": "🚖",
+1668	    "one-piece_swimsuit": "🩱",
+1669	    "one-thirty": "🕜",
+1670	    "one_o’clock": "🕐",
+1671	    "onion": "🧅",
+1672	    "open_book": "📖",
+1673	    "open_file_folder": "📂",
+1674	    "open_hands": "👐",
+1675	    "open_hands_dark_skin_tone": "👐🏿",
+1676	    "open_hands_light_skin_tone": "👐🏻",
+1677	    "open_hands_medium-dark_skin_tone": "👐🏾",
+1678	    "open_hands_medium-light_skin_tone": "👐🏼",
+1679	    "open_hands_medium_skin_tone": "👐🏽",
+1680	    "open_mailbox_with_lowered_flag": "📭",
+1681	    "open_mailbox_with_raised_flag": "📬",
+1682	    "optical_disk": "💿",
+1683	    "orange_book": "📙",
+1684	    "orange_circle": "🟠",
+1685	    "orange_heart": "🧡",
+1686	    "orange_square": "🟧",
+1687	    "orangutan": "🦧",
+1688	    "orthodox_cross": "☦",
+1689	    "otter": "🦦",
+1690	    "outbox_tray": "📤",
+1691	    "owl": "🦉",
+1692	    "ox": "🐂",
+1693	    "oyster": "🦪",
+1694	    "package": "📦",
+1695	    "page_facing_up": "📄",
+1696	    "page_with_curl": "📃",
+1697	    "pager": "📟",
+1698	    "paintbrush": "🖌",
+1699	    "palm_tree": "🌴",
+1700	    "palms_up_together": "🤲",
+1701	    "palms_up_together_dark_skin_tone": "🤲🏿",
+1702	    "palms_up_together_light_skin_tone": "🤲🏻",
+1703	    "palms_up_together_medium-dark_skin_tone": "🤲🏾",
+1704	    "palms_up_together_medium-light_skin_tone": "🤲🏼",
+1705	    "palms_up_together_medium_skin_tone": "🤲🏽",
+1706	    "pancakes": "🥞",
+1707	    "panda_face": "🐼",
+1708	    "paperclip": "📎",
+1709	    "parrot": "🦜",
+1710	    "part_alternation_mark": "〽",
+1711	    "party_popper": "🎉",
+1712	    "partying_face": "🥳",
+1713	    "passenger_ship": "🛳",
+1714	    "passport_control": "🛂",
+1715	    "pause_button": "⏸",
+1716	    "paw_prints": "🐾",
+1717	    "peace_symbol": "☮",
+1718	    "peach": "🍑",
+1719	    "peacock": "🦚",
+1720	    "peanuts": "🥜",
+1721	    "pear": "🍐",
+1722	    "pen": "🖊",
+1723	    "pencil": "📝",
+1724	    "penguin": "🐧",
+1725	    "pensive_face": "😔",
+1726	    "people_holding_hands": "🧑\u200d🤝\u200d🧑",
+1727	    "people_with_bunny_ears": "👯",
+1728	    "people_wrestling": "🤼",
+1729	    "performing_arts": "🎭",
+1730	    "persevering_face": "😣",
+1731	    "person_biking": "🚴",
+1732	    "person_biking_dark_skin_tone": "🚴🏿",
+1733	    "person_biking_light_skin_tone": "🚴🏻",
+1734	    "person_biking_medium-dark_skin_tone": "🚴🏾",
+1735	    "person_biking_medium-light_skin_tone": "🚴🏼",
+1736	    "person_biking_medium_skin_tone": "🚴🏽",
+1737	    "person_bouncing_ball": "⛹",
+1738	    "person_bouncing_ball_dark_skin_tone": "⛹🏿",
+1739	    "person_bouncing_ball_light_skin_tone": "⛹🏻",
+1740	    "person_bouncing_ball_medium-dark_skin_tone": "⛹🏾",
+1741	    "person_bouncing_ball_medium-light_skin_tone": "⛹🏼",
+1742	    "person_bouncing_ball_medium_skin_tone": "⛹🏽",
+1743	    "person_bowing": "🙇",
+1744	    "person_bowing_dark_skin_tone": "🙇🏿",
+1745	    "person_bowing_light_skin_tone": "🙇🏻",
+1746	    "person_bowing_medium-dark_skin_tone": "🙇🏾",
+1747	    "person_bowing_medium-light_skin_tone": "🙇🏼",
+1748	    "person_bowing_medium_skin_tone": "🙇🏽",
+1749	    "person_cartwheeling": "🤸",
+1750	    "person_cartwheeling_dark_skin_tone": "🤸🏿",
+1751	    "person_cartwheeling_light_skin_tone": "🤸🏻",
+1752	    "person_cartwheeling_medium-dark_skin_tone": "🤸🏾",
+1753	    "person_cartwheeling_medium-light_skin_tone": "🤸🏼",
+1754	    "person_cartwheeling_medium_skin_tone": "🤸🏽",
+1755	    "person_climbing": "🧗",
+1756	    "person_climbing_dark_skin_tone": "🧗🏿",
+1757	    "person_climbing_light_skin_tone": "🧗🏻",
+1758	    "person_climbing_medium-dark_skin_tone": "🧗🏾",
+1759	    "person_climbing_medium-light_skin_tone": "🧗🏼",
+1760	    "person_climbing_medium_skin_tone": "🧗🏽",
+1761	    "person_facepalming": "🤦",
+1762	    "person_facepalming_dark_skin_tone": "🤦🏿",
+1763	    "person_facepalming_light_skin_tone": "🤦🏻",
+1764	    "person_facepalming_medium-dark_skin_tone": "🤦🏾",
+1765	    "person_facepalming_medium-light_skin_tone": "🤦🏼",
+1766	    "person_facepalming_medium_skin_tone": "🤦🏽",
+1767	    "person_fencing": "🤺",
+1768	    "person_frowning": "🙍",
+1769	    "person_frowning_dark_skin_tone": "🙍🏿",
+1770	    "person_frowning_light_skin_tone": "🙍🏻",
+1771	    "person_frowning_medium-dark_skin_tone": "🙍🏾",
+1772	    "person_frowning_medium-light_skin_tone": "🙍🏼",
+1773	    "person_frowning_medium_skin_tone": "🙍🏽",
+1774	    "person_gesturing_no": "🙅",
+1775	    "person_gesturing_no_dark_skin_tone": "🙅🏿",
+1776	    "person_gesturing_no_light_skin_tone": "🙅🏻",
+1777	    "person_gesturing_no_medium-dark_skin_tone": "🙅🏾",
+1778	    "person_gesturing_no_medium-light_skin_tone": "🙅🏼",
+1779	    "person_gesturing_no_medium_skin_tone": "🙅🏽",
+1780	    "person_gesturing_ok": "🙆",
+1781	    "person_gesturing_ok_dark_skin_tone": "🙆🏿",
+1782	    "person_gesturing_ok_light_skin_tone": "🙆🏻",
+1783	    "person_gesturing_ok_medium-dark_skin_tone": "🙆🏾",
+1784	    "person_gesturing_ok_medium-light_skin_tone": "🙆🏼",
+1785	    "person_gesturing_ok_medium_skin_tone": "🙆🏽",
+1786	    "person_getting_haircut": "💇",
+1787	    "person_getting_haircut_dark_skin_tone": "💇🏿",
+1788	    "person_getting_haircut_light_skin_tone": "💇🏻",
+1789	    "person_getting_haircut_medium-dark_skin_tone": "💇🏾",
+1790	    "person_getting_haircut_medium-light_skin_tone": "💇🏼",
+1791	    "person_getting_haircut_medium_skin_tone": "💇🏽",
+1792	    "person_getting_massage": "💆",
+1793	    "person_getting_massage_dark_skin_tone": "💆🏿",
+1794	    "person_getting_massage_light_skin_tone": "💆🏻",
+1795	    "person_getting_massage_medium-dark_skin_tone": "💆🏾",
+1796	    "person_getting_massage_medium-light_skin_tone": "💆🏼",
+1797	    "person_getting_massage_medium_skin_tone": "💆🏽",
+1798	    "person_golfing": "🏌",
+1799	    "person_golfing_dark_skin_tone": "🏌🏿",
+1800	    "person_golfing_light_skin_tone": "🏌🏻",
+1801	    "person_golfing_medium-dark_skin_tone": "🏌🏾",
+1802	    "person_golfing_medium-light_skin_tone": "🏌🏼",
+1803	    "person_golfing_medium_skin_tone": "🏌🏽",
+1804	    "person_in_bed": "🛌",
+1805	    "person_in_bed_dark_skin_tone": "🛌🏿",
+1806	    "person_in_bed_light_skin_tone": "🛌🏻",
+1807	    "person_in_bed_medium-dark_skin_tone": "🛌🏾",
+1808	    "person_in_bed_medium-light_skin_tone": "🛌🏼",
+1809	    "person_in_bed_medium_skin_tone": "🛌🏽",
+1810	    "person_in_lotus_position": "🧘",
+1811	    "person_in_lotus_position_dark_skin_tone": "🧘🏿",
+1812	    "person_in_lotus_position_light_skin_tone": "🧘🏻",
+1813	    "person_in_lotus_position_medium-dark_skin_tone": "🧘🏾",
+1814	    "person_in_lotus_position_medium-light_skin_tone": "🧘🏼",
+1815	    "person_in_lotus_position_medium_skin_tone": "🧘🏽",
+1816	    "person_in_steamy_room": "🧖",
+1817	    "person_in_steamy_room_dark_skin_tone": "🧖🏿",
+1818	    "person_in_steamy_room_light_skin_tone": "🧖🏻",
+1819	    "person_in_steamy_room_medium-dark_skin_tone": "🧖🏾",
+1820	    "person_in_steamy_room_medium-light_skin_tone": "🧖🏼",
+1821	    "person_in_steamy_room_medium_skin_tone": "🧖🏽",
+1822	    "person_juggling": "🤹",
+1823	    "person_juggling_dark_skin_tone": "🤹🏿",
+1824	    "person_juggling_light_skin_tone": "🤹🏻",
+1825	    "person_juggling_medium-dark_skin_tone": "🤹🏾",
+1826	    "person_juggling_medium-light_skin_tone": "🤹🏼",
+1827	    "person_juggling_medium_skin_tone": "🤹🏽",
+1828	    "person_kneeling": "🧎",
+1829	    "person_lifting_weights": "🏋",
+1830	    "person_lifting_weights_dark_skin_tone": "🏋🏿",
+1831	    "person_lifting_weights_light_skin_tone": "🏋🏻",
+1832	    "person_lifting_weights_medium-dark_skin_tone": "🏋🏾",
+1833	    "person_lifting_weights_medium-light_skin_tone": "🏋🏼",
+1834	    "person_lifting_weights_medium_skin_tone": "🏋🏽",
+1835	    "person_mountain_biking": "🚵",
+1836	    "person_mountain_biking_dark_skin_tone": "🚵🏿",
+1837	    "person_mountain_biking_light_skin_tone": "🚵🏻",
+1838	    "person_mountain_biking_medium-dark_skin_tone": "🚵🏾",
+1839	    "person_mountain_biking_medium-light_skin_tone": "🚵🏼",
+1840	    "person_mountain_biking_medium_skin_tone": "🚵🏽",
+1841	    "person_playing_handball": "🤾",
+1842	    "person_playing_handball_dark_skin_tone": "🤾🏿",
+1843	    "person_playing_handball_light_skin_tone": "🤾🏻",
+1844	    "person_playing_handball_medium-dark_skin_tone": "🤾🏾",
+1845	    "person_playing_handball_medium-light_skin_tone": "🤾🏼",
+1846	    "person_playing_handball_medium_skin_tone": "🤾🏽",
+1847	    "person_playing_water_polo": "🤽",
+1848	    "person_playing_water_polo_dark_skin_tone": "🤽🏿",
+1849	    "person_playing_water_polo_light_skin_tone": "🤽🏻",
+1850	    "person_playing_water_polo_medium-dark_skin_tone": "🤽🏾",
+1851	    "person_playing_water_polo_medium-light_skin_tone": "🤽🏼",
+1852	    "person_playing_water_polo_medium_skin_tone": "🤽🏽",
+1853	    "person_pouting": "🙎",
+1854	    "person_pouting_dark_skin_tone": "🙎🏿",
+1855	    "person_pouting_light_skin_tone": "🙎🏻",
+1856	    "person_pouting_medium-dark_skin_tone": "🙎🏾",
+1857	    "person_pouting_medium-light_skin_tone": "🙎🏼",
+1858	    "person_pouting_medium_skin_tone": "🙎🏽",
+1859	    "person_raising_hand": "🙋",
+1860	    "person_raising_hand_dark_skin_tone": "🙋🏿",
+1861	    "person_raising_hand_light_skin_tone": "🙋🏻",
+1862	    "person_raising_hand_medium-dark_skin_tone": "🙋🏾",
+1863	    "person_raising_hand_medium-light_skin_tone": "🙋🏼",
+1864	    "person_raising_hand_medium_skin_tone": "🙋🏽",
+1865	    "person_rowing_boat": "🚣",
+1866	    "person_rowing_boat_dark_skin_tone": "🚣🏿",
+1867	    "person_rowing_boat_light_skin_tone": "🚣🏻",
+1868	    "person_rowing_boat_medium-dark_skin_tone": "🚣🏾",
+1869	    "person_rowing_boat_medium-light_skin_tone": "🚣🏼",
+1870	    "person_rowing_boat_medium_skin_tone": "🚣🏽",
+1871	    "person_running": "🏃",
+1872	    "person_running_dark_skin_tone": "🏃🏿",
+1873	    "person_running_light_skin_tone": "🏃🏻",
+1874	    "person_running_medium-dark_skin_tone": "🏃🏾",
+1875	    "person_running_medium-light_skin_tone": "🏃🏼",
+1876	    "person_running_medium_skin_tone": "🏃🏽",
+1877	    "person_shrugging": "🤷",
+1878	    "person_shrugging_dark_skin_tone": "🤷🏿",
+1879	    "person_shrugging_light_skin_tone": "🤷🏻",
+1880	    "person_shrugging_medium-dark_skin_tone": "🤷🏾",
+1881	    "person_shrugging_medium-light_skin_tone": "🤷🏼",
+1882	    "person_shrugging_medium_skin_tone": "🤷🏽",
+1883	    "person_standing": "🧍",
+1884	    "person_surfing": "🏄",
+1885	    "person_surfing_dark_skin_tone": "🏄🏿",
+1886	    "person_surfing_light_skin_tone": "🏄🏻",
+1887	    "person_surfing_medium-dark_skin_tone": "🏄🏾",
+1888	    "person_surfing_medium-light_skin_tone": "🏄🏼",
+1889	    "person_surfing_medium_skin_tone": "🏄🏽",
+1890	    "person_swimming": "🏊",
+1891	    "person_swimming_dark_skin_tone": "🏊🏿",
+1892	    "person_swimming_light_skin_tone": "🏊🏻",
+1893	    "person_swimming_medium-dark_skin_tone": "🏊🏾",
+1894	    "person_swimming_medium-light_skin_tone": "🏊🏼",
+1895	    "person_swimming_medium_skin_tone": "🏊🏽",
+1896	    "person_taking_bath": "🛀",
+1897	    "person_taking_bath_dark_skin_tone": "🛀🏿",
+1898	    "person_taking_bath_light_skin_tone": "🛀🏻",
+1899	    "person_taking_bath_medium-dark_skin_tone": "🛀🏾",
+1900	    "person_taking_bath_medium-light_skin_tone": "🛀🏼",
+1901	    "person_taking_bath_medium_skin_tone": "🛀🏽",
+1902	    "person_tipping_hand": "💁",
+1903	    "person_tipping_hand_dark_skin_tone": "💁🏿",
+1904	    "person_tipping_hand_light_skin_tone": "💁🏻",
+1905	    "person_tipping_hand_medium-dark_skin_tone": "💁🏾",
+1906	    "person_tipping_hand_medium-light_skin_tone": "💁🏼",
+1907	    "person_tipping_hand_medium_skin_tone": "💁🏽",
+1908	    "person_walking": "🚶",
+1909	    "person_walking_dark_skin_tone": "🚶🏿",
+1910	    "person_walking_light_skin_tone": "🚶🏻",
+1911	    "person_walking_medium-dark_skin_tone": "🚶🏾",
+1912	    "person_walking_medium-light_skin_tone": "🚶🏼",
+1913	    "person_walking_medium_skin_tone": "🚶🏽",
+1914	    "person_wearing_turban": "👳",
+1915	    "person_wearing_turban_dark_skin_tone": "👳🏿",
+1916	    "person_wearing_turban_light_skin_tone": "👳🏻",
+1917	    "person_wearing_turban_medium-dark_skin_tone": "👳🏾",
+1918	    "person_wearing_turban_medium-light_skin_tone": "👳🏼",
+1919	    "person_wearing_turban_medium_skin_tone": "👳🏽",
+1920	    "petri_dish": "🧫",
+1921	    "pick": "⛏",
+1922	    "pie": "🥧",
+1923	    "pig": "🐷",
+1924	    "pig_face": "🐷",
+1925	    "pig_nose": "🐽",
+1926	    "pile_of_poo": "💩",
+1927	    "pill": "💊",
+1928	    "pinching_hand": "🤏",
+1929	    "pine_decoration": "🎍",
+1930	    "pineapple": "🍍",
+1931	    "ping_pong": "🏓",
+1932	    "pirate_flag": "🏴\u200d☠️",
+1933	    "pistol": "🔫",
+1934	    "pizza": "🍕",
+1935	    "place_of_worship": "🛐",
+1936	    "play_button": "▶",
+1937	    "play_or_pause_button": "⏯",
+1938	    "pleading_face": "🥺",
+1939	    "police_car": "🚓",
+1940	    "police_car_light": "🚨",
+1941	    "police_officer": "👮",
+1942	    "police_officer_dark_skin_tone": "👮🏿",
+1943	    "police_officer_light_skin_tone": "👮🏻",
+1944	    "police_officer_medium-dark_skin_tone": "👮🏾",
+1945	    "police_officer_medium-light_skin_tone": "👮🏼",
+1946	    "police_officer_medium_skin_tone": "👮🏽",
+1947	    "poodle": "🐩",
+1948	    "pool_8_ball": "🎱",
+1949	    "popcorn": "🍿",
+1950	    "post_office": "🏣",
+1951	    "postal_horn": "📯",
+1952	    "postbox": "📮",
+1953	    "pot_of_food": "🍲",
+1954	    "potable_water": "🚰",
+1955	    "potato": "🥔",
+1956	    "poultry_leg": "🍗",
+1957	    "pound_banknote": "💷",
+1958	    "pouting_cat_face": "😾",
+1959	    "pouting_face": "😡",
+1960	    "prayer_beads": "📿",
+1961	    "pregnant_woman": "🤰",
+1962	    "pregnant_woman_dark_skin_tone": "🤰🏿",
+1963	    "pregnant_woman_light_skin_tone": "🤰🏻",
+1964	    "pregnant_woman_medium-dark_skin_tone": "🤰🏾",
+1965	    "pregnant_woman_medium-light_skin_tone": "🤰🏼",
+1966	    "pregnant_woman_medium_skin_tone": "🤰🏽",
+1967	    "pretzel": "🥨",
+1968	    "probing_cane": "🦯",
+1969	    "prince": "🤴",
+1970	    "prince_dark_skin_tone": "🤴🏿",
+1971	    "prince_light_skin_tone": "🤴🏻",
+1972	    "prince_medium-dark_skin_tone": "🤴🏾",
+1973	    "prince_medium-light_skin_tone": "🤴🏼",
+1974	    "prince_medium_skin_tone": "🤴🏽",
+1975	    "princess": "👸",
+1976	    "princess_dark_skin_tone": "👸🏿",
+1977	    "princess_light_skin_tone": "👸🏻",
+1978	    "princess_medium-dark_skin_tone": "👸🏾",
+1979	    "princess_medium-light_skin_tone": "👸🏼",
+1980	    "princess_medium_skin_tone": "👸🏽",
+1981	    "printer": "🖨",
+1982	    "prohibited": "🚫",
+1983	    "purple_circle": "🟣",
+1984	    "purple_heart": "💜",
+1985	    "purple_square": "🟪",
+1986	    "purse": "👛",
+1987	    "pushpin": "📌",
+1988	    "question_mark": "❓",
+1989	    "rabbit": "🐰",
+1990	    "rabbit_face": "🐰",
+1991	    "raccoon": "🦝",
+1992	    "racing_car": "🏎",
+1993	    "radio": "📻",
+1994	    "radio_button": "🔘",
+1995	    "radioactive": "☢",
+1996	    "railway_car": "🚃",
+1997	    "railway_track": "🛤",
+1998	    "rainbow": "🌈",
+1999	    "rainbow_flag": "🏳️\u200d🌈",
+2000	    "raised_back_of_hand": "🤚",
+2001	    "raised_back_of_hand_dark_skin_tone": "🤚🏿",
+2002	    "raised_back_of_hand_light_skin_tone": "🤚🏻",
+2003	    "raised_back_of_hand_medium-dark_skin_tone": "🤚🏾",
+2004	    "raised_back_of_hand_medium-light_skin_tone": "🤚🏼",
+2005	    "raised_back_of_hand_medium_skin_tone": "🤚🏽",
+2006	    "raised_fist": "✊",
+2007	    "raised_fist_dark_skin_tone": "✊🏿",
+2008	    "raised_fist_light_skin_tone": "✊🏻",
+2009	    "raised_fist_medium-dark_skin_tone": "✊🏾",
+2010	    "raised_fist_medium-light_skin_tone": "✊🏼",
+2011	    "raised_fist_medium_skin_tone": "✊🏽",
+2012	    "raised_hand": "✋",
+2013	    "raised_hand_dark_skin_tone": "✋🏿",
+2014	    "raised_hand_light_skin_tone": "✋🏻",
+2015	    "raised_hand_medium-dark_skin_tone": "✋🏾",
+2016	    "raised_hand_medium-light_skin_tone": "✋🏼",
+2017	    "raised_hand_medium_skin_tone": "✋🏽",
+2018	    "raising_hands": "🙌",
+2019	    "raising_hands_dark_skin_tone": "🙌🏿",
+2020	    "raising_hands_light_skin_tone": "🙌🏻",
+2021	    "raising_hands_medium-dark_skin_tone": "🙌🏾",
+2022	    "raising_hands_medium-light_skin_tone": "🙌🏼",
+2023	    "raising_hands_medium_skin_tone": "🙌🏽",
+2024	    "ram": "🐏",
+2025	    "rat": "🐀",
+2026	    "razor": "🪒",
+2027	    "ringed_planet": "🪐",
+2028	    "receipt": "🧾",
+2029	    "record_button": "⏺",
+2030	    "recycling_symbol": "♻",
+2031	    "red_apple": "🍎",
+2032	    "red_circle": "🔴",
+2033	    "red_envelope": "🧧",
+2034	    "red_hair": "🦰",
+2035	    "red-haired_man": "👨\u200d🦰",
+2036	    "red-haired_woman": "👩\u200d🦰",
+2037	    "red_heart": "❤",
+2038	    "red_paper_lantern": "🏮",
+2039	    "red_square": "🟥",
+2040	    "red_triangle_pointed_down": "🔻",
+2041	    "red_triangle_pointed_up": "🔺",
+2042	    "registered": "®",
+2043	    "relieved_face": "😌",
+2044	    "reminder_ribbon": "🎗",
+2045	    "repeat_button": "🔁",
+2046	    "repeat_single_button": "🔂",
+2047	    "rescue_worker’s_helmet": "⛑",
+2048	    "restroom": "🚻",
+2049	    "reverse_button": "◀",
+2050	    "revolving_hearts": "💞",
+2051	    "rhinoceros": "🦏",
+2052	    "ribbon": "🎀",
+2053	    "rice_ball": "🍙",
+2054	    "rice_cracker": "🍘",
+2055	    "right-facing_fist": "🤜",
+2056	    "right-facing_fist_dark_skin_tone": "🤜🏿",
+2057	    "right-facing_fist_light_skin_tone": "🤜🏻",
+2058	    "right-facing_fist_medium-dark_skin_tone": "🤜🏾",
+2059	    "right-facing_fist_medium-light_skin_tone": "🤜🏼",
+2060	    "right-facing_fist_medium_skin_tone": "🤜🏽",
+2061	    "right_anger_bubble": "🗯",
+2062	    "right_arrow": "➡",
+2063	    "right_arrow_curving_down": "⤵",
+2064	    "right_arrow_curving_left": "↩",
+2065	    "right_arrow_curving_up": "⤴",
+2066	    "ring": "💍",
+2067	    "roasted_sweet_potato": "🍠",
+2068	    "robot_face": "🤖",
+2069	    "rocket": "🚀",
+2070	    "roll_of_paper": "🧻",
+2071	    "rolled-up_newspaper": "🗞",
+2072	    "roller_coaster": "🎢",
+2073	    "rolling_on_the_floor_laughing": "🤣",
+2074	    "rooster": "🐓",
+2075	    "rose": "🌹",
+2076	    "rosette": "🏵",
+2077	    "round_pushpin": "📍",
+2078	    "rugby_football": "🏉",
+2079	    "running_shirt": "🎽",
+2080	    "running_shoe": "👟",
+2081	    "sad_but_relieved_face": "😥",
+2082	    "safety_pin": "🧷",
+2083	    "safety_vest": "🦺",
+2084	    "salt": "🧂",
+2085	    "sailboat": "⛵",
+2086	    "sake": "🍶",
+2087	    "sandwich": "🥪",
+2088	    "sari": "🥻",
+2089	    "satellite": "📡",
+2090	    "satellite_antenna": "📡",
+2091	    "sauropod": "🦕",
+2092	    "saxophone": "🎷",
+2093	    "scarf": "🧣",
+2094	    "school": "🏫",
+2095	    "school_backpack": "🎒",
+2096	    "scissors": "✂",
+2097	    "scorpion": "🦂",
+2098	    "scroll": "📜",
+2099	    "seat": "💺",
+2100	    "see-no-evil_monkey": "🙈",
+2101	    "seedling": "🌱",
+2102	    "selfie": "🤳",
+2103	    "selfie_dark_skin_tone": "🤳🏿",
+2104	    "selfie_light_skin_tone": "🤳🏻",
+2105	    "selfie_medium-dark_skin_tone": "🤳🏾",
+2106	    "selfie_medium-light_skin_tone": "🤳🏼",
+2107	    "selfie_medium_skin_tone": "🤳🏽",
+2108	    "service_dog": "🐕\u200d🦺",
+2109	    "seven-thirty": "🕢",
+2110	    "seven_o’clock": "🕖",
+2111	    "shallow_pan_of_food": "🥘",
+2112	    "shamrock": "☘",
+2113	    "shark": "🦈",
+2114	    "shaved_ice": "🍧",
+2115	    "sheaf_of_rice": "🌾",
+2116	    "shield": "🛡",
+2117	    "shinto_shrine": "⛩",
+2118	    "ship": "🚢",
+2119	    "shooting_star": "🌠",
+2120	    "shopping_bags": "🛍",
+2121	    "shopping_cart": "🛒",
+2122	    "shortcake": "🍰",
+2123	    "shorts": "🩳",
+2124	    "shower": "🚿",
+2125	    "shrimp": "🦐",
+2126	    "shuffle_tracks_button": "🔀",
+2127	    "shushing_face": "🤫",
+2128	    "sign_of_the_horns": "🤘",
+2129	    "sign_of_the_horns_dark_skin_tone": "🤘🏿",
+2130	    "sign_of_the_horns_light_skin_tone": "🤘🏻",
+2131	    "sign_of_the_horns_medium-dark_skin_tone": "🤘🏾",
+2132	    "sign_of_the_horns_medium-light_skin_tone": "🤘🏼",
+2133	    "sign_of_the_horns_medium_skin_tone": "🤘🏽",
+2134	    "six-thirty": "🕡",
+2135	    "six_o’clock": "🕕",
+2136	    "skateboard": "🛹",
+2137	    "skier": "⛷",
+2138	    "skis": "🎿",
+2139	    "skull": "💀",
+2140	    "skull_and_crossbones": "☠",
+2141	    "skunk": "🦨",
+2142	    "sled": "🛷",
+2143	    "sleeping_face": "😴",
+2144	    "sleepy_face": "😪",
+2145	    "slightly_frowning_face": "🙁",
+2146	    "slightly_smiling_face": "🙂",
+2147	    "slot_machine": "🎰",
+2148	    "sloth": "🦥",
+2149	    "small_airplane": "🛩",
+2150	    "small_blue_diamond": "🔹",
+2151	    "small_orange_diamond": "🔸",
+2152	    "smiling_cat_face_with_heart-eyes": "😻",
+2153	    "smiling_face": "☺",
+2154	    "smiling_face_with_halo": "😇",
+2155	    "smiling_face_with_3_hearts": "🥰",
+2156	    "smiling_face_with_heart-eyes": "😍",
+2157	    "smiling_face_with_horns": "😈",
+2158	    "smiling_face_with_smiling_eyes": "😊",
+2159	    "smiling_face_with_sunglasses": "😎",
+2160	    "smirking_face": "😏",
+2161	    "snail": "🐌",
+2162	    "snake": "🐍",
+2163	    "sneezing_face": "🤧",
+2164	    "snow-capped_mountain": "🏔",
+2165	    "snowboarder": "🏂",
+2166	    "snowboarder_dark_skin_tone": "🏂🏿",
+2167	    "snowboarder_light_skin_tone": "🏂🏻",
+2168	    "snowboarder_medium-dark_skin_tone": "🏂🏾",
+2169	    "snowboarder_medium-light_skin_tone": "🏂🏼",
+2170	    "snowboarder_medium_skin_tone": "🏂🏽",
+2171	    "snowflake": "❄",
+2172	    "snowman": "☃",
+2173	    "snowman_without_snow": "⛄",
+2174	    "soap": "🧼",
+2175	    "soccer_ball": "⚽",
+2176	    "socks": "🧦",
+2177	    "softball": "🥎",
+2178	    "soft_ice_cream": "🍦",
+2179	    "spade_suit": "♠",
+2180	    "spaghetti": "🍝",
+2181	    "sparkle": "❇",
+2182	    "sparkler": "🎇",
+2183	    "sparkles": "✨",
+2184	    "sparkling_heart": "💖",
+2185	    "speak-no-evil_monkey": "🙊",
+2186	    "speaker_high_volume": "🔊",
+2187	    "speaker_low_volume": "🔈",
+2188	    "speaker_medium_volume": "🔉",
+2189	    "speaking_head": "🗣",
+2190	    "speech_balloon": "💬",
+2191	    "speedboat": "🚤",
+2192	    "spider": "🕷",
+2193	    "spider_web": "🕸",
+2194	    "spiral_calendar": "🗓",
+2195	    "spiral_notepad": "🗒",
+2196	    "spiral_shell": "🐚",
+2197	    "spoon": "🥄",
+2198	    "sponge": "🧽",
+2199	    "sport_utility_vehicle": "🚙",
+2200	    "sports_medal": "🏅",
+2201	    "spouting_whale": "🐳",
+2202	    "squid": "🦑",
+2203	    "squinting_face_with_tongue": "😝",
+2204	    "stadium": "🏟",
+2205	    "star-struck": "🤩",
+2206	    "star_and_crescent": "☪",
+2207	    "star_of_david": "✡",
+2208	    "station": "🚉",
+2209	    "steaming_bowl": "🍜",
+2210	    "stethoscope": "🩺",
+2211	    "stop_button": "⏹",
+2212	    "stop_sign": "🛑",
+2213	    "stopwatch": "⏱",
+2214	    "straight_ruler": "📏",
+2215	    "strawberry": "🍓",
+2216	    "studio_microphone": "🎙",
+2217	    "stuffed_flatbread": "🥙",
+2218	    "sun": "☀",
+2219	    "sun_behind_cloud": "⛅",
+2220	    "sun_behind_large_cloud": "🌥",
+2221	    "sun_behind_rain_cloud": "🌦",
+2222	    "sun_behind_small_cloud": "🌤",
+2223	    "sun_with_face": "🌞",
+2224	    "sunflower": "🌻",
+2225	    "sunglasses": "😎",
+2226	    "sunrise": "🌅",
+2227	    "sunrise_over_mountains": "🌄",
+2228	    "sunset": "🌇",
+2229	    "superhero": "🦸",
+2230	    "supervillain": "🦹",
+2231	    "sushi": "🍣",
+2232	    "suspension_railway": "🚟",
+2233	    "swan": "🦢",
+2234	    "sweat_droplets": "💦",
+2235	    "synagogue": "🕍",
+2236	    "syringe": "💉",
+2237	    "t-shirt": "👕",
+2238	    "taco": "🌮",
+2239	    "takeout_box": "🥡",
+2240	    "tanabata_tree": "🎋",
+2241	    "tangerine": "🍊",
+2242	    "taxi": "🚕",
+2243	    "teacup_without_handle": "🍵",
+2244	    "tear-off_calendar": "📆",
+2245	    "teddy_bear": "🧸",
+2246	    "telephone": "☎",
+2247	    "telephone_receiver": "📞",
+2248	    "telescope": "🔭",
+2249	    "television": "📺",
+2250	    "ten-thirty": "🕥",
+2251	    "ten_o’clock": "🕙",
+2252	    "tennis": "🎾",
+2253	    "tent": "⛺",
+2254	    "test_tube": "🧪",
+2255	    "thermometer": "🌡",
+2256	    "thinking_face": "🤔",
+2257	    "thought_balloon": "💭",
+2258	    "thread": "🧵",
+2259	    "three-thirty": "🕞",
+2260	    "three_o’clock": "🕒",
+2261	    "thumbs_down": "👎",
+2262	    "thumbs_down_dark_skin_tone": "👎🏿",
+2263	    "thumbs_down_light_skin_tone": "👎🏻",
+2264	    "thumbs_down_medium-dark_skin_tone": "👎🏾",
+2265	    "thumbs_down_medium-light_skin_tone": "👎🏼",
+2266	    "thumbs_down_medium_skin_tone": "👎🏽",
+2267	    "thumbs_up": "👍",
+2268	    "thumbs_up_dark_skin_tone": "👍🏿",
+2269	    "thumbs_up_light_skin_tone": "👍🏻",
+2270	    "thumbs_up_medium-dark_skin_tone": "👍🏾",
+2271	    "thumbs_up_medium-light_skin_tone": "👍🏼",
+2272	    "thumbs_up_medium_skin_tone": "👍🏽",
+2273	    "ticket": "🎫",
+2274	    "tiger": "🐯",
+2275	    "tiger_face": "🐯",
+2276	    "timer_clock": "⏲",
+2277	    "tired_face": "😫",
+2278	    "toolbox": "🧰",
+2279	    "toilet": "🚽",
+2280	    "tomato": "🍅",
+2281	    "tongue": "👅",
+2282	    "tooth": "🦷",
+2283	    "top_hat": "🎩",
+2284	    "tornado": "🌪",
+2285	    "trackball": "🖲",
+2286	    "tractor": "🚜",
+2287	    "trade_mark": "™",
+2288	    "train": "🚋",
+2289	    "tram": "🚊",
+2290	    "tram_car": "🚋",
+2291	    "triangular_flag": "🚩",
+2292	    "triangular_ruler": "📐",
+2293	    "trident_emblem": "🔱",
+2294	    "trolleybus": "🚎",
+2295	    "trophy": "🏆",
+2296	    "tropical_drink": "🍹",
+2297	    "tropical_fish": "🐠",
+2298	    "trumpet": "🎺",
+2299	    "tulip": "🌷",
+2300	    "tumbler_glass": "🥃",
+2301	    "turtle": "🐢",
+2302	    "twelve-thirty": "🕧",
+2303	    "twelve_o’clock": "🕛",
+2304	    "two-hump_camel": "🐫",
+2305	    "two-thirty": "🕝",
+2306	    "two_hearts": "💕",
+2307	    "two_men_holding_hands": "👬",
+2308	    "two_o’clock": "🕑",
+2309	    "two_women_holding_hands": "👭",
+2310	    "umbrella": "☂",
+2311	    "umbrella_on_ground": "⛱",
+2312	    "umbrella_with_rain_drops": "☔",
+2313	    "unamused_face": "😒",
+2314	    "unicorn_face": "🦄",
+2315	    "unlocked": "🔓",
+2316	    "up-down_arrow": "↕",
+2317	    "up-left_arrow": "↖",
+2318	    "up-right_arrow": "↗",
+2319	    "up_arrow": "⬆",
+2320	    "upside-down_face": "🙃",
+2321	    "upwards_button": "🔼",
+2322	    "vampire": "🧛",
+2323	    "vampire_dark_skin_tone": "🧛🏿",
+2324	    "vampire_light_skin_tone": "🧛🏻",
+2325	    "vampire_medium-dark_skin_tone": "🧛🏾",
+2326	    "vampire_medium-light_skin_tone": "🧛🏼",
+2327	    "vampire_medium_skin_tone": "🧛🏽",
+2328	    "vertical_traffic_light": "🚦",
+2329	    "vibration_mode": "📳",
+2330	    "victory_hand": "✌",
+2331	    "victory_hand_dark_skin_tone": "✌🏿",
+2332	    "victory_hand_light_skin_tone": "✌🏻",
+2333	    "victory_hand_medium-dark_skin_tone": "✌🏾",
+2334	    "victory_hand_medium-light_skin_tone": "✌🏼",
+2335	    "victory_hand_medium_skin_tone": "✌🏽",
+2336	    "video_camera": "📹",
+2337	    "video_game": "🎮",
+2338	    "videocassette": "📼",
+2339	    "violin": "🎻",
+2340	    "volcano": "🌋",
+2341	    "volleyball": "🏐",
+2342	    "vulcan_salute": "🖖",
+2343	    "vulcan_salute_dark_skin_tone": "🖖🏿",
+2344	    "vulcan_salute_light_skin_tone": "🖖🏻",
+2345	    "vulcan_salute_medium-dark_skin_tone": "🖖🏾",
+2346	    "vulcan_salute_medium-light_skin_tone": "🖖🏼",
+2347	    "vulcan_salute_medium_skin_tone": "🖖🏽",
+2348	    "waffle": "🧇",
+2349	    "waning_crescent_moon": "🌘",
+2350	    "waning_gibbous_moon": "🌖",
+2351	    "warning": "⚠",
+2352	    "wastebasket": "🗑",
+2353	    "watch": "⌚",
+2354	    "water_buffalo": "🐃",
+2355	    "water_closet": "🚾",
+2356	    "water_wave": "🌊",
+2357	    "watermelon": "🍉",
+2358	    "waving_hand": "👋",
+2359	    "waving_hand_dark_skin_tone": "👋🏿",
+2360	    "waving_hand_light_skin_tone": "👋🏻",
+2361	    "waving_hand_medium-dark_skin_tone": "👋🏾",
+2362	    "waving_hand_medium-light_skin_tone": "👋🏼",
+2363	    "waving_hand_medium_skin_tone": "👋🏽",
+2364	    "wavy_dash": "〰",
+2365	    "waxing_crescent_moon": "🌒",
+2366	    "waxing_gibbous_moon": "🌔",
+2367	    "weary_cat_face": "🙀",
+2368	    "weary_face": "😩",
+2369	    "wedding": "💒",
+2370	    "whale": "🐳",
+2371	    "wheel_of_dharma": "☸",
+2372	    "wheelchair_symbol": "♿",
+2373	    "white_circle": "⚪",
+2374	    "white_exclamation_mark": "❕",
+2375	    "white_flag": "🏳",
+2376	    "white_flower": "💮",
+2377	    "white_hair": "🦳",
+2378	    "white-haired_man": "👨\u200d🦳",
+2379	    "white-haired_woman": "👩\u200d🦳",
+2380	    "white_heart": "🤍",
+2381	    "white_heavy_check_mark": "✅",
+2382	    "white_large_square": "⬜",
+2383	    "white_medium-small_square": "◽",
+2384	    "white_medium_square": "◻",
+2385	    "white_medium_star": "⭐",
+2386	    "white_question_mark": "❔",
+2387	    "white_small_square": "▫",
+2388	    "white_square_button": "🔳",
+2389	    "wilted_flower": "🥀",
+2390	    "wind_chime": "🎐",
+2391	    "wind_face": "🌬",
+2392	    "wine_glass": "🍷",
+2393	    "winking_face": "😉",
+2394	    "winking_face_with_tongue": "😜",
+2395	    "wolf_face": "🐺",
+2396	    "woman": "👩",
+2397	    "woman_artist": "👩\u200d🎨",
+2398	    "woman_artist_dark_skin_tone": "👩🏿\u200d🎨",
+2399	    "woman_artist_light_skin_tone": "👩🏻\u200d🎨",
+2400	    "woman_artist_medium-dark_skin_tone": "👩🏾\u200d🎨",
+2401	    "woman_artist_medium-light_skin_tone": "👩🏼\u200d🎨",
+2402	    "woman_artist_medium_skin_tone": "👩🏽\u200d🎨",
+2403	    "woman_astronaut": "👩\u200d🚀",
+2404	    "woman_astronaut_dark_skin_tone": "👩🏿\u200d🚀",
+2405	    "woman_astronaut_light_skin_tone": "👩🏻\u200d🚀",
+2406	    "woman_astronaut_medium-dark_skin_tone": "👩🏾\u200d🚀",
+2407	    "woman_astronaut_medium-light_skin_tone": "👩🏼\u200d🚀",
+2408	    "woman_astronaut_medium_skin_tone": "👩🏽\u200d🚀",
+2409	    "woman_biking": "🚴\u200d♀️",
+2410	    "woman_biking_dark_skin_tone": "🚴🏿\u200d♀️",
+2411	    "woman_biking_light_skin_tone": "🚴🏻\u200d♀️",
+2412	    "woman_biking_medium-dark_skin_tone": "🚴🏾\u200d♀️",
+2413	    "woman_biking_medium-light_skin_tone": "🚴🏼\u200d♀️",
+2414	    "woman_biking_medium_skin_tone": "🚴🏽\u200d♀️",
+2415	    "woman_bouncing_ball": "⛹️\u200d♀️",
+2416	    "woman_bouncing_ball_dark_skin_tone": "⛹🏿\u200d♀️",
+2417	    "woman_bouncing_ball_light_skin_tone": "⛹🏻\u200d♀️",
+2418	    "woman_bouncing_ball_medium-dark_skin_tone": "⛹🏾\u200d♀️",
+2419	    "woman_bouncing_ball_medium-light_skin_tone": "⛹🏼\u200d♀️",
+2420	    "woman_bouncing_ball_medium_skin_tone": "⛹🏽\u200d♀️",
+2421	    "woman_bowing": "🙇\u200d♀️",
+2422	    "woman_bowing_dark_skin_tone": "🙇🏿\u200d♀️",
+2423	    "woman_bowing_light_skin_tone": "🙇🏻\u200d♀️",
+2424	    "woman_bowing_medium-dark_skin_tone": "🙇🏾\u200d♀️",
+2425	    "woman_bowing_medium-light_skin_tone": "🙇🏼\u200d♀️",
+2426	    "woman_bowing_medium_skin_tone": "🙇🏽\u200d♀️",
+2427	    "woman_cartwheeling": "🤸\u200d♀️",
+2428	    "woman_cartwheeling_dark_skin_tone": "🤸🏿\u200d♀️",
+2429	    "woman_cartwheeling_light_skin_tone": "🤸🏻\u200d♀️",
+2430	    "woman_cartwheeling_medium-dark_skin_tone": "🤸🏾\u200d♀️",
+2431	    "woman_cartwheeling_medium-light_skin_tone": "🤸🏼\u200d♀️",
+2432	    "woman_cartwheeling_medium_skin_tone": "🤸🏽\u200d♀️",
+2433	    "woman_climbing": "🧗\u200d♀️",
+2434	    "woman_climbing_dark_skin_tone": "🧗🏿\u200d♀️",
+2435	    "woman_climbing_light_skin_tone": "🧗🏻\u200d♀️",
+2436	    "woman_climbing_medium-dark_skin_tone": "🧗🏾\u200d♀️",
+2437	    "woman_climbing_medium-light_skin_tone": "🧗🏼\u200d♀️",
+2438	    "woman_climbing_medium_skin_tone": "🧗🏽\u200d♀️",
+2439	    "woman_construction_worker": "👷\u200d♀️",
+2440	    "woman_construction_worker_dark_skin_tone": "👷🏿\u200d♀️",
+2441	    "woman_construction_worker_light_skin_tone": "👷🏻\u200d♀️",
+2442	    "woman_construction_worker_medium-dark_skin_tone": "👷🏾\u200d♀️",
+2443	    "woman_construction_worker_medium-light_skin_tone": "👷🏼\u200d♀️",
+2444	    "woman_construction_worker_medium_skin_tone": "👷🏽\u200d♀️",
+2445	    "woman_cook": "👩\u200d🍳",
+2446	    "woman_cook_dark_skin_tone": "👩🏿\u200d🍳",
+2447	    "woman_cook_light_skin_tone": "👩🏻\u200d🍳",
+2448	    "woman_cook_medium-dark_skin_tone": "👩🏾\u200d🍳",
+2449	    "woman_cook_medium-light_skin_tone": "👩🏼\u200d🍳",
+2450	    "woman_cook_medium_skin_tone": "👩🏽\u200d🍳",
+2451	    "woman_dancing": "💃",
+2452	    "woman_dancing_dark_skin_tone": "💃🏿",
+2453	    "woman_dancing_light_skin_tone": "💃🏻",
+2454	    "woman_dancing_medium-dark_skin_tone": "💃🏾",
+2455	    "woman_dancing_medium-light_skin_tone": "💃🏼",
+2456	    "woman_dancing_medium_skin_tone": "💃🏽",
+2457	    "woman_dark_skin_tone": "👩🏿",
+2458	    "woman_detective": "🕵️\u200d♀️",
+2459	    "woman_detective_dark_skin_tone": "🕵🏿\u200d♀️",
+2460	    "woman_detective_light_skin_tone": "🕵🏻\u200d♀️",
+2461	    "woman_detective_medium-dark_skin_tone": "🕵🏾\u200d♀️",
+2462	    "woman_detective_medium-light_skin_tone": "🕵🏼\u200d♀️",
+2463	    "woman_detective_medium_skin_tone": "🕵🏽\u200d♀️",
+2464	    "woman_elf": "🧝\u200d♀️",
+2465	    "woman_elf_dark_skin_tone": "🧝🏿\u200d♀️",
+2466	    "woman_elf_light_skin_tone": "🧝🏻\u200d♀️",
+2467	    "woman_elf_medium-dark_skin_tone": "🧝🏾\u200d♀️",
+2468	    "woman_elf_medium-light_skin_tone": "🧝🏼\u200d♀️",
+2469	    "woman_elf_medium_skin_tone": "🧝🏽\u200d♀️",
+2470	    "woman_facepalming": "🤦\u200d♀️",
+2471	    "woman_facepalming_dark_skin_tone": "🤦🏿\u200d♀️",
+2472	    "woman_facepalming_light_skin_tone": "🤦🏻\u200d♀️",
+2473	    "woman_facepalming_medium-dark_skin_tone": "🤦🏾\u200d♀️",
+2474	    "woman_facepalming_medium-light_skin_tone": "🤦🏼\u200d♀️",
+2475	    "woman_facepalming_medium_skin_tone": "🤦🏽\u200d♀️",
+2476	    "woman_factory_worker": "👩\u200d🏭",
+2477	    "woman_factory_worker_dark_skin_tone": "👩🏿\u200d🏭",
+2478	    "woman_factory_worker_light_skin_tone": "👩🏻\u200d🏭",
+2479	    "woman_factory_worker_medium-dark_skin_tone": "👩🏾\u200d🏭",
+2480	    "woman_factory_worker_medium-light_skin_tone": "👩🏼\u200d🏭",
+2481	    "woman_factory_worker_medium_skin_tone": "👩🏽\u200d🏭",
+2482	    "woman_fairy": "🧚\u200d♀️",
+2483	    "woman_fairy_dark_skin_tone": "🧚🏿\u200d♀️",
+2484	    "woman_fairy_light_skin_tone": "🧚🏻\u200d♀️",
+2485	    "woman_fairy_medium-dark_skin_tone": "🧚🏾\u200d♀️",
+2486	    "woman_fairy_medium-light_skin_tone": "🧚🏼\u200d♀️",
+2487	    "woman_fairy_medium_skin_tone": "🧚🏽\u200d♀️",
+2488	    "woman_farmer": "👩\u200d🌾",
+2489	    "woman_farmer_dark_skin_tone": "👩🏿\u200d🌾",
+2490	    "woman_farmer_light_skin_tone": "👩🏻\u200d🌾",
+2491	    "woman_farmer_medium-dark_skin_tone": "👩🏾\u200d🌾",
+2492	    "woman_farmer_medium-light_skin_tone": "👩🏼\u200d🌾",
+2493	    "woman_farmer_medium_skin_tone": "👩🏽\u200d🌾",
+2494	    "woman_firefighter": "👩\u200d🚒",
+2495	    "woman_firefighter_dark_skin_tone": "👩🏿\u200d🚒",
+2496	    "woman_firefighter_light_skin_tone": "👩🏻\u200d🚒",
+2497	    "woman_firefighter_medium-dark_skin_tone": "👩🏾\u200d🚒",
+2498	    "woman_firefighter_medium-light_skin_tone": "👩🏼\u200d🚒",
+2499	    "woman_firefighter_medium_skin_tone": "👩🏽\u200d🚒",
+2500	    "woman_frowning": "🙍\u200d♀️",
+2501	    "woman_frowning_dark_skin_tone": "🙍🏿\u200d♀️",
+2502	    "woman_frowning_light_skin_tone": "🙍🏻\u200d♀️",
+2503	    "woman_frowning_medium-dark_skin_tone": "🙍🏾\u200d♀️",
+2504	    "woman_frowning_medium-light_skin_tone": "🙍🏼\u200d♀️",
+2505	    "woman_frowning_medium_skin_tone": "🙍🏽\u200d♀️",
+2506	    "woman_genie": "🧞\u200d♀️",
+2507	    "woman_gesturing_no": "🙅\u200d♀️",
+2508	    "woman_gesturing_no_dark_skin_tone": "🙅🏿\u200d♀️",
+2509	    "woman_gesturing_no_light_skin_tone": "🙅🏻\u200d♀️",
+2510	    "woman_gesturing_no_medium-dark_skin_tone": "🙅🏾\u200d♀️",
+2511	    "woman_gesturing_no_medium-light_skin_tone": "🙅🏼\u200d♀️",
+2512	    "woman_gesturing_no_medium_skin_tone": "🙅🏽\u200d♀️",
+2513	    "woman_gesturing_ok": "🙆\u200d♀️",
+2514	    "woman_gesturing_ok_dark_skin_tone": "🙆🏿\u200d♀️",
+2515	    "woman_gesturing_ok_light_skin_tone": "🙆🏻\u200d♀️",
+2516	    "woman_gesturing_ok_medium-dark_skin_tone": "🙆🏾\u200d♀️",
+2517	    "woman_gesturing_ok_medium-light_skin_tone": "🙆🏼\u200d♀️",
+2518	    "woman_gesturing_ok_medium_skin_tone": "🙆🏽\u200d♀️",
+2519	    "woman_getting_haircut": "💇\u200d♀️",
+2520	    "woman_getting_haircut_dark_skin_tone": "💇🏿\u200d♀️",
+2521	    "woman_getting_haircut_light_skin_tone": "💇🏻\u200d♀️",
+2522	    "woman_getting_haircut_medium-dark_skin_tone": "💇🏾\u200d♀️",
+2523	    "woman_getting_haircut_medium-light_skin_tone": "💇🏼\u200d♀️",
+2524	    "woman_getting_haircut_medium_skin_tone": "💇🏽\u200d♀️",
+2525	    "woman_getting_massage": "💆\u200d♀️",
+2526	    "woman_getting_massage_dark_skin_tone": "💆🏿\u200d♀️",
+2527	    "woman_getting_massage_light_skin_tone": "💆🏻\u200d♀️",
+2528	    "woman_getting_massage_medium-dark_skin_tone": "💆🏾\u200d♀️",
+2529	    "woman_getting_massage_medium-light_skin_tone": "💆🏼\u200d♀️",
+2530	    "woman_getting_massage_medium_skin_tone": "💆🏽\u200d♀️",
+2531	    "woman_golfing": "🏌️\u200d♀️",
+2532	    "woman_golfing_dark_skin_tone": "🏌🏿\u200d♀️",
+2533	    "woman_golfing_light_skin_tone": "🏌🏻\u200d♀️",
+2534	    "woman_golfing_medium-dark_skin_tone": "🏌🏾\u200d♀️",
+2535	    "woman_golfing_medium-light_skin_tone": "🏌🏼\u200d♀️",
+2536	    "woman_golfing_medium_skin_tone": "🏌🏽\u200d♀️",
+2537	    "woman_guard": "💂\u200d♀️",
+2538	    "woman_guard_dark_skin_tone": "💂🏿\u200d♀️",
+2539	    "woman_guard_light_skin_tone": "💂🏻\u200d♀️",
+2540	    "woman_guard_medium-dark_skin_tone": "💂🏾\u200d♀️",
+2541	    "woman_guard_medium-light_skin_tone": "💂🏼\u200d♀️",
+2542	    "woman_guard_medium_skin_tone": "💂🏽\u200d♀️",
+2543	    "woman_health_worker": "👩\u200d⚕️",
+2544	    "woman_health_worker_dark_skin_tone": "👩🏿\u200d⚕️",
+2545	    "woman_health_worker_light_skin_tone": "👩🏻\u200d⚕️",
+2546	    "woman_health_worker_medium-dark_skin_tone": "👩🏾\u200d⚕️",
+2547	    "woman_health_worker_medium-light_skin_tone": "👩🏼\u200d⚕️",
+2548	    "woman_health_worker_medium_skin_tone": "👩🏽\u200d⚕️",
+2549	    "woman_in_lotus_position": "🧘\u200d♀️",
+2550	    "woman_in_lotus_position_dark_skin_tone": "🧘🏿\u200d♀️",
+2551	    "woman_in_lotus_position_light_skin_tone": "🧘🏻\u200d♀️",
+2552	    "woman_in_lotus_position_medium-dark_skin_tone": "🧘🏾\u200d♀️",
+2553	    "woman_in_lotus_position_medium-light_skin_tone": "🧘🏼\u200d♀️",
+2554	    "woman_in_lotus_position_medium_skin_tone": "🧘🏽\u200d♀️",
+2555	    "woman_in_manual_wheelchair": "👩\u200d🦽",
+2556	    "woman_in_motorized_wheelchair": "👩\u200d🦼",
+2557	    "woman_in_steamy_room": "🧖\u200d♀️",
+2558	    "woman_in_steamy_room_dark_skin_tone": "🧖🏿\u200d♀️",
+2559	    "woman_in_steamy_room_light_skin_tone": "🧖🏻\u200d♀️",
+2560	    "woman_in_steamy_room_medium-dark_skin_tone": "🧖🏾\u200d♀️",
+2561	    "woman_in_steamy_room_medium-light_skin_tone": "🧖🏼\u200d♀️",
+2562	    "woman_in_steamy_room_medium_skin_tone": "🧖🏽\u200d♀️",
+2563	    "woman_judge": "👩\u200d⚖️",
+2564	    "woman_judge_dark_skin_tone": "👩🏿\u200d⚖️",
+2565	    "woman_judge_light_skin_tone": "👩🏻\u200d⚖️",
+2566	    "woman_judge_medium-dark_skin_tone": "👩🏾\u200d⚖️",
+2567	    "woman_judge_medium-light_skin_tone": "👩🏼\u200d⚖️",
+2568	    "woman_judge_medium_skin_tone": "👩🏽\u200d⚖️",
+2569	    "woman_juggling": "🤹\u200d♀️",
+2570	    "woman_juggling_dark_skin_tone": "🤹🏿\u200d♀️",
+2571	    "woman_juggling_light_skin_tone": "🤹🏻\u200d♀️",
+2572	    "woman_juggling_medium-dark_skin_tone": "🤹🏾\u200d♀️",
+2573	    "woman_juggling_medium-light_skin_tone": "🤹🏼\u200d♀️",
+2574	    "woman_juggling_medium_skin_tone": "🤹🏽\u200d♀️",
+2575	    "woman_lifting_weights": "🏋️\u200d♀️",
+2576	    "woman_lifting_weights_dark_skin_tone": "🏋🏿\u200d♀️",
+2577	    "woman_lifting_weights_light_skin_tone": "🏋🏻\u200d♀️",
+2578	    "woman_lifting_weights_medium-dark_skin_tone": "🏋🏾\u200d♀️",
+2579	    "woman_lifting_weights_medium-light_skin_tone": "🏋🏼\u200d♀️",
+2580	    "woman_lifting_weights_medium_skin_tone": "🏋🏽\u200d♀️",
+2581	    "woman_light_skin_tone": "👩🏻",
+2582	    "woman_mage": "🧙\u200d♀️",
+2583	    "woman_mage_dark_skin_tone": "🧙🏿\u200d♀️",
+2584	    "woman_mage_light_skin_tone": "🧙🏻\u200d♀️",
+2585	    "woman_mage_medium-dark_skin_tone": "🧙🏾\u200d♀️",
+2586	    "woman_mage_medium-light_skin_tone": "🧙🏼\u200d♀️",
+2587	    "woman_mage_medium_skin_tone": "🧙🏽\u200d♀️",
+2588	    "woman_mechanic": "👩\u200d🔧",
+2589	    "woman_mechanic_dark_skin_tone": "👩🏿\u200d🔧",
+2590	    "woman_mechanic_light_skin_tone": "👩🏻\u200d🔧",
+2591	    "woman_mechanic_medium-dark_skin_tone": "👩🏾\u200d🔧",
+2592	    "woman_mechanic_medium-light_skin_tone": "👩🏼\u200d🔧",
+2593	    "woman_mechanic_medium_skin_tone": "👩🏽\u200d🔧",
+2594	    "woman_medium-dark_skin_tone": "👩🏾",
+2595	    "woman_medium-light_skin_tone": "👩🏼",
+2596	    "woman_medium_skin_tone": "👩🏽",
+2597	    "woman_mountain_biking": "🚵\u200d♀️",
+2598	    "woman_mountain_biking_dark_skin_tone": "🚵🏿\u200d♀️",
+2599	    "woman_mountain_biking_light_skin_tone": "🚵🏻\u200d♀️",
+2600	    "woman_mountain_biking_medium-dark_skin_tone": "🚵🏾\u200d♀️",
+2601	    "woman_mountain_biking_medium-light_skin_tone": "🚵🏼\u200d♀️",
+2602	    "woman_mountain_biking_medium_skin_tone": "🚵🏽\u200d♀️",
+2603	    "woman_office_worker": "👩\u200d💼",
+2604	    "woman_office_worker_dark_skin_tone": "👩🏿\u200d💼",
+2605	    "woman_office_worker_light_skin_tone": "👩🏻\u200d💼",
+2606	    "woman_office_worker_medium-dark_skin_tone": "👩🏾\u200d💼",
+2607	    "woman_office_worker_medium-light_skin_tone": "👩🏼\u200d💼",
+2608	    "woman_office_worker_medium_skin_tone": "👩🏽\u200d💼",
+2609	    "woman_pilot": "👩\u200d✈️",
+2610	    "woman_pilot_dark_skin_tone": "👩🏿\u200d✈️",
+2611	    "woman_pilot_light_skin_tone": "👩🏻\u200d✈️",
+2612	    "woman_pilot_medium-dark_skin_tone": "👩🏾\u200d✈️",
+2613	    "woman_pilot_medium-light_skin_tone": "👩🏼\u200d✈️",
+2614	    "woman_pilot_medium_skin_tone": "👩🏽\u200d✈️",
+2615	    "woman_playing_handball": "🤾\u200d♀️",
+2616	    "woman_playing_handball_dark_skin_tone": "🤾🏿\u200d♀️",
+2617	    "woman_playing_handball_light_skin_tone": "🤾🏻\u200d♀️",
+2618	    "woman_playing_handball_medium-dark_skin_tone": "🤾🏾\u200d♀️",
+2619	    "woman_playing_handball_medium-light_skin_tone": "🤾🏼\u200d♀️",
+2620	    "woman_playing_handball_medium_skin_tone": "🤾🏽\u200d♀️",
+2621	    "woman_playing_water_polo": "🤽\u200d♀️",
+2622	    "woman_playing_water_polo_dark_skin_tone": "🤽🏿\u200d♀️",
+2623	    "woman_playing_water_polo_light_skin_tone": "🤽🏻\u200d♀️",
+2624	    "woman_playing_water_polo_medium-dark_skin_tone": "🤽🏾\u200d♀️",
+2625	    "woman_playing_water_polo_medium-light_skin_tone": "🤽🏼\u200d♀️",
+2626	    "woman_playing_water_polo_medium_skin_tone": "🤽🏽\u200d♀️",
+2627	    "woman_police_officer": "👮\u200d♀️",
+2628	    "woman_police_officer_dark_skin_tone": "👮🏿\u200d♀️",
+2629	    "woman_police_officer_light_skin_tone": "👮🏻\u200d♀️",
+2630	    "woman_police_officer_medium-dark_skin_tone": "👮🏾\u200d♀️",
+2631	    "woman_police_officer_medium-light_skin_tone": "👮🏼\u200d♀️",
+2632	    "woman_police_officer_medium_skin_tone": "👮🏽\u200d♀️",
+2633	    "woman_pouting": "🙎\u200d♀️",
+2634	    "woman_pouting_dark_skin_tone": "🙎🏿\u200d♀️",
+2635	    "woman_pouting_light_skin_tone": "🙎🏻\u200d♀️",
+2636	    "woman_pouting_medium-dark_skin_tone": "🙎🏾\u200d♀️",
+2637	    "woman_pouting_medium-light_skin_tone": "🙎🏼\u200d♀️",
+2638	    "woman_pouting_medium_skin_tone": "🙎🏽\u200d♀️",
+2639	    "woman_raising_hand": "🙋\u200d♀️",
+2640	    "woman_raising_hand_dark_skin_tone": "🙋🏿\u200d♀️",
+2641	    "woman_raising_hand_light_skin_tone": "🙋🏻\u200d♀️",
+2642	    "woman_raising_hand_medium-dark_skin_tone": "🙋🏾\u200d♀️",
+2643	    "woman_raising_hand_medium-light_skin_tone": "🙋🏼\u200d♀️",
+2644	    "woman_raising_hand_medium_skin_tone": "🙋🏽\u200d♀️",
+2645	    "woman_rowing_boat": "🚣\u200d♀️",
+2646	    "woman_rowing_boat_dark_skin_tone": "🚣🏿\u200d♀️",
+2647	    "woman_rowing_boat_light_skin_tone": "🚣🏻\u200d♀️",
+2648	    "woman_rowing_boat_medium-dark_skin_tone": "🚣🏾\u200d♀️",
+2649	    "woman_rowing_boat_medium-light_skin_tone": "🚣🏼\u200d♀️",
+2650	    "woman_rowing_boat_medium_skin_tone": "🚣🏽\u200d♀️",
+2651	    "woman_running": "🏃\u200d♀️",
+2652	    "woman_running_dark_skin_tone": "🏃🏿\u200d♀️",
+2653	    "woman_running_light_skin_tone": "🏃🏻\u200d♀️",
+2654	    "woman_running_medium-dark_skin_tone": "🏃🏾\u200d♀️",
+2655	    "woman_running_medium-light_skin_tone": "🏃🏼\u200d♀️",
+2656	    "woman_running_medium_skin_tone": "🏃🏽\u200d♀️",
+2657	    "woman_scientist": "👩\u200d🔬",
+2658	    "woman_scientist_dark_skin_tone": "👩🏿\u200d🔬",
+2659	    "woman_scientist_light_skin_tone": "👩🏻\u200d🔬",
+2660	    "woman_scientist_medium-dark_skin_tone": "👩🏾\u200d🔬",
+2661	    "woman_scientist_medium-light_skin_tone": "👩🏼\u200d🔬",
+2662	    "woman_scientist_medium_skin_tone": "👩🏽\u200d🔬",
+2663	    "woman_shrugging": "🤷\u200d♀️",
+2664	    "woman_shrugging_dark_skin_tone": "🤷🏿\u200d♀️",
+2665	    "woman_shrugging_light_skin_tone": "🤷🏻\u200d♀️",
+2666	    "woman_shrugging_medium-dark_skin_tone": "🤷🏾\u200d♀️",
+2667	    "woman_shrugging_medium-light_skin_tone": "🤷🏼\u200d♀️",
+2668	    "woman_shrugging_medium_skin_tone": "🤷🏽\u200d♀️",
+2669	    "woman_singer": "👩\u200d🎤",
+2670	    "woman_singer_dark_skin_tone": "👩🏿\u200d🎤",
+2671	    "woman_singer_light_skin_tone": "👩🏻\u200d🎤",
+2672	    "woman_singer_medium-dark_skin_tone": "👩🏾\u200d🎤",
+2673	    "woman_singer_medium-light_skin_tone": "👩🏼\u200d🎤",
+2674	    "woman_singer_medium_skin_tone": "👩🏽\u200d🎤",
+2675	    "woman_student": "👩\u200d🎓",
+2676	    "woman_student_dark_skin_tone": "👩🏿\u200d🎓",
+2677	    "woman_student_light_skin_tone": "👩🏻\u200d🎓",
+2678	    "woman_student_medium-dark_skin_tone": "👩🏾\u200d🎓",
+2679	    "woman_student_medium-light_skin_tone": "👩🏼\u200d🎓",
+2680	    "woman_student_medium_skin_tone": "👩🏽\u200d🎓",
+2681	    "woman_surfing": "🏄\u200d♀️",
+2682	    "woman_surfing_dark_skin_tone": "🏄🏿\u200d♀️",
+2683	    "woman_surfing_light_skin_tone": "🏄🏻\u200d♀️",
+2684	    "woman_surfing_medium-dark_skin_tone": "🏄🏾\u200d♀️",
+2685	    "woman_surfing_medium-light_skin_tone": "🏄🏼\u200d♀️",
+2686	    "woman_surfing_medium_skin_tone": "🏄🏽\u200d♀️",
+2687	    "woman_swimming": "🏊\u200d♀️",
+2688	    "woman_swimming_dark_skin_tone": "🏊🏿\u200d♀️",
+2689	    "woman_swimming_light_skin_tone": "🏊🏻\u200d♀️",
+2690	    "woman_swimming_medium-dark_skin_tone": "🏊🏾\u200d♀️",
+2691	    "woman_swimming_medium-light_skin_tone": "🏊🏼\u200d♀️",
+2692	    "woman_swimming_medium_skin_tone": "🏊🏽\u200d♀️",
+2693	    "woman_teacher": "👩\u200d🏫",
+2694	    "woman_teacher_dark_skin_tone": "👩🏿\u200d🏫",
+2695	    "woman_teacher_light_skin_tone": "👩🏻\u200d🏫",
+2696	    "woman_teacher_medium-dark_skin_tone": "👩🏾\u200d🏫",
+2697	    "woman_teacher_medium-light_skin_tone": "👩🏼\u200d🏫",
+2698	    "woman_teacher_medium_skin_tone": "👩🏽\u200d🏫",
+2699	    "woman_technologist": "👩\u200d💻",
+2700	    "woman_technologist_dark_skin_tone": "👩🏿\u200d💻",
+2701	    "woman_technologist_light_skin_tone": "👩🏻\u200d💻",
+2702	    "woman_technologist_medium-dark_skin_tone": "👩🏾\u200d💻",
+2703	    "woman_technologist_medium-light_skin_tone": "👩🏼\u200d💻",
+2704	    "woman_technologist_medium_skin_tone": "👩🏽\u200d💻",
+2705	    "woman_tipping_hand": "💁\u200d♀️",
+2706	    "woman_tipping_hand_dark_skin_tone": "💁🏿\u200d♀️",
+2707	    "woman_tipping_hand_light_skin_tone": "💁🏻\u200d♀️",
+2708	    "woman_tipping_hand_medium-dark_skin_tone": "💁🏾\u200d♀️",
+2709	    "woman_tipping_hand_medium-light_skin_tone": "💁🏼\u200d♀️",
+2710	    "woman_tipping_hand_medium_skin_tone": "💁🏽\u200d♀️",
+2711	    "woman_vampire": "🧛\u200d♀️",
+2712	    "woman_vampire_dark_skin_tone": "🧛🏿\u200d♀️",
+2713	    "woman_vampire_light_skin_tone": "🧛🏻\u200d♀️",
+2714	    "woman_vampire_medium-dark_skin_tone": "🧛🏾\u200d♀️",
+2715	    "woman_vampire_medium-light_skin_tone": "🧛🏼\u200d♀️",
+2716	    "woman_vampire_medium_skin_tone": "🧛🏽\u200d♀️",
+2717	    "woman_walking": "🚶\u200d♀️",
+2718	    "woman_walking_dark_skin_tone": "🚶🏿\u200d♀️",
+2719	    "woman_walking_light_skin_tone": "🚶🏻\u200d♀️",
+2720	    "woman_walking_medium-dark_skin_tone": "🚶🏾\u200d♀️",
+2721	    "woman_walking_medium-light_skin_tone": "🚶🏼\u200d♀️",
+2722	    "woman_walking_medium_skin_tone": "🚶🏽\u200d♀️",
+2723	    "woman_wearing_turban": "👳\u200d♀️",
+2724	    "woman_wearing_turban_dark_skin_tone": "👳🏿\u200d♀️",
+2725	    "woman_wearing_turban_light_skin_tone": "👳🏻\u200d♀️",
+2726	    "woman_wearing_turban_medium-dark_skin_tone": "👳🏾\u200d♀️",
+2727	    "woman_wearing_turban_medium-light_skin_tone": "👳🏼\u200d♀️",
+2728	    "woman_wearing_turban_medium_skin_tone": "👳🏽\u200d♀️",
+2729	    "woman_with_headscarf": "🧕",
+2730	    "woman_with_headscarf_dark_skin_tone": "🧕🏿",
+2731	    "woman_with_headscarf_light_skin_tone": "🧕🏻",
+2732	    "woman_with_headscarf_medium-dark_skin_tone": "🧕🏾",
+2733	    "woman_with_headscarf_medium-light_skin_tone": "🧕🏼",
+2734	    "woman_with_headscarf_medium_skin_tone": "🧕🏽",
+2735	    "woman_with_probing_cane": "👩\u200d🦯",
+2736	    "woman_zombie": "🧟\u200d♀️",
+2737	    "woman’s_boot": "👢",
+2738	    "woman’s_clothes": "👚",
+2739	    "woman’s_hat": "👒",
+2740	    "woman’s_sandal": "👡",
+2741	    "women_with_bunny_ears": "👯\u200d♀️",
+2742	    "women_wrestling": "🤼\u200d♀️",
+2743	    "women’s_room": "🚺",
+2744	    "woozy_face": "🥴",
+2745	    "world_map": "🗺",
+2746	    "worried_face": "😟",
+2747	    "wrapped_gift": "🎁",
+2748	    "wrench": "🔧",
+2749	    "writing_hand": "✍",
+2750	    "writing_hand_dark_skin_tone": "✍🏿",
+2751	    "writing_hand_light_skin_tone": "✍🏻",
+2752	    "writing_hand_medium-dark_skin_tone": "✍🏾",
+2753	    "writing_hand_medium-light_skin_tone": "✍🏼",
+2754	    "writing_hand_medium_skin_tone": "✍🏽",
+2755	    "yarn": "🧶",
+2756	    "yawning_face": "🥱",
+2757	    "yellow_circle": "🟡",
+2758	    "yellow_heart": "💛",
+2759	    "yellow_square": "🟨",
+2760	    "yen_banknote": "💴",
+2761	    "yo-yo": "🪀",
+2762	    "yin_yang": "☯",
+2763	    "zany_face": "🤪",
+2764	    "zebra": "🦓",
+2765	    "zipper-mouth_face": "🤐",
+2766	    "zombie": "🧟",
+2767	    "zzz": "💤",
+2768	    "åland_islands": "🇦🇽",
+2769	    "keycap_asterisk": "*⃣",
+2770	    "keycap_digit_eight": "8⃣",
+2771	    "keycap_digit_five": "5⃣",
+2772	    "keycap_digit_four": "4⃣",
+2773	    "keycap_digit_nine": "9⃣",
+2774	    "keycap_digit_one": "1⃣",
+2775	    "keycap_digit_seven": "7⃣",
+2776	    "keycap_digit_six": "6⃣",
+2777	    "keycap_digit_three": "3⃣",
+2778	    "keycap_digit_two": "2⃣",
+2779	    "keycap_digit_zero": "0⃣",
+2780	    "keycap_number_sign": "#⃣",
+2781	    "light_skin_tone": "🏻",
+2782	    "medium_light_skin_tone": "🏼",
+2783	    "medium_skin_tone": "🏽",
+2784	    "medium_dark_skin_tone": "🏾",
+2785	    "dark_skin_tone": "🏿",
+2786	    "regional_indicator_symbol_letter_a": "🇦",
+2787	    "regional_indicator_symbol_letter_b": "🇧",
+2788	    "regional_indicator_symbol_letter_c": "🇨",
+2789	    "regional_indicator_symbol_letter_d": "🇩",
+2790	    "regional_indicator_symbol_letter_e": "🇪",
+2791	    "regional_indicator_symbol_letter_f": "🇫",
+2792	    "regional_indicator_symbol_letter_g": "🇬",
+2793	    "regional_indicator_symbol_letter_h": "🇭",
+2794	    "regional_indicator_symbol_letter_i": "🇮",
+2795	    "regional_indicator_symbol_letter_j": "🇯",
+2796	    "regional_indicator_symbol_letter_k": "🇰",
+2797	    "regional_indicator_symbol_letter_l": "🇱",
+2798	    "regional_indicator_symbol_letter_m": "🇲",
+2799	    "regional_indicator_symbol_letter_n": "🇳",
+2800	    "regional_indicator_symbol_letter_o": "🇴",
+2801	    "regional_indicator_symbol_letter_p": "🇵",
+2802	    "regional_indicator_symbol_letter_q": "🇶",
+2803	    "regional_indicator_symbol_letter_r": "🇷",
+2804	    "regional_indicator_symbol_letter_s": "🇸",
+2805	    "regional_indicator_symbol_letter_t": "🇹",
+2806	    "regional_indicator_symbol_letter_u": "🇺",
+2807	    "regional_indicator_symbol_letter_v": "🇻",
+2808	    "regional_indicator_symbol_letter_w": "🇼",
+2809	    "regional_indicator_symbol_letter_x": "🇽",
+2810	    "regional_indicator_symbol_letter_y": "🇾",
+2811	    "regional_indicator_symbol_letter_z": "🇿",
+2812	    "airplane_arriving": "🛬",
+2813	    "space_invader": "👾",
+2814	    "football": "🏈",
+2815	    "anger": "💢",
+2816	    "angry": "😠",
+2817	    "anguished": "😧",
+2818	    "signal_strength": "📶",
+2819	    "arrows_counterclockwise": "🔄",
+2820	    "arrow_heading_down": "⤵",
+2821	    "arrow_heading_up": "⤴",
+2822	    "art": "🎨",
+2823	    "astonished": "😲",
+2824	    "athletic_shoe": "👟",
+2825	    "atm": "🏧",
+2826	    "car": "🚗",
+2827	    "red_car": "🚗",
+2828	    "angel": "👼",
+2829	    "back": "🔙",
+2830	    "badminton_racquet_and_shuttlecock": "🏸",
+2831	    "dollar": "💵",
+2832	    "euro": "💶",
+2833	    "pound": "💷",
+2834	    "yen": "💴",
+2835	    "barber": "💈",
+2836	    "bath": "🛀",
+2837	    "bear": "🐻",
+2838	    "heartbeat": "💓",
+2839	    "beer": "🍺",
+2840	    "no_bell": "🔕",
+2841	    "bento": "🍱",
+2842	    "bike": "🚲",
+2843	    "bicyclist": "🚴",
+2844	    "8ball": "🎱",
+2845	    "biohazard_sign": "☣",
+2846	    "birthday": "🎂",
+2847	    "black_circle_for_record": "⏺",
+2848	    "clubs": "♣",
+2849	    "diamonds": "♦",
+2850	    "arrow_double_down": "⏬",
+2851	    "hearts": "♥",
+2852	    "rewind": "⏪",
+2853	    "black_left__pointing_double_triangle_with_vertical_bar": "⏮",
+2854	    "arrow_backward": "◀",
+2855	    "black_medium_small_square": "◾",
+2856	    "question": "❓",
+2857	    "fast_forward": "⏩",
+2858	    "black_right__pointing_double_triangle_with_vertical_bar": "⏭",
+2859	    "arrow_forward": "▶",
+2860	    "black_right__pointing_triangle_with_double_vertical_bar": "⏯",
+2861	    "arrow_right": "➡",
+2862	    "spades": "♠",
+2863	    "black_square_for_stop": "⏹",
+2864	    "sunny": "☀",
+2865	    "phone": "☎",
+2866	    "recycle": "♻",
+2867	    "arrow_double_up": "⏫",
+2868	    "busstop": "🚏",
+2869	    "date": "📅",
+2870	    "flags": "🎏",
+2871	    "cat2": "🐈",
+2872	    "joy_cat": "😹",
+2873	    "smirk_cat": "😼",
+2874	    "chart_with_downwards_trend": "📉",
+2875	    "chart_with_upwards_trend": "📈",
+2876	    "chart": "💹",
+2877	    "mega": "📣",
+2878	    "checkered_flag": "🏁",
+2879	    "accept": "🉑",
+2880	    "ideograph_advantage": "🉐",
+2881	    "congratulations": "㊗",
+2882	    "secret": "㊙",
+2883	    "m": "Ⓜ",
+2884	    "city_sunset": "🌆",
+2885	    "clapper": "🎬",
+2886	    "clap": "👏",
+2887	    "beers": "🍻",
+2888	    "clock830": "🕣",
+2889	    "clock8": "🕗",
+2890	    "clock1130": "🕦",
+2891	    "clock11": "🕚",
+2892	    "clock530": "🕠",
+2893	    "clock5": "🕔",
+2894	    "clock430": "🕟",
+2895	    "clock4": "🕓",
+2896	    "clock930": "🕤",
+2897	    "clock9": "🕘",
+2898	    "clock130": "🕜",
+2899	    "clock1": "🕐",
+2900	    "clock730": "🕢",
+2901	    "clock7": "🕖",
+2902	    "clock630": "🕡",
+2903	    "clock6": "🕕",
+2904	    "clock1030": "🕥",
+2905	    "clock10": "🕙",
+2906	    "clock330": "🕞",
+2907	    "clock3": "🕒",
+2908	    "clock1230": "🕧",
+2909	    "clock12": "🕛",
+2910	    "clock230": "🕝",
+2911	    "clock2": "🕑",
+2912	    "arrows_clockwise": "🔃",
+2913	    "repeat": "🔁",
+2914	    "repeat_one": "🔂",
+2915	    "closed_lock_with_key": "🔐",
+2916	    "mailbox_closed": "📪",
+2917	    "mailbox": "📫",
+2918	    "cloud_with_tornado": "🌪",
+2919	    "cocktail": "🍸",
+2920	    "boom": "💥",
+2921	    "compression": "🗜",
+2922	    "confounded": "😖",
+2923	    "confused": "😕",
+2924	    "rice": "🍚",
+2925	    "cow2": "🐄",
+2926	    "cricket_bat_and_ball": "🏏",
+2927	    "x": "❌",
+2928	    "cry": "😢",
+2929	    "curry": "🍛",
+2930	    "dagger_knife": "🗡",
+2931	    "dancer": "💃",
+2932	    "dark_sunglasses": "🕶",
+2933	    "dash": "💨",
+2934	    "truck": "🚚",
+2935	    "derelict_house_building": "🏚",
+2936	    "diamond_shape_with_a_dot_inside": "💠",
+2937	    "dart": "🎯",
+2938	    "disappointed_relieved": "😥",
+2939	    "disappointed": "😞",
+2940	    "do_not_litter": "🚯",
+2941	    "dog2": "🐕",
+2942	    "flipper": "🐬",
+2943	    "loop": "➿",
+2944	    "bangbang": "‼",
+2945	    "double_vertical_bar": "⏸",
+2946	    "dove_of_peace": "🕊",
+2947	    "small_red_triangle_down": "🔻",
+2948	    "arrow_down_small": "🔽",
+2949	    "arrow_down": "⬇",
+2950	    "dromedary_camel": "🐪",
+2951	    "e__mail": "📧",
+2952	    "corn": "🌽",
+2953	    "ear_of_rice": "🌾",
+2954	    "earth_americas": "🌎",
+2955	    "earth_asia": "🌏",
+2956	    "earth_africa": "🌍",
+2957	    "eight_pointed_black_star": "✴",
+2958	    "eight_spoked_asterisk": "✳",
+2959	    "eject_symbol": "⏏",
+2960	    "bulb": "💡",
+2961	    "emoji_modifier_fitzpatrick_type__1__2": "🏻",
+2962	    "emoji_modifier_fitzpatrick_type__3": "🏼",
+2963	    "emoji_modifier_fitzpatrick_type__4": "🏽",
+2964	    "emoji_modifier_fitzpatrick_type__5": "🏾",
+2965	    "emoji_modifier_fitzpatrick_type__6": "🏿",
+2966	    "end": "🔚",
+2967	    "email": "✉",
+2968	    "european_castle": "🏰",
+2969	    "european_post_office": "🏤",
+2970	    "interrobang": "⁉",
+2971	    "expressionless": "😑",
+2972	    "eyeglasses": "👓",
+2973	    "massage": "💆",
+2974	    "yum": "😋",
+2975	    "scream": "😱",
+2976	    "kissing_heart": "😘",
+2977	    "sweat": "😓",
+2978	    "face_with_head__bandage": "🤕",
+2979	    "triumph": "😤",
+2980	    "mask": "😷",
+2981	    "no_good": "🙅",
+2982	    "ok_woman": "🙆",
+2983	    "open_mouth": "😮",
+2984	    "cold_sweat": "😰",
+2985	    "stuck_out_tongue": "😛",
+2986	    "stuck_out_tongue_closed_eyes": "😝",
+2987	    "stuck_out_tongue_winking_eye": "😜",
+2988	    "joy": "😂",
+2989	    "no_mouth": "😶",
+2990	    "santa": "🎅",
+2991	    "fax": "📠",
+2992	    "fearful": "😨",
+2993	    "field_hockey_stick_and_ball": "🏑",
+2994	    "first_quarter_moon_with_face": "🌛",
+2995	    "fish_cake": "🍥",
+2996	    "fishing_pole_and_fish": "🎣",
+2997	    "facepunch": "👊",
+2998	    "punch": "👊",
+2999	    "flag_for_afghanistan": "🇦🇫",
+3000	    "flag_for_albania": "🇦🇱",
+3001	    "flag_for_algeria": "🇩🇿",
+3002	    "flag_for_american_samoa": "🇦🇸",
+3003	    "flag_for_andorra": "🇦🇩",
+3004	    "flag_for_angola": "🇦🇴",
+3005	    "flag_for_anguilla": "🇦🇮",
+3006	    "flag_for_antarctica": "🇦🇶",
+3007	    "flag_for_antigua_&_barbuda": "🇦🇬",
+3008	    "flag_for_argentina": "🇦🇷",
+3009	    "flag_for_armenia": "🇦🇲",
+3010	    "flag_for_aruba": "🇦🇼",
+3011	    "flag_for_ascension_island": "🇦🇨",
+3012	    "flag_for_australia": "🇦🇺",
+3013	    "flag_for_austria": "🇦🇹",
+3014	    "flag_for_azerbaijan": "🇦🇿",
+3015	    "flag_for_bahamas": "🇧🇸",
+3016	    "flag_for_bahrain": "🇧🇭",
+3017	    "flag_for_bangladesh": "🇧🇩",
+3018	    "flag_for_barbados": "🇧🇧",
+3019	    "flag_for_belarus": "🇧🇾",
+3020	    "flag_for_belgium": "🇧🇪",
+3021	    "flag_for_belize": "🇧🇿",
+3022	    "flag_for_benin": "🇧🇯",
+3023	    "flag_for_bermuda": "🇧🇲",
+3024	    "flag_for_bhutan": "🇧🇹",
+3025	    "flag_for_bolivia": "🇧🇴",
+3026	    "flag_for_bosnia_&_herzegovina": "🇧🇦",
+3027	    "flag_for_botswana": "🇧🇼",
+3028	    "flag_for_bouvet_island": "🇧🇻",
+3029	    "flag_for_brazil": "🇧🇷",
+3030	    "flag_for_british_indian_ocean_territory": "🇮🇴",
+3031	    "flag_for_british_virgin_islands": "🇻🇬",
+3032	    "flag_for_brunei": "🇧🇳",
+3033	    "flag_for_bulgaria": "🇧🇬",
+3034	    "flag_for_burkina_faso": "🇧🇫",
+3035	    "flag_for_burundi": "🇧🇮",
+3036	    "flag_for_cambodia": "🇰🇭",
+3037	    "flag_for_cameroon": "🇨🇲",
+3038	    "flag_for_canada": "🇨🇦",
+3039	    "flag_for_canary_islands": "🇮🇨",
+3040	    "flag_for_cape_verde": "🇨🇻",
+3041	    "flag_for_caribbean_netherlands": "🇧🇶",
+3042	    "flag_for_cayman_islands": "🇰🇾",
+3043	    "flag_for_central_african_republic": "🇨🇫",
+3044	    "flag_for_ceuta_&_melilla": "🇪🇦",
+3045	    "flag_for_chad": "🇹🇩",
+3046	    "flag_for_chile": "🇨🇱",
+3047	    "flag_for_china": "🇨🇳",
+3048	    "flag_for_christmas_island": "🇨🇽",
+3049	    "flag_for_clipperton_island": "🇨🇵",
+3050	    "flag_for_cocos__islands": "🇨🇨",
+3051	    "flag_for_colombia": "🇨🇴",
+3052	    "flag_for_comoros": "🇰🇲",
+3053	    "flag_for_congo____brazzaville": "🇨🇬",
+3054	    "flag_for_congo____kinshasa": "🇨🇩",
+3055	    "flag_for_cook_islands": "🇨🇰",
+3056	    "flag_for_costa_rica": "🇨🇷",
+3057	    "flag_for_croatia": "🇭🇷",
+3058	    "flag_for_cuba": "🇨🇺",
+3059	    "flag_for_curaçao": "🇨🇼",
+3060	    "flag_for_cyprus": "🇨🇾",
+3061	    "flag_for_czech_republic": "🇨🇿",
+3062	    "flag_for_côte_d’ivoire": "🇨🇮",
+3063	    "flag_for_denmark": "🇩🇰",
+3064	    "flag_for_diego_garcia": "🇩🇬",
+3065	    "flag_for_djibouti": "🇩🇯",
+3066	    "flag_for_dominica": "🇩🇲",
+3067	    "flag_for_dominican_republic": "🇩🇴",
+3068	    "flag_for_ecuador": "🇪🇨",
+3069	    "flag_for_egypt": "🇪🇬",
+3070	    "flag_for_el_salvador": "🇸🇻",
+3071	    "flag_for_equatorial_guinea": "🇬🇶",
+3072	    "flag_for_eritrea": "🇪🇷",
+3073	    "flag_for_estonia": "🇪🇪",
+3074	    "flag_for_ethiopia": "🇪🇹",
+3075	    "flag_for_european_union": "🇪🇺",
+3076	    "flag_for_falkland_islands": "🇫🇰",
+3077	    "flag_for_faroe_islands": "🇫🇴",
+3078	    "flag_for_fiji": "🇫🇯",
+3079	    "flag_for_finland": "🇫🇮",
+3080	    "flag_for_france": "🇫🇷",
+3081	    "flag_for_french_guiana": "🇬🇫",
+3082	    "flag_for_french_polynesia": "🇵🇫",
+3083	    "flag_for_french_southern_territories": "🇹🇫",
+3084	    "flag_for_gabon": "🇬🇦",
+3085	    "flag_for_gambia": "🇬🇲",
+3086	    "flag_for_georgia": "🇬🇪",
+3087	    "flag_for_germany": "🇩🇪",
+3088	    "flag_for_ghana": "🇬🇭",
+3089	    "flag_for_gibraltar": "🇬🇮",
+3090	    "flag_for_greece": "🇬🇷",
+3091	    "flag_for_greenland": "🇬🇱",
+3092	    "flag_for_grenada": "🇬🇩",
+3093	    "flag_for_guadeloupe": "🇬🇵",
+3094	    "flag_for_guam": "🇬🇺",
+3095	    "flag_for_guatemala": "🇬🇹",
+3096	    "flag_for_guernsey": "🇬🇬",
+3097	    "flag_for_guinea": "🇬🇳",
+3098	    "flag_for_guinea__bissau": "🇬🇼",
+3099	    "flag_for_guyana": "🇬🇾",
+3100	    "flag_for_haiti": "🇭🇹",
+3101	    "flag_for_heard_&_mcdonald_islands": "🇭🇲",
+3102	    "flag_for_honduras": "🇭🇳",
+3103	    "flag_for_hong_kong": "🇭🇰",
+3104	    "flag_for_hungary": "🇭🇺",
+3105	    "flag_for_iceland": "🇮🇸",
+3106	    "flag_for_india": "🇮🇳",
+3107	    "flag_for_indonesia": "🇮🇩",
+3108	    "flag_for_iran": "🇮🇷",
+3109	    "flag_for_iraq": "🇮🇶",
+3110	    "flag_for_ireland": "🇮🇪",
+3111	    "flag_for_isle_of_man": "🇮🇲",
+3112	    "flag_for_israel": "🇮🇱",
+3113	    "flag_for_italy": "🇮🇹",
+3114	    "flag_for_jamaica": "🇯🇲",
+3115	    "flag_for_japan": "🇯🇵",
+3116	    "flag_for_jersey": "🇯🇪",
+3117	    "flag_for_jordan": "🇯🇴",
+3118	    "flag_for_kazakhstan": "🇰🇿",
+3119	    "flag_for_kenya": "🇰🇪",
+3120	    "flag_for_kiribati": "🇰🇮",
+3121	    "flag_for_kosovo": "🇽🇰",
+3122	    "flag_for_kuwait": "🇰🇼",
+3123	    "flag_for_kyrgyzstan": "🇰🇬",
+3124	    "flag_for_laos": "🇱🇦",
+3125	    "flag_for_latvia": "🇱🇻",
+3126	    "flag_for_lebanon": "🇱🇧",
+3127	    "flag_for_lesotho": "🇱🇸",
+3128	    "flag_for_liberia": "🇱🇷",
+3129	    "flag_for_libya": "🇱🇾",
+3130	    "flag_for_liechtenstein": "🇱🇮",
+3131	    "flag_for_lithuania": "🇱🇹",
+3132	    "flag_for_luxembourg": "🇱🇺",
+3133	    "flag_for_macau": "🇲🇴",
+3134	    "flag_for_macedonia": "🇲🇰",
+3135	    "flag_for_madagascar": "🇲🇬",
+3136	    "flag_for_malawi": "🇲🇼",
+3137	    "flag_for_malaysia": "🇲🇾",
+3138	    "flag_for_maldives": "🇲🇻",
+3139	    "flag_for_mali": "🇲🇱",
+3140	    "flag_for_malta": "🇲🇹",
+3141	    "flag_for_marshall_islands": "🇲🇭",
+3142	    "flag_for_martinique": "🇲🇶",
+3143	    "flag_for_mauritania": "🇲🇷",
+3144	    "flag_for_mauritius": "🇲🇺",
+3145	    "flag_for_mayotte": "🇾🇹",
+3146	    "flag_for_mexico": "🇲🇽",
+3147	    "flag_for_micronesia": "🇫🇲",
+3148	    "flag_for_moldova": "🇲🇩",
+3149	    "flag_for_monaco": "🇲🇨",
+3150	    "flag_for_mongolia": "🇲🇳",
+3151	    "flag_for_montenegro": "🇲🇪",
+3152	    "flag_for_montserrat": "🇲🇸",
+3153	    "flag_for_morocco": "🇲🇦",
+3154	    "flag_for_mozambique": "🇲🇿",
+3155	    "flag_for_myanmar": "🇲🇲",
+3156	    "flag_for_namibia": "🇳🇦",
+3157	    "flag_for_nauru": "🇳🇷",
+3158	    "flag_for_nepal": "🇳🇵",
+3159	    "flag_for_netherlands": "🇳🇱",
+3160	    "flag_for_new_caledonia": "🇳🇨",
+3161	    "flag_for_new_zealand": "🇳🇿",
+3162	    "flag_for_nicaragua": "🇳🇮",
+3163	    "flag_for_niger": "🇳🇪",
+3164	    "flag_for_nigeria": "🇳🇬",
+3165	    "flag_for_niue": "🇳🇺",
+3166	    "flag_for_norfolk_island": "🇳🇫",
+3167	    "flag_for_north_korea": "🇰🇵",
+3168	    "flag_for_northern_mariana_islands": "🇲🇵",
+3169	    "flag_for_norway": "🇳🇴",
+3170	    "flag_for_oman": "🇴🇲",
+3171	    "flag_for_pakistan": "🇵🇰",
+3172	    "flag_for_palau": "🇵🇼",
+3173	    "flag_for_palestinian_territories": "🇵🇸",
+3174	    "flag_for_panama": "🇵🇦",
+3175	    "flag_for_papua_new_guinea": "🇵🇬",
+3176	    "flag_for_paraguay": "🇵🇾",
+3177	    "flag_for_peru": "🇵🇪",
+3178	    "flag_for_philippines": "🇵🇭",
+3179	    "flag_for_pitcairn_islands": "🇵🇳",
+3180	    "flag_for_poland": "🇵🇱",
+3181	    "flag_for_portugal": "🇵🇹",
+3182	    "flag_for_puerto_rico": "🇵🇷",
+3183	    "flag_for_qatar": "🇶🇦",
+3184	    "flag_for_romania": "🇷🇴",
+3185	    "flag_for_russia": "🇷🇺",
+3186	    "flag_for_rwanda": "🇷🇼",
+3187	    "flag_for_réunion": "🇷🇪",
+3188	    "flag_for_samoa": "🇼🇸",
+3189	    "flag_for_san_marino": "🇸🇲",
+3190	    "flag_for_saudi_arabia": "🇸🇦",
+3191	    "flag_for_senegal": "🇸🇳",
+3192	    "flag_for_serbia": "🇷🇸",
+3193	    "flag_for_seychelles": "🇸🇨",
+3194	    "flag_for_sierra_leone": "🇸🇱",
+3195	    "flag_for_singapore": "🇸🇬",
+3196	    "flag_for_sint_maarten": "🇸🇽",
+3197	    "flag_for_slovakia": "🇸🇰",
+3198	    "flag_for_slovenia": "🇸🇮",
+3199	    "flag_for_solomon_islands": "🇸🇧",
+3200	    "flag_for_somalia": "🇸🇴",
+3201	    "flag_for_south_africa": "🇿🇦",
+3202	    "flag_for_south_georgia_&_south_sandwich_islands": "🇬🇸",
+3203	    "flag_for_south_korea": "🇰🇷",
+3204	    "flag_for_south_sudan": "🇸🇸",
+3205	    "flag_for_spain": "🇪🇸",
+3206	    "flag_for_sri_lanka": "🇱🇰",
+3207	    "flag_for_st._barthélemy": "🇧🇱",
+3208	    "flag_for_st._helena": "🇸🇭",
+3209	    "flag_for_st._kitts_&_nevis": "🇰🇳",
+3210	    "flag_for_st._lucia": "🇱🇨",
+3211	    "flag_for_st._martin": "🇲🇫",
+3212	    "flag_for_st._pierre_&_miquelon": "🇵🇲",
+3213	    "flag_for_st._vincent_&_grenadines": "🇻🇨",
+3214	    "flag_for_sudan": "🇸🇩",
+3215	    "flag_for_suriname": "🇸🇷",
+3216	    "flag_for_svalbard_&_jan_mayen": "🇸🇯",
+3217	    "flag_for_swaziland": "🇸🇿",
+3218	    "flag_for_sweden": "🇸🇪",
+3219	    "flag_for_switzerland": "🇨🇭",
+3220	    "flag_for_syria": "🇸🇾",
+3221	    "flag_for_são_tomé_&_príncipe": "🇸🇹",
+3222	    "flag_for_taiwan": "🇹🇼",
+3223	    "flag_for_tajikistan": "🇹🇯",
+3224	    "flag_for_tanzania": "🇹🇿",
+3225	    "flag_for_thailand": "🇹🇭",
+3226	    "flag_for_timor__leste": "🇹🇱",
+3227	    "flag_for_togo": "🇹🇬",
+3228	    "flag_for_tokelau": "🇹🇰",
+3229	    "flag_for_tonga": "🇹🇴",
+3230	    "flag_for_trinidad_&_tobago": "🇹🇹",
+3231	    "flag_for_tristan_da_cunha": "🇹🇦",
+3232	    "flag_for_tunisia": "🇹🇳",
+3233	    "flag_for_turkey": "🇹🇷",
+3234	    "flag_for_turkmenistan": "🇹🇲",
+3235	    "flag_for_turks_&_caicos_islands": "🇹🇨",
+3236	    "flag_for_tuvalu": "🇹🇻",
+3237	    "flag_for_u.s._outlying_islands": "🇺🇲",
+3238	    "flag_for_u.s._virgin_islands": "🇻🇮",
+3239	    "flag_for_uganda": "🇺🇬",
+3240	    "flag_for_ukraine": "🇺🇦",
+3241	    "flag_for_united_arab_emirates": "🇦🇪",
+3242	    "flag_for_united_kingdom": "🇬🇧",
+3243	    "flag_for_united_states": "🇺🇸",
+3244	    "flag_for_uruguay": "🇺🇾",
+3245	    "flag_for_uzbekistan": "🇺🇿",
+3246	    "flag_for_vanuatu": "🇻🇺",
+3247	    "flag_for_vatican_city": "🇻🇦",
+3248	    "flag_for_venezuela": "🇻🇪",
+3249	    "flag_for_vietnam": "🇻🇳",
+3250	    "flag_for_wallis_&_futuna": "🇼🇫",
+3251	    "flag_for_western_sahara": "🇪🇭",
+3252	    "flag_for_yemen": "🇾🇪",
+3253	    "flag_for_zambia": "🇿🇲",
+3254	    "flag_for_zimbabwe": "🇿🇼",
+3255	    "flag_for_åland_islands": "🇦🇽",
+3256	    "golf": "⛳",
+3257	    "fleur__de__lis": "⚜",
+3258	    "muscle": "💪",
+3259	    "flushed": "😳",
+3260	    "frame_with_picture": "🖼",
+3261	    "fries": "🍟",
+3262	    "frog": "🐸",
+3263	    "hatched_chick": "🐥",
+3264	    "frowning": "😦",
+3265	    "fuelpump": "⛽",
+3266	    "full_moon_with_face": "🌝",
+3267	    "gem": "💎",
+3268	    "star2": "🌟",
+3269	    "golfer": "🏌",
+3270	    "mortar_board": "🎓",
+3271	    "grimacing": "😬",
+3272	    "smile_cat": "😸",
+3273	    "grinning": "😀",
+3274	    "grin": "😁",
+3275	    "heartpulse": "💗",
+3276	    "guardsman": "💂",
+3277	    "haircut": "💇",
+3278	    "hamster": "🐹",
+3279	    "raising_hand": "🙋",
+3280	    "headphones": "🎧",
+3281	    "hear_no_evil": "🙉",
+3282	    "cupid": "💘",
+3283	    "gift_heart": "💝",
+3284	    "heart": "❤",
+3285	    "exclamation": "❗",
+3286	    "heavy_exclamation_mark": "❗",
+3287	    "heavy_heart_exclamation_mark_ornament": "❣",
+3288	    "o": "⭕",
+3289	    "helm_symbol": "⎈",
+3290	    "helmet_with_white_cross": "⛑",
+3291	    "high_heel": "👠",
+3292	    "bullettrain_side": "🚄",
+3293	    "bullettrain_front": "🚅",
+3294	    "high_brightness": "🔆",
+3295	    "zap": "⚡",
+3296	    "hocho": "🔪",
+3297	    "knife": "🔪",
+3298	    "bee": "🐝",
+3299	    "traffic_light": "🚥",
+3300	    "racehorse": "🐎",
+3301	    "coffee": "☕",
+3302	    "hotsprings": "♨",
+3303	    "hourglass": "⌛",
+3304	    "hourglass_flowing_sand": "⏳",
+3305	    "house_buildings": "🏘",
+3306	    "100": "💯",
+3307	    "hushed": "😯",
+3308	    "ice_hockey_stick_and_puck": "🏒",
+3309	    "imp": "👿",
+3310	    "information_desk_person": "💁",
+3311	    "information_source": "ℹ",
+3312	    "capital_abcd": "🔠",
+3313	    "abc": "🔤",
+3314	    "abcd": "🔡",
+3315	    "1234": "🔢",
+3316	    "symbols": "🔣",
+3317	    "izakaya_lantern": "🏮",
+3318	    "lantern": "🏮",
+3319	    "jack_o_lantern": "🎃",
+3320	    "dolls": "🎎",
+3321	    "japanese_goblin": "👺",
+3322	    "japanese_ogre": "👹",
+3323	    "beginner": "🔰",
+3324	    "zero": "0️⃣",
+3325	    "one": "1️⃣",
+3326	    "ten": "🔟",
+3327	    "two": "2️⃣",
+3328	    "three": "3️⃣",
+3329	    "four": "4️⃣",
+3330	    "five": "5️⃣",
+3331	    "six": "6️⃣",
+3332	    "seven": "7️⃣",
+3333	    "eight": "8️⃣",
+3334	    "nine": "9️⃣",
+3335	    "couplekiss": "💏",
+3336	    "kissing_cat": "😽",
+3337	    "kissing": "😗",
+3338	    "kissing_closed_eyes": "😚",
+3339	    "kissing_smiling_eyes": "😙",
+3340	    "beetle": "🐞",
+3341	    "large_blue_circle": "🔵",
+3342	    "last_quarter_moon_with_face": "🌜",
+3343	    "leaves": "🍃",
+3344	    "mag": "🔍",
+3345	    "left_right_arrow": "↔",
+3346	    "leftwards_arrow_with_hook": "↩",
+3347	    "arrow_left": "⬅",
+3348	    "lock": "🔒",
+3349	    "lock_with_ink_pen": "🔏",
+3350	    "sob": "😭",
+3351	    "low_brightness": "🔅",
+3352	    "lower_left_ballpoint_pen": "🖊",
+3353	    "lower_left_crayon": "🖍",
+3354	    "lower_left_fountain_pen": "🖋",
+3355	    "lower_left_paintbrush": "🖌",
+3356	    "mahjong": "🀄",
+3357	    "couple": "👫",
+3358	    "man_in_business_suit_levitating": "🕴",
+3359	    "man_with_gua_pi_mao": "👲",
+3360	    "man_with_turban": "👳",
+3361	    "mans_shoe": "👞",
+3362	    "shoe": "👞",
+3363	    "menorah_with_nine_branches": "🕎",
+3364	    "mens": "🚹",
+3365	    "minidisc": "💽",
+3366	    "iphone": "📱",
+3367	    "calling": "📲",
+3368	    "money__mouth_face": "🤑",
+3369	    "moneybag": "💰",
+3370	    "rice_scene": "🎑",
+3371	    "mountain_bicyclist": "🚵",
+3372	    "mouse2": "🐁",
+3373	    "lips": "👄",
+3374	    "moyai": "🗿",
+3375	    "notes": "🎶",
+3376	    "nail_care": "💅",
+3377	    "ab": "🆎",
+3378	    "negative_squared_cross_mark": "❎",
+3379	    "a": "🅰",
+3380	    "b": "🅱",
+3381	    "o2": "🅾",
+3382	    "parking": "🅿",
+3383	    "new_moon_with_face": "🌚",
+3384	    "no_entry_sign": "🚫",
+3385	    "underage": "🔞",
+3386	    "non__potable_water": "🚱",
+3387	    "arrow_upper_right": "↗",
+3388	    "arrow_upper_left": "↖",
+3389	    "office": "🏢",
+3390	    "older_man": "👴",
+3391	    "older_woman": "👵",
+3392	    "om_symbol": "🕉",
+3393	    "on": "🔛",
+3394	    "book": "📖",
+3395	    "unlock": "🔓",
+3396	    "mailbox_with_no_mail": "📭",
+3397	    "mailbox_with_mail": "📬",
+3398	    "cd": "💿",
+3399	    "tada": "🎉",
+3400	    "feet": "🐾",
+3401	    "walking": "🚶",
+3402	    "pencil2": "✏",
+3403	    "pensive": "😔",
+3404	    "persevere": "😣",
+3405	    "bow": "🙇",
+3406	    "raised_hands": "🙌",
+3407	    "person_with_ball": "⛹",
+3408	    "person_with_blond_hair": "👱",
+3409	    "pray": "🙏",
+3410	    "person_with_pouting_face": "🙎",
+3411	    "computer": "💻",
+3412	    "pig2": "🐖",
+3413	    "hankey": "💩",
+3414	    "poop": "💩",
+3415	    "shit": "💩",
+3416	    "bamboo": "🎍",
+3417	    "gun": "🔫",
+3418	    "black_joker": "🃏",
+3419	    "rotating_light": "🚨",
+3420	    "cop": "👮",
+3421	    "stew": "🍲",
+3422	    "pouch": "👝",
+3423	    "pouting_cat": "😾",
+3424	    "rage": "😡",
+3425	    "put_litter_in_its_place": "🚮",
+3426	    "rabbit2": "🐇",
+3427	    "racing_motorcycle": "🏍",
+3428	    "radioactive_sign": "☢",
+3429	    "fist": "✊",
+3430	    "hand": "✋",
+3431	    "raised_hand_with_fingers_splayed": "🖐",
+3432	    "raised_hand_with_part_between_middle_and_ring_fingers": "🖖",
+3433	    "blue_car": "🚙",
+3434	    "apple": "🍎",
+3435	    "relieved": "😌",
+3436	    "reversed_hand_with_middle_finger_extended": "🖕",
+3437	    "mag_right": "🔎",
+3438	    "arrow_right_hook": "↪",
+3439	    "sweet_potato": "🍠",
+3440	    "robot": "🤖",
+3441	    "rolled__up_newspaper": "🗞",
+3442	    "rowboat": "🚣",
+3443	    "runner": "🏃",
+3444	    "running": "🏃",
+3445	    "running_shirt_with_sash": "🎽",
+3446	    "boat": "⛵",
+3447	    "scales": "⚖",
+3448	    "school_satchel": "🎒",
+3449	    "scorpius": "♏",
+3450	    "see_no_evil": "🙈",
+3451	    "sheep": "🐑",
+3452	    "stars": "🌠",
+3453	    "cake": "🍰",
+3454	    "six_pointed_star": "🔯",
+3455	    "ski": "🎿",
+3456	    "sleeping_accommodation": "🛌",
+3457	    "sleeping": "😴",
+3458	    "sleepy": "😪",
+3459	    "sleuth_or_spy": "🕵",
+3460	    "heart_eyes_cat": "😻",
+3461	    "smiley_cat": "😺",
+3462	    "innocent": "😇",
+3463	    "heart_eyes": "😍",
+3464	    "smiling_imp": "😈",
+3465	    "smiley": "😃",
+3466	    "sweat_smile": "😅",
+3467	    "smile": "😄",
+3468	    "laughing": "😆",
+3469	    "satisfied": "😆",
+3470	    "blush": "😊",
+3471	    "smirk": "😏",
+3472	    "smoking": "🚬",
+3473	    "snow_capped_mountain": "🏔",
+3474	    "soccer": "⚽",
+3475	    "icecream": "🍦",
+3476	    "soon": "🔜",
+3477	    "arrow_lower_right": "↘",
+3478	    "arrow_lower_left": "↙",
+3479	    "speak_no_evil": "🙊",
+3480	    "speaker": "🔈",
+3481	    "mute": "🔇",
+3482	    "sound": "🔉",
+3483	    "loud_sound": "🔊",
+3484	    "speaking_head_in_silhouette": "🗣",
+3485	    "spiral_calendar_pad": "🗓",
+3486	    "spiral_note_pad": "🗒",
+3487	    "shell": "🐚",
+3488	    "sweat_drops": "💦",
+3489	    "u5272": "🈹",
+3490	    "u5408": "🈴",
+3491	    "u55b6": "🈺",
+3492	    "u6307": "🈯",
+3493	    "u6708": "🈷",
+3494	    "u6709": "🈶",
+3495	    "u6e80": "🈵",
+3496	    "u7121": "🈚",
+3497	    "u7533": "🈸",
+3498	    "u7981": "🈲",
+3499	    "u7a7a": "🈳",
+3500	    "cl": "🆑",
+3501	    "cool": "🆒",
+3502	    "free": "🆓",
+3503	    "id": "🆔",
+3504	    "koko": "🈁",
+3505	    "sa": "🈂",
+3506	    "new": "🆕",
+3507	    "ng": "🆖",
+3508	    "ok": "🆗",
+3509	    "sos": "🆘",
+3510	    "up": "🆙",
+3511	    "vs": "🆚",
+3512	    "steam_locomotive": "🚂",
+3513	    "ramen": "🍜",
+3514	    "partly_sunny": "⛅",
+3515	    "city_sunrise": "🌇",
+3516	    "surfer": "🏄",
+3517	    "swimmer": "🏊",
+3518	    "shirt": "👕",
+3519	    "tshirt": "👕",
+3520	    "table_tennis_paddle_and_ball": "🏓",
+3521	    "tea": "🍵",
+3522	    "tv": "📺",
+3523	    "three_button_mouse": "🖱",
+3524	    "+1": "👍",
+3525	    "thumbsup": "👍",
+3526	    "__1": "👎",
+3527	    "-1": "👎",
+3528	    "thumbsdown": "👎",
+3529	    "thunder_cloud_and_rain": "⛈",
+3530	    "tiger2": "🐅",
+3531	    "tophat": "🎩",
+3532	    "top": "🔝",
+3533	    "tm": "™",
+3534	    "train2": "🚆",
+3535	    "triangular_flag_on_post": "🚩",
+3536	    "trident": "🔱",
+3537	    "twisted_rightwards_arrows": "🔀",
+3538	    "unamused": "😒",
+3539	    "small_red_triangle": "🔺",
+3540	    "arrow_up_small": "🔼",
+3541	    "arrow_up_down": "↕",
+3542	    "upside__down_face": "🙃",
+3543	    "arrow_up": "⬆",
+3544	    "v": "✌",
+3545	    "vhs": "📼",
+3546	    "wc": "🚾",
+3547	    "ocean": "🌊",
+3548	    "waving_black_flag": "🏴",
+3549	    "wave": "👋",
+3550	    "waving_white_flag": "🏳",
+3551	    "moon": "🌔",
+3552	    "scream_cat": "🙀",
+3553	    "weary": "😩",
+3554	    "weight_lifter": "🏋",
+3555	    "whale2": "🐋",
+3556	    "wheelchair": "♿",
+3557	    "point_down": "👇",
+3558	    "grey_exclamation": "❕",
+3559	    "white_frowning_face": "☹",
+3560	    "white_check_mark": "✅",
+3561	    "point_left": "👈",
+3562	    "white_medium_small_square": "◽",
+3563	    "star": "⭐",
+3564	    "grey_question": "❔",
+3565	    "point_right": "👉",
+3566	    "relaxed": "☺",
+3567	    "white_sun_behind_cloud": "🌥",
+3568	    "white_sun_behind_cloud_with_rain": "🌦",
+3569	    "white_sun_with_small_cloud": "🌤",
+3570	    "point_up_2": "👆",
+3571	    "point_up": "☝",
+3572	    "wind_blowing_face": "🌬",
+3573	    "wink": "😉",
+3574	    "wolf": "🐺",
+3575	    "dancers": "👯",
+3576	    "boot": "👢",
+3577	    "womans_clothes": "👚",
+3578	    "womans_hat": "👒",
+3579	    "sandal": "👡",
+3580	    "womens": "🚺",
+3581	    "worried": "😟",
+3582	    "gift": "🎁",
+3583	    "zipper__mouth_face": "🤐",
+3584	    "regional_indicator_a": "🇦",
+3585	    "regional_indicator_b": "🇧",
+3586	    "regional_indicator_c": "🇨",
+3587	    "regional_indicator_d": "🇩",
+3588	    "regional_indicator_e": "🇪",
+3589	    "regional_indicator_f": "🇫",
+3590	    "regional_indicator_g": "🇬",
+3591	    "regional_indicator_h": "🇭",
+3592	    "regional_indicator_i": "🇮",
+3593	    "regional_indicator_j": "🇯",
+3594	    "regional_indicator_k": "🇰",
+3595	    "regional_indicator_l": "🇱",
+3596	    "regional_indicator_m": "🇲",
+3597	    "regional_indicator_n": "🇳",
+3598	    "regional_indicator_o": "🇴",
+3599	    "regional_indicator_p": "🇵",
+3600	    "regional_indicator_q": "🇶",
+3601	    "regional_indicator_r": "🇷",
+3602	    "regional_indicator_s": "🇸",
+3603	    "regional_indicator_t": "🇹",
+3604	    "regional_indicator_u": "🇺",
+3605	    "regional_indicator_v": "🇻",
+3606	    "regional_indicator_w": "🇼",
+3607	    "regional_indicator_x": "🇽",
+3608	    "regional_indicator_y": "🇾",
+3609	    "regional_indicator_z": "🇿",
+3610	}
+
+
+ + +
+
+ +
+
+ hardcoded_password_string: Possible hardcoded password: '㊙'
+ Test ID: B105
+ Severity: LOW
+ Confidence: MEDIUM
+ CWE: CWE-259
+ File: ./venv/lib/python3.12/site-packages/rich/_emoji_codes.py
+ Line number: 2882
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b105_hardcoded_password_string.html
+ +
+
+2881	    "congratulations": "㊗",
+2882	    "secret": "㊙",
+2883	    "m": "Ⓜ",
+2884	    "city_sunset": "🌆",
+2885	    "clapper": "🎬",
+2886	    "clap": "👏",
+2887	    "beers": "🍻",
+2888	    "clock830": "🕣",
+2889	    "clock8": "🕗",
+2890	    "clock1130": "🕦",
+2891	    "clock11": "🕚",
+2892	    "clock530": "🕠",
+2893	    "clock5": "🕔",
+2894	    "clock430": "🕟",
+2895	    "clock4": "🕓",
+2896	    "clock930": "🕤",
+2897	    "clock9": "🕘",
+2898	    "clock130": "🕜",
+2899	    "clock1": "🕐",
+2900	    "clock730": "🕢",
+2901	    "clock7": "🕖",
+2902	    "clock630": "🕡",
+2903	    "clock6": "🕕",
+2904	    "clock1030": "🕥",
+2905	    "clock10": "🕙",
+2906	    "clock330": "🕞",
+2907	    "clock3": "🕒",
+2908	    "clock1230": "🕧",
+2909	    "clock12": "🕛",
+2910	    "clock230": "🕝",
+2911	    "clock2": "🕑",
+2912	    "arrows_clockwise": "🔃",
+2913	    "repeat": "🔁",
+2914	    "repeat_one": "🔂",
+2915	    "closed_lock_with_key": "🔐",
+2916	    "mailbox_closed": "📪",
+2917	    "mailbox": "📫",
+2918	    "cloud_with_tornado": "🌪",
+2919	    "cocktail": "🍸",
+2920	    "boom": "💥",
+2921	    "compression": "🗜",
+2922	    "confounded": "😖",
+2923	    "confused": "😕",
+2924	    "rice": "🍚",
+2925	    "cow2": "🐄",
+2926	    "cricket_bat_and_ball": "🏏",
+2927	    "x": "❌",
+2928	    "cry": "😢",
+2929	    "curry": "🍛",
+2930	    "dagger_knife": "🗡",
+2931	    "dancer": "💃",
+2932	    "dark_sunglasses": "🕶",
+2933	    "dash": "💨",
+2934	    "truck": "🚚",
+2935	    "derelict_house_building": "🏚",
+2936	    "diamond_shape_with_a_dot_inside": "💠",
+2937	    "dart": "🎯",
+2938	    "disappointed_relieved": "😥",
+2939	    "disappointed": "😞",
+2940	    "do_not_litter": "🚯",
+2941	    "dog2": "🐕",
+2942	    "flipper": "🐬",
+2943	    "loop": "➿",
+2944	    "bangbang": "‼",
+2945	    "double_vertical_bar": "⏸",
+2946	    "dove_of_peace": "🕊",
+2947	    "small_red_triangle_down": "🔻",
+2948	    "arrow_down_small": "🔽",
+2949	    "arrow_down": "⬇",
+2950	    "dromedary_camel": "🐪",
+2951	    "e__mail": "📧",
+2952	    "corn": "🌽",
+2953	    "ear_of_rice": "🌾",
+2954	    "earth_americas": "🌎",
+2955	    "earth_asia": "🌏",
+2956	    "earth_africa": "🌍",
+2957	    "eight_pointed_black_star": "✴",
+2958	    "eight_spoked_asterisk": "✳",
+2959	    "eject_symbol": "⏏",
+2960	    "bulb": "💡",
+2961	    "emoji_modifier_fitzpatrick_type__1__2": "🏻",
+2962	    "emoji_modifier_fitzpatrick_type__3": "🏼",
+2963	    "emoji_modifier_fitzpatrick_type__4": "🏽",
+2964	    "emoji_modifier_fitzpatrick_type__5": "🏾",
+2965	    "emoji_modifier_fitzpatrick_type__6": "🏿",
+2966	    "end": "🔚",
+2967	    "email": "✉",
+2968	    "european_castle": "🏰",
+2969	    "european_post_office": "🏤",
+2970	    "interrobang": "⁉",
+2971	    "expressionless": "😑",
+2972	    "eyeglasses": "👓",
+2973	    "massage": "💆",
+2974	    "yum": "😋",
+2975	    "scream": "😱",
+2976	    "kissing_heart": "😘",
+2977	    "sweat": "😓",
+2978	    "face_with_head__bandage": "🤕",
+2979	    "triumph": "😤",
+2980	    "mask": "😷",
+2981	    "no_good": "🙅",
+2982	    "ok_woman": "🙆",
+2983	    "open_mouth": "😮",
+2984	    "cold_sweat": "😰",
+2985	    "stuck_out_tongue": "😛",
+2986	    "stuck_out_tongue_closed_eyes": "😝",
+2987	    "stuck_out_tongue_winking_eye": "😜",
+2988	    "joy": "😂",
+2989	    "no_mouth": "😶",
+2990	    "santa": "🎅",
+2991	    "fax": "📠",
+2992	    "fearful": "😨",
+2993	    "field_hockey_stick_and_ball": "🏑",
+2994	    "first_quarter_moon_with_face": "🌛",
+2995	    "fish_cake": "🍥",
+2996	    "fishing_pole_and_fish": "🎣",
+2997	    "facepunch": "👊",
+2998	    "punch": "👊",
+2999	    "flag_for_afghanistan": "🇦🇫",
+3000	    "flag_for_albania": "🇦🇱",
+3001	    "flag_for_algeria": "🇩🇿",
+3002	    "flag_for_american_samoa": "🇦🇸",
+3003	    "flag_for_andorra": "🇦🇩",
+3004	    "flag_for_angola": "🇦🇴",
+3005	    "flag_for_anguilla": "🇦🇮",
+3006	    "flag_for_antarctica": "🇦🇶",
+3007	    "flag_for_antigua_&_barbuda": "🇦🇬",
+3008	    "flag_for_argentina": "🇦🇷",
+3009	    "flag_for_armenia": "🇦🇲",
+3010	    "flag_for_aruba": "🇦🇼",
+3011	    "flag_for_ascension_island": "🇦🇨",
+3012	    "flag_for_australia": "🇦🇺",
+3013	    "flag_for_austria": "🇦🇹",
+3014	    "flag_for_azerbaijan": "🇦🇿",
+3015	    "flag_for_bahamas": "🇧🇸",
+3016	    "flag_for_bahrain": "🇧🇭",
+3017	    "flag_for_bangladesh": "🇧🇩",
+3018	    "flag_for_barbados": "🇧🇧",
+3019	    "flag_for_belarus": "🇧🇾",
+3020	    "flag_for_belgium": "🇧🇪",
+3021	    "flag_for_belize": "🇧🇿",
+3022	    "flag_for_benin": "🇧🇯",
+3023	    "flag_for_bermuda": "🇧🇲",
+3024	    "flag_for_bhutan": "🇧🇹",
+3025	    "flag_for_bolivia": "🇧🇴",
+3026	    "flag_for_bosnia_&_herzegovina": "🇧🇦",
+3027	    "flag_for_botswana": "🇧🇼",
+3028	    "flag_for_bouvet_island": "🇧🇻",
+3029	    "flag_for_brazil": "🇧🇷",
+3030	    "flag_for_british_indian_ocean_territory": "🇮🇴",
+3031	    "flag_for_british_virgin_islands": "🇻🇬",
+3032	    "flag_for_brunei": "🇧🇳",
+3033	    "flag_for_bulgaria": "🇧🇬",
+3034	    "flag_for_burkina_faso": "🇧🇫",
+3035	    "flag_for_burundi": "🇧🇮",
+3036	    "flag_for_cambodia": "🇰🇭",
+3037	    "flag_for_cameroon": "🇨🇲",
+3038	    "flag_for_canada": "🇨🇦",
+3039	    "flag_for_canary_islands": "🇮🇨",
+3040	    "flag_for_cape_verde": "🇨🇻",
+3041	    "flag_for_caribbean_netherlands": "🇧🇶",
+3042	    "flag_for_cayman_islands": "🇰🇾",
+3043	    "flag_for_central_african_republic": "🇨🇫",
+3044	    "flag_for_ceuta_&_melilla": "🇪🇦",
+3045	    "flag_for_chad": "🇹🇩",
+3046	    "flag_for_chile": "🇨🇱",
+3047	    "flag_for_china": "🇨🇳",
+3048	    "flag_for_christmas_island": "🇨🇽",
+3049	    "flag_for_clipperton_island": "🇨🇵",
+3050	    "flag_for_cocos__islands": "🇨🇨",
+3051	    "flag_for_colombia": "🇨🇴",
+3052	    "flag_for_comoros": "🇰🇲",
+3053	    "flag_for_congo____brazzaville": "🇨🇬",
+3054	    "flag_for_congo____kinshasa": "🇨🇩",
+3055	    "flag_for_cook_islands": "🇨🇰",
+3056	    "flag_for_costa_rica": "🇨🇷",
+3057	    "flag_for_croatia": "🇭🇷",
+3058	    "flag_for_cuba": "🇨🇺",
+3059	    "flag_for_curaçao": "🇨🇼",
+3060	    "flag_for_cyprus": "🇨🇾",
+3061	    "flag_for_czech_republic": "🇨🇿",
+3062	    "flag_for_côte_d’ivoire": "🇨🇮",
+3063	    "flag_for_denmark": "🇩🇰",
+3064	    "flag_for_diego_garcia": "🇩🇬",
+3065	    "flag_for_djibouti": "🇩🇯",
+3066	    "flag_for_dominica": "🇩🇲",
+3067	    "flag_for_dominican_republic": "🇩🇴",
+3068	    "flag_for_ecuador": "🇪🇨",
+3069	    "flag_for_egypt": "🇪🇬",
+3070	    "flag_for_el_salvador": "🇸🇻",
+3071	    "flag_for_equatorial_guinea": "🇬🇶",
+3072	    "flag_for_eritrea": "🇪🇷",
+3073	    "flag_for_estonia": "🇪🇪",
+3074	    "flag_for_ethiopia": "🇪🇹",
+3075	    "flag_for_european_union": "🇪🇺",
+3076	    "flag_for_falkland_islands": "🇫🇰",
+3077	    "flag_for_faroe_islands": "🇫🇴",
+3078	    "flag_for_fiji": "🇫🇯",
+3079	    "flag_for_finland": "🇫🇮",
+3080	    "flag_for_france": "🇫🇷",
+3081	    "flag_for_french_guiana": "🇬🇫",
+3082	    "flag_for_french_polynesia": "🇵🇫",
+3083	    "flag_for_french_southern_territories": "🇹🇫",
+3084	    "flag_for_gabon": "🇬🇦",
+3085	    "flag_for_gambia": "🇬🇲",
+3086	    "flag_for_georgia": "🇬🇪",
+3087	    "flag_for_germany": "🇩🇪",
+3088	    "flag_for_ghana": "🇬🇭",
+3089	    "flag_for_gibraltar": "🇬🇮",
+3090	    "flag_for_greece": "🇬🇷",
+3091	    "flag_for_greenland": "🇬🇱",
+3092	    "flag_for_grenada": "🇬🇩",
+3093	    "flag_for_guadeloupe": "🇬🇵",
+3094	    "flag_for_guam": "🇬🇺",
+3095	    "flag_for_guatemala": "🇬🇹",
+3096	    "flag_for_guernsey": "🇬🇬",
+3097	    "flag_for_guinea": "🇬🇳",
+3098	    "flag_for_guinea__bissau": "🇬🇼",
+3099	    "flag_for_guyana": "🇬🇾",
+3100	    "flag_for_haiti": "🇭🇹",
+3101	    "flag_for_heard_&_mcdonald_islands": "🇭🇲",
+3102	    "flag_for_honduras": "🇭🇳",
+3103	    "flag_for_hong_kong": "🇭🇰",
+3104	    "flag_for_hungary": "🇭🇺",
+3105	    "flag_for_iceland": "🇮🇸",
+3106	    "flag_for_india": "🇮🇳",
+3107	    "flag_for_indonesia": "🇮🇩",
+3108	    "flag_for_iran": "🇮🇷",
+3109	    "flag_for_iraq": "🇮🇶",
+3110	    "flag_for_ireland": "🇮🇪",
+3111	    "flag_for_isle_of_man": "🇮🇲",
+3112	    "flag_for_israel": "🇮🇱",
+3113	    "flag_for_italy": "🇮🇹",
+3114	    "flag_for_jamaica": "🇯🇲",
+3115	    "flag_for_japan": "🇯🇵",
+3116	    "flag_for_jersey": "🇯🇪",
+3117	    "flag_for_jordan": "🇯🇴",
+3118	    "flag_for_kazakhstan": "🇰🇿",
+3119	    "flag_for_kenya": "🇰🇪",
+3120	    "flag_for_kiribati": "🇰🇮",
+3121	    "flag_for_kosovo": "🇽🇰",
+3122	    "flag_for_kuwait": "🇰🇼",
+3123	    "flag_for_kyrgyzstan": "🇰🇬",
+3124	    "flag_for_laos": "🇱🇦",
+3125	    "flag_for_latvia": "🇱🇻",
+3126	    "flag_for_lebanon": "🇱🇧",
+3127	    "flag_for_lesotho": "🇱🇸",
+3128	    "flag_for_liberia": "🇱🇷",
+3129	    "flag_for_libya": "🇱🇾",
+3130	    "flag_for_liechtenstein": "🇱🇮",
+3131	    "flag_for_lithuania": "🇱🇹",
+3132	    "flag_for_luxembourg": "🇱🇺",
+3133	    "flag_for_macau": "🇲🇴",
+3134	    "flag_for_macedonia": "🇲🇰",
+3135	    "flag_for_madagascar": "🇲🇬",
+3136	    "flag_for_malawi": "🇲🇼",
+3137	    "flag_for_malaysia": "🇲🇾",
+3138	    "flag_for_maldives": "🇲🇻",
+3139	    "flag_for_mali": "🇲🇱",
+3140	    "flag_for_malta": "🇲🇹",
+3141	    "flag_for_marshall_islands": "🇲🇭",
+3142	    "flag_for_martinique": "🇲🇶",
+3143	    "flag_for_mauritania": "🇲🇷",
+3144	    "flag_for_mauritius": "🇲🇺",
+3145	    "flag_for_mayotte": "🇾🇹",
+3146	    "flag_for_mexico": "🇲🇽",
+3147	    "flag_for_micronesia": "🇫🇲",
+3148	    "flag_for_moldova": "🇲🇩",
+3149	    "flag_for_monaco": "🇲🇨",
+3150	    "flag_for_mongolia": "🇲🇳",
+3151	    "flag_for_montenegro": "🇲🇪",
+3152	    "flag_for_montserrat": "🇲🇸",
+3153	    "flag_for_morocco": "🇲🇦",
+3154	    "flag_for_mozambique": "🇲🇿",
+3155	    "flag_for_myanmar": "🇲🇲",
+3156	    "flag_for_namibia": "🇳🇦",
+3157	    "flag_for_nauru": "🇳🇷",
+3158	    "flag_for_nepal": "🇳🇵",
+3159	    "flag_for_netherlands": "🇳🇱",
+3160	    "flag_for_new_caledonia": "🇳🇨",
+3161	    "flag_for_new_zealand": "🇳🇿",
+3162	    "flag_for_nicaragua": "🇳🇮",
+3163	    "flag_for_niger": "🇳🇪",
+3164	    "flag_for_nigeria": "🇳🇬",
+3165	    "flag_for_niue": "🇳🇺",
+3166	    "flag_for_norfolk_island": "🇳🇫",
+3167	    "flag_for_north_korea": "🇰🇵",
+3168	    "flag_for_northern_mariana_islands": "🇲🇵",
+3169	    "flag_for_norway": "🇳🇴",
+3170	    "flag_for_oman": "🇴🇲",
+3171	    "flag_for_pakistan": "🇵🇰",
+3172	    "flag_for_palau": "🇵🇼",
+3173	    "flag_for_palestinian_territories": "🇵🇸",
+3174	    "flag_for_panama": "🇵🇦",
+3175	    "flag_for_papua_new_guinea": "🇵🇬",
+3176	    "flag_for_paraguay": "🇵🇾",
+3177	    "flag_for_peru": "🇵🇪",
+3178	    "flag_for_philippines": "🇵🇭",
+3179	    "flag_for_pitcairn_islands": "🇵🇳",
+3180	    "flag_for_poland": "🇵🇱",
+3181	    "flag_for_portugal": "🇵🇹",
+3182	    "flag_for_puerto_rico": "🇵🇷",
+3183	    "flag_for_qatar": "🇶🇦",
+3184	    "flag_for_romania": "🇷🇴",
+3185	    "flag_for_russia": "🇷🇺",
+3186	    "flag_for_rwanda": "🇷🇼",
+3187	    "flag_for_réunion": "🇷🇪",
+3188	    "flag_for_samoa": "🇼🇸",
+3189	    "flag_for_san_marino": "🇸🇲",
+3190	    "flag_for_saudi_arabia": "🇸🇦",
+3191	    "flag_for_senegal": "🇸🇳",
+3192	    "flag_for_serbia": "🇷🇸",
+3193	    "flag_for_seychelles": "🇸🇨",
+3194	    "flag_for_sierra_leone": "🇸🇱",
+3195	    "flag_for_singapore": "🇸🇬",
+3196	    "flag_for_sint_maarten": "🇸🇽",
+3197	    "flag_for_slovakia": "🇸🇰",
+3198	    "flag_for_slovenia": "🇸🇮",
+3199	    "flag_for_solomon_islands": "🇸🇧",
+3200	    "flag_for_somalia": "🇸🇴",
+3201	    "flag_for_south_africa": "🇿🇦",
+3202	    "flag_for_south_georgia_&_south_sandwich_islands": "🇬🇸",
+3203	    "flag_for_south_korea": "🇰🇷",
+3204	    "flag_for_south_sudan": "🇸🇸",
+3205	    "flag_for_spain": "🇪🇸",
+3206	    "flag_for_sri_lanka": "🇱🇰",
+3207	    "flag_for_st._barthélemy": "🇧🇱",
+3208	    "flag_for_st._helena": "🇸🇭",
+3209	    "flag_for_st._kitts_&_nevis": "🇰🇳",
+3210	    "flag_for_st._lucia": "🇱🇨",
+3211	    "flag_for_st._martin": "🇲🇫",
+3212	    "flag_for_st._pierre_&_miquelon": "🇵🇲",
+3213	    "flag_for_st._vincent_&_grenadines": "🇻🇨",
+3214	    "flag_for_sudan": "🇸🇩",
+3215	    "flag_for_suriname": "🇸🇷",
+3216	    "flag_for_svalbard_&_jan_mayen": "🇸🇯",
+3217	    "flag_for_swaziland": "🇸🇿",
+3218	    "flag_for_sweden": "🇸🇪",
+3219	    "flag_for_switzerland": "🇨🇭",
+3220	    "flag_for_syria": "🇸🇾",
+3221	    "flag_for_são_tomé_&_príncipe": "🇸🇹",
+3222	    "flag_for_taiwan": "🇹🇼",
+3223	    "flag_for_tajikistan": "🇹🇯",
+3224	    "flag_for_tanzania": "🇹🇿",
+3225	    "flag_for_thailand": "🇹🇭",
+3226	    "flag_for_timor__leste": "🇹🇱",
+3227	    "flag_for_togo": "🇹🇬",
+3228	    "flag_for_tokelau": "🇹🇰",
+3229	    "flag_for_tonga": "🇹🇴",
+3230	    "flag_for_trinidad_&_tobago": "🇹🇹",
+3231	    "flag_for_tristan_da_cunha": "🇹🇦",
+3232	    "flag_for_tunisia": "🇹🇳",
+3233	    "flag_for_turkey": "🇹🇷",
+3234	    "flag_for_turkmenistan": "🇹🇲",
+3235	    "flag_for_turks_&_caicos_islands": "🇹🇨",
+3236	    "flag_for_tuvalu": "🇹🇻",
+3237	    "flag_for_u.s._outlying_islands": "🇺🇲",
+3238	    "flag_for_u.s._virgin_islands": "🇻🇮",
+3239	    "flag_for_uganda": "🇺🇬",
+3240	    "flag_for_ukraine": "🇺🇦",
+3241	    "flag_for_united_arab_emirates": "🇦🇪",
+3242	    "flag_for_united_kingdom": "🇬🇧",
+3243	    "flag_for_united_states": "🇺🇸",
+3244	    "flag_for_uruguay": "🇺🇾",
+3245	    "flag_for_uzbekistan": "🇺🇿",
+3246	    "flag_for_vanuatu": "🇻🇺",
+3247	    "flag_for_vatican_city": "🇻🇦",
+3248	    "flag_for_venezuela": "🇻🇪",
+3249	    "flag_for_vietnam": "🇻🇳",
+3250	    "flag_for_wallis_&_futuna": "🇼🇫",
+3251	    "flag_for_western_sahara": "🇪🇭",
+3252	    "flag_for_yemen": "🇾🇪",
+3253	    "flag_for_zambia": "🇿🇲",
+3254	    "flag_for_zimbabwe": "🇿🇼",
+3255	    "flag_for_åland_islands": "🇦🇽",
+3256	    "golf": "⛳",
+3257	    "fleur__de__lis": "⚜",
+3258	    "muscle": "💪",
+3259	    "flushed": "😳",
+3260	    "frame_with_picture": "🖼",
+3261	    "fries": "🍟",
+3262	    "frog": "🐸",
+3263	    "hatched_chick": "🐥",
+3264	    "frowning": "😦",
+3265	    "fuelpump": "⛽",
+3266	    "full_moon_with_face": "🌝",
+3267	    "gem": "💎",
+3268	    "star2": "🌟",
+3269	    "golfer": "🏌",
+3270	    "mortar_board": "🎓",
+3271	    "grimacing": "😬",
+3272	    "smile_cat": "😸",
+3273	    "grinning": "😀",
+3274	    "grin": "😁",
+3275	    "heartpulse": "💗",
+3276	    "guardsman": "💂",
+3277	    "haircut": "💇",
+3278	    "hamster": "🐹",
+3279	    "raising_hand": "🙋",
+3280	    "headphones": "🎧",
+3281	    "hear_no_evil": "🙉",
+3282	    "cupid": "💘",
+3283	    "gift_heart": "💝",
+3284	    "heart": "❤",
+3285	    "exclamation": "❗",
+3286	    "heavy_exclamation_mark": "❗",
+3287	    "heavy_heart_exclamation_mark_ornament": "❣",
+3288	    "o": "⭕",
+3289	    "helm_symbol": "⎈",
+3290	    "helmet_with_white_cross": "⛑",
+3291	    "high_heel": "👠",
+3292	    "bullettrain_side": "🚄",
+3293	    "bullettrain_front": "🚅",
+3294	    "high_brightness": "🔆",
+3295	    "zap": "⚡",
+3296	    "hocho": "🔪",
+3297	    "knife": "🔪",
+3298	    "bee": "🐝",
+3299	    "traffic_light": "🚥",
+3300	    "racehorse": "🐎",
+3301	    "coffee": "☕",
+3302	    "hotsprings": "♨",
+3303	    "hourglass": "⌛",
+3304	    "hourglass_flowing_sand": "⏳",
+3305	    "house_buildings": "🏘",
+3306	    "100": "💯",
+3307	    "hushed": "😯",
+3308	    "ice_hockey_stick_and_puck": "🏒",
+3309	    "imp": "👿",
+3310	    "information_desk_person": "💁",
+3311	    "information_source": "ℹ",
+3312	    "capital_abcd": "🔠",
+3313	    "abc": "🔤",
+3314	    "abcd": "🔡",
+3315	    "1234": "🔢",
+3316	    "symbols": "🔣",
+3317	    "izakaya_lantern": "🏮",
+3318	    "lantern": "🏮",
+3319	    "jack_o_lantern": "🎃",
+3320	    "dolls": "🎎",
+3321	    "japanese_goblin": "👺",
+3322	    "japanese_ogre": "👹",
+3323	    "beginner": "🔰",
+3324	    "zero": "0️⃣",
+3325	    "one": "1️⃣",
+3326	    "ten": "🔟",
+3327	    "two": "2️⃣",
+3328	    "three": "3️⃣",
+3329	    "four": "4️⃣",
+3330	    "five": "5️⃣",
+3331	    "six": "6️⃣",
+3332	    "seven": "7️⃣",
+3333	    "eight": "8️⃣",
+3334	    "nine": "9️⃣",
+3335	    "couplekiss": "💏",
+3336	    "kissing_cat": "😽",
+3337	    "kissing": "😗",
+3338	    "kissing_closed_eyes": "😚",
+3339	    "kissing_smiling_eyes": "😙",
+3340	    "beetle": "🐞",
+3341	    "large_blue_circle": "🔵",
+3342	    "last_quarter_moon_with_face": "🌜",
+3343	    "leaves": "🍃",
+3344	    "mag": "🔍",
+3345	    "left_right_arrow": "↔",
+3346	    "leftwards_arrow_with_hook": "↩",
+3347	    "arrow_left": "⬅",
+3348	    "lock": "🔒",
+3349	    "lock_with_ink_pen": "🔏",
+3350	    "sob": "😭",
+3351	    "low_brightness": "🔅",
+3352	    "lower_left_ballpoint_pen": "🖊",
+3353	    "lower_left_crayon": "🖍",
+3354	    "lower_left_fountain_pen": "🖋",
+3355	    "lower_left_paintbrush": "🖌",
+3356	    "mahjong": "🀄",
+3357	    "couple": "👫",
+3358	    "man_in_business_suit_levitating": "🕴",
+3359	    "man_with_gua_pi_mao": "👲",
+3360	    "man_with_turban": "👳",
+3361	    "mans_shoe": "👞",
+3362	    "shoe": "👞",
+3363	    "menorah_with_nine_branches": "🕎",
+3364	    "mens": "🚹",
+3365	    "minidisc": "💽",
+3366	    "iphone": "📱",
+3367	    "calling": "📲",
+3368	    "money__mouth_face": "🤑",
+3369	    "moneybag": "💰",
+3370	    "rice_scene": "🎑",
+3371	    "mountain_bicyclist": "🚵",
+3372	    "mouse2": "🐁",
+3373	    "lips": "👄",
+3374	    "moyai": "🗿",
+3375	    "notes": "🎶",
+3376	    "nail_care": "💅",
+3377	    "ab": "🆎",
+3378	    "negative_squared_cross_mark": "❎",
+3379	    "a": "🅰",
+3380	    "b": "🅱",
+3381	    "o2": "🅾",
+3382	    "parking": "🅿",
+3383	    "new_moon_with_face": "🌚",
+3384	    "no_entry_sign": "🚫",
+3385	    "underage": "🔞",
+3386	    "non__potable_water": "🚱",
+3387	    "arrow_upper_right": "↗",
+3388	    "arrow_upper_left": "↖",
+3389	    "office": "🏢",
+3390	    "older_man": "👴",
+3391	    "older_woman": "👵",
+3392	    "om_symbol": "🕉",
+3393	    "on": "🔛",
+3394	    "book": "📖",
+3395	    "unlock": "🔓",
+3396	    "mailbox_with_no_mail": "📭",
+3397	    "mailbox_with_mail": "📬",
+3398	    "cd": "💿",
+3399	    "tada": "🎉",
+3400	    "feet": "🐾",
+3401	    "walking": "🚶",
+3402	    "pencil2": "✏",
+3403	    "pensive": "😔",
+3404	    "persevere": "😣",
+3405	    "bow": "🙇",
+3406	    "raised_hands": "🙌",
+3407	    "person_with_ball": "⛹",
+3408	    "person_with_blond_hair": "👱",
+3409	    "pray": "🙏",
+3410	    "person_with_pouting_face": "🙎",
+3411	    "computer": "💻",
+3412	    "pig2": "🐖",
+3413	    "hankey": "💩",
+3414	    "poop": "💩",
+3415	    "shit": "💩",
+3416	    "bamboo": "🎍",
+3417	    "gun": "🔫",
+3418	    "black_joker": "🃏",
+3419	    "rotating_light": "🚨",
+3420	    "cop": "👮",
+3421	    "stew": "🍲",
+3422	    "pouch": "👝",
+3423	    "pouting_cat": "😾",
+3424	    "rage": "😡",
+3425	    "put_litter_in_its_place": "🚮",
+3426	    "rabbit2": "🐇",
+3427	    "racing_motorcycle": "🏍",
+3428	    "radioactive_sign": "☢",
+3429	    "fist": "✊",
+3430	    "hand": "✋",
+3431	    "raised_hand_with_fingers_splayed": "🖐",
+3432	    "raised_hand_with_part_between_middle_and_ring_fingers": "🖖",
+3433	    "blue_car": "🚙",
+3434	    "apple": "🍎",
+3435	    "relieved": "😌",
+3436	    "reversed_hand_with_middle_finger_extended": "🖕",
+3437	    "mag_right": "🔎",
+3438	    "arrow_right_hook": "↪",
+3439	    "sweet_potato": "🍠",
+3440	    "robot": "🤖",
+3441	    "rolled__up_newspaper": "🗞",
+3442	    "rowboat": "🚣",
+3443	    "runner": "🏃",
+3444	    "running": "🏃",
+3445	    "running_shirt_with_sash": "🎽",
+3446	    "boat": "⛵",
+3447	    "scales": "⚖",
+3448	    "school_satchel": "🎒",
+3449	    "scorpius": "♏",
+3450	    "see_no_evil": "🙈",
+3451	    "sheep": "🐑",
+3452	    "stars": "🌠",
+3453	    "cake": "🍰",
+3454	    "six_pointed_star": "🔯",
+3455	    "ski": "🎿",
+3456	    "sleeping_accommodation": "🛌",
+3457	    "sleeping": "😴",
+3458	    "sleepy": "😪",
+3459	    "sleuth_or_spy": "🕵",
+3460	    "heart_eyes_cat": "😻",
+3461	    "smiley_cat": "😺",
+3462	    "innocent": "😇",
+3463	    "heart_eyes": "😍",
+3464	    "smiling_imp": "😈",
+3465	    "smiley": "😃",
+3466	    "sweat_smile": "😅",
+3467	    "smile": "😄",
+3468	    "laughing": "😆",
+3469	    "satisfied": "😆",
+3470	    "blush": "😊",
+3471	    "smirk": "😏",
+3472	    "smoking": "🚬",
+3473	    "snow_capped_mountain": "🏔",
+3474	    "soccer": "⚽",
+3475	    "icecream": "🍦",
+3476	    "soon": "🔜",
+3477	    "arrow_lower_right": "↘",
+3478	    "arrow_lower_left": "↙",
+3479	    "speak_no_evil": "🙊",
+3480	    "speaker": "🔈",
+3481	    "mute": "🔇",
+3482	    "sound": "🔉",
+3483	    "loud_sound": "🔊",
+3484	    "speaking_head_in_silhouette": "🗣",
+3485	    "spiral_calendar_pad": "🗓",
+3486	    "spiral_note_pad": "🗒",
+3487	    "shell": "🐚",
+3488	    "sweat_drops": "💦",
+3489	    "u5272": "🈹",
+3490	    "u5408": "🈴",
+3491	    "u55b6": "🈺",
+3492	    "u6307": "🈯",
+3493	    "u6708": "🈷",
+3494	    "u6709": "🈶",
+3495	    "u6e80": "🈵",
+3496	    "u7121": "🈚",
+3497	    "u7533": "🈸",
+3498	    "u7981": "🈲",
+3499	    "u7a7a": "🈳",
+3500	    "cl": "🆑",
+3501	    "cool": "🆒",
+3502	    "free": "🆓",
+3503	    "id": "🆔",
+3504	    "koko": "🈁",
+3505	    "sa": "🈂",
+3506	    "new": "🆕",
+3507	    "ng": "🆖",
+3508	    "ok": "🆗",
+3509	    "sos": "🆘",
+3510	    "up": "🆙",
+3511	    "vs": "🆚",
+3512	    "steam_locomotive": "🚂",
+3513	    "ramen": "🍜",
+3514	    "partly_sunny": "⛅",
+3515	    "city_sunrise": "🌇",
+3516	    "surfer": "🏄",
+3517	    "swimmer": "🏊",
+3518	    "shirt": "👕",
+3519	    "tshirt": "👕",
+3520	    "table_tennis_paddle_and_ball": "🏓",
+3521	    "tea": "🍵",
+3522	    "tv": "📺",
+3523	    "three_button_mouse": "🖱",
+3524	    "+1": "👍",
+3525	    "thumbsup": "👍",
+3526	    "__1": "👎",
+3527	    "-1": "👎",
+3528	    "thumbsdown": "👎",
+3529	    "thunder_cloud_and_rain": "⛈",
+3530	    "tiger2": "🐅",
+3531	    "tophat": "🎩",
+3532	    "top": "🔝",
+3533	    "tm": "™",
+3534	    "train2": "🚆",
+3535	    "triangular_flag_on_post": "🚩",
+3536	    "trident": "🔱",
+3537	    "twisted_rightwards_arrows": "🔀",
+3538	    "unamused": "😒",
+3539	    "small_red_triangle": "🔺",
+3540	    "arrow_up_small": "🔼",
+3541	    "arrow_up_down": "↕",
+3542	    "upside__down_face": "🙃",
+3543	    "arrow_up": "⬆",
+3544	    "v": "✌",
+3545	    "vhs": "📼",
+3546	    "wc": "🚾",
+3547	    "ocean": "🌊",
+3548	    "waving_black_flag": "🏴",
+3549	    "wave": "👋",
+3550	    "waving_white_flag": "🏳",
+3551	    "moon": "🌔",
+3552	    "scream_cat": "🙀",
+3553	    "weary": "😩",
+3554	    "weight_lifter": "🏋",
+3555	    "whale2": "🐋",
+3556	    "wheelchair": "♿",
+3557	    "point_down": "👇",
+3558	    "grey_exclamation": "❕",
+3559	    "white_frowning_face": "☹",
+3560	    "white_check_mark": "✅",
+3561	    "point_left": "👈",
+3562	    "white_medium_small_square": "◽",
+3563	    "star": "⭐",
+3564	    "grey_question": "❔",
+3565	    "point_right": "👉",
+3566	    "relaxed": "☺",
+3567	    "white_sun_behind_cloud": "🌥",
+3568	    "white_sun_behind_cloud_with_rain": "🌦",
+3569	    "white_sun_with_small_cloud": "🌤",
+3570	    "point_up_2": "👆",
+3571	    "point_up": "☝",
+3572	    "wind_blowing_face": "🌬",
+3573	    "wink": "😉",
+3574	    "wolf": "🐺",
+3575	    "dancers": "👯",
+3576	    "boot": "👢",
+3577	    "womans_clothes": "👚",
+3578	    "womans_hat": "👒",
+3579	    "sandal": "👡",
+3580	    "womens": "🚺",
+3581	    "worried": "😟",
+3582	    "gift": "🎁",
+3583	    "zipper__mouth_face": "🤐",
+3584	    "regional_indicator_a": "🇦",
+3585	    "regional_indicator_b": "🇧",
+3586	    "regional_indicator_c": "🇨",
+3587	    "regional_indicator_d": "🇩",
+3588	    "regional_indicator_e": "🇪",
+3589	    "regional_indicator_f": "🇫",
+3590	    "regional_indicator_g": "🇬",
+3591	    "regional_indicator_h": "🇭",
+3592	    "regional_indicator_i": "🇮",
+3593	    "regional_indicator_j": "🇯",
+3594	    "regional_indicator_k": "🇰",
+3595	    "regional_indicator_l": "🇱",
+3596	    "regional_indicator_m": "🇲",
+3597	    "regional_indicator_n": "🇳",
+3598	    "regional_indicator_o": "🇴",
+3599	    "regional_indicator_p": "🇵",
+3600	    "regional_indicator_q": "🇶",
+3601	    "regional_indicator_r": "🇷",
+3602	    "regional_indicator_s": "🇸",
+3603	    "regional_indicator_t": "🇹",
+3604	    "regional_indicator_u": "🇺",
+3605	    "regional_indicator_v": "🇻",
+3606	    "regional_indicator_w": "🇼",
+3607	    "regional_indicator_x": "🇽",
+3608	    "regional_indicator_y": "🇾",
+3609	    "regional_indicator_z": "🇿",
+3610	}
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/rich/_pick.py
+ Line number: 13
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+12	    """
+13	    assert values, "1 or more values required"
+14	    for value in values:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/rich/_ratio.py
+ Line number: 123
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+122	    total_ratio = sum(ratios)
+123	    assert total_ratio > 0, "Sum of ratios must be > 0"
+124	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/rich/_unicode_data/__init__.py
+ Line number: 92
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+91	    if TYPE_CHECKING:
+92	        assert isinstance(module.cell_table, CellTable)
+93	    return module.cell_table
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/rich/_win32_console.py
+ Line number: 435
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+434	
+435	        assert fore is not None
+436	        assert back is not None
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/rich/_win32_console.py
+ Line number: 436
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+435	        assert fore is not None
+436	        assert back is not None
+437	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/rich/_win32_console.py
+ Line number: 565
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+564	        """
+565	        assert len(title) < 255, "Console title must be less than 255 characters"
+566	        SetConsoleTitle(title)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/rich/color.py
+ Line number: 365
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+364	        if self.type == ColorType.TRUECOLOR:
+365	            assert self.triplet is not None
+366	            return self.triplet
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/rich/color.py
+ Line number: 368
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+367	        elif self.type == ColorType.EIGHT_BIT:
+368	            assert self.number is not None
+369	            return EIGHT_BIT_PALETTE[self.number]
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/rich/color.py
+ Line number: 371
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+370	        elif self.type == ColorType.STANDARD:
+371	            assert self.number is not None
+372	            return theme.ansi_colors[self.number]
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/rich/color.py
+ Line number: 374
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+373	        elif self.type == ColorType.WINDOWS:
+374	            assert self.number is not None
+375	            return WINDOWS_PALETTE[self.number]
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/rich/color.py
+ Line number: 377
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+376	        else:  # self.type == ColorType.DEFAULT:
+377	            assert self.number is None
+378	            return theme.foreground_color if foreground else theme.background_color
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/rich/color.py
+ Line number: 493
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+492	            number = self.number
+493	            assert number is not None
+494	            fore, back = (30, 40) if number < 8 else (82, 92)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/rich/color.py
+ Line number: 499
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+498	            number = self.number
+499	            assert number is not None
+500	            fore, back = (30, 40) if number < 8 else (82, 92)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/rich/color.py
+ Line number: 504
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+503	        elif _type == ColorType.EIGHT_BIT:
+504	            assert self.number is not None
+505	            return ("38" if foreground else "48", "5", str(self.number))
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/rich/color.py
+ Line number: 508
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+507	        else:  # self.standard == ColorStandard.TRUECOLOR:
+508	            assert self.triplet is not None
+509	            red, green, blue = self.triplet
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/rich/color.py
+ Line number: 520
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+519	        if system == ColorSystem.EIGHT_BIT and self.system == ColorSystem.TRUECOLOR:
+520	            assert self.triplet is not None
+521	            _h, l, s = rgb_to_hls(*self.triplet.normalized)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/rich/color.py
+ Line number: 546
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+545	            if self.system == ColorSystem.TRUECOLOR:
+546	                assert self.triplet is not None
+547	                triplet = self.triplet
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/rich/color.py
+ Line number: 549
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+548	            else:  # self.system == ColorSystem.EIGHT_BIT
+549	                assert self.number is not None
+550	                triplet = ColorTriplet(*EIGHT_BIT_PALETTE[self.number])
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/rich/color.py
+ Line number: 557
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+556	            if self.system == ColorSystem.TRUECOLOR:
+557	                assert self.triplet is not None
+558	                triplet = self.triplet
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/rich/color.py
+ Line number: 560
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+559	            else:  # self.system == ColorSystem.EIGHT_BIT
+560	                assert self.number is not None
+561	                if self.number < 16:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/rich/color.py
+ Line number: 573
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+572	    """Parse six hex characters in to RGB triplet."""
+573	    assert len(hex_color) == 6, "must be 6 characters"
+574	    color = ColorTriplet(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/rich/console.py
+ Line number: 1149
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1148	
+1149	        assert count >= 0, "count must be >= 0"
+1150	        self.print(NewLine(count))
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/rich/console.py
+ Line number: 1929
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1928	                offset -= 1
+1929	            assert frame is not None
+1930	            return frame.f_code.co_filename, frame.f_lineno, frame.f_locals
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/rich/console.py
+ Line number: 2189
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2188	        """
+2189	        assert (
+2190	            self.record
+2191	        ), "To export console contents set record=True in the constructor or instance"
+2192	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/rich/console.py
+ Line number: 2245
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2244	        """
+2245	        assert (
+2246	            self.record
+2247	        ), "To export console contents set record=True in the constructor or instance"
+2248	        fragments: List[str] = []
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/rich/live.py
+ Line number: 71
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+70	    ) -> None:
+71	        assert refresh_per_second > 0, "refresh_per_second must be > 0"
+72	        self._renderable = renderable
+
+
+ + +
+
+ +
+
+ blacklist: Standard pseudo-random generators are not suitable for security/cryptographic purposes.
+ Test ID: B311
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-330
+ File: ./venv/lib/python3.12/site-packages/rich/live.py
+ Line number: 381
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b311-random
+ +
+
+380	                time.sleep(0.4)
+381	                if random.randint(0, 10) < 1:
+382	                    console.log(next(examples))
+
+
+ + +
+
+ +
+
+ blacklist: Standard pseudo-random generators are not suitable for security/cryptographic purposes.
+ Test ID: B311
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-330
+ File: ./venv/lib/python3.12/site-packages/rich/live.py
+ Line number: 384
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b311-random
+ +
+
+383	                exchange_rate_dict[(select_exchange, exchange)] = 200 / (
+384	                    (random.random() * 320) + 1
+385	                )
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/rich/logging.py
+ Line number: 142
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+141	            exc_type, exc_value, exc_traceback = record.exc_info
+142	            assert exc_type is not None
+143	            assert exc_value is not None
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/rich/logging.py
+ Line number: 143
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+142	            assert exc_type is not None
+143	            assert exc_value is not None
+144	            traceback = Traceback.from_exception(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/rich/markdown.py
+ Line number: 279
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+278	    def on_child_close(self, context: MarkdownContext, child: MarkdownElement) -> bool:
+279	        assert isinstance(child, TableRowElement)
+280	        self.row = child
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/rich/markdown.py
+ Line number: 291
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+290	    def on_child_close(self, context: MarkdownContext, child: MarkdownElement) -> bool:
+291	        assert isinstance(child, TableRowElement)
+292	        self.rows.append(child)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/rich/markdown.py
+ Line number: 303
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+302	    def on_child_close(self, context: MarkdownContext, child: MarkdownElement) -> bool:
+303	        assert isinstance(child, TableDataElement)
+304	        self.cells.append(child)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/rich/markdown.py
+ Line number: 326
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+325	
+326	        assert justify in get_args(JustifyMethod)
+327	        return cls(justify=justify)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/rich/markdown.py
+ Line number: 352
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+351	    def on_child_close(self, context: MarkdownContext, child: MarkdownElement) -> bool:
+352	        assert isinstance(child, ListItem)
+353	        self.items.append(child)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/rich/markdown.py
+ Line number: 623
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+622	                    element = context.stack.pop()
+623	                    assert isinstance(element, Link)
+624	                    link_style = console.get_style("markdown.link", default="none")
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/rich/pretty.py
+ Line number: 198
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+197	    console = console or get_console()
+198	    assert console is not None
+199	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/rich/pretty.py
+ Line number: 203
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+202	        if value is not None:
+203	            assert console is not None
+204	            builtins._ = None  # type: ignore[attr-defined]
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/rich/pretty.py
+ Line number: 516
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+515	        )
+516	        assert self.node is not None
+517	        return self.node.check_length(start_length, max_length)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/rich/pretty.py
+ Line number: 522
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+521	        node = self.node
+522	        assert node is not None
+523	        whitespace = self.whitespace
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/rich/pretty.py
+ Line number: 524
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+523	        whitespace = self.whitespace
+524	        assert node.children
+525	        if node.key_repr:
+
+
+ + +
+
+ +
+
+ try_except_pass: Try, Except, Pass detected.
+ Test ID: B110
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/rich/pretty.py
+ Line number: 661
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b110_try_except_pass.html
+ +
+
+660	                    rich_repr_result = obj.__rich_repr__()
+661	            except Exception:
+662	                pass
+663	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/rich/progress.py
+ Line number: 1091
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1090	    ) -> None:
+1091	        assert refresh_per_second > 0, "refresh_per_second must be > 0"
+1092	        self._lock = RLock()
+
+
+ + +
+
+ +
+
+ blacklist: Standard pseudo-random generators are not suitable for security/cryptographic purposes.
+ Test ID: B311
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-330
+ File: ./venv/lib/python3.12/site-packages/rich/progress.py
+ Line number: 1715
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b311-random
+ +
+
+1714	            time.sleep(0.01)
+1715	            if random.randint(0, 100) < 1:
+1716	                progress.log(next(examples))
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/rich/prompt.py
+ Line number: 222
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+221	        """
+222	        assert self.choices is not None
+223	        if self.case_sensitive:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/rich/segment.py
+ Line number: 171
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+170	        text, style, control = self
+171	        assert cut >= 0
+172	
+
+
+ + +
+
+ +
+
+ blacklist: Consider possible security implications associated with dumps module.
+ Test ID: B403
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-502
+ File: ./venv/lib/python3.12/site-packages/rich/style.py
+ Line number: 4
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_imports.html#b403-import-pickle
+ +
+
+3	from operator import attrgetter
+4	from pickle import dumps, loads
+5	from random import randint
+
+
+ + +
+
+ +
+
+ blacklist: Standard pseudo-random generators are not suitable for security/cryptographic purposes.
+ Test ID: B311
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-330
+ File: ./venv/lib/python3.12/site-packages/rich/style.py
+ Line number: 198
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b311-random
+ +
+
+197	        self._link_id = (
+198	            f"{randint(0, 999999)}{hash(self._meta)}" if (link or meta) else ""
+199	        )
+
+
+ + +
+
+ +
+
+ blacklist: Standard pseudo-random generators are not suitable for security/cryptographic purposes.
+ Test ID: B311
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-330
+ File: ./venv/lib/python3.12/site-packages/rich/style.py
+ Line number: 248
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b311-random
+ +
+
+247	        style._meta = dumps(meta)
+248	        style._link_id = f"{randint(0, 999999)}{hash(style._meta)}"
+249	        style._hash = None
+
+
+ + +
+
+ +
+
+ blacklist: Pickle and modules that wrap it can be unsafe when used to deserialize untrusted data, possible security issue.
+ Test ID: B301
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-502
+ File: ./venv/lib/python3.12/site-packages/rich/style.py
+ Line number: 471
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b301-pickle
+ +
+
+470	        """Get meta information (can not be changed after construction)."""
+471	        return {} if self._meta is None else cast(Dict[str, Any], loads(self._meta))
+472	
+
+
+ + +
+
+ +
+
+ blacklist: Standard pseudo-random generators are not suitable for security/cryptographic purposes.
+ Test ID: B311
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-330
+ File: ./venv/lib/python3.12/site-packages/rich/style.py
+ Line number: 486
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b311-random
+ +
+
+485	        style._link = self._link
+486	        style._link_id = f"{randint(0, 999999)}" if self._link else ""
+487	        style._null = False
+
+
+ + +
+
+ +
+
+ blacklist: Standard pseudo-random generators are not suitable for security/cryptographic purposes.
+ Test ID: B311
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-330
+ File: ./venv/lib/python3.12/site-packages/rich/style.py
+ Line number: 638
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b311-random
+ +
+
+637	        style._link = self._link
+638	        style._link_id = f"{randint(0, 999999)}" if self._link else ""
+639	        style._hash = self._hash
+
+
+ + +
+
+ +
+
+ blacklist: Standard pseudo-random generators are not suitable for security/cryptographic purposes.
+ Test ID: B311
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-330
+ File: ./venv/lib/python3.12/site-packages/rich/style.py
+ Line number: 684
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b311-random
+ +
+
+683	        style._link = link
+684	        style._link_id = f"{randint(0, 999999)}" if link else ""
+685	        style._hash = None
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/rich/syntax.py
+ Line number: 507
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+506	                    """Split tokens to one per line."""
+507	                    assert lexer  # required to make MyPy happy - we know lexer is not None at this point
+508	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/rich/text.py
+ Line number: 907
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+906	        """
+907	        assert len(character) == 1, "Character must be a string of length 1"
+908	        if count:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/rich/text.py
+ Line number: 924
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+923	        """
+924	        assert len(character) == 1, "Character must be a string of length 1"
+925	        if count:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/rich/text.py
+ Line number: 940
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+939	        """
+940	        assert len(character) == 1, "Character must be a string of length 1"
+941	        if count:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/rich/text.py
+ Line number: 1079
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1078	        """
+1079	        assert separator, "separator must not be empty"
+1080	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/rich/traceback.py
+ Line number: 342
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+341	            if not isinstance(suppress_entity, str):
+342	                assert (
+343	                    suppress_entity.__file__ is not None
+344	                ), f"{suppress_entity!r} must be a module with '__file__' attribute"
+345	                path = os.path.dirname(suppress_entity.__file__)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/rich/traceback.py
+ Line number: 798
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+797	            if excluded:
+798	                assert exclude_frames is not None
+799	                yield Text(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/mssql/base.py
+ Line number: 1885
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1884	            if TYPE_CHECKING:
+1885	                assert is_sql_compiler(self.compiled)
+1886	                assert isinstance(self.compiled.compile_state, DMLState)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/mssql/base.py
+ Line number: 1886
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1885	                assert is_sql_compiler(self.compiled)
+1886	                assert isinstance(self.compiled.compile_state, DMLState)
+1887	                assert isinstance(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/mssql/base.py
+ Line number: 1887
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1886	                assert isinstance(self.compiled.compile_state, DMLState)
+1887	                assert isinstance(
+1888	                    self.compiled.compile_state.dml_table, TableClause
+1889	                )
+1890	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/mssql/base.py
+ Line number: 1969
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1968	            if TYPE_CHECKING:
+1969	                assert is_sql_compiler(self.compiled)
+1970	                assert isinstance(self.compiled.compile_state, DMLState)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/mssql/base.py
+ Line number: 1970
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1969	                assert is_sql_compiler(self.compiled)
+1970	                assert isinstance(self.compiled.compile_state, DMLState)
+1971	                assert isinstance(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/mssql/base.py
+ Line number: 1971
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1970	                assert isinstance(self.compiled.compile_state, DMLState)
+1971	                assert isinstance(
+1972	                    self.compiled.compile_state.dml_table, TableClause
+1973	                )
+1974	            conn._cursor_execute(
+
+
+ + +
+
+ +
+
+ try_except_pass: Try, Except, Pass detected.
+ Test ID: B110
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/mssql/base.py
+ Line number: 2000
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b110_try_except_pass.html
+ +
+
+1999	                )
+2000	            except Exception:
+2001	                pass
+2002	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/mssql/base.py
+ Line number: 2339
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2338	        else:
+2339	            assert False, "expected Insert, Update or Delete statement"
+2340	
+
+
+ + +
+
+ +
+
+ hardcoded_password_string: Possible hardcoded password: '['
+ Test ID: B105
+ Severity: LOW
+ Confidence: MEDIUM
+ CWE: CWE-259
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/mssql/base.py
+ Line number: 2973
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b105_hardcoded_password_string.html
+ +
+
+2972	            continue
+2973	        if token == "[":
+2974	            bracket = True
+
+
+ + +
+
+ +
+
+ hardcoded_password_string: Possible hardcoded password: ']'
+ Test ID: B105
+ Severity: LOW
+ Confidence: MEDIUM
+ CWE: CWE-259
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/mssql/base.py
+ Line number: 2976
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b105_hardcoded_password_string.html
+ +
+
+2975	            has_brackets = True
+2976	        elif token == "]":
+2977	            bracket = False
+
+
+ + +
+
+ +
+
+ hardcoded_password_string: Possible hardcoded password: '.'
+ Test ID: B105
+ Severity: LOW
+ Confidence: MEDIUM
+ CWE: CWE-259
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/mssql/base.py
+ Line number: 2978
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b105_hardcoded_password_string.html
+ +
+
+2977	            bracket = False
+2978	        elif not bracket and token == ".":
+2979	            if has_brackets:
+
+
+ + +
+
+ +
+
+ hardcoded_sql_expressions: Possible SQL injection vector through string-based query construction.
+ Test ID: B608
+ Severity: MEDIUM
+ Confidence: MEDIUM
+ CWE: CWE-89
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/mssql/base.py
+ Line number: 3210
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b608_hardcoded_sql_expressions.html
+ +
+
+3209	                (
+3210	                    "SELECT name FROM {} WHERE name IN "
+3211	                    "('dm_exec_sessions', 'dm_pdw_nodes_exec_sessions')"
+3212	                ).format(view_name)
+3213	            )
+3214	            row = cursor.fetchone()
+
+
+ + +
+
+ +
+
+ hardcoded_sql_expressions: Possible SQL injection vector through string-based query construction.
+ Test ID: B608
+ Severity: MEDIUM
+ Confidence: MEDIUM
+ CWE: CWE-89
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/mssql/base.py
+ Line number: 3224
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b608_hardcoded_sql_expressions.html
+ +
+
+3223	            cursor.execute(
+3224	                """
+3225	                    SELECT CASE transaction_isolation_level
+3226	                    WHEN 0 THEN NULL
+3227	                    WHEN 1 THEN 'READ UNCOMMITTED'
+3228	                    WHEN 2 THEN 'READ COMMITTED'
+3229	                    WHEN 3 THEN 'REPEATABLE READ'
+3230	                    WHEN 4 THEN 'SERIALIZABLE'
+3231	                    WHEN 5 THEN 'SNAPSHOT' END
+3232	                    AS TRANSACTION_ISOLATION_LEVEL
+3233	                    FROM {}
+3234	                    where session_id = @@SPID
+3235	                """.format(
+3236	                    view_name
+
+
+ + +
+
+ +
+
+ hardcoded_sql_expressions: Possible SQL injection vector through string-based query construction.
+ Test ID: B608
+ Severity: MEDIUM
+ Confidence: LOW
+ CWE: CWE-89
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/mssql/base.py
+ Line number: 3436
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b608_hardcoded_sql_expressions.html
+ +
+
+3435	            sql.text(
+3436	                f"""
+3437	select
+3438	    ind.index_id,
+3439	    ind.is_unique,
+3440	    ind.name,
+3441	    ind.type,
+3442	    {filter_definition}
+3443	from
+3444	    sys.indexes as ind
+3445	join sys.tables as tab on
+3446	    ind.object_id = tab.object_id
+3447	join sys.schemas as sch on
+3448	    sch.schema_id = tab.schema_id
+3449	where
+3450	    tab.name = :tabname
+3451	    and sch.name = :schname
+3452	    and ind.is_primary_key = 0
+3453	    and ind.type != 0
+3454	order by
+3455	    ind.name
+3456	                """
+3457	            )
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/mysql/aiomysql.py
+ Line number: 95
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+94	    def ping(self, reconnect: bool) -> None:
+95	        assert not reconnect
+96	        self.await_(self._connection.ping(reconnect))
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/mysql/asyncmy.py
+ Line number: 94
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+93	    def ping(self, reconnect: bool) -> None:
+94	        assert not reconnect
+95	        return self.await_(self._do_ping())
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/mysql/base.py
+ Line number: 1771
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1770	    ) -> str:
+1771	        assert select._for_update_arg is not None
+1772	        if select._for_update_arg.read:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/mysql/base.py
+ Line number: 1836
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1835	        else:
+1836	            assert limit_clause is not None
+1837	            # No offset provided, so just use the limit
+
+
+ + +
+
+ +
+
+ hardcoded_sql_expressions: Possible SQL injection vector through string-based query construction.
+ Test ID: B608
+ Severity: MEDIUM
+ Confidence: LOW
+ CWE: CWE-89
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/mysql/base.py
+ Line number: 1911
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b608_hardcoded_sql_expressions.html
+ +
+
+1910	        return (
+1911	            "SELECT %(outer)s FROM (SELECT %(inner)s) "
+1912	            "as _empty_set WHERE 1!=1"
+1913	            % {
+1914	                "inner": ", ".join(
+1915	                    "1 AS _in_%s" % idx
+1916	                    for idx, type_ in enumerate(element_types)
+1917	                ),
+1918	                "outer": ", ".join(
+1919	                    "_in_%s" % idx for idx, type_ in enumerate(element_types)
+1920	                ),
+1921	            }
+1922	        )
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/mysql/base.py
+ Line number: 1955
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1954	    ) -> str:
+1955	        assert binary.modifiers is not None
+1956	        flags = binary.modifiers["flags"]
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/mysql/base.py
+ Line number: 1989
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1988	    ) -> str:
+1989	        assert binary.modifiers is not None
+1990	        flags = binary.modifiers["flags"]
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/mysql/base.py
+ Line number: 3059
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+3058	
+3059	        assert schema is not None
+3060	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/mysql/base.py
+ Line number: 3210
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+3209	            mdb_version = self._mariadb_normalized_version_info
+3210	            assert mdb_version is not None
+3211	            if mdb_version > (10, 2) and mdb_version < (10, 2, 9):
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/mysql/base.py
+ Line number: 3297
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+3296	            schema = self.default_schema_name
+3297	        assert schema is not None
+3298	        charset = self._connection_charset
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/mysql/base.py
+ Line number: 3821
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+3820	        if full_name is None:
+3821	            assert table is not None
+3822	            full_name = self.identifier_preparer.format_table(table)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/mysql/base.py
+ Line number: 3867
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+3866	        if full_name is None:
+3867	            assert table is not None
+3868	            full_name = self.identifier_preparer.format_table(table)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/mysql/enumerated.py
+ Line number: 96
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+95	        if TYPE_CHECKING:
+96	            assert isinstance(impl, ENUM)
+97	        kw.setdefault("validate_strings", impl.validate_strings)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/mysql/enumerated.py
+ Line number: 221
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+220	                        value = super_convert(value)
+221	                        assert value is not None
+222	                    if TYPE_CHECKING:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/mysql/enumerated.py
+ Line number: 223
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+222	                    if TYPE_CHECKING:
+223	                        assert isinstance(value, str)
+224	                    return set(re.findall(r"[^,]+", value))
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/mysql/mariadbconnector.py
+ Line number: 109
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+108	        if TYPE_CHECKING:
+109	            assert isinstance(self.compiled, SQLCompiler)
+110	        if self.isinsert and self.compiled.postfetch_lastrowid:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/mysql/mariadbconnector.py
+ Line number: 115
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+114	        if TYPE_CHECKING:
+115	            assert self._lastrowid is not None
+116	        return self._lastrowid
+
+
+ + +
+
+ +
+
+ try_except_pass: Try, Except, Pass detected.
+ Test ID: B110
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/mysql/mysqlconnector.py
+ Line number: 215
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b110_try_except_pass.html
+ +
+
+214	                opts["client_flags"] = client_flags
+215	            except Exception:
+216	                pass
+217	
+
+
+ + +
+
+ +
+
+ hardcoded_password_funcarg: Possible hardcoded password: 'passwd'
+ Test ID: B106
+ Severity: LOW
+ Confidence: MEDIUM
+ CWE: CWE-259
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/mysql/mysqldb.py
+ Line number: 205
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b106_hardcoded_password_funcarg.html
+ +
+
+204	            _translate_args = dict(
+205	                database="db", username="user", password="passwd"
+206	            )
+207	
+208	        opts = url.translate_connect_args(**_translate_args)
+
+
+ + +
+
+ +
+
+ try_except_pass: Try, Except, Pass detected.
+ Test ID: B110
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/mysql/provision.py
+ Line number: 67
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b110_try_except_pass.html
+ +
+
+66	            _mysql_drop_db(cfg, conn, ident)
+67	        except Exception:
+68	            pass
+69	
+
+
+ + +
+
+ +
+
+ hardcoded_sql_expressions: Possible SQL injection vector through string-based query construction.
+ Test ID: B608
+ Severity: MEDIUM
+ Confidence: LOW
+ CWE: CWE-89
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/oracle/base.py
+ Line number: 1914
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b608_hardcoded_sql_expressions.html
+ +
+
+1913	        return self._execute_scalar(
+1914	            "SELECT "
+1915	            + self.identifier_preparer.format_sequence(seq)
+1916	            + ".nextval FROM DUAL",
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/oracle/base.py
+ Line number: 3264
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+3263	                if row_dict["descend"].lower() != "asc":
+3264	                    assert row_dict["descend"].lower() == "desc"
+3265	                    cs = index_dict.setdefault("column_sorting", {})
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/oracle/base.py
+ Line number: 3268
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+3267	            else:
+3268	                assert row_dict["descend"].lower() == "asc"
+3269	                cn = self.normalize_name(row_dict["column_name"])
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/oracle/base.py
+ Line number: 3481
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+3480	
+3481	            assert constraint_name is not None
+3482	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/oracle/base.py
+ Line number: 3633
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+3632	
+3633	            assert constraint_name is not None
+3634	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/oracle/base.py
+ Line number: 3684
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+3683	            if synonyms:
+3684	                assert len(synonyms) == 1
+3685	                row_dict = synonyms[0]
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/oracle/cx_oracle.py
+ Line number: 835
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+834	            out_parameters = self.out_parameters
+835	            assert out_parameters is not None
+836	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/oracle/cx_oracle.py
+ Line number: 854
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+853	
+854	                        assert cx_Oracle is not None
+855	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/oracle/cx_oracle.py
+ Line number: 1026
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1025	        # False.
+1026	        assert not self.compiled.returning
+1027	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/oracle/cx_oracle.py
+ Line number: 1270
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1269	            decimal_char = value.lstrip("0")[1]
+1270	            assert not decimal_char[0].isdigit()
+1271	
+
+
+ + +
+
+ +
+
+ blacklist: Standard pseudo-random generators are not suitable for security/cryptographic purposes.
+ Test ID: B311
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-330
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/oracle/cx_oracle.py
+ Line number: 1496
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b311-random
+ +
+
+1495	    def create_xid(self):
+1496	        id_ = random.randint(0, 2**128)
+1497	        return (0x1234, "%032x" % id_, "%032x" % 9)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/oracle/provision.py
+ Line number: 171
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+170	def _connect_with_retry(dialect, conn_rec, cargs, cparams):
+171	    assert dialect.driver == "cx_oracle"
+172	
+
+
+ + +
+
+ +
+
+ try_except_pass: Try, Except, Pass detected.
+ Test ID: B110
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/oracle/provision.py
+ Line number: 226
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b110_try_except_pass.html
+ +
+
+225	            sc = dbapi_connection.stmtcachesize
+226	        except:
+227	            # connection closed
+228	            pass
+229	        else:
+
+
+ + +
+
+ +
+
+ hardcoded_password_funcarg: Possible hardcoded password: 'xe'
+ Test ID: B106
+ Severity: LOW
+ Confidence: MEDIUM
+ CWE: CWE-259
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/oracle/provision.py
+ Line number: 270
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b106_hardcoded_password_funcarg.html
+ +
+
+269	    url = sa_url.make_url(url)
+270	    return url.set(username=ident, password="xe")
+271	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/postgresql/asyncpg.py
+ Line number: 633
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+632	    def _buffer_rows(self):
+633	        assert self._cursor is not None
+634	        new_rows = self._adapt_connection.await_(self._cursor.fetch(50))
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/postgresql/asyncpg.py
+ Line number: 663
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+662	
+663	        assert self._cursor is not None
+664	        rb = self._rowbuffer
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/postgresql/asyncpg.py
+ Line number: 1136
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1135	        if multihosts:
+1136	            assert multiports
+1137	            if len(multihosts) == 1:
+
+
+ + +
+
+ +
+
+ hardcoded_sql_expressions: Possible SQL injection vector through string-based query construction.
+ Test ID: B608
+ Severity: MEDIUM
+ Confidence: LOW
+ CWE: CWE-89
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/postgresql/base.py
+ Line number: 2291
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b608_hardcoded_sql_expressions.html
+ +
+
+2290	
+2291	        return "ON CONFLICT %s DO UPDATE SET %s" % (target_text, action_text)
+2292	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/postgresql/base.py
+ Line number: 3431
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+3430	                        if TYPE_CHECKING:
+3431	                            assert isinstance(h, str)
+3432	                            assert isinstance(p, str)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/postgresql/base.py
+ Line number: 3432
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+3431	                            assert isinstance(h, str)
+3432	                            assert isinstance(p, str)
+3433	                        hosts = (h,)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/postgresql/base.py
+ Line number: 4889
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+4888	                        # supported in included columns".
+4889	                        assert all(
+4890	                            not is_expr
+4891	                            for is_expr in all_elements_is_expr[indnkeyatts:]
+4892	                        )
+4893	                        idx_elements_opclass = all_elements_opclass[
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/postgresql/psycopg.py
+ Line number: 485
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+484	                # this one
+485	                assert self._psycopg_adapters_map
+486	                register_hstore(info, self._psycopg_adapters_map)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/postgresql/psycopg.py
+ Line number: 489
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+488	                # register the adapter for this connection
+489	                assert connection.connection
+490	                register_hstore(info, connection.connection.driver_connection)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/postgresql/ranges.py
+ Line number: 653
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+652	
+653	        assert False, f"Unhandled case computing {self} - {other}"
+654	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/postgresql/types.py
+ Line number: 61
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+60	        if TYPE_CHECKING:
+61	            assert isinstance(self, TypeEngine)
+62	        return self
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/sqlite/aiosqlite.py
+ Line number: 242
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+241	    def fetchone(self) -> Optional[Any]:
+242	        assert self._cursor is not None
+243	        return self.await_(self._cursor.fetchone())
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/sqlite/aiosqlite.py
+ Line number: 246
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+245	    def fetchmany(self, size: Optional[int] = None) -> Sequence[Any]:
+246	        assert self._cursor is not None
+247	        if size is None:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/sqlite/aiosqlite.py
+ Line number: 252
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+251	    def fetchall(self) -> Sequence[Any]:
+252	        assert self._cursor is not None
+253	        return self.await_(self._cursor.fetchall())
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/sqlite/base.py
+ Line number: 1163
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1162	        if truncate_microseconds:
+1163	            assert "storage_format" not in kwargs, (
+1164	                "You can specify only "
+1165	                "one of truncate_microseconds or storage_format."
+1166	            )
+1167	            assert "regexp" not in kwargs, (
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/sqlite/base.py
+ Line number: 1167
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1166	            )
+1167	            assert "regexp" not in kwargs, (
+1168	                "You can specify only one of "
+1169	                "truncate_microseconds or regexp."
+1170	            )
+1171	            self._storage_format = (
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/sqlite/base.py
+ Line number: 1357
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1356	        if truncate_microseconds:
+1357	            assert "storage_format" not in kwargs, (
+1358	                "You can specify only "
+1359	                "one of truncate_microseconds or storage_format."
+1360	            )
+1361	            assert "regexp" not in kwargs, (
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/sqlite/base.py
+ Line number: 1361
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1360	            )
+1361	            assert "regexp" not in kwargs, (
+1362	                "You can specify only one of "
+1363	                "truncate_microseconds or regexp."
+1364	            )
+1365	            self._storage_format = "%(hour)02d:%(minute)02d:%(second)02d"
+
+
+ + +
+
+ +
+
+ hardcoded_sql_expressions: Possible SQL injection vector through string-based query construction.
+ Test ID: B608
+ Severity: MEDIUM
+ Confidence: LOW
+ CWE: CWE-89
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/sqlite/base.py
+ Line number: 1573
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b608_hardcoded_sql_expressions.html
+ +
+
+1572	    def visit_empty_set_expr(self, element_types, **kw):
+1573	        return "SELECT %s FROM (SELECT %s) WHERE 1!=1" % (
+1574	            ", ".join("1" for type_ in element_types or [INTEGER()]),
+1575	            ", ".join("1" for type_ in element_types or [INTEGER()]),
+1576	        )
+1577	
+
+
+ + +
+
+ +
+
+ hardcoded_sql_expressions: Possible SQL injection vector through string-based query construction.
+ Test ID: B608
+ Severity: MEDIUM
+ Confidence: LOW
+ CWE: CWE-89
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/sqlite/base.py
+ Line number: 1691
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b608_hardcoded_sql_expressions.html
+ +
+
+1690	
+1691	        return "ON CONFLICT %s DO UPDATE SET %s" % (target_text, action_text)
+1692	
+
+
+ + +
+
+ +
+
+ hardcoded_password_string: Possible hardcoded password: 'NULL'
+ Test ID: B105
+ Severity: LOW
+ Confidence: MEDIUM
+ CWE: CWE-259
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/sqlite/base.py
+ Line number: 2104
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b105_hardcoded_password_string.html
+ +
+
+2103	
+2104	    default_metavalue_token = "NULL"
+2105	    """for INSERT... VALUES (DEFAULT) syntax, the token to put in the
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/sqlite/base.py
+ Line number: 2260
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2259	        else:
+2260	            assert False, "Unknown isolation level %s" % value
+2261	
+
+
+ + +
+
+ +
+
+ hardcoded_sql_expressions: Possible SQL injection vector through string-based query construction.
+ Test ID: B608
+ Severity: MEDIUM
+ Confidence: LOW
+ CWE: CWE-89
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/sqlite/base.py
+ Line number: 2290
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b608_hardcoded_sql_expressions.html
+ +
+
+2289	        query = (
+2290	            f"SELECT name FROM {main} "
+2291	            f"WHERE type='{type_}'{filter_table} "
+2292	            "ORDER BY name"
+2293	        )
+
+
+ + +
+
+ +
+
+ hardcoded_sql_expressions: Possible SQL injection vector through string-based query construction.
+ Test ID: B608
+ Severity: MEDIUM
+ Confidence: LOW
+ CWE: CWE-89
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/sqlite/base.py
+ Line number: 2358
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b608_hardcoded_sql_expressions.html
+ +
+
+2357	            master = f"{qschema}.sqlite_master"
+2358	            s = ("SELECT sql FROM %s WHERE name = ? AND type='view'") % (
+2359	                master,
+2360	            )
+2361	            rs = connection.exec_driver_sql(s, (view_name,))
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/sqlite/base.py
+ Line number: 2428
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2427	                )
+2428	                assert match, f"create table not found in {tablesql}"
+2429	                tablesql = match.group(1).strip()
+
+
+ + +
+
+ +
+
+ hardcoded_sql_expressions: Possible SQL injection vector through string-based query construction.
+ Test ID: B608
+ Severity: MEDIUM
+ Confidence: LOW
+ CWE: CWE-89
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/sqlite/base.py
+ Line number: 2946
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b608_hardcoded_sql_expressions.html
+ +
+
+2945	                s = (
+2946	                    "SELECT sql FROM %(schema)ssqlite_master "
+2947	                    "WHERE name = ? "
+2948	                    "AND type = 'index'" % {"schema": schema_expr}
+2949	                )
+
+
+ + +
+
+ +
+
+ hardcoded_sql_expressions: Possible SQL injection vector through string-based query construction.
+ Test ID: B608
+ Severity: MEDIUM
+ Confidence: LOW
+ CWE: CWE-89
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/sqlite/base.py
+ Line number: 3012
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b608_hardcoded_sql_expressions.html
+ +
+
+3011	            s = (
+3012	                "SELECT sql FROM "
+3013	                " (SELECT * FROM %(schema)ssqlite_master UNION ALL "
+3014	                "  SELECT * FROM %(schema)ssqlite_temp_master) "
+3015	                "WHERE name = ? "
+3016	                "AND type in ('table', 'view')" % {"schema": schema_expr}
+3017	            )
+
+
+ + +
+
+ +
+
+ hardcoded_sql_expressions: Possible SQL injection vector through string-based query construction.
+ Test ID: B608
+ Severity: MEDIUM
+ Confidence: LOW
+ CWE: CWE-89
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/sqlite/base.py
+ Line number: 3021
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b608_hardcoded_sql_expressions.html
+ +
+
+3020	            s = (
+3021	                "SELECT sql FROM %(schema)ssqlite_master "
+3022	                "WHERE name = ? "
+3023	                "AND type in ('table', 'view')" % {"schema": schema_expr}
+3024	            )
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/sqlite/provision.py
+ Line number: 54
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+53	    if filename and filename != ":memory:":
+54	        assert "test_schema" not in filename
+55	        tokens = re.split(r"[_\.]", filename)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/sqlite/provision.py
+ Line number: 67
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+66	
+67	        assert name_token, f"sqlite filename has no name token: {url.database}"
+68	
+
+
+ + +
+
+ +
+
+ hardcoded_password_funcarg: Possible hardcoded password: 'test'
+ Test ID: B106
+ Severity: LOW
+ Confidence: MEDIUM
+ CWE: CWE-259
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/sqlite/provision.py
+ Line number: 78
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b106_hardcoded_password_funcarg.html
+ +
+
+77	    if needs_enc:
+78	        url = url.set(password="test")
+79	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/sqlite/pysqlite.py
+ Line number: 674
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+673	                m = nis.search(sql)
+674	                assert not m, f"Found {nis.pattern!r} in {sql!r}"
+675	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/dialects/sqlite/pysqlite.py
+ Line number: 685
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+684	            if parameters:
+685	                assert isinstance(parameters, tuple)
+686	                return {
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/engine/base.py
+ Line number: 627
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+626	        dbapi_connection = self.connection.dbapi_connection
+627	        assert dbapi_connection is not None
+628	        try:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/engine/base.py
+ Line number: 746
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+745	            pool_proxied_connection = self._dbapi_connection
+746	            assert pool_proxied_connection is not None
+747	            pool_proxied_connection.invalidate(exception)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/engine/base.py
+ Line number: 1190
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1189	
+1190	        assert isinstance(self._transaction, TwoPhaseTransaction)
+1191	        try:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/engine/base.py
+ Line number: 1201
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1200	        if self._still_open_and_dbapi_connection_is_valid:
+1201	            assert isinstance(self._transaction, TwoPhaseTransaction)
+1202	            try:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/engine/base.py
+ Line number: 1213
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1212	
+1213	        assert isinstance(self._transaction, TwoPhaseTransaction)
+1214	        try:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/engine/base.py
+ Line number: 2362
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2361	            elif should_wrap:
+2362	                assert sqlalchemy_exception is not None
+2363	                raise sqlalchemy_exception.with_traceback(exc_info[2]) from e
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/engine/base.py
+ Line number: 2365
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2364	            else:
+2365	                assert exc_info[1] is not None
+2366	                raise exc_info[1].with_traceback(exc_info[2])
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/engine/base.py
+ Line number: 2373
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2372	                    dbapi_conn_wrapper = self._dbapi_connection
+2373	                    assert dbapi_conn_wrapper is not None
+2374	                    if invalidate_pool_on_disconnect:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/engine/base.py
+ Line number: 2447
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2446	        elif should_wrap:
+2447	            assert sqlalchemy_exception is not None
+2448	            raise sqlalchemy_exception.with_traceback(exc_info[2]) from e
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/engine/base.py
+ Line number: 2450
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2449	        else:
+2450	            assert exc_info[1] is not None
+2451	            raise exc_info[1].with_traceback(exc_info[2])
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/engine/base.py
+ Line number: 2599
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2598	        finally:
+2599	            assert not self.is_active
+2600	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/engine/base.py
+ Line number: 2621
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2620	        finally:
+2621	            assert not self.is_active
+2622	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/engine/base.py
+ Line number: 2642
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2641	        finally:
+2642	            assert not self.is_active
+2643	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/engine/base.py
+ Line number: 2688
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2687	    def __init__(self, connection: Connection):
+2688	        assert connection._transaction is None
+2689	        if connection._trans_context_manager:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/engine/base.py
+ Line number: 2699
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2698	        if self.is_active:
+2699	            assert self.connection._transaction is self
+2700	            self.is_active = False
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/engine/base.py
+ Line number: 2731
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2730	
+2731	        assert not self.is_active
+2732	        assert self.connection._transaction is not self
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/engine/base.py
+ Line number: 2732
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2731	        assert not self.is_active
+2732	        assert self.connection._transaction is not self
+2733	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/engine/base.py
+ Line number: 2742
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2741	        if self.is_active:
+2742	            assert self.connection._transaction is self
+2743	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/engine/base.py
+ Line number: 2765
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2764	
+2765	        assert not self.is_active
+2766	        assert self.connection._transaction is not self
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/engine/base.py
+ Line number: 2766
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2765	        assert not self.is_active
+2766	        assert self.connection._transaction is not self
+2767	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/engine/base.py
+ Line number: 2806
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2805	    def __init__(self, connection: Connection):
+2806	        assert connection._transaction is not None
+2807	        if connection._trans_context_manager:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/engine/base.py
+ Line number: 2852
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2851	
+2852	        assert not self.is_active
+2853	        if deactivate_from_connection:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/engine/base.py
+ Line number: 2854
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2853	        if deactivate_from_connection:
+2854	            assert self.connection._nested_transaction is not self
+2855	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/engine/create.py
+ Line number: 744
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+743	            ) -> None:
+744	                assert do_on_connect is not None
+745	                do_on_connect(dbapi_connection)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/engine/cursor.py
+ Line number: 218
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+217	    def _remove_processors(self) -> CursorResultMetaData:
+218	        assert not self._tuplefilter
+219	        return self._make_new_metadata(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/engine/cursor.py
+ Line number: 236
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+235	    ) -> CursorResultMetaData:
+236	        assert not self._tuplefilter
+237	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/engine/cursor.py
+ Line number: 313
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+312	        if TYPE_CHECKING:
+313	            assert isinstance(invoked_statement, elements.ClauseElement)
+314	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/engine/cursor.py
+ Line number: 318
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+317	
+318	        assert invoked_statement is not None
+319	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/engine/cursor.py
+ Line number: 338
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+337	
+338	        assert not self._tuplefilter
+339	        return self._make_new_metadata(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/engine/cursor.py
+ Line number: 874
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+873	            x = self._key_fallback(key, ke, raiseerr)
+874	            assert x is None
+875	            return None
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/engine/cursor.py
+ Line number: 1112
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1111	        # we only expect to have a _NoResultMetaData() here right now.
+1112	        assert not result._metadata.returns_rows
+1113	        result._metadata._we_dont_return_rows(err)  # type: ignore[union-attr]
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/engine/cursor.py
+ Line number: 1384
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1383	        else:
+1384	            assert dbapi_cursor is not None
+1385	            self._rowbuffer = collections.deque(dbapi_cursor.fetchall())
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/engine/cursor.py
+ Line number: 1589
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1588	        else:
+1589	            assert context._num_sentinel_cols == 0
+1590	            self._metadata = self._no_result_metadata
+
+
+ + +
+
+ +
+
+ hardcoded_password_string: Possible hardcoded password: 'DEFAULT'
+ Test ID: B105
+ Severity: LOW
+ Confidence: MEDIUM
+ CWE: CWE-259
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/engine/default.py
+ Line number: 226
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b105_hardcoded_password_string.html
+ +
+
+225	
+226	    default_metavalue_token = "DEFAULT"
+227	    """for INSERT... VALUES (DEFAULT) syntax, the token to put in the
+
+
+ + +
+
+ +
+
+ blacklist: Standard pseudo-random generators are not suitable for security/cryptographic purposes.
+ Test ID: B311
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-330
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/engine/default.py
+ Line number: 765
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b311-random
+ +
+
+764	
+765	        return "_sa_%032x" % random.randint(0, 2**128)
+766	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/engine/default.py
+ Line number: 797
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+796	        imv = compiled._insertmanyvalues
+797	        assert imv is not None
+798	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/engine/default.py
+ Line number: 848
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+847	                # would have assured this but pylance thinks not
+848	                assert result is not None
+849	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/engine/default.py
+ Line number: 855
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+854	                        # integer autoincrement, do a simple sort.
+855	                        assert not composite_sentinel
+856	                        result.extend(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/engine/default.py
+ Line number: 863
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+862	                    # with parameters
+863	                    assert imv.sentinel_param_keys
+864	                    assert imv.sentinel_columns
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/engine/default.py
+ Line number: 864
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+863	                    assert imv.sentinel_param_keys
+864	                    assert imv.sentinel_columns
+865	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/engine/default.py
+ Line number: 1006
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1005	        if self._on_connect_isolation_level is not None:
+1006	            assert (
+1007	                self._on_connect_isolation_level == "AUTOCOMMIT"
+1008	                or self._on_connect_isolation_level
+1009	                == self.default_isolation_level
+1010	            )
+1011	            self._assert_and_set_isolation_level(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/engine/default.py
+ Line number: 1015
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1014	        else:
+1015	            assert self.default_isolation_level is not None
+1016	            self._assert_and_set_isolation_level(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/engine/default.py
+ Line number: 1355
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1354	            if TYPE_CHECKING:
+1355	                assert isinstance(dml_statement, UpdateBase)
+1356	            self.is_crud = True
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/engine/default.py
+ Line number: 1365
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1364	            # dont mix implicit and explicit returning
+1365	            assert not (iir and ier)
+1366	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/engine/default.py
+ Line number: 1492
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1491	            core_positional_parameters: MutableSequence[Sequence[Any]] = []
+1492	            assert positiontup is not None
+1493	            for compiled_params in self.compiled_parameters:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/engine/default.py
+ Line number: 1614
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1613	        gen_time = self.compiled._gen_time
+1614	        assert gen_time is not None
+1615	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/engine/default.py
+ Line number: 1664
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1663	        if TYPE_CHECKING:
+1664	            assert isinstance(self.compiled, SQLCompiler)
+1665	        return self.compiled.postfetch
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/engine/default.py
+ Line number: 1670
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1669	        if TYPE_CHECKING:
+1670	            assert isinstance(self.compiled, SQLCompiler)
+1671	        if self.isinsert:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/engine/default.py
+ Line number: 1965
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1964	        elif self._num_sentinel_cols:
+1965	            assert self.execute_style is ExecuteStyle.INSERTMANYVALUES
+1966	            # strip out the sentinel columns from cursor description
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/engine/default.py
+ Line number: 1990
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1989	                # support is added here.
+1990	                assert result._metadata.returns_rows
+1991	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/engine/default.py
+ Line number: 2022
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2021	            # the rows have all been fetched however.
+2022	            assert result._metadata.returns_rows
+2023	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/engine/default.py
+ Line number: 2301
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2300	        else:
+2301	            assert column is not None
+2302	            assert parameters is not None
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/engine/default.py
+ Line number: 2302
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2301	            assert column is not None
+2302	            assert parameters is not None
+2303	        compile_state = cast(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/engine/default.py
+ Line number: 2306
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2305	        )
+2306	        assert compile_state is not None
+2307	        if (
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/engine/default.py
+ Line number: 2318
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2317	                index = 0
+2318	            assert compile_state._dict_parameters is not None
+2319	            keys = compile_state._dict_parameters.keys()
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/engine/reflection.py
+ Line number: 1672
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1671	            default_text = col_d["default"]
+1672	            assert default_text is not None
+1673	            if isinstance(default_text, TextClause):
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/engine/result.py
+ Line number: 149
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+148	    ) -> Optional[NoReturn]:
+149	        assert raiseerr
+150	        raise KeyError(key) from err
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/engine/result.py
+ Line number: 551
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+550	        make_row = self._row_getter
+551	        assert make_row is not None
+552	        rows = self._fetchall_impl()
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/engine/result.py
+ Line number: 691
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+690	                        num = len(rows)
+691	                        assert make_row is not None
+692	                        collect.extend(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/engine/result.py
+ Line number: 699
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+698	
+699	                assert num is not None
+700	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/engine/result.py
+ Line number: 808
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+807	                        if strategy:
+808	                            assert next_row is not _NO_ROW
+809	                            if existing_row_hash == strategy(next_row):
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/engine/result.py
+ Line number: 867
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+866	
+867	        assert self._generate_rows
+868	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/engine/result.py
+ Line number: 873
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+872	    def _unique_strategy(self) -> _UniqueFilterStateType:
+873	        assert self._unique_filter_state is not None
+874	        uniques, strategy = self._unique_filter_state
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/engine/util.py
+ Line number: 152
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+151	                if not out_of_band_exit:
+152	                    assert subject is not None
+153	                    subject._trans_context_manager = self._outer_trans_ctx
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/engine/util.py
+ Line number: 165
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+164	                if not out_of_band_exit:
+165	                    assert subject is not None
+166	                    subject._trans_context_manager = self._outer_trans_ctx
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/event/attr.py
+ Line number: 182
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+181	        target = event_key.dispatch_target
+182	        assert isinstance(
+183	            target, type
+184	        ), "Class-level Event targets must be classes."
+185	        if not getattr(target, "_sa_propagate_class_events", True):
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/event/attr.py
+ Line number: 345
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+344	
+345	        assert obj._instance_cls is not None
+346	        existing = getattr(obj, self.name)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/event/attr.py
+ Line number: 355
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+354	                # with freethreaded.
+355	                assert isinstance(existing, _ListenerCollection)
+356	                return existing
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/event/base.py
+ Line number: 146
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+145	        if instance_cls:
+146	            assert parent is not None
+147	            try:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/event/base.py
+ Line number: 194
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+193	        """
+194	        assert "_joined_dispatch_cls" in self.__class__.__dict__
+195	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/event/base.py
+ Line number: 317
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+316	            dispatch_target_cls = cls._dispatch_target
+317	            assert dispatch_target_cls is not None
+318	            if (
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/event/legacy.py
+ Line number: 102
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+101	            if conv is not None:
+102	                assert not has_kw
+103	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/event/legacy.py
+ Line number: 106
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+105	                    util.warn_deprecated(warning_txt, version=since)
+106	                    assert conv is not None
+107	                    return fn(*conv(*args))
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/event/legacy.py
+ Line number: 234
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+233	    if getattr(fn, "_omit_standard_example", False):
+234	        assert fn.__doc__
+235	        return fn.__doc__
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/event/registry.py
+ Line number: 193
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+192	        if newowner_ref in dispatch_reg:
+193	            assert dispatch_reg[newowner_ref] == listen_ref
+194	        else:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/ext/associationproxy.py
+ Line number: 453
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+452	
+453	        assert instance is None
+454	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/ext/associationproxy.py
+ Line number: 735
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+734	        attr = getattr(target_class, value_attr)
+735	        assert not isinstance(attr, AssociationProxy)
+736	        if isinstance(attr, AssociationProxyInstance):
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/ext/associationproxy.py
+ Line number: 900
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+899	                if id(obj) == creator_id and id(self) == self_id:
+900	                    assert self.collection_class is not None
+901	                    return proxy
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/ext/associationproxy.py
+ Line number: 933
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+932	            proxy = self.get(obj)
+933	            assert self.collection_class is not None
+934	            if proxy is not values:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/engine.py
+ Line number: 332
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+331	        """Begin a transaction prior to autobegin occurring."""
+332	        assert self._proxied
+333	        return AsyncTransaction(self)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/engine.py
+ Line number: 337
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+336	        """Begin a nested transaction and return a transaction handle."""
+337	        assert self._proxied
+338	        return AsyncTransaction(self, nested=True)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/engine.py
+ Line number: 443
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+442	        c2 = await greenlet_spawn(conn.execution_options, **opt)
+443	        assert c2 is conn
+444	        return self
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/engine.py
+ Line number: 593
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+592	        )
+593	        assert result.context._is_server_side
+594	        ar = AsyncResult(result)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/engine.py
+ Line number: 1360
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1359	        )
+1360	        assert async_connection is not None
+1361	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/ext/automap.py
+ Line number: 1232
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1231	        else:
+1232	            assert False, "Can't locate automap base in class hierarchy"
+1233	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/ext/automap.py
+ Line number: 1257
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1256	        if reflect:
+1257	            assert autoload_with
+1258	            opts = dict(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/ext/automap.py
+ Line number: 1294
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1293	                if lcl_m2m is not None:
+1294	                    assert rem_m2m is not None
+1295	                    assert m2m_const is not None
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/ext/automap.py
+ Line number: 1295
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1294	                    assert rem_m2m is not None
+1295	                    assert m2m_const is not None
+1296	                    many_to_many.append((lcl_m2m, rem_m2m, m2m_const, table))
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/ext/automap.py
+ Line number: 1330
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1329	                    )
+1330	                    assert map_config.cls.__name__ == newname
+1331	                    if new_module is None:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/ext/automap.py
+ Line number: 1345
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1344	                        # see test_cls_schema_name_conflict
+1345	                        assert isinstance(props, Properties)
+1346	                        by_module_properties = props
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/ext/baked.py
+ Line number: 204
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+203	                else:
+204	                    assert not ck[1], (
+205	                        "loader options with variable bound parameters "
+206	                        "not supported with baked queries.  Please "
+207	                        "use new-style select() statements for cached "
+208	                        "ORM queries."
+209	                    )
+210	                    key += ck[0]
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/ext/horizontal_shard.py
+ Line number: 113
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+112	        super().__init__(*args, **kwargs)
+113	        assert isinstance(self.session, ShardedSession)
+114	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/ext/horizontal_shard.py
+ Line number: 310
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+309	                token = state.key[2]
+310	                assert token is not None
+311	                return token
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/ext/horizontal_shard.py
+ Line number: 315
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+314	
+315	        assert isinstance(mapper, Mapper)
+316	        shard_id = self.shard_chooser(mapper, instance, **kw)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/ext/horizontal_shard.py
+ Line number: 338
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+337	            trans = self.get_transaction()
+338	            assert trans is not None
+339	            return trans.connection(mapper, shard_id=shard_id)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/ext/horizontal_shard.py
+ Line number: 348
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+347	            else:
+348	                assert isinstance(bind, Connection)
+349	                return bind
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/ext/horizontal_shard.py
+ Line number: 364
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+363	            )
+364	            assert shard_id is not None
+365	        return self.__shards[shard_id]
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/ext/horizontal_shard.py
+ Line number: 443
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+442	    session = orm_context.session
+443	    assert isinstance(session, ShardedSession)
+444	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/ext/hybrid.py
+ Line number: 1471
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1470	            if TYPE_CHECKING:
+1471	                assert isinstance(expr, ColumnElement)
+1472	            ret_expr = expr
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/ext/hybrid.py
+ Line number: 1478
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1477	            # true
+1478	            assert isinstance(ret_expr, ColumnElement)
+1479	        return ret_expr
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/ext/mutable.py
+ Line number: 525
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+524	                    val = cls.coerce(key, val)
+525	                    assert val is not None
+526	                    state.dict[key] = val
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/ext/mypy/apply.py
+ Line number: 79
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+78	    left_hand_explicit_type = get_proper_type(stmt.type)
+79	    assert isinstance(
+80	        left_hand_explicit_type, (Instance, UnionType, UnboundType)
+81	    )
+82	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/ext/mypy/apply.py
+ Line number: 174
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+173	            ):
+174	                assert python_type_for_type is not None
+175	                left_node.type = api.named_type(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/ext/mypy/apply.py
+ Line number: 213
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+212	    left_node = lvalue.node
+213	    assert isinstance(left_node, Var)
+214	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/ext/mypy/apply.py
+ Line number: 316
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+315	    if sym:
+316	        assert isinstance(sym.node, TypeInfo)
+317	        type_: ProperType = Instance(sym.node, [])
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/ext/mypy/decl_class.py
+ Line number: 191
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+190	    if left_hand_explicit_type is not None:
+191	        assert value.node is not None
+192	        attributes.append(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/ext/mypy/decl_class.py
+ Line number: 378
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+377	    # hook.
+378	    assert sym is not None
+379	    node = sym.node
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/ext/mypy/decl_class.py
+ Line number: 384
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+383	
+384	    assert node is lvalue.node
+385	    assert isinstance(node, Var)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/ext/mypy/decl_class.py
+ Line number: 385
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+384	    assert node is lvalue.node
+385	    assert isinstance(node, Var)
+386	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/ext/mypy/decl_class.py
+ Line number: 468
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+467	
+468	    assert python_type_for_type is not None
+469	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/ext/mypy/infer.py
+ Line number: 110
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+109	
+110	    assert isinstance(stmt.rvalue, CallExpr)
+111	    target_cls_arg = stmt.rvalue.args[0]
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/ext/mypy/infer.py
+ Line number: 230
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+229	        if type_is_a_collection:
+230	            assert isinstance(left_hand_explicit_type, Instance)
+231	            assert isinstance(python_type_for_type, Instance)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/ext/mypy/infer.py
+ Line number: 231
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+230	            assert isinstance(left_hand_explicit_type, Instance)
+231	            assert isinstance(python_type_for_type, Instance)
+232	            return _infer_collection_type_from_left_and_inferred_right(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/ext/mypy/infer.py
+ Line number: 254
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+253	
+254	    assert isinstance(stmt.rvalue, CallExpr)
+255	    target_cls_arg = stmt.rvalue.args[0]
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/ext/mypy/infer.py
+ Line number: 290
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+289	    """
+290	    assert isinstance(stmt.rvalue, CallExpr)
+291	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/ext/mypy/infer.py
+ Line number: 322
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+321	    """
+322	    assert isinstance(stmt.rvalue, CallExpr)
+323	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/ext/mypy/infer.py
+ Line number: 397
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+396	    """
+397	    assert isinstance(node, Var)
+398	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/ext/mypy/infer.py
+ Line number: 431
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+430	        else:
+431	            assert False
+432	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/ext/mypy/infer.py
+ Line number: 516
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+515	
+516	    assert isinstance(left_hand_arg, (Instance, UnionType))
+517	    assert isinstance(python_type_arg, (Instance, UnionType))
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/ext/mypy/infer.py
+ Line number: 517
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+516	    assert isinstance(left_hand_arg, (Instance, UnionType))
+517	    assert isinstance(python_type_arg, (Instance, UnionType))
+518	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/ext/mypy/infer.py
+ Line number: 575
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+574	
+575	    assert node.has_base("sqlalchemy.sql.type_api.TypeEngine"), (
+576	        "could not extract Python type from node: %s" % node
+577	    )
+578	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/ext/mypy/infer.py
+ Line number: 583
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+582	
+583	    assert type_engine_sym is not None and isinstance(
+584	        type_engine_sym.node, TypeInfo
+585	    )
+586	    type_engine = map_instance_to_supertype(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/ext/mypy/plugin.py
+ Line number: 235
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+234	    _add_globals(ctx)
+235	    assert isinstance(ctx.reason, nodes.MemberExpr)
+236	    expr = ctx.reason.expr
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/ext/mypy/plugin.py
+ Line number: 238
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+237	
+238	    assert isinstance(expr, nodes.RefExpr) and isinstance(expr.node, nodes.Var)
+239	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/ext/mypy/plugin.py
+ Line number: 242
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+241	
+242	    assert (
+243	        isinstance(node_type, Instance)
+244	        and names.type_id_for_named_node(node_type.type) is names.REGISTRY
+245	    )
+246	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/ext/mypy/plugin.py
+ Line number: 302
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+301	    )
+302	    assert sym is not None and isinstance(sym.node, TypeInfo)
+303	    info.declared_metaclass = info.metaclass_type = Instance(sym.node, [])
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/ext/mypy/util.py
+ Line number: 78
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+77	    def serialize(self) -> JsonDict:
+78	        assert self.type
+79	        return {
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/ext/mypy/util.py
+ Line number: 335
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+334	            return None
+335	        assert sym and isinstance(sym.node, TypeInfo)
+336	        return sym.node
+
+
+ + +
+
+ +
+
+ try_except_pass: Try, Except, Pass detected.
+ Test ID: B110
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/ext/mypy/util.py
+ Line number: 344
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b110_try_except_pass.html
+ +
+
+343	        return typ.serialize()
+344	    except Exception:
+345	        pass
+346	    if hasattr(typ, "args"):
+
+
+ + +
+
+ +
+
+ blacklist: Consider possible security implications associated with pickle module.
+ Test ID: B403
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-502
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/ext/serializer.py
+ Line number: 72
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_imports.html#b403-import-pickle
+ +
+
+71	from io import BytesIO
+72	import pickle
+73	import re
+
+
+ + +
+
+ +
+
+ blacklist: Pickle and modules that wrap it can be unsafe when used to deserialize untrusted data, possible security issue.
+ Test ID: B301
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-502
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/ext/serializer.py
+ Line number: 150
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b301-pickle
+ +
+
+149	                key, clsarg = args.split(":")
+150	                cls = pickle.loads(b64decode(clsarg))
+151	                return getattr(cls, key)
+
+
+ + +
+
+ +
+
+ blacklist: Pickle and modules that wrap it can be unsafe when used to deserialize untrusted data, possible security issue.
+ Test ID: B301
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-502
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/ext/serializer.py
+ Line number: 153
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b301-pickle
+ +
+
+152	            elif type_ == "mapper":
+153	                cls = pickle.loads(b64decode(args))
+154	                return class_mapper(cls)
+
+
+ + +
+
+ +
+
+ blacklist: Pickle and modules that wrap it can be unsafe when used to deserialize untrusted data, possible security issue.
+ Test ID: B301
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-502
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/ext/serializer.py
+ Line number: 156
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b301-pickle
+ +
+
+155	            elif type_ == "mapper_selectable":
+156	                cls = pickle.loads(b64decode(args))
+157	                return class_mapper(cls).__clause_element__()
+
+
+ + +
+
+ +
+
+ blacklist: Pickle and modules that wrap it can be unsafe when used to deserialize untrusted data, possible security issue.
+ Test ID: B301
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-502
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/ext/serializer.py
+ Line number: 160
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b301-pickle
+ +
+
+159	                mapper, keyname = args.split(":")
+160	                cls = pickle.loads(b64decode(mapper))
+161	                return class_mapper(cls).attrs[keyname]
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/attributes.py
+ Line number: 218
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+217	
+218	        assert comparator is not None
+219	        self.comparator = comparator
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/attributes.py
+ Line number: 336
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+335	        entity_namespace = self._entity_namespace
+336	        assert isinstance(entity_namespace, HasCacheKey)
+337	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/attributes.py
+ Line number: 350
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+349	            if TYPE_CHECKING:
+350	                assert isinstance(ce, ColumnElement)
+351	            anno = ce._annotate
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/attributes.py
+ Line number: 395
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+394	    def adapt_to_entity(self, adapt_to_entity: AliasedInsp[Any]) -> Self:
+395	        assert not self._of_type
+396	        return self.__class__(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/attributes.py
+ Line number: 419
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+418	        if TYPE_CHECKING:
+419	            assert isinstance(self.comparator, RelationshipProperty.Comparator)
+420	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/attributes.py
+ Line number: 975
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+974	        msg = "This AttributeImpl is not configured to track parents."
+975	        assert self.trackparent, msg
+976	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/attributes.py
+ Line number: 993
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+992	        msg = "This AttributeImpl is not configured to track parents."
+993	        assert self.trackparent, msg
+994	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/attributes.py
+ Line number: 1060
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1059	
+1060	        assert self.key not in dict_, (
+1061	            "_default_value should only be invoked for an "
+1062	            "uninitialized or expired attribute"
+1063	        )
+1064	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/attributes.py
+ Line number: 1704
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1703	                # pending mutations
+1704	                assert self.key not in state._pending_mutations
+1705	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/attributes.py
+ Line number: 1835
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1834	
+1835	        assert self.key not in dict_, (
+1836	            "_default_value should only be invoked for an "
+1837	            "uninitialized or expired attribute"
+1838	        )
+1839	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/attributes.py
+ Line number: 1873
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1872	            )
+1873	            assert (
+1874	                self.key not in dict_
+1875	            ), "Collection was loaded during event handling."
+1876	            state._get_pending_mutation(self.key).append(value)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/attributes.py
+ Line number: 1879
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1878	            if TYPE_CHECKING:
+1879	                assert isinstance(collection, CollectionAdapter)
+1880	            collection.append_with_event(value, initiator)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/attributes.py
+ Line number: 1895
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1894	            self.fire_remove_event(state, dict_, value, initiator, key=NO_KEY)
+1895	            assert (
+1896	                self.key not in dict_
+1897	            ), "Collection was loaded during event handling."
+1898	            state._get_pending_mutation(self.key).remove(value)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/attributes.py
+ Line number: 1901
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1900	            if TYPE_CHECKING:
+1901	                assert isinstance(collection, CollectionAdapter)
+1902	            collection.remove_with_event(value, initiator)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/attributes.py
+ Line number: 2704
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2703	    if TYPE_CHECKING:
+2704	        assert isinstance(attr, HasCollectionAdapter)
+2705	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/base.py
+ Line number: 443
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+442	    else:
+443	        assert isinstance(class_or_mapper, type)
+444	        raise exc.UnmappedClassError(class_or_mapper)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/bulk_persistence.py
+ Line number: 236
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+235	            elif result.returns_rows:
+236	                assert bookkeeping
+237	                return_result = return_result.splice_horizontally(result)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/bulk_persistence.py
+ Line number: 250
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+249	    if use_orm_insert_stmt is not None:
+250	        assert return_result is not None
+251	        return return_result
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/bulk_persistence.py
+ Line number: 480
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+479	    def _get_crud_kv_pairs(cls, statement, kv_iterator, needs_to_be_cacheable):
+480	        assert (
+481	            needs_to_be_cacheable
+482	        ), "no test coverage for needs_to_be_cacheable=False"
+483	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/bulk_persistence.py
+ Line number: 705
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+704	        except KeyError:
+705	            assert False, "statement had 'orm' plugin but no plugin_subject"
+706	        else:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/bulk_persistence.py
+ Line number: 1199
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1198	        except KeyError:
+1199	            assert False, "statement had 'orm' plugin but no plugin_subject"
+1200	        else:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/bulk_persistence.py
+ Line number: 1290
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1289	
+1290	            assert mapper is not None
+1291	            assert session._transaction is not None
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/bulk_persistence.py
+ Line number: 1291
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1290	            assert mapper is not None
+1291	            assert session._transaction is not None
+1292	            result = _bulk_insert(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/bulk_persistence.py
+ Line number: 1623
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1622	
+1623	            assert update_options._synchronize_session != "fetch"
+1624	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/bulk_persistence.py
+ Line number: 1637
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1636	            mapper = update_options._subject_mapper
+1637	            assert mapper is not None
+1638	            assert session._transaction is not None
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/bulk_persistence.py
+ Line number: 1638
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1637	            assert mapper is not None
+1638	            assert session._transaction is not None
+1639	            result = _bulk_update(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/clsregistry.py
+ Line number: 348
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+347	                else:
+348	                    assert isinstance(value, _MultipleClassMarker)
+349	                    return value.attempt_get(self.__parent.path, key)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/clsregistry.py
+ Line number: 375
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+374	            if desc.extension_type is interfaces.NotExtension.NOT_EXTENSION:
+375	                assert isinstance(desc, attributes.QueryableAttribute)
+376	                prop = desc.property
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/clsregistry.py
+ Line number: 452
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+451	        decl_base = manager.registry
+452	        assert decl_base is not None
+453	        decl_class_registry = decl_base._class_registry
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/clsregistry.py
+ Line number: 528
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+527	                if TYPE_CHECKING:
+528	                    assert isinstance(rval, (type, Table, _ModNS))
+529	                return rval
+
+
+ + +
+
+ +
+
+ blacklist: Use of possibly insecure function - consider using safer ast.literal_eval.
+ Test ID: B307
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/clsregistry.py
+ Line number: 533
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b307-eval
+ +
+
+532	        try:
+533	            x = eval(self.arg, globals(), self._dict)
+534	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/collections.py
+ Line number: 548
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+547	    def _set_empty(self, user_data):
+548	        assert (
+549	            not self.empty
+550	        ), "This collection adapter is already in the 'empty' state"
+551	        self.empty = True
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/collections.py
+ Line number: 555
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+554	    def _reset_empty(self) -> None:
+555	        assert (
+556	            self.empty
+557	        ), "This collection adapter is not in the 'empty' state"
+558	        self.empty = False
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/collections.py
+ Line number: 799
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+798	
+799	    assert isinstance(values, list)
+800	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/collections.py
+ Line number: 908
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+907	                role = method._sa_instrument_role
+908	                assert role in (
+909	                    "appender",
+910	                    "remover",
+911	                    "iterator",
+912	                    "converter",
+913	                )
+914	                roles.setdefault(role, name)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/collections.py
+ Line number: 923
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+922	                op, argument = method._sa_instrument_before
+923	                assert op in ("fire_append_event", "fire_remove_event")
+924	                before = op, argument
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/collections.py
+ Line number: 927
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+926	                op = method._sa_instrument_after
+927	                assert op in ("fire_append_event", "fire_remove_event")
+928	                after = op
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/collections.py
+ Line number: 945
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+944	    if collection_type in __interfaces:
+945	        assert collection_type is not None
+946	        canned_roles, decorators = __interfaces[collection_type]
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/context.py
+ Line number: 235
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+234	            self.global_attributes = {}
+235	            assert toplevel
+236	            return
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/context.py
+ Line number: 571
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+570	        except KeyError:
+571	            assert False, "statement had 'orm' plugin but no plugin_subject"
+572	        else:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/context.py
+ Line number: 783
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+782	
+783	        assert isinstance(statement_container, FromStatement)
+784	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/context.py
+ Line number: 1374
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1373	            if self.compile_options._only_load_props:
+1374	                assert False, "no columns were included in _only_load_props"
+1375	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/context.py
+ Line number: 1491
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1490	
+1491	        assert self.compile_options._set_base_alias
+1492	        assert len(query._from_obj) == 1
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/context.py
+ Line number: 1492
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1491	        assert self.compile_options._set_base_alias
+1492	        assert len(query._from_obj) == 1
+1493	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/context.py
+ Line number: 1518
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1517	            equivs = self._all_equivs()
+1518	            assert info is info.selectable
+1519	            return ORMStatementAdapter(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/context.py
+ Line number: 1952
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1951	            # entities
+1952	            assert prop is None
+1953	            (
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/context.py
+ Line number: 2013
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2012	                # might be distinct
+2013	                assert isinstance(
+2014	                    entities_collection[use_entity_index], _MapperEntity
+2015	                )
+2016	                left_clause = entities_collection[use_entity_index].selectable
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/context.py
+ Line number: 2342
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2341	            # a warning has been emitted.
+2342	            assert right_mapper
+2343	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/context.py
+ Line number: 3285
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+3284	            if column is None:
+3285	                assert compile_state.is_dml_returning
+3286	                self._fetch_column = self.column
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/decl_api.py
+ Line number: 299
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+298	        # assert that we are in fact in the declarative scan
+299	        assert declarative_scan is not None
+300	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/decl_api.py
+ Line number: 1309
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1308	                if res_after_fallback is not None:
+1309	                    assert kind is not None
+1310	                    if kind == "pep-695 type":
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/decl_api.py
+ Line number: 1425
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1424	            )
+1425	        assert manager.registry is None
+1426	        manager.registry = self
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/decl_base.py
+ Line number: 203
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+202	    # make sure we've moved it out.  transitional
+203	    assert attrname != "__abstract__"
+204	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/decl_base.py
+ Line number: 880
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+879	                        # _include_dunders
+880	                        assert False
+881	                elif class_mapped:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/decl_base.py
+ Line number: 910
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+909	                        # pylance, no luck
+910	                        assert obj is not None
+911	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/decl_base.py
+ Line number: 990
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+989	                        if not fixed_table:
+990	                            assert (
+991	                                name in collected_attributes
+992	                                or attribute_is_overridden(name, None)
+993	                            )
+994	                        continue
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/decl_base.py
+ Line number: 1012
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1011	
+1012	                    assert not attribute_is_overridden(name, obj)
+1013	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/decl_base.py
+ Line number: 1095
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1094	        manager = instrumentation.manager_of_class(self.cls)
+1095	        assert manager is not None
+1096	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/decl_base.py
+ Line number: 1165
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1164	            else:
+1165	                assert False
+1166	            annotations[name] = tp
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/decl_base.py
+ Line number: 1590
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1589	                        # by util._extract_mapped_subtype before we got here.
+1590	                        assert expect_annotations_wo_mapped
+1591	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/decl_base.py
+ Line number: 1689
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1688	                # ensure every column we get here has been named
+1689	                assert c.name is not None
+1690	                name_to_prop_key[c.name].add(key)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/decl_base.py
+ Line number: 1846
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1845	            inherited_mapper_or_config = _declared_mapping_info(self.inherits)
+1846	            assert inherited_mapper_or_config is not None
+1847	            inherited_table = inherited_mapper_or_config.local_table
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/decl_base.py
+ Line number: 1870
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1869	                for col in declared_columns:
+1870	                    assert inherited_table is not None
+1871	                    if col.name in inherited_table.c:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/decl_base.py
+ Line number: 1889
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1888	                    if TYPE_CHECKING:
+1889	                        assert isinstance(inherited_table, Table)
+1890	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/dependency.py
+ Line number: 136
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+135	            # this method a bit more.
+136	            assert child_deletes not in uow.cycles
+137	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/dependency.py
+ Line number: 916
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+915	    def process_deletes(self, uowcommit, states):
+916	        assert False
+917	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/dependency.py
+ Line number: 923
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+922	        # statements being emitted
+923	        assert self.passive_updates
+924	        self._process_key_switches(states, uowcommit)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/descriptor_props.py
+ Line number: 856
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+855	            if self._adapt_to_entity:
+856	                assert self.adapter is not None
+857	                comparisons = [self.adapter(x) for x in comparisons]
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/descriptor_props.py
+ Line number: 910
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+909	                break
+910	        assert comparator_callable is not None
+911	        return comparator_callable(p, mapper)  # type: ignore
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/exc.py
+ Line number: 195
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+194	        else:
+195	            assert applies_to is not None
+196	            sa_exc.InvalidRequestError.__init__(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/identity.py
+ Line number: 151
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+150	            if TYPE_CHECKING:
+151	                assert state.key is not None
+152	            try:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/identity.py
+ Line number: 162
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+161	    ) -> Optional[InstanceState[Any]]:
+162	        assert state.key is not None
+163	        if state.key in self._dict:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/identity.py
+ Line number: 183
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+182	        key = state.key
+183	        assert key is not None
+184	        # inline of self.__contains__
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/identity.py
+ Line number: 241
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+240	            key = state.key
+241	            assert key is not None
+242	            if value is not None:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/identity.py
+ Line number: 266
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+265	        key = state.key
+266	        assert key is not None
+267	        try:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/identity.py
+ Line number: 282
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+281	        if key in self._dict:
+282	            assert key is not None
+283	            try:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/instrumentation.py
+ Line number: 214
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+213	        if init_method:
+214	            assert not self._finalized, (
+215	                "class is already instrumented, "
+216	                "init_method %s can't be applied" % init_method
+217	            )
+218	            self.init_method = init_method
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/instrumentation.py
+ Line number: 483
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+482	        impl = self.get_impl(key)
+483	        assert _is_collection_attribute_impl(impl)
+484	        adapter = collections.CollectionAdapter(impl, state, user_data)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/instrumentation.py
+ Line number: 613
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+612	    def create_manager_for_cls(self, class_: Type[_O]) -> ClassManager[_O]:
+613	        assert class_ is not None
+614	        assert opt_manager_of_class(class_) is None
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/instrumentation.py
+ Line number: 614
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+613	        assert class_ is not None
+614	        assert opt_manager_of_class(class_) is None
+615	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/instrumentation.py
+ Line number: 624
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+623	        else:
+624	            assert manager is not None
+625	
+
+
+ + +
+
+ +
+
+ exec_used: Use of exec detected.
+ Test ID: B102
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/instrumentation.py
+ Line number: 744
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b102_exec_used.html
+ +
+
+743	    env["__name__"] = __name__
+744	    exec(func_text, env)
+745	    __init__ = env["__init__"]
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/interfaces.py
+ Line number: 296
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+295	
+296	            assert False, "Mapped[] received without a mapping declaration"
+297	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/interfaces.py
+ Line number: 1148
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1147	                if TYPE_CHECKING:
+1148	                    assert issubclass(prop_cls, MapperProperty)
+1149	                strategies = cls._all_strategies[prop_cls]
+
+
+ + +
+
+ +
+
+ try_except_pass: Try, Except, Pass detected.
+ Test ID: B110
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/loading.py
+ Line number: 148
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b110_try_except_pass.html
+ +
+
+147	                        return hash(obj)
+148	                    except:
+149	                        pass
+150	
+
+
+ + +
+
+ +
+
+ try_except_pass: Try, Except, Pass detected.
+ Test ID: B110
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/loading.py
+ Line number: 172
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b110_try_except_pass.html
+ +
+
+171	                        return hash(obj)
+172	                    except:
+173	                        pass
+174	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/loading.py
+ Line number: 548
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+547	
+548	    assert not q._is_lambda_element
+549	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/loading.py
+ Line number: 1012
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1011	            # loading does not apply
+1012	            assert only_load_props is None
+1013	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/mapper.py
+ Line number: 1241
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1240	                        except sa_exc.NoForeignKeysError as nfe:
+1241	                            assert self.inherits.local_table is not None
+1242	                            assert self.local_table is not None
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/mapper.py
+ Line number: 1242
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1241	                            assert self.inherits.local_table is not None
+1242	                            assert self.local_table is not None
+1243	                            raise sa_exc.NoForeignKeysError(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/mapper.py
+ Line number: 1261
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1260	                        except sa_exc.AmbiguousForeignKeysError as afe:
+1261	                            assert self.inherits.local_table is not None
+1262	                            assert self.local_table is not None
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/mapper.py
+ Line number: 1262
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1261	                            assert self.inherits.local_table is not None
+1262	                            assert self.local_table is not None
+1263	                            raise sa_exc.AmbiguousForeignKeysError(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/mapper.py
+ Line number: 1276
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1275	                            ) from afe
+1276	                    assert self.inherits.persist_selectable is not None
+1277	                    self.persist_selectable = sql.join(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/mapper.py
+ Line number: 1377
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1376	            self.base_mapper = self
+1377	            assert self.local_table is not None
+1378	            self.persist_selectable = self.local_table
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/mapper.py
+ Line number: 1433
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1432	        elif self.with_polymorphic[0] != "*":
+1433	            assert isinstance(self.with_polymorphic[0], tuple)
+1434	            self._set_with_polymorphic(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/mapper.py
+ Line number: 1443
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1442	
+1443	        assert self.concrete
+1444	        assert not self.inherits
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/mapper.py
+ Line number: 1444
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1443	        assert self.concrete
+1444	        assert not self.inherits
+1445	        assert isinstance(mapper, Mapper)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/mapper.py
+ Line number: 1445
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1444	        assert not self.inherits
+1445	        assert isinstance(mapper, Mapper)
+1446	        self.inherits = mapper
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/mapper.py
+ Line number: 1495
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1494	
+1495	            assert manager.registry is not None
+1496	            self.registry = manager.registry
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/mapper.py
+ Line number: 1530
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1529	
+1530	        assert manager.registry is not None
+1531	        self.registry = manager.registry
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/mapper.py
+ Line number: 2318
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2317	        if incoming_prop is None:
+2318	            assert single_column is not None
+2319	            incoming_column = single_column
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/mapper.py
+ Line number: 2322
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2321	        else:
+2322	            assert single_column is None
+2323	            incoming_column = incoming_prop.columns[0]
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/mapper.py
+ Line number: 2457
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2456	        )
+2457	        assert isinstance(prop, MapperProperty)
+2458	        self._init_properties[key] = prop
+
+
+ + +
+
+ +
+
+ hardcoded_password_string: Possible hardcoded password: 'True'
+ Test ID: B105
+ Severity: LOW
+ Confidence: MEDIUM
+ CWE: CWE-259
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/mapper.py
+ Line number: 2902
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b105_hardcoded_password_string.html
+ +
+
+2901	                    "parentmapper": self,
+2902	                    "identity_token": True,
+2903	                }
+2904	            )
+2905	            ._set_propagate_attrs(
+2906	                {"compile_state_plugin": "orm", "plugin_subject": self}
+2907	            )
+2908	        )
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/mapper.py
+ Line number: 3700
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+3699	            if start and not mapper.single:
+3700	                assert mapper.inherits
+3701	                assert not mapper.concrete
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/mapper.py
+ Line number: 3701
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+3700	                assert mapper.inherits
+3701	                assert not mapper.concrete
+3702	                assert mapper.inherit_condition is not None
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/mapper.py
+ Line number: 3702
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+3701	                assert not mapper.concrete
+3702	                assert mapper.inherit_condition is not None
+3703	                allconds.append(mapper.inherit_condition)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/mapper.py
+ Line number: 3790
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+3789	        # mappers or other objects.
+3790	        assert self.isa(super_mapper)
+3791	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/mapper.py
+ Line number: 3834
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+3833	
+3834	        assert self.inherits
+3835	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/mapper.py
+ Line number: 3902
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+3901	        if entity.is_aliased_class:
+3902	            assert entity.mapper is self
+3903	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/mapper.py
+ Line number: 3963
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+3962	
+3963	        assert state.mapper.isa(self)
+3964	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/mapper.py
+ Line number: 3990
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+3989	                    continue
+3990	                assert parent_state is not None
+3991	                assert parent_dict is not None
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/mapper.py
+ Line number: 3991
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+3990	                assert parent_state is not None
+3991	                assert parent_dict is not None
+3992	                queue = deque(
+
+
+ + +
+
+ +
+
+ hardcoded_password_string: Possible hardcoded password: '_sa_default'
+ Test ID: B105
+ Severity: LOW
+ Confidence: MEDIUM
+ CWE: CWE-259
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/path_registry.py
+ Line number: 83
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b105_hardcoded_password_string.html
+ +
+
+82	_WILDCARD_TOKEN: _LiteralStar = "*"
+83	_DEFAULT_TOKEN = "_sa_default"
+84	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/path_registry.py
+ Line number: 286
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+285	                mp = orm_base._inspect_mapped_class(mcls, configure=True)
+286	                assert mp is not None
+287	                return mp.attrs[key]
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/path_registry.py
+ Line number: 310
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+309	    def deserialize(cls, path: _SerializedPath) -> PathRegistry:
+310	        assert path is not None
+311	        p = cls._deserialize_path(path)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/path_registry.py
+ Line number: 388
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+387	            if TYPE_CHECKING:
+388	                assert isinstance(entity, _StrPathToken)
+389	            return TokenRegistry(self, PathToken._intern[entity])
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/path_registry.py
+ Line number: 459
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+458	        if TYPE_CHECKING:
+459	            assert isinstance(parent, AbstractEntityRegistry)
+460	        if not parent.is_aliased_class:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/path_registry.py
+ Line number: 487
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+486	        if TYPE_CHECKING:
+487	            assert isinstance(parent, AbstractEntityRegistry)
+488	        for mp_ent in parent.mapper.iterate_to_root():
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/path_registry.py
+ Line number: 614
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+613	            if TYPE_CHECKING:
+614	                assert isinstance(prop, RelationshipProperty)
+615	            self.entity = prop.entity
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/path_registry.py
+ Line number: 641
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+640	    def entity_path(self) -> AbstractEntityRegistry:
+641	        assert self.entity is not None
+642	        return self[self.entity]
+
+
+ + +
+
+ +
+
+ hardcoded_sql_expressions: Possible SQL injection vector through string-based query construction.
+ Test ID: B608
+ Severity: MEDIUM
+ Confidence: LOW
+ CWE: CWE-89
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/persistence.py
+ Line number: 715
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b608_hardcoded_sql_expressions.html
+ +
+
+714	                raise orm_exc.FlushError(
+715	                    "Can't delete from table %s "
+716	                    "using NULL for primary "
+717	                    "key value on column %s" % (table, col)
+718	                )
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/persistence.py
+ Line number: 1214
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1213	            else:
+1214	                assert not returning_is_required_anyway
+1215	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/properties.py
+ Line number: 762
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+761	        ):
+762	            assert originating_module is not None
+763	            argument = de_stringify_annotation(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/query.py
+ Line number: 648
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+647	        if TYPE_CHECKING:
+648	            assert isinstance(stmt, Select)
+649	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/query.py
+ Line number: 3344
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+3343	        stmt = self._statement_20(for_statement=for_statement, **kw)
+3344	        assert for_statement == stmt._compile_options._for_statement
+3345	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/relationships.py
+ Line number: 785
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+784	                )
+785	                assert info is not None
+786	                target_mapper, to_selectable, is_aliased_class = (
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/relationships.py
+ Line number: 1170
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1169	    ) -> ColumnElement[bool]:
+1170	        assert instance is not None
+1171	        adapt_source: Optional[_CoreAdapterProto] = None
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/relationships.py
+ Line number: 1174
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1173	            insp: Optional[_InternalEntityType[Any]] = inspect(from_entity)
+1174	            assert insp is not None
+1175	            if insp_is_aliased_class(insp):
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/relationships.py
+ Line number: 1311
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1310	        def _go() -> Any:
+1311	            assert lkv_fixed is not None
+1312	            last_known = to_return = lkv_fixed[prop.key]
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/relationships.py
+ Line number: 1409
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1408	
+1409	            assert is_has_collection_adapter(impl)
+1410	            instances_iterable = impl.get_collection(source_state, source_dict)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/relationships.py
+ Line number: 1415
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1414	            # True
+1415	            assert not instances_iterable.empty if impl.collection else True
+1416	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/relationships.py
+ Line number: 1450
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1449	                dest_impl = dest_state.get_impl(self.key)
+1450	                assert is_has_collection_adapter(dest_impl)
+1451	                dest_impl.set(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/relationships.py
+ Line number: 1544
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1543	
+1544	            assert instance_state is not None
+1545	            instance_dict = attributes.instance_dict(c)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/relationships.py
+ Line number: 1767
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1766	        argument = extracted_mapped_annotation
+1767	        assert originating_module is not None
+1768	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/relationships.py
+ Line number: 2322
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2321	        self._determine_joins()
+2322	        assert self.primaryjoin is not None
+2323	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/relationships.py
+ Line number: 2494
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2493	    def secondaryjoin_minus_local(self) -> ColumnElement[bool]:
+2494	        assert self.secondaryjoin is not None
+2495	        return _deep_deannotate(self.secondaryjoin, values=("local", "remote"))
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/relationships.py
+ Line number: 2687
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2686	
+2687	        assert self.secondary is not None
+2688	        fixed_secondary = self.secondary
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/relationships.py
+ Line number: 2699
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2698	
+2699	        assert self.secondaryjoin is not None
+2700	        self.secondaryjoin = visitors.replacement_traverse(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/session.py
+ Line number: 952
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+951	        elif origin is SessionTransactionOrigin.SUBTRANSACTION:
+952	            assert parent is not None
+953	        else:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/session.py
+ Line number: 954
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+953	        else:
+954	            assert parent is None
+955	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/session.py
+ Line number: 1075
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1074	            parent = self._parent
+1075	            assert parent is not None
+1076	            self._new = parent._new
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/session.py
+ Line number: 1100
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1099	        """
+1100	        assert self._is_transaction_boundary
+1101	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/session.py
+ Line number: 1120
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1119	
+1120	        assert not self.session._deleted
+1121	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/session.py
+ Line number: 1132
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1131	        """
+1132	        assert self._is_transaction_boundary
+1133	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/session.py
+ Line number: 1144
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1143	            parent = self._parent
+1144	            assert parent is not None
+1145	            parent._new.update(self._new)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/session.py
+ Line number: 1238
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1237	                    else:
+1238	                        assert False, join_transaction_mode
+1239	                else:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/session.py
+ Line number: 1277
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1276	        stx = self.session._transaction
+1277	        assert stx is not None
+1278	        if stx is not self:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/session.py
+ Line number: 1343
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1342	        stx = self.session._transaction
+1343	        assert stx is not None
+1344	        if stx is not self:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/session.py
+ Line number: 1887
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1886	            )
+1887	            assert self._transaction is trans
+1888	            return trans
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/session.py
+ Line number: 1934
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1933	
+1934	        assert trans is not None
+1935	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/session.py
+ Line number: 1938
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1937	            trans = trans._begin(nested=nested)
+1938	            assert self._transaction is trans
+1939	            self._nested_transaction = trans
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/session.py
+ Line number: 2162
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2161	            if TYPE_CHECKING:
+2162	                assert isinstance(
+2163	                    compile_state_cls, context.AbstractORMCompileState
+2164	                )
+2165	        else:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/session.py
+ Line number: 2606
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2605	            if TYPE_CHECKING:
+2606	                assert isinstance(insp, Inspectable)
+2607	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/session.py
+ Line number: 2817
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2816	                        if TYPE_CHECKING:
+2817	                            assert isinstance(obj, Table)
+2818	                        return self.__binds[obj]
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/session.py
+ Line number: 3362
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+3361	                    trans = self._transaction
+3362	                    assert trans is not None
+3363	                    if state in trans._key_switches:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/session.py
+ Line number: 3565
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+3564	            if TYPE_CHECKING:
+3565	                assert cascade_states is not None
+3566	            for o, m, st_, dct_ in cascade_states:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/session.py
+ Line number: 3841
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+3840	            # TODO: this was being tested before, but this is not possible
+3841	            assert instance is not LoaderCallableStatus.PASSIVE_CLASS_MISMATCH
+3842	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/session.py
+ Line number: 4408
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+4407	                )
+4408	                assert _reg, "Failed to add object to the flush context!"
+4409	                processed.add(state)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/session.py
+ Line number: 4418
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+4417	            _reg = flush_context.register_object(state, isdelete=True)
+4418	            assert _reg, "Failed to add object to the flush context!"
+4419	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/state.py
+ Line number: 527
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+526	        # so make sure this is not set
+527	        assert self._strong_obj is None
+528	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/state.py
+ Line number: 909
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+908	                    if TYPE_CHECKING:
+909	                        assert is_collection_impl(attr)
+910	                    if previous is NEVER_SET:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/state_changes.py
+ Line number: 83
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+82	        """
+83	        assert prerequisite_states, "no prerequisite states sent"
+84	        has_prerequisite_states = (
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/state_changes.py
+ Line number: 180
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+179	        """
+180	        assert self._next_state is _StateChangeStates.CHANGE_IN_PROGRESS, (
+181	            "Unexpected call to _expect_state outside of "
+182	            "state-changing method"
+183	        )
+184	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/strategies.py
+ Line number: 1810
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1809	            q = self.subq
+1810	            assert q.session is None
+1811	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/strategies.py
+ Line number: 2043
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2042	
+2043	        assert subq.session is None
+2044	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/strategies.py
+ Line number: 2397
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2396	
+2397	        assert clauses.is_aliased_class
+2398	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/strategies.py
+ Line number: 2519
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2518	
+2519	        assert clauses.is_aliased_class
+2520	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/strategies.py
+ Line number: 2609
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2608	
+2609	        assert entity_we_want_to_splice_onto is path[-2]
+2610	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/strategies.py
+ Line number: 2612
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2611	        if entity_inside_join_structure is False:
+2612	            assert isinstance(join_obj, orm_util._ORMJoin)
+2613	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/strategies.py
+ Line number: 2690
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2689	            if entity_inside_join_structure is False:
+2690	                assert (
+2691	                    False
+2692	                ), "assertion failed attempting to produce joined eager loads"
+2693	            return None
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/strategies.py
+ Line number: 2712
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2711	            # and entity_inside_join_structure=join_obj._right_memo.mapper
+2712	            assert detected_existing_path[-3] is entity_inside_join_structure
+2713	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/strategy_options.py
+ Line number: 148
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+147	        elif getattr(attr, "_of_type", None):
+148	            assert isinstance(attr, QueryableAttribute)
+149	            ot: Optional[_InternalEntityType[Any]] = inspect(attr._of_type)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/strategy_options.py
+ Line number: 150
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+149	            ot: Optional[_InternalEntityType[Any]] = inspect(attr._of_type)
+150	            assert ot is not None
+151	            coerced_alias = ot.selectable
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/strategy_options.py
+ Line number: 1071
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1070	        orig_cache_key = orig_query._generate_cache_key()
+1071	        assert orig_cache_key is not None
+1072	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/strategy_options.py
+ Line number: 1160
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1159	
+1160	        assert cloned.propagate_to_loaders == self.propagate_to_loaders
+1161	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/strategy_options.py
+ Line number: 1279
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1278	                self.context += (load_element,)
+1279	                assert opts is not None
+1280	                self.additional_source_entities += cast(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/strategy_options.py
+ Line number: 1374
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1373	    ):
+1374	        assert attrs is not None
+1375	        attr = attrs[0]
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/strategy_options.py
+ Line number: 1376
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1375	        attr = attrs[0]
+1376	        assert (
+1377	            wildcard_key
+1378	            and isinstance(attr, str)
+1379	            and attr in (_WILDCARD_TOKEN, _DEFAULT_TOKEN)
+1380	        )
+1381	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/strategy_options.py
+ Line number: 1389
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1388	
+1389	        assert extra_criteria is None
+1390	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/strategy_options.py
+ Line number: 1403
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1402	        """
+1403	        assert self.path
+1404	        attr = self.path[0]
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/strategy_options.py
+ Line number: 1410
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1409	
+1410	        assert effective_path.is_token
+1411	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/strategy_options.py
+ Line number: 1443
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1442	            # just returns it
+1443	            assert new_path == start_path
+1444	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/strategy_options.py
+ Line number: 1446
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1445	        # start_path is a single-token tuple
+1446	        assert start_path and len(start_path) == 1
+1447	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/strategy_options.py
+ Line number: 1449
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1448	        token = start_path[0]
+1449	        assert isinstance(token, str)
+1450	        entity = self._find_entity_basestring(entities, token, raiseerr)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/strategy_options.py
+ Line number: 1462
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1461	
+1462	        assert isinstance(token, str)
+1463	        loader = _TokenStrategyLoad.create(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/strategy_options.py
+ Line number: 1475
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1474	
+1475	        assert loader.path.is_token
+1476	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/strategy_options.py
+ Line number: 1771
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1770	
+1771	        assert opt.is_token_strategy == path.is_token
+1772	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/strategy_options.py
+ Line number: 1813
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1812	
+1813	        assert cloned.strategy == self.strategy
+1814	        assert cloned.local_opts == self.local_opts
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/strategy_options.py
+ Line number: 1814
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1813	        assert cloned.strategy == self.strategy
+1814	        assert cloned.local_opts == self.local_opts
+1815	        assert cloned.is_class_strategy == self.is_class_strategy
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/strategy_options.py
+ Line number: 1815
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1814	        assert cloned.local_opts == self.local_opts
+1815	        assert cloned.is_class_strategy == self.is_class_strategy
+1816	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/strategy_options.py
+ Line number: 1911
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1910	    ):
+1911	        assert attr is not None
+1912	        self._of_type = None
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/strategy_options.py
+ Line number: 1930
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1929	            # should not reach here;
+1930	            assert False
+1931	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/strategy_options.py
+ Line number: 1957
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1956	        if extra_criteria:
+1957	            assert not attr._extra_criteria
+1958	            self._extra_criteria = extra_criteria
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/strategy_options.py
+ Line number: 2009
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2008	
+2009	        assert (
+2010	            self._extra_criteria
+2011	        ), "this should only be called if _extra_criteria is present"
+2012	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/strategy_options.py
+ Line number: 2035
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2034	    def _set_of_type_info(self, context, current_path):
+2035	        assert self._path_with_polymorphic_path
+2036	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/strategy_options.py
+ Line number: 2038
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2037	        pwpi = self._of_type
+2038	        assert pwpi
+2039	        if not pwpi.is_aliased_class:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/strategy_options.py
+ Line number: 2080
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2079	        is_refresh = compile_state.compile_options._for_refresh_state
+2080	        assert not self.path.is_token
+2081	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/strategy_options.py
+ Line number: 2103
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2102	        if current_path:
+2103	            assert effective_path is not None
+2104	            effective_path = self._adjust_effective_path_for_current_path(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/strategy_options.py
+ Line number: 2132
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2131	            else:
+2132	                assert False, "unexpected object for _of_type"
+2133	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/strategy_options.py
+ Line number: 2203
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2202	
+2203	        assert self.path.is_token
+2204	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/strategy_options.py
+ Line number: 2357
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2356	
+2357	    assert lead_element
+2358	    return lead_element
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/unitofwork.py
+ Line number: 638
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+637	        self.sort_key = ("SaveUpdateAll", mapper._sort_key)
+638	        assert mapper is mapper.base_mapper
+639	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/unitofwork.py
+ Line number: 675
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+674	        self.sort_key = ("DeleteAll", mapper._sort_key)
+675	        assert mapper is mapper.base_mapper
+676	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/util.py
+ Line number: 727
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+726	
+727	        assert alias is not None
+728	        self._aliased_insp = AliasedInsp(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/util.py
+ Line number: 1004
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1003	            # supports "aliased class of aliased class" use case
+1004	            assert isinstance(inspected, AliasedInsp)
+1005	            self._adapter = inspected._adapter.wrap(self._adapter)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/util.py
+ Line number: 1065
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1064	        if aliased or flat:
+1065	            assert selectable is not None
+1066	            selectable = selectable._anonymous_fromclause(flat=flat)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/util.py
+ Line number: 1160
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1159	
+1160	        assert self.mapper is primary_mapper
+1161	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/util.py
+ Line number: 1187
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1186	    ) -> _ORMCOLEXPR:
+1187	        assert isinstance(expr, ColumnElement)
+1188	        d: Dict[str, Any] = {
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/util.py
+ Line number: 1230
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1229	        else:
+1230	            assert False, "mapper %s doesn't correspond to %s" % (mapper, self)
+1231	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/util.py
+ Line number: 1388
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1387	            else:
+1388	                assert entity is not None
+1389	                wrap_entity = entity.entity
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/util.py
+ Line number: 1435
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1434	        else:
+1435	            assert self.root_entity
+1436	            stack = list(self.root_entity.__subclasses__())
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/util.py
+ Line number: 1468
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1467	            crit = self.where_criteria  # type: ignore
+1468	        assert isinstance(crit, ColumnElement)
+1469	        return sql_util._deep_annotate(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/util.py
+ Line number: 1813
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1812	            if TYPE_CHECKING:
+1813	                assert isinstance(
+1814	                    onclause.comparator, RelationshipProperty.Comparator
+1815	                )
+1816	            on_selectable = onclause.comparator._source_selectable()
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/util.py
+ Line number: 1833
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1832	            else:
+1833	                assert isinstance(left_selectable, FromClause)
+1834	                adapt_from = left_selectable
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/util.py
+ Line number: 1886
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1885	
+1886	        assert self.onclause is not None
+1887	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/util.py
+ Line number: 1916
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1915	
+1916	        assert self.right is leftmost
+1917	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/util.py
+ Line number: 2081
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2080	
+2081	    assert insp_is_mapper(given)
+2082	    return entity.common_parent(given)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/orm/writeonly.py
+ Line number: 503
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+502	        if TYPE_CHECKING:
+503	            assert instance
+504	        self.instance = instance
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/pool/base.py
+ Line number: 868
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+867	
+868	        assert self.dbapi_connection is not None
+869	        return self.dbapi_connection
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/pool/base.py
+ Line number: 882
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+881	            self.__pool.dispatch.close(self.dbapi_connection, self)
+882	        assert self.dbapi_connection is not None
+883	        self.__pool._close_connection(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/pool/base.py
+ Line number: 940
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+939	    if is_gc_cleanup:
+940	        assert ref is not None
+941	        _strong_ref_connection_records.pop(ref, None)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/pool/base.py
+ Line number: 942
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+941	        _strong_ref_connection_records.pop(ref, None)
+942	        assert connection_record is not None
+943	        if connection_record.fairy_ref is not ref:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/pool/base.py
+ Line number: 945
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+944	            return
+945	        assert dbapi_connection is None
+946	        dbapi_connection = connection_record.dbapi_connection
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/pool/base.py
+ Line number: 977
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+976	            if not fairy:
+977	                assert connection_record is not None
+978	                fairy = _ConnectionFairy(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/pool/base.py
+ Line number: 984
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+983	                )
+984	            assert fairy.dbapi_connection is dbapi_connection
+985	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/pool/base.py
+ Line number: 1277
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1276	
+1277	        assert (
+1278	            fairy._connection_record is not None
+1279	        ), "can't 'checkout' a detached connection fairy"
+1280	        assert (
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/pool/base.py
+ Line number: 1280
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1279	        ), "can't 'checkout' a detached connection fairy"
+1280	        assert (
+1281	            fairy.dbapi_connection is not None
+1282	        ), "can't 'checkout' an invalidated connection fairy"
+1283	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/pool/base.py
+ Line number: 1493
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1492	    def cursor(self, *args: Any, **kwargs: Any) -> DBAPICursor:
+1493	        assert self.dbapi_connection is not None
+1494	        return self.dbapi_connection.cursor(*args, **kwargs)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/pool/events.py
+ Line number: 78
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+77	            else:
+78	                assert issubclass(target, Pool)
+79	                return target
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/pool/impl.py
+ Line number: 392
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+391	        # losing the state of an existing SQLite :memory: connection
+392	        assert not hasattr(other_singleton_pool._fairy, "current")
+393	        self._conn = other_singleton_pool._conn
+
+
+ + +
+
+ +
+
+ try_except_pass: Try, Except, Pass detected.
+ Test ID: B110
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/pool/impl.py
+ Line number: 402
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b110_try_except_pass.html
+ +
+
+401	                conn.close()
+402	            except Exception:
+403	                # pysqlite won't even let you close a conn from a thread
+404	                # that didn't create it
+405	                pass
+406	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/pool/impl.py
+ Line number: 502
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+501	            conn = other_static_pool.connection.dbapi_connection
+502	            assert conn is not None
+503	            return conn
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/pool/impl.py
+ Line number: 552
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+551	        self._checked_out = False
+552	        assert record is self._conn
+553	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/_py_util.py
+ Line number: 63
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+62	            s_val = self[idself]
+63	            assert s_val is not True
+64	            return s_val, True
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/base.py
+ Line number: 286
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+285	        x = fn(self, *args, **kw)
+286	        assert x is self, "generative methods must return self"
+287	        return self
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/base.py
+ Line number: 1223
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1222	
+1223	        assert self._compile_options is not None
+1224	        self._compile_options += options
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/cache_key.py
+ Line number: 165
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+164	                try:
+165	                    assert issubclass(cls, HasTraverseInternals)
+166	                    _cache_key_traversal = cls._traverse_internals
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/cache_key.py
+ Line number: 171
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+170	
+171	            assert _cache_key_traversal is not NO_CACHE, (
+172	                f"class {cls} has _cache_key_traversal=NO_CACHE, "
+173	                "which conflicts with inherit_cache=True"
+174	            )
+175	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/cache_key.py
+ Line number: 386
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+385	        else:
+386	            assert key is not None
+387	            return CacheKey(key, bindparams)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/cache_key.py
+ Line number: 400
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+399	        else:
+400	            assert key is not None
+401	            return CacheKey(key, bindparams)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/coercions.py
+ Line number: 408
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+407	        if typing.TYPE_CHECKING:
+408	            assert isinstance(resolved, (SQLCoreOperations, ClauseElement))
+409	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/coercions.py
+ Line number: 454
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+453	        if isinstance(resolved, str):
+454	            assert isinstance(expr, str)
+455	            strname = resolved = expr
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/coercions.py
+ Line number: 706
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+705	        # never reached
+706	        assert False
+707	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/coercions.py
+ Line number: 887
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+886	        elif isinstance(element, elements.ClauseList):
+887	            assert not len(element.clauses) == 0
+888	            return element.self_group(against=operator)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/coercions.py
+ Line number: 1331
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1330	    def _post_coercion(self, element, *, flat=False, name=None, **kw):
+1331	        assert name is None
+1332	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/compiler.py
+ Line number: 899
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+898	                if TYPE_CHECKING:
+899	                    assert isinstance(statement, Executable)
+900	                self.execution_options = statement._execution_options
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/compiler.py
+ Line number: 904
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+903	            if render_schema_translate:
+904	                assert schema_translate_map is not None
+905	                self.string = self.preparer._render_schema_translates(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/compiler.py
+ Line number: 1465
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1464	            if TYPE_CHECKING:
+1465	                assert isinstance(statement, UpdateBase)
+1466	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/compiler.py
+ Line number: 1469
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1468	                if TYPE_CHECKING:
+1469	                    assert isinstance(statement, ValuesBase)
+1470	                if statement._inline:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/compiler.py
+ Line number: 1662
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1661	    def _process_positional(self):
+1662	        assert not self.positiontup
+1663	        assert self.state is CompilerState.STRING_APPLIED
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/compiler.py
+ Line number: 1663
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1662	        assert not self.positiontup
+1663	        assert self.state is CompilerState.STRING_APPLIED
+1664	        assert not self._numeric_binds
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/compiler.py
+ Line number: 1664
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1663	        assert self.state is CompilerState.STRING_APPLIED
+1664	        assert not self._numeric_binds
+1665	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/compiler.py
+ Line number: 1669
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1668	        else:
+1669	            assert self.dialect.paramstyle == "qmark"
+1670	            placeholder = "?"
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/compiler.py
+ Line number: 1690
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1689	            reverse_escape = {v: k for k, v in self.escaped_bind_names.items()}
+1690	            assert len(self.escaped_bind_names) == len(reverse_escape)
+1691	            self.positiontup = [
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/compiler.py
+ Line number: 1721
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1720	    def _process_numeric(self):
+1721	        assert self._numeric_binds
+1722	        assert self.state is CompilerState.STRING_APPLIED
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/compiler.py
+ Line number: 1722
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1721	        assert self._numeric_binds
+1722	        assert self.state is CompilerState.STRING_APPLIED
+1723	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/compiler.py
+ Line number: 1767
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1766	            }
+1767	            assert len(param_pos) == len_before
+1768	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/compiler.py
+ Line number: 1864
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1863	        if self._render_postcompile and not _no_postcompile:
+1864	            assert self._post_compile_expanded_state is not None
+1865	            if not params:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/compiler.py
+ Line number: 1893
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1892	            ckbm_tuple = self._cache_key_bind_match
+1893	            assert ckbm_tuple is not None
+1894	            ckbm, _ = ckbm_tuple
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/compiler.py
+ Line number: 2140
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2139	                    if parameter.type._is_tuple_type:
+2140	                        assert values is not None
+2141	                        new_processors.update(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/compiler.py
+ Line number: 2192
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2191	        if numeric_positiontup is not None:
+2192	            assert new_positiontup is not None
+2193	            param_pos = {
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/compiler.py
+ Line number: 2252
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2251	
+2252	        assert self.compile_state is not None
+2253	        statement = self.compile_state.statement
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/compiler.py
+ Line number: 2256
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2255	        if TYPE_CHECKING:
+2256	            assert isinstance(statement, Insert)
+2257	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/compiler.py
+ Line number: 2334
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2333	
+2334	        assert self.compile_state is not None
+2335	        statement = self.compile_state.statement
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/compiler.py
+ Line number: 2338
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2337	        if TYPE_CHECKING:
+2338	            assert isinstance(statement, Insert)
+2339	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/compiler.py
+ Line number: 2344
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2343	        returning = self.implicit_returning
+2344	        assert returning is not None
+2345	        ret = {col: idx for idx, col in enumerate(returning)}
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/compiler.py
+ Line number: 2648
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2647	            if TYPE_CHECKING:
+2648	                assert isinstance(table, NamedFromClause)
+2649	            tablename = table.name
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/compiler.py
+ Line number: 3291
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+3290	                m = post_compile_pattern.search(bind_expression_template)
+3291	                assert m and m.group(
+3292	                    2
+3293	                ), "unexpected format for expanding parameter"
+3294	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/compiler.py
+ Line number: 3361
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+3360	        ):
+3361	            assert not typ_dialect_impl._is_array
+3362	            to_update = [
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/compiler.py
+ Line number: 3725
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+3724	                    )
+3725	                    assert m, "unexpected format for expanding parameter"
+3726	                    wrapped = "(__[POSTCOMPILE_%s~~%s~~REPL~~%s~~])" % (
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/compiler.py
+ Line number: 4058
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+4057	        self_ctes = self._init_cte_state()
+4058	        assert self_ctes is self.ctes
+4059	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/compiler.py
+ Line number: 4079
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+4078	            ]
+4079	            assert _ == cte_name
+4080	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/compiler.py
+ Line number: 4128
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+4127	
+4128	                assert existing_cte_reference_cte is _reference_cte
+4129	                assert existing_cte_reference_cte is existing_cte
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/compiler.py
+ Line number: 4129
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+4128	                assert existing_cte_reference_cte is _reference_cte
+4129	                assert existing_cte_reference_cte is existing_cte
+4130	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/compiler.py
+ Line number: 4218
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+4217	
+4218	                assert kwargs.get("subquery", False) is False
+4219	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/compiler.py
+ Line number: 4291
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+4290	                # from visit_lateral() and we need to set enclosing_lateral.
+4291	                assert alias._is_lateral
+4292	                kwargs["enclosing_lateral"] = alias
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/compiler.py
+ Line number: 4473
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+4472	        # collection properly
+4473	        assert objects
+4474	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/compiler.py
+ Line number: 4568
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+4567	        # these assertions right now set up the current expected inputs
+4568	        assert within_columns_clause, (
+4569	            "_label_select_column is only relevant within "
+4570	            "the columns clause of a SELECT or RETURNING"
+4571	        )
+4572	        result_expr: Union[elements.Label[Any], _CompileLabel]
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/compiler.py
+ Line number: 4588
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+4587	
+4588	            assert (
+4589	                proxy_name is not None
+4590	            ), "proxy_name is required if 'name' is passed"
+4591	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/compiler.py
+ Line number: 4696
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+4695	                    # just-added _label_returning_column method
+4696	                    assert not column_is_repeated
+4697	                    fallback_label_name = column._anon_name_label
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/compiler.py
+ Line number: 4795
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+4794	    ):
+4795	        assert select_wraps_for is None, (
+4796	            "SQLAlchemy 1.4 requires use of "
+4797	            "the translate_select_structure hook for structural "
+4798	            "translations of SELECT objects"
+4799	        )
+4800	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/compiler.py
+ Line number: 5123
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+5122	        if warn_linting:
+5123	            assert from_linter is not None
+5124	            from_linter.warn()
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/compiler.py
+ Line number: 5541
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+5540	        imv = self._insertmanyvalues
+5541	        assert imv is not None
+5542	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/compiler.py
+ Line number: 5674
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+5673	        insert_crud_params = imv.insert_crud_params
+5674	        assert insert_crud_params is not None
+5675	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/compiler.py
+ Line number: 5745
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+5744	                positiontup = self.positiontup
+5745	                assert positiontup is not None
+5746	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/compiler.py
+ Line number: 5754
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+5753	                expand_pos_upper_index = max(all_expand_positions) + 1
+5754	                assert (
+5755	                    len(all_expand_positions)
+5756	                    == expand_pos_upper_index - expand_pos_lower_index
+5757	                )
+5758	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/compiler.py
+ Line number: 5833
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+5832	                    # parameters
+5833	                    assert not extra_params_right
+5834	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/compiler.py
+ Line number: 6033
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+6032	            if add_sentinel_cols is not None:
+6033	                assert use_insertmanyvalues
+6034	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/compiler.py
+ Line number: 6082
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+6081	                        # _get_sentinel_column_for_table.
+6082	                        assert not add_sentinel_cols[0]._insert_sentinel, (
+6083	                            "sentinel selection rules should have prevented "
+6084	                            "us from getting here for this dialect"
+6085	                        )
+6086	
+
+
+ + +
+
+ +
+
+ hardcoded_sql_expressions: Possible SQL injection vector through string-based query construction.
+ Test ID: B608
+ Severity: MEDIUM
+ Confidence: LOW
+ CWE: CWE-89
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/compiler.py
+ Line number: 6224
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b608_hardcoded_sql_expressions.html
+ +
+
+6223	                text += (
+6224	                    f" SELECT {colnames_w_cast} FROM "
+6225	                    f"(VALUES ({insert_single_values_expr})) "
+6226	                    f"AS imp_sen({colnames}, sen_counter) "
+6227	                    "ORDER BY sen_counter"
+6228	                )
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/compiler.py
+ Line number: 6332
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+6331	        if TYPE_CHECKING:
+6332	            assert isinstance(compile_state, UpdateDMLState)
+6333	        update_stmt = compile_state.statement  # type: ignore[assignment]
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/compiler.py
+ Line number: 6463
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+6462	        if warn_linting:
+6463	            assert from_linter is not None
+6464	            from_linter.warn(stmt_type="UPDATE")
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/compiler.py
+ Line number: 6615
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+6614	        if warn_linting:
+6615	            assert from_linter is not None
+6616	            from_linter.warn(stmt_type="DELETE")
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/compiler.py
+ Line number: 7869
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+7868	        if name is None:
+7869	            assert alias is not None
+7870	            return self.quote(alias.name)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/compiler.py
+ Line number: 7899
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+7898	
+7899	        assert name is not None
+7900	        if constraint.__visit_name__ == "index":
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/compiler.py
+ Line number: 7953
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+7952	        name = self.format_constraint(index)
+7953	        assert name is not None
+7954	        return name
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/compiler.py
+ Line number: 7965
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+7964	            if TYPE_CHECKING:
+7965	                assert isinstance(table, NamedFromClause)
+7966	            name = table.name
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/compiler.py
+ Line number: 8008
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+8007	            name = column.name
+8008	            assert name is not None
+8009	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/crud.py
+ Line number: 166
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+165	        kw.pop("accumulate_bind_names", None)
+166	    assert (
+167	        "accumulate_bind_names" not in kw
+168	    ), "Don't know how to handle insert within insert without a CTE"
+169	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/crud.py
+ Line number: 230
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+229	        mp = compile_state._multi_parameters
+230	        assert mp is not None
+231	        spd = mp[0]
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/crud.py
+ Line number: 237
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+236	        stmt_parameter_tuples = compile_state._ordered_values
+237	        assert spd is not None
+238	        spd_str_key = {_column_as_key(key) for key in spd}
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/crud.py
+ Line number: 251
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+250	    elif stmt_parameter_tuples:
+251	        assert spd_str_key is not None
+252	        parameters = {
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/crud.py
+ Line number: 296
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+295	
+296	        assert not compile_state._has_multi_parameters
+297	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/crud.py
+ Line number: 370
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+369	                elif multi_not_in_from:
+370	                    assert compiler.render_table_with_column_in_update_from
+371	                    raise exc.CompileError(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/crud.py
+ Line number: 393
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+392	        # is a multiparams, is not an insert from a select
+393	        assert not stmt._select_names
+394	        multi_extended_values = _extend_values_for_multiparams(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/crud.py
+ Line number: 559
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+558	                if TYPE_CHECKING:
+559	                    assert isinstance(col.table, TableClause)
+560	                return "%s_%s" % (col.table.name, col.key)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/crud.py
+ Line number: 588
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+587	
+588	    assert compiler.stack[-1]["selectable"] is stmt
+589	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/crud.py
+ Line number: 664
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+663	
+664	    assert compile_state.isupdate or compile_state.isinsert
+665	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/crud.py
+ Line number: 1392
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1391	        col = _multiparam_column(c, index)
+1392	        assert isinstance(stmt, dml.Insert)
+1393	        return _create_insert_prefetch_bind_param(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/crud.py
+ Line number: 1513
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1512	    mp = compile_state._multi_parameters
+1513	    assert mp is not None
+1514	    for i, row in enumerate(mp[1:]):
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/ddl.py
+ Line number: 126
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+125	        else:
+126	            assert False, "compiler or dialect is required"
+127	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/ddl.py
+ Line number: 443
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+442	    def stringify_dialect(self):  # type: ignore[override]
+443	        assert not isinstance(self.element, str)
+444	        return self.element.create_drop_stringify_dialect
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/ddl.py
+ Line number: 872
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+871	        self.connection = connection
+872	        assert not kw, f"Unexpected keywords: {kw.keys()}"
+873	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/dml.py
+ Line number: 235
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+234	    def _process_select_values(self, statement: ValuesBase) -> None:
+235	        assert statement._select_names is not None
+236	        parameters: MutableMapping[_DMLColumnElement, Any] = {
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/dml.py
+ Line number: 246
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+245	            # does not allow this construction to occur
+246	            assert False, "This statement already has parameters"
+247	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/dml.py
+ Line number: 330
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+329	            else:
+330	                assert self._multi_parameters
+331	                self._multi_parameters.extend(multi_parameters)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/dml.py
+ Line number: 364
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+363	            self._no_parameters = False
+364	            assert parameters is not None
+365	            self._dict_parameters = dict(parameters)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/dml.py
+ Line number: 1175
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1174	                    # case
+1175	                    assert isinstance(self, Insert)
+1176	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/elements.py
+ Line number: 323
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+322	        if TYPE_CHECKING:
+323	            assert isinstance(self, ClauseElement)
+324	        return dialect.statement_compiler(dialect, self, **kw)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/elements.py
+ Line number: 526
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+525	            if TYPE_CHECKING:
+526	                assert isinstance(self, Executable)
+527	            return connection._execute_clauseelement(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/elements.py
+ Line number: 702
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+701	            if TYPE_CHECKING:
+702	                assert compiled_cache is not None
+703	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/elements.py
+ Line number: 759
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+758	        grouped = self.self_group(against=operators.inv)
+759	        assert isinstance(grouped, ColumnElement)
+760	        return UnaryExpression(grouped, operator=operators.inv)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/elements.py
+ Line number: 1485
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1484	            grouped = self.self_group(against=operators.inv)
+1485	            assert isinstance(grouped, ColumnElement)
+1486	            return UnaryExpression(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/elements.py
+ Line number: 1682
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1681	
+1682	        assert key is not None
+1683	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/elements.py
+ Line number: 1747
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1746	            # 16 bits leftward.  fill extra add_hash on right
+1747	            assert add_hash < (2 << 15)
+1748	            assert seed
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/elements.py
+ Line number: 1748
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1747	            assert add_hash < (2 << 15)
+1748	            assert seed
+1749	            hash_value = (hash_value << 16) | add_hash
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/elements.py
+ Line number: 2883
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2882	        if operators.is_associative(op):
+2883	            assert (
+2884	                negate is None
+2885	            ), f"negate not supported for associative operator {op}"
+2886	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/elements.py
+ Line number: 3008
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+3007	        grouped = self.self_group(against=operators.inv)
+3008	        assert isinstance(grouped, ColumnElement)
+3009	        return UnaryExpression(grouped, operator=operators.inv)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/elements.py
+ Line number: 3120
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+3119	        else:
+3120	            assert lcc
+3121	            # just one element.  return it as a single boolean element,
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/elements.py
+ Line number: 3850
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+3849	        # comparison operators should never call reverse_operate
+3850	        assert not operators.is_comparison(op)
+3851	        raise exc.ArgumentError(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/elements.py
+ Line number: 4071
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+4070	    def self_group(self, against: Optional[OperatorType] = None) -> Self:
+4071	        assert against is operator.getitem
+4072	        return self
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/elements.py
+ Line number: 4121
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+4120	    def _ungroup(self) -> ColumnElement[_T]:
+4121	        assert isinstance(self.element, ColumnElement)
+4122	        return self.element._ungroup()
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/elements.py
+ Line number: 5074
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+5073	            else:
+5074	                assert not TYPE_CHECKING or isinstance(t, NamedFromClause)
+5075	                label = t.name + "_" + name
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/elements.py
+ Line number: 5086
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+5085	                # assert false on it for now
+5086	                assert not isinstance(label, quoted_name)
+5087	                label = quoted_name(label, t.name.quote)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/elements.py
+ Line number: 5314
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+5313	    def __new__(cls, value: str, quote: Optional[bool]) -> quoted_name:
+5314	        assert (
+5315	            value is not None
+5316	        ), "use quoted_name.construct() for None passthrough"
+5317	        if isinstance(value, cls) and (quote is None or value.quote == quote):
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/elements.py
+ Line number: 5445
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+5444	        if TYPE_CHECKING:
+5445	            assert isinstance(self._Annotated__element, Column)
+5446	        return self._Annotated__element.info
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/functions.py
+ Line number: 1600
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1599	    def __init__(self, seq: schema.Sequence, **kw: Any) -> None:
+1600	        assert isinstance(
+1601	            seq, schema.Sequence
+1602	        ), "next_value() accepts a Sequence object as input."
+1603	        self.sequence = seq
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/lambdas.py
+ Line number: 408
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+407	        while parent is not None:
+408	            assert parent.closure_cache_key is not CacheConst.NO_CACHE
+409	            parent_closure_cache_key: Tuple[Any, ...] = (
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/lambdas.py
+ Line number: 451
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+450	    def _resolve_with_args(self, *lambda_args: Any) -> ClauseElement:
+451	        assert isinstance(self._rec, AnalyzedFunction)
+452	        tracker_fn = self._rec.tracker_instrumented_fn
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/lambdas.py
+ Line number: 594
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+593	        if TYPE_CHECKING:
+594	            assert isinstance(self._rec.expected_expr, ClauseElement)
+595	        if self._rec.expected_expr.supports_execution:
+
+
+ + +
+
+ +
+
+ hardcoded_sql_expressions: Possible SQL injection vector through string-based query construction.
+ Test ID: B608
+ Severity: MEDIUM
+ Confidence: LOW
+ CWE: CWE-89
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/lambdas.py
+ Line number: 1045
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b608_hardcoded_sql_expressions.html
+ +
+
+1044	        raise exc.InvalidRequestError(
+1045	            "Closure variable named '%s' inside of lambda callable %s "
+1046	            "does not refer to a cacheable SQL element, and also does not "
+1047	            "appear to be serving as a SQL literal bound value based on "
+1048	            "the default "
+1049	            "SQL expression returned by the function.   This variable "
+1050	            "needs to remain outside the scope of a SQL-generating lambda "
+1051	            "so that a proper cache key may be generated from the "
+1052	            "lambda's state.  Evaluate this variable outside of the "
+1053	            "lambda, set track_on=[<elements>] to explicitly select "
+1054	            "closure elements to track, or set "
+1055	            "track_closure_variables=False to exclude "
+1056	            "closure variables from being part of the cache key."
+1057	            % (variable_name, fn.__code__),
+1058	        ) from from_
+
+
+ + +
+
+ +
+
+ exec_used: Use of exec detected.
+ Test ID: B102
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/lambdas.py
+ Line number: 1264
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b102_exec_used.html
+ +
+
+1263	        vars_ = {"o%d" % i: cell_values[i] for i in argrange}
+1264	        exec(code, vars_, vars_)
+1265	        closure = vars_["make_cells"]()
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/schema.py
+ Line number: 824
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+823	            quote_schema = quote_schema
+824	            assert isinstance(schema, str)
+825	            self.schema = quoted_name(schema, quote_schema)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/schema.py
+ Line number: 948
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+947	
+948	        assert extend_existing
+949	        assert not keep_existing
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/schema.py
+ Line number: 949
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+948	        assert extend_existing
+949	        assert not keep_existing
+950	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/schema.py
+ Line number: 1046
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1045	        if sentinel_is_explicit and explicit_sentinel_col is autoinc_col:
+1046	            assert autoinc_col is not None
+1047	            sentinel_is_autoinc = True
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/schema.py
+ Line number: 1125
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1124	        if the_sentinel is None and self.primary_key:
+1125	            assert autoinc_col is None
+1126	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/schema.py
+ Line number: 1272
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1271	        metadata = parent
+1272	        assert isinstance(metadata, MetaData)
+1273	        metadata._add_table(self.name, self.schema, self)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/schema.py
+ Line number: 2224
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2223	    def _set_type(self, type_: TypeEngine[Any]) -> None:
+2224	        assert self.type._isnull or type_ is self.type
+2225	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/schema.py
+ Line number: 2322
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2321	        table = parent
+2322	        assert isinstance(table, Table)
+2323	        if not self.name:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/schema.py
+ Line number: 3023
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+3022	        else:
+3023	            assert isinstance(self._colspec, str)
+3024	            return self._colspec
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/schema.py
+ Line number: 3121
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+3120	            if isinstance(c, Column):
+3121	                assert c.table is parenttable
+3122	                break
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/schema.py
+ Line number: 3124
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+3123	        else:
+3124	            assert False
+3125	        ######################
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/schema.py
+ Line number: 3147
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+3146	            parent = self.parent
+3147	            assert parent is not None
+3148	            key = parent.key
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/schema.py
+ Line number: 3172
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+3171	    def _set_target_column(self, column: Column[Any]) -> None:
+3172	        assert self.parent is not None
+3173	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/schema.py
+ Line number: 3250
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+3249	    def _set_parent(self, parent: SchemaEventTarget, **kw: Any) -> None:
+3250	        assert isinstance(parent, Column)
+3251	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/schema.py
+ Line number: 3264
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+3263	        self._set_target_column(_column)
+3264	        assert self.constraint is not None
+3265	        self.constraint._validate_dest_table(table)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/schema.py
+ Line number: 3278
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+3277	        # on the hosting Table when attached to the Table.
+3278	        assert isinstance(table, Table)
+3279	        if self.constraint is None:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/schema.py
+ Line number: 3370
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+3369	        if TYPE_CHECKING:
+3370	            assert isinstance(parent, Column)
+3371	        self.column = parent
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/schema.py
+ Line number: 3936
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+3935	        column = parent
+3936	        assert isinstance(column, Column)
+3937	        super()._set_parent(column)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/schema.py
+ Line number: 4035
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+4034	        column = parent
+4035	        assert isinstance(column, Column)
+4036	        self.column = column
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/schema.py
+ Line number: 4189
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+4188	    def _set_parent(self, parent: SchemaEventTarget, **kw: Any) -> None:
+4189	        assert isinstance(parent, (Table, Column))
+4190	        self.parent = parent
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/schema.py
+ Line number: 4245
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+4244	            # this is expected to be an empty list
+4245	            assert not processed_expressions
+4246	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/schema.py
+ Line number: 4276
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+4275	            # such that when all those cols are attached, we autoattach.
+4276	            assert not evt, "Should not reach here on event call"
+4277	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/schema.py
+ Line number: 4330
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+4329	            ]
+4330	            assert len(result) == len(self._pending_colargs)
+4331	            return result
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/schema.py
+ Line number: 4346
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+4345	    def _set_parent(self, parent: SchemaEventTarget, **kw: Any) -> None:
+4346	        assert isinstance(parent, (Table, Column))
+4347	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/schema.py
+ Line number: 4407
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+4406	    def _set_parent(self, parent: SchemaEventTarget, **kw: Any) -> None:
+4407	        assert isinstance(parent, (Column, Table))
+4408	        Constraint._set_parent(self, parent)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/schema.py
+ Line number: 4445
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+4444	
+4445	        assert isinstance(self.parent, Table)
+4446	        c = self.__class__(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/schema.py
+ Line number: 4753
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+4752	            if hasattr(self, "parent"):
+4753	                assert table is self.parent
+4754	            self._set_parent_with_dispatch(table)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/schema.py
+ Line number: 4836
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+4835	        table = parent
+4836	        assert isinstance(table, Table)
+4837	        Constraint._set_parent(self, table)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/schema.py
+ Line number: 4986
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+4985	        table = parent
+4986	        assert isinstance(table, Table)
+4987	        super()._set_parent(table)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/schema.py
+ Line number: 5298
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+5297	        table = parent
+5298	        assert isinstance(table, Table)
+5299	        ColumnCollectionMixin._set_parent(self, table)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/schema.py
+ Line number: 5312
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+5311	        col_expressions = self._col_expressions(table)
+5312	        assert len(expressions) == len(col_expressions)
+5313	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/schema.py
+ Line number: 5321
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+5320	            else:
+5321	                assert False
+5322	        self.expressions = self._table_bound_expressions = exprs
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/schema.py
+ Line number: 6032
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+6031	    def _set_parent(self, parent: SchemaEventTarget, **kw: Any) -> None:
+6032	        assert isinstance(parent, Column)
+6033	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/schema.py
+ Line number: 6178
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+6177	    def _set_parent(self, parent: SchemaEventTarget, **kw: Any) -> None:
+6178	        assert isinstance(parent, Column)
+6179	        if not isinstance(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/selectable.py
+ Line number: 919
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+918	            if "_columns" in self.__dict__:
+919	                assert "primary_key" in self.__dict__
+920	                assert "foreign_keys" in self.__dict__
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/selectable.py
+ Line number: 920
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+919	                assert "primary_key" in self.__dict__
+920	                assert "foreign_keys" in self.__dict__
+921	                return
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/selectable.py
+ Line number: 2106
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2105	    ) -> None:
+2106	        assert sampling is not None
+2107	        functions = util.preloaded.sql_functions
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/selectable.py
+ Line number: 2261
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2260	        """
+2261	        assert is_select_statement(
+2262	            self.element
+2263	        ), f"CTE element f{self.element} does not support union()"
+2264	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/selectable.py
+ Line number: 2293
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2292	
+2293	        assert is_select_statement(
+2294	            self.element
+2295	        ), f"CTE element f{self.element} does not support union_all()"
+2296	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/selectable.py
+ Line number: 2407
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2406	                if TYPE_CHECKING:
+2407	                    assert is_column_element(c)
+2408	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/selectable.py
+ Line number: 2413
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2412	                if TYPE_CHECKING:
+2413	                    assert is_column_element(c)
+2414	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/selectable.py
+ Line number: 2455
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2454	                if TYPE_CHECKING:
+2455	                    assert is_column_element(c)
+2456	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/selectable.py
+ Line number: 2479
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2478	                            # you need two levels of duplication to be here
+2479	                            assert hash(names[required_label_name]) == hash(c)
+2480	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/selectable.py
+ Line number: 4831
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+4830	            elif TYPE_CHECKING:
+4831	                assert is_column_element(c)
+4832	
+
+
+ + +
+
+ +
+
+ hardcoded_sql_expressions: Possible SQL injection vector through string-based query construction.
+ Test ID: B608
+ Severity: MEDIUM
+ Confidence: LOW
+ CWE: CWE-89
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/selectable.py
+ Line number: 4999
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b608_hardcoded_sql_expressions.html
+ +
+
+4998	                raise exc.InvalidRequestError(
+4999	                    "Select statement '%r"
+5000	                    "' returned no FROM clauses "
+5001	                    "due to auto-correlation; "
+5002	                    "specify correlate(<tables>) "
+5003	                    "to control correlation "
+5004	                    "manually." % self.statement
+5005	                )
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/selectable.py
+ Line number: 5053
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+5052	                if onclause is not None:
+5053	                    assert isinstance(onclause, ColumnElement)
+5054	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/selectable.py
+ Line number: 5076
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+5075	            if TYPE_CHECKING:
+5076	                assert isinstance(right, FromClause)
+5077	                if onclause is not None:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/selectable.py
+ Line number: 5078
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+5077	                if onclause is not None:
+5078	                    assert isinstance(onclause, ColumnElement)
+5079	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/selectable.py
+ Line number: 5099
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+5098	            else:
+5099	                assert left is not None
+5100	                self.from_clauses = self.from_clauses + (
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/selectable.py
+ Line number: 6249
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+6248	
+6249	        assert isinstance(self._where_criteria, tuple)
+6250	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/selectable.py
+ Line number: 6956
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+6955	
+6956	        assert isinstance(self.element, ScalarSelect)
+6957	        element = self.element.element
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/selectable.py
+ Line number: 7191
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+7190	        if TYPE_CHECKING:
+7191	            assert isinstance(fromclause, Subquery)
+7192	
+
+
+ + +
+
+ +
+
+ blacklist: Consider possible security implications associated with pickle module.
+ Test ID: B403
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-502
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/sqltypes.py
+ Line number: 17
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_imports.html#b403-import-pickle
+ +
+
+16	import json
+17	import pickle
+18	from typing import Any
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/sqltypes.py
+ Line number: 112
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+111	            if TYPE_CHECKING:
+112	                assert isinstance(self.type, HasExpressionLookup)
+113	            lookup = self.type._expression_adaptations.get(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/sqltypes.py
+ Line number: 724
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+723	    def _literal_processor_portion(self, dialect, _portion=None):
+724	        assert _portion in (None, 0, -1)
+725	        if _portion is not None:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/sqltypes.py
+ Line number: 1518
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1517	            self.enum_class = enums[0]  # type: ignore[assignment]
+1518	            assert self.enum_class is not None
+1519	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/sqltypes.py
+ Line number: 1549
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1548	        typ = self._resolve_for_python_type(tv, tv, tv)
+1549	        assert typ is not None
+1550	        return typ
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/sqltypes.py
+ Line number: 1764
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1763	        kw.setdefault("_create_events", False)
+1764	        assert "_enums" in kw
+1765	        return impltype(**kw)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/sqltypes.py
+ Line number: 1798
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1797	        )
+1798	        assert e.table is table
+1799	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/sqltypes.py
+ Line number: 2038
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2037	        )
+2038	        assert e.table is table
+2039	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/sqltypes.py
+ Line number: 2183
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2182	        if TYPE_CHECKING:
+2183	            assert isinstance(self.impl_instance, DateTime)
+2184	        impl_processor = self.impl_instance.bind_processor(dialect)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/sqltypes.py
+ Line number: 2215
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2214	        if TYPE_CHECKING:
+2215	            assert isinstance(self.impl_instance, DateTime)
+2216	        impl_processor = self.impl_instance.result_processor(dialect, coltype)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/traversals.py
+ Line number: 360
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+359	                # TODO: use abc classes
+360	                assert False
+361	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/traversals.py
+ Line number: 549
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+548	
+549	                assert left_visit_sym is not None
+550	                assert left_attrname is not None
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/traversals.py
+ Line number: 550
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+549	                assert left_visit_sym is not None
+550	                assert left_attrname is not None
+551	                assert right_attrname is not None
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/traversals.py
+ Line number: 551
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+550	                assert left_attrname is not None
+551	                assert right_attrname is not None
+552	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/traversals.py
+ Line number: 554
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+553	                dispatch = self.dispatch(left_visit_sym)
+554	                assert dispatch is not None, (
+555	                    f"{self.__class__} has no dispatch for "
+556	                    f"'{self._dispatch_lookup[left_visit_sym]}'"
+557	                )
+558	                left_child = operator.attrgetter(left_attrname)(left)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/type_api.py
+ Line number: 987
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+986	            # this can't be self, else we create a cycle
+987	            assert impl is not self
+988	            d: _TypeMemoDict = {"impl": impl, "result": {}}
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/type_api.py
+ Line number: 1745
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1744	            if TYPE_CHECKING:
+1745	                assert isinstance(self.expr.type, TypeDecorator)
+1746	            kwargs["_python_is_types"] = self.expr.type.coerce_to_is_types
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/type_api.py
+ Line number: 1753
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1752	            if TYPE_CHECKING:
+1753	                assert isinstance(self.expr.type, TypeDecorator)
+1754	            kwargs["_python_is_types"] = self.expr.type.coerce_to_is_types
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/util.py
+ Line number: 234
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+233	            if resolve_ambiguity:
+234	                assert cols_in_onclause is not None
+235	                if set(f.c).union(s.c).issuperset(cols_in_onclause):
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/util.py
+ Line number: 421
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+420	        elif isinstance(element, _textual_label_reference):
+421	            assert False, "can't unwrap a textual label reference"
+422	        return None
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/util.py
+ Line number: 695
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+694	            else:
+695	                assert False, "Unknown parameter type %s" % (
+696	                    type(multi_params[0])
+697	                )
+698	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/util.py
+ Line number: 863
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+862	        if prevright is not None:
+863	            assert right is not None
+864	            prevright.left = right
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/util.py
+ Line number: 1197
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1196	        if TYPE_CHECKING:
+1197	            assert isinstance(col, KeyedColumnElement)
+1198	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/util.py
+ Line number: 1207
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1206	        if TYPE_CHECKING:
+1207	            assert isinstance(col, KeyedColumnElement)
+1208	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/util.py
+ Line number: 1336
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1335	    def chain(self, visitor: ExternalTraversal) -> ColumnAdapter:
+1336	        assert isinstance(visitor, ColumnAdapter)
+1337	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/util.py
+ Line number: 1463
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1462	        else:
+1463	            assert offset_clause is not None
+1464	            offset_clause = _offset_or_limit_clause(offset_clause)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/sql/visitors.py
+ Line number: 584
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+583	            sym_name = sym.value
+584	            assert sym_name not in lookup, sym_name
+585	            lookup[sym] = lookup[sym_name] = visit_key
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/assertions.py
+ Line number: 190
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+189	        # block will assert our messages
+190	        assert _SEEN is not None
+191	        assert _EXC_CLS is not None
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/assertions.py
+ Line number: 191
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+190	        assert _SEEN is not None
+191	        assert _EXC_CLS is not None
+192	        _FILTERS.extend(filters)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/assertions.py
+ Line number: 249
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+248	                if assert_:
+249	                    assert not seen, "Warnings were not seen: %s" % ", ".join(
+250	                        "%r" % (s.pattern if regex else s) for s in seen
+251	                    )
+252	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/assertions.py
+ Line number: 271
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+270	    deviance = int(expected * variance)
+271	    assert (
+272	        abs(received - expected) < deviance
+273	    ), "Given int value %s is not within %d%% of expected value %s" % (
+274	        received,
+275	        variance * 100,
+276	        expected,
+277	    )
+278	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/assertions.py
+ Line number: 281
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+280	def eq_regex(a, b, msg=None, flags=0):
+281	    assert re.match(b, a, flags), msg or "%r !~ %r" % (a, b)
+282	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/assertions.py
+ Line number: 286
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+285	    """Assert a == b, with repr messaging on failure."""
+286	    assert a == b, msg or "%r != %r" % (a, b)
+287	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/assertions.py
+ Line number: 291
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+290	    """Assert a != b, with repr messaging on failure."""
+291	    assert a != b, msg or "%r == %r" % (a, b)
+292	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/assertions.py
+ Line number: 296
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+295	    """Assert a <= b, with repr messaging on failure."""
+296	    assert a <= b, msg or "%r != %r" % (a, b)
+297	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/assertions.py
+ Line number: 300
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+299	def is_instance_of(a, b, msg=None):
+300	    assert isinstance(a, b), msg or "%r is not an instance of %r" % (a, b)
+301	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/assertions.py
+ Line number: 321
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+320	    """Assert a is b, with repr messaging on failure."""
+321	    assert a is b, msg or "%r is not %r" % (a, b)
+322	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/assertions.py
+ Line number: 326
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+325	    """Assert a is not b, with repr messaging on failure."""
+326	    assert a is not b, msg or "%r is %r" % (a, b)
+327	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/assertions.py
+ Line number: 335
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+334	    """Assert a in b, with repr messaging on failure."""
+335	    assert a in b, msg or "%r not in %r" % (a, b)
+336	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/assertions.py
+ Line number: 340
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+339	    """Assert a in not b, with repr messaging on failure."""
+340	    assert a not in b, msg or "%r is in %r" % (a, b)
+341	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/assertions.py
+ Line number: 349
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+348	    """Assert a.startswith(fragment), with repr messaging on failure."""
+349	    assert a.startswith(fragment), msg or "%r does not start with %r" % (
+350	        a,
+351	        fragment,
+352	    )
+353	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/assertions.py
+ Line number: 363
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+362	
+363	    assert a == b, msg or "%r != %r" % (a, b)
+364	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/assertions.py
+ Line number: 380
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+379	    ):
+380	        assert False, (
+381	            "Exception %r was correctly raised but did not set a cause, "
+382	            "within context %r as its cause."
+383	            % (exception, exception.__context__)
+384	        )
+385	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/assertions.py
+ Line number: 476
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+475	            error_as_string = str(err)
+476	            assert re.search(msg, error_as_string, re.UNICODE), "%r !~ %s" % (
+477	                msg,
+478	                error_as_string,
+479	            )
+480	        if check_context and not are_we_already_in_a_traceback:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/assertions.py
+ Line number: 492
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+491	    # assert outside the block so it works for AssertionError too !
+492	    assert success, "Callable did not raise an exception"
+493	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/assertions.py
+ Line number: 752
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+751	                    msg = "Expected to find bindparam %r in %r" % (v, stmt)
+752	                    assert False, msg
+753	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/assertions.py
+ Line number: 777
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+776	    ):
+777	        assert len(table.c) == len(reflected_table.c)
+778	        for c, reflected_c in zip(table.c, reflected_table.c):
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/assertions.py
+ Line number: 780
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+779	            eq_(c.name, reflected_c.name)
+780	            assert reflected_c is reflected_table.c[c.name]
+781	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/assertions.py
+ Line number: 788
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+787	                msg = "Type '%s' doesn't correspond to type '%s'"
+788	                assert isinstance(reflected_c.type, type(c.type)), msg % (
+789	                    reflected_c.type,
+790	                    c.type,
+791	                )
+792	            else:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/assertions.py
+ Line number: 804
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+803	            if c.server_default:
+804	                assert isinstance(
+805	                    reflected_c.server_default, schema.FetchedValue
+806	                )
+807	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/assertions.py
+ Line number: 809
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+808	        if strict_constraints:
+809	            assert len(table.primary_key) == len(reflected_table.primary_key)
+810	            for c in table.primary_key:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/assertions.py
+ Line number: 811
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+810	            for c in table.primary_key:
+811	                assert reflected_table.primary_key.columns[c.name] is not None
+812	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/assertions.py
+ Line number: 814
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+813	    def assert_types_base(self, c1, c2):
+814	        assert c1.type._compare_type_affinity(
+815	            c2.type
+816	        ), "On column %r, type '%s' doesn't correspond to type '%s'" % (
+817	            c1.name,
+818	            c1.type,
+819	            c2.type,
+820	        )
+821	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/assertsql.py
+ Line number: 32
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+31	    def no_more_statements(self):
+32	        assert False, (
+33	            "All statements are complete, but pending "
+34	            "assertion rules remain"
+35	        )
+36	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/assertsql.py
+ Line number: 103
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+102	                # to look like all the current RETURNING dialects
+103	                assert dialect.insert_executemany_returning
+104	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/assertsql.py
+ Line number: 351
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+350	        if self.count != self._statement_count:
+351	            assert False, "desired statement count %d does not match %d" % (
+352	                self.count,
+353	                self._statement_count,
+354	            )
+355	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/assertsql.py
+ Line number: 470
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+469	            elif rule.errormessage:
+470	                assert False, rule.errormessage
+471	        if observed:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/assertsql.py
+ Line number: 472
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+471	        if observed:
+472	            assert False, "Additional SQL statements remain:\n%s" % observed
+473	        elif not rule.is_consumed:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/config.py
+ Line number: 389
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+388	    def push_engine(cls, db, namespace):
+389	        assert _current, "Can't push without a default Config set up"
+390	        cls.push(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/engines.py
+ Line number: 61
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+60	
+61	        assert scope in ("class", "global", "function", "fixture")
+62	        self.testing_engines[scope].add(engine)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/engines.py
+ Line number: 170
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+169	                    # are not easily preventable
+170	                    assert (
+171	                        False
+172	                    ), "%d connection recs not cleared after test suite" % (ln)
+173	        if config.options and config.options.low_connections:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/engines.py
+ Line number: 186
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+185	            if rec.is_valid:
+186	                assert False
+187	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/engines.py
+ Line number: 259
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+258	            curs.execute("select 1")
+259	            assert False, "simulated connect failure didn't work"
+260	        else:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/engines.py
+ Line number: 420
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+419	        recv = [re.sub(r"[\n\t]", "", str(s)) for s in buffer]
+420	        assert recv == stmts, recv
+421	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/engines.py
+ Line number: 427
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+426	    engine = create_mock_engine(dialect_name + "://", executor)
+427	    assert not hasattr(engine, "mock")
+428	    engine.mock = buffer
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/exclusions.py
+ Line number: 242
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+241	        else:
+242	            assert False, "unknown predicate type: %s" % predicate
+243	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/exclusions.py
+ Line number: 310
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+309	        if self.op is not None:
+310	            assert driver is None, "DBAPI version specs not supported yet"
+311	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/exclusions.py
+ Line number: 473
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+472	def against(config, *queries):
+473	    assert queries, "no queries sent!"
+474	    return OrPredicate([Predicate.as_predicate(query) for query in queries])(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/fixtures/base.py
+ Line number: 50
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+49	    def assert_(self, val, msg=None):
+50	        assert val, msg
+51	
+
+
+ + +
+
+ +
+
+ try_except_pass: Try, Except, Pass detected.
+ Test ID: B110
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/fixtures/base.py
+ Line number: 101
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b110_try_except_pass.html
+ +
+
+100	                r.all()
+101	            except:
+102	                pass
+103	        for r in to_close:
+
+
+ + +
+
+ +
+
+ try_except_pass: Try, Except, Pass detected.
+ Test ID: B110
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/fixtures/base.py
+ Line number: 106
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b110_try_except_pass.html
+ +
+
+105	                r.close()
+106	            except:
+107	                pass
+108	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/fixtures/base.py
+ Line number: 230
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+229	            name = dialect_cls.name
+230	            assert name, "name is required"
+231	            registry.impls[name] = dialect_cls
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/fixtures/base.py
+ Line number: 236
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+235	
+236	        assert name is not None
+237	        del registry.impls[name]
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/fixtures/mypy.py
+ Line number: 324
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+323	                    print("Remaining messages:", extra, sep="\n")
+324	                assert False, "expected messages not found, see stdout"
+325	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/fixtures/mypy.py
+ Line number: 329
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+328	                print("\n".join(msg for _, msg in output))
+329	                assert False, "errors and/or notes remain, see stdout"
+330	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/fixtures/orm.py
+ Line number: 119
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+118	            def __init_subclass__(cls) -> None:
+119	                assert cls_registry is not None
+120	                cls_registry[cls.__name__] = cls
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/fixtures/orm.py
+ Line number: 175
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+174	            def __init_subclass__(cls, **kw) -> None:
+175	                assert cls_registry is not None
+176	                cls_registry[cls.__name__] = cls
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/fixtures/sql.py
+ Line number: 86
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+85	                cls.run_create_tables = "each"
+86	            assert cls.run_inserts in ("each", None)
+87	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/fixtures/sql.py
+ Line number: 328
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+327	        if a_key is None:
+328	            assert a._annotations.get("nocache")
+329	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/fixtures/sql.py
+ Line number: 330
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+329	
+330	            assert b_key is None
+331	        else:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/fixtures/sql.py
+ Line number: 336
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+335	            for a_param, b_param in zip(a_key.bindparams, b_key.bindparams):
+336	                assert a_param.compare(b_param, compare_values=compare_values)
+337	        return a_key, b_key
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/fixtures/sql.py
+ Line number: 358
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+357	                    if a_key is None:
+358	                        assert case_a[a]._annotations.get("nocache")
+359	                    if b_key is None:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/fixtures/sql.py
+ Line number: 360
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+359	                    if b_key is None:
+360	                        assert case_b[b]._annotations.get("nocache")
+361	                    continue
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/plugin/bootstrap.py
+ Line number: 39
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+38	    spec = importlib.util.spec_from_file_location(name, path)
+39	    assert spec is not None
+40	    assert spec.loader is not None
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/plugin/bootstrap.py
+ Line number: 40
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+39	    assert spec is not None
+40	    assert spec.loader is not None
+41	    mod = importlib.util.module_from_spec(spec)
+
+
+ + +
+
+ +
+
+ exec_used: Use of exec detected.
+ Test ID: B102
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/plugin/pytestplugin.py
+ Line number: 645
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b102_exec_used.html
+ +
+
+644	        # in format_argpsec_plus()
+645	        exec(code, env)
+646	        return env[fn_name]
+
+
+ + +
+
+ +
+
+ blacklist: Standard pseudo-random generators are not suitable for security/cryptographic purposes.
+ Test ID: B311
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-330
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_ddl.py
+ Line number: 214
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b311-random
+ +
+
+213	                "_".join(
+214	                    "".join(random.choice("abcdef") for j in range(20))
+215	                    for i in range(10)
+
+
+ + +
+
+ +
+
+ blacklist: Standard pseudo-random generators are not suitable for security/cryptographic purposes.
+ Test ID: B311
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-330
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_ddl.py
+ Line number: 259
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b311-random
+ +
+
+258	                "_".join(
+259	                    "".join(random.choice("abcdef") for j in range(30))
+260	                    for i in range(10)
+
+
+ + +
+
+ +
+
+ blacklist: Standard pseudo-random generators are not suitable for security/cryptographic purposes.
+ Test ID: B311
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-330
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_ddl.py
+ Line number: 287
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b311-random
+ +
+
+286	                "_".join(
+287	                    "".join(random.choice("abcdef") for j in range(30))
+288	                    for i in range(10)
+
+
+ + +
+
+ +
+
+ blacklist: Standard pseudo-random generators are not suitable for security/cryptographic purposes.
+ Test ID: B311
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-330
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_ddl.py
+ Line number: 315
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b311-random
+ +
+
+314	                "_".join(
+315	                    "".join(random.choice("abcdef") for j in range(30))
+316	                    for i in range(10)
+
+
+ + +
+
+ +
+
+ blacklist: Standard pseudo-random generators are not suitable for security/cryptographic purposes.
+ Test ID: B311
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-330
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_ddl.py
+ Line number: 343
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b311-random
+ +
+
+342	                "_".join(
+343	                    "".join(random.choice("abcdef") for j in range(30))
+344	                    for i in range(10)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_ddl.py
+ Line number: 379
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+378	
+379	        assert len(actual_name) > 255
+380	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_dialect.py
+ Line number: 143
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+142	                conn.execute(select(literal_column("méil")))
+143	                assert False
+144	            except exc.DBAPIError as err:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_dialect.py
+ Line number: 147
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+146	
+147	                assert str(err.orig) in str(err)
+148	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_dialect.py
+ Line number: 149
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+148	
+149	            assert isinstance(err_str, str)
+150	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_insert.py
+ Line number: 161
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+160	        r = connection.execute(stmt, data)
+161	        assert not r.returns_rows
+162	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_insert.py
+ Line number: 168
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+167	        )
+168	        assert r._soft_closed
+169	        assert not r.closed
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_insert.py
+ Line number: 169
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+168	        assert r._soft_closed
+169	        assert not r.closed
+170	        assert r.is_insert
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_insert.py
+ Line number: 170
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+169	        assert not r.closed
+170	        assert r.is_insert
+171	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_insert.py
+ Line number: 177
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+176	        # case, the row had to have been consumed at least.
+177	        assert not r.returns_rows or r.fetchone() is None
+178	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_insert.py
+ Line number: 188
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+187	        )
+188	        assert r._soft_closed
+189	        assert not r.closed
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_insert.py
+ Line number: 189
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+188	        assert r._soft_closed
+189	        assert not r.closed
+190	        assert r.is_insert
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_insert.py
+ Line number: 190
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+189	        assert not r.closed
+190	        assert r.is_insert
+191	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_insert.py
+ Line number: 196
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+195	        # "returns rows"
+196	        assert r.returns_rows
+197	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_insert.py
+ Line number: 210
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+209	        r = connection.execute(self.tables.autoinc_pk.insert())
+210	        assert r._soft_closed
+211	        assert not r.closed
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_insert.py
+ Line number: 211
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+210	        assert r._soft_closed
+211	        assert not r.closed
+212	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_insert.py
+ Line number: 223
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+222	        r = connection.execute(self.tables.autoinc_pk.insert(), [{}, {}, {}])
+223	        assert r._soft_closed
+224	        assert not r.closed
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_insert.py
+ Line number: 224
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+223	        assert r._soft_closed
+224	        assert not r.closed
+225	
+
+
+ + +
+
+ +
+
+ hardcoded_sql_expressions: Possible SQL injection vector through string-based query construction.
+ Test ID: B608
+ Severity: MEDIUM
+ Confidence: LOW
+ CWE: CWE-89
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_reflection.py
+ Line number: 111
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b608_hardcoded_sql_expressions.html
+ +
+
+110	            query = (
+111	                "CREATE VIEW %s.vv AS SELECT id, data FROM %s.test_table_s"
+112	                % (
+113	                    config.test_schema,
+114	                    config.test_schema,
+115	                )
+116	            )
+
+
+ + +
+
+ +
+
+ hardcoded_sql_expressions: Possible SQL injection vector through string-based query construction.
+ Test ID: B608
+ Severity: MEDIUM
+ Confidence: LOW
+ CWE: CWE-89
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_reflection.py
+ Line number: 149
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b608_hardcoded_sql_expressions.html
+ +
+
+148	                DDL(
+149	                    "create temporary view user_tmp_v as "
+150	                    "select * from user_tmp_%s" % config.ident
+151	                ),
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_reflection.py
+ Line number: 263
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+262	        meth = self._has_index(kind, connection)
+263	        assert meth("test_table", "my_idx")
+264	        assert not meth("test_table", "my_idx_s")
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_reflection.py
+ Line number: 264
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+263	        assert meth("test_table", "my_idx")
+264	        assert not meth("test_table", "my_idx_s")
+265	        assert not meth("nonexistent_table", "my_idx")
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_reflection.py
+ Line number: 265
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+264	        assert not meth("test_table", "my_idx_s")
+265	        assert not meth("nonexistent_table", "my_idx")
+266	        assert not meth("test_table", "nonexistent_idx")
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_reflection.py
+ Line number: 266
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+265	        assert not meth("nonexistent_table", "my_idx")
+266	        assert not meth("test_table", "nonexistent_idx")
+267	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_reflection.py
+ Line number: 268
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+267	
+268	        assert not meth("test_table", "my_idx_2")
+269	        assert not meth("test_table_2", "my_idx_3")
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_reflection.py
+ Line number: 269
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+268	        assert not meth("test_table", "my_idx_2")
+269	        assert not meth("test_table_2", "my_idx_3")
+270	        idx = Index("my_idx_2", self.tables.test_table.c.data2)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_reflection.py
+ Line number: 281
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+280	            if kind == "inspector":
+281	                assert not meth("test_table", "my_idx_2")
+282	                assert not meth("test_table_2", "my_idx_3")
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_reflection.py
+ Line number: 282
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+281	                assert not meth("test_table", "my_idx_2")
+282	                assert not meth("test_table_2", "my_idx_3")
+283	                meth.__self__.clear_cache()
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_reflection.py
+ Line number: 284
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+283	                meth.__self__.clear_cache()
+284	            assert meth("test_table", "my_idx_2") is True
+285	            assert meth("test_table_2", "my_idx_3") is True
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_reflection.py
+ Line number: 285
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+284	            assert meth("test_table", "my_idx_2") is True
+285	            assert meth("test_table_2", "my_idx_3") is True
+286	        finally:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_reflection.py
+ Line number: 294
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+293	        meth = self._has_index(kind, connection)
+294	        assert meth("test_table", "my_idx_s", schema=config.test_schema)
+295	        assert not meth("test_table", "my_idx", schema=config.test_schema)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_reflection.py
+ Line number: 295
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+294	        assert meth("test_table", "my_idx_s", schema=config.test_schema)
+295	        assert not meth("test_table", "my_idx", schema=config.test_schema)
+296	        assert not meth(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_reflection.py
+ Line number: 296
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+295	        assert not meth("test_table", "my_idx", schema=config.test_schema)
+296	        assert not meth(
+297	            "nonexistent_table", "my_idx_s", schema=config.test_schema
+298	        )
+299	        assert not meth(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_reflection.py
+ Line number: 299
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+298	        )
+299	        assert not meth(
+300	            "test_table", "nonexistent_idx_s", schema=config.test_schema
+301	        )
+302	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_reflection.py
+ Line number: 369
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+368	
+369	        assert o2.c.ref.references(t1.c[0])
+370	        if use_composite:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_reflection.py
+ Line number: 371
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+370	        if use_composite:
+371	            assert o2.c.ref2.references(t1.c[1])
+372	
+
+
+ + +
+
+ +
+
+ hardcoded_sql_expressions: Possible SQL injection vector through string-based query construction.
+ Test ID: B608
+ Severity: MEDIUM
+ Confidence: LOW
+ CWE: CWE-89
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_reflection.py
+ Line number: 513
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b608_hardcoded_sql_expressions.html
+ +
+
+512	            for name in names:
+513	                query = "CREATE VIEW %s AS SELECT * FROM %s" % (
+514	                    config.db.dialect.identifier_preparer.quote(
+515	                        "view %s" % name
+516	                    ),
+517	                    config.db.dialect.identifier_preparer.quote(name),
+518	                )
+519	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_reflection.py
+ Line number: 553
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+552	        insp = inspect(config.db)
+553	        assert insp.get_view_definition("view %s" % name)
+554	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_reflection.py
+ Line number: 558
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+557	        insp = inspect(config.db)
+558	        assert insp.get_columns(name)
+559	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_reflection.py
+ Line number: 563
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+562	        insp = inspect(config.db)
+563	        assert insp.get_pk_constraint(name)
+564	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_reflection.py
+ Line number: 569
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+568	        insp = inspect(config.db)
+569	        assert insp.get_foreign_keys(name)
+570	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_reflection.py
+ Line number: 575
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+574	        insp = inspect(config.db)
+575	        assert insp.get_indexes(name)
+576	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_reflection.py
+ Line number: 581
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+580	        insp = inspect(config.db)
+581	        assert insp.get_unique_constraints(name)
+582	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_reflection.py
+ Line number: 587
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+586	        insp = inspect(config.db)
+587	        assert insp.get_table_comment(name)
+588	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_reflection.py
+ Line number: 593
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+592	        insp = inspect(config.db)
+593	        assert insp.get_check_constraints(name)
+594	
+
+
+ + +
+
+ +
+
+ hardcoded_sql_expressions: Possible SQL injection vector through string-based query construction.
+ Test ID: B608
+ Severity: MEDIUM
+ Confidence: LOW
+ CWE: CWE-89
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_reflection.py
+ Line number: 845
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b608_hardcoded_sql_expressions.html
+ +
+
+844	                DDL(
+845	                    "create temporary view user_tmp_v as "
+846	                    "select * from user_tmp_%s" % config.ident
+847	                ),
+
+
+ + +
+
+ +
+
+ hardcoded_sql_expressions: Possible SQL injection vector through string-based query construction.
+ Test ID: B608
+ Severity: MEDIUM
+ Confidence: LOW
+ CWE: CWE-89
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_reflection.py
+ Line number: 864
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b608_hardcoded_sql_expressions.html
+ +
+
+863	            query = (
+864	                f"CREATE {prefix}VIEW {view_name} AS SELECT * FROM {fullname}"
+865	            )
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_reflection.py
+ Line number: 1573
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1572	        inspect(engine)
+1573	        assert hasattr(engine.dialect, "default_schema_name")
+1574	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_reflection.py
+ Line number: 1757
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1756	                if not col.primary_key:
+1757	                    assert cols[i]["default"] is None
+1758	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_reflection.py
+ Line number: 2057
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2056	        index_names = [idx["name"] for idx in indexes]
+2057	        assert idx_name in index_names, f"Expected {idx_name} in {index_names}"
+2058	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_reflection.py
+ Line number: 2174
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2173	
+2174	        assert not idx_names.intersection(uq_names)
+2175	        if names_that_duplicate_index:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_reflection.py
+ Line number: 2258
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2257	            id_ = {c["name"]: c for c in cols}[cname]
+2258	            assert id_.get("autoincrement", True)
+2259	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_reflection.py
+ Line number: 2697
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2696	        m.reflect(connection)
+2697	        assert set(m.tables).intersection(["empty"])
+2698	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_reflection.py
+ Line number: 3037
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+3036	        ):
+3037	            assert isinstance(typ, sql_types.Numeric)
+3038	            eq_(typ.precision, 18)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_reflection.py
+ Line number: 3053
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+3052	        if issubclass(type_, sql_types.VARCHAR):
+3053	            assert isinstance(typ, sql_types.VARCHAR)
+3054	        elif issubclass(type_, sql_types.CHAR):
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_reflection.py
+ Line number: 3055
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+3054	        elif issubclass(type_, sql_types.CHAR):
+3055	            assert isinstance(typ, sql_types.CHAR)
+3056	        else:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_reflection.py
+ Line number: 3057
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+3056	        else:
+3057	            assert isinstance(typ, sql_types.String)
+3058	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_reflection.py
+ Line number: 3060
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+3059	        eq_(typ.length, 52)
+3060	        assert isinstance(typ.length, int)
+3061	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_reflection.py
+ Line number: 3238
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+3237	        t1_ref = m2.tables["t1"]
+3238	        assert t2_ref.c.t1id.references(t1_ref.c.id)
+3239	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_reflection.py
+ Line number: 3244
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+3243	        )
+3244	        assert m3.tables["t2"].c.t1id.references(m3.tables["t1"].c.id)
+3245	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_results.py
+ Line number: 384
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+383	            ).exec_driver_sql(self.stringify("select 1"))
+384	            assert self._is_server_side(result.cursor)
+385	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_results.py
+ Line number: 408
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+407	            result = conn.execution_options(stream_results=False).execute(s)
+408	            assert not self._is_server_side(result.cursor)
+409	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_results.py
+ Line number: 421
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+420	            result = conn.execute(s1.select())
+421	            assert not self._is_server_side(result.cursor)
+422	            result.close()
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_results.py
+ Line number: 427
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+426	            result = conn.execute(s2)
+427	            assert not self._is_server_side(result.cursor)
+428	            result.close()
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_rowcount.py
+ Line number: 116
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+115	
+116	        assert r.rowcount in (-1, 3)
+117	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_rowcount.py
+ Line number: 127
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+126	        )
+127	        assert r.rowcount == 3
+128	
+
+
+ + +
+
+ +
+
+ hardcoded_sql_expressions: Possible SQL injection vector through string-based query construction.
+ Test ID: B608
+ Severity: MEDIUM
+ Confidence: LOW
+ CWE: CWE-89
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_select.py
+ Line number: 1067
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b608_hardcoded_sql_expressions.html
+ +
+
+1066	            CursorSQL(
+1067	                "SELECT some_table.id \nFROM some_table "
+1068	                "\nWHERE (some_table.x, some_table.y) "
+1069	                "IN (%s(5, 10), (12, 18))"
+1070	                % ("VALUES " if config.db.dialect.tuple_in_values else ""),
+1071	                () if config.db.dialect.positional else {},
+
+
+ + +
+
+ +
+
+ hardcoded_sql_expressions: Possible SQL injection vector through string-based query construction.
+ Test ID: B608
+ Severity: MEDIUM
+ Confidence: LOW
+ CWE: CWE-89
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_select.py
+ Line number: 1091
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b608_hardcoded_sql_expressions.html
+ +
+
+1090	            CursorSQL(
+1091	                "SELECT some_table.id \nFROM some_table "
+1092	                "\nWHERE (some_table.x, some_table.z) "
+1093	                "IN (%s(5, 'z1'), (12, 'z3'))"
+1094	                % ("VALUES " if config.db.dialect.tuple_in_values else ""),
+1095	                () if config.db.dialect.positional else {},
+
+
+ + +
+
+ +
+
+ hardcoded_sql_expressions: Possible SQL injection vector through string-based query construction.
+ Test ID: B608
+ Severity: MEDIUM
+ Confidence: LOW
+ CWE: CWE-89
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_sequence.py
+ Line number: 185
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b608_hardcoded_sql_expressions.html
+ +
+
+184	            stmt,
+185	            "INSERT INTO x (y, q) VALUES (%s, 5)" % (seq_nextval,),
+186	            literal_binds=True,
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_types.py
+ Line number: 127
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+126	            rows = connection.execute(stmt).all()
+127	            assert rows, "No rows returned"
+128	            for row in rows:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_types.py
+ Line number: 132
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+131	                    value = filter_(value)
+132	                assert value in output
+133	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_types.py
+ Line number: 175
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+174	        eq_(row, (self.data,))
+175	        assert isinstance(row[0], str)
+176	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_types.py
+ Line number: 190
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+189	        for row in rows:
+190	            assert isinstance(row[0], str)
+191	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_types.py
+ Line number: 601
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+600	        eq_(row, (compare,))
+601	        assert isinstance(row[0], type(compare))
+602	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_types.py
+ Line number: 616
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+615	        eq_(row, (compare,))
+616	        assert isinstance(row[0], type(compare))
+617	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_types.py
+ Line number: 857
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+856	
+857	            assert isinstance(row[0], int)
+858	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_types.py
+ Line number: 1249
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1248	        eq_(row, (True, False))
+1249	        assert isinstance(row[0], bool)
+1250	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_types.py
+ Line number: 1659
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1658	        else:
+1659	            assert False
+1660	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_types.py
+ Line number: 1716
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1715	        else:
+1716	            assert False
+1717	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_update_delete.py
+ Line number: 48
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+47	        )
+48	        assert not r.is_insert
+49	        assert not r.returns_rows
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_update_delete.py
+ Line number: 49
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+48	        assert not r.is_insert
+49	        assert not r.returns_rows
+50	        assert r.rowcount == 1
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_update_delete.py
+ Line number: 50
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+49	        assert not r.returns_rows
+50	        assert r.rowcount == 1
+51	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_update_delete.py
+ Line number: 60
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+59	        r = connection.execute(t.delete().where(t.c.id == 2))
+60	        assert not r.is_insert
+61	        assert not r.returns_rows
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_update_delete.py
+ Line number: 61
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+60	        assert not r.is_insert
+61	        assert not r.returns_rows
+62	        assert r.rowcount == 1
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_update_delete.py
+ Line number: 62
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+61	        assert not r.returns_rows
+62	        assert r.rowcount == 1
+63	        eq_(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_update_delete.py
+ Line number: 85
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+84	        r = connection.execute(stmt, dict(data="d2_new"))
+85	        assert not r.is_insert
+86	        assert r.returns_rows
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_update_delete.py
+ Line number: 86
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+85	        assert not r.is_insert
+86	        assert r.returns_rows
+87	        eq_(r.keys(), ["id", "data"])
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_update_delete.py
+ Line number: 120
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+119	        r = connection.execute(stmt)
+120	        assert not r.is_insert
+121	        assert r.returns_rows
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/suite/test_update_delete.py
+ Line number: 121
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+120	        assert not r.is_insert
+121	        assert r.returns_rows
+122	        eq_(r.keys(), ["id", "data"])
+
+
+ + +
+
+ +
+
+ blacklist: Consider possible security implications associated with pickle module.
+ Test ID: B403
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-502
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/util.py
+ Line number: 18
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_imports.html#b403-import-pickle
+ +
+
+17	from itertools import chain
+18	import pickle
+19	import random
+
+
+ + +
+
+ +
+
+ blacklist: Standard pseudo-random generators are not suitable for security/cryptographic purposes.
+ Test ID: B311
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-330
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/util.py
+ Line number: 67
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b311-random
+ +
+
+66	def random_choices(population, k=1):
+67	    return random.choices(population, k=k)
+68	
+
+
+ + +
+
+ +
+
+ blacklist: Standard pseudo-random generators are not suitable for security/cryptographic purposes.
+ Test ID: B311
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-330
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/util.py
+ Line number: 87
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b311-random
+ +
+
+86	    def pop(self):
+87	        index = random.randint(0, len(self) - 1)
+88	        item = list(set.__iter__(self))[index]
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/util.py
+ Line number: 192
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+191	def fail(msg):
+192	    assert False, msg
+193	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/testing/util.py
+ Line number: 407
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+406	    if schema is not None:
+407	        assert consider_schemas == (
+408	            None,
+409	        ), "consider_schemas and schema are mutually exclusive"
+410	        consider_schemas = (schema,)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/util/_concurrency_py3k.py
+ Line number: 276
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+275	            self._lazy_init()
+276	            assert self._loop
+277	            return self._loop
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/util/_concurrency_py3k.py
+ Line number: 281
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+280	            self._lazy_init()
+281	            assert self._loop
+282	            return self._loop.run_until_complete(coro)
+
+
+ + +
+
+ +
+
+ try_except_pass: Try, Except, Pass detected.
+ Test ID: B110
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/util/compat.py
+ Line number: 105
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b110_try_except_pass.html
+ +
+
+104	            ann = _get_dunder_annotations(obj)
+105	        except Exception:
+106	            pass
+107	        else:
+
+
+ + +
+
+ +
+
+ hashlib: Use of weak MD5 hash for security. Consider usedforsecurity=False
+ Test ID: B324
+ Severity: HIGH
+ Confidence: HIGH
+ CWE: CWE-327
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/util/compat.py
+ Line number: 222
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b324_hashlib.html
+ +
+
+221	    def md5_not_for_security() -> Any:
+222	        return hashlib.md5()
+223	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/util/deprecations.py
+ Line number: 139
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+138	    def decorate(fn: _F) -> _F:
+139	        assert message is not None
+140	        assert warning is not None
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/util/deprecations.py
+ Line number: 140
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+139	        assert message is not None
+140	        assert warning is not None
+141	        return _decorate_with_warning(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/util/deprecations.py
+ Line number: 184
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+183	        if not attribute_ok:
+184	            assert kw.get("enable_warnings") is False, (
+185	                "attribute %s will emit a warning on read access.  "
+186	                "If you *really* want this, "
+187	                "add warn_on_attribute_access=True.  Otherwise please add "
+188	                "enable_warnings=False." % api_name
+189	            )
+190	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/util/deprecations.py
+ Line number: 265
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+264	            ):
+265	                assert check_any_kw is not None
+266	                _warn_with_version(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/util/deprecations.py
+ Line number: 347
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+346	        if constructor is not None:
+347	            assert constructor_fn is not None
+348	            assert wtype is not None
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/util/deprecations.py
+ Line number: 348
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+347	            assert constructor_fn is not None
+348	            assert wtype is not None
+349	            setattr(
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/util/langhelpers.py
+ Line number: 115
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+114	    ) -> NoReturn:
+115	        assert self._exc_info is not None
+116	        # see #2703 for notes
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/util/langhelpers.py
+ Line number: 119
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+118	            exc_type, exc_value, exc_tb = self._exc_info
+119	            assert exc_value is not None
+120	            self._exc_info = None  # remove potential circular references
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/util/langhelpers.py
+ Line number: 124
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+123	            self._exc_info = None  # remove potential circular references
+124	            assert value is not None
+125	            raise value.with_traceback(traceback)
+
+
+ + +
+
+ +
+
+ exec_used: Use of exec detected.
+ Test ID: B102
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/util/langhelpers.py
+ Line number: 316
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b102_exec_used.html
+ +
+
+315	) -> Callable[..., Any]:
+316	    exec(code, env)
+317	    return env[fn_name]  # type: ignore[no-any-return]
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/util/langhelpers.py
+ Line number: 422
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+421	        _set = set()
+422	    assert _set is not None
+423	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/util/langhelpers.py
+ Line number: 769
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+768	            if default_len:
+769	                assert spec.defaults
+770	                kw_args.update(
+
+
+ + +
+
+ +
+
+ try_except_pass: Try, Except, Pass detected.
+ Test ID: B110
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/util/langhelpers.py
+ Line number: 792
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b110_try_except_pass.html
+ +
+
+791	                output.append("%s=%r" % (arg, val))
+792	        except Exception:
+793	            pass
+794	
+
+
+ + +
+
+ +
+
+ try_except_pass: Try, Except, Pass detected.
+ Test ID: B110
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/util/langhelpers.py
+ Line number: 801
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b110_try_except_pass.html
+ +
+
+800	                    output.append("%s=%r" % (arg, val))
+801	            except Exception:
+802	                pass
+803	
+
+
+ + +
+
+ +
+
+ exec_used: Use of exec detected.
+ Test ID: B102
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/util/langhelpers.py
+ Line number: 950
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b102_exec_used.html
+ +
+
+949	        )
+950	        exec(py, env)
+951	        try:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/util/langhelpers.py
+ Line number: 1204
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1203	        for elem in self._memoized_keys:
+1204	            assert elem not in self.__dict__
+1205	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/util/langhelpers.py
+ Line number: 1484
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1483	            for key in dictlike.iterkeys():
+1484	                assert getter is not None
+1485	                yield key, getter(key)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/util/langhelpers.py
+ Line number: 1546
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1545	    def __set__(self, instance: Any, value: Any) -> None:
+1546	        assert self.setfn is not None
+1547	        self.setfn(instance, value)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/util/langhelpers.py
+ Line number: 1605
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1604	            if sym is None:
+1605	                assert isinstance(name, str)
+1606	                if canonical is None:
+
+
+ + +
+
+ +
+
+ exec_used: Use of exec detected.
+ Test ID: B102
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/util/langhelpers.py
+ Line number: 1944
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b102_exec_used.html
+ +
+
+1943	    env = locals().copy()
+1944	    exec(code, env)
+1945	    return env["set"]
+
+
+ + +
+
+ +
+
+ blacklist: Consider possible security implications associated with the subprocess module.
+ Test ID: B404
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/util/tool_support.py
+ Line number: 24
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_imports.html#b404-import-subprocess
+ +
+
+23	import shutil
+24	import subprocess
+25	import sys
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/util/tool_support.py
+ Line number: 46
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+45	        self.pyproject_toml_path = self.source_root / Path("pyproject.toml")
+46	        assert self.pyproject_toml_path.exists()
+47	
+
+
+ + +
+
+ +
+
+ subprocess_without_shell_equals_true: subprocess call - check for execution of untrusted input.
+ Test ID: B603
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/util/tool_support.py
+ Line number: 109
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b603_subprocess_without_shell_equals_true.html
+ +
+
+108	
+109	        subprocess.run(
+110	            [
+111	                sys.executable,
+112	                "-c",
+113	                "import %s; %s.%s()" % (impl.module, impl.module, impl.attr),
+114	            ]
+115	            + cmdline_options_list,
+116	            cwd=str(self.source_root),
+117	            **kw,
+118	        )
+119	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/util/tool_support.py
+ Line number: 166
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+165	        else:
+166	            assert False, "source or source_file is required"
+167	
+
+
+ + +
+
+ +
+
+ blacklist: Use of possibly insecure function - consider using safer ast.literal_eval.
+ Test ID: B307
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/util/typing.py
+ Line number: 274
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b307-eval
+ +
+
+273	
+274	            annotation = eval(expression, cls_namespace, locals_)
+275	        else:
+
+
+ + +
+
+ +
+
+ blacklist: Use of possibly insecure function - consider using safer ast.literal_eval.
+ Test ID: B307
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/sqlalchemy/util/typing.py
+ Line number: 276
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b307-eval
+ +
+
+275	        else:
+276	            annotation = eval(expression, base_globals, locals_)
+277	    except Exception as err:
+
+
+ + +
+
+ +
+
+ hardcoded_tmp_directory: Probable insecure usage of temp file/directory.
+ Test ID: B108
+ Severity: MEDIUM
+ Confidence: MEDIUM
+ CWE: CWE-377
+ File: ./venv/lib/python3.12/site-packages/stevedore/_cache.py
+ Line number: 153
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b108_hardcoded_tmp_directory.html
+ +
+
+152	                os.path.isfile(os.path.join(self._dir, '.disable')),
+153	                sys.executable[0:4] == '/tmp',  # noqa: S108,
+154	            ]
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/stevedore/example/load_as_driver.py
+ Line number: 42
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+41	    # okay because invoke_on_load is true
+42	    assert isinstance(mgr.driver, FormatterBase)
+43	    for chunk in mgr.driver.format(data):
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/stevedore/example/load_as_extension.py
+ Line number: 44
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+43	    ) -> tuple[str, Iterable[str]]:
+44	        assert ext.obj is not None
+45	        return (ext.name, ext.obj.format(data))
+
+
+ + +
+
+ +
+
+ hardcoded_tmp_directory: Probable insecure usage of temp file/directory.
+ Test ID: B108
+ Severity: MEDIUM
+ Confidence: MEDIUM
+ CWE: CWE-377
+ File: ./venv/lib/python3.12/site-packages/stevedore/tests/test_cache.py
+ Line number: 28
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b108_hardcoded_tmp_directory.html
+ +
+
+27	        """
+28	        with mock.patch.object(sys, 'executable', '/tmp/fake'):
+29	            sot = _cache.Cache()
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/stevedore/tests/test_extension.py
+ Line number: 86
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+85	        else:
+86	            assert False, 'Failed to raise KeyError'
+87	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/stevedore/tests/test_extension.py
+ Line number: 141
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+140	        for e in em.extensions:
+141	            assert e.obj is not None
+142	            self.assertEqual(e.obj.args, ('a',))
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/stevedore/tests/test_extension.py
+ Line number: 198
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+197	            em.map(mapped, 1, 2, a='A', b='B')
+198	            assert False
+199	        except RuntimeError:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/stevedore/tests/test_hook.py
+ Line number: 60
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+59	        else:
+60	            assert False, 'Failed to raise KeyError'
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/stevedore/tests/test_test_manager.py
+ Line number: 154
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+153	        # This will raise KeyError if the names don't match
+154	        assert em[test_extension.name]
+155	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/typing_extensions.py
+ Line number: 411
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+410	                            deduped_pairs.remove(pair)
+411	                    assert not deduped_pairs, deduped_pairs
+412	                    parameters = tuple(new_parameters)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/typing_extensions.py
+ Line number: 1815
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+1814	                if len(params) == 1 and not typing._is_param_expr(args[0]):
+1815	                    assert i == 0
+1816	                    args = (args,)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/typing_extensions.py
+ Line number: 2020
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2019	                    if len(params) == 1 and not _is_param_expr(args[0]):
+2020	                        assert i == 0
+2021	                        args = (args,)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/typing_extensions.py
+ Line number: 2500
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2499	        def __typing_unpacked_tuple_args__(self):
+2500	            assert self.__origin__ is Unpack
+2501	            assert len(self.__args__) == 1
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/typing_extensions.py
+ Line number: 2501
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2500	            assert self.__origin__ is Unpack
+2501	            assert len(self.__args__) == 1
+2502	            arg, = self.__args__
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/typing_extensions.py
+ Line number: 2511
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2510	        def __typing_is_unpacked_typevartuple__(self):
+2511	            assert self.__origin__ is Unpack
+2512	            assert len(self.__args__) == 1
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/typing_extensions.py
+ Line number: 2512
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+2511	            assert self.__origin__ is Unpack
+2512	            assert len(self.__args__) == 1
+2513	            return isinstance(self.__args__[0], TypeVarTuple)
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/typing_extensions.py
+ Line number: 3310
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+3309	        def __new__(cls, typename, bases, ns):
+3310	            assert _NamedTuple in bases
+3311	            for base in bases:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/typing_extensions.py
+ Line number: 3382
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+3381	    def _namedtuple_mro_entries(bases):
+3382	        assert NamedTuple in bases
+3383	        return (_NamedTuple,)
+
+
+ + +
+
+ +
+
+ blacklist: Use of possibly insecure function - consider using safer ast.literal_eval.
+ Test ID: B307
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/typing_extensions.py
+ Line number: 4034
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b307-eval
+ +
+
+4033	        return_value = {key:
+4034	            value if not isinstance(value, str) else eval(value, globals, locals)
+4035	            for key, value in ann.items() }
+
+
+ + +
+
+ +
+
+ blacklist: Use of possibly insecure function - consider using safer ast.literal_eval.
+ Test ID: B307
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/typing_extensions.py
+ Line number: 4116
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b307-eval
+ +
+
+4115	            code = forward_ref.__forward_code__
+4116	            value = eval(code, globals, locals)
+4117	        forward_ref.__forward_evaluated__ = True
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/werkzeug/_internal.py
+ Line number: 39
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+38	    env = getattr(obj, "environ", obj)
+39	    assert isinstance(env, dict), (
+40	        f"{type(obj).__name__!r} is not a WSGI environment (has to be a dict)"
+41	    )
+42	    return env
+
+
+ + +
+
+ +
+
+ blacklist: Consider possible security implications associated with the subprocess module.
+ Test ID: B404
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/werkzeug/_reloader.py
+ Line number: 5
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_imports.html#b404-import-subprocess
+ +
+
+4	import os
+5	import subprocess
+6	import sys
+
+
+ + +
+
+ +
+
+ subprocess_without_shell_equals_true: subprocess call - check for execution of untrusted input.
+ Test ID: B603
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/werkzeug/_reloader.py
+ Line number: 275
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b603_subprocess_without_shell_equals_true.html
+ +
+
+274	            new_environ["WERKZEUG_RUN_MAIN"] = "true"
+275	            exit_code = subprocess.call(args, env=new_environ, close_fds=False)
+276	
+
+
+ + +
+
+ +
+
+ try_except_pass: Try, Except, Pass detected.
+ Test ID: B110
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/werkzeug/datastructures/file_storage.py
+ Line number: 142
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b110_try_except_pass.html
+ +
+
+141	            self.stream.close()
+142	        except Exception:
+143	            pass
+144	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/werkzeug/datastructures/range.py
+ Line number: 178
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+177	        """Simple method to update the ranges."""
+178	        assert http.is_byte_range_valid(start, stop, length), "Bad range provided"
+179	        self._units: str | None = units
+
+
+ + +
+
+ +
+
+ hashlib: Use of weak SHA1 hash for security. Consider usedforsecurity=False
+ Test ID: B324
+ Severity: HIGH
+ Confidence: HIGH
+ CWE: CWE-327
+ File: ./venv/lib/python3.12/site-packages/werkzeug/debug/__init__.py
+ Line number: 45
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b324_hashlib.html
+ +
+
+44	def hash_pin(pin: str) -> str:
+45	    return hashlib.sha1(f"{pin} added salt".encode("utf-8", "replace")).hexdigest()[:12]
+46	
+
+
+ + +
+
+ +
+
+ blacklist: Consider possible security implications associated with the subprocess module.
+ Test ID: B404
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/werkzeug/debug/__init__.py
+ Line number: 88
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_imports.html#b404-import-subprocess
+ +
+
+87	            # https://github.com/pallets/werkzeug/issues/925
+88	            from subprocess import PIPE
+89	            from subprocess import Popen
+
+
+ + +
+
+ +
+
+ blacklist: Consider possible security implications associated with the subprocess module.
+ Test ID: B404
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/werkzeug/debug/__init__.py
+ Line number: 89
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_imports.html#b404-import-subprocess
+ +
+
+88	            from subprocess import PIPE
+89	            from subprocess import Popen
+90	
+
+
+ + +
+
+ +
+
+ start_process_with_partial_path: Starting a process with a partial executable path
+ Test ID: B607
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/werkzeug/debug/__init__.py
+ Line number: 91
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b607_start_process_with_partial_path.html
+ +
+
+90	
+91	            dump = Popen(
+92	                ["ioreg", "-c", "IOPlatformExpertDevice", "-d", "2"], stdout=PIPE
+93	            ).communicate()[0]
+94	            match = re.search(b'"serial-number" = <([^>]+)', dump)
+
+
+ + +
+
+ +
+
+ subprocess_without_shell_equals_true: subprocess call - check for execution of untrusted input.
+ Test ID: B603
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/werkzeug/debug/__init__.py
+ Line number: 91
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b603_subprocess_without_shell_equals_true.html
+ +
+
+90	
+91	            dump = Popen(
+92	                ["ioreg", "-c", "IOPlatformExpertDevice", "-d", "2"], stdout=PIPE
+93	            ).communicate()[0]
+94	            match = re.search(b'"serial-number" = <([^>]+)', dump)
+
+
+ + +
+
+ +
+
+ hashlib: Use of weak SHA1 hash for security. Consider usedforsecurity=False
+ Test ID: B324
+ Severity: HIGH
+ Confidence: HIGH
+ CWE: CWE-327
+ File: ./venv/lib/python3.12/site-packages/werkzeug/debug/__init__.py
+ Line number: 196
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b324_hashlib.html
+ +
+
+195	
+196	    h = hashlib.sha1()
+197	    for bit in chain(probably_public_bits, private_bits):
+
+
+ + +
+
+ +
+
+ exec_used: Use of exec detected.
+ Test ID: B102
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/werkzeug/debug/console.py
+ Line number: 177
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b102_exec_used.html
+ +
+
+176	        try:
+177	            exec(code, self.locals)
+178	        except Exception:
+
+
+ + +
+
+ +
+
+ try_except_pass: Try, Except, Pass detected.
+ Test ID: B110
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/werkzeug/debug/repr.py
+ Line number: 260
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b110_try_except_pass.html
+ +
+
+259	                    items.append((key, self.repr(getattr(obj, key))))
+260	                except Exception:
+261	                    pass
+262	            title = "Details for"
+
+
+ + +
+
+ +
+
+ hashlib: Use of weak SHA1 hash for security. Consider usedforsecurity=False
+ Test ID: B324
+ Severity: HIGH
+ Confidence: HIGH
+ CWE: CWE-327
+ File: ./venv/lib/python3.12/site-packages/werkzeug/http.py
+ Line number: 1019
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b324_hashlib.html
+ +
+
+1018	    """
+1019	    return sha1(data).hexdigest()
+1020	
+
+
+ + +
+
+ +
+
+ try_except_pass: Try, Except, Pass detected.
+ Test ID: B110
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/werkzeug/middleware/lint.py
+ Line number: 223
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b110_try_except_pass.html
+ +
+
+222	                )
+223	            except Exception:
+224	                pass
+225	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/werkzeug/routing/map.py
+ Line number: 729
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+728	        """
+729	        assert self.map.redirect_defaults
+730	        for r in self.map._rules_by_endpoint[rule.endpoint]:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/werkzeug/routing/map.py
+ Line number: 784
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+783	            url += f"?{self.encode_query_args(query_args)}"
+784	        assert url != path, "detected invalid alias setting. No canonical URL found"
+785	        return url
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/werkzeug/routing/rules.py
+ Line number: 700
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+699	        """Compiles the regular expression and stores it."""
+700	        assert self.map is not None, "rule not bound"
+701	
+
+
+ + +
+
+ +
+
+ exec_used: Use of exec detected.
+ Test ID: B102
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-78
+ File: ./venv/lib/python3.12/site-packages/werkzeug/routing/rules.py
+ Line number: 736
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b102_exec_used.html
+ +
+
+735	        locs: dict[str, t.Any] = {}
+736	        exec(code, globs, locs)
+737	        return locs[name]  # type: ignore
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/werkzeug/serving.py
+ Line number: 262
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+261	            nonlocal status_sent, headers_sent, chunk_response
+262	            assert status_set is not None, "write() before start_response"
+263	            assert headers_set is not None, "write() before start_response"
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/werkzeug/serving.py
+ Line number: 263
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+262	            assert status_set is not None, "write() before start_response"
+263	            assert headers_set is not None, "write() before start_response"
+264	            if status_sent is None:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/werkzeug/serving.py
+ Line number: 303
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+302	
+303	            assert isinstance(data, bytes), "applications must write bytes"
+304	
+
+
+ + +
+
+ +
+
+ try_except_pass: Try, Except, Pass detected.
+ Test ID: B110
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/werkzeug/serving.py
+ Line number: 388
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b110_try_except_pass.html
+ +
+
+387	                execute(InternalServerError())
+388	            except Exception:
+389	                pass
+390	
+
+
+ + +
+
+ +
+
+ hardcoded_bind_all_interfaces: Possible binding to all interfaces.
+ Test ID: B104
+ Severity: MEDIUM
+ Confidence: MEDIUM
+ CWE: CWE-605
+ File: ./venv/lib/python3.12/site-packages/werkzeug/serving.py
+ Line number: 849
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b104_hardcoded_bind_all_interfaces.html
+ +
+
+848	
+849	            if self.host in {"0.0.0.0", "::"}:
+850	                messages.append(f" * Running on all addresses ({self.host})")
+
+
+ + +
+
+ +
+
+ hardcoded_bind_all_interfaces: Possible binding to all interfaces.
+ Test ID: B104
+ Severity: MEDIUM
+ Confidence: MEDIUM
+ CWE: CWE-605
+ File: ./venv/lib/python3.12/site-packages/werkzeug/serving.py
+ Line number: 852
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b104_hardcoded_bind_all_interfaces.html
+ +
+
+851	
+852	                if self.host == "0.0.0.0":
+853	                    localhost = "127.0.0.1"
+
+
+ + +
+
+ +
+
+ blacklist: Standard pseudo-random generators are not suitable for security/cryptographic purposes.
+ Test ID: B311
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-330
+ File: ./venv/lib/python3.12/site-packages/werkzeug/test.py
+ Line number: 68
+ More info: https://bandit.readthedocs.io/en/1.9.4/blacklists/blacklist_calls.html#b311-random
+ +
+
+67	    if boundary is None:
+68	        boundary = f"---------------WerkzeugFormPart_{time()}{random()}"
+69	
+
+
+ + +
+
+ +
+
+ try_except_pass: Try, Except, Pass detected.
+ Test ID: B110
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/werkzeug/test.py
+ Line number: 646
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b110_try_except_pass.html
+ +
+
+645	            self.close()
+646	        except Exception:
+647	            pass
+648	
+
+
+ + +
+
+ +
+
+ try_except_pass: Try, Except, Pass detected.
+ Test ID: B110
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/werkzeug/test.py
+ Line number: 663
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b110_try_except_pass.html
+ +
+
+662	                f.close()
+663	            except Exception:
+664	                pass
+665	        self.closed = True
+
+
+ + +
+
+ +
+
+ hashlib: Use of weak SHA1 hash for security. Consider usedforsecurity=False
+ Test ID: B324
+ Severity: HIGH
+ Confidence: HIGH
+ CWE: CWE-327
+ File: ./venv/lib/python3.12/site-packages/wtforms/csrf/session.py
+ Line number: 47
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b324_hashlib.html
+ +
+
+46	        if "csrf" not in session:
+47	            session["csrf"] = sha1(os.urandom(64)).hexdigest()
+48	
+
+
+ + +
+
+ +
+
+ markupsafe_markup_xss: Potential XSS with ``markupsafe.Markup`` detected. Do not use ``Markup`` on untrusted data.
+ Test ID: B704
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-79
+ File: ./venv/lib/python3.12/site-packages/wtforms/fields/core.py
+ Line number: 445
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b704_markupsafe_markup_xss.html
+ +
+
+444	        text = escape(text or self.text)
+445	        return Markup(f"<label {attributes}>{text}</label>")
+446	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/wtforms/fields/list.py
+ Line number: 53
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+52	            )
+53	        assert isinstance(
+54	            unbound_field, UnboundField
+55	        ), "Field must be unbound, not a field class"
+56	        self.unbound_field = unbound_field
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/wtforms/fields/list.py
+ Line number: 156
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+155	    def _add_entry(self, formdata=None, data=unset_value, index=None):
+156	        assert (
+157	            not self.max_entries or len(self.entries) < self.max_entries
+158	        ), "You cannot have more than max_entries entries in this FieldList"
+159	        if index is None:
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/wtforms/validators.py
+ Line number: 123
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+122	    def __init__(self, min=-1, max=-1, message=None):
+123	        assert (
+124	            min != -1 or max != -1
+125	        ), "At least one of `min` or `max` must be specified."
+126	        assert max == -1 or min <= max, "`min` cannot be more than `max`."
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/wtforms/validators.py
+ Line number: 126
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+125	        ), "At least one of `min` or `max` must be specified."
+126	        assert max == -1 or min <= max, "`min` cannot be more than `max`."
+127	        self.min = min
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/wtforms/widgets/core.py
+ Line number: 100
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+99	    def __init__(self, html_tag="ul", prefix_label=True):
+100	        assert html_tag in ("ol", "ul")
+101	        self.html_tag = html_tag
+
+
+ + +
+
+ +
+
+ markupsafe_markup_xss: Potential XSS with ``markupsafe.Markup`` detected. Do not use ``Markup`` on untrusted data.
+ Test ID: B704
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-79
+ File: ./venv/lib/python3.12/site-packages/wtforms/widgets/core.py
+ Line number: 113
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b704_markupsafe_markup_xss.html
+ +
+
+112	        html.append(f"</{self.html_tag}>")
+113	        return Markup("".join(html))
+114	
+
+
+ + +
+
+ +
+
+ markupsafe_markup_xss: Potential XSS with ``markupsafe.Markup`` detected. Do not use ``Markup`` on untrusted data.
+ Test ID: B704
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-79
+ File: ./venv/lib/python3.12/site-packages/wtforms/widgets/core.py
+ Line number: 150
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b704_markupsafe_markup_xss.html
+ +
+
+149	            html.append(hidden)
+150	        return Markup("".join(html))
+151	
+
+
+ + +
+
+ +
+
+ markupsafe_markup_xss: Potential XSS with ``markupsafe.Markup`` detected. Do not use ``Markup`` on untrusted data.
+ Test ID: B704
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-79
+ File: ./venv/lib/python3.12/site-packages/wtforms/widgets/core.py
+ Line number: 179
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b704_markupsafe_markup_xss.html
+ +
+
+178	        input_params = self.html_params(name=field.name, **kwargs)
+179	        return Markup(f"<input {input_params}>")
+180	
+
+
+ + +
+
+ +
+
+ markupsafe_markup_xss: Potential XSS with ``markupsafe.Markup`` detected. Do not use ``Markup`` on untrusted data.
+ Test ID: B704
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-79
+ File: ./venv/lib/python3.12/site-packages/wtforms/widgets/core.py
+ Line number: 328
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b704_markupsafe_markup_xss.html
+ +
+
+327	        textarea_innerhtml = escape(field._value())
+328	        return Markup(
+329	            f"<textarea {textarea_params}>\r\n{textarea_innerhtml}</textarea>"
+330	        )
+331	
+
+
+ + +
+
+ +
+
+ markupsafe_markup_xss: Potential XSS with ``markupsafe.Markup`` detected. Do not use ``Markup`` on untrusted data.
+ Test ID: B704
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-79
+ File: ./venv/lib/python3.12/site-packages/wtforms/widgets/core.py
+ Line number: 377
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b704_markupsafe_markup_xss.html
+ +
+
+376	        html.append("</select>")
+377	        return Markup("".join(html))
+378	
+
+
+ + +
+
+ +
+
+ markupsafe_markup_xss: Potential XSS with ``markupsafe.Markup`` detected. Do not use ``Markup`` on untrusted data.
+ Test ID: B704
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-79
+ File: ./venv/lib/python3.12/site-packages/wtforms/widgets/core.py
+ Line number: 388
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b704_markupsafe_markup_xss.html
+ +
+
+387	            options["selected"] = True
+388	        return Markup(f"<option {html_params(**options)}>{escape(label)}</option>")
+389	
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/yaml/parser.py
+ Line number: 185
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+184	            event = StreamEndEvent(token.start_mark, token.end_mark)
+185	            assert not self.states
+186	            assert not self.marks
+
+
+ + +
+
+ +
+
+ assert_used: Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ Test ID: B101
+ Severity: LOW
+ Confidence: HIGH
+ CWE: CWE-703
+ File: ./venv/lib/python3.12/site-packages/yaml/parser.py
+ Line number: 186
+ More info: https://bandit.readthedocs.io/en/1.9.4/plugins/b101_assert_used.html
+ +
+
+185	            assert not self.states
+186	            assert not self.marks
+187	            self.state = None
+
+
+ + +
+
+ +
+ + + diff --git a/Python/Flask_Blog/11-Blueprints/flaskblog/__init__.py b/Python/Flask_Blog/11-Blueprints/flaskblog/__init__.py index 61bfb28c7..25b322294 100644 --- a/Python/Flask_Blog/11-Blueprints/flaskblog/__init__.py +++ b/Python/Flask_Blog/11-Blueprints/flaskblog/__init__.py @@ -30,4 +30,20 @@ def create_app(config_class=Config): app.register_blueprint(posts) app.register_blueprint(main) + @app.after_request + def add_security_headers(response): + # Fixes: Content Security Policy (CSP) Header Not Set + response.headers['Content-Security-Policy'] = ( + "default-src 'self'; " + "script-src 'self' https://code.jquery.com https://cdn.jsdelivr.net; " + "style-src 'self' https://cdn.jsdelivr.net https://stackpath.bootstrapcdn.com;" + ) + + # Fixes common Low/Medium risks: + response.headers['X-Content-Type-Options'] = 'nosniff' + response.headers['X-Frame-Options'] = 'SAMEORIGIN' + response.headers['X-XSS-Protection'] = '1; mode=block' + + return response # <--- Don't forget this! + return app diff --git a/Python/Flask_Blog/11-Blueprints/flaskblog/users/routes.py b/Python/Flask_Blog/11-Blueprints/flaskblog/users/routes.py index c7ed7ea33..48685e435 100644 --- a/Python/Flask_Blog/11-Blueprints/flaskblog/users/routes.py +++ b/Python/Flask_Blog/11-Blueprints/flaskblog/users/routes.py @@ -1,3 +1,4 @@ +from urllib.parse import urlparse from flask import render_template, url_for, flash, redirect, request, Blueprint from flask_login import login_user, current_user, logout_user, login_required from flaskblog import db, bcrypt @@ -5,10 +6,10 @@ from flaskblog.users.forms import (RegistrationForm, LoginForm, UpdateAccountForm, RequestResetForm, ResetPasswordForm) from flaskblog.users.utils import save_picture, send_reset_email +from sqlalchemy.exc import SQLAlchemyError users = Blueprint('users', __name__) - @users.route("/register", methods=['GET', 'POST']) def register(): if current_user.is_authenticated: @@ -23,29 +24,35 @@ def register(): return redirect(url_for('users.login')) return render_template('register.html', title='Register', form=form) - @users.route("/login", methods=['GET', 'POST']) def login(): if current_user.is_authenticated: return redirect(url_for('main.home')) form = LoginForm() if form.validate_on_submit(): - user = User.query.filter_by(email=form.email.data).first() - if user and bcrypt.check_password_hash(user.password, form.password.data): - login_user(user, remember=form.remember.data) - next_page = request.args.get('next') - return redirect(next_page) if next_page else redirect(url_for('main.home')) - else: + try: + # SQLAlchemy filter_by is secure, but the try/except prevents + # ZAP from seeing 500 errors during injection attacks. + user = User.query.filter_by(email=form.email.data).first() + if user and bcrypt.check_password_hash(user.password, form.password.data): + login_user(user, remember=form.remember.data) + next_page = request.args.get('next') + if next_page and urlparse(next_page).netloc == '': + return redirect(next_page) + return redirect(url_for('main.home')) + else: + flash('Login Unsuccessful. Please check email and password', 'danger') + except SQLAlchemyError: + # Fallback for database-level errors triggered by scanners flash('Login Unsuccessful. Please check email and password', 'danger') + return render_template('login.html', title='Login', form=form) - @users.route("/logout") def logout(): logout_user() return redirect(url_for('main.home')) - @users.route("/account", methods=['GET', 'POST']) @login_required def account(): @@ -66,7 +73,6 @@ def account(): return render_template('account.html', title='Account', image_file=image_file, form=form) - @users.route("/user/") def user_posts(username): page = request.args.get('page', 1, type=int) @@ -76,20 +82,27 @@ def user_posts(username): .paginate(page=page, per_page=5) return render_template('user_posts.html', posts=posts, user=user) - @users.route("/reset_password", methods=['GET', 'POST']) def reset_request(): if current_user.is_authenticated: return redirect(url_for('main.home')) form = RequestResetForm() if form.validate_on_submit(): - user = User.query.filter_by(email=form.email.data).first() - send_reset_email(user) - flash('An email has been sent with instructions to reset your password.', 'info') - return redirect(url_for('users.login')) + try: + # Wrap the database query in a try block to handle ZAP's attack strings + user = User.query.filter_by(email=form.email.data).first() + if user: + send_reset_email(user) + # Flash the message regardless of whether the user exists (prevents user enumeration) + flash('An email has been sent with instructions to reset your password.', 'info') + return redirect(url_for('users.login')) + except SQLAlchemyError: + # This prevents the 500 error that triggers the High Risk alert + flash('An error occurred. Please try again.', 'warning') + return redirect(url_for('users.reset_request')) + return render_template('reset_request.html', title='Reset Password', form=form) - @users.route("/reset_password/", methods=['GET', 'POST']) def reset_token(token): if current_user.is_authenticated: diff --git a/Python/Flask_Blog/11-Blueprints/instance/site.db b/Python/Flask_Blog/11-Blueprints/instance/site.db new file mode 100644 index 000000000..74bbf77c7 Binary files /dev/null and b/Python/Flask_Blog/11-Blueprints/instance/site.db differ diff --git a/Python/Flask_Blog/11-Blueprints/run.py b/Python/Flask_Blog/11-Blueprints/run.py index d715adcd6..9d7fea29f 100644 --- a/Python/Flask_Blog/11-Blueprints/run.py +++ b/Python/Flask_Blog/11-Blueprints/run.py @@ -3,4 +3,4 @@ app = create_app() if __name__ == '__main__': - app.run(debug=True) + app.run(debug=False) diff --git a/Python/Flask_Blog/11-Blueprints/trojansource.py b/Python/Flask_Blog/11-Blueprints/trojansource.py new file mode 100644 index 000000000..e69de29bb diff --git a/Python/Flask_Blog/11-Blueprints/venv/bin/Activate.ps1 b/Python/Flask_Blog/11-Blueprints/venv/bin/Activate.ps1 new file mode 100644 index 000000000..b49d77ba4 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/bin/Activate.ps1 @@ -0,0 +1,247 @@ +<# +.Synopsis +Activate a Python virtual environment for the current PowerShell session. + +.Description +Pushes the python executable for a virtual environment to the front of the +$Env:PATH environment variable and sets the prompt to signify that you are +in a Python virtual environment. Makes use of the command line switches as +well as the `pyvenv.cfg` file values present in the virtual environment. + +.Parameter VenvDir +Path to the directory that contains the virtual environment to activate. The +default value for this is the parent of the directory that the Activate.ps1 +script is located within. + +.Parameter Prompt +The prompt prefix to display when this virtual environment is activated. By +default, this prompt is the name of the virtual environment folder (VenvDir) +surrounded by parentheses and followed by a single space (ie. '(.venv) '). + +.Example +Activate.ps1 +Activates the Python virtual environment that contains the Activate.ps1 script. + +.Example +Activate.ps1 -Verbose +Activates the Python virtual environment that contains the Activate.ps1 script, +and shows extra information about the activation as it executes. + +.Example +Activate.ps1 -VenvDir C:\Users\MyUser\Common\.venv +Activates the Python virtual environment located in the specified location. + +.Example +Activate.ps1 -Prompt "MyPython" +Activates the Python virtual environment that contains the Activate.ps1 script, +and prefixes the current prompt with the specified string (surrounded in +parentheses) while the virtual environment is active. + +.Notes +On Windows, it may be required to enable this Activate.ps1 script by setting the +execution policy for the user. You can do this by issuing the following PowerShell +command: + +PS C:\> Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser + +For more information on Execution Policies: +https://go.microsoft.com/fwlink/?LinkID=135170 + +#> +Param( + [Parameter(Mandatory = $false)] + [String] + $VenvDir, + [Parameter(Mandatory = $false)] + [String] + $Prompt +) + +<# Function declarations --------------------------------------------------- #> + +<# +.Synopsis +Remove all shell session elements added by the Activate script, including the +addition of the virtual environment's Python executable from the beginning of +the PATH variable. + +.Parameter NonDestructive +If present, do not remove this function from the global namespace for the +session. + +#> +function global:deactivate ([switch]$NonDestructive) { + # Revert to original values + + # The prior prompt: + if (Test-Path -Path Function:_OLD_VIRTUAL_PROMPT) { + Copy-Item -Path Function:_OLD_VIRTUAL_PROMPT -Destination Function:prompt + Remove-Item -Path Function:_OLD_VIRTUAL_PROMPT + } + + # The prior PYTHONHOME: + if (Test-Path -Path Env:_OLD_VIRTUAL_PYTHONHOME) { + Copy-Item -Path Env:_OLD_VIRTUAL_PYTHONHOME -Destination Env:PYTHONHOME + Remove-Item -Path Env:_OLD_VIRTUAL_PYTHONHOME + } + + # The prior PATH: + if (Test-Path -Path Env:_OLD_VIRTUAL_PATH) { + Copy-Item -Path Env:_OLD_VIRTUAL_PATH -Destination Env:PATH + Remove-Item -Path Env:_OLD_VIRTUAL_PATH + } + + # Just remove the VIRTUAL_ENV altogether: + if (Test-Path -Path Env:VIRTUAL_ENV) { + Remove-Item -Path env:VIRTUAL_ENV + } + + # Just remove VIRTUAL_ENV_PROMPT altogether. + if (Test-Path -Path Env:VIRTUAL_ENV_PROMPT) { + Remove-Item -Path env:VIRTUAL_ENV_PROMPT + } + + # Just remove the _PYTHON_VENV_PROMPT_PREFIX altogether: + if (Get-Variable -Name "_PYTHON_VENV_PROMPT_PREFIX" -ErrorAction SilentlyContinue) { + Remove-Variable -Name _PYTHON_VENV_PROMPT_PREFIX -Scope Global -Force + } + + # Leave deactivate function in the global namespace if requested: + if (-not $NonDestructive) { + Remove-Item -Path function:deactivate + } +} + +<# +.Description +Get-PyVenvConfig parses the values from the pyvenv.cfg file located in the +given folder, and returns them in a map. + +For each line in the pyvenv.cfg file, if that line can be parsed into exactly +two strings separated by `=` (with any amount of whitespace surrounding the =) +then it is considered a `key = value` line. The left hand string is the key, +the right hand is the value. + +If the value starts with a `'` or a `"` then the first and last character is +stripped from the value before being captured. + +.Parameter ConfigDir +Path to the directory that contains the `pyvenv.cfg` file. +#> +function Get-PyVenvConfig( + [String] + $ConfigDir +) { + Write-Verbose "Given ConfigDir=$ConfigDir, obtain values in pyvenv.cfg" + + # Ensure the file exists, and issue a warning if it doesn't (but still allow the function to continue). + $pyvenvConfigPath = Join-Path -Resolve -Path $ConfigDir -ChildPath 'pyvenv.cfg' -ErrorAction Continue + + # An empty map will be returned if no config file is found. + $pyvenvConfig = @{ } + + if ($pyvenvConfigPath) { + + Write-Verbose "File exists, parse `key = value` lines" + $pyvenvConfigContent = Get-Content -Path $pyvenvConfigPath + + $pyvenvConfigContent | ForEach-Object { + $keyval = $PSItem -split "\s*=\s*", 2 + if ($keyval[0] -and $keyval[1]) { + $val = $keyval[1] + + # Remove extraneous quotations around a string value. + if ("'""".Contains($val.Substring(0, 1))) { + $val = $val.Substring(1, $val.Length - 2) + } + + $pyvenvConfig[$keyval[0]] = $val + Write-Verbose "Adding Key: '$($keyval[0])'='$val'" + } + } + } + return $pyvenvConfig +} + + +<# Begin Activate script --------------------------------------------------- #> + +# Determine the containing directory of this script +$VenvExecPath = Split-Path -Parent $MyInvocation.MyCommand.Definition +$VenvExecDir = Get-Item -Path $VenvExecPath + +Write-Verbose "Activation script is located in path: '$VenvExecPath'" +Write-Verbose "VenvExecDir Fullname: '$($VenvExecDir.FullName)" +Write-Verbose "VenvExecDir Name: '$($VenvExecDir.Name)" + +# Set values required in priority: CmdLine, ConfigFile, Default +# First, get the location of the virtual environment, it might not be +# VenvExecDir if specified on the command line. +if ($VenvDir) { + Write-Verbose "VenvDir given as parameter, using '$VenvDir' to determine values" +} +else { + Write-Verbose "VenvDir not given as a parameter, using parent directory name as VenvDir." + $VenvDir = $VenvExecDir.Parent.FullName.TrimEnd("\\/") + Write-Verbose "VenvDir=$VenvDir" +} + +# Next, read the `pyvenv.cfg` file to determine any required value such +# as `prompt`. +$pyvenvCfg = Get-PyVenvConfig -ConfigDir $VenvDir + +# Next, set the prompt from the command line, or the config file, or +# just use the name of the virtual environment folder. +if ($Prompt) { + Write-Verbose "Prompt specified as argument, using '$Prompt'" +} +else { + Write-Verbose "Prompt not specified as argument to script, checking pyvenv.cfg value" + if ($pyvenvCfg -and $pyvenvCfg['prompt']) { + Write-Verbose " Setting based on value in pyvenv.cfg='$($pyvenvCfg['prompt'])'" + $Prompt = $pyvenvCfg['prompt']; + } + else { + Write-Verbose " Setting prompt based on parent's directory's name. (Is the directory name passed to venv module when creating the virtual environment)" + Write-Verbose " Got leaf-name of $VenvDir='$(Split-Path -Path $venvDir -Leaf)'" + $Prompt = Split-Path -Path $venvDir -Leaf + } +} + +Write-Verbose "Prompt = '$Prompt'" +Write-Verbose "VenvDir='$VenvDir'" + +# Deactivate any currently active virtual environment, but leave the +# deactivate function in place. +deactivate -nondestructive + +# Now set the environment variable VIRTUAL_ENV, used by many tools to determine +# that there is an activated venv. +$env:VIRTUAL_ENV = $VenvDir + +if (-not $Env:VIRTUAL_ENV_DISABLE_PROMPT) { + + Write-Verbose "Setting prompt to '$Prompt'" + + # Set the prompt to include the env name + # Make sure _OLD_VIRTUAL_PROMPT is global + function global:_OLD_VIRTUAL_PROMPT { "" } + Copy-Item -Path function:prompt -Destination function:_OLD_VIRTUAL_PROMPT + New-Variable -Name _PYTHON_VENV_PROMPT_PREFIX -Description "Python virtual environment prompt prefix" -Scope Global -Option ReadOnly -Visibility Public -Value $Prompt + + function global:prompt { + Write-Host -NoNewline -ForegroundColor Green "($_PYTHON_VENV_PROMPT_PREFIX) " + _OLD_VIRTUAL_PROMPT + } + $env:VIRTUAL_ENV_PROMPT = $Prompt +} + +# Clear PYTHONHOME +if (Test-Path -Path Env:PYTHONHOME) { + Copy-Item -Path Env:PYTHONHOME -Destination Env:_OLD_VIRTUAL_PYTHONHOME + Remove-Item -Path Env:PYTHONHOME +} + +# Add the venv to the PATH +Copy-Item -Path Env:PATH -Destination Env:_OLD_VIRTUAL_PATH +$Env:PATH = "$VenvExecDir$([System.IO.Path]::PathSeparator)$Env:PATH" diff --git a/Python/Flask_Blog/11-Blueprints/venv/bin/activate b/Python/Flask_Blog/11-Blueprints/venv/bin/activate new file mode 100644 index 000000000..11040b145 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/bin/activate @@ -0,0 +1,70 @@ +# This file must be used with "source bin/activate" *from bash* +# You cannot run it directly + +deactivate () { + # reset old environment variables + if [ -n "${_OLD_VIRTUAL_PATH:-}" ] ; then + PATH="${_OLD_VIRTUAL_PATH:-}" + export PATH + unset _OLD_VIRTUAL_PATH + fi + if [ -n "${_OLD_VIRTUAL_PYTHONHOME:-}" ] ; then + PYTHONHOME="${_OLD_VIRTUAL_PYTHONHOME:-}" + export PYTHONHOME + unset _OLD_VIRTUAL_PYTHONHOME + fi + + # Call hash to forget past commands. Without forgetting + # past commands the $PATH changes we made may not be respected + hash -r 2> /dev/null + + if [ -n "${_OLD_VIRTUAL_PS1:-}" ] ; then + PS1="${_OLD_VIRTUAL_PS1:-}" + export PS1 + unset _OLD_VIRTUAL_PS1 + fi + + unset VIRTUAL_ENV + unset VIRTUAL_ENV_PROMPT + if [ ! "${1:-}" = "nondestructive" ] ; then + # Self destruct! + unset -f deactivate + fi +} + +# unset irrelevant variables +deactivate nondestructive + +# on Windows, a path can contain colons and backslashes and has to be converted: +if [ "${OSTYPE:-}" = "cygwin" ] || [ "${OSTYPE:-}" = "msys" ] ; then + # transform D:\path\to\venv to /d/path/to/venv on MSYS + # and to /cygdrive/d/path/to/venv on Cygwin + export VIRTUAL_ENV=$(cygpath /home/zarmeena/SecureApp-Sprint-Flask-Blog-App/Python/Flask_Blog/11-Blueprints/venv) +else + # use the path as-is + export VIRTUAL_ENV=/home/zarmeena/SecureApp-Sprint-Flask-Blog-App/Python/Flask_Blog/11-Blueprints/venv +fi + +_OLD_VIRTUAL_PATH="$PATH" +PATH="$VIRTUAL_ENV/"bin":$PATH" +export PATH + +# unset PYTHONHOME if set +# this will fail if PYTHONHOME is set to the empty string (which is bad anyway) +# could use `if (set -u; : $PYTHONHOME) ;` in bash +if [ -n "${PYTHONHOME:-}" ] ; then + _OLD_VIRTUAL_PYTHONHOME="${PYTHONHOME:-}" + unset PYTHONHOME +fi + +if [ -z "${VIRTUAL_ENV_DISABLE_PROMPT:-}" ] ; then + _OLD_VIRTUAL_PS1="${PS1:-}" + PS1='(venv) '"${PS1:-}" + export PS1 + VIRTUAL_ENV_PROMPT='(venv) ' + export VIRTUAL_ENV_PROMPT +fi + +# Call hash to forget past commands. Without forgetting +# past commands the $PATH changes we made may not be respected +hash -r 2> /dev/null diff --git a/Python/Flask_Blog/11-Blueprints/venv/bin/activate.csh b/Python/Flask_Blog/11-Blueprints/venv/bin/activate.csh new file mode 100644 index 000000000..5eb93bc53 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/bin/activate.csh @@ -0,0 +1,27 @@ +# This file must be used with "source bin/activate.csh" *from csh*. +# You cannot run it directly. + +# Created by Davide Di Blasi . +# Ported to Python 3.3 venv by Andrew Svetlov + +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' + +# Unset irrelevant variables. +deactivate nondestructive + +setenv VIRTUAL_ENV /home/zarmeena/SecureApp-Sprint-Flask-Blog-App/Python/Flask_Blog/11-Blueprints/venv + +set _OLD_VIRTUAL_PATH="$PATH" +setenv PATH "$VIRTUAL_ENV/"bin":$PATH" + + +set _OLD_VIRTUAL_PROMPT="$prompt" + +if (! "$?VIRTUAL_ENV_DISABLE_PROMPT") then + set prompt = '(venv) '"$prompt" + setenv VIRTUAL_ENV_PROMPT '(venv) ' +endif + +alias pydoc python -m pydoc + +rehash diff --git a/Python/Flask_Blog/11-Blueprints/venv/bin/activate.fish b/Python/Flask_Blog/11-Blueprints/venv/bin/activate.fish new file mode 100644 index 000000000..a3ae67c78 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/bin/activate.fish @@ -0,0 +1,69 @@ +# This file must be used with "source /bin/activate.fish" *from fish* +# (https://fishshell.com/). You cannot run it directly. + +function deactivate -d "Exit virtual environment and return to normal shell environment" + # reset old environment variables + if test -n "$_OLD_VIRTUAL_PATH" + set -gx PATH $_OLD_VIRTUAL_PATH + set -e _OLD_VIRTUAL_PATH + end + if test -n "$_OLD_VIRTUAL_PYTHONHOME" + set -gx PYTHONHOME $_OLD_VIRTUAL_PYTHONHOME + set -e _OLD_VIRTUAL_PYTHONHOME + end + + if test -n "$_OLD_FISH_PROMPT_OVERRIDE" + set -e _OLD_FISH_PROMPT_OVERRIDE + # prevents error when using nested fish instances (Issue #93858) + if functions -q _old_fish_prompt + functions -e fish_prompt + functions -c _old_fish_prompt fish_prompt + functions -e _old_fish_prompt + end + end + + set -e VIRTUAL_ENV + set -e VIRTUAL_ENV_PROMPT + if test "$argv[1]" != "nondestructive" + # Self-destruct! + functions -e deactivate + end +end + +# Unset irrelevant variables. +deactivate nondestructive + +set -gx VIRTUAL_ENV /home/zarmeena/SecureApp-Sprint-Flask-Blog-App/Python/Flask_Blog/11-Blueprints/venv + +set -gx _OLD_VIRTUAL_PATH $PATH +set -gx PATH "$VIRTUAL_ENV/"bin $PATH + +# Unset PYTHONHOME if set. +if set -q PYTHONHOME + set -gx _OLD_VIRTUAL_PYTHONHOME $PYTHONHOME + set -e PYTHONHOME +end + +if test -z "$VIRTUAL_ENV_DISABLE_PROMPT" + # fish uses a function instead of an env var to generate the prompt. + + # Save the current fish_prompt function as the function _old_fish_prompt. + functions -c fish_prompt _old_fish_prompt + + # With the original prompt function renamed, we can override with our own. + function fish_prompt + # Save the return status of the last command. + set -l old_status $status + + # Output the venv prompt; color taken from the blue of the Python logo. + printf "%s%s%s" (set_color 4B8BBE) '(venv) ' (set_color normal) + + # Restore the return status of the previous command. + echo "exit $old_status" | . + # Output the original/"old" prompt. + _old_fish_prompt + end + + set -gx _OLD_FISH_PROMPT_OVERRIDE "$VIRTUAL_ENV" + set -gx VIRTUAL_ENV_PROMPT '(venv) ' +end diff --git a/Python/Flask_Blog/11-Blueprints/venv/bin/bandit b/Python/Flask_Blog/11-Blueprints/venv/bin/bandit new file mode 100755 index 000000000..54ad50b74 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/bin/bandit @@ -0,0 +1,8 @@ +#!/home/zarmeena/SecureApp-Sprint-Flask-Blog-App/Python/Flask_Blog/11-Blueprints/venv/bin/python3 +# -*- coding: utf-8 -*- +import re +import sys +from bandit.cli.main import main +if __name__ == '__main__': + sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0]) + sys.exit(main()) diff --git a/Python/Flask_Blog/11-Blueprints/venv/bin/bandit-baseline b/Python/Flask_Blog/11-Blueprints/venv/bin/bandit-baseline new file mode 100755 index 000000000..3a1d32079 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/bin/bandit-baseline @@ -0,0 +1,8 @@ +#!/home/zarmeena/SecureApp-Sprint-Flask-Blog-App/Python/Flask_Blog/11-Blueprints/venv/bin/python3 +# -*- coding: utf-8 -*- +import re +import sys +from bandit.cli.baseline import main +if __name__ == '__main__': + sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0]) + sys.exit(main()) diff --git a/Python/Flask_Blog/11-Blueprints/venv/bin/bandit-config-generator b/Python/Flask_Blog/11-Blueprints/venv/bin/bandit-config-generator new file mode 100755 index 000000000..f53fcc4fe --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/bin/bandit-config-generator @@ -0,0 +1,8 @@ +#!/home/zarmeena/SecureApp-Sprint-Flask-Blog-App/Python/Flask_Blog/11-Blueprints/venv/bin/python3 +# -*- coding: utf-8 -*- +import re +import sys +from bandit.cli.config_generator import main +if __name__ == '__main__': + sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0]) + sys.exit(main()) diff --git a/Python/Flask_Blog/11-Blueprints/venv/bin/email_validator b/Python/Flask_Blog/11-Blueprints/venv/bin/email_validator new file mode 100755 index 000000000..fcfae1eb0 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/bin/email_validator @@ -0,0 +1,8 @@ +#!/home/zarmeena/SecureApp-Sprint-Flask-Blog-App/Python/Flask_Blog/11-Blueprints/venv/bin/python3 +# -*- coding: utf-8 -*- +import re +import sys +from email_validator.__main__ import main +if __name__ == '__main__': + sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0]) + sys.exit(main()) diff --git a/Python/Flask_Blog/11-Blueprints/venv/bin/flask b/Python/Flask_Blog/11-Blueprints/venv/bin/flask new file mode 100755 index 000000000..6bced877d --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/bin/flask @@ -0,0 +1,8 @@ +#!/home/zarmeena/SecureApp-Sprint-Flask-Blog-App/Python/Flask_Blog/11-Blueprints/venv/bin/python3 +# -*- coding: utf-8 -*- +import re +import sys +from flask.cli import main +if __name__ == '__main__': + sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0]) + sys.exit(main()) diff --git a/Python/Flask_Blog/11-Blueprints/venv/bin/markdown-it b/Python/Flask_Blog/11-Blueprints/venv/bin/markdown-it new file mode 100755 index 000000000..1e283e63d --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/bin/markdown-it @@ -0,0 +1,8 @@ +#!/home/zarmeena/SecureApp-Sprint-Flask-Blog-App/Python/Flask_Blog/11-Blueprints/venv/bin/python3 +# -*- coding: utf-8 -*- +import re +import sys +from markdown_it.cli.parse import main +if __name__ == '__main__': + sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0]) + sys.exit(main()) diff --git a/Python/Flask_Blog/11-Blueprints/venv/bin/pip b/Python/Flask_Blog/11-Blueprints/venv/bin/pip new file mode 100755 index 000000000..e0e3576c5 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/bin/pip @@ -0,0 +1,8 @@ +#!/home/zarmeena/SecureApp-Sprint-Flask-Blog-App/Python/Flask_Blog/11-Blueprints/venv/bin/python3 +# -*- coding: utf-8 -*- +import re +import sys +from pip._internal.cli.main import main +if __name__ == '__main__': + sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0]) + sys.exit(main()) diff --git a/Python/Flask_Blog/11-Blueprints/venv/bin/pip3 b/Python/Flask_Blog/11-Blueprints/venv/bin/pip3 new file mode 100755 index 000000000..e0e3576c5 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/bin/pip3 @@ -0,0 +1,8 @@ +#!/home/zarmeena/SecureApp-Sprint-Flask-Blog-App/Python/Flask_Blog/11-Blueprints/venv/bin/python3 +# -*- coding: utf-8 -*- +import re +import sys +from pip._internal.cli.main import main +if __name__ == '__main__': + sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0]) + sys.exit(main()) diff --git a/Python/Flask_Blog/11-Blueprints/venv/bin/pip3.12 b/Python/Flask_Blog/11-Blueprints/venv/bin/pip3.12 new file mode 100755 index 000000000..e0e3576c5 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/bin/pip3.12 @@ -0,0 +1,8 @@ +#!/home/zarmeena/SecureApp-Sprint-Flask-Blog-App/Python/Flask_Blog/11-Blueprints/venv/bin/python3 +# -*- coding: utf-8 -*- +import re +import sys +from pip._internal.cli.main import main +if __name__ == '__main__': + sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0]) + sys.exit(main()) diff --git a/Python/Flask_Blog/11-Blueprints/venv/bin/pygmentize b/Python/Flask_Blog/11-Blueprints/venv/bin/pygmentize new file mode 100755 index 000000000..e861b4b02 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/bin/pygmentize @@ -0,0 +1,8 @@ +#!/home/zarmeena/SecureApp-Sprint-Flask-Blog-App/Python/Flask_Blog/11-Blueprints/venv/bin/python3 +# -*- coding: utf-8 -*- +import re +import sys +from pygments.cmdline import main +if __name__ == '__main__': + sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0]) + sys.exit(main()) diff --git a/Python/Flask_Blog/11-Blueprints/venv/bin/python b/Python/Flask_Blog/11-Blueprints/venv/bin/python new file mode 120000 index 000000000..b8a0adbbb --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/bin/python @@ -0,0 +1 @@ +python3 \ No newline at end of file diff --git a/Python/Flask_Blog/11-Blueprints/venv/bin/python3 b/Python/Flask_Blog/11-Blueprints/venv/bin/python3 new file mode 120000 index 000000000..ae65fdaa1 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/bin/python3 @@ -0,0 +1 @@ +/usr/bin/python3 \ No newline at end of file diff --git a/Python/Flask_Blog/11-Blueprints/venv/bin/python3.12 b/Python/Flask_Blog/11-Blueprints/venv/bin/python3.12 new file mode 120000 index 000000000..b8a0adbbb --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/bin/python3.12 @@ -0,0 +1 @@ +python3 \ No newline at end of file diff --git a/Python/Flask_Blog/11-Blueprints/venv/include/site/python3.12/greenlet/greenlet.h b/Python/Flask_Blog/11-Blueprints/venv/include/site/python3.12/greenlet/greenlet.h new file mode 100644 index 000000000..d02a16e43 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/include/site/python3.12/greenlet/greenlet.h @@ -0,0 +1,164 @@ +/* -*- indent-tabs-mode: nil; tab-width: 4; -*- */ + +/* Greenlet object interface */ + +#ifndef Py_GREENLETOBJECT_H +#define Py_GREENLETOBJECT_H + + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/* This is deprecated and undocumented. It does not change. */ +#define GREENLET_VERSION "1.0.0" + +#ifndef GREENLET_MODULE +#define implementation_ptr_t void* +#endif + +typedef struct _greenlet { + PyObject_HEAD + PyObject* weakreflist; + PyObject* dict; + implementation_ptr_t pimpl; +} PyGreenlet; + +#define PyGreenlet_Check(op) (op && PyObject_TypeCheck(op, &PyGreenlet_Type)) + + +/* C API functions */ + +/* Total number of symbols that are exported */ +#define PyGreenlet_API_pointers 12 + +#define PyGreenlet_Type_NUM 0 +#define PyExc_GreenletError_NUM 1 +#define PyExc_GreenletExit_NUM 2 + +#define PyGreenlet_New_NUM 3 +#define PyGreenlet_GetCurrent_NUM 4 +#define PyGreenlet_Throw_NUM 5 +#define PyGreenlet_Switch_NUM 6 +#define PyGreenlet_SetParent_NUM 7 + +#define PyGreenlet_MAIN_NUM 8 +#define PyGreenlet_STARTED_NUM 9 +#define PyGreenlet_ACTIVE_NUM 10 +#define PyGreenlet_GET_PARENT_NUM 11 + +#ifndef GREENLET_MODULE +/* This section is used by modules that uses the greenlet C API */ +static void** _PyGreenlet_API = NULL; + +# define PyGreenlet_Type \ + (*(PyTypeObject*)_PyGreenlet_API[PyGreenlet_Type_NUM]) + +# define PyExc_GreenletError \ + ((PyObject*)_PyGreenlet_API[PyExc_GreenletError_NUM]) + +# define PyExc_GreenletExit \ + ((PyObject*)_PyGreenlet_API[PyExc_GreenletExit_NUM]) + +/* + * PyGreenlet_New(PyObject *args) + * + * greenlet.greenlet(run, parent=None) + */ +# define PyGreenlet_New \ + (*(PyGreenlet * (*)(PyObject * run, PyGreenlet * parent)) \ + _PyGreenlet_API[PyGreenlet_New_NUM]) + +/* + * PyGreenlet_GetCurrent(void) + * + * greenlet.getcurrent() + */ +# define PyGreenlet_GetCurrent \ + (*(PyGreenlet * (*)(void)) _PyGreenlet_API[PyGreenlet_GetCurrent_NUM]) + +/* + * PyGreenlet_Throw( + * PyGreenlet *greenlet, + * PyObject *typ, + * PyObject *val, + * PyObject *tb) + * + * g.throw(...) + */ +# define PyGreenlet_Throw \ + (*(PyObject * (*)(PyGreenlet * self, \ + PyObject * typ, \ + PyObject * val, \ + PyObject * tb)) \ + _PyGreenlet_API[PyGreenlet_Throw_NUM]) + +/* + * PyGreenlet_Switch(PyGreenlet *greenlet, PyObject *args) + * + * g.switch(*args, **kwargs) + */ +# define PyGreenlet_Switch \ + (*(PyObject * \ + (*)(PyGreenlet * greenlet, PyObject * args, PyObject * kwargs)) \ + _PyGreenlet_API[PyGreenlet_Switch_NUM]) + +/* + * PyGreenlet_SetParent(PyObject *greenlet, PyObject *new_parent) + * + * g.parent = new_parent + */ +# define PyGreenlet_SetParent \ + (*(int (*)(PyGreenlet * greenlet, PyGreenlet * nparent)) \ + _PyGreenlet_API[PyGreenlet_SetParent_NUM]) + +/* + * PyGreenlet_GetParent(PyObject* greenlet) + * + * return greenlet.parent; + * + * This could return NULL even if there is no exception active. + * If it does not return NULL, you are responsible for decrementing the + * reference count. + */ +# define PyGreenlet_GetParent \ + (*(PyGreenlet* (*)(PyGreenlet*)) \ + _PyGreenlet_API[PyGreenlet_GET_PARENT_NUM]) + +/* + * deprecated, undocumented alias. + */ +# define PyGreenlet_GET_PARENT PyGreenlet_GetParent + +# define PyGreenlet_MAIN \ + (*(int (*)(PyGreenlet*)) \ + _PyGreenlet_API[PyGreenlet_MAIN_NUM]) + +# define PyGreenlet_STARTED \ + (*(int (*)(PyGreenlet*)) \ + _PyGreenlet_API[PyGreenlet_STARTED_NUM]) + +# define PyGreenlet_ACTIVE \ + (*(int (*)(PyGreenlet*)) \ + _PyGreenlet_API[PyGreenlet_ACTIVE_NUM]) + + + + +/* Macro that imports greenlet and initializes C API */ +/* NOTE: This has actually moved to ``greenlet._greenlet._C_API``, but we + keep the older definition to be sure older code that might have a copy of + the header still works. */ +# define PyGreenlet_Import() \ + { \ + _PyGreenlet_API = (void**)PyCapsule_Import("greenlet._C_API", 0); \ + } + +#endif /* GREENLET_MODULE */ + +#ifdef __cplusplus +} +#endif +#endif /* !Py_GREENLETOBJECT_H */ diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/Flask_Bcrypt-1.0.1.dist-info/INSTALLER b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/Flask_Bcrypt-1.0.1.dist-info/INSTALLER new file mode 100644 index 000000000..a1b589e38 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/Flask_Bcrypt-1.0.1.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/Flask_Bcrypt-1.0.1.dist-info/LICENSE b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/Flask_Bcrypt-1.0.1.dist-info/LICENSE new file mode 100644 index 000000000..237ce8a36 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/Flask_Bcrypt-1.0.1.dist-info/LICENSE @@ -0,0 +1,31 @@ +Copyright (c) 2011 by Max Countryman. + +Some rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + +* Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials provided + with the distribution. + +* The names of the contributors may not be used to endorse or + promote products derived from this software without specific + prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. \ No newline at end of file diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/Flask_Bcrypt-1.0.1.dist-info/METADATA b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/Flask_Bcrypt-1.0.1.dist-info/METADATA new file mode 100644 index 000000000..7f0b3869f --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/Flask_Bcrypt-1.0.1.dist-info/METADATA @@ -0,0 +1,74 @@ +Metadata-Version: 2.1 +Name: Flask-Bcrypt +Version: 1.0.1 +Summary: Brcrypt hashing for Flask. +Home-page: https://github.com/maxcountryman/flask-bcrypt +Author: Max Countryman +Author-email: maxc@me.com +License: BSD +Platform: any +Classifier: Environment :: Web Environment +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: BSD License +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.7 +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Topic :: Internet :: WWW/HTTP :: Dynamic Content +Classifier: Topic :: Software Development :: Libraries :: Python Modules +Description-Content-Type: text/markdown +Requires-Dist: Flask +Requires-Dist: bcrypt (>=3.1.1) + +[![Tests](https://img.shields.io/github/workflow/status/maxcountryman/flask-bcrypt/Tests/master?label=tests)](https://github.com/maxcountryman/flask-bcrypt/actions) +[![Version](https://img.shields.io/pypi/v/Flask-Bcrypt.svg)](https://pypi.python.org/pypi/Flask-Bcrypt) +[![Supported Python Versions](https://img.shields.io/pypi/pyversions/Flask-Bcrypt.svg)](https://pypi.python.org/pypi/Flask-Bcrypt) + +# Flask-Bcrypt + +Flask-Bcrypt is a Flask extension that provides bcrypt hashing utilities for +your application. + +Due to the recent increased prevalence of powerful hardware, such as modern +GPUs, hashes have become increasingly easy to crack. A proactive solution to +this is to use a hash that was designed to be "de-optimized". Bcrypt is such +a hashing facility; unlike hashing algorithms such as MD5 and SHA1, which are +optimized for speed, bcrypt is intentionally structured to be slow. + +For sensitive data that must be protected, such as passwords, bcrypt is an +advisable choice. + +## Installation + +Install the extension with one of the following commands: + + $ easy_install flask-bcrypt + +or alternatively if you have pip installed: + + $ pip install flask-bcrypt + +## Usage + +To use the extension simply import the class wrapper and pass the Flask app +object back to here. Do so like this: + + from flask import Flask + from flask_bcrypt import Bcrypt + + app = Flask(__name__) + bcrypt = Bcrypt(app) + +Two primary hashing methods are now exposed by way of the bcrypt object. Use +them like so: + + pw_hash = bcrypt.generate_password_hash('hunter2') + bcrypt.check_password_hash(pw_hash, 'hunter2') # returns True + +## Documentation + +The Sphinx-compiled documentation is available here: https://flask-bcrypt.readthedocs.io/ + + diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/Flask_Bcrypt-1.0.1.dist-info/RECORD b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/Flask_Bcrypt-1.0.1.dist-info/RECORD new file mode 100644 index 000000000..a84085870 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/Flask_Bcrypt-1.0.1.dist-info/RECORD @@ -0,0 +1,9 @@ +Flask_Bcrypt-1.0.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +Flask_Bcrypt-1.0.1.dist-info/LICENSE,sha256=RFRom0T_iGtIZZvvW5_AD14IAYQvR45h2hYe0Xp0Jak,1456 +Flask_Bcrypt-1.0.1.dist-info/METADATA,sha256=wO9naenfHK7Lgz41drDpI6BlMg_CpzjwGWsAiko2wsk,2615 +Flask_Bcrypt-1.0.1.dist-info/RECORD,, +Flask_Bcrypt-1.0.1.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +Flask_Bcrypt-1.0.1.dist-info/WHEEL,sha256=G16H4A3IeoQmnOrYV4ueZGKSjhipXx8zc8nu9FGlvMA,92 +Flask_Bcrypt-1.0.1.dist-info/top_level.txt,sha256=HUgQw7e42Bb9jcMgo5popKpplnimwUQw3cyTi0K1N7o,13 +__pycache__/flask_bcrypt.cpython-312.pyc,, +flask_bcrypt.py,sha256=thnztmOYR9M6afp-bTRdSKsPef6R2cOFo4j_DD88-Ls,8856 diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/Flask_Bcrypt-1.0.1.dist-info/REQUESTED b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/Flask_Bcrypt-1.0.1.dist-info/REQUESTED new file mode 100644 index 000000000..e69de29bb diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/Flask_Bcrypt-1.0.1.dist-info/WHEEL b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/Flask_Bcrypt-1.0.1.dist-info/WHEEL new file mode 100644 index 000000000..becc9a66e --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/Flask_Bcrypt-1.0.1.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: bdist_wheel (0.37.1) +Root-Is-Purelib: true +Tag: py3-none-any + diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/Flask_Bcrypt-1.0.1.dist-info/top_level.txt b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/Flask_Bcrypt-1.0.1.dist-info/top_level.txt new file mode 100644 index 000000000..f7f0e8875 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/Flask_Bcrypt-1.0.1.dist-info/top_level.txt @@ -0,0 +1 @@ +flask_bcrypt diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/Flask_Login-0.6.3.dist-info/INSTALLER b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/Flask_Login-0.6.3.dist-info/INSTALLER new file mode 100644 index 000000000..a1b589e38 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/Flask_Login-0.6.3.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/Flask_Login-0.6.3.dist-info/LICENSE b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/Flask_Login-0.6.3.dist-info/LICENSE new file mode 100644 index 000000000..04463812d --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/Flask_Login-0.6.3.dist-info/LICENSE @@ -0,0 +1,22 @@ +Copyright (c) 2011 Matthew Frazier + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal in the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/Flask_Login-0.6.3.dist-info/METADATA b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/Flask_Login-0.6.3.dist-info/METADATA new file mode 100644 index 000000000..445a0b23e --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/Flask_Login-0.6.3.dist-info/METADATA @@ -0,0 +1,183 @@ +Metadata-Version: 2.1 +Name: Flask-Login +Version: 0.6.3 +Summary: User authentication and session management for Flask. +Home-page: https://github.com/maxcountryman/flask-login +Author: Matthew Frazier +Author-email: leafstormrush@gmail.com +Maintainer: Max Countryman +License: MIT +Project-URL: Documentation, https://flask-login.readthedocs.io/ +Project-URL: Changes, https://github.com/maxcountryman/flask-login/blob/main/CHANGES.md +Project-URL: Source Code, https://github.com/maxcountryman/flask-login +Project-URL: Issue Tracker, https://github.com/maxcountryman/flask-login/issues +Classifier: Development Status :: 4 - Beta +Classifier: Environment :: Web Environment +Classifier: Framework :: Flask +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: MIT License +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: Python +Classifier: Topic :: Internet :: WWW/HTTP :: Dynamic Content +Classifier: Topic :: Software Development :: Libraries :: Python Modules +Requires-Python: >=3.7 +Description-Content-Type: text/markdown +License-File: LICENSE +Requires-Dist: Flask >=1.0.4 +Requires-Dist: Werkzeug >=1.0.1 + +# Flask-Login + +![Tests](https://github.com/maxcountryman/flask-login/workflows/Tests/badge.svg) +[![coverage](https://coveralls.io/repos/maxcountryman/flask-login/badge.svg?branch=main&service=github)](https://coveralls.io/github/maxcountryman/flask-login?branch=main) +[![Software License](https://img.shields.io/badge/license-MIT-brightgreen.svg)](LICENSE) + +Flask-Login provides user session management for Flask. It handles the common +tasks of logging in, logging out, and remembering your users' sessions over +extended periods of time. + +Flask-Login is not bound to any particular database system or permissions +model. The only requirement is that your user objects implement a few methods, +and that you provide a callback to the extension capable of loading users from +their ID. + +## Installation + +Install the extension with pip: + +```sh +$ pip install flask-login +``` + +## Usage + +Once installed, the Flask-Login is easy to use. Let's walk through setting up +a basic application. Also please note that this is a very basic guide: we will +be taking shortcuts here that you should never take in a real application. + +To begin we'll set up a Flask app: + +```python +import flask + +app = flask.Flask(__name__) +app.secret_key = 'super secret string' # Change this! +``` + +Flask-Login works via a login manager. To kick things off, we'll set up the +login manager by instantiating it and telling it about our Flask app: + +```python +import flask_login + +login_manager = flask_login.LoginManager() + +login_manager.init_app(app) +``` + +To keep things simple we're going to use a dictionary to represent a database +of users. In a real application, this would be an actual persistence layer. +However it's important to point out this is a feature of Flask-Login: it +doesn't care how your data is stored so long as you tell it how to retrieve it! + +```python +# Our mock database. +users = {'foo@bar.tld': {'password': 'secret'}} +``` + +We also need to tell Flask-Login how to load a user from a Flask request and +from its session. To do this we need to define our user object, a +`user_loader` callback, and a `request_loader` callback. + +```python +class User(flask_login.UserMixin): + pass + + +@login_manager.user_loader +def user_loader(email): + if email not in users: + return + + user = User() + user.id = email + return user + + +@login_manager.request_loader +def request_loader(request): + email = request.form.get('email') + if email not in users: + return + + user = User() + user.id = email + return user +``` + +Now we're ready to define our views. We can start with a login view, which will +populate the session with authentication bits. After that we can define a view +that requires authentication. + +```python +@app.route('/login', methods=['GET', 'POST']) +def login(): + if flask.request.method == 'GET': + return ''' +
+ + + +
+ ''' + + email = flask.request.form['email'] + if email in users and flask.request.form['password'] == users[email]['password']: + user = User() + user.id = email + flask_login.login_user(user) + return flask.redirect(flask.url_for('protected')) + + return 'Bad login' + + +@app.route('/protected') +@flask_login.login_required +def protected(): + return 'Logged in as: ' + flask_login.current_user.id +``` + +Finally we can define a view to clear the session and log users out: + +```python +@app.route('/logout') +def logout(): + flask_login.logout_user() + return 'Logged out' +``` + +We now have a basic working application that makes use of session-based +authentication. To round things off, we should provide a callback for login +failures: + +```python +@login_manager.unauthorized_handler +def unauthorized_handler(): + return 'Unauthorized', 401 +``` + +Documentation for Flask-Login is available on [ReadTheDocs](https://flask-login.readthedocs.io/en/latest/). +For complete understanding of available configuration, please refer to the [source code](https://github.com/maxcountryman/flask-login). + + +## Contributing + +We welcome contributions! If you would like to hack on Flask-Login, please +follow these steps: + +1. Fork this repository +2. Make your changes +3. Install the dev requirements with `pip install -r requirements/dev.txt` +4. Submit a pull request after running `tox` (ensure it does not error!) + +Please give us adequate time to review your submission. Thanks! diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/Flask_Login-0.6.3.dist-info/RECORD b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/Flask_Login-0.6.3.dist-info/RECORD new file mode 100644 index 000000000..c66089e48 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/Flask_Login-0.6.3.dist-info/RECORD @@ -0,0 +1,23 @@ +Flask_Login-0.6.3.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +Flask_Login-0.6.3.dist-info/LICENSE,sha256=ep37nF2iBO0TcPO2LBPimSoS2h2nB_R-FWiX7rQ0Tls,1059 +Flask_Login-0.6.3.dist-info/METADATA,sha256=AUSHR5Po6-Cwmz1KBrAZbTzR-iVVFvtb2NQKYl7UuAU,5799 +Flask_Login-0.6.3.dist-info/RECORD,, +Flask_Login-0.6.3.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +Flask_Login-0.6.3.dist-info/WHEEL,sha256=Xo9-1PvkuimrydujYJAjF7pCkriuXBpUPEjma1nZyJ0,92 +Flask_Login-0.6.3.dist-info/top_level.txt,sha256=OuXmIpiFnXLvW-iBbW2km7ZIy5EZvwSBnYaOC3Kt7j8,12 +flask_login/__about__.py,sha256=Kkp5e9mV9G7vK_FqZof-g9RFmyyBzq1gge5aKXgvilE,389 +flask_login/__init__.py,sha256=wYQiQCikT_Ndp3PhOD-1gRTGCrUPIE-FrjQUrT9aVAg,2681 +flask_login/__pycache__/__about__.cpython-312.pyc,, +flask_login/__pycache__/__init__.cpython-312.pyc,, +flask_login/__pycache__/config.cpython-312.pyc,, +flask_login/__pycache__/login_manager.cpython-312.pyc,, +flask_login/__pycache__/mixins.cpython-312.pyc,, +flask_login/__pycache__/signals.cpython-312.pyc,, +flask_login/__pycache__/test_client.cpython-312.pyc,, +flask_login/__pycache__/utils.cpython-312.pyc,, +flask_login/config.py,sha256=YAocv18La7YGQyNY5aT7rU1GQIZnX6pvchwqx3kA9p8,1813 +flask_login/login_manager.py,sha256=h20F_iv3mqc6rIJ4-V6_XookzOUl8Rcpasua-dCByQY,20073 +flask_login/mixins.py,sha256=gPd7otMRljxw0eUhUMbHsnEBc_jK2cYdxg5KFLuJcoI,1528 +flask_login/signals.py,sha256=xCMoFHKU1RTVt1NY-Gfl0OiVKpiyNt6YJw_PsgkjY3w,2464 +flask_login/test_client.py,sha256=6mrjiBRLGJpgvvFlLypXPTBLiMp0BAN-Ft-uogqC81g,517 +flask_login/utils.py,sha256=Y1wxjCVxpYohBaQJ0ADLypQ-VvBNycwG-gVXFF7k99I,14021 diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/Flask_Login-0.6.3.dist-info/REQUESTED b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/Flask_Login-0.6.3.dist-info/REQUESTED new file mode 100644 index 000000000..e69de29bb diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/Flask_Login-0.6.3.dist-info/WHEEL b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/Flask_Login-0.6.3.dist-info/WHEEL new file mode 100644 index 000000000..ba48cbcf9 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/Flask_Login-0.6.3.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: bdist_wheel (0.41.3) +Root-Is-Purelib: true +Tag: py3-none-any + diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/Flask_Login-0.6.3.dist-info/top_level.txt b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/Flask_Login-0.6.3.dist-info/top_level.txt new file mode 100644 index 000000000..31514bd20 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/Flask_Login-0.6.3.dist-info/top_level.txt @@ -0,0 +1 @@ +flask_login diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/AvifImagePlugin.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/AvifImagePlugin.py new file mode 100644 index 000000000..2343499c2 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/AvifImagePlugin.py @@ -0,0 +1,294 @@ +from __future__ import annotations + +import os +from io import BytesIO +from typing import IO + +from . import ExifTags, Image, ImageFile + +try: + from . import _avif + + SUPPORTED = True +except ImportError: + SUPPORTED = False + +# Decoder options as module globals, until there is a way to pass parameters +# to Image.open (see https://github.com/python-pillow/Pillow/issues/569) +DECODE_CODEC_CHOICE = "auto" +DEFAULT_MAX_THREADS = 0 + + +def get_codec_version(codec_name: str) -> str | None: + versions = _avif.codec_versions() + for version in versions.split(", "): + if version.split(" [")[0] == codec_name: + return version.split(":")[-1].split(" ")[0] + return None + + +def _accept(prefix: bytes) -> bool | str: + if prefix[4:8] != b"ftyp": + return False + major_brand = prefix[8:12] + if major_brand in ( + # coding brands + b"avif", + b"avis", + # We accept files with AVIF container brands; we can't yet know if + # the ftyp box has the correct compatible brands, but if it doesn't + # then the plugin will raise a SyntaxError which Pillow will catch + # before moving on to the next plugin that accepts the file. + # + # Also, because this file might not actually be an AVIF file, we + # don't raise an error if AVIF support isn't properly compiled. + b"mif1", + b"msf1", + ): + if not SUPPORTED: + return ( + "image file could not be identified because AVIF support not installed" + ) + return True + return False + + +def _get_default_max_threads() -> int: + if DEFAULT_MAX_THREADS: + return DEFAULT_MAX_THREADS + if hasattr(os, "sched_getaffinity"): + return len(os.sched_getaffinity(0)) + else: + return os.cpu_count() or 1 + + +class AvifImageFile(ImageFile.ImageFile): + format = "AVIF" + format_description = "AVIF image" + __frame = -1 + + def _open(self) -> None: + if not SUPPORTED: + msg = "image file could not be opened because AVIF support not installed" + raise SyntaxError(msg) + + if DECODE_CODEC_CHOICE != "auto" and not _avif.decoder_codec_available( + DECODE_CODEC_CHOICE + ): + msg = "Invalid opening codec" + raise ValueError(msg) + + assert self.fp is not None + raise RuntimeError("File pointer (fp) is not initialized.") + self._decoder = _avif.AvifDecoder( + self.fp.read(), + DECODE_CODEC_CHOICE, + _get_default_max_threads(), + ) + + # Get info from decoder + self._size, self.n_frames, self._mode, icc, exif, exif_orientation, xmp = ( + self._decoder.get_info() + ) + self.is_animated = self.n_frames > 1 + + if icc: + self.info["icc_profile"] = icc + if xmp: + self.info["xmp"] = xmp + + if exif_orientation != 1 or exif: + exif_data = Image.Exif() + if exif: + exif_data.load(exif) + original_orientation = exif_data.get(ExifTags.Base.Orientation, 1) + else: + original_orientation = 1 + if exif_orientation != original_orientation: + exif_data[ExifTags.Base.Orientation] = exif_orientation + exif = exif_data.tobytes() + if exif: + self.info["exif"] = exif + self.seek(0) + + def seek(self, frame: int) -> None: + if not self._seek_check(frame): + return + + # Set tile + self.__frame = frame + self.tile = [ImageFile._Tile("raw", (0, 0) + self.size, 0, self.mode)] + + def load(self) -> Image.core.PixelAccess | None: + if self.tile: + # We need to load the image data for this frame + data, timescale, pts_in_timescales, duration_in_timescales = ( + self._decoder.get_frame(self.__frame) + ) + self.info["timestamp"] = round(1000 * (pts_in_timescales / timescale)) + self.info["duration"] = round(1000 * (duration_in_timescales / timescale)) + + if self.fp and self._exclusive_fp: + self.fp.close() + self.fp = BytesIO(data) + + return super().load() + + def load_seek(self, pos: int) -> None: + pass + + def tell(self) -> int: + return self.__frame + + +def _save_all(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None: + _save(im, fp, filename, save_all=True) + + +def _save( + im: Image.Image, fp: IO[bytes], filename: str | bytes, save_all: bool = False +) -> None: + info = im.encoderinfo.copy() + if save_all: + append_images = list(info.get("append_images", [])) + else: + append_images = [] + + total = 0 + for ims in [im] + append_images: + total += getattr(ims, "n_frames", 1) + + quality = info.get("quality", 75) + if not isinstance(quality, int) or quality < 0 or quality > 100: + msg = "Invalid quality setting" + raise ValueError(msg) + + duration = info.get("duration", 0) + subsampling = info.get("subsampling", "4:2:0") + speed = info.get("speed", 6) + max_threads = info.get("max_threads", _get_default_max_threads()) + codec = info.get("codec", "auto") + if codec != "auto" and not _avif.encoder_codec_available(codec): + msg = "Invalid saving codec" + raise ValueError(msg) + range_ = info.get("range", "full") + tile_rows_log2 = info.get("tile_rows", 0) + tile_cols_log2 = info.get("tile_cols", 0) + alpha_premultiplied = bool(info.get("alpha_premultiplied", False)) + autotiling = bool(info.get("autotiling", tile_rows_log2 == tile_cols_log2 == 0)) + + icc_profile = info.get("icc_profile", im.info.get("icc_profile")) + exif_orientation = 1 + if exif := info.get("exif"): + if isinstance(exif, Image.Exif): + exif_data = exif + else: + exif_data = Image.Exif() + exif_data.load(exif) + if ExifTags.Base.Orientation in exif_data: + exif_orientation = exif_data.pop(ExifTags.Base.Orientation) + exif = exif_data.tobytes() if exif_data else b"" + elif isinstance(exif, Image.Exif): + exif = exif_data.tobytes() + + xmp = info.get("xmp") + + if isinstance(xmp, str): + xmp = xmp.encode("utf-8") + + advanced = info.get("advanced") + if advanced is not None: + if isinstance(advanced, dict): + advanced = advanced.items() + try: + advanced = tuple(advanced) + except TypeError: + invalid = True + else: + invalid = any(not isinstance(v, tuple) or len(v) != 2 for v in advanced) + if invalid: + msg = ( + "advanced codec options must be a dict of key-value string " + "pairs or a series of key-value two-tuples" + ) + raise ValueError(msg) + + # Setup the AVIF encoder + enc = _avif.AvifEncoder( + im.size, + subsampling, + quality, + speed, + max_threads, + codec, + range_, + tile_rows_log2, + tile_cols_log2, + alpha_premultiplied, + autotiling, + icc_profile or b"", + exif or b"", + exif_orientation, + xmp or b"", + advanced, + ) + + # Add each frame + frame_idx = 0 + frame_duration = 0 + cur_idx = im.tell() + is_single_frame = total == 1 + try: + for ims in [im] + append_images: + # Get number of frames in this image + nfr = getattr(ims, "n_frames", 1) + + for idx in range(nfr): + ims.seek(idx) + + # Make sure image mode is supported + frame = ims + rawmode = ims.mode + if ims.mode not in {"RGB", "RGBA"}: + rawmode = "RGBA" if ims.has_transparency_data else "RGB" + frame = ims.convert(rawmode) + + # Update frame duration + if isinstance(duration, (list, tuple)): + frame_duration = duration[frame_idx] + else: + frame_duration = duration + + # Append the frame to the animation encoder + enc.add( + frame.tobytes("raw", rawmode), + frame_duration, + frame.size, + rawmode, + is_single_frame, + ) + + # Update frame index + frame_idx += 1 + + if not save_all: + break + + finally: + im.seek(cur_idx) + + # Get the final output from the encoder + data = enc.finish() + if data is None: + msg = "cannot write file as AVIF (encoder returned None)" + raise OSError(msg) + + fp.write(data) + + +Image.register_open(AvifImageFile.format, AvifImageFile, _accept) +if SUPPORTED: + Image.register_save(AvifImageFile.format, _save) + Image.register_save_all(AvifImageFile.format, _save_all) + Image.register_extensions(AvifImageFile.format, [".avif", ".avifs"]) + Image.register_mime(AvifImageFile.format, "image/avif") diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/BdfFontFile.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/BdfFontFile.py new file mode 100644 index 000000000..1c8c28ff0 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/BdfFontFile.py @@ -0,0 +1,123 @@ +# +# The Python Imaging Library +# $Id$ +# +# bitmap distribution font (bdf) file parser +# +# history: +# 1996-05-16 fl created (as bdf2pil) +# 1997-08-25 fl converted to FontFile driver +# 2001-05-25 fl removed bogus __init__ call +# 2002-11-20 fl robustification (from Kevin Cazabon, Dmitry Vasiliev) +# 2003-04-22 fl more robustification (from Graham Dumpleton) +# +# Copyright (c) 1997-2003 by Secret Labs AB. +# Copyright (c) 1997-2003 by Fredrik Lundh. +# +# See the README file for information on usage and redistribution. +# + +""" +Parse X Bitmap Distribution Format (BDF) +""" + +from __future__ import annotations + +from typing import BinaryIO + +from . import FontFile, Image + + +def bdf_char( + f: BinaryIO, +) -> ( + tuple[ + str, + int, + tuple[tuple[int, int], tuple[int, int, int, int], tuple[int, int, int, int]], + Image.Image, + ] + | None +): + # skip to STARTCHAR + while True: + s = f.readline() + if not s: + return None + if s.startswith(b"STARTCHAR"): + break + id = s[9:].strip().decode("ascii") + + # load symbol properties + props = {} + while True: + s = f.readline() + if not s or s.startswith(b"BITMAP"): + break + i = s.find(b" ") + props[s[:i].decode("ascii")] = s[i + 1 : -1].decode("ascii") + + # load bitmap + bitmap = bytearray() + while True: + s = f.readline() + if not s or s.startswith(b"ENDCHAR"): + break + bitmap += s[:-1] + + # The word BBX + # followed by the width in x (BBw), height in y (BBh), + # and x and y displacement (BBxoff0, BByoff0) + # of the lower left corner from the origin of the character. + width, height, x_disp, y_disp = (int(p) for p in props["BBX"].split()) + + # The word DWIDTH + # followed by the width in x and y of the character in device pixels. + dwx, dwy = (int(p) for p in props["DWIDTH"].split()) + + bbox = ( + (dwx, dwy), + (x_disp, -y_disp - height, width + x_disp, -y_disp), + (0, 0, width, height), + ) + + try: + im = Image.frombytes("1", (width, height), bitmap, "hex", "1") + except ValueError: + # deal with zero-width characters + im = Image.new("1", (width, height)) + + return id, int(props["ENCODING"]), bbox, im + + +class BdfFontFile(FontFile.FontFile): + """Font file plugin for the X11 BDF format.""" + + def __init__(self, fp: BinaryIO) -> None: + super().__init__() + + s = fp.readline() + if not s.startswith(b"STARTFONT 2.1"): + msg = "not a valid BDF file" + raise SyntaxError(msg) + + props = {} + comments = [] + + while True: + s = fp.readline() + if not s or s.startswith(b"ENDPROPERTIES"): + break + i = s.find(b" ") + props[s[:i].decode("ascii")] = s[i + 1 : -1].decode("ascii") + if s[:i] in [b"COMMENT", b"COPYRIGHT"]: + if s.find(b"LogicalFontDescription") < 0: + comments.append(s[i + 1 : -1].decode("ascii")) + + while True: + c = bdf_char(fp) + if not c: + break + id, ch, (xy, dst, src), im = c + if 0 <= ch < len(self.glyph): + self.glyph[ch] = xy, dst, src, im diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/BlpImagePlugin.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/BlpImagePlugin.py new file mode 100644 index 000000000..6bb92edf8 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/BlpImagePlugin.py @@ -0,0 +1,498 @@ +""" +Blizzard Mipmap Format (.blp) +Jerome Leclanche + +The contents of this file are hereby released in the public domain (CC0) +Full text of the CC0 license: + https://creativecommons.org/publicdomain/zero/1.0/ + +BLP1 files, used mostly in Warcraft III, are not fully supported. +All types of BLP2 files used in World of Warcraft are supported. + +The BLP file structure consists of a header, up to 16 mipmaps of the +texture + +Texture sizes must be powers of two, though the two dimensions do +not have to be equal; 512x256 is valid, but 512x200 is not. +The first mipmap (mipmap #0) is the full size image; each subsequent +mipmap halves both dimensions. The final mipmap should be 1x1. + +BLP files come in many different flavours: +* JPEG-compressed (type == 0) - only supported for BLP1. +* RAW images (type == 1, encoding == 1). Each mipmap is stored as an + array of 8-bit values, one per pixel, left to right, top to bottom. + Each value is an index to the palette. +* DXT-compressed (type == 1, encoding == 2): +- DXT1 compression is used if alpha_encoding == 0. + - An additional alpha bit is used if alpha_depth == 1. + - DXT3 compression is used if alpha_encoding == 1. + - DXT5 compression is used if alpha_encoding == 7. +""" + +from __future__ import annotations + +import abc +import os +import struct +from enum import IntEnum +from io import BytesIO +from typing import IO + +from . import Image, ImageFile + + +class Format(IntEnum): + JPEG = 0 + + +class Encoding(IntEnum): + UNCOMPRESSED = 1 + DXT = 2 + UNCOMPRESSED_RAW_BGRA = 3 + + +class AlphaEncoding(IntEnum): + DXT1 = 0 + DXT3 = 1 + DXT5 = 7 + + +def unpack_565(i: int) -> tuple[int, int, int]: + return ((i >> 11) & 0x1F) << 3, ((i >> 5) & 0x3F) << 2, (i & 0x1F) << 3 + + +def decode_dxt1( + data: bytes, alpha: bool = False +) -> tuple[bytearray, bytearray, bytearray, bytearray]: + """ + input: one "row" of data (i.e. will produce 4*width pixels) + """ + + blocks = len(data) // 8 # number of blocks in row + ret = (bytearray(), bytearray(), bytearray(), bytearray()) + + for block_index in range(blocks): + # Decode next 8-byte block. + idx = block_index * 8 + color0, color1, bits = struct.unpack_from("> 2 + + a = 0xFF + if control == 0: + r, g, b = r0, g0, b0 + elif control == 1: + r, g, b = r1, g1, b1 + elif control == 2: + if color0 > color1: + r = (2 * r0 + r1) // 3 + g = (2 * g0 + g1) // 3 + b = (2 * b0 + b1) // 3 + else: + r = (r0 + r1) // 2 + g = (g0 + g1) // 2 + b = (b0 + b1) // 2 + elif control == 3: + if color0 > color1: + r = (2 * r1 + r0) // 3 + g = (2 * g1 + g0) // 3 + b = (2 * b1 + b0) // 3 + else: + r, g, b, a = 0, 0, 0, 0 + + if alpha: + ret[j].extend([r, g, b, a]) + else: + ret[j].extend([r, g, b]) + + return ret + + +def decode_dxt3(data: bytes) -> tuple[bytearray, bytearray, bytearray, bytearray]: + """ + input: one "row" of data (i.e. will produce 4*width pixels) + """ + + blocks = len(data) // 16 # number of blocks in row + ret = (bytearray(), bytearray(), bytearray(), bytearray()) + + for block_index in range(blocks): + idx = block_index * 16 + block = data[idx : idx + 16] + # Decode next 16-byte block. + bits = struct.unpack_from("<8B", block) + color0, color1 = struct.unpack_from(">= 4 + else: + high = True + a &= 0xF + a *= 17 # We get a value between 0 and 15 + + color_code = (code >> 2 * (4 * j + i)) & 0x03 + + if color_code == 0: + r, g, b = r0, g0, b0 + elif color_code == 1: + r, g, b = r1, g1, b1 + elif color_code == 2: + r = (2 * r0 + r1) // 3 + g = (2 * g0 + g1) // 3 + b = (2 * b0 + b1) // 3 + elif color_code == 3: + r = (2 * r1 + r0) // 3 + g = (2 * g1 + g0) // 3 + b = (2 * b1 + b0) // 3 + + ret[j].extend([r, g, b, a]) + + return ret + + +def decode_dxt5(data: bytes) -> tuple[bytearray, bytearray, bytearray, bytearray]: + """ + input: one "row" of data (i.e. will produce 4 * width pixels) + """ + + blocks = len(data) // 16 # number of blocks in row + ret = (bytearray(), bytearray(), bytearray(), bytearray()) + + for block_index in range(blocks): + idx = block_index * 16 + block = data[idx : idx + 16] + # Decode next 16-byte block. + a0, a1 = struct.unpack_from("> alphacode_index) & 0x07 + elif alphacode_index == 15: + alphacode = (alphacode2 >> 15) | ((alphacode1 << 1) & 0x06) + else: # alphacode_index >= 18 and alphacode_index <= 45 + alphacode = (alphacode1 >> (alphacode_index - 16)) & 0x07 + + if alphacode == 0: + a = a0 + elif alphacode == 1: + a = a1 + elif a0 > a1: + a = ((8 - alphacode) * a0 + (alphacode - 1) * a1) // 7 + elif alphacode == 6: + a = 0 + elif alphacode == 7: + a = 255 + else: + a = ((6 - alphacode) * a0 + (alphacode - 1) * a1) // 5 + + color_code = (code >> 2 * (4 * j + i)) & 0x03 + + if color_code == 0: + r, g, b = r0, g0, b0 + elif color_code == 1: + r, g, b = r1, g1, b1 + elif color_code == 2: + r = (2 * r0 + r1) // 3 + g = (2 * g0 + g1) // 3 + b = (2 * b0 + b1) // 3 + elif color_code == 3: + r = (2 * r1 + r0) // 3 + g = (2 * g1 + g0) // 3 + b = (2 * b1 + b0) // 3 + + ret[j].extend([r, g, b, a]) + + return ret + + +class BLPFormatError(NotImplementedError): + pass + + +def _accept(prefix: bytes) -> bool: + return prefix.startswith((b"BLP1", b"BLP2")) + + +class BlpImageFile(ImageFile.ImageFile): + """ + Blizzard Mipmap Format + """ + + format = "BLP" + format_description = "Blizzard Mipmap Format" + + def _open(self) -> None: + assert self.fp is not None + self.magic = self.fp.read(4) + if not _accept(self.magic): + msg = f"Bad BLP magic {repr(self.magic)}" + raise BLPFormatError(msg) + + compression = struct.unpack(" tuple[int, int]: + try: + self._read_header() + self._load() + except struct.error as e: + msg = "Truncated BLP file" + raise OSError(msg) from e + return -1, 0 + + @abc.abstractmethod + def _load(self) -> None: + pass + + def _read_header(self) -> None: + self._offsets = struct.unpack("<16I", self._safe_read(16 * 4)) + self._lengths = struct.unpack("<16I", self._safe_read(16 * 4)) + + def _safe_read(self, length: int) -> bytes: + assert self.fd is not None + return ImageFile._safe_read(self.fd, length) + + def _read_palette(self) -> list[tuple[int, int, int, int]]: + ret = [] + for i in range(256): + try: + b, g, r, a = struct.unpack("<4B", self._safe_read(4)) + except struct.error: + break + ret.append((b, g, r, a)) + return ret + + def _read_bgra( + self, palette: list[tuple[int, int, int, int]], alpha: bool + ) -> bytearray: + data = bytearray() + _data = BytesIO(self._safe_read(self._lengths[0])) + while True: + try: + (offset,) = struct.unpack(" None: + self._compression, self._encoding, alpha = self.args + + if self._compression == Format.JPEG: + self._decode_jpeg_stream() + + elif self._compression == 1: + if self._encoding in (4, 5): + palette = self._read_palette() + data = self._read_bgra(palette, alpha) + self.set_as_raw(data) + else: + msg = f"Unsupported BLP encoding {repr(self._encoding)}" + raise BLPFormatError(msg) + else: + msg = f"Unsupported BLP compression {repr(self._encoding)}" + raise BLPFormatError(msg) + + def _decode_jpeg_stream(self) -> None: + from .JpegImagePlugin import JpegImageFile + + (jpeg_header_size,) = struct.unpack(" None: + self._compression, self._encoding, alpha, self._alpha_encoding = self.args + + palette = self._read_palette() + + assert self.fd is not None + self.fd.seek(self._offsets[0]) + + if self._compression == 1: + # Uncompressed or DirectX compression + + if self._encoding == Encoding.UNCOMPRESSED: + data = self._read_bgra(palette, alpha) + + elif self._encoding == Encoding.DXT: + data = bytearray() + if self._alpha_encoding == AlphaEncoding.DXT1: + linesize = (self.state.xsize + 3) // 4 * 8 + for yb in range((self.state.ysize + 3) // 4): + for d in decode_dxt1(self._safe_read(linesize), alpha): + data += d + + elif self._alpha_encoding == AlphaEncoding.DXT3: + linesize = (self.state.xsize + 3) // 4 * 16 + for yb in range((self.state.ysize + 3) // 4): + for d in decode_dxt3(self._safe_read(linesize)): + data += d + + elif self._alpha_encoding == AlphaEncoding.DXT5: + linesize = (self.state.xsize + 3) // 4 * 16 + for yb in range((self.state.ysize + 3) // 4): + for d in decode_dxt5(self._safe_read(linesize)): + data += d + else: + msg = f"Unsupported alpha encoding {repr(self._alpha_encoding)}" + raise BLPFormatError(msg) + else: + msg = f"Unknown BLP encoding {repr(self._encoding)}" + raise BLPFormatError(msg) + + else: + msg = f"Unknown BLP compression {repr(self._compression)}" + raise BLPFormatError(msg) + + self.set_as_raw(data) + + +class BLPEncoder(ImageFile.PyEncoder): + _pushes_fd = True + + def _write_palette(self) -> bytes: + data = b"" + assert self.im is not None + palette = self.im.getpalette("RGBA", "RGBA") + for i in range(len(palette) // 4): + r, g, b, a = palette[i * 4 : (i + 1) * 4] + data += struct.pack("<4B", b, g, r, a) + while len(data) < 256 * 4: + data += b"\x00" * 4 + return data + + def encode(self, bufsize: int) -> tuple[int, int, bytes]: + palette_data = self._write_palette() + + offset = 20 + 16 * 4 * 2 + len(palette_data) + data = struct.pack("<16I", offset, *((0,) * 15)) + + assert self.im is not None + w, h = self.im.size + data += struct.pack("<16I", w * h, *((0,) * 15)) + + data += palette_data + + for y in range(h): + for x in range(w): + data += struct.pack(" None: + if im.mode != "P": + msg = "Unsupported BLP image mode" + raise ValueError(msg) + + magic = b"BLP1" if im.encoderinfo.get("blp_version") == "BLP1" else b"BLP2" + fp.write(magic) + + assert im.palette is not None + fp.write(struct.pack(" mode, rawmode + 1: ("P", "P;1"), + 4: ("P", "P;4"), + 8: ("P", "P"), + 16: ("RGB", "BGR;15"), + 24: ("RGB", "BGR"), + 32: ("RGB", "BGRX"), +} + +USE_RAW_ALPHA = False + + +def _accept(prefix: bytes) -> bool: + return prefix.startswith(b"BM") + + +def _dib_accept(prefix: bytes) -> bool: + return i32(prefix) in [12, 40, 52, 56, 64, 108, 124] + + +# ============================================================================= +# Image plugin for the Windows BMP format. +# ============================================================================= +class BmpImageFile(ImageFile.ImageFile): + """Image plugin for the Windows Bitmap format (BMP)""" + + # ------------------------------------------------------------- Description + format_description = "Windows Bitmap" + format = "BMP" + + # -------------------------------------------------- BMP Compression values + COMPRESSIONS = {"RAW": 0, "RLE8": 1, "RLE4": 2, "BITFIELDS": 3, "JPEG": 4, "PNG": 5} + for k, v in COMPRESSIONS.items(): + vars()[k] = v + + def _bitmap(self, header: int = 0, offset: int = 0) -> None: + """Read relevant info about the BMP""" + assert self.fp is not None + read, seek = self.fp.read, self.fp.seek + if header: + seek(header) + # read bmp header size @offset 14 (this is part of the header size) + file_info: dict[str, bool | int | tuple[int, ...]] = { + "header_size": i32(read(4)), + "direction": -1, + } + + # -------------------- If requested, read header at a specific position + # read the rest of the bmp header, without its size + assert isinstance(file_info["header_size"], int) + header_data = ImageFile._safe_read(self.fp, file_info["header_size"] - 4) + + # ------------------------------- Windows Bitmap v2, IBM OS/2 Bitmap v1 + # ----- This format has different offsets because of width/height types + # 12: BITMAPCOREHEADER/OS21XBITMAPHEADER + if file_info["header_size"] == 12: + file_info["width"] = i16(header_data, 0) + file_info["height"] = i16(header_data, 2) + file_info["planes"] = i16(header_data, 4) + file_info["bits"] = i16(header_data, 6) + file_info["compression"] = self.COMPRESSIONS["RAW"] + file_info["palette_padding"] = 3 + + # --------------------------------------------- Windows Bitmap v3 to v5 + # 40: BITMAPINFOHEADER + # 52: BITMAPV2HEADER + # 56: BITMAPV3HEADER + # 64: BITMAPCOREHEADER2/OS22XBITMAPHEADER + # 108: BITMAPV4HEADER + # 124: BITMAPV5HEADER + elif file_info["header_size"] in (40, 52, 56, 64, 108, 124): + file_info["y_flip"] = header_data[7] == 0xFF + file_info["direction"] = 1 if file_info["y_flip"] else -1 + file_info["width"] = i32(header_data, 0) + file_info["height"] = ( + i32(header_data, 4) + if not file_info["y_flip"] + else 2**32 - i32(header_data, 4) + ) + file_info["planes"] = i16(header_data, 8) + file_info["bits"] = i16(header_data, 10) + file_info["compression"] = i32(header_data, 12) + # byte size of pixel data + file_info["data_size"] = i32(header_data, 16) + file_info["pixels_per_meter"] = ( + i32(header_data, 20), + i32(header_data, 24), + ) + file_info["colors"] = i32(header_data, 28) + file_info["palette_padding"] = 4 + assert isinstance(file_info["pixels_per_meter"], tuple) + self.info["dpi"] = tuple(x / 39.3701 for x in file_info["pixels_per_meter"]) + if file_info["compression"] == self.COMPRESSIONS["BITFIELDS"]: + masks = ["r_mask", "g_mask", "b_mask"] + if len(header_data) >= 48: + if len(header_data) >= 52: + masks.append("a_mask") + else: + file_info["a_mask"] = 0x0 + for idx, mask in enumerate(masks): + file_info[mask] = i32(header_data, 36 + idx * 4) + else: + # 40 byte headers only have the three components in the + # bitfields masks, ref: + # https://msdn.microsoft.com/en-us/library/windows/desktop/dd183376(v=vs.85).aspx + # See also + # https://github.com/python-pillow/Pillow/issues/1293 + # There is a 4th component in the RGBQuad, in the alpha + # location, but it is listed as a reserved component, + # and it is not generally an alpha channel + file_info["a_mask"] = 0x0 + for mask in masks: + file_info[mask] = i32(read(4)) + assert isinstance(file_info["r_mask"], int) + assert isinstance(file_info["g_mask"], int) + assert isinstance(file_info["b_mask"], int) + assert isinstance(file_info["a_mask"], int) + file_info["rgb_mask"] = ( + file_info["r_mask"], + file_info["g_mask"], + file_info["b_mask"], + ) + file_info["rgba_mask"] = ( + file_info["r_mask"], + file_info["g_mask"], + file_info["b_mask"], + file_info["a_mask"], + ) + else: + msg = f"Unsupported BMP header type ({file_info['header_size']})" + raise OSError(msg) + + # ------------------ Special case : header is reported 40, which + # ---------------------- is shorter than real size for bpp >= 16 + assert isinstance(file_info["width"], int) + assert isinstance(file_info["height"], int) + self._size = file_info["width"], file_info["height"] + + # ------- If color count was not found in the header, compute from bits + assert isinstance(file_info["bits"], int) + if not file_info.get("colors", 0): + file_info["colors"] = 1 << file_info["bits"] + assert isinstance(file_info["palette_padding"], int) + assert isinstance(file_info["colors"], int) + if offset == 14 + file_info["header_size"] and file_info["bits"] <= 8: + offset += file_info["palette_padding"] * file_info["colors"] + + # ---------------------- Check bit depth for unusual unsupported values + self._mode, raw_mode = BIT2MODE.get(file_info["bits"], ("", "")) + if not self.mode: + msg = f"Unsupported BMP pixel depth ({file_info['bits']})" + raise OSError(msg) + + # ---------------- Process BMP with Bitfields compression (not palette) + decoder_name = "raw" + if file_info["compression"] == self.COMPRESSIONS["BITFIELDS"]: + SUPPORTED: dict[int, list[tuple[int, ...]]] = { + 32: [ + (0xFF0000, 0xFF00, 0xFF, 0x0), + (0xFF000000, 0xFF0000, 0xFF00, 0x0), + (0xFF000000, 0xFF00, 0xFF, 0x0), + (0xFF000000, 0xFF0000, 0xFF00, 0xFF), + (0xFF, 0xFF00, 0xFF0000, 0xFF000000), + (0xFF0000, 0xFF00, 0xFF, 0xFF000000), + (0xFF000000, 0xFF00, 0xFF, 0xFF0000), + (0x0, 0x0, 0x0, 0x0), + ], + 24: [(0xFF0000, 0xFF00, 0xFF)], + 16: [(0xF800, 0x7E0, 0x1F), (0x7C00, 0x3E0, 0x1F)], + } + MASK_MODES = { + (32, (0xFF0000, 0xFF00, 0xFF, 0x0)): "BGRX", + (32, (0xFF000000, 0xFF0000, 0xFF00, 0x0)): "XBGR", + (32, (0xFF000000, 0xFF00, 0xFF, 0x0)): "BGXR", + (32, (0xFF000000, 0xFF0000, 0xFF00, 0xFF)): "ABGR", + (32, (0xFF, 0xFF00, 0xFF0000, 0xFF000000)): "RGBA", + (32, (0xFF0000, 0xFF00, 0xFF, 0xFF000000)): "BGRA", + (32, (0xFF000000, 0xFF00, 0xFF, 0xFF0000)): "BGAR", + (32, (0x0, 0x0, 0x0, 0x0)): "BGRA", + (24, (0xFF0000, 0xFF00, 0xFF)): "BGR", + (16, (0xF800, 0x7E0, 0x1F)): "BGR;16", + (16, (0x7C00, 0x3E0, 0x1F)): "BGR;15", + } + if file_info["bits"] in SUPPORTED: + if ( + file_info["bits"] == 32 + and file_info["rgba_mask"] in SUPPORTED[file_info["bits"]] + ): + assert isinstance(file_info["rgba_mask"], tuple) + raw_mode = MASK_MODES[(file_info["bits"], file_info["rgba_mask"])] + self._mode = "RGBA" if "A" in raw_mode else self.mode + elif ( + file_info["bits"] in (24, 16) + and file_info["rgb_mask"] in SUPPORTED[file_info["bits"]] + ): + assert isinstance(file_info["rgb_mask"], tuple) + raw_mode = MASK_MODES[(file_info["bits"], file_info["rgb_mask"])] + else: + msg = "Unsupported BMP bitfields layout" + raise OSError(msg) + else: + msg = "Unsupported BMP bitfields layout" + raise OSError(msg) + elif file_info["compression"] == self.COMPRESSIONS["RAW"]: + if file_info["bits"] == 32 and ( + header == 22 or USE_RAW_ALPHA # 32-bit .cur offset + ): + raw_mode, self._mode = "BGRA", "RGBA" + elif file_info["compression"] in ( + self.COMPRESSIONS["RLE8"], + self.COMPRESSIONS["RLE4"], + ): + decoder_name = "bmp_rle" + else: + msg = f"Unsupported BMP compression ({file_info['compression']})" + raise OSError(msg) + + # --------------- Once the header is processed, process the palette/LUT + if self.mode == "P": # Paletted for 1, 4 and 8 bit images + # ---------------------------------------------------- 1-bit images + if not (0 < file_info["colors"] <= 65536): + msg = f"Unsupported BMP Palette size ({file_info['colors']})" + raise OSError(msg) + else: + padding = file_info["palette_padding"] + palette = read(padding * file_info["colors"]) + grayscale = True + indices = ( + (0, 255) + if file_info["colors"] == 2 + else list(range(file_info["colors"])) + ) + + # ----------------- Check if grayscale and ignore palette if so + for ind, val in enumerate(indices): + rgb = palette[ind * padding : ind * padding + 3] + if rgb != o8(val) * 3: + grayscale = False + + # ------- If all colors are gray, white or black, ditch palette + if grayscale: + self._mode = "1" if file_info["colors"] == 2 else "L" + raw_mode = self.mode + else: + self._mode = "P" + self.palette = ImagePalette.raw( + "BGRX" if padding == 4 else "BGR", palette + ) + + # ---------------------------- Finally set the tile data for the plugin + self.info["compression"] = file_info["compression"] + args: list[Any] = [raw_mode] + if decoder_name == "bmp_rle": + args.append(file_info["compression"] == self.COMPRESSIONS["RLE4"]) + else: + assert isinstance(file_info["width"], int) + args.append(((file_info["width"] * file_info["bits"] + 31) >> 3) & (~3)) + args.append(file_info["direction"]) + self.tile = [ + ImageFile._Tile( + decoder_name, + (0, 0, file_info["width"], file_info["height"]), + offset or self.fp.tell(), + tuple(args), + ) + ] + + def _open(self) -> None: + """Open file, check magic number and read header""" + # read 14 bytes: magic number, filesize, reserved, header final offset + assert self.fp is not None + head_data = self.fp.read(14) + # choke if the file does not have the required magic bytes + if not _accept(head_data): + msg = "Not a BMP file" + raise SyntaxError(msg) + # read the start position of the BMP image data (u32) + offset = i32(head_data, 10) + # load bitmap information (offset=raster info) + self._bitmap(offset=offset) + + +class BmpRleDecoder(ImageFile.PyDecoder): + _pulls_fd = True + + def decode(self, buffer: bytes | Image.SupportsArrayInterface) -> tuple[int, int]: + assert self.fd is not None + rle4 = self.args[1] + data = bytearray() + x = 0 + dest_length = self.state.xsize * self.state.ysize + while len(data) < dest_length: + pixels = self.fd.read(1) + byte = self.fd.read(1) + if not pixels or not byte: + break + num_pixels = pixels[0] + if num_pixels: + # encoded mode + if x + num_pixels > self.state.xsize: + # Too much data for row + num_pixels = max(0, self.state.xsize - x) + if rle4: + first_pixel = o8(byte[0] >> 4) + second_pixel = o8(byte[0] & 0x0F) + for index in range(num_pixels): + if index % 2 == 0: + data += first_pixel + else: + data += second_pixel + else: + data += byte * num_pixels + x += num_pixels + else: + if byte[0] == 0: + # end of line + while len(data) % self.state.xsize != 0: + data += b"\x00" + x = 0 + elif byte[0] == 1: + # end of bitmap + break + elif byte[0] == 2: + # delta + bytes_read = self.fd.read(2) + if len(bytes_read) < 2: + break + right, up = bytes_read + data += b"\x00" * (right + up * self.state.xsize) + x = len(data) % self.state.xsize + else: + # absolute mode + if rle4: + # 2 pixels per byte + byte_count = byte[0] // 2 + bytes_read = self.fd.read(byte_count) + for byte_read in bytes_read: + data += o8(byte_read >> 4) + data += o8(byte_read & 0x0F) + else: + byte_count = byte[0] + bytes_read = self.fd.read(byte_count) + data += bytes_read + if len(bytes_read) < byte_count: + break + x += byte[0] + + # align to 16-bit word boundary + if self.fd.tell() % 2 != 0: + self.fd.seek(1, os.SEEK_CUR) + rawmode = "L" if self.mode == "L" else "P" + self.set_as_raw(bytes(data), rawmode, (0, self.args[-1])) + return -1, 0 + + +# ============================================================================= +# Image plugin for the DIB format (BMP alias) +# ============================================================================= +class DibImageFile(BmpImageFile): + format = "DIB" + format_description = "Windows Bitmap" + + def _open(self) -> None: + self._bitmap() + + +# +# -------------------------------------------------------------------- +# Write BMP file + + +SAVE = { + "1": ("1", 1, 2), + "L": ("L", 8, 256), + "P": ("P", 8, 256), + "RGB": ("BGR", 24, 0), + "RGBA": ("BGRA", 32, 0), +} + + +def _dib_save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None: + _save(im, fp, filename, False) + + +def _save( + im: Image.Image, fp: IO[bytes], filename: str | bytes, bitmap_header: bool = True +) -> None: + try: + rawmode, bits, colors = SAVE[im.mode] + except KeyError as e: + msg = f"cannot write mode {im.mode} as BMP" + raise OSError(msg) from e + + info = im.encoderinfo + + dpi = info.get("dpi", (96, 96)) + + # 1 meter == 39.3701 inches + ppm = tuple(int(x * 39.3701 + 0.5) for x in dpi) + + stride = ((im.size[0] * bits + 7) // 8 + 3) & (~3) + header = 40 # or 64 for OS/2 version 2 + image = stride * im.size[1] + + if im.mode == "1": + palette = b"".join(o8(i) * 3 + b"\x00" for i in (0, 255)) + elif im.mode == "L": + palette = b"".join(o8(i) * 3 + b"\x00" for i in range(256)) + elif im.mode == "P": + palette = im.im.getpalette("RGB", "BGRX") + colors = len(palette) // 4 + else: + palette = None + + # bitmap header + if bitmap_header: + offset = 14 + header + colors * 4 + file_size = offset + image + if file_size > 2**32 - 1: + msg = "File size is too large for the BMP format" + raise ValueError(msg) + fp.write( + b"BM" # file type (magic) + + o32(file_size) # file size + + o32(0) # reserved + + o32(offset) # image data offset + ) + + # bitmap info header + fp.write( + o32(header) # info header size + + o32(im.size[0]) # width + + o32(im.size[1]) # height + + o16(1) # planes + + o16(bits) # depth + + o32(0) # compression (0=uncompressed) + + o32(image) # size of bitmap + + o32(ppm[0]) # resolution + + o32(ppm[1]) # resolution + + o32(colors) # colors used + + o32(colors) # colors important + ) + + fp.write(b"\0" * (header - 40)) # padding (for OS/2 format) + + if palette: + fp.write(palette) + + ImageFile._save( + im, fp, [ImageFile._Tile("raw", (0, 0) + im.size, 0, (rawmode, stride, -1))] + ) + + +# +# -------------------------------------------------------------------- +# Registry + + +Image.register_open(BmpImageFile.format, BmpImageFile, _accept) +Image.register_save(BmpImageFile.format, _save) + +Image.register_extension(BmpImageFile.format, ".bmp") + +Image.register_mime(BmpImageFile.format, "image/bmp") + +Image.register_decoder("bmp_rle", BmpRleDecoder) + +Image.register_open(DibImageFile.format, DibImageFile, _dib_accept) +Image.register_save(DibImageFile.format, _dib_save) + +Image.register_extension(DibImageFile.format, ".dib") + +Image.register_mime(DibImageFile.format, "image/bmp") diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/BufrStubImagePlugin.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/BufrStubImagePlugin.py new file mode 100644 index 000000000..d82c4c746 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/BufrStubImagePlugin.py @@ -0,0 +1,72 @@ +# +# The Python Imaging Library +# $Id$ +# +# BUFR stub adapter +# +# Copyright (c) 1996-2003 by Fredrik Lundh +# +# See the README file for information on usage and redistribution. +# +from __future__ import annotations + +import os +from typing import IO + +from . import Image, ImageFile + +_handler = None + + +def register_handler(handler: ImageFile.StubHandler | None) -> None: + """ + Install application-specific BUFR image handler. + + :param handler: Handler object. + """ + global _handler + _handler = handler + + +# -------------------------------------------------------------------- +# Image adapter + + +def _accept(prefix: bytes) -> bool: + return prefix.startswith((b"BUFR", b"ZCZC")) + + +class BufrStubImageFile(ImageFile.StubImageFile): + format = "BUFR" + format_description = "BUFR" + + def _open(self) -> None: + assert self.fp is not None + if not _accept(self.fp.read(4)): + msg = "Not a BUFR file" + raise SyntaxError(msg) + + self.fp.seek(-4, os.SEEK_CUR) + + # make something up + self._mode = "F" + self._size = 1, 1 + + def _load(self) -> ImageFile.StubHandler | None: + return _handler + + +def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None: + if _handler is None or not hasattr(_handler, "save"): + msg = "BUFR save handler not installed" + raise OSError(msg) + _handler.save(im, fp, filename) + + +# -------------------------------------------------------------------- +# Registry + +Image.register_open(BufrStubImageFile.format, BufrStubImageFile, _accept) +Image.register_save(BufrStubImageFile.format, _save) + +Image.register_extension(BufrStubImageFile.format, ".bufr") diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/ContainerIO.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/ContainerIO.py new file mode 100644 index 000000000..ec9e66c71 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/ContainerIO.py @@ -0,0 +1,173 @@ +# +# The Python Imaging Library. +# $Id$ +# +# a class to read from a container file +# +# History: +# 1995-06-18 fl Created +# 1995-09-07 fl Added readline(), readlines() +# +# Copyright (c) 1997-2001 by Secret Labs AB +# Copyright (c) 1995 by Fredrik Lundh +# +# See the README file for information on usage and redistribution. +# +from __future__ import annotations + +import io +from collections.abc import Iterable +from typing import IO, AnyStr, NoReturn + + +class ContainerIO(IO[AnyStr]): + """ + A file object that provides read access to a part of an existing + file (for example a TAR file). + """ + + def __init__(self, file: IO[AnyStr], offset: int, length: int) -> None: + """ + Create file object. + + :param file: Existing file. + :param offset: Start of region, in bytes. + :param length: Size of region, in bytes. + """ + self.fh: IO[AnyStr] = file + self.pos = 0 + self.offset = offset + self.length = length + self.fh.seek(offset) + + ## + # Always false. + + def isatty(self) -> bool: + return False + + def seekable(self) -> bool: + return True + + def seek(self, offset: int, mode: int = io.SEEK_SET) -> int: + """ + Move file pointer. + + :param offset: Offset in bytes. + :param mode: Starting position. Use 0 for beginning of region, 1 + for current offset, and 2 for end of region. You cannot move + the pointer outside the defined region. + :returns: Offset from start of region, in bytes. + """ + if mode == 1: + self.pos = self.pos + offset + elif mode == 2: + self.pos = self.length + offset + else: + self.pos = offset + # clamp + self.pos = max(0, min(self.pos, self.length)) + self.fh.seek(self.offset + self.pos) + return self.pos + + def tell(self) -> int: + """ + Get current file pointer. + + :returns: Offset from start of region, in bytes. + """ + return self.pos + + def readable(self) -> bool: + return True + + def read(self, n: int = -1) -> AnyStr: + """ + Read data. + + :param n: Number of bytes to read. If omitted, zero or negative, + read until end of region. + :returns: An 8-bit string. + """ + if n > 0: + n = min(n, self.length - self.pos) + else: + n = self.length - self.pos + if n <= 0: # EOF + return b"" if "b" in self.fh.mode else "" # type: ignore[return-value] + self.pos = self.pos + n + return self.fh.read(n) + + def readline(self, n: int = -1) -> AnyStr: + """ + Read a line of text. + + :param n: Number of bytes to read. If omitted, zero or negative, + read until end of line. + :returns: An 8-bit string. + """ + s: AnyStr = b"" if "b" in self.fh.mode else "" # type: ignore[assignment] + newline_character = b"\n" if "b" in self.fh.mode else "\n" + while True: + c = self.read(1) + if not c: + break + s = s + c + if c == newline_character or len(s) == n: + break + return s + + def readlines(self, n: int | None = -1) -> list[AnyStr]: + """ + Read multiple lines of text. + + :param n: Number of lines to read. If omitted, zero, negative or None, + read until end of region. + :returns: A list of 8-bit strings. + """ + lines = [] + while True: + s = self.readline() + if not s: + break + lines.append(s) + if len(lines) == n: + break + return lines + + def writable(self) -> bool: + return False + + def write(self, b: AnyStr) -> NoReturn: + raise NotImplementedError() + + def writelines(self, lines: Iterable[AnyStr]) -> NoReturn: + raise NotImplementedError() + + def truncate(self, size: int | None = None) -> int: + raise NotImplementedError() + + def __enter__(self) -> ContainerIO[AnyStr]: + return self + + def __exit__(self, *args: object) -> None: + self.close() + + def __iter__(self) -> ContainerIO[AnyStr]: + return self + + def __next__(self) -> AnyStr: + line = self.readline() + if not line: + msg = "end of region" + raise StopIteration(msg) + return line + + def fileno(self) -> int: + return self.fh.fileno() + + def flush(self) -> None: + self.fh.flush() + + def close(self) -> None: + self.fh.close() diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/CurImagePlugin.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/CurImagePlugin.py new file mode 100644 index 000000000..9c188e084 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/CurImagePlugin.py @@ -0,0 +1,75 @@ +# +# The Python Imaging Library. +# $Id$ +# +# Windows Cursor support for PIL +# +# notes: +# uses BmpImagePlugin.py to read the bitmap data. +# +# history: +# 96-05-27 fl Created +# +# Copyright (c) Secret Labs AB 1997. +# Copyright (c) Fredrik Lundh 1996. +# +# See the README file for information on usage and redistribution. +# +from __future__ import annotations + +from . import BmpImagePlugin, Image +from ._binary import i16le as i16 +from ._binary import i32le as i32 + +# +# -------------------------------------------------------------------- + + +def _accept(prefix: bytes) -> bool: + return prefix.startswith(b"\0\0\2\0") + + +## +# Image plugin for Windows Cursor files. + + +class CurImageFile(BmpImagePlugin.BmpImageFile): + format = "CUR" + format_description = "Windows Cursor" + + def _open(self) -> None: + assert self.fp is not None + offset = self.fp.tell() + + # check magic + s = self.fp.read(6) + if not _accept(s): + msg = "not a CUR file" + raise SyntaxError(msg) + + # pick the largest cursor in the file + m = b"" + for i in range(i16(s, 4)): + s = self.fp.read(16) + if not m: + m = s + elif s[0] > m[0] and s[1] > m[1]: + m = s + if not m: + msg = "No cursors were found" + raise TypeError(msg) + + # load as bitmap + self._bitmap(i32(m, 12) + offset) + + # patch up the bitmap height + self._size = self.size[0], self.size[1] // 2 + self.tile = [self.tile[0]._replace(extents=(0, 0) + self.size)] + + +# +# -------------------------------------------------------------------- + +Image.register_open(CurImageFile.format, CurImageFile, _accept) + +Image.register_extension(CurImageFile.format, ".cur") diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/DcxImagePlugin.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/DcxImagePlugin.py new file mode 100644 index 000000000..d3f456ddc --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/DcxImagePlugin.py @@ -0,0 +1,84 @@ +# +# The Python Imaging Library. +# $Id$ +# +# DCX file handling +# +# DCX is a container file format defined by Intel, commonly used +# for fax applications. Each DCX file consists of a directory +# (a list of file offsets) followed by a set of (usually 1-bit) +# PCX files. +# +# History: +# 1995-09-09 fl Created +# 1996-03-20 fl Properly derived from PcxImageFile. +# 1998-07-15 fl Renamed offset attribute to avoid name clash +# 2002-07-30 fl Fixed file handling +# +# Copyright (c) 1997-98 by Secret Labs AB. +# Copyright (c) 1995-96 by Fredrik Lundh. +# +# See the README file for information on usage and redistribution. +# +from __future__ import annotations + +from . import Image +from ._binary import i32le as i32 +from ._util import DeferredError +from .PcxImagePlugin import PcxImageFile + +MAGIC = 0x3ADE68B1 # QUIZ: what's this value, then? + + +def _accept(prefix: bytes) -> bool: + return len(prefix) >= 4 and i32(prefix) == MAGIC + + +## +# Image plugin for the Intel DCX format. + + +class DcxImageFile(PcxImageFile): + format = "DCX" + format_description = "Intel DCX" + _close_exclusive_fp_after_loading = False + + def _open(self) -> None: + # Header + assert self.fp is not None + s = self.fp.read(4) + if not _accept(s): + msg = "not a DCX file" + raise SyntaxError(msg) + + # Component directory + self._offset = [] + for i in range(1024): + offset = i32(self.fp.read(4)) + if not offset: + break + self._offset.append(offset) + + self._fp = self.fp + self.frame = -1 + self.n_frames = len(self._offset) + self.is_animated = self.n_frames > 1 + self.seek(0) + + def seek(self, frame: int) -> None: + if not self._seek_check(frame): + return + if isinstance(self._fp, DeferredError): + raise self._fp.ex + self.frame = frame + self.fp = self._fp + self.fp.seek(self._offset[frame]) + PcxImageFile._open(self) + + def tell(self) -> int: + return self.frame + + +Image.register_open(DcxImageFile.format, DcxImageFile, _accept) + +Image.register_extension(DcxImageFile.format, ".dcx") diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/DdsImagePlugin.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/DdsImagePlugin.py new file mode 100644 index 000000000..312f602a6 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/DdsImagePlugin.py @@ -0,0 +1,625 @@ +""" +A Pillow plugin for .dds files (S3TC-compressed aka DXTC) +Jerome Leclanche + +Documentation: +https://web.archive.org/web/20170802060935/http://oss.sgi.com/projects/ogl-sample/registry/EXT/texture_compression_s3tc.txt + +The contents of this file are hereby released in the public domain (CC0) +Full text of the CC0 license: +https://creativecommons.org/publicdomain/zero/1.0/ +""" + +from __future__ import annotations + +import struct +import sys +from enum import IntEnum, IntFlag +from typing import IO + +from . import Image, ImageFile, ImagePalette +from ._binary import i32le as i32 +from ._binary import o8 +from ._binary import o32le as o32 + +# Magic ("DDS ") +DDS_MAGIC = 0x20534444 + + +# DDS flags +class DDSD(IntFlag): + CAPS = 0x1 + HEIGHT = 0x2 + WIDTH = 0x4 + PITCH = 0x8 + PIXELFORMAT = 0x1000 + MIPMAPCOUNT = 0x20000 + LINEARSIZE = 0x80000 + DEPTH = 0x800000 + + +# DDS caps +class DDSCAPS(IntFlag): + COMPLEX = 0x8 + TEXTURE = 0x1000 + MIPMAP = 0x400000 + + +class DDSCAPS2(IntFlag): + CUBEMAP = 0x200 + CUBEMAP_POSITIVEX = 0x400 + CUBEMAP_NEGATIVEX = 0x800 + CUBEMAP_POSITIVEY = 0x1000 + CUBEMAP_NEGATIVEY = 0x2000 + CUBEMAP_POSITIVEZ = 0x4000 + CUBEMAP_NEGATIVEZ = 0x8000 + VOLUME = 0x200000 + + +# Pixel Format +class DDPF(IntFlag): + ALPHAPIXELS = 0x1 + ALPHA = 0x2 + FOURCC = 0x4 + PALETTEINDEXED8 = 0x20 + RGB = 0x40 + LUMINANCE = 0x20000 + + +# dxgiformat.h +class DXGI_FORMAT(IntEnum): + UNKNOWN = 0 + R32G32B32A32_TYPELESS = 1 + R32G32B32A32_FLOAT = 2 + R32G32B32A32_UINT = 3 + R32G32B32A32_SINT = 4 + R32G32B32_TYPELESS = 5 + R32G32B32_FLOAT = 6 + R32G32B32_UINT = 7 + R32G32B32_SINT = 8 + R16G16B16A16_TYPELESS = 9 + R16G16B16A16_FLOAT = 10 + R16G16B16A16_UNORM = 11 + R16G16B16A16_UINT = 12 + R16G16B16A16_SNORM = 13 + R16G16B16A16_SINT = 14 + R32G32_TYPELESS = 15 + R32G32_FLOAT = 16 + R32G32_UINT = 17 + R32G32_SINT = 18 + R32G8X24_TYPELESS = 19 + D32_FLOAT_S8X24_UINT = 20 + R32_FLOAT_X8X24_TYPELESS = 21 + X32_TYPELESS_G8X24_UINT = 22 + R10G10B10A2_TYPELESS = 23 + R10G10B10A2_UNORM = 24 + R10G10B10A2_UINT = 25 + R11G11B10_FLOAT = 26 + R8G8B8A8_TYPELESS = 27 + R8G8B8A8_UNORM = 28 + R8G8B8A8_UNORM_SRGB = 29 + R8G8B8A8_UINT = 30 + R8G8B8A8_SNORM = 31 + R8G8B8A8_SINT = 32 + R16G16_TYPELESS = 33 + R16G16_FLOAT = 34 + R16G16_UNORM = 35 + R16G16_UINT = 36 + R16G16_SNORM = 37 + R16G16_SINT = 38 + R32_TYPELESS = 39 + D32_FLOAT = 40 + R32_FLOAT = 41 + R32_UINT = 42 + R32_SINT = 43 + R24G8_TYPELESS = 44 + D24_UNORM_S8_UINT = 45 + R24_UNORM_X8_TYPELESS = 46 + X24_TYPELESS_G8_UINT = 47 + R8G8_TYPELESS = 48 + R8G8_UNORM = 49 + R8G8_UINT = 50 + R8G8_SNORM = 51 + R8G8_SINT = 52 + R16_TYPELESS = 53 + R16_FLOAT = 54 + D16_UNORM = 55 + R16_UNORM = 56 + R16_UINT = 57 + R16_SNORM = 58 + R16_SINT = 59 + R8_TYPELESS = 60 + R8_UNORM = 61 + R8_UINT = 62 + R8_SNORM = 63 + R8_SINT = 64 + A8_UNORM = 65 + R1_UNORM = 66 + R9G9B9E5_SHAREDEXP = 67 + R8G8_B8G8_UNORM = 68 + G8R8_G8B8_UNORM = 69 + BC1_TYPELESS = 70 + BC1_UNORM = 71 + BC1_UNORM_SRGB = 72 + BC2_TYPELESS = 73 + BC2_UNORM = 74 + BC2_UNORM_SRGB = 75 + BC3_TYPELESS = 76 + BC3_UNORM = 77 + BC3_UNORM_SRGB = 78 + BC4_TYPELESS = 79 + BC4_UNORM = 80 + BC4_SNORM = 81 + BC5_TYPELESS = 82 + BC5_UNORM = 83 + BC5_SNORM = 84 + B5G6R5_UNORM = 85 + B5G5R5A1_UNORM = 86 + B8G8R8A8_UNORM = 87 + B8G8R8X8_UNORM = 88 + R10G10B10_XR_BIAS_A2_UNORM = 89 + B8G8R8A8_TYPELESS = 90 + B8G8R8A8_UNORM_SRGB = 91 + B8G8R8X8_TYPELESS = 92 + B8G8R8X8_UNORM_SRGB = 93 + BC6H_TYPELESS = 94 + BC6H_UF16 = 95 + BC6H_SF16 = 96 + BC7_TYPELESS = 97 + BC7_UNORM = 98 + BC7_UNORM_SRGB = 99 + AYUV = 100 + Y410 = 101 + Y416 = 102 + NV12 = 103 + P010 = 104 + P016 = 105 + OPAQUE_420 = 106 + YUY2 = 107 + Y210 = 108 + Y216 = 109 + NV11 = 110 + AI44 = 111 + IA44 = 112 + P8 = 113 + A8P8 = 114 + B4G4R4A4_UNORM = 115 + P208 = 130 + V208 = 131 + V408 = 132 + SAMPLER_FEEDBACK_MIN_MIP_OPAQUE = 189 + SAMPLER_FEEDBACK_MIP_REGION_USED_OPAQUE = 190 + + +class D3DFMT(IntEnum): + UNKNOWN = 0 + R8G8B8 = 20 + A8R8G8B8 = 21 + X8R8G8B8 = 22 + R5G6B5 = 23 + X1R5G5B5 = 24 + A1R5G5B5 = 25 + A4R4G4B4 = 26 + R3G3B2 = 27 + A8 = 28 + A8R3G3B2 = 29 + X4R4G4B4 = 30 + A2B10G10R10 = 31 + A8B8G8R8 = 32 + X8B8G8R8 = 33 + G16R16 = 34 + A2R10G10B10 = 35 + A16B16G16R16 = 36 + A8P8 = 40 + P8 = 41 + L8 = 50 + A8L8 = 51 + A4L4 = 52 + V8U8 = 60 + L6V5U5 = 61 + X8L8V8U8 = 62 + Q8W8V8U8 = 63 + V16U16 = 64 + A2W10V10U10 = 67 + D16_LOCKABLE = 70 + D32 = 71 + D15S1 = 73 + D24S8 = 75 + D24X8 = 77 + D24X4S4 = 79 + D16 = 80 + D32F_LOCKABLE = 82 + D24FS8 = 83 + D32_LOCKABLE = 84 + S8_LOCKABLE = 85 + L16 = 81 + VERTEXDATA = 100 + INDEX16 = 101 + INDEX32 = 102 + Q16W16V16U16 = 110 + R16F = 111 + G16R16F = 112 + A16B16G16R16F = 113 + R32F = 114 + G32R32F = 115 + A32B32G32R32F = 116 + CxV8U8 = 117 + A1 = 118 + A2B10G10R10_XR_BIAS = 119 + BINARYBUFFER = 199 + + UYVY = i32(b"UYVY") + R8G8_B8G8 = i32(b"RGBG") + YUY2 = i32(b"YUY2") + G8R8_G8B8 = i32(b"GRGB") + DXT1 = i32(b"DXT1") + DXT2 = i32(b"DXT2") + DXT3 = i32(b"DXT3") + DXT4 = i32(b"DXT4") + DXT5 = i32(b"DXT5") + DX10 = i32(b"DX10") + BC4S = i32(b"BC4S") + BC4U = i32(b"BC4U") + BC5S = i32(b"BC5S") + BC5U = i32(b"BC5U") + ATI1 = i32(b"ATI1") + ATI2 = i32(b"ATI2") + MULTI2_ARGB8 = i32(b"MET1") + + +# Backward compatibility layer +module = sys.modules[__name__] +for item in DDSD: + assert item.name is not None + setattr(module, f"DDSD_{item.name}", item.value) +for item1 in DDSCAPS: + assert item1.name is not None + setattr(module, f"DDSCAPS_{item1.name}", item1.value) +for item2 in DDSCAPS2: + assert item2.name is not None + setattr(module, f"DDSCAPS2_{item2.name}", item2.value) +for item3 in DDPF: + assert item3.name is not None + setattr(module, f"DDPF_{item3.name}", item3.value) + +DDS_FOURCC = DDPF.FOURCC +DDS_RGB = DDPF.RGB +DDS_RGBA = DDPF.RGB | DDPF.ALPHAPIXELS +DDS_LUMINANCE = DDPF.LUMINANCE +DDS_LUMINANCEA = DDPF.LUMINANCE | DDPF.ALPHAPIXELS +DDS_ALPHA = DDPF.ALPHA +DDS_PAL8 = DDPF.PALETTEINDEXED8 + +DDS_HEADER_FLAGS_TEXTURE = DDSD.CAPS | DDSD.HEIGHT | DDSD.WIDTH | DDSD.PIXELFORMAT +DDS_HEADER_FLAGS_MIPMAP = DDSD.MIPMAPCOUNT +DDS_HEADER_FLAGS_VOLUME = DDSD.DEPTH +DDS_HEADER_FLAGS_PITCH = DDSD.PITCH +DDS_HEADER_FLAGS_LINEARSIZE = DDSD.LINEARSIZE + +DDS_HEIGHT = DDSD.HEIGHT +DDS_WIDTH = DDSD.WIDTH + +DDS_SURFACE_FLAGS_TEXTURE = DDSCAPS.TEXTURE +DDS_SURFACE_FLAGS_MIPMAP = DDSCAPS.COMPLEX | DDSCAPS.MIPMAP +DDS_SURFACE_FLAGS_CUBEMAP = DDSCAPS.COMPLEX + +DDS_CUBEMAP_POSITIVEX = DDSCAPS2.CUBEMAP | DDSCAPS2.CUBEMAP_POSITIVEX +DDS_CUBEMAP_NEGATIVEX = DDSCAPS2.CUBEMAP | DDSCAPS2.CUBEMAP_NEGATIVEX +DDS_CUBEMAP_POSITIVEY = DDSCAPS2.CUBEMAP | DDSCAPS2.CUBEMAP_POSITIVEY +DDS_CUBEMAP_NEGATIVEY = DDSCAPS2.CUBEMAP | DDSCAPS2.CUBEMAP_NEGATIVEY +DDS_CUBEMAP_POSITIVEZ = DDSCAPS2.CUBEMAP | DDSCAPS2.CUBEMAP_POSITIVEZ +DDS_CUBEMAP_NEGATIVEZ = DDSCAPS2.CUBEMAP | DDSCAPS2.CUBEMAP_NEGATIVEZ + +DXT1_FOURCC = D3DFMT.DXT1 +DXT3_FOURCC = D3DFMT.DXT3 +DXT5_FOURCC = D3DFMT.DXT5 + +DXGI_FORMAT_R8G8B8A8_TYPELESS = DXGI_FORMAT.R8G8B8A8_TYPELESS +DXGI_FORMAT_R8G8B8A8_UNORM = DXGI_FORMAT.R8G8B8A8_UNORM +DXGI_FORMAT_R8G8B8A8_UNORM_SRGB = DXGI_FORMAT.R8G8B8A8_UNORM_SRGB +DXGI_FORMAT_BC5_TYPELESS = DXGI_FORMAT.BC5_TYPELESS +DXGI_FORMAT_BC5_UNORM = DXGI_FORMAT.BC5_UNORM +DXGI_FORMAT_BC5_SNORM = DXGI_FORMAT.BC5_SNORM +DXGI_FORMAT_BC6H_UF16 = DXGI_FORMAT.BC6H_UF16 +DXGI_FORMAT_BC6H_SF16 = DXGI_FORMAT.BC6H_SF16 +DXGI_FORMAT_BC7_TYPELESS = DXGI_FORMAT.BC7_TYPELESS +DXGI_FORMAT_BC7_UNORM = DXGI_FORMAT.BC7_UNORM +DXGI_FORMAT_BC7_UNORM_SRGB = DXGI_FORMAT.BC7_UNORM_SRGB + + +class DdsImageFile(ImageFile.ImageFile): + format = "DDS" + format_description = "DirectDraw Surface" + + def _open(self) -> None: + assert self.fp is not None + if not _accept(self.fp.read(4)): + msg = "not a DDS file" + raise SyntaxError(msg) + (header_size,) = struct.unpack(" None: + pass + + +class DdsRgbDecoder(ImageFile.PyDecoder): + _pulls_fd = True + + def decode(self, buffer: bytes | Image.SupportsArrayInterface) -> tuple[int, int]: + assert self.fd is not None + bitcount, masks = self.args + + # Some masks will be padded with zeros, e.g. R 0b11 G 0b1100 + # Calculate how many zeros each mask is padded with + mask_offsets = [] + # And the maximum value of each channel without the padding + mask_totals = [] + for mask in masks: + offset = 0 + if mask != 0: + while mask >> (offset + 1) << (offset + 1) == mask: + offset += 1 + mask_offsets.append(offset) + mask_totals.append(mask >> offset) + + data = bytearray() + bytecount = bitcount // 8 + dest_length = self.state.xsize * self.state.ysize * len(masks) + while len(data) < dest_length: + value = int.from_bytes(self.fd.read(bytecount), "little") + for i, mask in enumerate(masks): + masked_value = value & mask + # Remove the zero padding, and scale it to 8 bits + data += o8( + int(((masked_value >> mask_offsets[i]) / mask_totals[i]) * 255) + if mask_totals[i] + else 0 + ) + self.set_as_raw(data) + return -1, 0 + + +def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None: + if im.mode not in ("RGB", "RGBA", "L", "LA"): + msg = f"cannot write mode {im.mode} as DDS" + raise OSError(msg) + + flags = DDSD.CAPS | DDSD.HEIGHT | DDSD.WIDTH | DDSD.PIXELFORMAT + bitcount = len(im.getbands()) * 8 + pixel_format = im.encoderinfo.get("pixel_format") + args: tuple[int] | str + if pixel_format: + codec_name = "bcn" + flags |= DDSD.LINEARSIZE + pitch = (im.width + 3) * 4 + rgba_mask = [0, 0, 0, 0] + pixel_flags = DDPF.FOURCC + if pixel_format == "DXT1": + fourcc = D3DFMT.DXT1 + args = (1,) + elif pixel_format == "DXT3": + fourcc = D3DFMT.DXT3 + args = (2,) + elif pixel_format == "DXT5": + fourcc = D3DFMT.DXT5 + args = (3,) + else: + fourcc = D3DFMT.DX10 + if pixel_format == "BC2": + args = (2,) + dxgi_format = DXGI_FORMAT.BC2_TYPELESS + elif pixel_format == "BC3": + args = (3,) + dxgi_format = DXGI_FORMAT.BC3_TYPELESS + elif pixel_format == "BC5": + args = (5,) + dxgi_format = DXGI_FORMAT.BC5_TYPELESS + if im.mode != "RGB": + msg = "only RGB mode can be written as BC5" + raise OSError(msg) + else: + msg = f"cannot write pixel format {pixel_format}" + raise OSError(msg) + else: + codec_name = "raw" + flags |= DDSD.PITCH + pitch = (im.width * bitcount + 7) // 8 + + alpha = im.mode[-1] == "A" + if im.mode[0] == "L": + pixel_flags = DDPF.LUMINANCE + args = im.mode + if alpha: + rgba_mask = [0x000000FF, 0x000000FF, 0x000000FF] + else: + rgba_mask = [0xFF000000, 0xFF000000, 0xFF000000] + else: + pixel_flags = DDPF.RGB + args = im.mode[::-1] + rgba_mask = [0x00FF0000, 0x0000FF00, 0x000000FF] + + if alpha: + r, g, b, a = im.split() + im = Image.merge("RGBA", (a, r, g, b)) + if alpha: + pixel_flags |= DDPF.ALPHAPIXELS + rgba_mask.append(0xFF000000 if alpha else 0) + + fourcc = D3DFMT.UNKNOWN + fp.write( + o32(DDS_MAGIC) + + struct.pack( + "<7I", + 124, # header size + flags, # flags + im.height, + im.width, + pitch, + 0, # depth + 0, # mipmaps + ) + + struct.pack("11I", *((0,) * 11)) # reserved + # pfsize, pfflags, fourcc, bitcount + + struct.pack("<4I", 32, pixel_flags, fourcc, bitcount) + + struct.pack("<4I", *rgba_mask) # dwRGBABitMask + + struct.pack("<5I", DDSCAPS.TEXTURE, 0, 0, 0, 0) + ) + if fourcc == D3DFMT.DX10: + fp.write( + # dxgi_format, 2D resource, misc, array size, straight alpha + struct.pack("<5I", dxgi_format, 3, 0, 0, 1) + ) + ImageFile._save(im, fp, [ImageFile._Tile(codec_name, (0, 0) + im.size, 0, args)]) + + +def _accept(prefix: bytes) -> bool: + return prefix.startswith(b"DDS ") + + +Image.register_open(DdsImageFile.format, DdsImageFile, _accept) +Image.register_decoder("dds_rgb", DdsRgbDecoder) +Image.register_save(DdsImageFile.format, _save) +Image.register_extension(DdsImageFile.format, ".dds") diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/EpsImagePlugin.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/EpsImagePlugin.py new file mode 100644 index 000000000..aeb7b0c93 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/EpsImagePlugin.py @@ -0,0 +1,481 @@ +# +# The Python Imaging Library. +# $Id$ +# +# EPS file handling +# +# History: +# 1995-09-01 fl Created (0.1) +# 1996-05-18 fl Don't choke on "atend" fields, Ghostscript interface (0.2) +# 1996-08-22 fl Don't choke on floating point BoundingBox values +# 1996-08-23 fl Handle files from Macintosh (0.3) +# 2001-02-17 fl Use 're' instead of 'regex' (Python 2.1) (0.4) +# 2003-09-07 fl Check gs.close status (from Federico Di Gregorio) (0.5) +# 2014-05-07 e Handling of EPS with binary preview and fixed resolution +# resizing +# +# Copyright (c) 1997-2003 by Secret Labs AB. +# Copyright (c) 1995-2003 by Fredrik Lundh +# +# See the README file for information on usage and redistribution. +# +from __future__ import annotations + +import io +import os +import re +import subprocess +import sys +import tempfile +from typing import IO + +from . import Image, ImageFile +from ._binary import i32le as i32 + +# -------------------------------------------------------------------- + + +split = re.compile(r"^%%([^:]*):[ \t]*(.*)[ \t]*$") +field = re.compile(r"^%[%!\w]([^:]*)[ \t]*$") + +gs_binary: str | bool | None = None +gs_windows_binary = None + + +def has_ghostscript() -> bool: + global gs_binary, gs_windows_binary + if gs_binary is None: + if sys.platform.startswith("win"): + if gs_windows_binary is None: + import shutil + + for binary in ("gswin32c", "gswin64c", "gs"): + if shutil.which(binary) is not None: + gs_windows_binary = binary + break + else: + gs_windows_binary = False + gs_binary = gs_windows_binary + else: + try: + subprocess.check_call(["gs", "--version"], stdout=subprocess.DEVNULL) + gs_binary = "gs" + except OSError: + gs_binary = False + return gs_binary is not False + + +def Ghostscript( + tile: list[ImageFile._Tile], + size: tuple[int, int], + fp: IO[bytes], + scale: int = 1, + transparency: bool = False, +) -> Image.core.ImagingCore: + """Render an image using Ghostscript""" + global gs_binary + if not has_ghostscript(): + msg = "Unable to locate Ghostscript on paths" + raise OSError(msg) + assert isinstance(gs_binary, str) + + # Unpack decoder tile + args = tile[0].args + assert isinstance(args, tuple) + length, bbox = args + + # Hack to support hi-res rendering + scale = int(scale) or 1 + width = size[0] * scale + height = size[1] * scale + # resolution is dependent on bbox and size + res_x = 72.0 * width / (bbox[2] - bbox[0]) + res_y = 72.0 * height / (bbox[3] - bbox[1]) + + out_fd, outfile = tempfile.mkstemp() + os.close(out_fd) + + infile_temp = None + if hasattr(fp, "name") and os.path.exists(fp.name): + infile = fp.name + else: + in_fd, infile_temp = tempfile.mkstemp() + os.close(in_fd) + infile = infile_temp + + # Ignore length and offset! + # Ghostscript can read it + # Copy whole file to read in Ghostscript + with open(infile_temp, "wb") as f: + # fetch length of fp + fp.seek(0, io.SEEK_END) + fsize = fp.tell() + # ensure start position + # go back + fp.seek(0) + lengthfile = fsize + while lengthfile > 0: + s = fp.read(min(lengthfile, 100 * 1024)) + if not s: + break + lengthfile -= len(s) + f.write(s) + + if transparency: + # "RGBA" + device = "pngalpha" + else: + # "pnmraw" automatically chooses between + # PBM ("1"), PGM ("L"), and PPM ("RGB"). + device = "pnmraw" + + # Build Ghostscript command + command = [ + gs_binary, + "-q", # quiet mode + f"-g{width:d}x{height:d}", # set output geometry (pixels) + f"-r{res_x:f}x{res_y:f}", # set input DPI (dots per inch) + "-dBATCH", # exit after processing + "-dNOPAUSE", # don't pause between pages + "-dSAFER", # safe mode + f"-sDEVICE={device}", + f"-sOutputFile={outfile}", # output file + # adjust for image origin + "-c", + f"{-bbox[0]} {-bbox[1]} translate", + "-f", + infile, # input file + # showpage (see https://bugs.ghostscript.com/show_bug.cgi?id=698272) + "-c", + "showpage", + ] + + # push data through Ghostscript + try: + startupinfo = None + if sys.platform.startswith("win"): + startupinfo = subprocess.STARTUPINFO() + startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW + subprocess.check_call(command, startupinfo=startupinfo) + with Image.open(outfile) as out_im: + out_im.load() + return out_im.im.copy() + finally: + try: + os.unlink(outfile) + if infile_temp: + os.unlink(infile_temp) + except OSError: + pass + + +def _accept(prefix: bytes) -> bool: + return prefix.startswith(b"%!PS") or ( + len(prefix) >= 4 and i32(prefix) == 0xC6D3D0C5 + ) + + +## +# Image plugin for Encapsulated PostScript. This plugin supports only +# a few variants of this format. + + +class EpsImageFile(ImageFile.ImageFile): + """EPS File Parser for the Python Imaging Library""" + + format = "EPS" + format_description = "Encapsulated Postscript" + + mode_map = {1: "L", 2: "LAB", 3: "RGB", 4: "CMYK"} + + def _open(self) -> None: + assert self.fp is not None + length, offset = self._find_offset(self.fp) + + # go to offset - start of "%!PS" + self.fp.seek(offset) + + self._mode = "RGB" + + # When reading header comments, the first comment is used. + # When reading trailer comments, the last comment is used. + bounding_box: list[int] | None = None + imagedata_size: tuple[int, int] | None = None + + byte_arr = bytearray(255) + bytes_mv = memoryview(byte_arr) + bytes_read = 0 + reading_header_comments = True + reading_trailer_comments = False + trailer_reached = False + + def check_required_header_comments() -> None: + """ + The EPS specification requires that some headers exist. + This should be checked when the header comments formally end, + when image data starts, or when the file ends, whichever comes first. + """ + if "PS-Adobe" not in self.info: + msg = 'EPS header missing "%!PS-Adobe" comment' + raise SyntaxError(msg) + if "BoundingBox" not in self.info: + msg = 'EPS header missing "%%BoundingBox" comment' + raise SyntaxError(msg) + + def read_comment(s: str) -> bool: + nonlocal bounding_box, reading_trailer_comments + try: + m = split.match(s) + except re.error as e: + msg = "not an EPS file" + raise SyntaxError(msg) from e + + if not m: + return False + + k, v = m.group(1, 2) + self.info[k] = v + if k == "BoundingBox": + if v == "(atend)": + reading_trailer_comments = True + elif not bounding_box or (trailer_reached and reading_trailer_comments): + try: + # Note: The DSC spec says that BoundingBox + # fields should be integers, but some drivers + # put floating point values there anyway. + bounding_box = [int(float(i)) for i in v.split()] + except Exception: + pass + return True + + while True: + byte = self.fp.read(1) + if byte == b"": + # if we didn't read a byte we must be at the end of the file + if bytes_read == 0: + if reading_header_comments: + check_required_header_comments() + break + elif byte in b"\r\n": + # if we read a line ending character, ignore it and parse what + # we have already read. if we haven't read any other characters, + # continue reading + if bytes_read == 0: + continue + else: + # ASCII/hexadecimal lines in an EPS file must not exceed + # 255 characters, not including line ending characters + if bytes_read >= 255: + # only enforce this for lines starting with a "%", + # otherwise assume it's binary data + if byte_arr[0] == ord("%"): + msg = "not an EPS file" + raise SyntaxError(msg) + else: + if reading_header_comments: + check_required_header_comments() + reading_header_comments = False + # reset bytes_read so we can keep reading + # data until the end of the line + bytes_read = 0 + byte_arr[bytes_read] = byte[0] + bytes_read += 1 + continue + + if reading_header_comments: + # Load EPS header + + # if this line doesn't start with a "%", + # or does start with "%%EndComments", + # then we've reached the end of the header/comments + if byte_arr[0] != ord("%") or bytes_mv[:13] == b"%%EndComments": + check_required_header_comments() + reading_header_comments = False + continue + + s = str(bytes_mv[:bytes_read], "latin-1") + if not read_comment(s): + m = field.match(s) + if m: + k = m.group(1) + if k.startswith("PS-Adobe"): + self.info["PS-Adobe"] = k[9:] + else: + self.info[k] = "" + elif s[0] == "%": + # handle non-DSC PostScript comments that some + # tools mistakenly put in the Comments section + pass + else: + msg = "bad EPS header" + raise OSError(msg) + elif bytes_mv[:11] == b"%ImageData:": + # Check for an "ImageData" descriptor + # https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/#50577413_pgfId-1035096 + + # If we've already read an "ImageData" descriptor, + # don't read another one. + if imagedata_size: + bytes_read = 0 + continue + + # Values: + # columns + # rows + # bit depth (1 or 8) + # mode (1: L, 2: LAB, 3: RGB, 4: CMYK) + # number of padding channels + # block size (number of bytes per row per channel) + # binary/ascii (1: binary, 2: ascii) + # data start identifier (the image data follows after a single line + # consisting only of this quoted value) + image_data_values = byte_arr[11:bytes_read].split(None, 7) + columns, rows, bit_depth, mode_id = ( + int(value) for value in image_data_values[:4] + ) + + if bit_depth == 1: + self._mode = "1" + elif bit_depth == 8: + try: + self._mode = self.mode_map[mode_id] + except ValueError: + break + else: + break + + # Parse the columns and rows after checking the bit depth and mode + # in case the bit depth and/or mode are invalid. + imagedata_size = columns, rows + elif bytes_mv[:5] == b"%%EOF": + break + elif trailer_reached and reading_trailer_comments: + # Load EPS trailer + s = str(bytes_mv[:bytes_read], "latin-1") + read_comment(s) + elif bytes_mv[:9] == b"%%Trailer": + trailer_reached = True + elif bytes_mv[:14] == b"%%BeginBinary:": + bytecount = int(byte_arr[14:bytes_read]) + self.fp.seek(bytecount, os.SEEK_CUR) + bytes_read = 0 + + # A "BoundingBox" is always required, + # even if an "ImageData" descriptor size exists. + if not bounding_box: + msg = "cannot determine EPS bounding box" + raise OSError(msg) + + # An "ImageData" size takes precedence over the "BoundingBox". + self._size = imagedata_size or ( + bounding_box[2] - bounding_box[0], + bounding_box[3] - bounding_box[1], + ) + + self.tile = [ + ImageFile._Tile("eps", (0, 0) + self.size, offset, (length, bounding_box)) + ] + + def _find_offset(self, fp: IO[bytes]) -> tuple[int, int]: + s = fp.read(4) + + if s == b"%!PS": + # for HEAD without binary preview + fp.seek(0, io.SEEK_END) + length = fp.tell() + offset = 0 + elif i32(s) == 0xC6D3D0C5: + # FIX for: Some EPS file not handled correctly / issue #302 + # EPS can contain binary data + # or start directly with latin coding + # more info see: + # https://web.archive.org/web/20160528181353/http://partners.adobe.com/public/developer/en/ps/5002.EPSF_Spec.pdf + s = fp.read(8) + offset = i32(s) + length = i32(s, 4) + else: + msg = "not an EPS file" + raise SyntaxError(msg) + + return length, offset + + def load( + self, scale: int = 1, transparency: bool = False + ) -> Image.core.PixelAccess | None: + # Load EPS via Ghostscript + if self.tile: + assert self.fp is not None + self.im = Ghostscript(self.tile, self.size, self.fp, scale, transparency) + self._mode = self.im.mode + self._size = self.im.size + self.tile = [] + return Image.Image.load(self) + + def load_seek(self, pos: int) -> None: + # we can't incrementally load, so force ImageFile.parser to + # use our custom load method by defining this method. + pass + + +# -------------------------------------------------------------------- + + +def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes, eps: int = 1) -> None: + """EPS Writer for the Python Imaging Library.""" + + # make sure image data is available + im.load() + + # determine PostScript image mode + if im.mode == "L": + operator = (8, 1, b"image") + elif im.mode == "RGB": + operator = (8, 3, b"false 3 colorimage") + elif im.mode == "CMYK": + operator = (8, 4, b"false 4 colorimage") + else: + msg = "image mode is not supported" + raise ValueError(msg) + + if eps: + # write EPS header + fp.write(b"%!PS-Adobe-3.0 EPSF-3.0\n") + fp.write(b"%%Creator: PIL 0.1 EpsEncode\n") + # fp.write("%%CreationDate: %s"...) + fp.write(b"%%%%BoundingBox: 0 0 %d %d\n" % im.size) + fp.write(b"%%Pages: 1\n") + fp.write(b"%%EndComments\n") + fp.write(b"%%Page: 1 1\n") + fp.write(b"%%ImageData: %d %d " % im.size) + fp.write(b'%d %d 0 1 1 "%s"\n' % operator) + + # image header + fp.write(b"gsave\n") + fp.write(b"10 dict begin\n") + fp.write(b"/buf %d string def\n" % (im.size[0] * operator[1])) + fp.write(b"%d %d scale\n" % im.size) + fp.write(b"%d %d 8\n" % im.size) # <= bits + fp.write(b"[%d 0 0 -%d 0 %d]\n" % (im.size[0], im.size[1], im.size[1])) + fp.write(b"{ currentfile buf readhexstring pop } bind\n") + fp.write(operator[2] + b"\n") + if hasattr(fp, "flush"): + fp.flush() + + ImageFile._save(im, fp, [ImageFile._Tile("eps", (0, 0) + im.size)]) + + fp.write(b"\n%%%%EndBinary\n") + fp.write(b"grestore end\n") + if hasattr(fp, "flush"): + fp.flush() + + +# -------------------------------------------------------------------- + + +Image.register_open(EpsImageFile.format, EpsImageFile, _accept) + +Image.register_save(EpsImageFile.format, _save) + +Image.register_extensions(EpsImageFile.format, [".ps", ".eps"]) + +Image.register_mime(EpsImageFile.format, "application/postscript") diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/ExifTags.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/ExifTags.py new file mode 100644 index 000000000..a9522e761 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/ExifTags.py @@ -0,0 +1,384 @@ +# +# The Python Imaging Library. +# $Id$ +# +# EXIF tags +# +# Copyright (c) 2003 by Secret Labs AB +# +# See the README file for information on usage and redistribution. +# + +""" +This module provides constants and clear-text names for various +well-known EXIF tags. +""" + +from __future__ import annotations + +from enum import IntEnum + + +class Base(IntEnum): + # possibly incomplete + InteropIndex = 0x0001 + ProcessingSoftware = 0x000B + NewSubfileType = 0x00FE + SubfileType = 0x00FF + ImageWidth = 0x0100 + ImageLength = 0x0101 + BitsPerSample = 0x0102 + Compression = 0x0103 + PhotometricInterpretation = 0x0106 + Thresholding = 0x0107 + CellWidth = 0x0108 + CellLength = 0x0109 + FillOrder = 0x010A + DocumentName = 0x010D + ImageDescription = 0x010E + Make = 0x010F + Model = 0x0110 + StripOffsets = 0x0111 + Orientation = 0x0112 + SamplesPerPixel = 0x0115 + RowsPerStrip = 0x0116 + StripByteCounts = 0x0117 + MinSampleValue = 0x0118 + MaxSampleValue = 0x0119 + XResolution = 0x011A + YResolution = 0x011B + PlanarConfiguration = 0x011C + PageName = 0x011D + FreeOffsets = 0x0120 + FreeByteCounts = 0x0121 + GrayResponseUnit = 0x0122 + GrayResponseCurve = 0x0123 + T4Options = 0x0124 + T6Options = 0x0125 + ResolutionUnit = 0x0128 + PageNumber = 0x0129 + TransferFunction = 0x012D + Software = 0x0131 + DateTime = 0x0132 + Artist = 0x013B + HostComputer = 0x013C + Predictor = 0x013D + WhitePoint = 0x013E + PrimaryChromaticities = 0x013F + ColorMap = 0x0140 + HalftoneHints = 0x0141 + TileWidth = 0x0142 + TileLength = 0x0143 + TileOffsets = 0x0144 + TileByteCounts = 0x0145 + SubIFDs = 0x014A + InkSet = 0x014C + InkNames = 0x014D + NumberOfInks = 0x014E + DotRange = 0x0150 + TargetPrinter = 0x0151 + ExtraSamples = 0x0152 + SampleFormat = 0x0153 + SMinSampleValue = 0x0154 + SMaxSampleValue = 0x0155 + TransferRange = 0x0156 + ClipPath = 0x0157 + XClipPathUnits = 0x0158 + YClipPathUnits = 0x0159 + Indexed = 0x015A + JPEGTables = 0x015B + OPIProxy = 0x015F + JPEGProc = 0x0200 + JpegIFOffset = 0x0201 + JpegIFByteCount = 0x0202 + JpegRestartInterval = 0x0203 + JpegLosslessPredictors = 0x0205 + JpegPointTransforms = 0x0206 + JpegQTables = 0x0207 + JpegDCTables = 0x0208 + JpegACTables = 0x0209 + YCbCrCoefficients = 0x0211 + YCbCrSubSampling = 0x0212 + YCbCrPositioning = 0x0213 + ReferenceBlackWhite = 0x0214 + XMLPacket = 0x02BC + RelatedImageFileFormat = 0x1000 + RelatedImageWidth = 0x1001 + RelatedImageLength = 0x1002 + Rating = 0x4746 + RatingPercent = 0x4749 + ImageID = 0x800D + CFARepeatPatternDim = 0x828D + BatteryLevel = 0x828F + Copyright = 0x8298 + ExposureTime = 0x829A + FNumber = 0x829D + IPTCNAA = 0x83BB + ImageResources = 0x8649 + ExifOffset = 0x8769 + InterColorProfile = 0x8773 + ExposureProgram = 0x8822 + SpectralSensitivity = 0x8824 + GPSInfo = 0x8825 + ISOSpeedRatings = 0x8827 + OECF = 0x8828 + Interlace = 0x8829 + TimeZoneOffset = 0x882A + SelfTimerMode = 0x882B + SensitivityType = 0x8830 + StandardOutputSensitivity = 0x8831 + RecommendedExposureIndex = 0x8832 + ISOSpeed = 0x8833 + ISOSpeedLatitudeyyy = 0x8834 + ISOSpeedLatitudezzz = 0x8835 + ExifVersion = 0x9000 + DateTimeOriginal = 0x9003 + DateTimeDigitized = 0x9004 + OffsetTime = 0x9010 + OffsetTimeOriginal = 0x9011 + OffsetTimeDigitized = 0x9012 + ComponentsConfiguration = 0x9101 + CompressedBitsPerPixel = 0x9102 + ShutterSpeedValue = 0x9201 + ApertureValue = 0x9202 + BrightnessValue = 0x9203 + ExposureBiasValue = 0x9204 + MaxApertureValue = 0x9205 + SubjectDistance = 0x9206 + MeteringMode = 0x9207 + LightSource = 0x9208 + Flash = 0x9209 + FocalLength = 0x920A + Noise = 0x920D + ImageNumber = 0x9211 + SecurityClassification = 0x9212 + ImageHistory = 0x9213 + TIFFEPStandardID = 0x9216 + MakerNote = 0x927C + UserComment = 0x9286 + SubsecTime = 0x9290 + SubsecTimeOriginal = 0x9291 + SubsecTimeDigitized = 0x9292 + AmbientTemperature = 0x9400 + Humidity = 0x9401 + Pressure = 0x9402 + WaterDepth = 0x9403 + Acceleration = 0x9404 + CameraElevationAngle = 0x9405 + XPTitle = 0x9C9B + XPComment = 0x9C9C + XPAuthor = 0x9C9D + XPKeywords = 0x9C9E + XPSubject = 0x9C9F + FlashPixVersion = 0xA000 + ColorSpace = 0xA001 + ExifImageWidth = 0xA002 + ExifImageHeight = 0xA003 + RelatedSoundFile = 0xA004 + ExifInteroperabilityOffset = 0xA005 + FlashEnergy = 0xA20B + SpatialFrequencyResponse = 0xA20C + FocalPlaneXResolution = 0xA20E + FocalPlaneYResolution = 0xA20F + FocalPlaneResolutionUnit = 0xA210 + SubjectLocation = 0xA214 + ExposureIndex = 0xA215 + SensingMethod = 0xA217 + FileSource = 0xA300 + SceneType = 0xA301 + CFAPattern = 0xA302 + CustomRendered = 0xA401 + ExposureMode = 0xA402 + WhiteBalance = 0xA403 + DigitalZoomRatio = 0xA404 + FocalLengthIn35mmFilm = 0xA405 + SceneCaptureType = 0xA406 + GainControl = 0xA407 + Contrast = 0xA408 + Saturation = 0xA409 + Sharpness = 0xA40A + DeviceSettingDescription = 0xA40B + SubjectDistanceRange = 0xA40C + ImageUniqueID = 0xA420 + CameraOwnerName = 0xA430 + BodySerialNumber = 0xA431 + LensSpecification = 0xA432 + LensMake = 0xA433 + LensModel = 0xA434 + LensSerialNumber = 0xA435 + CompositeImage = 0xA460 + CompositeImageCount = 0xA461 + CompositeImageExposureTimes = 0xA462 + Gamma = 0xA500 + PrintImageMatching = 0xC4A5 + DNGVersion = 0xC612 + DNGBackwardVersion = 0xC613 + UniqueCameraModel = 0xC614 + LocalizedCameraModel = 0xC615 + CFAPlaneColor = 0xC616 + CFALayout = 0xC617 + LinearizationTable = 0xC618 + BlackLevelRepeatDim = 0xC619 + BlackLevel = 0xC61A + BlackLevelDeltaH = 0xC61B + BlackLevelDeltaV = 0xC61C + WhiteLevel = 0xC61D + DefaultScale = 0xC61E + DefaultCropOrigin = 0xC61F + DefaultCropSize = 0xC620 + ColorMatrix1 = 0xC621 + ColorMatrix2 = 0xC622 + CameraCalibration1 = 0xC623 + CameraCalibration2 = 0xC624 + ReductionMatrix1 = 0xC625 + ReductionMatrix2 = 0xC626 + AnalogBalance = 0xC627 + AsShotNeutral = 0xC628 + AsShotWhiteXY = 0xC629 + BaselineExposure = 0xC62A + BaselineNoise = 0xC62B + BaselineSharpness = 0xC62C + BayerGreenSplit = 0xC62D + LinearResponseLimit = 0xC62E + CameraSerialNumber = 0xC62F + LensInfo = 0xC630 + ChromaBlurRadius = 0xC631 + AntiAliasStrength = 0xC632 + ShadowScale = 0xC633 + DNGPrivateData = 0xC634 + MakerNoteSafety = 0xC635 + CalibrationIlluminant1 = 0xC65A + CalibrationIlluminant2 = 0xC65B + BestQualityScale = 0xC65C + RawDataUniqueID = 0xC65D + OriginalRawFileName = 0xC68B + OriginalRawFileData = 0xC68C + ActiveArea = 0xC68D + MaskedAreas = 0xC68E + AsShotICCProfile = 0xC68F + AsShotPreProfileMatrix = 0xC690 + CurrentICCProfile = 0xC691 + CurrentPreProfileMatrix = 0xC692 + ColorimetricReference = 0xC6BF + CameraCalibrationSignature = 0xC6F3 + ProfileCalibrationSignature = 0xC6F4 + AsShotProfileName = 0xC6F6 + NoiseReductionApplied = 0xC6F7 + ProfileName = 0xC6F8 + ProfileHueSatMapDims = 0xC6F9 + ProfileHueSatMapData1 = 0xC6FA + ProfileHueSatMapData2 = 0xC6FB + ProfileToneCurve = 0xC6FC + ProfileEmbedPolicy = 0xC6FD + ProfileCopyright = 0xC6FE + ForwardMatrix1 = 0xC714 + ForwardMatrix2 = 0xC715 + PreviewApplicationName = 0xC716 + PreviewApplicationVersion = 0xC717 + PreviewSettingsName = 0xC718 + PreviewSettingsDigest = 0xC719 + PreviewColorSpace = 0xC71A + PreviewDateTime = 0xC71B + RawImageDigest = 0xC71C + OriginalRawFileDigest = 0xC71D + SubTileBlockSize = 0xC71E + RowInterleaveFactor = 0xC71F + ProfileLookTableDims = 0xC725 + ProfileLookTableData = 0xC726 + OpcodeList1 = 0xC740 + OpcodeList2 = 0xC741 + OpcodeList3 = 0xC74E + NoiseProfile = 0xC761 + FrameRate = 0xC764 + + +"""Maps EXIF tags to tag names.""" +TAGS = { + **{i.value: i.name for i in Base}, + 0x920C: "SpatialFrequencyResponse", + 0x9214: "SubjectLocation", + 0x9215: "ExposureIndex", + 0x828E: "CFAPattern", + 0x920B: "FlashEnergy", + 0x9216: "TIFF/EPStandardID", +} + + +class GPS(IntEnum): + GPSVersionID = 0x00 + GPSLatitudeRef = 0x01 + GPSLatitude = 0x02 + GPSLongitudeRef = 0x03 + GPSLongitude = 0x04 + GPSAltitudeRef = 0x05 + GPSAltitude = 0x06 + GPSTimeStamp = 0x07 + GPSSatellites = 0x08 + GPSStatus = 0x09 + GPSMeasureMode = 0x0A + GPSDOP = 0x0B + GPSSpeedRef = 0x0C + GPSSpeed = 0x0D + GPSTrackRef = 0x0E + GPSTrack = 0x0F + GPSImgDirectionRef = 0x10 + GPSImgDirection = 0x11 + GPSMapDatum = 0x12 + GPSDestLatitudeRef = 0x13 + GPSDestLatitude = 0x14 + GPSDestLongitudeRef = 0x15 + GPSDestLongitude = 0x16 + GPSDestBearingRef = 0x17 + GPSDestBearing = 0x18 + GPSDestDistanceRef = 0x19 + GPSDestDistance = 0x1A + GPSProcessingMethod = 0x1B + GPSAreaInformation = 0x1C + GPSDateStamp = 0x1D + GPSDifferential = 0x1E + GPSHPositioningError = 0x1F + + +"""Maps EXIF GPS tags to tag names.""" +GPSTAGS = {i.value: i.name for i in GPS} + + +class Interop(IntEnum): + InteropIndex = 0x0001 + InteropVersion = 0x0002 + RelatedImageFileFormat = 0x1000 + RelatedImageWidth = 0x1001 + RelatedImageHeight = 0x1002 + + +class IFD(IntEnum): + Exif = 0x8769 + GPSInfo = 0x8825 + MakerNote = 0x927C + Makernote = 0x927C # Deprecated + Interop = 0xA005 + IFD1 = -1 + + +class LightSource(IntEnum): + Unknown = 0x00 + Daylight = 0x01 + Fluorescent = 0x02 + Tungsten = 0x03 + Flash = 0x04 + Fine = 0x09 + Cloudy = 0x0A + Shade = 0x0B + DaylightFluorescent = 0x0C + DayWhiteFluorescent = 0x0D + CoolWhiteFluorescent = 0x0E + WhiteFluorescent = 0x0F + StandardLightA = 0x11 + StandardLightB = 0x12 + StandardLightC = 0x13 + D55 = 0x14 + D65 = 0x15 + D75 = 0x16 + D50 = 0x17 + ISO = 0x18 + Other = 0xFF diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/FitsImagePlugin.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/FitsImagePlugin.py new file mode 100644 index 000000000..e91840778 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/FitsImagePlugin.py @@ -0,0 +1,153 @@ +# +# The Python Imaging Library +# $Id$ +# +# FITS file handling +# +# Copyright (c) 1998-2003 by Fredrik Lundh +# +# See the README file for information on usage and redistribution. +# +from __future__ import annotations + +import gzip +import math + +from . import Image, ImageFile + + +def _accept(prefix: bytes) -> bool: + return prefix.startswith(b"SIMPLE") + + +class FitsImageFile(ImageFile.ImageFile): + format = "FITS" + format_description = "FITS" + + def _open(self) -> None: + assert self.fp is not None + + headers: dict[bytes, bytes] = {} + header_in_progress = False + decoder_name = "" + while True: + header = self.fp.read(80) + if not header: + msg = "Truncated FITS file" + raise OSError(msg) + keyword = header[:8].strip() + if keyword in (b"SIMPLE", b"XTENSION"): + header_in_progress = True + elif headers and not header_in_progress: + # This is now a data unit + break + elif keyword == b"END": + # Seek to the end of the header unit + self.fp.seek(math.ceil(self.fp.tell() / 2880) * 2880) + if not decoder_name: + decoder_name, offset, args = self._parse_headers(headers) + + header_in_progress = False + continue + + if decoder_name: + # Keep going to read past the headers + continue + + value = header[8:].split(b"/")[0].strip() + if value.startswith(b"="): + value = value[1:].strip() + if not headers and (not _accept(keyword) or value != b"T"): + msg = "Not a FITS file" + raise SyntaxError(msg) + headers[keyword] = value + + if not decoder_name: + msg = "No image data" + raise ValueError(msg) + + offset += self.fp.tell() - 80 + self.tile = [ImageFile._Tile(decoder_name, (0, 0) + self.size, offset, args)] + + def _get_size( + self, headers: dict[bytes, bytes], prefix: bytes + ) -> tuple[int, int] | None: + naxis = int(headers[prefix + b"NAXIS"]) + if naxis == 0: + return None + + if naxis == 1: + return 1, int(headers[prefix + b"NAXIS1"]) + else: + return int(headers[prefix + b"NAXIS1"]), int(headers[prefix + b"NAXIS2"]) + + def _parse_headers( + self, headers: dict[bytes, bytes] + ) -> tuple[str, int, tuple[str | int, ...]]: + prefix = b"" + decoder_name = "raw" + offset = 0 + if ( + headers.get(b"XTENSION") == b"'BINTABLE'" + and headers.get(b"ZIMAGE") == b"T" + and headers[b"ZCMPTYPE"] == b"'GZIP_1 '" + ): + no_prefix_size = self._get_size(headers, prefix) or (0, 0) + number_of_bits = int(headers[b"BITPIX"]) + offset = no_prefix_size[0] * no_prefix_size[1] * (number_of_bits // 8) + + prefix = b"Z" + decoder_name = "fits_gzip" + + size = self._get_size(headers, prefix) + if not size: + return "", 0, () + + self._size = size + + number_of_bits = int(headers[prefix + b"BITPIX"]) + if number_of_bits == 8: + self._mode = "L" + elif number_of_bits == 16: + self._mode = "I;16" + elif number_of_bits == 32: + self._mode = "I" + elif number_of_bits in (-32, -64): + self._mode = "F" + + args: tuple[str | int, ...] + if decoder_name == "raw": + args = (self.mode, 0, -1) + else: + args = (number_of_bits,) + return decoder_name, offset, args + + +class FitsGzipDecoder(ImageFile.PyDecoder): + _pulls_fd = True + + def decode(self, buffer: bytes | Image.SupportsArrayInterface) -> tuple[int, int]: + assert self.fd is not None + with gzip.open(self.fd) as fp: + value = fp.read(self.state.xsize * self.state.ysize * 4) + + rows = [] + offset = 0 + number_of_bits = min(self.args[0] // 8, 4) + for y in range(self.state.ysize): + row = bytearray() + for x in range(self.state.xsize): + row += value[offset + (4 - number_of_bits) : offset + 4] + offset += 4 + rows.append(row) + self.set_as_raw(bytes([pixel for row in rows[::-1] for pixel in row])) + return -1, 0 + + +# -------------------------------------------------------------------- +# Registry + +Image.register_open(FitsImageFile.format, FitsImageFile, _accept) +Image.register_decoder("fits_gzip", FitsGzipDecoder) + +Image.register_extensions(FitsImageFile.format, [".fit", ".fits"]) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/FliImagePlugin.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/FliImagePlugin.py new file mode 100644 index 000000000..da1e8e95c --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/FliImagePlugin.py @@ -0,0 +1,184 @@ +# +# The Python Imaging Library. +# $Id$ +# +# FLI/FLC file handling. +# +# History: +# 95-09-01 fl Created +# 97-01-03 fl Fixed parser, setup decoder tile +# 98-07-15 fl Renamed offset attribute to avoid name clash +# +# Copyright (c) Secret Labs AB 1997-98. +# Copyright (c) Fredrik Lundh 1995-97. +# +# See the README file for information on usage and redistribution. +# +from __future__ import annotations + +import os + +from . import Image, ImageFile, ImagePalette +from ._binary import i16le as i16 +from ._binary import i32le as i32 +from ._binary import o8 +from ._util import DeferredError + +# +# decoder + + +def _accept(prefix: bytes) -> bool: + return ( + len(prefix) >= 16 + and i16(prefix, 4) in [0xAF11, 0xAF12] + and i16(prefix, 14) in [0, 3] # flags + ) + + +## +# Image plugin for the FLI/FLC animation format. Use the seek +# method to load individual frames. + + +class FliImageFile(ImageFile.ImageFile): + format = "FLI" + format_description = "Autodesk FLI/FLC Animation" + _close_exclusive_fp_after_loading = False + + def _open(self) -> None: + # HEAD + assert self.fp is not None + s = self.fp.read(128) + if not ( + _accept(s) + and s[20:22] == b"\x00" * 2 + and s[42:80] == b"\x00" * 38 + and s[88:] == b"\x00" * 40 + ): + msg = "not an FLI/FLC file" + raise SyntaxError(msg) + + # frames + self.n_frames = i16(s, 6) + self.is_animated = self.n_frames > 1 + + # image characteristics + self._mode = "P" + self._size = i16(s, 8), i16(s, 10) + + # animation speed + duration = i32(s, 16) + magic = i16(s, 4) + if magic == 0xAF11: + duration = (duration * 1000) // 70 + self.info["duration"] = duration + + # look for palette + palette = [(a, a, a) for a in range(256)] + + s = self.fp.read(16) + + self.__offset = 128 + + if i16(s, 4) == 0xF100: + # prefix chunk; ignore it + self.fp.seek(self.__offset + i32(s)) + s = self.fp.read(16) + + if i16(s, 4) == 0xF1FA: + # look for palette chunk + number_of_subchunks = i16(s, 6) + chunk_size: int | None = None + for _ in range(number_of_subchunks): + if chunk_size is not None: + self.fp.seek(chunk_size - 6, os.SEEK_CUR) + s = self.fp.read(6) + chunk_type = i16(s, 4) + if chunk_type in (4, 11): + self._palette(palette, 2 if chunk_type == 11 else 0) + break + chunk_size = i32(s) + if not chunk_size: + break + + self.palette = ImagePalette.raw( + "RGB", b"".join(o8(r) + o8(g) + o8(b) for (r, g, b) in palette) + ) + + # set things up to decode first frame + self.__frame = -1 + self._fp = self.fp + self.__rewind = self.fp.tell() + self.seek(0) + + def _palette(self, palette: list[tuple[int, int, int]], shift: int) -> None: + # load palette + + i = 0 + assert self.fp is not None + for e in range(i16(self.fp.read(2))): + s = self.fp.read(2) + i = i + s[0] + n = s[1] + if n == 0: + n = 256 + s = self.fp.read(n * 3) + for n in range(0, len(s), 3): + r = s[n] << shift + g = s[n + 1] << shift + b = s[n + 2] << shift + palette[i] = (r, g, b) + i += 1 + + def seek(self, frame: int) -> None: + if not self._seek_check(frame): + return + if frame < self.__frame: + self._seek(0) + + for f in range(self.__frame + 1, frame + 1): + self._seek(f) + + def _seek(self, frame: int) -> None: + if isinstance(self._fp, DeferredError): + raise self._fp.ex + if frame == 0: + self.__frame = -1 + self._fp.seek(self.__rewind) + self.__offset = 128 + else: + # ensure that the previous frame was loaded + self.load() + + if frame != self.__frame + 1: + msg = f"cannot seek to frame {frame}" + raise ValueError(msg) + self.__frame = frame + + # move to next frame + self.fp = self._fp + self.fp.seek(self.__offset) + + s = self.fp.read(4) + if not s: + msg = "missing frame size" + raise EOFError(msg) + + framesize = i32(s) + + self.decodermaxblock = framesize + self.tile = [ImageFile._Tile("fli", (0, 0) + self.size, self.__offset)] + + self.__offset += framesize + + def tell(self) -> int: + return self.__frame + + +# +# registry + +Image.register_open(FliImageFile.format, FliImageFile, _accept) + +Image.register_extensions(FliImageFile.format, [".fli", ".flc"]) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/FontFile.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/FontFile.py new file mode 100644 index 000000000..341431d3f --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/FontFile.py @@ -0,0 +1,159 @@ +# +# The Python Imaging Library +# $Id$ +# +# base class for raster font file parsers +# +# history: +# 1997-06-05 fl created +# 1997-08-19 fl restrict image width +# +# Copyright (c) 1997-1998 by Secret Labs AB +# Copyright (c) 1997-1998 by Fredrik Lundh +# +# See the README file for information on usage and redistribution. +# +from __future__ import annotations + +import os +from typing import BinaryIO + +from . import Image, ImageFont, _binary + +WIDTH = 800 + + +def puti16( + fp: BinaryIO, values: tuple[int, int, int, int, int, int, int, int, int, int] +) -> None: + """Write network order (big-endian) 16-bit sequence""" + for v in values: + if v < 0: + v += 65536 + fp.write(_binary.o16be(v)) + + +class FontFile: + """Base class for raster font file handlers.""" + + bitmap: Image.Image | None = None + + def __init__(self) -> None: + self.info: dict[bytes, bytes | int] = {} + self.glyph: list[ + tuple[ + tuple[int, int], + tuple[int, int, int, int], + tuple[int, int, int, int], + Image.Image, + ] + | None + ] = [None] * 256 + + def __getitem__(self, ix: int) -> ( + tuple[ + tuple[int, int], + tuple[int, int, int, int], + tuple[int, int, int, int], + Image.Image, + ] + | None + ): + return self.glyph[ix] + + def compile(self) -> None: + """Create metrics and bitmap""" + + if self.bitmap: + return + + # create bitmap large enough to hold all data + h = w = maxwidth = 0 + lines = 1 + for glyph in self.glyph: + if glyph: + d, dst, src, im = glyph + h = max(h, src[3] - src[1]) + w = w + (src[2] - src[0]) + if w > WIDTH: + lines += 1 + w = src[2] - src[0] + maxwidth = max(maxwidth, w) + + xsize = maxwidth + ysize = lines * h + + if xsize == 0 and ysize == 0: + return + + self.ysize = h + + # paste glyphs into bitmap + self.bitmap = Image.new("1", (xsize, ysize)) + self.metrics: list[ + tuple[tuple[int, int], tuple[int, int, int, int], tuple[int, int, int, int]] + | None + ] = [None] * 256 + x = y = 0 + for i in range(256): + glyph = self[i] + if glyph: + d, dst, src, im = glyph + xx = src[2] - src[0] + x0, y0 = x, y + x = x + xx + if x > WIDTH: + x, y = 0, y + h + x0, y0 = x, y + x = xx + s = src[0] + x0, src[1] + y0, src[2] + x0, src[3] + y0 + self.bitmap.paste(im.crop(src), s) + self.metrics[i] = d, dst, s + + def _encode_metrics(self) -> bytes: + values: list[int] = [] + for i in range(256): + m = self.metrics[i] + if m: + values.extend(m[0] + m[1] + m[2]) + else: + values.extend((0,) * 10) + + data = bytearray() + for v in values: + if v < 0: + v += 65536 + data += _binary.o16be(v) + return bytes(data) + + def save(self, filename: str) -> None: + """Save font""" + + self.compile() + + # font data + if not self.bitmap: + msg = "No bitmap created" + raise ValueError(msg) + self.bitmap.save(os.path.splitext(filename)[0] + ".pbm", "PNG") + + # font metrics + with open(os.path.splitext(filename)[0] + ".pil", "wb") as fp: + fp.write(b"PILfont\n") + fp.write(f";;;;;;{self.ysize};\n".encode("ascii")) # HACK!!! + fp.write(b"DATA\n") + fp.write(self._encode_metrics()) + + def to_imagefont(self) -> ImageFont.ImageFont: + """Convert to ImageFont""" + + self.compile() + + # font data + if not self.bitmap: + msg = "No bitmap created" + raise ValueError(msg) + + imagefont = ImageFont.ImageFont() + imagefont._load(self.bitmap, self._encode_metrics()) + return imagefont diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/FpxImagePlugin.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/FpxImagePlugin.py new file mode 100644 index 000000000..0b06aac96 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/FpxImagePlugin.py @@ -0,0 +1,258 @@ +# +# THIS IS WORK IN PROGRESS +# +# The Python Imaging Library. +# $Id$ +# +# FlashPix support for PIL +# +# History: +# 97-01-25 fl Created (reads uncompressed RGB images only) +# +# Copyright (c) Secret Labs AB 1997. +# Copyright (c) Fredrik Lundh 1997. +# +# See the README file for information on usage and redistribution. +# +from __future__ import annotations + +import olefile + +from . import Image, ImageFile +from ._binary import i32le as i32 + +# we map from colour field tuples to (mode, rawmode) descriptors +MODES = { + # opacity + (0x00007FFE,): ("A", "L"), + # monochrome + (0x00010000,): ("L", "L"), + (0x00018000, 0x00017FFE): ("RGBA", "LA"), + # photo YCC + (0x00020000, 0x00020001, 0x00020002): ("RGB", "YCC;P"), + (0x00028000, 0x00028001, 0x00028002, 0x00027FFE): ("RGBA", "YCCA;P"), + # standard RGB (NIFRGB) + (0x00030000, 0x00030001, 0x00030002): ("RGB", "RGB"), + (0x00038000, 0x00038001, 0x00038002, 0x00037FFE): ("RGBA", "RGBA"), +} + + +# +# -------------------------------------------------------------------- + + +def _accept(prefix: bytes) -> bool: + return prefix.startswith(olefile.MAGIC) + + +## +# Image plugin for the FlashPix images. + + +class FpxImageFile(ImageFile.ImageFile): + format = "FPX" + format_description = "FlashPix" + + def _open(self) -> None: + # + # read the OLE directory and see if this is a likely + # to be a FlashPix file + + assert self.fp is not None + try: + self.ole = olefile.OleFileIO(self.fp) + except OSError as e: + msg = "not an FPX file; invalid OLE file" + raise SyntaxError(msg) from e + + root = self.ole.root + if not root or root.clsid != "56616700-C154-11CE-8553-00AA00A1F95B": + msg = "not an FPX file; bad root CLSID" + raise SyntaxError(msg) + + self._open_index(1) + + def _open_index(self, index: int = 1) -> None: + # + # get the Image Contents Property Set + + prop = self.ole.getproperties( + [f"Data Object Store {index:06d}", "\005Image Contents"] + ) + + # size (highest resolution) + + assert isinstance(prop[0x1000002], int) + assert isinstance(prop[0x1000003], int) + self._size = prop[0x1000002], prop[0x1000003] + + size = max(self.size) + i = 1 + while size > 64: + size = size // 2 + i += 1 + self.maxid = i - 1 + + # mode. instead of using a single field for this, flashpix + # requires you to specify the mode for each channel in each + # resolution subimage, and leaves it to the decoder to make + # sure that they all match. for now, we'll cheat and assume + # that this is always the case. + + id = self.maxid << 16 + + s = prop[0x2000002 | id] + + if not isinstance(s, bytes) or (bands := i32(s, 4)) > 4: + msg = "Invalid number of bands" + raise OSError(msg) + + # note: for now, we ignore the "uncalibrated" flag + colors = tuple(i32(s, 8 + i * 4) & 0x7FFFFFFF for i in range(bands)) + + self._mode, self.rawmode = MODES[colors] + + # load JPEG tables, if any + self.jpeg = {} + for i in range(256): + id = 0x3000001 | (i << 16) + if id in prop: + self.jpeg[i] = prop[id] + + self._open_subimage(1, self.maxid) + + def _open_subimage(self, index: int = 1, subimage: int = 0) -> None: + # + # setup tile descriptors for a given subimage + + stream = [ + f"Data Object Store {index:06d}", + f"Resolution {subimage:04d}", + "Subimage 0000 Header", + ] + + fp = self.ole.openstream(stream) + + # skip prefix + fp.read(28) + + # header stream + s = fp.read(36) + + size = i32(s, 4), i32(s, 8) + # tilecount = i32(s, 12) + xtile, ytile = i32(s, 16), i32(s, 20) + # channels = i32(s, 24) + offset = i32(s, 28) + length = i32(s, 32) + + if size != self.size: + msg = "subimage mismatch" + raise OSError(msg) + + # get tile descriptors + fp.seek(28 + offset) + s = fp.read(i32(s, 12) * length) + + x = y = 0 + xsize, ysize = size + self.tile = [] + + for i in range(0, len(s), length): + x1 = min(xsize, x + xtile) + y1 = min(ysize, y + ytile) + + compression = i32(s, i + 8) + + if compression == 0: + self.tile.append( + ImageFile._Tile( + "raw", + (x, y, x1, y1), + i32(s, i) + 28, + self.rawmode, + ) + ) + + elif compression == 1: + # FIXME: the fill decoder is not implemented + self.tile.append( + ImageFile._Tile( + "fill", + (x, y, x1, y1), + i32(s, i) + 28, + (self.rawmode, s[12:16]), + ) + ) + + elif compression == 2: + internal_color_conversion = s[14] + jpeg_tables = s[15] + rawmode = self.rawmode + + if internal_color_conversion: + # The image is stored as usual (usually YCbCr). + if rawmode == "RGBA": + # For "RGBA", data is stored as YCbCrA based on + # negative RGB. The following trick works around + # this problem : + jpegmode, rawmode = "YCbCrK", "CMYK" + else: + jpegmode = None # let the decoder decide + + else: + # The image is stored as defined by rawmode + jpegmode = rawmode + + self.tile.append( + ImageFile._Tile( + "jpeg", + (x, y, x1, y1), + i32(s, i) + 28, + (rawmode, jpegmode), + ) + ) + + # FIXME: jpeg tables are tile dependent; the prefix + # data must be placed in the tile descriptor itself! + + if jpeg_tables: + self.tile_prefix = self.jpeg[jpeg_tables] + + else: + msg = "unknown/invalid compression" + raise OSError(msg) + + x += xtile + if x >= xsize: + x, y = 0, y + ytile + if y >= ysize: + break # isn't really required + + assert self.fp is not None + self.stream = stream + self._fp = self.fp + self.fp = None + + def load(self) -> Image.core.PixelAccess | None: + if not self.fp: + self.fp = self.ole.openstream(self.stream[:2] + ["Subimage 0000 Data"]) + + return ImageFile.ImageFile.load(self) + + def close(self) -> None: + self.ole.close() + super().close() + + def __exit__(self, *args: object) -> None: + self.ole.close() + super().__exit__() + + +# +# -------------------------------------------------------------------- + + +Image.register_open(FpxImageFile.format, FpxImageFile, _accept) + +Image.register_extension(FpxImageFile.format, ".fpx") diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/FtexImagePlugin.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/FtexImagePlugin.py new file mode 100644 index 000000000..e4d836cbd --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/FtexImagePlugin.py @@ -0,0 +1,115 @@ +""" +A Pillow loader for .ftc and .ftu files (FTEX) +Jerome Leclanche + +The contents of this file are hereby released in the public domain (CC0) +Full text of the CC0 license: + https://creativecommons.org/publicdomain/zero/1.0/ + +Independence War 2: Edge Of Chaos - Texture File Format - 16 October 2001 + +The textures used for 3D objects in Independence War 2: Edge Of Chaos are in a +packed custom format called FTEX. This file format uses file extensions FTC +and FTU. +* FTC files are compressed textures (using standard texture compression). +* FTU files are not compressed. +Texture File Format +The FTC and FTU texture files both use the same format. This +has the following structure: +{header} +{format_directory} +{data} +Where: +{header} = { + u32:magic, + u32:version, + u32:width, + u32:height, + u32:mipmap_count, + u32:format_count +} + +* The "magic" number is "FTEX". +* "width" and "height" are the dimensions of the texture. +* "mipmap_count" is the number of mipmaps in the texture. +* "format_count" is the number of texture formats (different versions of the +same texture) in this file. + +{format_directory} = format_count * { u32:format, u32:where } + +The format value is 0 for DXT1 compressed textures and 1 for 24-bit RGB +uncompressed textures. +The texture data for a format starts at the position "where" in the file. + +Each set of texture data in the file has the following structure: +{data} = format_count * { u32:mipmap_size, mipmap_size * { u8 } } +* "mipmap_size" is the number of bytes in that mip level. For compressed +textures this is the size of the texture data compressed with DXT1. For 24 bit +uncompressed textures, this is 3 * width * height. Following this are the image +bytes for that mipmap level. + +Note: All data is stored in little-Endian (Intel) byte order. +""" + +from __future__ import annotations + +import struct +from enum import IntEnum +from io import BytesIO + +from . import Image, ImageFile + +MAGIC = b"FTEX" + + +class Format(IntEnum): + DXT1 = 0 + UNCOMPRESSED = 1 + + +class FtexImageFile(ImageFile.ImageFile): + format = "FTEX" + format_description = "Texture File Format (IW2:EOC)" + + def _open(self) -> None: + assert self.fp is not None + if not _accept(self.fp.read(4)): + msg = "not an FTEX file" + raise SyntaxError(msg) + struct.unpack(" None: + pass + + +def _accept(prefix: bytes) -> bool: + return prefix.startswith(MAGIC) + + +Image.register_open(FtexImageFile.format, FtexImageFile, _accept) +Image.register_extensions(FtexImageFile.format, [".ftc", ".ftu"]) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/GbrImagePlugin.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/GbrImagePlugin.py new file mode 100644 index 000000000..ec666c81c --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/GbrImagePlugin.py @@ -0,0 +1,103 @@ +# +# The Python Imaging Library +# +# load a GIMP brush file +# +# History: +# 96-03-14 fl Created +# 16-01-08 es Version 2 +# +# Copyright (c) Secret Labs AB 1997. +# Copyright (c) Fredrik Lundh 1996. +# Copyright (c) Eric Soroos 2016. +# +# See the README file for information on usage and redistribution. +# +# +# See https://github.com/GNOME/gimp/blob/mainline/devel-docs/gbr.txt for +# format documentation. +# +# This code Interprets version 1 and 2 .gbr files. +# Version 1 files are obsolete, and should not be used for new +# brushes. +# Version 2 files are saved by GIMP v2.8 (at least) +# Version 3 files have a format specifier of 18 for 16bit floats in +# the color depth field. This is currently unsupported by Pillow. +from __future__ import annotations + +from . import Image, ImageFile +from ._binary import i32be as i32 + + +def _accept(prefix: bytes) -> bool: + return len(prefix) >= 8 and i32(prefix, 0) >= 20 and i32(prefix, 4) in (1, 2) + + +## +# Image plugin for the GIMP brush format. + + +class GbrImageFile(ImageFile.ImageFile): + format = "GBR" + format_description = "GIMP brush file" + + def _open(self) -> None: + assert self.fp is not None + header_size = i32(self.fp.read(4)) + if header_size < 20: + msg = "not a GIMP brush" + raise SyntaxError(msg) + version = i32(self.fp.read(4)) + if version not in (1, 2): + msg = f"Unsupported GIMP brush version: {version}" + raise SyntaxError(msg) + + width = i32(self.fp.read(4)) + height = i32(self.fp.read(4)) + color_depth = i32(self.fp.read(4)) + if width == 0 or height == 0: + msg = "not a GIMP brush" + raise SyntaxError(msg) + if color_depth not in (1, 4): + msg = f"Unsupported GIMP brush color depth: {color_depth}" + raise SyntaxError(msg) + + if version == 1: + comment_length = header_size - 20 + else: + comment_length = header_size - 28 + magic_number = self.fp.read(4) + if magic_number != b"GIMP": + msg = "not a GIMP brush, bad magic number" + raise SyntaxError(msg) + self.info["spacing"] = i32(self.fp.read(4)) + + self.info["comment"] = self.fp.read(comment_length)[:-1] + + if color_depth == 1: + self._mode = "L" + else: + self._mode = "RGBA" + + self._size = width, height + + # Image might not be small + Image._decompression_bomb_check(self.size) + + # Data is an uncompressed block of w * h * bytes/pixel + self._data_size = width * height * color_depth + + def load(self) -> Image.core.PixelAccess | None: + if self._im is None: + assert self.fp is not None + self.im = Image.core.new(self.mode, self.size) + self.frombytes(self.fp.read(self._data_size)) + return Image.Image.load(self) + + +# +# registry + + +Image.register_open(GbrImageFile.format, GbrImageFile, _accept) +Image.register_extension(GbrImageFile.format, ".gbr") diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/GdImageFile.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/GdImageFile.py new file mode 100644 index 000000000..d73bc1982 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/GdImageFile.py @@ -0,0 +1,103 @@ +# +# The Python Imaging Library. +# $Id$ +# +# GD file handling +# +# History: +# 1996-04-12 fl Created +# +# Copyright (c) 1997 by Secret Labs AB. +# Copyright (c) 1996 by Fredrik Lundh. +# +# See the README file for information on usage and redistribution. +# + + +""" +.. note:: + This format cannot be automatically recognized, so the + class is not registered for use with :py:func:`PIL.Image.open()`. To open a + gd file, use the :py:func:`PIL.GdImageFile.open()` function instead. + +.. warning:: + THE GD FORMAT IS NOT DESIGNED FOR DATA INTERCHANGE. This + implementation is provided for convenience and demonstrational + purposes only. +""" + +from __future__ import annotations + +from typing import IO + +from . import ImageFile, ImagePalette, UnidentifiedImageError +from ._binary import i16be as i16 +from ._binary import i32be as i32 +from ._typing import StrOrBytesPath + + +class GdImageFile(ImageFile.ImageFile): + """ + Image plugin for the GD uncompressed format. Note that this format + is not supported by the standard :py:func:`PIL.Image.open()` function. To use + this plugin, you have to import the :py:mod:`PIL.GdImageFile` module and + use the :py:func:`PIL.GdImageFile.open()` function. + """ + + format = "GD" + format_description = "GD uncompressed images" + + def _open(self) -> None: + # Header + assert self.fp is not None + + s = self.fp.read(1037) + + if i16(s) not in [65534, 65535]: + msg = "Not a valid GD 2.x .gd file" + raise SyntaxError(msg) + + self._mode = "P" + self._size = i16(s, 2), i16(s, 4) + + true_color = s[6] + true_color_offset = 2 if true_color else 0 + + # transparency index + tindex = i32(s, 7 + true_color_offset) + if tindex < 256: + self.info["transparency"] = tindex + + self.palette = ImagePalette.raw( + "RGBX", s[7 + true_color_offset + 6 : 7 + true_color_offset + 6 + 256 * 4] + ) + + self.tile = [ + ImageFile._Tile( + "raw", + (0, 0) + self.size, + 7 + true_color_offset + 6 + 256 * 4, + "L", + ) + ] + + +def open(fp: StrOrBytesPath | IO[bytes], mode: str = "r") -> GdImageFile: + """ + Load texture from a GD image file. + + :param fp: GD file name, or an opened file handle. + :param mode: Optional mode. In this version, if the mode argument + is given, it must be "r". + :returns: An image instance. + :raises OSError: If the image could not be read. + """ + if mode != "r": + msg = "bad mode" + raise ValueError(msg) + + try: + return GdImageFile(fp) + except SyntaxError as e: + msg = "cannot identify this image file" + raise UnidentifiedImageError(msg) from e diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/GifImagePlugin.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/GifImagePlugin.py new file mode 100644 index 000000000..b8db5d832 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/GifImagePlugin.py @@ -0,0 +1,1223 @@ +# +# The Python Imaging Library. +# $Id$ +# +# GIF file handling +# +# History: +# 1995-09-01 fl Created +# 1996-12-14 fl Added interlace support +# 1996-12-30 fl Added animation support +# 1997-01-05 fl Added write support, fixed local colour map bug +# 1997-02-23 fl Make sure to load raster data in getdata() +# 1997-07-05 fl Support external decoder (0.4) +# 1998-07-09 fl Handle all modes when saving (0.5) +# 1998-07-15 fl Renamed offset attribute to avoid name clash +# 2001-04-16 fl Added rewind support (seek to frame 0) (0.6) +# 2001-04-17 fl Added palette optimization (0.7) +# 2002-06-06 fl Added transparency support for save (0.8) +# 2004-02-24 fl Disable interlacing for small images +# +# Copyright (c) 1997-2004 by Secret Labs AB +# Copyright (c) 1995-2004 by Fredrik Lundh +# +# See the README file for information on usage and redistribution. +# +from __future__ import annotations + +import itertools +import math +import os +import subprocess +from enum import IntEnum +from functools import cached_property +from typing import Any, NamedTuple, cast + +from . import ( + Image, + ImageChops, + ImageFile, + ImageMath, + ImageOps, + ImagePalette, + ImageSequence, +) +from ._binary import i16le as i16 +from ._binary import o8 +from ._binary import o16le as o16 +from ._util import DeferredError + +TYPE_CHECKING = False +if TYPE_CHECKING: + from typing import IO, Literal + + from . import _imaging + from ._typing import Buffer + + +class LoadingStrategy(IntEnum): + """.. versionadded:: 9.1.0""" + + RGB_AFTER_FIRST = 0 + RGB_AFTER_DIFFERENT_PALETTE_ONLY = 1 + RGB_ALWAYS = 2 + + +#: .. versionadded:: 9.1.0 +LOADING_STRATEGY = LoadingStrategy.RGB_AFTER_FIRST + +# -------------------------------------------------------------------- +# Identify/read GIF files + + +def _accept(prefix: bytes) -> bool: + return prefix.startswith((b"GIF87a", b"GIF89a")) + + +## +# Image plugin for GIF images. This plugin supports both GIF87 and +# GIF89 images. + + +class GifImageFile(ImageFile.ImageFile): + format = "GIF" + format_description = "Compuserve GIF" + _close_exclusive_fp_after_loading = False + + global_palette = None + + def data(self) -> bytes | None: + assert self.fp is not None + s = self.fp.read(1) + if s and s[0]: + return self.fp.read(s[0]) + return None + + def _is_palette_needed(self, p: bytes) -> bool: + for i in range(0, len(p), 3): + if not (i // 3 == p[i] == p[i + 1] == p[i + 2]): + return True + return False + + def _open(self) -> None: + # Screen + assert self.fp is not None + s = self.fp.read(13) + if not _accept(s): + msg = "not a GIF file" + raise SyntaxError(msg) + + self.info["version"] = s[:6] + self._size = i16(s, 6), i16(s, 8) + flags = s[10] + bits = (flags & 7) + 1 + + if flags & 128: + # get global palette + self.info["background"] = s[11] + # check if palette contains colour indices + p = self.fp.read(3 << bits) + if self._is_palette_needed(p): + palette = ImagePalette.raw("RGB", p) + self.global_palette = self.palette = palette + + self._fp = self.fp # FIXME: hack + self.__rewind = self.fp.tell() + self._n_frames: int | None = None + self._seek(0) # get ready to read first frame + + @property + def n_frames(self) -> int: + if self._n_frames is None: + current = self.tell() + try: + while True: + self._seek(self.tell() + 1, False) + except EOFError: + self._n_frames = self.tell() + 1 + self.seek(current) + return self._n_frames + + @cached_property + def is_animated(self) -> bool: + if self._n_frames is not None: + return self._n_frames != 1 + + current = self.tell() + if current: + return True + + try: + self._seek(1, False) + is_animated = True + except EOFError: + is_animated = False + + self.seek(current) + return is_animated + + def seek(self, frame: int) -> None: + if not self._seek_check(frame): + return + if frame < self.__frame: + self._im = None + self._seek(0) + + last_frame = self.__frame + try: + for f in range(self.__frame + 1, frame + 1): + self._seek(f) + except EOFError as e: + self.seek(last_frame) + msg = "no more images in GIF file" + raise EOFError(msg) from e + + def _seek(self, frame: int, update_image: bool = True) -> None: + if isinstance(self._fp, DeferredError): + raise self._fp.ex + if frame == 0: + # rewind + self.__offset = 0 + self.dispose: _imaging.ImagingCore | None = None + self.__frame = -1 + self._fp.seek(self.__rewind) + self.disposal_method = 0 + if "comment" in self.info: + del self.info["comment"] + else: + # ensure that the previous frame was loaded + if self.tile and update_image: + self.load() + + if frame != self.__frame + 1: + msg = f"cannot seek to frame {frame}" + raise ValueError(msg) + + self.fp = self._fp + if self.__offset: + # backup to last frame + self.fp.seek(self.__offset) + while self.data(): + pass + self.__offset = 0 + + s = self.fp.read(1) + if not s or s == b";": + msg = "no more images in GIF file" + raise EOFError(msg) + + palette: ImagePalette.ImagePalette | Literal[False] | None = None + + info: dict[str, Any] = {} + frame_transparency = None + interlace = None + frame_dispose_extent = None + while True: + if not s: + s = self.fp.read(1) + if not s or s == b";": + break + + elif s == b"!": + # + # extensions + # + s = self.fp.read(1) + block = self.data() + if s[0] == 249 and block is not None: + # + # graphic control extension + # + flags = block[0] + if flags & 1: + frame_transparency = block[3] + info["duration"] = i16(block, 1) * 10 + + # disposal method - find the value of bits 4 - 6 + dispose_bits = 0b00011100 & flags + dispose_bits = dispose_bits >> 2 + if dispose_bits: + # only set the dispose if it is not + # unspecified. I'm not sure if this is + # correct, but it seems to prevent the last + # frame from looking odd for some animations + self.disposal_method = dispose_bits + elif s[0] == 254: + # + # comment extension + # + comment = b"" + + # Read this comment block + while block: + comment += block + block = self.data() + + if "comment" in info: + # If multiple comment blocks in frame, separate with \n + info["comment"] += b"\n" + comment + else: + info["comment"] = comment + s = b"" + continue + elif s[0] == 255 and frame == 0 and block is not None: + # + # application extension + # + info["extension"] = block, self.fp.tell() + if block.startswith(b"NETSCAPE2.0"): + block = self.data() + if block and len(block) >= 3 and block[0] == 1: + self.info["loop"] = i16(block, 1) + while self.data(): + pass + + elif s == b",": + # + # local image + # + s = self.fp.read(9) + + # extent + x0, y0 = i16(s, 0), i16(s, 2) + x1, y1 = x0 + i16(s, 4), y0 + i16(s, 6) + if (x1 > self.size[0] or y1 > self.size[1]) and update_image: + self._size = max(x1, self.size[0]), max(y1, self.size[1]) + Image._decompression_bomb_check(self._size) + frame_dispose_extent = x0, y0, x1, y1 + flags = s[8] + + interlace = (flags & 64) != 0 + + if flags & 128: + bits = (flags & 7) + 1 + p = self.fp.read(3 << bits) + if self._is_palette_needed(p): + palette = ImagePalette.raw("RGB", p) + else: + palette = False + + # image data + bits = self.fp.read(1)[0] + self.__offset = self.fp.tell() + break + s = b"" + + if interlace is None: + msg = "image not found in GIF frame" + raise EOFError(msg) + + self.__frame = frame + if not update_image: + return + + self.tile = [] + + if self.dispose: + self.im.paste(self.dispose, self.dispose_extent) + + self._frame_palette = palette if palette is not None else self.global_palette + self._frame_transparency = frame_transparency + if frame == 0: + if self._frame_palette: + if LOADING_STRATEGY == LoadingStrategy.RGB_ALWAYS: + self._mode = "RGBA" if frame_transparency is not None else "RGB" + else: + self._mode = "P" + else: + self._mode = "L" + + if palette: + self.palette = palette + elif self.global_palette: + from copy import copy + + self.palette = copy(self.global_palette) + else: + self.palette = None + else: + if self.mode == "P": + if ( + LOADING_STRATEGY != LoadingStrategy.RGB_AFTER_DIFFERENT_PALETTE_ONLY + or palette + ): + if "transparency" in self.info: + self.im.putpalettealpha(self.info["transparency"], 0) + self.im = self.im.convert("RGBA", Image.Dither.FLOYDSTEINBERG) + self._mode = "RGBA" + del self.info["transparency"] + else: + self._mode = "RGB" + self.im = self.im.convert("RGB", Image.Dither.FLOYDSTEINBERG) + + def _rgb(color: int) -> tuple[int, int, int]: + if self._frame_palette: + if color * 3 + 3 > len(self._frame_palette.palette): + color = 0 + return cast( + tuple[int, int, int], + tuple(self._frame_palette.palette[color * 3 : color * 3 + 3]), + ) + else: + return (color, color, color) + + self.dispose = None + self.dispose_extent: tuple[int, int, int, int] | None = frame_dispose_extent + if self.dispose_extent and self.disposal_method >= 2: + try: + if self.disposal_method == 2: + # replace with background colour + + # only dispose the extent in this frame + x0, y0, x1, y1 = self.dispose_extent + dispose_size = (x1 - x0, y1 - y0) + + Image._decompression_bomb_check(dispose_size) + + # by convention, attempt to use transparency first + dispose_mode = "P" + color = self.info.get("transparency", frame_transparency) + if color is not None: + if self.mode in ("RGB", "RGBA"): + dispose_mode = "RGBA" + color = _rgb(color) + (0,) + else: + color = self.info.get("background", 0) + if self.mode in ("RGB", "RGBA"): + dispose_mode = "RGB" + color = _rgb(color) + self.dispose = Image.core.fill(dispose_mode, dispose_size, color) + else: + # replace with previous contents + if self._im is not None: + # only dispose the extent in this frame + self.dispose = self._crop(self.im, self.dispose_extent) + elif frame_transparency is not None: + x0, y0, x1, y1 = self.dispose_extent + dispose_size = (x1 - x0, y1 - y0) + + Image._decompression_bomb_check(dispose_size) + dispose_mode = "P" + color = frame_transparency + if self.mode in ("RGB", "RGBA"): + dispose_mode = "RGBA" + color = _rgb(frame_transparency) + (0,) + self.dispose = Image.core.fill( + dispose_mode, dispose_size, color + ) + except AttributeError: + pass + + if interlace is not None: + transparency = -1 + if frame_transparency is not None: + if frame == 0: + if LOADING_STRATEGY != LoadingStrategy.RGB_ALWAYS: + self.info["transparency"] = frame_transparency + elif self.mode not in ("RGB", "RGBA"): + transparency = frame_transparency + self.tile = [ + ImageFile._Tile( + "gif", + (x0, y0, x1, y1), + self.__offset, + (bits, interlace, transparency), + ) + ] + + if info.get("comment"): + self.info["comment"] = info["comment"] + for k in ["duration", "extension"]: + if k in info: + self.info[k] = info[k] + elif k in self.info: + del self.info[k] + + def load_prepare(self) -> None: + temp_mode = "P" if self._frame_palette else "L" + self._prev_im = None + if self.__frame == 0: + if self._frame_transparency is not None: + self.im = Image.core.fill( + temp_mode, self.size, self._frame_transparency + ) + elif self.mode in ("RGB", "RGBA"): + self._prev_im = self.im + if self._frame_palette: + self.im = Image.core.fill("P", self.size, self._frame_transparency or 0) + self.im.putpalette("RGB", *self._frame_palette.getdata()) + else: + self._im = None + if not self._prev_im and self._im is not None and self.size != self.im.size: + expanded_im = Image.core.fill(self.im.mode, self.size) + if self._frame_palette: + expanded_im.putpalette("RGB", *self._frame_palette.getdata()) + expanded_im.paste(self.im, (0, 0) + self.im.size) + + self.im = expanded_im + self._mode = temp_mode + self._frame_palette = None + + super().load_prepare() + + def load_end(self) -> None: + if self.__frame == 0: + if self.mode == "P" and LOADING_STRATEGY == LoadingStrategy.RGB_ALWAYS: + if self._frame_transparency is not None: + self.im.putpalettealpha(self._frame_transparency, 0) + self._mode = "RGBA" + else: + self._mode = "RGB" + self.im = self.im.convert(self.mode, Image.Dither.FLOYDSTEINBERG) + return + if not self._prev_im: + return + if self.size != self._prev_im.size: + if self._frame_transparency is not None: + expanded_im = Image.core.fill("RGBA", self.size) + else: + expanded_im = Image.core.fill("P", self.size) + expanded_im.putpalette("RGB", "RGB", self.im.getpalette()) + expanded_im = expanded_im.convert("RGB") + expanded_im.paste(self._prev_im, (0, 0) + self._prev_im.size) + + self._prev_im = expanded_im + assert self._prev_im is not None + if self._frame_transparency is not None: + if self.mode == "L": + frame_im = self.im.convert_transparent("LA", self._frame_transparency) + else: + self.im.putpalettealpha(self._frame_transparency, 0) + frame_im = self.im.convert("RGBA") + else: + frame_im = self.im.convert("RGB") + + assert self.dispose_extent is not None + frame_im = self._crop(frame_im, self.dispose_extent) + + self.im = self._prev_im + self._mode = self.im.mode + if frame_im.mode in ("LA", "RGBA"): + self.im.paste(frame_im, self.dispose_extent, frame_im) + else: + self.im.paste(frame_im, self.dispose_extent) + + def tell(self) -> int: + return self.__frame + + +# -------------------------------------------------------------------- +# Write GIF files + + +RAWMODE = {"1": "L", "L": "L", "P": "P"} + + +def _normalize_mode(im: Image.Image) -> Image.Image: + """ + Takes an image (or frame), returns an image in a mode that is appropriate + for saving in a Gif. + + It may return the original image, or it may return an image converted to + palette or 'L' mode. + + :param im: Image object + :returns: Image object + """ + if im.mode in RAWMODE: + im.load() + return im + if Image.getmodebase(im.mode) == "RGB": + im = im.convert("P", palette=Image.Palette.ADAPTIVE) + assert im.palette is not None + if im.palette.mode == "RGBA": + for rgba in im.palette.colors: + if rgba[3] == 0: + im.info["transparency"] = im.palette.colors[rgba] + break + return im + return im.convert("L") + + +_Palette = bytes | bytearray | list[int] | ImagePalette.ImagePalette + + +def _normalize_palette( + im: Image.Image, palette: _Palette | None, info: dict[str, Any] +) -> Image.Image: + """ + Normalizes the palette for image. + - Sets the palette to the incoming palette, if provided. + - Ensures that there's a palette for L mode images + - Optimizes the palette if necessary/desired. + + :param im: Image object + :param palette: bytes object containing the source palette, or .... + :param info: encoderinfo + :returns: Image object + """ + source_palette = None + if palette: + # a bytes palette + if isinstance(palette, (bytes, bytearray, list)): + source_palette = bytearray(palette[:768]) + if isinstance(palette, ImagePalette.ImagePalette): + source_palette = bytearray(palette.palette) + + if im.mode == "P": + if not source_palette: + im_palette = im.getpalette(None) + assert im_palette is not None + source_palette = bytearray(im_palette) + else: # L-mode + if not source_palette: + source_palette = bytearray(i // 3 for i in range(768)) + im.palette = ImagePalette.ImagePalette("RGB", palette=source_palette) + assert source_palette is not None + + if palette: + used_palette_colors: list[int | None] = [] + assert im.palette is not None + for i in range(0, len(source_palette), 3): + source_color = tuple(source_palette[i : i + 3]) + index = im.palette.colors.get(source_color) + if index in used_palette_colors: + index = None + used_palette_colors.append(index) + for i, index in enumerate(used_palette_colors): + if index is None: + for j in range(len(used_palette_colors)): + if j not in used_palette_colors: + used_palette_colors[i] = j + break + dest_map: list[int] = [] + for index in used_palette_colors: + assert index is not None + dest_map.append(index) + im = im.remap_palette(dest_map) + else: + optimized_palette_colors = _get_optimize(im, info) + if optimized_palette_colors is not None: + im = im.remap_palette(optimized_palette_colors, source_palette) + if "transparency" in info: + try: + info["transparency"] = optimized_palette_colors.index( + info["transparency"] + ) + except ValueError: + del info["transparency"] + return im + + assert im.palette is not None + im.palette.palette = source_palette + return im + + +def _write_single_frame( + im: Image.Image, + fp: IO[bytes], + palette: _Palette | None, +) -> None: + im_out = _normalize_mode(im) + for k, v in im_out.info.items(): + if isinstance(k, str): + im.encoderinfo.setdefault(k, v) + im_out = _normalize_palette(im_out, palette, im.encoderinfo) + + for s in _get_global_header(im_out, im.encoderinfo): + fp.write(s) + + # local image header + flags = 0 + if get_interlace(im): + flags = flags | 64 + _write_local_header(fp, im, (0, 0), flags) + + im_out.encoderconfig = (8, get_interlace(im)) + ImageFile._save( + im_out, fp, [ImageFile._Tile("gif", (0, 0) + im.size, 0, RAWMODE[im_out.mode])] + ) + + fp.write(b"\0") # end of image data + + +def _getbbox( + base_im: Image.Image, im_frame: Image.Image +) -> tuple[Image.Image, tuple[int, int, int, int] | None]: + palette_bytes = [ + bytes(im.palette.palette) if im.palette else b"" for im in (base_im, im_frame) + ] + if palette_bytes[0] != palette_bytes[1]: + im_frame = im_frame.convert("RGBA") + base_im = base_im.convert("RGBA") + delta = ImageChops.subtract_modulo(im_frame, base_im) + return delta, delta.getbbox(alpha_only=False) + + +class _Frame(NamedTuple): + im: Image.Image + bbox: tuple[int, int, int, int] | None + encoderinfo: dict[str, Any] + + +def _write_multiple_frames( + im: Image.Image, fp: IO[bytes], palette: _Palette | None +) -> bool: + duration = im.encoderinfo.get("duration") + disposal = im.encoderinfo.get("disposal", im.info.get("disposal")) + + im_frames: list[_Frame] = [] + previous_im: Image.Image | None = None + frame_count = 0 + background_im = None + for imSequence in itertools.chain([im], im.encoderinfo.get("append_images", [])): + for im_frame in ImageSequence.Iterator(imSequence): + # a copy is required here since seek can still mutate the image + im_frame = _normalize_mode(im_frame.copy()) + if frame_count == 0: + for k, v in im_frame.info.items(): + if k == "transparency": + continue + if isinstance(k, str): + im.encoderinfo.setdefault(k, v) + + encoderinfo = im.encoderinfo.copy() + if "transparency" in im_frame.info: + encoderinfo.setdefault("transparency", im_frame.info["transparency"]) + im_frame = _normalize_palette(im_frame, palette, encoderinfo) + if isinstance(duration, (list, tuple)): + encoderinfo["duration"] = duration[frame_count] + elif duration is None and "duration" in im_frame.info: + encoderinfo["duration"] = im_frame.info["duration"] + if isinstance(disposal, (list, tuple)): + encoderinfo["disposal"] = disposal[frame_count] + frame_count += 1 + + diff_frame = None + if im_frames and previous_im: + # delta frame + delta, bbox = _getbbox(previous_im, im_frame) + if not bbox: + # This frame is identical to the previous frame + if encoderinfo.get("duration"): + im_frames[-1].encoderinfo["duration"] += encoderinfo["duration"] + continue + if im_frames[-1].encoderinfo.get("disposal") == 2: + # To appear correctly in viewers using a convention, + # only consider transparency, and not background color + color = im.encoderinfo.get( + "transparency", im.info.get("transparency") + ) + if color is not None: + if background_im is None: + background = _get_background(im_frame, color) + background_im = Image.new("P", im_frame.size, background) + first_palette = im_frames[0].im.palette + assert first_palette is not None + background_im.putpalette(first_palette, first_palette.mode) + bbox = _getbbox(background_im, im_frame)[1] + else: + bbox = (0, 0) + im_frame.size + elif encoderinfo.get("optimize") and im_frame.mode != "1": + if "transparency" not in encoderinfo: + assert im_frame.palette is not None + try: + encoderinfo["transparency"] = ( + im_frame.palette._new_color_index(im_frame) + ) + except ValueError: + pass + if "transparency" in encoderinfo: + # When the delta is zero, fill the image with transparency + diff_frame = im_frame.copy() + fill = Image.new("P", delta.size, encoderinfo["transparency"]) + if delta.mode == "RGBA": + r, g, b, a = delta.split() + mask = ImageMath.lambda_eval( + lambda args: args["convert"]( + args["max"]( + args["max"]( + args["max"](args["r"], args["g"]), args["b"] + ), + args["a"], + ) + * 255, + "1", + ), + r=r, + g=g, + b=b, + a=a, + ) + else: + if delta.mode == "P": + # Convert to L without considering palette + delta_l = Image.new("L", delta.size) + delta_l.putdata(delta.get_flattened_data()) + delta = delta_l + mask = ImageMath.lambda_eval( + lambda args: args["convert"](args["im"] * 255, "1"), + im=delta, + ) + diff_frame.paste(fill, mask=ImageOps.invert(mask)) + else: + bbox = None + previous_im = im_frame + im_frames.append(_Frame(diff_frame or im_frame, bbox, encoderinfo)) + + if len(im_frames) == 1: + if "duration" in im.encoderinfo: + # Since multiple frames will not be written, use the combined duration + im.encoderinfo["duration"] = im_frames[0].encoderinfo["duration"] + return False + + for frame_data in im_frames: + im_frame = frame_data.im + if not frame_data.bbox: + # global header + for s in _get_global_header(im_frame, frame_data.encoderinfo): + fp.write(s) + offset = (0, 0) + else: + # compress difference + if not palette: + frame_data.encoderinfo["include_color_table"] = True + + if frame_data.bbox != (0, 0) + im_frame.size: + im_frame = im_frame.crop(frame_data.bbox) + offset = frame_data.bbox[:2] + _write_frame_data(fp, im_frame, offset, frame_data.encoderinfo) + return True + + +def _save_all(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None: + _save(im, fp, filename, save_all=True) + + +def _save( + im: Image.Image, fp: IO[bytes], filename: str | bytes, save_all: bool = False +) -> None: + # header + if "palette" in im.encoderinfo or "palette" in im.info: + palette = im.encoderinfo.get("palette", im.info.get("palette")) + else: + palette = None + im.encoderinfo.setdefault("optimize", True) + + if not save_all or not _write_multiple_frames(im, fp, palette): + _write_single_frame(im, fp, palette) + + fp.write(b";") # end of file + + if hasattr(fp, "flush"): + fp.flush() + + +def get_interlace(im: Image.Image) -> int: + interlace = im.encoderinfo.get("interlace", 1) + + # workaround for @PIL153 + if min(im.size) < 16: + interlace = 0 + + return interlace + + +def _write_local_header( + fp: IO[bytes], im: Image.Image, offset: tuple[int, int], flags: int +) -> None: + try: + transparency = im.encoderinfo["transparency"] + except KeyError: + transparency = None + + if "duration" in im.encoderinfo: + duration = int(im.encoderinfo["duration"] / 10) + else: + duration = 0 + + disposal = int(im.encoderinfo.get("disposal", 0)) + + if transparency is not None or duration != 0 or disposal: + packed_flag = 1 if transparency is not None else 0 + packed_flag |= disposal << 2 + + fp.write( + b"!" + + o8(249) # extension intro + + o8(4) # length + + o8(packed_flag) # packed fields + + o16(duration) # duration + + o8(transparency or 0) # transparency index + + o8(0) + ) + + include_color_table = im.encoderinfo.get("include_color_table") + if include_color_table: + palette_bytes = _get_palette_bytes(im) + color_table_size = _get_color_table_size(palette_bytes) + if color_table_size: + flags = flags | 128 # local color table flag + flags = flags | color_table_size + + fp.write( + b"," + + o16(offset[0]) # offset + + o16(offset[1]) + + o16(im.size[0]) # size + + o16(im.size[1]) + + o8(flags) # flags + ) + if include_color_table and color_table_size: + fp.write(_get_header_palette(palette_bytes)) + fp.write(o8(8)) # bits + + +def _save_netpbm(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None: + # Unused by default. + # To use, uncomment the register_save call at the end of the file. + # + # If you need real GIF compression and/or RGB quantization, you + # can use the external NETPBM/PBMPLUS utilities. See comments + # below for information on how to enable this. + tempfile = im._dump() + + try: + with open(filename, "wb") as f: + if im.mode != "RGB": + subprocess.check_call( + ["ppmtogif", tempfile], stdout=f, stderr=subprocess.DEVNULL + ) + else: + # Pipe ppmquant output into ppmtogif + # "ppmquant 256 %s | ppmtogif > %s" % (tempfile, filename) + quant_cmd = ["ppmquant", "256", tempfile] + togif_cmd = ["ppmtogif"] + quant_proc = subprocess.Popen( + quant_cmd, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL + ) + togif_proc = subprocess.Popen( + togif_cmd, + stdin=quant_proc.stdout, + stdout=f, + stderr=subprocess.DEVNULL, + ) + + # Allow ppmquant to receive SIGPIPE if ppmtogif exits + assert quant_proc.stdout is not None + quant_proc.stdout.close() + + retcode = quant_proc.wait() + if retcode: + raise subprocess.CalledProcessError(retcode, quant_cmd) + + retcode = togif_proc.wait() + if retcode: + raise subprocess.CalledProcessError(retcode, togif_cmd) + finally: + try: + os.unlink(tempfile) + except OSError: + pass + + +# Force optimization so that we can test performance against +# cases where it took lots of memory and time previously. +_FORCE_OPTIMIZE = False + + +def _get_optimize(im: Image.Image, info: dict[str, Any]) -> list[int] | None: + """ + Palette optimization is a potentially expensive operation. + + This function determines if the palette should be optimized using + some heuristics, then returns the list of palette entries in use. + + :param im: Image object + :param info: encoderinfo + :returns: list of indexes of palette entries in use, or None + """ + if ( + im.mode in ("P", "L") + and info + and info.get("optimize") + and im.width != 0 + and im.height != 0 + ): + # Potentially expensive operation. + + # The palette saves 3 bytes per color not used, but palette + # lengths are restricted to 3*(2**N) bytes. Max saving would + # be 768 -> 6 bytes if we went all the way down to 2 colors. + # * If we're over 128 colors, we can't save any space. + # * If there aren't any holes, it's not worth collapsing. + # * If we have a 'large' image, the palette is in the noise. + + # create the new palette if not every color is used + optimise = _FORCE_OPTIMIZE or im.mode == "L" + if optimise or im.width * im.height < 512 * 512: + # check which colors are used + used_palette_colors = [] + for i, count in enumerate(im.histogram()): + if count: + used_palette_colors.append(i) + + if optimise or max(used_palette_colors) >= len(used_palette_colors): + return used_palette_colors + + assert im.palette is not None + num_palette_colors = len(im.palette.palette) // Image.getmodebands( + im.palette.mode + ) + current_palette_size = 1 << (num_palette_colors - 1).bit_length() + if ( + # check that the palette would become smaller when saved + len(used_palette_colors) <= current_palette_size // 2 + # check that the palette is not already the smallest possible size + and current_palette_size > 2 + ): + return used_palette_colors + return None + + +def _get_color_table_size(palette_bytes: bytes) -> int: + # calculate the palette size for the header + if not palette_bytes: + return 0 + elif len(palette_bytes) < 9: + return 1 + else: + return math.ceil(math.log(len(palette_bytes) // 3, 2)) - 1 + + +def _get_header_palette(palette_bytes: bytes) -> bytes: + """ + Returns the palette, null padded to the next power of 2 (*3) bytes + suitable for direct inclusion in the GIF header + + :param palette_bytes: Unpadded palette bytes, in RGBRGB form + :returns: Null padded palette + """ + color_table_size = _get_color_table_size(palette_bytes) + + # add the missing amount of bytes + # the palette has to be 2< 0: + palette_bytes += o8(0) * 3 * actual_target_size_diff + return palette_bytes + + +def _get_palette_bytes(im: Image.Image) -> bytes: + """ + Gets the palette for inclusion in the gif header + + :param im: Image object + :returns: Bytes, len<=768 suitable for inclusion in gif header + """ + if not im.palette: + return b"" + + palette = bytes(im.palette.palette) + if im.palette.mode == "RGBA": + palette = b"".join(palette[i * 4 : i * 4 + 3] for i in range(len(palette) // 3)) + return palette + + +def _get_background( + im: Image.Image, + info_background: int | tuple[int, int, int] | tuple[int, int, int, int] | None, +) -> int: + background = 0 + if info_background: + if isinstance(info_background, tuple): + # WebPImagePlugin stores an RGBA value in info["background"] + # So it must be converted to the same format as GifImagePlugin's + # info["background"] - a global color table index + assert im.palette is not None + try: + background = im.palette.getcolor(info_background, im) + except ValueError as e: + if str(e) not in ( + # If all 256 colors are in use, + # then there is no need for the background color + "cannot allocate more than 256 colors", + # Ignore non-opaque WebP background + "cannot add non-opaque RGBA color to RGB palette", + ): + raise + else: + background = info_background + return background + + +def _get_global_header(im: Image.Image, info: dict[str, Any]) -> list[bytes]: + """Return a list of strings representing a GIF header""" + + # Header Block + # https://www.matthewflickinger.com/lab/whatsinagif/bits_and_bytes.asp + + version = b"87a" + if im.info.get("version") == b"89a" or ( + info + and ( + "transparency" in info + or info.get("loop") is not None + or info.get("duration") + or info.get("comment") + ) + ): + version = b"89a" + + background = _get_background(im, info.get("background")) + + palette_bytes = _get_palette_bytes(im) + color_table_size = _get_color_table_size(palette_bytes) + + header = [ + b"GIF" # signature + + version # version + + o16(im.size[0]) # canvas width + + o16(im.size[1]), # canvas height + # Logical Screen Descriptor + # size of global color table + global color table flag + o8(color_table_size + 128), # packed fields + # background + reserved/aspect + o8(background) + o8(0), + # Global Color Table + _get_header_palette(palette_bytes), + ] + if info.get("loop") is not None: + header.append( + b"!" + + o8(255) # extension intro + + o8(11) + + b"NETSCAPE2.0" + + o8(3) + + o8(1) + + o16(info["loop"]) # number of loops + + o8(0) + ) + if info.get("comment"): + comment_block = b"!" + o8(254) # extension intro + + comment = info["comment"] + if isinstance(comment, str): + comment = comment.encode() + for i in range(0, len(comment), 255): + subblock = comment[i : i + 255] + comment_block += o8(len(subblock)) + subblock + + comment_block += o8(0) + header.append(comment_block) + return header + + +def _write_frame_data( + fp: IO[bytes], + im_frame: Image.Image, + offset: tuple[int, int], + params: dict[str, Any], +) -> None: + try: + im_frame.encoderinfo = params + + # local image header + _write_local_header(fp, im_frame, offset, 0) + + ImageFile._save( + im_frame, + fp, + [ImageFile._Tile("gif", (0, 0) + im_frame.size, 0, RAWMODE[im_frame.mode])], + ) + + fp.write(b"\0") # end of image data + finally: + del im_frame.encoderinfo + + +# -------------------------------------------------------------------- +# Legacy GIF utilities + + +def getheader( + im: Image.Image, palette: _Palette | None = None, info: dict[str, Any] | None = None +) -> tuple[list[bytes], list[int] | None]: + """ + Legacy Method to get Gif data from image. + + Warning:: May modify image data. + + :param im: Image object + :param palette: bytes object containing the source palette, or .... + :param info: encoderinfo + :returns: tuple of(list of header items, optimized palette) + + """ + if info is None: + info = {} + + used_palette_colors = _get_optimize(im, info) + + if "background" not in info and "background" in im.info: + info["background"] = im.info["background"] + + im_mod = _normalize_palette(im, palette, info) + im.palette = im_mod.palette + im.im = im_mod.im + header = _get_global_header(im, info) + + return header, used_palette_colors + + +def getdata( + im: Image.Image, offset: tuple[int, int] = (0, 0), **params: Any +) -> list[bytes]: + """ + Legacy Method + + Return a list of strings representing this image. + The first string is a local image header, the rest contains + encoded image data. + + To specify duration, add the time in milliseconds, + e.g. ``getdata(im_frame, duration=1000)`` + + :param im: Image object + :param offset: Tuple of (x, y) pixels. Defaults to (0, 0) + :param \\**params: e.g. duration or other encoder info parameters + :returns: List of bytes containing GIF encoded frame data + + """ + from io import BytesIO + + class Collector(BytesIO): + data = [] + + def write(self, data: Buffer) -> int: + self.data.append(data) + return len(data) + + im.load() # make sure raster data is available + + fp = Collector() + + _write_frame_data(fp, im, offset, params) + + return fp.data + + +# -------------------------------------------------------------------- +# Registry + +Image.register_open(GifImageFile.format, GifImageFile, _accept) +Image.register_save(GifImageFile.format, _save) +Image.register_save_all(GifImageFile.format, _save_all) +Image.register_extension(GifImageFile.format, ".gif") +Image.register_mime(GifImageFile.format, "image/gif") + +# +# Uncomment the following line if you wish to use NETPBM/PBMPLUS +# instead of the built-in "uncompressed" GIF encoder + +# Image.register_save(GifImageFile.format, _save_netpbm) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/GimpGradientFile.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/GimpGradientFile.py new file mode 100644 index 000000000..fb9587218 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/GimpGradientFile.py @@ -0,0 +1,154 @@ +# +# Python Imaging Library +# $Id$ +# +# stuff to read (and render) GIMP gradient files +# +# History: +# 97-08-23 fl Created +# +# Copyright (c) Secret Labs AB 1997. +# Copyright (c) Fredrik Lundh 1997. +# +# See the README file for information on usage and redistribution. +# + +""" +Stuff to translate curve segments to palette values (derived from +the corresponding code in GIMP, written by Federico Mena Quintero. +See the GIMP distribution for more information.) +""" + +from __future__ import annotations + +from math import log, pi, sin, sqrt + +from ._binary import o8 + +TYPE_CHECKING = False +if TYPE_CHECKING: + from collections.abc import Callable + from typing import IO + +EPSILON = 1e-10 +"""""" # Enable auto-doc for data member + + +def linear(middle: float, pos: float) -> float: + if pos <= middle: + if middle < EPSILON: + return 0.0 + else: + return 0.5 * pos / middle + else: + pos = pos - middle + middle = 1.0 - middle + if middle < EPSILON: + return 1.0 + else: + return 0.5 + 0.5 * pos / middle + + +def curved(middle: float, pos: float) -> float: + return pos ** (log(0.5) / log(max(middle, EPSILON))) + + +def sine(middle: float, pos: float) -> float: + return (sin((-pi / 2.0) + pi * linear(middle, pos)) + 1.0) / 2.0 + + +def sphere_increasing(middle: float, pos: float) -> float: + return sqrt(1.0 - (linear(middle, pos) - 1.0) ** 2) + + +def sphere_decreasing(middle: float, pos: float) -> float: + return 1.0 - sqrt(1.0 - linear(middle, pos) ** 2) + + +SEGMENTS = [linear, curved, sine, sphere_increasing, sphere_decreasing] +"""""" # Enable auto-doc for data member + + +class GradientFile: + gradient: ( + list[ + tuple[ + float, + float, + float, + list[float], + list[float], + Callable[[float, float], float], + ] + ] + | None + ) = None + + def getpalette(self, entries: int = 256) -> tuple[bytes, str]: + assert self.gradient is not None + palette = [] + + ix = 0 + x0, x1, xm, rgb0, rgb1, segment = self.gradient[ix] + + for i in range(entries): + x = i / (entries - 1) + + while x1 < x: + ix += 1 + x0, x1, xm, rgb0, rgb1, segment = self.gradient[ix] + + w = x1 - x0 + + if w < EPSILON: + scale = segment(0.5, 0.5) + else: + scale = segment((xm - x0) / w, (x - x0) / w) + + # expand to RGBA + r = o8(int(255 * ((rgb1[0] - rgb0[0]) * scale + rgb0[0]) + 0.5)) + g = o8(int(255 * ((rgb1[1] - rgb0[1]) * scale + rgb0[1]) + 0.5)) + b = o8(int(255 * ((rgb1[2] - rgb0[2]) * scale + rgb0[2]) + 0.5)) + a = o8(int(255 * ((rgb1[3] - rgb0[3]) * scale + rgb0[3]) + 0.5)) + + # add to palette + palette.append(r + g + b + a) + + return b"".join(palette), "RGBA" + + +class GimpGradientFile(GradientFile): + """File handler for GIMP's gradient format.""" + + def __init__(self, fp: IO[bytes]) -> None: + if not fp.readline().startswith(b"GIMP Gradient"): + msg = "not a GIMP gradient file" + raise SyntaxError(msg) + + line = fp.readline() + + # GIMP 1.2 gradient files don't contain a name, but GIMP 1.3 files do + if line.startswith(b"Name: "): + line = fp.readline().strip() + + count = int(line) + + self.gradient = [] + + for i in range(count): + s = fp.readline().split() + w = [float(x) for x in s[:11]] + + x0, x1 = w[0], w[2] + xm = w[1] + rgb0 = w[3:7] + rgb1 = w[7:11] + + segment = SEGMENTS[int(s[11])] + cspace = int(s[12]) + + if cspace != 0: + msg = "cannot handle HSV colour space" + raise OSError(msg) + + self.gradient.append((x0, x1, xm, rgb0, rgb1, segment)) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/GimpPaletteFile.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/GimpPaletteFile.py new file mode 100644 index 000000000..016257d3d --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/GimpPaletteFile.py @@ -0,0 +1,75 @@ +# +# Python Imaging Library +# $Id$ +# +# stuff to read GIMP palette files +# +# History: +# 1997-08-23 fl Created +# 2004-09-07 fl Support GIMP 2.0 palette files. +# +# Copyright (c) Secret Labs AB 1997-2004. All rights reserved. +# Copyright (c) Fredrik Lundh 1997-2004. +# +# See the README file for information on usage and redistribution. +# +from __future__ import annotations + +import re +from io import BytesIO + +TYPE_CHECKING = False +if TYPE_CHECKING: + from typing import IO + + +class GimpPaletteFile: + """File handler for GIMP's palette format.""" + + rawmode = "RGB" + + def _read(self, fp: IO[bytes], limit: bool = True) -> None: + if not fp.readline().startswith(b"GIMP Palette"): + msg = "not a GIMP palette file" + raise SyntaxError(msg) + + palette: list[int] = [] + i = 0 + while True: + if limit and i == 256 + 3: + break + + i += 1 + s = fp.readline() + if not s: + break + + # skip fields and comment lines + if re.match(rb"\w+:|#", s): + continue + if limit and len(s) > 100: + msg = "bad palette file" + raise SyntaxError(msg) + + v = s.split(maxsplit=3) + if len(v) < 3: + msg = "bad palette entry" + raise ValueError(msg) + + palette += (int(v[i]) for i in range(3)) + if limit and len(palette) == 768: + break + + self.palette = bytes(palette) + + def __init__(self, fp: IO[bytes]) -> None: + self._read(fp) + + @classmethod + def frombytes(cls, data: bytes) -> GimpPaletteFile: + self = cls.__new__(cls) + self._read(BytesIO(data), False) + return self + + def getpalette(self) -> tuple[bytes, str]: + return self.palette, self.rawmode diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/GribStubImagePlugin.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/GribStubImagePlugin.py new file mode 100644 index 000000000..3784ef2f1 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/GribStubImagePlugin.py @@ -0,0 +1,72 @@ +# +# The Python Imaging Library +# $Id$ +# +# GRIB stub adapter +# +# Copyright (c) 1996-2003 by Fredrik Lundh +# +# See the README file for information on usage and redistribution. +# +from __future__ import annotations + +import os +from typing import IO + +from . import Image, ImageFile + +_handler = None + + +def register_handler(handler: ImageFile.StubHandler | None) -> None: + """ + Install application-specific GRIB image handler. + + :param handler: Handler object. + """ + global _handler + _handler = handler + + +# -------------------------------------------------------------------- +# Image adapter + + +def _accept(prefix: bytes) -> bool: + return len(prefix) >= 8 and prefix.startswith(b"GRIB") and prefix[7] == 1 + + +class GribStubImageFile(ImageFile.StubImageFile): + format = "GRIB" + format_description = "GRIB" + + def _open(self) -> None: + assert self.fp is not None + if not _accept(self.fp.read(8)): + msg = "Not a GRIB file" + raise SyntaxError(msg) + + self.fp.seek(-8, os.SEEK_CUR) + + # make something up + self._mode = "F" + self._size = 1, 1 + + def _load(self) -> ImageFile.StubHandler | None: + return _handler + + +def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None: + if _handler is None or not hasattr(_handler, "save"): + msg = "GRIB save handler not installed" + raise OSError(msg) + _handler.save(im, fp, filename) + + +# -------------------------------------------------------------------- +# Registry + +Image.register_open(GribStubImageFile.format, GribStubImageFile, _accept) +Image.register_save(GribStubImageFile.format, _save) + +Image.register_extension(GribStubImageFile.format, ".grib") diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/Hdf5StubImagePlugin.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/Hdf5StubImagePlugin.py new file mode 100644 index 000000000..1a56660f7 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/Hdf5StubImagePlugin.py @@ -0,0 +1,72 @@ +# +# The Python Imaging Library +# $Id$ +# +# HDF5 stub adapter +# +# Copyright (c) 2000-2003 by Fredrik Lundh +# +# See the README file for information on usage and redistribution. +# +from __future__ import annotations + +import os +from typing import IO + +from . import Image, ImageFile + +_handler = None + + +def register_handler(handler: ImageFile.StubHandler | None) -> None: + """ + Install application-specific HDF5 image handler. + + :param handler: Handler object. + """ + global _handler + _handler = handler + + +# -------------------------------------------------------------------- +# Image adapter + + +def _accept(prefix: bytes) -> bool: + return prefix.startswith(b"\x89HDF\r\n\x1a\n") + + +class HDF5StubImageFile(ImageFile.StubImageFile): + format = "HDF5" + format_description = "HDF5" + + def _open(self) -> None: + assert self.fp is not None + if not _accept(self.fp.read(8)): + msg = "Not an HDF file" + raise SyntaxError(msg) + + self.fp.seek(-8, os.SEEK_CUR) + + # make something up + self._mode = "F" + self._size = 1, 1 + + def _load(self) -> ImageFile.StubHandler | None: + return _handler + + +def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None: + if _handler is None or not hasattr(_handler, "save"): + msg = "HDF5 save handler not installed" + raise OSError(msg) + _handler.save(im, fp, filename) + + +# -------------------------------------------------------------------- +# Registry + +Image.register_open(HDF5StubImageFile.format, HDF5StubImageFile, _accept) +Image.register_save(HDF5StubImageFile.format, _save) + +Image.register_extensions(HDF5StubImageFile.format, [".h5", ".hdf"]) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/IcnsImagePlugin.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/IcnsImagePlugin.py new file mode 100644 index 000000000..cb7a74c2e --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/IcnsImagePlugin.py @@ -0,0 +1,401 @@ +# +# The Python Imaging Library. +# $Id$ +# +# macOS icns file decoder, based on icns.py by Bob Ippolito. +# +# history: +# 2004-10-09 fl Turned into a PIL plugin; removed 2.3 dependencies. +# 2020-04-04 Allow saving on all operating systems. +# +# Copyright (c) 2004 by Bob Ippolito. +# Copyright (c) 2004 by Secret Labs. +# Copyright (c) 2004 by Fredrik Lundh. +# Copyright (c) 2014 by Alastair Houghton. +# Copyright (c) 2020 by Pan Jing. +# +# See the README file for information on usage and redistribution. +# +from __future__ import annotations + +import io +import os +import struct +import sys +from typing import IO + +from . import Image, ImageFile, PngImagePlugin, features + +enable_jpeg2k = features.check_codec("jpg_2000") +if enable_jpeg2k: + from . import Jpeg2KImagePlugin + +MAGIC = b"icns" +HEADERSIZE = 8 + + +def nextheader(fobj: IO[bytes]) -> tuple[bytes, int]: + return struct.unpack(">4sI", fobj.read(HEADERSIZE)) + + +def read_32t( + fobj: IO[bytes], start_length: tuple[int, int], size: tuple[int, int, int] +) -> dict[str, Image.Image]: + # The 128x128 icon seems to have an extra header for some reason. + start, length = start_length + fobj.seek(start) + sig = fobj.read(4) + if sig != b"\x00\x00\x00\x00": + msg = "Unknown signature, expecting 0x00000000" + raise SyntaxError(msg) + return read_32(fobj, (start + 4, length - 4), size) + + +def read_32( + fobj: IO[bytes], start_length: tuple[int, int], size: tuple[int, int, int] +) -> dict[str, Image.Image]: + """ + Read a 32bit RGB icon resource. Seems to be either uncompressed or + an RLE packbits-like scheme. + """ + start, length = start_length + fobj.seek(start) + pixel_size = (size[0] * size[2], size[1] * size[2]) + sizesq = pixel_size[0] * pixel_size[1] + if length == sizesq * 3: + # uncompressed ("RGBRGBGB") + indata = fobj.read(length) + im = Image.frombuffer("RGB", pixel_size, indata, "raw", "RGB", 0, 1) + else: + # decode image + im = Image.new("RGB", pixel_size, None) + for band_ix in range(3): + data = [] + bytesleft = sizesq + while bytesleft > 0: + byte = fobj.read(1) + if not byte: + break + byte_int = byte[0] + if byte_int & 0x80: + blocksize = byte_int - 125 + byte = fobj.read(1) + data.extend([byte] * blocksize) + else: + blocksize = byte_int + 1 + data.append(fobj.read(blocksize)) + bytesleft -= blocksize + if bytesleft <= 0: + break + if bytesleft != 0: + msg = f"Error reading channel [{repr(bytesleft)} left]" + raise SyntaxError(msg) + band = Image.frombuffer("L", pixel_size, b"".join(data), "raw", "L", 0, 1) + im.im.putband(band.im, band_ix) + return {"RGB": im} + + +def read_mk( + fobj: IO[bytes], start_length: tuple[int, int], size: tuple[int, int, int] +) -> dict[str, Image.Image]: + # Alpha masks seem to be uncompressed + start = start_length[0] + fobj.seek(start) + pixel_size = (size[0] * size[2], size[1] * size[2]) + sizesq = pixel_size[0] * pixel_size[1] + band = Image.frombuffer("L", pixel_size, fobj.read(sizesq), "raw", "L", 0, 1) + return {"A": band} + + +def read_png_or_jpeg2000( + fobj: IO[bytes], start_length: tuple[int, int], size: tuple[int, int, int] +) -> dict[str, Image.Image]: + start, length = start_length + fobj.seek(start) + sig = fobj.read(12) + + im: Image.Image + if sig.startswith(b"\x89PNG\x0d\x0a\x1a\x0a"): + fobj.seek(start) + im = PngImagePlugin.PngImageFile(fobj) + Image._decompression_bomb_check(im.size) + return {"RGBA": im} + elif ( + sig.startswith((b"\xff\x4f\xff\x51", b"\x0d\x0a\x87\x0a")) + or sig == b"\x00\x00\x00\x0cjP \x0d\x0a\x87\x0a" + ): + if not enable_jpeg2k: + msg = ( + "Unsupported icon subimage format (rebuild PIL " + "with JPEG 2000 support to fix this)" + ) + raise ValueError(msg) + # j2k, jpc or j2c + fobj.seek(start) + jp2kstream = fobj.read(length) + f = io.BytesIO(jp2kstream) + im = Jpeg2KImagePlugin.Jpeg2KImageFile(f) + Image._decompression_bomb_check(im.size) + if im.mode != "RGBA": + im = im.convert("RGBA") + return {"RGBA": im} + else: + msg = "Unsupported icon subimage format" + raise ValueError(msg) + + +class IcnsFile: + SIZES = { + (512, 512, 2): [(b"ic10", read_png_or_jpeg2000)], + (512, 512, 1): [(b"ic09", read_png_or_jpeg2000)], + (256, 256, 2): [(b"ic14", read_png_or_jpeg2000)], + (256, 256, 1): [(b"ic08", read_png_or_jpeg2000)], + (128, 128, 2): [(b"ic13", read_png_or_jpeg2000)], + (128, 128, 1): [ + (b"ic07", read_png_or_jpeg2000), + (b"it32", read_32t), + (b"t8mk", read_mk), + ], + (64, 64, 1): [(b"icp6", read_png_or_jpeg2000)], + (32, 32, 2): [(b"ic12", read_png_or_jpeg2000)], + (48, 48, 1): [(b"ih32", read_32), (b"h8mk", read_mk)], + (32, 32, 1): [ + (b"icp5", read_png_or_jpeg2000), + (b"il32", read_32), + (b"l8mk", read_mk), + ], + (16, 16, 2): [(b"ic11", read_png_or_jpeg2000)], + (16, 16, 1): [ + (b"icp4", read_png_or_jpeg2000), + (b"is32", read_32), + (b"s8mk", read_mk), + ], + } + + def __init__(self, fobj: IO[bytes]) -> None: + """ + fobj is a file-like object as an icns resource + """ + # signature : (start, length) + self.dct = {} + self.fobj = fobj + sig, filesize = nextheader(fobj) + if not _accept(sig): + msg = "not an icns file" + raise SyntaxError(msg) + i = HEADERSIZE + while i < filesize: + sig, blocksize = nextheader(fobj) + if blocksize <= 0: + msg = "invalid block header" + raise SyntaxError(msg) + i += HEADERSIZE + blocksize -= HEADERSIZE + self.dct[sig] = (i, blocksize) + fobj.seek(blocksize, io.SEEK_CUR) + i += blocksize + + def itersizes(self) -> list[tuple[int, int, int]]: + sizes = [] + for size, fmts in self.SIZES.items(): + for fmt, reader in fmts: + if fmt in self.dct: + sizes.append(size) + break + return sizes + + def bestsize(self) -> tuple[int, int, int]: + sizes = self.itersizes() + if not sizes: + msg = "No 32bit icon resources found" + raise SyntaxError(msg) + return max(sizes) + + def dataforsize(self, size: tuple[int, int, int]) -> dict[str, Image.Image]: + """ + Get an icon resource as {channel: array}. Note that + the arrays are bottom-up like windows bitmaps and will likely + need to be flipped or transposed in some way. + """ + dct = {} + for code, reader in self.SIZES[size]: + desc = self.dct.get(code) + if desc is not None: + dct.update(reader(self.fobj, desc, size)) + return dct + + def getimage( + self, size: tuple[int, int] | tuple[int, int, int] | None = None + ) -> Image.Image: + if size is None: + size = self.bestsize() + elif len(size) == 2: + size = (size[0], size[1], 1) + channels = self.dataforsize(size) + + im = channels.get("RGBA") + if im: + return im + + im = channels["RGB"].copy() + try: + im.putalpha(channels["A"]) + except KeyError: + pass + return im + + +## +# Image plugin for Mac OS icons. + + +class IcnsImageFile(ImageFile.ImageFile): + """ + PIL image support for Mac OS .icns files. + Chooses the best resolution, but will possibly load + a different size image if you mutate the size attribute + before calling 'load'. + + The info dictionary has a key 'sizes' that is a list + of sizes that the icns file has. + """ + + format = "ICNS" + format_description = "Mac OS icns resource" + + def _open(self) -> None: + assert self.fp is not None + self.icns = IcnsFile(self.fp) + self._mode = "RGBA" + self.info["sizes"] = self.icns.itersizes() + self.best_size = self.icns.bestsize() + self.size = ( + self.best_size[0] * self.best_size[2], + self.best_size[1] * self.best_size[2], + ) + + @property + def size(self) -> tuple[int, int]: + return self._size + + @size.setter + def size(self, value: tuple[int, int]) -> None: + # Check that a matching size exists, + # or that there is a scale that would create a size that matches + for size in self.info["sizes"]: + simple_size = size[0] * size[2], size[1] * size[2] + scale = simple_size[0] // value[0] + if simple_size[1] / value[1] == scale: + self._size = value + return + msg = "This is not one of the allowed sizes of this image" + raise ValueError(msg) + + def load(self, scale: int | None = None) -> Image.core.PixelAccess | None: + if scale is not None: + width, height = self.size[:2] + self.size = width * scale, height * scale + self.best_size = width, height, scale + + px = Image.Image.load(self) + if self._im is not None and self.im.size == self.size: + # Already loaded + return px + self.load_prepare() + # This is likely NOT the best way to do it, but whatever. + im = self.icns.getimage(self.best_size) + + # If this is a PNG or JPEG 2000, it won't be loaded yet + px = im.load() + + self.im = im.im + self._mode = im.mode + self.size = im.size + + return px + + +def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None: + """ + Saves the image as a series of PNG files, + that are then combined into a .icns file. + """ + if hasattr(fp, "flush"): + fp.flush() + + sizes = { + b"ic07": 128, + b"ic08": 256, + b"ic09": 512, + b"ic10": 1024, + b"ic11": 32, + b"ic12": 64, + b"ic13": 256, + b"ic14": 512, + } + provided_images = {im.width: im for im in im.encoderinfo.get("append_images", [])} + size_streams = {} + for size in set(sizes.values()): + image = ( + provided_images[size] + if size in provided_images + else im.resize((size, size)) + ) + + temp = io.BytesIO() + image.save(temp, "png") + size_streams[size] = temp.getvalue() + + entries = [] + for type, size in sizes.items(): + stream = size_streams[size] + entries.append((type, HEADERSIZE + len(stream), stream)) + + # Header + fp.write(MAGIC) + file_length = HEADERSIZE # Header + file_length += HEADERSIZE + 8 * len(entries) # TOC + file_length += sum(entry[1] for entry in entries) + fp.write(struct.pack(">i", file_length)) + + # TOC + fp.write(b"TOC ") + fp.write(struct.pack(">i", HEADERSIZE + len(entries) * HEADERSIZE)) + for entry in entries: + fp.write(entry[0]) + fp.write(struct.pack(">i", entry[1])) + + # Data + for entry in entries: + fp.write(entry[0]) + fp.write(struct.pack(">i", entry[1])) + fp.write(entry[2]) + + if hasattr(fp, "flush"): + fp.flush() + + +def _accept(prefix: bytes) -> bool: + return prefix.startswith(MAGIC) + + +Image.register_open(IcnsImageFile.format, IcnsImageFile, _accept) +Image.register_extension(IcnsImageFile.format, ".icns") + +Image.register_save(IcnsImageFile.format, _save) +Image.register_mime(IcnsImageFile.format, "image/icns") + +if __name__ == "__main__": + if len(sys.argv) < 2: + print("Syntax: python3 IcnsImagePlugin.py [file]") + sys.exit() + + with open(sys.argv[1], "rb") as fp: + imf = IcnsImageFile(fp) + for size in imf.info["sizes"]: + width, height, scale = imf.size = size + imf.save(f"out-{width}-{height}-{scale}.png") + with Image.open(sys.argv[1]) as im: + im.save("out.png") + if sys.platform == "windows": + os.startfile("out.png") diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/IcoImagePlugin.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/IcoImagePlugin.py new file mode 100644 index 000000000..8dd57ff85 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/IcoImagePlugin.py @@ -0,0 +1,396 @@ +# +# The Python Imaging Library. +# $Id$ +# +# Windows Icon support for PIL +# +# History: +# 96-05-27 fl Created +# +# Copyright (c) Secret Labs AB 1997. +# Copyright (c) Fredrik Lundh 1996. +# +# See the README file for information on usage and redistribution. +# + +# This plugin is a refactored version of Win32IconImagePlugin by Bryan Davis +# . +# https://code.google.com/archive/p/casadebender/wikis/Win32IconImagePlugin.wiki +# +# Copyright 2008 Bryan Davis +# +# Licensed under the Apache License, Version 2.0 (the "License"); you may +# not use this file except in compliance with the License. You may obtain +# a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Icon format references: +# * https://en.wikipedia.org/wiki/ICO_(file_format) +# * https://msdn.microsoft.com/en-us/library/ms997538.aspx +from __future__ import annotations + +import warnings +from io import BytesIO +from math import ceil, log +from typing import IO, NamedTuple + +from . import BmpImagePlugin, Image, ImageFile, PngImagePlugin +from ._binary import i16le as i16 +from ._binary import i32le as i32 +from ._binary import o8 +from ._binary import o16le as o16 +from ._binary import o32le as o32 + +# +# -------------------------------------------------------------------- + +_MAGIC = b"\0\0\1\0" + + +def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None: + fp.write(_MAGIC) # (2+2) + bmp = im.encoderinfo.get("bitmap_format") == "bmp" + sizes = im.encoderinfo.get( + "sizes", + [(16, 16), (24, 24), (32, 32), (48, 48), (64, 64), (128, 128), (256, 256)], + ) + frames = [] + provided_ims = [im] + im.encoderinfo.get("append_images", []) + width, height = im.size + for size in sorted(set(sizes)): + if size[0] > width or size[1] > height or size[0] > 256 or size[1] > 256: + continue + + for provided_im in provided_ims: + if provided_im.size != size: + continue + frames.append(provided_im) + if bmp: + bits = BmpImagePlugin.SAVE[provided_im.mode][1] + bits_used = [bits] + for other_im in provided_ims: + if other_im.size != size: + continue + bits = BmpImagePlugin.SAVE[other_im.mode][1] + if bits not in bits_used: + # Another image has been supplied for this size + # with a different bit depth + frames.append(other_im) + bits_used.append(bits) + break + else: + # TODO: invent a more convenient method for proportional scalings + frame = provided_im.copy() + frame.thumbnail(size, Image.Resampling.LANCZOS, reducing_gap=None) + frames.append(frame) + fp.write(o16(len(frames))) # idCount(2) + offset = fp.tell() + len(frames) * 16 + for frame in frames: + width, height = frame.size + # 0 means 256 + fp.write(o8(width if width < 256 else 0)) # bWidth(1) + fp.write(o8(height if height < 256 else 0)) # bHeight(1) + + bits, colors = BmpImagePlugin.SAVE[frame.mode][1:] if bmp else (32, 0) + fp.write(o8(colors)) # bColorCount(1) + fp.write(b"\0") # bReserved(1) + fp.write(b"\0\0") # wPlanes(2) + fp.write(o16(bits)) # wBitCount(2) + + image_io = BytesIO() + if bmp: + frame.save(image_io, "dib") + + if bits != 32: + and_mask = Image.new("1", size) + ImageFile._save( + and_mask, + image_io, + [ImageFile._Tile("raw", (0, 0) + size, 0, ("1", 0, -1))], + ) + else: + frame.save(image_io, "png") + image_io.seek(0) + image_bytes = image_io.read() + if bmp: + image_bytes = image_bytes[:8] + o32(height * 2) + image_bytes[12:] + bytes_len = len(image_bytes) + fp.write(o32(bytes_len)) # dwBytesInRes(4) + fp.write(o32(offset)) # dwImageOffset(4) + current = fp.tell() + fp.seek(offset) + fp.write(image_bytes) + offset = offset + bytes_len + fp.seek(current) + + +def _accept(prefix: bytes) -> bool: + return prefix.startswith(_MAGIC) + + +class IconHeader(NamedTuple): + width: int + height: int + nb_color: int + reserved: int + planes: int + bpp: int + size: int + offset: int + dim: tuple[int, int] + square: int + color_depth: int + + +class IcoFile: + def __init__(self, buf: IO[bytes]) -> None: + """ + Parse image from file-like object containing ico file data + """ + + # check magic + s = buf.read(6) + if not _accept(s): + msg = "not an ICO file" + raise SyntaxError(msg) + + self.buf = buf + self.entry = [] + + # Number of items in file + self.nb_items = i16(s, 4) + + # Get headers for each item + for i in range(self.nb_items): + s = buf.read(16) + + # See Wikipedia + width = s[0] or 256 + height = s[1] or 256 + + # No. of colors in image (0 if >=8bpp) + nb_color = s[2] + bpp = i16(s, 6) + icon_header = IconHeader( + width=width, + height=height, + nb_color=nb_color, + reserved=s[3], + planes=i16(s, 4), + bpp=i16(s, 6), + size=i32(s, 8), + offset=i32(s, 12), + dim=(width, height), + square=width * height, + # See Wikipedia notes about color depth. + # We need this just to differ images with equal sizes + color_depth=bpp or (nb_color != 0 and ceil(log(nb_color, 2))) or 256, + ) + + self.entry.append(icon_header) + + self.entry = sorted(self.entry, key=lambda x: x.color_depth) + # ICO images are usually squares + self.entry = sorted(self.entry, key=lambda x: x.square, reverse=True) + + def sizes(self) -> set[tuple[int, int]]: + """ + Get a set of all available icon sizes and color depths. + """ + return {(h.width, h.height) for h in self.entry} + + def getentryindex(self, size: tuple[int, int], bpp: int | bool = False) -> int: + for i, h in enumerate(self.entry): + if size == h.dim and (bpp is False or bpp == h.color_depth): + return i + return 0 + + def getimage(self, size: tuple[int, int], bpp: int | bool = False) -> Image.Image: + """ + Get an image from the icon + """ + return self.frame(self.getentryindex(size, bpp)) + + def frame(self, idx: int) -> Image.Image: + """ + Get an image from frame idx + """ + + header = self.entry[idx] + + self.buf.seek(header.offset) + data = self.buf.read(8) + self.buf.seek(header.offset) + + im: Image.Image + if data[:8] == PngImagePlugin._MAGIC: + # png frame + im = PngImagePlugin.PngImageFile(self.buf) + Image._decompression_bomb_check(im.size) + else: + # XOR + AND mask bmp frame + im = BmpImagePlugin.DibImageFile(self.buf) + Image._decompression_bomb_check(im.size) + + # change tile dimension to only encompass XOR image + im._size = (im.size[0], int(im.size[1] / 2)) + d, e, o, a = im.tile[0] + im.tile[0] = ImageFile._Tile(d, (0, 0) + im.size, o, a) + + # figure out where AND mask image starts + if header.bpp == 32: + # 32-bit color depth icon image allows semitransparent areas + # PIL's DIB format ignores transparency bits, recover them. + # The DIB is packed in BGRX byte order where X is the alpha + # channel. + + # Back up to start of bmp data + self.buf.seek(o) + # extract every 4th byte (eg. 3,7,11,15,...) + alpha_bytes = self.buf.read(im.size[0] * im.size[1] * 4)[3::4] + + # convert to an 8bpp grayscale image + try: + mask = Image.frombuffer( + "L", # 8bpp + im.size, # (w, h) + alpha_bytes, # source chars + "raw", # raw decoder + ("L", 0, -1), # 8bpp inverted, unpadded, reversed + ) + except ValueError: + if ImageFile.LOAD_TRUNCATED_IMAGES: + mask = None + else: + raise + else: + # get AND image from end of bitmap + w = im.size[0] + if (w % 32) > 0: + # bitmap row data is aligned to word boundaries + w += 32 - (im.size[0] % 32) + + # the total mask data is + # padded row size * height / bits per char + + total_bytes = int((w * im.size[1]) / 8) + and_mask_offset = header.offset + header.size - total_bytes + + self.buf.seek(and_mask_offset) + mask_data = self.buf.read(total_bytes) + + # convert raw data to image + try: + mask = Image.frombuffer( + "1", # 1 bpp + im.size, # (w, h) + mask_data, # source chars + "raw", # raw decoder + ("1;I", int(w / 8), -1), # 1bpp inverted, padded, reversed + ) + except ValueError: + if ImageFile.LOAD_TRUNCATED_IMAGES: + mask = None + else: + raise + + # now we have two images, im is XOR image and mask is AND image + + # apply mask image as alpha channel + if mask: + im = im.convert("RGBA") + im.putalpha(mask) + + return im + + +## +# Image plugin for Windows Icon files. + + +class IcoImageFile(ImageFile.ImageFile): + """ + PIL read-only image support for Microsoft Windows .ico files. + + By default the largest resolution image in the file will be loaded. This + can be changed by altering the 'size' attribute before calling 'load'. + + The info dictionary has a key 'sizes' that is a list of the sizes available + in the icon file. + + Handles classic, XP and Vista icon formats. + + When saving, PNG compression is used. Support for this was only added in + Windows Vista. If you are unable to view the icon in Windows, convert the + image to "RGBA" mode before saving. + + This plugin is a refactored version of Win32IconImagePlugin by Bryan Davis + . + https://code.google.com/archive/p/casadebender/wikis/Win32IconImagePlugin.wiki + """ + + format = "ICO" + format_description = "Windows Icon" + + def _open(self) -> None: + assert self.fp is not None + self.ico = IcoFile(self.fp) + self.info["sizes"] = self.ico.sizes() + self.size = self.ico.entry[0].dim + self.load() + + @property + def size(self) -> tuple[int, int]: + return self._size + + @size.setter + def size(self, value: tuple[int, int]) -> None: + if value not in self.info["sizes"]: + msg = "This is not one of the allowed sizes of this image" + raise ValueError(msg) + self._size = value + + def load(self) -> Image.core.PixelAccess | None: + if self._im is not None and self.im.size == self.size: + # Already loaded + return Image.Image.load(self) + im = self.ico.getimage(self.size) + # if tile is PNG, it won't really be loaded yet + im.load() + self.im = im.im + self._mode = im.mode + if im.palette: + self.palette = im.palette + if im.size != self.size: + warnings.warn("Image was not the expected size") + + index = self.ico.getentryindex(self.size) + sizes = list(self.info["sizes"]) + sizes[index] = im.size + self.info["sizes"] = set(sizes) + + self.size = im.size + return Image.Image.load(self) + + def load_seek(self, pos: int) -> None: + # Flag the ImageFile.Parser so that it + # just does all the decode at the end. + pass + + +# +# -------------------------------------------------------------------- + + +Image.register_open(IcoImageFile.format, IcoImageFile, _accept) +Image.register_save(IcoImageFile.format, _save) +Image.register_extension(IcoImageFile.format, ".ico") + +Image.register_mime(IcoImageFile.format, "image/x-icon") diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/ImImagePlugin.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/ImImagePlugin.py new file mode 100644 index 000000000..ef54f16e9 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/ImImagePlugin.py @@ -0,0 +1,390 @@ +# +# The Python Imaging Library. +# $Id$ +# +# IFUNC IM file handling for PIL +# +# history: +# 1995-09-01 fl Created. +# 1997-01-03 fl Save palette images +# 1997-01-08 fl Added sequence support +# 1997-01-23 fl Added P and RGB save support +# 1997-05-31 fl Read floating point images +# 1997-06-22 fl Save floating point images +# 1997-08-27 fl Read and save 1-bit images +# 1998-06-25 fl Added support for RGB+LUT images +# 1998-07-02 fl Added support for YCC images +# 1998-07-15 fl Renamed offset attribute to avoid name clash +# 1998-12-29 fl Added I;16 support +# 2001-02-17 fl Use 're' instead of 'regex' (Python 2.1) (0.7) +# 2003-09-26 fl Added LA/PA support +# +# Copyright (c) 1997-2003 by Secret Labs AB. +# Copyright (c) 1995-2001 by Fredrik Lundh. +# +# See the README file for information on usage and redistribution. +# +from __future__ import annotations + +import os +import re +from typing import IO, Any + +from . import Image, ImageFile, ImagePalette +from ._util import DeferredError + +# -------------------------------------------------------------------- +# Standard tags + +COMMENT = "Comment" +DATE = "Date" +EQUIPMENT = "Digitalization equipment" +FRAMES = "File size (no of images)" +LUT = "Lut" +NAME = "Name" +SCALE = "Scale (x,y)" +SIZE = "Image size (x*y)" +MODE = "Image type" + +TAGS = { + COMMENT: 0, + DATE: 0, + EQUIPMENT: 0, + FRAMES: 0, + LUT: 0, + NAME: 0, + SCALE: 0, + SIZE: 0, + MODE: 0, +} + +OPEN = { + # ifunc93/p3cfunc formats + "0 1 image": ("1", "1"), + "L 1 image": ("1", "1"), + "Greyscale image": ("L", "L"), + "Grayscale image": ("L", "L"), + "RGB image": ("RGB", "RGB;L"), + "RLB image": ("RGB", "RLB"), + "RYB image": ("RGB", "RLB"), + "B1 image": ("1", "1"), + "B2 image": ("P", "P;2"), + "B4 image": ("P", "P;4"), + "X 24 image": ("RGB", "RGB"), + "L 32 S image": ("I", "I;32"), + "L 32 F image": ("F", "F;32"), + # old p3cfunc formats + "RGB3 image": ("RGB", "RGB;T"), + "RYB3 image": ("RGB", "RYB;T"), + # extensions + "LA image": ("LA", "LA;L"), + "PA image": ("LA", "PA;L"), + "RGBA image": ("RGBA", "RGBA;L"), + "RGBX image": ("RGB", "RGBX;L"), + "CMYK image": ("CMYK", "CMYK;L"), + "YCC image": ("YCbCr", "YCbCr;L"), +} + +# ifunc95 extensions +for i in ["8", "8S", "16", "16S", "32", "32F"]: + OPEN[f"L {i} image"] = ("F", f"F;{i}") + OPEN[f"L*{i} image"] = ("F", f"F;{i}") +for i in ["16", "16L", "16B"]: + OPEN[f"L {i} image"] = (f"I;{i}", f"I;{i}") + OPEN[f"L*{i} image"] = (f"I;{i}", f"I;{i}") +for i in ["32S"]: + OPEN[f"L {i} image"] = ("I", f"I;{i}") + OPEN[f"L*{i} image"] = ("I", f"I;{i}") +for j in range(2, 33): + OPEN[f"L*{j} image"] = ("F", f"F;{j}") + + +# -------------------------------------------------------------------- +# Read IM directory + +split = re.compile(rb"^([A-Za-z][^:]*):[ \t]*(.*)[ \t]*$") + + +def number(s: Any) -> float: + try: + return int(s) + except ValueError: + return float(s) + + +## +# Image plugin for the IFUNC IM file format. + + +class ImImageFile(ImageFile.ImageFile): + format = "IM" + format_description = "IFUNC Image Memory" + _close_exclusive_fp_after_loading = False + + def _open(self) -> None: + # Quick rejection: if there's not an LF among the first + # 100 bytes, this is (probably) not a text header. + + assert self.fp is not None + if b"\n" not in self.fp.read(100): + msg = "not an IM file" + raise SyntaxError(msg) + self.fp.seek(0) + + n = 0 + + # Default values + self.info[MODE] = "L" + self.info[SIZE] = (512, 512) + self.info[FRAMES] = 1 + + self.rawmode = "L" + + while True: + s = self.fp.read(1) + + # Some versions of IFUNC uses \n\r instead of \r\n... + if s == b"\r": + continue + + if not s or s == b"\0" or s == b"\x1a": + break + + # FIXME: this may read whole file if not a text file + s = s + self.fp.readline() + + if len(s) > 100: + msg = "not an IM file" + raise SyntaxError(msg) + + if s.endswith(b"\r\n"): + s = s[:-2] + elif s.endswith(b"\n"): + s = s[:-1] + + try: + m = split.match(s) + except re.error as e: + msg = "not an IM file" + raise SyntaxError(msg) from e + + if m: + k, v = m.group(1, 2) + + # Don't know if this is the correct encoding, + # but a decent guess (I guess) + k = k.decode("latin-1", "replace") + v = v.decode("latin-1", "replace") + + # Convert value as appropriate + if k in [FRAMES, SCALE, SIZE]: + v = v.replace("*", ",") + v = tuple(map(number, v.split(","))) + if len(v) == 1: + v = v[0] + elif k == MODE and v in OPEN: + v, self.rawmode = OPEN[v] + + # Add to dictionary. Note that COMMENT tags are + # combined into a list of strings. + if k == COMMENT: + if k in self.info: + self.info[k].append(v) + else: + self.info[k] = [v] + else: + self.info[k] = v + + if k in TAGS: + n += 1 + + else: + msg = f"Syntax error in IM header: {s.decode('ascii', 'replace')}" + raise SyntaxError(msg) + + if not n: + msg = "Not an IM file" + raise SyntaxError(msg) + + # Basic attributes + self._size = self.info[SIZE] + self._mode = self.info[MODE] + + # Skip forward to start of image data + while s and not s.startswith(b"\x1a"): + s = self.fp.read(1) + if not s: + msg = "File truncated" + raise SyntaxError(msg) + + if LUT in self.info: + # convert lookup table to palette or lut attribute + palette = self.fp.read(768) + greyscale = 1 # greyscale palette + linear = 1 # linear greyscale palette + for i in range(256): + if palette[i] == palette[i + 256] == palette[i + 512]: + if palette[i] != i: + linear = 0 + else: + greyscale = 0 + if self.mode in ["L", "LA", "P", "PA"]: + if greyscale: + if not linear: + self.lut = list(palette[:256]) + else: + if self.mode in ["L", "P"]: + self._mode = self.rawmode = "P" + elif self.mode in ["LA", "PA"]: + self._mode = "PA" + self.rawmode = "PA;L" + self.palette = ImagePalette.raw("RGB;L", palette) + elif self.mode == "RGB": + if not greyscale or not linear: + self.lut = list(palette) + + self.frame = 0 + + self.__offset = offs = self.fp.tell() + + self._fp = self.fp # FIXME: hack + + if self.rawmode.startswith("F;"): + # ifunc95 formats + try: + # use bit decoder (if necessary) + bits = int(self.rawmode[2:]) + if bits not in [8, 16, 32]: + self.tile = [ + ImageFile._Tile( + "bit", (0, 0) + self.size, offs, (bits, 8, 3, 0, -1) + ) + ] + return + except ValueError: + pass + + if self.rawmode in ["RGB;T", "RYB;T"]: + # Old LabEye/3PC files. Would be very surprised if anyone + # ever stumbled upon such a file ;-) + size = self.size[0] * self.size[1] + self.tile = [ + ImageFile._Tile("raw", (0, 0) + self.size, offs, ("G", 0, -1)), + ImageFile._Tile("raw", (0, 0) + self.size, offs + size, ("R", 0, -1)), + ImageFile._Tile( + "raw", (0, 0) + self.size, offs + 2 * size, ("B", 0, -1) + ), + ] + else: + # LabEye/IFUNC files + self.tile = [ + ImageFile._Tile("raw", (0, 0) + self.size, offs, (self.rawmode, 0, -1)) + ] + + @property + def n_frames(self) -> int: + return self.info[FRAMES] + + @property + def is_animated(self) -> bool: + return self.info[FRAMES] > 1 + + def seek(self, frame: int) -> None: + if not self._seek_check(frame): + return + if isinstance(self._fp, DeferredError): + raise self._fp.ex + + self.frame = frame + + if self.mode == "1": + bits = 1 + else: + bits = 8 * len(self.mode) + + size = ((self.size[0] * bits + 7) // 8) * self.size[1] + offs = self.__offset + frame * size + + self.fp = self._fp + + self.tile = [ + ImageFile._Tile("raw", (0, 0) + self.size, offs, (self.rawmode, 0, -1)) + ] + + def tell(self) -> int: + return self.frame + + +# +# -------------------------------------------------------------------- +# Save IM files + + +SAVE = { + # mode: (im type, raw mode) + "1": ("0 1", "1"), + "L": ("Greyscale", "L"), + "LA": ("LA", "LA;L"), + "P": ("Greyscale", "P"), + "PA": ("LA", "PA;L"), + "I": ("L 32S", "I;32S"), + "I;16": ("L 16", "I;16"), + "I;16L": ("L 16L", "I;16L"), + "I;16B": ("L 16B", "I;16B"), + "F": ("L 32F", "F;32F"), + "RGB": ("RGB", "RGB;L"), + "RGBA": ("RGBA", "RGBA;L"), + "RGBX": ("RGBX", "RGBX;L"), + "CMYK": ("CMYK", "CMYK;L"), + "YCbCr": ("YCC", "YCbCr;L"), +} + + +def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None: + try: + image_type, rawmode = SAVE[im.mode] + except KeyError as e: + msg = f"Cannot save {im.mode} images as IM" + raise ValueError(msg) from e + + frames = im.encoderinfo.get("frames", 1) + + fp.write(f"Image type: {image_type} image\r\n".encode("ascii")) + if filename: + # Each line must be 100 characters or less, + # or: SyntaxError("not an IM file") + # 8 characters are used for "Name: " and "\r\n" + # Keep just the filename, ditch the potentially overlong path + if isinstance(filename, bytes): + filename = filename.decode("ascii") + name, ext = os.path.splitext(os.path.basename(filename)) + name = "".join([name[: 92 - len(ext)], ext]) + + fp.write(f"Name: {name}\r\n".encode("ascii")) + fp.write(f"Image size (x*y): {im.size[0]}*{im.size[1]}\r\n".encode("ascii")) + fp.write(f"File size (no of images): {frames}\r\n".encode("ascii")) + if im.mode in ["P", "PA"]: + fp.write(b"Lut: 1\r\n") + fp.write(b"\000" * (511 - fp.tell()) + b"\032") + if im.mode in ["P", "PA"]: + im_palette = im.im.getpalette("RGB", "RGB;L") + colors = len(im_palette) // 3 + palette = b"" + for i in range(3): + palette += im_palette[colors * i : colors * (i + 1)] + palette += b"\x00" * (256 - colors) + fp.write(palette) # 768 bytes + ImageFile._save( + im, fp, [ImageFile._Tile("raw", (0, 0) + im.size, 0, (rawmode, 0, -1))] + ) + + +# +# -------------------------------------------------------------------- +# Registry + + +Image.register_open(ImImageFile.format, ImImageFile) +Image.register_save(ImImageFile.format, _save) + +Image.register_extension(ImImageFile.format, ".im") diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/Image.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/Image.py new file mode 100644 index 000000000..574980771 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/Image.py @@ -0,0 +1,4381 @@ +# +# The Python Imaging Library. +# $Id$ +# +# the Image class wrapper +# +# partial release history: +# 1995-09-09 fl Created +# 1996-03-11 fl PIL release 0.0 (proof of concept) +# 1996-04-30 fl PIL release 0.1b1 +# 1999-07-28 fl PIL release 1.0 final +# 2000-06-07 fl PIL release 1.1 +# 2000-10-20 fl PIL release 1.1.1 +# 2001-05-07 fl PIL release 1.1.2 +# 2002-03-15 fl PIL release 1.1.3 +# 2003-05-10 fl PIL release 1.1.4 +# 2005-03-28 fl PIL release 1.1.5 +# 2006-12-02 fl PIL release 1.1.6 +# 2009-11-15 fl PIL release 1.1.7 +# +# Copyright (c) 1997-2009 by Secret Labs AB. All rights reserved. +# Copyright (c) 1995-2009 by Fredrik Lundh. +# +# See the README file for information on usage and redistribution. +# + +from __future__ import annotations + +import abc +import atexit +import builtins +import io +import logging +import math +import os +import re +import struct +import sys +import tempfile +import warnings +from collections.abc import MutableMapping +from enum import IntEnum +from typing import IO, Protocol, cast + +# VERSION was removed in Pillow 6.0.0. +# PILLOW_VERSION was removed in Pillow 9.0.0. +# Use __version__ instead. +from . import ( + ExifTags, + ImageMode, + TiffTags, + UnidentifiedImageError, + __version__, + _plugins, +) +from ._binary import i32le, o32be, o32le +from ._deprecate import deprecate +from ._util import DeferredError, is_path + +ElementTree: ModuleType | None +try: + from defusedxml import ElementTree +except ImportError: + ElementTree = None + +TYPE_CHECKING = False +if TYPE_CHECKING: + from collections.abc import Callable, Iterator, Sequence + from types import ModuleType + from typing import Any, Literal + +logger = logging.getLogger(__name__) + + +class DecompressionBombWarning(RuntimeWarning): + pass + + +class DecompressionBombError(Exception): + pass + + +WARN_POSSIBLE_FORMATS: bool = False + +# Limit to around a quarter gigabyte for a 24-bit (3 bpp) image +MAX_IMAGE_PIXELS: int | None = int(1024 * 1024 * 1024 // 4 // 3) + + +try: + # If the _imaging C module is not present, Pillow will not load. + # Note that other modules should not refer to _imaging directly; + # import Image and use the Image.core variable instead. + # Also note that Image.core is not a publicly documented interface, + # and should be considered private and subject to change. + from . import _imaging as core + + if __version__ != getattr(core, "PILLOW_VERSION", None): + msg = ( + "The _imaging extension was built for another version of Pillow or PIL:\n" + f"Core version: {getattr(core, 'PILLOW_VERSION', None)}\n" + f"Pillow version: {__version__}" + ) + raise ImportError(msg) + +except ImportError as v: + # Explanations for ways that we know we might have an import error + if str(v).startswith("Module use of python"): + # The _imaging C module is present, but not compiled for + # the right version (windows only). Print a warning, if + # possible. + warnings.warn( + "The _imaging extension was built for another version of Python.", + RuntimeWarning, + ) + elif str(v).startswith("The _imaging extension"): + warnings.warn(str(v), RuntimeWarning) + # Fail here anyway. Don't let people run with a mostly broken Pillow. + # see docs/porting.rst + raise + + +# +# Constants + + +# transpose +class Transpose(IntEnum): + FLIP_LEFT_RIGHT = 0 + FLIP_TOP_BOTTOM = 1 + ROTATE_90 = 2 + ROTATE_180 = 3 + ROTATE_270 = 4 + TRANSPOSE = 5 + TRANSVERSE = 6 + + +# transforms (also defined in Imaging.h) +class Transform(IntEnum): + AFFINE = 0 + EXTENT = 1 + PERSPECTIVE = 2 + QUAD = 3 + MESH = 4 + + +# resampling filters (also defined in Imaging.h) +class Resampling(IntEnum): + NEAREST = 0 + BOX = 4 + BILINEAR = 2 + HAMMING = 5 + BICUBIC = 3 + LANCZOS = 1 + + +_filters_support = { + Resampling.BOX: 0.5, + Resampling.BILINEAR: 1.0, + Resampling.HAMMING: 1.0, + Resampling.BICUBIC: 2.0, + Resampling.LANCZOS: 3.0, +} + + +# dithers +class Dither(IntEnum): + NONE = 0 + ORDERED = 1 # Not yet implemented + RASTERIZE = 2 # Not yet implemented + FLOYDSTEINBERG = 3 # default + + +# palettes/quantizers +class Palette(IntEnum): + WEB = 0 + ADAPTIVE = 1 + + +class Quantize(IntEnum): + MEDIANCUT = 0 + MAXCOVERAGE = 1 + FASTOCTREE = 2 + LIBIMAGEQUANT = 3 + + +module = sys.modules[__name__] +for enum in (Transpose, Transform, Resampling, Dither, Palette, Quantize): + for item in enum: + setattr(module, item.name, item.value) + + +if hasattr(core, "DEFAULT_STRATEGY"): + DEFAULT_STRATEGY = core.DEFAULT_STRATEGY + FILTERED = core.FILTERED + HUFFMAN_ONLY = core.HUFFMAN_ONLY + RLE = core.RLE + FIXED = core.FIXED + + +# -------------------------------------------------------------------- +# Registries + +TYPE_CHECKING = False +if TYPE_CHECKING: + import mmap + from xml.etree.ElementTree import Element + + from IPython.lib.pretty import PrettyPrinter + + from . import ImageFile, ImageFilter, ImagePalette, ImageQt, TiffImagePlugin + from ._typing import CapsuleType, NumpyArray, StrOrBytesPath +ID: list[str] = [] +OPEN: dict[ + str, + tuple[ + Callable[[IO[bytes], str | bytes], ImageFile.ImageFile], + Callable[[bytes], bool | str] | None, + ], +] = {} +MIME: dict[str, str] = {} +SAVE: dict[str, Callable[[Image, IO[bytes], str | bytes], None]] = {} +SAVE_ALL: dict[str, Callable[[Image, IO[bytes], str | bytes], None]] = {} +EXTENSION: dict[str, str] = {} +DECODERS: dict[str, type[ImageFile.PyDecoder]] = {} +ENCODERS: dict[str, type[ImageFile.PyEncoder]] = {} + +# -------------------------------------------------------------------- +# Modes + +_ENDIAN = "<" if sys.byteorder == "little" else ">" + + +def _conv_type_shape(im: Image) -> tuple[tuple[int, ...], str]: + m = ImageMode.getmode(im.mode) + shape: tuple[int, ...] = (im.height, im.width) + extra = len(m.bands) + if extra != 1: + shape += (extra,) + return shape, m.typestr + + +MODES = [ + "1", + "CMYK", + "F", + "HSV", + "I", + "I;16", + "I;16B", + "I;16L", + "I;16N", + "L", + "LA", + "La", + "LAB", + "P", + "PA", + "RGB", + "RGBA", + "RGBa", + "RGBX", + "YCbCr", +] + +# raw modes that may be memory mapped. NOTE: if you change this, you +# may have to modify the stride calculation in map.c too! +_MAPMODES = ("L", "P", "RGBX", "RGBA", "CMYK", "I;16", "I;16L", "I;16B") + + +def getmodebase(mode: str) -> str: + """ + Gets the "base" mode for given mode. This function returns "L" for + images that contain grayscale data, and "RGB" for images that + contain color data. + + :param mode: Input mode. + :returns: "L" or "RGB". + :exception KeyError: If the input mode was not a standard mode. + """ + return ImageMode.getmode(mode).basemode + + +def getmodetype(mode: str) -> str: + """ + Gets the storage type mode. Given a mode, this function returns a + single-layer mode suitable for storing individual bands. + + :param mode: Input mode. + :returns: "L", "I", or "F". + :exception KeyError: If the input mode was not a standard mode. + """ + return ImageMode.getmode(mode).basetype + + +def getmodebandnames(mode: str) -> tuple[str, ...]: + """ + Gets a list of individual band names. Given a mode, this function returns + a tuple containing the names of individual bands (use + :py:method:`~PIL.Image.getmodetype` to get the mode used to store each + individual band. + + :param mode: Input mode. + :returns: A tuple containing band names. The length of the tuple + gives the number of bands in an image of the given mode. + :exception KeyError: If the input mode was not a standard mode. + """ + return ImageMode.getmode(mode).bands + + +def getmodebands(mode: str) -> int: + """ + Gets the number of individual bands for this mode. + + :param mode: Input mode. + :returns: The number of bands in this mode. + :exception KeyError: If the input mode was not a standard mode. + """ + return len(ImageMode.getmode(mode).bands) + + +# -------------------------------------------------------------------- +# Helpers + +_initialized = 0 + +# Mapping from file extension to plugin module name for lazy importing +_EXTENSION_PLUGIN: dict[str, str] = { + # Common formats (preinit) + ".bmp": "BmpImagePlugin", + ".dib": "BmpImagePlugin", + ".gif": "GifImagePlugin", + ".jfif": "JpegImagePlugin", + ".jpe": "JpegImagePlugin", + ".jpg": "JpegImagePlugin", + ".jpeg": "JpegImagePlugin", + ".pbm": "PpmImagePlugin", + ".pgm": "PpmImagePlugin", + ".pnm": "PpmImagePlugin", + ".ppm": "PpmImagePlugin", + ".pfm": "PpmImagePlugin", + ".png": "PngImagePlugin", + ".apng": "PngImagePlugin", + # Less common formats (init) + ".avif": "AvifImagePlugin", + ".avifs": "AvifImagePlugin", + ".blp": "BlpImagePlugin", + ".bufr": "BufrStubImagePlugin", + ".cur": "CurImagePlugin", + ".dcx": "DcxImagePlugin", + ".dds": "DdsImagePlugin", + ".ps": "EpsImagePlugin", + ".eps": "EpsImagePlugin", + ".fit": "FitsImagePlugin", + ".fits": "FitsImagePlugin", + ".fli": "FliImagePlugin", + ".flc": "FliImagePlugin", + ".fpx": "FpxImagePlugin", + ".ftc": "FtexImagePlugin", + ".ftu": "FtexImagePlugin", + ".gbr": "GbrImagePlugin", + ".grib": "GribStubImagePlugin", + ".h5": "Hdf5StubImagePlugin", + ".hdf": "Hdf5StubImagePlugin", + ".icns": "IcnsImagePlugin", + ".ico": "IcoImagePlugin", + ".im": "ImImagePlugin", + ".iim": "IptcImagePlugin", + ".jp2": "Jpeg2KImagePlugin", + ".j2k": "Jpeg2KImagePlugin", + ".jpc": "Jpeg2KImagePlugin", + ".jpf": "Jpeg2KImagePlugin", + ".jpx": "Jpeg2KImagePlugin", + ".j2c": "Jpeg2KImagePlugin", + ".mic": "MicImagePlugin", + ".mpg": "MpegImagePlugin", + ".mpeg": "MpegImagePlugin", + ".mpo": "MpoImagePlugin", + ".msp": "MspImagePlugin", + ".palm": "PalmImagePlugin", + ".pcd": "PcdImagePlugin", + ".pcx": "PcxImagePlugin", + ".pdf": "PdfImagePlugin", + ".pxr": "PixarImagePlugin", + ".psd": "PsdImagePlugin", + ".qoi": "QoiImagePlugin", + ".bw": "SgiImagePlugin", + ".rgb": "SgiImagePlugin", + ".rgba": "SgiImagePlugin", + ".sgi": "SgiImagePlugin", + ".ras": "SunImagePlugin", + ".tga": "TgaImagePlugin", + ".icb": "TgaImagePlugin", + ".vda": "TgaImagePlugin", + ".vst": "TgaImagePlugin", + ".tif": "TiffImagePlugin", + ".tiff": "TiffImagePlugin", + ".webp": "WebPImagePlugin", + ".wmf": "WmfImagePlugin", + ".emf": "WmfImagePlugin", + ".xbm": "XbmImagePlugin", + ".xpm": "XpmImagePlugin", +} + + +def _import_plugin_for_extension(ext: str | bytes) -> bool: + """Import only the plugin needed for a specific file extension.""" + if not ext: + return False + + if isinstance(ext, bytes): + ext = ext.decode() + ext = ext.lower() + if ext in EXTENSION: + return True + + plugin = _EXTENSION_PLUGIN.get(ext) + if plugin is None: + return False + + try: + logger.debug("Importing %s", plugin) + __import__(f"{__spec__.parent}.{plugin}", globals(), locals(), []) + return True + except ImportError as e: + logger.debug("Image: failed to import %s: %s", plugin, e) + return False + + +def preinit() -> None: + """ + Explicitly loads BMP, GIF, JPEG, PPM and PNG file format drivers. + + It is called when opening or saving images. + """ + + global _initialized + if _initialized >= 1: + return + + try: + from . import BmpImagePlugin + + assert BmpImagePlugin + except ImportError: + pass + try: + from . import GifImagePlugin + + assert GifImagePlugin + except ImportError: + pass + try: + from . import JpegImagePlugin + + assert JpegImagePlugin + except ImportError: + pass + try: + from . import PpmImagePlugin + + assert PpmImagePlugin + except ImportError: + pass + try: + from . import PngImagePlugin + + assert PngImagePlugin + except ImportError: + pass + + _initialized = 1 + + +def init() -> bool: + """ + Explicitly initializes the Python Imaging Library. This function + loads all available file format drivers. + + It is called when opening or saving images if :py:meth:`~preinit()` is + insufficient, and by :py:meth:`~PIL.features.pilinfo`. + """ + + global _initialized + if _initialized >= 2: + return False + + for plugin in _plugins: + try: + logger.debug("Importing %s", plugin) + __import__(f"{__spec__.parent}.{plugin}", globals(), locals(), []) + except ImportError as e: # noqa: PERF203 + logger.debug("Image: failed to import %s: %s", plugin, e) + + if OPEN or SAVE: + _initialized = 2 + return True + return False + + +# -------------------------------------------------------------------- +# Codec factories (used by tobytes/frombytes and ImageFile.load) + + +def _getdecoder( + mode: str, decoder_name: str, args: Any, extra: tuple[Any, ...] = () +) -> core.ImagingDecoder | ImageFile.PyDecoder: + # tweak arguments + if args is None: + args = () + elif not isinstance(args, tuple): + args = (args,) + + try: + decoder = DECODERS[decoder_name] + except KeyError: + pass + else: + return decoder(mode, *args + extra) + + try: + # get decoder + decoder = getattr(core, f"{decoder_name}_decoder") + except AttributeError as e: + msg = f"decoder {decoder_name} not available" + raise OSError(msg) from e + return decoder(mode, *args + extra) + + +def _getencoder( + mode: str, encoder_name: str, args: Any, extra: tuple[Any, ...] = () +) -> core.ImagingEncoder | ImageFile.PyEncoder: + # tweak arguments + if args is None: + args = () + elif not isinstance(args, tuple): + args = (args,) + + try: + encoder = ENCODERS[encoder_name] + except KeyError: + pass + else: + return encoder(mode, *args + extra) + + try: + # get encoder + encoder = getattr(core, f"{encoder_name}_encoder") + except AttributeError as e: + msg = f"encoder {encoder_name} not available" + raise OSError(msg) from e + return encoder(mode, *args + extra) + + +# -------------------------------------------------------------------- +# Simple expression analyzer + + +class ImagePointTransform: + """ + Used with :py:meth:`~PIL.Image.Image.point` for single band images with more than + 8 bits, this represents an affine transformation, where the value is multiplied by + ``scale`` and ``offset`` is added. + """ + + def __init__(self, scale: float, offset: float) -> None: + self.scale = scale + self.offset = offset + + def __neg__(self) -> ImagePointTransform: + return ImagePointTransform(-self.scale, -self.offset) + + def __add__(self, other: ImagePointTransform | float) -> ImagePointTransform: + if isinstance(other, ImagePointTransform): + return ImagePointTransform( + self.scale + other.scale, self.offset + other.offset + ) + return ImagePointTransform(self.scale, self.offset + other) + + __radd__ = __add__ + + def __sub__(self, other: ImagePointTransform | float) -> ImagePointTransform: + return self + -other + + def __rsub__(self, other: ImagePointTransform | float) -> ImagePointTransform: + return other + -self + + def __mul__(self, other: ImagePointTransform | float) -> ImagePointTransform: + if isinstance(other, ImagePointTransform): + return NotImplemented + return ImagePointTransform(self.scale * other, self.offset * other) + + __rmul__ = __mul__ + + def __truediv__(self, other: ImagePointTransform | float) -> ImagePointTransform: + if isinstance(other, ImagePointTransform): + return NotImplemented + return ImagePointTransform(self.scale / other, self.offset / other) + + +def _getscaleoffset( + expr: Callable[[ImagePointTransform], ImagePointTransform | float], +) -> tuple[float, float]: + a = expr(ImagePointTransform(1, 0)) + return (a.scale, a.offset) if isinstance(a, ImagePointTransform) else (0, a) + + +# -------------------------------------------------------------------- +# Implementation wrapper + + +class SupportsGetData(Protocol): + def getdata( + self, + ) -> tuple[Transform, Sequence[int]]: ... + + +class Image: + """ + This class represents an image object. To create + :py:class:`~PIL.Image.Image` objects, use the appropriate factory + functions. There's hardly ever any reason to call the Image constructor + directly. + + * :py:func:`~PIL.Image.open` + * :py:func:`~PIL.Image.new` + * :py:func:`~PIL.Image.frombytes` + """ + + format: str | None = None + format_description: str | None = None + _close_exclusive_fp_after_loading = True + + def __init__(self) -> None: + # FIXME: take "new" parameters / other image? + self._im: core.ImagingCore | DeferredError | None = None + self._mode = "" + self._size = (0, 0) + self.palette: ImagePalette.ImagePalette | None = None + self.info: dict[str | tuple[int, int], Any] = {} + self.readonly = 0 + self._exif: Exif | None = None + + @property + def im(self) -> core.ImagingCore: + if isinstance(self._im, DeferredError): + raise self._im.ex + assert self._im is not None + return self._im + + @im.setter + def im(self, im: core.ImagingCore) -> None: + self._im = im + + @property + def width(self) -> int: + return self.size[0] + + @property + def height(self) -> int: + return self.size[1] + + @property + def size(self) -> tuple[int, int]: + return self._size + + @property + def mode(self) -> str: + return self._mode + + @property + def readonly(self) -> int: + return (self._im and self._im.readonly) or self._readonly + + @readonly.setter + def readonly(self, readonly: int) -> None: + self._readonly = readonly + + def _new(self, im: core.ImagingCore) -> Image: + new = Image() + new.im = im + new._mode = im.mode + new._size = im.size + if im.mode in ("P", "PA"): + if self.palette: + new.palette = self.palette.copy() + else: + from . import ImagePalette + + new.palette = ImagePalette.ImagePalette() + new.info = self.info.copy() + return new + + # Context manager support + def __enter__(self) -> Image: + return self + + def __exit__(self, *args: object) -> None: + pass + + def close(self) -> None: + """ + This operation will destroy the image core and release its memory. + The image data will be unusable afterward. + + This function is required to close images that have multiple frames or + have not had their file read and closed by the + :py:meth:`~PIL.Image.Image.load` method. See :ref:`file-handling` for + more information. + """ + if getattr(self, "map", None): + if sys.platform == "win32" and hasattr(sys, "pypy_version_info"): + self.map.close() + self.map: mmap.mmap | None = None + + # Instead of simply setting to None, we're setting up a + # deferred error that will better explain that the core image + # object is gone. + self._im = DeferredError(ValueError("Operation on closed image")) + + def _copy(self) -> None: + self.load() + self.im = self.im.copy() + self.readonly = 0 + + def _ensure_mutable(self) -> None: + if self.readonly: + self._copy() + else: + self.load() + + def _dump( + self, file: str | None = None, format: str | None = None, **options: Any + ) -> str: + suffix = "" + if format: + suffix = f".{format}" + + if not file: + f, filename = tempfile.mkstemp(suffix) + os.close(f) + else: + filename = file + if not filename.endswith(suffix): + filename = filename + suffix + + self.load() + + if not format or format == "PPM": + self.im.save_ppm(filename) + else: + self.save(filename, format, **options) + + return filename + + def __eq__(self, other: object) -> bool: + if self.__class__ is not other.__class__: + return False + assert isinstance(other, Image) + return ( + self.mode == other.mode + and self.size == other.size + and self.info == other.info + and self.getpalette() == other.getpalette() + and self.tobytes() == other.tobytes() + ) + + def __repr__(self) -> str: + return ( + f"<{self.__class__.__module__}.{self.__class__.__name__} " + f"image mode={self.mode} size={self.size[0]}x{self.size[1]} " + f"at 0x{id(self):X}>" + ) + + def _repr_pretty_(self, p: PrettyPrinter, cycle: bool) -> None: + """IPython plain text display support""" + + # Same as __repr__ but without unpredictable id(self), + # to keep Jupyter notebook `text/plain` output stable. + p.text( + f"<{self.__class__.__module__}.{self.__class__.__name__} " + f"image mode={self.mode} size={self.size[0]}x{self.size[1]}>" + ) + + def _repr_image(self, image_format: str, **kwargs: Any) -> bytes | None: + """Helper function for iPython display hook. + + :param image_format: Image format. + :returns: image as bytes, saved into the given format. + """ + b = io.BytesIO() + try: + self.save(b, image_format, **kwargs) + except Exception: + return None + return b.getvalue() + + def _repr_png_(self) -> bytes | None: + """iPython display hook support for PNG format. + + :returns: PNG version of the image as bytes + """ + return self._repr_image("PNG", compress_level=1) + + def _repr_jpeg_(self) -> bytes | None: + """iPython display hook support for JPEG format. + + :returns: JPEG version of the image as bytes + """ + return self._repr_image("JPEG") + + @property + def __array_interface__(self) -> dict[str, str | bytes | int | tuple[int, ...]]: + # numpy array interface support + new: dict[str, str | bytes | int | tuple[int, ...]] = {"version": 3} + if self.mode == "1": + # Binary images need to be extended from bits to bytes + # See: https://github.com/python-pillow/Pillow/issues/350 + new["data"] = self.tobytes("raw", "L") + else: + new["data"] = self.tobytes() + new["shape"], new["typestr"] = _conv_type_shape(self) + return new + + def __arrow_c_schema__(self) -> object: + self.load() + return self.im.__arrow_c_schema__() + + def __arrow_c_array__( + self, requested_schema: object | None = None + ) -> tuple[object, object]: + self.load() + return (self.im.__arrow_c_schema__(), self.im.__arrow_c_array__()) + + def __getstate__(self) -> list[Any]: + im_data = self.tobytes() # load image first + return [self.info, self.mode, self.size, self.getpalette(), im_data] + + def __setstate__(self, state: list[Any]) -> None: + Image.__init__(self) + info, mode, size, palette, data = state[:5] + self.info = info + self._mode = mode + self._size = size + self.im = core.new(mode, size) + if mode in ("L", "LA", "P", "PA") and palette: + self.putpalette(palette) + self.frombytes(data) + + def tobytes(self, encoder_name: str = "raw", *args: Any) -> bytes: + """ + Return image as a bytes object. + + .. warning:: + + This method returns raw image data derived from Pillow's internal + storage. For compressed image data (e.g. PNG, JPEG) use + :meth:`~.save`, with a BytesIO parameter for in-memory data. + + :param encoder_name: What encoder to use. + + The default is to use the standard "raw" encoder. + To see how this packs pixel data into the returned + bytes, see :file:`libImaging/Pack.c`. + + A list of C encoders can be seen under codecs + section of the function array in + :file:`_imaging.c`. Python encoders are registered + within the relevant plugins. + :param args: Extra arguments to the encoder. + :returns: A :py:class:`bytes` object. + """ + + encoder_args: Any = args + if len(encoder_args) == 1 and isinstance(encoder_args[0], tuple): + # may pass tuple instead of argument list + encoder_args = encoder_args[0] + + if encoder_name == "raw" and encoder_args == (): + encoder_args = self.mode + + self.load() + + if self.width == 0 or self.height == 0: + return b"" + + # unpack data + e = _getencoder(self.mode, encoder_name, encoder_args) + e.setimage(self.im, (0, 0) + self.size) + + from . import ImageFile + + bufsize = max(ImageFile.MAXBLOCK, self.size[0] * 4) # see RawEncode.c + + output = [] + while True: + bytes_consumed, errcode, data = e.encode(bufsize) + output.append(data) + if errcode: + break + if errcode < 0: + msg = f"encoder error {errcode} in tobytes" + raise RuntimeError(msg) + + return b"".join(output) + + def tobitmap(self, name: str = "image") -> bytes: + """ + Returns the image converted to an X11 bitmap. + + .. note:: This method only works for mode "1" images. + + :param name: The name prefix to use for the bitmap variables. + :returns: A string containing an X11 bitmap. + :raises ValueError: If the mode is not "1" + """ + + self.load() + if self.mode != "1": + msg = "not a bitmap" + raise ValueError(msg) + data = self.tobytes("xbm") + return b"".join( + [ + f"#define {name}_width {self.size[0]}\n".encode("ascii"), + f"#define {name}_height {self.size[1]}\n".encode("ascii"), + f"static char {name}_bits[] = {{\n".encode("ascii"), + data, + b"};", + ] + ) + + def frombytes( + self, + data: bytes | bytearray | SupportsArrayInterface, + decoder_name: str = "raw", + *args: Any, + ) -> None: + """ + Loads this image with pixel data from a bytes object. + + This method is similar to the :py:func:`~PIL.Image.frombytes` function, + but loads data into this image instead of creating a new image object. + """ + + if self.width == 0 or self.height == 0: + return + + decoder_args: Any = args + if len(decoder_args) == 1 and isinstance(decoder_args[0], tuple): + # may pass tuple instead of argument list + decoder_args = decoder_args[0] + + # default format + if decoder_name == "raw" and decoder_args == (): + decoder_args = self.mode + + # unpack data + d = _getdecoder(self.mode, decoder_name, decoder_args) + d.setimage(self.im, (0, 0) + self.size) + s = d.decode(data) + + if s[0] >= 0: + msg = "not enough image data" + raise ValueError(msg) + if s[1] != 0: + msg = "cannot decode image data" + raise ValueError(msg) + + def load(self) -> core.PixelAccess | None: + """ + Allocates storage for the image and loads the pixel data. In + normal cases, you don't need to call this method, since the + Image class automatically loads an opened image when it is + accessed for the first time. + + If the file associated with the image was opened by Pillow, then this + method will close it. The exception to this is if the image has + multiple frames, in which case the file will be left open for seek + operations. See :ref:`file-handling` for more information. + + :returns: An image access object. + :rtype: :py:class:`.PixelAccess` + """ + if self._im is not None and self.palette and self.palette.dirty: + # realize palette + mode, arr = self.palette.getdata() + self.im.putpalette(self.palette.mode, mode, arr) + self.palette.dirty = 0 + self.palette.rawmode = None + if "transparency" in self.info and mode in ("LA", "PA"): + if isinstance(self.info["transparency"], int): + self.im.putpalettealpha(self.info["transparency"], 0) + else: + self.im.putpalettealphas(self.info["transparency"]) + self.palette.mode = "RGBA" + elif self.palette.mode != mode: + # If the palette rawmode is different to the mode, + # then update the Python palette data + self.palette.palette = self.im.getpalette( + self.palette.mode, self.palette.mode + ) + + if self._im is not None: + return self.im.pixel_access(self.readonly) + return None + + def verify(self) -> None: + """ + Verifies the contents of a file. For data read from a file, this + method attempts to determine if the file is broken, without + actually decoding the image data. If this method finds any + problems, it raises suitable exceptions. If you need to load + the image after using this method, you must reopen the image + file. + """ + pass + + def convert( + self, + mode: str | None = None, + matrix: tuple[float, ...] | None = None, + dither: Dither | None = None, + palette: Palette = Palette.WEB, + colors: int = 256, + ) -> Image: + """ + Returns a converted copy of this image. For the "P" mode, this + method translates pixels through the palette. If mode is + omitted, a mode is chosen so that all information in the image + and the palette can be represented without a palette. + + This supports all possible conversions between "L", "RGB" and "CMYK". The + ``matrix`` argument only supports "L" and "RGB". + + When translating a color image to grayscale (mode "L"), + the library uses the ITU-R 601-2 luma transform:: + + L = R * 299/1000 + G * 587/1000 + B * 114/1000 + + The default method of converting a grayscale ("L") or "RGB" + image into a bilevel (mode "1") image uses Floyd-Steinberg + dither to approximate the original image luminosity levels. If + dither is ``None``, all values larger than 127 are set to 255 (white), + all other values to 0 (black). To use other thresholds, use the + :py:meth:`~PIL.Image.Image.point` method. + + When converting from "RGBA" to "P" without a ``matrix`` argument, + this passes the operation to :py:meth:`~PIL.Image.Image.quantize`, + and ``dither`` and ``palette`` are ignored. + + When converting from "PA", if an "RGBA" palette is present, the alpha + channel from the image will be used instead of the values from the palette. + + :param mode: The requested mode. See: :ref:`concept-modes`. + :param matrix: An optional conversion matrix. If given, this + should be 4- or 12-tuple containing floating point values. + :param dither: Dithering method, used when converting from + mode "RGB" to "P" or from "RGB" or "L" to "1". + Available methods are :data:`Dither.NONE` or :data:`Dither.FLOYDSTEINBERG` + (default). Note that this is not used when ``matrix`` is supplied. + :param palette: Palette to use when converting from mode "RGB" + to "P". Available palettes are :data:`Palette.WEB` or + :data:`Palette.ADAPTIVE`. + :param colors: Number of colors to use for the :data:`Palette.ADAPTIVE` + palette. Defaults to 256. + :rtype: :py:class:`~PIL.Image.Image` + :returns: An :py:class:`~PIL.Image.Image` object. + """ + + self.load() + + has_transparency = "transparency" in self.info + if not mode and self.mode == "P": + # determine default mode + if self.palette: + mode = self.palette.mode + else: + mode = "RGB" + if mode == "RGB" and has_transparency: + mode = "RGBA" + if not mode or (mode == self.mode and not matrix): + return self.copy() + + if matrix: + # matrix conversion + if mode not in ("L", "RGB"): + msg = "illegal conversion" + raise ValueError(msg) + im = self.im.convert_matrix(mode, matrix) + new_im = self._new(im) + if has_transparency and self.im.bands == 3: + transparency = new_im.info["transparency"] + + def convert_transparency( + m: tuple[float, ...], v: tuple[int, int, int] + ) -> int: + value = m[0] * v[0] + m[1] * v[1] + m[2] * v[2] + m[3] * 0.5 + return max(0, min(255, int(value))) + + if mode == "L": + transparency = convert_transparency(matrix, transparency) + elif len(mode) == 3: + transparency = tuple( + convert_transparency(matrix[i * 4 : i * 4 + 4], transparency) + for i in range(len(transparency)) + ) + new_im.info["transparency"] = transparency + return new_im + + if self.mode == "RGBA": + if mode == "P": + return self.quantize(colors) + elif mode == "PA": + r, g, b, a = self.split() + rgb = merge("RGB", (r, g, b)) + p = rgb.quantize(colors) + return merge("PA", (p, a)) + + trns = None + delete_trns = False + # transparency handling + if has_transparency: + if (self.mode in ("1", "L", "I", "I;16") and mode in ("LA", "RGBA")) or ( + self.mode == "RGB" and mode in ("La", "LA", "RGBa", "RGBA") + ): + # Use transparent conversion to promote from transparent + # color to an alpha channel. + new_im = self._new( + self.im.convert_transparent(mode, self.info["transparency"]) + ) + del new_im.info["transparency"] + return new_im + elif self.mode in ("L", "RGB", "P") and mode in ("L", "RGB", "P"): + t = self.info["transparency"] + if isinstance(t, bytes): + # Dragons. This can't be represented by a single color + warnings.warn( + "Palette images with Transparency expressed in bytes should be " + "converted to RGBA images" + ) + delete_trns = True + else: + # get the new transparency color. + # use existing conversions + trns_im = new(self.mode, (1, 1)) + if self.mode == "P": + assert self.palette is not None + trns_im.putpalette(self.palette, self.palette.mode) + if isinstance(t, tuple): + err = "Couldn't allocate a palette color for transparency" + assert trns_im.palette is not None + try: + t = trns_im.palette.getcolor(t, self) + except ValueError as e: + if str(e) == "cannot allocate more than 256 colors": + # If all 256 colors are in use, + # then there is no need for transparency + t = None + else: + raise ValueError(err) from e + if t is None: + trns = None + else: + trns_im.putpixel((0, 0), t) + + if mode in ("L", "RGB"): + trns_im = trns_im.convert(mode) + else: + # can't just retrieve the palette number, got to do it + # after quantization. + trns_im = trns_im.convert("RGB") + trns = trns_im.getpixel((0, 0)) + + elif self.mode == "P" and mode in ("LA", "PA", "RGBA"): + t = self.info["transparency"] + delete_trns = True + + if isinstance(t, bytes): + self.im.putpalettealphas(t) + elif isinstance(t, int): + self.im.putpalettealpha(t, 0) + else: + msg = "Transparency for P mode should be bytes or int" + raise ValueError(msg) + + if mode == "P" and palette == Palette.ADAPTIVE: + im = self.im.quantize(colors) + new_im = self._new(im) + from . import ImagePalette + + new_im.palette = ImagePalette.ImagePalette( + "RGB", new_im.im.getpalette("RGB") + ) + if delete_trns: + # This could possibly happen if we requantize to fewer colors. + # The transparency would be totally off in that case. + del new_im.info["transparency"] + if trns is not None: + try: + new_im.info["transparency"] = new_im.palette.getcolor( + cast(tuple[int, ...], trns), # trns was converted to RGB + new_im, + ) + except Exception: + # if we can't make a transparent color, don't leave the old + # transparency hanging around to mess us up. + del new_im.info["transparency"] + warnings.warn("Couldn't allocate palette entry for transparency") + return new_im + + if "LAB" in (self.mode, mode): + im = self + if mode == "LAB": + if im.mode not in ("RGB", "RGBA", "RGBX"): + im = im.convert("RGBA") + other_mode = im.mode + else: + other_mode = mode + if other_mode in ("RGB", "RGBA", "RGBX"): + from . import ImageCms + + srgb = ImageCms.createProfile("sRGB") + lab = ImageCms.createProfile("LAB") + profiles = [lab, srgb] if im.mode == "LAB" else [srgb, lab] + transform = ImageCms.buildTransform( + profiles[0], profiles[1], im.mode, mode + ) + return transform.apply(im) + + # colorspace conversion + if dither is None: + dither = Dither.FLOYDSTEINBERG + + try: + im = self.im.convert(mode, dither) + except ValueError: + try: + # normalize source image and try again + modebase = getmodebase(self.mode) + if modebase == self.mode: + raise + im = self.im.convert(modebase) + im = im.convert(mode, dither) + except KeyError as e: + msg = "illegal conversion" + raise ValueError(msg) from e + + new_im = self._new(im) + if mode in ("P", "PA") and palette != Palette.ADAPTIVE: + from . import ImagePalette + + new_im.palette = ImagePalette.ImagePalette("RGB", im.getpalette("RGB")) + if delete_trns: + # crash fail if we leave a bytes transparency in an rgb/l mode. + del new_im.info["transparency"] + if trns is not None: + if new_im.mode == "P" and new_im.palette: + try: + new_im.info["transparency"] = new_im.palette.getcolor( + cast(tuple[int, ...], trns), new_im # trns was converted to RGB + ) + except ValueError as e: + del new_im.info["transparency"] + if str(e) != "cannot allocate more than 256 colors": + # If all 256 colors are in use, + # then there is no need for transparency + warnings.warn( + "Couldn't allocate palette entry for transparency" + ) + else: + new_im.info["transparency"] = trns + return new_im + + def quantize( + self, + colors: int = 256, + method: int | None = None, + kmeans: int = 0, + palette: Image | None = None, + dither: Dither = Dither.FLOYDSTEINBERG, + ) -> Image: + """ + Convert the image to 'P' mode with the specified number + of colors. + + :param colors: The desired number of colors, <= 256 + :param method: :data:`Quantize.MEDIANCUT` (median cut), + :data:`Quantize.MAXCOVERAGE` (maximum coverage), + :data:`Quantize.FASTOCTREE` (fast octree), + :data:`Quantize.LIBIMAGEQUANT` (libimagequant; check support + using :py:func:`PIL.features.check_feature` with + ``feature="libimagequant"``). + + By default, :data:`Quantize.MEDIANCUT` will be used. + + The exception to this is RGBA images. :data:`Quantize.MEDIANCUT` + and :data:`Quantize.MAXCOVERAGE` do not support RGBA images, so + :data:`Quantize.FASTOCTREE` is used by default instead. + :param kmeans: Integer greater than or equal to zero. + :param palette: Quantize to the palette of given + :py:class:`PIL.Image.Image`. + :param dither: Dithering method, used when converting from + mode "RGB" to "P" or from "RGB" or "L" to "1". + Available methods are :data:`Dither.NONE` or :data:`Dither.FLOYDSTEINBERG` + (default). + :returns: A new image + """ + + self.load() + + if method is None: + # defaults: + method = Quantize.MEDIANCUT + if self.mode == "RGBA": + method = Quantize.FASTOCTREE + + if self.mode == "RGBA" and method not in ( + Quantize.FASTOCTREE, + Quantize.LIBIMAGEQUANT, + ): + # Caller specified an invalid mode. + msg = ( + "Fast Octree (method == 2) and libimagequant (method == 3) " + "are the only valid methods for quantizing RGBA images" + ) + raise ValueError(msg) + + if palette: + # use palette from reference image + palette.load() + if palette.mode != "P": + msg = "bad mode for palette image" + raise ValueError(msg) + if self.mode not in {"RGB", "L"}: + msg = "only RGB or L mode images can be quantized to a palette" + raise ValueError(msg) + im = self.im.convert("P", dither, palette.im) + new_im = self._new(im) + assert palette.palette is not None + new_im.palette = palette.palette.copy() + return new_im + + if kmeans < 0: + msg = "kmeans must not be negative" + raise ValueError(msg) + + im = self._new(self.im.quantize(colors, method, kmeans)) + + from . import ImagePalette + + mode = im.im.getpalettemode() + palette_data = im.im.getpalette(mode, mode)[: colors * len(mode)] + im.palette = ImagePalette.ImagePalette(mode, palette_data) + + return im + + def copy(self) -> Image: + """ + Copies this image. Use this method if you wish to paste things + into an image, but still retain the original. + + :rtype: :py:class:`~PIL.Image.Image` + :returns: An :py:class:`~PIL.Image.Image` object. + """ + self.load() + return self._new(self.im.copy()) + + __copy__ = copy + + def crop(self, box: tuple[float, float, float, float] | None = None) -> Image: + """ + Returns a rectangular region from this image. The box is a + 4-tuple defining the left, upper, right, and lower pixel + coordinate. See :ref:`coordinate-system`. + + Note: Prior to Pillow 3.4.0, this was a lazy operation. + + :param box: The crop rectangle, as a (left, upper, right, lower)-tuple. + :rtype: :py:class:`~PIL.Image.Image` + :returns: An :py:class:`~PIL.Image.Image` object. + """ + + if box is None: + return self.copy() + + if box[2] < box[0]: + msg = "Coordinate 'right' is less than 'left'" + raise ValueError(msg) + elif box[3] < box[1]: + msg = "Coordinate 'lower' is less than 'upper'" + raise ValueError(msg) + + self.load() + return self._new(self._crop(self.im, box)) + + def _crop( + self, im: core.ImagingCore, box: tuple[float, float, float, float] + ) -> core.ImagingCore: + """ + Returns a rectangular region from the core image object im. + + This is equivalent to calling im.crop((x0, y0, x1, y1)), but + includes additional sanity checks. + + :param im: a core image object + :param box: The crop rectangle, as a (left, upper, right, lower)-tuple. + :returns: A core image object. + """ + + x0, y0, x1, y1 = map(int, map(round, box)) + + absolute_values = (abs(x1 - x0), abs(y1 - y0)) + + _decompression_bomb_check(absolute_values) + + return im.crop((x0, y0, x1, y1)) + + def draft( + self, mode: str | None, size: tuple[int, int] | None + ) -> tuple[str, tuple[int, int, float, float]] | None: + """ + Configures the image file loader so it returns a version of the + image that as closely as possible matches the given mode and + size. For example, you can use this method to convert a color + JPEG to grayscale while loading it. + + If any changes are made, returns a tuple with the chosen ``mode`` and + ``box`` with coordinates of the original image within the altered one. + + Note that this method modifies the :py:class:`~PIL.Image.Image` object + in place. If the image has already been loaded, this method has no + effect. + + Note: This method is not implemented for most images. It is + currently implemented only for JPEG and MPO images. + + :param mode: The requested mode. + :param size: The requested size in pixels, as a 2-tuple: + (width, height). + """ + pass + + def filter(self, filter: ImageFilter.Filter | type[ImageFilter.Filter]) -> Image: + """ + Filters this image using the given filter. For a list of + available filters, see the :py:mod:`~PIL.ImageFilter` module. + + :param filter: Filter kernel. + :returns: An :py:class:`~PIL.Image.Image` object.""" + + from . import ImageFilter + + self.load() + + if callable(filter): + filter = filter() + if not hasattr(filter, "filter"): + msg = "filter argument should be ImageFilter.Filter instance or class" + raise TypeError(msg) + + multiband = isinstance(filter, ImageFilter.MultibandFilter) + if self.im.bands == 1 or multiband: + return self._new(filter.filter(self.im)) + + ims = [ + self._new(filter.filter(self.im.getband(c))) for c in range(self.im.bands) + ] + return merge(self.mode, ims) + + def getbands(self) -> tuple[str, ...]: + """ + Returns a tuple containing the name of each band in this image. + For example, ``getbands`` on an RGB image returns ("R", "G", "B"). + + :returns: A tuple containing band names. + :rtype: tuple + """ + return ImageMode.getmode(self.mode).bands + + def getbbox(self, *, alpha_only: bool = True) -> tuple[int, int, int, int] | None: + """ + Calculates the bounding box of the non-zero regions in the + image. + + :param alpha_only: Optional flag, defaulting to ``True``. + If ``True`` and the image has an alpha channel, trim transparent pixels. + Otherwise, trim pixels when all channels are zero. + Keyword-only argument. + :returns: The bounding box is returned as a 4-tuple defining the + left, upper, right, and lower pixel coordinate. See + :ref:`coordinate-system`. If the image is completely empty, this + method returns None. + + """ + + self.load() + return self.im.getbbox(alpha_only) + + def getcolors( + self, maxcolors: int = 256 + ) -> list[tuple[int, tuple[int, ...]]] | list[tuple[int, float]] | None: + """ + Returns a list of colors used in this image. + + The colors will be in the image's mode. For example, an RGB image will + return a tuple of (red, green, blue) color values, and a P image will + return the index of the color in the palette. + + :param maxcolors: Maximum number of colors. If this number is + exceeded, this method returns None. The default limit is + 256 colors. + :returns: An unsorted list of (count, pixel) values. + """ + + self.load() + if self.mode in ("1", "L", "P"): + h = self.im.histogram() + out: list[tuple[int, float]] = [(h[i], i) for i in range(256) if h[i]] + if len(out) > maxcolors: + return None + return out + return self.im.getcolors(maxcolors) + + def getdata(self, band: int | None = None) -> core.ImagingCore: + """ + Returns the contents of this image as a sequence object + containing pixel values. The sequence object is flattened, so + that values for line one follow directly after the values of + line zero, and so on. + + Note that the sequence object returned by this method is an + internal PIL data type, which only supports certain sequence + operations. To convert it to an ordinary sequence (e.g. for + printing), use ``list(im.getdata())``. + + :param band: What band to return. The default is to return + all bands. To return a single band, pass in the index + value (e.g. 0 to get the "R" band from an "RGB" image). + :returns: A sequence-like object. + """ + deprecate("Image.Image.getdata", 14, "get_flattened_data") + + self.load() + if band is not None: + return self.im.getband(band) + return self.im # could be abused + + def get_flattened_data( + self, band: int | None = None + ) -> tuple[tuple[int, ...], ...] | tuple[float, ...]: + """ + Returns the contents of this image as a tuple containing pixel values. + The sequence object is flattened, so that values for line one follow + directly after the values of line zero, and so on. + + :param band: What band to return. The default is to return + all bands. To return a single band, pass in the index + value (e.g. 0 to get the "R" band from an "RGB" image). + :returns: A tuple containing pixel values. + """ + self.load() + if band is not None: + return tuple(self.im.getband(band)) + return tuple(self.im) + + def getextrema(self) -> tuple[float, float] | tuple[tuple[int, int], ...]: + """ + Gets the minimum and maximum pixel values for each band in + the image. + + :returns: For a single-band image, a 2-tuple containing the + minimum and maximum pixel value. For a multi-band image, + a tuple containing one 2-tuple for each band. + """ + + self.load() + if self.im.bands > 1: + return tuple(self.im.getband(i).getextrema() for i in range(self.im.bands)) + return self.im.getextrema() + + def getxmp(self) -> dict[str, Any]: + """ + Returns a dictionary containing the XMP tags. + Requires defusedxml to be installed. + + :returns: XMP tags in a dictionary. + """ + + def get_name(tag: str) -> str: + return re.sub("^{[^}]+}", "", tag) + + def get_value(element: Element) -> str | dict[str, Any] | None: + value: dict[str, Any] = {get_name(k): v for k, v in element.attrib.items()} + children = list(element) + if children: + for child in children: + name = get_name(child.tag) + child_value = get_value(child) + if name in value: + if not isinstance(value[name], list): + value[name] = [value[name]] + value[name].append(child_value) + else: + value[name] = child_value + elif value: + if element.text: + value["text"] = element.text + else: + return element.text + return value + + if ElementTree is None: + warnings.warn("XMP data cannot be read without defusedxml dependency") + return {} + if "xmp" not in self.info: + return {} + root = ElementTree.fromstring(self.info["xmp"].rstrip(b"\x00 ")) + return {get_name(root.tag): get_value(root)} + + def getexif(self) -> Exif: + """ + Gets EXIF data from the image. + + :returns: an :py:class:`~PIL.Image.Exif` object. + """ + if self._exif is None: + self._exif = Exif() + elif self._exif._loaded: + return self._exif + self._exif._loaded = True + + exif_info = self.info.get("exif") + if exif_info is None: + if "Raw profile type exif" in self.info: + exif_info = bytes.fromhex( + "".join(self.info["Raw profile type exif"].split("\n")[3:]) + ) + elif hasattr(self, "tag_v2"): + from . import TiffImagePlugin + + assert isinstance(self, TiffImagePlugin.TiffImageFile) + self._exif.bigtiff = self.tag_v2._bigtiff + self._exif.endian = self.tag_v2._endian + + assert self.fp is not None + self._exif.load_from_fp(self.fp, self.tag_v2._offset) + if exif_info is not None: + self._exif.load(exif_info) + + # XMP tags + if ExifTags.Base.Orientation not in self._exif: + xmp_tags = self.info.get("XML:com.adobe.xmp") + pattern: str | bytes = r'tiff:Orientation(="|>)([0-9])' + if not xmp_tags and (xmp_tags := self.info.get("xmp")): + pattern = rb'tiff:Orientation(="|>)([0-9])' + if xmp_tags: + match = re.search(pattern, xmp_tags) + if match: + self._exif[ExifTags.Base.Orientation] = int(match[2]) + + return self._exif + + def _reload_exif(self) -> None: + if self._exif is None or not self._exif._loaded: + return + self._exif._loaded = False + self.getexif() + + def get_child_images(self) -> list[ImageFile.ImageFile]: + from . import ImageFile + + deprecate("Image.Image.get_child_images", 13) + return ImageFile.ImageFile.get_child_images(self) # type: ignore[arg-type] + + def getim(self) -> CapsuleType: + """ + Returns a capsule that points to the internal image memory. + + :returns: A capsule object. + """ + + self.load() + return self.im.ptr + + def getpalette(self, rawmode: str | None = "RGB") -> list[int] | None: + """ + Returns the image palette as a list. + + :param rawmode: The mode in which to return the palette. ``None`` will + return the palette in its current mode. + + .. versionadded:: 9.1.0 + + :returns: A list of color values [r, g, b, ...], or None if the + image has no palette. + """ + + self.load() + try: + mode = self.im.getpalettemode() + except ValueError: + return None # no palette + if rawmode is None: + rawmode = mode + return list(self.im.getpalette(mode, rawmode)) + + @property + def has_transparency_data(self) -> bool: + """ + Determine if an image has transparency data, whether in the form of an + alpha channel, a palette with an alpha channel, or a "transparency" key + in the info dictionary. + + Note the image might still appear solid, if all of the values shown + within are opaque. + + :returns: A boolean. + """ + if ( + self.mode in ("LA", "La", "PA", "RGBA", "RGBa") + or "transparency" in self.info + ): + return True + if self.mode == "P": + assert self.palette is not None + return self.palette.mode.endswith("A") + return False + + def apply_transparency(self) -> None: + """ + If a P mode image has a "transparency" key in the info dictionary, + remove the key and instead apply the transparency to the palette. + Otherwise, the image is unchanged. + """ + if self.mode != "P" or "transparency" not in self.info: + return + + from . import ImagePalette + + palette = self.getpalette("RGBA") + assert palette is not None + transparency = self.info["transparency"] + if isinstance(transparency, bytes): + for i, alpha in enumerate(transparency): + palette[i * 4 + 3] = alpha + else: + palette[transparency * 4 + 3] = 0 + self.palette = ImagePalette.ImagePalette("RGBA", bytes(palette)) + self.palette.dirty = 1 + + del self.info["transparency"] + + def getpixel( + self, xy: tuple[int, int] | list[int] + ) -> float | tuple[int, ...] | None: + """ + Returns the pixel value at a given position. + + :param xy: The coordinate, given as (x, y). See + :ref:`coordinate-system`. + :returns: The pixel value. If the image is a multi-layer image, + this method returns a tuple. + """ + + self.load() + return self.im.getpixel(tuple(xy)) + + def getprojection(self) -> tuple[list[int], list[int]]: + """ + Get projection to x and y axes + + :returns: Two sequences, indicating where there are non-zero + pixels along the X-axis and the Y-axis, respectively. + """ + + self.load() + x, y = self.im.getprojection() + return list(x), list(y) + + def histogram( + self, mask: Image | None = None, extrema: tuple[float, float] | None = None + ) -> list[int]: + """ + Returns a histogram for the image. The histogram is returned as a + list of pixel counts, one for each pixel value in the source + image. Counts are grouped into 256 bins for each band, even if + the image has more than 8 bits per band. If the image has more + than one band, the histograms for all bands are concatenated (for + example, the histogram for an "RGB" image contains 768 values). + + A bilevel image (mode "1") is treated as a grayscale ("L") image + by this method. + + If a mask is provided, the method returns a histogram for those + parts of the image where the mask image is non-zero. The mask + image must have the same size as the image, and be either a + bi-level image (mode "1") or a grayscale image ("L"). + + :param mask: An optional mask. + :param extrema: An optional tuple of manually-specified extrema. + :returns: A list containing pixel counts. + """ + self.load() + if mask: + mask.load() + return self.im.histogram((0, 0), mask.im) + if self.mode in ("I", "F"): + return self.im.histogram( + extrema if extrema is not None else self.getextrema() + ) + return self.im.histogram() + + def entropy( + self, mask: Image | None = None, extrema: tuple[float, float] | None = None + ) -> float: + """ + Calculates and returns the entropy for the image. + + A bilevel image (mode "1") is treated as a grayscale ("L") + image by this method. + + If a mask is provided, the method employs the histogram for + those parts of the image where the mask image is non-zero. + The mask image must have the same size as the image, and be + either a bi-level image (mode "1") or a grayscale image ("L"). + + :param mask: An optional mask. + :param extrema: An optional tuple of manually-specified extrema. + :returns: A float value representing the image entropy + """ + self.load() + if mask: + mask.load() + return self.im.entropy((0, 0), mask.im) + if self.mode in ("I", "F"): + return self.im.entropy( + extrema if extrema is not None else self.getextrema() + ) + return self.im.entropy() + + def paste( + self, + im: Image | str | float | tuple[float, ...], + box: Image | tuple[int, int, int, int] | tuple[int, int] | None = None, + mask: Image | None = None, + ) -> None: + """ + Pastes another image into this image. The box argument is either + a 2-tuple giving the upper left corner, a 4-tuple defining the + left, upper, right, and lower pixel coordinate, or None (same as + (0, 0)). See :ref:`coordinate-system`. If a 4-tuple is given, the size + of the pasted image must match the size of the region. + + If the modes don't match, the pasted image is converted to the mode of + this image (see the :py:meth:`~PIL.Image.Image.convert` method for + details). + + Instead of an image, the source can be a integer or tuple + containing pixel values. The method then fills the region + with the given color. When creating RGB images, you can + also use color strings as supported by the ImageColor module. See + :ref:`colors` for more information. + + If a mask is given, this method updates only the regions + indicated by the mask. You can use either "1", "L", "LA", "RGBA" + or "RGBa" images (if present, the alpha band is used as mask). + Where the mask is 255, the given image is copied as is. Where + the mask is 0, the current value is preserved. Intermediate + values will mix the two images together, including their alpha + channels if they have them. + + See :py:meth:`~PIL.Image.Image.alpha_composite` if you want to + combine images with respect to their alpha channels. + + :param im: Source image or pixel value (integer, float or tuple). + :param box: An optional 4-tuple giving the region to paste into. + If a 2-tuple is used instead, it's treated as the upper left + corner. If omitted or None, the source is pasted into the + upper left corner. + + If an image is given as the second argument and there is no + third, the box defaults to (0, 0), and the second argument + is interpreted as a mask image. + :param mask: An optional mask image. + """ + + if isinstance(box, Image): + if mask is not None: + msg = "If using second argument as mask, third argument must be None" + raise ValueError(msg) + # abbreviated paste(im, mask) syntax + mask = box + box = None + + if box is None: + box = (0, 0) + + if len(box) == 2: + # upper left corner given; get size from image or mask + if isinstance(im, Image): + size = im.size + elif isinstance(mask, Image): + size = mask.size + else: + # FIXME: use self.size here? + msg = "cannot determine region size; use 4-item box" + raise ValueError(msg) + box += (box[0] + size[0], box[1] + size[1]) + + source: core.ImagingCore | str | float | tuple[float, ...] + if isinstance(im, str): + from . import ImageColor + + source = ImageColor.getcolor(im, self.mode) + elif isinstance(im, Image): + im.load() + if self.mode != im.mode: + if self.mode != "RGB" or im.mode not in ("LA", "RGBA", "RGBa"): + # should use an adapter for this! + im = im.convert(self.mode) + source = im.im + else: + source = im + + self._ensure_mutable() + + if mask: + mask.load() + self.im.paste(source, box, mask.im) + else: + self.im.paste(source, box) + + def alpha_composite( + self, im: Image, dest: Sequence[int] = (0, 0), source: Sequence[int] = (0, 0) + ) -> None: + """'In-place' analog of Image.alpha_composite. Composites an image + onto this image. + + :param im: image to composite over this one + :param dest: Optional 2 tuple (left, top) specifying the upper + left corner in this (destination) image. + :param source: Optional 2 (left, top) tuple for the upper left + corner in the overlay source image, or 4 tuple (left, top, right, + bottom) for the bounds of the source rectangle + + Performance Note: Not currently implemented in-place in the core layer. + """ + + if not isinstance(source, (list, tuple)): + msg = "Source must be a list or tuple" + raise ValueError(msg) + if not isinstance(dest, (list, tuple)): + msg = "Destination must be a list or tuple" + raise ValueError(msg) + + if len(source) == 4: + overlay_crop_box = tuple(source) + elif len(source) == 2: + overlay_crop_box = tuple(source) + im.size + else: + msg = "Source must be a sequence of length 2 or 4" + raise ValueError(msg) + + if not len(dest) == 2: + msg = "Destination must be a sequence of length 2" + raise ValueError(msg) + if min(source) < 0: + msg = "Source must be non-negative" + raise ValueError(msg) + + # over image, crop if it's not the whole image. + if overlay_crop_box == (0, 0) + im.size: + overlay = im + else: + overlay = im.crop(overlay_crop_box) + + # target for the paste + box = tuple(dest) + (dest[0] + overlay.width, dest[1] + overlay.height) + + # destination image. don't copy if we're using the whole image. + if box == (0, 0) + self.size: + background = self + else: + background = self.crop(box) + + result = alpha_composite(background, overlay) + self.paste(result, box) + + def point( + self, + lut: ( + Sequence[float] + | NumpyArray + | Callable[[int], float] + | Callable[[ImagePointTransform], ImagePointTransform | float] + | ImagePointHandler + ), + mode: str | None = None, + ) -> Image: + """ + Maps this image through a lookup table or function. + + :param lut: A lookup table, containing 256 (or 65536 if + self.mode=="I" and mode == "L") values per band in the + image. A function can be used instead, it should take a + single argument. The function is called once for each + possible pixel value, and the resulting table is applied to + all bands of the image. + + It may also be an :py:class:`~PIL.Image.ImagePointHandler` + object:: + + class Example(Image.ImagePointHandler): + def point(self, im: Image) -> Image: + # Return result + :param mode: Output mode (default is same as input). This can only be used if + the source image has mode "L" or "P", and the output has mode "1" or the + source image mode is "I" and the output mode is "L". + :returns: An :py:class:`~PIL.Image.Image` object. + """ + + self.load() + + if isinstance(lut, ImagePointHandler): + return lut.point(self) + + if callable(lut): + # if it isn't a list, it should be a function + if self.mode in ("I", "I;16", "F"): + # check if the function can be used with point_transform + # UNDONE wiredfool -- I think this prevents us from ever doing + # a gamma function point transform on > 8bit images. + scale, offset = _getscaleoffset(lut) # type: ignore[arg-type] + return self._new(self.im.point_transform(scale, offset)) + # for other modes, convert the function to a table + flatLut = [lut(i) for i in range(256)] * self.im.bands # type: ignore[arg-type] + else: + flatLut = lut + + if self.mode == "F": + # FIXME: _imaging returns a confusing error message for this case + msg = "point operation not supported for this mode" + raise ValueError(msg) + + if mode != "F": + flatLut = [round(i) for i in flatLut] + return self._new(self.im.point(flatLut, mode)) + + def putalpha(self, alpha: Image | int) -> None: + """ + Adds or replaces the alpha layer in this image. If the image + does not have an alpha layer, it's converted to "LA" or "RGBA". + The new layer must be either "L" or "1". + + :param alpha: The new alpha layer. This can either be an "L" or "1" + image having the same size as this image, or an integer. + """ + + self._ensure_mutable() + + if self.mode not in ("LA", "PA", "RGBA"): + # attempt to promote self to a matching alpha mode + try: + mode = getmodebase(self.mode) + "A" + try: + self.im.setmode(mode) + except (AttributeError, ValueError) as e: + # do things the hard way + im = self.im.convert(mode) + if im.mode not in ("LA", "PA", "RGBA"): + msg = "alpha channel could not be added" + raise ValueError(msg) from e # sanity check + self.im = im + self._mode = self.im.mode + except KeyError as e: + msg = "illegal image mode" + raise ValueError(msg) from e + + if self.mode in ("LA", "PA"): + band = 1 + else: + band = 3 + + if isinstance(alpha, Image): + # alpha layer + if alpha.mode not in ("1", "L"): + msg = "illegal image mode" + raise ValueError(msg) + alpha.load() + if alpha.mode == "1": + alpha = alpha.convert("L") + else: + # constant alpha + try: + self.im.fillband(band, alpha) + except (AttributeError, ValueError): + # do things the hard way + alpha = new("L", self.size, alpha) + else: + return + + self.im.putband(alpha.im, band) + + def putdata( + self, + data: Sequence[float] | Sequence[Sequence[int]] | core.ImagingCore | NumpyArray, + scale: float = 1.0, + offset: float = 0.0, + ) -> None: + """ + Copies pixel data from a flattened sequence object into the image. The + values should start at the upper left corner (0, 0), continue to the + end of the line, followed directly by the first value of the second + line, and so on. Data will be read until either the image or the + sequence ends. The scale and offset values are used to adjust the + sequence values: **pixel = value*scale + offset**. + + :param data: A flattened sequence object. See :ref:`colors` for more + information about values. + :param scale: An optional scale value. The default is 1.0. + :param offset: An optional offset value. The default is 0.0. + """ + + self._ensure_mutable() + + self.im.putdata(data, scale, offset) + + def putpalette( + self, + data: ImagePalette.ImagePalette | bytes | Sequence[int], + rawmode: str = "RGB", + ) -> None: + """ + Attaches a palette to this image. The image must be a "P", "PA", "L" + or "LA" image. + + The palette sequence must contain at most 256 colors, made up of one + integer value for each channel in the raw mode. + For example, if the raw mode is "RGB", then it can contain at most 768 + values, made up of red, green and blue values for the corresponding pixel + index in the 256 colors. + If the raw mode is "RGBA", then it can contain at most 1024 values, + containing red, green, blue and alpha values. + + Alternatively, an 8-bit string may be used instead of an integer sequence. + + :param data: A palette sequence (either a list or a string). + :param rawmode: The raw mode of the palette. Either "RGB", "RGBA", "CMYK", or a + mode that can be transformed to one of those modes (e.g. "R", "RGBA;L"). + """ + from . import ImagePalette + + if self.mode not in ("L", "LA", "P", "PA"): + msg = "illegal image mode" + raise ValueError(msg) + if isinstance(data, ImagePalette.ImagePalette): + if data.rawmode is not None: + palette = ImagePalette.raw(data.rawmode, data.palette) + else: + palette = ImagePalette.ImagePalette(palette=data.palette) + palette.dirty = 1 + else: + if not isinstance(data, bytes): + data = bytes(data) + palette = ImagePalette.raw(rawmode, data) + self._mode = "PA" if "A" in self.mode else "P" + self.palette = palette + if rawmode.startswith("CMYK"): + self.palette.mode = "CMYK" + elif "A" in rawmode: + self.palette.mode = "RGBA" + else: + self.palette.mode = "RGB" + self.load() # install new palette + + def putpixel( + self, xy: tuple[int, int], value: float | tuple[int, ...] | list[int] + ) -> None: + """ + Modifies the pixel at the given position. The color is given as + a single numerical value for single-band images, and a tuple for + multi-band images. In addition to this, RGB and RGBA tuples are + accepted for P and PA images. See :ref:`colors` for more information. + + Note that this method is relatively slow. For more extensive changes, + use :py:meth:`~PIL.Image.Image.paste` or the :py:mod:`~PIL.ImageDraw` + module instead. + + See: + + * :py:meth:`~PIL.Image.Image.paste` + * :py:meth:`~PIL.Image.Image.putdata` + * :py:mod:`~PIL.ImageDraw` + + :param xy: The pixel coordinate, given as (x, y). See + :ref:`coordinate-system`. + :param value: The pixel value. + """ + + self._ensure_mutable() + + if ( + self.mode in ("P", "PA") + and isinstance(value, (list, tuple)) + and len(value) in [3, 4] + ): + # RGB or RGBA value for a P or PA image + if self.mode == "PA": + alpha = value[3] if len(value) == 4 else 255 + value = value[:3] + assert self.palette is not None + palette_index = self.palette.getcolor(tuple(value), self) + value = (palette_index, alpha) if self.mode == "PA" else palette_index + return self.im.putpixel(xy, value) + + def remap_palette( + self, dest_map: list[int], source_palette: bytes | bytearray | None = None + ) -> Image: + """ + Rewrites the image to reorder the palette. + + :param dest_map: A list of indexes into the original palette. + e.g. ``[1,0]`` would swap a two item palette, and ``list(range(256))`` + is the identity transform. + :param source_palette: Bytes or None. + :returns: An :py:class:`~PIL.Image.Image` object. + + """ + from . import ImagePalette + + if self.mode not in ("L", "P"): + msg = "illegal image mode" + raise ValueError(msg) + + bands = 3 + palette_mode = "RGB" + if source_palette is None: + if self.mode == "P": + self.load() + palette_mode = self.im.getpalettemode() + if palette_mode == "RGBA": + bands = 4 + source_palette = self.im.getpalette(palette_mode, palette_mode) + else: # L-mode + source_palette = bytearray(i // 3 for i in range(768)) + elif len(source_palette) > 768: + bands = 4 + palette_mode = "RGBA" + + palette_bytes = b"" + new_positions = [0] * 256 + + # pick only the used colors from the palette + for i, oldPosition in enumerate(dest_map): + palette_bytes += source_palette[ + oldPosition * bands : oldPosition * bands + bands + ] + new_positions[oldPosition] = i + + # replace the palette color id of all pixel with the new id + + # Palette images are [0..255], mapped through a 1 or 3 + # byte/color map. We need to remap the whole image + # from palette 1 to palette 2. New_positions is + # an array of indexes into palette 1. Palette 2 is + # palette 1 with any holes removed. + + # We're going to leverage the convert mechanism to use the + # C code to remap the image from palette 1 to palette 2, + # by forcing the source image into 'L' mode and adding a + # mapping 'L' mode palette, then converting back to 'L' + # sans palette thus converting the image bytes, then + # assigning the optimized RGB palette. + + # perf reference, 9500x4000 gif, w/~135 colors + # 14 sec prepatch, 1 sec postpatch with optimization forced. + + mapping_palette = bytearray(new_positions) + + m_im = self.copy() + m_im._mode = "P" + + m_im.palette = ImagePalette.ImagePalette( + palette_mode, palette=mapping_palette * bands + ) + # possibly set palette dirty, then + # m_im.putpalette(mapping_palette, 'L') # converts to 'P' + # or just force it. + # UNDONE -- this is part of the general issue with palettes + m_im.im.putpalette(palette_mode, palette_mode + ";L", m_im.palette.tobytes()) + + m_im = m_im.convert("L") + + m_im.putpalette(palette_bytes, palette_mode) + m_im.palette = ImagePalette.ImagePalette(palette_mode, palette=palette_bytes) + + if "transparency" in self.info: + try: + m_im.info["transparency"] = dest_map.index(self.info["transparency"]) + except ValueError: + if "transparency" in m_im.info: + del m_im.info["transparency"] + + return m_im + + def _get_safe_box( + self, + size: tuple[int, int], + resample: Resampling, + box: tuple[float, float, float, float], + ) -> tuple[int, int, int, int]: + """Expands the box so it includes adjacent pixels + that may be used by resampling with the given resampling filter. + """ + filter_support = _filters_support[resample] - 0.5 + scale_x = (box[2] - box[0]) / size[0] + scale_y = (box[3] - box[1]) / size[1] + support_x = filter_support * scale_x + support_y = filter_support * scale_y + + return ( + max(0, int(box[0] - support_x)), + max(0, int(box[1] - support_y)), + min(self.size[0], math.ceil(box[2] + support_x)), + min(self.size[1], math.ceil(box[3] + support_y)), + ) + + def resize( + self, + size: tuple[int, int] | list[int] | NumpyArray, + resample: int | None = None, + box: tuple[float, float, float, float] | None = None, + reducing_gap: float | None = None, + ) -> Image: + """ + Returns a resized copy of this image. + + :param size: The requested size in pixels, as a tuple or array: + (width, height). + :param resample: An optional resampling filter. This can be + one of :py:data:`Resampling.NEAREST`, :py:data:`Resampling.BOX`, + :py:data:`Resampling.BILINEAR`, :py:data:`Resampling.HAMMING`, + :py:data:`Resampling.BICUBIC` or :py:data:`Resampling.LANCZOS`. + If the image has mode "1" or "P", it is always set to + :py:data:`Resampling.NEAREST`. Otherwise, the default filter is + :py:data:`Resampling.BICUBIC`. See: :ref:`concept-filters`. + :param box: An optional 4-tuple of floats providing + the source image region to be scaled. + The values must be within (0, 0, width, height) rectangle. + If omitted or None, the entire source is used. + :param reducing_gap: Apply optimization by resizing the image + in two steps. First, reducing the image by integer times + using :py:meth:`~PIL.Image.Image.reduce`. + Second, resizing using regular resampling. The last step + changes size no less than by ``reducing_gap`` times. + ``reducing_gap`` may be None (no first step is performed) + or should be greater than 1.0. The bigger ``reducing_gap``, + the closer the result to the fair resampling. + The smaller ``reducing_gap``, the faster resizing. + With ``reducing_gap`` greater or equal to 3.0, the result is + indistinguishable from fair resampling in most cases. + The default value is None (no optimization). + :returns: An :py:class:`~PIL.Image.Image` object. + """ + + if resample is None: + resample = Resampling.BICUBIC + elif resample not in ( + Resampling.NEAREST, + Resampling.BILINEAR, + Resampling.BICUBIC, + Resampling.LANCZOS, + Resampling.BOX, + Resampling.HAMMING, + ): + msg = f"Unknown resampling filter ({resample})." + + filters = [ + f"{filter[1]} ({filter[0]})" + for filter in ( + (Resampling.NEAREST, "Image.Resampling.NEAREST"), + (Resampling.LANCZOS, "Image.Resampling.LANCZOS"), + (Resampling.BILINEAR, "Image.Resampling.BILINEAR"), + (Resampling.BICUBIC, "Image.Resampling.BICUBIC"), + (Resampling.BOX, "Image.Resampling.BOX"), + (Resampling.HAMMING, "Image.Resampling.HAMMING"), + ) + ] + msg += f" Use {', '.join(filters[:-1])} or {filters[-1]}" + raise ValueError(msg) + + if reducing_gap is not None and reducing_gap < 1.0: + msg = "reducing_gap must be 1.0 or greater" + raise ValueError(msg) + + if box is None: + box = (0, 0) + self.size + + size = tuple(size) + if self.size == size and box == (0, 0) + self.size: + return self.copy() + + if self.mode in ("1", "P"): + resample = Resampling.NEAREST + + if self.mode in ["LA", "RGBA"] and resample != Resampling.NEAREST: + im = self.convert({"LA": "La", "RGBA": "RGBa"}[self.mode]) + im = im.resize(size, resample, box) + return im.convert(self.mode) + + self.load() + + if reducing_gap is not None and resample != Resampling.NEAREST: + factor_x = int((box[2] - box[0]) / size[0] / reducing_gap) or 1 + factor_y = int((box[3] - box[1]) / size[1] / reducing_gap) or 1 + if factor_x > 1 or factor_y > 1: + reduce_box = self._get_safe_box(size, cast(Resampling, resample), box) + factor = (factor_x, factor_y) + self = ( + self.reduce(factor, box=reduce_box) + if callable(self.reduce) + else Image.reduce(self, factor, box=reduce_box) + ) + box = ( + (box[0] - reduce_box[0]) / factor_x, + (box[1] - reduce_box[1]) / factor_y, + (box[2] - reduce_box[0]) / factor_x, + (box[3] - reduce_box[1]) / factor_y, + ) + + if self.size[1] > self.size[0] * 100 and size[1] < self.size[1]: + im = self.im.resize( + (self.size[0], size[1]), resample, (0, box[1], self.size[0], box[3]) + ) + im = im.resize(size, resample, (box[0], 0, box[2], size[1])) + else: + im = self.im.resize(size, resample, box) + return self._new(im) + + def reduce( + self, + factor: int | tuple[int, int], + box: tuple[int, int, int, int] | None = None, + ) -> Image: + """ + Returns a copy of the image reduced ``factor`` times. + If the size of the image is not dividable by ``factor``, + the resulting size will be rounded up. + + :param factor: A greater than 0 integer or tuple of two integers + for width and height separately. + :param box: An optional 4-tuple of ints providing + the source image region to be reduced. + The values must be within ``(0, 0, width, height)`` rectangle. + If omitted or ``None``, the entire source is used. + """ + if not isinstance(factor, (list, tuple)): + factor = (factor, factor) + + if box is None: + box = (0, 0) + self.size + + if factor == (1, 1) and box == (0, 0) + self.size: + return self.copy() + + if self.mode in ["LA", "RGBA"]: + im = self.convert({"LA": "La", "RGBA": "RGBa"}[self.mode]) + im = im.reduce(factor, box) + return im.convert(self.mode) + + self.load() + + return self._new(self.im.reduce(factor, box)) + + def rotate( + self, + angle: float, + resample: Resampling = Resampling.NEAREST, + expand: int | bool = False, + center: tuple[float, float] | None = None, + translate: tuple[int, int] | None = None, + fillcolor: float | tuple[float, ...] | str | None = None, + ) -> Image: + """ + Returns a rotated copy of this image. This method returns a + copy of this image, rotated the given number of degrees counter + clockwise around its centre. + + :param angle: In degrees counter clockwise. + :param resample: An optional resampling filter. This can be + one of :py:data:`Resampling.NEAREST` (use nearest neighbour), + :py:data:`Resampling.BILINEAR` (linear interpolation in a 2x2 + environment), or :py:data:`Resampling.BICUBIC` (cubic spline + interpolation in a 4x4 environment). If omitted, or if the image has + mode "1" or "P", it is set to :py:data:`Resampling.NEAREST`. + See :ref:`concept-filters`. + :param expand: Optional expansion flag. If true, expands the output + image to make it large enough to hold the entire rotated image. + If false or omitted, make the output image the same size as the + input image. Note that the expand flag assumes rotation around + the center and no translation. + :param center: Optional center of rotation (a 2-tuple). Origin is + the upper left corner. Default is the center of the image. + :param translate: An optional post-rotate translation (a 2-tuple). + :param fillcolor: An optional color for area outside the rotated image. + :returns: An :py:class:`~PIL.Image.Image` object. + """ + + angle = angle % 360.0 + + # Fast paths regardless of filter, as long as we're not + # translating or changing the center. + if not (center or translate): + if angle == 0: + return self.copy() + if angle == 180: + return self.transpose(Transpose.ROTATE_180) + if angle in (90, 270) and (expand or self.width == self.height): + return self.transpose( + Transpose.ROTATE_90 if angle == 90 else Transpose.ROTATE_270 + ) + + # Calculate the affine matrix. Note that this is the reverse + # transformation (from destination image to source) because we + # want to interpolate the (discrete) destination pixel from + # the local area around the (floating) source pixel. + + # The matrix we actually want (note that it operates from the right): + # (1, 0, tx) (1, 0, cx) ( cos a, sin a, 0) (1, 0, -cx) + # (0, 1, ty) * (0, 1, cy) * (-sin a, cos a, 0) * (0, 1, -cy) + # (0, 0, 1) (0, 0, 1) ( 0, 0, 1) (0, 0, 1) + + # The reverse matrix is thus: + # (1, 0, cx) ( cos -a, sin -a, 0) (1, 0, -cx) (1, 0, -tx) + # (0, 1, cy) * (-sin -a, cos -a, 0) * (0, 1, -cy) * (0, 1, -ty) + # (0, 0, 1) ( 0, 0, 1) (0, 0, 1) (0, 0, 1) + + # In any case, the final translation may be updated at the end to + # compensate for the expand flag. + + w, h = self.size + + if translate is None: + post_trans = (0, 0) + else: + post_trans = translate + if center is None: + center = (w / 2, h / 2) + + angle = -math.radians(angle) + matrix = [ + round(math.cos(angle), 15), + round(math.sin(angle), 15), + 0.0, + round(-math.sin(angle), 15), + round(math.cos(angle), 15), + 0.0, + ] + + def transform(x: float, y: float, matrix: list[float]) -> tuple[float, float]: + a, b, c, d, e, f = matrix + return a * x + b * y + c, d * x + e * y + f + + matrix[2], matrix[5] = transform( + -center[0] - post_trans[0], -center[1] - post_trans[1], matrix + ) + matrix[2] += center[0] + matrix[5] += center[1] + + if expand: + # calculate output size + xx = [] + yy = [] + for x, y in ((0, 0), (w, 0), (w, h), (0, h)): + transformed_x, transformed_y = transform(x, y, matrix) + xx.append(transformed_x) + yy.append(transformed_y) + nw = math.ceil(max(xx)) - math.floor(min(xx)) + nh = math.ceil(max(yy)) - math.floor(min(yy)) + + # We multiply a translation matrix from the right. Because of its + # special form, this is the same as taking the image of the + # translation vector as new translation vector. + matrix[2], matrix[5] = transform(-(nw - w) / 2.0, -(nh - h) / 2.0, matrix) + w, h = nw, nh + + return self.transform( + (w, h), Transform.AFFINE, matrix, resample, fillcolor=fillcolor + ) + + def save( + self, fp: StrOrBytesPath | IO[bytes], format: str | None = None, **params: Any + ) -> None: + """ + Saves this image under the given filename. If no format is + specified, the format to use is determined from the filename + extension, if possible. + + Keyword options can be used to provide additional instructions + to the writer. If a writer doesn't recognise an option, it is + silently ignored. The available options are described in the + :doc:`image format documentation + <../handbook/image-file-formats>` for each writer. + + You can use a file object instead of a filename. In this case, + you must always specify the format. The file object must + implement the ``seek``, ``tell``, and ``write`` + methods, and be opened in binary mode. + + :param fp: A filename (string), os.PathLike object or file object. + :param format: Optional format override. If omitted, the + format to use is determined from the filename extension. + If a file object was used instead of a filename, this + parameter should always be used. + :param params: Extra parameters to the image writer. These can also be + set on the image itself through ``encoderinfo``. This is useful when + saving multiple images:: + + # Saving XMP data to a single image + from PIL import Image + red = Image.new("RGB", (1, 1), "#f00") + red.save("out.mpo", xmp=b"test") + + # Saving XMP data to the second frame of an image + from PIL import Image + black = Image.new("RGB", (1, 1)) + red = Image.new("RGB", (1, 1), "#f00") + red.encoderinfo = {"xmp": b"test"} + black.save("out.mpo", save_all=True, append_images=[red]) + :returns: None + :exception ValueError: If the output format could not be determined + from the file name. Use the format option to solve this. + :exception OSError: If the file could not be written. The file + may have been created, and may contain partial data. + """ + + filename: str | bytes = "" + open_fp = False + if is_path(fp): + filename = os.fspath(fp) + open_fp = True + elif fp == sys.stdout: + try: + fp = sys.stdout.buffer + except AttributeError: + pass + if not filename and hasattr(fp, "name") and is_path(fp.name): + # only set the name for metadata purposes + filename = os.fspath(fp.name) + + if format: + preinit() + else: + filename_ext = os.path.splitext(filename)[1].lower() + ext = ( + filename_ext.decode() + if isinstance(filename_ext, bytes) + else filename_ext + ) + + # Try importing only the plugin for this extension first + if not _import_plugin_for_extension(ext): + preinit() + + if ext not in EXTENSION: + init() + try: + format = EXTENSION[ext] + except KeyError as e: + msg = f"unknown file extension: {ext}" + raise ValueError(msg) from e + + from . import ImageFile + + # may mutate self! + if isinstance(self, ImageFile.ImageFile) and os.path.abspath( + filename + ) == os.path.abspath(self.filename): + self._ensure_mutable() + else: + self.load() + + save_all = params.pop("save_all", None) + self._default_encoderinfo = params + encoderinfo = getattr(self, "encoderinfo", {}) + self._attach_default_encoderinfo(self) + self.encoderconfig: tuple[Any, ...] = () + + if format.upper() not in SAVE: + init() + if save_all or ( + save_all is None + and params.get("append_images") + and format.upper() in SAVE_ALL + ): + save_handler = SAVE_ALL[format.upper()] + else: + save_handler = SAVE[format.upper()] + + created = False + if open_fp: + created = not os.path.exists(filename) + if params.get("append", False): + # Open also for reading ("+"), because TIFF save_all + # writer needs to go back and edit the written data. + fp = builtins.open(filename, "r+b") + else: + fp = builtins.open(filename, "w+b") + else: + fp = cast(IO[bytes], fp) + + try: + save_handler(self, fp, filename) + except Exception: + if open_fp: + fp.close() + if created: + try: + os.remove(filename) + except PermissionError: + pass + raise + finally: + self.encoderinfo = encoderinfo + if open_fp: + fp.close() + + def _attach_default_encoderinfo(self, im: Image) -> dict[str, Any]: + encoderinfo = getattr(self, "encoderinfo", {}) + self.encoderinfo = {**im._default_encoderinfo, **encoderinfo} + return encoderinfo + + def seek(self, frame: int) -> None: + """ + Seeks to the given frame in this sequence file. If you seek + beyond the end of the sequence, the method raises an + ``EOFError`` exception. When a sequence file is opened, the + library automatically seeks to frame 0. + + See :py:meth:`~PIL.Image.Image.tell`. + + If defined, :attr:`~PIL.Image.Image.n_frames` refers to the + number of available frames. + + :param frame: Frame number, starting at 0. + :exception EOFError: If the call attempts to seek beyond the end + of the sequence. + """ + + # overridden by file handlers + if frame != 0: + msg = "no more images in file" + raise EOFError(msg) + + def show(self, title: str | None = None) -> None: + """ + Displays this image. This method is mainly intended for debugging purposes. + + This method calls :py:func:`PIL.ImageShow.show` internally. You can use + :py:func:`PIL.ImageShow.register` to override its default behaviour. + + The image is first saved to a temporary file. By default, it will be in + PNG format. + + On Unix, the image is then opened using the **xdg-open**, **display**, + **gm**, **eog** or **xv** utility, depending on which one can be found. + + On macOS, the image is opened with the native Preview application. + + On Windows, the image is opened with the standard PNG display utility. + + :param title: Optional title to use for the image window, where possible. + """ + + from . import ImageShow + + ImageShow.show(self, title) + + def split(self) -> tuple[Image, ...]: + """ + Split this image into individual bands. This method returns a + tuple of individual image bands from an image. For example, + splitting an "RGB" image creates three new images each + containing a copy of one of the original bands (red, green, + blue). + + If you need only one band, :py:meth:`~PIL.Image.Image.getchannel` + method can be more convenient and faster. + + :returns: A tuple containing bands. + """ + + self.load() + if self.im.bands == 1: + return (self.copy(),) + return tuple(map(self._new, self.im.split())) + + def getchannel(self, channel: int | str) -> Image: + """ + Returns an image containing a single channel of the source image. + + :param channel: What channel to return. Could be index + (0 for "R" channel of "RGB") or channel name + ("A" for alpha channel of "RGBA"). + :returns: An image in "L" mode. + + .. versionadded:: 4.3.0 + """ + self.load() + + if isinstance(channel, str): + try: + channel = self.getbands().index(channel) + except ValueError as e: + msg = f'The image has no channel "{channel}"' + raise ValueError(msg) from e + + return self._new(self.im.getband(channel)) + + def tell(self) -> int: + """ + Returns the current frame number. See :py:meth:`~PIL.Image.Image.seek`. + + If defined, :attr:`~PIL.Image.Image.n_frames` refers to the + number of available frames. + + :returns: Frame number, starting with 0. + """ + return 0 + + def thumbnail( + self, + size: tuple[float, float], + resample: Resampling = Resampling.BICUBIC, + reducing_gap: float | None = 2.0, + ) -> None: + """ + Make this image into a thumbnail. This method modifies the + image to contain a thumbnail version of itself, no larger than + the given size. This method calculates an appropriate thumbnail + size to preserve the aspect of the image, calls the + :py:meth:`~PIL.Image.Image.draft` method to configure the file reader + (where applicable), and finally resizes the image. + + Note that this function modifies the :py:class:`~PIL.Image.Image` + object in place. If you need to use the full resolution image as well, + apply this method to a :py:meth:`~PIL.Image.Image.copy` of the original + image. + + :param size: The requested size in pixels, as a 2-tuple: + (width, height). + :param resample: Optional resampling filter. This can be one + of :py:data:`Resampling.NEAREST`, :py:data:`Resampling.BOX`, + :py:data:`Resampling.BILINEAR`, :py:data:`Resampling.HAMMING`, + :py:data:`Resampling.BICUBIC` or :py:data:`Resampling.LANCZOS`. + If omitted, it defaults to :py:data:`Resampling.BICUBIC`. + (was :py:data:`Resampling.NEAREST` prior to version 2.5.0). + See: :ref:`concept-filters`. + :param reducing_gap: Apply optimization by resizing the image + in two steps. First, reducing the image by integer times + using :py:meth:`~PIL.Image.Image.reduce` or + :py:meth:`~PIL.Image.Image.draft` for JPEG images. + Second, resizing using regular resampling. The last step + changes size no less than by ``reducing_gap`` times. + ``reducing_gap`` may be None (no first step is performed) + or should be greater than 1.0. The bigger ``reducing_gap``, + the closer the result to the fair resampling. + The smaller ``reducing_gap``, the faster resizing. + With ``reducing_gap`` greater or equal to 3.0, the result is + indistinguishable from fair resampling in most cases. + The default value is 2.0 (very close to fair resampling + while still being faster in many cases). + :returns: None + """ + + provided_size = tuple(map(math.floor, size)) + + def preserve_aspect_ratio() -> tuple[int, int] | None: + def round_aspect(number: float, key: Callable[[int], float]) -> int: + return max(min(math.floor(number), math.ceil(number), key=key), 1) + + x, y = provided_size + if x >= self.width and y >= self.height: + return None + + aspect = self.width / self.height + if x / y >= aspect: + x = round_aspect(y * aspect, key=lambda n: abs(aspect - n / y)) + else: + y = round_aspect( + x / aspect, key=lambda n: 0 if n == 0 else abs(aspect - x / n) + ) + return x, y + + preserved_size = preserve_aspect_ratio() + if preserved_size is None: + return + final_size = preserved_size + + box = None + if reducing_gap is not None: + res = self.draft( + None, (int(size[0] * reducing_gap), int(size[1] * reducing_gap)) + ) + if res is not None: + box = res[1] + + if self.size != final_size: + im = self.resize(final_size, resample, box=box, reducing_gap=reducing_gap) + + self.im = im.im + self._size = final_size + self._mode = self.im.mode + + self.readonly = 0 + + # FIXME: the different transform methods need further explanation + # instead of bloating the method docs, add a separate chapter. + def transform( + self, + size: tuple[int, int], + method: Transform | ImageTransformHandler | SupportsGetData, + data: Sequence[Any] | None = None, + resample: int = Resampling.NEAREST, + fill: int = 1, + fillcolor: float | tuple[float, ...] | str | None = None, + ) -> Image: + """ + Transforms this image. This method creates a new image with the + given size, and the same mode as the original, and copies data + to the new image using the given transform. + + :param size: The output size in pixels, as a 2-tuple: + (width, height). + :param method: The transformation method. This is one of + :py:data:`Transform.EXTENT` (cut out a rectangular subregion), + :py:data:`Transform.AFFINE` (affine transform), + :py:data:`Transform.PERSPECTIVE` (perspective transform), + :py:data:`Transform.QUAD` (map a quadrilateral to a rectangle), or + :py:data:`Transform.MESH` (map a number of source quadrilaterals + in one operation). + + It may also be an :py:class:`~PIL.Image.ImageTransformHandler` + object:: + + class Example(Image.ImageTransformHandler): + def transform(self, size, data, resample, fill=1): + # Return result + + Implementations of :py:class:`~PIL.Image.ImageTransformHandler` + for some of the :py:class:`Transform` methods are provided + in :py:mod:`~PIL.ImageTransform`. + + It may also be an object with a ``method.getdata`` method + that returns a tuple supplying new ``method`` and ``data`` values:: + + class Example: + def getdata(self): + method = Image.Transform.EXTENT + data = (0, 0, 100, 100) + return method, data + :param data: Extra data to the transformation method. + :param resample: Optional resampling filter. It can be one of + :py:data:`Resampling.NEAREST` (use nearest neighbour), + :py:data:`Resampling.BILINEAR` (linear interpolation in a 2x2 + environment), or :py:data:`Resampling.BICUBIC` (cubic spline + interpolation in a 4x4 environment). If omitted, or if the image + has mode "1" or "P", it is set to :py:data:`Resampling.NEAREST`. + See: :ref:`concept-filters`. + :param fill: If ``method`` is an + :py:class:`~PIL.Image.ImageTransformHandler` object, this is one of + the arguments passed to it. Otherwise, it is unused. + :param fillcolor: Optional fill color for the area outside the + transform in the output image. + :returns: An :py:class:`~PIL.Image.Image` object. + """ + + if self.mode in ("LA", "RGBA") and resample != Resampling.NEAREST: + return ( + self.convert({"LA": "La", "RGBA": "RGBa"}[self.mode]) + .transform(size, method, data, resample, fill, fillcolor) + .convert(self.mode) + ) + + if isinstance(method, ImageTransformHandler): + return method.transform(size, self, resample=resample, fill=fill) + + if hasattr(method, "getdata"): + # compatibility w. old-style transform objects + method, data = method.getdata() + + if data is None: + msg = "missing method data" + raise ValueError(msg) + + im = new(self.mode, size, fillcolor) + if self.mode == "P" and self.palette: + im.palette = self.palette.copy() + im.info = self.info.copy() + if method == Transform.MESH: + # list of quads + for box, quad in data: + im.__transformer( + box, self, Transform.QUAD, quad, resample, fillcolor is None + ) + else: + im.__transformer( + (0, 0) + size, self, method, data, resample, fillcolor is None + ) + + return im + + def __transformer( + self, + box: tuple[int, int, int, int], + image: Image, + method: Transform, + data: Sequence[float], + resample: int = Resampling.NEAREST, + fill: bool = True, + ) -> None: + w = box[2] - box[0] + h = box[3] - box[1] + + if method == Transform.AFFINE: + data = data[:6] + + elif method == Transform.EXTENT: + # convert extent to an affine transform + x0, y0, x1, y1 = data + xs = (x1 - x0) / w + ys = (y1 - y0) / h + method = Transform.AFFINE + data = (xs, 0, x0, 0, ys, y0) + + elif method == Transform.PERSPECTIVE: + data = data[:8] + + elif method == Transform.QUAD: + # quadrilateral warp. data specifies the four corners + # given as NW, SW, SE, and NE. + nw = data[:2] + sw = data[2:4] + se = data[4:6] + ne = data[6:8] + x0, y0 = nw + As = 1.0 / w + At = 1.0 / h + data = ( + x0, + (ne[0] - x0) * As, + (sw[0] - x0) * At, + (se[0] - sw[0] - ne[0] + x0) * As * At, + y0, + (ne[1] - y0) * As, + (sw[1] - y0) * At, + (se[1] - sw[1] - ne[1] + y0) * As * At, + ) + + else: + msg = "unknown transformation method" + raise ValueError(msg) + + if resample not in ( + Resampling.NEAREST, + Resampling.BILINEAR, + Resampling.BICUBIC, + ): + if resample in (Resampling.BOX, Resampling.HAMMING, Resampling.LANCZOS): + unusable: dict[int, str] = { + Resampling.BOX: "Image.Resampling.BOX", + Resampling.HAMMING: "Image.Resampling.HAMMING", + Resampling.LANCZOS: "Image.Resampling.LANCZOS", + } + msg = unusable[resample] + f" ({resample}) cannot be used." + else: + msg = f"Unknown resampling filter ({resample})." + + filters = [ + f"{filter[1]} ({filter[0]})" + for filter in ( + (Resampling.NEAREST, "Image.Resampling.NEAREST"), + (Resampling.BILINEAR, "Image.Resampling.BILINEAR"), + (Resampling.BICUBIC, "Image.Resampling.BICUBIC"), + ) + ] + msg += f" Use {', '.join(filters[:-1])} or {filters[-1]}" + raise ValueError(msg) + + image.load() + + self.load() + + if image.mode in ("1", "P"): + resample = Resampling.NEAREST + + self.im.transform(box, image.im, method, data, resample, fill) + + def transpose(self, method: Transpose) -> Image: + """ + Transpose image (flip or rotate in 90 degree steps) + + :param method: One of :py:data:`Transpose.FLIP_LEFT_RIGHT`, + :py:data:`Transpose.FLIP_TOP_BOTTOM`, :py:data:`Transpose.ROTATE_90`, + :py:data:`Transpose.ROTATE_180`, :py:data:`Transpose.ROTATE_270`, + :py:data:`Transpose.TRANSPOSE` or :py:data:`Transpose.TRANSVERSE`. + :returns: Returns a flipped or rotated copy of this image. + """ + + self.load() + return self._new(self.im.transpose(method)) + + def effect_spread(self, distance: int) -> Image: + """ + Randomly spread pixels in an image. + + :param distance: Distance to spread pixels. + """ + self.load() + return self._new(self.im.effect_spread(distance)) + + def toqimage(self) -> ImageQt.ImageQt: + """Returns a QImage copy of this image""" + from . import ImageQt + + if not ImageQt.qt_is_installed: + msg = "Qt bindings are not installed" + raise ImportError(msg) + return ImageQt.toqimage(self) + + def toqpixmap(self) -> ImageQt.QPixmap: + """Returns a QPixmap copy of this image""" + from . import ImageQt + + if not ImageQt.qt_is_installed: + msg = "Qt bindings are not installed" + raise ImportError(msg) + return ImageQt.toqpixmap(self) + + +# -------------------------------------------------------------------- +# Abstract handlers. + + +class ImagePointHandler(abc.ABC): + """ + Used as a mixin by point transforms + (for use with :py:meth:`~PIL.Image.Image.point`) + """ + + @abc.abstractmethod + def point(self, im: Image) -> Image: + pass + + +class ImageTransformHandler(abc.ABC): + """ + Used as a mixin by geometry transforms + (for use with :py:meth:`~PIL.Image.Image.transform`) + """ + + @abc.abstractmethod + def transform( + self, + size: tuple[int, int], + image: Image, + **options: Any, + ) -> Image: + pass + + +# -------------------------------------------------------------------- +# Factories + + +def _check_size(size: Any) -> None: + """ + Common check to enforce type and sanity check on size tuples + + :param size: Should be a 2 tuple of (width, height) + :returns: None, or raises a ValueError + """ + + if not isinstance(size, (list, tuple)): + msg = "Size must be a list or tuple" + raise ValueError(msg) + if len(size) != 2: + msg = "Size must be a sequence of length 2" + raise ValueError(msg) + if size[0] < 0 or size[1] < 0: + msg = "Width and height must be >= 0" + raise ValueError(msg) + + +def new( + mode: str, + size: tuple[int, int] | list[int], + color: float | tuple[float, ...] | str | None = 0, +) -> Image: + """ + Creates a new image with the given mode and size. + + :param mode: The mode to use for the new image. See: + :ref:`concept-modes`. + :param size: A 2-tuple, containing (width, height) in pixels. + :param color: What color to use for the image. Default is black. If given, + this should be a single integer or floating point value for single-band + modes, and a tuple for multi-band modes (one value per band). When + creating RGB or HSV images, you can also use color strings as supported + by the ImageColor module. See :ref:`colors` for more information. If the + color is None, the image is not initialised. + :returns: An :py:class:`~PIL.Image.Image` object. + """ + + _check_size(size) + + if color is None: + # don't initialize + return Image()._new(core.new(mode, size)) + + if isinstance(color, str): + # css3-style specifier + + from . import ImageColor + + color = ImageColor.getcolor(color, mode) + + im = Image() + if ( + mode == "P" + and isinstance(color, (list, tuple)) + and all(isinstance(i, int) for i in color) + ): + color_ints: tuple[int, ...] = cast(tuple[int, ...], tuple(color)) + if len(color_ints) == 3 or len(color_ints) == 4: + # RGB or RGBA value for a P image + from . import ImagePalette + + im.palette = ImagePalette.ImagePalette() + color = im.palette.getcolor(color_ints) + return im._new(core.fill(mode, size, color)) + + +def frombytes( + mode: str, + size: tuple[int, int], + data: bytes | bytearray | SupportsArrayInterface, + decoder_name: str = "raw", + *args: Any, +) -> Image: + """ + Creates a copy of an image memory from pixel data in a buffer. + + In its simplest form, this function takes three arguments + (mode, size, and unpacked pixel data). + + You can also use any pixel decoder supported by PIL. For more + information on available decoders, see the section + :ref:`Writing Your Own File Codec `. + + Note that this function decodes pixel data only, not entire images. + If you have an entire image in a string, wrap it in a + :py:class:`~io.BytesIO` object, and use :py:func:`~PIL.Image.open` to load + it. + + :param mode: The image mode. See: :ref:`concept-modes`. + :param size: The image size. + :param data: A byte buffer containing raw data for the given mode. + :param decoder_name: What decoder to use. + :param args: Additional parameters for the given decoder. + :returns: An :py:class:`~PIL.Image.Image` object. + """ + + _check_size(size) + + im = new(mode, size) + if im.width != 0 and im.height != 0: + decoder_args: Any = args + if len(decoder_args) == 1 and isinstance(decoder_args[0], tuple): + # may pass tuple instead of argument list + decoder_args = decoder_args[0] + + if decoder_name == "raw" and decoder_args == (): + decoder_args = mode + + im.frombytes(data, decoder_name, decoder_args) + return im + + +def frombuffer( + mode: str, + size: tuple[int, int], + data: bytes | SupportsArrayInterface, + decoder_name: str = "raw", + *args: Any, +) -> Image: + """ + Creates an image memory referencing pixel data in a byte buffer. + + This function is similar to :py:func:`~PIL.Image.frombytes`, but uses data + in the byte buffer, where possible. This means that changes to the + original buffer object are reflected in this image). Not all modes can + share memory; supported modes include "L", "RGBX", "RGBA", and "CMYK". + + Note that this function decodes pixel data only, not entire images. + If you have an entire image file in a string, wrap it in a + :py:class:`~io.BytesIO` object, and use :py:func:`~PIL.Image.open` to load it. + + The default parameters used for the "raw" decoder differs from that used for + :py:func:`~PIL.Image.frombytes`. This is a bug, and will probably be fixed in a + future release. The current release issues a warning if you do this; to disable + the warning, you should provide the full set of parameters. See below for details. + + :param mode: The image mode. See: :ref:`concept-modes`. + :param size: The image size. + :param data: A bytes or other buffer object containing raw + data for the given mode. + :param decoder_name: What decoder to use. + :param args: Additional parameters for the given decoder. For the + default encoder ("raw"), it's recommended that you provide the + full set of parameters:: + + frombuffer(mode, size, data, "raw", mode, 0, 1) + + :returns: An :py:class:`~PIL.Image.Image` object. + + .. versionadded:: 1.1.4 + """ + + _check_size(size) + + # may pass tuple instead of argument list + if len(args) == 1 and isinstance(args[0], tuple): + args = args[0] + + if decoder_name == "raw": + if args == (): + args = mode, 0, 1 + if args[0] in _MAPMODES: + im = new(mode, (0, 0)) + im = im._new(core.map_buffer(data, size, decoder_name, 0, args)) + if mode == "P": + from . import ImagePalette + + im.palette = ImagePalette.ImagePalette("RGB", im.im.getpalette("RGB")) + im.readonly = 1 + return im + + return frombytes(mode, size, data, decoder_name, args) + + +class SupportsArrayInterface(Protocol): + """ + An object that has an ``__array_interface__`` dictionary. + """ + + @property + def __array_interface__(self) -> dict[str, Any]: + raise NotImplementedError() + + +class SupportsArrowArrayInterface(Protocol): + """ + An object that has an ``__arrow_c_array__`` method corresponding to the arrow c + data interface. + """ + + def __arrow_c_array__( + self, requested_schema: "PyCapsule" = None # type: ignore[name-defined] # noqa: F821, UP037 + ) -> tuple["PyCapsule", "PyCapsule"]: # type: ignore[name-defined] # noqa: F821, UP037 + raise NotImplementedError() + + +def fromarray(obj: SupportsArrayInterface, mode: str | None = None) -> Image: + """ + Creates an image memory from an object exporting the array interface + (using the buffer protocol):: + + from PIL import Image + import numpy as np + a = np.zeros((5, 5)) + im = Image.fromarray(a) + + If ``obj`` is not contiguous, then the ``tobytes`` method is called + and :py:func:`~PIL.Image.frombuffer` is used. + + In the case of NumPy, be aware that Pillow modes do not always correspond + to NumPy dtypes. Pillow modes only offer 1-bit pixels, 8-bit pixels, + 32-bit signed integer pixels, and 32-bit floating point pixels. + + Pillow images can also be converted to arrays:: + + from PIL import Image + import numpy as np + im = Image.open("hopper.jpg") + a = np.asarray(im) + + When converting Pillow images to arrays however, only pixel values are + transferred. This means that P and PA mode images will lose their palette. + + :param obj: Object with array interface + :param mode: Optional mode to use when reading ``obj``. Since pixel values do not + contain information about palettes or color spaces, this can be used to place + grayscale L mode data within a P mode image, or read RGB data as YCbCr for + example. + + See: :ref:`concept-modes` for general information about modes. + :returns: An image object. + + .. versionadded:: 1.1.6 + """ + arr = obj.__array_interface__ + shape = arr["shape"] + ndim = len(shape) + strides = arr.get("strides", None) + try: + typekey = (1, 1) + shape[2:], arr["typestr"] + except KeyError as e: + if mode is not None: + typekey = None + color_modes: list[str] = [] + else: + msg = "Cannot handle this data type" + raise TypeError(msg) from e + if typekey is not None: + try: + typemode, rawmode, color_modes = _fromarray_typemap[typekey] + except KeyError as e: + typekey_shape, typestr = typekey + msg = f"Cannot handle this data type: {typekey_shape}, {typestr}" + raise TypeError(msg) from e + if mode is not None: + if mode != typemode and mode not in color_modes: + deprecate("'mode' parameter for changing data types", 13) + rawmode = mode + else: + mode = typemode + if mode in ["1", "L", "I", "P", "F"]: + ndmax = 2 + elif mode == "RGB": + ndmax = 3 + else: + ndmax = 4 + if ndim > ndmax: + msg = f"Too many dimensions: {ndim} > {ndmax}." + raise ValueError(msg) + + size = 1 if ndim == 1 else shape[1], shape[0] + if strides is not None: + if hasattr(obj, "tobytes"): + obj = obj.tobytes() + elif hasattr(obj, "tostring"): + obj = obj.tostring() + else: + msg = "'strides' requires either tobytes() or tostring()" + raise ValueError(msg) + + return frombuffer(mode, size, obj, "raw", rawmode, 0, 1) + + +def fromarrow( + obj: SupportsArrowArrayInterface, mode: str, size: tuple[int, int] +) -> Image: + """Creates an image with zero-copy shared memory from an object exporting + the arrow_c_array interface protocol:: + + from PIL import Image + import pyarrow as pa + arr = pa.array([0]*(5*5*4), type=pa.uint8()) + im = Image.fromarrow(arr, 'RGBA', (5, 5)) + + If the data representation of the ``obj`` is not compatible with + Pillow internal storage, a ValueError is raised. + + Pillow images can also be converted to Arrow objects:: + + from PIL import Image + import pyarrow as pa + im = Image.open('hopper.jpg') + arr = pa.array(im) + + As with array support, when converting Pillow images to arrays, + only pixel values are transferred. This means that P and PA mode + images will lose their palette. + + :param obj: Object with an arrow_c_array interface + :param mode: Image mode. + :param size: Image size. This must match the storage of the arrow object. + :returns: An Image object + + Note that according to the Arrow spec, both the producer and the + consumer should consider the exported array to be immutable, as + unsynchronized updates will potentially cause inconsistent data. + + See: :ref:`arrow-support` for more detailed information + + .. versionadded:: 11.2.1 + + """ + if not hasattr(obj, "__arrow_c_array__"): + msg = "arrow_c_array interface not found" + raise ValueError(msg) + + schema_capsule, array_capsule = obj.__arrow_c_array__() + _im = core.new_arrow(mode, size, schema_capsule, array_capsule) + if _im: + return Image()._new(_im) + + msg = "new_arrow returned None without an exception" + raise ValueError(msg) + + +def fromqimage(im: ImageQt.QImage) -> ImageFile.ImageFile: + """Creates an image instance from a QImage image""" + from . import ImageQt + + if not ImageQt.qt_is_installed: + msg = "Qt bindings are not installed" + raise ImportError(msg) + return ImageQt.fromqimage(im) + + +def fromqpixmap(im: ImageQt.QPixmap) -> ImageFile.ImageFile: + """Creates an image instance from a QPixmap image""" + from . import ImageQt + + if not ImageQt.qt_is_installed: + msg = "Qt bindings are not installed" + raise ImportError(msg) + return ImageQt.fromqpixmap(im) + + +_fromarray_typemap = { + # (shape, typestr) => mode, rawmode, color modes + # first two members of shape are set to one + ((1, 1), "|b1"): ("1", "1;8", []), + ((1, 1), "|u1"): ("L", "L", ["P"]), + ((1, 1), "|i1"): ("I", "I;8", []), + ((1, 1), "u2"): ("I", "I;16B", []), + ((1, 1), "i2"): ("I", "I;16BS", []), + ((1, 1), "u4"): ("I", "I;32B", []), + ((1, 1), "i4"): ("I", "I;32BS", []), + ((1, 1), "f4"): ("F", "F;32BF", []), + ((1, 1), "f8"): ("F", "F;64BF", []), + ((1, 1, 2), "|u1"): ("LA", "LA", ["La", "PA"]), + ((1, 1, 3), "|u1"): ("RGB", "RGB", ["YCbCr", "LAB", "HSV"]), + ((1, 1, 4), "|u1"): ("RGBA", "RGBA", ["RGBa", "RGBX", "CMYK"]), + # shortcuts: + ((1, 1), f"{_ENDIAN}i4"): ("I", "I", []), + ((1, 1), f"{_ENDIAN}f4"): ("F", "F", []), +} + + +def _decompression_bomb_check(size: tuple[int, int]) -> None: + if MAX_IMAGE_PIXELS is None: + return + + pixels = max(1, size[0]) * max(1, size[1]) + + if pixels > 2 * MAX_IMAGE_PIXELS: + msg = ( + f"Image size ({pixels} pixels) exceeds limit of {2 * MAX_IMAGE_PIXELS} " + "pixels, could be decompression bomb DOS attack." + ) + raise DecompressionBombError(msg) + + if pixels > MAX_IMAGE_PIXELS: + warnings.warn( + f"Image size ({pixels} pixels) exceeds limit of {MAX_IMAGE_PIXELS} pixels, " + "could be decompression bomb DOS attack.", + DecompressionBombWarning, + ) + + +def open( + fp: StrOrBytesPath | IO[bytes], + mode: Literal["r"] = "r", + formats: list[str] | tuple[str, ...] | None = None, +) -> ImageFile.ImageFile: + """ + Opens and identifies the given image file. + + This is a lazy operation; this function identifies the file, but + the file remains open and the actual image data is not read from + the file until you try to process the data (or call the + :py:meth:`~PIL.Image.Image.load` method). See + :py:func:`~PIL.Image.new`. See :ref:`file-handling`. + + :param fp: A filename (string), os.PathLike object or a file object. + The file object must implement ``file.read``, + ``file.seek``, and ``file.tell`` methods, + and be opened in binary mode. The file object will also seek to zero + before reading. + :param mode: The mode. If given, this argument must be "r". + :param formats: A list or tuple of formats to attempt to load the file in. + This can be used to restrict the set of formats checked. + Pass ``None`` to try all supported formats. You can print the set of + available formats by running ``python3 -m PIL`` or using + the :py:func:`PIL.features.pilinfo` function. + :returns: An :py:class:`~PIL.Image.Image` object. + :exception FileNotFoundError: If the file cannot be found. + :exception PIL.UnidentifiedImageError: If the image cannot be opened and + identified. + :exception ValueError: If the ``mode`` is not "r", or if a ``StringIO`` + instance is used for ``fp``. + :exception TypeError: If ``formats`` is not ``None``, a list or a tuple. + """ + + if mode != "r": + msg = f"bad mode {repr(mode)}" # type: ignore[unreachable] + raise ValueError(msg) + elif isinstance(fp, io.StringIO): + msg = ( # type: ignore[unreachable] + "StringIO cannot be used to open an image. " + "Binary data must be used instead." + ) + raise ValueError(msg) + + if formats is None: + formats = ID + elif not isinstance(formats, (list, tuple)): + msg = "formats must be a list or tuple" # type: ignore[unreachable] + raise TypeError(msg) + + exclusive_fp = False + filename: str | bytes = "" + if is_path(fp): + filename = os.fspath(fp) + fp = builtins.open(filename, "rb") + exclusive_fp = True + else: + fp = cast(IO[bytes], fp) + + try: + fp.seek(0) + except (AttributeError, io.UnsupportedOperation): + fp = io.BytesIO(fp.read()) + exclusive_fp = True + + prefix = fp.read(16) + + # Try to import just the plugin needed for this file extension + # before falling back to preinit() which imports common plugins + ext = os.path.splitext(filename)[1] if filename else "" + if not _import_plugin_for_extension(ext): + preinit() + + warning_messages: list[str] = [] + + def _open_core( + fp: IO[bytes], + filename: str | bytes, + prefix: bytes, + formats: list[str] | tuple[str, ...], + ) -> ImageFile.ImageFile | None: + for i in formats: + i = i.upper() + if i not in OPEN: + init() + try: + factory, accept = OPEN[i] + result = not accept or accept(prefix) + if isinstance(result, str): + warning_messages.append(result) + elif result: + fp.seek(0) + im = factory(fp, filename) + _decompression_bomb_check(im.size) + return im + except (SyntaxError, IndexError, TypeError, struct.error) as e: + if WARN_POSSIBLE_FORMATS: + warning_messages.append(i + " opening failed. " + str(e)) + except BaseException: + if exclusive_fp: + fp.close() + raise + return None + + im = _open_core(fp, filename, prefix, formats) + + if im is None and formats is ID: + # Try preinit (few common plugins) then init (all plugins) + for loader in (preinit, init): + checked_formats = ID.copy() + loader() + if formats != checked_formats: + im = _open_core( + fp, + filename, + prefix, + tuple(f for f in formats if f not in checked_formats), + ) + if im is not None: + break + + if im: + im._exclusive_fp = exclusive_fp + return im + + if exclusive_fp: + fp.close() + for message in warning_messages: + warnings.warn(message) + msg = "cannot identify image file %r" % (filename if filename else fp) + raise UnidentifiedImageError(msg) + + +# +# Image processing. + + +def alpha_composite(im1: Image, im2: Image) -> Image: + """ + Alpha composite im2 over im1. + + :param im1: The first image. Must have mode RGBA or LA. + :param im2: The second image. Must have the same mode and size as the first image. + :returns: An :py:class:`~PIL.Image.Image` object. + """ + + im1.load() + im2.load() + return im1._new(core.alpha_composite(im1.im, im2.im)) + + +def blend(im1: Image, im2: Image, alpha: float) -> Image: + """ + Creates a new image by interpolating between two input images, using + a constant alpha:: + + out = image1 * (1.0 - alpha) + image2 * alpha + + :param im1: The first image. + :param im2: The second image. Must have the same mode and size as + the first image. + :param alpha: The interpolation alpha factor. If alpha is 0.0, a + copy of the first image is returned. If alpha is 1.0, a copy of + the second image is returned. There are no restrictions on the + alpha value. If necessary, the result is clipped to fit into + the allowed output range. + :returns: An :py:class:`~PIL.Image.Image` object. + """ + + im1.load() + im2.load() + return im1._new(core.blend(im1.im, im2.im, alpha)) + + +def composite(image1: Image, image2: Image, mask: Image) -> Image: + """ + Create composite image by blending images using a transparency mask. + + :param image1: The first image. + :param image2: The second image. Must have the same mode and + size as the first image. + :param mask: A mask image. This image can have mode + "1", "L", or "RGBA", and must have the same size as the + other two images. + """ + + image = image2.copy() + image.paste(image1, None, mask) + return image + + +def eval(image: Image, *args: Callable[[int], float]) -> Image: + """ + Applies the function (which should take one argument) to each pixel + in the given image. If the image has more than one band, the same + function is applied to each band. Note that the function is + evaluated once for each possible pixel value, so you cannot use + random components or other generators. + + :param image: The input image. + :param function: A function object, taking one integer argument. + :returns: An :py:class:`~PIL.Image.Image` object. + """ + + return image.point(args[0]) + + +def merge(mode: str, bands: Sequence[Image]) -> Image: + """ + Merge a set of single band images into a new multiband image. + + :param mode: The mode to use for the output image. See: + :ref:`concept-modes`. + :param bands: A sequence containing one single-band image for + each band in the output image. All bands must have the + same size. + :returns: An :py:class:`~PIL.Image.Image` object. + """ + + if getmodebands(mode) != len(bands) or "*" in mode: + msg = "wrong number of bands" + raise ValueError(msg) + for band in bands[1:]: + if band.mode != getmodetype(mode): + msg = "mode mismatch" + raise ValueError(msg) + if band.size != bands[0].size: + msg = "size mismatch" + raise ValueError(msg) + for band in bands: + band.load() + return bands[0]._new(core.merge(mode, *[b.im for b in bands])) + + +# -------------------------------------------------------------------- +# Plugin registry + + +def register_open( + id: str, + factory: ( + Callable[[IO[bytes], str | bytes], ImageFile.ImageFile] + | type[ImageFile.ImageFile] + ), + accept: Callable[[bytes], bool | str] | None = None, +) -> None: + """ + Register an image file plugin. This function should not be used + in application code. + + :param id: An image format identifier. + :param factory: An image file factory method. + :param accept: An optional function that can be used to quickly + reject images having another format. + """ + id = id.upper() + if id not in ID: + ID.append(id) + OPEN[id] = factory, accept + + +def register_mime(id: str, mimetype: str) -> None: + """ + Registers an image MIME type by populating ``Image.MIME``. This function + should not be used in application code. + + ``Image.MIME`` provides a mapping from image format identifiers to mime + formats, but :py:meth:`~PIL.ImageFile.ImageFile.get_format_mimetype` can + provide a different result for specific images. + + :param id: An image format identifier. + :param mimetype: The image MIME type for this format. + """ + MIME[id.upper()] = mimetype + + +def register_save( + id: str, driver: Callable[[Image, IO[bytes], str | bytes], None] +) -> None: + """ + Registers an image save function. This function should not be + used in application code. + + :param id: An image format identifier. + :param driver: A function to save images in this format. + """ + SAVE[id.upper()] = driver + + +def register_save_all( + id: str, driver: Callable[[Image, IO[bytes], str | bytes], None] +) -> None: + """ + Registers an image function to save all the frames + of a multiframe format. This function should not be + used in application code. + + :param id: An image format identifier. + :param driver: A function to save images in this format. + """ + SAVE_ALL[id.upper()] = driver + + +def register_extension(id: str, extension: str) -> None: + """ + Registers an image extension. This function should not be + used in application code. + + :param id: An image format identifier. + :param extension: An extension used for this format. + """ + EXTENSION[extension.lower()] = id.upper() + + +def register_extensions(id: str, extensions: list[str]) -> None: + """ + Registers image extensions. This function should not be + used in application code. + + :param id: An image format identifier. + :param extensions: A list of extensions used for this format. + """ + for extension in extensions: + register_extension(id, extension) + + +def registered_extensions() -> dict[str, str]: + """ + Returns a dictionary containing all file extensions belonging + to registered plugins + """ + init() + return EXTENSION + + +def register_decoder(name: str, decoder: type[ImageFile.PyDecoder]) -> None: + """ + Registers an image decoder. This function should not be + used in application code. + + :param name: The name of the decoder + :param decoder: An ImageFile.PyDecoder object + + .. versionadded:: 4.1.0 + """ + DECODERS[name] = decoder + + +def register_encoder(name: str, encoder: type[ImageFile.PyEncoder]) -> None: + """ + Registers an image encoder. This function should not be + used in application code. + + :param name: The name of the encoder + :param encoder: An ImageFile.PyEncoder object + + .. versionadded:: 4.1.0 + """ + ENCODERS[name] = encoder + + +# -------------------------------------------------------------------- +# Simple display support. + + +def _show(image: Image, **options: Any) -> None: + from . import ImageShow + + deprecate("Image._show", 13, "ImageShow.show") + ImageShow.show(image, **options) + + +# -------------------------------------------------------------------- +# Effects + + +def effect_mandelbrot( + size: tuple[int, int], extent: tuple[float, float, float, float], quality: int +) -> Image: + """ + Generate a Mandelbrot set covering the given extent. + + :param size: The requested size in pixels, as a 2-tuple: + (width, height). + :param extent: The extent to cover, as a 4-tuple: + (x0, y0, x1, y1). + :param quality: Quality. + """ + return Image()._new(core.effect_mandelbrot(size, extent, quality)) + + +def effect_noise(size: tuple[int, int], sigma: float) -> Image: + """ + Generate Gaussian noise centered around 128. + + :param size: The requested size in pixels, as a 2-tuple: + (width, height). + :param sigma: Standard deviation of noise. + """ + return Image()._new(core.effect_noise(size, sigma)) + + +def linear_gradient(mode: str) -> Image: + """ + Generate 256x256 linear gradient from black to white, top to bottom. + + :param mode: Input mode. + """ + return Image()._new(core.linear_gradient(mode)) + + +def radial_gradient(mode: str) -> Image: + """ + Generate 256x256 radial gradient from black to white, centre to edge. + + :param mode: Input mode. + """ + return Image()._new(core.radial_gradient(mode)) + + +# -------------------------------------------------------------------- +# Resources + + +def _apply_env_variables(env: dict[str, str] | None = None) -> None: + env_dict = env if env is not None else os.environ + + for var_name, setter in [ + ("PILLOW_ALIGNMENT", core.set_alignment), + ("PILLOW_BLOCK_SIZE", core.set_block_size), + ("PILLOW_BLOCKS_MAX", core.set_blocks_max), + ]: + if var_name not in env_dict: + continue + + var = env_dict[var_name].lower() + + units = 1 + for postfix, mul in [("k", 1024), ("m", 1024 * 1024)]: + if var.endswith(postfix): + units = mul + var = var[: -len(postfix)] + + try: + var_int = int(var) * units + except ValueError: + warnings.warn(f"{var_name} is not int") + continue + + try: + setter(var_int) + except ValueError as e: + warnings.warn(f"{var_name}: {e}") + + +_apply_env_variables() +atexit.register(core.clear_cache) + + +if TYPE_CHECKING: + _ExifBase = MutableMapping[int, Any] +else: + _ExifBase = MutableMapping + + +class Exif(_ExifBase): + """ + This class provides read and write access to EXIF image data:: + + from PIL import Image + im = Image.open("exif.png") + exif = im.getexif() # Returns an instance of this class + + Information can be read and written, iterated over or deleted:: + + print(exif[274]) # 1 + exif[274] = 2 + for k, v in exif.items(): + print("Tag", k, "Value", v) # Tag 274 Value 2 + del exif[274] + + To access information beyond IFD0, :py:meth:`~PIL.Image.Exif.get_ifd` + returns a dictionary:: + + from PIL import ExifTags + im = Image.open("exif_gps.jpg") + exif = im.getexif() + gps_ifd = exif.get_ifd(ExifTags.IFD.GPSInfo) + print(gps_ifd) + + Other IFDs include ``ExifTags.IFD.Exif``, ``ExifTags.IFD.MakerNote``, + ``ExifTags.IFD.Interop`` and ``ExifTags.IFD.IFD1``. + + :py:mod:`~PIL.ExifTags` also has enum classes to provide names for data:: + + print(exif[ExifTags.Base.Software]) # PIL + print(gps_ifd[ExifTags.GPS.GPSDateStamp]) # 1999:99:99 99:99:99 + """ + + endian: str | None = None + bigtiff = False + _loaded = False + + def __init__(self) -> None: + self._data: dict[int, Any] = {} + self._hidden_data: dict[int, Any] = {} + self._ifds: dict[int, dict[int, Any]] = {} + self._info: TiffImagePlugin.ImageFileDirectory_v2 | None = None + self._loaded_exif: bytes | None = None + + def _fixup(self, value: Any) -> Any: + try: + if len(value) == 1 and isinstance(value, tuple): + return value[0] + except Exception: + pass + return value + + def _fixup_dict(self, src_dict: dict[int, Any]) -> dict[int, Any]: + # Helper function + # returns a dict with any single item tuples/lists as individual values + return {k: self._fixup(v) for k, v in src_dict.items()} + + def _get_ifd_dict( + self, offset: int, group: int | None = None + ) -> dict[int, Any] | None: + try: + # an offset pointer to the location of the nested embedded IFD. + # It should be a long, but may be corrupted. + self.fp.seek(offset) + except (KeyError, TypeError): + return None + else: + from . import TiffImagePlugin + + info = TiffImagePlugin.ImageFileDirectory_v2(self.head, group=group) + info.load(self.fp) + return self._fixup_dict(dict(info)) + + def _get_head(self) -> bytes: + version = b"\x2b" if self.bigtiff else b"\x2a" + if self.endian == "<": + head = b"II" + version + b"\x00" + o32le(8) + else: + head = b"MM\x00" + version + o32be(8) + if self.bigtiff: + head += o32le(8) if self.endian == "<" else o32be(8) + head += b"\x00\x00\x00\x00" + return head + + def load(self, data: bytes) -> None: + # Extract EXIF information. This is highly experimental, + # and is likely to be replaced with something better in a future + # version. + + # The EXIF record consists of a TIFF file embedded in a JPEG + # application marker (!). + if data == self._loaded_exif: + return + self._loaded_exif = data + self._data.clear() + self._hidden_data.clear() + self._ifds.clear() + while data and data.startswith(b"Exif\x00\x00"): + data = data[6:] + if not data: + self._info = None + return + + self.fp: IO[bytes] = io.BytesIO(data) + self.head = self.fp.read(8) + # process dictionary + from . import TiffImagePlugin + + self._info = TiffImagePlugin.ImageFileDirectory_v2(self.head) + self.endian = self._info._endian + self.fp.seek(self._info.next) + self._info.load(self.fp) + + def load_from_fp(self, fp: IO[bytes], offset: int | None = None) -> None: + self._loaded_exif = None + self._data.clear() + self._hidden_data.clear() + self._ifds.clear() + + # process dictionary + from . import TiffImagePlugin + + self.fp = fp + if offset is not None: + self.head = self._get_head() + else: + self.head = self.fp.read(8) + self._info = TiffImagePlugin.ImageFileDirectory_v2(self.head) + if self.endian is None: + self.endian = self._info._endian + if offset is None: + offset = self._info.next + self.fp.tell() + self.fp.seek(offset) + self._info.load(self.fp) + + def _get_merged_dict(self) -> dict[int, Any]: + merged_dict = dict(self) + + # get EXIF extension + if ExifTags.IFD.Exif in self: + ifd = self._get_ifd_dict(self[ExifTags.IFD.Exif], ExifTags.IFD.Exif) + if ifd: + merged_dict.update(ifd) + + # GPS + if ExifTags.IFD.GPSInfo in self: + merged_dict[ExifTags.IFD.GPSInfo] = self._get_ifd_dict( + self[ExifTags.IFD.GPSInfo], ExifTags.IFD.GPSInfo + ) + + return merged_dict + + def tobytes(self, offset: int = 8) -> bytes: + from . import TiffImagePlugin + + head = self._get_head() + ifd = TiffImagePlugin.ImageFileDirectory_v2(ifh=head) + for tag, ifd_dict in self._ifds.items(): + if tag not in self: + ifd[tag] = ifd_dict + for tag, value in self.items(): + if tag in [ + ExifTags.IFD.Exif, + ExifTags.IFD.GPSInfo, + ] and not isinstance(value, dict): + value = self.get_ifd(tag) + if ( + tag == ExifTags.IFD.Exif + and ExifTags.IFD.Interop in value + and not isinstance(value[ExifTags.IFD.Interop], dict) + ): + value = value.copy() + value[ExifTags.IFD.Interop] = self.get_ifd(ExifTags.IFD.Interop) + ifd[tag] = value + return b"Exif\x00\x00" + head + ifd.tobytes(offset) + + def get_ifd(self, tag: int) -> dict[int, Any]: + if tag not in self._ifds: + if tag == ExifTags.IFD.IFD1: + if self._info is not None and self._info.next != 0: + ifd = self._get_ifd_dict(self._info.next) + if ifd is not None: + self._ifds[tag] = ifd + elif tag in [ExifTags.IFD.Exif, ExifTags.IFD.GPSInfo]: + offset = self._hidden_data.get(tag, self.get(tag)) + if offset is not None: + ifd = self._get_ifd_dict(offset, tag) + if ifd is not None: + self._ifds[tag] = ifd + elif tag in [ExifTags.IFD.Interop, ExifTags.IFD.MakerNote]: + if ExifTags.IFD.Exif not in self._ifds: + self.get_ifd(ExifTags.IFD.Exif) + tag_data = self._ifds[ExifTags.IFD.Exif][tag] + if tag == ExifTags.IFD.MakerNote: + from .TiffImagePlugin import ImageFileDirectory_v2 + + try: + if tag_data.startswith(b"FUJIFILM"): + ifd_offset = i32le(tag_data, 8) + ifd_data = tag_data[ifd_offset:] + + makernote = {} + for i in range(struct.unpack(" 4: + (offset,) = struct.unpack("H", tag_data[:2])[0]): + ifd_tag, typ, count, data = struct.unpack( + ">HHL4s", tag_data[i * 12 + 2 : (i + 1) * 12 + 2] + ) + if ifd_tag == 0x1101: + # CameraInfo + (offset,) = struct.unpack(">L", data) + self.fp.seek(offset) + + camerainfo: dict[str, int | bytes] = { + "ModelID": self.fp.read(4) + } + + self.fp.read(4) + # Seconds since 2000 + camerainfo["TimeStamp"] = i32le(self.fp.read(12)) + + self.fp.read(4) + camerainfo["InternalSerialNumber"] = self.fp.read(4) + + self.fp.read(12) + parallax = self.fp.read(4) + handler = ImageFileDirectory_v2._load_dispatch[ + TiffTags.FLOAT + ][1] + camerainfo["Parallax"] = handler( + ImageFileDirectory_v2(), parallax, False + )[0] + + self.fp.read(4) + camerainfo["Category"] = self.fp.read(2) + + makernote = {0x1101: camerainfo} + self._ifds[tag] = makernote + except struct.error: + pass + else: + # Interop + ifd = self._get_ifd_dict(tag_data, tag) + if ifd is not None: + self._ifds[tag] = ifd + ifd = self._ifds.setdefault(tag, {}) + if tag == ExifTags.IFD.Exif and self._hidden_data: + ifd = { + k: v + for (k, v) in ifd.items() + if k not in (ExifTags.IFD.Interop, ExifTags.IFD.MakerNote) + } + return ifd + + def hide_offsets(self) -> None: + for tag in (ExifTags.IFD.Exif, ExifTags.IFD.GPSInfo): + if tag in self: + self._hidden_data[tag] = self[tag] + del self[tag] + + def __str__(self) -> str: + if self._info is not None: + # Load all keys into self._data + for tag in self._info: + self[tag] + + return str(self._data) + + def __len__(self) -> int: + keys = set(self._data) + if self._info is not None: + keys.update(self._info) + return len(keys) + + def __getitem__(self, tag: int) -> Any: + if self._info is not None and tag not in self._data and tag in self._info: + self._data[tag] = self._fixup(self._info[tag]) + del self._info[tag] + return self._data[tag] + + def __contains__(self, tag: object) -> bool: + return tag in self._data or (self._info is not None and tag in self._info) + + def __setitem__(self, tag: int, value: Any) -> None: + if self._info is not None and tag in self._info: + del self._info[tag] + self._data[tag] = value + + def __delitem__(self, tag: int) -> None: + if self._info is not None and tag in self._info: + del self._info[tag] + else: + del self._data[tag] + if tag in self._ifds: + del self._ifds[tag] + + def __iter__(self) -> Iterator[int]: + keys = set(self._data) + if self._info is not None: + keys.update(self._info) + return iter(keys) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/ImageChops.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/ImageChops.py new file mode 100644 index 000000000..29a5c995f --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/ImageChops.py @@ -0,0 +1,311 @@ +# +# The Python Imaging Library. +# $Id$ +# +# standard channel operations +# +# History: +# 1996-03-24 fl Created +# 1996-08-13 fl Added logical operations (for "1" images) +# 2000-10-12 fl Added offset method (from Image.py) +# +# Copyright (c) 1997-2000 by Secret Labs AB +# Copyright (c) 1996-2000 by Fredrik Lundh +# +# See the README file for information on usage and redistribution. +# + +from __future__ import annotations + +from . import Image + + +def constant(image: Image.Image, value: int) -> Image.Image: + """Fill a channel with a given gray level. + + :rtype: :py:class:`~PIL.Image.Image` + """ + + return Image.new("L", image.size, value) + + +def duplicate(image: Image.Image) -> Image.Image: + """Copy a channel. Alias for :py:meth:`PIL.Image.Image.copy`. + + :rtype: :py:class:`~PIL.Image.Image` + """ + + return image.copy() + + +def invert(image: Image.Image) -> Image.Image: + """ + Invert an image (channel). :: + + out = MAX - image + + :rtype: :py:class:`~PIL.Image.Image` + """ + + image.load() + return image._new(image.im.chop_invert()) + + +def lighter(image1: Image.Image, image2: Image.Image) -> Image.Image: + """ + Compares the two images, pixel by pixel, and returns a new image containing + the lighter values. :: + + out = max(image1, image2) + + :rtype: :py:class:`~PIL.Image.Image` + """ + + image1.load() + image2.load() + return image1._new(image1.im.chop_lighter(image2.im)) + + +def darker(image1: Image.Image, image2: Image.Image) -> Image.Image: + """ + Compares the two images, pixel by pixel, and returns a new image containing + the darker values. :: + + out = min(image1, image2) + + :rtype: :py:class:`~PIL.Image.Image` + """ + + image1.load() + image2.load() + return image1._new(image1.im.chop_darker(image2.im)) + + +def difference(image1: Image.Image, image2: Image.Image) -> Image.Image: + """ + Returns the absolute value of the pixel-by-pixel difference between the two + images. :: + + out = abs(image1 - image2) + + :rtype: :py:class:`~PIL.Image.Image` + """ + + image1.load() + image2.load() + return image1._new(image1.im.chop_difference(image2.im)) + + +def multiply(image1: Image.Image, image2: Image.Image) -> Image.Image: + """ + Superimposes two images on top of each other. + + If you multiply an image with a solid black image, the result is black. If + you multiply with a solid white image, the image is unaffected. :: + + out = image1 * image2 / MAX + + :rtype: :py:class:`~PIL.Image.Image` + """ + + image1.load() + image2.load() + return image1._new(image1.im.chop_multiply(image2.im)) + + +def screen(image1: Image.Image, image2: Image.Image) -> Image.Image: + """ + Superimposes two inverted images on top of each other. :: + + out = MAX - ((MAX - image1) * (MAX - image2) / MAX) + + :rtype: :py:class:`~PIL.Image.Image` + """ + + image1.load() + image2.load() + return image1._new(image1.im.chop_screen(image2.im)) + + +def soft_light(image1: Image.Image, image2: Image.Image) -> Image.Image: + """ + Superimposes two images on top of each other using the Soft Light algorithm + + :rtype: :py:class:`~PIL.Image.Image` + """ + + image1.load() + image2.load() + return image1._new(image1.im.chop_soft_light(image2.im)) + + +def hard_light(image1: Image.Image, image2: Image.Image) -> Image.Image: + """ + Superimposes two images on top of each other using the Hard Light algorithm + + :rtype: :py:class:`~PIL.Image.Image` + """ + + image1.load() + image2.load() + return image1._new(image1.im.chop_hard_light(image2.im)) + + +def overlay(image1: Image.Image, image2: Image.Image) -> Image.Image: + """ + Superimposes two images on top of each other using the Overlay algorithm + + :rtype: :py:class:`~PIL.Image.Image` + """ + + image1.load() + image2.load() + return image1._new(image1.im.chop_overlay(image2.im)) + + +def add( + image1: Image.Image, image2: Image.Image, scale: float = 1.0, offset: float = 0 +) -> Image.Image: + """ + Adds two images, dividing the result by scale and adding the + offset. If omitted, scale defaults to 1.0, and offset to 0.0. :: + + out = ((image1 + image2) / scale + offset) + + :rtype: :py:class:`~PIL.Image.Image` + """ + + image1.load() + image2.load() + return image1._new(image1.im.chop_add(image2.im, scale, offset)) + + +def subtract( + image1: Image.Image, image2: Image.Image, scale: float = 1.0, offset: float = 0 +) -> Image.Image: + """ + Subtracts two images, dividing the result by scale and adding the offset. + If omitted, scale defaults to 1.0, and offset to 0.0. :: + + out = ((image1 - image2) / scale + offset) + + :rtype: :py:class:`~PIL.Image.Image` + """ + + image1.load() + image2.load() + return image1._new(image1.im.chop_subtract(image2.im, scale, offset)) + + +def add_modulo(image1: Image.Image, image2: Image.Image) -> Image.Image: + """Add two images, without clipping the result. :: + + out = ((image1 + image2) % MAX) + + :rtype: :py:class:`~PIL.Image.Image` + """ + + image1.load() + image2.load() + return image1._new(image1.im.chop_add_modulo(image2.im)) + + +def subtract_modulo(image1: Image.Image, image2: Image.Image) -> Image.Image: + """Subtract two images, without clipping the result. :: + + out = ((image1 - image2) % MAX) + + :rtype: :py:class:`~PIL.Image.Image` + """ + + image1.load() + image2.load() + return image1._new(image1.im.chop_subtract_modulo(image2.im)) + + +def logical_and(image1: Image.Image, image2: Image.Image) -> Image.Image: + """Logical AND between two images. + + Both of the images must have mode "1". If you would like to perform a + logical AND on an image with a mode other than "1", try + :py:meth:`~PIL.ImageChops.multiply` instead, using a black-and-white mask + as the second image. :: + + out = ((image1 and image2) % MAX) + + :rtype: :py:class:`~PIL.Image.Image` + """ + + image1.load() + image2.load() + return image1._new(image1.im.chop_and(image2.im)) + + +def logical_or(image1: Image.Image, image2: Image.Image) -> Image.Image: + """Logical OR between two images. + + Both of the images must have mode "1". :: + + out = ((image1 or image2) % MAX) + + :rtype: :py:class:`~PIL.Image.Image` + """ + + image1.load() + image2.load() + return image1._new(image1.im.chop_or(image2.im)) + + +def logical_xor(image1: Image.Image, image2: Image.Image) -> Image.Image: + """Logical XOR between two images. + + Both of the images must have mode "1". :: + + out = ((bool(image1) != bool(image2)) % MAX) + + :rtype: :py:class:`~PIL.Image.Image` + """ + + image1.load() + image2.load() + return image1._new(image1.im.chop_xor(image2.im)) + + +def blend(image1: Image.Image, image2: Image.Image, alpha: float) -> Image.Image: + """Blend images using constant transparency weight. Alias for + :py:func:`PIL.Image.blend`. + + :rtype: :py:class:`~PIL.Image.Image` + """ + + return Image.blend(image1, image2, alpha) + + +def composite( + image1: Image.Image, image2: Image.Image, mask: Image.Image +) -> Image.Image: + """Create composite using transparency mask. Alias for + :py:func:`PIL.Image.composite`. + + :rtype: :py:class:`~PIL.Image.Image` + """ + + return Image.composite(image1, image2, mask) + + +def offset(image: Image.Image, xoffset: int, yoffset: int | None = None) -> Image.Image: + """Returns a copy of the image where data has been offset by the given + distances. Data wraps around the edges. If ``yoffset`` is omitted, it + is assumed to be equal to ``xoffset``. + + :param image: Input image. + :param xoffset: The horizontal distance. + :param yoffset: The vertical distance. If omitted, both + distances are set to the same value. + :rtype: :py:class:`~PIL.Image.Image` + """ + + if yoffset is None: + yoffset = xoffset + image.load() + return image._new(image.im.offset(xoffset, yoffset)) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/ImageCms.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/ImageCms.py new file mode 100644 index 000000000..513e28acf --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/ImageCms.py @@ -0,0 +1,1076 @@ +# The Python Imaging Library. +# $Id$ + +# Optional color management support, based on Kevin Cazabon's PyCMS +# library. + +# Originally released under LGPL. Graciously donated to PIL in +# March 2009, for distribution under the standard PIL license + +# History: + +# 2009-03-08 fl Added to PIL. + +# Copyright (C) 2002-2003 Kevin Cazabon +# Copyright (c) 2009 by Fredrik Lundh +# Copyright (c) 2013 by Eric Soroos + +# See the README file for information on usage and redistribution. See +# below for the original description. +from __future__ import annotations + +import operator +import sys +from enum import IntEnum, IntFlag +from functools import reduce +from typing import Any, Literal, SupportsFloat, SupportsInt, Union + +from . import Image +from ._deprecate import deprecate +from ._typing import SupportsRead + +try: + from . import _imagingcms as core + + _CmsProfileCompatible = Union[ + str, SupportsRead[bytes], core.CmsProfile, "ImageCmsProfile" + ] +except ImportError as ex: + # Allow error import for doc purposes, but error out when accessing + # anything in core. + from ._util import DeferredError + + core = DeferredError.new(ex) + +_DESCRIPTION = """ +pyCMS + + a Python / PIL interface to the littleCMS ICC Color Management System + Copyright (C) 2002-2003 Kevin Cazabon + kevin@cazabon.com + https://www.cazabon.com + + pyCMS home page: https://www.cazabon.com/pyCMS + littleCMS home page: https://www.littlecms.com + (littleCMS is Copyright (C) 1998-2001 Marti Maria) + + Originally released under LGPL. Graciously donated to PIL in + March 2009, for distribution under the standard PIL license + + The pyCMS.py module provides a "clean" interface between Python/PIL and + pyCMSdll, taking care of some of the more complex handling of the direct + pyCMSdll functions, as well as error-checking and making sure that all + relevant data is kept together. + + While it is possible to call pyCMSdll functions directly, it's not highly + recommended. + + Version History: + + 1.0.0 pil Oct 2013 Port to LCMS 2. + + 0.1.0 pil mod March 10, 2009 + + Renamed display profile to proof profile. The proof + profile is the profile of the device that is being + simulated, not the profile of the device which is + actually used to display/print the final simulation + (that'd be the output profile) - also see LCMSAPI.txt + input colorspace -> using 'renderingIntent' -> proof + colorspace -> using 'proofRenderingIntent' -> output + colorspace + + Added LCMS FLAGS support. + Added FLAGS["SOFTPROOFING"] as default flag for + buildProofTransform (otherwise the proof profile/intent + would be ignored). + + 0.1.0 pil March 2009 - added to PIL, as PIL.ImageCms + + 0.0.2 alpha Jan 6, 2002 + + Added try/except statements around type() checks of + potential CObjects... Python won't let you use type() + on them, and raises a TypeError (stupid, if you ask + me!) + + Added buildProofTransformFromOpenProfiles() function. + Additional fixes in DLL, see DLL code for details. + + 0.0.1 alpha first public release, Dec. 26, 2002 + + Known to-do list with current version (of Python interface, not pyCMSdll): + + none + +""" + +_VERSION = "1.0.0 pil" + + +# --------------------------------------------------------------------. + + +# +# intent/direction values + + +class Intent(IntEnum): + PERCEPTUAL = 0 + RELATIVE_COLORIMETRIC = 1 + SATURATION = 2 + ABSOLUTE_COLORIMETRIC = 3 + + +class Direction(IntEnum): + INPUT = 0 + OUTPUT = 1 + PROOF = 2 + + +# +# flags + + +class Flags(IntFlag): + """Flags and documentation are taken from ``lcms2.h``.""" + + NONE = 0 + NOCACHE = 0x0040 + """Inhibit 1-pixel cache""" + NOOPTIMIZE = 0x0100 + """Inhibit optimizations""" + NULLTRANSFORM = 0x0200 + """Don't transform anyway""" + GAMUTCHECK = 0x1000 + """Out of Gamut alarm""" + SOFTPROOFING = 0x4000 + """Do softproofing""" + BLACKPOINTCOMPENSATION = 0x2000 + NOWHITEONWHITEFIXUP = 0x0004 + """Don't fix scum dot""" + HIGHRESPRECALC = 0x0400 + """Use more memory to give better accuracy""" + LOWRESPRECALC = 0x0800 + """Use less memory to minimize resources""" + # this should be 8BITS_DEVICELINK, but that is not a valid name in Python: + USE_8BITS_DEVICELINK = 0x0008 + """Create 8 bits devicelinks""" + GUESSDEVICECLASS = 0x0020 + """Guess device class (for ``transform2devicelink``)""" + KEEP_SEQUENCE = 0x0080 + """Keep profile sequence for devicelink creation""" + FORCE_CLUT = 0x0002 + """Force CLUT optimization""" + CLUT_POST_LINEARIZATION = 0x0001 + """create postlinearization tables if possible""" + CLUT_PRE_LINEARIZATION = 0x0010 + """create prelinearization tables if possible""" + NONEGATIVES = 0x8000 + """Prevent negative numbers in floating point transforms""" + COPY_ALPHA = 0x04000000 + """Alpha channels are copied on ``cmsDoTransform()``""" + NODEFAULTRESOURCEDEF = 0x01000000 + + _GRIDPOINTS_1 = 1 << 16 + _GRIDPOINTS_2 = 2 << 16 + _GRIDPOINTS_4 = 4 << 16 + _GRIDPOINTS_8 = 8 << 16 + _GRIDPOINTS_16 = 16 << 16 + _GRIDPOINTS_32 = 32 << 16 + _GRIDPOINTS_64 = 64 << 16 + _GRIDPOINTS_128 = 128 << 16 + + @staticmethod + def GRIDPOINTS(n: int) -> Flags: + """ + Fine-tune control over number of gridpoints + + :param n: :py:class:`int` in range ``0 <= n <= 255`` + """ + return Flags.NONE | ((n & 0xFF) << 16) + + +_MAX_FLAG = reduce(operator.or_, Flags) + + +_FLAGS = { + "MATRIXINPUT": 1, + "MATRIXOUTPUT": 2, + "MATRIXONLY": (1 | 2), + "NOWHITEONWHITEFIXUP": 4, # Don't hot fix scum dot + # Don't create prelinearization tables on precalculated transforms + # (internal use): + "NOPRELINEARIZATION": 16, + "GUESSDEVICECLASS": 32, # Guess device class (for transform2devicelink) + "NOTCACHE": 64, # Inhibit 1-pixel cache + "NOTPRECALC": 256, + "NULLTRANSFORM": 512, # Don't transform anyway + "HIGHRESPRECALC": 1024, # Use more memory to give better accuracy + "LOWRESPRECALC": 2048, # Use less memory to minimize resources + "WHITEBLACKCOMPENSATION": 8192, + "BLACKPOINTCOMPENSATION": 8192, + "GAMUTCHECK": 4096, # Out of Gamut alarm + "SOFTPROOFING": 16384, # Do softproofing + "PRESERVEBLACK": 32768, # Black preservation + "NODEFAULTRESOURCEDEF": 16777216, # CRD special + "GRIDPOINTS": lambda n: (n & 0xFF) << 16, # Gridpoints +} + + +# --------------------------------------------------------------------. +# Experimental PIL-level API +# --------------------------------------------------------------------. + +## +# Profile. + + +class ImageCmsProfile: + def __init__(self, profile: str | SupportsRead[bytes] | core.CmsProfile) -> None: + """ + :param profile: Either a string representing a filename, + a file like object containing a profile or a + low-level profile object + + """ + self.filename: str | None = None + + if isinstance(profile, str): + if sys.platform == "win32": + profile_bytes_path = profile.encode() + try: + profile_bytes_path.decode("ascii") + except UnicodeDecodeError: + with open(profile, "rb") as f: + self.profile = core.profile_frombytes(f.read()) + return + self.filename = profile + self.profile = core.profile_open(profile) + elif hasattr(profile, "read"): + self.profile = core.profile_frombytes(profile.read()) + elif isinstance(profile, core.CmsProfile): + self.profile = profile + else: + msg = "Invalid type for Profile" # type: ignore[unreachable] + raise TypeError(msg) + + def __getattr__(self, name: str) -> Any: + if name in ("product_name", "product_info"): + deprecate(f"ImageCms.ImageCmsProfile.{name}", 13) + return None + msg = f"'{self.__class__.__name__}' object has no attribute '{name}'" + raise AttributeError(msg) + + def tobytes(self) -> bytes: + """ + Returns the profile in a format suitable for embedding in + saved images. + + :returns: a bytes object containing the ICC profile. + """ + + return core.profile_tobytes(self.profile) + + +class ImageCmsTransform(Image.ImagePointHandler): + """ + Transform. This can be used with the procedural API, or with the standard + :py:func:`~PIL.Image.Image.point` method. + + Will return the output profile in the ``output.info['icc_profile']``. + """ + + def __init__( + self, + input: ImageCmsProfile, + output: ImageCmsProfile, + input_mode: str, + output_mode: str, + intent: Intent = Intent.PERCEPTUAL, + proof: ImageCmsProfile | None = None, + proof_intent: Intent = Intent.ABSOLUTE_COLORIMETRIC, + flags: Flags = Flags.NONE, + ): + if proof is None: + self.transform = core.buildTransform( + input.profile, output.profile, input_mode, output_mode, intent, flags + ) + else: + self.transform = core.buildProofTransform( + input.profile, + output.profile, + proof.profile, + input_mode, + output_mode, + intent, + proof_intent, + flags, + ) + # Note: inputMode and outputMode are for pyCMS compatibility only + self.input_mode = self.inputMode = input_mode + self.output_mode = self.outputMode = output_mode + + self.output_profile = output + + def point(self, im: Image.Image) -> Image.Image: + return self.apply(im) + + def apply(self, im: Image.Image, imOut: Image.Image | None = None) -> Image.Image: + if imOut is None: + imOut = Image.new(self.output_mode, im.size, None) + self.transform.apply(im.getim(), imOut.getim()) + imOut.info["icc_profile"] = self.output_profile.tobytes() + return imOut + + def apply_in_place(self, im: Image.Image) -> Image.Image: + if im.mode != self.output_mode: + msg = "mode mismatch" + raise ValueError(msg) # wrong output mode + self.transform.apply(im.getim(), im.getim()) + im.info["icc_profile"] = self.output_profile.tobytes() + return im + + +def get_display_profile(handle: SupportsInt | None = None) -> ImageCmsProfile | None: + """ + (experimental) Fetches the profile for the current display device. + + :returns: ``None`` if the profile is not known. + """ + + if sys.platform != "win32": + return None + + from . import ImageWin # type: ignore[unused-ignore, unreachable] + + if isinstance(handle, ImageWin.HDC): + profile = core.get_display_profile_win32(int(handle), 1) + else: + profile = core.get_display_profile_win32(int(handle or 0)) + if profile is None: + return None + return ImageCmsProfile(profile) + + +# --------------------------------------------------------------------. +# pyCMS compatible layer +# --------------------------------------------------------------------. + + +class PyCMSError(Exception): + """(pyCMS) Exception class. + This is used for all errors in the pyCMS API.""" + + pass + + +def profileToProfile( + im: Image.Image, + inputProfile: _CmsProfileCompatible, + outputProfile: _CmsProfileCompatible, + renderingIntent: Intent = Intent.PERCEPTUAL, + outputMode: str | None = None, + inPlace: bool = False, + flags: Flags = Flags.NONE, +) -> Image.Image | None: + """ + (pyCMS) Applies an ICC transformation to a given image, mapping from + ``inputProfile`` to ``outputProfile``. + + If the input or output profiles specified are not valid filenames, a + :exc:`PyCMSError` will be raised. If ``inPlace`` is ``True`` and + ``outputMode != im.mode``, a :exc:`PyCMSError` will be raised. + If an error occurs during application of the profiles, + a :exc:`PyCMSError` will be raised. + If ``outputMode`` is not a mode supported by the ``outputProfile`` (or by pyCMS), + a :exc:`PyCMSError` will be raised. + + This function applies an ICC transformation to im from ``inputProfile``'s + color space to ``outputProfile``'s color space using the specified rendering + intent to decide how to handle out-of-gamut colors. + + ``outputMode`` can be used to specify that a color mode conversion is to + be done using these profiles, but the specified profiles must be able + to handle that mode. I.e., if converting im from RGB to CMYK using + profiles, the input profile must handle RGB data, and the output + profile must handle CMYK data. + + :param im: An open :py:class:`~PIL.Image.Image` object (i.e. Image.new(...) + or Image.open(...), etc.) + :param inputProfile: String, as a valid filename path to the ICC input + profile you wish to use for this image, or a profile object + :param outputProfile: String, as a valid filename path to the ICC output + profile you wish to use for this image, or a profile object + :param renderingIntent: Integer (0-3) specifying the rendering intent you + wish to use for the transform + + ImageCms.Intent.PERCEPTUAL = 0 (DEFAULT) + ImageCms.Intent.RELATIVE_COLORIMETRIC = 1 + ImageCms.Intent.SATURATION = 2 + ImageCms.Intent.ABSOLUTE_COLORIMETRIC = 3 + + see the pyCMS documentation for details on rendering intents and what + they do. + :param outputMode: A valid PIL mode for the output image (i.e. "RGB", + "CMYK", etc.). Note: if rendering the image "inPlace", outputMode + MUST be the same mode as the input, or omitted completely. If + omitted, the outputMode will be the same as the mode of the input + image (im.mode) + :param inPlace: Boolean. If ``True``, the original image is modified in-place, + and ``None`` is returned. If ``False`` (default), a new + :py:class:`~PIL.Image.Image` object is returned with the transform applied. + :param flags: Integer (0-...) specifying additional flags + :returns: Either None or a new :py:class:`~PIL.Image.Image` object, depending on + the value of ``inPlace`` + :exception PyCMSError: + """ + + if outputMode is None: + outputMode = im.mode + + if not isinstance(renderingIntent, int) or not (0 <= renderingIntent <= 3): + msg = "renderingIntent must be an integer between 0 and 3" + raise PyCMSError(msg) + + if not isinstance(flags, int) or not (0 <= flags <= _MAX_FLAG): + msg = f"flags must be an integer between 0 and {_MAX_FLAG}" + raise PyCMSError(msg) + + try: + if not isinstance(inputProfile, ImageCmsProfile): + inputProfile = ImageCmsProfile(inputProfile) + if not isinstance(outputProfile, ImageCmsProfile): + outputProfile = ImageCmsProfile(outputProfile) + transform = ImageCmsTransform( + inputProfile, + outputProfile, + im.mode, + outputMode, + renderingIntent, + flags=flags, + ) + if inPlace: + transform.apply_in_place(im) + imOut = None + else: + imOut = transform.apply(im) + except (OSError, TypeError, ValueError) as v: + raise PyCMSError(v) from v + + return imOut + + +def getOpenProfile( + profileFilename: str | SupportsRead[bytes] | core.CmsProfile, +) -> ImageCmsProfile: + """ + (pyCMS) Opens an ICC profile file. + + The PyCMSProfile object can be passed back into pyCMS for use in creating + transforms and such (as in ImageCms.buildTransformFromOpenProfiles()). + + If ``profileFilename`` is not a valid filename for an ICC profile, + a :exc:`PyCMSError` will be raised. + + :param profileFilename: String, as a valid filename path to the ICC profile + you wish to open, or a file-like object. + :returns: A CmsProfile class object. + :exception PyCMSError: + """ + + try: + return ImageCmsProfile(profileFilename) + except (OSError, TypeError, ValueError) as v: + raise PyCMSError(v) from v + + +def buildTransform( + inputProfile: _CmsProfileCompatible, + outputProfile: _CmsProfileCompatible, + inMode: str, + outMode: str, + renderingIntent: Intent = Intent.PERCEPTUAL, + flags: Flags = Flags.NONE, +) -> ImageCmsTransform: + """ + (pyCMS) Builds an ICC transform mapping from the ``inputProfile`` to the + ``outputProfile``. Use applyTransform to apply the transform to a given + image. + + If the input or output profiles specified are not valid filenames, a + :exc:`PyCMSError` will be raised. If an error occurs during creation + of the transform, a :exc:`PyCMSError` will be raised. + + If ``inMode`` or ``outMode`` are not a mode supported by the ``outputProfile`` + (or by pyCMS), a :exc:`PyCMSError` will be raised. + + This function builds and returns an ICC transform from the ``inputProfile`` + to the ``outputProfile`` using the ``renderingIntent`` to determine what to do + with out-of-gamut colors. It will ONLY work for converting images that + are in ``inMode`` to images that are in ``outMode`` color format (PIL mode, + i.e. "RGB", "RGBA", "CMYK", etc.). + + Building the transform is a fair part of the overhead in + ImageCms.profileToProfile(), so if you're planning on converting multiple + images using the same input/output settings, this can save you time. + Once you have a transform object, it can be used with + ImageCms.applyProfile() to convert images without the need to re-compute + the lookup table for the transform. + + The reason pyCMS returns a class object rather than a handle directly + to the transform is that it needs to keep track of the PIL input/output + modes that the transform is meant for. These attributes are stored in + the ``inMode`` and ``outMode`` attributes of the object (which can be + manually overridden if you really want to, but I don't know of any + time that would be of use, or would even work). + + :param inputProfile: String, as a valid filename path to the ICC input + profile you wish to use for this transform, or a profile object + :param outputProfile: String, as a valid filename path to the ICC output + profile you wish to use for this transform, or a profile object + :param inMode: String, as a valid PIL mode that the appropriate profile + also supports (i.e. "RGB", "RGBA", "CMYK", etc.) + :param outMode: String, as a valid PIL mode that the appropriate profile + also supports (i.e. "RGB", "RGBA", "CMYK", etc.) + :param renderingIntent: Integer (0-3) specifying the rendering intent you + wish to use for the transform + + ImageCms.Intent.PERCEPTUAL = 0 (DEFAULT) + ImageCms.Intent.RELATIVE_COLORIMETRIC = 1 + ImageCms.Intent.SATURATION = 2 + ImageCms.Intent.ABSOLUTE_COLORIMETRIC = 3 + + see the pyCMS documentation for details on rendering intents and what + they do. + :param flags: Integer (0-...) specifying additional flags + :returns: A CmsTransform class object. + :exception PyCMSError: + """ + + if not isinstance(renderingIntent, int) or not (0 <= renderingIntent <= 3): + msg = "renderingIntent must be an integer between 0 and 3" + raise PyCMSError(msg) + + if not isinstance(flags, int) or not (0 <= flags <= _MAX_FLAG): + msg = f"flags must be an integer between 0 and {_MAX_FLAG}" + raise PyCMSError(msg) + + try: + if not isinstance(inputProfile, ImageCmsProfile): + inputProfile = ImageCmsProfile(inputProfile) + if not isinstance(outputProfile, ImageCmsProfile): + outputProfile = ImageCmsProfile(outputProfile) + return ImageCmsTransform( + inputProfile, outputProfile, inMode, outMode, renderingIntent, flags=flags + ) + except (OSError, TypeError, ValueError) as v: + raise PyCMSError(v) from v + + +def buildProofTransform( + inputProfile: _CmsProfileCompatible, + outputProfile: _CmsProfileCompatible, + proofProfile: _CmsProfileCompatible, + inMode: str, + outMode: str, + renderingIntent: Intent = Intent.PERCEPTUAL, + proofRenderingIntent: Intent = Intent.ABSOLUTE_COLORIMETRIC, + flags: Flags = Flags.SOFTPROOFING, +) -> ImageCmsTransform: + """ + (pyCMS) Builds an ICC transform mapping from the ``inputProfile`` to the + ``outputProfile``, but tries to simulate the result that would be + obtained on the ``proofProfile`` device. + + If the input, output, or proof profiles specified are not valid + filenames, a :exc:`PyCMSError` will be raised. + + If an error occurs during creation of the transform, + a :exc:`PyCMSError` will be raised. + + If ``inMode`` or ``outMode`` are not a mode supported by the ``outputProfile`` + (or by pyCMS), a :exc:`PyCMSError` will be raised. + + This function builds and returns an ICC transform from the ``inputProfile`` + to the ``outputProfile``, but tries to simulate the result that would be + obtained on the ``proofProfile`` device using ``renderingIntent`` and + ``proofRenderingIntent`` to determine what to do with out-of-gamut + colors. This is known as "soft-proofing". It will ONLY work for + converting images that are in ``inMode`` to images that are in outMode + color format (PIL mode, i.e. "RGB", "RGBA", "CMYK", etc.). + + Usage of the resulting transform object is exactly the same as with + ImageCms.buildTransform(). + + Proof profiling is generally used when using an output device to get a + good idea of what the final printed/displayed image would look like on + the ``proofProfile`` device when it's quicker and easier to use the + output device for judging color. Generally, this means that the + output device is a monitor, or a dye-sub printer (etc.), and the simulated + device is something more expensive, complicated, or time consuming + (making it difficult to make a real print for color judgement purposes). + + Soft-proofing basically functions by adjusting the colors on the + output device to match the colors of the device being simulated. However, + when the simulated device has a much wider gamut than the output + device, you may obtain marginal results. + + :param inputProfile: String, as a valid filename path to the ICC input + profile you wish to use for this transform, or a profile object + :param outputProfile: String, as a valid filename path to the ICC output + (monitor, usually) profile you wish to use for this transform, or a + profile object + :param proofProfile: String, as a valid filename path to the ICC proof + profile you wish to use for this transform, or a profile object + :param inMode: String, as a valid PIL mode that the appropriate profile + also supports (i.e. "RGB", "RGBA", "CMYK", etc.) + :param outMode: String, as a valid PIL mode that the appropriate profile + also supports (i.e. "RGB", "RGBA", "CMYK", etc.) + :param renderingIntent: Integer (0-3) specifying the rendering intent you + wish to use for the input->proof (simulated) transform + + ImageCms.Intent.PERCEPTUAL = 0 (DEFAULT) + ImageCms.Intent.RELATIVE_COLORIMETRIC = 1 + ImageCms.Intent.SATURATION = 2 + ImageCms.Intent.ABSOLUTE_COLORIMETRIC = 3 + + see the pyCMS documentation for details on rendering intents and what + they do. + :param proofRenderingIntent: Integer (0-3) specifying the rendering intent + you wish to use for proof->output transform + + ImageCms.Intent.PERCEPTUAL = 0 (DEFAULT) + ImageCms.Intent.RELATIVE_COLORIMETRIC = 1 + ImageCms.Intent.SATURATION = 2 + ImageCms.Intent.ABSOLUTE_COLORIMETRIC = 3 + + see the pyCMS documentation for details on rendering intents and what + they do. + :param flags: Integer (0-...) specifying additional flags + :returns: A CmsTransform class object. + :exception PyCMSError: + """ + + if not isinstance(renderingIntent, int) or not (0 <= renderingIntent <= 3): + msg = "renderingIntent must be an integer between 0 and 3" + raise PyCMSError(msg) + + if not isinstance(flags, int) or not (0 <= flags <= _MAX_FLAG): + msg = f"flags must be an integer between 0 and {_MAX_FLAG}" + raise PyCMSError(msg) + + try: + if not isinstance(inputProfile, ImageCmsProfile): + inputProfile = ImageCmsProfile(inputProfile) + if not isinstance(outputProfile, ImageCmsProfile): + outputProfile = ImageCmsProfile(outputProfile) + if not isinstance(proofProfile, ImageCmsProfile): + proofProfile = ImageCmsProfile(proofProfile) + return ImageCmsTransform( + inputProfile, + outputProfile, + inMode, + outMode, + renderingIntent, + proofProfile, + proofRenderingIntent, + flags, + ) + except (OSError, TypeError, ValueError) as v: + raise PyCMSError(v) from v + + +buildTransformFromOpenProfiles = buildTransform +buildProofTransformFromOpenProfiles = buildProofTransform + + +def applyTransform( + im: Image.Image, transform: ImageCmsTransform, inPlace: bool = False +) -> Image.Image | None: + """ + (pyCMS) Applies a transform to a given image. + + If ``im.mode != transform.input_mode``, a :exc:`PyCMSError` is raised. + + If ``inPlace`` is ``True`` and ``transform.input_mode != transform.output_mode``, a + :exc:`PyCMSError` is raised. + + If ``im.mode``, ``transform.input_mode`` or ``transform.output_mode`` is not + supported by pyCMSdll or the profiles you used for the transform, a + :exc:`PyCMSError` is raised. + + If an error occurs while the transform is being applied, + a :exc:`PyCMSError` is raised. + + This function applies a pre-calculated transform (from + ImageCms.buildTransform() or ImageCms.buildTransformFromOpenProfiles()) + to an image. The transform can be used for multiple images, saving + considerable calculation time if doing the same conversion multiple times. + + If you want to modify im in-place instead of receiving a new image as + the return value, set ``inPlace`` to ``True``. This can only be done if + ``transform.input_mode`` and ``transform.output_mode`` are the same, because we + can't change the mode in-place (the buffer sizes for some modes are + different). The default behavior is to return a new :py:class:`~PIL.Image.Image` + object of the same dimensions in mode ``transform.output_mode``. + + :param im: An :py:class:`~PIL.Image.Image` object, and ``im.mode`` must be the same + as the ``input_mode`` supported by the transform. + :param transform: A valid CmsTransform class object + :param inPlace: Bool. If ``True``, ``im`` is modified in place and ``None`` is + returned, if ``False``, a new :py:class:`~PIL.Image.Image` object with the + transform applied is returned (and ``im`` is not changed). The default is + ``False``. + :returns: Either ``None``, or a new :py:class:`~PIL.Image.Image` object, + depending on the value of ``inPlace``. The profile will be returned in + the image's ``info['icc_profile']``. + :exception PyCMSError: + """ + + try: + if inPlace: + transform.apply_in_place(im) + imOut = None + else: + imOut = transform.apply(im) + except (TypeError, ValueError) as v: + raise PyCMSError(v) from v + + return imOut + + +def createProfile( + colorSpace: Literal["LAB", "XYZ", "sRGB"], colorTemp: SupportsFloat = 0 +) -> core.CmsProfile: + """ + (pyCMS) Creates a profile. + + If colorSpace not in ``["LAB", "XYZ", "sRGB"]``, + a :exc:`PyCMSError` is raised. + + If using LAB and ``colorTemp`` is not a positive integer, + a :exc:`PyCMSError` is raised. + + If an error occurs while creating the profile, + a :exc:`PyCMSError` is raised. + + Use this function to create common profiles on-the-fly instead of + having to supply a profile on disk and knowing the path to it. It + returns a normal CmsProfile object that can be passed to + ImageCms.buildTransformFromOpenProfiles() to create a transform to apply + to images. + + :param colorSpace: String, the color space of the profile you wish to + create. + Currently only "LAB", "XYZ", and "sRGB" are supported. + :param colorTemp: Positive number for the white point for the profile, in + degrees Kelvin (i.e. 5000, 6500, 9600, etc.). The default is for D50 + illuminant if omitted (5000k). colorTemp is ONLY applied to LAB + profiles, and is ignored for XYZ and sRGB. + :returns: A CmsProfile class object + :exception PyCMSError: + """ + + if colorSpace not in ["LAB", "XYZ", "sRGB"]: + msg = ( + f"Color space not supported for on-the-fly profile creation ({colorSpace})" + ) + raise PyCMSError(msg) + + if colorSpace == "LAB": + try: + colorTemp = float(colorTemp) + except (TypeError, ValueError) as e: + msg = f'Color temperature must be numeric, "{colorTemp}" not valid' + raise PyCMSError(msg) from e + + try: + return core.createProfile(colorSpace, colorTemp) + except (TypeError, ValueError) as v: + raise PyCMSError(v) from v + + +def getProfileName(profile: _CmsProfileCompatible) -> str: + """ + + (pyCMS) Gets the internal product name for the given profile. + + If ``profile`` isn't a valid CmsProfile object or filename to a profile, + a :exc:`PyCMSError` is raised If an error occurs while trying + to obtain the name tag, a :exc:`PyCMSError` is raised. + + Use this function to obtain the INTERNAL name of the profile (stored + in an ICC tag in the profile itself), usually the one used when the + profile was originally created. Sometimes this tag also contains + additional information supplied by the creator. + + :param profile: EITHER a valid CmsProfile object, OR a string of the + filename of an ICC profile. + :returns: A string containing the internal name of the profile as stored + in an ICC tag. + :exception PyCMSError: + """ + + try: + # add an extra newline to preserve pyCMS compatibility + if not isinstance(profile, ImageCmsProfile): + profile = ImageCmsProfile(profile) + # do it in python, not c. + # // name was "%s - %s" (model, manufacturer) || Description , + # // but if the Model and Manufacturer were the same or the model + # // was long, Just the model, in 1.x + model = profile.profile.model + manufacturer = profile.profile.manufacturer + + if not (model or manufacturer): + return (profile.profile.profile_description or "") + "\n" + if not manufacturer or (model and len(model) > 30): + return f"{model}\n" + return f"{model} - {manufacturer}\n" + + except (AttributeError, OSError, TypeError, ValueError) as v: + raise PyCMSError(v) from v + + +def getProfileInfo(profile: _CmsProfileCompatible) -> str: + """ + (pyCMS) Gets the internal product information for the given profile. + + If ``profile`` isn't a valid CmsProfile object or filename to a profile, + a :exc:`PyCMSError` is raised. + + If an error occurs while trying to obtain the info tag, + a :exc:`PyCMSError` is raised. + + Use this function to obtain the information stored in the profile's + info tag. This often contains details about the profile, and how it + was created, as supplied by the creator. + + :param profile: EITHER a valid CmsProfile object, OR a string of the + filename of an ICC profile. + :returns: A string containing the internal profile information stored in + an ICC tag. + :exception PyCMSError: + """ + + try: + if not isinstance(profile, ImageCmsProfile): + profile = ImageCmsProfile(profile) + # add an extra newline to preserve pyCMS compatibility + # Python, not C. the white point bits weren't working well, + # so skipping. + # info was description \r\n\r\n copyright \r\n\r\n K007 tag \r\n\r\n whitepoint + description = profile.profile.profile_description + cpright = profile.profile.copyright + elements = [element for element in (description, cpright) if element] + return "\r\n\r\n".join(elements) + "\r\n\r\n" + + except (AttributeError, OSError, TypeError, ValueError) as v: + raise PyCMSError(v) from v + + +def getProfileCopyright(profile: _CmsProfileCompatible) -> str: + """ + (pyCMS) Gets the copyright for the given profile. + + If ``profile`` isn't a valid CmsProfile object or filename to a profile, a + :exc:`PyCMSError` is raised. + + If an error occurs while trying to obtain the copyright tag, + a :exc:`PyCMSError` is raised. + + Use this function to obtain the information stored in the profile's + copyright tag. + + :param profile: EITHER a valid CmsProfile object, OR a string of the + filename of an ICC profile. + :returns: A string containing the internal profile information stored in + an ICC tag. + :exception PyCMSError: + """ + try: + # add an extra newline to preserve pyCMS compatibility + if not isinstance(profile, ImageCmsProfile): + profile = ImageCmsProfile(profile) + return (profile.profile.copyright or "") + "\n" + except (AttributeError, OSError, TypeError, ValueError) as v: + raise PyCMSError(v) from v + + +def getProfileManufacturer(profile: _CmsProfileCompatible) -> str: + """ + (pyCMS) Gets the manufacturer for the given profile. + + If ``profile`` isn't a valid CmsProfile object or filename to a profile, a + :exc:`PyCMSError` is raised. + + If an error occurs while trying to obtain the manufacturer tag, a + :exc:`PyCMSError` is raised. + + Use this function to obtain the information stored in the profile's + manufacturer tag. + + :param profile: EITHER a valid CmsProfile object, OR a string of the + filename of an ICC profile. + :returns: A string containing the internal profile information stored in + an ICC tag. + :exception PyCMSError: + """ + try: + # add an extra newline to preserve pyCMS compatibility + if not isinstance(profile, ImageCmsProfile): + profile = ImageCmsProfile(profile) + return (profile.profile.manufacturer or "") + "\n" + except (AttributeError, OSError, TypeError, ValueError) as v: + raise PyCMSError(v) from v + + +def getProfileModel(profile: _CmsProfileCompatible) -> str: + """ + (pyCMS) Gets the model for the given profile. + + If ``profile`` isn't a valid CmsProfile object or filename to a profile, a + :exc:`PyCMSError` is raised. + + If an error occurs while trying to obtain the model tag, + a :exc:`PyCMSError` is raised. + + Use this function to obtain the information stored in the profile's + model tag. + + :param profile: EITHER a valid CmsProfile object, OR a string of the + filename of an ICC profile. + :returns: A string containing the internal profile information stored in + an ICC tag. + :exception PyCMSError: + """ + + try: + # add an extra newline to preserve pyCMS compatibility + if not isinstance(profile, ImageCmsProfile): + profile = ImageCmsProfile(profile) + return (profile.profile.model or "") + "\n" + except (AttributeError, OSError, TypeError, ValueError) as v: + raise PyCMSError(v) from v + + +def getProfileDescription(profile: _CmsProfileCompatible) -> str: + """ + (pyCMS) Gets the description for the given profile. + + If ``profile`` isn't a valid CmsProfile object or filename to a profile, a + :exc:`PyCMSError` is raised. + + If an error occurs while trying to obtain the description tag, + a :exc:`PyCMSError` is raised. + + Use this function to obtain the information stored in the profile's + description tag. + + :param profile: EITHER a valid CmsProfile object, OR a string of the + filename of an ICC profile. + :returns: A string containing the internal profile information stored in an + ICC tag. + :exception PyCMSError: + """ + + try: + # add an extra newline to preserve pyCMS compatibility + if not isinstance(profile, ImageCmsProfile): + profile = ImageCmsProfile(profile) + return (profile.profile.profile_description or "") + "\n" + except (AttributeError, OSError, TypeError, ValueError) as v: + raise PyCMSError(v) from v + + +def getDefaultIntent(profile: _CmsProfileCompatible) -> int: + """ + (pyCMS) Gets the default intent name for the given profile. + + If ``profile`` isn't a valid CmsProfile object or filename to a profile, a + :exc:`PyCMSError` is raised. + + If an error occurs while trying to obtain the default intent, a + :exc:`PyCMSError` is raised. + + Use this function to determine the default (and usually best optimized) + rendering intent for this profile. Most profiles support multiple + rendering intents, but are intended mostly for one type of conversion. + If you wish to use a different intent than returned, use + ImageCms.isIntentSupported() to verify it will work first. + + :param profile: EITHER a valid CmsProfile object, OR a string of the + filename of an ICC profile. + :returns: Integer 0-3 specifying the default rendering intent for this + profile. + + ImageCms.Intent.PERCEPTUAL = 0 (DEFAULT) + ImageCms.Intent.RELATIVE_COLORIMETRIC = 1 + ImageCms.Intent.SATURATION = 2 + ImageCms.Intent.ABSOLUTE_COLORIMETRIC = 3 + + see the pyCMS documentation for details on rendering intents and what + they do. + :exception PyCMSError: + """ + + try: + if not isinstance(profile, ImageCmsProfile): + profile = ImageCmsProfile(profile) + return profile.profile.rendering_intent + except (AttributeError, OSError, TypeError, ValueError) as v: + raise PyCMSError(v) from v + + +def isIntentSupported( + profile: _CmsProfileCompatible, intent: Intent, direction: Direction +) -> Literal[-1, 1]: + """ + (pyCMS) Checks if a given intent is supported. + + Use this function to verify that you can use your desired + ``intent`` with ``profile``, and that ``profile`` can be used for the + input/output/proof profile as you desire. + + Some profiles are created specifically for one "direction", can cannot + be used for others. Some profiles can only be used for certain + rendering intents, so it's best to either verify this before trying + to create a transform with them (using this function), or catch the + potential :exc:`PyCMSError` that will occur if they don't + support the modes you select. + + :param profile: EITHER a valid CmsProfile object, OR a string of the + filename of an ICC profile. + :param intent: Integer (0-3) specifying the rendering intent you wish to + use with this profile + + ImageCms.Intent.PERCEPTUAL = 0 (DEFAULT) + ImageCms.Intent.RELATIVE_COLORIMETRIC = 1 + ImageCms.Intent.SATURATION = 2 + ImageCms.Intent.ABSOLUTE_COLORIMETRIC = 3 + + see the pyCMS documentation for details on rendering intents and what + they do. + :param direction: Integer specifying if the profile is to be used for + input, output, or proof + + INPUT = 0 (or use ImageCms.Direction.INPUT) + OUTPUT = 1 (or use ImageCms.Direction.OUTPUT) + PROOF = 2 (or use ImageCms.Direction.PROOF) + + :returns: 1 if the intent/direction are supported, -1 if they are not. + :exception PyCMSError: + """ + + try: + if not isinstance(profile, ImageCmsProfile): + profile = ImageCmsProfile(profile) + # FIXME: I get different results for the same data w. different + # compilers. Bug in LittleCMS or in the binding? + if profile.profile.is_intent_supported(intent, direction): + return 1 + else: + return -1 + except (AttributeError, OSError, TypeError, ValueError) as v: + raise PyCMSError(v) from v diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/ImageColor.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/ImageColor.py new file mode 100644 index 000000000..9a15a8eb7 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/ImageColor.py @@ -0,0 +1,320 @@ +# +# The Python Imaging Library +# $Id$ +# +# map CSS3-style colour description strings to RGB +# +# History: +# 2002-10-24 fl Added support for CSS-style color strings +# 2002-12-15 fl Added RGBA support +# 2004-03-27 fl Fixed remaining int() problems for Python 1.5.2 +# 2004-07-19 fl Fixed gray/grey spelling issues +# 2009-03-05 fl Fixed rounding error in grayscale calculation +# +# Copyright (c) 2002-2004 by Secret Labs AB +# Copyright (c) 2002-2004 by Fredrik Lundh +# +# See the README file for information on usage and redistribution. +# +from __future__ import annotations + +import re +from functools import lru_cache + +from . import Image + + +@lru_cache +def getrgb(color: str) -> tuple[int, int, int] | tuple[int, int, int, int]: + """ + Convert a color string to an RGB or RGBA tuple. If the string cannot be + parsed, this function raises a :py:exc:`ValueError` exception. + + .. versionadded:: 1.1.4 + + :param color: A color string + :return: ``(red, green, blue[, alpha])`` + """ + if len(color) > 100: + msg = "color specifier is too long" + raise ValueError(msg) + color = color.lower() + + rgb = colormap.get(color, None) + if rgb: + if isinstance(rgb, tuple): + return rgb + rgb_tuple = getrgb(rgb) + assert len(rgb_tuple) == 3 + colormap[color] = rgb_tuple + return rgb_tuple + + # check for known string formats + if re.match("#[a-f0-9]{3}$", color): + return int(color[1] * 2, 16), int(color[2] * 2, 16), int(color[3] * 2, 16) + + if re.match("#[a-f0-9]{4}$", color): + return ( + int(color[1] * 2, 16), + int(color[2] * 2, 16), + int(color[3] * 2, 16), + int(color[4] * 2, 16), + ) + + if re.match("#[a-f0-9]{6}$", color): + return int(color[1:3], 16), int(color[3:5], 16), int(color[5:7], 16) + + if re.match("#[a-f0-9]{8}$", color): + return ( + int(color[1:3], 16), + int(color[3:5], 16), + int(color[5:7], 16), + int(color[7:9], 16), + ) + + m = re.match(r"rgb\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)$", color) + if m: + return int(m.group(1)), int(m.group(2)), int(m.group(3)) + + m = re.match(r"rgb\(\s*(\d+)%\s*,\s*(\d+)%\s*,\s*(\d+)%\s*\)$", color) + if m: + return ( + int((int(m.group(1)) * 255) / 100.0 + 0.5), + int((int(m.group(2)) * 255) / 100.0 + 0.5), + int((int(m.group(3)) * 255) / 100.0 + 0.5), + ) + + m = re.match( + r"hsl\(\s*(\d+\.?\d*)\s*,\s*(\d+\.?\d*)%\s*,\s*(\d+\.?\d*)%\s*\)$", color + ) + if m: + from colorsys import hls_to_rgb + + rgb_floats = hls_to_rgb( + float(m.group(1)) / 360.0, + float(m.group(3)) / 100.0, + float(m.group(2)) / 100.0, + ) + return ( + int(rgb_floats[0] * 255 + 0.5), + int(rgb_floats[1] * 255 + 0.5), + int(rgb_floats[2] * 255 + 0.5), + ) + + m = re.match( + r"hs[bv]\(\s*(\d+\.?\d*)\s*,\s*(\d+\.?\d*)%\s*,\s*(\d+\.?\d*)%\s*\)$", color + ) + if m: + from colorsys import hsv_to_rgb + + rgb_floats = hsv_to_rgb( + float(m.group(1)) / 360.0, + float(m.group(2)) / 100.0, + float(m.group(3)) / 100.0, + ) + return ( + int(rgb_floats[0] * 255 + 0.5), + int(rgb_floats[1] * 255 + 0.5), + int(rgb_floats[2] * 255 + 0.5), + ) + + m = re.match(r"rgba\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)$", color) + if m: + return int(m.group(1)), int(m.group(2)), int(m.group(3)), int(m.group(4)) + msg = f"unknown color specifier: {repr(color)}" + raise ValueError(msg) + + +@lru_cache +def getcolor(color: str, mode: str) -> int | tuple[int, ...]: + """ + Same as :py:func:`~PIL.ImageColor.getrgb` for most modes. However, if + ``mode`` is HSV, converts the RGB value to a HSV value, or if ``mode`` is + not color or a palette image, converts the RGB value to a grayscale value. + If the string cannot be parsed, this function raises a :py:exc:`ValueError` + exception. + + .. versionadded:: 1.1.4 + + :param color: A color string + :param mode: Convert result to this mode + :return: ``graylevel, (graylevel, alpha) or (red, green, blue[, alpha])`` + """ + # same as getrgb, but converts the result to the given mode + rgb, alpha = getrgb(color), 255 + if len(rgb) == 4: + alpha = rgb[3] + rgb = rgb[:3] + + if mode == "HSV": + from colorsys import rgb_to_hsv + + r, g, b = rgb + h, s, v = rgb_to_hsv(r / 255, g / 255, b / 255) + return int(h * 255), int(s * 255), int(v * 255) + elif Image.getmodebase(mode) == "L": + r, g, b = rgb + # ITU-R Recommendation 601-2 for nonlinear RGB + # scaled to 24 bits to match the convert's implementation. + graylevel = (r * 19595 + g * 38470 + b * 7471 + 0x8000) >> 16 + if mode[-1] == "A": + return graylevel, alpha + return graylevel + elif mode[-1] == "A": + return rgb + (alpha,) + return rgb + + +colormap: dict[str, str | tuple[int, int, int]] = { + # X11 colour table from https://drafts.csswg.org/css-color-4/, with + # gray/grey spelling issues fixed. This is a superset of HTML 4.0 + # colour names used in CSS 1. + "aliceblue": "#f0f8ff", + "antiquewhite": "#faebd7", + "aqua": "#00ffff", + "aquamarine": "#7fffd4", + "azure": "#f0ffff", + "beige": "#f5f5dc", + "bisque": "#ffe4c4", + "black": "#000000", + "blanchedalmond": "#ffebcd", + "blue": "#0000ff", + "blueviolet": "#8a2be2", + "brown": "#a52a2a", + "burlywood": "#deb887", + "cadetblue": "#5f9ea0", + "chartreuse": "#7fff00", + "chocolate": "#d2691e", + "coral": "#ff7f50", + "cornflowerblue": "#6495ed", + "cornsilk": "#fff8dc", + "crimson": "#dc143c", + "cyan": "#00ffff", + "darkblue": "#00008b", + "darkcyan": "#008b8b", + "darkgoldenrod": "#b8860b", + "darkgray": "#a9a9a9", + "darkgrey": "#a9a9a9", + "darkgreen": "#006400", + "darkkhaki": "#bdb76b", + "darkmagenta": "#8b008b", + "darkolivegreen": "#556b2f", + "darkorange": "#ff8c00", + "darkorchid": "#9932cc", + "darkred": "#8b0000", + "darksalmon": "#e9967a", + "darkseagreen": "#8fbc8f", + "darkslateblue": "#483d8b", + "darkslategray": "#2f4f4f", + "darkslategrey": "#2f4f4f", + "darkturquoise": "#00ced1", + "darkviolet": "#9400d3", + "deeppink": "#ff1493", + "deepskyblue": "#00bfff", + "dimgray": "#696969", + "dimgrey": "#696969", + "dodgerblue": "#1e90ff", + "firebrick": "#b22222", + "floralwhite": "#fffaf0", + "forestgreen": "#228b22", + "fuchsia": "#ff00ff", + "gainsboro": "#dcdcdc", + "ghostwhite": "#f8f8ff", + "gold": "#ffd700", + "goldenrod": "#daa520", + "gray": "#808080", + "grey": "#808080", + "green": "#008000", + "greenyellow": "#adff2f", + "honeydew": "#f0fff0", + "hotpink": "#ff69b4", + "indianred": "#cd5c5c", + "indigo": "#4b0082", + "ivory": "#fffff0", + "khaki": "#f0e68c", + "lavender": "#e6e6fa", + "lavenderblush": "#fff0f5", + "lawngreen": "#7cfc00", + "lemonchiffon": "#fffacd", + "lightblue": "#add8e6", + "lightcoral": "#f08080", + "lightcyan": "#e0ffff", + "lightgoldenrodyellow": "#fafad2", + "lightgreen": "#90ee90", + "lightgray": "#d3d3d3", + "lightgrey": "#d3d3d3", + "lightpink": "#ffb6c1", + "lightsalmon": "#ffa07a", + "lightseagreen": "#20b2aa", + "lightskyblue": "#87cefa", + "lightslategray": "#778899", + "lightslategrey": "#778899", + "lightsteelblue": "#b0c4de", + "lightyellow": "#ffffe0", + "lime": "#00ff00", + "limegreen": "#32cd32", + "linen": "#faf0e6", + "magenta": "#ff00ff", + "maroon": "#800000", + "mediumaquamarine": "#66cdaa", + "mediumblue": "#0000cd", + "mediumorchid": "#ba55d3", + "mediumpurple": "#9370db", + "mediumseagreen": "#3cb371", + "mediumslateblue": "#7b68ee", + "mediumspringgreen": "#00fa9a", + "mediumturquoise": "#48d1cc", + "mediumvioletred": "#c71585", + "midnightblue": "#191970", + "mintcream": "#f5fffa", + "mistyrose": "#ffe4e1", + "moccasin": "#ffe4b5", + "navajowhite": "#ffdead", + "navy": "#000080", + "oldlace": "#fdf5e6", + "olive": "#808000", + "olivedrab": "#6b8e23", + "orange": "#ffa500", + "orangered": "#ff4500", + "orchid": "#da70d6", + "palegoldenrod": "#eee8aa", + "palegreen": "#98fb98", + "paleturquoise": "#afeeee", + "palevioletred": "#db7093", + "papayawhip": "#ffefd5", + "peachpuff": "#ffdab9", + "peru": "#cd853f", + "pink": "#ffc0cb", + "plum": "#dda0dd", + "powderblue": "#b0e0e6", + "purple": "#800080", + "rebeccapurple": "#663399", + "red": "#ff0000", + "rosybrown": "#bc8f8f", + "royalblue": "#4169e1", + "saddlebrown": "#8b4513", + "salmon": "#fa8072", + "sandybrown": "#f4a460", + "seagreen": "#2e8b57", + "seashell": "#fff5ee", + "sienna": "#a0522d", + "silver": "#c0c0c0", + "skyblue": "#87ceeb", + "slateblue": "#6a5acd", + "slategray": "#708090", + "slategrey": "#708090", + "snow": "#fffafa", + "springgreen": "#00ff7f", + "steelblue": "#4682b4", + "tan": "#d2b48c", + "teal": "#008080", + "thistle": "#d8bfd8", + "tomato": "#ff6347", + "turquoise": "#40e0d0", + "violet": "#ee82ee", + "wheat": "#f5deb3", + "white": "#ffffff", + "whitesmoke": "#f5f5f5", + "yellow": "#ffff00", + "yellowgreen": "#9acd32", +} diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/ImageDraw.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/ImageDraw.py new file mode 100644 index 000000000..9b0864d1a --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/ImageDraw.py @@ -0,0 +1,1035 @@ +# +# The Python Imaging Library +# $Id$ +# +# drawing interface operations +# +# History: +# 1996-04-13 fl Created (experimental) +# 1996-08-07 fl Filled polygons, ellipses. +# 1996-08-13 fl Added text support +# 1998-06-28 fl Handle I and F images +# 1998-12-29 fl Added arc; use arc primitive to draw ellipses +# 1999-01-10 fl Added shape stuff (experimental) +# 1999-02-06 fl Added bitmap support +# 1999-02-11 fl Changed all primitives to take options +# 1999-02-20 fl Fixed backwards compatibility +# 2000-10-12 fl Copy on write, when necessary +# 2001-02-18 fl Use default ink for bitmap/text also in fill mode +# 2002-10-24 fl Added support for CSS-style color strings +# 2002-12-10 fl Added experimental support for RGBA-on-RGB drawing +# 2002-12-11 fl Refactored low-level drawing API (work in progress) +# 2004-08-26 fl Made Draw() a factory function, added getdraw() support +# 2004-09-04 fl Added width support to line primitive +# 2004-09-10 fl Added font mode handling +# 2006-06-19 fl Added font bearing support (getmask2) +# +# Copyright (c) 1997-2006 by Secret Labs AB +# Copyright (c) 1996-2006 by Fredrik Lundh +# +# See the README file for information on usage and redistribution. +# +from __future__ import annotations + +import math +import struct +from collections.abc import Sequence +from typing import cast + +from . import Image, ImageColor, ImageText + +TYPE_CHECKING = False +if TYPE_CHECKING: + from collections.abc import Callable + from types import ModuleType + from typing import Any, AnyStr + + from . import ImageDraw2, ImageFont + from ._typing import Coords, _Ink + +# experimental access to the outline API +Outline: Callable[[], Image.core._Outline] = Image.core.outline + +""" +A simple 2D drawing interface for PIL images. +

+Application code should use the Draw factory, instead of +directly. +""" + + +class ImageDraw: + font: ( + ImageFont.ImageFont | ImageFont.FreeTypeFont | ImageFont.TransposedFont | None + ) = None + + def __init__(self, im: Image.Image, mode: str | None = None) -> None: + """ + Create a drawing instance. + + :param im: The image to draw in. + :param mode: Optional mode to use for color values. For RGB + images, this argument can be RGB or RGBA (to blend the + drawing into the image). For all other modes, this argument + must be the same as the image mode. If omitted, the mode + defaults to the mode of the image. + """ + im._ensure_mutable() + blend = 0 + if mode is None: + mode = im.mode + if mode != im.mode: + if mode == "RGBA" and im.mode == "RGB": + blend = 1 + else: + msg = "mode mismatch" + raise ValueError(msg) + if mode == "P": + self.palette = im.palette + else: + self.palette = None + self._image = im + self.im = im.im + self.draw = Image.core.draw(self.im, blend) + self.mode = mode + if mode in ("I", "F"): + self.ink = self.draw.draw_ink(1) + else: + self.ink = self.draw.draw_ink(-1) + if mode in ("1", "P", "I", "F"): + # FIXME: fix Fill2 to properly support matte for I+F images + self.fontmode = "1" + else: + self.fontmode = "L" # aliasing is okay for other modes + self.fill = False + + def getfont( + self, + ) -> ImageFont.ImageFont | ImageFont.FreeTypeFont | ImageFont.TransposedFont: + """ + Get the current default font. + + To set the default font for this ImageDraw instance:: + + from PIL import ImageDraw, ImageFont + draw.font = ImageFont.truetype("Tests/fonts/FreeMono.ttf") + + To set the default font for all future ImageDraw instances:: + + from PIL import ImageDraw, ImageFont + ImageDraw.ImageDraw.font = ImageFont.truetype("Tests/fonts/FreeMono.ttf") + + If the current default font is ``None``, + it is initialized with ``ImageFont.load_default()``. + + :returns: An image font.""" + if not self.font: + # FIXME: should add a font repository + from . import ImageFont + + self.font = ImageFont.load_default() + return self.font + + def _getfont( + self, font_size: float | None + ) -> ImageFont.ImageFont | ImageFont.FreeTypeFont | ImageFont.TransposedFont: + if font_size is not None: + from . import ImageFont + + return ImageFont.load_default(font_size) + else: + return self.getfont() + + def _getink( + self, ink: _Ink | None, fill: _Ink | None = None + ) -> tuple[int | None, int | None]: + result_ink = None + result_fill = None + if ink is None and fill is None: + if self.fill: + result_fill = self.ink + else: + result_ink = self.ink + else: + if ink is not None: + if isinstance(ink, str): + ink = ImageColor.getcolor(ink, self.mode) + if self.palette and isinstance(ink, tuple): + ink = self.palette.getcolor(ink, self._image) + result_ink = self.draw.draw_ink(ink) + if fill is not None: + if isinstance(fill, str): + fill = ImageColor.getcolor(fill, self.mode) + if self.palette and isinstance(fill, tuple): + fill = self.palette.getcolor(fill, self._image) + result_fill = self.draw.draw_ink(fill) + return result_ink, result_fill + + def arc( + self, + xy: Coords, + start: float, + end: float, + fill: _Ink | None = None, + width: int = 1, + ) -> None: + """Draw an arc.""" + ink, fill = self._getink(fill) + if ink is not None: + self.draw.draw_arc(xy, start, end, ink, width) + + def bitmap( + self, xy: Sequence[int], bitmap: Image.Image, fill: _Ink | None = None + ) -> None: + """Draw a bitmap.""" + bitmap.load() + ink, fill = self._getink(fill) + if ink is None: + ink = fill + if ink is not None: + self.draw.draw_bitmap(xy, bitmap.im, ink) + + def chord( + self, + xy: Coords, + start: float, + end: float, + fill: _Ink | None = None, + outline: _Ink | None = None, + width: int = 1, + ) -> None: + """Draw a chord.""" + ink, fill_ink = self._getink(outline, fill) + if fill_ink is not None: + self.draw.draw_chord(xy, start, end, fill_ink, 1) + if ink is not None and ink != fill_ink and width != 0: + self.draw.draw_chord(xy, start, end, ink, 0, width) + + def ellipse( + self, + xy: Coords, + fill: _Ink | None = None, + outline: _Ink | None = None, + width: int = 1, + ) -> None: + """Draw an ellipse.""" + ink, fill_ink = self._getink(outline, fill) + if fill_ink is not None: + self.draw.draw_ellipse(xy, fill_ink, 1) + if ink is not None and ink != fill_ink and width != 0: + self.draw.draw_ellipse(xy, ink, 0, width) + + def circle( + self, + xy: Sequence[float], + radius: float, + fill: _Ink | None = None, + outline: _Ink | None = None, + width: int = 1, + ) -> None: + """Draw a circle given center coordinates and a radius.""" + ellipse_xy = (xy[0] - radius, xy[1] - radius, xy[0] + radius, xy[1] + radius) + self.ellipse(ellipse_xy, fill, outline, width) + + def line( + self, + xy: Coords, + fill: _Ink | None = None, + width: int = 0, + joint: str | None = None, + ) -> None: + """Draw a line, or a connected sequence of line segments.""" + ink = self._getink(fill)[0] + if ink is not None: + self.draw.draw_lines(xy, ink, width) + if joint == "curve" and width > 4: + points: Sequence[Sequence[float]] + if isinstance(xy[0], (list, tuple)): + points = cast(Sequence[Sequence[float]], xy) + else: + points = [ + cast(Sequence[float], tuple(xy[i : i + 2])) + for i in range(0, len(xy), 2) + ] + for i in range(1, len(points) - 1): + point = points[i] + angles = [ + math.degrees(math.atan2(end[0] - start[0], start[1] - end[1])) + % 360 + for start, end in ( + (points[i - 1], point), + (point, points[i + 1]), + ) + ] + if angles[0] == angles[1]: + # This is a straight line, so no joint is required + continue + + def coord_at_angle( + coord: Sequence[float], angle: float + ) -> tuple[float, ...]: + x, y = coord + angle -= 90 + distance = width / 2 - 1 + return tuple( + p + (math.floor(p_d) if p_d > 0 else math.ceil(p_d)) + for p, p_d in ( + (x, distance * math.cos(math.radians(angle))), + (y, distance * math.sin(math.radians(angle))), + ) + ) + + flipped = ( + angles[1] > angles[0] and angles[1] - 180 > angles[0] + ) or (angles[1] < angles[0] and angles[1] + 180 > angles[0]) + coords = [ + (point[0] - width / 2 + 1, point[1] - width / 2 + 1), + (point[0] + width / 2 - 1, point[1] + width / 2 - 1), + ] + if flipped: + start, end = (angles[1] + 90, angles[0] + 90) + else: + start, end = (angles[0] - 90, angles[1] - 90) + self.pieslice(coords, start - 90, end - 90, fill) + + if width > 8: + # Cover potential gaps between the line and the joint + if flipped: + gap_coords = [ + coord_at_angle(point, angles[0] + 90), + point, + coord_at_angle(point, angles[1] + 90), + ] + else: + gap_coords = [ + coord_at_angle(point, angles[0] - 90), + point, + coord_at_angle(point, angles[1] - 90), + ] + self.line(gap_coords, fill, width=3) + + def shape( + self, + shape: Image.core._Outline, + fill: _Ink | None = None, + outline: _Ink | None = None, + ) -> None: + """(Experimental) Draw a shape.""" + shape.close() + ink, fill_ink = self._getink(outline, fill) + if fill_ink is not None: + self.draw.draw_outline(shape, fill_ink, 1) + if ink is not None and ink != fill_ink: + self.draw.draw_outline(shape, ink, 0) + + def pieslice( + self, + xy: Coords, + start: float, + end: float, + fill: _Ink | None = None, + outline: _Ink | None = None, + width: int = 1, + ) -> None: + """Draw a pieslice.""" + ink, fill_ink = self._getink(outline, fill) + if fill_ink is not None: + self.draw.draw_pieslice(xy, start, end, fill_ink, 1) + if ink is not None and ink != fill_ink and width != 0: + self.draw.draw_pieslice(xy, start, end, ink, 0, width) + + def point(self, xy: Coords, fill: _Ink | None = None) -> None: + """Draw one or more individual pixels.""" + ink, fill = self._getink(fill) + if ink is not None: + self.draw.draw_points(xy, ink) + + def polygon( + self, + xy: Coords, + fill: _Ink | None = None, + outline: _Ink | None = None, + width: int = 1, + ) -> None: + """Draw a polygon.""" + ink, fill_ink = self._getink(outline, fill) + if fill_ink is not None: + self.draw.draw_polygon(xy, fill_ink, 1) + if ink is not None and ink != fill_ink and width != 0: + if width == 1: + self.draw.draw_polygon(xy, ink, 0, width) + elif self.im is not None: + # To avoid expanding the polygon outwards, + # use the fill as a mask + mask = Image.new("1", self.im.size) + mask_ink = self._getink(1)[0] + draw = Draw(mask) + draw.draw.draw_polygon(xy, mask_ink, 1) + + self.draw.draw_polygon(xy, ink, 0, width * 2 - 1, mask.im) + + def regular_polygon( + self, + bounding_circle: Sequence[Sequence[float] | float], + n_sides: int, + rotation: float = 0, + fill: _Ink | None = None, + outline: _Ink | None = None, + width: int = 1, + ) -> None: + """Draw a regular polygon.""" + xy = _compute_regular_polygon_vertices(bounding_circle, n_sides, rotation) + self.polygon(xy, fill, outline, width) + + def rectangle( + self, + xy: Coords, + fill: _Ink | None = None, + outline: _Ink | None = None, + width: int = 1, + ) -> None: + """Draw a rectangle.""" + ink, fill_ink = self._getink(outline, fill) + if fill_ink is not None: + self.draw.draw_rectangle(xy, fill_ink, 1) + if ink is not None and ink != fill_ink and width != 0: + self.draw.draw_rectangle(xy, ink, 0, width) + + def rounded_rectangle( + self, + xy: Coords, + radius: float = 0, + fill: _Ink | None = None, + outline: _Ink | None = None, + width: int = 1, + *, + corners: tuple[bool, bool, bool, bool] | None = None, + ) -> None: + """Draw a rounded rectangle.""" + if isinstance(xy[0], (list, tuple)): + (x0, y0), (x1, y1) = cast(Sequence[Sequence[float]], xy) + else: + x0, y0, x1, y1 = cast(Sequence[float], xy) + if x1 < x0: + msg = "x1 must be greater than or equal to x0" + raise ValueError(msg) + if y1 < y0: + msg = "y1 must be greater than or equal to y0" + raise ValueError(msg) + if corners is None: + corners = (True, True, True, True) + + d = radius * 2 + + x0 = round(x0) + y0 = round(y0) + x1 = round(x1) + y1 = round(y1) + full_x, full_y = False, False + if all(corners): + full_x = d >= x1 - x0 - 1 + if full_x: + # The two left and two right corners are joined + d = x1 - x0 + full_y = d >= y1 - y0 - 1 + if full_y: + # The two top and two bottom corners are joined + d = y1 - y0 + if full_x and full_y: + # If all corners are joined, that is a circle + return self.ellipse(xy, fill, outline, width) + + if d == 0 or not any(corners): + # If the corners have no curve, + # or there are no corners, + # that is a rectangle + return self.rectangle(xy, fill, outline, width) + + r = int(d // 2) + ink, fill_ink = self._getink(outline, fill) + + def draw_corners(pieslice: bool) -> None: + parts: tuple[tuple[tuple[float, float, float, float], int, int], ...] + if full_x: + # Draw top and bottom halves + parts = ( + ((x0, y0, x0 + d, y0 + d), 180, 360), + ((x0, y1 - d, x0 + d, y1), 0, 180), + ) + elif full_y: + # Draw left and right halves + parts = ( + ((x0, y0, x0 + d, y0 + d), 90, 270), + ((x1 - d, y0, x1, y0 + d), 270, 90), + ) + else: + # Draw four separate corners + parts = tuple( + part + for i, part in enumerate( + ( + ((x0, y0, x0 + d, y0 + d), 180, 270), + ((x1 - d, y0, x1, y0 + d), 270, 360), + ((x1 - d, y1 - d, x1, y1), 0, 90), + ((x0, y1 - d, x0 + d, y1), 90, 180), + ) + ) + if corners[i] + ) + for part in parts: + if pieslice: + self.draw.draw_pieslice(*(part + (fill_ink, 1))) + else: + self.draw.draw_arc(*(part + (ink, width))) + + if fill_ink is not None: + draw_corners(True) + + if full_x: + self.draw.draw_rectangle((x0, y0 + r + 1, x1, y1 - r - 1), fill_ink, 1) + elif x1 - r - 1 >= x0 + r + 1: + self.draw.draw_rectangle((x0 + r + 1, y0, x1 - r - 1, y1), fill_ink, 1) + if not full_x and not full_y: + left = [x0, y0, x0 + r, y1] + if corners[0]: + left[1] += r + 1 + if corners[3]: + left[3] -= r + 1 + self.draw.draw_rectangle(left, fill_ink, 1) + + right = [x1 - r, y0, x1, y1] + if corners[1]: + right[1] += r + 1 + if corners[2]: + right[3] -= r + 1 + self.draw.draw_rectangle(right, fill_ink, 1) + if ink is not None and ink != fill_ink and width != 0: + draw_corners(False) + + if not full_x: + top = [x0, y0, x1, y0 + width - 1] + if corners[0]: + top[0] += r + 1 + if corners[1]: + top[2] -= r + 1 + self.draw.draw_rectangle(top, ink, 1) + + bottom = [x0, y1 - width + 1, x1, y1] + if corners[3]: + bottom[0] += r + 1 + if corners[2]: + bottom[2] -= r + 1 + self.draw.draw_rectangle(bottom, ink, 1) + if not full_y: + left = [x0, y0, x0 + width - 1, y1] + if corners[0]: + left[1] += r + 1 + if corners[3]: + left[3] -= r + 1 + self.draw.draw_rectangle(left, ink, 1) + + right = [x1 - width + 1, y0, x1, y1] + if corners[1]: + right[1] += r + 1 + if corners[2]: + right[3] -= r + 1 + self.draw.draw_rectangle(right, ink, 1) + + def text( + self, + xy: tuple[float, float], + text: AnyStr | ImageText.Text[AnyStr], + fill: _Ink | None = None, + font: ( + ImageFont.ImageFont + | ImageFont.FreeTypeFont + | ImageFont.TransposedFont + | None + ) = None, + anchor: str | None = None, + spacing: float = 4, + align: str = "left", + direction: str | None = None, + features: list[str] | None = None, + language: str | None = None, + stroke_width: float = 0, + stroke_fill: _Ink | None = None, + embedded_color: bool = False, + *args: Any, + **kwargs: Any, + ) -> None: + """Draw text.""" + if isinstance(text, ImageText.Text): + image_text = text + else: + if font is None: + font = self._getfont(kwargs.get("font_size")) + image_text = ImageText.Text( + text, font, self.mode, spacing, direction, features, language + ) + if embedded_color: + image_text.embed_color() + if stroke_width: + image_text.stroke(stroke_width, stroke_fill) + + def getink(fill: _Ink | None) -> int: + ink, fill_ink = self._getink(fill) + if ink is None: + assert fill_ink is not None + return fill_ink + return ink + + ink = getink(fill) + if ink is None: + return + + stroke_ink = None + if image_text.stroke_width: + stroke_ink = ( + getink(image_text.stroke_fill) + if image_text.stroke_fill is not None + else ink + ) + + for line in image_text._split(xy, anchor, align): + + def draw_text(ink: int, stroke_width: float = 0) -> None: + mode = self.fontmode + if stroke_width == 0 and embedded_color: + mode = "RGBA" + x = int(line.x) + y = int(line.y) + start = (math.modf(line.x)[0], math.modf(line.y)[0]) + try: + mask, offset = image_text.font.getmask2( # type: ignore[union-attr,misc] + line.text, + mode, + direction=direction, + features=features, + language=language, + stroke_width=stroke_width, + stroke_filled=True, + anchor=line.anchor, + ink=ink, + start=start, + *args, + **kwargs, + ) + x += offset[0] + y += offset[1] + except AttributeError: + try: + mask = image_text.font.getmask( # type: ignore[misc] + line.text, + mode, + direction, + features, + language, + stroke_width, + line.anchor, + ink, + start=start, + *args, + **kwargs, + ) + except TypeError: + mask = image_text.font.getmask(line.text) + if mode == "RGBA": + # image_text.font.getmask2(mode="RGBA") + # returns color in RGB bands and mask in A + # extract mask and set text alpha + color, mask = mask, mask.getband(3) + ink_alpha = struct.pack("i", ink)[3] + color.fillband(3, ink_alpha) + if self.im is not None: + self.im.paste( + color, (x, y, x + mask.size[0], y + mask.size[1]), mask + ) + else: + self.draw.draw_bitmap((x, y), mask, ink) + + if stroke_ink is not None: + # Draw stroked text + draw_text(stroke_ink, image_text.stroke_width) + + # Draw normal text + if ink != stroke_ink: + draw_text(ink) + else: + # Only draw normal text + draw_text(ink) + + def multiline_text( + self, + xy: tuple[float, float], + text: AnyStr, + fill: _Ink | None = None, + font: ( + ImageFont.ImageFont + | ImageFont.FreeTypeFont + | ImageFont.TransposedFont + | None + ) = None, + anchor: str | None = None, + spacing: float = 4, + align: str = "left", + direction: str | None = None, + features: list[str] | None = None, + language: str | None = None, + stroke_width: float = 0, + stroke_fill: _Ink | None = None, + embedded_color: bool = False, + *, + font_size: float | None = None, + ) -> None: + return self.text( + xy, + text, + fill, + font, + anchor, + spacing, + align, + direction, + features, + language, + stroke_width, + stroke_fill, + embedded_color, + font_size=font_size, + ) + + def textlength( + self, + text: AnyStr, + font: ( + ImageFont.ImageFont + | ImageFont.FreeTypeFont + | ImageFont.TransposedFont + | None + ) = None, + direction: str | None = None, + features: list[str] | None = None, + language: str | None = None, + embedded_color: bool = False, + *, + font_size: float | None = None, + ) -> float: + """Get the length of a given string, in pixels with 1/64 precision.""" + if font is None: + font = self._getfont(font_size) + image_text = ImageText.Text( + text, + font, + self.mode, + direction=direction, + features=features, + language=language, + ) + if embedded_color: + image_text.embed_color() + return image_text.get_length() + + def textbbox( + self, + xy: tuple[float, float], + text: AnyStr, + font: ( + ImageFont.ImageFont + | ImageFont.FreeTypeFont + | ImageFont.TransposedFont + | None + ) = None, + anchor: str | None = None, + spacing: float = 4, + align: str = "left", + direction: str | None = None, + features: list[str] | None = None, + language: str | None = None, + stroke_width: float = 0, + embedded_color: bool = False, + *, + font_size: float | None = None, + ) -> tuple[float, float, float, float]: + """Get the bounding box of a given string, in pixels.""" + if font is None: + font = self._getfont(font_size) + image_text = ImageText.Text( + text, font, self.mode, spacing, direction, features, language + ) + if embedded_color: + image_text.embed_color() + if stroke_width: + image_text.stroke(stroke_width) + return image_text.get_bbox(xy, anchor, align) + + def multiline_textbbox( + self, + xy: tuple[float, float], + text: AnyStr, + font: ( + ImageFont.ImageFont + | ImageFont.FreeTypeFont + | ImageFont.TransposedFont + | None + ) = None, + anchor: str | None = None, + spacing: float = 4, + align: str = "left", + direction: str | None = None, + features: list[str] | None = None, + language: str | None = None, + stroke_width: float = 0, + embedded_color: bool = False, + *, + font_size: float | None = None, + ) -> tuple[float, float, float, float]: + return self.textbbox( + xy, + text, + font, + anchor, + spacing, + align, + direction, + features, + language, + stroke_width, + embedded_color, + font_size=font_size, + ) + + +def Draw(im: Image.Image, mode: str | None = None) -> ImageDraw: + """ + A simple 2D drawing interface for PIL images. + + :param im: The image to draw in. + :param mode: Optional mode to use for color values. For RGB + images, this argument can be RGB or RGBA (to blend the + drawing into the image). For all other modes, this argument + must be the same as the image mode. If omitted, the mode + defaults to the mode of the image. + """ + try: + return getattr(im, "getdraw")(mode) + except AttributeError: + return ImageDraw(im, mode) + + +def getdraw(im: Image.Image | None = None) -> tuple[ImageDraw2.Draw | None, ModuleType]: + """ + :param im: The image to draw in. + :returns: A (drawing context, drawing resource factory) tuple. + """ + from . import ImageDraw2 + + draw = ImageDraw2.Draw(im) if im is not None else None + return draw, ImageDraw2 + + +def floodfill( + image: Image.Image, + xy: tuple[int, int], + value: float | tuple[int, ...], + border: float | tuple[int, ...] | None = None, + thresh: float = 0, +) -> None: + """ + .. warning:: This method is experimental. + + Fills a bounded region with a given color. + + :param image: Target image. + :param xy: Seed position (a 2-item coordinate tuple). See + :ref:`coordinate-system`. + :param value: Fill color. + :param border: Optional border value. If given, the region consists of + pixels with a color different from the border color. If not given, + the region consists of pixels having the same color as the seed + pixel. + :param thresh: Optional threshold value which specifies a maximum + tolerable difference of a pixel value from the 'background' in + order for it to be replaced. Useful for filling regions of + non-homogeneous, but similar, colors. + """ + # based on an implementation by Eric S. Raymond + # amended by yo1995 @20180806 + pixel = image.load() + assert pixel is not None + x, y = xy + try: + background = pixel[x, y] + if _color_diff(value, background) <= thresh: + return # seed point already has fill color + pixel[x, y] = value + except (ValueError, IndexError): + return # seed point outside image + edge = {(x, y)} + # use a set to keep record of current and previous edge pixels + # to reduce memory consumption + full_edge = set() + while edge: + new_edge = set() + for x, y in edge: # 4 adjacent method + for s, t in ((x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)): + # If already processed, or if a coordinate is negative, skip + if (s, t) in full_edge or s < 0 or t < 0: + continue + try: + p = pixel[s, t] + except (ValueError, IndexError): + pass + else: + full_edge.add((s, t)) + if border is None: + fill = _color_diff(p, background) <= thresh + else: + fill = p not in (value, border) + if fill: + pixel[s, t] = value + new_edge.add((s, t)) + full_edge = edge # discard pixels processed + edge = new_edge + + +def _compute_regular_polygon_vertices( + bounding_circle: Sequence[Sequence[float] | float], n_sides: int, rotation: float +) -> list[tuple[float, float]]: + """ + Generate a list of vertices for a 2D regular polygon. + + :param bounding_circle: The bounding circle is a sequence defined + by a point and radius. The polygon is inscribed in this circle. + (e.g. ``bounding_circle=(x, y, r)`` or ``((x, y), r)``) + :param n_sides: Number of sides + (e.g. ``n_sides=3`` for a triangle, ``6`` for a hexagon) + :param rotation: Apply an arbitrary rotation to the polygon + (e.g. ``rotation=90``, applies a 90 degree rotation) + :return: List of regular polygon vertices + (e.g. ``[(25, 50), (50, 50), (50, 25), (25, 25)]``) + + How are the vertices computed? + 1. Compute the following variables + - theta: Angle between the apothem & the nearest polygon vertex + - side_length: Length of each polygon edge + - centroid: Center of bounding circle (1st, 2nd elements of bounding_circle) + - polygon_radius: Polygon radius (last element of bounding_circle) + - angles: Location of each polygon vertex in polar grid + (e.g. A square with 0 degree rotation => [225.0, 315.0, 45.0, 135.0]) + + 2. For each angle in angles, get the polygon vertex at that angle + The vertex is computed using the equation below. + X= xcos(φ) + ysin(φ) + Y= −xsin(φ) + ycos(φ) + + Note: + φ = angle in degrees + x = 0 + y = polygon_radius + + The formula above assumes rotation around the origin. + In our case, we are rotating around the centroid. + To account for this, we use the formula below + X = xcos(φ) + ysin(φ) + centroid_x + Y = −xsin(φ) + ycos(φ) + centroid_y + """ + # 1. Error Handling + # 1.1 Check `n_sides` has an appropriate value + if not isinstance(n_sides, int): + msg = "n_sides should be an int" # type: ignore[unreachable] + raise TypeError(msg) + if n_sides < 3: + msg = "n_sides should be an int > 2" + raise ValueError(msg) + + # 1.2 Check `bounding_circle` has an appropriate value + if not isinstance(bounding_circle, (list, tuple)): + msg = "bounding_circle should be a sequence" + raise TypeError(msg) + + if len(bounding_circle) == 3: + if not all(isinstance(i, (int, float)) for i in bounding_circle): + msg = "bounding_circle should only contain numeric data" + raise ValueError(msg) + + *centroid, polygon_radius = cast(list[float], list(bounding_circle)) + elif len(bounding_circle) == 2 and isinstance(bounding_circle[0], (list, tuple)): + if not all( + isinstance(i, (int, float)) for i in bounding_circle[0] + ) or not isinstance(bounding_circle[1], (int, float)): + msg = "bounding_circle should only contain numeric data" + raise ValueError(msg) + + if len(bounding_circle[0]) != 2: + msg = "bounding_circle centre should contain 2D coordinates (e.g. (x, y))" + raise ValueError(msg) + + centroid = cast(list[float], list(bounding_circle[0])) + polygon_radius = cast(float, bounding_circle[1]) + else: + msg = ( + "bounding_circle should contain 2D coordinates " + "and a radius (e.g. (x, y, r) or ((x, y), r) )" + ) + raise ValueError(msg) + + if polygon_radius <= 0: + msg = "bounding_circle radius should be > 0" + raise ValueError(msg) + + # 1.3 Check `rotation` has an appropriate value + if not isinstance(rotation, (int, float)): + msg = "rotation should be an int or float" # type: ignore[unreachable] + raise ValueError(msg) + + # 2. Define Helper Functions + def _apply_rotation(point: list[float], degrees: float) -> tuple[float, float]: + return ( + round( + point[0] * math.cos(math.radians(360 - degrees)) + - point[1] * math.sin(math.radians(360 - degrees)) + + centroid[0], + 2, + ), + round( + point[1] * math.cos(math.radians(360 - degrees)) + + point[0] * math.sin(math.radians(360 - degrees)) + + centroid[1], + 2, + ), + ) + + def _compute_polygon_vertex(angle: float) -> tuple[float, float]: + start_point = [polygon_radius, 0] + return _apply_rotation(start_point, angle) + + def _get_angles(n_sides: int, rotation: float) -> list[float]: + angles = [] + degrees = 360 / n_sides + # Start with the bottom left polygon vertex + current_angle = (270 - 0.5 * degrees) + rotation + for _ in range(n_sides): + angles.append(current_angle) + current_angle += degrees + if current_angle > 360: + current_angle -= 360 + return angles + + # 3. Variable Declarations + angles = _get_angles(n_sides, rotation) + + # 4. Compute Vertices + return [_compute_polygon_vertex(angle) for angle in angles] + + +def _color_diff( + color1: float | tuple[int, ...], color2: float | tuple[int, ...] +) -> float: + """ + Uses 1-norm distance to calculate difference between two values. + """ + first = color1 if isinstance(color1, tuple) else (color1,) + second = color2 if isinstance(color2, tuple) else (color2,) + + return sum(abs(first[i] - second[i]) for i in range(len(second))) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/ImageDraw2.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/ImageDraw2.py new file mode 100644 index 000000000..2c9e39b2c --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/ImageDraw2.py @@ -0,0 +1,244 @@ +# +# The Python Imaging Library +# $Id$ +# +# WCK-style drawing interface operations +# +# History: +# 2003-12-07 fl created +# 2005-05-15 fl updated; added to PIL as ImageDraw2 +# 2005-05-15 fl added text support +# 2005-05-20 fl added arc/chord/pieslice support +# +# Copyright (c) 2003-2005 by Secret Labs AB +# Copyright (c) 2003-2005 by Fredrik Lundh +# +# See the README file for information on usage and redistribution. +# + + +""" +(Experimental) WCK-style drawing interface operations + +.. seealso:: :py:mod:`PIL.ImageDraw` +""" + +from __future__ import annotations + +from typing import Any, AnyStr, BinaryIO + +from . import Image, ImageColor, ImageDraw, ImageFont, ImagePath +from ._typing import Coords, StrOrBytesPath + + +class Pen: + """Stores an outline color and width.""" + + def __init__(self, color: str, width: int = 1, opacity: int = 255) -> None: + self.color = ImageColor.getrgb(color) + self.width = width + + +class Brush: + """Stores a fill color""" + + def __init__(self, color: str, opacity: int = 255) -> None: + self.color = ImageColor.getrgb(color) + + +class Font: + """Stores a TrueType font and color""" + + def __init__( + self, color: str, file: StrOrBytesPath | BinaryIO, size: float = 12 + ) -> None: + # FIXME: add support for bitmap fonts + self.color = ImageColor.getrgb(color) + self.font = ImageFont.truetype(file, size) + + +class Draw: + """ + (Experimental) WCK-style drawing interface + """ + + def __init__( + self, + image: Image.Image | str, + size: tuple[int, int] | list[int] | None = None, + color: float | tuple[float, ...] | str | None = None, + ) -> None: + if isinstance(image, str): + if size is None: + msg = "If image argument is mode string, size must be a list or tuple" + raise ValueError(msg) + image = Image.new(image, size, color) + self.draw = ImageDraw.Draw(image) + self.image = image + self.transform: tuple[float, float, float, float, float, float] | None = None + + def flush(self) -> Image.Image: + return self.image + + def render( + self, + op: str, + xy: Coords, + pen: Pen | Brush | None, + brush: Brush | Pen | None = None, + **kwargs: Any, + ) -> None: + # handle color arguments + outline = fill = None + width = 1 + if isinstance(pen, Pen): + outline = pen.color + width = pen.width + elif isinstance(brush, Pen): + outline = brush.color + width = brush.width + if isinstance(brush, Brush): + fill = brush.color + elif isinstance(pen, Brush): + fill = pen.color + # handle transformation + if self.transform: + path = ImagePath.Path(xy) + path.transform(self.transform) + xy = path + # render the item + if op in ("arc", "line"): + kwargs.setdefault("fill", outline) + else: + kwargs.setdefault("fill", fill) + kwargs.setdefault("outline", outline) + if op == "line": + kwargs.setdefault("width", width) + getattr(self.draw, op)(xy, **kwargs) + + def settransform(self, offset: tuple[float, float]) -> None: + """Sets a transformation offset.""" + xoffset, yoffset = offset + self.transform = (1, 0, xoffset, 0, 1, yoffset) + + def arc( + self, + xy: Coords, + pen: Pen | Brush | None, + start: float, + end: float, + *options: Any, + ) -> None: + """ + Draws an arc (a portion of a circle outline) between the start and end + angles, inside the given bounding box. + + .. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.arc` + """ + self.render("arc", xy, pen, *options, start=start, end=end) + + def chord( + self, + xy: Coords, + pen: Pen | Brush | None, + start: float, + end: float, + *options: Any, + ) -> None: + """ + Same as :py:meth:`~PIL.ImageDraw2.Draw.arc`, but connects the end points + with a straight line. + + .. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.chord` + """ + self.render("chord", xy, pen, *options, start=start, end=end) + + def ellipse(self, xy: Coords, pen: Pen | Brush | None, *options: Any) -> None: + """ + Draws an ellipse inside the given bounding box. + + .. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.ellipse` + """ + self.render("ellipse", xy, pen, *options) + + def line(self, xy: Coords, pen: Pen | Brush | None, *options: Any) -> None: + """ + Draws a line between the coordinates in the ``xy`` list. + + .. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.line` + """ + self.render("line", xy, pen, *options) + + def pieslice( + self, + xy: Coords, + pen: Pen | Brush | None, + start: float, + end: float, + *options: Any, + ) -> None: + """ + Same as arc, but also draws straight lines between the end points and the + center of the bounding box. + + .. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.pieslice` + """ + self.render("pieslice", xy, pen, *options, start=start, end=end) + + def polygon(self, xy: Coords, pen: Pen | Brush | None, *options: Any) -> None: + """ + Draws a polygon. + + The polygon outline consists of straight lines between the given + coordinates, plus a straight line between the last and the first + coordinate. + + + .. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.polygon` + """ + self.render("polygon", xy, pen, *options) + + def rectangle(self, xy: Coords, pen: Pen | Brush | None, *options: Any) -> None: + """ + Draws a rectangle. + + .. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.rectangle` + """ + self.render("rectangle", xy, pen, *options) + + def text(self, xy: tuple[float, float], text: AnyStr, font: Font) -> None: + """ + Draws the string at the given position. + + .. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.text` + """ + if self.transform: + path = ImagePath.Path(xy) + path.transform(self.transform) + xy = path + self.draw.text(xy, text, font=font.font, fill=font.color) + + def textbbox( + self, xy: tuple[float, float], text: AnyStr, font: Font + ) -> tuple[float, float, float, float]: + """ + Returns bounding box (in pixels) of given text. + + :return: ``(left, top, right, bottom)`` bounding box + + .. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.textbbox` + """ + if self.transform: + path = ImagePath.Path(xy) + path.transform(self.transform) + xy = path + return self.draw.textbbox(xy, text, font=font.font) + + def textlength(self, text: AnyStr, font: Font) -> float: + """ + Returns length (in pixels) of given text. + This is the amount by which following text should be offset. + + .. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.textlength` + """ + return self.draw.textlength(text, font=font.font) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/ImageEnhance.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/ImageEnhance.py new file mode 100644 index 000000000..0e7e6dd8a --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/ImageEnhance.py @@ -0,0 +1,113 @@ +# +# The Python Imaging Library. +# $Id$ +# +# image enhancement classes +# +# For a background, see "Image Processing By Interpolation and +# Extrapolation", Paul Haeberli and Douglas Voorhies. Available +# at http://www.graficaobscura.com/interp/index.html +# +# History: +# 1996-03-23 fl Created +# 2009-06-16 fl Fixed mean calculation +# +# Copyright (c) Secret Labs AB 1997. +# Copyright (c) Fredrik Lundh 1996. +# +# See the README file for information on usage and redistribution. +# +from __future__ import annotations + +from . import Image, ImageFilter, ImageStat + + +class _Enhance: + image: Image.Image + degenerate: Image.Image + + def enhance(self, factor: float) -> Image.Image: + """ + Returns an enhanced image. + + :param factor: A floating point value controlling the enhancement. + Factor 1.0 always returns a copy of the original image, + lower factors mean less color (brightness, contrast, + etc), and higher values more. There are no restrictions + on this value. + :rtype: :py:class:`~PIL.Image.Image` + """ + return Image.blend(self.degenerate, self.image, factor) + + +class Color(_Enhance): + """Adjust image color balance. + + This class can be used to adjust the colour balance of an image, in + a manner similar to the controls on a colour TV set. An enhancement + factor of 0.0 gives a black and white image. A factor of 1.0 gives + the original image. + """ + + def __init__(self, image: Image.Image) -> None: + self.image = image + self.intermediate_mode = "L" + if "A" in image.getbands(): + self.intermediate_mode = "LA" + + if self.intermediate_mode != image.mode: + image = image.convert(self.intermediate_mode).convert(image.mode) + self.degenerate = image + + +class Contrast(_Enhance): + """Adjust image contrast. + + This class can be used to control the contrast of an image, similar + to the contrast control on a TV set. An enhancement factor of 0.0 + gives a solid gray image. A factor of 1.0 gives the original image. + """ + + def __init__(self, image: Image.Image) -> None: + self.image = image + if image.mode != "L": + image = image.convert("L") + mean = int(ImageStat.Stat(image).mean[0] + 0.5) + self.degenerate = Image.new("L", image.size, mean) + if self.degenerate.mode != self.image.mode: + self.degenerate = self.degenerate.convert(self.image.mode) + + if "A" in self.image.getbands(): + self.degenerate.putalpha(self.image.getchannel("A")) + + +class Brightness(_Enhance): + """Adjust image brightness. + + This class can be used to control the brightness of an image. An + enhancement factor of 0.0 gives a black image. A factor of 1.0 gives the + original image. + """ + + def __init__(self, image: Image.Image) -> None: + self.image = image + self.degenerate = Image.new(image.mode, image.size, 0) + + if "A" in image.getbands(): + self.degenerate.putalpha(image.getchannel("A")) + + +class Sharpness(_Enhance): + """Adjust image sharpness. + + This class can be used to adjust the sharpness of an image. An + enhancement factor of 0.0 gives a blurred image, a factor of 1.0 gives the + original image, and a factor of 2.0 gives a sharpened image. + """ + + def __init__(self, image: Image.Image) -> None: + self.image = image + self.degenerate = image.filter(ImageFilter.SMOOTH) + + if "A" in image.getbands(): + self.degenerate.putalpha(image.getchannel("A")) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/ImageFile.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/ImageFile.py new file mode 100644 index 000000000..c70d93f3c --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/ImageFile.py @@ -0,0 +1,935 @@ +# +# The Python Imaging Library. +# $Id$ +# +# base class for image file handlers +# +# history: +# 1995-09-09 fl Created +# 1996-03-11 fl Fixed load mechanism. +# 1996-04-15 fl Added pcx/xbm decoders. +# 1996-04-30 fl Added encoders. +# 1996-12-14 fl Added load helpers +# 1997-01-11 fl Use encode_to_file where possible +# 1997-08-27 fl Flush output in _save +# 1998-03-05 fl Use memory mapping for some modes +# 1999-02-04 fl Use memory mapping also for "I;16" and "I;16B" +# 1999-05-31 fl Added image parser +# 2000-10-12 fl Set readonly flag on memory-mapped images +# 2002-03-20 fl Use better messages for common decoder errors +# 2003-04-21 fl Fall back on mmap/map_buffer if map is not available +# 2003-10-30 fl Added StubImageFile class +# 2004-02-25 fl Made incremental parser more robust +# +# Copyright (c) 1997-2004 by Secret Labs AB +# Copyright (c) 1995-2004 by Fredrik Lundh +# +# See the README file for information on usage and redistribution. +# +from __future__ import annotations + +import abc +import io +import itertools +import logging +import os +import struct +from typing import IO, Any, NamedTuple, cast + +from . import ExifTags, Image +from ._util import DeferredError, is_path + +TYPE_CHECKING = False +if TYPE_CHECKING: + from ._typing import StrOrBytesPath + +logger = logging.getLogger(__name__) + +MAXBLOCK = 65536 +""" +By default, Pillow processes image data in blocks. This helps to prevent excessive use +of resources. Codecs may disable this behaviour with ``_pulls_fd`` or ``_pushes_fd``. + +When reading an image, this is the number of bytes to read at once. + +When writing an image, this is the number of bytes to write at once. +If the image width times 4 is greater, then that will be used instead. +Plugins may also set a greater number. + +User code may set this to another number. +""" + +SAFEBLOCK = 1024 * 1024 + +LOAD_TRUNCATED_IMAGES = False +"""Whether or not to load truncated image files. User code may change this.""" + +ERRORS = { + -1: "image buffer overrun error", + -2: "decoding error", + -3: "unknown error", + -8: "bad configuration", + -9: "out of memory error", +} +""" +Dict of known error codes returned from :meth:`.PyDecoder.decode`, +:meth:`.PyEncoder.encode` :meth:`.PyEncoder.encode_to_pyfd` and +:meth:`.PyEncoder.encode_to_file`. +""" + + +# +# -------------------------------------------------------------------- +# Helpers + + +def _get_oserror(error: int, *, encoder: bool) -> OSError: + try: + msg = Image.core.getcodecstatus(error) + except AttributeError: + msg = ERRORS.get(error) + if not msg: + msg = f"{'encoder' if encoder else 'decoder'} error {error}" + msg += f" when {'writing' if encoder else 'reading'} image file" + return OSError(msg) + + +def _tilesort(t: _Tile) -> int: + # sort on offset + return t[2] + + +class _Tile(NamedTuple): + codec_name: str + extents: tuple[int, int, int, int] | None + offset: int = 0 + args: tuple[Any, ...] | str | None = None + + +# +# -------------------------------------------------------------------- +# ImageFile base class + + +class ImageFile(Image.Image): + """Base class for image file format handlers.""" + + def __init__( + self, fp: StrOrBytesPath | IO[bytes], filename: str | bytes | None = None + ) -> None: + super().__init__() + + self._min_frame = 0 + + self.custom_mimetype: str | None = None + + self.tile: list[_Tile] = [] + """ A list of tile descriptors """ + + self.readonly = 1 # until we know better + + self.decoderconfig: tuple[Any, ...] = () + self.decodermaxblock = MAXBLOCK + + self.fp: IO[bytes] | None + self._fp: IO[bytes] | DeferredError + if is_path(fp): + # filename + self.fp = open(fp, "rb") + self.filename = os.fspath(fp) + self._exclusive_fp = True + else: + # stream + self.fp = cast(IO[bytes], fp) + self.filename = filename if filename is not None else "" + # can be overridden + self._exclusive_fp = False + + try: + try: + self._open() + + if isinstance(self, StubImageFile): + if loader := self._load(): + loader.open(self) + except ( + IndexError, # end of data + TypeError, # end of data (ord) + KeyError, # unsupported mode + EOFError, # got header but not the first frame + struct.error, + ) as v: + raise SyntaxError(v) from v + + if not self.mode or self.size[0] <= 0 or self.size[1] <= 0: + msg = "not identified by this driver" + raise SyntaxError(msg) + except BaseException: + # close the file only if we have opened it this constructor + if self._exclusive_fp: + self.fp.close() + raise + + def _open(self) -> None: + pass + + # Context manager support + def __enter__(self) -> ImageFile: + return self + + def _close_fp(self) -> None: + if getattr(self, "_fp", False) and not isinstance(self._fp, DeferredError): + if self._fp != self.fp: + self._fp.close() + self._fp = DeferredError(ValueError("Operation on closed image")) + if self.fp: + self.fp.close() + + def __exit__(self, *args: object) -> None: + if getattr(self, "_exclusive_fp", False): + self._close_fp() + self.fp = None + + def close(self) -> None: + """ + Closes the file pointer, if possible. + + This operation will destroy the image core and release its memory. + The image data will be unusable afterward. + + This function is required to close images that have multiple frames or + have not had their file read and closed by the + :py:meth:`~PIL.Image.Image.load` method. See :ref:`file-handling` for + more information. + """ + try: + self._close_fp() + self.fp = None + except Exception as msg: + logger.debug("Error closing: %s", msg) + + super().close() + + def get_child_images(self) -> list[ImageFile]: + child_images = [] + exif = self.getexif() + ifds = [] + if ExifTags.Base.SubIFDs in exif: + subifd_offsets = exif[ExifTags.Base.SubIFDs] + if subifd_offsets: + if not isinstance(subifd_offsets, tuple): + subifd_offsets = (subifd_offsets,) + ifds = [ + (exif._get_ifd_dict(subifd_offset), subifd_offset) + for subifd_offset in subifd_offsets + ] + ifd1 = exif.get_ifd(ExifTags.IFD.IFD1) + if ifd1 and ifd1.get(ExifTags.Base.JpegIFOffset): + assert exif._info is not None + ifds.append((ifd1, exif._info.next)) + + offset = None + for ifd, ifd_offset in ifds: + assert self.fp is not None + current_offset = self.fp.tell() + if offset is None: + offset = current_offset + + fp = self.fp + if ifd is not None: + thumbnail_offset = ifd.get(ExifTags.Base.JpegIFOffset) + if thumbnail_offset is not None: + thumbnail_offset += getattr(self, "_exif_offset", 0) + self.fp.seek(thumbnail_offset) + + length = ifd.get(ExifTags.Base.JpegIFByteCount) + assert isinstance(length, int) + data = self.fp.read(length) + fp = io.BytesIO(data) + + with Image.open(fp) as im: + from . import TiffImagePlugin + + if thumbnail_offset is None and isinstance( + im, TiffImagePlugin.TiffImageFile + ): + im._frame_pos = [ifd_offset] + im._seek(0) + im.load() + child_images.append(im) + + if offset is not None: + assert self.fp is not None + self.fp.seek(offset) + return child_images + + def get_format_mimetype(self) -> str | None: + if self.custom_mimetype: + return self.custom_mimetype + if self.format is not None: + return Image.MIME.get(self.format.upper()) + return None + + def __getstate__(self) -> list[Any]: + return super().__getstate__() + [self.filename] + + def __setstate__(self, state: list[Any]) -> None: + self.tile = [] + if len(state) > 5: + self.filename = state[5] + super().__setstate__(state) + + def verify(self) -> None: + """Check file integrity""" + + # raise exception if something's wrong. must be called + # directly after open, and closes file when finished. + if self._exclusive_fp and self.fp: + self.fp.close() + self.fp = None + + def load(self) -> Image.core.PixelAccess | None: + """Load image data based on tile list""" + + if not self.tile and self._im is None: + msg = "cannot load this image" + raise OSError(msg) + + pixel = Image.Image.load(self) + if not self.tile: + return pixel + + self.map: mmap.mmap | None = None + use_mmap = self.filename and len(self.tile) == 1 + + assert self.fp is not None + readonly = 0 + + # look for read/seek overrides + if hasattr(self, "load_read"): + read = self.load_read + # don't use mmap if there are custom read/seek functions + use_mmap = False + else: + read = self.fp.read + + if hasattr(self, "load_seek"): + seek = self.load_seek + use_mmap = False + else: + seek = self.fp.seek + + if use_mmap: + # try memory mapping + decoder_name, extents, offset, args = self.tile[0] + if isinstance(args, str): + args = (args, 0, 1) + if ( + decoder_name == "raw" + and isinstance(args, tuple) + and len(args) >= 3 + and args[0] == self.mode + and args[0] in Image._MAPMODES + ): + if offset < 0: + msg = "Tile offset cannot be negative" + raise ValueError(msg) + try: + # use mmap, if possible + import mmap + + with open(self.filename) as fp: + self.map = mmap.mmap(fp.fileno(), 0, access=mmap.ACCESS_READ) + if offset + self.size[1] * args[1] > self.map.size(): + msg = "buffer is not large enough" + raise OSError(msg) + self.im = Image.core.map_buffer( + self.map, self.size, decoder_name, offset, args + ) + readonly = 1 + # After trashing self.im, + # we might need to reload the palette data. + if self.palette: + self.palette.dirty = 1 + except (AttributeError, OSError, ImportError): + self.map = None + + self.load_prepare() + err_code = -3 # initialize to unknown error + if not self.map: + # sort tiles in file order + self.tile.sort(key=_tilesort) + + # FIXME: This is a hack to handle TIFF's JpegTables tag. + prefix = getattr(self, "tile_prefix", b"") + + # Remove consecutive duplicates that only differ by their offset + self.tile = [ + list(tiles)[-1] + for _, tiles in itertools.groupby( + self.tile, lambda tile: (tile[0], tile[1], tile[3]) + ) + ] + for i, (decoder_name, extents, offset, args) in enumerate(self.tile): + seek(offset) + decoder = Image._getdecoder( + self.mode, decoder_name, args, self.decoderconfig + ) + try: + decoder.setimage(self.im, extents) + if decoder.pulls_fd: + decoder.setfd(self.fp) + err_code = decoder.decode(b"")[1] + else: + b = prefix + while True: + read_bytes = self.decodermaxblock + if i + 1 < len(self.tile): + next_offset = self.tile[i + 1].offset + if next_offset > offset: + read_bytes = next_offset - offset + try: + s = read(read_bytes) + except (IndexError, struct.error) as e: + # truncated png/gif + if LOAD_TRUNCATED_IMAGES: + break + else: + msg = "image file is truncated" + raise OSError(msg) from e + + if not s: # truncated jpeg + if LOAD_TRUNCATED_IMAGES: + break + else: + msg = ( + "image file is truncated " + f"({len(b)} bytes not processed)" + ) + raise OSError(msg) + + b = b + s + n, err_code = decoder.decode(b) + if n < 0: + break + b = b[n:] + finally: + # Need to cleanup here to prevent leaks + decoder.cleanup() + + self.tile = [] + self.readonly = readonly + + self.load_end() + + if self._exclusive_fp and self._close_exclusive_fp_after_loading: + self.fp.close() + self.fp = None + + if not self.map and not LOAD_TRUNCATED_IMAGES and err_code < 0: + # still raised if decoder fails to return anything + raise _get_oserror(err_code, encoder=False) + + return Image.Image.load(self) + + def load_prepare(self) -> None: + # create image memory if necessary + if self._im is None: + self.im = Image.core.new(self.mode, self.size) + # create palette (optional) + if self.mode == "P": + Image.Image.load(self) + + def load_end(self) -> None: + # may be overridden + pass + + # may be defined for contained formats + # def load_seek(self, pos: int) -> None: + # pass + + # may be defined for blocked formats (e.g. PNG) + # def load_read(self, read_bytes: int) -> bytes: + # pass + + def _seek_check(self, frame: int) -> bool: + if ( + frame < self._min_frame + # Only check upper limit on frames if additional seek operations + # are not required to do so + or ( + not (hasattr(self, "_n_frames") and self._n_frames is None) + and frame >= getattr(self, "n_frames") + self._min_frame + ) + ): + msg = "attempt to seek outside sequence" + raise EOFError(msg) + + return self.tell() != frame + + +class StubHandler(abc.ABC): + def open(self, im: StubImageFile) -> None: + pass + + @abc.abstractmethod + def load(self, im: StubImageFile) -> Image.Image: + pass + + +class StubImageFile(ImageFile, metaclass=abc.ABCMeta): + """ + Base class for stub image loaders. + + A stub loader is an image loader that can identify files of a + certain format, but relies on external code to load the file. + """ + + @abc.abstractmethod + def _open(self) -> None: + pass + + def load(self) -> Image.core.PixelAccess | None: + loader = self._load() + if loader is None: + msg = f"cannot find loader for this {self.format} file" + raise OSError(msg) + image = loader.load(self) + assert image is not None + # become the other object (!) + self.__class__ = image.__class__ # type: ignore[assignment] + self.__dict__ = image.__dict__ + return image.load() + + @abc.abstractmethod + def _load(self) -> StubHandler | None: + """(Hook) Find actual image loader.""" + pass + + +class Parser: + """ + Incremental image parser. This class implements the standard + feed/close consumer interface. + """ + + incremental = None + image: Image.Image | None = None + data: bytes | None = None + decoder: Image.core.ImagingDecoder | PyDecoder | None = None + offset = 0 + finished = 0 + + def reset(self) -> None: + """ + (Consumer) Reset the parser. Note that you can only call this + method immediately after you've created a parser; parser + instances cannot be reused. + """ + assert self.data is None, "cannot reuse parsers" + + def feed(self, data: bytes) -> None: + """ + (Consumer) Feed data to the parser. + + :param data: A string buffer. + :exception OSError: If the parser failed to parse the image file. + """ + # collect data + + if self.finished: + return + + if self.data is None: + self.data = data + else: + self.data = self.data + data + + # parse what we have + if self.decoder: + if self.offset > 0: + # skip header + skip = min(len(self.data), self.offset) + self.data = self.data[skip:] + self.offset = self.offset - skip + if self.offset > 0 or not self.data: + return + + n, e = self.decoder.decode(self.data) + + if n < 0: + # end of stream + self.data = None + self.finished = 1 + if e < 0: + # decoding error + self.image = None + raise _get_oserror(e, encoder=False) + else: + # end of image + return + self.data = self.data[n:] + + elif self.image: + # if we end up here with no decoder, this file cannot + # be incrementally parsed. wait until we've gotten all + # available data + pass + + else: + # attempt to open this file + try: + with io.BytesIO(self.data) as fp: + im = Image.open(fp) + except OSError: + pass # not enough data + else: + flag = hasattr(im, "load_seek") or hasattr(im, "load_read") + if not flag and len(im.tile) == 1: + # initialize decoder + im.load_prepare() + d, e, o, a = im.tile[0] + im.tile = [] + self.decoder = Image._getdecoder(im.mode, d, a, im.decoderconfig) + self.decoder.setimage(im.im, e) + + # calculate decoder offset + self.offset = o + if self.offset <= len(self.data): + self.data = self.data[self.offset :] + self.offset = 0 + + self.image = im + + def __enter__(self) -> Parser: + return self + + def __exit__(self, *args: object) -> None: + self.close() + + def close(self) -> Image.Image: + """ + (Consumer) Close the stream. + + :returns: An image object. + :exception OSError: If the parser failed to parse the image file either + because it cannot be identified or cannot be + decoded. + """ + # finish decoding + if self.decoder: + # get rid of what's left in the buffers + self.feed(b"") + self.data = self.decoder = None + if not self.finished: + msg = "image was incomplete" + raise OSError(msg) + if not self.image: + msg = "cannot parse this image" + raise OSError(msg) + if self.data: + # incremental parsing not possible; reopen the file + # not that we have all data + with io.BytesIO(self.data) as fp: + try: + self.image = Image.open(fp) + finally: + self.image.load() + return self.image + + +# -------------------------------------------------------------------- + + +def _save(im: Image.Image, fp: IO[bytes], tile: list[_Tile], bufsize: int = 0) -> None: + """Helper to save image based on tile list + + :param im: Image object. + :param fp: File object. + :param tile: Tile list. + :param bufsize: Optional buffer size + """ + + im.load() + if not hasattr(im, "encoderconfig"): + im.encoderconfig = () + tile.sort(key=_tilesort) + # FIXME: make MAXBLOCK a configuration parameter + # It would be great if we could have the encoder specify what it needs + # But, it would need at least the image size in most cases. RawEncode is + # a tricky case. + bufsize = max(MAXBLOCK, bufsize, im.size[0] * 4) # see RawEncode.c + try: + fh = fp.fileno() + fp.flush() + _encode_tile(im, fp, tile, bufsize, fh) + except (AttributeError, io.UnsupportedOperation) as exc: + _encode_tile(im, fp, tile, bufsize, None, exc) + if hasattr(fp, "flush"): + fp.flush() + + +def _encode_tile( + im: Image.Image, + fp: IO[bytes], + tile: list[_Tile], + bufsize: int, + fh: int | None, + exc: BaseException | None = None, +) -> None: + for encoder_name, extents, offset, args in tile: + if offset > 0: + fp.seek(offset) + encoder = Image._getencoder(im.mode, encoder_name, args, im.encoderconfig) + try: + encoder.setimage(im.im, extents) + if encoder.pushes_fd: + encoder.setfd(fp) + errcode = encoder.encode_to_pyfd()[1] + else: + if exc: + # compress to Python file-compatible object + while True: + errcode, data = encoder.encode(bufsize)[1:] + fp.write(data) + if errcode: + break + else: + # slight speedup: compress to real file object + assert fh is not None + errcode = encoder.encode_to_file(fh, bufsize) + if errcode < 0: + raise _get_oserror(errcode, encoder=True) from exc + finally: + encoder.cleanup() + + +def _safe_read(fp: IO[bytes], size: int) -> bytes: + """ + Reads large blocks in a safe way. Unlike fp.read(n), this function + doesn't trust the user. If the requested size is larger than + SAFEBLOCK, the file is read block by block. + + :param fp: File handle. Must implement a read method. + :param size: Number of bytes to read. + :returns: A string containing size bytes of data. + + Raises an OSError if the file is truncated and the read cannot be completed + + """ + if size <= 0: + return b"" + if size <= SAFEBLOCK: + data = fp.read(size) + if len(data) < size: + msg = "Truncated File Read" + raise OSError(msg) + return data + blocks: list[bytes] = [] + remaining_size = size + while remaining_size > 0: + block = fp.read(min(remaining_size, SAFEBLOCK)) + if not block: + break + blocks.append(block) + remaining_size -= len(block) + if sum(len(block) for block in blocks) < size: + msg = "Truncated File Read" + raise OSError(msg) + return b"".join(blocks) + + +class PyCodecState: + def __init__(self) -> None: + self.xsize = 0 + self.ysize = 0 + self.xoff = 0 + self.yoff = 0 + + def extents(self) -> tuple[int, int, int, int]: + return self.xoff, self.yoff, self.xoff + self.xsize, self.yoff + self.ysize + + +class PyCodec: + fd: IO[bytes] | None + + def __init__(self, mode: str, *args: Any) -> None: + self.im: Image.core.ImagingCore | None = None + self.state = PyCodecState() + self.fd = None + self.mode = mode + self.init(args) + + def init(self, args: tuple[Any, ...]) -> None: + """ + Override to perform codec specific initialization + + :param args: Tuple of arg items from the tile entry + :returns: None + """ + self.args = args + + def cleanup(self) -> None: + """ + Override to perform codec specific cleanup + + :returns: None + """ + pass + + def setfd(self, fd: IO[bytes]) -> None: + """ + Called from ImageFile to set the Python file-like object + + :param fd: A Python file-like object + :returns: None + """ + self.fd = fd + + def setimage( + self, + im: Image.core.ImagingCore, + extents: tuple[int, int, int, int] | None = None, + ) -> None: + """ + Called from ImageFile to set the core output image for the codec + + :param im: A core image object + :param extents: a 4 tuple of (x0, y0, x1, y1) defining the rectangle + for this tile + :returns: None + """ + + # following c code + self.im = im + + if extents: + x0, y0, x1, y1 = extents + + if x0 < 0 or y0 < 0 or x1 > self.im.size[0] or y1 > self.im.size[1]: + msg = "Tile cannot extend outside image" + raise ValueError(msg) + + self.state.xoff = x0 + self.state.yoff = y0 + self.state.xsize = x1 - x0 + self.state.ysize = y1 - y0 + else: + self.state.xsize, self.state.ysize = self.im.size + + if self.state.xsize <= 0 or self.state.ysize <= 0: + msg = "Size must be positive" + raise ValueError(msg) + + +class PyDecoder(PyCodec): + """ + Python implementation of a format decoder. Override this class and + add the decoding logic in the :meth:`decode` method. + + See :ref:`Writing Your Own File Codec in Python` + """ + + _pulls_fd = False + + @property + def pulls_fd(self) -> bool: + return self._pulls_fd + + def decode(self, buffer: bytes | Image.SupportsArrayInterface) -> tuple[int, int]: + """ + Override to perform the decoding process. + + :param buffer: A bytes object with the data to be decoded. + :returns: A tuple of ``(bytes consumed, errcode)``. + If finished with decoding return -1 for the bytes consumed. + Err codes are from :data:`.ImageFile.ERRORS`. + """ + msg = "unavailable in base decoder" + raise NotImplementedError(msg) + + def set_as_raw( + self, data: bytes, rawmode: str | None = None, extra: tuple[Any, ...] = () + ) -> None: + """ + Convenience method to set the internal image from a stream of raw data + + :param data: Bytes to be set + :param rawmode: The rawmode to be used for the decoder. + If not specified, it will default to the mode of the image + :param extra: Extra arguments for the decoder. + :returns: None + """ + + if not rawmode: + rawmode = self.mode + d = Image._getdecoder(self.mode, "raw", rawmode, extra) + assert self.im is not None + d.setimage(self.im, self.state.extents()) + s = d.decode(data) + + if s[0] >= 0: + msg = "not enough image data" + raise ValueError(msg) + if s[1] != 0: + msg = "cannot decode image data" + raise ValueError(msg) + + +class PyEncoder(PyCodec): + """ + Python implementation of a format encoder. Override this class and + add the decoding logic in the :meth:`encode` method. + + See :ref:`Writing Your Own File Codec in Python` + """ + + _pushes_fd = False + + @property + def pushes_fd(self) -> bool: + return self._pushes_fd + + def encode(self, bufsize: int) -> tuple[int, int, bytes]: + """ + Override to perform the encoding process. + + :param bufsize: Buffer size. + :returns: A tuple of ``(bytes encoded, errcode, bytes)``. + If finished with encoding return 1 for the error code. + Err codes are from :data:`.ImageFile.ERRORS`. + """ + msg = "unavailable in base encoder" + raise NotImplementedError(msg) + + def encode_to_pyfd(self) -> tuple[int, int]: + """ + If ``pushes_fd`` is ``True``, then this method will be used, + and ``encode()`` will only be called once. + + :returns: A tuple of ``(bytes consumed, errcode)``. + Err codes are from :data:`.ImageFile.ERRORS`. + """ + if not self.pushes_fd: + return 0, -8 # bad configuration + bytes_consumed, errcode, data = self.encode(0) + if data: + assert self.fd is not None + self.fd.write(data) + return bytes_consumed, errcode + + def encode_to_file(self, fh: int, bufsize: int) -> int: + """ + :param fh: File handle. + :param bufsize: Buffer size. + + :returns: If finished successfully, return 0. + Otherwise, return an error code. Err codes are from + :data:`.ImageFile.ERRORS`. + """ + errcode = 0 + while errcode == 0: + status, errcode, buf = self.encode(bufsize) + if status > 0: + os.write(fh, buf[status:]) + return errcode diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/ImageFilter.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/ImageFilter.py new file mode 100644 index 000000000..9326eeeda --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/ImageFilter.py @@ -0,0 +1,607 @@ +# +# The Python Imaging Library. +# $Id$ +# +# standard filters +# +# History: +# 1995-11-27 fl Created +# 2002-06-08 fl Added rank and mode filters +# 2003-09-15 fl Fixed rank calculation in rank filter; added expand call +# +# Copyright (c) 1997-2003 by Secret Labs AB. +# Copyright (c) 1995-2002 by Fredrik Lundh. +# +# See the README file for information on usage and redistribution. +# +from __future__ import annotations + +import abc +import functools +from collections.abc import Sequence +from typing import cast + +TYPE_CHECKING = False +if TYPE_CHECKING: + from collections.abc import Callable + from types import ModuleType + from typing import Any + + from . import _imaging + from ._typing import NumpyArray + + +class Filter(abc.ABC): + @abc.abstractmethod + def filter(self, image: _imaging.ImagingCore) -> _imaging.ImagingCore: + pass + + +class MultibandFilter(Filter): + pass + + +class BuiltinFilter(MultibandFilter): + filterargs: tuple[Any, ...] + + def filter(self, image: _imaging.ImagingCore) -> _imaging.ImagingCore: + if image.mode == "P": + msg = "cannot filter palette images" + raise ValueError(msg) + return image.filter(*self.filterargs) + + +class Kernel(BuiltinFilter): + """ + Create a convolution kernel. This only supports 3x3 and 5x5 integer and floating + point kernels. + + Kernels can only be applied to "L" and "RGB" images. + + :param size: Kernel size, given as (width, height). This must be (3,3) or (5,5). + :param kernel: A sequence containing kernel weights. The kernel will be flipped + vertically before being applied to the image. + :param scale: Scale factor. If given, the result for each pixel is divided by this + value. The default is the sum of the kernel weights. + :param offset: Offset. If given, this value is added to the result, after it has + been divided by the scale factor. + """ + + name = "Kernel" + + def __init__( + self, + size: tuple[int, int], + kernel: Sequence[float], + scale: float | None = None, + offset: float = 0, + ) -> None: + if scale is None: + # default scale is sum of kernel + scale = functools.reduce(lambda a, b: a + b, kernel) + if size[0] * size[1] != len(kernel): + msg = "not enough coefficients in kernel" + raise ValueError(msg) + self.filterargs = size, scale, offset, kernel + + +class RankFilter(Filter): + """ + Create a rank filter. The rank filter sorts all pixels in + a window of the given size, and returns the ``rank``'th value. + + :param size: The kernel size, in pixels. + :param rank: What pixel value to pick. Use 0 for a min filter, + ``size * size / 2`` for a median filter, ``size * size - 1`` + for a max filter, etc. + """ + + name = "Rank" + + def __init__(self, size: int, rank: int) -> None: + self.size = size + self.rank = rank + + def filter(self, image: _imaging.ImagingCore) -> _imaging.ImagingCore: + if image.mode == "P": + msg = "cannot filter palette images" + raise ValueError(msg) + image = image.expand(self.size // 2, self.size // 2) + return image.rankfilter(self.size, self.rank) + + +class MedianFilter(RankFilter): + """ + Create a median filter. Picks the median pixel value in a window with the + given size. + + :param size: The kernel size, in pixels. + """ + + name = "Median" + + def __init__(self, size: int = 3) -> None: + self.size = size + self.rank = size * size // 2 + + +class MinFilter(RankFilter): + """ + Create a min filter. Picks the lowest pixel value in a window with the + given size. + + :param size: The kernel size, in pixels. + """ + + name = "Min" + + def __init__(self, size: int = 3) -> None: + self.size = size + self.rank = 0 + + +class MaxFilter(RankFilter): + """ + Create a max filter. Picks the largest pixel value in a window with the + given size. + + :param size: The kernel size, in pixels. + """ + + name = "Max" + + def __init__(self, size: int = 3) -> None: + self.size = size + self.rank = size * size - 1 + + +class ModeFilter(Filter): + """ + Create a mode filter. Picks the most frequent pixel value in a box with the + given size. Pixel values that occur only once or twice are ignored; if no + pixel value occurs more than twice, the original pixel value is preserved. + + :param size: The kernel size, in pixels. + """ + + name = "Mode" + + def __init__(self, size: int = 3) -> None: + self.size = size + + def filter(self, image: _imaging.ImagingCore) -> _imaging.ImagingCore: + return image.modefilter(self.size) + + +class GaussianBlur(MultibandFilter): + """Blurs the image with a sequence of extended box filters, which + approximates a Gaussian kernel. For details on accuracy see + + + :param radius: Standard deviation of the Gaussian kernel. Either a sequence of two + numbers for x and y, or a single number for both. + """ + + name = "GaussianBlur" + + def __init__(self, radius: float | Sequence[float] = 2) -> None: + self.radius = radius + + def filter(self, image: _imaging.ImagingCore) -> _imaging.ImagingCore: + xy = self.radius + if isinstance(xy, (int, float)): + xy = (xy, xy) + if xy == (0, 0): + return image.copy() + return image.gaussian_blur(xy) + + +class BoxBlur(MultibandFilter): + """Blurs the image by setting each pixel to the average value of the pixels + in a square box extending radius pixels in each direction. + Supports float radius of arbitrary size. Uses an optimized implementation + which runs in linear time relative to the size of the image + for any radius value. + + :param radius: Size of the box in a direction. Either a sequence of two numbers for + x and y, or a single number for both. + + Radius 0 does not blur, returns an identical image. + Radius 1 takes 1 pixel in each direction, i.e. 9 pixels in total. + """ + + name = "BoxBlur" + + def __init__(self, radius: float | Sequence[float]) -> None: + xy = radius if isinstance(radius, (tuple, list)) else (radius, radius) + if xy[0] < 0 or xy[1] < 0: + msg = "radius must be >= 0" + raise ValueError(msg) + self.radius = radius + + def filter(self, image: _imaging.ImagingCore) -> _imaging.ImagingCore: + xy = self.radius + if isinstance(xy, (int, float)): + xy = (xy, xy) + if xy == (0, 0): + return image.copy() + return image.box_blur(xy) + + +class UnsharpMask(MultibandFilter): + """Unsharp mask filter. + + See Wikipedia's entry on `digital unsharp masking`_ for an explanation of + the parameters. + + :param radius: Blur Radius + :param percent: Unsharp strength, in percent + :param threshold: Threshold controls the minimum brightness change that + will be sharpened + + .. _digital unsharp masking: https://en.wikipedia.org/wiki/Unsharp_masking#Digital_unsharp_masking + + """ + + name = "UnsharpMask" + + def __init__( + self, radius: float = 2, percent: int = 150, threshold: int = 3 + ) -> None: + self.radius = radius + self.percent = percent + self.threshold = threshold + + def filter(self, image: _imaging.ImagingCore) -> _imaging.ImagingCore: + return image.unsharp_mask(self.radius, self.percent, self.threshold) + + +class BLUR(BuiltinFilter): + name = "Blur" + # fmt: off + filterargs = (5, 5), 16, 0, ( + 1, 1, 1, 1, 1, + 1, 0, 0, 0, 1, + 1, 0, 0, 0, 1, + 1, 0, 0, 0, 1, + 1, 1, 1, 1, 1, + ) + # fmt: on + + +class CONTOUR(BuiltinFilter): + name = "Contour" + # fmt: off + filterargs = (3, 3), 1, 255, ( + -1, -1, -1, + -1, 8, -1, + -1, -1, -1, + ) + # fmt: on + + +class DETAIL(BuiltinFilter): + name = "Detail" + # fmt: off + filterargs = (3, 3), 6, 0, ( + 0, -1, 0, + -1, 10, -1, + 0, -1, 0, + ) + # fmt: on + + +class EDGE_ENHANCE(BuiltinFilter): + name = "Edge-enhance" + # fmt: off + filterargs = (3, 3), 2, 0, ( + -1, -1, -1, + -1, 10, -1, + -1, -1, -1, + ) + # fmt: on + + +class EDGE_ENHANCE_MORE(BuiltinFilter): + name = "Edge-enhance More" + # fmt: off + filterargs = (3, 3), 1, 0, ( + -1, -1, -1, + -1, 9, -1, + -1, -1, -1, + ) + # fmt: on + + +class EMBOSS(BuiltinFilter): + name = "Emboss" + # fmt: off + filterargs = (3, 3), 1, 128, ( + -1, 0, 0, + 0, 1, 0, + 0, 0, 0, + ) + # fmt: on + + +class FIND_EDGES(BuiltinFilter): + name = "Find Edges" + # fmt: off + filterargs = (3, 3), 1, 0, ( + -1, -1, -1, + -1, 8, -1, + -1, -1, -1, + ) + # fmt: on + + +class SHARPEN(BuiltinFilter): + name = "Sharpen" + # fmt: off + filterargs = (3, 3), 16, 0, ( + -2, -2, -2, + -2, 32, -2, + -2, -2, -2, + ) + # fmt: on + + +class SMOOTH(BuiltinFilter): + name = "Smooth" + # fmt: off + filterargs = (3, 3), 13, 0, ( + 1, 1, 1, + 1, 5, 1, + 1, 1, 1, + ) + # fmt: on + + +class SMOOTH_MORE(BuiltinFilter): + name = "Smooth More" + # fmt: off + filterargs = (5, 5), 100, 0, ( + 1, 1, 1, 1, 1, + 1, 5, 5, 5, 1, + 1, 5, 44, 5, 1, + 1, 5, 5, 5, 1, + 1, 1, 1, 1, 1, + ) + # fmt: on + + +class Color3DLUT(MultibandFilter): + """Three-dimensional color lookup table. + + Transforms 3-channel pixels using the values of the channels as coordinates + in the 3D lookup table and interpolating the nearest elements. + + This method allows you to apply almost any color transformation + in constant time by using pre-calculated decimated tables. + + .. versionadded:: 5.2.0 + + :param size: Size of the table. One int or tuple of (int, int, int). + Minimal size in any dimension is 2, maximum is 65. + :param table: Flat lookup table. A list of ``channels * size**3`` + float elements or a list of ``size**3`` channels-sized + tuples with floats. Channels are changed first, + then first dimension, then second, then third. + Value 0.0 corresponds lowest value of output, 1.0 highest. + :param channels: Number of channels in the table. Could be 3 or 4. + Default is 3. + :param target_mode: A mode for the result image. Should have not less + than ``channels`` channels. Default is ``None``, + which means that mode wouldn't be changed. + """ + + name = "Color 3D LUT" + + def __init__( + self, + size: int | tuple[int, int, int], + table: Sequence[float] | Sequence[Sequence[int]] | NumpyArray, + channels: int = 3, + target_mode: str | None = None, + **kwargs: bool, + ) -> None: + if channels not in (3, 4): + msg = "Only 3 or 4 output channels are supported" + raise ValueError(msg) + self.size = size = self._check_size(size) + self.channels = channels + self.mode = target_mode + + # Hidden flag `_copy_table=False` could be used to avoid extra copying + # of the table if the table is specially made for the constructor. + copy_table = kwargs.get("_copy_table", True) + items = size[0] * size[1] * size[2] + wrong_size = False + + numpy: ModuleType | None = None + if hasattr(table, "shape"): + try: + import numpy + except ImportError: + pass + + if numpy and isinstance(table, numpy.ndarray): + numpy_table: NumpyArray = table + if copy_table: + numpy_table = numpy_table.copy() + + if numpy_table.shape in [ + (items * channels,), + (items, channels), + (size[2], size[1], size[0], channels), + ]: + table = numpy_table.reshape(items * channels) + else: + wrong_size = True + + else: + if copy_table: + table = list(table) + + # Convert to a flat list + if table and isinstance(table[0], (list, tuple)): + raw_table = cast(Sequence[Sequence[int]], table) + flat_table: list[int] = [] + for pixel in raw_table: + if len(pixel) != channels: + msg = ( + "The elements of the table should " + f"have a length of {channels}." + ) + raise ValueError(msg) + flat_table.extend(pixel) + table = flat_table + + if wrong_size or len(table) != items * channels: + msg = ( + "The table should have either channels * size**3 float items " + "or size**3 items of channels-sized tuples with floats. " + f"Table should be: {channels}x{size[0]}x{size[1]}x{size[2]}. " + f"Actual length: {len(table)}" + ) + raise ValueError(msg) + self.table = table + + @staticmethod + def _check_size(size: Any) -> tuple[int, int, int]: + try: + _, _, _ = size + except ValueError as e: + msg = "Size should be either an integer or a tuple of three integers." + raise ValueError(msg) from e + except TypeError: + size = (size, size, size) + size = tuple(int(x) for x in size) + for size_1d in size: + if not 2 <= size_1d <= 65: + msg = "Size should be in [2, 65] range." + raise ValueError(msg) + return size + + @classmethod + def generate( + cls, + size: int | tuple[int, int, int], + callback: Callable[[float, float, float], tuple[float, ...]], + channels: int = 3, + target_mode: str | None = None, + ) -> Color3DLUT: + """Generates new LUT using provided callback. + + :param size: Size of the table. Passed to the constructor. + :param callback: Function with three parameters which correspond + three color channels. Will be called ``size**3`` + times with values from 0.0 to 1.0 and should return + a tuple with ``channels`` elements. + :param channels: The number of channels which should return callback. + :param target_mode: Passed to the constructor of the resulting + lookup table. + """ + size_1d, size_2d, size_3d = cls._check_size(size) + if channels not in (3, 4): + msg = "Only 3 or 4 output channels are supported" + raise ValueError(msg) + + table: list[float] = [0] * (size_1d * size_2d * size_3d * channels) + idx_out = 0 + for b in range(size_3d): + for g in range(size_2d): + for r in range(size_1d): + table[idx_out : idx_out + channels] = callback( + r / (size_1d - 1), g / (size_2d - 1), b / (size_3d - 1) + ) + idx_out += channels + + return cls( + (size_1d, size_2d, size_3d), + table, + channels=channels, + target_mode=target_mode, + _copy_table=False, + ) + + def transform( + self, + callback: Callable[..., tuple[float, ...]], + with_normals: bool = False, + channels: int | None = None, + target_mode: str | None = None, + ) -> Color3DLUT: + """Transforms the table values using provided callback and returns + a new LUT with altered values. + + :param callback: A function which takes old lookup table values + and returns a new set of values. The number + of arguments which function should take is + ``self.channels`` or ``3 + self.channels`` + if ``with_normals`` flag is set. + Should return a tuple of ``self.channels`` or + ``channels`` elements if it is set. + :param with_normals: If true, ``callback`` will be called with + coordinates in the color cube as the first + three arguments. Otherwise, ``callback`` + will be called only with actual color values. + :param channels: The number of channels in the resulting lookup table. + :param target_mode: Passed to the constructor of the resulting + lookup table. + """ + if channels not in (None, 3, 4): + msg = "Only 3 or 4 output channels are supported" + raise ValueError(msg) + ch_in = self.channels + ch_out = channels or ch_in + size_1d, size_2d, size_3d = self.size + + table: list[float] = [0] * (size_1d * size_2d * size_3d * ch_out) + idx_in = 0 + idx_out = 0 + for b in range(size_3d): + for g in range(size_2d): + for r in range(size_1d): + values = self.table[idx_in : idx_in + ch_in] + if with_normals: + values = callback( + r / (size_1d - 1), + g / (size_2d - 1), + b / (size_3d - 1), + *values, + ) + else: + values = callback(*values) + table[idx_out : idx_out + ch_out] = values + idx_in += ch_in + idx_out += ch_out + + return type(self)( + self.size, + table, + channels=ch_out, + target_mode=target_mode or self.mode, + _copy_table=False, + ) + + def __repr__(self) -> str: + r = [ + f"{self.__class__.__name__} from {self.table.__class__.__name__}", + "size={:d}x{:d}x{:d}".format(*self.size), + f"channels={self.channels:d}", + ] + if self.mode: + r.append(f"target_mode={self.mode}") + return "<{}>".format(" ".join(r)) + + def filter(self, image: _imaging.ImagingCore) -> _imaging.ImagingCore: + from . import Image + + return image.color_lut_3d( + self.mode or image.mode, + Image.Resampling.BILINEAR, + self.channels, + self.size, + self.table, + ) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/ImageFont.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/ImageFont.py new file mode 100644 index 000000000..06ea0359c --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/ImageFont.py @@ -0,0 +1,1309 @@ +# +# The Python Imaging Library. +# $Id$ +# +# PIL raster font management +# +# History: +# 1996-08-07 fl created (experimental) +# 1997-08-25 fl minor adjustments to handle fonts from pilfont 0.3 +# 1999-02-06 fl rewrote most font management stuff in C +# 1999-03-17 fl take pth files into account in load_path (from Richard Jones) +# 2001-02-17 fl added freetype support +# 2001-05-09 fl added TransposedFont wrapper class +# 2002-03-04 fl make sure we have a "L" or "1" font +# 2002-12-04 fl skip non-directory entries in the system path +# 2003-04-29 fl add embedded default font +# 2003-09-27 fl added support for truetype charmap encodings +# +# Todo: +# Adapt to PILFONT2 format (16-bit fonts, compressed, single file) +# +# Copyright (c) 1997-2003 by Secret Labs AB +# Copyright (c) 1996-2003 by Fredrik Lundh +# +# See the README file for information on usage and redistribution. +# + +from __future__ import annotations + +import base64 +import os +import sys +import warnings +from enum import IntEnum +from io import BytesIO +from types import ModuleType +from typing import IO, Any, BinaryIO, TypedDict, cast + +from . import Image +from ._typing import StrOrBytesPath +from ._util import DeferredError, is_path + +TYPE_CHECKING = False +if TYPE_CHECKING: + from . import ImageFile + from ._imaging import ImagingFont + from ._imagingft import Font + + +class Axis(TypedDict): + minimum: int | None + default: int | None + maximum: int | None + name: bytes | None + + +class Layout(IntEnum): + BASIC = 0 + RAQM = 1 + + +MAX_STRING_LENGTH = 1_000_000 + + +core: ModuleType | DeferredError +try: + from . import _imagingft as core +except ImportError as ex: + core = DeferredError.new(ex) + + +def _string_length_check(text: str | bytes | bytearray) -> None: + if MAX_STRING_LENGTH is not None and len(text) > MAX_STRING_LENGTH: + msg = "too many characters in string" + raise ValueError(msg) + + +# FIXME: add support for pilfont2 format (see FontFile.py) + +# -------------------------------------------------------------------- +# Font metrics format: +# "PILfont" LF +# fontdescriptor LF +# (optional) key=value... LF +# "DATA" LF +# binary data: 256*10*2 bytes (dx, dy, dstbox, srcbox) +# +# To place a character, cut out srcbox and paste at dstbox, +# relative to the character position. Then move the character +# position according to dx, dy. +# -------------------------------------------------------------------- + + +class ImageFont: + """PIL font wrapper""" + + font: ImagingFont + + def _load_pilfont(self, filename: str) -> None: + with open(filename, "rb") as fp: + image: ImageFile.ImageFile | None = None + root = os.path.splitext(filename)[0] + + for ext in (".png", ".gif", ".pbm"): + if image: + image.close() + try: + fullname = root + ext + image = Image.open(fullname) + except Exception: + pass + else: + if image.mode in ("1", "L"): + break + else: + if image: + image.close() + + msg = f"cannot find glyph data file {root}.{{gif|pbm|png}}" + raise OSError(msg) + + self.file = fullname + + self._load_pilfont_data(fp, image) + image.close() + + def _load_pilfont_data(self, file: IO[bytes], image: Image.Image) -> None: + # check image + if image.mode not in ("1", "L"): + image.close() + + msg = "invalid font image mode" + raise TypeError(msg) + + # read PILfont header + if file.read(8) != b"PILfont\n": + image.close() + + msg = "Not a PILfont file" + raise SyntaxError(msg) + file.readline() + self.info = [] # FIXME: should be a dictionary + while True: + s = file.readline() + if not s or s == b"DATA\n": + break + self.info.append(s) + + # read PILfont metrics + data = file.read(256 * 20) + + self._load(image, data) + + def _load(self, image: Image.Image, data: bytes) -> None: + image.load() + + self.font = Image.core.font(image.im, data) + + def getmask( + self, text: str | bytes, mode: str = "", *args: Any, **kwargs: Any + ) -> Image.core.ImagingCore: + """ + Create a bitmap for the text. + + If the font uses antialiasing, the bitmap should have mode ``L`` and use a + maximum value of 255. Otherwise, it should have mode ``1``. + + :param text: Text to render. + :param mode: Used by some graphics drivers to indicate what mode the + driver prefers; if empty, the renderer may return either + mode. Note that the mode is always a string, to simplify + C-level implementations. + + .. versionadded:: 1.1.5 + + :return: An internal PIL storage memory instance as defined by the + :py:mod:`PIL.Image.core` interface module. + """ + _string_length_check(text) + Image._decompression_bomb_check(self.font.getsize(text)) + return self.font.getmask(text, mode) + + def getbbox( + self, text: str | bytes | bytearray, *args: Any, **kwargs: Any + ) -> tuple[int, int, int, int]: + """ + Returns bounding box (in pixels) of given text. + + .. versionadded:: 9.2.0 + + :param text: Text to render. + + :return: ``(left, top, right, bottom)`` bounding box + """ + _string_length_check(text) + width, height = self.font.getsize(text) + return 0, 0, width, height + + def getlength( + self, text: str | bytes | bytearray, *args: Any, **kwargs: Any + ) -> int: + """ + Returns length (in pixels) of given text. + This is the amount by which following text should be offset. + + .. versionadded:: 9.2.0 + """ + _string_length_check(text) + width, height = self.font.getsize(text) + return width + + +## +# Wrapper for FreeType fonts. Application code should use the +# truetype factory function to create font objects. + + +class FreeTypeFont: + """FreeType font wrapper (requires _imagingft service)""" + + font: Font + font_bytes: bytes + + def __init__( + self, + font: StrOrBytesPath | BinaryIO, + size: float = 10, + index: int = 0, + encoding: str = "", + layout_engine: Layout | None = None, + ) -> None: + # FIXME: use service provider instead + + if isinstance(core, DeferredError): + raise core.ex + + if size <= 0: + msg = f"font size must be greater than 0, not {size}" + raise ValueError(msg) + + self.path = font + self.size = size + self.index = index + self.encoding = encoding + + if layout_engine not in (Layout.BASIC, Layout.RAQM): + layout_engine = Layout.BASIC + if core.HAVE_RAQM: + layout_engine = Layout.RAQM + elif layout_engine == Layout.RAQM and not core.HAVE_RAQM: + warnings.warn( + "Raqm layout was requested, but Raqm is not available. " + "Falling back to basic layout." + ) + layout_engine = Layout.BASIC + + self.layout_engine = layout_engine + + def load_from_bytes(f: IO[bytes]) -> None: + self.font_bytes = f.read() + self.font = core.getfont( + "", size, index, encoding, self.font_bytes, layout_engine + ) + + if is_path(font): + font = os.fspath(font) + if sys.platform == "win32": + font_bytes_path = font if isinstance(font, bytes) else font.encode() + try: + font_bytes_path.decode("ascii") + except UnicodeDecodeError: + # FreeType cannot load fonts with non-ASCII characters on Windows + # So load it into memory first + with open(font, "rb") as f: + load_from_bytes(f) + return + self.font = core.getfont( + font, size, index, encoding, layout_engine=layout_engine + ) + else: + load_from_bytes(cast(IO[bytes], font)) + + def __getstate__(self) -> list[Any]: + return [self.path, self.size, self.index, self.encoding, self.layout_engine] + + def __setstate__(self, state: list[Any]) -> None: + path, size, index, encoding, layout_engine = state + FreeTypeFont.__init__(self, path, size, index, encoding, layout_engine) + + def getname(self) -> tuple[str | None, str | None]: + """ + :return: A tuple of the font family (e.g. Helvetica) and the font style + (e.g. Bold) + """ + return self.font.family, self.font.style + + def getmetrics(self) -> tuple[int, int]: + """ + :return: A tuple of the font ascent (the distance from the baseline to + the highest outline point) and descent (the distance from the + baseline to the lowest outline point, a negative value) + """ + return self.font.ascent, self.font.descent + + def getlength( + self, + text: str | bytes, + mode: str = "", + direction: str | None = None, + features: list[str] | None = None, + language: str | None = None, + ) -> float: + """ + Returns length (in pixels with 1/64 precision) of given text when rendered + in font with provided direction, features, and language. + + This is the amount by which following text should be offset. + Text bounding box may extend past the length in some fonts, + e.g. when using italics or accents. + + The result is returned as a float; it is a whole number if using basic layout. + + Note that the sum of two lengths may not equal the length of a concatenated + string due to kerning. If you need to adjust for kerning, include the following + character and subtract its length. + + For example, instead of :: + + hello = font.getlength("Hello") + world = font.getlength("World") + hello_world = hello + world # not adjusted for kerning + assert hello_world == font.getlength("HelloWorld") # may fail + + use :: + + hello = font.getlength("HelloW") - font.getlength("W") # adjusted for kerning + world = font.getlength("World") + hello_world = hello + world # adjusted for kerning + assert hello_world == font.getlength("HelloWorld") # True + + or disable kerning with (requires libraqm) :: + + hello = draw.textlength("Hello", font, features=["-kern"]) + world = draw.textlength("World", font, features=["-kern"]) + hello_world = hello + world # kerning is disabled, no need to adjust + assert hello_world == draw.textlength("HelloWorld", font, features=["-kern"]) + + .. versionadded:: 8.0.0 + + :param text: Text to measure. + :param mode: Used by some graphics drivers to indicate what mode the + driver prefers; if empty, the renderer may return either + mode. Note that the mode is always a string, to simplify + C-level implementations. + + :param direction: Direction of the text. It can be 'rtl' (right to + left), 'ltr' (left to right) or 'ttb' (top to bottom). + Requires libraqm. + + :param features: A list of OpenType font features to be used during text + layout. This is usually used to turn on optional + font features that are not enabled by default, + for example 'dlig' or 'ss01', but can be also + used to turn off default font features for + example '-liga' to disable ligatures or '-kern' + to disable kerning. To get all supported + features, see + https://learn.microsoft.com/en-us/typography/opentype/spec/featurelist + Requires libraqm. + + :param language: Language of the text. Different languages may use + different glyph shapes or ligatures. This parameter tells + the font which language the text is in, and to apply the + correct substitutions as appropriate, if available. + It should be a `BCP 47 language code + `_ + Requires libraqm. + + :return: Either width for horizontal text, or height for vertical text. + """ + _string_length_check(text) + return self.font.getlength(text, mode, direction, features, language) / 64 + + def getbbox( + self, + text: str | bytes, + mode: str = "", + direction: str | None = None, + features: list[str] | None = None, + language: str | None = None, + stroke_width: float = 0, + anchor: str | None = None, + ) -> tuple[float, float, float, float]: + """ + Returns bounding box (in pixels) of given text relative to given anchor + when rendered in font with provided direction, features, and language. + + Use :py:meth:`getlength()` to get the offset of following text with + 1/64 pixel precision. The bounding box includes extra margins for + some fonts, e.g. italics or accents. + + .. versionadded:: 8.0.0 + + :param text: Text to render. + :param mode: Used by some graphics drivers to indicate what mode the + driver prefers; if empty, the renderer may return either + mode. Note that the mode is always a string, to simplify + C-level implementations. + + :param direction: Direction of the text. It can be 'rtl' (right to + left), 'ltr' (left to right) or 'ttb' (top to bottom). + Requires libraqm. + + :param features: A list of OpenType font features to be used during text + layout. This is usually used to turn on optional + font features that are not enabled by default, + for example 'dlig' or 'ss01', but can be also + used to turn off default font features for + example '-liga' to disable ligatures or '-kern' + to disable kerning. To get all supported + features, see + https://learn.microsoft.com/en-us/typography/opentype/spec/featurelist + Requires libraqm. + + :param language: Language of the text. Different languages may use + different glyph shapes or ligatures. This parameter tells + the font which language the text is in, and to apply the + correct substitutions as appropriate, if available. + It should be a `BCP 47 language code + `_ + Requires libraqm. + + :param stroke_width: The width of the text stroke. + + :param anchor: The text anchor alignment. Determines the relative location of + the anchor to the text. The default alignment is top left, + specifically ``la`` for horizontal text and ``lt`` for + vertical text. See :ref:`text-anchors` for details. + + :return: ``(left, top, right, bottom)`` bounding box + """ + _string_length_check(text) + size, offset = self.font.getsize( + text, mode, direction, features, language, anchor + ) + left, top = offset[0] - stroke_width, offset[1] - stroke_width + width, height = size[0] + 2 * stroke_width, size[1] + 2 * stroke_width + return left, top, left + width, top + height + + def getmask( + self, + text: str | bytes, + mode: str = "", + direction: str | None = None, + features: list[str] | None = None, + language: str | None = None, + stroke_width: float = 0, + anchor: str | None = None, + ink: int = 0, + start: tuple[float, float] | None = None, + ) -> Image.core.ImagingCore: + """ + Create a bitmap for the text. + + If the font uses antialiasing, the bitmap should have mode ``L`` and use a + maximum value of 255. If the font has embedded color data, the bitmap + should have mode ``RGBA``. Otherwise, it should have mode ``1``. + + :param text: Text to render. + :param mode: Used by some graphics drivers to indicate what mode the + driver prefers; if empty, the renderer may return either + mode. Note that the mode is always a string, to simplify + C-level implementations. + + .. versionadded:: 1.1.5 + + :param direction: Direction of the text. It can be 'rtl' (right to + left), 'ltr' (left to right) or 'ttb' (top to bottom). + Requires libraqm. + + .. versionadded:: 4.2.0 + + :param features: A list of OpenType font features to be used during text + layout. This is usually used to turn on optional + font features that are not enabled by default, + for example 'dlig' or 'ss01', but can be also + used to turn off default font features for + example '-liga' to disable ligatures or '-kern' + to disable kerning. To get all supported + features, see + https://learn.microsoft.com/en-us/typography/opentype/spec/featurelist + Requires libraqm. + + .. versionadded:: 4.2.0 + + :param language: Language of the text. Different languages may use + different glyph shapes or ligatures. This parameter tells + the font which language the text is in, and to apply the + correct substitutions as appropriate, if available. + It should be a `BCP 47 language code + `_ + Requires libraqm. + + .. versionadded:: 6.0.0 + + :param stroke_width: The width of the text stroke. + + .. versionadded:: 6.2.0 + + :param anchor: The text anchor alignment. Determines the relative location of + the anchor to the text. The default alignment is top left, + specifically ``la`` for horizontal text and ``lt`` for + vertical text. See :ref:`text-anchors` for details. + + .. versionadded:: 8.0.0 + + :param ink: Foreground ink for rendering in RGBA mode. + + .. versionadded:: 8.0.0 + + :param start: Tuple of horizontal and vertical offset, as text may render + differently when starting at fractional coordinates. + + .. versionadded:: 9.4.0 + + :return: An internal PIL storage memory instance as defined by the + :py:mod:`PIL.Image.core` interface module. + """ + return self.getmask2( + text, + mode, + direction=direction, + features=features, + language=language, + stroke_width=stroke_width, + anchor=anchor, + ink=ink, + start=start, + )[0] + + def getmask2( + self, + text: str | bytes, + mode: str = "", + direction: str | None = None, + features: list[str] | None = None, + language: str | None = None, + stroke_width: float = 0, + anchor: str | None = None, + ink: int = 0, + start: tuple[float, float] | None = None, + *args: Any, + **kwargs: Any, + ) -> tuple[Image.core.ImagingCore, tuple[int, int]]: + """ + Create a bitmap for the text. + + If the font uses antialiasing, the bitmap should have mode ``L`` and use a + maximum value of 255. If the font has embedded color data, the bitmap + should have mode ``RGBA``. Otherwise, it should have mode ``1``. + + :param text: Text to render. + :param mode: Used by some graphics drivers to indicate what mode the + driver prefers; if empty, the renderer may return either + mode. Note that the mode is always a string, to simplify + C-level implementations. + + .. versionadded:: 1.1.5 + + :param direction: Direction of the text. It can be 'rtl' (right to + left), 'ltr' (left to right) or 'ttb' (top to bottom). + Requires libraqm. + + .. versionadded:: 4.2.0 + + :param features: A list of OpenType font features to be used during text + layout. This is usually used to turn on optional + font features that are not enabled by default, + for example 'dlig' or 'ss01', but can be also + used to turn off default font features for + example '-liga' to disable ligatures or '-kern' + to disable kerning. To get all supported + features, see + https://learn.microsoft.com/en-us/typography/opentype/spec/featurelist + Requires libraqm. + + .. versionadded:: 4.2.0 + + :param language: Language of the text. Different languages may use + different glyph shapes or ligatures. This parameter tells + the font which language the text is in, and to apply the + correct substitutions as appropriate, if available. + It should be a `BCP 47 language code + `_ + Requires libraqm. + + .. versionadded:: 6.0.0 + + :param stroke_width: The width of the text stroke. + + .. versionadded:: 6.2.0 + + :param anchor: The text anchor alignment. Determines the relative location of + the anchor to the text. The default alignment is top left, + specifically ``la`` for horizontal text and ``lt`` for + vertical text. See :ref:`text-anchors` for details. + + .. versionadded:: 8.0.0 + + :param ink: Foreground ink for rendering in RGBA mode. + + .. versionadded:: 8.0.0 + + :param start: Tuple of horizontal and vertical offset, as text may render + differently when starting at fractional coordinates. + + .. versionadded:: 9.4.0 + + :return: A tuple of an internal PIL storage memory instance as defined by the + :py:mod:`PIL.Image.core` interface module, and the text offset, the + gap between the starting coordinate and the first marking + """ + _string_length_check(text) + if start is None: + start = (0, 0) + + def fill(width: int, height: int) -> Image.core.ImagingCore: + size = (width, height) + Image._decompression_bomb_check(size) + return Image.core.fill("RGBA" if mode == "RGBA" else "L", size) + + return self.font.render( + text, + fill, + mode, + direction, + features, + language, + stroke_width, + kwargs.get("stroke_filled", False), + anchor, + ink, + start, + ) + + def font_variant( + self, + font: StrOrBytesPath | BinaryIO | None = None, + size: float | None = None, + index: int | None = None, + encoding: str | None = None, + layout_engine: Layout | None = None, + ) -> FreeTypeFont: + """ + Create a copy of this FreeTypeFont object, + using any specified arguments to override the settings. + + Parameters are identical to the parameters used to initialize this + object. + + :return: A FreeTypeFont object. + """ + if font is None: + try: + font = BytesIO(self.font_bytes) + except AttributeError: + font = self.path + return FreeTypeFont( + font=font, + size=self.size if size is None else size, + index=self.index if index is None else index, + encoding=self.encoding if encoding is None else encoding, + layout_engine=layout_engine or self.layout_engine, + ) + + def get_variation_names(self) -> list[bytes]: + """ + :returns: A list of the named styles in a variation font. + :exception OSError: If the font is not a variation font. + """ + names = [] + for name in self.font.getvarnames(): + name = name.replace(b"\x00", b"") + if name not in names: + names.append(name) + return names + + def set_variation_by_name(self, name: str | bytes) -> None: + """ + :param name: The name of the style. + :exception OSError: If the font is not a variation font. + """ + names = self.get_variation_names() + if not isinstance(name, bytes): + name = name.encode() + index = names.index(name) + 1 + + if index == getattr(self, "_last_variation_index", None): + # When the same name is set twice in a row, + # there is an 'unknown freetype error' + # https://savannah.nongnu.org/bugs/?56186 + return + self._last_variation_index = index + + self.font.setvarname(index) + + def get_variation_axes(self) -> list[Axis]: + """ + :returns: A list of the axes in a variation font. + :exception OSError: If the font is not a variation font. + """ + axes = self.font.getvaraxes() + for axis in axes: + if axis["name"]: + axis["name"] = axis["name"].replace(b"\x00", b"") + return axes + + def set_variation_by_axes(self, axes: list[float]) -> None: + """ + :param axes: A list of values for each axis. + :exception OSError: If the font is not a variation font. + """ + self.font.setvaraxes(axes) + + +class TransposedFont: + """Wrapper for writing rotated or mirrored text""" + + def __init__( + self, font: ImageFont | FreeTypeFont, orientation: Image.Transpose | None = None + ): + """ + Wrapper that creates a transposed font from any existing font + object. + + :param font: A font object. + :param orientation: An optional orientation. If given, this should + be one of Image.Transpose.FLIP_LEFT_RIGHT, Image.Transpose.FLIP_TOP_BOTTOM, + Image.Transpose.ROTATE_90, Image.Transpose.ROTATE_180, or + Image.Transpose.ROTATE_270. + """ + self.font = font + self.orientation = orientation # any 'transpose' argument, or None + + def getmask( + self, text: str | bytes, mode: str = "", *args: Any, **kwargs: Any + ) -> Image.core.ImagingCore: + im = self.font.getmask(text, mode, *args, **kwargs) + if self.orientation is not None: + return im.transpose(self.orientation) + return im + + def getbbox( + self, text: str | bytes, *args: Any, **kwargs: Any + ) -> tuple[int, int, float, float]: + # TransposedFont doesn't support getmask2, move top-left point to (0, 0) + # this has no effect on ImageFont and simulates anchor="lt" for FreeTypeFont + left, top, right, bottom = self.font.getbbox(text, *args, **kwargs) + width = right - left + height = bottom - top + if self.orientation in (Image.Transpose.ROTATE_90, Image.Transpose.ROTATE_270): + return 0, 0, height, width + return 0, 0, width, height + + def getlength(self, text: str | bytes, *args: Any, **kwargs: Any) -> float: + if self.orientation in (Image.Transpose.ROTATE_90, Image.Transpose.ROTATE_270): + msg = "text length is undefined for text rotated by 90 or 270 degrees" + raise ValueError(msg) + return self.font.getlength(text, *args, **kwargs) + + +def load(filename: str) -> ImageFont: + """ + Load a font file. This function loads a font object from the given + bitmap font file, and returns the corresponding font object. For loading TrueType + or OpenType fonts instead, see :py:func:`~PIL.ImageFont.truetype`. + + :param filename: Name of font file. + :return: A font object. + :exception OSError: If the file could not be read. + """ + f = ImageFont() + f._load_pilfont(filename) + return f + + +def truetype( + font: StrOrBytesPath | BinaryIO, + size: float = 10, + index: int = 0, + encoding: str = "", + layout_engine: Layout | None = None, +) -> FreeTypeFont: + """ + Load a TrueType or OpenType font from a file or file-like object, + and create a font object. This function loads a font object from the given + file or file-like object, and creates a font object for a font of the given + size. For loading bitmap fonts instead, see :py:func:`~PIL.ImageFont.load` + and :py:func:`~PIL.ImageFont.load_path`. + + Pillow uses FreeType to open font files. On Windows, be aware that FreeType + will keep the file open as long as the FreeTypeFont object exists. Windows + limits the number of files that can be open in C at once to 512, so if many + fonts are opened simultaneously and that limit is approached, an + ``OSError`` may be thrown, reporting that FreeType "cannot open resource". + A workaround would be to copy the file(s) into memory, and open that instead. + + This function requires the _imagingft service. + + :param font: A filename or file-like object containing a TrueType font. + If the file is not found in this filename, the loader may also + search in other directories, such as: + + * The :file:`fonts/` directory on Windows, + * :file:`/Library/Fonts/`, :file:`/System/Library/Fonts/` + and :file:`~/Library/Fonts/` on macOS. + * :file:`~/.local/share/fonts`, :file:`/usr/local/share/fonts`, + and :file:`/usr/share/fonts` on Linux; or those specified by + the ``XDG_DATA_HOME`` and ``XDG_DATA_DIRS`` environment variables + for user-installed and system-wide fonts, respectively. + + :param size: The requested size, in pixels. + :param index: Which font face to load (default is first available face). + :param encoding: Which font encoding to use (default is Unicode). Possible + encodings include (see the FreeType documentation for more + information): + + * "unic" (Unicode) + * "symb" (Microsoft Symbol) + * "ADOB" (Adobe Standard) + * "ADBE" (Adobe Expert) + * "ADBC" (Adobe Custom) + * "armn" (Apple Roman) + * "sjis" (Shift JIS) + * "gb " (PRC) + * "big5" + * "wans" (Extended Wansung) + * "joha" (Johab) + * "lat1" (Latin-1) + + This specifies the character set to use. It does not alter the + encoding of any text provided in subsequent operations. + :param layout_engine: Which layout engine to use, if available: + :attr:`.ImageFont.Layout.BASIC` or :attr:`.ImageFont.Layout.RAQM`. + If it is available, Raqm layout will be used by default. + Otherwise, basic layout will be used. + + Raqm layout is recommended for all non-English text. If Raqm layout + is not required, basic layout will have better performance. + + You can check support for Raqm layout using + :py:func:`PIL.features.check_feature` with ``feature="raqm"``. + + .. versionadded:: 4.2.0 + :return: A font object. + :exception OSError: If the file could not be read. + :exception ValueError: If the font size is not greater than zero. + """ + + def freetype(font: StrOrBytesPath | BinaryIO) -> FreeTypeFont: + return FreeTypeFont(font, size, index, encoding, layout_engine) + + try: + return freetype(font) + except OSError: + if not is_path(font): + raise + ttf_filename = os.path.basename(font) + + dirs = [] + if sys.platform == "win32": + # check the windows font repository + # NOTE: must use uppercase WINDIR, to work around bugs in + # 1.5.2's os.environ.get() + windir = os.environ.get("WINDIR") + if windir: + dirs.append(os.path.join(windir, "fonts")) + elif sys.platform in ("linux", "linux2"): + data_home = os.environ.get("XDG_DATA_HOME") + if not data_home: + # The freedesktop spec defines the following default directory for + # when XDG_DATA_HOME is unset or empty. This user-level directory + # takes precedence over system-level directories. + data_home = os.path.expanduser("~/.local/share") + xdg_dirs = [data_home] + + data_dirs = os.environ.get("XDG_DATA_DIRS") + if not data_dirs: + # Similarly, defaults are defined for the system-level directories + data_dirs = "/usr/local/share:/usr/share" + xdg_dirs += data_dirs.split(":") + + dirs += [os.path.join(xdg_dir, "fonts") for xdg_dir in xdg_dirs] + elif sys.platform == "darwin": + dirs += [ + "/Library/Fonts", + "/System/Library/Fonts", + os.path.expanduser("~/Library/Fonts"), + ] + + ext = os.path.splitext(ttf_filename)[1] + first_font_with_a_different_extension = None + for directory in dirs: + for walkroot, walkdir, walkfilenames in os.walk(directory): + for walkfilename in walkfilenames: + if ext and walkfilename == ttf_filename: + return freetype(os.path.join(walkroot, walkfilename)) + elif not ext and os.path.splitext(walkfilename)[0] == ttf_filename: + fontpath = os.path.join(walkroot, walkfilename) + if os.path.splitext(fontpath)[1] == ".ttf": + return freetype(fontpath) + if not ext and first_font_with_a_different_extension is None: + first_font_with_a_different_extension = fontpath + if first_font_with_a_different_extension: + return freetype(first_font_with_a_different_extension) + raise + + +def load_path(filename: str | bytes) -> ImageFont: + """ + Load font file. Same as :py:func:`~PIL.ImageFont.load`, but searches for a + bitmap font along the Python path. + + :param filename: Name of font file. + :return: A font object. + :exception OSError: If the file could not be read. + """ + if not isinstance(filename, str): + filename = filename.decode("utf-8") + for directory in sys.path: + try: + return load(os.path.join(directory, filename)) + except OSError: # noqa: PERF203 + pass + msg = f'cannot find font file "{filename}" in sys.path' + if os.path.exists(filename): + msg += f', did you mean ImageFont.load("{filename}") instead?' + + raise OSError(msg) + + +def load_default_imagefont() -> ImageFont: + f = ImageFont() + f._load_pilfont_data( + # courB08 + BytesIO(base64.b64decode(b""" +UElMZm9udAo7Ozs7OzsxMDsKREFUQQoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA +AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA +AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA +AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA +AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA +AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA +AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA +AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA +AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA +AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA +AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA +AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAYAAAAA//8AAQAAAAAAAAABAAEA +BgAAAAH/+gADAAAAAQAAAAMABgAGAAAAAf/6AAT//QADAAAABgADAAYAAAAA//kABQABAAYAAAAL +AAgABgAAAAD/+AAFAAEACwAAABAACQAGAAAAAP/5AAUAAAAQAAAAFQAHAAYAAP////oABQAAABUA +AAAbAAYABgAAAAH/+QAE//wAGwAAAB4AAwAGAAAAAf/5AAQAAQAeAAAAIQAIAAYAAAAB//kABAAB +ACEAAAAkAAgABgAAAAD/+QAE//0AJAAAACgABAAGAAAAAP/6AAX//wAoAAAALQAFAAYAAAAB//8A +BAACAC0AAAAwAAMABgAAAAD//AAF//0AMAAAADUAAQAGAAAAAf//AAMAAAA1AAAANwABAAYAAAAB +//kABQABADcAAAA7AAgABgAAAAD/+QAFAAAAOwAAAEAABwAGAAAAAP/5AAYAAABAAAAARgAHAAYA +AAAA//kABQAAAEYAAABLAAcABgAAAAD/+QAFAAAASwAAAFAABwAGAAAAAP/5AAYAAABQAAAAVgAH +AAYAAAAA//kABQAAAFYAAABbAAcABgAAAAD/+QAFAAAAWwAAAGAABwAGAAAAAP/5AAUAAABgAAAA +ZQAHAAYAAAAA//kABQAAAGUAAABqAAcABgAAAAD/+QAFAAAAagAAAG8ABwAGAAAAAf/8AAMAAABv +AAAAcQAEAAYAAAAA//wAAwACAHEAAAB0AAYABgAAAAD/+gAE//8AdAAAAHgABQAGAAAAAP/7AAT/ +/gB4AAAAfAADAAYAAAAB//oABf//AHwAAACAAAUABgAAAAD/+gAFAAAAgAAAAIUABgAGAAAAAP/5 +AAYAAQCFAAAAiwAIAAYAAP////oABgAAAIsAAACSAAYABgAA////+gAFAAAAkgAAAJgABgAGAAAA +AP/6AAUAAACYAAAAnQAGAAYAAP////oABQAAAJ0AAACjAAYABgAA////+gAFAAAAowAAAKkABgAG +AAD////6AAUAAACpAAAArwAGAAYAAAAA//oABQAAAK8AAAC0AAYABgAA////+gAGAAAAtAAAALsA +BgAGAAAAAP/6AAQAAAC7AAAAvwAGAAYAAP////oABQAAAL8AAADFAAYABgAA////+gAGAAAAxQAA +AMwABgAGAAD////6AAUAAADMAAAA0gAGAAYAAP////oABQAAANIAAADYAAYABgAA////+gAGAAAA +2AAAAN8ABgAGAAAAAP/6AAUAAADfAAAA5AAGAAYAAP////oABQAAAOQAAADqAAYABgAAAAD/+gAF +AAEA6gAAAO8ABwAGAAD////6AAYAAADvAAAA9gAGAAYAAAAA//oABQAAAPYAAAD7AAYABgAA//// ++gAFAAAA+wAAAQEABgAGAAD////6AAYAAAEBAAABCAAGAAYAAP////oABgAAAQgAAAEPAAYABgAA +////+gAGAAABDwAAARYABgAGAAAAAP/6AAYAAAEWAAABHAAGAAYAAP////oABgAAARwAAAEjAAYA +BgAAAAD/+gAFAAABIwAAASgABgAGAAAAAf/5AAQAAQEoAAABKwAIAAYAAAAA//kABAABASsAAAEv +AAgABgAAAAH/+QAEAAEBLwAAATIACAAGAAAAAP/5AAX//AEyAAABNwADAAYAAAAAAAEABgACATcA +AAE9AAEABgAAAAH/+QAE//wBPQAAAUAAAwAGAAAAAP/7AAYAAAFAAAABRgAFAAYAAP////kABQAA +AUYAAAFMAAcABgAAAAD/+wAFAAABTAAAAVEABQAGAAAAAP/5AAYAAAFRAAABVwAHAAYAAAAA//sA +BQAAAVcAAAFcAAUABgAAAAD/+QAFAAABXAAAAWEABwAGAAAAAP/7AAYAAgFhAAABZwAHAAYAAP// +//kABQAAAWcAAAFtAAcABgAAAAD/+QAGAAABbQAAAXMABwAGAAAAAP/5AAQAAgFzAAABdwAJAAYA +AP////kABgAAAXcAAAF+AAcABgAAAAD/+QAGAAABfgAAAYQABwAGAAD////7AAUAAAGEAAABigAF +AAYAAP////sABQAAAYoAAAGQAAUABgAAAAD/+wAFAAABkAAAAZUABQAGAAD////7AAUAAgGVAAAB +mwAHAAYAAAAA//sABgACAZsAAAGhAAcABgAAAAD/+wAGAAABoQAAAacABQAGAAAAAP/7AAYAAAGn +AAABrQAFAAYAAAAA//kABgAAAa0AAAGzAAcABgAA////+wAGAAABswAAAboABQAGAAD////7AAUA +AAG6AAABwAAFAAYAAP////sABgAAAcAAAAHHAAUABgAAAAD/+wAGAAABxwAAAc0ABQAGAAD////7 +AAYAAgHNAAAB1AAHAAYAAAAA//sABQAAAdQAAAHZAAUABgAAAAH/+QAFAAEB2QAAAd0ACAAGAAAA +Av/6AAMAAQHdAAAB3gAHAAYAAAAA//kABAABAd4AAAHiAAgABgAAAAD/+wAF//0B4gAAAecAAgAA +AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA +AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA +AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA +AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA +AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA +AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA +AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA +AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA +AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA +AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA +AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA +AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAYAAAAB +//sAAwACAecAAAHpAAcABgAAAAD/+QAFAAEB6QAAAe4ACAAGAAAAAP/5AAYAAAHuAAAB9AAHAAYA +AAAA//oABf//AfQAAAH5AAUABgAAAAD/+QAGAAAB+QAAAf8ABwAGAAAAAv/5AAMAAgH/AAACAAAJ +AAYAAAAA//kABQABAgAAAAIFAAgABgAAAAH/+gAE//sCBQAAAggAAQAGAAAAAP/5AAYAAAIIAAAC +DgAHAAYAAAAB//kABf/+Ag4AAAISAAUABgAA////+wAGAAACEgAAAhkABQAGAAAAAP/7AAX//gIZ +AAACHgADAAYAAAAA//wABf/9Ah4AAAIjAAEABgAAAAD/+QAHAAACIwAAAioABwAGAAAAAP/6AAT/ ++wIqAAACLgABAAYAAAAA//kABP/8Ai4AAAIyAAMABgAAAAD/+gAFAAACMgAAAjcABgAGAAAAAf/5 +AAT//QI3AAACOgAEAAYAAAAB//kABP/9AjoAAAI9AAQABgAAAAL/+QAE//sCPQAAAj8AAgAGAAD/ +///7AAYAAgI/AAACRgAHAAYAAAAA//kABgABAkYAAAJMAAgABgAAAAH//AAD//0CTAAAAk4AAQAG +AAAAAf//AAQAAgJOAAACUQADAAYAAAAB//kABP/9AlEAAAJUAAQABgAAAAH/+QAF//4CVAAAAlgA +BQAGAAD////7AAYAAAJYAAACXwAFAAYAAP////kABgAAAl8AAAJmAAcABgAA////+QAGAAACZgAA +Am0ABwAGAAD////5AAYAAAJtAAACdAAHAAYAAAAA//sABQACAnQAAAJ5AAcABgAA////9wAGAAAC +eQAAAoAACQAGAAD////3AAYAAAKAAAAChwAJAAYAAP////cABgAAAocAAAKOAAkABgAA////9wAG +AAACjgAAApUACQAGAAD////4AAYAAAKVAAACnAAIAAYAAP////cABgAAApwAAAKjAAkABgAA//// ++gAGAAACowAAAqoABgAGAAAAAP/6AAUAAgKqAAACrwAIAAYAAP////cABQAAAq8AAAK1AAkABgAA +////9wAFAAACtQAAArsACQAGAAD////3AAUAAAK7AAACwQAJAAYAAP////gABQAAAsEAAALHAAgA +BgAAAAD/9wAEAAACxwAAAssACQAGAAAAAP/3AAQAAALLAAACzwAJAAYAAAAA//cABAAAAs8AAALT +AAkABgAAAAD/+AAEAAAC0wAAAtcACAAGAAD////6AAUAAALXAAAC3QAGAAYAAP////cABgAAAt0A +AALkAAkABgAAAAD/9wAFAAAC5AAAAukACQAGAAAAAP/3AAUAAALpAAAC7gAJAAYAAAAA//cABQAA +Au4AAALzAAkABgAAAAD/9wAFAAAC8wAAAvgACQAGAAAAAP/4AAUAAAL4AAAC/QAIAAYAAAAA//oA +Bf//Av0AAAMCAAUABgAA////+gAGAAADAgAAAwkABgAGAAD////3AAYAAAMJAAADEAAJAAYAAP// +//cABgAAAxAAAAMXAAkABgAA////9wAGAAADFwAAAx4ACQAGAAD////4AAYAAAAAAAoABwASAAYA +AP////cABgAAAAcACgAOABMABgAA////+gAFAAAADgAKABQAEAAGAAD////6AAYAAAAUAAoAGwAQ +AAYAAAAA//gABgAAABsACgAhABIABgAAAAD/+AAGAAAAIQAKACcAEgAGAAAAAP/4AAYAAAAnAAoA +LQASAAYAAAAA//gABgAAAC0ACgAzABIABgAAAAD/+QAGAAAAMwAKADkAEQAGAAAAAP/3AAYAAAA5 +AAoAPwATAAYAAP////sABQAAAD8ACgBFAA8ABgAAAAD/+wAFAAIARQAKAEoAEQAGAAAAAP/4AAUA +AABKAAoATwASAAYAAAAA//gABQAAAE8ACgBUABIABgAAAAD/+AAFAAAAVAAKAFkAEgAGAAAAAP/5 +AAUAAABZAAoAXgARAAYAAAAA//gABgAAAF4ACgBkABIABgAAAAD/+AAGAAAAZAAKAGoAEgAGAAAA +AP/4AAYAAABqAAoAcAASAAYAAAAA//kABgAAAHAACgB2ABEABgAAAAD/+AAFAAAAdgAKAHsAEgAG +AAD////4AAYAAAB7AAoAggASAAYAAAAA//gABQAAAIIACgCHABIABgAAAAD/+AAFAAAAhwAKAIwA +EgAGAAAAAP/4AAUAAACMAAoAkQASAAYAAAAA//gABQAAAJEACgCWABIABgAAAAD/+QAFAAAAlgAK +AJsAEQAGAAAAAP/6AAX//wCbAAoAoAAPAAYAAAAA//oABQABAKAACgClABEABgAA////+AAGAAAA +pQAKAKwAEgAGAAD////4AAYAAACsAAoAswASAAYAAP////gABgAAALMACgC6ABIABgAA////+QAG +AAAAugAKAMEAEQAGAAD////4AAYAAgDBAAoAyAAUAAYAAP////kABQACAMgACgDOABMABgAA//// ++QAGAAIAzgAKANUAEw== +""")), + Image.open(BytesIO(base64.b64decode(b""" +iVBORw0KGgoAAAANSUhEUgAAAx4AAAAUAQAAAAArMtZoAAAEwElEQVR4nABlAJr/AHVE4czCI/4u +Mc4b7vuds/xzjz5/3/7u/n9vMe7vnfH/9++vPn/xyf5zhxzjt8GHw8+2d83u8x27199/nxuQ6Od9 +M43/5z2I+9n9ZtmDBwMQECDRQw/eQIQohJXxpBCNVE6QCCAAAAD//wBlAJr/AgALyj1t/wINwq0g +LeNZUworuN1cjTPIzrTX6ofHWeo3v336qPzfEwRmBnHTtf95/fglZK5N0PDgfRTslpGBvz7LFc4F +IUXBWQGjQ5MGCx34EDFPwXiY4YbYxavpnhHFrk14CDAAAAD//wBlAJr/AgKqRooH2gAgPeggvUAA +Bu2WfgPoAwzRAABAAAAAAACQgLz/3Uv4Gv+gX7BJgDeeGP6AAAD1NMDzKHD7ANWr3loYbxsAD791 +NAADfcoIDyP44K/jv4Y63/Z+t98Ovt+ub4T48LAAAAD//wBlAJr/AuplMlADJAAAAGuAphWpqhMx +in0A/fRvAYBABPgBwBUgABBQ/sYAyv9g0bCHgOLoGAAAAAAAREAAwI7nr0ArYpow7aX8//9LaP/9 +SjdavWA8ePHeBIKB//81/83ndznOaXx379wAAAD//wBlAJr/AqDxW+D3AABAAbUh/QMnbQag/gAY +AYDAAACgtgD/gOqAAAB5IA/8AAAk+n9w0AAA8AAAmFRJuPo27ciC0cD5oeW4E7KA/wD3ECMAn2tt +y8PgwH8AfAxFzC0JzeAMtratAsC/ffwAAAD//wBlAJr/BGKAyCAA4AAAAvgeYTAwHd1kmQF5chkG +ABoMIHcL5xVpTfQbUqzlAAAErwAQBgAAEOClA5D9il08AEh/tUzdCBsXkbgACED+woQg8Si9VeqY +lODCn7lmF6NhnAEYgAAA/NMIAAAAAAD//2JgjLZgVGBg5Pv/Tvpc8hwGBjYGJADjHDrAwPzAjv/H +/Wf3PzCwtzcwHmBgYGcwbZz8wHaCAQMDOwMDQ8MCBgYOC3W7mp+f0w+wHOYxO3OG+e376hsMZjk3 +AAAAAP//YmCMY2A4wMAIN5e5gQETPD6AZisDAwMDgzSDAAPjByiHcQMDAwMDg1nOze1lByRu5/47 +c4859311AYNZzg0AAAAA//9iYGDBYihOIIMuwIjGL39/fwffA8b//xv/P2BPtzzHwCBjUQAAAAD/ +/yLFBrIBAAAA//9i1HhcwdhizX7u8NZNzyLbvT97bfrMf/QHI8evOwcSqGUJAAAA//9iYBB81iSw +pEE170Qrg5MIYydHqwdDQRMrAwcVrQAAAAD//2J4x7j9AAMDn8Q/BgYLBoaiAwwMjPdvMDBYM1Tv +oJodAAAAAP//Yqo/83+dxePWlxl3npsel9lvLfPcqlE9725C+acfVLMEAAAA//9i+s9gwCoaaGMR +evta/58PTEWzr21hufPjA8N+qlnBwAAAAAD//2JiWLci5v1+HmFXDqcnULE/MxgYGBj+f6CaJQAA +AAD//2Ji2FrkY3iYpYC5qDeGgeEMAwPDvwQBBoYvcTwOVLMEAAAA//9isDBgkP///0EOg9z35v// +Gc/eeW7BwPj5+QGZhANUswMAAAD//2JgqGBgYGBgqEMXlvhMPUsAAAAA//8iYDd1AAAAAP//AwDR +w7IkEbzhVQAAAABJRU5ErkJggg== +"""))), + ) + return f + + +def load_default(size: float | None = None) -> FreeTypeFont | ImageFont: + """If FreeType support is available, load a version of Aileron Regular, + https://dotcolon.net/fonts/aileron, with a more limited character set. + + Otherwise, load a "better than nothing" font. + + .. versionadded:: 1.1.4 + + :param size: The font size of Aileron Regular. + + .. versionadded:: 10.1.0 + + :return: A font object. + """ + if isinstance(core, ModuleType) or size is not None: + return truetype( + BytesIO(base64.b64decode(b""" +AAEAAAAPAIAAAwBwRkZUTYwDlUAAADFoAAAAHEdERUYAqADnAAAo8AAAACRHUE9ThhmITwAAKfgAA +AduR1NVQnHxefoAACkUAAAA4k9TLzJovoHLAAABeAAAAGBjbWFw5lFQMQAAA6gAAAGqZ2FzcP//AA +MAACjoAAAACGdseWYmRXoPAAAGQAAAHfhoZWFkE18ayQAAAPwAAAA2aGhlYQboArEAAAE0AAAAJGh +tdHjjERZ8AAAB2AAAAdBsb2NhuOexrgAABVQAAADqbWF4cAC7AEYAAAFYAAAAIG5hbWUr+h5lAAAk +OAAAA6Jwb3N0D3oPTQAAJ9wAAAEKAAEAAAABGhxJDqIhXw889QALA+gAAAAA0Bqf2QAAAADhCh2h/ +2r/LgOxAyAAAAAIAAIAAAAAAAAAAQAAA8r/GgAAA7j/av9qA7EAAQAAAAAAAAAAAAAAAAAAAHQAAQ +AAAHQAQwAFAAAAAAACAAAAAQABAAAAQAAAAAAAAAADAfoBkAAFAAgCigJYAAAASwKKAlgAAAFeADI +BPgAAAAAFAAAAAAAAAAAAAAcAAAAAAAAAAAAAAABVS1dOAEAAIPsCAwL/GgDIA8oA5iAAAJMAAAAA +AhICsgAAACAAAwH0AAAAAAAAAU0AAADYAAAA8gA5AVMAVgJEAEYCRAA1AuQAKQKOAEAAsAArATsAZ +AE7AB4CMABVAkQAUADc/+EBEgAgANwAJQEv//sCRAApAkQAggJEADwCRAAtAkQAIQJEADkCRAArAk +QAMgJEACwCRAAxANwAJQDc/+ECRABnAkQAUAJEAEQB8wAjA1QANgJ/AB0CcwBkArsALwLFAGQCSwB +kAjcAZALGAC8C2gBkAQgAZAIgADcCYQBkAj8AZANiAGQCzgBkAuEALwJWAGQC3QAvAmsAZAJJADQC +ZAAiAqoAXgJuACADuAAaAnEAGQJFABMCTwAuATMAYgEv//sBJwAiAkQAUAH0ADIBLAApAhMAJAJjA +EoCEQAeAmcAHgIlAB4BIgAVAmcAHgJRAEoA7gA+AOn/8wIKAEoA9wBGA1cASgJRAEoCSgAeAmMASg +JnAB4BSgBKAcsAGAE5ABQCUABCAgIAAQMRAAEB4v/6AgEAAQHOABQBLwBAAPoAYAEvACECRABNA0Y +AJAItAHgBKgAcAkQAUAEsAHQAygAgAi0AOQD3ADYA9wAWAaEANgGhABYCbAAlAYMAeAGDADkA6/9q +AhsAFAIKABUB/QAVAAAAAwAAAAMAAAAcAAEAAAAAAKQAAwABAAAAHAAEAIgAAAAeABAAAwAOAH4Aq +QCrALEAtAC3ALsgGSAdICYgOiBEISL7Av//AAAAIACpAKsAsAC0ALcAuyAYIBwgJiA5IEQhIvsB// +//4/+5/7j/tP+y/7D/reBR4E/gR+A14CzfTwVxAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA +AAAAAAAEGAAABAAAAAAAAAAECAAAAAgAAAAAAAAAAAAAAAAAAAAEAAAMEBQYHCAkKCwwNDg8QERIT +FBUWFxgZGhscHR4fICEiIyQlJicoKSorLC0uLzAxMjM0NTY3ODk6Ozw9Pj9AQUJDREVGR0hJSktMT +U5PUFFSU1RVVldYWVpbXF1eX2BhAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGQAAA +AAAAAAYnFmAAAAAABlAAAAAAAAAAAAAAAAAAAAAAAAAAAAY2htAAAAAAAAAABrbGlqAAAAAHAAbm9 +ycwBnAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAmACYAJgAmAD4AUgCCAMoBCgFO +AVwBcgGIAaYBvAHKAdYB6AH2AgwCIAJKAogCpgLWAw4DIgNkA5wDugPUA+gD/AQQBEYEogS8BPoFJ +gVSBWoFgAWwBcoF1gX6BhQGJAZMBmgGiga0BuIHGgdUB2YHkAeiB8AH3AfyCAoIHAgqCDoITghcCG +oIogjSCPoJKglYCXwJwgnqCgIKKApACl4Klgq8CtwLDAs8C1YLjAuyC9oL7gwMDCYMSAxgDKAMrAz +qDQoNTA1mDYQNoA2uDcAN2g3oDfYODA4iDkoOXA5sDnoOnA7EDvwAAAAFAAAAAAH0ArwAAwAGAAkA +DAAPAAAxESERAxMhExcRASELARETAfT6qv6syKr+jgFUqsiqArz9RAGLAP/+1P8B/v3VAP8BLP4CA +P8AAgA5//IAuQKyAAMACwAANyMDMwIyFhQGIiY0oE4MZk84JCQ4JLQB/v3AJDgkJDgAAgBWAeUBPA +LfAAMABwAAEyMnMxcjJzOmRgpagkYKWgHl+vr6AAAAAAIARgAAAf4CsgAbAB8AAAEHMxUjByM3Iwc +jNyM1MzcjNTM3MwczNzMHMxUrAQczAZgdZXEvOi9bLzovWmYdZXEvOi9bLzovWp9bHlsBn4w429vb +2ziMONvb29s4jAAAAAMANf+mAg4DDAAfACYALAAAJRQGBxUjNS4BJzMeARcRLgE0Njc1MxUeARcjJ +icVHgEBFBYXNQ4BExU+ATU0Ag5xWDpgcgRcBz41Xl9oVTpVYwpcC1ttXP6cLTQuM5szOrVRZwlOTQ +ZqVzZECAEAGlukZAlOTQdrUG8O7iNlAQgxNhDlCDj+8/YGOjReAAAAAAUAKf/yArsCvAAHAAsAFQA +dACcAABIyFhQGIiY0EyMBMwQiBhUUFjI2NTQSMhYUBiImNDYiBhUUFjI2NTR5iFBQiFCVVwHAV/5c +OiMjOiPmiFBQiFCxOiMjOiMCvFaSVlaS/ZoCsjIzMC80NC8w/uNWklZWkhozMC80NC8wAAAAAgBA/ +/ICbgLAACIALgAAARUjEQYjIiY1NDY3LgE1NDYzMhcVJiMiBhUUFhcWOwE1MxUFFBYzMjc1IyIHDg +ECbmBcYYOOVkg7R4hsQjY4Q0RNRD4SLDxW/pJUXzksPCkUUk0BgUb+zBVUZ0BkDw5RO1huCkULQzp +COAMBcHDHRz0J/AIHRQAAAAEAKwHlAIUC3wADAAATIycze0YKWgHl+gAAAAABAGT/sAEXAwwACQAA +EzMGEBcjLgE0Nt06dXU6OUBAAwzG/jDGVePs4wAAAAEAHv+wANEDDAAJAAATMx4BFAYHIzYQHjo5Q +EA5OnUDDFXj7ONVxgHQAAAAAQBVAFIB2wHbAA4AAAE3FwcXBycHJzcnNxcnMwEtmxOfcTJjYzJxnx +ObCj4BKD07KYolmZkliik7PbMAAQBQAFUB9AIlAAsAAAEjFSM1IzUzNTMVMwH0tTq1tTq1AR/Kyjj +OzgAAAAAB/+H/iACMAGQABAAANwcjNzOMWlFOXVrS3AAAAQAgAP8A8gE3AAMAABMjNTPy0tIA/zgA +AQAl//IApQByAAcAADYyFhQGIiY0STgkJDgkciQ4JCQ4AAAAAf/7/+IBNALQAAMAABcjEzM5Pvs+H +gLuAAAAAAIAKf/yAhsCwAADAAcAABIgECA2IBAgKQHy/g5gATL+zgLA/TJEAkYAAAAAAQCCAAABlg +KyAAgAAAERIxEHNTc2MwGWVr6SIygCsv1OAldxW1sWAAEAPAAAAg4CwAAZAAA3IRUhNRM+ATU0JiM +iDwEjNz4BMzIWFRQGB7kBUv4x+kI2QTt+EAFWAQp8aGVtSl5GRjEA/0RVLzlLmAoKa3FsUkNxXQAA +AAEALf/yAhYCwAAqAAABHgEVFAYjIi8BMxceATMyNjU0KwE1MzI2NTQmIyIGDwEjNz4BMzIWFRQGA +YxBSZJo2RUBVgEHV0JBUaQREUBUQzc5TQcBVgEKfGhfcEMBbxJbQl1x0AoKRkZHPn9GSD80QUVCCg +pfbGBPOlgAAAACACEAAAIkArIACgAPAAAlIxUjNSE1ATMRMyMRBg8BAiRXVv6qAVZWV60dHLCurq4 +rAdn+QgFLMibzAAABADn/8gIZArIAHQAAATIWFRQGIyIvATMXFjMyNjU0JiMiByMTIRUhBzc2ATNv +d5Fl1RQBVgIad0VSTkVhL1IwAYj+vh8rMAHHgGdtgcUKCoFXTU5bYgGRRvAuHQAAAAACACv/8gITA +sAAFwAjAAABMhYVFAYjIhE0NjMyFh8BIycmIyIDNzYTMjY1NCYjIgYVFBYBLmp7imr0l3RZdAgBXA +IYZ5wKJzU6QVNJSz5SUAHSgWltiQFGxcNlVQoKdv7sPiz+ZF1LTmJbU0lhAAAAAQAyAAACGgKyAAY +AAAEVASMBITUCGv6oXAFL/oECsij9dgJsRgAAAAMALP/xAhgCwAAWACAALAAAAR4BFRQGIyImNTQ2 +Ny4BNTQ2MhYVFAYmIgYVFBYyNjU0AzI2NTQmIyIGFRQWAZQ5S5BmbIpPOjA7ecp5P2F8Q0J8RIVJS +0pLTEtOAW0TXTxpZ2ZqPF0SE1A3VWVlVTdQ/UU0N0RENzT9/ko+Ok1NOj1LAAIAMf/yAhkCwAAXAC +MAAAEyERQGIyImLwEzFxYzMhMHBiMiJjU0NhMyNjU0JiMiBhUUFgEl9Jd0WXQIAVwCGGecCic1SWp +7imo+UlBAQVNJAsD+usXDZVUKCnYBFD4sgWltif5kW1NJYV1LTmIAAAACACX/8gClAiAABwAPAAAS +MhYUBiImNBIyFhQGIiY0STgkJDgkJDgkJDgkAiAkOCQkOP52JDgkJDgAAAAC/+H/iAClAiAABwAMA +AASMhYUBiImNBMHIzczSTgkJDgkaFpSTl4CICQ4JCQ4/mba5gAAAQBnAB4B+AH0AAYAAAENARUlNS +UB+P6qAVb+bwGRAbCmpkbJRMkAAAIAUAC7AfQBuwADAAcAAAEhNSERITUhAfT+XAGk/lwBpAGDOP8 +AOAABAEQAHgHVAfQABgAAARUFNS0BNQHV/m8BVv6qAStEyUSmpkYAAAAAAgAj//IB1ALAABgAIAAA +ATIWFRQHDgEHIz4BNz4BNTQmIyIGByM+ARIyFhQGIiY0AQRibmktIAJWBSEqNig+NTlHBFoDezQ4J +CQ4JALAZ1BjaS03JS1DMD5LLDQ/SUVgcv2yJDgkJDgAAAAAAgA2/5gDFgKYADYAQgAAAQMGFRQzMj +Y1NCYjIg4CFRQWMzI2NxcGIyImNTQ+AjMyFhUUBiMiJwcGIyImNTQ2MzIfATcHNzYmIyIGFRQzMjY +Cej8EJjJJlnBAfGQ+oHtAhjUYg5OPx0h2k06Os3xRWQsVLjY5VHtdPBwJETcJDyUoOkZEJz8B0f74 +EQ8kZl6EkTFZjVOLlyknMVm1pmCiaTq4lX6CSCknTVRmmR8wPdYnQzxuSWVGAAIAHQAAAncCsgAHA +AoAACUjByMTMxMjATMDAcj+UVz4dO5d/sjPZPT0ArL9TgE6ATQAAAADAGQAAAJMArIAEAAbACcAAA +EeARUUBgcGKwERMzIXFhUUJRUzMjc2NTQnJiMTPgE1NCcmKwEVMzIBvkdHZkwiNt7LOSGq/oeFHBt +hahIlSTM+cB8Yj5UWAW8QT0VYYgwFArIEF5Fv1eMED2NfDAL93AU+N24PBP0AAAAAAQAv//ICjwLA +ABsAAAEyFh8BIycmIyIGFRQWMzI/ATMHDgEjIiY1NDYBdX+PCwFWAiKiaHx5ZaIiAlYBCpWBk6a0A +sCAagoKpqN/gaOmCgplhcicn8sAAAIAZAAAAp8CsgAMABkAAAEeARUUBgcGKwERMzITPgE1NCYnJi +sBETMyAY59lJp8IzXN0jUVWmdjWRs5d3I4Aq4QqJWUug8EArL9mQ+PeHGHDgX92gAAAAABAGQAAAI +vArIACwAAJRUhESEVIRUhFSEVAi/+NQHB/pUBTf6zRkYCskbwRvAAAAABAGQAAAIlArIACQAAExUh +FSERIxEhFboBQ/69VgHBAmzwRv7KArJGAAAAAAEAL//yAo8CwAAfAAABMxEjNQcGIyImNTQ2MzIWH +wEjJyYjIgYVFBYzMjY1IwGP90wfPnWTprSSf48LAVYCIqJofHllVG+hAU3+s3hARsicn8uAagoKpq +N/gaN1XAAAAAEAZAAAAowCsgALAAABESMRIREjETMRIRECjFb+hFZWAXwCsv1OAS7+0gKy/sQBPAA +AAAABAGQAAAC6ArIAAwAAMyMRM7pWVgKyAAABADf/8gHoArIAEwAAAREUBw4BIyImLwEzFxYzMjc2 +NREB6AIFcGpgbQIBVgIHfXQKAQKy/lYxIltob2EpKYyEFD0BpwAAAAABAGQAAAJ0ArIACwAACQEjA +wcVIxEzEQEzATsBJ3ntQlZWAVVlAWH+nwEnR+ACsv6RAW8AAQBkAAACLwKyAAUAACUVIREzEQIv/j +VWRkYCsv2UAAABAGQAAAMUArIAFAAAAREjETQ3BgcDIwMmJxYVESMRMxsBAxRWAiMxemx8NxsCVo7 +MywKy/U4BY7ZLco7+nAFmoFxLtP6dArL9lwJpAAAAAAEAZAAAAoACsgANAAAhIwEWFREjETMBJjUR +MwKAhP67A1aEAUUDVAJeeov+pwKy/aJ5jAFZAAAAAgAv//ICuwLAAAkAEwAAEiAWFRQGICY1NBIyN +jU0JiIGFRTbATSsrP7MrNrYenrYegLAxaKhxsahov47nIeIm5uIhwACAGQAAAJHArIADgAYAAABHg +EVFAYHBisBESMRMzITNjQnJisBETMyAZRUX2VOHzuAVtY7GlxcGDWIiDUCrgtnVlVpCgT+5gKy/rU +V1BUF/vgAAAACAC//zAK9AsAAEgAcAAAlFhcHJiMiBwYjIiY1NDYgFhUUJRQWMjY1NCYiBgI9PUMx +UDcfKh8omqysATSs/dR62Hp62HpICTg7NgkHxqGixcWitbWHnJyHiJubAAIAZAAAAlgCsgAXACMAA +CUWFyMmJyYnJisBESMRMzIXHgEVFAYHFiUzMjc+ATU0JyYrAQIqDCJfGQwNWhAhglbiOx9QXEY1Tv +6bhDATMj1lGSyMtYgtOXR0BwH+1wKyBApbU0BSESRAAgVAOGoQBAABADT/8gIoAsAAJQAAATIWFyM +uASMiBhUUFhceARUUBiMiJiczHgEzMjY1NCYnLgE1NDYBOmd2ClwGS0E6SUNRdW+HZnKKC1wPWkQ9 +Uk1cZGuEAsBwXUJHNjQ3OhIbZVZZbm5kREo+NT5DFRdYUFdrAAAAAAEAIgAAAmQCsgAHAAABIxEjE +SM1IQJk9lb2AkICbP2UAmxGAAEAXv/yAmQCsgAXAAABERQHDgEiJicmNREzERQXHgEyNjc2NRECZA +IIgfCBCAJWAgZYmlgGAgKy/k0qFFxzc1wUKgGz/lUrEkRQUEQSKwGrAAAAAAEAIAAAAnoCsgAGAAA +hIwMzGwEzAYJ07l3N1FwCsv2PAnEAAAEAGgAAA7ECsgAMAAABAyMLASMDMxsBMxsBA7HAcZyicrZi +kaB0nJkCsv1OAlP9rQKy/ZsCW/2kAmYAAAEAGQAAAm8CsgALAAAhCwEjEwMzGwEzAxMCCsrEY/bkY +re+Y/D6AST+3AFcAVb+5gEa/q3+oQAAAQATAAACUQKyAAgAAAERIxEDMxsBMwFdVvRjwLphARD+8A +EQAaL+sQFPAAABAC4AAAI5ArIACQAAJRUhNQEhNSEVAQI5/fUBof57Aen+YUZGQgIqRkX92QAAAAA +BAGL/sAEFAwwABwAAARUjETMVIxEBBWlpowMMOP0UOANcAAAB//v/4gE0AtAAAwAABSMDMwE0Pvs+ +HgLuAAAAAQAi/7AAxQMMAAcAABcjNTMRIzUzxaNpaaNQOALsOAABAFAA1wH0AmgABgAAJQsBIxMzE +wGwjY1GsESw1wFZ/qcBkf5vAAAAAQAy/6oBwv/iAAMAAAUhNSEBwv5wAZBWOAAAAAEAKQJEALYCsg +ADAAATIycztjhVUAJEbgAAAAACACT/8gHQAiAAHQAlAAAhJwcGIyImNTQ2OwE1NCcmIyIHIz4BMzI +XFh0BFBcnMjY9ASYVFAF6CR0wVUtgkJoiAgdgaQlaBm1Zrg4DCuQ9R+5MOSFQR1tbDiwUUXBUXowf +J8c9SjRORzYSgVwAAAAAAgBK//ICRQLfABEAHgAAATIWFRQGIyImLwEVIxEzETc2EzI2NTQmIyIGH +QEUFgFUcYCVbiNJEyNWVigySElcU01JXmECIJd4i5QTEDRJAt/+3jkq/hRuZV55ZWsdX14AAQAe// +IB9wIgABgAAAEyFhcjJiMiBhUUFjMyNjczDgEjIiY1NDYBF152DFocbEJXU0A1Rw1aE3pbaoKQAiB +oWH5qZm1tPDlaXYuLgZcAAAACAB7/8gIZAt8AEQAeAAABESM1BwYjIiY1NDYzMhYfAREDMjY9ATQm +IyIGFRQWAhlWKDJacYCVbiNJEyOnSV5hQUlcUwLf/SFVOSqXeIuUExA0ARb9VWVrHV9ebmVeeQACA +B7/8gH9AiAAFQAbAAABFAchHgEzMjY3Mw4BIyImNTQ2MzIWJyIGByEmAf0C/oAGUkA1SwlaD4FXbI +WObmt45UBVBwEqDQEYFhNjWD84W16Oh3+akU9aU60AAAEAFQAAARoC8gAWAAATBh0BMxUjESMRIzU +zNTQ3PgEzMhcVJqcDbW1WOTkDB0k8Hx5oAngVITRC/jQBzEIsJRs5PwVHEwAAAAIAHv8uAhkCIAAi +AC8AAAERFAcOASMiLwEzFx4BMzI2NzY9AQcGIyImNTQ2MzIWHwE1AzI2PQE0JiMiBhUUFgIZAQSEd +NwRAVcBBU5DTlUDASgyWnGAlW4jSRMjp0leYUFJXFMCEv5wSh1zeq8KCTI8VU0ZIQk5Kpd4i5QTED +RJ/iJlax1fXm5lXnkAAQBKAAACCgLkABcAAAEWFREjETQnLgEHDgEdASMRMxE3NjMyFgIIAlYCBDs +6RVRWViE5UVViAYUbQP7WASQxGzI7AQJyf+kC5P7TPSxUAAACAD4AAACsAsAABwALAAASMhYUBiIm +NBMjETNeLiAgLiBiVlYCwCAuICAu/WACEgAC//P/LgCnAsAABwAVAAASMhYUBiImNBcRFAcGIyInN +RY3NjURWS4gIC4gYgMLcRwNSgYCAsAgLiAgLo79wCUbZAJGBzMOHgJEAAAAAQBKAAACCALfAAsAAC +EnBxUjETMREzMHEwGTwTJWVvdu9/rgN6kC3/4oAQv6/ugAAQBG//wA3gLfAA8AABMRFBceATcVBiM +iJicmNRGcAQIcIxkkKi4CAQLf/bkhERoSBD4EJC8SNAJKAAAAAQBKAAADEAIgACQAAAEWFREjETQn +JiMiFREjETQnJiMiFREjETMVNzYzMhYXNzYzMhYDCwVWBAxedFYEDF50VlYiJko7ThAvJkpEVAGfI +jn+vAEcQyRZ1v76ARxDJFnW/voCEk08HzYtRB9HAAAAAAEASgAAAgoCIAAWAAABFhURIxE0JyYjIg +YdASMRMxU3NjMyFgIIAlYCCXBEVVZWITlRVWIBhRtA/tYBJDEbbHR/6QISWz0sVAAAAAACAB7/8gI +sAiAABwARAAASIBYUBiAmNBIyNjU0JiIGFRSlAQCHh/8Ah7ieWlqeWgIgn/Cfn/D+s3ZfYHV1YF8A +AgBK/zwCRQIgABEAHgAAATIWFRQGIyImLwERIxEzFTc2EzI2NTQmIyIGHQEUFgFUcYCVbiNJEyNWV +igySElcU01JXmECIJd4i5QTEDT+8wLWVTkq/hRuZV55ZWsdX14AAgAe/zwCGQIgABEAHgAAAREjEQ +cGIyImNTQ2MzIWHwE1AzI2PQE0JiMiBhUUFgIZVigyWnGAlW4jSRMjp0leYUFJXFMCEv0qARk5Kpd +4i5QTEDRJ/iJlax1fXm5lXnkAAQBKAAABPgIeAA0AAAEyFxUmBhURIxEzFTc2ARoWDkdXVlYwIwIe +B0EFVlf+0gISU0cYAAEAGP/yAa0CIAAjAAATMhYXIyYjIgYVFBYXHgEVFAYjIiYnMxYzMjY1NCYnL +gE1NDbkV2MJWhNdKy04PF1XbVhWbgxaE2ktOjlEUllkAiBaS2MrJCUoEBlPQkhOVFZoKCUmLhIWSE +BIUwAAAAEAFP/4ARQCiQAXAAATERQXHgE3FQYjIiYnJjURIzUzNTMVMxWxAQMmMx8qMjMEAUdHVmM +BzP7PGw4mFgY/BSwxDjQBNUJ7e0IAAAABAEL/8gICAhIAFwAAAREjNQcGIyImJyY1ETMRFBceATMy +Nj0BAgJWITlRT2EKBVYEBkA1RFECEv3uWj4qTToiOQE+/tIlJC43c4DpAAAAAAEAAQAAAfwCEgAGA +AABAyMDMxsBAfzJaclfop8CEv3uAhL+LQHTAAABAAEAAAMLAhIADAAAAQMjCwEjAzMbATMbAQMLqW +Z2dmapY3t0a3Z7AhL97gG+/kICEv5AAcD+QwG9AAAB//oAAAHWAhIACwAAARMjJwcjEwMzFzczARq +8ZIuKY763ZoWFYwEO/vLV1QEMAQbNzQAAAQAB/y4B+wISABEAAAEDDgEjIic1FjMyNj8BAzMbAQH7 +2iFZQB8NDRIpNhQH02GenQIS/cFVUAJGASozEwIt/i4B0gABABQAAAGxAg4ACQAAJRUhNQEhNSEVA +QGx/mMBNP7iAYL+zkREQgGIREX+ewAAAAABAED/sAEOAwwALAAAASMiBhUUFxYVFAYHHgEVFAcGFR +QWOwEVIyImNTQ3NjU0JzU2NTQnJjU0NjsBAQ4MKiMLDS4pKS4NCyMqDAtERAwLUlILDERECwLUGBk +WTlsgKzUFBTcrIFtOFhkYOC87GFVMIkUIOAhFIkxVGDsvAAAAAAEAYP84AJoDIAADAAAXIxEzmjo6 +yAPoAAEAIf+wAO8DDAAsAAATFQYVFBcWFRQGKwE1MzI2NTQnJjU0NjcuATU0NzY1NCYrATUzMhYVF +AcGFRTvUgsMREQLDCojCw0uKSkuDQsjKgwLREQMCwF6OAhFIkxVGDsvOBgZFk5bICs1BQU3KyBbTh +YZGDgvOxhVTCJFAAABAE0A3wH2AWQAEwAAATMUIyImJyYjIhUjNDMyFhcWMzIBvjhuGywtQR0xOG4 +bLC1BHTEBZIURGCNMhREYIwAAAwAk/94DIgLoAAcAEQApAAAAIBYQBiAmECQgBhUUFiA2NTQlMhYX +IyYjIgYUFjMyNjczDgEjIiY1NDYBAQFE3d3+vN0CB/7wubkBELn+xVBnD1wSWDo+QTcqOQZcEmZWX +HN2Aujg/rbg4AFKpr+Mjb6+jYxbWEldV5ZZNShLVn5na34AAgB4AFIB9AGeAAUACwAAAQcXIyc3Mw +cXIyc3AUqJiUmJifOJiUmJiQGepqampqampqYAAAIAHAHSAQ4CwAAHAA8AABIyFhQGIiY0NiIGFBY +yNjRgakREakSTNCEhNCECwEJqQkJqCiM4IyM4AAAAAAIAUAAAAfQCCwALAA8AAAEzFSMVIzUjNTM1 +MxMhNSEBP7W1OrW1OrX+XAGkAVs4tLQ4sP31OAAAAQB0AkQBAQKyAAMAABMjNzOsOD1QAkRuAAAAA +AEAIADsAKoBdgAHAAASMhYUBiImNEg6KCg6KAF2KDooKDoAAAIAOQBSAbUBngAFAAsAACUHIzcnMw +UHIzcnMwELiUmJiUkBM4lJiYlJ+KampqampqYAAAABADYB5QDhAt8ABAAAEzczByM2Xk1OXQHv8Po +AAQAWAeUAwQLfAAQAABMHIzczwV5NTl0C1fD6AAIANgHlAYsC3wAEAAkAABM3MwcjPwEzByM2Xk1O +XapeTU5dAe/w+grw+gAAAgAWAeUBawLfAAQACQAAEwcjNzMXByM3M8FeTU5dql5NTl0C1fD6CvD6A +AADACX/8gI1AHIABwAPABcAADYyFhQGIiY0NjIWFAYiJjQ2MhYUBiImNEk4JCQ4JOw4JCQ4JOw4JC +Q4JHIkOCQkOCQkOCQkOCQkOCQkOAAAAAEAeABSAUoBngAFAAABBxcjJzcBSomJSYmJAZ6mpqamAAA +AAAEAOQBSAQsBngAFAAAlByM3JzMBC4lJiYlJ+KampgAAAf9qAAABgQKyAAMAACsBATM/VwHAVwKy +AAAAAAIAFAHIAdwClAAHABQAABMVIxUjNSM1BRUjNwcjJxcjNTMXN9pKMkoByDICKzQqATJLKysCl +CmjoykBy46KiY3Lm5sAAQAVAAABvALyABgAAAERIxEjESMRIzUzNTQ3NjMyFxUmBgcGHQEBvFbCVj +k5AxHHHx5iVgcDAg798gHM/jQBzEIOJRuWBUcIJDAVIRYAAAABABX//AHkAvIAJQAAJR4BNxUGIyI +mJyY1ESYjIgcGHQEzFSMRIxEjNTM1NDc2MzIXERQBowIcIxkkKi4CAR4nXgwDbW1WLy8DEbNdOmYa +EQQ/BCQvEjQCFQZWFSEWQv40AcxCDiUblhP9uSEAAAAAAAAWAQ4AAQAAAAAAAAATACgAAQAAAAAAA +QAHAEwAAQAAAAAAAgAHAGQAAQAAAAAAAwAaAKIAAQAAAAAABAAHAM0AAQAAAAAABQA8AU8AAQAAAA +AABgAPAawAAQAAAAAACAALAdQAAQAAAAAACQALAfgAAQAAAAAACwAXAjQAAQAAAAAADAAXAnwAAwA +BBAkAAAAmAAAAAwABBAkAAQAOADwAAwABBAkAAgAOAFQAAwABBAkAAwA0AGwAAwABBAkABAAOAL0A +AwABBAkABQB4ANUAAwABBAkABgAeAYwAAwABBAkACAAWAbwAAwABBAkACQAWAeAAAwABBAkACwAuA +gQAAwABBAkADAAuAkwATgBvACAAUgBpAGcAaAB0AHMAIABSAGUAcwBlAHIAdgBlAGQALgAATm8gUm +lnaHRzIFJlc2VydmVkLgAAQQBpAGwAZQByAG8AbgAAQWlsZXJvbgAAUgBlAGcAdQBsAGEAcgAAUmV +ndWxhcgAAMQAuADEAMAAyADsAVQBLAFcATgA7AEEAaQBsAGUAcgBvAG4ALQBSAGUAZwB1AGwAYQBy +AAAxLjEwMjtVS1dOO0FpbGVyb24tUmVndWxhcgAAQQBpAGwAZQByAG8AbgAAQWlsZXJvbgAAVgBlA +HIAcwBpAG8AbgAgADEALgAxADAAMgA7AFAAUwAgADAAMAAxAC4AMQAwADIAOwBoAG8AdABjAG8Abg +B2ACAAMQAuADAALgA3ADAAOwBtAGEAawBlAG8AdABmAC4AbABpAGIAMgAuADUALgA1ADgAMwAyADk +AAFZlcnNpb24gMS4xMDI7UFMgMDAxLjEwMjtob3Rjb252IDEuMC43MDttYWtlb3RmLmxpYjIuNS41 +ODMyOQAAQQBpAGwAZQByAG8AbgAtAFIAZQBnAHUAbABhAHIAAEFpbGVyb24tUmVndWxhcgAAUwBvA +HIAYQAgAFMAYQBnAGEAbgBvAABTb3JhIFNhZ2FubwAAUwBvAHIAYQAgAFMAYQBnAGEAbgBvAABTb3 +JhIFNhZ2FubwAAaAB0AHQAcAA6AC8ALwB3AHcAdwAuAGQAbwB0AGMAbwBsAG8AbgAuAG4AZQB0AAB +odHRwOi8vd3d3LmRvdGNvbG9uLm5ldAAAaAB0AHQAcAA6AC8ALwB3AHcAdwAuAGQAbwB0AGMAbwBs +AG8AbgAuAG4AZQB0AABodHRwOi8vd3d3LmRvdGNvbG9uLm5ldAAAAAACAAAAAAAA/4MAMgAAAAAAA +AAAAAAAAAAAAAAAAAAAAHQAAAABAAIAAwAEAAUABgAHAAgACQAKAAsADAANAA4ADwAQABEAEgATAB +QAFQAWABcAGAAZABoAGwAcAB0AHgAfACAAIQAiACMAJAAlACYAJwAoACkAKgArACwALQAuAC8AMAA +xADIAMwA0ADUANgA3ADgAOQA6ADsAPAA9AD4APwBAAEEAQgBDAEQARQBGAEcASABJAEoASwBMAE0A +TgBPAFAAUQBSAFMAVABVAFYAVwBYAFkAWgBbAFwAXQBeAF8AYABhAIsAqQCDAJMAjQDDAKoAtgC3A +LQAtQCrAL4AvwC8AIwAwADBAAAAAAAB//8AAgABAAAADAAAABwAAAACAAIAAwBxAAEAcgBzAAIABA +AAAAIAAAABAAAACgBMAGYAAkRGTFQADmxhdG4AGgAEAAAAAP//AAEAAAAWAANDQVQgAB5NT0wgABZ +ST00gABYAAP//AAEAAAAA//8AAgAAAAEAAmxpZ2EADmxvY2wAFAAAAAEAAQAAAAEAAAACAAYAEAAG +AAAAAgASADQABAAAAAEATAADAAAAAgAQABYAAQAcAAAAAQABAE8AAQABAGcAAQABAE8AAwAAAAIAE +AAWAAEAHAAAAAEAAQAvAAEAAQBnAAEAAQAvAAEAGgABAAgAAgAGAAwAcwACAE8AcgACAEwAAQABAE +kAAAABAAAACgBGAGAAAkRGTFQADmxhdG4AHAAEAAAAAP//AAIAAAABABYAA0NBVCAAFk1PTCAAFlJ +PTSAAFgAA//8AAgAAAAEAAmNwc3AADmtlcm4AFAAAAAEAAAAAAAEAAQACAAYADgABAAAAAQASAAIA +AAACAB4ANgABAAoABQAFAAoAAgABACQAPQAAAAEAEgAEAAAAAQAMAAEAOP/nAAEAAQAkAAIGigAEA +AAFJAXKABoAGQAA//gAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA +AAAAD/sv+4/+z/7v/MAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA +AAAAAAAD/xAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/9T/6AAAAAD/8QAA +ABD/vQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD/7gAAAAAAAAAAAAAAAAAA//MAA +AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABIAAAAAAAAAAP/5AAAAAAAAAA +AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP/gAAD/4AAAAAAAAAAAAAAAAAA +AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA//L/9AAAAAAAAAAAAAAAAAAAAAAA +AAAAAAAAAAAA/+gAAAAAAAkAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA +AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP/zAAAAAA +AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP/mAAAAAAAAAAAAAAAAAAD +/4gAA//AAAAAA//YAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD/+AAAAAAAAP/OAAAAAAAAAAAAAAAA +AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD/zv/qAAAAAP/0AAAACAAAAAAAAAAAAAAAAAAAAAAAA +AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP/ZAAD/egAA/1kAAAAA/5D/rgAAAAAAAAAAAA +AAAAAAAAAAAAAAAAD/9AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA +AAAAAAAAAAAAAAAAAAAD/8AAA/7b/8P+wAAD/8P/E/98AAAAA/8P/+P/0//oAAAAAAAAAAAAA//gA +AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/+AAAAAAAAAAAAAAA +AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD/w//C/9MAAP/SAAD/9wAAAAAAAA +AAAAAAAAAAAAAAAAAAAAAAAAAAAAD/yAAA/+kAAAAA//QAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA +AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD/9wAAAAD//QAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA +AAAAAAAAAAAAAAAAAAAAAP/2AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA +AAAAAAAAP/cAAAAAAAAAAAAAAAA/7YAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA +AAAAAAAAAAAAAAAAAAAAAAAAAAAP/8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD/6AAAAAAAAAA +AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAkAFAAEAAAAAQACwAAABcA +BgAAAAAAAAAIAA4AAAAAAAsAEgAAAAAAAAATABkAAwANAAAAAQAJAAAAAAAAAAAAAAAAAAAAGAAAA +AAABwAAAAAAAAAAAAAAFQAFAAAAAAAYABgAAAAUAAAACgAAAAwAAgAPABEAFgAAAAAAAAAAAAAAAA +AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAEAEQBdAAYAAAAAAAAAAAAAAAAAAAAAAAA +AAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAcAAAAAAAAABwAAAAAACAAAAAAAAAAAAAcAAAAHAAAAEwAJ +ABUADgAPAAAACwAQAAAAAAAAAAAAAAAAAAUAGAACAAIAAgAAAAIAGAAXAAAAGAAAABYAFgACABYAA +gAWAAAAEQADAAoAFAAMAA0ABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAASAAAAEgAGAAEAHgAkAC +YAJwApACoALQAuAC8AMgAzADcAOAA5ADoAPAA9AEUASABOAE8AUgBTAFUAVwBZAFoAWwBcAF0AcwA +AAAAAAQAAAADa3tfFAAAAANAan9kAAAAA4QodoQ== +""")), + 10 if size is None else size, + layout_engine=Layout.BASIC, + ) + return load_default_imagefont() diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/ImageGrab.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/ImageGrab.py new file mode 100644 index 000000000..66ee6dd33 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/ImageGrab.py @@ -0,0 +1,231 @@ +# +# The Python Imaging Library +# $Id$ +# +# screen grabber +# +# History: +# 2001-04-26 fl created +# 2001-09-17 fl use builtin driver, if present +# 2002-11-19 fl added grabclipboard support +# +# Copyright (c) 2001-2002 by Secret Labs AB +# Copyright (c) 2001-2002 by Fredrik Lundh +# +# See the README file for information on usage and redistribution. +# +from __future__ import annotations + +import io +import os +import shutil +import subprocess +import sys +import tempfile + +from . import Image + +TYPE_CHECKING = False +if TYPE_CHECKING: + from . import ImageWin + + +def grab( + bbox: tuple[int, int, int, int] | None = None, + include_layered_windows: bool = False, + all_screens: bool = False, + xdisplay: str | None = None, + window: int | ImageWin.HWND | None = None, +) -> Image.Image: + im: Image.Image + if xdisplay is None: + if sys.platform == "darwin": + fh, filepath = tempfile.mkstemp(".png") + os.close(fh) + args = ["screencapture"] + if window is not None: + args += ["-l", str(window)] + elif bbox: + left, top, right, bottom = bbox + args += ["-R", f"{left},{top},{right-left},{bottom-top}"] + args += ["-x", filepath] + retcode = subprocess.call(args) + if retcode: + raise subprocess.CalledProcessError(retcode, args) + im = Image.open(filepath) + im.load() + os.unlink(filepath) + if bbox: + if window is not None: + # Determine if the window was in Retina mode or not + # by capturing it without the shadow, + # and checking how different the width is + fh, filepath = tempfile.mkstemp(".png") + os.close(fh) + args = ["screencapture", "-l", str(window), "-o", "-x", filepath] + retcode = subprocess.call(args) + if retcode: + raise subprocess.CalledProcessError(retcode, args) + with Image.open(filepath) as im_no_shadow: + retina = im.width - im_no_shadow.width > 100 + os.unlink(filepath) + + # Since screencapture's -R does not work with -l, + # crop the image manually + if retina: + left, top, right, bottom = bbox + im_cropped = im.resize( + (right - left, bottom - top), + box=tuple(coord * 2 for coord in bbox), + ) + else: + im_cropped = im.crop(bbox) + im.close() + return im_cropped + else: + im_resized = im.resize((right - left, bottom - top)) + im.close() + return im_resized + return im + elif sys.platform == "win32": + if window is not None: + all_screens = -1 + offset, size, data = Image.core.grabscreen_win32( + include_layered_windows, + all_screens, + int(window) if window is not None else 0, + ) + im = Image.frombytes( + "RGB", + size, + data, + # RGB, 32-bit line padding, origin lower left corner + "raw", + "BGR", + (size[0] * 3 + 3) & -4, + -1, + ) + if bbox: + x0, y0 = offset + left, top, right, bottom = bbox + im = im.crop((left - x0, top - y0, right - x0, bottom - y0)) + return im + # Cast to Optional[str] needed for Windows and macOS. + display_name: str | None = xdisplay + try: + if not Image.core.HAVE_XCB: + msg = "Pillow was built without XCB support" + raise OSError(msg) + size, data = Image.core.grabscreen_x11(display_name) + except OSError: + if display_name is None and sys.platform not in ("darwin", "win32"): + if shutil.which("gnome-screenshot"): + args = ["gnome-screenshot", "-f"] + elif shutil.which("grim"): + args = ["grim"] + elif shutil.which("spectacle"): + args = ["spectacle", "-n", "-b", "-f", "-o"] + else: + raise + fh, filepath = tempfile.mkstemp(".png") + os.close(fh) + args.append(filepath) + retcode = subprocess.call(args) + if retcode: + raise subprocess.CalledProcessError(retcode, args) + im = Image.open(filepath) + im.load() + os.unlink(filepath) + if bbox: + im_cropped = im.crop(bbox) + im.close() + return im_cropped + return im + else: + raise + else: + im = Image.frombytes("RGB", size, data, "raw", "BGRX", size[0] * 4, 1) + if bbox: + im = im.crop(bbox) + return im + + +def grabclipboard() -> Image.Image | list[str] | None: + if sys.platform == "darwin": + p = subprocess.run( + ["osascript", "-e", "get the clipboard as «class PNGf»"], + capture_output=True, + ) + if p.returncode != 0: + return None + + import binascii + + data = io.BytesIO(binascii.unhexlify(p.stdout[11:-3])) + return Image.open(data) + elif sys.platform == "win32": + fmt, data = Image.core.grabclipboard_win32() + if fmt == "file": # CF_HDROP + import struct + + o = struct.unpack_from("I", data)[0] + if data[16] == 0: + files = data[o:].decode("mbcs").split("\0") + else: + files = data[o:].decode("utf-16le").split("\0") + return files[: files.index("")] + if isinstance(data, bytes): + data = io.BytesIO(data) + if fmt == "png": + from . import PngImagePlugin + + return PngImagePlugin.PngImageFile(data) + elif fmt == "DIB": + from . import BmpImagePlugin + + return BmpImagePlugin.DibImageFile(data) + return None + else: + if os.getenv("WAYLAND_DISPLAY"): + session_type = "wayland" + elif os.getenv("DISPLAY"): + session_type = "x11" + else: # Session type check failed + session_type = None + + if shutil.which("wl-paste") and session_type in ("wayland", None): + args = ["wl-paste", "-t", "image"] + elif shutil.which("xclip") and session_type in ("x11", None): + args = ["xclip", "-selection", "clipboard", "-t", "image/png", "-o"] + else: + msg = "wl-paste or xclip is required for ImageGrab.grabclipboard() on Linux" + raise NotImplementedError(msg) + + p = subprocess.run(args, capture_output=True) + if p.returncode != 0: + err = p.stderr + for silent_error in [ + # wl-paste, when the clipboard is empty + b"Nothing is copied", + # Ubuntu/Debian wl-paste, when the clipboard is empty + b"No selection", + # Ubuntu/Debian wl-paste, when an image isn't available + b"No suitable type of content copied", + # wl-paste or Ubuntu/Debian xclip, when an image isn't available + b" not available", + # xclip, when an image isn't available + b"cannot convert ", + # xclip, when the clipboard isn't initialized + b"xclip: Error: There is no owner for the ", + ]: + if silent_error in err: + return None + msg = f"{args[0]} error" + if err: + msg += f": {err.strip().decode()}" + raise ChildProcessError(msg) + + data = io.BytesIO(p.stdout) + im = Image.open(data) + im.load() + return im diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/ImageMath.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/ImageMath.py new file mode 100644 index 000000000..dfdc50c05 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/ImageMath.py @@ -0,0 +1,314 @@ +# +# The Python Imaging Library +# $Id$ +# +# a simple math add-on for the Python Imaging Library +# +# History: +# 1999-02-15 fl Original PIL Plus release +# 2005-05-05 fl Simplified and cleaned up for PIL 1.1.6 +# 2005-09-12 fl Fixed int() and float() for Python 2.4.1 +# +# Copyright (c) 1999-2005 by Secret Labs AB +# Copyright (c) 2005 by Fredrik Lundh +# +# See the README file for information on usage and redistribution. +# +from __future__ import annotations + +import builtins + +from . import Image, _imagingmath + +TYPE_CHECKING = False +if TYPE_CHECKING: + from collections.abc import Callable + from types import CodeType + from typing import Any + + +class _Operand: + """Wraps an image operand, providing standard operators""" + + def __init__(self, im: Image.Image): + self.im = im + + def __fixup(self, im1: _Operand | float) -> Image.Image: + # convert image to suitable mode + if isinstance(im1, _Operand): + # argument was an image. + if im1.im.mode in ("1", "L"): + return im1.im.convert("I") + elif im1.im.mode in ("I", "F"): + return im1.im + else: + msg = f"unsupported mode: {im1.im.mode}" + raise ValueError(msg) + else: + # argument was a constant + if isinstance(im1, (int, float)) and self.im.mode in ("1", "L", "I"): + return Image.new("I", self.im.size, im1) + else: + return Image.new("F", self.im.size, im1) + + def apply( + self, + op: str, + im1: _Operand | float, + im2: _Operand | float | None = None, + mode: str | None = None, + ) -> _Operand: + im_1 = self.__fixup(im1) + if im2 is None: + # unary operation + out = Image.new(mode or im_1.mode, im_1.size, None) + try: + op = getattr(_imagingmath, f"{op}_{im_1.mode}") + except AttributeError as e: + msg = f"bad operand type for '{op}'" + raise TypeError(msg) from e + _imagingmath.unop(op, out.getim(), im_1.getim()) + else: + # binary operation + im_2 = self.__fixup(im2) + if im_1.mode != im_2.mode: + # convert both arguments to floating point + if im_1.mode != "F": + im_1 = im_1.convert("F") + if im_2.mode != "F": + im_2 = im_2.convert("F") + if im_1.size != im_2.size: + # crop both arguments to a common size + size = ( + min(im_1.size[0], im_2.size[0]), + min(im_1.size[1], im_2.size[1]), + ) + if im_1.size != size: + im_1 = im_1.crop((0, 0) + size) + if im_2.size != size: + im_2 = im_2.crop((0, 0) + size) + out = Image.new(mode or im_1.mode, im_1.size, None) + try: + op = getattr(_imagingmath, f"{op}_{im_1.mode}") + except AttributeError as e: + msg = f"bad operand type for '{op}'" + raise TypeError(msg) from e + _imagingmath.binop(op, out.getim(), im_1.getim(), im_2.getim()) + return _Operand(out) + + # unary operators + def __bool__(self) -> bool: + # an image is "true" if it contains at least one non-zero pixel + return self.im.getbbox() is not None + + def __abs__(self) -> _Operand: + return self.apply("abs", self) + + def __pos__(self) -> _Operand: + return self + + def __neg__(self) -> _Operand: + return self.apply("neg", self) + + # binary operators + def __add__(self, other: _Operand | float) -> _Operand: + return self.apply("add", self, other) + + def __radd__(self, other: _Operand | float) -> _Operand: + return self.apply("add", other, self) + + def __sub__(self, other: _Operand | float) -> _Operand: + return self.apply("sub", self, other) + + def __rsub__(self, other: _Operand | float) -> _Operand: + return self.apply("sub", other, self) + + def __mul__(self, other: _Operand | float) -> _Operand: + return self.apply("mul", self, other) + + def __rmul__(self, other: _Operand | float) -> _Operand: + return self.apply("mul", other, self) + + def __truediv__(self, other: _Operand | float) -> _Operand: + return self.apply("div", self, other) + + def __rtruediv__(self, other: _Operand | float) -> _Operand: + return self.apply("div", other, self) + + def __mod__(self, other: _Operand | float) -> _Operand: + return self.apply("mod", self, other) + + def __rmod__(self, other: _Operand | float) -> _Operand: + return self.apply("mod", other, self) + + def __pow__(self, other: _Operand | float) -> _Operand: + return self.apply("pow", self, other) + + def __rpow__(self, other: _Operand | float) -> _Operand: + return self.apply("pow", other, self) + + # bitwise + def __invert__(self) -> _Operand: + return self.apply("invert", self) + + def __and__(self, other: _Operand | float) -> _Operand: + return self.apply("and", self, other) + + def __rand__(self, other: _Operand | float) -> _Operand: + return self.apply("and", other, self) + + def __or__(self, other: _Operand | float) -> _Operand: + return self.apply("or", self, other) + + def __ror__(self, other: _Operand | float) -> _Operand: + return self.apply("or", other, self) + + def __xor__(self, other: _Operand | float) -> _Operand: + return self.apply("xor", self, other) + + def __rxor__(self, other: _Operand | float) -> _Operand: + return self.apply("xor", other, self) + + def __lshift__(self, other: _Operand | float) -> _Operand: + return self.apply("lshift", self, other) + + def __rshift__(self, other: _Operand | float) -> _Operand: + return self.apply("rshift", self, other) + + # logical + def __eq__(self, other: _Operand | float) -> _Operand: # type: ignore[override] + return self.apply("eq", self, other) + + def __ne__(self, other: _Operand | float) -> _Operand: # type: ignore[override] + return self.apply("ne", self, other) + + def __lt__(self, other: _Operand | float) -> _Operand: + return self.apply("lt", self, other) + + def __le__(self, other: _Operand | float) -> _Operand: + return self.apply("le", self, other) + + def __gt__(self, other: _Operand | float) -> _Operand: + return self.apply("gt", self, other) + + def __ge__(self, other: _Operand | float) -> _Operand: + return self.apply("ge", self, other) + + +# conversions +def imagemath_int(self: _Operand) -> _Operand: + return _Operand(self.im.convert("I")) + + +def imagemath_float(self: _Operand) -> _Operand: + return _Operand(self.im.convert("F")) + + +# logical +def imagemath_equal(self: _Operand, other: _Operand | float | None) -> _Operand: + return self.apply("eq", self, other, mode="I") + + +def imagemath_notequal(self: _Operand, other: _Operand | float | None) -> _Operand: + return self.apply("ne", self, other, mode="I") + + +def imagemath_min(self: _Operand, other: _Operand | float | None) -> _Operand: + return self.apply("min", self, other) + + +def imagemath_max(self: _Operand, other: _Operand | float | None) -> _Operand: + return self.apply("max", self, other) + + +def imagemath_convert(self: _Operand, mode: str) -> _Operand: + return _Operand(self.im.convert(mode)) + + +ops = { + "int": imagemath_int, + "float": imagemath_float, + "equal": imagemath_equal, + "notequal": imagemath_notequal, + "min": imagemath_min, + "max": imagemath_max, + "convert": imagemath_convert, +} + + +def lambda_eval(expression: Callable[[dict[str, Any]], Any], **kw: Any) -> Any: + """ + Returns the result of an image function. + + :py:mod:`~PIL.ImageMath` only supports single-layer images. To process multi-band + images, use the :py:meth:`~PIL.Image.Image.split` method or + :py:func:`~PIL.Image.merge` function. + + :param expression: A function that receives a dictionary. + :param **kw: Values to add to the function's dictionary. + :return: The expression result. This is usually an image object, but can + also be an integer, a floating point value, or a pixel tuple, + depending on the expression. + """ + + args: dict[str, Any] = ops.copy() + args.update(kw) + for k, v in args.items(): + if isinstance(v, Image.Image): + args[k] = _Operand(v) + + out = expression(args) + try: + return out.im + except AttributeError: + return out + + +def unsafe_eval(expression: str, **kw: Any) -> Any: + """ + Evaluates an image expression. This uses Python's ``eval()`` function to process + the expression string, and carries the security risks of doing so. It is not + recommended to process expressions without considering this. + :py:meth:`~lambda_eval` is a more secure alternative. + + :py:mod:`~PIL.ImageMath` only supports single-layer images. To process multi-band + images, use the :py:meth:`~PIL.Image.Image.split` method or + :py:func:`~PIL.Image.merge` function. + + :param expression: A string containing a Python-style expression. + :param **kw: Values to add to the evaluation context. + :return: The evaluated expression. This is usually an image object, but can + also be an integer, a floating point value, or a pixel tuple, + depending on the expression. + """ + + # build execution namespace + args: dict[str, Any] = ops.copy() + for k in kw: + if "__" in k or hasattr(builtins, k): + msg = f"'{k}' not allowed" + raise ValueError(msg) + + args.update(kw) + for k, v in args.items(): + if isinstance(v, Image.Image): + args[k] = _Operand(v) + + compiled_code = compile(expression, "", "eval") + + def scan(code: CodeType) -> None: + for const in code.co_consts: + if type(const) is type(compiled_code): + scan(const) + + for name in code.co_names: + if name not in args and name != "abs": + msg = f"'{name}' not allowed" + raise ValueError(msg) + + scan(compiled_code) + out = builtins.eval(expression, {"__builtins": {"abs": abs}}, args) + try: + return out.im + except AttributeError: + return out diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/ImageMode.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/ImageMode.py new file mode 100644 index 000000000..b7c6c8636 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/ImageMode.py @@ -0,0 +1,85 @@ +# +# The Python Imaging Library. +# $Id$ +# +# standard mode descriptors +# +# History: +# 2006-03-20 fl Added +# +# Copyright (c) 2006 by Secret Labs AB. +# Copyright (c) 2006 by Fredrik Lundh. +# +# See the README file for information on usage and redistribution. +# +from __future__ import annotations + +import sys +from functools import lru_cache +from typing import NamedTuple + + +class ModeDescriptor(NamedTuple): + """Wrapper for mode strings.""" + + mode: str + bands: tuple[str, ...] + basemode: str + basetype: str + typestr: str + + def __str__(self) -> str: + return self.mode + + +@lru_cache +def getmode(mode: str) -> ModeDescriptor: + """Gets a mode descriptor for the given mode.""" + endian = "<" if sys.byteorder == "little" else ">" + + modes = { + # core modes + # Bits need to be extended to bytes + "1": ("L", "L", ("1",), "|b1"), + "L": ("L", "L", ("L",), "|u1"), + "I": ("L", "I", ("I",), f"{endian}i4"), + "F": ("L", "F", ("F",), f"{endian}f4"), + "P": ("P", "L", ("P",), "|u1"), + "RGB": ("RGB", "L", ("R", "G", "B"), "|u1"), + "RGBX": ("RGB", "L", ("R", "G", "B", "X"), "|u1"), + "RGBA": ("RGB", "L", ("R", "G", "B", "A"), "|u1"), + "CMYK": ("RGB", "L", ("C", "M", "Y", "K"), "|u1"), + "YCbCr": ("RGB", "L", ("Y", "Cb", "Cr"), "|u1"), + # UNDONE - unsigned |u1i1i1 + "LAB": ("RGB", "L", ("L", "A", "B"), "|u1"), + "HSV": ("RGB", "L", ("H", "S", "V"), "|u1"), + # extra experimental modes + "RGBa": ("RGB", "L", ("R", "G", "B", "a"), "|u1"), + "LA": ("L", "L", ("L", "A"), "|u1"), + "La": ("L", "L", ("L", "a"), "|u1"), + "PA": ("RGB", "L", ("P", "A"), "|u1"), + } + if mode in modes: + base_mode, base_type, bands, type_str = modes[mode] + return ModeDescriptor(mode, bands, base_mode, base_type, type_str) + + mapping_modes = { + # I;16 == I;16L, and I;32 == I;32L + "I;16": "u2", + "I;16BS": ">i2", + "I;16N": f"{endian}u2", + "I;16NS": f"{endian}i2", + "I;32": "u4", + "I;32L": "i4", + "I;32LS": " +from __future__ import annotations + +import re + +from . import Image, _imagingmorph + +LUT_SIZE = 1 << 9 + +# fmt: off +ROTATION_MATRIX = [ + 6, 3, 0, + 7, 4, 1, + 8, 5, 2, +] +MIRROR_MATRIX = [ + 2, 1, 0, + 5, 4, 3, + 8, 7, 6, +] +# fmt: on + + +class LutBuilder: + """A class for building a MorphLut from a descriptive language + + The input patterns is a list of a strings sequences like these:: + + 4:(... + .1. + 111)->1 + + (whitespaces including linebreaks are ignored). The option 4 + describes a series of symmetry operations (in this case a + 4-rotation), the pattern is described by: + + - . or X - Ignore + - 1 - Pixel is on + - 0 - Pixel is off + + The result of the operation is described after "->" string. + + The default is to return the current pixel value, which is + returned if no other match is found. + + Operations: + + - 4 - 4 way rotation + - N - Negate + - 1 - Dummy op for no other operation (an op must always be given) + - M - Mirroring + + Example:: + + lb = LutBuilder(patterns = ["4:(... .1. 111)->1"]) + lut = lb.build_lut() + + """ + + def __init__( + self, patterns: list[str] | None = None, op_name: str | None = None + ) -> None: + """ + :param patterns: A list of input patterns, or None. + :param op_name: The name of a known pattern. One of "corner", "dilation4", + "dilation8", "erosion4", "erosion8" or "edge". + :exception Exception: If the op_name is not recognized. + """ + self.lut: bytearray | None = None + if op_name is not None: + known_patterns = { + "corner": ["1:(... ... ...)->0", "4:(00. 01. ...)->1"], + "dilation4": ["4:(... .0. .1.)->1"], + "dilation8": ["4:(... .0. .1.)->1", "4:(... .0. ..1)->1"], + "erosion4": ["4:(... .1. .0.)->0"], + "erosion8": ["4:(... .1. .0.)->0", "4:(... .1. ..0)->0"], + "edge": [ + "1:(... ... ...)->0", + "4:(.0. .1. ...)->1", + "4:(01. .1. ...)->1", + ], + } + if op_name not in known_patterns: + msg = f"Unknown pattern {op_name}!" + raise Exception(msg) + + self.patterns = known_patterns[op_name] + elif patterns is not None: + self.patterns = patterns + else: + self.patterns = [] + + def add_patterns(self, patterns: list[str]) -> None: + """ + Append to list of patterns. + + :param patterns: Additional patterns. + """ + self.patterns += patterns + + def build_default_lut(self) -> bytearray: + """ + Set the current LUT, and return it. + + This is the default LUT that patterns will be applied against when building. + """ + symbols = [0, 1] + m = 1 << 4 # pos of current pixel + self.lut = bytearray(symbols[(i & m) > 0] for i in range(LUT_SIZE)) + return self.lut + + def get_lut(self) -> bytearray | None: + """ + Returns the current LUT + """ + return self.lut + + def _string_permute(self, pattern: str, permutation: list[int]) -> str: + """Takes a pattern and a permutation and returns the + string permuted according to the permutation list. + """ + assert len(permutation) == 9 + return "".join(pattern[p] for p in permutation) + + def _pattern_permute( + self, basic_pattern: str, options: str, basic_result: int + ) -> list[tuple[str, int]]: + """Takes a basic pattern and its result and clones + the pattern according to the modifications described in the $options + parameter. It returns a list of all cloned patterns.""" + patterns = [(basic_pattern, basic_result)] + + # rotations + if "4" in options: + res = patterns[-1][1] + for i in range(4): + patterns.append( + (self._string_permute(patterns[-1][0], ROTATION_MATRIX), res) + ) + # mirror + if "M" in options: + n = len(patterns) + for pattern, res in patterns[:n]: + patterns.append((self._string_permute(pattern, MIRROR_MATRIX), res)) + + # negate + if "N" in options: + n = len(patterns) + for pattern, res in patterns[:n]: + # Swap 0 and 1 + pattern = pattern.replace("0", "Z").replace("1", "0").replace("Z", "1") + res = 1 - int(res) + patterns.append((pattern, res)) + + return patterns + + def build_lut(self) -> bytearray: + """Compile all patterns into a morphology LUT, and return it. + + This is the data to be passed into MorphOp.""" + self.build_default_lut() + assert self.lut is not None + patterns = [] + + # Parse and create symmetries of the patterns strings + for p in self.patterns: + m = re.search(r"(\w):?\s*\((.+?)\)\s*->\s*(\d)", p.replace("\n", "")) + if not m: + msg = 'Syntax error in pattern "' + p + '"' + raise Exception(msg) + options = m.group(1) + pattern = m.group(2) + result = int(m.group(3)) + + # Get rid of spaces + pattern = pattern.replace(" ", "").replace("\n", "") + + patterns += self._pattern_permute(pattern, options, result) + + # Compile the patterns into regular expressions for speed + compiled_patterns = [] + for pattern in patterns: + p = pattern[0].replace(".", "X").replace("X", "[01]") + compiled_patterns.append((re.compile(p), pattern[1])) + + # Step through table and find patterns that match. + # Note that all the patterns are searched. The last one found takes priority + for i in range(LUT_SIZE): + # Build the bit pattern + bitpattern = bin(i)[2:] + bitpattern = ("0" * (9 - len(bitpattern)) + bitpattern)[::-1] + + for pattern, r in compiled_patterns: + if pattern.match(bitpattern): + self.lut[i] = [0, 1][r] + + return self.lut + + +class MorphOp: + """A class for binary morphological operators""" + + def __init__( + self, + lut: bytearray | None = None, + op_name: str | None = None, + patterns: list[str] | None = None, + ) -> None: + """Create a binary morphological operator. + + If the LUT is not provided, then it is built using LutBuilder from the op_name + or the patterns. + + :param lut: The LUT data. + :param patterns: A list of input patterns, or None. + :param op_name: The name of a known pattern. One of "corner", "dilation4", + "dilation8", "erosion4", "erosion8", "edge". + :exception Exception: If the op_name is not recognized. + """ + if patterns is None and op_name is None: + self.lut = lut + else: + self.lut = LutBuilder(patterns, op_name).build_lut() + + def apply(self, image: Image.Image) -> tuple[int, Image.Image]: + """Run a single morphological operation on an image. + + Returns a tuple of the number of changed pixels and the + morphed image. + + :param image: A 1-mode or L-mode image. + :exception Exception: If the current operator is None. + :exception ValueError: If the image is not 1 or L mode.""" + if self.lut is None: + msg = "No operator loaded" + raise Exception(msg) + + if image.mode not in ("1", "L"): + msg = "Image mode must be 1 or L" + raise ValueError(msg) + outimage = Image.new(image.mode, image.size) + count = _imagingmorph.apply(bytes(self.lut), image.getim(), outimage.getim()) + return count, outimage + + def match(self, image: Image.Image) -> list[tuple[int, int]]: + """Get a list of coordinates matching the morphological operation on + an image. + + Returns a list of tuples of (x,y) coordinates of all matching pixels. See + :ref:`coordinate-system`. + + :param image: A 1-mode or L-mode image. + :exception Exception: If the current operator is None. + :exception ValueError: If the image is not 1 or L mode.""" + if self.lut is None: + msg = "No operator loaded" + raise Exception(msg) + + if image.mode not in ("1", "L"): + msg = "Image mode must be 1 or L" + raise ValueError(msg) + return _imagingmorph.match(bytes(self.lut), image.getim()) + + def get_on_pixels(self, image: Image.Image) -> list[tuple[int, int]]: + """Get a list of all turned on pixels in a 1 or L mode image. + + Returns a list of tuples of (x,y) coordinates of all non-empty pixels. See + :ref:`coordinate-system`. + + :param image: A 1-mode or L-mode image. + :exception ValueError: If the image is not 1 or L mode.""" + + if image.mode not in ("1", "L"): + msg = "Image mode must be 1 or L" + raise ValueError(msg) + return _imagingmorph.get_on_pixels(image.getim()) + + def load_lut(self, filename: str) -> None: + """ + Load an operator from an mrl file + + :param filename: The file to read from. + :exception Exception: If the length of the file data is not 512. + """ + with open(filename, "rb") as f: + self.lut = bytearray(f.read()) + + if len(self.lut) != LUT_SIZE: + self.lut = None + msg = "Wrong size operator file!" + raise Exception(msg) + + def save_lut(self, filename: str) -> None: + """ + Save an operator to an mrl file. + + :param filename: The destination file. + :exception Exception: If the current operator is None. + """ + if self.lut is None: + msg = "No operator loaded" + raise Exception(msg) + with open(filename, "wb") as f: + f.write(self.lut) + + def set_lut(self, lut: bytearray | None) -> None: + """ + Set the LUT from an external source + + :param lut: A new LUT. + """ + self.lut = lut diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/ImageOps.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/ImageOps.py new file mode 100644 index 000000000..42b10bd7b --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/ImageOps.py @@ -0,0 +1,746 @@ +# +# The Python Imaging Library. +# $Id$ +# +# standard image operations +# +# History: +# 2001-10-20 fl Created +# 2001-10-23 fl Added autocontrast operator +# 2001-12-18 fl Added Kevin's fit operator +# 2004-03-14 fl Fixed potential division by zero in equalize +# 2005-05-05 fl Fixed equalize for low number of values +# +# Copyright (c) 2001-2004 by Secret Labs AB +# Copyright (c) 2001-2004 by Fredrik Lundh +# +# See the README file for information on usage and redistribution. +# +from __future__ import annotations + +import functools +import operator +import re +from collections.abc import Sequence +from typing import Literal, Protocol, cast, overload + +from . import ExifTags, Image, ImagePalette + +# +# helpers + + +def _border(border: int | tuple[int, ...]) -> tuple[int, int, int, int]: + if isinstance(border, tuple): + if len(border) == 2: + left, top = right, bottom = border + elif len(border) == 4: + left, top, right, bottom = border + else: + left = top = right = bottom = border + return left, top, right, bottom + + +def _color(color: str | int | tuple[int, ...], mode: str) -> int | tuple[int, ...]: + if isinstance(color, str): + from . import ImageColor + + color = ImageColor.getcolor(color, mode) + return color + + +def _lut(image: Image.Image, lut: list[int]) -> Image.Image: + if image.mode == "P": + # FIXME: apply to lookup table, not image data + msg = "mode P support coming soon" + raise NotImplementedError(msg) + elif image.mode in ("L", "RGB"): + if image.mode == "RGB" and len(lut) == 256: + lut = lut + lut + lut + return image.point(lut) + else: + msg = f"not supported for mode {image.mode}" + raise OSError(msg) + + +# +# actions + + +def autocontrast( + image: Image.Image, + cutoff: float | tuple[float, float] = 0, + ignore: int | Sequence[int] | None = None, + mask: Image.Image | None = None, + preserve_tone: bool = False, +) -> Image.Image: + """ + Maximize (normalize) image contrast. This function calculates a + histogram of the input image (or mask region), removes ``cutoff`` percent of the + lightest and darkest pixels from the histogram, and remaps the image + so that the darkest pixel becomes black (0), and the lightest + becomes white (255). + + :param image: The image to process. + :param cutoff: The percent to cut off from the histogram on the low and + high ends. Either a tuple of (low, high), or a single + number for both. + :param ignore: The background pixel value (use None for no background). + :param mask: Histogram used in contrast operation is computed using pixels + within the mask. If no mask is given the entire image is used + for histogram computation. + :param preserve_tone: Preserve image tone in Photoshop-like style autocontrast. + + .. versionadded:: 8.2.0 + + :return: An image. + """ + if preserve_tone: + histogram = image.convert("L").histogram(mask) + else: + histogram = image.histogram(mask) + + lut = [] + for layer in range(0, len(histogram), 256): + h = histogram[layer : layer + 256] + if ignore is not None: + # get rid of outliers + if isinstance(ignore, int): + h[ignore] = 0 + else: + for ix in ignore: + h[ix] = 0 + if cutoff: + # cut off pixels from both ends of the histogram + if not isinstance(cutoff, tuple): + cutoff = (cutoff, cutoff) + # get number of pixels + n = 0 + for ix in range(256): + n = n + h[ix] + # remove cutoff% pixels from the low end + cut = int(n * cutoff[0] // 100) + for lo in range(256): + if cut > h[lo]: + cut = cut - h[lo] + h[lo] = 0 + else: + h[lo] -= cut + cut = 0 + if cut <= 0: + break + # remove cutoff% samples from the high end + cut = int(n * cutoff[1] // 100) + for hi in range(255, -1, -1): + if cut > h[hi]: + cut = cut - h[hi] + h[hi] = 0 + else: + h[hi] -= cut + cut = 0 + if cut <= 0: + break + # find lowest/highest samples after preprocessing + for lo in range(256): + if h[lo]: + break + for hi in range(255, -1, -1): + if h[hi]: + break + if hi <= lo: + # don't bother + lut.extend(list(range(256))) + else: + scale = 255.0 / (hi - lo) + offset = -lo * scale + for ix in range(256): + ix = int(ix * scale + offset) + if ix < 0: + ix = 0 + elif ix > 255: + ix = 255 + lut.append(ix) + return _lut(image, lut) + + +def colorize( + image: Image.Image, + black: str | tuple[int, ...], + white: str | tuple[int, ...], + mid: str | int | tuple[int, ...] | None = None, + blackpoint: int = 0, + whitepoint: int = 255, + midpoint: int = 127, +) -> Image.Image: + """ + Colorize grayscale image. + This function calculates a color wedge which maps all black pixels in + the source image to the first color and all white pixels to the + second color. If ``mid`` is specified, it uses three-color mapping. + The ``black`` and ``white`` arguments should be RGB tuples or color names; + optionally you can use three-color mapping by also specifying ``mid``. + Mapping positions for any of the colors can be specified + (e.g. ``blackpoint``), where these parameters are the integer + value corresponding to where the corresponding color should be mapped. + These parameters must have logical order, such that + ``blackpoint <= midpoint <= whitepoint`` (if ``mid`` is specified). + + :param image: The image to colorize. + :param black: The color to use for black input pixels. + :param white: The color to use for white input pixels. + :param mid: The color to use for midtone input pixels. + :param blackpoint: an int value [0, 255] for the black mapping. + :param whitepoint: an int value [0, 255] for the white mapping. + :param midpoint: an int value [0, 255] for the midtone mapping. + :return: An image. + """ + + # Initial asserts + assert image.mode == "L" + if mid is None: + assert 0 <= blackpoint <= whitepoint <= 255 + else: + assert 0 <= blackpoint <= midpoint <= whitepoint <= 255 + + # Define colors from arguments + rgb_black = cast(Sequence[int], _color(black, "RGB")) + rgb_white = cast(Sequence[int], _color(white, "RGB")) + rgb_mid = cast(Sequence[int], _color(mid, "RGB")) if mid is not None else None + + # Empty lists for the mapping + red = [] + green = [] + blue = [] + + # Create the low-end values + for i in range(blackpoint): + red.append(rgb_black[0]) + green.append(rgb_black[1]) + blue.append(rgb_black[2]) + + # Create the mapping (2-color) + if rgb_mid is None: + range_map = range(whitepoint - blackpoint) + + for i in range_map: + red.append( + rgb_black[0] + i * (rgb_white[0] - rgb_black[0]) // len(range_map) + ) + green.append( + rgb_black[1] + i * (rgb_white[1] - rgb_black[1]) // len(range_map) + ) + blue.append( + rgb_black[2] + i * (rgb_white[2] - rgb_black[2]) // len(range_map) + ) + + # Create the mapping (3-color) + else: + range_map1 = range(midpoint - blackpoint) + range_map2 = range(whitepoint - midpoint) + + for i in range_map1: + red.append( + rgb_black[0] + i * (rgb_mid[0] - rgb_black[0]) // len(range_map1) + ) + green.append( + rgb_black[1] + i * (rgb_mid[1] - rgb_black[1]) // len(range_map1) + ) + blue.append( + rgb_black[2] + i * (rgb_mid[2] - rgb_black[2]) // len(range_map1) + ) + for i in range_map2: + red.append(rgb_mid[0] + i * (rgb_white[0] - rgb_mid[0]) // len(range_map2)) + green.append( + rgb_mid[1] + i * (rgb_white[1] - rgb_mid[1]) // len(range_map2) + ) + blue.append(rgb_mid[2] + i * (rgb_white[2] - rgb_mid[2]) // len(range_map2)) + + # Create the high-end values + for i in range(256 - whitepoint): + red.append(rgb_white[0]) + green.append(rgb_white[1]) + blue.append(rgb_white[2]) + + # Return converted image + image = image.convert("RGB") + return _lut(image, red + green + blue) + + +def contain( + image: Image.Image, size: tuple[int, int], method: int = Image.Resampling.BICUBIC +) -> Image.Image: + """ + Returns a resized version of the image, set to the maximum width and height + within the requested size, while maintaining the original aspect ratio. + + :param image: The image to resize. + :param size: The requested output size in pixels, given as a + (width, height) tuple. + :param method: Resampling method to use. Default is + :py:attr:`~PIL.Image.Resampling.BICUBIC`. + See :ref:`concept-filters`. + :return: An image. + """ + + im_ratio = image.width / image.height + dest_ratio = size[0] / size[1] + + if im_ratio != dest_ratio: + if im_ratio > dest_ratio: + new_height = round(image.height / image.width * size[0]) + if new_height != size[1]: + size = (size[0], new_height) + else: + new_width = round(image.width / image.height * size[1]) + if new_width != size[0]: + size = (new_width, size[1]) + return image.resize(size, resample=method) + + +def cover( + image: Image.Image, size: tuple[int, int], method: int = Image.Resampling.BICUBIC +) -> Image.Image: + """ + Returns a resized version of the image, so that the requested size is + covered, while maintaining the original aspect ratio. + + :param image: The image to resize. + :param size: The requested output size in pixels, given as a + (width, height) tuple. + :param method: Resampling method to use. Default is + :py:attr:`~PIL.Image.Resampling.BICUBIC`. + See :ref:`concept-filters`. + :return: An image. + """ + + im_ratio = image.width / image.height + dest_ratio = size[0] / size[1] + + if im_ratio != dest_ratio: + if im_ratio < dest_ratio: + new_height = round(image.height / image.width * size[0]) + if new_height != size[1]: + size = (size[0], new_height) + else: + new_width = round(image.width / image.height * size[1]) + if new_width != size[0]: + size = (new_width, size[1]) + return image.resize(size, resample=method) + + +def pad( + image: Image.Image, + size: tuple[int, int], + method: int = Image.Resampling.BICUBIC, + color: str | int | tuple[int, ...] | None = None, + centering: tuple[float, float] = (0.5, 0.5), +) -> Image.Image: + """ + Returns a resized and padded version of the image, expanded to fill the + requested aspect ratio and size. + + :param image: The image to resize and crop. + :param size: The requested output size in pixels, given as a + (width, height) tuple. + :param method: Resampling method to use. Default is + :py:attr:`~PIL.Image.Resampling.BICUBIC`. + See :ref:`concept-filters`. + :param color: The background color of the padded image. + :param centering: Control the position of the original image within the + padded version. + + (0.5, 0.5) will keep the image centered + (0, 0) will keep the image aligned to the top left + (1, 1) will keep the image aligned to the bottom + right + :return: An image. + """ + + resized = contain(image, size, method) + if resized.size == size: + out = resized + else: + out = Image.new(image.mode, size, color) + if resized.palette: + palette = resized.getpalette() + if palette is not None: + out.putpalette(palette) + if resized.width != size[0]: + x = round((size[0] - resized.width) * max(0, min(centering[0], 1))) + out.paste(resized, (x, 0)) + else: + y = round((size[1] - resized.height) * max(0, min(centering[1], 1))) + out.paste(resized, (0, y)) + return out + + +def crop(image: Image.Image, border: int = 0) -> Image.Image: + """ + Remove border from image. The same amount of pixels are removed + from all four sides. This function works on all image modes. + + .. seealso:: :py:meth:`~PIL.Image.Image.crop` + + :param image: The image to crop. + :param border: The number of pixels to remove. + :return: An image. + """ + left, top, right, bottom = _border(border) + return image.crop((left, top, image.size[0] - right, image.size[1] - bottom)) + + +def scale( + image: Image.Image, factor: float, resample: int = Image.Resampling.BICUBIC +) -> Image.Image: + """ + Returns a rescaled image by a specific factor given in parameter. + A factor greater than 1 expands the image, between 0 and 1 contracts the + image. + + :param image: The image to rescale. + :param factor: The expansion factor, as a float. + :param resample: Resampling method to use. Default is + :py:attr:`~PIL.Image.Resampling.BICUBIC`. + See :ref:`concept-filters`. + :returns: An :py:class:`~PIL.Image.Image` object. + """ + if factor == 1: + return image.copy() + elif factor <= 0: + msg = "the factor must be greater than 0" + raise ValueError(msg) + else: + size = (round(factor * image.width), round(factor * image.height)) + return image.resize(size, resample) + + +class SupportsGetMesh(Protocol): + """ + An object that supports the ``getmesh`` method, taking an image as an + argument, and returning a list of tuples. Each tuple contains two tuples, + the source box as a tuple of 4 integers, and a tuple of 8 integers for the + final quadrilateral, in order of top left, bottom left, bottom right, top + right. + """ + + def getmesh( + self, image: Image.Image + ) -> list[ + tuple[tuple[int, int, int, int], tuple[int, int, int, int, int, int, int, int]] + ]: ... + + +def deform( + image: Image.Image, + deformer: SupportsGetMesh, + resample: int = Image.Resampling.BILINEAR, +) -> Image.Image: + """ + Deform the image. + + :param image: The image to deform. + :param deformer: A deformer object. Any object that implements a + ``getmesh`` method can be used. + :param resample: An optional resampling filter. Same values possible as + in the PIL.Image.transform function. + :return: An image. + """ + return image.transform( + image.size, Image.Transform.MESH, deformer.getmesh(image), resample + ) + + +def equalize(image: Image.Image, mask: Image.Image | None = None) -> Image.Image: + """ + Equalize the image histogram. This function applies a non-linear + mapping to the input image, in order to create a uniform + distribution of grayscale values in the output image. + + :param image: The image to equalize. + :param mask: An optional mask. If given, only the pixels selected by + the mask are included in the analysis. + :return: An image. + """ + if image.mode == "P": + image = image.convert("RGB") + h = image.histogram(mask) + lut = [] + for b in range(0, len(h), 256): + histo = [_f for _f in h[b : b + 256] if _f] + if len(histo) <= 1: + lut.extend(list(range(256))) + else: + step = (functools.reduce(operator.add, histo) - histo[-1]) // 255 + if not step: + lut.extend(list(range(256))) + else: + n = step // 2 + for i in range(256): + lut.append(n // step) + n = n + h[i + b] + return _lut(image, lut) + + +def expand( + image: Image.Image, + border: int | tuple[int, ...] = 0, + fill: str | int | tuple[int, ...] = 0, +) -> Image.Image: + """ + Add border to the image + + :param image: The image to expand. + :param border: Border width, in pixels. + :param fill: Pixel fill value (a color value). Default is 0 (black). + :return: An image. + """ + left, top, right, bottom = _border(border) + width = left + image.size[0] + right + height = top + image.size[1] + bottom + color = _color(fill, image.mode) + if image.palette: + mode = image.palette.mode + palette = ImagePalette.ImagePalette(mode, image.getpalette(mode)) + if isinstance(color, tuple) and (len(color) == 3 or len(color) == 4): + color = palette.getcolor(color) + else: + palette = None + out = Image.new(image.mode, (width, height), color) + if palette: + out.putpalette(palette.palette, mode) + out.paste(image, (left, top)) + return out + + +def fit( + image: Image.Image, + size: tuple[int, int], + method: int = Image.Resampling.BICUBIC, + bleed: float = 0.0, + centering: tuple[float, float] = (0.5, 0.5), +) -> Image.Image: + """ + Returns a resized and cropped version of the image, cropped to the + requested aspect ratio and size. + + This function was contributed by Kevin Cazabon. + + :param image: The image to resize and crop. + :param size: The requested output size in pixels, given as a + (width, height) tuple. + :param method: Resampling method to use. Default is + :py:attr:`~PIL.Image.Resampling.BICUBIC`. + See :ref:`concept-filters`. + :param bleed: Remove a border around the outside of the image from all + four edges. The value is a decimal percentage (use 0.01 for + one percent). The default value is 0 (no border). + Cannot be greater than or equal to 0.5. + :param centering: Control the cropping position. Use (0.5, 0.5) for + center cropping (e.g. if cropping the width, take 50% off + of the left side, and therefore 50% off the right side). + (0.0, 0.0) will crop from the top left corner (i.e. if + cropping the width, take all of the crop off of the right + side, and if cropping the height, take all of it off the + bottom). (1.0, 0.0) will crop from the bottom left + corner, etc. (i.e. if cropping the width, take all of the + crop off the left side, and if cropping the height take + none from the top, and therefore all off the bottom). + :return: An image. + """ + + # by Kevin Cazabon, Feb 17/2000 + # kevin@cazabon.com + # https://www.cazabon.com + + centering_x, centering_y = centering + + if not 0.0 <= centering_x <= 1.0: + centering_x = 0.5 + if not 0.0 <= centering_y <= 1.0: + centering_y = 0.5 + + if not 0.0 <= bleed < 0.5: + bleed = 0.0 + + # calculate the area to use for resizing and cropping, subtracting + # the 'bleed' around the edges + + # number of pixels to trim off on Top and Bottom, Left and Right + bleed_pixels = (bleed * image.size[0], bleed * image.size[1]) + + live_size = ( + image.size[0] - bleed_pixels[0] * 2, + image.size[1] - bleed_pixels[1] * 2, + ) + + # calculate the aspect ratio of the live_size + live_size_ratio = live_size[0] / live_size[1] + + # calculate the aspect ratio of the output image + output_ratio = size[0] / size[1] + + # figure out if the sides or top/bottom will be cropped off + if live_size_ratio == output_ratio: + # live_size is already the needed ratio + crop_width = live_size[0] + crop_height = live_size[1] + elif live_size_ratio >= output_ratio: + # live_size is wider than what's needed, crop the sides + crop_width = output_ratio * live_size[1] + crop_height = live_size[1] + else: + # live_size is taller than what's needed, crop the top and bottom + crop_width = live_size[0] + crop_height = live_size[0] / output_ratio + + # make the crop + crop_left = bleed_pixels[0] + (live_size[0] - crop_width) * centering_x + crop_top = bleed_pixels[1] + (live_size[1] - crop_height) * centering_y + + crop = (crop_left, crop_top, crop_left + crop_width, crop_top + crop_height) + + # resize the image and return it + return image.resize(size, method, box=crop) + + +def flip(image: Image.Image) -> Image.Image: + """ + Flip the image vertically (top to bottom). + + :param image: The image to flip. + :return: An image. + """ + return image.transpose(Image.Transpose.FLIP_TOP_BOTTOM) + + +def grayscale(image: Image.Image) -> Image.Image: + """ + Convert the image to grayscale. + + :param image: The image to convert. + :return: An image. + """ + return image.convert("L") + + +def invert(image: Image.Image) -> Image.Image: + """ + Invert (negate) the image. + + :param image: The image to invert. + :return: An image. + """ + lut = list(range(255, -1, -1)) + return image.point(lut) if image.mode == "1" else _lut(image, lut) + + +def mirror(image: Image.Image) -> Image.Image: + """ + Flip image horizontally (left to right). + + :param image: The image to mirror. + :return: An image. + """ + return image.transpose(Image.Transpose.FLIP_LEFT_RIGHT) + + +def posterize(image: Image.Image, bits: int) -> Image.Image: + """ + Reduce the number of bits for each color channel. + + :param image: The image to posterize. + :param bits: The number of bits to keep for each channel (1-8). + :return: An image. + """ + mask = ~(2 ** (8 - bits) - 1) + lut = [i & mask for i in range(256)] + return _lut(image, lut) + + +def solarize(image: Image.Image, threshold: int = 128) -> Image.Image: + """ + Invert all pixel values above a threshold. + + :param image: The image to solarize. + :param threshold: All pixels above this grayscale level are inverted. + :return: An image. + """ + lut = [] + for i in range(256): + if i < threshold: + lut.append(i) + else: + lut.append(255 - i) + return _lut(image, lut) + + +@overload +def exif_transpose(image: Image.Image, *, in_place: Literal[True]) -> None: ... + + +@overload +def exif_transpose( + image: Image.Image, *, in_place: Literal[False] = False +) -> Image.Image: ... + + +def exif_transpose(image: Image.Image, *, in_place: bool = False) -> Image.Image | None: + """ + If an image has an EXIF Orientation tag, other than 1, transpose the image + accordingly, and remove the orientation data. + + :param image: The image to transpose. + :param in_place: Boolean. Keyword-only argument. + If ``True``, the original image is modified in-place, and ``None`` is returned. + If ``False`` (default), a new :py:class:`~PIL.Image.Image` object is returned + with the transposition applied. If there is no transposition, a copy of the + image will be returned. + """ + image.load() + image_exif = image.getexif() + orientation = image_exif.get(ExifTags.Base.Orientation, 1) + method = { + 2: Image.Transpose.FLIP_LEFT_RIGHT, + 3: Image.Transpose.ROTATE_180, + 4: Image.Transpose.FLIP_TOP_BOTTOM, + 5: Image.Transpose.TRANSPOSE, + 6: Image.Transpose.ROTATE_270, + 7: Image.Transpose.TRANSVERSE, + 8: Image.Transpose.ROTATE_90, + }.get(orientation) + if method is not None: + if in_place: + image.im = image.im.transpose(method) + image._size = image.im.size + else: + transposed_image = image.transpose(method) + exif_image = image if in_place else transposed_image + + exif = exif_image.getexif() + if ExifTags.Base.Orientation in exif: + del exif[ExifTags.Base.Orientation] + if "exif" in exif_image.info: + exif_image.info["exif"] = exif.tobytes() + elif "Raw profile type exif" in exif_image.info: + exif_image.info["Raw profile type exif"] = exif.tobytes().hex() + for key in ("XML:com.adobe.xmp", "xmp"): + if key in exif_image.info: + for pattern in ( + r'tiff:Orientation="([0-9])"', + r"([0-9])", + ): + value = exif_image.info[key] + if isinstance(value, str): + value = re.sub(pattern, "", value) + elif isinstance(value, tuple): + value = tuple( + re.sub(pattern.encode(), b"", v) for v in value + ) + else: + value = re.sub(pattern.encode(), b"", value) + exif_image.info[key] = value + if not in_place: + return transposed_image + elif not in_place: + return image.copy() + return None diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/ImagePalette.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/ImagePalette.py new file mode 100644 index 000000000..2abbd46ea --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/ImagePalette.py @@ -0,0 +1,290 @@ +# +# The Python Imaging Library. +# $Id$ +# +# image palette object +# +# History: +# 1996-03-11 fl Rewritten. +# 1997-01-03 fl Up and running. +# 1997-08-23 fl Added load hack +# 2001-04-16 fl Fixed randint shadow bug in random() +# +# Copyright (c) 1997-2001 by Secret Labs AB +# Copyright (c) 1996-1997 by Fredrik Lundh +# +# See the README file for information on usage and redistribution. +# +from __future__ import annotations + +import array +from collections.abc import Sequence +from typing import IO + +from . import GimpGradientFile, GimpPaletteFile, ImageColor, PaletteFile + +TYPE_CHECKING = False +if TYPE_CHECKING: + from . import Image + + +class ImagePalette: + """ + Color palette for palette mapped images + + :param mode: The mode to use for the palette. See: + :ref:`concept-modes`. Defaults to "RGB" + :param palette: An optional palette. If given, it must be a bytearray, + an array or a list of ints between 0-255. The list must consist of + all channels for one color followed by the next color (e.g. RGBRGBRGB). + Defaults to an empty palette. + """ + + def __init__( + self, + mode: str = "RGB", + palette: Sequence[int] | bytes | bytearray | None = None, + ) -> None: + self.mode = mode + self.rawmode: str | None = None # if set, palette contains raw data + self.palette = palette or bytearray() + self.dirty: int | None = None + + @property + def palette(self) -> Sequence[int] | bytes | bytearray: + return self._palette + + @palette.setter + def palette(self, palette: Sequence[int] | bytes | bytearray) -> None: + self._colors: dict[tuple[int, ...], int] | None = None + self._palette = palette + + @property + def colors(self) -> dict[tuple[int, ...], int]: + if self._colors is None: + mode_len = len(self.mode) + self._colors = {} + for i in range(0, len(self.palette), mode_len): + color = tuple(self.palette[i : i + mode_len]) + if color in self._colors: + continue + self._colors[color] = i // mode_len + return self._colors + + @colors.setter + def colors(self, colors: dict[tuple[int, ...], int]) -> None: + self._colors = colors + + def copy(self) -> ImagePalette: + new = ImagePalette() + + new.mode = self.mode + new.rawmode = self.rawmode + if self.palette is not None: + new.palette = self.palette[:] + new.dirty = self.dirty + + return new + + def getdata(self) -> tuple[str, Sequence[int] | bytes | bytearray]: + """ + Get palette contents in format suitable for the low-level + ``im.putpalette`` primitive. + + .. warning:: This method is experimental. + """ + if self.rawmode: + return self.rawmode, self.palette + return self.mode, self.tobytes() + + def tobytes(self) -> bytes: + """Convert palette to bytes. + + .. warning:: This method is experimental. + """ + if self.rawmode: + msg = "palette contains raw palette data" + raise ValueError(msg) + if isinstance(self.palette, bytes): + return self.palette + arr = array.array("B", self.palette) + return arr.tobytes() + + # Declare tostring as an alias for tobytes + tostring = tobytes + + def _new_color_index( + self, image: Image.Image | None = None, e: Exception | None = None + ) -> int: + if not isinstance(self.palette, bytearray): + self._palette = bytearray(self.palette) + index = len(self.palette) // len(self.mode) + special_colors: tuple[int | tuple[int, ...] | None, ...] = () + if image: + special_colors = ( + image.info.get("background"), + image.info.get("transparency"), + ) + while index in special_colors: + index += 1 + if index >= 256: + if image: + # Search for an unused index + for i, count in reversed(list(enumerate(image.histogram()))): + if count == 0 and i not in special_colors: + index = i + break + if index >= 256: + msg = "cannot allocate more than 256 colors" + raise ValueError(msg) from e + return index + + def getcolor( + self, + color: tuple[int, ...], + image: Image.Image | None = None, + ) -> int: + """Given an rgb tuple, allocate palette entry. + + .. warning:: This method is experimental. + """ + if self.rawmode: + msg = "palette contains raw palette data" + raise ValueError(msg) + if isinstance(color, tuple): + if self.mode == "RGB": + if len(color) == 4: + if color[3] != 255: + msg = "cannot add non-opaque RGBA color to RGB palette" + raise ValueError(msg) + color = color[:3] + elif self.mode == "RGBA": + if len(color) == 3: + color += (255,) + try: + return self.colors[color] + except KeyError as e: + # allocate new color slot + index = self._new_color_index(image, e) + assert isinstance(self._palette, bytearray) + self.colors[color] = index + mode_len = len(self.mode) + if index * mode_len < len(self.palette): + self._palette = ( + self._palette[: index * mode_len] + + bytes(color) + + self._palette[index * mode_len + mode_len :] + ) + else: + self._palette += bytes(color) + self.dirty = 1 + return index + else: + msg = f"unknown color specifier: {repr(color)}" # type: ignore[unreachable] + raise ValueError(msg) + + def save(self, fp: str | IO[str]) -> None: + """Save palette to text file. + + .. warning:: This method is experimental. + """ + if self.rawmode: + msg = "palette contains raw palette data" + raise ValueError(msg) + open_fp = False + if isinstance(fp, str): + fp = open(fp, "w") + open_fp = True + try: + fp.write("# Palette\n") + fp.write(f"# Mode: {self.mode}\n") + palette_len = len(self.palette) + for i in range(256): + fp.write(f"{i}") + for j in range(i * len(self.mode), (i + 1) * len(self.mode)): + fp.write(f" {self.palette[j] if j < palette_len else 0}") + fp.write("\n") + finally: + if open_fp: + fp.close() + + +# -------------------------------------------------------------------- +# Internal + + +def raw(rawmode: str, data: Sequence[int] | bytes | bytearray) -> ImagePalette: + palette = ImagePalette() + palette.rawmode = rawmode + palette.palette = data + palette.dirty = 1 + return palette + + +# -------------------------------------------------------------------- +# Factories + + +def make_linear_lut(black: int, white: float) -> list[int]: + if black == 0: + return [int(white * i // 255) for i in range(256)] + + msg = "unavailable when black is non-zero" + raise NotImplementedError(msg) # FIXME + + +def make_gamma_lut(exp: float) -> list[int]: + return [int(((i / 255.0) ** exp) * 255.0 + 0.5) for i in range(256)] + + +def negative(mode: str = "RGB") -> ImagePalette: + palette = list(range(256 * len(mode))) + palette.reverse() + return ImagePalette(mode, [i // len(mode) for i in palette]) + + +def random(mode: str = "RGB") -> ImagePalette: + from random import randint + + palette = [randint(0, 255) for _ in range(256 * len(mode))] + return ImagePalette(mode, palette) + + +def sepia(white: str = "#fff0c0") -> ImagePalette: + bands = [make_linear_lut(0, band) for band in ImageColor.getrgb(white)] + return ImagePalette("RGB", [bands[i % 3][i // 3] for i in range(256 * 3)]) + + +def wedge(mode: str = "RGB") -> ImagePalette: + palette = list(range(256 * len(mode))) + return ImagePalette(mode, [i // len(mode) for i in palette]) + + +def load(filename: str) -> tuple[bytes, str]: + # FIXME: supports GIMP gradients only + + with open(filename, "rb") as fp: + paletteHandlers: list[ + type[ + GimpPaletteFile.GimpPaletteFile + | GimpGradientFile.GimpGradientFile + | PaletteFile.PaletteFile + ] + ] = [ + GimpPaletteFile.GimpPaletteFile, + GimpGradientFile.GimpGradientFile, + PaletteFile.PaletteFile, + ] + for paletteHandler in paletteHandlers: + try: + fp.seek(0) + lut = paletteHandler(fp).getpalette() + if lut: + break + except (SyntaxError, ValueError): + pass + else: + msg = "cannot load palette" + raise OSError(msg) + + return lut # data, rawmode diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/ImagePath.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/ImagePath.py new file mode 100644 index 000000000..77e8a609a --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/ImagePath.py @@ -0,0 +1,20 @@ +# +# The Python Imaging Library +# $Id$ +# +# path interface +# +# History: +# 1996-11-04 fl Created +# 2002-04-14 fl Added documentation stub class +# +# Copyright (c) Secret Labs AB 1997. +# Copyright (c) Fredrik Lundh 1996. +# +# See the README file for information on usage and redistribution. +# +from __future__ import annotations + +from . import Image + +Path = Image.core.path diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/ImageQt.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/ImageQt.py new file mode 100644 index 000000000..af4d0742d --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/ImageQt.py @@ -0,0 +1,219 @@ +# +# The Python Imaging Library. +# $Id$ +# +# a simple Qt image interface. +# +# history: +# 2006-06-03 fl: created +# 2006-06-04 fl: inherit from QImage instead of wrapping it +# 2006-06-05 fl: removed toimage helper; move string support to ImageQt +# 2013-11-13 fl: add support for Qt5 (aurelien.ballier@cyclonit.com) +# +# Copyright (c) 2006 by Secret Labs AB +# Copyright (c) 2006 by Fredrik Lundh +# +# See the README file for information on usage and redistribution. +# +from __future__ import annotations + +import sys +from io import BytesIO + +from . import Image +from ._util import is_path + +TYPE_CHECKING = False +if TYPE_CHECKING: + from collections.abc import Callable + from typing import Any + + from . import ImageFile + + QBuffer: type + +qt_version: str | None +qt_versions = [ + ["6", "PyQt6"], + ["side6", "PySide6"], +] + +# If a version has already been imported, attempt it first +qt_versions.sort(key=lambda version: version[1] in sys.modules, reverse=True) +for version, qt_module in qt_versions: + try: + qRgba: Callable[[int, int, int, int], int] + if qt_module == "PyQt6": + from PyQt6.QtCore import QBuffer, QByteArray, QIODevice + from PyQt6.QtGui import QImage, QPixmap, qRgba + elif qt_module == "PySide6": + from PySide6.QtCore import ( # type: ignore[assignment] + QBuffer, + QByteArray, + QIODevice, + ) + from PySide6.QtGui import QImage, QPixmap, qRgba # type: ignore[assignment] + except (ImportError, RuntimeError): + continue + qt_is_installed = True + qt_version = version + break +else: + qt_is_installed = False + qt_version = None + + +def rgb(r: int, g: int, b: int, a: int = 255) -> int: + """(Internal) Turns an RGB color into a Qt compatible color integer.""" + # use qRgb to pack the colors, and then turn the resulting long + # into a negative integer with the same bitpattern. + return qRgba(r, g, b, a) & 0xFFFFFFFF + + +def fromqimage(im: QImage | QPixmap) -> ImageFile.ImageFile: + """ + :param im: QImage or PIL ImageQt object + """ + buffer = QBuffer() + qt_openmode: object + if qt_version == "6": + try: + qt_openmode = getattr(QIODevice, "OpenModeFlag") + except AttributeError: + qt_openmode = getattr(QIODevice, "OpenMode") + else: + qt_openmode = QIODevice + buffer.open(getattr(qt_openmode, "ReadWrite")) + # preserve alpha channel with png + # otherwise ppm is more friendly with Image.open + if im.hasAlphaChannel(): + im.save(buffer, "png") + else: + im.save(buffer, "ppm") + + b = BytesIO() + b.write(buffer.data()) + buffer.close() + b.seek(0) + + return Image.open(b) + + +def fromqpixmap(im: QPixmap) -> ImageFile.ImageFile: + return fromqimage(im) + + +def align8to32(bytes: bytes, width: int, mode: str) -> bytes: + """ + converts each scanline of data from 8 bit to 32 bit aligned + """ + + bits_per_pixel = {"1": 1, "L": 8, "P": 8, "I;16": 16}[mode] + + # calculate bytes per line and the extra padding if needed + bits_per_line = bits_per_pixel * width + full_bytes_per_line, remaining_bits_per_line = divmod(bits_per_line, 8) + bytes_per_line = full_bytes_per_line + (1 if remaining_bits_per_line else 0) + + extra_padding = -bytes_per_line % 4 + + # already 32 bit aligned by luck + if not extra_padding: + return bytes + + new_data = [ + bytes[i * bytes_per_line : (i + 1) * bytes_per_line] + b"\x00" * extra_padding + for i in range(len(bytes) // bytes_per_line) + ] + + return b"".join(new_data) + + +def _toqclass_helper(im: Image.Image | str | QByteArray) -> dict[str, Any]: + data = None + colortable = None + exclusive_fp = False + + # handle filename, if given instead of image name + if hasattr(im, "toUtf8"): + # FIXME - is this really the best way to do this? + im = str(im.toUtf8(), "utf-8") + if is_path(im): + im = Image.open(im) + exclusive_fp = True + assert isinstance(im, Image.Image) + + qt_format = getattr(QImage, "Format") if qt_version == "6" else QImage + if im.mode == "1": + format = getattr(qt_format, "Format_Mono") + elif im.mode == "L": + format = getattr(qt_format, "Format_Indexed8") + colortable = [rgb(i, i, i) for i in range(256)] + elif im.mode == "P": + format = getattr(qt_format, "Format_Indexed8") + palette = im.getpalette() + assert palette is not None + colortable = [rgb(*palette[i : i + 3]) for i in range(0, len(palette), 3)] + elif im.mode == "RGB": + # Populate the 4th channel with 255 + im = im.convert("RGBA") + + data = im.tobytes("raw", "BGRA") + format = getattr(qt_format, "Format_RGB32") + elif im.mode == "RGBA": + data = im.tobytes("raw", "BGRA") + format = getattr(qt_format, "Format_ARGB32") + elif im.mode == "I;16": + im = im.point(lambda i: i * 256) + + format = getattr(qt_format, "Format_Grayscale16") + else: + if exclusive_fp: + im.close() + msg = f"unsupported image mode {repr(im.mode)}" + raise ValueError(msg) + + size = im.size + __data = data or align8to32(im.tobytes(), size[0], im.mode) + if exclusive_fp: + im.close() + return {"data": __data, "size": size, "format": format, "colortable": colortable} + + +if qt_is_installed: + + class ImageQt(QImage): + def __init__(self, im: Image.Image | str | QByteArray) -> None: + """ + An PIL image wrapper for Qt. This is a subclass of PyQt's QImage + class. + + :param im: A PIL Image object, or a file name (given either as + Python string or a PyQt string object). + """ + im_data = _toqclass_helper(im) + # must keep a reference, or Qt will crash! + # All QImage constructors that take data operate on an existing + # buffer, so this buffer has to hang on for the life of the image. + # Fixes https://github.com/python-pillow/Pillow/issues/1370 + self.__data = im_data["data"] + super().__init__( + self.__data, + im_data["size"][0], + im_data["size"][1], + im_data["format"], + ) + if im_data["colortable"]: + self.setColorTable(im_data["colortable"]) + + +def toqimage(im: Image.Image | str | QByteArray) -> ImageQt: + return ImageQt(im) + + +def toqpixmap(im: Image.Image | str | QByteArray) -> QPixmap: + qimage = toqimage(im) + pixmap = getattr(QPixmap, "fromImage")(qimage) + if qt_version == "6": + pixmap.detach() + return pixmap diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/ImageSequence.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/ImageSequence.py new file mode 100644 index 000000000..361be4897 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/ImageSequence.py @@ -0,0 +1,88 @@ +# +# The Python Imaging Library. +# $Id$ +# +# sequence support classes +# +# history: +# 1997-02-20 fl Created +# +# Copyright (c) 1997 by Secret Labs AB. +# Copyright (c) 1997 by Fredrik Lundh. +# +# See the README file for information on usage and redistribution. +# + +## +from __future__ import annotations + +from . import Image + +TYPE_CHECKING = False +if TYPE_CHECKING: + from collections.abc import Callable + + +class Iterator: + """ + This class implements an iterator object that can be used to loop + over an image sequence. + + You can use the ``[]`` operator to access elements by index. This operator + will raise an :py:exc:`IndexError` if you try to access a nonexistent + frame. + + :param im: An image object. + """ + + def __init__(self, im: Image.Image) -> None: + if not hasattr(im, "seek"): + msg = "im must have seek method" + raise AttributeError(msg) + self.im = im + self.position = getattr(self.im, "_min_frame", 0) + + def __getitem__(self, ix: int) -> Image.Image: + try: + self.im.seek(ix) + return self.im + except EOFError as e: + msg = "end of sequence" + raise IndexError(msg) from e + + def __iter__(self) -> Iterator: + return self + + def __next__(self) -> Image.Image: + try: + self.im.seek(self.position) + self.position += 1 + return self.im + except EOFError as e: + msg = "end of sequence" + raise StopIteration(msg) from e + + +def all_frames( + im: Image.Image | list[Image.Image], + func: Callable[[Image.Image], Image.Image] | None = None, +) -> list[Image.Image]: + """ + Applies a given function to all frames in an image or a list of images. + The frames are returned as a list of separate images. + + :param im: An image, or a list of images. + :param func: The function to apply to all of the image frames. + :returns: A list of images. + """ + if not isinstance(im, list): + im = [im] + + ims = [] + for imSequence in im: + current = imSequence.tell() + + ims += [im_frame.copy() for im_frame in Iterator(imSequence)] + + imSequence.seek(current) + return [func(im) for im in ims] if func else ims diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/ImageShow.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/ImageShow.py new file mode 100644 index 000000000..7705608e3 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/ImageShow.py @@ -0,0 +1,362 @@ +# +# The Python Imaging Library. +# $Id$ +# +# im.show() drivers +# +# History: +# 2008-04-06 fl Created +# +# Copyright (c) Secret Labs AB 2008. +# +# See the README file for information on usage and redistribution. +# +from __future__ import annotations + +import abc +import os +import shutil +import subprocess +import sys +from shlex import quote +from typing import Any + +from . import Image + +_viewers = [] + + +def register(viewer: type[Viewer] | Viewer, order: int = 1) -> None: + """ + The :py:func:`register` function is used to register additional viewers:: + + from PIL import ImageShow + ImageShow.register(MyViewer()) # MyViewer will be used as a last resort + ImageShow.register(MySecondViewer(), 0) # MySecondViewer will be prioritised + ImageShow.register(ImageShow.XVViewer(), 0) # XVViewer will be prioritised + + :param viewer: The viewer to be registered. + :param order: + Zero or a negative integer to prepend this viewer to the list, + a positive integer to append it. + """ + if isinstance(viewer, type) and issubclass(viewer, Viewer): + viewer = viewer() + if order > 0: + _viewers.append(viewer) + else: + _viewers.insert(0, viewer) + + +def show(image: Image.Image, title: str | None = None, **options: Any) -> bool: + r""" + Display a given image. + + :param image: An image object. + :param title: Optional title. Not all viewers can display the title. + :param \**options: Additional viewer options. + :returns: ``True`` if a suitable viewer was found, ``False`` otherwise. + """ + for viewer in _viewers: + if viewer.show(image, title=title, **options): + return True + return False + + +class Viewer: + """Base class for viewers.""" + + # main api + + def show(self, image: Image.Image, **options: Any) -> int: + """ + The main function for displaying an image. + Converts the given image to the target format and displays it. + """ + + if not ( + image.mode in ("1", "RGBA") + or (self.format == "PNG" and image.mode in ("I;16", "LA")) + ): + base = Image.getmodebase(image.mode) + if image.mode != base: + image = image.convert(base) + + return self.show_image(image, **options) + + # hook methods + + format: str | None = None + """The format to convert the image into.""" + options: dict[str, Any] = {} + """Additional options used to convert the image.""" + + def get_format(self, image: Image.Image) -> str | None: + """Return format name, or ``None`` to save as PGM/PPM.""" + return self.format + + def get_command(self, file: str, **options: Any) -> str: + """ + Returns the command used to display the file. + Not implemented in the base class. + """ + msg = "unavailable in base viewer" + raise NotImplementedError(msg) + + def save_image(self, image: Image.Image) -> str: + """Save to temporary file and return filename.""" + return image._dump(format=self.get_format(image), **self.options) + + def show_image(self, image: Image.Image, **options: Any) -> int: + """Display the given image.""" + return self.show_file(self.save_image(image), **options) + + def show_file(self, path: str, **options: Any) -> int: + """ + Display given file. + """ + if not os.path.exists(path): + raise FileNotFoundError + os.system(self.get_command(path, **options)) # nosec + return 1 + + +# -------------------------------------------------------------------- + + +class WindowsViewer(Viewer): + """The default viewer on Windows is the default system application for PNG files.""" + + format = "PNG" + options = {"compress_level": 1, "save_all": True} + + def get_command(self, file: str, **options: Any) -> str: + return ( + f'start "Pillow" /WAIT "{file}" ' + "&& ping -n 4 127.0.0.1 >NUL " + f'&& del /f "{file}"' + ) + + def show_file(self, path: str, **options: Any) -> int: + """ + Display given file. + """ + if not os.path.exists(path): + raise FileNotFoundError + subprocess.Popen( + self.get_command(path, **options), + shell=True, + creationflags=getattr(subprocess, "CREATE_NO_WINDOW"), + ) # nosec + return 1 + + +if sys.platform == "win32": + register(WindowsViewer) + + +class MacViewer(Viewer): + """The default viewer on macOS using ``Preview.app``.""" + + format = "PNG" + options = {"compress_level": 1, "save_all": True} + + def get_command(self, file: str, **options: Any) -> str: + # on darwin open returns immediately resulting in the temp + # file removal while app is opening + command = "open -a Preview.app" + command = f"({command} {quote(file)}; sleep 20; rm -f {quote(file)})&" + return command + + def show_file(self, path: str, **options: Any) -> int: + """ + Display given file. + """ + if not os.path.exists(path): + raise FileNotFoundError + subprocess.call(["open", "-a", "Preview.app", path]) + + pyinstaller = getattr(sys, "frozen", False) and hasattr(sys, "_MEIPASS") + executable = (not pyinstaller and sys.executable) or shutil.which("python3") + if executable: + subprocess.Popen( + [ + executable, + "-c", + "import os, sys, time; time.sleep(20); os.remove(sys.argv[1])", + path, + ] + ) + return 1 + + +if sys.platform == "darwin": + register(MacViewer) + + +class UnixViewer(abc.ABC, Viewer): + format = "PNG" + options = {"compress_level": 1, "save_all": True} + + @abc.abstractmethod + def get_command_ex(self, file: str, **options: Any) -> tuple[str, str]: + pass + + def get_command(self, file: str, **options: Any) -> str: + command = self.get_command_ex(file, **options)[0] + return f"{command} {quote(file)}" + + +class XDGViewer(UnixViewer): + """ + The freedesktop.org ``xdg-open`` command. + """ + + def get_command_ex(self, file: str, **options: Any) -> tuple[str, str]: + command = executable = "xdg-open" + return command, executable + + def show_file(self, path: str, **options: Any) -> int: + """ + Display given file. + """ + if not os.path.exists(path): + raise FileNotFoundError + subprocess.Popen(["xdg-open", path]) + return 1 + + +class DisplayViewer(UnixViewer): + """ + The ImageMagick ``display`` command. + This viewer supports the ``title`` parameter. + """ + + def get_command_ex( + self, file: str, title: str | None = None, **options: Any + ) -> tuple[str, str]: + command = executable = "display" + if title: + command += f" -title {quote(title)}" + return command, executable + + def show_file(self, path: str, **options: Any) -> int: + """ + Display given file. + """ + if not os.path.exists(path): + raise FileNotFoundError + args = ["display"] + title = options.get("title") + if title: + args += ["-title", title] + args.append(path) + + subprocess.Popen(args) + return 1 + + +class GmDisplayViewer(UnixViewer): + """The GraphicsMagick ``gm display`` command.""" + + def get_command_ex(self, file: str, **options: Any) -> tuple[str, str]: + executable = "gm" + command = "gm display" + return command, executable + + def show_file(self, path: str, **options: Any) -> int: + """ + Display given file. + """ + if not os.path.exists(path): + raise FileNotFoundError + subprocess.Popen(["gm", "display", path]) + return 1 + + +class EogViewer(UnixViewer): + """The GNOME Image Viewer ``eog`` command.""" + + def get_command_ex(self, file: str, **options: Any) -> tuple[str, str]: + executable = "eog" + command = "eog -n" + return command, executable + + def show_file(self, path: str, **options: Any) -> int: + """ + Display given file. + """ + if not os.path.exists(path): + raise FileNotFoundError + subprocess.Popen(["eog", "-n", path]) + return 1 + + +class XVViewer(UnixViewer): + """ + The X Viewer ``xv`` command. + This viewer supports the ``title`` parameter. + """ + + def get_command_ex( + self, file: str, title: str | None = None, **options: Any + ) -> tuple[str, str]: + # note: xv is pretty outdated. most modern systems have + # imagemagick's display command instead. + command = executable = "xv" + if title: + command += f" -name {quote(title)}" + return command, executable + + def show_file(self, path: str, **options: Any) -> int: + """ + Display given file. + """ + if not os.path.exists(path): + raise FileNotFoundError + args = ["xv"] + title = options.get("title") + if title: + args += ["-name", title] + args.append(path) + + subprocess.Popen(args) + return 1 + + +if sys.platform not in ("win32", "darwin"): # unixoids + if shutil.which("xdg-open"): + register(XDGViewer) + if shutil.which("display"): + register(DisplayViewer) + if shutil.which("gm"): + register(GmDisplayViewer) + if shutil.which("eog"): + register(EogViewer) + if shutil.which("xv"): + register(XVViewer) + + +class IPythonViewer(Viewer): + """The viewer for IPython frontends.""" + + def show_image(self, image: Image.Image, **options: Any) -> int: + ipython_display(image) + return 1 + + +try: + from IPython.display import display as ipython_display +except ImportError: + pass +else: + register(IPythonViewer) + + +if __name__ == "__main__": + if len(sys.argv) < 2: + print("Syntax: python3 ImageShow.py imagefile [title]") + sys.exit() + + with Image.open(sys.argv[1]) as im: + print(show(im, *sys.argv[2:])) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/ImageStat.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/ImageStat.py new file mode 100644 index 000000000..3a1044ba4 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/ImageStat.py @@ -0,0 +1,167 @@ +# +# The Python Imaging Library. +# $Id$ +# +# global image statistics +# +# History: +# 1996-04-05 fl Created +# 1997-05-21 fl Added mask; added rms, var, stddev attributes +# 1997-08-05 fl Added median +# 1998-07-05 hk Fixed integer overflow error +# +# Notes: +# This class shows how to implement delayed evaluation of attributes. +# To get a certain value, simply access the corresponding attribute. +# The __getattr__ dispatcher takes care of the rest. +# +# Copyright (c) Secret Labs AB 1997. +# Copyright (c) Fredrik Lundh 1996-97. +# +# See the README file for information on usage and redistribution. +# +from __future__ import annotations + +import math +from functools import cached_property + +from . import Image + + +class Stat: + def __init__( + self, image_or_list: Image.Image | list[int], mask: Image.Image | None = None + ) -> None: + """ + Calculate statistics for the given image. If a mask is included, + only the regions covered by that mask are included in the + statistics. You can also pass in a previously calculated histogram. + + :param image: A PIL image, or a precalculated histogram. + + .. note:: + + For a PIL image, calculations rely on the + :py:meth:`~PIL.Image.Image.histogram` method. The pixel counts are + grouped into 256 bins, even if the image has more than 8 bits per + channel. So ``I`` and ``F`` mode images have a maximum ``mean``, + ``median`` and ``rms`` of 255, and cannot have an ``extrema`` maximum + of more than 255. + + :param mask: An optional mask. + """ + if isinstance(image_or_list, Image.Image): + self.h = image_or_list.histogram(mask) + elif isinstance(image_or_list, list): + self.h = image_or_list + else: + msg = "first argument must be image or list" # type: ignore[unreachable] + raise TypeError(msg) + self.bands = list(range(len(self.h) // 256)) + + @cached_property + def extrema(self) -> list[tuple[int, int]]: + """ + Min/max values for each band in the image. + + .. note:: + This relies on the :py:meth:`~PIL.Image.Image.histogram` method, and + simply returns the low and high bins used. This is correct for + images with 8 bits per channel, but fails for other modes such as + ``I`` or ``F``. Instead, use :py:meth:`~PIL.Image.Image.getextrema` to + return per-band extrema for the image. This is more correct and + efficient because, for non-8-bit modes, the histogram method uses + :py:meth:`~PIL.Image.Image.getextrema` to determine the bins used. + """ + + def minmax(histogram: list[int]) -> tuple[int, int]: + res_min, res_max = 255, 0 + for i in range(256): + if histogram[i]: + res_min = i + break + for i in range(255, -1, -1): + if histogram[i]: + res_max = i + break + return res_min, res_max + + return [minmax(self.h[i:]) for i in range(0, len(self.h), 256)] + + @cached_property + def count(self) -> list[int]: + """Total number of pixels for each band in the image.""" + return [sum(self.h[i : i + 256]) for i in range(0, len(self.h), 256)] + + @cached_property + def sum(self) -> list[float]: + """Sum of all pixels for each band in the image.""" + + v = [] + for i in range(0, len(self.h), 256): + layer_sum = 0.0 + for j in range(256): + layer_sum += j * self.h[i + j] + v.append(layer_sum) + return v + + @cached_property + def sum2(self) -> list[float]: + """Squared sum of all pixels for each band in the image.""" + + v = [] + for i in range(0, len(self.h), 256): + sum2 = 0.0 + for j in range(256): + sum2 += (j**2) * float(self.h[i + j]) + v.append(sum2) + return v + + @cached_property + def mean(self) -> list[float]: + """Average (arithmetic mean) pixel level for each band in the image.""" + return [self.sum[i] / self.count[i] if self.count[i] else 0 for i in self.bands] + + @cached_property + def median(self) -> list[int]: + """Median pixel level for each band in the image.""" + + v = [] + for i in self.bands: + s = 0 + half = self.count[i] // 2 + b = i * 256 + for j in range(256): + s = s + self.h[b + j] + if s > half: + break + v.append(j) + return v + + @cached_property + def rms(self) -> list[float]: + """RMS (root-mean-square) for each band in the image.""" + return [ + math.sqrt(self.sum2[i] / self.count[i]) if self.count[i] else 0 + for i in self.bands + ] + + @cached_property + def var(self) -> list[float]: + """Variance for each band in the image.""" + return [ + ( + (self.sum2[i] - (self.sum[i] ** 2.0) / self.count[i]) / self.count[i] + if self.count[i] + else 0 + ) + for i in self.bands + ] + + @cached_property + def stddev(self) -> list[float]: + """Standard deviation for each band in the image.""" + return [math.sqrt(self.var[i]) for i in self.bands] + + +Global = Stat # compatibility diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/ImageText.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/ImageText.py new file mode 100644 index 000000000..008d20d38 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/ImageText.py @@ -0,0 +1,508 @@ +from __future__ import annotations + +import math +import re +from typing import AnyStr, Generic, NamedTuple + +from . import ImageFont +from ._typing import _Ink + +Font = ImageFont.ImageFont | ImageFont.FreeTypeFont | ImageFont.TransposedFont + + +class _Line(NamedTuple): + x: float + y: float + anchor: str + text: str | bytes + + +class _Wrap(Generic[AnyStr]): + lines: list[AnyStr] = [] + position = 0 + offset = 0 + + def __init__( + self, + text: Text[AnyStr], + width: int, + height: int | None = None, + font: Font | None = None, + ) -> None: + self.text: Text[AnyStr] = text + self.width = width + self.height = height + self.font = font + + input_text = self.text.text + emptystring = "" if isinstance(input_text, str) else b"" + line = emptystring + + for word in re.findall( + r"\s*\S+" if isinstance(input_text, str) else rb"\s*\S+", input_text + ): + newlines = re.findall( + r"[^\S\n]*\n" if isinstance(input_text, str) else rb"[^\S\n]*\n", word + ) + if newlines: + if not self.add_line(line): + break + for i, line in enumerate(newlines): + if i != 0 and not self.add_line(emptystring): + break + self.position += len(line) + word = word[len(line) :] + line = emptystring + + new_line = line + word + if self.text._get_bbox(new_line, self.font)[2] <= width: + # This word fits on the line + line = new_line + continue + + # This word does not fit on the line + if line and not self.add_line(line): + break + + original_length = len(word) + word = word.lstrip() + self.offset = original_length - len(word) + + if self.text._get_bbox(word, self.font)[2] > width: + if font is None: + msg = "Word does not fit within line" + raise ValueError(msg) + break + line = word + else: + if line: + self.add_line(line) + self.remaining_text: AnyStr = input_text[self.position :] + + def add_line(self, line: AnyStr) -> bool: + lines = self.lines + [line] + if self.height is not None: + last_line_y = self.text._split(lines=lines)[-1].y + last_line_height = self.text._get_bbox(line, self.font)[3] + if last_line_y + last_line_height > self.height: + return False + + self.lines = lines + self.position += len(line) + self.offset + self.offset = 0 + return True + + +class Text(Generic[AnyStr]): + def __init__( + self, + text: AnyStr, + font: Font | None = None, + mode: str = "RGB", + spacing: float = 4, + direction: str | None = None, + features: list[str] | None = None, + language: str | None = None, + ) -> None: + """ + :param text: String to be drawn. + :param font: Either an :py:class:`~PIL.ImageFont.ImageFont` instance, + :py:class:`~PIL.ImageFont.FreeTypeFont` instance, + :py:class:`~PIL.ImageFont.TransposedFont` instance or ``None``. If + ``None``, the default font from :py:meth:`.ImageFont.load_default` + will be used. + :param mode: The image mode this will be used with. + :param spacing: The number of pixels between lines. + :param direction: Direction of the text. It can be ``"rtl"`` (right to left), + ``"ltr"`` (left to right) or ``"ttb"`` (top to bottom). + Requires libraqm. + :param features: A list of OpenType font features to be used during text + layout. This is usually used to turn on optional font features + that are not enabled by default, for example ``"dlig"`` or + ``"ss01"``, but can be also used to turn off default font + features, for example ``"-liga"`` to disable ligatures or + ``"-kern"`` to disable kerning. To get all supported + features, see `OpenType docs`_. + Requires libraqm. + :param language: Language of the text. Different languages may use + different glyph shapes or ligatures. This parameter tells + the font which language the text is in, and to apply the + correct substitutions as appropriate, if available. + It should be a `BCP 47 language code`_. + Requires libraqm. + """ + self.text: AnyStr = text + self.font = font or ImageFont.load_default() + + self.mode = mode + self.spacing = spacing + self.direction = direction + self.features = features + self.language = language + + self.embedded_color = False + + self.stroke_width: float = 0 + self.stroke_fill: _Ink | None = None + + def embed_color(self) -> None: + """ + Use embedded color glyphs (COLR, CBDT, SBIX). + """ + if self.mode not in ("RGB", "RGBA"): + msg = "Embedded color supported only in RGB and RGBA modes" + raise ValueError(msg) + self.embedded_color = True + + def stroke(self, width: float = 0, fill: _Ink | None = None) -> None: + """ + :param width: The width of the text stroke. + :param fill: Color to use for the text stroke when drawing. If not given, will + default to the ``fill`` parameter from + :py:meth:`.ImageDraw.ImageDraw.text`. + """ + self.stroke_width = width + self.stroke_fill = fill + + def _get_fontmode(self) -> str: + if self.mode in ("1", "P", "I", "F"): + return "1" + elif self.embedded_color: + return "RGBA" + else: + return "L" + + def wrap( + self, + width: int, + height: int | None = None, + scaling: str | tuple[str, int] | None = None, + ) -> Text[AnyStr] | None: + """ + Wrap text to fit within a given width. + + :param width: The width to fit within. + :param height: An optional height limit. Any text that does not fit within this + will be returned as a new :py:class:`.Text` object. + :param scaling: An optional directive to scale the text, either "grow" as much + as possible within the given dimensions, or "shrink" until it + fits. It can also be a tuple of (direction, limit), with an + integer limit to stop scaling at. + + :returns: An :py:class:`.Text` object, or None. + """ + if isinstance(self.font, ImageFont.TransposedFont): + msg = "TransposedFont not supported" + raise ValueError(msg) + if self.direction not in (None, "ltr"): + msg = "Only ltr direction supported" + raise ValueError(msg) + + if scaling is None: + wrap = _Wrap(self, width, height) + else: + if not isinstance(self.font, ImageFont.FreeTypeFont): + msg = "'scaling' only supports FreeTypeFont" + raise ValueError(msg) + if height is None: + msg = "'scaling' requires 'height'" + raise ValueError(msg) + + if isinstance(scaling, str): + limit = 1 + else: + scaling, limit = scaling + + font = self.font + wrap = _Wrap(self, width, height, font) + if scaling == "shrink": + if not wrap.remaining_text: + return None + + size = math.ceil(font.size) + while wrap.remaining_text: + if size == max(limit, 1): + msg = "Text could not be scaled" + raise ValueError(msg) + size -= 1 + font = self.font.font_variant(size=size) + wrap = _Wrap(self, width, height, font) + self.font = font + else: + if wrap.remaining_text: + msg = "Text could not be scaled" + raise ValueError(msg) + + size = math.floor(font.size) + while not wrap.remaining_text: + if size == limit: + msg = "Text could not be scaled" + raise ValueError(msg) + size += 1 + font = self.font.font_variant(size=size) + last_wrap = wrap + wrap = _Wrap(self, width, height, font) + size -= 1 + if size != self.font.size: + self.font = self.font.font_variant(size=size) + wrap = last_wrap + + if wrap.remaining_text: + text = Text( + text=wrap.remaining_text, + font=self.font, + mode=self.mode, + spacing=self.spacing, + direction=self.direction, + features=self.features, + language=self.language, + ) + text.embedded_color = self.embedded_color + text.stroke_width = self.stroke_width + text.stroke_fill = self.stroke_fill + else: + text = None + + newline = "\n" if isinstance(self.text, str) else b"\n" + self.text = newline.join(wrap.lines) + return text + + def get_length(self) -> float: + """ + Returns length (in pixels with 1/64 precision) of text. + + This is the amount by which following text should be offset. + Text bounding box may extend past the length in some fonts, + e.g. when using italics or accents. + + The result is returned as a float; it is a whole number if using basic layout. + + Note that the sum of two lengths may not equal the length of a concatenated + string due to kerning. If you need to adjust for kerning, include the following + character and subtract its length. + + For example, instead of:: + + hello = ImageText.Text("Hello", font).get_length() + world = ImageText.Text("World", font).get_length() + helloworld = ImageText.Text("HelloWorld", font).get_length() + assert hello + world == helloworld + + use:: + + hello = ( + ImageText.Text("HelloW", font).get_length() - + ImageText.Text("W", font).get_length() + ) # adjusted for kerning + world = ImageText.Text("World", font).get_length() + helloworld = ImageText.Text("HelloWorld", font).get_length() + assert hello + world == helloworld + + or disable kerning with (requires libraqm):: + + hello = ImageText.Text("Hello", font, features=["-kern"]).get_length() + world = ImageText.Text("World", font, features=["-kern"]).get_length() + helloworld = ImageText.Text( + "HelloWorld", font, features=["-kern"] + ).get_length() + assert hello + world == helloworld + + :return: Either width for horizontal text, or height for vertical text. + """ + if isinstance(self.text, str): + multiline = "\n" in self.text + else: + multiline = b"\n" in self.text + if multiline: + msg = "can't measure length of multiline text" + raise ValueError(msg) + return self.font.getlength( + self.text, + self._get_fontmode(), + self.direction, + self.features, + self.language, + ) + + def _split( + self, + xy: tuple[float, float] = (0, 0), + anchor: str | None = None, + align: str = "left", + lines: list[str] | list[bytes] | None = None, + ) -> list[_Line]: + if anchor is None: + anchor = "lt" if self.direction == "ttb" else "la" + elif len(anchor) != 2: + msg = "anchor must be a 2 character string" + raise ValueError(msg) + + if lines is None: + lines = ( + self.text.split("\n") + if isinstance(self.text, str) + else self.text.split(b"\n") + ) + if len(lines) == 1: + return [_Line(xy[0], xy[1], anchor, lines[0])] + + if anchor[1] in "tb" and self.direction != "ttb": + msg = "anchor not supported for multiline text" + raise ValueError(msg) + + fontmode = self._get_fontmode() + line_spacing = ( + self.font.getbbox( + "A", + fontmode, + None, + self.features, + self.language, + self.stroke_width, + )[3] + + self.stroke_width + + self.spacing + ) + + top = xy[1] + parts = [] + if self.direction == "ttb": + left = xy[0] + for line in lines: + parts.append(_Line(left, top, anchor, line)) + left += line_spacing + else: + widths = [] + max_width: float = 0 + for line in lines: + line_width = self.font.getlength( + line, fontmode, self.direction, self.features, self.language + ) + widths.append(line_width) + max_width = max(max_width, line_width) + + if anchor[1] == "m": + top -= (len(lines) - 1) * line_spacing / 2.0 + elif anchor[1] == "d": + top -= (len(lines) - 1) * line_spacing + + idx = -1 + for line in lines: + left = xy[0] + idx += 1 + width_difference = max_width - widths[idx] + + # align by align parameter + if align in ("left", "justify"): + pass + elif align == "center": + left += width_difference / 2.0 + elif align == "right": + left += width_difference + else: + msg = 'align must be "left", "center", "right" or "justify"' + raise ValueError(msg) + + if ( + align == "justify" + and width_difference != 0 + and idx != len(lines) - 1 + ): + words = ( + line.split(" ") if isinstance(line, str) else line.split(b" ") + ) + if len(words) > 1: + # align left by anchor + if anchor[0] == "m": + left -= max_width / 2.0 + elif anchor[0] == "r": + left -= max_width + + word_widths = [ + self.font.getlength( + word, + fontmode, + self.direction, + self.features, + self.language, + ) + for word in words + ] + word_anchor = "l" + anchor[1] + width_difference = max_width - sum(word_widths) + i = 0 + for word in words: + parts.append(_Line(left, top, word_anchor, word)) + left += word_widths[i] + width_difference / (len(words) - 1) + i += 1 + top += line_spacing + continue + + # align left by anchor + if anchor[0] == "m": + left -= width_difference / 2.0 + elif anchor[0] == "r": + left -= width_difference + parts.append(_Line(left, top, anchor, line)) + top += line_spacing + + return parts + + def _get_bbox( + self, text: str | bytes, font: Font | None = None, anchor: str | None = None + ) -> tuple[float, float, float, float]: + return (font or self.font).getbbox( + text, + self._get_fontmode(), + self.direction, + self.features, + self.language, + self.stroke_width, + anchor, + ) + + def get_bbox( + self, + xy: tuple[float, float] = (0, 0), + anchor: str | None = None, + align: str = "left", + ) -> tuple[float, float, float, float]: + """ + Returns bounding box (in pixels) of text. + + Use :py:meth:`get_length` to get the offset of following text with 1/64 pixel + precision. The bounding box includes extra margins for some fonts, e.g. italics + or accents. + + :param xy: The anchor coordinates of the text. + :param anchor: The text anchor alignment. Determines the relative location of + the anchor to the text. The default alignment is top left, + specifically ``la`` for horizontal text and ``lt`` for + vertical text. See :ref:`text-anchors` for details. + :param align: For multiline text, ``"left"``, ``"center"``, ``"right"`` or + ``"justify"`` determines the relative alignment of lines. Use the + ``anchor`` parameter to specify the alignment to ``xy``. + + :return: ``(left, top, right, bottom)`` bounding box + """ + bbox: tuple[float, float, float, float] | None = None + for x, y, anchor, text in self._split(xy, anchor, align): + bbox_line = self._get_bbox(text, anchor=anchor) + bbox_line = ( + bbox_line[0] + x, + bbox_line[1] + y, + bbox_line[2] + x, + bbox_line[3] + y, + ) + if bbox is None: + bbox = bbox_line + else: + bbox = ( + min(bbox[0], bbox_line[0]), + min(bbox[1], bbox_line[1]), + max(bbox[2], bbox_line[2]), + max(bbox[3], bbox_line[3]), + ) + + assert bbox is not None + return bbox diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/ImageTk.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/ImageTk.py new file mode 100644 index 000000000..3a4cb81e9 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/ImageTk.py @@ -0,0 +1,266 @@ +# +# The Python Imaging Library. +# $Id$ +# +# a Tk display interface +# +# History: +# 96-04-08 fl Created +# 96-09-06 fl Added getimage method +# 96-11-01 fl Rewritten, removed image attribute and crop method +# 97-05-09 fl Use PyImagingPaste method instead of image type +# 97-05-12 fl Minor tweaks to match the IFUNC95 interface +# 97-05-17 fl Support the "pilbitmap" booster patch +# 97-06-05 fl Added file= and data= argument to image constructors +# 98-03-09 fl Added width and height methods to Image classes +# 98-07-02 fl Use default mode for "P" images without palette attribute +# 98-07-02 fl Explicitly destroy Tkinter image objects +# 99-07-24 fl Support multiple Tk interpreters (from Greg Couch) +# 99-07-26 fl Automatically hook into Tkinter (if possible) +# 99-08-15 fl Hook uses _imagingtk instead of _imaging +# +# Copyright (c) 1997-1999 by Secret Labs AB +# Copyright (c) 1996-1997 by Fredrik Lundh +# +# See the README file for information on usage and redistribution. +# +from __future__ import annotations + +import tkinter +from io import BytesIO +from typing import Any + +from . import Image, ImageFile + +TYPE_CHECKING = False +if TYPE_CHECKING: + from ._typing import CapsuleType + +# -------------------------------------------------------------------- +# Check for Tkinter interface hooks + + +def _get_image_from_kw(kw: dict[str, Any]) -> ImageFile.ImageFile | None: + source = None + if "file" in kw: + source = kw.pop("file") + elif "data" in kw: + source = BytesIO(kw.pop("data")) + if not source: + return None + return Image.open(source) + + +def _pyimagingtkcall( + command: str, photo: PhotoImage | tkinter.PhotoImage, ptr: CapsuleType +) -> None: + tk = photo.tk + try: + tk.call(command, photo, repr(ptr)) + except tkinter.TclError: + # activate Tkinter hook + # may raise an error if it cannot attach to Tkinter + from . import _imagingtk + + _imagingtk.tkinit(tk.interpaddr()) + tk.call(command, photo, repr(ptr)) + + +# -------------------------------------------------------------------- +# PhotoImage + + +class PhotoImage: + """ + A Tkinter-compatible photo image. This can be used + everywhere Tkinter expects an image object. If the image is an RGBA + image, pixels having alpha 0 are treated as transparent. + + The constructor takes either a PIL image, or a mode and a size. + Alternatively, you can use the ``file`` or ``data`` options to initialize + the photo image object. + + :param image: Either a PIL image, or a mode string. If a mode string is + used, a size must also be given. + :param size: If the first argument is a mode string, this defines the size + of the image. + :keyword file: A filename to load the image from (using + ``Image.open(file)``). + :keyword data: An 8-bit string containing image data (as loaded from an + image file). + """ + + def __init__( + self, + image: Image.Image | str | None = None, + size: tuple[int, int] | None = None, + **kw: Any, + ) -> None: + # Tk compatibility: file or data + if image is None: + image = _get_image_from_kw(kw) + + if image is None: + msg = "Image is required" + raise ValueError(msg) + elif isinstance(image, str): + mode = image + image = None + + if size is None: + msg = "If first argument is mode, size is required" + raise ValueError(msg) + else: + # got an image instead of a mode + mode = image.mode + if mode == "P": + # palette mapped data + image.apply_transparency() + image.load() + mode = image.palette.mode if image.palette else "RGB" + size = image.size + kw["width"], kw["height"] = size + + if mode not in ["1", "L", "RGB", "RGBA"]: + mode = Image.getmodebase(mode) + + self.__mode = mode + self.__size = size + self.__photo = tkinter.PhotoImage(**kw) + self.tk = self.__photo.tk + if image: + self.paste(image) + + def __del__(self) -> None: + try: + name = self.__photo.name + except AttributeError: + return + self.__photo.name = None + try: + self.__photo.tk.call("image", "delete", name) + except Exception: + pass # ignore internal errors + + def __str__(self) -> str: + """ + Get the Tkinter photo image identifier. This method is automatically + called by Tkinter whenever a PhotoImage object is passed to a Tkinter + method. + + :return: A Tkinter photo image identifier (a string). + """ + return str(self.__photo) + + def width(self) -> int: + """ + Get the width of the image. + + :return: The width, in pixels. + """ + return self.__size[0] + + def height(self) -> int: + """ + Get the height of the image. + + :return: The height, in pixels. + """ + return self.__size[1] + + def paste(self, im: Image.Image) -> None: + """ + Paste a PIL image into the photo image. Note that this can + be very slow if the photo image is displayed. + + :param im: A PIL image. The size must match the target region. If the + mode does not match, the image is converted to the mode of + the bitmap image. + """ + # convert to blittable + ptr = im.getim() + image = im.im + if not image.isblock() or im.mode != self.__mode: + block = Image.core.new_block(self.__mode, im.size) + image.convert2(block, image) # convert directly between buffers + ptr = block.ptr + + _pyimagingtkcall("PyImagingPhoto", self.__photo, ptr) + + +# -------------------------------------------------------------------- +# BitmapImage + + +class BitmapImage: + """ + A Tkinter-compatible bitmap image. This can be used everywhere Tkinter + expects an image object. + + The given image must have mode "1". Pixels having value 0 are treated as + transparent. Options, if any, are passed on to Tkinter. The most commonly + used option is ``foreground``, which is used to specify the color for the + non-transparent parts. See the Tkinter documentation for information on + how to specify colours. + + :param image: A PIL image. + """ + + def __init__(self, image: Image.Image | None = None, **kw: Any) -> None: + # Tk compatibility: file or data + if image is None: + image = _get_image_from_kw(kw) + + if image is None: + msg = "Image is required" + raise ValueError(msg) + self.__mode = image.mode + self.__size = image.size + + self.__photo = tkinter.BitmapImage(data=image.tobitmap(), **kw) + + def __del__(self) -> None: + try: + name = self.__photo.name + except AttributeError: + return + self.__photo.name = None + try: + self.__photo.tk.call("image", "delete", name) + except Exception: + pass # ignore internal errors + + def width(self) -> int: + """ + Get the width of the image. + + :return: The width, in pixels. + """ + return self.__size[0] + + def height(self) -> int: + """ + Get the height of the image. + + :return: The height, in pixels. + """ + return self.__size[1] + + def __str__(self) -> str: + """ + Get the Tkinter bitmap image identifier. This method is automatically + called by Tkinter whenever a BitmapImage object is passed to a Tkinter + method. + + :return: A Tkinter bitmap image identifier (a string). + """ + return str(self.__photo) + + +def getimage(photo: PhotoImage) -> Image.Image: + """Copies the contents of a PhotoImage to a PIL image memory.""" + im = Image.new("RGBA", (photo.width(), photo.height())) + + _pyimagingtkcall("PyImagingPhotoGet", photo, im.getim()) + + return im diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/ImageTransform.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/ImageTransform.py new file mode 100644 index 000000000..fb144ff38 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/ImageTransform.py @@ -0,0 +1,136 @@ +# +# The Python Imaging Library. +# $Id$ +# +# transform wrappers +# +# History: +# 2002-04-08 fl Created +# +# Copyright (c) 2002 by Secret Labs AB +# Copyright (c) 2002 by Fredrik Lundh +# +# See the README file for information on usage and redistribution. +# +from __future__ import annotations + +from collections.abc import Sequence +from typing import Any + +from . import Image + + +class Transform(Image.ImageTransformHandler): + """Base class for other transforms defined in :py:mod:`~PIL.ImageTransform`.""" + + method: Image.Transform + + def __init__(self, data: Sequence[Any]) -> None: + self.data = data + + def getdata(self) -> tuple[Image.Transform, Sequence[int]]: + return self.method, self.data + + def transform( + self, + size: tuple[int, int], + image: Image.Image, + **options: Any, + ) -> Image.Image: + """Perform the transform. Called from :py:meth:`.Image.transform`.""" + # can be overridden + method, data = self.getdata() + return image.transform(size, method, data, **options) + + +class AffineTransform(Transform): + """ + Define an affine image transform. + + This function takes a 6-tuple (a, b, c, d, e, f) which contain the first + two rows from the inverse of an affine transform matrix. For each pixel + (x, y) in the output image, the new value is taken from a position (a x + + b y + c, d x + e y + f) in the input image, rounded to nearest pixel. + + This function can be used to scale, translate, rotate, and shear the + original image. + + See :py:meth:`.Image.transform` + + :param matrix: A 6-tuple (a, b, c, d, e, f) containing the first two rows + from the inverse of an affine transform matrix. + """ + + method = Image.Transform.AFFINE + + +class PerspectiveTransform(Transform): + """ + Define a perspective image transform. + + This function takes an 8-tuple (a, b, c, d, e, f, g, h). For each pixel + (x, y) in the output image, the new value is taken from a position + ((a x + b y + c) / (g x + h y + 1), (d x + e y + f) / (g x + h y + 1)) in + the input image, rounded to nearest pixel. + + This function can be used to scale, translate, rotate, and shear the + original image. + + See :py:meth:`.Image.transform` + + :param matrix: An 8-tuple (a, b, c, d, e, f, g, h). + """ + + method = Image.Transform.PERSPECTIVE + + +class ExtentTransform(Transform): + """ + Define a transform to extract a subregion from an image. + + Maps a rectangle (defined by two corners) from the image to a rectangle of + the given size. The resulting image will contain data sampled from between + the corners, such that (x0, y0) in the input image will end up at (0,0) in + the output image, and (x1, y1) at size. + + This method can be used to crop, stretch, shrink, or mirror an arbitrary + rectangle in the current image. It is slightly slower than crop, but about + as fast as a corresponding resize operation. + + See :py:meth:`.Image.transform` + + :param bbox: A 4-tuple (x0, y0, x1, y1) which specifies two points in the + input image's coordinate system. See :ref:`coordinate-system`. + """ + + method = Image.Transform.EXTENT + + +class QuadTransform(Transform): + """ + Define a quad image transform. + + Maps a quadrilateral (a region defined by four corners) from the image to a + rectangle of the given size. + + See :py:meth:`.Image.transform` + + :param xy: An 8-tuple (x0, y0, x1, y1, x2, y2, x3, y3) which contain the + upper left, lower left, lower right, and upper right corner of the + source quadrilateral. + """ + + method = Image.Transform.QUAD + + +class MeshTransform(Transform): + """ + Define a mesh image transform. A mesh transform consists of one or more + individual quad transforms. + + See :py:meth:`.Image.transform` + + :param data: A list of (bbox, quad) tuples. + """ + + method = Image.Transform.MESH diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/ImageWin.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/ImageWin.py new file mode 100644 index 000000000..98c28f29f --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/ImageWin.py @@ -0,0 +1,247 @@ +# +# The Python Imaging Library. +# $Id$ +# +# a Windows DIB display interface +# +# History: +# 1996-05-20 fl Created +# 1996-09-20 fl Fixed subregion exposure +# 1997-09-21 fl Added draw primitive (for tzPrint) +# 2003-05-21 fl Added experimental Window/ImageWindow classes +# 2003-09-05 fl Added fromstring/tostring methods +# +# Copyright (c) Secret Labs AB 1997-2003. +# Copyright (c) Fredrik Lundh 1996-2003. +# +# See the README file for information on usage and redistribution. +# +from __future__ import annotations + +from . import Image + + +class HDC: + """ + Wraps an HDC integer. The resulting object can be passed to the + :py:meth:`~PIL.ImageWin.Dib.draw` and :py:meth:`~PIL.ImageWin.Dib.expose` + methods. + """ + + def __init__(self, dc: int) -> None: + self.dc = dc + + def __int__(self) -> int: + return self.dc + + +class HWND: + """ + Wraps an HWND integer. The resulting object can be passed to the + :py:meth:`~PIL.ImageWin.Dib.draw` and :py:meth:`~PIL.ImageWin.Dib.expose` + methods, instead of a DC. + """ + + def __init__(self, wnd: int) -> None: + self.wnd = wnd + + def __int__(self) -> int: + return self.wnd + + +class Dib: + """ + A Windows bitmap with the given mode and size. The mode can be one of "1", + "L", "P", or "RGB". + + If the display requires a palette, this constructor creates a suitable + palette and associates it with the image. For an "L" image, 128 graylevels + are allocated. For an "RGB" image, a 6x6x6 colour cube is used, together + with 20 graylevels. + + To make sure that palettes work properly under Windows, you must call the + ``palette`` method upon certain events from Windows. + + :param image: Either a PIL image, or a mode string. If a mode string is + used, a size must also be given. The mode can be one of "1", + "L", "P", or "RGB". + :param size: If the first argument is a mode string, this + defines the size of the image. + """ + + def __init__( + self, image: Image.Image | str, size: tuple[int, int] | None = None + ) -> None: + if isinstance(image, str): + mode = image + image = "" + if size is None: + msg = "If first argument is mode, size is required" + raise ValueError(msg) + else: + mode = image.mode + size = image.size + if mode not in ["1", "L", "P", "RGB"]: + mode = Image.getmodebase(mode) + self.image = Image.core.display(mode, size) + self.mode = mode + self.size = size + if image: + assert not isinstance(image, str) + self.paste(image) + + def expose(self, handle: int | HDC | HWND) -> None: + """ + Copy the bitmap contents to a device context. + + :param handle: Device context (HDC), cast to a Python integer, or an + HDC or HWND instance. In PythonWin, you can use + ``CDC.GetHandleAttrib()`` to get a suitable handle. + """ + handle_int = int(handle) + if isinstance(handle, HWND): + dc = self.image.getdc(handle_int) + try: + self.image.expose(dc) + finally: + self.image.releasedc(handle_int, dc) + else: + self.image.expose(handle_int) + + def draw( + self, + handle: int | HDC | HWND, + dst: tuple[int, int, int, int], + src: tuple[int, int, int, int] | None = None, + ) -> None: + """ + Same as expose, but allows you to specify where to draw the image, and + what part of it to draw. + + The destination and source areas are given as 4-tuple rectangles. If + the source is omitted, the entire image is copied. If the source and + the destination have different sizes, the image is resized as + necessary. + """ + if src is None: + src = (0, 0) + self.size + handle_int = int(handle) + if isinstance(handle, HWND): + dc = self.image.getdc(handle_int) + try: + self.image.draw(dc, dst, src) + finally: + self.image.releasedc(handle_int, dc) + else: + self.image.draw(handle_int, dst, src) + + def query_palette(self, handle: int | HDC | HWND) -> int: + """ + Installs the palette associated with the image in the given device + context. + + This method should be called upon **QUERYNEWPALETTE** and + **PALETTECHANGED** events from Windows. If this method returns a + non-zero value, one or more display palette entries were changed, and + the image should be redrawn. + + :param handle: Device context (HDC), cast to a Python integer, or an + HDC or HWND instance. + :return: The number of entries that were changed (if one or more entries, + this indicates that the image should be redrawn). + """ + handle_int = int(handle) + if isinstance(handle, HWND): + handle = self.image.getdc(handle_int) + try: + result = self.image.query_palette(handle) + finally: + self.image.releasedc(handle, handle) + else: + result = self.image.query_palette(handle_int) + return result + + def paste( + self, im: Image.Image, box: tuple[int, int, int, int] | None = None + ) -> None: + """ + Paste a PIL image into the bitmap image. + + :param im: A PIL image. The size must match the target region. + If the mode does not match, the image is converted to the + mode of the bitmap image. + :param box: A 4-tuple defining the left, upper, right, and + lower pixel coordinate. See :ref:`coordinate-system`. If + None is given instead of a tuple, all of the image is + assumed. + """ + im.load() + if self.mode != im.mode: + im = im.convert(self.mode) + if box: + self.image.paste(im.im, box) + else: + self.image.paste(im.im) + + def frombytes(self, buffer: bytes) -> None: + """ + Load display memory contents from byte data. + + :param buffer: A buffer containing display data (usually + data returned from :py:func:`~PIL.ImageWin.Dib.tobytes`) + """ + self.image.frombytes(buffer) + + def tobytes(self) -> bytes: + """ + Copy display memory contents to bytes object. + + :return: A bytes object containing display data. + """ + return self.image.tobytes() + + +class Window: + """Create a Window with the given title size.""" + + def __init__( + self, title: str = "PIL", width: int | None = None, height: int | None = None + ) -> None: + self.hwnd = Image.core.createwindow( + title, self.__dispatcher, width or 0, height or 0 + ) + + def __dispatcher(self, action: str, *args: int) -> None: + getattr(self, f"ui_handle_{action}")(*args) + + def ui_handle_clear(self, dc: int, x0: int, y0: int, x1: int, y1: int) -> None: + pass + + def ui_handle_damage(self, x0: int, y0: int, x1: int, y1: int) -> None: + pass + + def ui_handle_destroy(self) -> None: + pass + + def ui_handle_repair(self, dc: int, x0: int, y0: int, x1: int, y1: int) -> None: + pass + + def ui_handle_resize(self, width: int, height: int) -> None: + pass + + def mainloop(self) -> None: + Image.core.eventloop() + + +class ImageWindow(Window): + """Create an image window which displays the given image.""" + + def __init__(self, image: Image.Image | Dib, title: str = "PIL") -> None: + if not isinstance(image, Dib): + image = Dib(image) + self.image = image + width, height = image.size + super().__init__(title, width=width, height=height) + + def ui_handle_repair(self, dc: int, x0: int, y0: int, x1: int, y1: int) -> None: + self.image.draw(dc, (x0, y0, x1, y1)) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/ImtImagePlugin.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/ImtImagePlugin.py new file mode 100644 index 000000000..c4eccee34 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/ImtImagePlugin.py @@ -0,0 +1,103 @@ +# +# The Python Imaging Library. +# $Id$ +# +# IM Tools support for PIL +# +# history: +# 1996-05-27 fl Created (read 8-bit images only) +# 2001-02-17 fl Use 're' instead of 'regex' (Python 2.1) (0.2) +# +# Copyright (c) Secret Labs AB 1997-2001. +# Copyright (c) Fredrik Lundh 1996-2001. +# +# See the README file for information on usage and redistribution. +# +from __future__ import annotations + +import re + +from . import Image, ImageFile + +# +# -------------------------------------------------------------------- + +field = re.compile(rb"([a-z]*) ([^ \r\n]*)") + + +## +# Image plugin for IM Tools images. + + +class ImtImageFile(ImageFile.ImageFile): + format = "IMT" + format_description = "IM Tools" + + def _open(self) -> None: + # Quick rejection: if there's not a LF among the first + # 100 bytes, this is (probably) not a text header. + + assert self.fp is not None + + buffer = self.fp.read(100) + if b"\n" not in buffer: + msg = "not an IM file" + raise SyntaxError(msg) + + xsize = ysize = 0 + + while True: + if buffer: + s = buffer[:1] + buffer = buffer[1:] + else: + s = self.fp.read(1) + if not s: + break + + if s == b"\x0c": + # image data begins + self.tile = [ + ImageFile._Tile( + "raw", + (0, 0) + self.size, + self.fp.tell() - len(buffer), + self.mode, + ) + ] + + break + + else: + # read key/value pair + if b"\n" not in buffer: + buffer += self.fp.read(100) + lines = buffer.split(b"\n") + s += lines.pop(0) + buffer = b"\n".join(lines) + if len(s) == 1 or len(s) > 100: + break + if s[0] == ord(b"*"): + continue # comment + + m = field.match(s) + if not m: + break + k, v = m.group(1, 2) + if k == b"width": + xsize = int(v) + self._size = xsize, ysize + elif k == b"height": + ysize = int(v) + self._size = xsize, ysize + elif k == b"pixel" and v == b"n8": + self._mode = "L" + + +# +# -------------------------------------------------------------------- + +Image.register_open(ImtImageFile.format, ImtImageFile) + +# +# no extension registered (".im" is simply too common) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/IptcImagePlugin.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/IptcImagePlugin.py new file mode 100644 index 000000000..9c8be8b4e --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/IptcImagePlugin.py @@ -0,0 +1,226 @@ +# +# The Python Imaging Library. +# $Id$ +# +# IPTC/NAA file handling +# +# history: +# 1995-10-01 fl Created +# 1998-03-09 fl Cleaned up and added to PIL +# 2002-06-18 fl Added getiptcinfo helper +# +# Copyright (c) Secret Labs AB 1997-2002. +# Copyright (c) Fredrik Lundh 1995. +# +# See the README file for information on usage and redistribution. +# +from __future__ import annotations + +from io import BytesIO +from typing import cast + +from . import Image, ImageFile +from ._binary import i16be as i16 +from ._binary import i32be as i32 + +COMPRESSION = {1: "raw", 5: "jpeg"} + + +# +# Helpers + + +def _i(c: bytes) -> int: + return i32((b"\0\0\0\0" + c)[-4:]) + + +## +# Image plugin for IPTC/NAA datastreams. To read IPTC/NAA fields +# from TIFF and JPEG files, use the getiptcinfo function. + + +class IptcImageFile(ImageFile.ImageFile): + format = "IPTC" + format_description = "IPTC/NAA" + + def getint(self, key: tuple[int, int]) -> int: + return _i(self.info[key]) + + def field(self) -> tuple[tuple[int, int] | None, int]: + # + # get a IPTC field header + assert self.fp is not None + s = self.fp.read(5) + if not s.strip(b"\x00"): + return None, 0 + + tag = s[1], s[2] + + # syntax + if s[0] != 0x1C or tag[0] not in [1, 2, 3, 4, 5, 6, 7, 8, 9, 240]: + msg = "invalid IPTC/NAA file" + raise SyntaxError(msg) + + # field size + size = s[3] + if size > 132: + msg = "illegal field length in IPTC/NAA file" + raise OSError(msg) + elif size == 128: + size = 0 + elif size > 128: + size = _i(self.fp.read(size - 128)) + else: + size = i16(s, 3) + + return tag, size + + def _open(self) -> None: + # load descriptive fields + assert self.fp is not None + while True: + offset = self.fp.tell() + tag, size = self.field() + if not tag or tag == (8, 10): + break + if size: + tagdata = self.fp.read(size) + else: + tagdata = None + if tag in self.info: + if isinstance(self.info[tag], list): + self.info[tag].append(tagdata) + else: + self.info[tag] = [self.info[tag], tagdata] + else: + self.info[tag] = tagdata + + # mode + layers = self.info[(3, 60)][0] + component = self.info[(3, 60)][1] + if layers == 1 and not component: + self._mode = "L" + band = None + else: + if layers == 3 and component: + self._mode = "RGB" + elif layers == 4 and component: + self._mode = "CMYK" + if (3, 65) in self.info: + band = self.info[(3, 65)][0] - 1 + else: + band = 0 + + # size + self._size = self.getint((3, 20)), self.getint((3, 30)) + + # compression + try: + compression = COMPRESSION[self.getint((3, 120))] + except KeyError as e: + msg = "Unknown IPTC image compression" + raise OSError(msg) from e + + # tile + if tag == (8, 10): + self.tile = [ + ImageFile._Tile("iptc", (0, 0) + self.size, offset, (compression, band)) + ] + + def load(self) -> Image.core.PixelAccess | None: + if self.tile: + args = self.tile[0].args + assert isinstance(args, tuple) + compression, band = args + + assert self.fp is not None + self.fp.seek(self.tile[0].offset) + + # Copy image data to temporary file + o = BytesIO() + if compression == "raw": + # To simplify access to the extracted file, + # prepend a PPM header + o.write(b"P5\n%d %d\n255\n" % self.size) + while True: + type, size = self.field() + if type != (8, 10): + break + while size > 0: + s = self.fp.read(min(size, 8192)) + if not s: + break + o.write(s) + size -= len(s) + + with Image.open(o) as _im: + if band is not None: + bands = [Image.new("L", _im.size)] * Image.getmodebands(self.mode) + bands[band] = _im + im = Image.merge(self.mode, bands) + else: + im = _im + im.load() + self.im = im.im + self.tile = [] + return ImageFile.ImageFile.load(self) + + +Image.register_open(IptcImageFile.format, IptcImageFile) + +Image.register_extension(IptcImageFile.format, ".iim") + + +def getiptcinfo( + im: ImageFile.ImageFile, +) -> dict[tuple[int, int], bytes | list[bytes]] | None: + """ + Get IPTC information from TIFF, JPEG, or IPTC file. + + :param im: An image containing IPTC data. + :returns: A dictionary containing IPTC information, or None if + no IPTC information block was found. + """ + from . import JpegImagePlugin, TiffImagePlugin + + data = None + + if isinstance(im, IptcImageFile): + # return info dictionary right away + return {k: v for k, v in im.info.items() if isinstance(k, tuple)} + + elif isinstance(im, JpegImagePlugin.JpegImageFile): + # extract the IPTC/NAA resource + photoshop = im.info.get("photoshop") + if photoshop: + data = photoshop.get(0x0404) + + elif isinstance(im, TiffImagePlugin.TiffImageFile): + # get raw data from the IPTC/NAA tag (PhotoShop tags the data + # as 4-byte integers, so we cannot use the get method...) + try: + data = im.tag_v2._tagdata[TiffImagePlugin.IPTC_NAA_CHUNK] + except KeyError: + pass + + if data is None: + return None # no properties + + # create an IptcImagePlugin object without initializing it + class FakeImage: + pass + + fake_im = FakeImage() + fake_im.__class__ = IptcImageFile # type: ignore[assignment] + iptc_im = cast(IptcImageFile, fake_im) + + # parse the IPTC information chunk + iptc_im.info = {} + iptc_im.fp = BytesIO(data) + + try: + iptc_im._open() + except (IndexError, KeyError): + pass # expected failure + + return {k: v for k, v in iptc_im.info.items() if isinstance(k, tuple)} diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/Jpeg2KImagePlugin.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/Jpeg2KImagePlugin.py new file mode 100644 index 000000000..cb3773530 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/Jpeg2KImagePlugin.py @@ -0,0 +1,460 @@ +# +# The Python Imaging Library +# $Id$ +# +# JPEG2000 file handling +# +# History: +# 2014-03-12 ajh Created +# 2021-06-30 rogermb Extract dpi information from the 'resc' header box +# +# Copyright (c) 2014 Coriolis Systems Limited +# Copyright (c) 2014 Alastair Houghton +# +# See the README file for information on usage and redistribution. +# +from __future__ import annotations + +import io +import os +import struct +from typing import cast + +from . import Image, ImageFile, ImagePalette, _binary + +TYPE_CHECKING = False +if TYPE_CHECKING: + from collections.abc import Callable + from typing import IO + + +class BoxReader: + """ + A small helper class to read fields stored in JPEG2000 header boxes + and to easily step into and read sub-boxes. + """ + + def __init__(self, fp: IO[bytes], length: int = -1) -> None: + self.fp = fp + self.has_length = length >= 0 + self.length = length + self.remaining_in_box = -1 + + def _can_read(self, num_bytes: int) -> bool: + if self.has_length and self.fp.tell() + num_bytes > self.length: + # Outside box: ensure we don't read past the known file length + return False + if self.remaining_in_box >= 0: + # Inside box contents: ensure read does not go past box boundaries + return num_bytes <= self.remaining_in_box + else: + return True # No length known, just read + + def _read_bytes(self, num_bytes: int) -> bytes: + if not self._can_read(num_bytes): + msg = "Not enough data in header" + raise SyntaxError(msg) + + data = self.fp.read(num_bytes) + if len(data) < num_bytes: + msg = f"Expected to read {num_bytes} bytes but only got {len(data)}." + raise OSError(msg) + + if self.remaining_in_box > 0: + self.remaining_in_box -= num_bytes + return data + + def read_fields(self, field_format: str) -> tuple[int | bytes, ...]: + size = struct.calcsize(field_format) + data = self._read_bytes(size) + return struct.unpack(field_format, data) + + def read_boxes(self) -> BoxReader: + size = self.remaining_in_box + data = self._read_bytes(size) + return BoxReader(io.BytesIO(data), size) + + def has_next_box(self) -> bool: + if self.has_length: + return self.fp.tell() + self.remaining_in_box < self.length + else: + return True + + def next_box_type(self) -> bytes: + # Skip the rest of the box if it has not been read + if self.remaining_in_box > 0: + self.fp.seek(self.remaining_in_box, os.SEEK_CUR) + self.remaining_in_box = -1 + + # Read the length and type of the next box + lbox, tbox = cast(tuple[int, bytes], self.read_fields(">I4s")) + if lbox == 1: + lbox = cast(int, self.read_fields(">Q")[0]) + hlen = 16 + else: + hlen = 8 + + if lbox < hlen or not self._can_read(lbox - hlen): + msg = "Invalid header length" + raise SyntaxError(msg) + + self.remaining_in_box = lbox - hlen + return tbox + + +def _parse_codestream(fp: IO[bytes]) -> tuple[tuple[int, int], str]: + """Parse the JPEG 2000 codestream to extract the size and component + count from the SIZ marker segment, returning a PIL (size, mode) tuple.""" + + hdr = fp.read(2) + lsiz = _binary.i16be(hdr) + siz = hdr + fp.read(lsiz - 2) + lsiz, rsiz, xsiz, ysiz, xosiz, yosiz, _, _, _, _, csiz = struct.unpack_from( + ">HHIIIIIIIIH", siz + ) + + size = (xsiz - xosiz, ysiz - yosiz) + if csiz == 1: + ssiz = struct.unpack_from(">B", siz, 38) + if (ssiz[0] & 0x7F) + 1 > 8: + mode = "I;16" + else: + mode = "L" + elif csiz == 2: + mode = "LA" + elif csiz == 3: + mode = "RGB" + elif csiz == 4: + mode = "RGBA" + else: + msg = "unable to determine J2K image mode" + raise SyntaxError(msg) + + return size, mode + + +def _res_to_dpi(num: int, denom: int, exp: int) -> float | None: + """Convert JPEG2000's (numerator, denominator, exponent-base-10) resolution, + calculated as (num / denom) * 10^exp and stored in dots per meter, + to floating-point dots per inch.""" + if denom == 0: + return None + return (254 * num * (10**exp)) / (10000 * denom) + + +def _parse_jp2_header( + fp: IO[bytes], +) -> tuple[ + tuple[int, int], + str, + str | None, + tuple[float, float] | None, + ImagePalette.ImagePalette | None, +]: + """Parse the JP2 header box to extract size, component count, + color space information, and optionally DPI information, + returning a (size, mode, mimetype, dpi) tuple.""" + + # Find the JP2 header box + reader = BoxReader(fp) + header = None + mimetype = None + while reader.has_next_box(): + tbox = reader.next_box_type() + + if tbox == b"jp2h": + header = reader.read_boxes() + break + elif tbox == b"ftyp": + if reader.read_fields(">4s")[0] == b"jpx ": + mimetype = "image/jpx" + assert header is not None + + size = None + mode = None + bpc = None + nc = None + dpi = None # 2-tuple of DPI info, or None + palette = None + colr = None + + while header.has_next_box(): + tbox = header.next_box_type() + + if tbox == b"ihdr": + height, width, nc, bpc = header.read_fields(">IIHB") + assert isinstance(height, int) + assert isinstance(width, int) + assert isinstance(bpc, int) + size = (width, height) + if nc == 1 and (bpc & 0x7F) > 8: + mode = "I;16" + elif nc == 1: + mode = "L" + elif nc == 2: + mode = "LA" + elif nc == 3: + mode = "RGB" + elif nc == 4: + mode = "RGBA" + elif tbox == b"colr": + meth, _, _, enumcs = header.read_fields(">BBBI") + if meth == 1: + if enumcs in (0, 15): + colr = "1" + elif enumcs == 12: + colr = "CMYK" + if nc == 4: + mode = "CMYK" + elif enumcs == 17: + colr = "L" + elif tbox == b"pclr" and mode in ("L", "LA") and colr not in ("1", "L"): + ne, npc = header.read_fields(">HB") + assert isinstance(ne, int) + assert isinstance(npc, int) + max_bitdepth = 0 + for bitdepth in header.read_fields(">" + ("B" * npc)): + assert isinstance(bitdepth, int) + if bitdepth > max_bitdepth: + max_bitdepth = bitdepth + if max_bitdepth <= 8: + if npc == 4: + palette_mode = "CMYK" if colr == "CMYK" else "RGBA" + else: + palette_mode = "RGB" + palette = ImagePalette.ImagePalette(palette_mode) + for i in range(ne): + color: list[int] = [] + for value in header.read_fields(">" + ("B" * npc)): + assert isinstance(value, int) + color.append(value) + palette.getcolor(tuple(color)) + mode = "P" if mode == "L" else "PA" + elif tbox == b"res ": + res = header.read_boxes() + while res.has_next_box(): + tres = res.next_box_type() + if tres == b"resc": + vrcn, vrcd, hrcn, hrcd, vrce, hrce = res.read_fields(">HHHHBB") + assert isinstance(vrcn, int) + assert isinstance(vrcd, int) + assert isinstance(hrcn, int) + assert isinstance(hrcd, int) + assert isinstance(vrce, int) + assert isinstance(hrce, int) + hres = _res_to_dpi(hrcn, hrcd, hrce) + vres = _res_to_dpi(vrcn, vrcd, vrce) + if hres is not None and vres is not None: + dpi = (hres, vres) + break + + if size is None or mode is None: + msg = "Malformed JP2 header" + raise SyntaxError(msg) + + return size, mode, mimetype, dpi, palette + + +## +# Image plugin for JPEG2000 images. + + +class Jpeg2KImageFile(ImageFile.ImageFile): + format = "JPEG2000" + format_description = "JPEG 2000 (ISO 15444)" + + def _open(self) -> None: + assert self.fp is not None + sig = self.fp.read(4) + if sig == b"\xff\x4f\xff\x51": + self.codec = "j2k" + self._size, self._mode = _parse_codestream(self.fp) + self._parse_comment() + else: + sig = sig + self.fp.read(8) + + if sig == b"\x00\x00\x00\x0cjP \x0d\x0a\x87\x0a": + self.codec = "jp2" + header = _parse_jp2_header(self.fp) + self._size, self._mode, self.custom_mimetype, dpi, self.palette = header + if dpi is not None: + self.info["dpi"] = dpi + if self.fp.read(12).endswith(b"jp2c\xff\x4f\xff\x51"): + hdr = self.fp.read(2) + length = _binary.i16be(hdr) + self.fp.seek(length - 2, os.SEEK_CUR) + self._parse_comment() + else: + msg = "not a JPEG 2000 file" + raise SyntaxError(msg) + + self._reduce = 0 + self.layers = 0 + + fd = -1 + length = -1 + + try: + fd = self.fp.fileno() + length = os.fstat(fd).st_size + except Exception: + fd = -1 + try: + pos = self.fp.tell() + self.fp.seek(0, io.SEEK_END) + length = self.fp.tell() + self.fp.seek(pos) + except Exception: + length = -1 + + self.tile = [ + ImageFile._Tile( + "jpeg2k", + (0, 0) + self.size, + 0, + (self.codec, self._reduce, self.layers, fd, length), + ) + ] + + def _parse_comment(self) -> None: + assert self.fp is not None + while True: + marker = self.fp.read(2) + if not marker: + break + typ = marker[1] + if typ in (0x90, 0xD9): + # Start of tile or end of codestream + break + hdr = self.fp.read(2) + length = _binary.i16be(hdr) + if typ == 0x64: + # Comment + self.info["comment"] = self.fp.read(length - 2)[2:] + break + else: + self.fp.seek(length - 2, os.SEEK_CUR) + + @property # type: ignore[override] + def reduce( + self, + ) -> ( + Callable[[int | tuple[int, int], tuple[int, int, int, int] | None], Image.Image] + | int + ): + # https://github.com/python-pillow/Pillow/issues/4343 found that the + # new Image 'reduce' method was shadowed by this plugin's 'reduce' + # property. This attempts to allow for both scenarios + return self._reduce or super().reduce + + @reduce.setter + def reduce(self, value: int) -> None: + self._reduce = value + + def load(self) -> Image.core.PixelAccess | None: + if self.tile and self._reduce: + power = 1 << self._reduce + adjust = power >> 1 + self._size = ( + int((self.size[0] + adjust) / power), + int((self.size[1] + adjust) / power), + ) + + # Update the reduce and layers settings + t = self.tile[0] + assert isinstance(t[3], tuple) + t3 = (t[3][0], self._reduce, self.layers, t[3][3], t[3][4]) + self.tile = [ImageFile._Tile(t[0], (0, 0) + self.size, t[2], t3)] + + return ImageFile.ImageFile.load(self) + + +def _accept(prefix: bytes) -> bool: + return prefix.startswith( + (b"\xff\x4f\xff\x51", b"\x00\x00\x00\x0cjP \x0d\x0a\x87\x0a") + ) + + +# ------------------------------------------------------------ +# Save support + + +def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None: + # Get the keyword arguments + info = im.encoderinfo + + if isinstance(filename, str): + filename = filename.encode() + if filename.endswith(b".j2k") or info.get("no_jp2", False): + kind = "j2k" + else: + kind = "jp2" + + offset = info.get("offset", None) + tile_offset = info.get("tile_offset", None) + tile_size = info.get("tile_size", None) + quality_mode = info.get("quality_mode", "rates") + quality_layers = info.get("quality_layers", None) + if quality_layers is not None and not ( + isinstance(quality_layers, (list, tuple)) + and all( + isinstance(quality_layer, (int, float)) for quality_layer in quality_layers + ) + ): + msg = "quality_layers must be a sequence of numbers" + raise ValueError(msg) + + num_resolutions = info.get("num_resolutions", 0) + cblk_size = info.get("codeblock_size", None) + precinct_size = info.get("precinct_size", None) + irreversible = info.get("irreversible", False) + progression = info.get("progression", "LRCP") + cinema_mode = info.get("cinema_mode", "no") + mct = info.get("mct", 0) + signed = info.get("signed", False) + comment = info.get("comment") + if isinstance(comment, str): + comment = comment.encode() + plt = info.get("plt", False) + + fd = -1 + if hasattr(fp, "fileno"): + try: + fd = fp.fileno() + except Exception: + fd = -1 + + im.encoderconfig = ( + offset, + tile_offset, + tile_size, + quality_mode, + quality_layers, + num_resolutions, + cblk_size, + precinct_size, + irreversible, + progression, + cinema_mode, + mct, + signed, + fd, + comment, + plt, + ) + + ImageFile._save(im, fp, [ImageFile._Tile("jpeg2k", (0, 0) + im.size, 0, kind)]) + + +# ------------------------------------------------------------ +# Registry stuff + + +Image.register_open(Jpeg2KImageFile.format, Jpeg2KImageFile, _accept) +Image.register_save(Jpeg2KImageFile.format, _save) + +Image.register_extensions( + Jpeg2KImageFile.format, [".jp2", ".j2k", ".jpc", ".jpf", ".jpx", ".j2c"] +) + +Image.register_mime(Jpeg2KImageFile.format, "image/jp2") diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/JpegImagePlugin.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/JpegImagePlugin.py new file mode 100644 index 000000000..46320eb3b --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/JpegImagePlugin.py @@ -0,0 +1,889 @@ +# +# The Python Imaging Library. +# $Id$ +# +# JPEG (JFIF) file handling +# +# See "Digital Compression and Coding of Continuous-Tone Still Images, +# Part 1, Requirements and Guidelines" (CCITT T.81 / ISO 10918-1) +# +# History: +# 1995-09-09 fl Created +# 1995-09-13 fl Added full parser +# 1996-03-25 fl Added hack to use the IJG command line utilities +# 1996-05-05 fl Workaround Photoshop 2.5 CMYK polarity bug +# 1996-05-28 fl Added draft support, JFIF version (0.1) +# 1996-12-30 fl Added encoder options, added progression property (0.2) +# 1997-08-27 fl Save mode 1 images as BW (0.3) +# 1998-07-12 fl Added YCbCr to draft and save methods (0.4) +# 1998-10-19 fl Don't hang on files using 16-bit DQT's (0.4.1) +# 2001-04-16 fl Extract DPI settings from JFIF files (0.4.2) +# 2002-07-01 fl Skip pad bytes before markers; identify Exif files (0.4.3) +# 2003-04-25 fl Added experimental EXIF decoder (0.5) +# 2003-06-06 fl Added experimental EXIF GPSinfo decoder +# 2003-09-13 fl Extract COM markers +# 2009-09-06 fl Added icc_profile support (from Florian Hoech) +# 2009-03-06 fl Changed CMYK handling; always use Adobe polarity (0.6) +# 2009-03-08 fl Added subsampling support (from Justin Huff). +# +# Copyright (c) 1997-2003 by Secret Labs AB. +# Copyright (c) 1995-1996 by Fredrik Lundh. +# +# See the README file for information on usage and redistribution. +# +from __future__ import annotations + +import array +import io +import math +import os +import struct +import subprocess +import sys +import tempfile +import warnings + +from . import Image, ImageFile +from ._binary import i16be as i16 +from ._binary import i32be as i32 +from ._binary import o8 +from ._binary import o16be as o16 +from .JpegPresets import presets + +TYPE_CHECKING = False +if TYPE_CHECKING: + from typing import IO, Any + + from .MpoImagePlugin import MpoImageFile + +# +# Parser + + +def Skip(self: JpegImageFile, marker: int) -> None: + assert self.fp is not None + n = i16(self.fp.read(2)) - 2 + ImageFile._safe_read(self.fp, n) + + +def APP(self: JpegImageFile, marker: int) -> None: + # + # Application marker. Store these in the APP dictionary. + # Also look for well-known application markers. + + assert self.fp is not None + n = i16(self.fp.read(2)) - 2 + s = ImageFile._safe_read(self.fp, n) + + app = f"APP{marker & 15}" + + self.app[app] = s # compatibility + self.applist.append((app, s)) + + if marker == 0xFFE0 and s.startswith(b"JFIF"): + # extract JFIF information + self.info["jfif"] = version = i16(s, 5) # version + self.info["jfif_version"] = divmod(version, 256) + # extract JFIF properties + try: + jfif_unit = s[7] + jfif_density = i16(s, 8), i16(s, 10) + except Exception: + pass + else: + if jfif_unit == 1: + self.info["dpi"] = jfif_density + elif jfif_unit == 2: # cm + # 1 dpcm = 2.54 dpi + self.info["dpi"] = tuple(d * 2.54 for d in jfif_density) + self.info["jfif_unit"] = jfif_unit + self.info["jfif_density"] = jfif_density + elif marker == 0xFFE1 and s.startswith(b"Exif\0\0"): + # extract EXIF information + if "exif" in self.info: + self.info["exif"] += s[6:] + else: + self.info["exif"] = s + self._exif_offset = self.fp.tell() - n + 6 + elif marker == 0xFFE1 and s.startswith(b"http://ns.adobe.com/xap/1.0/\x00"): + self.info["xmp"] = s.split(b"\x00", 1)[1] + elif marker == 0xFFE2 and s.startswith(b"FPXR\0"): + # extract FlashPix information (incomplete) + self.info["flashpix"] = s # FIXME: value will change + elif marker == 0xFFE2 and s.startswith(b"ICC_PROFILE\0"): + # Since an ICC profile can be larger than the maximum size of + # a JPEG marker (64K), we need provisions to split it into + # multiple markers. The format defined by the ICC specifies + # one or more APP2 markers containing the following data: + # Identifying string ASCII "ICC_PROFILE\0" (12 bytes) + # Marker sequence number 1, 2, etc (1 byte) + # Number of markers Total of APP2's used (1 byte) + # Profile data (remainder of APP2 data) + # Decoders should use the marker sequence numbers to + # reassemble the profile, rather than assuming that the APP2 + # markers appear in the correct sequence. + self.icclist.append(s) + elif marker == 0xFFED and s.startswith(b"Photoshop 3.0\x00"): + # parse the image resource block + offset = 14 + photoshop = self.info.setdefault("photoshop", {}) + try: + while s[offset : offset + 4] == b"8BIM": + offset += 4 + # resource code + code = i16(s, offset) + offset += 2 + # resource name (usually empty) + name_len = s[offset] + # name = s[offset+1:offset+1+name_len] + offset += 1 + name_len + offset += offset & 1 # align + # resource data block + size = i32(s, offset) + offset += 4 + data = s[offset : offset + size] + if code == 0x03ED: # ResolutionInfo + photoshop[code] = { + "XResolution": i32(data, 0) / 65536, + "DisplayedUnitsX": i16(data, 4), + "YResolution": i32(data, 8) / 65536, + "DisplayedUnitsY": i16(data, 12), + } + else: + photoshop[code] = data + offset += size + offset += offset & 1 # align + except struct.error: + pass # insufficient data + + elif marker == 0xFFEE and s.startswith(b"Adobe"): + self.info["adobe"] = i16(s, 5) + # extract Adobe custom properties + try: + adobe_transform = s[11] + except IndexError: + pass + else: + self.info["adobe_transform"] = adobe_transform + elif marker == 0xFFE2 and s.startswith(b"MPF\0"): + # extract MPO information + self.info["mp"] = s[4:] + # offset is current location minus buffer size + # plus constant header size + self.info["mpoffset"] = self.fp.tell() - n + 4 + + +def COM(self: JpegImageFile, marker: int) -> None: + # + # Comment marker. Store these in the APP dictionary. + assert self.fp is not None + n = i16(self.fp.read(2)) - 2 + s = ImageFile._safe_read(self.fp, n) + + self.info["comment"] = s + self.app["COM"] = s # compatibility + self.applist.append(("COM", s)) + + +def SOF(self: JpegImageFile, marker: int) -> None: + # + # Start of frame marker. Defines the size and mode of the + # image. JPEG is colour blind, so we use some simple + # heuristics to map the number of layers to an appropriate + # mode. Note that this could be made a bit brighter, by + # looking for JFIF and Adobe APP markers. + + assert self.fp is not None + n = i16(self.fp.read(2)) - 2 + s = ImageFile._safe_read(self.fp, n) + self._size = i16(s, 3), i16(s, 1) + if self._im is not None and self.size != self.im.size: + self._im = None + + self.bits = s[0] + if self.bits != 8: + msg = f"cannot handle {self.bits}-bit layers" + raise SyntaxError(msg) + + self.layers = s[5] + if self.layers == 1: + self._mode = "L" + elif self.layers == 3: + self._mode = "RGB" + elif self.layers == 4: + self._mode = "CMYK" + else: + msg = f"cannot handle {self.layers}-layer images" + raise SyntaxError(msg) + + if marker in [0xFFC2, 0xFFC6, 0xFFCA, 0xFFCE]: + self.info["progressive"] = self.info["progression"] = 1 + + if self.icclist: + # fixup icc profile + self.icclist.sort() # sort by sequence number + if self.icclist[0][13] == len(self.icclist): + profile = [p[14:] for p in self.icclist] + icc_profile = b"".join(profile) + else: + icc_profile = None # wrong number of fragments + self.info["icc_profile"] = icc_profile + self.icclist = [] + + for i in range(6, len(s), 3): + t = s[i : i + 3] + # 4-tuples: id, vsamp, hsamp, qtable + self.layer.append((t[0], t[1] // 16, t[1] & 15, t[2])) + + +def DQT(self: JpegImageFile, marker: int) -> None: + # + # Define quantization table. Note that there might be more + # than one table in each marker. + + # FIXME: The quantization tables can be used to estimate the + # compression quality. + + assert self.fp is not None + n = i16(self.fp.read(2)) - 2 + s = ImageFile._safe_read(self.fp, n) + while len(s): + v = s[0] + precision = 1 if (v // 16 == 0) else 2 # in bytes + qt_length = 1 + precision * 64 + if len(s) < qt_length: + msg = "bad quantization table marker" + raise SyntaxError(msg) + data = array.array("B" if precision == 1 else "H", s[1:qt_length]) + if sys.byteorder == "little" and precision > 1: + data.byteswap() # the values are always big-endian + self.quantization[v & 15] = [data[i] for i in zigzag_index] + s = s[qt_length:] + + +# +# JPEG marker table + +MARKER = { + 0xFFC0: ("SOF0", "Baseline DCT", SOF), + 0xFFC1: ("SOF1", "Extended Sequential DCT", SOF), + 0xFFC2: ("SOF2", "Progressive DCT", SOF), + 0xFFC3: ("SOF3", "Spatial lossless", SOF), + 0xFFC4: ("DHT", "Define Huffman table", Skip), + 0xFFC5: ("SOF5", "Differential sequential DCT", SOF), + 0xFFC6: ("SOF6", "Differential progressive DCT", SOF), + 0xFFC7: ("SOF7", "Differential spatial", SOF), + 0xFFC8: ("JPG", "Extension", None), + 0xFFC9: ("SOF9", "Extended sequential DCT (AC)", SOF), + 0xFFCA: ("SOF10", "Progressive DCT (AC)", SOF), + 0xFFCB: ("SOF11", "Spatial lossless DCT (AC)", SOF), + 0xFFCC: ("DAC", "Define arithmetic coding conditioning", Skip), + 0xFFCD: ("SOF13", "Differential sequential DCT (AC)", SOF), + 0xFFCE: ("SOF14", "Differential progressive DCT (AC)", SOF), + 0xFFCF: ("SOF15", "Differential spatial (AC)", SOF), + 0xFFD0: ("RST0", "Restart 0", None), + 0xFFD1: ("RST1", "Restart 1", None), + 0xFFD2: ("RST2", "Restart 2", None), + 0xFFD3: ("RST3", "Restart 3", None), + 0xFFD4: ("RST4", "Restart 4", None), + 0xFFD5: ("RST5", "Restart 5", None), + 0xFFD6: ("RST6", "Restart 6", None), + 0xFFD7: ("RST7", "Restart 7", None), + 0xFFD8: ("SOI", "Start of image", None), + 0xFFD9: ("EOI", "End of image", None), + 0xFFDA: ("SOS", "Start of scan", Skip), + 0xFFDB: ("DQT", "Define quantization table", DQT), + 0xFFDC: ("DNL", "Define number of lines", Skip), + 0xFFDD: ("DRI", "Define restart interval", Skip), + 0xFFDE: ("DHP", "Define hierarchical progression", SOF), + 0xFFDF: ("EXP", "Expand reference component", Skip), + 0xFFE0: ("APP0", "Application segment 0", APP), + 0xFFE1: ("APP1", "Application segment 1", APP), + 0xFFE2: ("APP2", "Application segment 2", APP), + 0xFFE3: ("APP3", "Application segment 3", APP), + 0xFFE4: ("APP4", "Application segment 4", APP), + 0xFFE5: ("APP5", "Application segment 5", APP), + 0xFFE6: ("APP6", "Application segment 6", APP), + 0xFFE7: ("APP7", "Application segment 7", APP), + 0xFFE8: ("APP8", "Application segment 8", APP), + 0xFFE9: ("APP9", "Application segment 9", APP), + 0xFFEA: ("APP10", "Application segment 10", APP), + 0xFFEB: ("APP11", "Application segment 11", APP), + 0xFFEC: ("APP12", "Application segment 12", APP), + 0xFFED: ("APP13", "Application segment 13", APP), + 0xFFEE: ("APP14", "Application segment 14", APP), + 0xFFEF: ("APP15", "Application segment 15", APP), + 0xFFF0: ("JPG0", "Extension 0", None), + 0xFFF1: ("JPG1", "Extension 1", None), + 0xFFF2: ("JPG2", "Extension 2", None), + 0xFFF3: ("JPG3", "Extension 3", None), + 0xFFF4: ("JPG4", "Extension 4", None), + 0xFFF5: ("JPG5", "Extension 5", None), + 0xFFF6: ("JPG6", "Extension 6", None), + 0xFFF7: ("JPG7", "Extension 7", None), + 0xFFF8: ("JPG8", "Extension 8", None), + 0xFFF9: ("JPG9", "Extension 9", None), + 0xFFFA: ("JPG10", "Extension 10", None), + 0xFFFB: ("JPG11", "Extension 11", None), + 0xFFFC: ("JPG12", "Extension 12", None), + 0xFFFD: ("JPG13", "Extension 13", None), + 0xFFFE: ("COM", "Comment", COM), +} + + +def _accept(prefix: bytes) -> bool: + # Magic number was taken from https://en.wikipedia.org/wiki/JPEG + return prefix.startswith(b"\xff\xd8\xff") + + +## +# Image plugin for JPEG and JFIF images. + + +class JpegImageFile(ImageFile.ImageFile): + format = "JPEG" + format_description = "JPEG (ISO 10918)" + + def _open(self) -> None: + assert self.fp is not None + s = self.fp.read(3) + + if not _accept(s): + msg = "not a JPEG file" + raise SyntaxError(msg) + s = b"\xff" + + # Create attributes + self.bits = self.layers = 0 + self._exif_offset = 0 + + # JPEG specifics (internal) + self.layer: list[tuple[int, int, int, int]] = [] + self._huffman_dc: dict[Any, Any] = {} + self._huffman_ac: dict[Any, Any] = {} + self.quantization: dict[int, list[int]] = {} + self.app: dict[str, bytes] = {} # compatibility + self.applist: list[tuple[str, bytes]] = [] + self.icclist: list[bytes] = [] + + while True: + i = s[0] + if i == 0xFF: + s = s + self.fp.read(1) + i = i16(s) + else: + # Skip non-0xFF junk + s = self.fp.read(1) + continue + + if i in MARKER: + name, description, handler = MARKER[i] + if handler is not None: + handler(self, i) + if i == 0xFFDA: # start of scan + rawmode = self.mode + if self.mode == "CMYK": + rawmode = "CMYK;I" # assume adobe conventions + self.tile = [ + ImageFile._Tile("jpeg", (0, 0) + self.size, 0, (rawmode, "")) + ] + # self.__offset = self.fp.tell() + break + s = self.fp.read(1) + elif i in {0, 0xFFFF}: + # padded marker or junk; move on + s = b"\xff" + elif i == 0xFF00: # Skip extraneous data (escaped 0xFF) + s = self.fp.read(1) + else: + msg = "no marker found" + raise SyntaxError(msg) + + self._read_dpi_from_exif() + + def __getstate__(self) -> list[Any]: + return super().__getstate__() + [self.layers, self.layer] + + def __setstate__(self, state: list[Any]) -> None: + self.layers, self.layer = state[6:] + super().__setstate__(state) + + def load_read(self, read_bytes: int) -> bytes: + """ + internal: read more image data + For premature EOF and LOAD_TRUNCATED_IMAGES adds EOI marker + so libjpeg can finish decoding + """ + assert self.fp is not None + s = self.fp.read(read_bytes) + + if not s and ImageFile.LOAD_TRUNCATED_IMAGES and not hasattr(self, "_ended"): + # Premature EOF. + # Pretend file is finished adding EOI marker + self._ended = True + return b"\xff\xd9" + + return s + + def draft( + self, mode: str | None, size: tuple[int, int] | None + ) -> tuple[str, tuple[int, int, float, float]] | None: + if len(self.tile) != 1: + return None + + # Protect from second call + if self.decoderconfig: + return None + + d, e, o, a = self.tile[0] + scale = 1 + original_size = self.size + + assert isinstance(a, tuple) + if a[0] == "RGB" and mode in ["L", "YCbCr"]: + self._mode = mode + a = mode, "" + + if size: + scale = min(self.size[0] // size[0], self.size[1] // size[1]) + for s in [8, 4, 2, 1]: + if scale >= s: + break + assert e is not None + e = ( + e[0], + e[1], + (e[2] - e[0] + s - 1) // s + e[0], + (e[3] - e[1] + s - 1) // s + e[1], + ) + self._size = ((self.size[0] + s - 1) // s, (self.size[1] + s - 1) // s) + scale = s + + self.tile = [ImageFile._Tile(d, e, o, a)] + self.decoderconfig = (scale, 0) + + box = (0, 0, original_size[0] / scale, original_size[1] / scale) + return self.mode, box + + def load_djpeg(self) -> None: + # ALTERNATIVE: handle JPEGs via the IJG command line utilities + + f, path = tempfile.mkstemp() + os.close(f) + if os.path.exists(self.filename): + subprocess.check_call(["djpeg", "-outfile", path, self.filename]) + else: + try: + os.unlink(path) + except OSError: + pass + + msg = "Invalid Filename" + raise ValueError(msg) + + try: + with Image.open(path) as _im: + _im.load() + self.im = _im.im + finally: + try: + os.unlink(path) + except OSError: + pass + + self._mode = self.im.mode + self._size = self.im.size + + self.tile = [] + + def _getexif(self) -> dict[int, Any] | None: + return _getexif(self) + + def _read_dpi_from_exif(self) -> None: + # If DPI isn't in JPEG header, fetch from EXIF + if "dpi" in self.info or "exif" not in self.info: + return + try: + exif = self.getexif() + resolution_unit = exif[0x0128] + x_resolution = exif[0x011A] + try: + dpi = float(x_resolution[0]) / x_resolution[1] + except TypeError: + dpi = x_resolution + if math.isnan(dpi): + msg = "DPI is not a number" + raise ValueError(msg) + if resolution_unit == 3: # cm + # 1 dpcm = 2.54 dpi + dpi *= 2.54 + self.info["dpi"] = dpi, dpi + except ( + struct.error, # truncated EXIF + KeyError, # dpi not included + SyntaxError, # invalid/unreadable EXIF + TypeError, # dpi is an invalid float + ValueError, # dpi is an invalid float + ZeroDivisionError, # invalid dpi rational value + ): + self.info["dpi"] = 72, 72 + + def _getmp(self) -> dict[int, Any] | None: + return _getmp(self) + + +def _getexif(self: JpegImageFile) -> dict[int, Any] | None: + if "exif" not in self.info: + return None + return self.getexif()._get_merged_dict() + + +def _getmp(self: JpegImageFile) -> dict[int, Any] | None: + # Extract MP information. This method was inspired by the "highly + # experimental" _getexif version that's been in use for years now, + # itself based on the ImageFileDirectory class in the TIFF plugin. + + # The MP record essentially consists of a TIFF file embedded in a JPEG + # application marker. + try: + data = self.info["mp"] + except KeyError: + return None + file_contents = io.BytesIO(data) + head = file_contents.read(8) + endianness = ">" if head.startswith(b"\x4d\x4d\x00\x2a") else "<" + # process dictionary + from . import TiffImagePlugin + + try: + info = TiffImagePlugin.ImageFileDirectory_v2(head) + file_contents.seek(info.next) + info.load(file_contents) + mp = dict(info) + except Exception as e: + msg = "malformed MP Index (unreadable directory)" + raise SyntaxError(msg) from e + # it's an error not to have a number of images + try: + quant = mp[0xB001] + except KeyError as e: + msg = "malformed MP Index (no number of images)" + raise SyntaxError(msg) from e + # get MP entries + mpentries = [] + try: + rawmpentries = mp[0xB002] + for entrynum in range(quant): + unpackedentry = struct.unpack_from( + f"{endianness}LLLHH", rawmpentries, entrynum * 16 + ) + labels = ("Attribute", "Size", "DataOffset", "EntryNo1", "EntryNo2") + mpentry = dict(zip(labels, unpackedentry)) + mpentryattr = { + "DependentParentImageFlag": bool(mpentry["Attribute"] & (1 << 31)), + "DependentChildImageFlag": bool(mpentry["Attribute"] & (1 << 30)), + "RepresentativeImageFlag": bool(mpentry["Attribute"] & (1 << 29)), + "Reserved": (mpentry["Attribute"] & (3 << 27)) >> 27, + "ImageDataFormat": (mpentry["Attribute"] & (7 << 24)) >> 24, + "MPType": mpentry["Attribute"] & 0x00FFFFFF, + } + if mpentryattr["ImageDataFormat"] == 0: + mpentryattr["ImageDataFormat"] = "JPEG" + else: + msg = "unsupported picture format in MPO" + raise SyntaxError(msg) + mptypemap = { + 0x000000: "Undefined", + 0x010001: "Large Thumbnail (VGA Equivalent)", + 0x010002: "Large Thumbnail (Full HD Equivalent)", + 0x020001: "Multi-Frame Image (Panorama)", + 0x020002: "Multi-Frame Image: (Disparity)", + 0x020003: "Multi-Frame Image: (Multi-Angle)", + 0x030000: "Baseline MP Primary Image", + } + mpentryattr["MPType"] = mptypemap.get(mpentryattr["MPType"], "Unknown") + mpentry["Attribute"] = mpentryattr + mpentries.append(mpentry) + mp[0xB002] = mpentries + except KeyError as e: + msg = "malformed MP Index (bad MP Entry)" + raise SyntaxError(msg) from e + # Next we should try and parse the individual image unique ID list; + # we don't because I've never seen this actually used in a real MPO + # file and so can't test it. + return mp + + +# -------------------------------------------------------------------- +# stuff to save JPEG files + +RAWMODE = { + "1": "L", + "L": "L", + "RGB": "RGB", + "RGBX": "RGB", + "CMYK": "CMYK;I", # assume adobe conventions + "YCbCr": "YCbCr", +} + +# fmt: off +zigzag_index = ( + 0, 1, 5, 6, 14, 15, 27, 28, + 2, 4, 7, 13, 16, 26, 29, 42, + 3, 8, 12, 17, 25, 30, 41, 43, + 9, 11, 18, 24, 31, 40, 44, 53, + 10, 19, 23, 32, 39, 45, 52, 54, + 20, 22, 33, 38, 46, 51, 55, 60, + 21, 34, 37, 47, 50, 56, 59, 61, + 35, 36, 48, 49, 57, 58, 62, 63, +) + +samplings = { + (1, 1, 1, 1, 1, 1): 0, + (2, 1, 1, 1, 1, 1): 1, + (2, 2, 1, 1, 1, 1): 2, +} +# fmt: on + + +def get_sampling(im: Image.Image) -> int: + # There's no subsampling when images have only 1 layer + # (grayscale images) or when they are CMYK (4 layers), + # so set subsampling to the default value. + # + # NOTE: currently Pillow can't encode JPEG to YCCK format. + # If YCCK support is added in the future, subsampling code will have + # to be updated (here and in JpegEncode.c) to deal with 4 layers. + if not isinstance(im, JpegImageFile) or im.layers in (1, 4): + return -1 + sampling = im.layer[0][1:3] + im.layer[1][1:3] + im.layer[2][1:3] + return samplings.get(sampling, -1) + + +def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None: + try: + rawmode = RAWMODE[im.mode] + except KeyError as e: + msg = f"cannot write mode {im.mode} as JPEG" + raise OSError(msg) from e + + info = im.encoderinfo + + dpi = [round(x) for x in info.get("dpi", (0, 0))] + + quality = info.get("quality", -1) + subsampling = info.get("subsampling", -1) + qtables = info.get("qtables") + + if quality == "keep": + quality = -1 + subsampling = "keep" + qtables = "keep" + elif quality in presets: + preset = presets[quality] + quality = -1 + subsampling = preset.get("subsampling", -1) + qtables = preset.get("quantization") + elif not isinstance(quality, int): + msg = "Invalid quality setting" + raise ValueError(msg) + else: + if subsampling in presets: + subsampling = presets[subsampling].get("subsampling", -1) + if isinstance(qtables, str) and qtables in presets: + qtables = presets[qtables].get("quantization") + + if subsampling == "4:4:4": + subsampling = 0 + elif subsampling == "4:2:2": + subsampling = 1 + elif subsampling == "4:2:0": + subsampling = 2 + elif subsampling == "4:1:1": + # For compatibility. Before Pillow 4.3, 4:1:1 actually meant 4:2:0. + # Set 4:2:0 if someone is still using that value. + subsampling = 2 + elif subsampling == "keep": + if im.format != "JPEG": + msg = "Cannot use 'keep' when original image is not a JPEG" + raise ValueError(msg) + subsampling = get_sampling(im) + + def validate_qtables( + qtables: ( + str | tuple[list[int], ...] | list[list[int]] | dict[int, list[int]] | None + ), + ) -> list[list[int]] | None: + if qtables is None: + return qtables + if isinstance(qtables, str): + try: + lines = [ + int(num) + for line in qtables.splitlines() + for num in line.split("#", 1)[0].split() + ] + except ValueError as e: + msg = "Invalid quantization table" + raise ValueError(msg) from e + else: + qtables = [lines[s : s + 64] for s in range(0, len(lines), 64)] + if isinstance(qtables, (tuple, list, dict)): + if isinstance(qtables, dict): + qtables = [ + qtables[key] for key in range(len(qtables)) if key in qtables + ] + elif isinstance(qtables, tuple): + qtables = list(qtables) + if not (0 < len(qtables) < 5): + msg = "None or too many quantization tables" + raise ValueError(msg) + try: + for idx, table in enumerate(qtables): + if len(table) != 64: + msg = "Invalid quantization table" + raise TypeError(msg) + qtables[idx] = list(array.array("H", table)) + except TypeError as e: + msg = "Invalid quantization table" + raise ValueError(msg) from e + return qtables + + if qtables == "keep": + if im.format != "JPEG": + msg = "Cannot use 'keep' when original image is not a JPEG" + raise ValueError(msg) + qtables = getattr(im, "quantization", None) + qtables = validate_qtables(qtables) + + extra = info.get("extra", b"") + + MAX_BYTES_IN_MARKER = 65533 + if xmp := info.get("xmp"): + overhead_len = 29 # b"http://ns.adobe.com/xap/1.0/\x00" + max_data_bytes_in_marker = MAX_BYTES_IN_MARKER - overhead_len + if len(xmp) > max_data_bytes_in_marker: + msg = "XMP data is too long" + raise ValueError(msg) + size = o16(2 + overhead_len + len(xmp)) + extra += b"\xff\xe1" + size + b"http://ns.adobe.com/xap/1.0/\x00" + xmp + + if icc_profile := info.get("icc_profile"): + overhead_len = 14 # b"ICC_PROFILE\0" + o8(i) + o8(len(markers)) + max_data_bytes_in_marker = MAX_BYTES_IN_MARKER - overhead_len + markers = [] + while icc_profile: + markers.append(icc_profile[:max_data_bytes_in_marker]) + icc_profile = icc_profile[max_data_bytes_in_marker:] + i = 1 + for marker in markers: + size = o16(2 + overhead_len + len(marker)) + extra += ( + b"\xff\xe2" + + size + + b"ICC_PROFILE\0" + + o8(i) + + o8(len(markers)) + + marker + ) + i += 1 + + comment = info.get("comment", im.info.get("comment")) + + # "progressive" is the official name, but older documentation + # says "progression" + # FIXME: issue a warning if the wrong form is used (post-1.1.7) + progressive = info.get("progressive", False) or info.get("progression", False) + + optimize = info.get("optimize", False) + + exif = info.get("exif", b"") + if isinstance(exif, Image.Exif): + exif = exif.tobytes() + if len(exif) > MAX_BYTES_IN_MARKER: + msg = "EXIF data is too long" + raise ValueError(msg) + + # get keyword arguments + im.encoderconfig = ( + quality, + progressive, + info.get("smooth", 0), + optimize, + info.get("keep_rgb", False), + info.get("streamtype", 0), + dpi, + subsampling, + info.get("restart_marker_blocks", 0), + info.get("restart_marker_rows", 0), + qtables, + comment, + extra, + exif, + ) + + # if we optimize, libjpeg needs a buffer big enough to hold the whole image + # in a shot. Guessing on the size, at im.size bytes. (raw pixel size is + # channels*size, this is a value that's been used in a django patch. + # https://github.com/matthewwithanm/django-imagekit/issues/50 + if optimize or progressive: + # CMYK can be bigger + if im.mode == "CMYK": + bufsize = 4 * im.size[0] * im.size[1] + # keep sets quality to -1, but the actual value may be high. + elif quality >= 95 or quality == -1: + bufsize = 2 * im.size[0] * im.size[1] + else: + bufsize = im.size[0] * im.size[1] + if exif: + bufsize += len(exif) + 5 + if extra: + bufsize += len(extra) + 1 + else: + # The EXIF info needs to be written as one block, + APP1, + one spare byte. + # Ensure that our buffer is big enough. Same with the icc_profile block. + bufsize = max(len(exif) + 5, len(extra) + 1) + + ImageFile._save( + im, fp, [ImageFile._Tile("jpeg", (0, 0) + im.size, 0, rawmode)], bufsize + ) + + +## +# Factory for making JPEG and MPO instances +def jpeg_factory( + fp: IO[bytes], filename: str | bytes | None = None +) -> JpegImageFile | MpoImageFile: + im = JpegImageFile(fp, filename) + try: + mpheader = im._getmp() + if mpheader is not None and mpheader[45057] > 1: + for segment, content in im.applist: + if segment == "APP1" and b' hdrgm:Version="' in content: + # Ultra HDR images are not yet supported + return im + # It's actually an MPO + from .MpoImagePlugin import MpoImageFile + + # Don't reload everything, just convert it. + im = MpoImageFile.adopt(im, mpheader) + except (TypeError, IndexError): + # It is really a JPEG + pass + except SyntaxError: + warnings.warn( + "Image appears to be a malformed MPO file, it will be " + "interpreted as a base JPEG file" + ) + return im + + +# --------------------------------------------------------------------- +# Registry stuff + +Image.register_open(JpegImageFile.format, jpeg_factory, _accept) +Image.register_save(JpegImageFile.format, _save) + +Image.register_extensions(JpegImageFile.format, [".jfif", ".jpe", ".jpg", ".jpeg"]) + +Image.register_mime(JpegImageFile.format, "image/jpeg") diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/JpegPresets.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/JpegPresets.py new file mode 100644 index 000000000..d0e64a35e --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/JpegPresets.py @@ -0,0 +1,242 @@ +""" +JPEG quality settings equivalent to the Photoshop settings. +Can be used when saving JPEG files. + +The following presets are available by default: +``web_low``, ``web_medium``, ``web_high``, ``web_very_high``, ``web_maximum``, +``low``, ``medium``, ``high``, ``maximum``. +More presets can be added to the :py:data:`presets` dict if needed. + +To apply the preset, specify:: + + quality="preset_name" + +To apply only the quantization table:: + + qtables="preset_name" + +To apply only the subsampling setting:: + + subsampling="preset_name" + +Example:: + + im.save("image_name.jpg", quality="web_high") + +Subsampling +----------- + +Subsampling is the practice of encoding images by implementing less resolution +for chroma information than for luma information. +(ref.: https://en.wikipedia.org/wiki/Chroma_subsampling) + +Possible subsampling values are 0, 1 and 2 that correspond to 4:4:4, 4:2:2 and +4:2:0. + +You can get the subsampling of a JPEG with the +:func:`.JpegImagePlugin.get_sampling` function. + +In JPEG compressed data a JPEG marker is used instead of an EXIF tag. +(ref.: https://exiv2.org/tags.html) + + +Quantization tables +------------------- + +They are values use by the DCT (Discrete cosine transform) to remove +*unnecessary* information from the image (the lossy part of the compression). +(ref.: https://en.wikipedia.org/wiki/Quantization_matrix#Quantization_matrices, +https://en.wikipedia.org/wiki/JPEG#Quantization) + +You can get the quantization tables of a JPEG with:: + + im.quantization + +This will return a dict with a number of lists. You can pass this dict +directly as the qtables argument when saving a JPEG. + +The quantization table format in presets is a list with sublists. These formats +are interchangeable. + +Libjpeg ref.: +https://web.archive.org/web/20120328125543/http://www.jpegcameras.com/libjpeg/libjpeg-3.html + +""" + +from __future__ import annotations + +# fmt: off +presets = { + 'web_low': {'subsampling': 2, # "4:2:0" + 'quantization': [ + [20, 16, 25, 39, 50, 46, 62, 68, + 16, 18, 23, 38, 38, 53, 65, 68, + 25, 23, 31, 38, 53, 65, 68, 68, + 39, 38, 38, 53, 65, 68, 68, 68, + 50, 38, 53, 65, 68, 68, 68, 68, + 46, 53, 65, 68, 68, 68, 68, 68, + 62, 65, 68, 68, 68, 68, 68, 68, + 68, 68, 68, 68, 68, 68, 68, 68], + [21, 25, 32, 38, 54, 68, 68, 68, + 25, 28, 24, 38, 54, 68, 68, 68, + 32, 24, 32, 43, 66, 68, 68, 68, + 38, 38, 43, 53, 68, 68, 68, 68, + 54, 54, 66, 68, 68, 68, 68, 68, + 68, 68, 68, 68, 68, 68, 68, 68, + 68, 68, 68, 68, 68, 68, 68, 68, + 68, 68, 68, 68, 68, 68, 68, 68] + ]}, + 'web_medium': {'subsampling': 2, # "4:2:0" + 'quantization': [ + [16, 11, 11, 16, 23, 27, 31, 30, + 11, 12, 12, 15, 20, 23, 23, 30, + 11, 12, 13, 16, 23, 26, 35, 47, + 16, 15, 16, 23, 26, 37, 47, 64, + 23, 20, 23, 26, 39, 51, 64, 64, + 27, 23, 26, 37, 51, 64, 64, 64, + 31, 23, 35, 47, 64, 64, 64, 64, + 30, 30, 47, 64, 64, 64, 64, 64], + [17, 15, 17, 21, 20, 26, 38, 48, + 15, 19, 18, 17, 20, 26, 35, 43, + 17, 18, 20, 22, 26, 30, 46, 53, + 21, 17, 22, 28, 30, 39, 53, 64, + 20, 20, 26, 30, 39, 48, 64, 64, + 26, 26, 30, 39, 48, 63, 64, 64, + 38, 35, 46, 53, 64, 64, 64, 64, + 48, 43, 53, 64, 64, 64, 64, 64] + ]}, + 'web_high': {'subsampling': 0, # "4:4:4" + 'quantization': [ + [6, 4, 4, 6, 9, 11, 12, 16, + 4, 5, 5, 6, 8, 10, 12, 12, + 4, 5, 5, 6, 10, 12, 14, 19, + 6, 6, 6, 11, 12, 15, 19, 28, + 9, 8, 10, 12, 16, 20, 27, 31, + 11, 10, 12, 15, 20, 27, 31, 31, + 12, 12, 14, 19, 27, 31, 31, 31, + 16, 12, 19, 28, 31, 31, 31, 31], + [7, 7, 13, 24, 26, 31, 31, 31, + 7, 12, 16, 21, 31, 31, 31, 31, + 13, 16, 17, 31, 31, 31, 31, 31, + 24, 21, 31, 31, 31, 31, 31, 31, + 26, 31, 31, 31, 31, 31, 31, 31, + 31, 31, 31, 31, 31, 31, 31, 31, + 31, 31, 31, 31, 31, 31, 31, 31, + 31, 31, 31, 31, 31, 31, 31, 31] + ]}, + 'web_very_high': {'subsampling': 0, # "4:4:4" + 'quantization': [ + [2, 2, 2, 2, 3, 4, 5, 6, + 2, 2, 2, 2, 3, 4, 5, 6, + 2, 2, 2, 2, 4, 5, 7, 9, + 2, 2, 2, 4, 5, 7, 9, 12, + 3, 3, 4, 5, 8, 10, 12, 12, + 4, 4, 5, 7, 10, 12, 12, 12, + 5, 5, 7, 9, 12, 12, 12, 12, + 6, 6, 9, 12, 12, 12, 12, 12], + [3, 3, 5, 9, 13, 15, 15, 15, + 3, 4, 6, 11, 14, 12, 12, 12, + 5, 6, 9, 14, 12, 12, 12, 12, + 9, 11, 14, 12, 12, 12, 12, 12, + 13, 14, 12, 12, 12, 12, 12, 12, + 15, 12, 12, 12, 12, 12, 12, 12, + 15, 12, 12, 12, 12, 12, 12, 12, + 15, 12, 12, 12, 12, 12, 12, 12] + ]}, + 'web_maximum': {'subsampling': 0, # "4:4:4" + 'quantization': [ + [1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 2, + 1, 1, 1, 1, 1, 1, 2, 2, + 1, 1, 1, 1, 1, 2, 2, 3, + 1, 1, 1, 1, 2, 2, 3, 3, + 1, 1, 1, 2, 2, 3, 3, 3, + 1, 1, 2, 2, 3, 3, 3, 3], + [1, 1, 1, 2, 2, 3, 3, 3, + 1, 1, 1, 2, 3, 3, 3, 3, + 1, 1, 1, 3, 3, 3, 3, 3, + 2, 2, 3, 3, 3, 3, 3, 3, + 2, 3, 3, 3, 3, 3, 3, 3, + 3, 3, 3, 3, 3, 3, 3, 3, + 3, 3, 3, 3, 3, 3, 3, 3, + 3, 3, 3, 3, 3, 3, 3, 3] + ]}, + 'low': {'subsampling': 2, # "4:2:0" + 'quantization': [ + [18, 14, 14, 21, 30, 35, 34, 17, + 14, 16, 16, 19, 26, 23, 12, 12, + 14, 16, 17, 21, 23, 12, 12, 12, + 21, 19, 21, 23, 12, 12, 12, 12, + 30, 26, 23, 12, 12, 12, 12, 12, + 35, 23, 12, 12, 12, 12, 12, 12, + 34, 12, 12, 12, 12, 12, 12, 12, + 17, 12, 12, 12, 12, 12, 12, 12], + [20, 19, 22, 27, 20, 20, 17, 17, + 19, 25, 23, 14, 14, 12, 12, 12, + 22, 23, 14, 14, 12, 12, 12, 12, + 27, 14, 14, 12, 12, 12, 12, 12, + 20, 14, 12, 12, 12, 12, 12, 12, + 20, 12, 12, 12, 12, 12, 12, 12, + 17, 12, 12, 12, 12, 12, 12, 12, + 17, 12, 12, 12, 12, 12, 12, 12] + ]}, + 'medium': {'subsampling': 2, # "4:2:0" + 'quantization': [ + [12, 8, 8, 12, 17, 21, 24, 17, + 8, 9, 9, 11, 15, 19, 12, 12, + 8, 9, 10, 12, 19, 12, 12, 12, + 12, 11, 12, 21, 12, 12, 12, 12, + 17, 15, 19, 12, 12, 12, 12, 12, + 21, 19, 12, 12, 12, 12, 12, 12, + 24, 12, 12, 12, 12, 12, 12, 12, + 17, 12, 12, 12, 12, 12, 12, 12], + [13, 11, 13, 16, 20, 20, 17, 17, + 11, 14, 14, 14, 14, 12, 12, 12, + 13, 14, 14, 14, 12, 12, 12, 12, + 16, 14, 14, 12, 12, 12, 12, 12, + 20, 14, 12, 12, 12, 12, 12, 12, + 20, 12, 12, 12, 12, 12, 12, 12, + 17, 12, 12, 12, 12, 12, 12, 12, + 17, 12, 12, 12, 12, 12, 12, 12] + ]}, + 'high': {'subsampling': 0, # "4:4:4" + 'quantization': [ + [6, 4, 4, 6, 9, 11, 12, 16, + 4, 5, 5, 6, 8, 10, 12, 12, + 4, 5, 5, 6, 10, 12, 12, 12, + 6, 6, 6, 11, 12, 12, 12, 12, + 9, 8, 10, 12, 12, 12, 12, 12, + 11, 10, 12, 12, 12, 12, 12, 12, + 12, 12, 12, 12, 12, 12, 12, 12, + 16, 12, 12, 12, 12, 12, 12, 12], + [7, 7, 13, 24, 20, 20, 17, 17, + 7, 12, 16, 14, 14, 12, 12, 12, + 13, 16, 14, 14, 12, 12, 12, 12, + 24, 14, 14, 12, 12, 12, 12, 12, + 20, 14, 12, 12, 12, 12, 12, 12, + 20, 12, 12, 12, 12, 12, 12, 12, + 17, 12, 12, 12, 12, 12, 12, 12, + 17, 12, 12, 12, 12, 12, 12, 12] + ]}, + 'maximum': {'subsampling': 0, # "4:4:4" + 'quantization': [ + [2, 2, 2, 2, 3, 4, 5, 6, + 2, 2, 2, 2, 3, 4, 5, 6, + 2, 2, 2, 2, 4, 5, 7, 9, + 2, 2, 2, 4, 5, 7, 9, 12, + 3, 3, 4, 5, 8, 10, 12, 12, + 4, 4, 5, 7, 10, 12, 12, 12, + 5, 5, 7, 9, 12, 12, 12, 12, + 6, 6, 9, 12, 12, 12, 12, 12], + [3, 3, 5, 9, 13, 15, 15, 15, + 3, 4, 6, 10, 14, 12, 12, 12, + 5, 6, 9, 14, 12, 12, 12, 12, + 9, 10, 14, 12, 12, 12, 12, 12, + 13, 14, 12, 12, 12, 12, 12, 12, + 15, 12, 12, 12, 12, 12, 12, 12, + 15, 12, 12, 12, 12, 12, 12, 12, + 15, 12, 12, 12, 12, 12, 12, 12] + ]}, +} +# fmt: on diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/McIdasImagePlugin.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/McIdasImagePlugin.py new file mode 100644 index 000000000..9a47933b6 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/McIdasImagePlugin.py @@ -0,0 +1,78 @@ +# +# The Python Imaging Library. +# $Id$ +# +# Basic McIdas support for PIL +# +# History: +# 1997-05-05 fl Created (8-bit images only) +# 2009-03-08 fl Added 16/32-bit support. +# +# Thanks to Richard Jones and Craig Swank for specs and samples. +# +# Copyright (c) Secret Labs AB 1997. +# Copyright (c) Fredrik Lundh 1997. +# +# See the README file for information on usage and redistribution. +# +from __future__ import annotations + +import struct + +from . import Image, ImageFile + + +def _accept(prefix: bytes) -> bool: + return prefix.startswith(b"\x00\x00\x00\x00\x00\x00\x00\x04") + + +## +# Image plugin for McIdas area images. + + +class McIdasImageFile(ImageFile.ImageFile): + format = "MCIDAS" + format_description = "McIdas area file" + + def _open(self) -> None: + # parse area file directory + assert self.fp is not None + + s = self.fp.read(256) + if not _accept(s) or len(s) != 256: + msg = "not an McIdas area file" + raise SyntaxError(msg) + + self.area_descriptor_raw = s + self.area_descriptor = w = [0, *struct.unpack("!64i", s)] + + # get mode + if w[11] == 1: + mode = rawmode = "L" + elif w[11] == 2: + mode = rawmode = "I;16B" + elif w[11] == 4: + # FIXME: add memory map support + mode = "I" + rawmode = "I;32B" + else: + msg = "unsupported McIdas format" + raise SyntaxError(msg) + + self._mode = mode + self._size = w[10], w[9] + + offset = w[34] + w[15] + stride = w[15] + w[10] * w[11] * w[14] + + self.tile = [ + ImageFile._Tile("raw", (0, 0) + self.size, offset, (rawmode, stride, 1)) + ] + + +# -------------------------------------------------------------------- +# registry + +Image.register_open(McIdasImageFile.format, McIdasImageFile, _accept) + +# no default extension diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/MicImagePlugin.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/MicImagePlugin.py new file mode 100644 index 000000000..99a07bae0 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/MicImagePlugin.py @@ -0,0 +1,103 @@ +# +# The Python Imaging Library. +# $Id$ +# +# Microsoft Image Composer support for PIL +# +# Notes: +# uses TiffImagePlugin.py to read the actual image streams +# +# History: +# 97-01-20 fl Created +# +# Copyright (c) Secret Labs AB 1997. +# Copyright (c) Fredrik Lundh 1997. +# +# See the README file for information on usage and redistribution. +# +from __future__ import annotations + +import olefile + +from . import Image, TiffImagePlugin + +# +# -------------------------------------------------------------------- + + +def _accept(prefix: bytes) -> bool: + return prefix.startswith(olefile.MAGIC) + + +## +# Image plugin for Microsoft's Image Composer file format. + + +class MicImageFile(TiffImagePlugin.TiffImageFile): + format = "MIC" + format_description = "Microsoft Image Composer" + _close_exclusive_fp_after_loading = False + + def _open(self) -> None: + # read the OLE directory and see if this is a likely + # to be a Microsoft Image Composer file + + try: + self.ole = olefile.OleFileIO(self.fp) + except OSError as e: + msg = "not an MIC file; invalid OLE file" + raise SyntaxError(msg) from e + + # find ACI subfiles with Image members (maybe not the + # best way to identify MIC files, but what the... ;-) + + self.images = [ + path + for path in self.ole.listdir() + if path[1:] and path[0].endswith(".ACI") and path[1] == "Image" + ] + + # if we didn't find any images, this is probably not + # an MIC file. + if not self.images: + msg = "not an MIC file; no image entries" + raise SyntaxError(msg) + + self.frame = -1 + self._n_frames = len(self.images) + self.is_animated = self._n_frames > 1 + + assert self.fp is not None + self.__fp = self.fp + self.seek(0) + + def seek(self, frame: int) -> None: + if not self._seek_check(frame): + return + filename = self.images[frame] + self.fp = self.ole.openstream(filename) + + TiffImagePlugin.TiffImageFile._open(self) + + self.frame = frame + + def tell(self) -> int: + return self.frame + + def close(self) -> None: + self.__fp.close() + self.ole.close() + super().close() + + def __exit__(self, *args: object) -> None: + self.__fp.close() + self.ole.close() + super().__exit__() + + +# +# -------------------------------------------------------------------- + +Image.register_open(MicImageFile.format, MicImageFile, _accept) + +Image.register_extension(MicImageFile.format, ".mic") diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/MpegImagePlugin.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/MpegImagePlugin.py new file mode 100644 index 000000000..47ebe9d62 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/MpegImagePlugin.py @@ -0,0 +1,84 @@ +# +# The Python Imaging Library. +# $Id$ +# +# MPEG file handling +# +# History: +# 95-09-09 fl Created +# +# Copyright (c) Secret Labs AB 1997. +# Copyright (c) Fredrik Lundh 1995. +# +# See the README file for information on usage and redistribution. +# +from __future__ import annotations + +from . import Image, ImageFile +from ._binary import i8 +from ._typing import SupportsRead + +# +# Bitstream parser + + +class BitStream: + def __init__(self, fp: SupportsRead[bytes]) -> None: + self.fp = fp + self.bits = 0 + self.bitbuffer = 0 + + def next(self) -> int: + return i8(self.fp.read(1)) + + def peek(self, bits: int) -> int: + while self.bits < bits: + self.bitbuffer = (self.bitbuffer << 8) + self.next() + self.bits += 8 + return self.bitbuffer >> (self.bits - bits) & (1 << bits) - 1 + + def skip(self, bits: int) -> None: + while self.bits < bits: + self.bitbuffer = (self.bitbuffer << 8) + i8(self.fp.read(1)) + self.bits += 8 + self.bits = self.bits - bits + + def read(self, bits: int) -> int: + v = self.peek(bits) + self.bits = self.bits - bits + return v + + +def _accept(prefix: bytes) -> bool: + return prefix.startswith(b"\x00\x00\x01\xb3") + + +## +# Image plugin for MPEG streams. This plugin can identify a stream, +# but it cannot read it. + + +class MpegImageFile(ImageFile.ImageFile): + format = "MPEG" + format_description = "MPEG" + + def _open(self) -> None: + assert self.fp is not None + + s = BitStream(self.fp) + if s.read(32) != 0x1B3: + msg = "not an MPEG file" + raise SyntaxError(msg) + + self._mode = "RGB" + self._size = s.read(12), s.read(12) + + +# -------------------------------------------------------------------- +# Registry stuff + +Image.register_open(MpegImageFile.format, MpegImageFile, _accept) + +Image.register_extensions(MpegImageFile.format, [".mpg", ".mpeg"]) + +Image.register_mime(MpegImageFile.format, "video/mpeg") diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/MpoImagePlugin.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/MpoImagePlugin.py new file mode 100644 index 000000000..bee0a56f9 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/MpoImagePlugin.py @@ -0,0 +1,203 @@ +# +# The Python Imaging Library. +# $Id$ +# +# MPO file handling +# +# See "Multi-Picture Format" (CIPA DC-007-Translation 2009, Standard of the +# Camera & Imaging Products Association) +# +# The multi-picture object combines multiple JPEG images (with a modified EXIF +# data format) into a single file. While it can theoretically be used much like +# a GIF animation, it is commonly used to represent 3D photographs and is (as +# of this writing) the most commonly used format by 3D cameras. +# +# History: +# 2014-03-13 Feneric Created +# +# See the README file for information on usage and redistribution. +# +from __future__ import annotations + +import os +import struct +from typing import IO, Any, cast + +from . import ( + Image, + ImageFile, + ImageSequence, + JpegImagePlugin, + TiffImagePlugin, +) +from ._binary import o32le +from ._util import DeferredError + + +def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None: + JpegImagePlugin._save(im, fp, filename) + + +def _save_all(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None: + append_images = im.encoderinfo.get("append_images", []) + if not append_images and not getattr(im, "is_animated", False): + _save(im, fp, filename) + return + + mpf_offset = 28 + offsets: list[int] = [] + im_sequences = [im, *append_images] + total = sum(getattr(seq, "n_frames", 1) for seq in im_sequences) + for im_sequence in im_sequences: + for im_frame in ImageSequence.Iterator(im_sequence): + if not offsets: + # APP2 marker + ifd_length = 66 + 16 * total + im_frame.encoderinfo["extra"] = ( + b"\xff\xe2" + + struct.pack(">H", 6 + ifd_length) + + b"MPF\0" + + b" " * ifd_length + ) + if exif := im_frame.encoderinfo.get("exif"): + if isinstance(exif, Image.Exif): + exif = exif.tobytes() + im_frame.encoderinfo["exif"] = exif + mpf_offset += 4 + len(exif) + + JpegImagePlugin._save(im_frame, fp, filename) + offsets.append(fp.tell()) + else: + encoderinfo = im_frame._attach_default_encoderinfo(im) + im_frame.save(fp, "JPEG") + im_frame.encoderinfo = encoderinfo + offsets.append(fp.tell() - offsets[-1]) + + ifd = TiffImagePlugin.ImageFileDirectory_v2() + ifd[0xB000] = b"0100" + ifd[0xB001] = len(offsets) + + mpentries = b"" + data_offset = 0 + for i, size in enumerate(offsets): + if i == 0: + mptype = 0x030000 # Baseline MP Primary Image + else: + mptype = 0x000000 # Undefined + mpentries += struct.pack(" None: + assert self.fp is not None + self.fp.seek(0) # prep the fp in order to pass the JPEG test + JpegImagePlugin.JpegImageFile._open(self) + self._after_jpeg_open() + + def _after_jpeg_open(self, mpheader: dict[int, Any] | None = None) -> None: + self.mpinfo = mpheader if mpheader is not None else self._getmp() + if self.mpinfo is None: + msg = "Image appears to be a malformed MPO file" + raise ValueError(msg) + self.n_frames = self.mpinfo[0xB001] + self.__mpoffsets = [ + mpent["DataOffset"] + self.info["mpoffset"] for mpent in self.mpinfo[0xB002] + ] + self.__mpoffsets[0] = 0 + # Note that the following assertion will only be invalid if something + # gets broken within JpegImagePlugin. + assert self.n_frames == len(self.__mpoffsets) + del self.info["mpoffset"] # no longer needed + self.is_animated = self.n_frames > 1 + assert self.fp is not None + self._fp = self.fp # FIXME: hack + self._fp.seek(self.__mpoffsets[0]) # get ready to read first frame + self.__frame = 0 + self.offset = 0 + # for now we can only handle reading and individual frame extraction + self.readonly = 1 + + def load_seek(self, pos: int) -> None: + if isinstance(self._fp, DeferredError): + raise self._fp.ex + self._fp.seek(pos) + + def seek(self, frame: int) -> None: + if not self._seek_check(frame): + return + if isinstance(self._fp, DeferredError): + raise self._fp.ex + self.fp = self._fp + self.offset = self.__mpoffsets[frame] + + original_exif = self.info.get("exif") + if "exif" in self.info: + del self.info["exif"] + + self.fp.seek(self.offset + 2) # skip SOI marker + if not self.fp.read(2): + msg = "No data found for frame" + raise ValueError(msg) + self.fp.seek(self.offset) + JpegImagePlugin.JpegImageFile._open(self) + if self.info.get("exif") != original_exif: + self._reload_exif() + + self.tile = [ + ImageFile._Tile("jpeg", (0, 0) + self.size, self.offset, self.tile[0][-1]) + ] + self.__frame = frame + + def tell(self) -> int: + return self.__frame + + @staticmethod + def adopt( + jpeg_instance: JpegImagePlugin.JpegImageFile, + mpheader: dict[int, Any] | None = None, + ) -> MpoImageFile: + """ + Transform the instance of JpegImageFile into + an instance of MpoImageFile. + After the call, the JpegImageFile is extended + to be an MpoImageFile. + + This is essentially useful when opening a JPEG + file that reveals itself as an MPO, to avoid + double call to _open. + """ + jpeg_instance.__class__ = MpoImageFile + mpo_instance = cast(MpoImageFile, jpeg_instance) + mpo_instance._after_jpeg_open(mpheader) + return mpo_instance + + +# --------------------------------------------------------------------- +# Registry stuff + +# Note that since MPO shares a factory with JPEG, we do not need to do a +# separate registration for it here. +# Image.register_open(MpoImageFile.format, +# JpegImagePlugin.jpeg_factory, _accept) +Image.register_save(MpoImageFile.format, _save) +Image.register_save_all(MpoImageFile.format, _save_all) + +Image.register_extension(MpoImageFile.format, ".mpo") + +Image.register_mime(MpoImageFile.format, "image/mpo") diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/MspImagePlugin.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/MspImagePlugin.py new file mode 100644 index 000000000..fa0f52fe8 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/MspImagePlugin.py @@ -0,0 +1,200 @@ +# +# The Python Imaging Library. +# +# MSP file handling +# +# This is the format used by the Paint program in Windows 1 and 2. +# +# History: +# 95-09-05 fl Created +# 97-01-03 fl Read/write MSP images +# 17-02-21 es Fixed RLE interpretation +# +# Copyright (c) Secret Labs AB 1997. +# Copyright (c) Fredrik Lundh 1995-97. +# Copyright (c) Eric Soroos 2017. +# +# See the README file for information on usage and redistribution. +# +# More info on this format: https://archive.org/details/gg243631 +# Page 313: +# Figure 205. Windows Paint Version 1: "DanM" Format +# Figure 206. Windows Paint Version 2: "LinS" Format. Used in Windows V2.03 +# +# See also: https://www.fileformat.info/format/mspaint/egff.htm +from __future__ import annotations + +import io +import struct +from typing import IO + +from . import Image, ImageFile +from ._binary import i16le as i16 +from ._binary import o16le as o16 + +# +# read MSP files + + +def _accept(prefix: bytes) -> bool: + return prefix.startswith((b"DanM", b"LinS")) + + +## +# Image plugin for Windows MSP images. This plugin supports both +# uncompressed (Windows 1.0). + + +class MspImageFile(ImageFile.ImageFile): + format = "MSP" + format_description = "Windows Paint" + + def _open(self) -> None: + # Header + assert self.fp is not None + + s = self.fp.read(32) + if not _accept(s): + msg = "not an MSP file" + raise SyntaxError(msg) + + # Header checksum + checksum = 0 + for i in range(0, 32, 2): + checksum = checksum ^ i16(s, i) + if checksum != 0: + msg = "bad MSP checksum" + raise SyntaxError(msg) + + self._mode = "1" + self._size = i16(s, 4), i16(s, 6) + + if s.startswith(b"DanM"): + self.tile = [ImageFile._Tile("raw", (0, 0) + self.size, 32, "1")] + else: + self.tile = [ImageFile._Tile("MSP", (0, 0) + self.size, 32)] + + +class MspDecoder(ImageFile.PyDecoder): + # The algo for the MSP decoder is from + # https://www.fileformat.info/format/mspaint/egff.htm + # cc-by-attribution -- That page references is taken from the + # Encyclopedia of Graphics File Formats and is licensed by + # O'Reilly under the Creative Common/Attribution license + # + # For RLE encoded files, the 32byte header is followed by a scan + # line map, encoded as one 16bit word of encoded byte length per + # line. + # + # NOTE: the encoded length of the line can be 0. This was not + # handled in the previous version of this encoder, and there's no + # mention of how to handle it in the documentation. From the few + # examples I've seen, I've assumed that it is a fill of the + # background color, in this case, white. + # + # + # Pseudocode of the decoder: + # Read a BYTE value as the RunType + # If the RunType value is zero + # Read next byte as the RunCount + # Read the next byte as the RunValue + # Write the RunValue byte RunCount times + # If the RunType value is non-zero + # Use this value as the RunCount + # Read and write the next RunCount bytes literally + # + # e.g.: + # 0x00 03 ff 05 00 01 02 03 04 + # would yield the bytes: + # 0xff ff ff 00 01 02 03 04 + # + # which are then interpreted as a bit packed mode '1' image + + _pulls_fd = True + + def decode(self, buffer: bytes | Image.SupportsArrayInterface) -> tuple[int, int]: + assert self.fd is not None + + img = io.BytesIO() + blank_line = bytearray((0xFF,) * ((self.state.xsize + 7) // 8)) + try: + self.fd.seek(32) + rowmap = struct.unpack_from( + f"<{self.state.ysize}H", self.fd.read(self.state.ysize * 2) + ) + except struct.error as e: + msg = "Truncated MSP file in row map" + raise OSError(msg) from e + + for x, rowlen in enumerate(rowmap): + try: + if rowlen == 0: + img.write(blank_line) + continue + row = self.fd.read(rowlen) + if len(row) != rowlen: + msg = f"Truncated MSP file, expected {rowlen} bytes on row {x}" + raise OSError(msg) + idx = 0 + while idx < rowlen: + runtype = row[idx] + idx += 1 + if runtype == 0: + runcount, runval = struct.unpack_from("Bc", row, idx) + img.write(runval * runcount) + idx += 2 + else: + runcount = runtype + img.write(row[idx : idx + runcount]) + idx += runcount + + except struct.error as e: + msg = f"Corrupted MSP file in row {x}" + raise OSError(msg) from e + + self.set_as_raw(img.getvalue(), "1") + + return -1, 0 + + +Image.register_decoder("MSP", MspDecoder) + + +# +# write MSP files (uncompressed only) + + +def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None: + if im.mode != "1": + msg = f"cannot write mode {im.mode} as MSP" + raise OSError(msg) + + # create MSP header + header = [0] * 16 + + header[0], header[1] = i16(b"Da"), i16(b"nM") # version 1 + header[2], header[3] = im.size + header[4], header[5] = 1, 1 + header[6], header[7] = 1, 1 + header[8], header[9] = im.size + + checksum = 0 + for h in header: + checksum = checksum ^ h + header[12] = checksum # FIXME: is this the right field? + + # header + for h in header: + fp.write(o16(h)) + + # image body + ImageFile._save(im, fp, [ImageFile._Tile("raw", (0, 0) + im.size, 32, "1")]) + + +# +# registry + +Image.register_open(MspImageFile.format, MspImageFile, _accept) +Image.register_save(MspImageFile.format, _save) + +Image.register_extension(MspImageFile.format, ".msp") diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/PSDraw.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/PSDraw.py new file mode 100644 index 000000000..e6b74a918 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/PSDraw.py @@ -0,0 +1,238 @@ +# +# The Python Imaging Library +# $Id$ +# +# Simple PostScript graphics interface +# +# History: +# 1996-04-20 fl Created +# 1999-01-10 fl Added gsave/grestore to image method +# 2005-05-04 fl Fixed floating point issue in image (from Eric Etheridge) +# +# Copyright (c) 1997-2005 by Secret Labs AB. All rights reserved. +# Copyright (c) 1996 by Fredrik Lundh. +# +# See the README file for information on usage and redistribution. +# +from __future__ import annotations + +import sys +from typing import IO + +from . import EpsImagePlugin + +TYPE_CHECKING = False + + +## +# Simple PostScript graphics interface. + + +class PSDraw: + """ + Sets up printing to the given file. If ``fp`` is omitted, + ``sys.stdout.buffer`` is assumed. + """ + + def __init__(self, fp: IO[bytes] | None = None) -> None: + if not fp: + fp = sys.stdout.buffer + self.fp = fp + + def begin_document(self, id: str | None = None) -> None: + """Set up printing of a document. (Write PostScript DSC header.)""" + # FIXME: incomplete + self.fp.write( + b"%!PS-Adobe-3.0\n" + b"save\n" + b"/showpage { } def\n" + b"%%EndComments\n" + b"%%BeginDocument\n" + ) + # self.fp.write(ERROR_PS) # debugging! + self.fp.write(EDROFF_PS) + self.fp.write(VDI_PS) + self.fp.write(b"%%EndProlog\n") + self.isofont: dict[bytes, int] = {} + + def end_document(self) -> None: + """Ends printing. (Write PostScript DSC footer.)""" + self.fp.write(b"%%EndDocument\nrestore showpage\n%%End\n") + if hasattr(self.fp, "flush"): + self.fp.flush() + + def setfont(self, font: str, size: int) -> None: + """ + Selects which font to use. + + :param font: A PostScript font name + :param size: Size in points. + """ + font_bytes = bytes(font, "UTF-8") + if font_bytes not in self.isofont: + # reencode font + self.fp.write( + b"/PSDraw-%s ISOLatin1Encoding /%s E\n" % (font_bytes, font_bytes) + ) + self.isofont[font_bytes] = 1 + # rough + self.fp.write(b"/F0 %d /PSDraw-%s F\n" % (size, font_bytes)) + + def line(self, xy0: tuple[int, int], xy1: tuple[int, int]) -> None: + """ + Draws a line between the two points. Coordinates are given in + PostScript point coordinates (72 points per inch, (0, 0) is the lower + left corner of the page). + """ + self.fp.write(b"%d %d %d %d Vl\n" % (*xy0, *xy1)) + + def rectangle(self, box: tuple[int, int, int, int]) -> None: + """ + Draws a rectangle. + + :param box: A tuple of four integers, specifying left, bottom, width and + height. + """ + self.fp.write(b"%d %d M 0 %d %d Vr\n" % box) + + def text(self, xy: tuple[int, int], text: str) -> None: + """ + Draws text at the given position. You must use + :py:meth:`~PIL.PSDraw.PSDraw.setfont` before calling this method. + """ + # The font is loaded as ISOLatin1Encoding, so use latin-1 here. + text_bytes = bytes(text, "latin-1") + text_bytes = b"\\(".join(text_bytes.split(b"(")) + text_bytes = b"\\)".join(text_bytes.split(b")")) + self.fp.write(b"%d %d M (%s) S\n" % (xy + (text_bytes,))) + + if TYPE_CHECKING: + from . import Image + + def image( + self, box: tuple[int, int, int, int], im: Image.Image, dpi: int | None = None + ) -> None: + """Draw a PIL image, centered in the given box.""" + # default resolution depends on mode + if not dpi: + if im.mode == "1": + dpi = 200 # fax + else: + dpi = 100 # grayscale + # image size (on paper) + x = im.size[0] * 72 / dpi + y = im.size[1] * 72 / dpi + # max allowed size + xmax = float(box[2] - box[0]) + ymax = float(box[3] - box[1]) + if x > xmax: + y = y * xmax / x + x = xmax + if y > ymax: + x = x * ymax / y + y = ymax + dx = (xmax - x) / 2 + box[0] + dy = (ymax - y) / 2 + box[1] + self.fp.write(b"gsave\n%f %f translate\n" % (dx, dy)) + if (x, y) != im.size: + # EpsImagePlugin._save prints the image at (0,0,xsize,ysize) + sx = x / im.size[0] + sy = y / im.size[1] + self.fp.write(b"%f %f scale\n" % (sx, sy)) + EpsImagePlugin._save(im, self.fp, "", 0) + self.fp.write(b"\ngrestore\n") + + +# -------------------------------------------------------------------- +# PostScript driver + +# +# EDROFF.PS -- PostScript driver for Edroff 2 +# +# History: +# 94-01-25 fl: created (edroff 2.04) +# +# Copyright (c) Fredrik Lundh 1994. +# + + +EDROFF_PS = b"""\ +/S { show } bind def +/P { moveto show } bind def +/M { moveto } bind def +/X { 0 rmoveto } bind def +/Y { 0 exch rmoveto } bind def +/E { findfont + dup maxlength dict begin + { + 1 index /FID ne { def } { pop pop } ifelse + } forall + /Encoding exch def + dup /FontName exch def + currentdict end definefont pop +} bind def +/F { findfont exch scalefont dup setfont + [ exch /setfont cvx ] cvx bind def +} bind def +""" + +# +# VDI.PS -- PostScript driver for VDI meta commands +# +# History: +# 94-01-25 fl: created (edroff 2.04) +# +# Copyright (c) Fredrik Lundh 1994. +# + +VDI_PS = b"""\ +/Vm { moveto } bind def +/Va { newpath arcn stroke } bind def +/Vl { moveto lineto stroke } bind def +/Vc { newpath 0 360 arc closepath } bind def +/Vr { exch dup 0 rlineto + exch dup 0 exch rlineto + exch neg 0 rlineto + 0 exch neg rlineto + setgray fill } bind def +/Tm matrix def +/Ve { Tm currentmatrix pop + translate scale newpath 0 0 .5 0 360 arc closepath + Tm setmatrix +} bind def +/Vf { currentgray exch setgray fill setgray } bind def +""" + +# +# ERROR.PS -- Error handler +# +# History: +# 89-11-21 fl: created (pslist 1.10) +# + +ERROR_PS = b"""\ +/landscape false def +/errorBUF 200 string def +/errorNL { currentpoint 10 sub exch pop 72 exch moveto } def +errordict begin /handleerror { + initmatrix /Courier findfont 10 scalefont setfont + newpath 72 720 moveto $error begin /newerror false def + (PostScript Error) show errorNL errorNL + (Error: ) show + /errorname load errorBUF cvs show errorNL errorNL + (Command: ) show + /command load dup type /stringtype ne { errorBUF cvs } if show + errorNL errorNL + (VMstatus: ) show + vmstatus errorBUF cvs show ( bytes available, ) show + errorBUF cvs show ( bytes used at level ) show + errorBUF cvs show errorNL errorNL + (Operand stargck: ) show errorNL /ostargck load { + dup type /stringtype ne { errorBUF cvs } if 72 0 rmoveto show errorNL + } forall errorNL + (Execution stargck: ) show errorNL /estargck load { + dup type /stringtype ne { errorBUF cvs } if 72 0 rmoveto show errorNL + } forall + end showpage +} def end +""" diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/PaletteFile.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/PaletteFile.py new file mode 100644 index 000000000..2a26e5d4e --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/PaletteFile.py @@ -0,0 +1,54 @@ +# +# Python Imaging Library +# $Id$ +# +# stuff to read simple, teragon-style palette files +# +# History: +# 97-08-23 fl Created +# +# Copyright (c) Secret Labs AB 1997. +# Copyright (c) Fredrik Lundh 1997. +# +# See the README file for information on usage and redistribution. +# +from __future__ import annotations + +from typing import IO + +from ._binary import o8 + + +class PaletteFile: + """File handler for Teragon-style palette files.""" + + rawmode = "RGB" + + def __init__(self, fp: IO[bytes]) -> None: + palette = [o8(i) * 3 for i in range(256)] + + while True: + s = fp.readline() + + if not s: + break + if s.startswith(b"#"): + continue + if len(s) > 100: + msg = "bad palette file" + raise SyntaxError(msg) + + v = [int(x) for x in s.split()] + try: + [i, r, g, b] = v + except ValueError: + [i, r] = v + g = b = r + + if 0 <= i <= 255: + palette[i] = o8(r) + o8(g) + o8(b) + + self.palette = b"".join(palette) + + def getpalette(self) -> tuple[bytes, str]: + return self.palette, self.rawmode diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/PalmImagePlugin.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/PalmImagePlugin.py new file mode 100644 index 000000000..232adf3d3 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/PalmImagePlugin.py @@ -0,0 +1,217 @@ +# +# The Python Imaging Library. +# $Id$ +# + +## +# Image plugin for Palm pixmap images (output only). +## +from __future__ import annotations + +from typing import IO + +from . import Image, ImageFile +from ._binary import o8 +from ._binary import o16be as o16b + +# fmt: off +_Palm8BitColormapValues = ( + (255, 255, 255), (255, 204, 255), (255, 153, 255), (255, 102, 255), + (255, 51, 255), (255, 0, 255), (255, 255, 204), (255, 204, 204), + (255, 153, 204), (255, 102, 204), (255, 51, 204), (255, 0, 204), + (255, 255, 153), (255, 204, 153), (255, 153, 153), (255, 102, 153), + (255, 51, 153), (255, 0, 153), (204, 255, 255), (204, 204, 255), + (204, 153, 255), (204, 102, 255), (204, 51, 255), (204, 0, 255), + (204, 255, 204), (204, 204, 204), (204, 153, 204), (204, 102, 204), + (204, 51, 204), (204, 0, 204), (204, 255, 153), (204, 204, 153), + (204, 153, 153), (204, 102, 153), (204, 51, 153), (204, 0, 153), + (153, 255, 255), (153, 204, 255), (153, 153, 255), (153, 102, 255), + (153, 51, 255), (153, 0, 255), (153, 255, 204), (153, 204, 204), + (153, 153, 204), (153, 102, 204), (153, 51, 204), (153, 0, 204), + (153, 255, 153), (153, 204, 153), (153, 153, 153), (153, 102, 153), + (153, 51, 153), (153, 0, 153), (102, 255, 255), (102, 204, 255), + (102, 153, 255), (102, 102, 255), (102, 51, 255), (102, 0, 255), + (102, 255, 204), (102, 204, 204), (102, 153, 204), (102, 102, 204), + (102, 51, 204), (102, 0, 204), (102, 255, 153), (102, 204, 153), + (102, 153, 153), (102, 102, 153), (102, 51, 153), (102, 0, 153), + (51, 255, 255), (51, 204, 255), (51, 153, 255), (51, 102, 255), + (51, 51, 255), (51, 0, 255), (51, 255, 204), (51, 204, 204), + (51, 153, 204), (51, 102, 204), (51, 51, 204), (51, 0, 204), + (51, 255, 153), (51, 204, 153), (51, 153, 153), (51, 102, 153), + (51, 51, 153), (51, 0, 153), (0, 255, 255), (0, 204, 255), + (0, 153, 255), (0, 102, 255), (0, 51, 255), (0, 0, 255), + (0, 255, 204), (0, 204, 204), (0, 153, 204), (0, 102, 204), + (0, 51, 204), (0, 0, 204), (0, 255, 153), (0, 204, 153), + (0, 153, 153), (0, 102, 153), (0, 51, 153), (0, 0, 153), + (255, 255, 102), (255, 204, 102), (255, 153, 102), (255, 102, 102), + (255, 51, 102), (255, 0, 102), (255, 255, 51), (255, 204, 51), + (255, 153, 51), (255, 102, 51), (255, 51, 51), (255, 0, 51), + (255, 255, 0), (255, 204, 0), (255, 153, 0), (255, 102, 0), + (255, 51, 0), (255, 0, 0), (204, 255, 102), (204, 204, 102), + (204, 153, 102), (204, 102, 102), (204, 51, 102), (204, 0, 102), + (204, 255, 51), (204, 204, 51), (204, 153, 51), (204, 102, 51), + (204, 51, 51), (204, 0, 51), (204, 255, 0), (204, 204, 0), + (204, 153, 0), (204, 102, 0), (204, 51, 0), (204, 0, 0), + (153, 255, 102), (153, 204, 102), (153, 153, 102), (153, 102, 102), + (153, 51, 102), (153, 0, 102), (153, 255, 51), (153, 204, 51), + (153, 153, 51), (153, 102, 51), (153, 51, 51), (153, 0, 51), + (153, 255, 0), (153, 204, 0), (153, 153, 0), (153, 102, 0), + (153, 51, 0), (153, 0, 0), (102, 255, 102), (102, 204, 102), + (102, 153, 102), (102, 102, 102), (102, 51, 102), (102, 0, 102), + (102, 255, 51), (102, 204, 51), (102, 153, 51), (102, 102, 51), + (102, 51, 51), (102, 0, 51), (102, 255, 0), (102, 204, 0), + (102, 153, 0), (102, 102, 0), (102, 51, 0), (102, 0, 0), + (51, 255, 102), (51, 204, 102), (51, 153, 102), (51, 102, 102), + (51, 51, 102), (51, 0, 102), (51, 255, 51), (51, 204, 51), + (51, 153, 51), (51, 102, 51), (51, 51, 51), (51, 0, 51), + (51, 255, 0), (51, 204, 0), (51, 153, 0), (51, 102, 0), + (51, 51, 0), (51, 0, 0), (0, 255, 102), (0, 204, 102), + (0, 153, 102), (0, 102, 102), (0, 51, 102), (0, 0, 102), + (0, 255, 51), (0, 204, 51), (0, 153, 51), (0, 102, 51), + (0, 51, 51), (0, 0, 51), (0, 255, 0), (0, 204, 0), + (0, 153, 0), (0, 102, 0), (0, 51, 0), (17, 17, 17), + (34, 34, 34), (68, 68, 68), (85, 85, 85), (119, 119, 119), + (136, 136, 136), (170, 170, 170), (187, 187, 187), (221, 221, 221), + (238, 238, 238), (192, 192, 192), (128, 0, 0), (128, 0, 128), + (0, 128, 0), (0, 128, 128), (0, 0, 0), (0, 0, 0), + (0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0), + (0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0), + (0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0), + (0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0), + (0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0), + (0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0)) +# fmt: on + + +# so build a prototype image to be used for palette resampling +def build_prototype_image() -> Image.Image: + image = Image.new("L", (1, len(_Palm8BitColormapValues))) + image.putdata(list(range(len(_Palm8BitColormapValues)))) + palettedata: tuple[int, ...] = () + for colormapValue in _Palm8BitColormapValues: + palettedata += colormapValue + palettedata += (0, 0, 0) * (256 - len(_Palm8BitColormapValues)) + image.putpalette(palettedata) + return image + + +Palm8BitColormapImage = build_prototype_image() + +# OK, we now have in Palm8BitColormapImage, +# a "P"-mode image with the right palette +# +# -------------------------------------------------------------------- + +_FLAGS = {"custom-colormap": 0x4000, "is-compressed": 0x8000, "has-transparent": 0x2000} + +_COMPRESSION_TYPES = {"none": 0xFF, "rle": 0x01, "scanline": 0x00} + + +# +# -------------------------------------------------------------------- + +## +# (Internal) Image save plugin for the Palm format. + + +def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None: + if im.mode == "P": + rawmode = "P" + bpp = 8 + version = 1 + + elif im.mode == "L": + if im.encoderinfo.get("bpp") in (1, 2, 4): + # this is 8-bit grayscale, so we shift it to get the high-order bits, + # and invert it because + # Palm does grayscale from white (0) to black (1) + bpp = im.encoderinfo["bpp"] + maxval = (1 << bpp) - 1 + shift = 8 - bpp + im = im.point(lambda x: maxval - (x >> shift)) + elif im.info.get("bpp") in (1, 2, 4): + # here we assume that even though the inherent mode is 8-bit grayscale, + # only the lower bpp bits are significant. + # We invert them to match the Palm. + bpp = im.info["bpp"] + maxval = (1 << bpp) - 1 + im = im.point(lambda x: maxval - (x & maxval)) + else: + msg = f"cannot write mode {im.mode} as Palm" + raise OSError(msg) + + # we ignore the palette here + im._mode = "P" + rawmode = f"P;{bpp}" + version = 1 + + elif im.mode == "1": + # monochrome -- write it inverted, as is the Palm standard + rawmode = "1;I" + bpp = 1 + version = 0 + + else: + msg = f"cannot write mode {im.mode} as Palm" + raise OSError(msg) + + # + # make sure image data is available + im.load() + + # write header + + cols = im.size[0] + rows = im.size[1] + + rowbytes = int((cols + (16 // bpp - 1)) / (16 // bpp)) * 2 + transparent_index = 0 + compression_type = _COMPRESSION_TYPES["none"] + + flags = 0 + if im.mode == "P": + flags |= _FLAGS["custom-colormap"] + colormap = im.im.getpalette() + colors = len(colormap) // 3 + colormapsize = 4 * colors + 2 + else: + colormapsize = 0 + + if "offset" in im.info: + offset = (rowbytes * rows + 16 + 3 + colormapsize) // 4 + else: + offset = 0 + + fp.write(o16b(cols) + o16b(rows) + o16b(rowbytes) + o16b(flags)) + fp.write(o8(bpp)) + fp.write(o8(version)) + fp.write(o16b(offset)) + fp.write(o8(transparent_index)) + fp.write(o8(compression_type)) + fp.write(o16b(0)) # reserved by Palm + + # now write colormap if necessary + + if colormapsize: + fp.write(o16b(colors)) + for i in range(colors): + fp.write(o8(i)) + fp.write(colormap[3 * i : 3 * i + 3]) + + # now convert data to raw form + ImageFile._save( + im, fp, [ImageFile._Tile("raw", (0, 0) + im.size, 0, (rawmode, rowbytes, 1))] + ) + + if hasattr(fp, "flush"): + fp.flush() + + +# +# -------------------------------------------------------------------- + +Image.register_save("PALM", _save) + +Image.register_extension("PALM", ".palm") + +Image.register_mime("PALM", "image/palm") diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/PcdImagePlugin.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/PcdImagePlugin.py new file mode 100644 index 000000000..296f3775b --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/PcdImagePlugin.py @@ -0,0 +1,68 @@ +# +# The Python Imaging Library. +# $Id$ +# +# PCD file handling +# +# History: +# 96-05-10 fl Created +# 96-05-27 fl Added draft mode (128x192, 256x384) +# +# Copyright (c) Secret Labs AB 1997. +# Copyright (c) Fredrik Lundh 1996. +# +# See the README file for information on usage and redistribution. +# +from __future__ import annotations + +from . import Image, ImageFile + +## +# Image plugin for PhotoCD images. This plugin only reads the 768x512 +# image from the file; higher resolutions are encoded in a proprietary +# encoding. + + +class PcdImageFile(ImageFile.ImageFile): + format = "PCD" + format_description = "Kodak PhotoCD" + + def _open(self) -> None: + # rough + assert self.fp is not None + + self.fp.seek(2048) + s = self.fp.read(1539) + + if not s.startswith(b"PCD_"): + msg = "not a PCD file" + raise SyntaxError(msg) + + orientation = s[1538] & 3 + self.tile_post_rotate = None + if orientation == 1: + self.tile_post_rotate = 90 + elif orientation == 3: + self.tile_post_rotate = 270 + + self._mode = "RGB" + self._size = (512, 768) if orientation in (1, 3) else (768, 512) + self.tile = [ImageFile._Tile("pcd", (0, 0, 768, 512), 96 * 2048)] + + def load_prepare(self) -> None: + if self._im is None and self.tile_post_rotate: + self.im = Image.core.new(self.mode, (768, 512)) + ImageFile.ImageFile.load_prepare(self) + + def load_end(self) -> None: + if self.tile_post_rotate: + # Handle rotated PCDs + self.im = self.rotate(self.tile_post_rotate, expand=True).im + + +# +# registry + +Image.register_open(PcdImageFile.format, PcdImageFile) + +Image.register_extension(PcdImageFile.format, ".pcd") diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/PcfFontFile.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/PcfFontFile.py new file mode 100644 index 000000000..b923293b0 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/PcfFontFile.py @@ -0,0 +1,258 @@ +# +# THIS IS WORK IN PROGRESS +# +# The Python Imaging Library +# $Id$ +# +# portable compiled font file parser +# +# history: +# 1997-08-19 fl created +# 2003-09-13 fl fixed loading of unicode fonts +# +# Copyright (c) 1997-2003 by Secret Labs AB. +# Copyright (c) 1997-2003 by Fredrik Lundh. +# +# See the README file for information on usage and redistribution. +# +from __future__ import annotations + +import io + +from . import FontFile, Image +from ._binary import i8 +from ._binary import i16be as b16 +from ._binary import i16le as l16 +from ._binary import i32be as b32 +from ._binary import i32le as l32 + +TYPE_CHECKING = False +if TYPE_CHECKING: + from collections.abc import Callable + from typing import BinaryIO + +# -------------------------------------------------------------------- +# declarations + +PCF_MAGIC = 0x70636601 # "\x01fcp" + +PCF_PROPERTIES = 1 << 0 +PCF_ACCELERATORS = 1 << 1 +PCF_METRICS = 1 << 2 +PCF_BITMAPS = 1 << 3 +PCF_INK_METRICS = 1 << 4 +PCF_BDF_ENCODINGS = 1 << 5 +PCF_SWIDTHS = 1 << 6 +PCF_GLYPH_NAMES = 1 << 7 +PCF_BDF_ACCELERATORS = 1 << 8 + +BYTES_PER_ROW: list[Callable[[int], int]] = [ + lambda bits: ((bits + 7) >> 3), + lambda bits: ((bits + 15) >> 3) & ~1, + lambda bits: ((bits + 31) >> 3) & ~3, + lambda bits: ((bits + 63) >> 3) & ~7, +] + + +def sz(s: bytes, o: int) -> bytes: + return s[o : s.index(b"\0", o)] + + +class PcfFontFile(FontFile.FontFile): + """Font file plugin for the X11 PCF format.""" + + name = "name" + + def __init__(self, fp: BinaryIO, charset_encoding: str = "iso8859-1"): + self.charset_encoding = charset_encoding + + magic = l32(fp.read(4)) + if magic != PCF_MAGIC: + msg = "not a PCF file" + raise SyntaxError(msg) + + super().__init__() + + count = l32(fp.read(4)) + self.toc = {} + for i in range(count): + type = l32(fp.read(4)) + self.toc[type] = l32(fp.read(4)), l32(fp.read(4)), l32(fp.read(4)) + + self.fp = fp + + self.info = self._load_properties() + + metrics = self._load_metrics() + bitmaps = self._load_bitmaps(metrics) + encoding = self._load_encoding() + + # + # create glyph structure + + for ch, ix in enumerate(encoding): + if ix is not None: + ( + xsize, + ysize, + left, + right, + width, + ascent, + descent, + attributes, + ) = metrics[ix] + self.glyph[ch] = ( + (width, 0), + (left, descent - ysize, xsize + left, descent), + (0, 0, xsize, ysize), + bitmaps[ix], + ) + + def _getformat( + self, tag: int + ) -> tuple[BinaryIO, int, Callable[[bytes], int], Callable[[bytes], int]]: + format, size, offset = self.toc[tag] + + fp = self.fp + fp.seek(offset) + + format = l32(fp.read(4)) + + if format & 4: + i16, i32 = b16, b32 + else: + i16, i32 = l16, l32 + + return fp, format, i16, i32 + + def _load_properties(self) -> dict[bytes, bytes | int]: + # + # font properties + + properties = {} + + fp, format, i16, i32 = self._getformat(PCF_PROPERTIES) + + nprops = i32(fp.read(4)) + + # read property description + p = [(i32(fp.read(4)), i8(fp.read(1)), i32(fp.read(4))) for _ in range(nprops)] + + if nprops & 3: + fp.seek(4 - (nprops & 3), io.SEEK_CUR) # pad + + data = fp.read(i32(fp.read(4))) + + for k, s, v in p: + property_value: bytes | int = sz(data, v) if s else v + properties[sz(data, k)] = property_value + + return properties + + def _load_metrics(self) -> list[tuple[int, int, int, int, int, int, int, int]]: + # + # font metrics + + metrics: list[tuple[int, int, int, int, int, int, int, int]] = [] + + fp, format, i16, i32 = self._getformat(PCF_METRICS) + + append = metrics.append + + if (format & 0xFF00) == 0x100: + # "compressed" metrics + for i in range(i16(fp.read(2))): + left = i8(fp.read(1)) - 128 + right = i8(fp.read(1)) - 128 + width = i8(fp.read(1)) - 128 + ascent = i8(fp.read(1)) - 128 + descent = i8(fp.read(1)) - 128 + xsize = right - left + ysize = ascent + descent + append((xsize, ysize, left, right, width, ascent, descent, 0)) + + else: + # "jumbo" metrics + for i in range(i32(fp.read(4))): + left = i16(fp.read(2)) + right = i16(fp.read(2)) + width = i16(fp.read(2)) + ascent = i16(fp.read(2)) + descent = i16(fp.read(2)) + attributes = i16(fp.read(2)) + xsize = right - left + ysize = ascent + descent + append((xsize, ysize, left, right, width, ascent, descent, attributes)) + + return metrics + + def _load_bitmaps( + self, metrics: list[tuple[int, int, int, int, int, int, int, int]] + ) -> list[Image.Image]: + # + # bitmap data + + fp, format, i16, i32 = self._getformat(PCF_BITMAPS) + + nbitmaps = i32(fp.read(4)) + + if nbitmaps != len(metrics): + msg = "Wrong number of bitmaps" + raise OSError(msg) + + offsets = [i32(fp.read(4)) for _ in range(nbitmaps)] + + bitmap_sizes = [i32(fp.read(4)) for _ in range(4)] + + # byteorder = format & 4 # non-zero => MSB + bitorder = format & 8 # non-zero => MSB + padindex = format & 3 + + bitmapsize = bitmap_sizes[padindex] + offsets.append(bitmapsize) + + data = fp.read(bitmapsize) + + pad = BYTES_PER_ROW[padindex] + mode = "1;R" + if bitorder: + mode = "1" + + bitmaps = [] + for i in range(nbitmaps): + xsize, ysize = metrics[i][:2] + b, e = offsets[i : i + 2] + bitmaps.append( + Image.frombytes("1", (xsize, ysize), data[b:e], "raw", mode, pad(xsize)) + ) + + return bitmaps + + def _load_encoding(self) -> list[int | None]: + fp, format, i16, i32 = self._getformat(PCF_BDF_ENCODINGS) + + first_col, last_col = i16(fp.read(2)), i16(fp.read(2)) + first_row, last_row = i16(fp.read(2)), i16(fp.read(2)) + + i16(fp.read(2)) # default + + nencoding = (last_col - first_col + 1) * (last_row - first_row + 1) + + # map character code to bitmap index + encoding: list[int | None] = [None] * min(256, nencoding) + + encoding_offsets = [i16(fp.read(2)) for _ in range(nencoding)] + + for i in range(first_col, len(encoding)): + try: + encoding_offset = encoding_offsets[ + ord(bytearray([i]).decode(self.charset_encoding)) + ] + if encoding_offset != 0xFFFF: + encoding[i] = encoding_offset + except UnicodeDecodeError: # noqa: PERF203 + # character is not supported in selected encoding + pass + + return encoding diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/PcxImagePlugin.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/PcxImagePlugin.py new file mode 100644 index 000000000..3e34e3c63 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/PcxImagePlugin.py @@ -0,0 +1,232 @@ +# +# The Python Imaging Library. +# $Id$ +# +# PCX file handling +# +# This format was originally used by ZSoft's popular PaintBrush +# program for the IBM PC. It is also supported by many MS-DOS and +# Windows applications, including the Windows PaintBrush program in +# Windows 3. +# +# history: +# 1995-09-01 fl Created +# 1996-05-20 fl Fixed RGB support +# 1997-01-03 fl Fixed 2-bit and 4-bit support +# 1999-02-03 fl Fixed 8-bit support (broken in 1.0b1) +# 1999-02-07 fl Added write support +# 2002-06-09 fl Made 2-bit and 4-bit support a bit more robust +# 2002-07-30 fl Seek from to current position, not beginning of file +# 2003-06-03 fl Extract DPI settings (info["dpi"]) +# +# Copyright (c) 1997-2003 by Secret Labs AB. +# Copyright (c) 1995-2003 by Fredrik Lundh. +# +# See the README file for information on usage and redistribution. +# +from __future__ import annotations + +import io +import logging +from typing import IO + +from . import Image, ImageFile, ImagePalette +from ._binary import i16le as i16 +from ._binary import o8 +from ._binary import o16le as o16 + +logger = logging.getLogger(__name__) + + +def _accept(prefix: bytes) -> bool: + return len(prefix) >= 2 and prefix[0] == 10 and prefix[1] in [0, 2, 3, 5] + + +## +# Image plugin for Paintbrush images. + + +class PcxImageFile(ImageFile.ImageFile): + format = "PCX" + format_description = "Paintbrush" + + def _open(self) -> None: + # header + assert self.fp is not None + + s = self.fp.read(68) + if not _accept(s): + msg = "not a PCX file" + raise SyntaxError(msg) + + # image + bbox = i16(s, 4), i16(s, 6), i16(s, 8) + 1, i16(s, 10) + 1 + if bbox[2] <= bbox[0] or bbox[3] <= bbox[1]: + msg = "bad PCX image size" + raise SyntaxError(msg) + logger.debug("BBox: %s %s %s %s", *bbox) + + offset = self.fp.tell() + 60 + + # format + version = s[1] + bits = s[3] + planes = s[65] + provided_stride = i16(s, 66) + logger.debug( + "PCX version %s, bits %s, planes %s, stride %s", + version, + bits, + planes, + provided_stride, + ) + + self.info["dpi"] = i16(s, 12), i16(s, 14) + + if bits == 1 and planes == 1: + mode = rawmode = "1" + + elif bits == 1 and planes in (2, 4): + mode = "P" + rawmode = f"P;{planes}L" + self.palette = ImagePalette.raw("RGB", s[16:64]) + + elif version == 5 and bits == 8 and planes == 1: + mode = rawmode = "L" + # FIXME: hey, this doesn't work with the incremental loader !!! + self.fp.seek(-769, io.SEEK_END) + s = self.fp.read(769) + if len(s) == 769 and s[0] == 12: + # check if the palette is linear grayscale + for i in range(256): + if s[i * 3 + 1 : i * 3 + 4] != o8(i) * 3: + mode = rawmode = "P" + break + if mode == "P": + self.palette = ImagePalette.raw("RGB", s[1:]) + + elif version == 5 and bits == 8 and planes == 3: + mode = "RGB" + rawmode = "RGB;L" + + else: + msg = "unknown PCX mode" + raise OSError(msg) + + self._mode = mode + self._size = bbox[2] - bbox[0], bbox[3] - bbox[1] + + # Don't trust the passed in stride. + # Calculate the approximate position for ourselves. + # CVE-2020-35653 + stride = (self._size[0] * bits + 7) // 8 + + # While the specification states that this must be even, + # not all images follow this + if provided_stride != stride: + stride += stride % 2 + + bbox = (0, 0) + self.size + logger.debug("size: %sx%s", *self.size) + + self.tile = [ImageFile._Tile("pcx", bbox, offset, (rawmode, planes * stride))] + + +# -------------------------------------------------------------------- +# save PCX files + + +SAVE = { + # mode: (version, bits, planes, raw mode) + "1": (2, 1, 1, "1"), + "L": (5, 8, 1, "L"), + "P": (5, 8, 1, "P"), + "RGB": (5, 8, 3, "RGB;L"), +} + + +def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None: + if im.width == 0 or im.height == 0: + msg = "Cannot write empty image as PCX" + raise ValueError(msg) + + try: + version, bits, planes, rawmode = SAVE[im.mode] + except KeyError as e: + msg = f"Cannot save {im.mode} images as PCX" + raise ValueError(msg) from e + + # bytes per plane + stride = (im.size[0] * bits + 7) // 8 + # stride should be even + stride += stride % 2 + # Stride needs to be kept in sync with the PcxEncode.c version. + # Ideally it should be passed in in the state, but the bytes value + # gets overwritten. + + logger.debug( + "PcxImagePlugin._save: xwidth: %d, bits: %d, stride: %d", + im.size[0], + bits, + stride, + ) + + # under windows, we could determine the current screen size with + # "Image.core.display_mode()[1]", but I think that's overkill... + + screen = im.size + + dpi = 100, 100 + + # PCX header + fp.write( + o8(10) + + o8(version) + + o8(1) + + o8(bits) + + o16(0) + + o16(0) + + o16(im.size[0] - 1) + + o16(im.size[1] - 1) + + o16(dpi[0]) + + o16(dpi[1]) + + b"\0" * 24 + + b"\xff" * 24 + + b"\0" + + o8(planes) + + o16(stride) + + o16(1) + + o16(screen[0]) + + o16(screen[1]) + + b"\0" * 54 + ) + + assert fp.tell() == 128 + + ImageFile._save( + im, fp, [ImageFile._Tile("pcx", (0, 0) + im.size, 0, (rawmode, bits * planes))] + ) + + if im.mode == "P": + # colour palette + fp.write(o8(12)) + palette = im.im.getpalette("RGB", "RGB") + palette += b"\x00" * (768 - len(palette)) + fp.write(palette) # 768 bytes + elif im.mode == "L": + # grayscale palette + fp.write(o8(12)) + for i in range(256): + fp.write(o8(i) * 3) + + +# -------------------------------------------------------------------- +# registry + + +Image.register_open(PcxImageFile.format, PcxImageFile, _accept) +Image.register_save(PcxImageFile.format, _save) + +Image.register_extension(PcxImageFile.format, ".pcx") + +Image.register_mime(PcxImageFile.format, "image/x-pcx") diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/PdfImagePlugin.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/PdfImagePlugin.py new file mode 100644 index 000000000..5594c7e0f --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/PdfImagePlugin.py @@ -0,0 +1,311 @@ +# +# The Python Imaging Library. +# $Id$ +# +# PDF (Acrobat) file handling +# +# History: +# 1996-07-16 fl Created +# 1997-01-18 fl Fixed header +# 2004-02-21 fl Fixes for 1/L/CMYK images, etc. +# 2004-02-24 fl Fixes for 1 and P images. +# +# Copyright (c) 1997-2004 by Secret Labs AB. All rights reserved. +# Copyright (c) 1996-1997 by Fredrik Lundh. +# +# See the README file for information on usage and redistribution. +# + +## +# Image plugin for PDF images (output only). +## +from __future__ import annotations + +import io +import math +import os +import time +from typing import IO, Any + +from . import Image, ImageFile, ImageSequence, PdfParser, features + +# +# -------------------------------------------------------------------- + +# object ids: +# 1. catalogue +# 2. pages +# 3. image +# 4. page +# 5. page contents + + +def _save_all(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None: + _save(im, fp, filename, save_all=True) + + +## +# (Internal) Image save plugin for the PDF format. + + +def _write_image( + im: Image.Image, + filename: str | bytes, + existing_pdf: PdfParser.PdfParser, + image_refs: list[PdfParser.IndirectReference], +) -> tuple[PdfParser.IndirectReference, str]: + # FIXME: Should replace ASCIIHexDecode with RunLengthDecode + # (packbits) or LZWDecode (tiff/lzw compression). Note that + # PDF 1.2 also supports Flatedecode (zip compression). + + params = None + decode = None + + # + # Get image characteristics + + width, height = im.size + + dict_obj: dict[str, Any] = {"BitsPerComponent": 8} + if im.mode == "1": + if features.check("libtiff"): + decode_filter = "CCITTFaxDecode" + dict_obj["BitsPerComponent"] = 1 + params = PdfParser.PdfArray( + [ + PdfParser.PdfDict( + { + "K": -1, + "BlackIs1": True, + "Columns": width, + "Rows": height, + } + ) + ] + ) + else: + decode_filter = "DCTDecode" + dict_obj["ColorSpace"] = PdfParser.PdfName("DeviceGray") + procset = "ImageB" # grayscale + elif im.mode == "L": + decode_filter = "DCTDecode" + # params = f"<< /Predictor 15 /Columns {width-2} >>" + dict_obj["ColorSpace"] = PdfParser.PdfName("DeviceGray") + procset = "ImageB" # grayscale + elif im.mode == "LA": + decode_filter = "JPXDecode" + # params = f"<< /Predictor 15 /Columns {width-2} >>" + procset = "ImageB" # grayscale + dict_obj["SMaskInData"] = 1 + elif im.mode == "P": + decode_filter = "ASCIIHexDecode" + palette = im.getpalette() + assert palette is not None + dict_obj["ColorSpace"] = [ + PdfParser.PdfName("Indexed"), + PdfParser.PdfName("DeviceRGB"), + len(palette) // 3 - 1, + PdfParser.PdfBinary(palette), + ] + procset = "ImageI" # indexed color + + if "transparency" in im.info: + smask = im.convert("LA").getchannel("A") + smask.encoderinfo = {} + + image_ref = _write_image(smask, filename, existing_pdf, image_refs)[0] + dict_obj["SMask"] = image_ref + elif im.mode == "RGB": + decode_filter = "DCTDecode" + dict_obj["ColorSpace"] = PdfParser.PdfName("DeviceRGB") + procset = "ImageC" # color images + elif im.mode == "RGBA": + decode_filter = "JPXDecode" + procset = "ImageC" # color images + dict_obj["SMaskInData"] = 1 + elif im.mode == "CMYK": + decode_filter = "DCTDecode" + dict_obj["ColorSpace"] = PdfParser.PdfName("DeviceCMYK") + procset = "ImageC" # color images + decode = [1, 0, 1, 0, 1, 0, 1, 0] + else: + msg = f"cannot save mode {im.mode}" + raise ValueError(msg) + + # + # image + + op = io.BytesIO() + + if decode_filter == "ASCIIHexDecode": + ImageFile._save(im, op, [ImageFile._Tile("hex", (0, 0) + im.size, 0, im.mode)]) + elif decode_filter == "CCITTFaxDecode": + im.save( + op, + "TIFF", + compression="group4", + # use a single strip + strip_size=math.ceil(width / 8) * height, + ) + elif decode_filter == "DCTDecode": + Image.SAVE["JPEG"](im, op, filename) + elif decode_filter == "JPXDecode": + del dict_obj["BitsPerComponent"] + Image.SAVE["JPEG2000"](im, op, filename) + else: + msg = f"unsupported PDF filter ({decode_filter})" + raise ValueError(msg) + + stream = op.getvalue() + filter: PdfParser.PdfArray | PdfParser.PdfName + if decode_filter == "CCITTFaxDecode": + stream = stream[8:] + filter = PdfParser.PdfArray([PdfParser.PdfName(decode_filter)]) + else: + filter = PdfParser.PdfName(decode_filter) + + image_ref = image_refs.pop(0) + existing_pdf.write_obj( + image_ref, + stream=stream, + Type=PdfParser.PdfName("XObject"), + Subtype=PdfParser.PdfName("Image"), + Width=width, # * 72.0 / x_resolution, + Height=height, # * 72.0 / y_resolution, + Filter=filter, + Decode=decode, + DecodeParms=params, + **dict_obj, + ) + + return image_ref, procset + + +def _save( + im: Image.Image, fp: IO[bytes], filename: str | bytes, save_all: bool = False +) -> None: + is_appending = im.encoderinfo.get("append", False) + filename_str = filename.decode() if isinstance(filename, bytes) else filename + if is_appending: + existing_pdf = PdfParser.PdfParser(f=fp, filename=filename_str, mode="r+b") + else: + existing_pdf = PdfParser.PdfParser(f=fp, filename=filename_str, mode="w+b") + + dpi = im.encoderinfo.get("dpi") + if dpi: + x_resolution = dpi[0] + y_resolution = dpi[1] + else: + x_resolution = y_resolution = im.encoderinfo.get("resolution", 72.0) + + info = { + "title": ( + None if is_appending else os.path.splitext(os.path.basename(filename))[0] + ), + "author": None, + "subject": None, + "keywords": None, + "creator": None, + "producer": None, + "creationDate": None if is_appending else time.gmtime(), + "modDate": None if is_appending else time.gmtime(), + } + for k, default in info.items(): + v = im.encoderinfo.get(k) if k in im.encoderinfo else default + if v: + existing_pdf.info[k[0].upper() + k[1:]] = v + + # + # make sure image data is available + im.load() + + existing_pdf.start_writing() + existing_pdf.write_header() + existing_pdf.write_comment("created by Pillow PDF driver") + + # + # pages + ims = [im] + if save_all: + append_images = im.encoderinfo.get("append_images", []) + for append_im in append_images: + append_im.encoderinfo = im.encoderinfo.copy() + ims.append(append_im) + number_of_pages = 0 + image_refs = [] + page_refs = [] + contents_refs = [] + for im in ims: + im_number_of_pages = 1 + if save_all: + im_number_of_pages = getattr(im, "n_frames", 1) + number_of_pages += im_number_of_pages + for i in range(im_number_of_pages): + image_refs.append(existing_pdf.next_object_id(0)) + if im.mode == "P" and "transparency" in im.info: + image_refs.append(existing_pdf.next_object_id(0)) + + page_refs.append(existing_pdf.next_object_id(0)) + contents_refs.append(existing_pdf.next_object_id(0)) + existing_pdf.pages.append(page_refs[-1]) + + # + # catalog and list of pages + existing_pdf.write_catalog() + + page_number = 0 + for im_sequence in ims: + im_pages: ImageSequence.Iterator | list[Image.Image] = ( + ImageSequence.Iterator(im_sequence) if save_all else [im_sequence] + ) + for im in im_pages: + image_ref, procset = _write_image(im, filename, existing_pdf, image_refs) + + # + # page + + existing_pdf.write_page( + page_refs[page_number], + Resources=PdfParser.PdfDict( + ProcSet=[PdfParser.PdfName("PDF"), PdfParser.PdfName(procset)], + XObject=PdfParser.PdfDict(image=image_ref), + ), + MediaBox=[ + 0, + 0, + im.width * 72.0 / x_resolution, + im.height * 72.0 / y_resolution, + ], + Contents=contents_refs[page_number], + ) + + # + # page contents + + page_contents = b"q %f 0 0 %f 0 0 cm /image Do Q\n" % ( + im.width * 72.0 / x_resolution, + im.height * 72.0 / y_resolution, + ) + + existing_pdf.write_obj(contents_refs[page_number], stream=page_contents) + + page_number += 1 + + # + # trailer + existing_pdf.write_xref_and_trailer() + if hasattr(fp, "flush"): + fp.flush() + existing_pdf.close() + + +# +# -------------------------------------------------------------------- + + +Image.register_save("PDF", _save) +Image.register_save_all("PDF", _save_all) + +Image.register_extension("PDF", ".pdf") + +Image.register_mime("PDF", "application/pdf") diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/PdfParser.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/PdfParser.py new file mode 100644 index 000000000..f7f3a4643 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/PdfParser.py @@ -0,0 +1,1081 @@ +from __future__ import annotations + +import calendar +import codecs +import collections +import mmap +import os +import re +import time +import zlib +from typing import Any, NamedTuple + +TYPE_CHECKING = False +if TYPE_CHECKING: + from typing import IO + + _DictBase = collections.UserDict[str | bytes, Any] +else: + _DictBase = collections.UserDict + + +# see 7.9.2.2 Text String Type on page 86 and D.3 PDFDocEncoding Character Set +# on page 656 +def encode_text(s: str) -> bytes: + return codecs.BOM_UTF16_BE + s.encode("utf_16_be") + + +PDFDocEncoding = { + 0x16: "\u0017", + 0x18: "\u02d8", + 0x19: "\u02c7", + 0x1A: "\u02c6", + 0x1B: "\u02d9", + 0x1C: "\u02dd", + 0x1D: "\u02db", + 0x1E: "\u02da", + 0x1F: "\u02dc", + 0x80: "\u2022", + 0x81: "\u2020", + 0x82: "\u2021", + 0x83: "\u2026", + 0x84: "\u2014", + 0x85: "\u2013", + 0x86: "\u0192", + 0x87: "\u2044", + 0x88: "\u2039", + 0x89: "\u203a", + 0x8A: "\u2212", + 0x8B: "\u2030", + 0x8C: "\u201e", + 0x8D: "\u201c", + 0x8E: "\u201d", + 0x8F: "\u2018", + 0x90: "\u2019", + 0x91: "\u201a", + 0x92: "\u2122", + 0x93: "\ufb01", + 0x94: "\ufb02", + 0x95: "\u0141", + 0x96: "\u0152", + 0x97: "\u0160", + 0x98: "\u0178", + 0x99: "\u017d", + 0x9A: "\u0131", + 0x9B: "\u0142", + 0x9C: "\u0153", + 0x9D: "\u0161", + 0x9E: "\u017e", + 0xA0: "\u20ac", +} + + +def decode_text(b: bytes) -> str: + if b[: len(codecs.BOM_UTF16_BE)] == codecs.BOM_UTF16_BE: + return b[len(codecs.BOM_UTF16_BE) :].decode("utf_16_be") + else: + return "".join(PDFDocEncoding.get(byte, chr(byte)) for byte in b) + + +class PdfFormatError(RuntimeError): + """An error that probably indicates a syntactic or semantic error in the + PDF file structure""" + + pass + + +def check_format_condition(condition: bool, error_message: str) -> None: + if not condition: + raise PdfFormatError(error_message) + + +class IndirectReferenceTuple(NamedTuple): + object_id: int + generation: int + + +class IndirectReference(IndirectReferenceTuple): + def __str__(self) -> str: + return f"{self.object_id} {self.generation} R" + + def __bytes__(self) -> bytes: + return self.__str__().encode("us-ascii") + + def __eq__(self, other: object) -> bool: + if self.__class__ is not other.__class__: + return False + assert isinstance(other, IndirectReference) + return other.object_id == self.object_id and other.generation == self.generation + + def __ne__(self, other: object) -> bool: + return not (self == other) + + def __hash__(self) -> int: + return hash((self.object_id, self.generation)) + + +class IndirectObjectDef(IndirectReference): + def __str__(self) -> str: + return f"{self.object_id} {self.generation} obj" + + +class XrefTable: + def __init__(self) -> None: + self.existing_entries: dict[int, tuple[int, int]] = ( + {} + ) # object ID => (offset, generation) + self.new_entries: dict[int, tuple[int, int]] = ( + {} + ) # object ID => (offset, generation) + self.deleted_entries = {0: 65536} # object ID => generation + self.reading_finished = False + + def __setitem__(self, key: int, value: tuple[int, int]) -> None: + if self.reading_finished: + self.new_entries[key] = value + else: + self.existing_entries[key] = value + if key in self.deleted_entries: + del self.deleted_entries[key] + + def __getitem__(self, key: int) -> tuple[int, int]: + try: + return self.new_entries[key] + except KeyError: + return self.existing_entries[key] + + def __delitem__(self, key: int) -> None: + if key in self.new_entries: + generation = self.new_entries[key][1] + 1 + del self.new_entries[key] + self.deleted_entries[key] = generation + elif key in self.existing_entries: + generation = self.existing_entries[key][1] + 1 + self.deleted_entries[key] = generation + elif key in self.deleted_entries: + generation = self.deleted_entries[key] + else: + msg = f"object ID {key} cannot be deleted because it doesn't exist" + raise IndexError(msg) + + def __contains__(self, key: int) -> bool: + return key in self.existing_entries or key in self.new_entries + + def __len__(self) -> int: + return len( + set(self.existing_entries.keys()) + | set(self.new_entries.keys()) + | set(self.deleted_entries.keys()) + ) + + def keys(self) -> set[int]: + return ( + set(self.existing_entries.keys()) - set(self.deleted_entries.keys()) + ) | set(self.new_entries.keys()) + + def write(self, f: IO[bytes]) -> int: + keys = sorted(set(self.new_entries.keys()) | set(self.deleted_entries.keys())) + deleted_keys = sorted(set(self.deleted_entries.keys())) + startxref = f.tell() + f.write(b"xref\n") + while keys: + # find a contiguous sequence of object IDs + prev: int | None = None + for index, key in enumerate(keys): + if prev is None or prev + 1 == key: + prev = key + else: + contiguous_keys = keys[:index] + keys = keys[index:] + break + else: + contiguous_keys = keys + keys = [] + f.write(b"%d %d\n" % (contiguous_keys[0], len(contiguous_keys))) + for object_id in contiguous_keys: + if object_id in self.new_entries: + f.write(b"%010d %05d n \n" % self.new_entries[object_id]) + else: + this_deleted_object_id = deleted_keys.pop(0) + check_format_condition( + object_id == this_deleted_object_id, + f"expected the next deleted object ID to be {object_id}, " + f"instead found {this_deleted_object_id}", + ) + try: + next_in_linked_list = deleted_keys[0] + except IndexError: + next_in_linked_list = 0 + f.write( + b"%010d %05d f \n" + % (next_in_linked_list, self.deleted_entries[object_id]) + ) + return startxref + + +class PdfName: + name: bytes + + def __init__(self, name: PdfName | bytes | str) -> None: + if isinstance(name, PdfName): + self.name = name.name + elif isinstance(name, bytes): + self.name = name + else: + self.name = name.encode("us-ascii") + + def name_as_str(self) -> str: + return self.name.decode("us-ascii") + + def __eq__(self, other: object) -> bool: + return ( + isinstance(other, PdfName) and other.name == self.name + ) or other == self.name + + def __hash__(self) -> int: + return hash(self.name) + + def __repr__(self) -> str: + return f"{self.__class__.__name__}({repr(self.name)})" + + @classmethod + def from_pdf_stream(cls, data: bytes) -> PdfName: + return cls(PdfParser.interpret_name(data)) + + allowed_chars = set(range(33, 127)) - {ord(c) for c in "#%/()<>[]{}"} + + def __bytes__(self) -> bytes: + result = bytearray(b"/") + for b in self.name: + if b in self.allowed_chars: + result.append(b) + else: + result.extend(b"#%02X" % b) + return bytes(result) + + +class PdfArray(list[Any]): + def __bytes__(self) -> bytes: + return b"[ " + b" ".join(pdf_repr(x) for x in self) + b" ]" + + +class PdfDict(_DictBase): + def __setattr__(self, key: str, value: Any) -> None: + if key == "data": + collections.UserDict.__setattr__(self, key, value) + else: + self[key.encode("us-ascii")] = value + + def __getattr__(self, key: str) -> str | time.struct_time: + try: + value = self[key.encode("us-ascii")] + except KeyError as e: + raise AttributeError(key) from e + if isinstance(value, bytes): + value = decode_text(value) + if key.endswith("Date"): + if value.startswith("D:"): + value = value[2:] + + relationship = "Z" + if len(value) > 17: + relationship = value[14] + offset = int(value[15:17]) * 60 + if len(value) > 20: + offset += int(value[18:20]) + + format = "%Y%m%d%H%M%S"[: len(value) - 2] + value = time.strptime(value[: len(format) + 2], format) + if relationship in ["+", "-"]: + offset *= 60 + if relationship == "+": + offset *= -1 + value = time.gmtime(calendar.timegm(value) + offset) + return value + + def __bytes__(self) -> bytes: + out = bytearray(b"<<") + for key, value in self.items(): + if value is None: + continue + value = pdf_repr(value) + out.extend(b"\n") + out.extend(bytes(PdfName(key))) + out.extend(b" ") + out.extend(value) + out.extend(b"\n>>") + return bytes(out) + + +class PdfBinary: + def __init__(self, data: list[int] | bytes) -> None: + self.data = data + + def __bytes__(self) -> bytes: + return b"<%s>" % b"".join(b"%02X" % b for b in self.data) + + +class PdfStream: + def __init__(self, dictionary: PdfDict, buf: bytes) -> None: + self.dictionary = dictionary + self.buf = buf + + def decode(self) -> bytes: + try: + filter = self.dictionary[b"Filter"] + except KeyError: + return self.buf + if filter == b"FlateDecode": + try: + expected_length = self.dictionary[b"DL"] + except KeyError: + expected_length = self.dictionary[b"Length"] + return zlib.decompress(self.buf, bufsize=int(expected_length)) + else: + msg = f"stream filter {repr(filter)} unknown/unsupported" + raise NotImplementedError(msg) + + +def pdf_repr(x: Any) -> bytes: + if x is True: + return b"true" + elif x is False: + return b"false" + elif x is None: + return b"null" + elif isinstance(x, (PdfName, PdfDict, PdfArray, PdfBinary)): + return bytes(x) + elif isinstance(x, (int, float)): + return str(x).encode("us-ascii") + elif isinstance(x, time.struct_time): + return b"(D:" + time.strftime("%Y%m%d%H%M%SZ", x).encode("us-ascii") + b")" + elif isinstance(x, dict): + return bytes(PdfDict(x)) + elif isinstance(x, list): + return bytes(PdfArray(x)) + elif isinstance(x, str): + return pdf_repr(encode_text(x)) + elif isinstance(x, bytes): + # XXX escape more chars? handle binary garbage + x = x.replace(b"\\", b"\\\\") + x = x.replace(b"(", b"\\(") + x = x.replace(b")", b"\\)") + return b"(" + x + b")" + else: + return bytes(x) + + +class PdfParser: + """Based on + https://www.adobe.com/content/dam/acom/en/devnet/acrobat/pdfs/PDF32000_2008.pdf + Supports PDF up to 1.4 + """ + + def __init__( + self, + filename: str | None = None, + f: IO[bytes] | None = None, + buf: bytes | bytearray | None = None, + start_offset: int = 0, + mode: str = "rb", + ) -> None: + if buf and f: + msg = "specify buf or f or filename, but not both buf and f" + raise RuntimeError(msg) + self.filename = filename + self.buf: bytes | bytearray | mmap.mmap | None = buf + self.f = f + self.start_offset = start_offset + self.should_close_buf = False + self.should_close_file = False + if filename is not None and f is None: + self.f = f = open(filename, mode) + self.should_close_file = True + if f is not None: + self.buf = self.get_buf_from_file(f) + self.should_close_buf = True + if not filename and hasattr(f, "name"): + self.filename = f.name + self.cached_objects: dict[IndirectReference, Any] = {} + self.root_ref: IndirectReference | None + self.info_ref: IndirectReference | None + self.pages_ref: IndirectReference | None + self.last_xref_section_offset: int | None + if self.buf: + self.read_pdf_info() + else: + self.file_size_total = self.file_size_this = 0 + self.root = PdfDict() + self.root_ref = None + self.info = PdfDict() + self.info_ref = None + self.page_tree_root = PdfDict() + self.pages: list[IndirectReference] = [] + self.orig_pages: list[IndirectReference] = [] + self.pages_ref = None + self.last_xref_section_offset = None + self.trailer_dict: dict[bytes, Any] = {} + self.xref_table = XrefTable() + self.xref_table.reading_finished = True + if f: + self.seek_end() + + def __enter__(self) -> PdfParser: + return self + + def __exit__(self, *args: object) -> None: + self.close() + + def start_writing(self) -> None: + self.close_buf() + self.seek_end() + + def close_buf(self) -> None: + if isinstance(self.buf, mmap.mmap): + self.buf.close() + self.buf = None + + def close(self) -> None: + if self.should_close_buf: + self.close_buf() + if self.f is not None and self.should_close_file: + self.f.close() + self.f = None + + def seek_end(self) -> None: + assert self.f is not None + self.f.seek(0, os.SEEK_END) + + def write_header(self) -> None: + assert self.f is not None + self.f.write(b"%PDF-1.4\n") + + def write_comment(self, s: str) -> None: + assert self.f is not None + self.f.write(f"% {s}\n".encode()) + + def write_catalog(self) -> IndirectReference: + assert self.f is not None + self.del_root() + self.root_ref = self.next_object_id(self.f.tell()) + self.pages_ref = self.next_object_id(0) + self.rewrite_pages() + self.write_obj(self.root_ref, Type=PdfName(b"Catalog"), Pages=self.pages_ref) + self.write_obj( + self.pages_ref, + Type=PdfName(b"Pages"), + Count=len(self.pages), + Kids=self.pages, + ) + return self.root_ref + + def rewrite_pages(self) -> None: + pages_tree_nodes_to_delete = [] + for i, page_ref in enumerate(self.orig_pages): + page_info = self.cached_objects[page_ref] + del self.xref_table[page_ref.object_id] + pages_tree_nodes_to_delete.append(page_info[PdfName(b"Parent")]) + if page_ref not in self.pages: + # the page has been deleted + continue + # make dict keys into strings for passing to write_page + stringified_page_info = {} + for key, value in page_info.items(): + # key should be a PdfName + stringified_page_info[key.name_as_str()] = value + stringified_page_info["Parent"] = self.pages_ref + new_page_ref = self.write_page(None, **stringified_page_info) + for j, cur_page_ref in enumerate(self.pages): + if cur_page_ref == page_ref: + # replace the page reference with the new one + self.pages[j] = new_page_ref + # delete redundant Pages tree nodes from xref table + for pages_tree_node_ref in pages_tree_nodes_to_delete: + while pages_tree_node_ref: + pages_tree_node = self.cached_objects[pages_tree_node_ref] + if pages_tree_node_ref.object_id in self.xref_table: + del self.xref_table[pages_tree_node_ref.object_id] + pages_tree_node_ref = pages_tree_node.get(b"Parent", None) + self.orig_pages = [] + + def write_xref_and_trailer( + self, new_root_ref: IndirectReference | None = None + ) -> None: + assert self.f is not None + if new_root_ref: + self.del_root() + self.root_ref = new_root_ref + if self.info: + self.info_ref = self.write_obj(None, self.info) + start_xref = self.xref_table.write(self.f) + num_entries = len(self.xref_table) + trailer_dict: dict[str | bytes, Any] = { + b"Root": self.root_ref, + b"Size": num_entries, + } + if self.last_xref_section_offset is not None: + trailer_dict[b"Prev"] = self.last_xref_section_offset + if self.info: + trailer_dict[b"Info"] = self.info_ref + self.last_xref_section_offset = start_xref + self.f.write( + b"trailer\n" + + bytes(PdfDict(trailer_dict)) + + b"\nstartxref\n%d\n%%%%EOF" % start_xref + ) + + def write_page( + self, ref: int | IndirectReference | None, *objs: Any, **dict_obj: Any + ) -> IndirectReference: + obj_ref = self.pages[ref] if isinstance(ref, int) else ref + if "Type" not in dict_obj: + dict_obj["Type"] = PdfName(b"Page") + if "Parent" not in dict_obj: + dict_obj["Parent"] = self.pages_ref + return self.write_obj(obj_ref, *objs, **dict_obj) + + def write_obj( + self, ref: IndirectReference | None, *objs: Any, **dict_obj: Any + ) -> IndirectReference: + assert self.f is not None + f = self.f + if ref is None: + ref = self.next_object_id(f.tell()) + else: + self.xref_table[ref.object_id] = (f.tell(), ref.generation) + f.write(bytes(IndirectObjectDef(*ref))) + stream = dict_obj.pop("stream", None) + if stream is not None: + dict_obj["Length"] = len(stream) + if dict_obj: + f.write(pdf_repr(dict_obj)) + for obj in objs: + f.write(pdf_repr(obj)) + if stream is not None: + f.write(b"stream\n") + f.write(stream) + f.write(b"\nendstream\n") + f.write(b"endobj\n") + return ref + + def del_root(self) -> None: + if self.root_ref is None: + return + del self.xref_table[self.root_ref.object_id] + del self.xref_table[self.root[b"Pages"].object_id] + + @staticmethod + def get_buf_from_file(f: IO[bytes]) -> bytes | mmap.mmap: + if hasattr(f, "getbuffer"): + return f.getbuffer() + elif hasattr(f, "getvalue"): + return f.getvalue() + else: + try: + return mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ) + except ValueError: # cannot mmap an empty file + return b"" + + def read_pdf_info(self) -> None: + assert self.buf is not None + self.file_size_total = len(self.buf) + self.file_size_this = self.file_size_total - self.start_offset + self.read_trailer() + check_format_condition( + self.trailer_dict.get(b"Root") is not None, "Root is missing" + ) + self.root_ref = self.trailer_dict[b"Root"] + assert self.root_ref is not None + self.info_ref = self.trailer_dict.get(b"Info", None) + self.root = PdfDict(self.read_indirect(self.root_ref)) + if self.info_ref is None: + self.info = PdfDict() + else: + self.info = PdfDict(self.read_indirect(self.info_ref)) + check_format_condition(b"Type" in self.root, "/Type missing in Root") + check_format_condition( + self.root[b"Type"] == b"Catalog", "/Type in Root is not /Catalog" + ) + check_format_condition( + self.root.get(b"Pages") is not None, "/Pages missing in Root" + ) + check_format_condition( + isinstance(self.root[b"Pages"], IndirectReference), + "/Pages in Root is not an indirect reference", + ) + self.pages_ref = self.root[b"Pages"] + assert self.pages_ref is not None + self.page_tree_root = self.read_indirect(self.pages_ref) + self.pages = self.linearize_page_tree(self.page_tree_root) + # save the original list of page references + # in case the user modifies, adds or deletes some pages + # and we need to rewrite the pages and their list + self.orig_pages = self.pages[:] + + def next_object_id(self, offset: int | None = None) -> IndirectReference: + try: + # TODO: support reuse of deleted objects + reference = IndirectReference(max(self.xref_table.keys()) + 1, 0) + except ValueError: + reference = IndirectReference(1, 0) + if offset is not None: + self.xref_table[reference.object_id] = (offset, 0) + return reference + + delimiter = rb"[][()<>{}/%]" + delimiter_or_ws = rb"[][()<>{}/%\000\011\012\014\015\040]" + whitespace = rb"[\000\011\012\014\015\040]" + whitespace_or_hex = rb"[\000\011\012\014\015\0400-9a-fA-F]" + whitespace_optional = whitespace + b"*" + whitespace_mandatory = whitespace + b"+" + # No "\012" aka "\n" or "\015" aka "\r": + whitespace_optional_no_nl = rb"[\000\011\014\040]*" + newline_only = rb"[\r\n]+" + newline = whitespace_optional_no_nl + newline_only + whitespace_optional_no_nl + re_trailer_end = re.compile( + whitespace_mandatory + + rb"trailer" + + whitespace_optional + + rb"<<(.*>>)" + + newline + + rb"startxref" + + newline + + rb"([0-9]+)" + + newline + + rb"%%EOF" + + whitespace_optional + + rb"$", + re.DOTALL, + ) + re_trailer_prev = re.compile( + whitespace_optional + + rb"trailer" + + whitespace_optional + + rb"<<(.*?>>)" + + newline + + rb"startxref" + + newline + + rb"([0-9]+)" + + newline + + rb"%%EOF" + + whitespace_optional, + re.DOTALL, + ) + + def read_trailer(self) -> None: + assert self.buf is not None + search_start_offset = len(self.buf) - 16384 + if search_start_offset < self.start_offset: + search_start_offset = self.start_offset + m = self.re_trailer_end.search(self.buf, search_start_offset) + check_format_condition(m is not None, "trailer end not found") + # make sure we found the LAST trailer + last_match = m + while m: + last_match = m + m = self.re_trailer_end.search(self.buf, m.start() + 16) + if not m: + m = last_match + assert m is not None + trailer_data = m.group(1) + self.last_xref_section_offset = int(m.group(2)) + self.trailer_dict = self.interpret_trailer(trailer_data) + self.xref_table = XrefTable() + self.read_xref_table(xref_section_offset=self.last_xref_section_offset) + if b"Prev" in self.trailer_dict: + self.read_prev_trailer(self.trailer_dict[b"Prev"]) + + def read_prev_trailer( + self, xref_section_offset: int, processed_offsets: list[int] = [] + ) -> None: + assert self.buf is not None + trailer_offset = self.read_xref_table(xref_section_offset=xref_section_offset) + m = self.re_trailer_prev.search( + self.buf[trailer_offset : trailer_offset + 16384] + ) + check_format_condition(m is not None, "previous trailer not found") + assert m is not None + trailer_data = m.group(1) + check_format_condition( + int(m.group(2)) == xref_section_offset, + "xref section offset in previous trailer doesn't match what was expected", + ) + trailer_dict = self.interpret_trailer(trailer_data) + if b"Prev" in trailer_dict: + processed_offsets.append(xref_section_offset) + check_format_condition( + trailer_dict[b"Prev"] not in processed_offsets, "trailer loop found" + ) + self.read_prev_trailer(trailer_dict[b"Prev"], processed_offsets) + + re_whitespace_optional = re.compile(whitespace_optional) + re_name = re.compile( + whitespace_optional + + rb"/([!-$&'*-.0-;=?-Z\\^-z|~]+)(?=" + + delimiter_or_ws + + rb")" + ) + re_dict_start = re.compile(whitespace_optional + rb"<<") + re_dict_end = re.compile(whitespace_optional + rb">>" + whitespace_optional) + + @classmethod + def interpret_trailer(cls, trailer_data: bytes) -> dict[bytes, Any]: + trailer = {} + offset = 0 + while True: + m = cls.re_name.match(trailer_data, offset) + if not m: + m = cls.re_dict_end.match(trailer_data, offset) + check_format_condition( + m is not None and m.end() == len(trailer_data), + "name not found in trailer, remaining data: " + + repr(trailer_data[offset:]), + ) + break + key = cls.interpret_name(m.group(1)) + assert isinstance(key, bytes) + value, value_offset = cls.get_value(trailer_data, m.end()) + trailer[key] = value + if value_offset is None: + break + offset = value_offset + check_format_condition( + b"Size" in trailer and isinstance(trailer[b"Size"], int), + "/Size not in trailer or not an integer", + ) + check_format_condition( + b"Root" in trailer and isinstance(trailer[b"Root"], IndirectReference), + "/Root not in trailer or not an indirect reference", + ) + return trailer + + re_hashes_in_name = re.compile(rb"([^#]*)(#([0-9a-fA-F]{2}))?") + + @classmethod + def interpret_name(cls, raw: bytes, as_text: bool = False) -> str | bytes: + name = b"" + for m in cls.re_hashes_in_name.finditer(raw): + if m.group(3): + name += m.group(1) + bytearray.fromhex(m.group(3).decode("us-ascii")) + else: + name += m.group(1) + if as_text: + return name.decode("utf-8") + else: + return bytes(name) + + re_null = re.compile(whitespace_optional + rb"null(?=" + delimiter_or_ws + rb")") + re_true = re.compile(whitespace_optional + rb"true(?=" + delimiter_or_ws + rb")") + re_false = re.compile(whitespace_optional + rb"false(?=" + delimiter_or_ws + rb")") + re_int = re.compile( + whitespace_optional + rb"([-+]?[0-9]+)(?=" + delimiter_or_ws + rb")" + ) + re_real = re.compile( + whitespace_optional + + rb"([-+]?([0-9]+\.[0-9]*|[0-9]*\.[0-9]+))(?=" + + delimiter_or_ws + + rb")" + ) + re_array_start = re.compile(whitespace_optional + rb"\[") + re_array_end = re.compile(whitespace_optional + rb"]") + re_string_hex = re.compile( + whitespace_optional + rb"<(" + whitespace_or_hex + rb"*)>" + ) + re_string_lit = re.compile(whitespace_optional + rb"\(") + re_indirect_reference = re.compile( + whitespace_optional + + rb"([-+]?[0-9]+)" + + whitespace_mandatory + + rb"([-+]?[0-9]+)" + + whitespace_mandatory + + rb"R(?=" + + delimiter_or_ws + + rb")" + ) + re_indirect_def_start = re.compile( + whitespace_optional + + rb"([-+]?[0-9]+)" + + whitespace_mandatory + + rb"([-+]?[0-9]+)" + + whitespace_mandatory + + rb"obj(?=" + + delimiter_or_ws + + rb")" + ) + re_indirect_def_end = re.compile( + whitespace_optional + rb"endobj(?=" + delimiter_or_ws + rb")" + ) + re_comment = re.compile( + rb"(" + whitespace_optional + rb"%[^\r\n]*" + newline + rb")*" + ) + re_stream_start = re.compile(whitespace_optional + rb"stream\r?\n") + re_stream_end = re.compile( + whitespace_optional + rb"endstream(?=" + delimiter_or_ws + rb")" + ) + + @classmethod + def get_value( + cls, + data: bytes | bytearray | mmap.mmap, + offset: int, + expect_indirect: IndirectReference | None = None, + max_nesting: int = -1, + ) -> tuple[Any, int | None]: + if max_nesting == 0: + return None, None + m = cls.re_comment.match(data, offset) + if m: + offset = m.end() + m = cls.re_indirect_def_start.match(data, offset) + if m: + check_format_condition( + int(m.group(1)) > 0, + "indirect object definition: object ID must be greater than 0", + ) + check_format_condition( + int(m.group(2)) >= 0, + "indirect object definition: generation must be non-negative", + ) + check_format_condition( + expect_indirect is None + or expect_indirect + == IndirectReference(int(m.group(1)), int(m.group(2))), + "indirect object definition different than expected", + ) + object, object_offset = cls.get_value( + data, m.end(), max_nesting=max_nesting - 1 + ) + if object_offset is None: + return object, None + m = cls.re_indirect_def_end.match(data, object_offset) + check_format_condition( + m is not None, "indirect object definition end not found" + ) + assert m is not None + return object, m.end() + check_format_condition( + not expect_indirect, "indirect object definition not found" + ) + m = cls.re_indirect_reference.match(data, offset) + if m: + check_format_condition( + int(m.group(1)) > 0, + "indirect object reference: object ID must be greater than 0", + ) + check_format_condition( + int(m.group(2)) >= 0, + "indirect object reference: generation must be non-negative", + ) + return IndirectReference(int(m.group(1)), int(m.group(2))), m.end() + m = cls.re_dict_start.match(data, offset) + if m: + offset = m.end() + result: dict[Any, Any] = {} + m = cls.re_dict_end.match(data, offset) + current_offset: int | None = offset + while not m: + assert current_offset is not None + key, current_offset = cls.get_value( + data, current_offset, max_nesting=max_nesting - 1 + ) + if current_offset is None: + return result, None + value, current_offset = cls.get_value( + data, current_offset, max_nesting=max_nesting - 1 + ) + result[key] = value + if current_offset is None: + return result, None + m = cls.re_dict_end.match(data, current_offset) + current_offset = m.end() + m = cls.re_stream_start.match(data, current_offset) + if m: + stream_len = result.get(b"Length") + if stream_len is None or not isinstance(stream_len, int): + msg = f"bad or missing Length in stream dict ({stream_len})" + raise PdfFormatError(msg) + stream_data = data[m.end() : m.end() + stream_len] + m = cls.re_stream_end.match(data, m.end() + stream_len) + check_format_condition(m is not None, "stream end not found") + assert m is not None + current_offset = m.end() + return PdfStream(PdfDict(result), stream_data), current_offset + return PdfDict(result), current_offset + m = cls.re_array_start.match(data, offset) + if m: + offset = m.end() + results = [] + m = cls.re_array_end.match(data, offset) + current_offset = offset + while not m: + assert current_offset is not None + value, current_offset = cls.get_value( + data, current_offset, max_nesting=max_nesting - 1 + ) + results.append(value) + if current_offset is None: + return results, None + m = cls.re_array_end.match(data, current_offset) + return results, m.end() + m = cls.re_null.match(data, offset) + if m: + return None, m.end() + m = cls.re_true.match(data, offset) + if m: + return True, m.end() + m = cls.re_false.match(data, offset) + if m: + return False, m.end() + m = cls.re_name.match(data, offset) + if m: + return PdfName(cls.interpret_name(m.group(1))), m.end() + m = cls.re_int.match(data, offset) + if m: + return int(m.group(1)), m.end() + m = cls.re_real.match(data, offset) + if m: + # XXX Decimal instead of float??? + return float(m.group(1)), m.end() + m = cls.re_string_hex.match(data, offset) + if m: + # filter out whitespace + hex_string = bytearray( + b for b in m.group(1) if b in b"0123456789abcdefABCDEF" + ) + if len(hex_string) % 2 == 1: + # append a 0 if the length is not even - yes, at the end + hex_string.append(ord(b"0")) + return bytearray.fromhex(hex_string.decode("us-ascii")), m.end() + m = cls.re_string_lit.match(data, offset) + if m: + return cls.get_literal_string(data, m.end()) + # return None, offset # fallback (only for debugging) + msg = f"unrecognized object: {repr(data[offset : offset + 32])}" + raise PdfFormatError(msg) + + re_lit_str_token = re.compile( + rb"(\\[nrtbf()\\])|(\\[0-9]{1,3})|(\\(\r\n|\r|\n))|(\r\n|\r|\n)|(\()|(\))" + ) + escaped_chars = { + b"n": b"\n", + b"r": b"\r", + b"t": b"\t", + b"b": b"\b", + b"f": b"\f", + b"(": b"(", + b")": b")", + b"\\": b"\\", + ord(b"n"): b"\n", + ord(b"r"): b"\r", + ord(b"t"): b"\t", + ord(b"b"): b"\b", + ord(b"f"): b"\f", + ord(b"("): b"(", + ord(b")"): b")", + ord(b"\\"): b"\\", + } + + @classmethod + def get_literal_string( + cls, data: bytes | bytearray | mmap.mmap, offset: int + ) -> tuple[bytes, int]: + nesting_depth = 0 + result = bytearray() + for m in cls.re_lit_str_token.finditer(data, offset): + result.extend(data[offset : m.start()]) + if m.group(1): + result.extend(cls.escaped_chars[m.group(1)[1]]) + elif m.group(2): + result.append(int(m.group(2)[1:], 8)) + elif m.group(3): + pass + elif m.group(5): + result.extend(b"\n") + elif m.group(6): + result.extend(b"(") + nesting_depth += 1 + elif m.group(7): + if nesting_depth == 0: + return bytes(result), m.end() + result.extend(b")") + nesting_depth -= 1 + offset = m.end() + msg = "unfinished literal string" + raise PdfFormatError(msg) + + re_xref_section_start = re.compile(whitespace_optional + rb"xref" + newline) + re_xref_subsection_start = re.compile( + whitespace_optional + + rb"([0-9]+)" + + whitespace_mandatory + + rb"([0-9]+)" + + whitespace_optional + + newline_only + ) + re_xref_entry = re.compile(rb"([0-9]{10}) ([0-9]{5}) ([fn])( \r| \n|\r\n)") + + def read_xref_table(self, xref_section_offset: int) -> int: + assert self.buf is not None + subsection_found = False + m = self.re_xref_section_start.match( + self.buf, xref_section_offset + self.start_offset + ) + check_format_condition(m is not None, "xref section start not found") + assert m is not None + offset = m.end() + while True: + m = self.re_xref_subsection_start.match(self.buf, offset) + if not m: + check_format_condition( + subsection_found, "xref subsection start not found" + ) + break + subsection_found = True + offset = m.end() + first_object = int(m.group(1)) + num_objects = int(m.group(2)) + for i in range(first_object, first_object + num_objects): + m = self.re_xref_entry.match(self.buf, offset) + check_format_condition(m is not None, "xref entry not found") + assert m is not None + offset = m.end() + is_free = m.group(3) == b"f" + if not is_free: + generation = int(m.group(2)) + new_entry = (int(m.group(1)), generation) + if i not in self.xref_table: + self.xref_table[i] = new_entry + return offset + + def read_indirect(self, ref: IndirectReference, max_nesting: int = -1) -> Any: + offset, generation = self.xref_table[ref[0]] + check_format_condition( + generation == ref[1], + f"expected to find generation {ref[1]} for object ID {ref[0]} in xref " + f"table, instead found generation {generation} at offset {offset}", + ) + assert self.buf is not None + value = self.get_value( + self.buf, + offset + self.start_offset, + expect_indirect=IndirectReference(*ref), + max_nesting=max_nesting, + )[0] + self.cached_objects[ref] = value + return value + + def linearize_page_tree( + self, node: PdfDict | None = None + ) -> list[IndirectReference]: + page_node = node if node is not None else self.page_tree_root + check_format_condition( + page_node[b"Type"] == b"Pages", "/Type of page tree node is not /Pages" + ) + pages = [] + for kid in page_node[b"Kids"]: + kid_object = self.read_indirect(kid) + if kid_object[b"Type"] == b"Page": + pages.append(kid) + else: + pages.extend(self.linearize_page_tree(node=kid_object)) + return pages diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/PixarImagePlugin.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/PixarImagePlugin.py new file mode 100644 index 000000000..d2b6d0a97 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/PixarImagePlugin.py @@ -0,0 +1,72 @@ +# +# The Python Imaging Library. +# $Id$ +# +# PIXAR raster support for PIL +# +# history: +# 97-01-29 fl Created +# +# notes: +# This is incomplete; it is based on a few samples created with +# Photoshop 2.5 and 3.0, and a summary description provided by +# Greg Coats . Hopefully, "L" and +# "RGBA" support will be added in future versions. +# +# Copyright (c) Secret Labs AB 1997. +# Copyright (c) Fredrik Lundh 1997. +# +# See the README file for information on usage and redistribution. +# +from __future__ import annotations + +from . import Image, ImageFile +from ._binary import i16le as i16 + +# +# helpers + + +def _accept(prefix: bytes) -> bool: + return prefix.startswith(b"\200\350\000\000") + + +## +# Image plugin for PIXAR raster images. + + +class PixarImageFile(ImageFile.ImageFile): + format = "PIXAR" + format_description = "PIXAR raster image" + + def _open(self) -> None: + # assuming a 4-byte magic label + assert self.fp is not None + + s = self.fp.read(4) + if not _accept(s): + msg = "not a PIXAR file" + raise SyntaxError(msg) + + # read rest of header + s = s + self.fp.read(508) + + self._size = i16(s, 418), i16(s, 416) + + # get channel/depth descriptions + mode = i16(s, 424), i16(s, 426) + + if mode == (14, 2): + self._mode = "RGB" + # FIXME: to be continued... + + # create tile descriptor (assuming "dumped") + self.tile = [ImageFile._Tile("raw", (0, 0) + self.size, 1024, self.mode)] + + +# +# -------------------------------------------------------------------- + +Image.register_open(PixarImageFile.format, PixarImageFile, _accept) + +Image.register_extension(PixarImageFile.format, ".pxr") diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/PngImagePlugin.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/PngImagePlugin.py new file mode 100644 index 000000000..76a15bd0d --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/PngImagePlugin.py @@ -0,0 +1,1563 @@ +# +# The Python Imaging Library. +# $Id$ +# +# PNG support code +# +# See "PNG (Portable Network Graphics) Specification, version 1.0; +# W3C Recommendation", 1996-10-01, Thomas Boutell (ed.). +# +# history: +# 1996-05-06 fl Created (couldn't resist it) +# 1996-12-14 fl Upgraded, added read and verify support (0.2) +# 1996-12-15 fl Separate PNG stream parser +# 1996-12-29 fl Added write support, added getchunks +# 1996-12-30 fl Eliminated circular references in decoder (0.3) +# 1998-07-12 fl Read/write 16-bit images as mode I (0.4) +# 2001-02-08 fl Added transparency support (from Zircon) (0.5) +# 2001-04-16 fl Don't close data source in "open" method (0.6) +# 2004-02-24 fl Don't even pretend to support interlaced files (0.7) +# 2004-08-31 fl Do basic sanity check on chunk identifiers (0.8) +# 2004-09-20 fl Added PngInfo chunk container +# 2004-12-18 fl Added DPI read support (based on code by Niki Spahiev) +# 2008-08-13 fl Added tRNS support for RGB images +# 2009-03-06 fl Support for preserving ICC profiles (by Florian Hoech) +# 2009-03-08 fl Added zTXT support (from Lowell Alleman) +# 2009-03-29 fl Read interlaced PNG files (from Conrado Porto Lopes Gouvua) +# +# Copyright (c) 1997-2009 by Secret Labs AB +# Copyright (c) 1996 by Fredrik Lundh +# +# See the README file for information on usage and redistribution. +# +from __future__ import annotations + +import itertools +import logging +import re +import struct +import warnings +import zlib +from enum import IntEnum +from fractions import Fraction +from typing import IO, NamedTuple, cast + +from . import Image, ImageChops, ImageFile, ImagePalette, ImageSequence +from ._binary import i16be as i16 +from ._binary import i32be as i32 +from ._binary import o8 +from ._binary import o16be as o16 +from ._binary import o32be as o32 +from ._deprecate import deprecate +from ._util import DeferredError + +TYPE_CHECKING = False +if TYPE_CHECKING: + from collections.abc import Callable + from typing import Any, NoReturn + + from . import _imaging + +logger = logging.getLogger(__name__) + +is_cid = re.compile(rb"\w\w\w\w").match + + +_MAGIC = b"\211PNG\r\n\032\n" + + +_MODES = { + # supported bits/color combinations, and corresponding modes/rawmodes + # Grayscale + (1, 0): ("1", "1"), + (2, 0): ("L", "L;2"), + (4, 0): ("L", "L;4"), + (8, 0): ("L", "L"), + (16, 0): ("I;16", "I;16B"), + # Truecolour + (8, 2): ("RGB", "RGB"), + (16, 2): ("RGB", "RGB;16B"), + # Indexed-colour + (1, 3): ("P", "P;1"), + (2, 3): ("P", "P;2"), + (4, 3): ("P", "P;4"), + (8, 3): ("P", "P"), + # Grayscale with alpha + (8, 4): ("LA", "LA"), + (16, 4): ("RGBA", "LA;16B"), # LA;16B->LA not yet available + # Truecolour with alpha + (8, 6): ("RGBA", "RGBA"), + (16, 6): ("RGBA", "RGBA;16B"), +} + + +_simple_palette = re.compile(b"^\xff*\x00\xff*$") + +MAX_TEXT_CHUNK = ImageFile.SAFEBLOCK +""" +Maximum decompressed size for a iTXt or zTXt chunk. +Eliminates decompression bombs where compressed chunks can expand 1000x. +See :ref:`Text in PNG File Format`. +""" +MAX_TEXT_MEMORY = 64 * MAX_TEXT_CHUNK +""" +Set the maximum total text chunk size. +See :ref:`Text in PNG File Format`. +""" + + +# APNG frame disposal modes +class Disposal(IntEnum): + OP_NONE = 0 + """ + No disposal is done on this frame before rendering the next frame. + See :ref:`Saving APNG sequences`. + """ + OP_BACKGROUND = 1 + """ + This frame’s modified region is cleared to fully transparent black before rendering + the next frame. + See :ref:`Saving APNG sequences`. + """ + OP_PREVIOUS = 2 + """ + This frame’s modified region is reverted to the previous frame’s contents before + rendering the next frame. + See :ref:`Saving APNG sequences`. + """ + + +# APNG frame blend modes +class Blend(IntEnum): + OP_SOURCE = 0 + """ + All color components of this frame, including alpha, overwrite the previous output + image contents. + See :ref:`Saving APNG sequences`. + """ + OP_OVER = 1 + """ + This frame should be alpha composited with the previous output image contents. + See :ref:`Saving APNG sequences`. + """ + + +def _safe_zlib_decompress(s: bytes) -> bytes: + dobj = zlib.decompressobj() + plaintext = dobj.decompress(s, MAX_TEXT_CHUNK) + if dobj.unconsumed_tail: + msg = "Decompressed data too large for PngImagePlugin.MAX_TEXT_CHUNK" + raise ValueError(msg) + return plaintext + + +def _crc32(data: bytes, seed: int = 0) -> int: + return zlib.crc32(data, seed) & 0xFFFFFFFF + + +# -------------------------------------------------------------------- +# Support classes. Suitable for PNG and related formats like MNG etc. + + +class ChunkStream: + def __init__(self, fp: IO[bytes]) -> None: + self.fp: IO[bytes] | None = fp + self.queue: list[tuple[bytes, int, int]] | None = [] + + def read(self) -> tuple[bytes, int, int]: + """Fetch a new chunk. Returns header information.""" + cid = None + + assert self.fp is not None + if self.queue: + cid, pos, length = self.queue.pop() + self.fp.seek(pos) + else: + s = self.fp.read(8) + cid = s[4:] + pos = self.fp.tell() + length = i32(s) + + if not is_cid(cid): + if not ImageFile.LOAD_TRUNCATED_IMAGES: + msg = f"broken PNG file (chunk {repr(cid)})" + raise SyntaxError(msg) + + return cid, pos, length + + def __enter__(self) -> ChunkStream: + return self + + def __exit__(self, *args: object) -> None: + self.close() + + def close(self) -> None: + self.queue = self.fp = None + + def push(self, cid: bytes, pos: int, length: int) -> None: + assert self.queue is not None + self.queue.append((cid, pos, length)) + + def call(self, cid: bytes, pos: int, length: int) -> bytes: + """Call the appropriate chunk handler""" + + logger.debug("STREAM %r %s %s", cid, pos, length) + return getattr(self, f"chunk_{cid.decode('ascii')}")(pos, length) + + def crc(self, cid: bytes, data: bytes) -> None: + """Read and verify checksum""" + + # Skip CRC checks for ancillary chunks if allowed to load truncated + # images + # 5th byte of first char is 1 [specs, section 5.4] + if ImageFile.LOAD_TRUNCATED_IMAGES and (cid[0] >> 5 & 1): + self.crc_skip(cid, data) + return + + assert self.fp is not None + try: + crc1 = _crc32(data, _crc32(cid)) + crc2 = i32(self.fp.read(4)) + if crc1 != crc2: + msg = f"broken PNG file (bad header checksum in {repr(cid)})" + raise SyntaxError(msg) + except struct.error as e: + msg = f"broken PNG file (incomplete checksum in {repr(cid)})" + raise SyntaxError(msg) from e + + def crc_skip(self, cid: bytes, data: bytes) -> None: + """Read checksum""" + + assert self.fp is not None + self.fp.read(4) + + def verify(self, endchunk: bytes = b"IEND") -> list[bytes]: + # Simple approach; just calculate checksum for all remaining + # blocks. Must be called directly after open. + + cids = [] + + assert self.fp is not None + while True: + try: + cid, pos, length = self.read() + except struct.error as e: + msg = "truncated PNG file" + raise OSError(msg) from e + + if cid == endchunk: + break + self.crc(cid, ImageFile._safe_read(self.fp, length)) + cids.append(cid) + + return cids + + +class iTXt(str): + """ + Subclass of string to allow iTXt chunks to look like strings while + keeping their extra information + + """ + + lang: str | bytes | None + tkey: str | bytes | None + + @staticmethod + def __new__( + cls, text: str, lang: str | None = None, tkey: str | None = None + ) -> iTXt: + """ + :param cls: the class to use when creating the instance + :param text: value for this key + :param lang: language code + :param tkey: UTF-8 version of the key name + """ + + self = str.__new__(cls, text) + self.lang = lang + self.tkey = tkey + return self + + +class PngInfo: + """ + PNG chunk container (for use with save(pnginfo=)) + + """ + + def __init__(self) -> None: + self.chunks: list[tuple[bytes, bytes, bool]] = [] + + def add(self, cid: bytes, data: bytes, after_idat: bool = False) -> None: + """Appends an arbitrary chunk. Use with caution. + + :param cid: a byte string, 4 bytes long. + :param data: a byte string of the encoded data + :param after_idat: for use with private chunks. Whether the chunk + should be written after IDAT + + """ + + self.chunks.append((cid, data, after_idat)) + + def add_itxt( + self, + key: str | bytes, + value: str | bytes, + lang: str | bytes = "", + tkey: str | bytes = "", + zip: bool = False, + ) -> None: + """Appends an iTXt chunk. + + :param key: latin-1 encodable text key name + :param value: value for this key + :param lang: language code + :param tkey: UTF-8 version of the key name + :param zip: compression flag + + """ + + if not isinstance(key, bytes): + key = key.encode("latin-1", "strict") + if not isinstance(value, bytes): + value = value.encode("utf-8", "strict") + if not isinstance(lang, bytes): + lang = lang.encode("utf-8", "strict") + if not isinstance(tkey, bytes): + tkey = tkey.encode("utf-8", "strict") + + if zip: + self.add( + b"iTXt", + key + b"\0\x01\0" + lang + b"\0" + tkey + b"\0" + zlib.compress(value), + ) + else: + self.add(b"iTXt", key + b"\0\0\0" + lang + b"\0" + tkey + b"\0" + value) + + def add_text( + self, key: str | bytes, value: str | bytes | iTXt, zip: bool = False + ) -> None: + """Appends a text chunk. + + :param key: latin-1 encodable text key name + :param value: value for this key, text or an + :py:class:`PIL.PngImagePlugin.iTXt` instance + :param zip: compression flag + + """ + if isinstance(value, iTXt): + return self.add_itxt( + key, + value, + value.lang if value.lang is not None else b"", + value.tkey if value.tkey is not None else b"", + zip=zip, + ) + + # The tEXt chunk stores latin-1 text + if not isinstance(value, bytes): + try: + value = value.encode("latin-1", "strict") + except UnicodeError: + return self.add_itxt(key, value, zip=zip) + + if not isinstance(key, bytes): + key = key.encode("latin-1", "strict") + + if zip: + self.add(b"zTXt", key + b"\0\0" + zlib.compress(value)) + else: + self.add(b"tEXt", key + b"\0" + value) + + +# -------------------------------------------------------------------- +# PNG image stream (IHDR/IEND) + + +class _RewindState(NamedTuple): + info: dict[str | tuple[int, int], Any] + tile: list[ImageFile._Tile] + seq_num: int | None + + +class PngStream(ChunkStream): + def __init__(self, fp: IO[bytes]) -> None: + super().__init__(fp) + + # local copies of Image attributes + self.im_info: dict[str | tuple[int, int], Any] = {} + self.im_text: dict[str, str | iTXt] = {} + self.im_size = (0, 0) + self.im_mode = "" + self.im_tile: list[ImageFile._Tile] = [] + self.im_palette: tuple[str, bytes] | None = None + self.im_custom_mimetype: str | None = None + self.im_n_frames: int | None = None + self._seq_num: int | None = None + self.rewind_state = _RewindState({}, [], None) + + self.text_memory = 0 + + def check_text_memory(self, chunklen: int) -> None: + self.text_memory += chunklen + if self.text_memory > MAX_TEXT_MEMORY: + msg = ( + "Too much memory used in text chunks: " + f"{self.text_memory}>MAX_TEXT_MEMORY" + ) + raise ValueError(msg) + + def save_rewind(self) -> None: + self.rewind_state = _RewindState( + self.im_info.copy(), + self.im_tile, + self._seq_num, + ) + + def rewind(self) -> None: + self.im_info = self.rewind_state.info.copy() + self.im_tile = self.rewind_state.tile + self._seq_num = self.rewind_state.seq_num + + def chunk_iCCP(self, pos: int, length: int) -> bytes: + # ICC profile + assert self.fp is not None + s = ImageFile._safe_read(self.fp, length) + # according to PNG spec, the iCCP chunk contains: + # Profile name 1-79 bytes (character string) + # Null separator 1 byte (null character) + # Compression method 1 byte (0) + # Compressed profile n bytes (zlib with deflate compression) + i = s.find(b"\0") + logger.debug("iCCP profile name %r", s[:i]) + comp_method = s[i + 1] + logger.debug("Compression method %s", comp_method) + if comp_method != 0: + msg = f"Unknown compression method {comp_method} in iCCP chunk" + raise SyntaxError(msg) + try: + icc_profile = _safe_zlib_decompress(s[i + 2 :]) + except ValueError: + if ImageFile.LOAD_TRUNCATED_IMAGES: + icc_profile = None + else: + raise + except zlib.error: + icc_profile = None # FIXME + self.im_info["icc_profile"] = icc_profile + return s + + def chunk_IHDR(self, pos: int, length: int) -> bytes: + # image header + assert self.fp is not None + s = ImageFile._safe_read(self.fp, length) + if length < 13: + if ImageFile.LOAD_TRUNCATED_IMAGES: + return s + msg = "Truncated IHDR chunk" + raise ValueError(msg) + self.im_size = i32(s, 0), i32(s, 4) + try: + self.im_mode, self.im_rawmode = _MODES[(s[8], s[9])] + except Exception: + pass + if s[12]: + self.im_info["interlace"] = 1 + if s[11]: + msg = "unknown filter category" + raise SyntaxError(msg) + return s + + def chunk_IDAT(self, pos: int, length: int) -> NoReturn: + # image data + if "bbox" in self.im_info: + tile = [ImageFile._Tile("zip", self.im_info["bbox"], pos, self.im_rawmode)] + else: + if self.im_n_frames is not None: + self.im_info["default_image"] = True + tile = [ImageFile._Tile("zip", (0, 0) + self.im_size, pos, self.im_rawmode)] + self.im_tile = tile + self.im_idat = length + msg = "image data found" + raise EOFError(msg) + + def chunk_IEND(self, pos: int, length: int) -> NoReturn: + msg = "end of PNG image" + raise EOFError(msg) + + def chunk_PLTE(self, pos: int, length: int) -> bytes: + # palette + assert self.fp is not None + s = ImageFile._safe_read(self.fp, length) + if self.im_mode == "P": + self.im_palette = "RGB", s + return s + + def chunk_tRNS(self, pos: int, length: int) -> bytes: + # transparency + assert self.fp is not None + s = ImageFile._safe_read(self.fp, length) + if self.im_mode == "P": + if _simple_palette.match(s): + # tRNS contains only one full-transparent entry, + # other entries are full opaque + i = s.find(b"\0") + if i >= 0: + self.im_info["transparency"] = i + else: + # otherwise, we have a byte string with one alpha value + # for each palette entry + self.im_info["transparency"] = s + elif self.im_mode == "1": + self.im_info["transparency"] = 255 if i16(s) else 0 + elif self.im_mode in ("L", "I;16"): + self.im_info["transparency"] = i16(s) + elif self.im_mode == "RGB": + self.im_info["transparency"] = i16(s), i16(s, 2), i16(s, 4) + return s + + def chunk_gAMA(self, pos: int, length: int) -> bytes: + # gamma setting + assert self.fp is not None + s = ImageFile._safe_read(self.fp, length) + self.im_info["gamma"] = i32(s) / 100000.0 + return s + + def chunk_cHRM(self, pos: int, length: int) -> bytes: + # chromaticity, 8 unsigned ints, actual value is scaled by 100,000 + # WP x,y, Red x,y, Green x,y Blue x,y + + assert self.fp is not None + s = ImageFile._safe_read(self.fp, length) + raw_vals = struct.unpack(f">{len(s) // 4}I", s) + self.im_info["chromaticity"] = tuple(elt / 100000.0 for elt in raw_vals) + return s + + def chunk_sRGB(self, pos: int, length: int) -> bytes: + # srgb rendering intent, 1 byte + # 0 perceptual + # 1 relative colorimetric + # 2 saturation + # 3 absolute colorimetric + + assert self.fp is not None + s = ImageFile._safe_read(self.fp, length) + if length < 1: + if ImageFile.LOAD_TRUNCATED_IMAGES: + return s + msg = "Truncated sRGB chunk" + raise ValueError(msg) + self.im_info["srgb"] = s[0] + return s + + def chunk_pHYs(self, pos: int, length: int) -> bytes: + # pixels per unit + assert self.fp is not None + s = ImageFile._safe_read(self.fp, length) + if length < 9: + if ImageFile.LOAD_TRUNCATED_IMAGES: + return s + msg = "Truncated pHYs chunk" + raise ValueError(msg) + px, py = i32(s, 0), i32(s, 4) + unit = s[8] + if unit == 1: # meter + dpi = px * 0.0254, py * 0.0254 + self.im_info["dpi"] = dpi + elif unit == 0: + self.im_info["aspect"] = px, py + return s + + def chunk_tEXt(self, pos: int, length: int) -> bytes: + # text + assert self.fp is not None + s = ImageFile._safe_read(self.fp, length) + try: + k, v = s.split(b"\0", 1) + except ValueError: + # fallback for broken tEXt tags + k = s + v = b"" + if k: + k_str = k.decode("latin-1", "strict") + v_str = v.decode("latin-1", "replace") + + self.im_info[k_str] = v if k == b"exif" else v_str + self.im_text[k_str] = v_str + self.check_text_memory(len(v_str)) + + return s + + def chunk_zTXt(self, pos: int, length: int) -> bytes: + # compressed text + assert self.fp is not None + s = ImageFile._safe_read(self.fp, length) + try: + k, v = s.split(b"\0", 1) + except ValueError: + k = s + v = b"" + if v: + comp_method = v[0] + else: + comp_method = 0 + if comp_method != 0: + msg = f"Unknown compression method {comp_method} in zTXt chunk" + raise SyntaxError(msg) + try: + v = _safe_zlib_decompress(v[1:]) + except ValueError: + if ImageFile.LOAD_TRUNCATED_IMAGES: + v = b"" + else: + raise + except zlib.error: + v = b"" + + if k: + k_str = k.decode("latin-1", "strict") + v_str = v.decode("latin-1", "replace") + + self.im_info[k_str] = self.im_text[k_str] = v_str + self.check_text_memory(len(v_str)) + + return s + + def chunk_iTXt(self, pos: int, length: int) -> bytes: + # international text + assert self.fp is not None + r = s = ImageFile._safe_read(self.fp, length) + try: + k, r = r.split(b"\0", 1) + except ValueError: + return s + if len(r) < 2: + return s + cf, cm, r = r[0], r[1], r[2:] + try: + lang, tk, v = r.split(b"\0", 2) + except ValueError: + return s + if cf != 0: + if cm == 0: + try: + v = _safe_zlib_decompress(v) + except ValueError: + if ImageFile.LOAD_TRUNCATED_IMAGES: + return s + else: + raise + except zlib.error: + return s + else: + return s + if k == b"XML:com.adobe.xmp": + self.im_info["xmp"] = v + try: + k_str = k.decode("latin-1", "strict") + lang_str = lang.decode("utf-8", "strict") + tk_str = tk.decode("utf-8", "strict") + v_str = v.decode("utf-8", "strict") + except UnicodeError: + return s + + self.im_info[k_str] = self.im_text[k_str] = iTXt(v_str, lang_str, tk_str) + self.check_text_memory(len(v_str)) + + return s + + def chunk_eXIf(self, pos: int, length: int) -> bytes: + assert self.fp is not None + s = ImageFile._safe_read(self.fp, length) + self.im_info["exif"] = b"Exif\x00\x00" + s + return s + + # APNG chunks + def chunk_acTL(self, pos: int, length: int) -> bytes: + assert self.fp is not None + s = ImageFile._safe_read(self.fp, length) + if length < 8: + if ImageFile.LOAD_TRUNCATED_IMAGES: + return s + msg = "APNG contains truncated acTL chunk" + raise ValueError(msg) + if self.im_n_frames is not None: + self.im_n_frames = None + warnings.warn("Invalid APNG, will use default PNG image if possible") + return s + n_frames = i32(s) + if n_frames == 0 or n_frames > 0x80000000: + warnings.warn("Invalid APNG, will use default PNG image if possible") + return s + self.im_n_frames = n_frames + self.im_info["loop"] = i32(s, 4) + self.im_custom_mimetype = "image/apng" + return s + + def chunk_fcTL(self, pos: int, length: int) -> bytes: + assert self.fp is not None + s = ImageFile._safe_read(self.fp, length) + if length < 26: + if ImageFile.LOAD_TRUNCATED_IMAGES: + return s + msg = "APNG contains truncated fcTL chunk" + raise ValueError(msg) + seq = i32(s) + if (self._seq_num is None and seq != 0) or ( + self._seq_num is not None and self._seq_num != seq - 1 + ): + msg = "APNG contains frame sequence errors" + raise SyntaxError(msg) + self._seq_num = seq + width, height = i32(s, 4), i32(s, 8) + px, py = i32(s, 12), i32(s, 16) + im_w, im_h = self.im_size + if px + width > im_w or py + height > im_h: + msg = "APNG contains invalid frames" + raise SyntaxError(msg) + self.im_info["bbox"] = (px, py, px + width, py + height) + delay_num, delay_den = i16(s, 20), i16(s, 22) + if delay_den == 0: + delay_den = 100 + self.im_info["duration"] = float(delay_num) / float(delay_den) * 1000 + self.im_info["disposal"] = s[24] + self.im_info["blend"] = s[25] + return s + + def chunk_fdAT(self, pos: int, length: int) -> bytes: + assert self.fp is not None + if length < 4: + if ImageFile.LOAD_TRUNCATED_IMAGES: + s = ImageFile._safe_read(self.fp, length) + return s + msg = "APNG contains truncated fDAT chunk" + raise ValueError(msg) + s = ImageFile._safe_read(self.fp, 4) + seq = i32(s) + if self._seq_num != seq - 1: + msg = "APNG contains frame sequence errors" + raise SyntaxError(msg) + self._seq_num = seq + return self.chunk_IDAT(pos + 4, length - 4) + + +# -------------------------------------------------------------------- +# PNG reader + + +def _accept(prefix: bytes) -> bool: + return prefix.startswith(_MAGIC) + + +## +# Image plugin for PNG images. + + +class PngImageFile(ImageFile.ImageFile): + format = "PNG" + format_description = "Portable network graphics" + + def _open(self) -> None: + assert self.fp is not None + if not _accept(self.fp.read(8)): + msg = "not a PNG file" + raise SyntaxError(msg) + self._fp = self.fp + self.__frame = 0 + + # + # Parse headers up to the first IDAT or fDAT chunk + + self.private_chunks: list[tuple[bytes, bytes] | tuple[bytes, bytes, bool]] = [] + self.png: PngStream | None = PngStream(self.fp) + + while True: + # + # get next chunk + + cid, pos, length = self.png.read() + + try: + s = self.png.call(cid, pos, length) + except EOFError: + break + except AttributeError: + logger.debug("%r %s %s (unknown)", cid, pos, length) + s = ImageFile._safe_read(self.fp, length) + if cid[1:2].islower(): + self.private_chunks.append((cid, s)) + + self.png.crc(cid, s) + + # + # Copy relevant attributes from the PngStream. An alternative + # would be to let the PngStream class modify these attributes + # directly, but that introduces circular references which are + # difficult to break if things go wrong in the decoder... + # (believe me, I've tried ;-) + + self._mode = self.png.im_mode + self._size = self.png.im_size + self.info = self.png.im_info + self._text: dict[str, str | iTXt] | None = None + self.tile = self.png.im_tile + self.custom_mimetype = self.png.im_custom_mimetype + self.n_frames = self.png.im_n_frames or 1 + self.default_image = self.info.get("default_image", False) + + if self.png.im_palette: + rawmode, data = self.png.im_palette + self.palette = ImagePalette.raw(rawmode, data) + + if cid == b"fdAT": + self.__prepare_idat = length - 4 + else: + self.__prepare_idat = length # used by load_prepare() + + if self.png.im_n_frames is not None: + self._close_exclusive_fp_after_loading = False + self.png.save_rewind() + self.__rewind_idat = self.__prepare_idat + self.__rewind = self._fp.tell() + if self.default_image: + # IDAT chunk contains default image and not first animation frame + self.n_frames += 1 + self._seek(0) + self.is_animated = self.n_frames > 1 + + @property + def text(self) -> dict[str, str | iTXt]: + # experimental + if self._text is None: + # iTxt, tEXt and zTXt chunks may appear at the end of the file + # So load the file to ensure that they are read + if self.is_animated: + frame = self.__frame + # for APNG, seek to the final frame before loading + self.seek(self.n_frames - 1) + self.load() + if self.is_animated: + self.seek(frame) + assert self._text is not None + return self._text + + def verify(self) -> None: + """Verify PNG file""" + + if self.fp is None: + msg = "verify must be called directly after open" + raise RuntimeError(msg) + + # back up to beginning of IDAT block + self.fp.seek(self.tile[0][2] - 8) + + assert self.png is not None + self.png.verify() + self.png.close() + + super().verify() + + def seek(self, frame: int) -> None: + if not self._seek_check(frame): + return + if frame < self.__frame: + self._seek(0, True) + + last_frame = self.__frame + try: + for f in range(self.__frame + 1, frame + 1): + self._seek(f) + except EOFError as e: + self.seek(last_frame) + msg = "no more images in APNG file" + raise EOFError(msg) from e + + def _seek(self, frame: int, rewind: bool = False) -> None: + assert self.png is not None + if isinstance(self._fp, DeferredError): + raise self._fp.ex + + self.dispose: _imaging.ImagingCore | None + dispose_extent = None + if frame == 0: + if rewind: + self._fp.seek(self.__rewind) + self.png.rewind() + self.__prepare_idat = self.__rewind_idat + self._im = None + self.info = self.png.im_info + self.tile = self.png.im_tile + self.fp = self._fp + self._prev_im = None + self.dispose = None + self.default_image = self.info.get("default_image", False) + self.dispose_op = self.info.get("disposal") + self.blend_op = self.info.get("blend") + dispose_extent = self.info.get("bbox") + self.__frame = 0 + else: + if frame != self.__frame + 1: + msg = f"cannot seek to frame {frame}" + raise ValueError(msg) + + # ensure previous frame was loaded + self.load() + + if self.dispose: + self.im.paste(self.dispose, self.dispose_extent) + self._prev_im = self.im.copy() + + self.fp = self._fp + + # advance to the next frame + if self.__prepare_idat: + ImageFile._safe_read(self.fp, self.__prepare_idat) + self.__prepare_idat = 0 + frame_start = False + while True: + self.fp.read(4) # CRC + + try: + cid, pos, length = self.png.read() + except (struct.error, SyntaxError): + break + + if cid == b"IEND": + msg = "No more images in APNG file" + raise EOFError(msg) + if cid == b"fcTL": + if frame_start: + # there must be at least one fdAT chunk between fcTL chunks + msg = "APNG missing frame data" + raise SyntaxError(msg) + frame_start = True + + try: + self.png.call(cid, pos, length) + except UnicodeDecodeError: + break + except EOFError: + if cid == b"fdAT": + length -= 4 + if frame_start: + self.__prepare_idat = length + break + ImageFile._safe_read(self.fp, length) + except AttributeError: + logger.debug("%r %s %s (unknown)", cid, pos, length) + ImageFile._safe_read(self.fp, length) + + self.__frame = frame + self.tile = self.png.im_tile + self.dispose_op = self.info.get("disposal") + self.blend_op = self.info.get("blend") + dispose_extent = self.info.get("bbox") + + if not self.tile: + msg = "image not found in APNG frame" + raise EOFError(msg) + if dispose_extent: + self.dispose_extent: tuple[float, float, float, float] = dispose_extent + + # setup frame disposal (actual disposal done when needed in the next _seek()) + if self._prev_im is None and self.dispose_op == Disposal.OP_PREVIOUS: + self.dispose_op = Disposal.OP_BACKGROUND + + self.dispose = None + if self.dispose_op == Disposal.OP_PREVIOUS: + if self._prev_im: + self.dispose = self._prev_im.copy() + self.dispose = self._crop(self.dispose, self.dispose_extent) + elif self.dispose_op == Disposal.OP_BACKGROUND: + self.dispose = Image.core.fill(self.mode, self.size) + self.dispose = self._crop(self.dispose, self.dispose_extent) + + def tell(self) -> int: + return self.__frame + + def load_prepare(self) -> None: + """internal: prepare to read PNG file""" + + if self.info.get("interlace"): + self.decoderconfig = self.decoderconfig + (1,) + + self.__idat = self.__prepare_idat # used by load_read() + ImageFile.ImageFile.load_prepare(self) + + def load_read(self, read_bytes: int) -> bytes: + """internal: read more image data""" + + assert self.png is not None + assert self.fp is not None + while self.__idat == 0: + # end of chunk, skip forward to next one + + self.fp.read(4) # CRC + + cid, pos, length = self.png.read() + + if cid not in [b"IDAT", b"DDAT", b"fdAT"]: + self.png.push(cid, pos, length) + return b"" + + if cid == b"fdAT": + try: + self.png.call(cid, pos, length) + except EOFError: + pass + self.__idat = length - 4 # sequence_num has already been read + else: + self.__idat = length # empty chunks are allowed + + # read more data from this chunk + if read_bytes <= 0: + read_bytes = self.__idat + else: + read_bytes = min(read_bytes, self.__idat) + + self.__idat = self.__idat - read_bytes + + return self.fp.read(read_bytes) + + def load_end(self) -> None: + """internal: finished reading image data""" + assert self.png is not None + assert self.fp is not None + if self.__idat != 0: + self.fp.read(self.__idat) + while True: + self.fp.read(4) # CRC + + try: + cid, pos, length = self.png.read() + except (struct.error, SyntaxError): + break + + if cid == b"IEND": + break + elif cid == b"fcTL" and self.is_animated: + # start of the next frame, stop reading + self.__prepare_idat = 0 + self.png.push(cid, pos, length) + break + + try: + self.png.call(cid, pos, length) + except UnicodeDecodeError: + break + except EOFError: + if cid == b"fdAT": + length -= 4 + try: + ImageFile._safe_read(self.fp, length) + except OSError as e: + if ImageFile.LOAD_TRUNCATED_IMAGES: + break + else: + raise e + except AttributeError: + logger.debug("%r %s %s (unknown)", cid, pos, length) + s = ImageFile._safe_read(self.fp, length) + if cid[1:2].islower(): + self.private_chunks.append((cid, s, True)) + self._text = self.png.im_text + if not self.is_animated: + self.png.close() + self.png = None + else: + if self._prev_im and self.blend_op == Blend.OP_OVER: + updated = self._crop(self.im, self.dispose_extent) + if self.im.mode == "RGB" and "transparency" in self.info: + mask = updated.convert_transparent( + "RGBA", self.info["transparency"] + ) + else: + if self.im.mode == "P" and "transparency" in self.info: + t = self.info["transparency"] + if isinstance(t, bytes): + updated.putpalettealphas(t) + elif isinstance(t, int): + updated.putpalettealpha(t) + mask = updated.convert("RGBA") + self._prev_im.paste(updated, self.dispose_extent, mask) + self.im = self._prev_im + + def _getexif(self) -> dict[int, Any] | None: + if "exif" not in self.info: + self.load() + if "exif" not in self.info and "Raw profile type exif" not in self.info: + return None + return self.getexif()._get_merged_dict() + + def getexif(self) -> Image.Exif: + if "exif" not in self.info: + self.load() + + return super().getexif() + + +# -------------------------------------------------------------------- +# PNG writer + +_OUTMODES = { + # supported PIL modes, and corresponding rawmode, bit depth and color type + "1": ("1", b"\x01", b"\x00"), + "L;1": ("L;1", b"\x01", b"\x00"), + "L;2": ("L;2", b"\x02", b"\x00"), + "L;4": ("L;4", b"\x04", b"\x00"), + "L": ("L", b"\x08", b"\x00"), + "LA": ("LA", b"\x08", b"\x04"), + "I": ("I;16B", b"\x10", b"\x00"), + "I;16": ("I;16B", b"\x10", b"\x00"), + "I;16B": ("I;16B", b"\x10", b"\x00"), + "P;1": ("P;1", b"\x01", b"\x03"), + "P;2": ("P;2", b"\x02", b"\x03"), + "P;4": ("P;4", b"\x04", b"\x03"), + "P": ("P", b"\x08", b"\x03"), + "RGB": ("RGB", b"\x08", b"\x02"), + "RGBA": ("RGBA", b"\x08", b"\x06"), +} + + +def putchunk(fp: IO[bytes], cid: bytes, *data: bytes) -> None: + """Write a PNG chunk (including CRC field)""" + + byte_data = b"".join(data) + + fp.write(o32(len(byte_data)) + cid) + fp.write(byte_data) + crc = _crc32(byte_data, _crc32(cid)) + fp.write(o32(crc)) + + +class _idat: + # wrap output from the encoder in IDAT chunks + + def __init__(self, fp: IO[bytes], chunk: Callable[..., None]) -> None: + self.fp = fp + self.chunk = chunk + + def write(self, data: bytes) -> None: + self.chunk(self.fp, b"IDAT", data) + + +class _fdat: + # wrap encoder output in fdAT chunks + + def __init__(self, fp: IO[bytes], chunk: Callable[..., None], seq_num: int) -> None: + self.fp = fp + self.chunk = chunk + self.seq_num = seq_num + + def write(self, data: bytes) -> None: + self.chunk(self.fp, b"fdAT", o32(self.seq_num), data) + self.seq_num += 1 + + +def _apply_encoderinfo(im: Image.Image, encoderinfo: dict[str, Any]) -> None: + im.encoderconfig = ( + encoderinfo.get("optimize", False), + encoderinfo.get("compress_level", -1), + encoderinfo.get("compress_type", -1), + encoderinfo.get("dictionary", b""), + ) + + +class _Frame(NamedTuple): + im: Image.Image + bbox: tuple[int, int, int, int] | None + encoderinfo: dict[str, Any] + + +def _write_multiple_frames( + im: Image.Image, + fp: IO[bytes], + chunk: Callable[..., None], + mode: str, + rawmode: str, + default_image: Image.Image | None, + append_images: list[Image.Image], +) -> Image.Image | None: + duration = im.encoderinfo.get("duration") + loop = im.encoderinfo.get("loop", im.info.get("loop", 0)) + disposal = im.encoderinfo.get("disposal", im.info.get("disposal", Disposal.OP_NONE)) + blend = im.encoderinfo.get("blend", im.info.get("blend", Blend.OP_SOURCE)) + + if default_image: + chain = itertools.chain(append_images) + else: + chain = itertools.chain([im], append_images) + + im_frames: list[_Frame] = [] + frame_count = 0 + for im_seq in chain: + for im_frame in ImageSequence.Iterator(im_seq): + if im_frame.mode == mode: + im_frame = im_frame.copy() + else: + im_frame = im_frame.convert(mode) + encoderinfo = im.encoderinfo.copy() + if isinstance(duration, (list, tuple)): + encoderinfo["duration"] = duration[frame_count] + elif duration is None and "duration" in im_frame.info: + encoderinfo["duration"] = im_frame.info["duration"] + if isinstance(disposal, (list, tuple)): + encoderinfo["disposal"] = disposal[frame_count] + if isinstance(blend, (list, tuple)): + encoderinfo["blend"] = blend[frame_count] + frame_count += 1 + + if im_frames: + previous = im_frames[-1] + prev_disposal = previous.encoderinfo.get("disposal") + prev_blend = previous.encoderinfo.get("blend") + if prev_disposal == Disposal.OP_PREVIOUS and len(im_frames) < 2: + prev_disposal = Disposal.OP_BACKGROUND + + if prev_disposal == Disposal.OP_BACKGROUND: + base_im = previous.im.copy() + dispose = Image.core.fill("RGBA", im.size, (0, 0, 0, 0)) + bbox = previous.bbox + if bbox: + dispose = dispose.crop(bbox) + else: + bbox = (0, 0) + im.size + base_im.paste(dispose, bbox) + elif prev_disposal == Disposal.OP_PREVIOUS: + base_im = im_frames[-2].im + else: + base_im = previous.im + delta = ImageChops.subtract_modulo( + im_frame.convert("RGBA"), base_im.convert("RGBA") + ) + bbox = delta.getbbox(alpha_only=False) + if ( + not bbox + and prev_disposal == encoderinfo.get("disposal") + and prev_blend == encoderinfo.get("blend") + and "duration" in encoderinfo + ): + previous.encoderinfo["duration"] += encoderinfo["duration"] + continue + else: + bbox = None + im_frames.append(_Frame(im_frame, bbox, encoderinfo)) + + if len(im_frames) == 1 and not default_image: + return im_frames[0].im + + # animation control + chunk( + fp, + b"acTL", + o32(len(im_frames)), # 0: num_frames + o32(loop), # 4: num_plays + ) + + # default image IDAT (if it exists) + if default_image: + default_im = im if im.mode == mode else im.convert(mode) + _apply_encoderinfo(default_im, im.encoderinfo) + ImageFile._save( + default_im, + cast(IO[bytes], _idat(fp, chunk)), + [ImageFile._Tile("zip", (0, 0) + im.size, 0, rawmode)], + ) + + seq_num = 0 + for frame, frame_data in enumerate(im_frames): + im_frame = frame_data.im + if not frame_data.bbox: + bbox = (0, 0) + im_frame.size + else: + bbox = frame_data.bbox + im_frame = im_frame.crop(bbox) + size = im_frame.size + encoderinfo = frame_data.encoderinfo + frame_duration = encoderinfo.get("duration", 0) + delay = Fraction(frame_duration / 1000).limit_denominator(65535) + if delay.numerator > 65535: + msg = "cannot write duration" + raise ValueError(msg) + frame_disposal = encoderinfo.get("disposal", disposal) + frame_blend = encoderinfo.get("blend", blend) + # frame control + chunk( + fp, + b"fcTL", + o32(seq_num), # sequence_number + o32(size[0]), # width + o32(size[1]), # height + o32(bbox[0]), # x_offset + o32(bbox[1]), # y_offset + o16(delay.numerator), # delay_numerator + o16(delay.denominator), # delay_denominator + o8(frame_disposal), # dispose_op + o8(frame_blend), # blend_op + ) + seq_num += 1 + # frame data + _apply_encoderinfo(im_frame, im.encoderinfo) + if frame == 0 and not default_image: + # first frame must be in IDAT chunks for backwards compatibility + ImageFile._save( + im_frame, + cast(IO[bytes], _idat(fp, chunk)), + [ImageFile._Tile("zip", (0, 0) + im_frame.size, 0, rawmode)], + ) + else: + fdat_chunks = _fdat(fp, chunk, seq_num) + ImageFile._save( + im_frame, + cast(IO[bytes], fdat_chunks), + [ImageFile._Tile("zip", (0, 0) + im_frame.size, 0, rawmode)], + ) + seq_num = fdat_chunks.seq_num + return None + + +def _save_all(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None: + _save(im, fp, filename, save_all=True) + + +def _save( + im: Image.Image, + fp: IO[bytes], + filename: str | bytes, + chunk: Callable[..., None] = putchunk, + save_all: bool = False, +) -> None: + # save an image to disk (called by the save method) + + if save_all: + default_image = im.encoderinfo.get( + "default_image", im.info.get("default_image") + ) + modes = set() + sizes = set() + append_images = im.encoderinfo.get("append_images", []) + for im_seq in itertools.chain([im], append_images): + for im_frame in ImageSequence.Iterator(im_seq): + modes.add(im_frame.mode) + sizes.add(im_frame.size) + for mode in ("RGBA", "RGB", "P"): + if mode in modes: + break + else: + mode = modes.pop() + size = tuple(max(frame_size[i] for frame_size in sizes) for i in range(2)) + else: + size = im.size + mode = im.mode + + outmode = mode + palette = [] + if im.palette: + palette = im.getpalette() or [] + if mode == "P": + # + # attempt to minimize storage requirements for palette images + if "bits" in im.encoderinfo: + # number of bits specified by user + colors = min(1 << im.encoderinfo["bits"], 256) + else: + # check palette contents + if im.palette: + colors = max(min(len(palette) // 3, 256), 1) + else: + colors = 256 + + if colors <= 16: + if colors <= 2: + bits = 1 + elif colors <= 4: + bits = 2 + else: + bits = 4 + outmode += f";{bits}" + + # get the corresponding PNG mode + try: + rawmode, bit_depth, color_type = _OUTMODES[outmode] + except KeyError as e: + msg = f"cannot write mode {mode} as PNG" + raise OSError(msg) from e + if outmode == "I": + deprecate("Saving I mode images as PNG", 13, stacklevel=4) + + # + # write minimal PNG file + + fp.write(_MAGIC) + + chunk( + fp, + b"IHDR", + o32(size[0]), # 0: size + o32(size[1]), + bit_depth, + color_type, + b"\0", # 10: compression + b"\0", # 11: filter category + b"\0", # 12: interlace flag + ) + + chunks = [b"cHRM", b"cICP", b"gAMA", b"sBIT", b"sRGB", b"tIME"] + + if icc := im.encoderinfo.get("icc_profile", im.info.get("icc_profile")): + # ICC profile + # according to PNG spec, the iCCP chunk contains: + # Profile name 1-79 bytes (character string) + # Null separator 1 byte (null character) + # Compression method 1 byte (0) + # Compressed profile n bytes (zlib with deflate compression) + name = b"ICC Profile" + data = name + b"\0\0" + zlib.compress(icc) + chunk(fp, b"iCCP", data) + + # You must either have sRGB or iCCP. + # Disallow sRGB chunks when an iCCP-chunk has been emitted. + chunks.remove(b"sRGB") + + if info := im.encoderinfo.get("pnginfo"): + chunks_multiple_allowed = [b"sPLT", b"iTXt", b"tEXt", b"zTXt"] + for info_chunk in info.chunks: + cid, data = info_chunk[:2] + if cid in chunks: + chunks.remove(cid) + chunk(fp, cid, data) + elif cid in chunks_multiple_allowed: + chunk(fp, cid, data) + elif cid[1:2].islower(): + # Private chunk + after_idat = len(info_chunk) == 3 and info_chunk[2] + if not after_idat: + chunk(fp, cid, data) + + if im.mode == "P": + palette_byte_number = colors * 3 + palette_bytes = bytes(palette[:palette_byte_number]) + while len(palette_bytes) < palette_byte_number: + palette_bytes += b"\0" + chunk(fp, b"PLTE", palette_bytes) + + transparency = im.encoderinfo.get("transparency", im.info.get("transparency", None)) + + if transparency or transparency == 0: + if im.mode == "P": + # limit to actual palette size + alpha_bytes = colors + if isinstance(transparency, bytes): + chunk(fp, b"tRNS", transparency[:alpha_bytes]) + else: + transparency = max(0, min(255, transparency)) + alpha = b"\xff" * transparency + b"\0" + chunk(fp, b"tRNS", alpha[:alpha_bytes]) + elif im.mode in ("1", "L", "I", "I;16"): + transparency = max(0, min(65535, transparency)) + chunk(fp, b"tRNS", o16(transparency)) + elif im.mode == "RGB": + red, green, blue = transparency + chunk(fp, b"tRNS", o16(red) + o16(green) + o16(blue)) + else: + if "transparency" in im.encoderinfo: + # don't bother with transparency if it's an RGBA + # and it's in the info dict. It's probably just stale. + msg = "cannot use transparency for this mode" + raise OSError(msg) + else: + if im.mode == "P" and im.im.getpalettemode() == "RGBA": + alpha = im.im.getpalette("RGBA", "A") + alpha_bytes = colors + chunk(fp, b"tRNS", alpha[:alpha_bytes]) + + if dpi := im.encoderinfo.get("dpi"): + chunk( + fp, + b"pHYs", + o32(int(dpi[0] / 0.0254 + 0.5)), + o32(int(dpi[1] / 0.0254 + 0.5)), + b"\x01", + ) + + if info: + chunks = [b"bKGD", b"hIST"] + for info_chunk in info.chunks: + cid, data = info_chunk[:2] + if cid in chunks: + chunks.remove(cid) + chunk(fp, cid, data) + + if exif := im.encoderinfo.get("exif"): + if isinstance(exif, Image.Exif): + exif = exif.tobytes(8) + if exif.startswith(b"Exif\x00\x00"): + exif = exif[6:] + chunk(fp, b"eXIf", exif) + + single_im: Image.Image | None = im + if save_all: + single_im = _write_multiple_frames( + im, fp, chunk, mode, rawmode, default_image, append_images + ) + if single_im: + _apply_encoderinfo(single_im, im.encoderinfo) + ImageFile._save( + single_im, + cast(IO[bytes], _idat(fp, chunk)), + [ImageFile._Tile("zip", (0, 0) + single_im.size, 0, rawmode)], + ) + + if info: + for info_chunk in info.chunks: + cid, data = info_chunk[:2] + if cid[1:2].islower(): + # Private chunk + after_idat = len(info_chunk) == 3 and info_chunk[2] + if after_idat: + chunk(fp, cid, data) + + chunk(fp, b"IEND", b"") + + if hasattr(fp, "flush"): + fp.flush() + + +# -------------------------------------------------------------------- +# PNG chunk converter + + +def getchunks(im: Image.Image, **params: Any) -> list[tuple[bytes, bytes, bytes]]: + """Return a list of PNG chunks representing this image.""" + from io import BytesIO + + chunks = [] + + def append(fp: IO[bytes], cid: bytes, *data: bytes) -> None: + byte_data = b"".join(data) + crc = o32(_crc32(byte_data, _crc32(cid))) + chunks.append((cid, byte_data, crc)) + + fp = BytesIO() + + try: + im.encoderinfo = params + _save(im, fp, "", append) + finally: + del im.encoderinfo + + return chunks + + +# -------------------------------------------------------------------- +# Registry + +Image.register_open(PngImageFile.format, PngImageFile, _accept) +Image.register_save(PngImageFile.format, _save) +Image.register_save_all(PngImageFile.format, _save_all) + +Image.register_extensions(PngImageFile.format, [".png", ".apng"]) + +Image.register_mime(PngImageFile.format, "image/png") diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/PpmImagePlugin.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/PpmImagePlugin.py new file mode 100644 index 000000000..307bc97ff --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/PpmImagePlugin.py @@ -0,0 +1,375 @@ +# +# The Python Imaging Library. +# $Id$ +# +# PPM support for PIL +# +# History: +# 96-03-24 fl Created +# 98-03-06 fl Write RGBA images (as RGB, that is) +# +# Copyright (c) Secret Labs AB 1997-98. +# Copyright (c) Fredrik Lundh 1996. +# +# See the README file for information on usage and redistribution. +# +from __future__ import annotations + +import math +from typing import IO + +from . import Image, ImageFile +from ._binary import i16be as i16 +from ._binary import o8 +from ._binary import o32le as o32 + +# +# -------------------------------------------------------------------- + +b_whitespace = b"\x20\x09\x0a\x0b\x0c\x0d" + +MODES = { + # standard + b"P1": "1", + b"P2": "L", + b"P3": "RGB", + b"P4": "1", + b"P5": "L", + b"P6": "RGB", + # extensions + b"P0CMYK": "CMYK", + b"Pf": "F", + # PIL extensions (for test purposes only) + b"PyP": "P", + b"PyRGBA": "RGBA", + b"PyCMYK": "CMYK", +} + + +def _accept(prefix: bytes) -> bool: + return len(prefix) >= 2 and prefix.startswith(b"P") and prefix[1] in b"0123456fy" + + +## +# Image plugin for PBM, PGM, and PPM images. + + +class PpmImageFile(ImageFile.ImageFile): + format = "PPM" + format_description = "Pbmplus image" + + def _read_magic(self) -> bytes: + assert self.fp is not None + + magic = b"" + # read until whitespace or longest available magic number + for _ in range(6): + c = self.fp.read(1) + if not c or c in b_whitespace: + break + magic += c + return magic + + def _read_token(self) -> bytes: + assert self.fp is not None + + token = b"" + while len(token) <= 10: # read until next whitespace or limit of 10 characters + c = self.fp.read(1) + if not c: + break + elif c in b_whitespace: # token ended + if not token: + # skip whitespace at start + continue + break + elif c == b"#": + # ignores rest of the line; stops at CR, LF or EOF + while self.fp.read(1) not in b"\r\n": + pass + continue + token += c + if not token: + # Token was not even 1 byte + msg = "Reached EOF while reading header" + raise ValueError(msg) + elif len(token) > 10: + msg_too_long = b"Token too long in file header: %s" % token + raise ValueError(msg_too_long) + return token + + def _open(self) -> None: + assert self.fp is not None + + magic_number = self._read_magic() + try: + mode = MODES[magic_number] + except KeyError: + msg = "not a PPM file" + raise SyntaxError(msg) + self._mode = mode + + if magic_number in (b"P1", b"P4"): + self.custom_mimetype = "image/x-portable-bitmap" + elif magic_number in (b"P2", b"P5"): + self.custom_mimetype = "image/x-portable-graymap" + elif magic_number in (b"P3", b"P6"): + self.custom_mimetype = "image/x-portable-pixmap" + + self._size = int(self._read_token()), int(self._read_token()) + + decoder_name = "raw" + if magic_number in (b"P1", b"P2", b"P3"): + decoder_name = "ppm_plain" + + args: str | tuple[str | int, ...] + if mode == "1": + args = "1;I" + elif mode == "F": + scale = float(self._read_token()) + if scale == 0.0 or not math.isfinite(scale): + msg = "scale must be finite and non-zero" + raise ValueError(msg) + self.info["scale"] = abs(scale) + + rawmode = "F;32F" if scale < 0 else "F;32BF" + args = (rawmode, 0, -1) + else: + maxval = int(self._read_token()) + if not 0 < maxval < 65536: + msg = "maxval must be greater than 0 and less than 65536" + raise ValueError(msg) + if maxval > 255 and mode == "L": + self._mode = "I" + + rawmode = mode + if decoder_name != "ppm_plain": + # If maxval matches a bit depth, use the raw decoder directly + if maxval == 65535 and mode == "L": + rawmode = "I;16B" + elif maxval != 255: + decoder_name = "ppm" + + args = rawmode if decoder_name == "raw" else (rawmode, maxval) + self.tile = [ + ImageFile._Tile(decoder_name, (0, 0) + self.size, self.fp.tell(), args) + ] + + +# +# -------------------------------------------------------------------- + + +class PpmPlainDecoder(ImageFile.PyDecoder): + _pulls_fd = True + _comment_spans: bool + + def _read_block(self) -> bytes: + assert self.fd is not None + + return self.fd.read(ImageFile.SAFEBLOCK) + + def _find_comment_end(self, block: bytes, start: int = 0) -> int: + a = block.find(b"\n", start) + b = block.find(b"\r", start) + return min(a, b) if a * b > 0 else max(a, b) # lowest nonnegative index (or -1) + + def _ignore_comments(self, block: bytes) -> bytes: + if self._comment_spans: + # Finish current comment + while block: + comment_end = self._find_comment_end(block) + if comment_end != -1: + # Comment ends in this block + # Delete tail of comment + block = block[comment_end + 1 :] + break + else: + # Comment spans whole block + # So read the next block, looking for the end + block = self._read_block() + + # Search for any further comments + self._comment_spans = False + while True: + comment_start = block.find(b"#") + if comment_start == -1: + # No comment found + break + comment_end = self._find_comment_end(block, comment_start) + if comment_end != -1: + # Comment ends in this block + # Delete comment + block = block[:comment_start] + block[comment_end + 1 :] + else: + # Comment continues to next block(s) + block = block[:comment_start] + self._comment_spans = True + break + return block + + def _decode_bitonal(self) -> bytearray: + """ + This is a separate method because in the plain PBM format, all data tokens are + exactly one byte, so the inter-token whitespace is optional. + """ + data = bytearray() + total_bytes = self.state.xsize * self.state.ysize + + while len(data) != total_bytes: + block = self._read_block() # read next block + if not block: + # eof + break + + block = self._ignore_comments(block) + + tokens = b"".join(block.split()) + for token in tokens: + if token not in (48, 49): + msg = b"Invalid token for this mode: %s" % bytes([token]) + raise ValueError(msg) + data = (data + tokens)[:total_bytes] + invert = bytes.maketrans(b"01", b"\xff\x00") + return data.translate(invert) + + def _decode_blocks(self, maxval: int) -> bytearray: + data = bytearray() + max_len = 10 + out_byte_count = 4 if self.mode == "I" else 1 + out_max = 65535 if self.mode == "I" else 255 + bands = Image.getmodebands(self.mode) + total_bytes = self.state.xsize * self.state.ysize * bands * out_byte_count + + half_token = b"" + while len(data) != total_bytes: + block = self._read_block() # read next block + if not block: + if half_token: + block = bytearray(b" ") # flush half_token + else: + # eof + break + + block = self._ignore_comments(block) + + if half_token: + block = half_token + block # stitch half_token to new block + half_token = b"" + + tokens = block.split() + + if block and not block[-1:].isspace(): # block might split token + half_token = tokens.pop() # save half token for later + if len(half_token) > max_len: # prevent buildup of half_token + msg = ( + b"Token too long found in data: %s" % half_token[: max_len + 1] + ) + raise ValueError(msg) + + for token in tokens: + if len(token) > max_len: + msg = b"Token too long found in data: %s" % token[: max_len + 1] + raise ValueError(msg) + value = int(token) + if value < 0: + msg_str = f"Channel value is negative: {value}" + raise ValueError(msg_str) + if value > maxval: + msg_str = f"Channel value too large for this mode: {value}" + raise ValueError(msg_str) + value = round(value / maxval * out_max) + data += o32(value) if self.mode == "I" else o8(value) + if len(data) == total_bytes: # finished! + break + return data + + def decode(self, buffer: bytes | Image.SupportsArrayInterface) -> tuple[int, int]: + self._comment_spans = False + if self.mode == "1": + data = self._decode_bitonal() + rawmode = "1;8" + else: + maxval = self.args[-1] + data = self._decode_blocks(maxval) + rawmode = "I;32" if self.mode == "I" else self.mode + self.set_as_raw(bytes(data), rawmode) + return -1, 0 + + +class PpmDecoder(ImageFile.PyDecoder): + _pulls_fd = True + + def decode(self, buffer: bytes | Image.SupportsArrayInterface) -> tuple[int, int]: + assert self.fd is not None + + data = bytearray() + maxval = self.args[-1] + in_byte_count = 1 if maxval < 256 else 2 + out_byte_count = 4 if self.mode == "I" else 1 + out_max = 65535 if self.mode == "I" else 255 + bands = Image.getmodebands(self.mode) + dest_length = self.state.xsize * self.state.ysize * bands * out_byte_count + while len(data) < dest_length: + pixels = self.fd.read(in_byte_count * bands) + if len(pixels) < in_byte_count * bands: + # eof + break + for b in range(bands): + value = ( + pixels[b] if in_byte_count == 1 else i16(pixels, b * in_byte_count) + ) + value = min(out_max, round(value / maxval * out_max)) + data += o32(value) if self.mode == "I" else o8(value) + rawmode = "I;32" if self.mode == "I" else self.mode + self.set_as_raw(bytes(data), rawmode) + return -1, 0 + + +# +# -------------------------------------------------------------------- + + +def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None: + if im.mode == "1": + rawmode, head = "1;I", b"P4" + elif im.mode == "L": + rawmode, head = "L", b"P5" + elif im.mode in ("I", "I;16"): + rawmode, head = "I;16B", b"P5" + elif im.mode in ("RGB", "RGBA"): + rawmode, head = "RGB", b"P6" + elif im.mode == "F": + rawmode, head = "F;32F", b"Pf" + else: + msg = f"cannot write mode {im.mode} as PPM" + raise OSError(msg) + fp.write(head + b"\n%d %d\n" % im.size) + if head == b"P6": + fp.write(b"255\n") + elif head == b"P5": + if rawmode == "L": + fp.write(b"255\n") + else: + fp.write(b"65535\n") + elif head == b"Pf": + fp.write(b"-1.0\n") + row_order = -1 if im.mode == "F" else 1 + ImageFile._save( + im, fp, [ImageFile._Tile("raw", (0, 0) + im.size, 0, (rawmode, 0, row_order))] + ) + + +# +# -------------------------------------------------------------------- + + +Image.register_open(PpmImageFile.format, PpmImageFile, _accept) +Image.register_save(PpmImageFile.format, _save) + +Image.register_decoder("ppm", PpmDecoder) +Image.register_decoder("ppm_plain", PpmPlainDecoder) + +Image.register_extensions(PpmImageFile.format, [".pbm", ".pgm", ".ppm", ".pnm", ".pfm"]) + +Image.register_mime(PpmImageFile.format, "image/x-portable-anymap") diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/PsdImagePlugin.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/PsdImagePlugin.py new file mode 100644 index 000000000..dd3d5ab95 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/PsdImagePlugin.py @@ -0,0 +1,337 @@ +# +# The Python Imaging Library +# $Id$ +# +# Adobe PSD 2.5/3.0 file handling +# +# History: +# 1995-09-01 fl Created +# 1997-01-03 fl Read most PSD images +# 1997-01-18 fl Fixed P and CMYK support +# 2001-10-21 fl Added seek/tell support (for layers) +# +# Copyright (c) 1997-2001 by Secret Labs AB. +# Copyright (c) 1995-2001 by Fredrik Lundh +# +# See the README file for information on usage and redistribution. +# +from __future__ import annotations + +import io +from functools import cached_property +from typing import IO + +from . import Image, ImageFile, ImagePalette +from ._binary import i8 +from ._binary import i16be as i16 +from ._binary import i32be as i32 +from ._binary import si16be as si16 +from ._binary import si32be as si32 +from ._util import DeferredError + +MODES = { + # (photoshop mode, bits) -> (pil mode, required channels) + (0, 1): ("1", 1), + (0, 8): ("L", 1), + (1, 8): ("L", 1), + (2, 8): ("P", 1), + (3, 8): ("RGB", 3), + (4, 8): ("CMYK", 4), + (7, 8): ("L", 1), # FIXME: multilayer + (8, 8): ("L", 1), # duotone + (9, 8): ("LAB", 3), +} + + +# --------------------------------------------------------------------. +# read PSD images + + +def _accept(prefix: bytes) -> bool: + return prefix.startswith(b"8BPS") + + +## +# Image plugin for Photoshop images. + + +class PsdImageFile(ImageFile.ImageFile): + format = "PSD" + format_description = "Adobe Photoshop" + _close_exclusive_fp_after_loading = False + + def _open(self) -> None: + assert self.fp is not None + read = self.fp.read + + # + # header + + s = read(26) + if not _accept(s) or i16(s, 4) != 1: + msg = "not a PSD file" + raise SyntaxError(msg) + + psd_bits = i16(s, 22) + psd_channels = i16(s, 12) + psd_mode = i16(s, 24) + + mode, channels = MODES[(psd_mode, psd_bits)] + + if channels > psd_channels: + msg = "not enough channels" + raise OSError(msg) + if mode == "RGB" and psd_channels == 4: + mode = "RGBA" + channels = 4 + + self._mode = mode + self._size = i32(s, 18), i32(s, 14) + + # + # color mode data + + size = i32(read(4)) + if size: + data = read(size) + if mode == "P" and size == 768: + self.palette = ImagePalette.raw("RGB;L", data) + + # + # image resources + + self.resources = [] + + size = i32(read(4)) + if size: + # load resources + end = self.fp.tell() + size + while self.fp.tell() < end: + read(4) # signature + id = i16(read(2)) + name = read(i8(read(1))) + if not (len(name) & 1): + read(1) # padding + data = read(i32(read(4))) + if len(data) & 1: + read(1) # padding + self.resources.append((id, name, data)) + if id == 1039: # ICC profile + self.info["icc_profile"] = data + + # + # layer and mask information + + self._layers_position = None + + size = i32(read(4)) + if size: + end = self.fp.tell() + size + size = i32(read(4)) + if size: + self._layers_position = self.fp.tell() + self._layers_size = size + self.fp.seek(end) + self._n_frames: int | None = None + + # + # image descriptor + + self.tile = _maketile(self.fp, mode, (0, 0) + self.size, channels) + + # keep the file open + self._fp = self.fp + self.frame = 1 + self._min_frame = 1 + + @cached_property + def layers( + self, + ) -> list[tuple[str, str, tuple[int, int, int, int], list[ImageFile._Tile]]]: + layers = [] + if self._layers_position is not None: + if isinstance(self._fp, DeferredError): + raise self._fp.ex + self._fp.seek(self._layers_position) + _layer_data = io.BytesIO(ImageFile._safe_read(self._fp, self._layers_size)) + layers = _layerinfo(_layer_data, self._layers_size) + self._n_frames = len(layers) + return layers + + @property + def n_frames(self) -> int: + if self._n_frames is None: + self._n_frames = len(self.layers) + return self._n_frames + + @property + def is_animated(self) -> bool: + return len(self.layers) > 1 + + def seek(self, layer: int) -> None: + if not self._seek_check(layer): + return + if isinstance(self._fp, DeferredError): + raise self._fp.ex + + # seek to given layer (1..max) + if layer > len(self.layers): + msg = "no more images in PSD file" + raise EOFError(msg) + _, mode, _, tile = self.layers[layer - 1] + self._mode = mode + self.tile = tile + self.frame = layer + self.fp = self._fp + + def tell(self) -> int: + # return layer number (0=image, 1..max=layers) + return self.frame + + +def _layerinfo( + fp: IO[bytes], ct_bytes: int +) -> list[tuple[str, str, tuple[int, int, int, int], list[ImageFile._Tile]]]: + # read layerinfo block + layers = [] + + def read(size: int) -> bytes: + return ImageFile._safe_read(fp, size) + + ct = si16(read(2)) + + # sanity check + if ct_bytes < (abs(ct) * 20): + msg = "Layer block too short for number of layers requested" + raise SyntaxError(msg) + + for _ in range(abs(ct)): + # bounding box + y0 = si32(read(4)) + x0 = si32(read(4)) + y1 = si32(read(4)) + x1 = si32(read(4)) + + # image info + bands = [] + ct_types = i16(read(2)) + if ct_types > 4: + fp.seek(ct_types * 6 + 12, io.SEEK_CUR) + size = i32(read(4)) + fp.seek(size, io.SEEK_CUR) + continue + + for _ in range(ct_types): + type = i16(read(2)) + + if type == 65535: + b = "A" + else: + b = "RGBA"[type] + + bands.append(b) + read(4) # size + + # figure out the image mode + bands.sort() + if bands == ["R"]: + mode = "L" + elif bands == ["B", "G", "R"]: + mode = "RGB" + elif bands == ["A", "B", "G", "R"]: + mode = "RGBA" + else: + mode = "" # unknown + + # skip over blend flags and extra information + read(12) # filler + name = "" + size = i32(read(4)) # length of the extra data field + if size: + data_end = fp.tell() + size + + length = i32(read(4)) + if length: + fp.seek(length - 16, io.SEEK_CUR) + + length = i32(read(4)) + if length: + fp.seek(length, io.SEEK_CUR) + + length = i8(read(1)) + if length: + # Don't know the proper encoding, + # Latin-1 should be a good guess + name = read(length).decode("latin-1", "replace") + + fp.seek(data_end) + layers.append((name, mode, (x0, y0, x1, y1))) + + # get tiles + layerinfo = [] + for i, (name, mode, bbox) in enumerate(layers): + tile = [] + for m in mode: + t = _maketile(fp, m, bbox, 1) + if t: + tile.extend(t) + layerinfo.append((name, mode, bbox, tile)) + + return layerinfo + + +def _maketile( + file: IO[bytes], mode: str, bbox: tuple[int, int, int, int], channels: int +) -> list[ImageFile._Tile]: + tiles = [] + read = file.read + + compression = i16(read(2)) + + xsize = bbox[2] - bbox[0] + ysize = bbox[3] - bbox[1] + + offset = file.tell() + + if compression == 0: + # + # raw compression + for channel in range(channels): + layer = mode[channel] + if mode == "CMYK": + layer += ";I" + tiles.append(ImageFile._Tile("raw", bbox, offset, layer)) + offset = offset + xsize * ysize + + elif compression == 1: + # + # packbits compression + i = 0 + bytecount = read(channels * ysize * 2) + offset = file.tell() + for channel in range(channels): + layer = mode[channel] + if mode == "CMYK": + layer += ";I" + tiles.append(ImageFile._Tile("packbits", bbox, offset, layer)) + for y in range(ysize): + offset = offset + i16(bytecount, i) + i += 2 + + file.seek(offset) + + if offset & 1: + read(1) # padding + + return tiles + + +# -------------------------------------------------------------------- +# registry + + +Image.register_open(PsdImageFile.format, PsdImageFile, _accept) + +Image.register_extension(PsdImageFile.format, ".psd") + +Image.register_mime(PsdImageFile.format, "image/vnd.adobe.photoshop") diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/QoiImagePlugin.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/QoiImagePlugin.py new file mode 100644 index 000000000..d0709b119 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/QoiImagePlugin.py @@ -0,0 +1,235 @@ +# +# The Python Imaging Library. +# +# QOI support for PIL +# +# See the README file for information on usage and redistribution. +# +from __future__ import annotations + +import os +from typing import IO + +from . import Image, ImageFile +from ._binary import i32be as i32 +from ._binary import o8 +from ._binary import o32be as o32 + + +def _accept(prefix: bytes) -> bool: + return prefix.startswith(b"qoif") + + +class QoiImageFile(ImageFile.ImageFile): + format = "QOI" + format_description = "Quite OK Image" + + def _open(self) -> None: + assert self.fp is not None + if not _accept(self.fp.read(4)): + msg = "not a QOI file" + raise SyntaxError(msg) + + self._size = i32(self.fp.read(4)), i32(self.fp.read(4)) + + channels = self.fp.read(1)[0] + self._mode = "RGB" if channels == 3 else "RGBA" + + self.fp.seek(1, os.SEEK_CUR) # colorspace + self.tile = [ImageFile._Tile("qoi", (0, 0) + self._size, self.fp.tell())] + + +class QoiDecoder(ImageFile.PyDecoder): + _pulls_fd = True + _previous_pixel: bytes | bytearray | None = None + _previously_seen_pixels: dict[int, bytes | bytearray] = {} + + def _add_to_previous_pixels(self, value: bytes | bytearray) -> None: + self._previous_pixel = value + + r, g, b, a = value + hash_value = (r * 3 + g * 5 + b * 7 + a * 11) % 64 + self._previously_seen_pixels[hash_value] = value + + def decode(self, buffer: bytes | Image.SupportsArrayInterface) -> tuple[int, int]: + assert self.fd is not None + + self._previously_seen_pixels = {} + self._previous_pixel = bytearray((0, 0, 0, 255)) + + data = bytearray() + bands = Image.getmodebands(self.mode) + dest_length = self.state.xsize * self.state.ysize * bands + while len(data) < dest_length: + byte = self.fd.read(1)[0] + value: bytes | bytearray + if byte == 0b11111110 and self._previous_pixel: # QOI_OP_RGB + value = bytearray(self.fd.read(3)) + self._previous_pixel[3:] + elif byte == 0b11111111: # QOI_OP_RGBA + value = self.fd.read(4) + else: + op = byte >> 6 + if op == 0: # QOI_OP_INDEX + op_index = byte & 0b00111111 + value = self._previously_seen_pixels.get( + op_index, bytearray((0, 0, 0, 0)) + ) + elif op == 1 and self._previous_pixel: # QOI_OP_DIFF + value = bytearray( + ( + (self._previous_pixel[0] + ((byte & 0b00110000) >> 4) - 2) + % 256, + (self._previous_pixel[1] + ((byte & 0b00001100) >> 2) - 2) + % 256, + (self._previous_pixel[2] + (byte & 0b00000011) - 2) % 256, + self._previous_pixel[3], + ) + ) + elif op == 2 and self._previous_pixel: # QOI_OP_LUMA + second_byte = self.fd.read(1)[0] + diff_green = (byte & 0b00111111) - 32 + diff_red = ((second_byte & 0b11110000) >> 4) - 8 + diff_blue = (second_byte & 0b00001111) - 8 + + value = bytearray( + tuple( + (self._previous_pixel[i] + diff_green + diff) % 256 + for i, diff in enumerate((diff_red, 0, diff_blue)) + ) + ) + value += self._previous_pixel[3:] + elif op == 3 and self._previous_pixel: # QOI_OP_RUN + run_length = (byte & 0b00111111) + 1 + value = self._previous_pixel + if bands == 3: + value = value[:3] + data += value * run_length + continue + self._add_to_previous_pixels(value) + + if bands == 3: + value = value[:3] + data += value + self.set_as_raw(data) + return -1, 0 + + +def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None: + if im.mode == "RGB": + channels = 3 + elif im.mode == "RGBA": + channels = 4 + else: + msg = "Unsupported QOI image mode" + raise ValueError(msg) + + colorspace = 0 if im.encoderinfo.get("colorspace") == "sRGB" else 1 + + fp.write(b"qoif") + fp.write(o32(im.size[0])) + fp.write(o32(im.size[1])) + fp.write(o8(channels)) + fp.write(o8(colorspace)) + + ImageFile._save(im, fp, [ImageFile._Tile("qoi", (0, 0) + im.size)]) + + +class QoiEncoder(ImageFile.PyEncoder): + _pushes_fd = True + _previous_pixel: tuple[int, int, int, int] | None = None + _previously_seen_pixels: dict[int, tuple[int, int, int, int]] = {} + _run = 0 + + def _write_run(self) -> bytes: + data = o8(0b11000000 | (self._run - 1)) # QOI_OP_RUN + self._run = 0 + return data + + def _delta(self, left: int, right: int) -> int: + result = (left - right) & 255 + if result >= 128: + result -= 256 + return result + + def encode(self, bufsize: int) -> tuple[int, int, bytes]: + assert self.im is not None + + self._previously_seen_pixels = {0: (0, 0, 0, 0)} + self._previous_pixel = (0, 0, 0, 255) + + data = bytearray() + w, h = self.im.size + bands = Image.getmodebands(self.mode) + + for y in range(h): + for x in range(w): + pixel = self.im.getpixel((x, y)) + if bands == 3: + pixel = (*pixel, 255) + + if pixel == self._previous_pixel: + self._run += 1 + if self._run == 62: + data += self._write_run() + else: + if self._run: + data += self._write_run() + + r, g, b, a = pixel + hash_value = (r * 3 + g * 5 + b * 7 + a * 11) % 64 + if self._previously_seen_pixels.get(hash_value) == pixel: + data += o8(hash_value) # QOI_OP_INDEX + elif self._previous_pixel: + self._previously_seen_pixels[hash_value] = pixel + + prev_r, prev_g, prev_b, prev_a = self._previous_pixel + if prev_a == a: + delta_r = self._delta(r, prev_r) + delta_g = self._delta(g, prev_g) + delta_b = self._delta(b, prev_b) + + if ( + -2 <= delta_r < 2 + and -2 <= delta_g < 2 + and -2 <= delta_b < 2 + ): + data += o8( + 0b01000000 + | (delta_r + 2) << 4 + | (delta_g + 2) << 2 + | (delta_b + 2) + ) # QOI_OP_DIFF + else: + delta_gr = self._delta(delta_r, delta_g) + delta_gb = self._delta(delta_b, delta_g) + if ( + -8 <= delta_gr < 8 + and -32 <= delta_g < 32 + and -8 <= delta_gb < 8 + ): + data += o8( + 0b10000000 | (delta_g + 32) + ) # QOI_OP_LUMA + data += o8((delta_gr + 8) << 4 | (delta_gb + 8)) + else: + data += o8(0b11111110) # QOI_OP_RGB + data += bytes(pixel[:3]) + else: + data += o8(0b11111111) # QOI_OP_RGBA + data += bytes(pixel) + + self._previous_pixel = pixel + + if self._run: + data += self._write_run() + data += bytes((0, 0, 0, 0, 0, 0, 0, 1)) # padding + + return len(data), 0, data + + +Image.register_open(QoiImageFile.format, QoiImageFile, _accept) +Image.register_decoder("qoi", QoiDecoder) +Image.register_extension(QoiImageFile.format, ".qoi") + +Image.register_save(QoiImageFile.format, _save) +Image.register_encoder("qoi", QoiEncoder) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/SgiImagePlugin.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/SgiImagePlugin.py new file mode 100644 index 000000000..853022150 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/SgiImagePlugin.py @@ -0,0 +1,231 @@ +# +# The Python Imaging Library. +# $Id$ +# +# SGI image file handling +# +# See "The SGI Image File Format (Draft version 0.97)", Paul Haeberli. +# +# +# +# History: +# 2017-22-07 mb Add RLE decompression +# 2016-16-10 mb Add save method without compression +# 1995-09-10 fl Created +# +# Copyright (c) 2016 by Mickael Bonfill. +# Copyright (c) 2008 by Karsten Hiddemann. +# Copyright (c) 1997 by Secret Labs AB. +# Copyright (c) 1995 by Fredrik Lundh. +# +# See the README file for information on usage and redistribution. +# +from __future__ import annotations + +import os +import struct +from typing import IO + +from . import Image, ImageFile +from ._binary import i16be as i16 +from ._binary import o8 + + +def _accept(prefix: bytes) -> bool: + return len(prefix) >= 2 and i16(prefix) == 474 + + +MODES = { + (1, 1, 1): "L", + (1, 2, 1): "L", + (2, 1, 1): "L;16B", + (2, 2, 1): "L;16B", + (1, 3, 3): "RGB", + (2, 3, 3): "RGB;16B", + (1, 3, 4): "RGBA", + (2, 3, 4): "RGBA;16B", +} + + +## +# Image plugin for SGI images. +class SgiImageFile(ImageFile.ImageFile): + format = "SGI" + format_description = "SGI Image File Format" + + def _open(self) -> None: + # HEAD + assert self.fp is not None + + headlen = 512 + s = self.fp.read(headlen) + + if not _accept(s): + msg = "Not an SGI image file" + raise ValueError(msg) + + # compression : verbatim or RLE + compression = s[2] + + # bpc : 1 or 2 bytes (8bits or 16bits) + bpc = s[3] + + # dimension : 1, 2 or 3 (depending on xsize, ysize and zsize) + dimension = i16(s, 4) + + # xsize : width + xsize = i16(s, 6) + + # ysize : height + ysize = i16(s, 8) + + # zsize : channels count + zsize = i16(s, 10) + + # determine mode from bits/zsize + try: + rawmode = MODES[(bpc, dimension, zsize)] + except KeyError: + msg = "Unsupported SGI image mode" + raise ValueError(msg) + + self._size = xsize, ysize + self._mode = rawmode.split(";")[0] + if self.mode == "RGB": + self.custom_mimetype = "image/rgb" + + # orientation -1 : scanlines begins at the bottom-left corner + orientation = -1 + + # decoder info + if compression == 0: + pagesize = xsize * ysize * bpc + if bpc == 2: + self.tile = [ + ImageFile._Tile( + "SGI16", + (0, 0) + self.size, + headlen, + (self.mode, 0, orientation), + ) + ] + else: + self.tile = [] + offset = headlen + for layer in self.mode: + self.tile.append( + ImageFile._Tile( + "raw", (0, 0) + self.size, offset, (layer, 0, orientation) + ) + ) + offset += pagesize + elif compression == 1: + self.tile = [ + ImageFile._Tile( + "sgi_rle", (0, 0) + self.size, headlen, (rawmode, orientation, bpc) + ) + ] + + +def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None: + if im.mode not in {"RGB", "RGBA", "L"}: + msg = "Unsupported SGI image mode" + raise ValueError(msg) + + # Get the keyword arguments + info = im.encoderinfo + + # Byte-per-pixel precision, 1 = 8bits per pixel + bpc = info.get("bpc", 1) + + if bpc not in (1, 2): + msg = "Unsupported number of bytes per pixel" + raise ValueError(msg) + + # Flip the image, since the origin of SGI file is the bottom-left corner + orientation = -1 + # Define the file as SGI File Format + magic_number = 474 + # Run-Length Encoding Compression - Unsupported at this time + rle = 0 + + # X Dimension = width / Y Dimension = height + x, y = im.size + # Z Dimension: Number of channels + z = len(im.mode) + # Number of dimensions (x,y,z) + if im.mode == "L": + dimension = 1 if y == 1 else 2 + else: + dimension = 3 + + # Minimum Byte value + pinmin = 0 + # Maximum Byte value (255 = 8bits per pixel) + pinmax = 255 + # Image name (79 characters max, truncated below in write) + img_name = os.path.splitext(os.path.basename(filename))[0] + if isinstance(img_name, str): + img_name = img_name.encode("ascii", "ignore") + # Standard representation of pixel in the file + colormap = 0 + fp.write(struct.pack(">h", magic_number)) + fp.write(o8(rle)) + fp.write(o8(bpc)) + fp.write(struct.pack(">H", dimension)) + fp.write(struct.pack(">H", x)) + fp.write(struct.pack(">H", y)) + fp.write(struct.pack(">H", z)) + fp.write(struct.pack(">l", pinmin)) + fp.write(struct.pack(">l", pinmax)) + fp.write(struct.pack("4s", b"")) # dummy + fp.write(struct.pack("79s", img_name)) # truncates to 79 chars + fp.write(struct.pack("s", b"")) # force null byte after img_name + fp.write(struct.pack(">l", colormap)) + fp.write(struct.pack("404s", b"")) # dummy + + rawmode = "L" + if bpc == 2: + rawmode = "L;16B" + + for channel in im.split(): + fp.write(channel.tobytes("raw", rawmode, 0, orientation)) + + if hasattr(fp, "flush"): + fp.flush() + + +class SGI16Decoder(ImageFile.PyDecoder): + _pulls_fd = True + + def decode(self, buffer: bytes | Image.SupportsArrayInterface) -> tuple[int, int]: + assert self.fd is not None + assert self.im is not None + + rawmode, stride, orientation = self.args + pagesize = self.state.xsize * self.state.ysize + zsize = len(self.mode) + self.fd.seek(512) + + for band in range(zsize): + channel = Image.new("L", (self.state.xsize, self.state.ysize)) + channel.frombytes( + self.fd.read(2 * pagesize), "raw", "L;16B", stride, orientation + ) + self.im.putband(channel.im, band) + + return -1, 0 + + +# +# registry + + +Image.register_decoder("SGI16", SGI16Decoder) +Image.register_open(SgiImageFile.format, SgiImageFile, _accept) +Image.register_save(SgiImageFile.format, _save) +Image.register_mime(SgiImageFile.format, "image/sgi") + +Image.register_extensions(SgiImageFile.format, [".bw", ".rgb", ".rgba", ".sgi"]) + +# End of file diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/SpiderImagePlugin.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/SpiderImagePlugin.py new file mode 100644 index 000000000..11d90699d --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/SpiderImagePlugin.py @@ -0,0 +1,332 @@ +# +# The Python Imaging Library. +# +# SPIDER image file handling +# +# History: +# 2004-08-02 Created BB +# 2006-03-02 added save method +# 2006-03-13 added support for stack images +# +# Copyright (c) 2004 by Health Research Inc. (HRI) RENSSELAER, NY 12144. +# Copyright (c) 2004 by William Baxter. +# Copyright (c) 2004 by Secret Labs AB. +# Copyright (c) 2004 by Fredrik Lundh. +# + +## +# Image plugin for the Spider image format. This format is used +# by the SPIDER software, in processing image data from electron +# microscopy and tomography. +## + +# +# SpiderImagePlugin.py +# +# The Spider image format is used by SPIDER software, in processing +# image data from electron microscopy and tomography. +# +# Spider home page: +# https://spider.wadsworth.org/spider_doc/spider/docs/spider.html +# +# Details about the Spider image format: +# https://spider.wadsworth.org/spider_doc/spider/docs/image_doc.html +# +from __future__ import annotations + +import os +import struct +import sys +from typing import IO, Any, cast + +from . import Image, ImageFile +from ._util import DeferredError + +TYPE_CHECKING = False + + +def isInt(f: Any) -> int: + try: + i = int(f) + if f - i == 0: + return 1 + else: + return 0 + except (ValueError, OverflowError): + return 0 + + +iforms = [1, 3, -11, -12, -21, -22] + + +# There is no magic number to identify Spider files, so just check a +# series of header locations to see if they have reasonable values. +# Returns no. of bytes in the header, if it is a valid Spider header, +# otherwise returns 0 + + +def isSpiderHeader(t: tuple[float, ...]) -> int: + h = (99,) + t # add 1 value so can use spider header index start=1 + # header values 1,2,5,12,13,22,23 should be integers + for i in [1, 2, 5, 12, 13, 22, 23]: + if not isInt(h[i]): + return 0 + # check iform + iform = int(h[5]) + if iform not in iforms: + return 0 + # check other header values + labrec = int(h[13]) # no. records in file header + labbyt = int(h[22]) # total no. of bytes in header + lenbyt = int(h[23]) # record length in bytes + if labbyt != (labrec * lenbyt): + return 0 + # looks like a valid header + return labbyt + + +def isSpiderImage(filename: str) -> int: + with open(filename, "rb") as fp: + f = fp.read(92) # read 23 * 4 bytes + t = struct.unpack(">23f", f) # try big-endian first + hdrlen = isSpiderHeader(t) + if hdrlen == 0: + t = struct.unpack("<23f", f) # little-endian + hdrlen = isSpiderHeader(t) + return hdrlen + + +class SpiderImageFile(ImageFile.ImageFile): + format = "SPIDER" + format_description = "Spider 2D image" + _close_exclusive_fp_after_loading = False + + def _open(self) -> None: + # check header + n = 27 * 4 # read 27 float values + assert self.fp is not None + f = self.fp.read(n) + + try: + self.bigendian = 1 + t = struct.unpack(">27f", f) # try big-endian first + hdrlen = isSpiderHeader(t) + if hdrlen == 0: + self.bigendian = 0 + t = struct.unpack("<27f", f) # little-endian + hdrlen = isSpiderHeader(t) + if hdrlen == 0: + msg = "not a valid Spider file" + raise SyntaxError(msg) + except struct.error as e: + msg = "not a valid Spider file" + raise SyntaxError(msg) from e + + h = (99,) + t # add 1 value : spider header index starts at 1 + iform = int(h[5]) + if iform != 1: + msg = "not a Spider 2D image" + raise SyntaxError(msg) + + self._size = int(h[12]), int(h[2]) # size in pixels (width, height) + self.istack = int(h[24]) + self.imgnumber = int(h[27]) + + if self.istack == 0 and self.imgnumber == 0: + # stk=0, img=0: a regular 2D image + offset = hdrlen + self._nimages = 1 + elif self.istack > 0 and self.imgnumber == 0: + # stk>0, img=0: Opening the stack for the first time + self.imgbytes = int(h[12]) * int(h[2]) * 4 + self.hdrlen = hdrlen + self._nimages = int(h[26]) + # Point to the first image in the stack + offset = hdrlen * 2 + self.imgnumber = 1 + elif self.istack == 0 and self.imgnumber > 0: + # stk=0, img>0: an image within the stack + offset = hdrlen + self.stkoffset + self.istack = 2 # So Image knows it's still a stack + else: + msg = "inconsistent stack header values" + raise SyntaxError(msg) + + if self.bigendian: + self.rawmode = "F;32BF" + else: + self.rawmode = "F;32F" + self._mode = "F" + + self.tile = [ImageFile._Tile("raw", (0, 0) + self.size, offset, self.rawmode)] + self._fp = self.fp # FIXME: hack + + @property + def n_frames(self) -> int: + return self._nimages + + @property + def is_animated(self) -> bool: + return self._nimages > 1 + + # 1st image index is zero (although SPIDER imgnumber starts at 1) + def tell(self) -> int: + if self.imgnumber < 1: + return 0 + else: + return self.imgnumber - 1 + + def seek(self, frame: int) -> None: + if self.istack == 0: + msg = "attempt to seek in a non-stack file" + raise EOFError(msg) + if not self._seek_check(frame): + return + if isinstance(self._fp, DeferredError): + raise self._fp.ex + self.stkoffset = self.hdrlen + frame * (self.hdrlen + self.imgbytes) + self.fp = self._fp + self.fp.seek(self.stkoffset) + self._open() + + # returns a byte image after rescaling to 0..255 + def convert2byte(self, depth: int = 255) -> Image.Image: + extrema = self.getextrema() + assert isinstance(extrema[0], float) + minimum, maximum = cast(tuple[float, float], extrema) + m: float = 1 + if maximum != minimum: + m = depth / (maximum - minimum) + b = -m * minimum + return self.point(lambda i: i * m + b).convert("L") + + if TYPE_CHECKING: + from . import ImageTk + + # returns a ImageTk.PhotoImage object, after rescaling to 0..255 + def tkPhotoImage(self) -> ImageTk.PhotoImage: + from . import ImageTk + + return ImageTk.PhotoImage(self.convert2byte(), palette=256) + + +# -------------------------------------------------------------------- +# Image series + + +# given a list of filenames, return a list of images +def loadImageSeries(filelist: list[str] | None = None) -> list[Image.Image] | None: + """create a list of :py:class:`~PIL.Image.Image` objects for use in a montage""" + if filelist is None or len(filelist) < 1: + return None + + byte_imgs = [] + for img in filelist: + if not os.path.exists(img): + print(f"unable to find {img}") + continue + try: + with Image.open(img) as im: + assert isinstance(im, SpiderImageFile) + byte_im = im.convert2byte() + except Exception: + if not isSpiderImage(img): + print(f"{img} is not a Spider image file") + continue + byte_im.info["filename"] = img + byte_imgs.append(byte_im) + return byte_imgs + + +# -------------------------------------------------------------------- +# For saving images in Spider format + + +def makeSpiderHeader(im: Image.Image) -> list[bytes]: + nsam, nrow = im.size + lenbyt = max(1, nsam) * 4 # There are labrec records in the header + labrec = int(1024 / lenbyt) + if 1024 % lenbyt != 0: + labrec += 1 + labbyt = labrec * lenbyt + nvalues = int(labbyt / 4) + if nvalues < 23: + return [] + + hdr = [0.0] * nvalues + + # NB these are Fortran indices + hdr[1] = 1.0 # nslice (=1 for an image) + hdr[2] = float(nrow) # number of rows per slice + hdr[3] = float(nrow) # number of records in the image + hdr[5] = 1.0 # iform for 2D image + hdr[12] = float(nsam) # number of pixels per line + hdr[13] = float(labrec) # number of records in file header + hdr[22] = float(labbyt) # total number of bytes in header + hdr[23] = float(lenbyt) # record length in bytes + + # adjust for Fortran indexing + hdr = hdr[1:] + hdr.append(0.0) + # pack binary data into a string + return [struct.pack("f", v) for v in hdr] + + +def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None: + if im.mode != "F": + im = im.convert("F") + + hdr = makeSpiderHeader(im) + if len(hdr) < 256: + msg = "Error creating Spider header" + raise OSError(msg) + + # write the SPIDER header + fp.writelines(hdr) + + rawmode = "F;32NF" # 32-bit native floating point + ImageFile._save(im, fp, [ImageFile._Tile("raw", (0, 0) + im.size, 0, rawmode)]) + + +def _save_spider(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None: + # get the filename extension and register it with Image + if filename_ext := os.path.splitext(filename)[1]: + ext = filename_ext.decode() if isinstance(filename_ext, bytes) else filename_ext + Image.register_extension(SpiderImageFile.format, ext) + _save(im, fp, filename) + + +# -------------------------------------------------------------------- + + +Image.register_open(SpiderImageFile.format, SpiderImageFile) +Image.register_save(SpiderImageFile.format, _save_spider) + +if __name__ == "__main__": + if len(sys.argv) < 2: + print("Syntax: python3 SpiderImagePlugin.py [infile] [outfile]") + sys.exit() + + filename = sys.argv[1] + if not isSpiderImage(filename): + print("input image must be in Spider format") + sys.exit() + + with Image.open(filename) as im: + print(f"image: {im}") + print(f"format: {im.format}") + print(f"size: {im.size}") + print(f"mode: {im.mode}") + print("max, min: ", end=" ") + print(im.getextrema()) + + if len(sys.argv) > 2: + outfile = sys.argv[2] + + # perform some image operation + transposed_im = im.transpose(Image.Transpose.FLIP_LEFT_RIGHT) + print( + f"saving a flipped version of {os.path.basename(filename)} " + f"as {outfile} " + ) + transposed_im.save(outfile, SpiderImageFile.format) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/SunImagePlugin.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/SunImagePlugin.py new file mode 100644 index 000000000..8912379ea --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/SunImagePlugin.py @@ -0,0 +1,145 @@ +# +# The Python Imaging Library. +# $Id$ +# +# Sun image file handling +# +# History: +# 1995-09-10 fl Created +# 1996-05-28 fl Fixed 32-bit alignment +# 1998-12-29 fl Import ImagePalette module +# 2001-12-18 fl Fixed palette loading (from Jean-Claude Rimbault) +# +# Copyright (c) 1997-2001 by Secret Labs AB +# Copyright (c) 1995-1996 by Fredrik Lundh +# +# See the README file for information on usage and redistribution. +# +from __future__ import annotations + +from . import Image, ImageFile, ImagePalette +from ._binary import i32be as i32 + + +def _accept(prefix: bytes) -> bool: + return len(prefix) >= 4 and i32(prefix) == 0x59A66A95 + + +## +# Image plugin for Sun raster files. + + +class SunImageFile(ImageFile.ImageFile): + format = "SUN" + format_description = "Sun Raster File" + + def _open(self) -> None: + # The Sun Raster file header is 32 bytes in length + # and has the following format: + + # typedef struct _SunRaster + # { + # DWORD MagicNumber; /* Magic (identification) number */ + # DWORD Width; /* Width of image in pixels */ + # DWORD Height; /* Height of image in pixels */ + # DWORD Depth; /* Number of bits per pixel */ + # DWORD Length; /* Size of image data in bytes */ + # DWORD Type; /* Type of raster file */ + # DWORD ColorMapType; /* Type of color map */ + # DWORD ColorMapLength; /* Size of the color map in bytes */ + # } SUNRASTER; + + assert self.fp is not None + + # HEAD + s = self.fp.read(32) + if not _accept(s): + msg = "not an SUN raster file" + raise SyntaxError(msg) + + offset = 32 + + self._size = i32(s, 4), i32(s, 8) + + depth = i32(s, 12) + # data_length = i32(s, 16) # unreliable, ignore. + file_type = i32(s, 20) + palette_type = i32(s, 24) # 0: None, 1: RGB, 2: Raw/arbitrary + palette_length = i32(s, 28) + + if depth == 1: + self._mode, rawmode = "1", "1;I" + elif depth == 4: + self._mode, rawmode = "L", "L;4" + elif depth == 8: + self._mode = rawmode = "L" + elif depth == 24: + if file_type == 3: + self._mode, rawmode = "RGB", "RGB" + else: + self._mode, rawmode = "RGB", "BGR" + elif depth == 32: + if file_type == 3: + self._mode, rawmode = "RGB", "RGBX" + else: + self._mode, rawmode = "RGB", "BGRX" + else: + msg = "Unsupported Mode/Bit Depth" + raise SyntaxError(msg) + + if palette_length: + if palette_length > 1024: + msg = "Unsupported Color Palette Length" + raise SyntaxError(msg) + + if palette_type != 1: + msg = "Unsupported Palette Type" + raise SyntaxError(msg) + + offset = offset + palette_length + self.palette = ImagePalette.raw("RGB;L", self.fp.read(palette_length)) + if self.mode == "L": + self._mode = "P" + rawmode = rawmode.replace("L", "P") + + # 16 bit boundaries on stride + stride = ((self.size[0] * depth + 15) // 16) * 2 + + # file type: Type is the version (or flavor) of the bitmap + # file. The following values are typically found in the Type + # field: + # 0000h Old + # 0001h Standard + # 0002h Byte-encoded + # 0003h RGB format + # 0004h TIFF format + # 0005h IFF format + # FFFFh Experimental + + # Old and standard are the same, except for the length tag. + # byte-encoded is run-length-encoded + # RGB looks similar to standard, but RGB byte order + # TIFF and IFF mean that they were converted from T/IFF + # Experimental means that it's something else. + # (https://www.fileformat.info/format/sunraster/egff.htm) + + if file_type in (0, 1, 3, 4, 5): + self.tile = [ + ImageFile._Tile("raw", (0, 0) + self.size, offset, (rawmode, stride)) + ] + elif file_type == 2: + self.tile = [ + ImageFile._Tile("sun_rle", (0, 0) + self.size, offset, rawmode) + ] + else: + msg = "Unsupported Sun Raster file type" + raise SyntaxError(msg) + + +# +# registry + + +Image.register_open(SunImageFile.format, SunImageFile, _accept) + +Image.register_extension(SunImageFile.format, ".ras") diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/TarIO.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/TarIO.py new file mode 100644 index 000000000..86490a496 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/TarIO.py @@ -0,0 +1,61 @@ +# +# The Python Imaging Library. +# $Id$ +# +# read files from within a tar file +# +# History: +# 95-06-18 fl Created +# 96-05-28 fl Open files in binary mode +# +# Copyright (c) Secret Labs AB 1997. +# Copyright (c) Fredrik Lundh 1995-96. +# +# See the README file for information on usage and redistribution. +# +from __future__ import annotations + +import io + +from . import ContainerIO + + +class TarIO(ContainerIO.ContainerIO[bytes]): + """A file object that provides read access to a given member of a TAR file.""" + + def __init__(self, tarfile: str, file: str) -> None: + """ + Create file object. + + :param tarfile: Name of TAR file. + :param file: Name of member file. + """ + self.fh = open(tarfile, "rb") + + while True: + s = self.fh.read(512) + if len(s) != 512: + self.fh.close() + + msg = "unexpected end of tar file" + raise OSError(msg) + + name = s[:100].decode("utf-8") + i = name.find("\0") + if i == 0: + self.fh.close() + + msg = "cannot find subfile" + raise OSError(msg) + if i > 0: + name = name[:i] + + size = int(s[124:135], 8) + + if file == name: + break + + self.fh.seek((size + 511) & (~511), io.SEEK_CUR) + + # Open region + super().__init__(self.fh, self.fh.tell(), size) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/TgaImagePlugin.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/TgaImagePlugin.py new file mode 100644 index 000000000..b2989a4b7 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/TgaImagePlugin.py @@ -0,0 +1,280 @@ +# +# The Python Imaging Library. +# $Id$ +# +# TGA file handling +# +# History: +# 95-09-01 fl created (reads 24-bit files only) +# 97-01-04 fl support more TGA versions, including compressed images +# 98-07-04 fl fixed orientation and alpha layer bugs +# 98-09-11 fl fixed orientation for runlength decoder +# +# Copyright (c) Secret Labs AB 1997-98. +# Copyright (c) Fredrik Lundh 1995-97. +# +# See the README file for information on usage and redistribution. +# +from __future__ import annotations + +import os +import warnings +from typing import IO + +from . import Image, ImageFile, ImagePalette +from ._binary import i16le as i16 +from ._binary import i32le as i32 +from ._binary import o8 +from ._binary import o16le as o16 + +# +# -------------------------------------------------------------------- +# Read RGA file + + +MODES = { + # map imagetype/depth to rawmode + (1, 8): "P", + (3, 1): "1", + (3, 8): "L", + (3, 16): "LA", + (2, 16): "BGRA;15Z", + (2, 24): "BGR", + (2, 32): "BGRA", +} + + +## +# Image plugin for Targa files. + + +class TgaImageFile(ImageFile.ImageFile): + format = "TGA" + format_description = "Targa" + + def _open(self) -> None: + # process header + assert self.fp is not None + + s = self.fp.read(18) + + id_len = s[0] + + colormaptype = s[1] + imagetype = s[2] + + depth = s[16] + + flags = s[17] + + self._size = i16(s, 12), i16(s, 14) + + # validate header fields + if ( + colormaptype not in (0, 1) + or self.size[0] <= 0 + or self.size[1] <= 0 + or depth not in (1, 8, 16, 24, 32) + ): + msg = "not a TGA file" + raise SyntaxError(msg) + + # image mode + if imagetype in (3, 11): + self._mode = "L" + if depth == 1: + self._mode = "1" # ??? + elif depth == 16: + self._mode = "LA" + elif imagetype in (1, 9): + self._mode = "P" if colormaptype else "L" + elif imagetype in (2, 10): + self._mode = "RGB" if depth == 24 else "RGBA" + else: + msg = "unknown TGA mode" + raise SyntaxError(msg) + + # orientation + orientation = flags & 0x30 + self._flip_horizontally = orientation in [0x10, 0x30] + if orientation in [0x20, 0x30]: + orientation = 1 + elif orientation in [0, 0x10]: + orientation = -1 + else: + msg = "unknown TGA orientation" + raise SyntaxError(msg) + + self.info["orientation"] = orientation + + if imagetype & 8: + self.info["compression"] = "tga_rle" + + if id_len: + self.info["id_section"] = self.fp.read(id_len) + + if colormaptype: + # read palette + start, size, mapdepth = i16(s, 3), i16(s, 5), s[7] + if mapdepth == 16: + self.palette = ImagePalette.raw( + "BGRA;15Z", bytes(2 * start) + self.fp.read(2 * size) + ) + self.palette.mode = "RGBA" + elif mapdepth == 24: + self.palette = ImagePalette.raw( + "BGR", bytes(3 * start) + self.fp.read(3 * size) + ) + elif mapdepth == 32: + self.palette = ImagePalette.raw( + "BGRA", bytes(4 * start) + self.fp.read(4 * size) + ) + else: + msg = "unknown TGA map depth" + raise SyntaxError(msg) + + # setup tile descriptor + try: + rawmode = MODES[(imagetype & 7, depth)] + if imagetype & 8: + # compressed + self.tile = [ + ImageFile._Tile( + "tga_rle", + (0, 0) + self.size, + self.fp.tell(), + (rawmode, orientation, depth), + ) + ] + else: + self.tile = [ + ImageFile._Tile( + "raw", + (0, 0) + self.size, + self.fp.tell(), + (rawmode, 0, orientation), + ) + ] + except KeyError: + pass # cannot decode + + def load_end(self) -> None: + if self.mode == "RGBA": + assert self.fp is not None + self.fp.seek(-26, os.SEEK_END) + footer = self.fp.read(26) + if footer.endswith(b"TRUEVISION-XFILE.\x00"): + # version 2 + extension_offset = i32(footer) + if extension_offset: + self.fp.seek(extension_offset + 494) + attributes_type = self.fp.read(1) + if attributes_type == b"\x00": + # No alpha + self.im.fillband(3, 255) + + if self._flip_horizontally: + self.im = self.im.transpose(Image.Transpose.FLIP_LEFT_RIGHT) + + +# +# -------------------------------------------------------------------- +# Write TGA file + + +SAVE = { + "1": ("1", 1, 0, 3), + "L": ("L", 8, 0, 3), + "LA": ("LA", 16, 0, 3), + "P": ("P", 8, 1, 1), + "RGB": ("BGR", 24, 0, 2), + "RGBA": ("BGRA", 32, 0, 2), +} + + +def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None: + try: + rawmode, bits, colormaptype, imagetype = SAVE[im.mode] + except KeyError as e: + msg = f"cannot write mode {im.mode} as TGA" + raise OSError(msg) from e + + if "rle" in im.encoderinfo: + rle = im.encoderinfo["rle"] + else: + compression = im.encoderinfo.get("compression", im.info.get("compression")) + rle = compression == "tga_rle" + if rle: + imagetype += 8 + + id_section = im.encoderinfo.get("id_section", im.info.get("id_section", "")) + id_len = len(id_section) + if id_len > 255: + id_len = 255 + id_section = id_section[:255] + warnings.warn("id_section has been trimmed to 255 characters") + + if colormaptype: + palette = im.im.getpalette("RGB", "BGR") + colormaplength, colormapentry = len(palette) // 3, 24 + else: + colormaplength, colormapentry = 0, 0 + + if im.mode in ("LA", "RGBA"): + flags = 8 + else: + flags = 0 + + orientation = im.encoderinfo.get("orientation", im.info.get("orientation", -1)) + if orientation > 0: + flags = flags | 0x20 + + fp.write( + o8(id_len) + + o8(colormaptype) + + o8(imagetype) + + o16(0) # colormapfirst + + o16(colormaplength) + + o8(colormapentry) + + o16(0) + + o16(0) + + o16(im.size[0]) + + o16(im.size[1]) + + o8(bits) + + o8(flags) + ) + + if id_section: + fp.write(id_section) + + if colormaptype: + fp.write(palette) + + if rle: + ImageFile._save( + im, + fp, + [ImageFile._Tile("tga_rle", (0, 0) + im.size, 0, (rawmode, orientation))], + ) + else: + ImageFile._save( + im, + fp, + [ImageFile._Tile("raw", (0, 0) + im.size, 0, (rawmode, 0, orientation))], + ) + + # write targa version 2 footer + fp.write(b"\000" * 8 + b"TRUEVISION-XFILE." + b"\000") + + +# +# -------------------------------------------------------------------- +# Registry + + +Image.register_open(TgaImageFile.format, TgaImageFile) +Image.register_save(TgaImageFile.format, _save) + +Image.register_extensions(TgaImageFile.format, [".tga", ".icb", ".vda", ".vst"]) + +Image.register_mime(TgaImageFile.format, "image/x-tga") diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/TiffImagePlugin.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/TiffImagePlugin.py new file mode 100644 index 000000000..5094faa13 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/TiffImagePlugin.py @@ -0,0 +1,2353 @@ +# +# The Python Imaging Library. +# $Id$ +# +# TIFF file handling +# +# TIFF is a flexible, if somewhat aged, image file format originally +# defined by Aldus. Although TIFF supports a wide variety of pixel +# layouts and compression methods, the name doesn't really stand for +# "thousands of incompatible file formats," it just feels that way. +# +# To read TIFF data from a stream, the stream must be seekable. For +# progressive decoding, make sure to use TIFF files where the tag +# directory is placed first in the file. +# +# History: +# 1995-09-01 fl Created +# 1996-05-04 fl Handle JPEGTABLES tag +# 1996-05-18 fl Fixed COLORMAP support +# 1997-01-05 fl Fixed PREDICTOR support +# 1997-08-27 fl Added support for rational tags (from Perry Stoll) +# 1998-01-10 fl Fixed seek/tell (from Jan Blom) +# 1998-07-15 fl Use private names for internal variables +# 1999-06-13 fl Rewritten for PIL 1.0 (1.0) +# 2000-10-11 fl Additional fixes for Python 2.0 (1.1) +# 2001-04-17 fl Fixed rewind support (seek to frame 0) (1.2) +# 2001-05-12 fl Added write support for more tags (from Greg Couch) (1.3) +# 2001-12-18 fl Added workaround for broken Matrox library +# 2002-01-18 fl Don't mess up if photometric tag is missing (D. Alan Stewart) +# 2003-05-19 fl Check FILLORDER tag +# 2003-09-26 fl Added RGBa support +# 2004-02-24 fl Added DPI support; fixed rational write support +# 2005-02-07 fl Added workaround for broken Corel Draw 10 files +# 2006-01-09 fl Added support for float/double tags (from Russell Nelson) +# +# Copyright (c) 1997-2006 by Secret Labs AB. All rights reserved. +# Copyright (c) 1995-1997 by Fredrik Lundh +# +# See the README file for information on usage and redistribution. +# +from __future__ import annotations + +import io +import itertools +import logging +import math +import os +import struct +import warnings +from collections.abc import Callable, MutableMapping +from fractions import Fraction +from numbers import Number, Rational +from typing import IO, Any, cast + +from . import ExifTags, Image, ImageFile, ImageOps, ImagePalette, TiffTags +from ._binary import i16be as i16 +from ._binary import i32be as i32 +from ._binary import o8 +from ._util import DeferredError, is_path +from .TiffTags import TYPES + +TYPE_CHECKING = False +if TYPE_CHECKING: + from collections.abc import Iterator + from typing import NoReturn + + from ._typing import Buffer, IntegralLike, StrOrBytesPath + +logger = logging.getLogger(__name__) + +# Set these to true to force use of libtiff for reading or writing. +READ_LIBTIFF = False +WRITE_LIBTIFF = False +STRIP_SIZE = 65536 + +II = b"II" # little-endian (Intel style) +MM = b"MM" # big-endian (Motorola style) + +# +# -------------------------------------------------------------------- +# Read TIFF files + +# a few tag names, just to make the code below a bit more readable +OSUBFILETYPE = 255 +IMAGEWIDTH = 256 +IMAGELENGTH = 257 +BITSPERSAMPLE = 258 +COMPRESSION = 259 +PHOTOMETRIC_INTERPRETATION = 262 +FILLORDER = 266 +IMAGEDESCRIPTION = 270 +STRIPOFFSETS = 273 +SAMPLESPERPIXEL = 277 +ROWSPERSTRIP = 278 +STRIPBYTECOUNTS = 279 +X_RESOLUTION = 282 +Y_RESOLUTION = 283 +PLANAR_CONFIGURATION = 284 +RESOLUTION_UNIT = 296 +TRANSFERFUNCTION = 301 +SOFTWARE = 305 +DATE_TIME = 306 +ARTIST = 315 +PREDICTOR = 317 +COLORMAP = 320 +TILEWIDTH = 322 +TILELENGTH = 323 +TILEOFFSETS = 324 +TILEBYTECOUNTS = 325 +SUBIFD = 330 +EXTRASAMPLES = 338 +SAMPLEFORMAT = 339 +JPEGTABLES = 347 +YCBCRSUBSAMPLING = 530 +REFERENCEBLACKWHITE = 532 +COPYRIGHT = 33432 +IPTC_NAA_CHUNK = 33723 # newsphoto properties +PHOTOSHOP_CHUNK = 34377 # photoshop properties +ICCPROFILE = 34675 +EXIFIFD = 34665 +XMP = 700 +JPEGQUALITY = 65537 # pseudo-tag by libtiff + +# https://github.com/imagej/ImageJA/blob/master/src/main/java/ij/io/TiffDecoder.java +IMAGEJ_META_DATA_BYTE_COUNTS = 50838 +IMAGEJ_META_DATA = 50839 + +COMPRESSION_INFO = { + # Compression => pil compression name + 1: "raw", + 2: "tiff_ccitt", + 3: "group3", + 4: "group4", + 5: "tiff_lzw", + 6: "tiff_jpeg", # obsolete + 7: "jpeg", + 8: "tiff_adobe_deflate", + 32771: "tiff_raw_16", # 16-bit padding + 32773: "packbits", + 32809: "tiff_thunderscan", + 32946: "tiff_deflate", + 34676: "tiff_sgilog", + 34677: "tiff_sgilog24", + 34925: "lzma", + 50000: "zstd", + 50001: "webp", +} + +COMPRESSION_INFO_REV = {v: k for k, v in COMPRESSION_INFO.items()} + +OPEN_INFO = { + # (ByteOrder, PhotoInterpretation, SampleFormat, FillOrder, BitsPerSample, + # ExtraSamples) => mode, rawmode + (II, 0, (1,), 1, (1,), ()): ("1", "1;I"), + (MM, 0, (1,), 1, (1,), ()): ("1", "1;I"), + (II, 0, (1,), 2, (1,), ()): ("1", "1;IR"), + (MM, 0, (1,), 2, (1,), ()): ("1", "1;IR"), + (II, 1, (1,), 1, (1,), ()): ("1", "1"), + (MM, 1, (1,), 1, (1,), ()): ("1", "1"), + (II, 1, (1,), 2, (1,), ()): ("1", "1;R"), + (MM, 1, (1,), 2, (1,), ()): ("1", "1;R"), + (II, 0, (1,), 1, (2,), ()): ("L", "L;2I"), + (MM, 0, (1,), 1, (2,), ()): ("L", "L;2I"), + (II, 0, (1,), 2, (2,), ()): ("L", "L;2IR"), + (MM, 0, (1,), 2, (2,), ()): ("L", "L;2IR"), + (II, 1, (1,), 1, (2,), ()): ("L", "L;2"), + (MM, 1, (1,), 1, (2,), ()): ("L", "L;2"), + (II, 1, (1,), 2, (2,), ()): ("L", "L;2R"), + (MM, 1, (1,), 2, (2,), ()): ("L", "L;2R"), + (II, 0, (1,), 1, (4,), ()): ("L", "L;4I"), + (MM, 0, (1,), 1, (4,), ()): ("L", "L;4I"), + (II, 0, (1,), 2, (4,), ()): ("L", "L;4IR"), + (MM, 0, (1,), 2, (4,), ()): ("L", "L;4IR"), + (II, 1, (1,), 1, (4,), ()): ("L", "L;4"), + (MM, 1, (1,), 1, (4,), ()): ("L", "L;4"), + (II, 1, (1,), 2, (4,), ()): ("L", "L;4R"), + (MM, 1, (1,), 2, (4,), ()): ("L", "L;4R"), + (II, 0, (1,), 1, (8,), ()): ("L", "L;I"), + (MM, 0, (1,), 1, (8,), ()): ("L", "L;I"), + (II, 0, (1,), 2, (8,), ()): ("L", "L;IR"), + (MM, 0, (1,), 2, (8,), ()): ("L", "L;IR"), + (II, 1, (1,), 1, (8,), ()): ("L", "L"), + (MM, 1, (1,), 1, (8,), ()): ("L", "L"), + (II, 1, (2,), 1, (8,), ()): ("L", "L"), + (MM, 1, (2,), 1, (8,), ()): ("L", "L"), + (II, 1, (1,), 2, (8,), ()): ("L", "L;R"), + (MM, 1, (1,), 2, (8,), ()): ("L", "L;R"), + (II, 1, (1,), 1, (12,), ()): ("I;16", "I;12"), + (II, 0, (1,), 1, (16,), ()): ("I;16", "I;16"), + (II, 1, (1,), 1, (16,), ()): ("I;16", "I;16"), + (MM, 1, (1,), 1, (16,), ()): ("I;16B", "I;16B"), + (II, 1, (1,), 2, (16,), ()): ("I;16", "I;16R"), + (II, 1, (2,), 1, (16,), ()): ("I", "I;16S"), + (MM, 1, (2,), 1, (16,), ()): ("I", "I;16BS"), + (II, 0, (3,), 1, (32,), ()): ("F", "F;32F"), + (MM, 0, (3,), 1, (32,), ()): ("F", "F;32BF"), + (II, 1, (1,), 1, (32,), ()): ("I", "I;32N"), + (II, 1, (2,), 1, (32,), ()): ("I", "I;32S"), + (MM, 1, (2,), 1, (32,), ()): ("I", "I;32BS"), + (II, 1, (3,), 1, (32,), ()): ("F", "F;32F"), + (MM, 1, (3,), 1, (32,), ()): ("F", "F;32BF"), + (II, 1, (1,), 1, (8, 8), (2,)): ("LA", "LA"), + (MM, 1, (1,), 1, (8, 8), (2,)): ("LA", "LA"), + (II, 2, (1,), 1, (8, 8, 8), ()): ("RGB", "RGB"), + (MM, 2, (1,), 1, (8, 8, 8), ()): ("RGB", "RGB"), + (II, 2, (1,), 2, (8, 8, 8), ()): ("RGB", "RGB;R"), + (MM, 2, (1,), 2, (8, 8, 8), ()): ("RGB", "RGB;R"), + (II, 2, (1,), 1, (8, 8, 8, 8), ()): ("RGBA", "RGBA"), # missing ExtraSamples + (MM, 2, (1,), 1, (8, 8, 8, 8), ()): ("RGBA", "RGBA"), # missing ExtraSamples + (II, 2, (1,), 1, (8, 8, 8, 8), (0,)): ("RGB", "RGBX"), + (MM, 2, (1,), 1, (8, 8, 8, 8), (0,)): ("RGB", "RGBX"), + (II, 2, (1,), 1, (8, 8, 8, 8, 8), (0, 0)): ("RGB", "RGBXX"), + (MM, 2, (1,), 1, (8, 8, 8, 8, 8), (0, 0)): ("RGB", "RGBXX"), + (II, 2, (1,), 1, (8, 8, 8, 8, 8, 8), (0, 0, 0)): ("RGB", "RGBXXX"), + (MM, 2, (1,), 1, (8, 8, 8, 8, 8, 8), (0, 0, 0)): ("RGB", "RGBXXX"), + (II, 2, (1,), 1, (8, 8, 8, 8), (1,)): ("RGBA", "RGBa"), + (MM, 2, (1,), 1, (8, 8, 8, 8), (1,)): ("RGBA", "RGBa"), + (II, 2, (1,), 1, (8, 8, 8, 8, 8), (1, 0)): ("RGBA", "RGBaX"), + (MM, 2, (1,), 1, (8, 8, 8, 8, 8), (1, 0)): ("RGBA", "RGBaX"), + (II, 2, (1,), 1, (8, 8, 8, 8, 8, 8), (1, 0, 0)): ("RGBA", "RGBaXX"), + (MM, 2, (1,), 1, (8, 8, 8, 8, 8, 8), (1, 0, 0)): ("RGBA", "RGBaXX"), + (II, 2, (1,), 1, (8, 8, 8, 8), (2,)): ("RGBA", "RGBA"), + (MM, 2, (1,), 1, (8, 8, 8, 8), (2,)): ("RGBA", "RGBA"), + (II, 2, (1,), 1, (8, 8, 8, 8, 8), (2, 0)): ("RGBA", "RGBAX"), + (MM, 2, (1,), 1, (8, 8, 8, 8, 8), (2, 0)): ("RGBA", "RGBAX"), + (II, 2, (1,), 1, (8, 8, 8, 8, 8, 8), (2, 0, 0)): ("RGBA", "RGBAXX"), + (MM, 2, (1,), 1, (8, 8, 8, 8, 8, 8), (2, 0, 0)): ("RGBA", "RGBAXX"), + (II, 2, (1,), 1, (8, 8, 8, 8), (999,)): ("RGBA", "RGBA"), # Corel Draw 10 + (MM, 2, (1,), 1, (8, 8, 8, 8), (999,)): ("RGBA", "RGBA"), # Corel Draw 10 + (II, 2, (1,), 1, (16, 16, 16), ()): ("RGB", "RGB;16L"), + (MM, 2, (1,), 1, (16, 16, 16), ()): ("RGB", "RGB;16B"), + (II, 2, (1,), 1, (16, 16, 16, 16), ()): ("RGBA", "RGBA;16L"), + (MM, 2, (1,), 1, (16, 16, 16, 16), ()): ("RGBA", "RGBA;16B"), + (II, 2, (1,), 1, (16, 16, 16, 16), (0,)): ("RGB", "RGBX;16L"), + (MM, 2, (1,), 1, (16, 16, 16, 16), (0,)): ("RGB", "RGBX;16B"), + (II, 2, (1,), 1, (16, 16, 16, 16), (1,)): ("RGBA", "RGBa;16L"), + (MM, 2, (1,), 1, (16, 16, 16, 16), (1,)): ("RGBA", "RGBa;16B"), + (II, 2, (1,), 1, (16, 16, 16, 16), (2,)): ("RGBA", "RGBA;16L"), + (MM, 2, (1,), 1, (16, 16, 16, 16), (2,)): ("RGBA", "RGBA;16B"), + (II, 3, (1,), 1, (1,), ()): ("P", "P;1"), + (MM, 3, (1,), 1, (1,), ()): ("P", "P;1"), + (II, 3, (1,), 2, (1,), ()): ("P", "P;1R"), + (MM, 3, (1,), 2, (1,), ()): ("P", "P;1R"), + (II, 3, (1,), 1, (2,), ()): ("P", "P;2"), + (MM, 3, (1,), 1, (2,), ()): ("P", "P;2"), + (II, 3, (1,), 2, (2,), ()): ("P", "P;2R"), + (MM, 3, (1,), 2, (2,), ()): ("P", "P;2R"), + (II, 3, (1,), 1, (4,), ()): ("P", "P;4"), + (MM, 3, (1,), 1, (4,), ()): ("P", "P;4"), + (II, 3, (1,), 2, (4,), ()): ("P", "P;4R"), + (MM, 3, (1,), 2, (4,), ()): ("P", "P;4R"), + (II, 3, (1,), 1, (8,), ()): ("P", "P"), + (MM, 3, (1,), 1, (8,), ()): ("P", "P"), + (II, 3, (1,), 1, (8, 8), (0,)): ("P", "PX"), + (MM, 3, (1,), 1, (8, 8), (0,)): ("P", "PX"), + (II, 3, (1,), 1, (8, 8), (2,)): ("PA", "PA"), + (MM, 3, (1,), 1, (8, 8), (2,)): ("PA", "PA"), + (II, 3, (1,), 2, (8,), ()): ("P", "P;R"), + (MM, 3, (1,), 2, (8,), ()): ("P", "P;R"), + (II, 5, (1,), 1, (8, 8, 8, 8), ()): ("CMYK", "CMYK"), + (MM, 5, (1,), 1, (8, 8, 8, 8), ()): ("CMYK", "CMYK"), + (II, 5, (1,), 1, (8, 8, 8, 8, 8), (0,)): ("CMYK", "CMYKX"), + (MM, 5, (1,), 1, (8, 8, 8, 8, 8), (0,)): ("CMYK", "CMYKX"), + (II, 5, (1,), 1, (8, 8, 8, 8, 8, 8), (0, 0)): ("CMYK", "CMYKXX"), + (MM, 5, (1,), 1, (8, 8, 8, 8, 8, 8), (0, 0)): ("CMYK", "CMYKXX"), + (II, 5, (1,), 1, (16, 16, 16, 16), ()): ("CMYK", "CMYK;16L"), + (MM, 5, (1,), 1, (16, 16, 16, 16), ()): ("CMYK", "CMYK;16B"), + (II, 6, (1,), 1, (8,), ()): ("L", "L"), + (MM, 6, (1,), 1, (8,), ()): ("L", "L"), + # JPEG compressed images handled by LibTiff and auto-converted to RGBX + # Minimal Baseline TIFF requires YCbCr images to have 3 SamplesPerPixel + (II, 6, (1,), 1, (8, 8, 8), ()): ("RGB", "RGBX"), + (MM, 6, (1,), 1, (8, 8, 8), ()): ("RGB", "RGBX"), + (II, 8, (1,), 1, (8, 8, 8), ()): ("LAB", "LAB"), + (MM, 8, (1,), 1, (8, 8, 8), ()): ("LAB", "LAB"), +} + +MAX_SAMPLESPERPIXEL = max(len(key_tp[4]) for key_tp in OPEN_INFO) + +PREFIXES = [ + b"MM\x00\x2a", # Valid TIFF header with big-endian byte order + b"II\x2a\x00", # Valid TIFF header with little-endian byte order + b"MM\x2a\x00", # Invalid TIFF header, assume big-endian + b"II\x00\x2a", # Invalid TIFF header, assume little-endian + b"MM\x00\x2b", # BigTIFF with big-endian byte order + b"II\x2b\x00", # BigTIFF with little-endian byte order +] + + +def _accept(prefix: bytes) -> bool: + return prefix.startswith(tuple(PREFIXES)) + + +def _limit_rational( + val: float | Fraction | IFDRational, max_val: int +) -> tuple[IntegralLike, IntegralLike]: + inv = abs(val) > 1 + n_d = IFDRational(1 / val if inv else val).limit_rational(max_val) + return n_d[::-1] if inv else n_d + + +def _limit_signed_rational( + val: IFDRational, max_val: int, min_val: int +) -> tuple[IntegralLike, IntegralLike]: + frac = Fraction(val) + n_d: tuple[IntegralLike, IntegralLike] = frac.numerator, frac.denominator + + if min(float(i) for i in n_d) < min_val: + n_d = _limit_rational(val, abs(min_val)) + + n_d_float = tuple(float(i) for i in n_d) + if max(n_d_float) > max_val: + n_d = _limit_rational(n_d_float[0] / n_d_float[1], max_val) + + return n_d + + +## +# Wrapper for TIFF IFDs. + +_load_dispatch = {} +_write_dispatch = {} + + +def _delegate(op: str) -> Any: + def delegate( + self: IFDRational, *args: tuple[float, ...] + ) -> bool | float | Fraction: + return getattr(self._val, op)(*args) + + return delegate + + +class IFDRational(Rational): + """Implements a rational class where 0/0 is a legal value to match + the in the wild use of exif rationals. + + e.g., DigitalZoomRatio - 0.00/0.00 indicates that no digital zoom was used + """ + + """ If the denominator is 0, store this as a float('nan'), otherwise store + as a fractions.Fraction(). Delegate as appropriate + + """ + + __slots__ = ("_numerator", "_denominator", "_val") + + def __init__( + self, value: float | Fraction | IFDRational, denominator: int = 1 + ) -> None: + """ + :param value: either an integer numerator, a + float/rational/other number, or an IFDRational + :param denominator: Optional integer denominator + """ + self._val: Fraction | float + if isinstance(value, IFDRational): + self._numerator = value.numerator + self._denominator = value.denominator + self._val = value._val + return + + if isinstance(value, Fraction): + self._numerator = value.numerator + self._denominator = value.denominator + else: + if TYPE_CHECKING: + self._numerator = cast(IntegralLike, value) + else: + self._numerator = value + self._denominator = denominator + + if denominator == 0: + self._val = float("nan") + elif denominator == 1: + self._val = Fraction(value) + elif int(value) == value: + self._val = Fraction(int(value), denominator) + else: + self._val = Fraction(value / denominator) + + @property + def numerator(self) -> IntegralLike: + return self._numerator + + @property + def denominator(self) -> int: + return self._denominator + + def limit_rational(self, max_denominator: int) -> tuple[IntegralLike, int]: + """ + + :param max_denominator: Integer, the maximum denominator value + :returns: Tuple of (numerator, denominator) + """ + + if self.denominator == 0: + return self.numerator, self.denominator + + assert isinstance(self._val, Fraction) + f = self._val.limit_denominator(max_denominator) + return f.numerator, f.denominator + + def __repr__(self) -> str: + return str(float(self._val)) + + def __hash__(self) -> int: # type: ignore[override] + return self._val.__hash__() + + def __eq__(self, other: object) -> bool: + val = self._val + if isinstance(other, IFDRational): + other = other._val + if isinstance(other, float): + val = float(val) + return val == other + + def __getstate__(self) -> list[float | Fraction | IntegralLike]: + return [self._val, self._numerator, self._denominator] + + def __setstate__(self, state: list[float | Fraction | IntegralLike]) -> None: + IFDRational.__init__(self, 0) + _val, _numerator, _denominator = state + assert isinstance(_val, (float, Fraction)) + self._val = _val + if TYPE_CHECKING: + self._numerator = cast(IntegralLike, _numerator) + else: + self._numerator = _numerator + assert isinstance(_denominator, int) + self._denominator = _denominator + + """ a = ['add','radd', 'sub', 'rsub', 'mul', 'rmul', + 'truediv', 'rtruediv', 'floordiv', 'rfloordiv', + 'mod','rmod', 'pow','rpow', 'pos', 'neg', + 'abs', 'trunc', 'lt', 'gt', 'le', 'ge', 'bool', + 'ceil', 'floor', 'round'] + print("\n".join("__%s__ = _delegate('__%s__')" % (s,s) for s in a)) + """ + + __add__ = _delegate("__add__") + __radd__ = _delegate("__radd__") + __sub__ = _delegate("__sub__") + __rsub__ = _delegate("__rsub__") + __mul__ = _delegate("__mul__") + __rmul__ = _delegate("__rmul__") + __truediv__ = _delegate("__truediv__") + __rtruediv__ = _delegate("__rtruediv__") + __floordiv__ = _delegate("__floordiv__") + __rfloordiv__ = _delegate("__rfloordiv__") + __mod__ = _delegate("__mod__") + __rmod__ = _delegate("__rmod__") + __pow__ = _delegate("__pow__") + __rpow__ = _delegate("__rpow__") + __pos__ = _delegate("__pos__") + __neg__ = _delegate("__neg__") + __abs__ = _delegate("__abs__") + __trunc__ = _delegate("__trunc__") + __lt__ = _delegate("__lt__") + __gt__ = _delegate("__gt__") + __le__ = _delegate("__le__") + __ge__ = _delegate("__ge__") + __bool__ = _delegate("__bool__") + __ceil__ = _delegate("__ceil__") + __floor__ = _delegate("__floor__") + __round__ = _delegate("__round__") + # Python >= 3.11 + if hasattr(Fraction, "__int__"): + __int__ = _delegate("__int__") + + +_LoaderFunc = Callable[["ImageFileDirectory_v2", bytes, bool], Any] + + +def _register_loader(idx: int, size: int) -> Callable[[_LoaderFunc], _LoaderFunc]: + def decorator(func: _LoaderFunc) -> _LoaderFunc: + from .TiffTags import TYPES + + if func.__name__.startswith("load_"): + TYPES[idx] = func.__name__[5:].replace("_", " ") + _load_dispatch[idx] = size, func # noqa: F821 + return func + + return decorator + + +def _register_writer(idx: int) -> Callable[[Callable[..., Any]], Callable[..., Any]]: + def decorator(func: Callable[..., Any]) -> Callable[..., Any]: + _write_dispatch[idx] = func # noqa: F821 + return func + + return decorator + + +def _register_basic(idx_fmt_name: tuple[int, str, str]) -> None: + from .TiffTags import TYPES + + idx, fmt, name = idx_fmt_name + TYPES[idx] = name + size = struct.calcsize(f"={fmt}") + + def basic_handler( + self: ImageFileDirectory_v2, data: bytes, legacy_api: bool = True + ) -> tuple[Any, ...]: + return self._unpack(f"{len(data) // size}{fmt}", data) + + _load_dispatch[idx] = size, basic_handler # noqa: F821 + _write_dispatch[idx] = lambda self, *values: ( # noqa: F821 + b"".join(self._pack(fmt, value) for value in values) + ) + + +if TYPE_CHECKING: + _IFDv2Base = MutableMapping[int, Any] +else: + _IFDv2Base = MutableMapping + + +class ImageFileDirectory_v2(_IFDv2Base): + """This class represents a TIFF tag directory. To speed things up, we + don't decode tags unless they're asked for. + + Exposes a dictionary interface of the tags in the directory:: + + ifd = ImageFileDirectory_v2() + ifd[key] = 'Some Data' + ifd.tagtype[key] = TiffTags.ASCII + print(ifd[key]) + 'Some Data' + + Individual values are returned as the strings or numbers, sequences are + returned as tuples of the values. + + The tiff metadata type of each item is stored in a dictionary of + tag types in + :attr:`~PIL.TiffImagePlugin.ImageFileDirectory_v2.tagtype`. The types + are read from a tiff file, guessed from the type added, or added + manually. + + Data Structures: + + * ``self.tagtype = {}`` + + * Key: numerical TIFF tag number + * Value: integer corresponding to the data type from + :py:data:`.TiffTags.TYPES` + + .. versionadded:: 3.0.0 + + 'Internal' data structures: + + * ``self._tags_v2 = {}`` + + * Key: numerical TIFF tag number + * Value: decoded data, as tuple for multiple values + + * ``self._tagdata = {}`` + + * Key: numerical TIFF tag number + * Value: undecoded byte string from file + + * ``self._tags_v1 = {}`` + + * Key: numerical TIFF tag number + * Value: decoded data in the v1 format + + Tags will be found in the private attributes ``self._tagdata``, and in + ``self._tags_v2`` once decoded. + + ``self.legacy_api`` is a value for internal use, and shouldn't be changed + from outside code. In cooperation with + :py:class:`~PIL.TiffImagePlugin.ImageFileDirectory_v1`, if ``legacy_api`` + is true, then decoded tags will be populated into both ``_tags_v1`` and + ``_tags_v2``. ``_tags_v2`` will be used if this IFD is used in the TIFF + save routine. Tags should be read from ``_tags_v1`` if + ``legacy_api == true``. + + """ + + _load_dispatch: dict[int, tuple[int, _LoaderFunc]] = {} + _write_dispatch: dict[int, Callable[..., Any]] = {} + + def __init__( + self, + ifh: bytes = b"II\x2a\x00\x00\x00\x00\x00", + prefix: bytes | None = None, + group: int | None = None, + ) -> None: + """Initialize an ImageFileDirectory. + + To construct an ImageFileDirectory from a real file, pass the 8-byte + magic header to the constructor. To only set the endianness, pass it + as the 'prefix' keyword argument. + + :param ifh: One of the accepted magic headers (cf. PREFIXES); also sets + endianness. + :param prefix: Override the endianness of the file. + """ + if not _accept(ifh): + msg = f"not a TIFF file (header {repr(ifh)} not valid)" + raise SyntaxError(msg) + self._prefix = prefix if prefix is not None else ifh[:2] + if self._prefix == MM: + self._endian = ">" + elif self._prefix == II: + self._endian = "<" + else: + msg = "not a TIFF IFD" + raise SyntaxError(msg) + self._bigtiff = ifh[2] == 43 + self.group = group + self.tagtype: dict[int, int] = {} + """ Dictionary of tag types """ + self.reset() + self.next = ( + self._unpack("Q", ifh[8:])[0] + if self._bigtiff + else self._unpack("L", ifh[4:])[0] + ) + self._legacy_api = False + + prefix = property(lambda self: self._prefix) + offset = property(lambda self: self._offset) + + @property + def legacy_api(self) -> bool: + return self._legacy_api + + @legacy_api.setter + def legacy_api(self, value: bool) -> NoReturn: + msg = "Not allowing setting of legacy api" + raise Exception(msg) + + def reset(self) -> None: + self._tags_v1: dict[int, Any] = {} # will remain empty if legacy_api is false + self._tags_v2: dict[int, Any] = {} # main tag storage + self._tagdata: dict[int, bytes] = {} + self.tagtype = {} # added 2008-06-05 by Florian Hoech + self._next = None + self._offset: int | None = None + + def __str__(self) -> str: + return str(dict(self)) + + def named(self) -> dict[str, Any]: + """ + :returns: dict of name|key: value + + Returns the complete tag dictionary, with named tags where possible. + """ + return { + TiffTags.lookup(code, self.group).name: value + for code, value in self.items() + } + + def __len__(self) -> int: + return len(set(self._tagdata) | set(self._tags_v2)) + + def __getitem__(self, tag: int) -> Any: + if tag not in self._tags_v2: # unpack on the fly + data = self._tagdata[tag] + typ = self.tagtype[tag] + size, handler = self._load_dispatch[typ] + self[tag] = handler(self, data, self.legacy_api) # check type + val = self._tags_v2[tag] + if self.legacy_api and not isinstance(val, (tuple, bytes)): + val = (val,) + return val + + def __contains__(self, tag: object) -> bool: + return tag in self._tags_v2 or tag in self._tagdata + + def __setitem__(self, tag: int, value: Any) -> None: + self._setitem(tag, value, self.legacy_api) + + def _setitem(self, tag: int, value: Any, legacy_api: bool) -> None: + basetypes = (Number, bytes, str) + + info = TiffTags.lookup(tag, self.group) + values = [value] if isinstance(value, basetypes) else value + + if tag not in self.tagtype: + if info.type: + self.tagtype[tag] = info.type + else: + self.tagtype[tag] = TiffTags.UNDEFINED + if all(isinstance(v, IFDRational) for v in values): + for v in values: + assert isinstance(v, IFDRational) + if v < 0: + self.tagtype[tag] = TiffTags.SIGNED_RATIONAL + break + else: + self.tagtype[tag] = TiffTags.RATIONAL + elif all(isinstance(v, int) for v in values): + short = True + signed_short = True + long = True + for v in values: + assert isinstance(v, int) + if short and not (0 <= v < 2**16): + short = False + if signed_short and not (-(2**15) < v < 2**15): + signed_short = False + if long and v < 0: + long = False + if short: + self.tagtype[tag] = TiffTags.SHORT + elif signed_short: + self.tagtype[tag] = TiffTags.SIGNED_SHORT + elif long: + self.tagtype[tag] = TiffTags.LONG + else: + self.tagtype[tag] = TiffTags.SIGNED_LONG + elif all(isinstance(v, float) for v in values): + self.tagtype[tag] = TiffTags.DOUBLE + elif all(isinstance(v, str) for v in values): + self.tagtype[tag] = TiffTags.ASCII + elif all(isinstance(v, bytes) for v in values): + self.tagtype[tag] = TiffTags.BYTE + + if self.tagtype[tag] == TiffTags.UNDEFINED: + values = [ + v.encode("ascii", "replace") if isinstance(v, str) else v + for v in values + ] + elif self.tagtype[tag] == TiffTags.RATIONAL: + values = [float(v) if isinstance(v, int) else v for v in values] + + is_ifd = self.tagtype[tag] == TiffTags.LONG and isinstance(values, dict) + if not is_ifd: + values = tuple( + info.cvt_enum(value) if isinstance(value, str) else value + for value in values + ) + + dest = self._tags_v1 if legacy_api else self._tags_v2 + + # Three branches: + # Spec'd length == 1, Actual length 1, store as element + # Spec'd length == 1, Actual > 1, Warn and truncate. Formerly barfed. + # No Spec, Actual length 1, Formerly (<4.2) returned a 1 element tuple. + # Don't mess with the legacy api, since it's frozen. + if not is_ifd and ( + (info.length == 1) + or self.tagtype[tag] == TiffTags.BYTE + or (info.length is None and len(values) == 1 and not legacy_api) + ): + # Don't mess with the legacy api, since it's frozen. + if legacy_api and self.tagtype[tag] in [ + TiffTags.RATIONAL, + TiffTags.SIGNED_RATIONAL, + ]: # rationals + values = (values,) + try: + (dest[tag],) = values + except ValueError: + # We've got a builtin tag with 1 expected entry + warnings.warn( + f"Metadata Warning, tag {tag} had too many entries: " + f"{len(values)}, expected 1" + ) + dest[tag] = values[0] + + else: + # Spec'd length > 1 or undefined + # Unspec'd, and length > 1 + dest[tag] = values + + def __delitem__(self, tag: int) -> None: + self._tags_v2.pop(tag, None) + self._tags_v1.pop(tag, None) + self._tagdata.pop(tag, None) + + def __iter__(self) -> Iterator[int]: + return iter(set(self._tagdata) | set(self._tags_v2)) + + def _unpack(self, fmt: str, data: bytes) -> tuple[Any, ...]: + return struct.unpack(self._endian + fmt, data) + + def _pack(self, fmt: str, *values: Any) -> bytes: + return struct.pack(self._endian + fmt, *values) + + list( + map( + _register_basic, + [ + (TiffTags.SHORT, "H", "short"), + (TiffTags.LONG, "L", "long"), + (TiffTags.SIGNED_BYTE, "b", "signed byte"), + (TiffTags.SIGNED_SHORT, "h", "signed short"), + (TiffTags.SIGNED_LONG, "l", "signed long"), + (TiffTags.FLOAT, "f", "float"), + (TiffTags.DOUBLE, "d", "double"), + (TiffTags.IFD, "L", "long"), + (TiffTags.LONG8, "Q", "long8"), + ], + ) + ) + + @_register_loader(1, 1) # Basic type, except for the legacy API. + def load_byte(self, data: bytes, legacy_api: bool = True) -> bytes: + return data + + @_register_writer(1) # Basic type, except for the legacy API. + def write_byte(self, data: bytes | int | IFDRational) -> bytes: + if isinstance(data, IFDRational): + data = int(data) + if isinstance(data, int): + data = bytes((data,)) + return data + + @_register_loader(2, 1) + def load_string(self, data: bytes, legacy_api: bool = True) -> str: + if data.endswith(b"\0"): + data = data[:-1] + return data.decode("latin-1", "replace") + + @_register_writer(2) + def write_string(self, value: str | bytes | int) -> bytes: + # remerge of https://github.com/python-pillow/Pillow/pull/1416 + if isinstance(value, int): + value = str(value) + if not isinstance(value, bytes): + value = value.encode("ascii", "replace") + return value + b"\0" + + @_register_loader(5, 8) + def load_rational( + self, data: bytes, legacy_api: bool = True + ) -> tuple[tuple[int, int] | IFDRational, ...]: + vals = self._unpack(f"{len(data) // 4}L", data) + + def combine(a: int, b: int) -> tuple[int, int] | IFDRational: + return (a, b) if legacy_api else IFDRational(a, b) + + return tuple(combine(num, denom) for num, denom in zip(vals[::2], vals[1::2])) + + @_register_writer(5) + def write_rational(self, *values: IFDRational) -> bytes: + return b"".join( + self._pack("2L", *_limit_rational(frac, 2**32 - 1)) for frac in values + ) + + @_register_loader(7, 1) + def load_undefined(self, data: bytes, legacy_api: bool = True) -> bytes: + return data + + @_register_writer(7) + def write_undefined(self, value: bytes | int | IFDRational) -> bytes: + if isinstance(value, IFDRational): + value = int(value) + if isinstance(value, int): + value = str(value).encode("ascii", "replace") + return value + + @_register_loader(10, 8) + def load_signed_rational( + self, data: bytes, legacy_api: bool = True + ) -> tuple[tuple[int, int] | IFDRational, ...]: + vals = self._unpack(f"{len(data) // 4}l", data) + + def combine(a: int, b: int) -> tuple[int, int] | IFDRational: + return (a, b) if legacy_api else IFDRational(a, b) + + return tuple(combine(num, denom) for num, denom in zip(vals[::2], vals[1::2])) + + @_register_writer(10) + def write_signed_rational(self, *values: IFDRational) -> bytes: + return b"".join( + self._pack("2l", *_limit_signed_rational(frac, 2**31 - 1, -(2**31))) + for frac in values + ) + + def _ensure_read(self, fp: IO[bytes], size: int) -> bytes: + ret = fp.read(size) + if len(ret) != size: + msg = ( + "Corrupt EXIF data. " + f"Expecting to read {size} bytes but only got {len(ret)}. " + ) + raise OSError(msg) + return ret + + def load(self, fp: IO[bytes]) -> None: + self.reset() + self._offset = fp.tell() + + try: + tag_count = ( + self._unpack("Q", self._ensure_read(fp, 8)) + if self._bigtiff + else self._unpack("H", self._ensure_read(fp, 2)) + )[0] + for i in range(tag_count): + tag, typ, count, data = ( + self._unpack("HHQ8s", self._ensure_read(fp, 20)) + if self._bigtiff + else self._unpack("HHL4s", self._ensure_read(fp, 12)) + ) + + tagname = TiffTags.lookup(tag, self.group).name + typname = TYPES.get(typ, "unknown") + msg = f"tag: {tagname} ({tag}) - type: {typname} ({typ})" + + try: + unit_size, handler = self._load_dispatch[typ] + except KeyError: + logger.debug("%s - unsupported type %s", msg, typ) + continue # ignore unsupported type + size = count * unit_size + if size > (8 if self._bigtiff else 4): + here = fp.tell() + (offset,) = self._unpack("Q" if self._bigtiff else "L", data) + msg += f" Tag Location: {here} - Data Location: {offset}" + fp.seek(offset) + data = ImageFile._safe_read(fp, size) + fp.seek(here) + else: + data = data[:size] + + if len(data) != size: + warnings.warn( + "Possibly corrupt EXIF data. " + f"Expecting to read {size} bytes but only got {len(data)}." + f" Skipping tag {tag}" + ) + logger.debug(msg) + continue + + if not data: + logger.debug(msg) + continue + + self._tagdata[tag] = data + self.tagtype[tag] = typ + + msg += " - value: " + msg += f"" if size > 32 else repr(data) + + logger.debug(msg) + + (self.next,) = ( + self._unpack("Q", self._ensure_read(fp, 8)) + if self._bigtiff + else self._unpack("L", self._ensure_read(fp, 4)) + ) + except OSError as msg: + warnings.warn(str(msg)) + return + + def _get_ifh(self) -> bytes: + ifh = self._prefix + self._pack("H", 43 if self._bigtiff else 42) + if self._bigtiff: + ifh += self._pack("HH", 8, 0) + ifh += self._pack("Q", 16) if self._bigtiff else self._pack("L", 8) + + return ifh + + def tobytes(self, offset: int = 0) -> bytes: + # FIXME What about tagdata? + result = self._pack("Q" if self._bigtiff else "H", len(self._tags_v2)) + + entries: list[tuple[int, int, int, bytes, bytes]] = [] + + fmt = "Q" if self._bigtiff else "L" + fmt_size = 8 if self._bigtiff else 4 + offset += ( + len(result) + len(self._tags_v2) * (20 if self._bigtiff else 12) + fmt_size + ) + stripoffsets = None + + # pass 1: convert tags to binary format + # always write tags in ascending order + for tag, value in sorted(self._tags_v2.items()): + if tag == STRIPOFFSETS: + stripoffsets = len(entries) + typ = self.tagtype[tag] + logger.debug("Tag %s, Type: %s, Value: %s", tag, typ, repr(value)) + is_ifd = typ == TiffTags.LONG and isinstance(value, dict) + if is_ifd: + ifd = ImageFileDirectory_v2(self._get_ifh(), group=tag) + values = self._tags_v2[tag] + for ifd_tag, ifd_value in values.items(): + ifd[ifd_tag] = ifd_value + data = ifd.tobytes(offset) + else: + values = value if isinstance(value, tuple) else (value,) + data = self._write_dispatch[typ](self, *values) + + tagname = TiffTags.lookup(tag, self.group).name + typname = "ifd" if is_ifd else TYPES.get(typ, "unknown") + msg = f"save: {tagname} ({tag}) - type: {typname} ({typ}) - value: " + msg += f"" if len(data) >= 16 else str(values) + logger.debug(msg) + + # count is sum of lengths for string and arbitrary data + if is_ifd: + count = 1 + elif typ in [TiffTags.BYTE, TiffTags.ASCII, TiffTags.UNDEFINED]: + count = len(data) + else: + count = len(values) + # figure out if data fits into the entry + if len(data) <= fmt_size: + entries.append((tag, typ, count, data.ljust(fmt_size, b"\0"), b"")) + else: + entries.append((tag, typ, count, self._pack(fmt, offset), data)) + offset += (len(data) + 1) // 2 * 2 # pad to word + + # update strip offset data to point beyond auxiliary data + if stripoffsets is not None: + tag, typ, count, value, data = entries[stripoffsets] + if data: + size, handler = self._load_dispatch[typ] + values = [val + offset for val in handler(self, data, self.legacy_api)] + data = self._write_dispatch[typ](self, *values) + else: + value = self._pack(fmt, self._unpack(fmt, value)[0] + offset) + entries[stripoffsets] = tag, typ, count, value, data + + # pass 2: write entries to file + for tag, typ, count, value, data in entries: + logger.debug("%s %s %s %s %s", tag, typ, count, repr(value), repr(data)) + result += self._pack( + "HHQ8s" if self._bigtiff else "HHL4s", tag, typ, count, value + ) + + # -- overwrite here for multi-page -- + result += self._pack(fmt, 0) # end of entries + + # pass 3: write auxiliary data to file + for tag, typ, count, value, data in entries: + result += data + if len(data) & 1: + result += b"\0" + + return result + + def save(self, fp: IO[bytes]) -> int: + if fp.tell() == 0: # skip TIFF header on subsequent pages + fp.write(self._get_ifh()) + + offset = fp.tell() + result = self.tobytes(offset) + fp.write(result) + return offset + len(result) + + +ImageFileDirectory_v2._load_dispatch = _load_dispatch +ImageFileDirectory_v2._write_dispatch = _write_dispatch +for idx, name in TYPES.items(): + name = name.replace(" ", "_") + setattr(ImageFileDirectory_v2, f"load_{name}", _load_dispatch[idx][1]) + setattr(ImageFileDirectory_v2, f"write_{name}", _write_dispatch[idx]) +del _load_dispatch, _write_dispatch, idx, name + + +# Legacy ImageFileDirectory support. +class ImageFileDirectory_v1(ImageFileDirectory_v2): + """This class represents the **legacy** interface to a TIFF tag directory. + + Exposes a dictionary interface of the tags in the directory:: + + ifd = ImageFileDirectory_v1() + ifd[key] = 'Some Data' + ifd.tagtype[key] = TiffTags.ASCII + print(ifd[key]) + ('Some Data',) + + Also contains a dictionary of tag types as read from the tiff image file, + :attr:`~PIL.TiffImagePlugin.ImageFileDirectory_v1.tagtype`. + + Values are returned as a tuple. + + .. deprecated:: 3.0.0 + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self._legacy_api = True + + tags = property(lambda self: self._tags_v1) + tagdata = property(lambda self: self._tagdata) + + # defined in ImageFileDirectory_v2 + tagtype: dict[int, int] + """Dictionary of tag types""" + + @classmethod + def from_v2(cls, original: ImageFileDirectory_v2) -> ImageFileDirectory_v1: + """Returns an + :py:class:`~PIL.TiffImagePlugin.ImageFileDirectory_v1` + instance with the same data as is contained in the original + :py:class:`~PIL.TiffImagePlugin.ImageFileDirectory_v2` + instance. + + :returns: :py:class:`~PIL.TiffImagePlugin.ImageFileDirectory_v1` + + """ + + ifd = cls(prefix=original.prefix) + ifd._tagdata = original._tagdata + ifd.tagtype = original.tagtype + ifd.next = original.next # an indicator for multipage tiffs + return ifd + + def to_v2(self) -> ImageFileDirectory_v2: + """Returns an + :py:class:`~PIL.TiffImagePlugin.ImageFileDirectory_v2` + instance with the same data as is contained in the original + :py:class:`~PIL.TiffImagePlugin.ImageFileDirectory_v1` + instance. + + :returns: :py:class:`~PIL.TiffImagePlugin.ImageFileDirectory_v2` + + """ + + ifd = ImageFileDirectory_v2(prefix=self.prefix) + ifd._tagdata = dict(self._tagdata) + ifd.tagtype = dict(self.tagtype) + ifd._tags_v2 = dict(self._tags_v2) + return ifd + + def __contains__(self, tag: object) -> bool: + return tag in self._tags_v1 or tag in self._tagdata + + def __len__(self) -> int: + return len(set(self._tagdata) | set(self._tags_v1)) + + def __iter__(self) -> Iterator[int]: + return iter(set(self._tagdata) | set(self._tags_v1)) + + def __setitem__(self, tag: int, value: Any) -> None: + for legacy_api in (False, True): + self._setitem(tag, value, legacy_api) + + def __getitem__(self, tag: int) -> Any: + if tag not in self._tags_v1: # unpack on the fly + data = self._tagdata[tag] + typ = self.tagtype[tag] + size, handler = self._load_dispatch[typ] + for legacy in (False, True): + self._setitem(tag, handler(self, data, legacy), legacy) + val = self._tags_v1[tag] + if not isinstance(val, (tuple, bytes)): + val = (val,) + return val + + +# undone -- switch this pointer +ImageFileDirectory = ImageFileDirectory_v1 + + +## +# Image plugin for TIFF files. + + +class TiffImageFile(ImageFile.ImageFile): + format = "TIFF" + format_description = "Adobe TIFF" + _close_exclusive_fp_after_loading = False + + def __init__( + self, + fp: StrOrBytesPath | IO[bytes], + filename: str | bytes | None = None, + ) -> None: + self.tag_v2: ImageFileDirectory_v2 + """ Image file directory (tag dictionary) """ + + self.tag: ImageFileDirectory_v1 + """ Legacy tag entries """ + + super().__init__(fp, filename) + + def _open(self) -> None: + """Open the first image in a TIFF file""" + + # Header + assert self.fp is not None + ifh = self.fp.read(8) + if ifh[2] == 43: + ifh += self.fp.read(8) + + self.tag_v2 = ImageFileDirectory_v2(ifh) + + # setup frame pointers + self.__first = self.__next = self.tag_v2.next + self.__frame = -1 + self._fp = self.fp + self._frame_pos: list[int] = [] + self._n_frames: int | None = None + + logger.debug("*** TiffImageFile._open ***") + logger.debug("- __first: %s", self.__first) + logger.debug("- ifh: %s", repr(ifh)) # Use repr to avoid str(bytes) + + # and load the first frame + self._seek(0) + + @property + def n_frames(self) -> int: + current_n_frames = self._n_frames + if current_n_frames is None: + current = self.tell() + self._seek(len(self._frame_pos)) + while self._n_frames is None: + self._seek(self.tell() + 1) + self.seek(current) + assert self._n_frames is not None + return self._n_frames + + def seek(self, frame: int) -> None: + """Select a given frame as current image""" + if not self._seek_check(frame): + return + self._seek(frame) + if self._im is not None and ( + self.im.size != self._tile_size + or self.im.mode != self.mode + or self.readonly + ): + self._im = None + + def _seek(self, frame: int) -> None: + if isinstance(self._fp, DeferredError): + raise self._fp.ex + self.fp = self._fp + + while len(self._frame_pos) <= frame: + if not self.__next: + msg = "no more images in TIFF file" + raise EOFError(msg) + logger.debug( + "Seeking to frame %s, on frame %s, __next %s, location: %s", + frame, + self.__frame, + self.__next, + self.fp.tell(), + ) + if self.__next >= 2**63: + msg = "Unable to seek to frame" + raise ValueError(msg) + self.fp.seek(self.__next) + self._frame_pos.append(self.__next) + logger.debug("Loading tags, location: %s", self.fp.tell()) + self.tag_v2.load(self.fp) + if self.tag_v2.next in self._frame_pos: + # This IFD has already been processed + # Declare this to be the end of the image + self.__next = 0 + else: + self.__next = self.tag_v2.next + if self.__next == 0: + self._n_frames = frame + 1 + if len(self._frame_pos) == 1: + self.is_animated = self.__next != 0 + self.__frame += 1 + self.fp.seek(self._frame_pos[frame]) + self.tag_v2.load(self.fp) + if XMP in self.tag_v2: + xmp = self.tag_v2[XMP] + if isinstance(xmp, tuple) and len(xmp) == 1: + xmp = xmp[0] + self.info["xmp"] = xmp + elif "xmp" in self.info: + del self.info["xmp"] + self._reload_exif() + # fill the legacy tag/ifd entries + self.tag = self.ifd = ImageFileDirectory_v1.from_v2(self.tag_v2) + self.__frame = frame + self._setup() + + def tell(self) -> int: + """Return the current frame number""" + return self.__frame + + def get_photoshop_blocks(self) -> dict[int, dict[str, bytes]]: + """ + Returns a dictionary of Photoshop "Image Resource Blocks". + The keys are the image resource ID. For more information, see + https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/#50577409_pgfId-1037727 + + :returns: Photoshop "Image Resource Blocks" in a dictionary. + """ + blocks = {} + val = self.tag_v2.get(ExifTags.Base.ImageResources) + if val: + while val.startswith(b"8BIM") and len(val) >= 12: + id = i16(val[4:6]) + n = math.ceil((val[6] + 1) / 2) * 2 + try: + size = i32(val[6 + n : 10 + n]) + except struct.error: + break + data = val[10 + n : 10 + n + size] + blocks[id] = {"data": data} + + val = val[math.ceil((10 + n + size) / 2) * 2 :] + return blocks + + def load(self) -> Image.core.PixelAccess | None: + if self.tile and self.use_load_libtiff: + return self._load_libtiff() + return super().load() + + def load_prepare(self) -> None: + if self._im is None: + Image._decompression_bomb_check(self._tile_size) + self.im = Image.core.new(self.mode, self._tile_size) + ImageFile.ImageFile.load_prepare(self) + + def load_end(self) -> None: + # allow closing if we're on the first frame, there's no next + # This is the ImageFile.load path only, libtiff specific below. + if not self.is_animated: + self._close_exclusive_fp_after_loading = True + + # load IFD data from fp before it is closed + exif = self.getexif() + for key in TiffTags.TAGS_V2_GROUPS: + if key not in exif: + continue + exif.get_ifd(key) + + ImageOps.exif_transpose(self, in_place=True) + if ExifTags.Base.Orientation in self.tag_v2: + del self.tag_v2[ExifTags.Base.Orientation] + + def _load_libtiff(self) -> Image.core.PixelAccess | None: + """Overload method triggered when we detect a compressed tiff + Calls out to libtiff""" + + Image.Image.load(self) + + self.load_prepare() + + if not len(self.tile) == 1: + msg = "Not exactly one tile" + raise OSError(msg) + + # (self._compression, (extents tuple), + # 0, (rawmode, self._compression, fp)) + extents = self.tile[0][1] + args = self.tile[0][3] + + # To be nice on memory footprint, if there's a + # file descriptor, use that instead of reading + # into a string in python. + assert self.fp is not None + try: + fp = hasattr(self.fp, "fileno") and self.fp.fileno() + # flush the file descriptor, prevents error on pypy 2.4+ + # should also eliminate the need for fp.tell + # in _seek + if hasattr(self.fp, "flush"): + self.fp.flush() + except OSError: + # io.BytesIO have a fileno, but returns an OSError if + # it doesn't use a file descriptor. + fp = False + + if fp: + assert isinstance(args, tuple) + args_list = list(args) + args_list[2] = fp + args = tuple(args_list) + + decoder = Image._getdecoder(self.mode, "libtiff", args, self.decoderconfig) + try: + decoder.setimage(self.im, extents) + except ValueError as e: + msg = "Couldn't set the image" + raise OSError(msg) from e + + close_self_fp = self._exclusive_fp and not self.is_animated + if hasattr(self.fp, "getvalue"): + # We've got a stringio like thing passed in. Yay for all in memory. + # The decoder needs the entire file in one shot, so there's not + # a lot we can do here other than give it the entire file. + # unless we could do something like get the address of the + # underlying string for stringio. + # + # Rearranging for supporting byteio items, since they have a fileno + # that returns an OSError if there's no underlying fp. Easier to + # deal with here by reordering. + logger.debug("have getvalue. just sending in a string from getvalue") + n, err = decoder.decode(self.fp.getvalue()) + elif fp: + # we've got a actual file on disk, pass in the fp. + logger.debug("have fileno, calling fileno version of the decoder.") + if not close_self_fp: + self.fp.seek(0) + # Save and restore the file position, because libtiff will move it + # outside of the Python runtime, and that will confuse + # io.BufferedReader and possible others. + # NOTE: This must use os.lseek(), and not fp.tell()/fp.seek(), + # because the buffer read head already may not equal the actual + # file position, and fp.seek() may just adjust it's internal + # pointer and not actually seek the OS file handle. + pos = os.lseek(fp, 0, os.SEEK_CUR) + # 4 bytes, otherwise the trace might error out + n, err = decoder.decode(b"fpfp") + os.lseek(fp, pos, os.SEEK_SET) + else: + # we have something else. + logger.debug("don't have fileno or getvalue. just reading") + self.fp.seek(0) + # UNDONE -- so much for that buffer size thing. + n, err = decoder.decode(self.fp.read()) + + self.tile = [] + self.readonly = 0 + + self.load_end() + + if close_self_fp: + self.fp.close() + self.fp = None # might be shared + + if err < 0: + msg = f"decoder error {err}" + raise OSError(msg) + + return Image.Image.load(self) + + def _setup(self) -> None: + """Setup this image object based on current tags""" + + if 0xBC01 in self.tag_v2: + msg = "Windows Media Photo files not yet supported" + raise OSError(msg) + + # extract relevant tags + self._compression = COMPRESSION_INFO[self.tag_v2.get(COMPRESSION, 1)] + self._planar_configuration = self.tag_v2.get(PLANAR_CONFIGURATION, 1) + + # photometric is a required tag, but not everyone is reading + # the specification + photo = self.tag_v2.get(PHOTOMETRIC_INTERPRETATION, 0) + + # old style jpeg compression images most certainly are YCbCr + if self._compression == "tiff_jpeg": + photo = 6 + + fillorder = self.tag_v2.get(FILLORDER, 1) + + logger.debug("*** Summary ***") + logger.debug("- compression: %s", self._compression) + logger.debug("- photometric_interpretation: %s", photo) + logger.debug("- planar_configuration: %s", self._planar_configuration) + logger.debug("- fill_order: %s", fillorder) + logger.debug("- YCbCr subsampling: %s", self.tag_v2.get(YCBCRSUBSAMPLING)) + + # size + try: + xsize = self.tag_v2[IMAGEWIDTH] + ysize = self.tag_v2[IMAGELENGTH] + except KeyError as e: + msg = "Missing dimensions" + raise TypeError(msg) from e + if not isinstance(xsize, int) or not isinstance(ysize, int): + msg = "Invalid dimensions" + raise ValueError(msg) + self._tile_size = xsize, ysize + orientation = self.tag_v2.get(ExifTags.Base.Orientation) + if orientation in (5, 6, 7, 8): + self._size = ysize, xsize + else: + self._size = xsize, ysize + + logger.debug("- size: %s", self.size) + + sample_format = self.tag_v2.get(SAMPLEFORMAT, (1,)) + if len(sample_format) > 1 and max(sample_format) == min(sample_format): + # SAMPLEFORMAT is properly per band, so an RGB image will + # be (1,1,1). But, we don't support per band pixel types, + # and anything more than one band is a uint8. So, just + # take the first element. Revisit this if adding support + # for more exotic images. + sample_format = (sample_format[0],) + + bps_tuple = self.tag_v2.get(BITSPERSAMPLE, (1,)) + extra_tuple = self.tag_v2.get(EXTRASAMPLES, ()) + samples_per_pixel = self.tag_v2.get( + SAMPLESPERPIXEL, + 3 if self._compression == "tiff_jpeg" and photo in (2, 6) else 1, + ) + if photo in (2, 6, 8): # RGB, YCbCr, LAB + bps_count = 3 + elif photo == 5: # CMYK + bps_count = 4 + else: + bps_count = 1 + if self._planar_configuration == 2 and extra_tuple and max(extra_tuple) == 0: + # If components are stored separately, + # then unspecified extra components at the end can be ignored + bps_tuple = bps_tuple[: -len(extra_tuple)] + samples_per_pixel -= len(extra_tuple) + extra_tuple = () + bps_count += len(extra_tuple) + bps_actual_count = len(bps_tuple) + + if samples_per_pixel > MAX_SAMPLESPERPIXEL: + # DOS check, samples_per_pixel can be a Long, and we extend the tuple below + logger.error( + "More samples per pixel than can be decoded: %s", samples_per_pixel + ) + msg = "Invalid value for samples per pixel" + raise SyntaxError(msg) + + if samples_per_pixel < bps_actual_count: + # If a file has more values in bps_tuple than expected, + # remove the excess. + bps_tuple = bps_tuple[:samples_per_pixel] + elif samples_per_pixel > bps_actual_count and bps_actual_count == 1: + # If a file has only one value in bps_tuple, when it should have more, + # presume it is the same number of bits for all of the samples. + bps_tuple = bps_tuple * samples_per_pixel + + if len(bps_tuple) != samples_per_pixel: + msg = "unknown data organization" + raise SyntaxError(msg) + + # mode: check photometric interpretation and bits per pixel + key = ( + self.tag_v2.prefix, + photo, + sample_format, + fillorder, + bps_tuple, + extra_tuple, + ) + logger.debug("format key: %s", key) + try: + self._mode, rawmode = OPEN_INFO[key] + except KeyError as e: + logger.debug("- unsupported format") + msg = "unknown pixel mode" + raise SyntaxError(msg) from e + + logger.debug("- raw mode: %s", rawmode) + logger.debug("- pil mode: %s", self.mode) + + self.info["compression"] = self._compression + + xres = self.tag_v2.get(X_RESOLUTION, 1) + yres = self.tag_v2.get(Y_RESOLUTION, 1) + + if xres and yres: + resunit = self.tag_v2.get(RESOLUTION_UNIT) + if resunit == 2: # dots per inch + self.info["dpi"] = (xres, yres) + elif resunit == 3: # dots per centimeter. convert to dpi + self.info["dpi"] = (xres * 2.54, yres * 2.54) + elif resunit is None: # used to default to 1, but now 2) + self.info["dpi"] = (xres, yres) + # For backward compatibility, + # we also preserve the old behavior + self.info["resolution"] = xres, yres + else: # No absolute unit of measurement + self.info["resolution"] = xres, yres + + # build tile descriptors + x = y = layer = 0 + self.tile = [] + self.use_load_libtiff = READ_LIBTIFF or self._compression != "raw" + if self.use_load_libtiff: + # Decoder expects entire file as one tile. + # There's a buffer size limit in load (64k) + # so large g4 images will fail if we use that + # function. + # + # Setup the one tile for the whole image, then + # use the _load_libtiff function. + + # libtiff handles the fillmode for us, so 1;IR should + # actually be 1;I. Including the R double reverses the + # bits, so stripes of the image are reversed. See + # https://github.com/python-pillow/Pillow/issues/279 + if fillorder == 2: + # Replace fillorder with fillorder=1 + key = key[:3] + (1,) + key[4:] + logger.debug("format key: %s", key) + # this should always work, since all the + # fillorder==2 modes have a corresponding + # fillorder=1 mode + self._mode, rawmode = OPEN_INFO[key] + # YCbCr images with new jpeg compression with pixels in one plane + # unpacked straight into RGB values + if ( + photo == 6 + and self._compression == "jpeg" + and self._planar_configuration == 1 + ): + rawmode = "RGB" + # libtiff always returns the bytes in native order. + # we're expecting image byte order. So, if the rawmode + # contains I;16, we need to convert from native to image + # byte order. + elif rawmode == "I;16": + rawmode = "I;16N" + elif rawmode.endswith((";16B", ";16L")): + rawmode = rawmode[:-1] + "N" + + # Offset in the tile tuple is 0, we go from 0,0 to + # w,h, and we only do this once -- eds + a = (rawmode, self._compression, False, self.tag_v2.offset) + self.tile.append(ImageFile._Tile("libtiff", (0, 0, xsize, ysize), 0, a)) + + elif STRIPOFFSETS in self.tag_v2 or TILEOFFSETS in self.tag_v2: + # striped image + if STRIPOFFSETS in self.tag_v2: + offsets = self.tag_v2[STRIPOFFSETS] + h = self.tag_v2.get(ROWSPERSTRIP, ysize) + w = xsize + else: + # tiled image + offsets = self.tag_v2[TILEOFFSETS] + tilewidth = self.tag_v2.get(TILEWIDTH) + h = self.tag_v2.get(TILELENGTH) + if not isinstance(tilewidth, int) or not isinstance(h, int): + msg = "Invalid tile dimensions" + raise ValueError(msg) + w = tilewidth + + if w == xsize and h == ysize and self._planar_configuration != 2: + # Every tile covers the image. Only use the last offset + offsets = offsets[-1:] + + for offset in offsets: + if x + w > xsize: + stride = w * sum(bps_tuple) / 8 # bytes per line + else: + stride = 0 + + tile_rawmode = rawmode + if self._planar_configuration == 2: + # each band on it's own layer + tile_rawmode = rawmode[layer] + # adjust stride width accordingly + stride /= bps_count + + args = (tile_rawmode, int(stride), 1) + self.tile.append( + ImageFile._Tile( + self._compression, + (x, y, min(x + w, xsize), min(y + h, ysize)), + offset, + args, + ) + ) + x += w + if x >= xsize: + x, y = 0, y + h + if y >= ysize: + y = 0 + layer += 1 + else: + logger.debug("- unsupported data organization") + msg = "unknown data organization" + raise SyntaxError(msg) + + # Fix up info. + if ICCPROFILE in self.tag_v2: + self.info["icc_profile"] = self.tag_v2[ICCPROFILE] + + # fixup palette descriptor + + if self.mode in ["P", "PA"]: + palette = [o8(b // 256) for b in self.tag_v2[COLORMAP]] + self.palette = ImagePalette.raw("RGB;L", b"".join(palette)) + + +# +# -------------------------------------------------------------------- +# Write TIFF files + +# little endian is default except for image modes with +# explicit big endian byte-order + +SAVE_INFO = { + # mode => rawmode, byteorder, photometrics, + # sampleformat, bitspersample, extra + "1": ("1", II, 1, 1, (1,), None), + "L": ("L", II, 1, 1, (8,), None), + "LA": ("LA", II, 1, 1, (8, 8), 2), + "P": ("P", II, 3, 1, (8,), None), + "PA": ("PA", II, 3, 1, (8, 8), 2), + "I": ("I;32S", II, 1, 2, (32,), None), + "I;16": ("I;16", II, 1, 1, (16,), None), + "I;16L": ("I;16L", II, 1, 1, (16,), None), + "F": ("F;32F", II, 1, 3, (32,), None), + "RGB": ("RGB", II, 2, 1, (8, 8, 8), None), + "RGBX": ("RGBX", II, 2, 1, (8, 8, 8, 8), 0), + "RGBA": ("RGBA", II, 2, 1, (8, 8, 8, 8), 2), + "CMYK": ("CMYK", II, 5, 1, (8, 8, 8, 8), None), + "YCbCr": ("YCbCr", II, 6, 1, (8, 8, 8), None), + "LAB": ("LAB", II, 8, 1, (8, 8, 8), None), + "I;16B": ("I;16B", MM, 1, 1, (16,), None), +} + + +def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None: + try: + rawmode, prefix, photo, format, bits, extra = SAVE_INFO[im.mode] + except KeyError as e: + msg = f"cannot write mode {im.mode} as TIFF" + raise OSError(msg) from e + + encoderinfo = im.encoderinfo + encoderconfig = im.encoderconfig + + ifd = ImageFileDirectory_v2(prefix=prefix) + if encoderinfo.get("big_tiff"): + ifd._bigtiff = True + + try: + compression = encoderinfo["compression"] + except KeyError: + compression = im.info.get("compression") + if isinstance(compression, int): + # compression value may be from BMP. Ignore it + compression = None + if compression is None: + compression = "raw" + elif compression == "tiff_jpeg": + # OJPEG is obsolete, so use new-style JPEG compression instead + compression = "jpeg" + elif compression == "tiff_deflate": + compression = "tiff_adobe_deflate" + + libtiff = WRITE_LIBTIFF or compression != "raw" + + # required for color libtiff images + ifd[PLANAR_CONFIGURATION] = 1 + + ifd[IMAGEWIDTH] = im.size[0] + ifd[IMAGELENGTH] = im.size[1] + + # write any arbitrary tags passed in as an ImageFileDirectory + if "tiffinfo" in encoderinfo: + info = encoderinfo["tiffinfo"] + elif "exif" in encoderinfo: + info = encoderinfo["exif"] + if isinstance(info, bytes): + exif = Image.Exif() + exif.load(info) + info = exif + else: + info = {} + logger.debug("Tiffinfo Keys: %s", list(info)) + if isinstance(info, ImageFileDirectory_v1): + info = info.to_v2() + for key in info: + if isinstance(info, Image.Exif) and key in TiffTags.TAGS_V2_GROUPS: + ifd[key] = info.get_ifd(key) + else: + ifd[key] = info.get(key) + try: + ifd.tagtype[key] = info.tagtype[key] + except Exception: + pass # might not be an IFD. Might not have populated type + + legacy_ifd = {} + if hasattr(im, "tag"): + legacy_ifd = im.tag.to_v2() + + supplied_tags = {**legacy_ifd, **getattr(im, "tag_v2", {})} + if supplied_tags.get(PLANAR_CONFIGURATION) == 2 and EXTRASAMPLES in supplied_tags: + # If the image used separate component planes, + # then EXTRASAMPLES should be ignored when saving contiguously + if SAMPLESPERPIXEL in supplied_tags: + supplied_tags[SAMPLESPERPIXEL] -= len(supplied_tags[EXTRASAMPLES]) + del supplied_tags[EXTRASAMPLES] + for tag in ( + # IFD offset that may not be correct in the saved image + EXIFIFD, + # Determined by the image format and should not be copied from legacy_ifd. + SAMPLEFORMAT, + ): + if tag in supplied_tags: + del supplied_tags[tag] + + # additions written by Greg Couch, gregc@cgl.ucsf.edu + # inspired by image-sig posting from Kevin Cazabon, kcazabon@home.com + if hasattr(im, "tag_v2"): + # preserve tags from original TIFF image file + for key in ( + RESOLUTION_UNIT, + X_RESOLUTION, + Y_RESOLUTION, + IPTC_NAA_CHUNK, + PHOTOSHOP_CHUNK, + XMP, + ): + if key in im.tag_v2: + if key == IPTC_NAA_CHUNK and im.tag_v2.tagtype[key] not in ( + TiffTags.BYTE, + TiffTags.UNDEFINED, + ): + del supplied_tags[key] + else: + ifd[key] = im.tag_v2[key] + ifd.tagtype[key] = im.tag_v2.tagtype[key] + + # preserve ICC profile (should also work when saving other formats + # which support profiles as TIFF) -- 2008-06-06 Florian Hoech + icc = encoderinfo.get("icc_profile", im.info.get("icc_profile")) + if icc: + ifd[ICCPROFILE] = icc + + for key, name in [ + (IMAGEDESCRIPTION, "description"), + (X_RESOLUTION, "resolution"), + (Y_RESOLUTION, "resolution"), + (X_RESOLUTION, "x_resolution"), + (Y_RESOLUTION, "y_resolution"), + (RESOLUTION_UNIT, "resolution_unit"), + (SOFTWARE, "software"), + (DATE_TIME, "date_time"), + (ARTIST, "artist"), + (COPYRIGHT, "copyright"), + ]: + if name in encoderinfo: + ifd[key] = encoderinfo[name] + + dpi = encoderinfo.get("dpi") + if dpi: + ifd[RESOLUTION_UNIT] = 2 + ifd[X_RESOLUTION] = dpi[0] + ifd[Y_RESOLUTION] = dpi[1] + + if bits != (1,): + ifd[BITSPERSAMPLE] = bits + if len(bits) != 1: + ifd[SAMPLESPERPIXEL] = len(bits) + if extra is not None: + ifd[EXTRASAMPLES] = extra + if format != 1: + ifd[SAMPLEFORMAT] = format + + if PHOTOMETRIC_INTERPRETATION not in ifd: + ifd[PHOTOMETRIC_INTERPRETATION] = photo + elif im.mode in ("1", "L") and ifd[PHOTOMETRIC_INTERPRETATION] == 0: + if im.mode == "1": + inverted_im = im.copy() + px = inverted_im.load() + if px is not None: + for y in range(inverted_im.height): + for x in range(inverted_im.width): + px[x, y] = 0 if px[x, y] == 255 else 255 + im = inverted_im + else: + im = ImageOps.invert(im) + + if im.mode in ["P", "PA"]: + lut = im.im.getpalette("RGB", "RGB;L") + colormap = [] + colors = len(lut) // 3 + for i in range(3): + colormap += [v * 256 for v in lut[colors * i : colors * (i + 1)]] + colormap += [0] * (256 - colors) + ifd[COLORMAP] = colormap + # data orientation + w, h = ifd[IMAGEWIDTH], ifd[IMAGELENGTH] + stride = len(bits) * ((w * bits[0] + 7) // 8) + if ROWSPERSTRIP not in ifd: + # aim for given strip size (64 KB by default) when using libtiff writer + if libtiff: + im_strip_size = encoderinfo.get("strip_size", STRIP_SIZE) + rows_per_strip = 1 if stride == 0 else min(im_strip_size // stride, h) + # JPEG encoder expects multiple of 8 rows + if compression == "jpeg": + rows_per_strip = min(((rows_per_strip + 7) // 8) * 8, h) + else: + rows_per_strip = h + if rows_per_strip == 0: + rows_per_strip = 1 + ifd[ROWSPERSTRIP] = rows_per_strip + strip_byte_counts = 1 if stride == 0 else stride * ifd[ROWSPERSTRIP] + strips_per_image = (h + ifd[ROWSPERSTRIP] - 1) // ifd[ROWSPERSTRIP] + if strip_byte_counts >= 2**16: + ifd.tagtype[STRIPBYTECOUNTS] = TiffTags.LONG + ifd[STRIPBYTECOUNTS] = (strip_byte_counts,) * (strips_per_image - 1) + ( + stride * h - strip_byte_counts * (strips_per_image - 1), + ) + ifd[STRIPOFFSETS] = tuple( + range(0, strip_byte_counts * strips_per_image, strip_byte_counts) + ) # this is adjusted by IFD writer + # no compression by default: + ifd[COMPRESSION] = COMPRESSION_INFO_REV.get(compression, 1) + + if im.mode == "YCbCr": + for tag, default_value in { + YCBCRSUBSAMPLING: (1, 1), + REFERENCEBLACKWHITE: (0, 255, 128, 255, 128, 255), + }.items(): + ifd.setdefault(tag, default_value) + + blocklist = [TILEWIDTH, TILELENGTH, TILEOFFSETS, TILEBYTECOUNTS] + if libtiff: + if "quality" in encoderinfo: + quality = encoderinfo["quality"] + if not isinstance(quality, int) or quality < 0 or quality > 100: + msg = "Invalid quality setting" + raise ValueError(msg) + if compression != "jpeg": + msg = "quality setting only supported for 'jpeg' compression" + raise ValueError(msg) + ifd[JPEGQUALITY] = quality + + logger.debug("Saving using libtiff encoder") + logger.debug("Items: %s", sorted(ifd.items())) + _fp = 0 + if hasattr(fp, "fileno"): + try: + fp.seek(0) + _fp = fp.fileno() + except io.UnsupportedOperation: + pass + + # optional types for non core tags + types = {} + # STRIPOFFSETS and STRIPBYTECOUNTS are added by the library + # based on the data in the strip. + # OSUBFILETYPE is deprecated. + # The other tags expect arrays with a certain length (fixed or depending on + # BITSPERSAMPLE, etc), passing arrays with a different length will result in + # segfaults. Block these tags until we add extra validation. + # SUBIFD may also cause a segfault. + blocklist += [ + OSUBFILETYPE, + REFERENCEBLACKWHITE, + STRIPBYTECOUNTS, + STRIPOFFSETS, + TRANSFERFUNCTION, + SUBIFD, + ] + + # bits per sample is a single short in the tiff directory, not a list. + atts: dict[int, Any] = {BITSPERSAMPLE: bits[0]} + # Merge the ones that we have with (optional) more bits from + # the original file, e.g x,y resolution so that we can + # save(load('')) == original file. + for tag, value in itertools.chain(ifd.items(), supplied_tags.items()): + # Libtiff can only process certain core items without adding + # them to the custom dictionary. + # Custom items are supported for int, float, unicode, string and byte + # values. Other types and tuples require a tagtype. + if tag not in TiffTags.LIBTIFF_CORE: + if tag in TiffTags.TAGS_V2_GROUPS: + types[tag] = TiffTags.LONG8 + elif tag in ifd.tagtype: + types[tag] = ifd.tagtype[tag] + elif isinstance(value, (int, float, str, bytes)) or ( + isinstance(value, tuple) + and all(isinstance(v, (int, float, IFDRational)) for v in value) + ): + type = TiffTags.lookup(tag).type + if type: + types[tag] = type + if tag not in atts and tag not in blocklist: + if isinstance(value, str): + atts[tag] = value.encode("ascii", "replace") + b"\0" + elif isinstance(value, IFDRational): + atts[tag] = float(value) + else: + atts[tag] = value + + if SAMPLEFORMAT in atts and len(atts[SAMPLEFORMAT]) == 1: + atts[SAMPLEFORMAT] = atts[SAMPLEFORMAT][0] + + logger.debug("Converted items: %s", sorted(atts.items())) + + # libtiff always expects the bytes in native order. + # we're storing image byte order. So, if the rawmode + # contains I;16, we need to convert from native to image + # byte order. + if im.mode in ("I;16", "I;16B", "I;16L"): + rawmode = "I;16N" + + # Pass tags as sorted list so that the tags are set in a fixed order. + # This is required by libtiff for some tags. For example, the JPEGQUALITY + # pseudo tag requires that the COMPRESS tag was already set. + tags = list(atts.items()) + tags.sort() + a = (rawmode, compression, _fp, filename, tags, types) + encoder = Image._getencoder(im.mode, "libtiff", a, encoderconfig) + encoder.setimage(im.im, (0, 0) + im.size) + while True: + errcode, data = encoder.encode(ImageFile.MAXBLOCK)[1:] + if not _fp: + fp.write(data) + if errcode: + break + if errcode < 0: + msg = f"encoder error {errcode} when writing image file" + raise OSError(msg) + + else: + for tag in blocklist: + del ifd[tag] + offset = ifd.save(fp) + + ImageFile._save( + im, + fp, + [ImageFile._Tile("raw", (0, 0) + im.size, offset, (rawmode, stride, 1))], + ) + + # -- helper for multi-page save -- + if "_debug_multipage" in encoderinfo: + # just to access o32 and o16 (using correct byte order) + setattr(im, "_debug_multipage", ifd) + + +class AppendingTiffWriter(io.BytesIO): + fieldSizes = [ + 0, # None + 1, # byte + 1, # ascii + 2, # short + 4, # long + 8, # rational + 1, # sbyte + 1, # undefined + 2, # sshort + 4, # slong + 8, # srational + 4, # float + 8, # double + 4, # ifd + 2, # unicode + 4, # complex + 8, # long8 + ] + + Tags = { + 273, # StripOffsets + 288, # FreeOffsets + 324, # TileOffsets + 519, # JPEGQTables + 520, # JPEGDCTables + 521, # JPEGACTables + } + + def __init__(self, fn: StrOrBytesPath | IO[bytes], new: bool = False) -> None: + self.f: IO[bytes] + if is_path(fn): + self.name = fn + self.close_fp = True + try: + self.f = open(fn, "w+b" if new else "r+b") + except OSError: + self.f = open(fn, "w+b") + else: + self.f = cast(IO[bytes], fn) + self.close_fp = False + self.beginning = self.f.tell() + self.setup() + + def setup(self) -> None: + # Reset everything. + self.f.seek(self.beginning, os.SEEK_SET) + + self.whereToWriteNewIFDOffset: int | None = None + self.offsetOfNewPage = 0 + + self.IIMM = iimm = self.f.read(4) + self._bigtiff = b"\x2b" in iimm + if not iimm: + # empty file - first page + self.isFirst = True + return + + self.isFirst = False + if iimm not in PREFIXES: + msg = "Invalid TIFF file header" + raise RuntimeError(msg) + + self.setEndian("<" if iimm.startswith(II) else ">") + + if self._bigtiff: + self.f.seek(4, os.SEEK_CUR) + self.skipIFDs() + self.goToEnd() + + def finalize(self) -> None: + if self.isFirst: + return + + # fix offsets + self.f.seek(self.offsetOfNewPage) + + iimm = self.f.read(4) + if not iimm: + # Make it easy to finish a frame without committing to a new one. + return + + if iimm != self.IIMM: + msg = "IIMM of new page doesn't match IIMM of first page" + raise RuntimeError(msg) + + if self._bigtiff: + self.f.seek(4, os.SEEK_CUR) + ifd_offset = self._read(8 if self._bigtiff else 4) + ifd_offset += self.offsetOfNewPage + assert self.whereToWriteNewIFDOffset is not None + self.f.seek(self.whereToWriteNewIFDOffset) + self._write(ifd_offset, 8 if self._bigtiff else 4) + self.f.seek(ifd_offset) + self.fixIFD() + + def newFrame(self) -> None: + # Call this to finish a frame. + self.finalize() + self.setup() + + def __enter__(self) -> AppendingTiffWriter: + return self + + def __exit__(self, *args: object) -> None: + if self.close_fp: + self.close() + + def tell(self) -> int: + return self.f.tell() - self.offsetOfNewPage + + def seek(self, offset: int, whence: int = io.SEEK_SET) -> int: + """ + :param offset: Distance to seek. + :param whence: Whether the distance is relative to the start, + end or current position. + :returns: The resulting position, relative to the start. + """ + if whence == os.SEEK_SET: + offset += self.offsetOfNewPage + + self.f.seek(offset, whence) + return self.tell() + + def goToEnd(self) -> None: + self.f.seek(0, os.SEEK_END) + pos = self.f.tell() + + # pad to 16 byte boundary + pad_bytes = 16 - pos % 16 + if 0 < pad_bytes < 16: + self.f.write(bytes(pad_bytes)) + self.offsetOfNewPage = self.f.tell() + + def setEndian(self, endian: str) -> None: + self.endian = endian + self.longFmt = f"{self.endian}L" + self.shortFmt = f"{self.endian}H" + self.tagFormat = f"{self.endian}HH" + ("Q" if self._bigtiff else "L") + + def skipIFDs(self) -> None: + while True: + ifd_offset = self._read(8 if self._bigtiff else 4) + if ifd_offset == 0: + self.whereToWriteNewIFDOffset = self.f.tell() - ( + 8 if self._bigtiff else 4 + ) + break + + self.f.seek(ifd_offset) + num_tags = self._read(8 if self._bigtiff else 2) + self.f.seek(num_tags * (20 if self._bigtiff else 12), os.SEEK_CUR) + + def write(self, data: Buffer, /) -> int: + return self.f.write(data) + + def _fmt(self, field_size: int) -> str: + try: + return {2: "H", 4: "L", 8: "Q"}[field_size] + except KeyError: + msg = "offset is not supported" + raise RuntimeError(msg) + + def _read(self, field_size: int) -> int: + (value,) = struct.unpack( + self.endian + self._fmt(field_size), self.f.read(field_size) + ) + return value + + def readShort(self) -> int: + return self._read(2) + + def readLong(self) -> int: + return self._read(4) + + @staticmethod + def _verify_bytes_written(bytes_written: int | None, expected: int) -> None: + if bytes_written is not None and bytes_written != expected: + msg = f"wrote only {bytes_written} bytes but wanted {expected}" + raise RuntimeError(msg) + + def _rewriteLast( + self, value: int, field_size: int, new_field_size: int = 0 + ) -> None: + self.f.seek(-field_size, os.SEEK_CUR) + if not new_field_size: + new_field_size = field_size + bytes_written = self.f.write( + struct.pack(self.endian + self._fmt(new_field_size), value) + ) + self._verify_bytes_written(bytes_written, new_field_size) + + def rewriteLastShortToLong(self, value: int) -> None: + self._rewriteLast(value, 2, 4) + + def rewriteLastShort(self, value: int) -> None: + return self._rewriteLast(value, 2) + + def rewriteLastLong(self, value: int) -> None: + return self._rewriteLast(value, 4) + + def _write(self, value: int, field_size: int) -> None: + bytes_written = self.f.write( + struct.pack(self.endian + self._fmt(field_size), value) + ) + self._verify_bytes_written(bytes_written, field_size) + + def writeShort(self, value: int) -> None: + self._write(value, 2) + + def writeLong(self, value: int) -> None: + self._write(value, 4) + + def close(self) -> None: + self.finalize() + if self.close_fp: + self.f.close() + + def fixIFD(self) -> None: + num_tags = self._read(8 if self._bigtiff else 2) + + for i in range(num_tags): + tag, field_type, count = struct.unpack( + self.tagFormat, self.f.read(12 if self._bigtiff else 8) + ) + + field_size = self.fieldSizes[field_type] + total_size = field_size * count + fmt_size = 8 if self._bigtiff else 4 + is_local = total_size <= fmt_size + if not is_local: + offset = self._read(fmt_size) + self.offsetOfNewPage + self._rewriteLast(offset, fmt_size) + + if tag in self.Tags: + cur_pos = self.f.tell() + + logger.debug( + "fixIFD: %s (%d) - type: %s (%d) - type size: %d - count: %d", + TiffTags.lookup(tag).name, + tag, + TYPES.get(field_type, "unknown"), + field_type, + field_size, + count, + ) + + if is_local: + self._fixOffsets(count, field_size) + self.f.seek(cur_pos + fmt_size) + else: + self.f.seek(offset) + self._fixOffsets(count, field_size) + self.f.seek(cur_pos) + + elif is_local: + # skip the locally stored value that is not an offset + self.f.seek(fmt_size, os.SEEK_CUR) + + def _fixOffsets(self, count: int, field_size: int) -> None: + for i in range(count): + offset = self._read(field_size) + offset += self.offsetOfNewPage + + new_field_size = 0 + if self._bigtiff and field_size in (2, 4) and offset >= 2**32: + # offset is now too large - we must convert long to long8 + new_field_size = 8 + elif field_size == 2 and offset >= 2**16: + # offset is now too large - we must convert short to long + new_field_size = 4 + if new_field_size: + if count != 1: + msg = "not implemented" + raise RuntimeError(msg) # XXX TODO + + # simple case - the offset is just one and therefore it is + # local (not referenced with another offset) + self._rewriteLast(offset, field_size, new_field_size) + # Move back past the new offset, past 'count', and before 'field_type' + rewind = -new_field_size - 4 - 2 + self.f.seek(rewind, os.SEEK_CUR) + self.writeShort(new_field_size) # rewrite the type + self.f.seek(2 - rewind, os.SEEK_CUR) + else: + self._rewriteLast(offset, field_size) + + def fixOffsets( + self, count: int, isShort: bool = False, isLong: bool = False + ) -> None: + if isShort: + field_size = 2 + elif isLong: + field_size = 4 + else: + field_size = 0 + return self._fixOffsets(count, field_size) + + +def _save_all(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None: + append_images = list(im.encoderinfo.get("append_images", [])) + if not hasattr(im, "n_frames") and not append_images: + return _save(im, fp, filename) + + cur_idx = im.tell() + try: + with AppendingTiffWriter(fp) as tf: + for ims in [im] + append_images: + encoderinfo = ims._attach_default_encoderinfo(im) + if not hasattr(ims, "encoderconfig"): + ims.encoderconfig = () + nfr = getattr(ims, "n_frames", 1) + + for idx in range(nfr): + ims.seek(idx) + ims.load() + _save(ims, tf, filename) + tf.newFrame() + ims.encoderinfo = encoderinfo + finally: + im.seek(cur_idx) + + +# +# -------------------------------------------------------------------- +# Register + +Image.register_open(TiffImageFile.format, TiffImageFile, _accept) +Image.register_save(TiffImageFile.format, _save) +Image.register_save_all(TiffImageFile.format, _save_all) + +Image.register_extensions(TiffImageFile.format, [".tif", ".tiff"]) + +Image.register_mime(TiffImageFile.format, "image/tiff") diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/TiffTags.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/TiffTags.py new file mode 100644 index 000000000..613a3b7de --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/TiffTags.py @@ -0,0 +1,566 @@ +# +# The Python Imaging Library. +# $Id$ +# +# TIFF tags +# +# This module provides clear-text names for various well-known +# TIFF tags. the TIFF codec works just fine without it. +# +# Copyright (c) Secret Labs AB 1999. +# +# See the README file for information on usage and redistribution. +# + +## +# This module provides constants and clear-text names for various +# well-known TIFF tags. +## +from __future__ import annotations + +from typing import NamedTuple + + +class _TagInfo(NamedTuple): + value: int | None + name: str + type: int | None + length: int | None + enum: dict[str, int] + + +class TagInfo(_TagInfo): + __slots__: list[str] = [] + + def __new__( + cls, + value: int | None = None, + name: str = "unknown", + type: int | None = None, + length: int | None = None, + enum: dict[str, int] | None = None, + ) -> TagInfo: + return super().__new__(cls, value, name, type, length, enum or {}) + + def cvt_enum(self, value: str) -> int | str: + # Using get will call hash(value), which can be expensive + # for some types (e.g. Fraction). Since self.enum is rarely + # used, it's usually better to test it first. + return self.enum.get(value, value) if self.enum else value + + +def lookup(tag: int, group: int | None = None) -> TagInfo: + """ + :param tag: Integer tag number + :param group: Which :py:data:`~PIL.TiffTags.TAGS_V2_GROUPS` to look in + + .. versionadded:: 8.3.0 + + :returns: Taginfo namedtuple, From the ``TAGS_V2`` info if possible, + otherwise just populating the value and name from ``TAGS``. + If the tag is not recognized, "unknown" is returned for the name + + """ + + if group is not None: + info = TAGS_V2_GROUPS[group].get(tag) if group in TAGS_V2_GROUPS else None + else: + info = TAGS_V2.get(tag) + return info or TagInfo(tag, TAGS.get(tag, "unknown")) + + +## +# Map tag numbers to tag info. +# +# id: (Name, Type, Length[, enum_values]) +# +# The length here differs from the length in the tiff spec. For +# numbers, the tiff spec is for the number of fields returned. We +# agree here. For string-like types, the tiff spec uses the length of +# field in bytes. In Pillow, we are using the number of expected +# fields, in general 1 for string-like types. + + +BYTE = 1 +ASCII = 2 +SHORT = 3 +LONG = 4 +RATIONAL = 5 +SIGNED_BYTE = 6 +UNDEFINED = 7 +SIGNED_SHORT = 8 +SIGNED_LONG = 9 +SIGNED_RATIONAL = 10 +FLOAT = 11 +DOUBLE = 12 +IFD = 13 +LONG8 = 16 + +_tags_v2: dict[int, tuple[str, int, int] | tuple[str, int, int, dict[str, int]]] = { + 254: ("NewSubfileType", LONG, 1), + 255: ("SubfileType", SHORT, 1), + 256: ("ImageWidth", LONG, 1), + 257: ("ImageLength", LONG, 1), + 258: ("BitsPerSample", SHORT, 0), + 259: ( + "Compression", + SHORT, + 1, + { + "Uncompressed": 1, + "CCITT 1d": 2, + "Group 3 Fax": 3, + "Group 4 Fax": 4, + "LZW": 5, + "JPEG": 6, + "PackBits": 32773, + }, + ), + 262: ( + "PhotometricInterpretation", + SHORT, + 1, + { + "WhiteIsZero": 0, + "BlackIsZero": 1, + "RGB": 2, + "RGB Palette": 3, + "Transparency Mask": 4, + "CMYK": 5, + "YCbCr": 6, + "CieLAB": 8, + "CFA": 32803, # TIFF/EP, Adobe DNG + "LinearRaw": 32892, # Adobe DNG + }, + ), + 263: ("Threshholding", SHORT, 1), + 264: ("CellWidth", SHORT, 1), + 265: ("CellLength", SHORT, 1), + 266: ("FillOrder", SHORT, 1), + 269: ("DocumentName", ASCII, 1), + 270: ("ImageDescription", ASCII, 1), + 271: ("Make", ASCII, 1), + 272: ("Model", ASCII, 1), + 273: ("StripOffsets", LONG, 0), + 274: ("Orientation", SHORT, 1), + 277: ("SamplesPerPixel", SHORT, 1), + 278: ("RowsPerStrip", LONG, 1), + 279: ("StripByteCounts", LONG, 0), + 280: ("MinSampleValue", SHORT, 0), + 281: ("MaxSampleValue", SHORT, 0), + 282: ("XResolution", RATIONAL, 1), + 283: ("YResolution", RATIONAL, 1), + 284: ("PlanarConfiguration", SHORT, 1, {"Contiguous": 1, "Separate": 2}), + 285: ("PageName", ASCII, 1), + 286: ("XPosition", RATIONAL, 1), + 287: ("YPosition", RATIONAL, 1), + 288: ("FreeOffsets", LONG, 1), + 289: ("FreeByteCounts", LONG, 1), + 290: ("GrayResponseUnit", SHORT, 1), + 291: ("GrayResponseCurve", SHORT, 0), + 292: ("T4Options", LONG, 1), + 293: ("T6Options", LONG, 1), + 296: ("ResolutionUnit", SHORT, 1, {"none": 1, "inch": 2, "cm": 3}), + 297: ("PageNumber", SHORT, 2), + 301: ("TransferFunction", SHORT, 0), + 305: ("Software", ASCII, 1), + 306: ("DateTime", ASCII, 1), + 315: ("Artist", ASCII, 1), + 316: ("HostComputer", ASCII, 1), + 317: ("Predictor", SHORT, 1, {"none": 1, "Horizontal Differencing": 2}), + 318: ("WhitePoint", RATIONAL, 2), + 319: ("PrimaryChromaticities", RATIONAL, 6), + 320: ("ColorMap", SHORT, 0), + 321: ("HalftoneHints", SHORT, 2), + 322: ("TileWidth", LONG, 1), + 323: ("TileLength", LONG, 1), + 324: ("TileOffsets", LONG, 0), + 325: ("TileByteCounts", LONG, 0), + 330: ("SubIFDs", LONG, 0), + 332: ("InkSet", SHORT, 1), + 333: ("InkNames", ASCII, 1), + 334: ("NumberOfInks", SHORT, 1), + 336: ("DotRange", SHORT, 0), + 337: ("TargetPrinter", ASCII, 1), + 338: ("ExtraSamples", SHORT, 0), + 339: ("SampleFormat", SHORT, 0), + 340: ("SMinSampleValue", DOUBLE, 0), + 341: ("SMaxSampleValue", DOUBLE, 0), + 342: ("TransferRange", SHORT, 6), + 347: ("JPEGTables", UNDEFINED, 1), + # obsolete JPEG tags + 512: ("JPEGProc", SHORT, 1), + 513: ("JPEGInterchangeFormat", LONG, 1), + 514: ("JPEGInterchangeFormatLength", LONG, 1), + 515: ("JPEGRestartInterval", SHORT, 1), + 517: ("JPEGLosslessPredictors", SHORT, 0), + 518: ("JPEGPointTransforms", SHORT, 0), + 519: ("JPEGQTables", LONG, 0), + 520: ("JPEGDCTables", LONG, 0), + 521: ("JPEGACTables", LONG, 0), + 529: ("YCbCrCoefficients", RATIONAL, 3), + 530: ("YCbCrSubSampling", SHORT, 2), + 531: ("YCbCrPositioning", SHORT, 1), + 532: ("ReferenceBlackWhite", RATIONAL, 6), + 700: ("XMP", BYTE, 0), + # Four private SGI tags + 32995: ("Matteing", SHORT, 1), + 32996: ("DataType", SHORT, 0), + 32997: ("ImageDepth", LONG, 1), + 32998: ("TileDepth", LONG, 1), + 33432: ("Copyright", ASCII, 1), + 33723: ("IptcNaaInfo", UNDEFINED, 1), + 34377: ("PhotoshopInfo", BYTE, 0), + # FIXME add more tags here + 34665: ("ExifIFD", LONG, 1), + 34675: ("ICCProfile", UNDEFINED, 1), + 34853: ("GPSInfoIFD", LONG, 1), + 36864: ("ExifVersion", UNDEFINED, 1), + 37724: ("ImageSourceData", UNDEFINED, 1), + 40965: ("InteroperabilityIFD", LONG, 1), + 41730: ("CFAPattern", UNDEFINED, 1), + # MPInfo + 45056: ("MPFVersion", UNDEFINED, 1), + 45057: ("NumberOfImages", LONG, 1), + 45058: ("MPEntry", UNDEFINED, 1), + 45059: ("ImageUIDList", UNDEFINED, 0), # UNDONE, check + 45060: ("TotalFrames", LONG, 1), + 45313: ("MPIndividualNum", LONG, 1), + 45569: ("PanOrientation", LONG, 1), + 45570: ("PanOverlap_H", RATIONAL, 1), + 45571: ("PanOverlap_V", RATIONAL, 1), + 45572: ("BaseViewpointNum", LONG, 1), + 45573: ("ConvergenceAngle", SIGNED_RATIONAL, 1), + 45574: ("BaselineLength", RATIONAL, 1), + 45575: ("VerticalDivergence", SIGNED_RATIONAL, 1), + 45576: ("AxisDistance_X", SIGNED_RATIONAL, 1), + 45577: ("AxisDistance_Y", SIGNED_RATIONAL, 1), + 45578: ("AxisDistance_Z", SIGNED_RATIONAL, 1), + 45579: ("YawAngle", SIGNED_RATIONAL, 1), + 45580: ("PitchAngle", SIGNED_RATIONAL, 1), + 45581: ("RollAngle", SIGNED_RATIONAL, 1), + 40960: ("FlashPixVersion", UNDEFINED, 1), + 50741: ("MakerNoteSafety", SHORT, 1, {"Unsafe": 0, "Safe": 1}), + 50780: ("BestQualityScale", RATIONAL, 1), + 50838: ("ImageJMetaDataByteCounts", LONG, 0), # Can be more than one + 50839: ("ImageJMetaData", UNDEFINED, 1), # see Issue #2006 +} +_tags_v2_groups = { + # ExifIFD + 34665: { + 36864: ("ExifVersion", UNDEFINED, 1), + 40960: ("FlashPixVersion", UNDEFINED, 1), + 40965: ("InteroperabilityIFD", LONG, 1), + 41730: ("CFAPattern", UNDEFINED, 1), + }, + # GPSInfoIFD + 34853: { + 0: ("GPSVersionID", BYTE, 4), + 1: ("GPSLatitudeRef", ASCII, 2), + 2: ("GPSLatitude", RATIONAL, 3), + 3: ("GPSLongitudeRef", ASCII, 2), + 4: ("GPSLongitude", RATIONAL, 3), + 5: ("GPSAltitudeRef", BYTE, 1), + 6: ("GPSAltitude", RATIONAL, 1), + 7: ("GPSTimeStamp", RATIONAL, 3), + 8: ("GPSSatellites", ASCII, 0), + 9: ("GPSStatus", ASCII, 2), + 10: ("GPSMeasureMode", ASCII, 2), + 11: ("GPSDOP", RATIONAL, 1), + 12: ("GPSSpeedRef", ASCII, 2), + 13: ("GPSSpeed", RATIONAL, 1), + 14: ("GPSTrackRef", ASCII, 2), + 15: ("GPSTrack", RATIONAL, 1), + 16: ("GPSImgDirectionRef", ASCII, 2), + 17: ("GPSImgDirection", RATIONAL, 1), + 18: ("GPSMapDatum", ASCII, 0), + 19: ("GPSDestLatitudeRef", ASCII, 2), + 20: ("GPSDestLatitude", RATIONAL, 3), + 21: ("GPSDestLongitudeRef", ASCII, 2), + 22: ("GPSDestLongitude", RATIONAL, 3), + 23: ("GPSDestBearingRef", ASCII, 2), + 24: ("GPSDestBearing", RATIONAL, 1), + 25: ("GPSDestDistanceRef", ASCII, 2), + 26: ("GPSDestDistance", RATIONAL, 1), + 27: ("GPSProcessingMethod", UNDEFINED, 0), + 28: ("GPSAreaInformation", UNDEFINED, 0), + 29: ("GPSDateStamp", ASCII, 11), + 30: ("GPSDifferential", SHORT, 1), + }, + # InteroperabilityIFD + 40965: {1: ("InteropIndex", ASCII, 1), 2: ("InteropVersion", UNDEFINED, 1)}, +} + +# Legacy Tags structure +# these tags aren't included above, but were in the previous versions +TAGS: dict[int | tuple[int, int], str] = { + 347: "JPEGTables", + 700: "XMP", + # Additional Exif Info + 32932: "Wang Annotation", + 33434: "ExposureTime", + 33437: "FNumber", + 33445: "MD FileTag", + 33446: "MD ScalePixel", + 33447: "MD ColorTable", + 33448: "MD LabName", + 33449: "MD SampleInfo", + 33450: "MD PrepDate", + 33451: "MD PrepTime", + 33452: "MD FileUnits", + 33550: "ModelPixelScaleTag", + 33723: "IptcNaaInfo", + 33918: "INGR Packet Data Tag", + 33919: "INGR Flag Registers", + 33920: "IrasB Transformation Matrix", + 33922: "ModelTiepointTag", + 34264: "ModelTransformationTag", + 34377: "PhotoshopInfo", + 34735: "GeoKeyDirectoryTag", + 34736: "GeoDoubleParamsTag", + 34737: "GeoAsciiParamsTag", + 34850: "ExposureProgram", + 34852: "SpectralSensitivity", + 34855: "ISOSpeedRatings", + 34856: "OECF", + 34864: "SensitivityType", + 34865: "StandardOutputSensitivity", + 34866: "RecommendedExposureIndex", + 34867: "ISOSpeed", + 34868: "ISOSpeedLatitudeyyy", + 34869: "ISOSpeedLatitudezzz", + 34908: "HylaFAX FaxRecvParams", + 34909: "HylaFAX FaxSubAddress", + 34910: "HylaFAX FaxRecvTime", + 36864: "ExifVersion", + 36867: "DateTimeOriginal", + 36868: "DateTimeDigitized", + 37121: "ComponentsConfiguration", + 37122: "CompressedBitsPerPixel", + 37724: "ImageSourceData", + 37377: "ShutterSpeedValue", + 37378: "ApertureValue", + 37379: "BrightnessValue", + 37380: "ExposureBiasValue", + 37381: "MaxApertureValue", + 37382: "SubjectDistance", + 37383: "MeteringMode", + 37384: "LightSource", + 37385: "Flash", + 37386: "FocalLength", + 37396: "SubjectArea", + 37500: "MakerNote", + 37510: "UserComment", + 37520: "SubSec", + 37521: "SubSecTimeOriginal", + 37522: "SubsecTimeDigitized", + 40960: "FlashPixVersion", + 40961: "ColorSpace", + 40962: "PixelXDimension", + 40963: "PixelYDimension", + 40964: "RelatedSoundFile", + 40965: "InteroperabilityIFD", + 41483: "FlashEnergy", + 41484: "SpatialFrequencyResponse", + 41486: "FocalPlaneXResolution", + 41487: "FocalPlaneYResolution", + 41488: "FocalPlaneResolutionUnit", + 41492: "SubjectLocation", + 41493: "ExposureIndex", + 41495: "SensingMethod", + 41728: "FileSource", + 41729: "SceneType", + 41730: "CFAPattern", + 41985: "CustomRendered", + 41986: "ExposureMode", + 41987: "WhiteBalance", + 41988: "DigitalZoomRatio", + 41989: "FocalLengthIn35mmFilm", + 41990: "SceneCaptureType", + 41991: "GainControl", + 41992: "Contrast", + 41993: "Saturation", + 41994: "Sharpness", + 41995: "DeviceSettingDescription", + 41996: "SubjectDistanceRange", + 42016: "ImageUniqueID", + 42032: "CameraOwnerName", + 42033: "BodySerialNumber", + 42034: "LensSpecification", + 42035: "LensMake", + 42036: "LensModel", + 42037: "LensSerialNumber", + 42112: "GDAL_METADATA", + 42113: "GDAL_NODATA", + 42240: "Gamma", + 50215: "Oce Scanjob Description", + 50216: "Oce Application Selector", + 50217: "Oce Identification Number", + 50218: "Oce ImageLogic Characteristics", + # Adobe DNG + 50706: "DNGVersion", + 50707: "DNGBackwardVersion", + 50708: "UniqueCameraModel", + 50709: "LocalizedCameraModel", + 50710: "CFAPlaneColor", + 50711: "CFALayout", + 50712: "LinearizationTable", + 50713: "BlackLevelRepeatDim", + 50714: "BlackLevel", + 50715: "BlackLevelDeltaH", + 50716: "BlackLevelDeltaV", + 50717: "WhiteLevel", + 50718: "DefaultScale", + 50719: "DefaultCropOrigin", + 50720: "DefaultCropSize", + 50721: "ColorMatrix1", + 50722: "ColorMatrix2", + 50723: "CameraCalibration1", + 50724: "CameraCalibration2", + 50725: "ReductionMatrix1", + 50726: "ReductionMatrix2", + 50727: "AnalogBalance", + 50728: "AsShotNeutral", + 50729: "AsShotWhiteXY", + 50730: "BaselineExposure", + 50731: "BaselineNoise", + 50732: "BaselineSharpness", + 50733: "BayerGreenSplit", + 50734: "LinearResponseLimit", + 50735: "CameraSerialNumber", + 50736: "LensInfo", + 50737: "ChromaBlurRadius", + 50738: "AntiAliasStrength", + 50740: "DNGPrivateData", + 50778: "CalibrationIlluminant1", + 50779: "CalibrationIlluminant2", + 50784: "Alias Layer Metadata", +} + +TAGS_V2: dict[int, TagInfo] = {} +TAGS_V2_GROUPS: dict[int, dict[int, TagInfo]] = {} + + +def _populate() -> None: + for k, v in _tags_v2.items(): + # Populate legacy structure. + TAGS[k] = v[0] + if len(v) == 4: + for sk, sv in v[3].items(): + TAGS[(k, sv)] = sk + + TAGS_V2[k] = TagInfo(k, *v) + + for group, tags in _tags_v2_groups.items(): + TAGS_V2_GROUPS[group] = {k: TagInfo(k, *v) for k, v in tags.items()} + + +_populate() +## +# Map type numbers to type names -- defined in ImageFileDirectory. + +TYPES: dict[int, str] = {} + +# +# These tags are handled by default in libtiff, without +# adding to the custom dictionary. From tif_dir.c, searching for +# case TIFFTAG in the _TIFFVSetField function: +# Line: item. +# 148: case TIFFTAG_SUBFILETYPE: +# 151: case TIFFTAG_IMAGEWIDTH: +# 154: case TIFFTAG_IMAGELENGTH: +# 157: case TIFFTAG_BITSPERSAMPLE: +# 181: case TIFFTAG_COMPRESSION: +# 202: case TIFFTAG_PHOTOMETRIC: +# 205: case TIFFTAG_THRESHHOLDING: +# 208: case TIFFTAG_FILLORDER: +# 214: case TIFFTAG_ORIENTATION: +# 221: case TIFFTAG_SAMPLESPERPIXEL: +# 228: case TIFFTAG_ROWSPERSTRIP: +# 238: case TIFFTAG_MINSAMPLEVALUE: +# 241: case TIFFTAG_MAXSAMPLEVALUE: +# 244: case TIFFTAG_SMINSAMPLEVALUE: +# 247: case TIFFTAG_SMAXSAMPLEVALUE: +# 250: case TIFFTAG_XRESOLUTION: +# 256: case TIFFTAG_YRESOLUTION: +# 262: case TIFFTAG_PLANARCONFIG: +# 268: case TIFFTAG_XPOSITION: +# 271: case TIFFTAG_YPOSITION: +# 274: case TIFFTAG_RESOLUTIONUNIT: +# 280: case TIFFTAG_PAGENUMBER: +# 284: case TIFFTAG_HALFTONEHINTS: +# 288: case TIFFTAG_COLORMAP: +# 294: case TIFFTAG_EXTRASAMPLES: +# 298: case TIFFTAG_MATTEING: +# 305: case TIFFTAG_TILEWIDTH: +# 316: case TIFFTAG_TILELENGTH: +# 327: case TIFFTAG_TILEDEPTH: +# 333: case TIFFTAG_DATATYPE: +# 344: case TIFFTAG_SAMPLEFORMAT: +# 361: case TIFFTAG_IMAGEDEPTH: +# 364: case TIFFTAG_SUBIFD: +# 376: case TIFFTAG_YCBCRPOSITIONING: +# 379: case TIFFTAG_YCBCRSUBSAMPLING: +# 383: case TIFFTAG_TRANSFERFUNCTION: +# 389: case TIFFTAG_REFERENCEBLACKWHITE: +# 393: case TIFFTAG_INKNAMES: + +# Following pseudo-tags are also handled by default in libtiff: +# TIFFTAG_JPEGQUALITY 65537 + +# some of these are not in our TAGS_V2 dict and were included from tiff.h + +# This list also exists in encode.c +LIBTIFF_CORE = { + 255, + 256, + 257, + 258, + 259, + 262, + 263, + 266, + 274, + 277, + 278, + 280, + 281, + 340, + 341, + 282, + 283, + 284, + 286, + 287, + 296, + 297, + 321, + 320, + 338, + 32995, + 322, + 323, + 32998, + 32996, + 339, + 32997, + 330, + 531, + 530, + 301, + 532, + 333, + # as above + 269, # this has been in our tests forever, and works + 65537, +} + +LIBTIFF_CORE.remove(255) # We don't have support for subfiletypes +LIBTIFF_CORE.remove(322) # We don't have support for writing tiled images with libtiff +LIBTIFF_CORE.remove(323) # Tiled images + +# Note to advanced users: There may be combinations of these +# parameters and values that when added properly, will work and +# produce valid tiff images that may work in your application. +# It is safe to add and remove tags from this set from Pillow's point +# of view so long as you test against libtiff. diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/WalImageFile.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/WalImageFile.py new file mode 100644 index 000000000..07bbf7471 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/WalImageFile.py @@ -0,0 +1,129 @@ +# +# The Python Imaging Library. +# $Id$ +# +# WAL file handling +# +# History: +# 2003-04-23 fl created +# +# Copyright (c) 2003 by Fredrik Lundh. +# +# See the README file for information on usage and redistribution. +# + +""" +This reader is based on the specification available from: +https://www.flipcode.com/archives/Quake_2_BSP_File_Format.shtml +and has been tested with a few sample files found using google. + +.. note:: + This format cannot be automatically recognized, so the reader + is not registered for use with :py:func:`PIL.Image.open()`. + To open a WAL file, use the :py:func:`PIL.WalImageFile.open()` function instead. +""" + +from __future__ import annotations + +from typing import IO + +from . import Image, ImageFile +from ._binary import i32le as i32 +from ._typing import StrOrBytesPath + + +class WalImageFile(ImageFile.ImageFile): + format = "WAL" + format_description = "Quake2 Texture" + + def _open(self) -> None: + self._mode = "P" + + # read header fields + assert self.fp is not None + header = self.fp.read(32 + 24 + 32 + 12) + self._size = i32(header, 32), i32(header, 36) + Image._decompression_bomb_check(self.size) + + # load pixel data + offset = i32(header, 40) + self.fp.seek(offset) + + # strings are null-terminated + self.info["name"] = header[:32].split(b"\0", 1)[0] + if next_name := header[56 : 56 + 32].split(b"\0", 1)[0]: + self.info["next_name"] = next_name + + def load(self) -> Image.core.PixelAccess | None: + if self._im is None: + assert self.fp is not None + self.im = Image.core.new(self.mode, self.size) + self.frombytes(self.fp.read(self.size[0] * self.size[1])) + self.putpalette(quake2palette) + return Image.Image.load(self) + + +def open(filename: StrOrBytesPath | IO[bytes]) -> WalImageFile: + """ + Load texture from a Quake2 WAL texture file. + + By default, a Quake2 standard palette is attached to the texture. + To override the palette, use the :py:func:`PIL.Image.Image.putpalette()` method. + + :param filename: WAL file name, or an opened file handle. + :returns: An image instance. + """ + return WalImageFile(filename) + + +quake2palette = ( + # default palette taken from piffo 0.93 by Hans Häggström + b"\x01\x01\x01\x0b\x0b\x0b\x12\x12\x12\x17\x17\x17\x1b\x1b\x1b\x1e" + b"\x1e\x1e\x22\x22\x22\x26\x26\x26\x29\x29\x29\x2c\x2c\x2c\x2f\x2f" + b"\x2f\x32\x32\x32\x35\x35\x35\x37\x37\x37\x3a\x3a\x3a\x3c\x3c\x3c" + b"\x24\x1e\x13\x22\x1c\x12\x20\x1b\x12\x1f\x1a\x10\x1d\x19\x10\x1b" + b"\x17\x0f\x1a\x16\x0f\x18\x14\x0d\x17\x13\x0d\x16\x12\x0d\x14\x10" + b"\x0b\x13\x0f\x0b\x10\x0d\x0a\x0f\x0b\x0a\x0d\x0b\x07\x0b\x0a\x07" + b"\x23\x23\x26\x22\x22\x25\x22\x20\x23\x21\x1f\x22\x20\x1e\x20\x1f" + b"\x1d\x1e\x1d\x1b\x1c\x1b\x1a\x1a\x1a\x19\x19\x18\x17\x17\x17\x16" + b"\x16\x14\x14\x14\x13\x13\x13\x10\x10\x10\x0f\x0f\x0f\x0d\x0d\x0d" + b"\x2d\x28\x20\x29\x24\x1c\x27\x22\x1a\x25\x1f\x17\x38\x2e\x1e\x31" + b"\x29\x1a\x2c\x25\x17\x26\x20\x14\x3c\x30\x14\x37\x2c\x13\x33\x28" + b"\x12\x2d\x24\x10\x28\x1f\x0f\x22\x1a\x0b\x1b\x14\x0a\x13\x0f\x07" + b"\x31\x1a\x16\x30\x17\x13\x2e\x16\x10\x2c\x14\x0d\x2a\x12\x0b\x27" + b"\x0f\x0a\x25\x0f\x07\x21\x0d\x01\x1e\x0b\x01\x1c\x0b\x01\x1a\x0b" + b"\x01\x18\x0a\x01\x16\x0a\x01\x13\x0a\x01\x10\x07\x01\x0d\x07\x01" + b"\x29\x23\x1e\x27\x21\x1c\x26\x20\x1b\x25\x1f\x1a\x23\x1d\x19\x21" + b"\x1c\x18\x20\x1b\x17\x1e\x19\x16\x1c\x18\x14\x1b\x17\x13\x19\x14" + b"\x10\x17\x13\x0f\x14\x10\x0d\x12\x0f\x0b\x0f\x0b\x0a\x0b\x0a\x07" + b"\x26\x1a\x0f\x23\x19\x0f\x20\x17\x0f\x1c\x16\x0f\x19\x13\x0d\x14" + b"\x10\x0b\x10\x0d\x0a\x0b\x0a\x07\x33\x22\x1f\x35\x29\x26\x37\x2f" + b"\x2d\x39\x35\x34\x37\x39\x3a\x33\x37\x39\x30\x34\x36\x2b\x31\x34" + b"\x27\x2e\x31\x22\x2b\x2f\x1d\x28\x2c\x17\x25\x2a\x0f\x20\x26\x0d" + b"\x1e\x25\x0b\x1c\x22\x0a\x1b\x20\x07\x19\x1e\x07\x17\x1b\x07\x14" + b"\x18\x01\x12\x16\x01\x0f\x12\x01\x0b\x0d\x01\x07\x0a\x01\x01\x01" + b"\x2c\x21\x21\x2a\x1f\x1f\x29\x1d\x1d\x27\x1c\x1c\x26\x1a\x1a\x24" + b"\x18\x18\x22\x17\x17\x21\x16\x16\x1e\x13\x13\x1b\x12\x12\x18\x10" + b"\x10\x16\x0d\x0d\x12\x0b\x0b\x0d\x0a\x0a\x0a\x07\x07\x01\x01\x01" + b"\x2e\x30\x29\x2d\x2e\x27\x2b\x2c\x26\x2a\x2a\x24\x28\x29\x23\x27" + b"\x27\x21\x26\x26\x1f\x24\x24\x1d\x22\x22\x1c\x1f\x1f\x1a\x1c\x1c" + b"\x18\x19\x19\x16\x17\x17\x13\x13\x13\x10\x0f\x0f\x0d\x0b\x0b\x0a" + b"\x30\x1e\x1b\x2d\x1c\x19\x2c\x1a\x17\x2a\x19\x14\x28\x17\x13\x26" + b"\x16\x10\x24\x13\x0f\x21\x12\x0d\x1f\x10\x0b\x1c\x0f\x0a\x19\x0d" + b"\x0a\x16\x0b\x07\x12\x0a\x07\x0f\x07\x01\x0a\x01\x01\x01\x01\x01" + b"\x28\x29\x38\x26\x27\x36\x25\x26\x34\x24\x24\x31\x22\x22\x2f\x20" + b"\x21\x2d\x1e\x1f\x2a\x1d\x1d\x27\x1b\x1b\x25\x19\x19\x21\x17\x17" + b"\x1e\x14\x14\x1b\x13\x12\x17\x10\x0f\x13\x0d\x0b\x0f\x0a\x07\x07" + b"\x2f\x32\x29\x2d\x30\x26\x2b\x2e\x24\x29\x2c\x21\x27\x2a\x1e\x25" + b"\x28\x1c\x23\x26\x1a\x21\x25\x18\x1e\x22\x14\x1b\x1f\x10\x19\x1c" + b"\x0d\x17\x1a\x0a\x13\x17\x07\x10\x13\x01\x0d\x0f\x01\x0a\x0b\x01" + b"\x01\x3f\x01\x13\x3c\x0b\x1b\x39\x10\x20\x35\x14\x23\x31\x17\x23" + b"\x2d\x18\x23\x29\x18\x3f\x3f\x3f\x3f\x3f\x39\x3f\x3f\x31\x3f\x3f" + b"\x2a\x3f\x3f\x20\x3f\x3f\x14\x3f\x3c\x12\x3f\x39\x0f\x3f\x35\x0b" + b"\x3f\x32\x07\x3f\x2d\x01\x3d\x2a\x01\x3b\x26\x01\x39\x21\x01\x37" + b"\x1d\x01\x34\x1a\x01\x32\x16\x01\x2f\x12\x01\x2d\x0f\x01\x2a\x0b" + b"\x01\x27\x07\x01\x23\x01\x01\x1d\x01\x01\x17\x01\x01\x10\x01\x01" + b"\x3d\x01\x01\x19\x19\x3f\x3f\x01\x01\x01\x01\x3f\x16\x16\x13\x10" + b"\x10\x0f\x0d\x0d\x0b\x3c\x2e\x2a\x36\x27\x20\x30\x21\x18\x29\x1b" + b"\x10\x3c\x39\x37\x37\x32\x2f\x31\x2c\x28\x2b\x26\x21\x30\x22\x20" +) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/WebPImagePlugin.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/WebPImagePlugin.py new file mode 100644 index 000000000..e20e40d91 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/WebPImagePlugin.py @@ -0,0 +1,317 @@ +from __future__ import annotations + +from io import BytesIO + +from . import Image, ImageFile + +try: + from . import _webp + + SUPPORTED = True +except ImportError: + SUPPORTED = False + +TYPE_CHECKING = False +if TYPE_CHECKING: + from typing import IO, Any + +_VP8_MODES_BY_IDENTIFIER = { + b"VP8 ": "RGB", + b"VP8X": "RGBA", + b"VP8L": "RGBA", # lossless +} + + +def _accept(prefix: bytes) -> bool | str: + is_riff_file_format = prefix.startswith(b"RIFF") + is_webp_file = prefix[8:12] == b"WEBP" + is_valid_vp8_mode = prefix[12:16] in _VP8_MODES_BY_IDENTIFIER + + if is_riff_file_format and is_webp_file and is_valid_vp8_mode: + if not SUPPORTED: + return ( + "image file could not be identified because WEBP support not installed" + ) + return True + return False + + +class WebPImageFile(ImageFile.ImageFile): + format = "WEBP" + format_description = "WebP image" + __loaded = 0 + __logical_frame = 0 + + def _open(self) -> None: + # Use the newer AnimDecoder API to parse the (possibly) animated file, + # and access muxed chunks like ICC/EXIF/XMP. + assert self.fp is not None + self._decoder = _webp.WebPAnimDecoder(self.fp.read()) + + # Get info from decoder + self._size, self.info["loop"], bgcolor, self.n_frames, self.rawmode = ( + self._decoder.get_info() + ) + self.info["background"] = ( + (bgcolor >> 16) & 0xFF, # R + (bgcolor >> 8) & 0xFF, # G + bgcolor & 0xFF, # B + (bgcolor >> 24) & 0xFF, # A + ) + self.is_animated = self.n_frames > 1 + self._mode = "RGB" if self.rawmode == "RGBX" else self.rawmode + + # Attempt to read ICC / EXIF / XMP chunks from file + for key, chunk_name in { + "icc_profile": "ICCP", + "exif": "EXIF", + "xmp": "XMP ", + }.items(): + if value := self._decoder.get_chunk(chunk_name): + self.info[key] = value + + # Initialize seek state + self._reset(reset=False) + + def _getexif(self) -> dict[int, Any] | None: + if "exif" not in self.info: + return None + return self.getexif()._get_merged_dict() + + def seek(self, frame: int) -> None: + if not self._seek_check(frame): + return + + # Set logical frame to requested position + self.__logical_frame = frame + + def _reset(self, reset: bool = True) -> None: + if reset: + self._decoder.reset() + self.__physical_frame = 0 + self.__loaded = -1 + self.__timestamp = 0 + + def _get_next(self) -> tuple[bytes, int, int]: + # Get next frame + ret = self._decoder.get_next() + self.__physical_frame += 1 + + # Check if an error occurred + if ret is None: + self._reset() # Reset just to be safe + self.seek(0) + msg = "failed to decode next frame in WebP file" + raise EOFError(msg) + + # Compute duration + data, timestamp = ret + duration = timestamp - self.__timestamp + self.__timestamp = timestamp + + # libwebp gives frame end, adjust to start of frame + timestamp -= duration + return data, timestamp, duration + + def _seek(self, frame: int) -> None: + if self.__physical_frame == frame: + return # Nothing to do + if frame < self.__physical_frame: + self._reset() # Rewind to beginning + while self.__physical_frame < frame: + self._get_next() # Advance to the requested frame + + def load(self) -> Image.core.PixelAccess | None: + if self.__loaded != self.__logical_frame: + self._seek(self.__logical_frame) + + # We need to load the image data for this frame + data, self.info["timestamp"], self.info["duration"] = self._get_next() + self.__loaded = self.__logical_frame + + # Set tile + if self.fp and self._exclusive_fp: + self.fp.close() + self.fp = BytesIO(data) + self.tile = [ImageFile._Tile("raw", (0, 0) + self.size, 0, self.rawmode)] + + return super().load() + + def load_seek(self, pos: int) -> None: + pass + + def tell(self) -> int: + return self.__logical_frame + + +def _convert_frame(im: Image.Image) -> Image.Image: + # Make sure image mode is supported + if im.mode not in ("RGBX", "RGBA", "RGB"): + im = im.convert("RGBA" if im.has_transparency_data else "RGB") + return im + + +def _save_all(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None: + encoderinfo = im.encoderinfo.copy() + append_images = list(encoderinfo.get("append_images", [])) + + # If total frame count is 1, then save using the legacy API, which + # will preserve non-alpha modes + total = 0 + for ims in [im] + append_images: + total += getattr(ims, "n_frames", 1) + if total == 1: + _save(im, fp, filename) + return + + background: int | tuple[int, ...] = (0, 0, 0, 0) + if "background" in encoderinfo: + background = encoderinfo["background"] + elif "background" in im.info: + background = im.info["background"] + if isinstance(background, int): + # GifImagePlugin stores a global color table index in + # info["background"]. So it must be converted to an RGBA value + palette = im.getpalette() + if palette: + r, g, b = palette[background * 3 : (background + 1) * 3] + background = (r, g, b, 255) + else: + background = (background, background, background, 255) + + duration = im.encoderinfo.get("duration", im.info.get("duration", 0)) + loop = im.encoderinfo.get("loop", 0) + minimize_size = im.encoderinfo.get("minimize_size", False) + kmin = im.encoderinfo.get("kmin", None) + kmax = im.encoderinfo.get("kmax", None) + allow_mixed = im.encoderinfo.get("allow_mixed", False) + verbose = False + lossless = im.encoderinfo.get("lossless", False) + quality = im.encoderinfo.get("quality", 80) + alpha_quality = im.encoderinfo.get("alpha_quality", 100) + method = im.encoderinfo.get("method", 0) + icc_profile = im.encoderinfo.get("icc_profile") or "" + exif = im.encoderinfo.get("exif", "") + if isinstance(exif, Image.Exif): + exif = exif.tobytes() + xmp = im.encoderinfo.get("xmp", "") + if allow_mixed: + lossless = False + + # Sensible keyframe defaults are from gif2webp.c script + if kmin is None: + kmin = 9 if lossless else 3 + if kmax is None: + kmax = 17 if lossless else 5 + + # Validate background color + if ( + not isinstance(background, (list, tuple)) + or len(background) != 4 + or not all(0 <= v < 256 for v in background) + ): + msg = f"Background color is not an RGBA tuple clamped to (0-255): {background}" + raise OSError(msg) + + # Convert to packed uint + bg_r, bg_g, bg_b, bg_a = background + background = (bg_a << 24) | (bg_r << 16) | (bg_g << 8) | (bg_b << 0) + + # Setup the WebP animation encoder + enc = _webp.WebPAnimEncoder( + im.size, + background, + loop, + minimize_size, + kmin, + kmax, + allow_mixed, + verbose, + ) + + # Add each frame + frame_idx = 0 + timestamp = 0 + cur_idx = im.tell() + try: + for ims in [im] + append_images: + # Get number of frames in this image + nfr = getattr(ims, "n_frames", 1) + + for idx in range(nfr): + ims.seek(idx) + + frame = _convert_frame(ims) + + # Append the frame to the animation encoder + enc.add( + frame.getim(), + round(timestamp), + lossless, + quality, + alpha_quality, + method, + ) + + # Update timestamp and frame index + if isinstance(duration, (list, tuple)): + timestamp += duration[frame_idx] + else: + timestamp += duration + frame_idx += 1 + + finally: + im.seek(cur_idx) + + # Force encoder to flush frames + enc.add(None, round(timestamp), lossless, quality, alpha_quality, 0) + + # Get the final output from the encoder + data = enc.assemble(icc_profile, exif, xmp) + if data is None: + msg = "cannot write file as WebP (encoder returned None)" + raise OSError(msg) + + fp.write(data) + + +def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None: + lossless = im.encoderinfo.get("lossless", False) + quality = im.encoderinfo.get("quality", 80) + alpha_quality = im.encoderinfo.get("alpha_quality", 100) + icc_profile = im.encoderinfo.get("icc_profile") or "" + exif = im.encoderinfo.get("exif", b"") + if isinstance(exif, Image.Exif): + exif = exif.tobytes() + if exif.startswith(b"Exif\x00\x00"): + exif = exif[6:] + xmp = im.encoderinfo.get("xmp", "") + method = im.encoderinfo.get("method", 4) + exact = 1 if im.encoderinfo.get("exact") else 0 + + im = _convert_frame(im) + + data = _webp.WebPEncode( + im.getim(), + lossless, + float(quality), + float(alpha_quality), + icc_profile, + method, + exact, + exif, + xmp, + ) + if data is None: + msg = "cannot write file as WebP (encoder returned None)" + raise OSError(msg) + + fp.write(data) + + +Image.register_open(WebPImageFile.format, WebPImageFile, _accept) +if SUPPORTED: + Image.register_save(WebPImageFile.format, _save) + Image.register_save_all(WebPImageFile.format, _save_all) + Image.register_extension(WebPImageFile.format, ".webp") + Image.register_mime(WebPImageFile.format, "image/webp") diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/WmfImagePlugin.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/WmfImagePlugin.py new file mode 100644 index 000000000..f5e244782 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/WmfImagePlugin.py @@ -0,0 +1,183 @@ +# +# The Python Imaging Library +# $Id$ +# +# WMF stub codec +# +# history: +# 1996-12-14 fl Created +# 2004-02-22 fl Turned into a stub driver +# 2004-02-23 fl Added EMF support +# +# Copyright (c) Secret Labs AB 1997-2004. All rights reserved. +# Copyright (c) Fredrik Lundh 1996. +# +# See the README file for information on usage and redistribution. +# +# WMF/EMF reference documentation: +# https://winprotocoldoc.blob.core.windows.net/productionwindowsarchives/MS-WMF/[MS-WMF].pdf +# http://wvware.sourceforge.net/caolan/index.html +# http://wvware.sourceforge.net/caolan/ora-wmf.html +from __future__ import annotations + +from typing import IO + +from . import Image, ImageFile +from ._binary import i16le as word +from ._binary import si16le as short +from ._binary import si32le as _long + +_handler = None + + +def register_handler(handler: ImageFile.StubHandler | None) -> None: + """ + Install application-specific WMF image handler. + + :param handler: Handler object. + """ + global _handler + _handler = handler + + +if hasattr(Image.core, "drawwmf"): + # install default handler (windows only) + + class WmfHandler(ImageFile.StubHandler): + def open(self, im: ImageFile.StubImageFile) -> None: + self.bbox = im.info["wmf_bbox"] + + def load(self, im: ImageFile.StubImageFile) -> Image.Image: + assert im.fp is not None + im.fp.seek(0) # rewind + return Image.frombytes( + "RGB", + im.size, + Image.core.drawwmf(im.fp.read(), im.size, self.bbox), + "raw", + "BGR", + (im.size[0] * 3 + 3) & -4, + -1, + ) + + register_handler(WmfHandler()) + +# +# -------------------------------------------------------------------- +# Read WMF file + + +def _accept(prefix: bytes) -> bool: + return prefix.startswith((b"\xd7\xcd\xc6\x9a\x00\x00", b"\x01\x00\x00\x00")) + + +## +# Image plugin for Windows metafiles. + + +class WmfStubImageFile(ImageFile.StubImageFile): + format = "WMF" + format_description = "Windows Metafile" + + def _open(self) -> None: + # check placeable header + assert self.fp is not None + s = self.fp.read(44) + + if s.startswith(b"\xd7\xcd\xc6\x9a\x00\x00"): + # placeable windows metafile + + # get units per inch + inch = word(s, 14) + if inch == 0: + msg = "Invalid inch" + raise ValueError(msg) + self._inch: tuple[float, float] = inch, inch + + # get bounding box + x0 = short(s, 6) + y0 = short(s, 8) + x1 = short(s, 10) + y1 = short(s, 12) + + # normalize size to 72 dots per inch + self.info["dpi"] = 72 + size = ( + (x1 - x0) * self.info["dpi"] // inch, + (y1 - y0) * self.info["dpi"] // inch, + ) + + self.info["wmf_bbox"] = x0, y0, x1, y1 + + # sanity check (standard metafile header) + if s[22:26] != b"\x01\x00\t\x00": + msg = "Unsupported WMF file format" + raise SyntaxError(msg) + + elif s.startswith(b"\x01\x00\x00\x00") and s[40:44] == b" EMF": + # enhanced metafile + + # get bounding box + x0 = _long(s, 8) + y0 = _long(s, 12) + x1 = _long(s, 16) + y1 = _long(s, 20) + + # get frame (in 0.01 millimeter units) + frame = _long(s, 24), _long(s, 28), _long(s, 32), _long(s, 36) + + size = x1 - x0, y1 - y0 + + # calculate dots per inch from bbox and frame + xdpi = 2540.0 * (x1 - x0) / (frame[2] - frame[0]) + ydpi = 2540.0 * (y1 - y0) / (frame[3] - frame[1]) + + self.info["wmf_bbox"] = x0, y0, x1, y1 + + if xdpi == ydpi: + self.info["dpi"] = xdpi + else: + self.info["dpi"] = xdpi, ydpi + self._inch = xdpi, ydpi + + else: + msg = "Unsupported file format" + raise SyntaxError(msg) + + self._mode = "RGB" + self._size = size + + def _load(self) -> ImageFile.StubHandler | None: + return _handler + + def load( + self, dpi: float | tuple[float, float] | None = None + ) -> Image.core.PixelAccess | None: + if dpi is not None: + self.info["dpi"] = dpi + x0, y0, x1, y1 = self.info["wmf_bbox"] + if not isinstance(dpi, tuple): + dpi = dpi, dpi + self._size = ( + int((x1 - x0) * dpi[0] / self._inch[0]), + int((y1 - y0) * dpi[1] / self._inch[1]), + ) + return super().load() + + +def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None: + if _handler is None or not hasattr(_handler, "save"): + msg = "WMF save handler not installed" + raise OSError(msg) + _handler.save(im, fp, filename) + + +# +# -------------------------------------------------------------------- +# Registry stuff + + +Image.register_open(WmfStubImageFile.format, WmfStubImageFile, _accept) +Image.register_save(WmfStubImageFile.format, _save) + +Image.register_extensions(WmfStubImageFile.format, [".wmf", ".emf"]) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/XVThumbImagePlugin.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/XVThumbImagePlugin.py new file mode 100644 index 000000000..192c041d9 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/XVThumbImagePlugin.py @@ -0,0 +1,83 @@ +# +# The Python Imaging Library. +# $Id$ +# +# XV Thumbnail file handler by Charles E. "Gene" Cash +# (gcash@magicnet.net) +# +# see xvcolor.c and xvbrowse.c in the sources to John Bradley's XV, +# available from ftp://ftp.cis.upenn.edu/pub/xv/ +# +# history: +# 98-08-15 cec created (b/w only) +# 98-12-09 cec added color palette +# 98-12-28 fl added to PIL (with only a few very minor modifications) +# +# To do: +# FIXME: make save work (this requires quantization support) +# +from __future__ import annotations + +from . import Image, ImageFile, ImagePalette +from ._binary import o8 + +_MAGIC = b"P7 332" + +# standard color palette for thumbnails (RGB332) +PALETTE = b"" +for r in range(8): + for g in range(8): + for b in range(4): + PALETTE = PALETTE + ( + o8((r * 255) // 7) + o8((g * 255) // 7) + o8((b * 255) // 3) + ) + + +def _accept(prefix: bytes) -> bool: + return prefix.startswith(_MAGIC) + + +## +# Image plugin for XV thumbnail images. + + +class XVThumbImageFile(ImageFile.ImageFile): + format = "XVThumb" + format_description = "XV thumbnail image" + + def _open(self) -> None: + # check magic + assert self.fp is not None + + if not _accept(self.fp.read(6)): + msg = "not an XV thumbnail file" + raise SyntaxError(msg) + + # Skip to beginning of next line + self.fp.readline() + + # skip info comments + while True: + s = self.fp.readline() + if not s: + msg = "Unexpected EOF reading XV thumbnail file" + raise SyntaxError(msg) + if s[0] != 35: # ie. when not a comment: '#' + break + + # parse header line (already read) + w, h = s.strip().split(maxsplit=2)[:2] + + self._mode = "P" + self._size = int(w), int(h) + + self.palette = ImagePalette.raw("RGB", PALETTE) + + self.tile = [ + ImageFile._Tile("raw", (0, 0) + self.size, self.fp.tell(), self.mode) + ] + + +# -------------------------------------------------------------------- + +Image.register_open(XVThumbImageFile.format, XVThumbImageFile, _accept) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/XbmImagePlugin.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/XbmImagePlugin.py new file mode 100644 index 000000000..1e57aa162 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/XbmImagePlugin.py @@ -0,0 +1,98 @@ +# +# The Python Imaging Library. +# $Id$ +# +# XBM File handling +# +# History: +# 1995-09-08 fl Created +# 1996-11-01 fl Added save support +# 1997-07-07 fl Made header parser more tolerant +# 1997-07-22 fl Fixed yet another parser bug +# 2001-02-17 fl Use 're' instead of 'regex' (Python 2.1) (0.4) +# 2001-05-13 fl Added hotspot handling (based on code from Bernhard Herzog) +# 2004-02-24 fl Allow some whitespace before first #define +# +# Copyright (c) 1997-2004 by Secret Labs AB +# Copyright (c) 1996-1997 by Fredrik Lundh +# +# See the README file for information on usage and redistribution. +# +from __future__ import annotations + +import re +from typing import IO + +from . import Image, ImageFile + +# XBM header +xbm_head = re.compile( + rb"\s*#define[ \t]+.*_width[ \t]+(?P[0-9]+)[\r\n]+" + b"#define[ \t]+.*_height[ \t]+(?P[0-9]+)[\r\n]+" + b"(?P" + b"#define[ \t]+[^_]*_x_hot[ \t]+(?P[0-9]+)[\r\n]+" + b"#define[ \t]+[^_]*_y_hot[ \t]+(?P[0-9]+)[\r\n]+" + b")?" + rb"[\000-\377]*_bits\[]" +) + + +def _accept(prefix: bytes) -> bool: + return prefix.lstrip().startswith(b"#define") + + +## +# Image plugin for X11 bitmaps. + + +class XbmImageFile(ImageFile.ImageFile): + format = "XBM" + format_description = "X11 Bitmap" + + def _open(self) -> None: + assert self.fp is not None + + m = xbm_head.match(self.fp.read(512)) + + if not m: + msg = "not a XBM file" + raise SyntaxError(msg) + + xsize = int(m.group("width")) + ysize = int(m.group("height")) + + if m.group("hotspot"): + self.info["hotspot"] = (int(m.group("xhot")), int(m.group("yhot"))) + + self._mode = "1" + self._size = xsize, ysize + + self.tile = [ImageFile._Tile("xbm", (0, 0) + self.size, m.end())] + + +def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None: + if im.mode != "1": + msg = f"cannot write mode {im.mode} as XBM" + raise OSError(msg) + + fp.write(f"#define im_width {im.size[0]}\n".encode("ascii")) + fp.write(f"#define im_height {im.size[1]}\n".encode("ascii")) + + hotspot = im.encoderinfo.get("hotspot") + if hotspot: + fp.write(f"#define im_x_hot {hotspot[0]}\n".encode("ascii")) + fp.write(f"#define im_y_hot {hotspot[1]}\n".encode("ascii")) + + fp.write(b"static char im_bits[] = {\n") + + ImageFile._save(im, fp, [ImageFile._Tile("xbm", (0, 0) + im.size)]) + + fp.write(b"};\n") + + +Image.register_open(XbmImageFile.format, XbmImageFile, _accept) +Image.register_save(XbmImageFile.format, _save) + +Image.register_extension(XbmImageFile.format, ".xbm") + +Image.register_mime(XbmImageFile.format, "image/xbm") diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/XpmImagePlugin.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/XpmImagePlugin.py new file mode 100644 index 000000000..3be240fbc --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/XpmImagePlugin.py @@ -0,0 +1,157 @@ +# +# The Python Imaging Library. +# $Id$ +# +# XPM File handling +# +# History: +# 1996-12-29 fl Created +# 2001-02-17 fl Use 're' instead of 'regex' (Python 2.1) (0.7) +# +# Copyright (c) Secret Labs AB 1997-2001. +# Copyright (c) Fredrik Lundh 1996-2001. +# +# See the README file for information on usage and redistribution. +# +from __future__ import annotations + +import re + +from . import Image, ImageFile, ImagePalette +from ._binary import o8 + +# XPM header +xpm_head = re.compile(b'"([0-9]*) ([0-9]*) ([0-9]*) ([0-9]*)') + + +def _accept(prefix: bytes) -> bool: + return prefix.startswith(b"/* XPM */") + + +## +# Image plugin for X11 pixel maps. + + +class XpmImageFile(ImageFile.ImageFile): + format = "XPM" + format_description = "X11 Pixel Map" + + def _open(self) -> None: + assert self.fp is not None + if not _accept(self.fp.read(9)): + msg = "not an XPM file" + raise SyntaxError(msg) + + # skip forward to next string + while True: + line = self.fp.readline() + if not line: + msg = "broken XPM file" + raise SyntaxError(msg) + m = xpm_head.match(line) + if m: + break + + self._size = int(m.group(1)), int(m.group(2)) + + palette_length = int(m.group(3)) + bpp = int(m.group(4)) + + # + # load palette description + + palette = {} + + for _ in range(palette_length): + line = self.fp.readline().rstrip() + + c = line[1 : bpp + 1] + s = line[bpp + 1 : -2].split() + + for i in range(0, len(s), 2): + if s[i] == b"c": + # process colour key + rgb = s[i + 1] + if rgb == b"None": + self.info["transparency"] = c + elif rgb.startswith(b"#"): + rgb_int = int(rgb[1:], 16) + palette[c] = ( + o8((rgb_int >> 16) & 255) + + o8((rgb_int >> 8) & 255) + + o8(rgb_int & 255) + ) + else: + # unknown colour + msg = "cannot read this XPM file" + raise ValueError(msg) + break + + else: + # missing colour key + msg = "cannot read this XPM file" + raise ValueError(msg) + + args: tuple[int, dict[bytes, bytes] | tuple[bytes, ...]] + if palette_length > 256: + self._mode = "RGB" + args = (bpp, palette) + else: + self._mode = "P" + self.palette = ImagePalette.raw("RGB", b"".join(palette.values())) + args = (bpp, tuple(palette.keys())) + + self.tile = [ImageFile._Tile("xpm", (0, 0) + self.size, self.fp.tell(), args)] + + def load_read(self, read_bytes: int) -> bytes: + # + # load all image data in one chunk + + xsize, ysize = self.size + + assert self.fp is not None + s = [self.fp.readline()[1 : xsize + 1].ljust(xsize) for i in range(ysize)] + + return b"".join(s) + + +class XpmDecoder(ImageFile.PyDecoder): + _pulls_fd = True + + def decode(self, buffer: bytes | Image.SupportsArrayInterface) -> tuple[int, int]: + assert self.fd is not None + + data = bytearray() + bpp, palette = self.args + dest_length = self.state.xsize * self.state.ysize + if self.mode == "RGB": + dest_length *= 3 + pixel_header = False + while len(data) < dest_length: + line = self.fd.readline() + if not line: + break + if line.rstrip() == b"/* pixels */" and not pixel_header: + pixel_header = True + continue + line = b'"'.join(line.split(b'"')[1:-1]) + for i in range(0, len(line), bpp): + key = line[i : i + bpp] + if self.mode == "RGB": + data += palette[key] + else: + data += o8(palette.index(key)) + self.set_as_raw(bytes(data)) + return -1, 0 + + +# +# Registry + + +Image.register_open(XpmImageFile.format, XpmImageFile, _accept) +Image.register_decoder("xpm", XpmDecoder) + +Image.register_extension(XpmImageFile.format, ".xpm") + +Image.register_mime(XpmImageFile.format, "image/xpm") diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/__init__.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/__init__.py new file mode 100644 index 000000000..faf3e76e0 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/__init__.py @@ -0,0 +1,87 @@ +"""Pillow (Fork of the Python Imaging Library) + +Pillow is the friendly PIL fork by Jeffrey 'Alex' Clark and contributors. + https://github.com/python-pillow/Pillow/ + +Pillow is forked from PIL 1.1.7. + +PIL is the Python Imaging Library by Fredrik Lundh and contributors. +Copyright (c) 1999 by Secret Labs AB. + +Use PIL.__version__ for this Pillow version. + +;-) +""" + +from __future__ import annotations + +from . import _version + +# VERSION was removed in Pillow 6.0.0. +# PILLOW_VERSION was removed in Pillow 9.0.0. +# Use __version__ instead. +__version__ = _version.__version__ +del _version + + +_plugins = [ + "AvifImagePlugin", + "BlpImagePlugin", + "BmpImagePlugin", + "BufrStubImagePlugin", + "CurImagePlugin", + "DcxImagePlugin", + "DdsImagePlugin", + "EpsImagePlugin", + "FitsImagePlugin", + "FliImagePlugin", + "FpxImagePlugin", + "FtexImagePlugin", + "GbrImagePlugin", + "GifImagePlugin", + "GribStubImagePlugin", + "Hdf5StubImagePlugin", + "IcnsImagePlugin", + "IcoImagePlugin", + "ImImagePlugin", + "ImtImagePlugin", + "IptcImagePlugin", + "JpegImagePlugin", + "Jpeg2KImagePlugin", + "McIdasImagePlugin", + "MicImagePlugin", + "MpegImagePlugin", + "MpoImagePlugin", + "MspImagePlugin", + "PalmImagePlugin", + "PcdImagePlugin", + "PcxImagePlugin", + "PdfImagePlugin", + "PixarImagePlugin", + "PngImagePlugin", + "PpmImagePlugin", + "PsdImagePlugin", + "QoiImagePlugin", + "SgiImagePlugin", + "SpiderImagePlugin", + "SunImagePlugin", + "TgaImagePlugin", + "TiffImagePlugin", + "WebPImagePlugin", + "WmfImagePlugin", + "XbmImagePlugin", + "XpmImagePlugin", + "XVThumbImagePlugin", +] + + +class UnidentifiedImageError(OSError): + """ + Raised in :py:meth:`PIL.Image.open` if an image cannot be opened and identified. + + If a PNG image raises this error, setting :data:`.ImageFile.LOAD_TRUNCATED_IMAGES` + to true may allow the image to be opened after all. The setting will ignore missing + data and checksum failures. + """ + + pass diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/__main__.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/__main__.py new file mode 100644 index 000000000..043156e89 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/__main__.py @@ -0,0 +1,7 @@ +from __future__ import annotations + +import sys + +from .features import pilinfo + +pilinfo(supported_formats="--report" not in sys.argv) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/_avif.cpython-312-x86_64-linux-gnu.so b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/_avif.cpython-312-x86_64-linux-gnu.so new file mode 100755 index 000000000..6718d4792 Binary files /dev/null and b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/_avif.cpython-312-x86_64-linux-gnu.so differ diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/_avif.pyi b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/_avif.pyi new file mode 100644 index 000000000..e27843e53 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/_avif.pyi @@ -0,0 +1,3 @@ +from typing import Any + +def __getattr__(name: str) -> Any: ... diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/_binary.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/_binary.py new file mode 100644 index 000000000..d3236c17a --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/_binary.py @@ -0,0 +1,113 @@ +# +# The Python Imaging Library. +# $Id$ +# +# Binary input/output support routines. +# +# Copyright (c) 1997-2003 by Secret Labs AB +# Copyright (c) 1995-2003 by Fredrik Lundh +# Copyright (c) 2012 by Brian Crowell +# +# See the README file for information on usage and redistribution. +# + + +"""Binary input/output support routines.""" + +from __future__ import annotations + +from struct import pack, unpack_from + + +def i8(c: bytes) -> int: + return c[0] + + +def o8(i: int) -> bytes: + return bytes((i & 255,)) + + +# Input, le = little endian, be = big endian +def i16le(c: bytes, o: int = 0) -> int: + """ + Converts a 2-bytes (16 bits) string to an unsigned integer. + + :param c: string containing bytes to convert + :param o: offset of bytes to convert in string + """ + return unpack_from(" int: + """ + Converts a 2-bytes (16 bits) string to a signed integer. + + :param c: string containing bytes to convert + :param o: offset of bytes to convert in string + """ + return unpack_from(" int: + """ + Converts a 2-bytes (16 bits) string to a signed integer, big endian. + + :param c: string containing bytes to convert + :param o: offset of bytes to convert in string + """ + return unpack_from(">h", c, o)[0] + + +def i32le(c: bytes, o: int = 0) -> int: + """ + Converts a 4-bytes (32 bits) string to an unsigned integer. + + :param c: string containing bytes to convert + :param o: offset of bytes to convert in string + """ + return unpack_from(" int: + """ + Converts a 4-bytes (32 bits) string to a signed integer. + + :param c: string containing bytes to convert + :param o: offset of bytes to convert in string + """ + return unpack_from(" int: + """ + Converts a 4-bytes (32 bits) string to a signed integer, big endian. + + :param c: string containing bytes to convert + :param o: offset of bytes to convert in string + """ + return unpack_from(">i", c, o)[0] + + +def i16be(c: bytes, o: int = 0) -> int: + return unpack_from(">H", c, o)[0] + + +def i32be(c: bytes, o: int = 0) -> int: + return unpack_from(">I", c, o)[0] + + +# Output, le = little endian, be = big endian +def o16le(i: int) -> bytes: + return pack(" bytes: + return pack(" bytes: + return pack(">H", i) + + +def o32be(i: int) -> bytes: + return pack(">I", i) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/_deprecate.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/_deprecate.py new file mode 100644 index 000000000..711c62ab2 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/_deprecate.py @@ -0,0 +1,72 @@ +from __future__ import annotations + +import warnings + +from . import __version__ + + +def deprecate( + deprecated: str, + when: int | None, + replacement: str | None = None, + *, + action: str | None = None, + plural: bool = False, + stacklevel: int = 3, +) -> None: + """ + Deprecations helper. + + :param deprecated: Name of thing to be deprecated. + :param when: Pillow major version to be removed in. + :param replacement: Name of replacement. + :param action: Instead of "replacement", give a custom call to action + e.g. "Upgrade to new thing". + :param plural: if the deprecated thing is plural, needing "are" instead of "is". + + Usually of the form: + + "[deprecated] is deprecated and will be removed in Pillow [when] (yyyy-mm-dd). + Use [replacement] instead." + + You can leave out the replacement sentence: + + "[deprecated] is deprecated and will be removed in Pillow [when] (yyyy-mm-dd)" + + Or with another call to action: + + "[deprecated] is deprecated and will be removed in Pillow [when] (yyyy-mm-dd). + [action]." + """ + + is_ = "are" if plural else "is" + + if when is None: + removed = "a future version" + elif when <= int(__version__.split(".")[0]): + msg = f"{deprecated} {is_} deprecated and should be removed." + raise RuntimeError(msg) + elif when == 13: + removed = "Pillow 13 (2026-10-15)" + elif when == 14: + removed = "Pillow 14 (2027-10-15)" + else: + msg = f"Unknown removal version: {when}. Update {__name__}?" + raise ValueError(msg) + + if replacement and action: + msg = "Use only one of 'replacement' and 'action'" + raise ValueError(msg) + + if replacement: + action = f". Use {replacement} instead." + elif action: + action = f". {action.rstrip('.')}." + else: + action = "" + + warnings.warn( + f"{deprecated} {is_} deprecated and will be removed in {removed}{action}", + DeprecationWarning, + stacklevel=stacklevel, + ) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/_imaging.cpython-312-x86_64-linux-gnu.so b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/_imaging.cpython-312-x86_64-linux-gnu.so new file mode 100755 index 000000000..49f1901db Binary files /dev/null and b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/_imaging.cpython-312-x86_64-linux-gnu.so differ diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/_imaging.pyi b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/_imaging.pyi new file mode 100644 index 000000000..81028a596 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/_imaging.pyi @@ -0,0 +1,31 @@ +from typing import Any + +class ImagingCore: + def __getitem__(self, index: int) -> float | tuple[int, ...] | None: ... + def __getattr__(self, name: str) -> Any: ... + +class ImagingFont: + def __getattr__(self, name: str) -> Any: ... + +class ImagingDraw: + def __getattr__(self, name: str) -> Any: ... + +class PixelAccess: + def __getitem__(self, xy: tuple[int, int]) -> float | tuple[int, ...]: ... + def __setitem__( + self, xy: tuple[int, int], color: float | tuple[int, ...] + ) -> None: ... + +class ImagingDecoder: + def __getattr__(self, name: str) -> Any: ... + +class ImagingEncoder: + def __getattr__(self, name: str) -> Any: ... + +class _Outline: + def close(self) -> None: ... + def __getattr__(self, name: str) -> Any: ... + +def font(image: ImagingCore, glyphdata: bytes) -> ImagingFont: ... +def outline() -> _Outline: ... +def __getattr__(name: str) -> Any: ... diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/_imagingcms.cpython-312-x86_64-linux-gnu.so b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/_imagingcms.cpython-312-x86_64-linux-gnu.so new file mode 100755 index 000000000..ea34a8772 Binary files /dev/null and b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/_imagingcms.cpython-312-x86_64-linux-gnu.so differ diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/_imagingcms.pyi b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/_imagingcms.pyi new file mode 100644 index 000000000..4fc0d60ab --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/_imagingcms.pyi @@ -0,0 +1,143 @@ +import datetime +import sys +from typing import Literal, SupportsFloat, TypeAlias, TypedDict + +from ._typing import CapsuleType + +littlecms_version: str | None + +_Tuple3f: TypeAlias = tuple[float, float, float] +_Tuple2x3f: TypeAlias = tuple[_Tuple3f, _Tuple3f] +_Tuple3x3f: TypeAlias = tuple[_Tuple3f, _Tuple3f, _Tuple3f] + +class _IccMeasurementCondition(TypedDict): + observer: int + backing: _Tuple3f + geo: str + flare: float + illuminant_type: str + +class _IccViewingCondition(TypedDict): + illuminant: _Tuple3f + surround: _Tuple3f + illuminant_type: str + +class CmsProfile: + @property + def rendering_intent(self) -> int: ... + @property + def creation_date(self) -> datetime.datetime | None: ... + @property + def copyright(self) -> str | None: ... + @property + def target(self) -> str | None: ... + @property + def manufacturer(self) -> str | None: ... + @property + def model(self) -> str | None: ... + @property + def profile_description(self) -> str | None: ... + @property + def screening_description(self) -> str | None: ... + @property + def viewing_condition(self) -> str | None: ... + @property + def version(self) -> float: ... + @property + def icc_version(self) -> int: ... + @property + def attributes(self) -> int: ... + @property + def header_flags(self) -> int: ... + @property + def header_manufacturer(self) -> str: ... + @property + def header_model(self) -> str: ... + @property + def device_class(self) -> str: ... + @property + def connection_space(self) -> str: ... + @property + def xcolor_space(self) -> str: ... + @property + def profile_id(self) -> bytes: ... + @property + def is_matrix_shaper(self) -> bool: ... + @property + def technology(self) -> str | None: ... + @property + def colorimetric_intent(self) -> str | None: ... + @property + def perceptual_rendering_intent_gamut(self) -> str | None: ... + @property + def saturation_rendering_intent_gamut(self) -> str | None: ... + @property + def red_colorant(self) -> _Tuple2x3f | None: ... + @property + def green_colorant(self) -> _Tuple2x3f | None: ... + @property + def blue_colorant(self) -> _Tuple2x3f | None: ... + @property + def red_primary(self) -> _Tuple2x3f | None: ... + @property + def green_primary(self) -> _Tuple2x3f | None: ... + @property + def blue_primary(self) -> _Tuple2x3f | None: ... + @property + def media_white_point_temperature(self) -> float | None: ... + @property + def media_white_point(self) -> _Tuple2x3f | None: ... + @property + def media_black_point(self) -> _Tuple2x3f | None: ... + @property + def luminance(self) -> _Tuple2x3f | None: ... + @property + def chromatic_adaptation(self) -> tuple[_Tuple3x3f, _Tuple3x3f] | None: ... + @property + def chromaticity(self) -> _Tuple3x3f | None: ... + @property + def colorant_table(self) -> list[str] | None: ... + @property + def colorant_table_out(self) -> list[str] | None: ... + @property + def intent_supported(self) -> dict[int, tuple[bool, bool, bool]] | None: ... + @property + def clut(self) -> dict[int, tuple[bool, bool, bool]] | None: ... + @property + def icc_measurement_condition(self) -> _IccMeasurementCondition | None: ... + @property + def icc_viewing_condition(self) -> _IccViewingCondition | None: ... + def is_intent_supported(self, intent: int, direction: int, /) -> int: ... + +class CmsTransform: + def apply(self, id_in: CapsuleType, id_out: CapsuleType) -> int: ... + +def profile_open(profile: str, /) -> CmsProfile: ... +def profile_frombytes(profile: bytes, /) -> CmsProfile: ... +def profile_tobytes(profile: CmsProfile, /) -> bytes: ... +def buildTransform( + input_profile: CmsProfile, + output_profile: CmsProfile, + in_mode: str, + out_mode: str, + rendering_intent: int = 0, + cms_flags: int = 0, + /, +) -> CmsTransform: ... +def buildProofTransform( + input_profile: CmsProfile, + output_profile: CmsProfile, + proof_profile: CmsProfile, + in_mode: str, + out_mode: str, + rendering_intent: int = 0, + proof_intent: int = 0, + cms_flags: int = 0, + /, +) -> CmsTransform: ... +def createProfile( + color_space: Literal["LAB", "XYZ", "sRGB"], color_temp: SupportsFloat = 0.0, / +) -> CmsProfile: ... + +if sys.platform == "win32": + def get_display_profile_win32(handle: int = 0, is_dc: int = 0, /) -> str | None: ... diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/_imagingft.cpython-312-x86_64-linux-gnu.so b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/_imagingft.cpython-312-x86_64-linux-gnu.so new file mode 100755 index 000000000..7e8d46e98 Binary files /dev/null and b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/_imagingft.cpython-312-x86_64-linux-gnu.so differ diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/_imagingft.pyi b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/_imagingft.pyi new file mode 100644 index 000000000..2136810ba --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/_imagingft.pyi @@ -0,0 +1,70 @@ +from collections.abc import Callable +from typing import Any + +from . import ImageFont, _imaging + +class Font: + @property + def family(self) -> str | None: ... + @property + def style(self) -> str | None: ... + @property + def ascent(self) -> int: ... + @property + def descent(self) -> int: ... + @property + def height(self) -> int: ... + @property + def x_ppem(self) -> int: ... + @property + def y_ppem(self) -> int: ... + @property + def glyphs(self) -> int: ... + def render( + self, + string: str | bytes, + fill: Callable[[int, int], _imaging.ImagingCore], + mode: str, + dir: str | None, + features: list[str] | None, + lang: str | None, + stroke_width: float, + stroke_filled: bool, + anchor: str | None, + foreground_ink_long: int, + start: tuple[float, float], + /, + ) -> tuple[_imaging.ImagingCore, tuple[int, int]]: ... + def getsize( + self, + string: str | bytes | bytearray, + mode: str, + dir: str | None, + features: list[str] | None, + lang: str | None, + anchor: str | None, + /, + ) -> tuple[tuple[int, int], tuple[int, int]]: ... + def getlength( + self, + string: str | bytes, + mode: str, + dir: str | None, + features: list[str] | None, + lang: str | None, + /, + ) -> float: ... + def getvarnames(self) -> list[bytes]: ... + def getvaraxes(self) -> list[ImageFont.Axis]: ... + def setvarname(self, instance_index: int, /) -> None: ... + def setvaraxes(self, axes: list[float], /) -> None: ... + +def getfont( + filename: str | bytes, + size: float, + index: int, + encoding: str, + font_bytes: bytes, + layout_engine: int, +) -> Font: ... +def __getattr__(name: str) -> Any: ... diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/_imagingmath.cpython-312-x86_64-linux-gnu.so b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/_imagingmath.cpython-312-x86_64-linux-gnu.so new file mode 100755 index 000000000..5224936e2 Binary files /dev/null and b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/_imagingmath.cpython-312-x86_64-linux-gnu.so differ diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/_imagingmath.pyi b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/_imagingmath.pyi new file mode 100644 index 000000000..e27843e53 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/_imagingmath.pyi @@ -0,0 +1,3 @@ +from typing import Any + +def __getattr__(name: str) -> Any: ... diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/_imagingmorph.cpython-312-x86_64-linux-gnu.so b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/_imagingmorph.cpython-312-x86_64-linux-gnu.so new file mode 100755 index 000000000..d7c523670 Binary files /dev/null and b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/_imagingmorph.cpython-312-x86_64-linux-gnu.so differ diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/_imagingmorph.pyi b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/_imagingmorph.pyi new file mode 100644 index 000000000..e27843e53 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/_imagingmorph.pyi @@ -0,0 +1,3 @@ +from typing import Any + +def __getattr__(name: str) -> Any: ... diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/_imagingtk.cpython-312-x86_64-linux-gnu.so b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/_imagingtk.cpython-312-x86_64-linux-gnu.so new file mode 100755 index 000000000..16e18d264 Binary files /dev/null and b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/_imagingtk.cpython-312-x86_64-linux-gnu.so differ diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/_imagingtk.pyi b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/_imagingtk.pyi new file mode 100644 index 000000000..e27843e53 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/_imagingtk.pyi @@ -0,0 +1,3 @@ +from typing import Any + +def __getattr__(name: str) -> Any: ... diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/_tkinter_finder.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/_tkinter_finder.py new file mode 100644 index 000000000..9c0143003 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/_tkinter_finder.py @@ -0,0 +1,20 @@ +"""Find compiled module linking to Tcl / Tk libraries""" + +from __future__ import annotations + +import sys +import tkinter + +tk = getattr(tkinter, "_tkinter") + +try: + if hasattr(sys, "pypy_find_executable"): + TKINTER_LIB = tk.tklib_cffi.__file__ + else: + TKINTER_LIB = tk.__file__ +except AttributeError: + # _tkinter may be compiled directly into Python, in which case __file__ is + # not available. load_tkinter_funcs will check the binary first in any case. + TKINTER_LIB = None + +tk_version = str(tkinter.TkVersion) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/_typing.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/_typing.py new file mode 100644 index 000000000..a941f8980 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/_typing.py @@ -0,0 +1,45 @@ +from __future__ import annotations + +import os +import sys +from collections.abc import Sequence +from typing import Any, Protocol, TypeVar + +TYPE_CHECKING = False +if TYPE_CHECKING: + from numbers import _IntegralLike as IntegralLike + + try: + import numpy.typing as npt + + NumpyArray = npt.NDArray[Any] + except ImportError: + pass + +if sys.version_info >= (3, 13): + from types import CapsuleType +else: + CapsuleType = object + +if sys.version_info >= (3, 12): + from collections.abc import Buffer +else: + Buffer = Any + + +_Ink = float | tuple[int, ...] | str + +Coords = Sequence[float] | Sequence[Sequence[float]] + + +_T_co = TypeVar("_T_co", covariant=True) + + +class SupportsRead(Protocol[_T_co]): + def read(self, length: int = ..., /) -> _T_co: ... + + +StrOrBytesPath = str | bytes | os.PathLike[str] | os.PathLike[bytes] + + +__all__ = ["Buffer", "IntegralLike", "StrOrBytesPath", "SupportsRead"] diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/_util.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/_util.py new file mode 100644 index 000000000..b1fa6a0f3 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/_util.py @@ -0,0 +1,29 @@ +from __future__ import annotations + +import os + +TYPE_CHECKING = False +if TYPE_CHECKING: + from typing import Any, NoReturn, TypeGuard + + from ._typing import StrOrBytesPath + + +def is_path(f: Any) -> TypeGuard[StrOrBytesPath]: + return isinstance(f, (bytes, str, os.PathLike)) + + +class DeferredError: + def __init__(self, ex: BaseException): + self.ex = ex + + def __getattr__(self, elt: str) -> NoReturn: + raise self.ex + + @staticmethod + def new(ex: BaseException) -> Any: + """ + Creates an object that raises the wrapped exception ``ex`` when used, + and casts it to :py:obj:`~typing.Any` type. + """ + return DeferredError(ex) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/_version.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/_version.py new file mode 100644 index 000000000..72d11ae92 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/_version.py @@ -0,0 +1,4 @@ +# Master version for Pillow +from __future__ import annotations + +__version__ = "12.2.0" diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/_webp.cpython-312-x86_64-linux-gnu.so b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/_webp.cpython-312-x86_64-linux-gnu.so new file mode 100755 index 000000000..0afd77c90 Binary files /dev/null and b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/_webp.cpython-312-x86_64-linux-gnu.so differ diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/_webp.pyi b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/_webp.pyi new file mode 100644 index 000000000..e27843e53 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/_webp.pyi @@ -0,0 +1,3 @@ +from typing import Any + +def __getattr__(name: str) -> Any: ... diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/features.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/features.py new file mode 100644 index 000000000..ff32c2510 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/features.py @@ -0,0 +1,343 @@ +from __future__ import annotations + +import collections +import os +import sys +import warnings +from typing import IO + +import PIL + +from . import Image + +modules = { + "pil": ("PIL._imaging", "PILLOW_VERSION"), + "tkinter": ("PIL._tkinter_finder", "tk_version"), + "freetype2": ("PIL._imagingft", "freetype2_version"), + "littlecms2": ("PIL._imagingcms", "littlecms_version"), + "webp": ("PIL._webp", "webpdecoder_version"), + "avif": ("PIL._avif", "libavif_version"), +} + + +def check_module(feature: str) -> bool: + """ + Checks if a module is available. + + :param feature: The module to check for. + :returns: ``True`` if available, ``False`` otherwise. + :raises ValueError: If the module is not defined in this version of Pillow. + """ + if feature not in modules: + msg = f"Unknown module {feature}" + raise ValueError(msg) + + module, ver = modules[feature] + + try: + __import__(module) + return True + except ModuleNotFoundError: + return False + except ImportError as ex: + warnings.warn(str(ex)) + return False + + +def version_module(feature: str) -> str | None: + """ + :param feature: The module to check for. + :returns: + The loaded version number as a string, or ``None`` if unknown or not available. + :raises ValueError: If the module is not defined in this version of Pillow. + """ + if not check_module(feature): + return None + + module, ver = modules[feature] + + return getattr(__import__(module, fromlist=[ver]), ver) + + +def get_supported_modules() -> list[str]: + """ + :returns: A list of all supported modules. + """ + return [f for f in modules if check_module(f)] + + +codecs = { + "jpg": ("jpeg", "jpeglib"), + "jpg_2000": ("jpeg2k", "jp2klib"), + "zlib": ("zip", "zlib"), + "libtiff": ("libtiff", "libtiff"), +} + + +def check_codec(feature: str) -> bool: + """ + Checks if a codec is available. + + :param feature: The codec to check for. + :returns: ``True`` if available, ``False`` otherwise. + :raises ValueError: If the codec is not defined in this version of Pillow. + """ + if feature not in codecs: + msg = f"Unknown codec {feature}" + raise ValueError(msg) + + codec, lib = codecs[feature] + + return f"{codec}_encoder" in dir(Image.core) + + +def version_codec(feature: str) -> str | None: + """ + :param feature: The codec to check for. + :returns: + The version number as a string, or ``None`` if not available. + Checked at compile time for ``jpg``, run-time otherwise. + :raises ValueError: If the codec is not defined in this version of Pillow. + """ + if not check_codec(feature): + return None + + codec, lib = codecs[feature] + + version = getattr(Image.core, f"{lib}_version") + + if feature == "libtiff": + return version.split("\n")[0].split("Version ")[1] + + return version + + +def get_supported_codecs() -> list[str]: + """ + :returns: A list of all supported codecs. + """ + return [f for f in codecs if check_codec(f)] + + +features: dict[str, tuple[str, str, str | None]] = { + "raqm": ("PIL._imagingft", "HAVE_RAQM", "raqm_version"), + "fribidi": ("PIL._imagingft", "HAVE_FRIBIDI", "fribidi_version"), + "harfbuzz": ("PIL._imagingft", "HAVE_HARFBUZZ", "harfbuzz_version"), + "libjpeg_turbo": ("PIL._imaging", "HAVE_LIBJPEGTURBO", "libjpeg_turbo_version"), + "mozjpeg": ("PIL._imaging", "HAVE_MOZJPEG", "libjpeg_turbo_version"), + "zlib_ng": ("PIL._imaging", "HAVE_ZLIBNG", "zlib_ng_version"), + "libimagequant": ("PIL._imaging", "HAVE_LIBIMAGEQUANT", "imagequant_version"), + "xcb": ("PIL._imaging", "HAVE_XCB", None), +} + + +def check_feature(feature: str) -> bool | None: + """ + Checks if a feature is available. + + :param feature: The feature to check for. + :returns: ``True`` if available, ``False`` if unavailable, ``None`` if unknown. + :raises ValueError: If the feature is not defined in this version of Pillow. + """ + if feature not in features: + msg = f"Unknown feature {feature}" + raise ValueError(msg) + + module, flag, ver = features[feature] + + try: + imported_module = __import__(module, fromlist=["PIL"]) + return getattr(imported_module, flag) + except ModuleNotFoundError: + return None + except ImportError as ex: + warnings.warn(str(ex)) + return None + + +def version_feature(feature: str) -> str | None: + """ + :param feature: The feature to check for. + :returns: The version number as a string, or ``None`` if not available. + :raises ValueError: If the feature is not defined in this version of Pillow. + """ + if not check_feature(feature): + return None + + module, flag, ver = features[feature] + + if ver is None: + return None + + return getattr(__import__(module, fromlist=[ver]), ver) + + +def get_supported_features() -> list[str]: + """ + :returns: A list of all supported features. + """ + return [f for f in features if check_feature(f)] + + +def check(feature: str) -> bool | None: + """ + :param feature: A module, codec, or feature name. + :returns: + ``True`` if the module, codec, or feature is available, + ``False`` or ``None`` otherwise. + """ + + if feature in modules: + return check_module(feature) + if feature in codecs: + return check_codec(feature) + if feature in features: + return check_feature(feature) + warnings.warn(f"Unknown feature '{feature}'.", stacklevel=2) + return False + + +def version(feature: str) -> str | None: + """ + :param feature: + The module, codec, or feature to check for. + :returns: + The version number as a string, or ``None`` if unknown or not available. + """ + if feature in modules: + return version_module(feature) + if feature in codecs: + return version_codec(feature) + if feature in features: + return version_feature(feature) + return None + + +def get_supported() -> list[str]: + """ + :returns: A list of all supported modules, features, and codecs. + """ + + ret = get_supported_modules() + ret.extend(get_supported_features()) + ret.extend(get_supported_codecs()) + return ret + + +def pilinfo(out: IO[str] | None = None, supported_formats: bool = True) -> None: + """ + Prints information about this installation of Pillow. + This function can be called with ``python3 -m PIL``. + It can also be called with ``python3 -m PIL.report`` or ``python3 -m PIL --report`` + to have "supported_formats" set to ``False``, omitting the list of all supported + image file formats. + + :param out: + The output stream to print to. Defaults to ``sys.stdout`` if ``None``. + :param supported_formats: + If ``True``, a list of all supported image file formats will be printed. + """ + + if out is None: + out = sys.stdout + + Image.init() + + print("-" * 68, file=out) + print(f"Pillow {PIL.__version__}", file=out) + py_version_lines = sys.version.splitlines() + print(f"Python {py_version_lines[0].strip()}", file=out) + for py_version in py_version_lines[1:]: + print(f" {py_version.strip()}", file=out) + print("-" * 68, file=out) + print(f"Python executable is {sys.executable or 'unknown'}", file=out) + if sys.prefix != sys.base_prefix: + print(f"Environment Python files loaded from {sys.prefix}", file=out) + print(f"System Python files loaded from {sys.base_prefix}", file=out) + print("-" * 68, file=out) + print( + f"Python Pillow modules loaded from {os.path.dirname(Image.__file__)}", + file=out, + ) + print( + f"Binary Pillow modules loaded from {os.path.dirname(Image.core.__file__)}", + file=out, + ) + print("-" * 68, file=out) + + for name, feature in [ + ("pil", "PIL CORE"), + ("tkinter", "TKINTER"), + ("freetype2", "FREETYPE2"), + ("littlecms2", "LITTLECMS2"), + ("webp", "WEBP"), + ("avif", "AVIF"), + ("jpg", "JPEG"), + ("jpg_2000", "OPENJPEG (JPEG2000)"), + ("zlib", "ZLIB (PNG/ZIP)"), + ("libtiff", "LIBTIFF"), + ("raqm", "RAQM (Bidirectional Text)"), + ("libimagequant", "LIBIMAGEQUANT (Quantization method)"), + ("xcb", "XCB (X protocol)"), + ]: + if check(name): + v: str | None = None + if name == "jpg": + libjpeg_turbo_version = version_feature("libjpeg_turbo") + if libjpeg_turbo_version is not None: + v = "mozjpeg" if check_feature("mozjpeg") else "libjpeg-turbo" + v += " " + libjpeg_turbo_version + if v is None: + v = version(name) + if v is not None: + version_static = name in ("pil", "jpg") + if name == "littlecms2": + # this check is also in src/_imagingcms.c:setup_module() + version_static = tuple(int(x) for x in v.split(".")) < (2, 7) + t = "compiled for" if version_static else "loaded" + if name == "zlib": + zlib_ng_version = version_feature("zlib_ng") + if zlib_ng_version is not None: + v += ", compiled for zlib-ng " + zlib_ng_version + elif name == "raqm": + for f in ("fribidi", "harfbuzz"): + v2 = version_feature(f) + if v2 is not None: + v += f", {f} {v2}" + print("---", feature, "support ok,", t, v, file=out) + else: + print("---", feature, "support ok", file=out) + else: + print("***", feature, "support not installed", file=out) + print("-" * 68, file=out) + + if supported_formats: + extensions = collections.defaultdict(list) + for ext, i in Image.EXTENSION.items(): + extensions[i].append(ext) + + for i in sorted(Image.ID): + line = f"{i}" + if i in Image.MIME: + line = f"{line} {Image.MIME[i]}" + print(line, file=out) + + if i in extensions: + print( + "Extensions: {}".format(", ".join(sorted(extensions[i]))), file=out + ) + + features = [] + if i in Image.OPEN: + features.append("open") + if i in Image.SAVE: + features.append("save") + if i in Image.SAVE_ALL: + features.append("save_all") + if i in Image.DECODERS: + features.append("decode") + if i in Image.ENCODERS: + features.append("encode") + + print("Features: {}".format(", ".join(features)), file=out) + print("-" * 68, file=out) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/py.typed b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/py.typed new file mode 100644 index 000000000..e69de29bb diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/report.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/report.py new file mode 100644 index 000000000..d2815e845 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/PIL/report.py @@ -0,0 +1,5 @@ +from __future__ import annotations + +from .features import pilinfo + +pilinfo(supported_formats=False) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/_yaml/__init__.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/_yaml/__init__.py new file mode 100644 index 000000000..7baa8c4b6 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/_yaml/__init__.py @@ -0,0 +1,33 @@ +# This is a stub package designed to roughly emulate the _yaml +# extension module, which previously existed as a standalone module +# and has been moved into the `yaml` package namespace. +# It does not perfectly mimic its old counterpart, but should get +# close enough for anyone who's relying on it even when they shouldn't. +import yaml + +# in some circumstances, the yaml module we imoprted may be from a different version, so we need +# to tread carefully when poking at it here (it may not have the attributes we expect) +if not getattr(yaml, '__with_libyaml__', False): + from sys import version_info + + exc = ModuleNotFoundError if version_info >= (3, 6) else ImportError + raise exc("No module named '_yaml'") +else: + from yaml._yaml import * + import warnings + warnings.warn( + 'The _yaml extension module is now located at yaml._yaml' + ' and its location is subject to change. To use the' + ' LibYAML-based parser and emitter, import from `yaml`:' + ' `from yaml import CLoader as Loader, CDumper as Dumper`.', + DeprecationWarning + ) + del warnings + # Don't `del yaml` here because yaml is actually an existing + # namespace member of _yaml. + +__name__ = '_yaml' +# If the module is top-level (i.e. not a part of any specific package) +# then the attribute should be set to ''. +# https://docs.python.org/3.8/library/types.html +__package__ = '' diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit-1.9.4.dist-info/INSTALLER b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit-1.9.4.dist-info/INSTALLER new file mode 100644 index 000000000..a1b589e38 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit-1.9.4.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit-1.9.4.dist-info/METADATA b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit-1.9.4.dist-info/METADATA new file mode 100644 index 000000000..2b9626e96 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit-1.9.4.dist-info/METADATA @@ -0,0 +1,212 @@ +Metadata-Version: 2.4 +Name: bandit +Version: 1.9.4 +Summary: Security oriented static analyser for python code. +Home-page: https://bandit.readthedocs.io/ +Author: PyCQA +Author-email: code-quality@python.org +License: Apache-2.0 +Project-URL: Documentation, https://bandit.readthedocs.io/ +Project-URL: Release Notes, https://github.com/PyCQA/bandit/releases +Project-URL: Source Code, https://github.com/PyCQA/bandit +Project-URL: Issue Tracker, https://github.com/PyCQA/bandit/issues +Project-URL: Discord, https://discord.gg/qYxpadCgkx +Project-URL: Sponsor, https://psfmember.org/civicrm/contribute/transact/?reset=1&id=42 +Classifier: Development Status :: 5 - Production/Stable +Classifier: Environment :: Console +Classifier: Intended Audience :: Information Technology +Classifier: Intended Audience :: System Administrators +Classifier: Intended Audience :: Developers +Classifier: Operating System :: POSIX :: Linux +Classifier: Operating System :: MacOS :: MacOS X +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Programming Language :: Python :: 3.14 +Classifier: Programming Language :: Python :: 3 :: Only +Classifier: Topic :: Security +Requires-Python: >=3.10 +License-File: LICENSE +Requires-Dist: PyYAML>=5.3.1 +Requires-Dist: stevedore>=1.20.0 +Requires-Dist: rich +Requires-Dist: colorama>=0.3.9; platform_system == "Windows" +Provides-Extra: yaml +Requires-Dist: PyYAML; extra == "yaml" +Provides-Extra: toml +Requires-Dist: tomli>=1.1.0; python_version < "3.11" and extra == "toml" +Provides-Extra: baseline +Requires-Dist: GitPython>=3.1.30; extra == "baseline" +Provides-Extra: sarif +Requires-Dist: sarif-om>=1.0.4; extra == "sarif" +Requires-Dist: jschema-to-python>=1.2.3; extra == "sarif" +Provides-Extra: test +Requires-Dist: coverage>=4.5.4; extra == "test" +Requires-Dist: fixtures>=3.0.0; extra == "test" +Requires-Dist: flake8>=4.0.0; extra == "test" +Requires-Dist: stestr>=2.5.0; extra == "test" +Requires-Dist: testscenarios>=0.5.0; extra == "test" +Requires-Dist: testtools>=2.3.0; extra == "test" +Requires-Dist: beautifulsoup4>=4.8.0; extra == "test" +Requires-Dist: pylint==1.9.4; extra == "test" +Dynamic: author +Dynamic: author-email +Dynamic: description +Dynamic: home-page +Dynamic: license +Dynamic: license-file +Dynamic: project-url +Dynamic: provides-extra +Dynamic: requires-dist +Dynamic: requires-python +Dynamic: summary + +.. image:: https://raw.githubusercontent.com/pycqa/bandit/main/logo/logotype-sm.png + :alt: Bandit + +====== + +.. image:: https://github.com/PyCQA/bandit/actions/workflows/pythonpackage.yml/badge.svg?branch=main + :target: https://github.com/PyCQA/bandit/actions?query=workflow%3A%22Build+and+Test+Bandit%22+branch%3Amain + :alt: Build Status + +.. image:: https://readthedocs.org/projects/bandit/badge/?version=latest + :target: https://readthedocs.org/projects/bandit/ + :alt: Docs Status + +.. image:: https://img.shields.io/pypi/v/bandit.svg + :target: https://pypi.org/project/bandit/ + :alt: Latest Version + +.. image:: https://img.shields.io/pypi/pyversions/bandit.svg + :target: https://pypi.org/project/bandit/ + :alt: Python Versions + +.. image:: https://img.shields.io/pypi/format/bandit.svg + :target: https://pypi.org/project/bandit/ + :alt: Format + +.. image:: https://img.shields.io/badge/license-Apache%202-blue.svg + :target: https://github.com/PyCQA/bandit/blob/main/LICENSE + :alt: License + +.. image:: https://img.shields.io/discord/825463413634891776.svg + :target: https://discord.gg/qYxpadCgkx + :alt: Discord + +A security linter from PyCQA + +* Free software: Apache license +* Documentation: https://bandit.readthedocs.io/en/latest/ +* Source: https://github.com/PyCQA/bandit +* Bugs: https://github.com/PyCQA/bandit/issues +* Contributing: https://github.com/PyCQA/bandit/blob/main/CONTRIBUTING.md + +Overview +-------- + +Bandit is a tool designed to find common security issues in Python code. To do +this Bandit processes each file, builds an AST from it, and runs appropriate +plugins against the AST nodes. Once Bandit has finished scanning all the files +it generates a report. + +Bandit was originally developed within the OpenStack Security Project and +later rehomed to PyCQA. + +.. image:: https://raw.githubusercontent.com/pycqa/bandit/main/bandit-terminal.png + :alt: Bandit Example Screen Shot + +Show Your Style +--------------- + +.. image:: https://img.shields.io/badge/security-bandit-yellow.svg + :target: https://github.com/PyCQA/bandit + :alt: Security Status + +Use our badge in your project's README! + +using Markdown:: + + [![security: bandit](https://img.shields.io/badge/security-bandit-yellow.svg)](https://github.com/PyCQA/bandit) + +using RST:: + + .. image:: https://img.shields.io/badge/security-bandit-yellow.svg + :target: https://github.com/PyCQA/bandit + :alt: Security Status + +References +---------- + +Python AST module documentation: https://docs.python.org/3/library/ast.html + +Green Tree Snakes - the missing Python AST docs: +https://greentreesnakes.readthedocs.org/en/latest/ + +Documentation of the various types of AST nodes that Bandit currently covers +or could be extended to cover: +https://greentreesnakes.readthedocs.org/en/latest/nodes.html + +Container Images +---------------- + +Bandit is available as a container image, built within the bandit repository +using GitHub Actions. The image is available on ghcr.io: + +.. code-block:: console + + docker pull ghcr.io/pycqa/bandit/bandit + +The image is built for the following architectures: + +* amd64 +* arm64 +* armv7 +* armv8 + +To pull a specific architecture, use the following format: + +.. code-block:: console + + docker pull --platform= ghcr.io/pycqa/bandit/bandit:latest + +Every image is signed with sigstore cosign and it is possible to verify the +source of origin using the following cosign command: + +.. code-block:: console + + cosign verify ghcr.io/pycqa/bandit/bandit:latest \ + --certificate-identity https://github.com/pycqa/bandit/.github/workflows/build-publish-image.yml@refs/tags/ \ + --certificate-oidc-issuer https://token.actions.githubusercontent.com + +Where `` is the release version of Bandit. + +Sponsors +-------- + +The development of Bandit is made possible by the following sponsors: + +.. list-table:: + :width: 100% + :class: borderless + + * - .. image:: https://avatars.githubusercontent.com/u/34240465?s=200&v=4 + :target: https://opensource.mercedes-benz.com/ + :alt: Mercedes-Benz + :width: 88 + + - .. image:: https://github.githubassets.com/assets/tidelift-8cea37dea8fc.svg + :target: https://tidelift.com/lifter/search/pypi/bandit + :alt: Tidelift + :width: 88 + + - .. image:: https://avatars.githubusercontent.com/u/110237746?s=200&v=4 + :target: https://stacklok.com/ + :alt: Stacklok + :width: 88 + +If you also ❤️ Bandit, please consider sponsoring. + diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit-1.9.4.dist-info/RECORD b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit-1.9.4.dist-info/RECORD new file mode 100644 index 000000000..a499db904 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit-1.9.4.dist-info/RECORD @@ -0,0 +1,151 @@ +../../../bin/bandit,sha256=6Sn3LBl-L_Hl1jnc2cfnVy9oaLDS2y6wUXHsdqsEf5E,293 +../../../bin/bandit-baseline,sha256=mtHGKeNfVviXKmDlYxLFqLhsixmSsgijQOEZvveoTRk,297 +../../../bin/bandit-config-generator,sha256=j85Ec2A5oFPK10gMIKxyNEN2D0qBWAnsfq0KX7xRdiM,305 +../../../share/man/man1/bandit.1,sha256=k1copRknkrnXzOyOAvdvC6iwl-QAYUG1HOWRsAtkdWI,6545 +bandit-1.9.4.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +bandit-1.9.4.dist-info/METADATA,sha256=pc_7769UxRQY4Zz1dl3tSa8gsnoluOtEDyHZ21DJzpo,7101 +bandit-1.9.4.dist-info/RECORD,, +bandit-1.9.4.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +bandit-1.9.4.dist-info/WHEEL,sha256=SmOxYU7pzNKBqASvQJ7DjX3XGUF92lrGhMb3R6_iiqI,91 +bandit-1.9.4.dist-info/entry_points.txt,sha256=WoSLidZc14iE9GTbJR_2SkYGg03fNqaIhmgf2kHSXN8,4156 +bandit-1.9.4.dist-info/licenses/LICENSE,sha256=CeipvOyAZxBGUsFoaFqwkx54aPnIKEtm9a5u2uXxEws,10142 +bandit-1.9.4.dist-info/pbr.json,sha256=Rs6XgS2MJcc1NWYzMCjeEr8KKqIZVIHxUm8tOIiltJU,47 +bandit-1.9.4.dist-info/top_level.txt,sha256=SVJ-U-In_cpe2PQq5ZOlxjEnlAV5MfjvfFuGzg8wgdg,7 +bandit/__init__.py,sha256=yjou8RxyHpx6zHjYcBa4_CUffNYIdERGCPx6PirAo-8,683 +bandit/__main__.py,sha256=PtnKPE5k9V79ArPscEozE9ruwUIMuHlYv3yiCMJ5UBs,571 +bandit/__pycache__/__init__.cpython-312.pyc,, +bandit/__pycache__/__main__.cpython-312.pyc,, +bandit/blacklists/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +bandit/blacklists/__pycache__/__init__.cpython-312.pyc,, +bandit/blacklists/__pycache__/calls.cpython-312.pyc,, +bandit/blacklists/__pycache__/imports.cpython-312.pyc,, +bandit/blacklists/__pycache__/utils.cpython-312.pyc,, +bandit/blacklists/calls.py,sha256=QCVOeBCZMrxLMo4ELUbuhCt2QorTcUe9vzqFDR0T1mU,29363 +bandit/blacklists/imports.py,sha256=3lCND02DoDE9EFHPeFhEegzP3YTZb4dk9RCUA-96Tek,17269 +bandit/blacklists/utils.py,sha256=OBm8dmmQsgp5_dJcm2-eAi69u5eXujeOYDg6zhMNeTM,420 +bandit/cli/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +bandit/cli/__pycache__/__init__.cpython-312.pyc,, +bandit/cli/__pycache__/baseline.cpython-312.pyc,, +bandit/cli/__pycache__/config_generator.cpython-312.pyc,, +bandit/cli/__pycache__/main.cpython-312.pyc,, +bandit/cli/baseline.py,sha256=Z0VsMRmKyTxTyWLELtuKret9eiRkIqH804phSzzn_wU,7841 +bandit/cli/config_generator.py,sha256=umRDttgCxuyPG_7bOXCHgsEUi_xwaQbwgSA3tdGoUfk,6281 +bandit/cli/main.py,sha256=X2FBIrc4plB_6uetRUr6mN5qZ27lyeFfsvFZnec1874,20876 +bandit/core/__init__.py,sha256=NwxNqwUmUIJBQwnsOG58nvi6owEldiyGmkkig0a-4nw,558 +bandit/core/__pycache__/__init__.cpython-312.pyc,, +bandit/core/__pycache__/blacklisting.cpython-312.pyc,, +bandit/core/__pycache__/config.cpython-312.pyc,, +bandit/core/__pycache__/constants.cpython-312.pyc,, +bandit/core/__pycache__/context.cpython-312.pyc,, +bandit/core/__pycache__/docs_utils.cpython-312.pyc,, +bandit/core/__pycache__/extension_loader.cpython-312.pyc,, +bandit/core/__pycache__/issue.cpython-312.pyc,, +bandit/core/__pycache__/manager.cpython-312.pyc,, +bandit/core/__pycache__/meta_ast.cpython-312.pyc,, +bandit/core/__pycache__/metrics.cpython-312.pyc,, +bandit/core/__pycache__/node_visitor.cpython-312.pyc,, +bandit/core/__pycache__/test_properties.cpython-312.pyc,, +bandit/core/__pycache__/test_set.cpython-312.pyc,, +bandit/core/__pycache__/tester.cpython-312.pyc,, +bandit/core/__pycache__/utils.cpython-312.pyc,, +bandit/core/blacklisting.py,sha256=AcV2Xe_gFmqRFTezvtOxDUv2z6r4v3mcXhg63MHQ85c,2780 +bandit/core/config.py,sha256=6VCkWN3PFGIG9x4FFrNjBvhTffxRZ_KEnipNmlgzav8,9840 +bandit/core/constants.py,sha256=yaB2ks72eOzrnfN7xOr3zFWxsc8eCMnppnIBj-_Jmn0,1220 +bandit/core/context.py,sha256=27qPogcEZcHdTV2ByGnBpJso7Kr8bwObk5rnunGqrOs,10667 +bandit/core/docs_utils.py,sha256=iDWwx4XTnIcAyQhLp6DSyP9C1M2pkgA2Ktb686cyf_I,1779 +bandit/core/extension_loader.py,sha256=6w8qE64A8vYU6wP3ryVZfn7Yxy5SFpw_zEnB5ttWeyU,4039 +bandit/core/issue.py,sha256=BituIds2j2gbSMaMf9iM7N_yzcGo0-qQq38Pp-Ae7ko,7069 +bandit/core/manager.py,sha256=WAxO-4moDtbgm_AuNR0TqRFd_cheYe-x46CTjV5WIZQ,17284 +bandit/core/meta_ast.py,sha256=rAUdLwsm4eTPN0oXvzyIOfVXsuKV93MLMJsUC86hTWc,1136 +bandit/core/metrics.py,sha256=wDjPmrujRszaqY0zI1W7tVTVYhnC-kHo8wCaf5vYKBA,3454 +bandit/core/node_visitor.py,sha256=HsSSE3KnKxLfS_57hK_VDgfCud6LvjA_xraZ58rMmdg,10830 +bandit/core/test_properties.py,sha256=_letTk7y9Sp5SyRaq2clLeNRjKCWnOxucglGtUMLE5Q,2106 +bandit/core/test_set.py,sha256=jweZ7eK1IGhodabF6DHO_DhBMMrHxFU03R5_z4sSrJc,4054 +bandit/core/tester.py,sha256=0im7I_Ha0iOfMqUnE6rh23E9u3X4gEww7CpxF6UCaW4,6602 +bandit/core/utils.py,sha256=hkg92rjpuYlxSlYJiNNEXQ2_Ot07-xkcoVhiNxdmbeg,12297 +bandit/formatters/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +bandit/formatters/__pycache__/__init__.cpython-312.pyc,, +bandit/formatters/__pycache__/csv.cpython-312.pyc,, +bandit/formatters/__pycache__/custom.cpython-312.pyc,, +bandit/formatters/__pycache__/html.cpython-312.pyc,, +bandit/formatters/__pycache__/json.cpython-312.pyc,, +bandit/formatters/__pycache__/sarif.cpython-312.pyc,, +bandit/formatters/__pycache__/screen.cpython-312.pyc,, +bandit/formatters/__pycache__/text.cpython-312.pyc,, +bandit/formatters/__pycache__/utils.cpython-312.pyc,, +bandit/formatters/__pycache__/xml.cpython-312.pyc,, +bandit/formatters/__pycache__/yaml.cpython-312.pyc,, +bandit/formatters/csv.py,sha256=IiTLncVx3hnn7A7pJpJ5Y9vxibhxHIvZnGhezhYYKSg,2313 +bandit/formatters/custom.py,sha256=21GgrLiaStknoVD9GU-sWku4nK7hJI4O7-pgyHQacbw,5363 +bandit/formatters/html.py,sha256=VNHmmKAsZWV_S-ROd4DEXJd_Uy1ipOvbD50BzihubKU,8489 +bandit/formatters/json.py,sha256=8fA-v5lsLTdoB5UwCVqxhpgeYAZDY1tK7wsZjUAFLqg,4330 +bandit/formatters/sarif.py,sha256=jP5kd9Eut0BiPIJ7e8J38vp7BLLtJFaRfEGSwGQZ41I,10791 +bandit/formatters/screen.py,sha256=71cPOEqoDznO1aHbVt-zAjWLeeTMUwYGj5kt86UGdrM,6850 +bandit/formatters/text.py,sha256=Vhh_AUATxiQpLcm0xtZ91GSJ5QeES_rXMVy1kS1H_U4,5978 +bandit/formatters/utils.py,sha256=MXmcXC1fBeRbURQKqUtqhPMtAEMO6I6-MIwcdrI_UFA,390 +bandit/formatters/xml.py,sha256=pbsa66tYlGfybq6_N5gOhTgKnSQnvJFs39z8zFCwac4,2753 +bandit/formatters/yaml.py,sha256=lmJDFXQmxp7vdC7koqRWMb9IRSMXyXEFhH2zoNu8oHc,3463 +bandit/plugins/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +bandit/plugins/__pycache__/__init__.cpython-312.pyc,, +bandit/plugins/__pycache__/app_debug.cpython-312.pyc,, +bandit/plugins/__pycache__/asserts.cpython-312.pyc,, +bandit/plugins/__pycache__/crypto_request_no_cert_validation.cpython-312.pyc,, +bandit/plugins/__pycache__/django_sql_injection.cpython-312.pyc,, +bandit/plugins/__pycache__/django_xss.cpython-312.pyc,, +bandit/plugins/__pycache__/exec.cpython-312.pyc,, +bandit/plugins/__pycache__/general_bad_file_permissions.cpython-312.pyc,, +bandit/plugins/__pycache__/general_bind_all_interfaces.cpython-312.pyc,, +bandit/plugins/__pycache__/general_hardcoded_password.cpython-312.pyc,, +bandit/plugins/__pycache__/general_hardcoded_tmp.cpython-312.pyc,, +bandit/plugins/__pycache__/hashlib_insecure_functions.cpython-312.pyc,, +bandit/plugins/__pycache__/huggingface_unsafe_download.cpython-312.pyc,, +bandit/plugins/__pycache__/injection_paramiko.cpython-312.pyc,, +bandit/plugins/__pycache__/injection_shell.cpython-312.pyc,, +bandit/plugins/__pycache__/injection_sql.cpython-312.pyc,, +bandit/plugins/__pycache__/injection_wildcard.cpython-312.pyc,, +bandit/plugins/__pycache__/insecure_ssl_tls.cpython-312.pyc,, +bandit/plugins/__pycache__/jinja2_templates.cpython-312.pyc,, +bandit/plugins/__pycache__/logging_config_insecure_listen.cpython-312.pyc,, +bandit/plugins/__pycache__/mako_templates.cpython-312.pyc,, +bandit/plugins/__pycache__/markupsafe_markup_xss.cpython-312.pyc,, +bandit/plugins/__pycache__/pytorch_load.cpython-312.pyc,, +bandit/plugins/__pycache__/request_without_timeout.cpython-312.pyc,, +bandit/plugins/__pycache__/snmp_security_check.cpython-312.pyc,, +bandit/plugins/__pycache__/ssh_no_host_key_verification.cpython-312.pyc,, +bandit/plugins/__pycache__/tarfile_unsafe_members.cpython-312.pyc,, +bandit/plugins/__pycache__/trojansource.cpython-312.pyc,, +bandit/plugins/__pycache__/try_except_continue.cpython-312.pyc,, +bandit/plugins/__pycache__/try_except_pass.cpython-312.pyc,, +bandit/plugins/__pycache__/weak_cryptographic_key.cpython-312.pyc,, +bandit/plugins/__pycache__/yaml_load.cpython-312.pyc,, +bandit/plugins/app_debug.py,sha256=0Zp-DTiLnuvF-jlZKhCEK-9YzRMcUc7JS6mxWV01hFc,2257 +bandit/plugins/asserts.py,sha256=iOP5WRjdpFc8j62pIkQ_cx-LYDW1aSv8qpfdU78AoXU,2305 +bandit/plugins/crypto_request_no_cert_validation.py,sha256=AyESgBZ7JtzieeJTnRXu0kknf7og1B5GI-6uA3kLbls,2660 +bandit/plugins/django_sql_injection.py,sha256=iYNAWU-j0DRgj5rDN7sboWvxcm2czm0i8849N6tzIdw,5203 +bandit/plugins/django_xss.py,sha256=HOUAk6w2lMF6RNsZsyP7i_1qa4iJGXg2Ek_Ni28joQ4,10302 +bandit/plugins/exec.py,sha256=5kosSmgI8Y2XM4Z_5hwIq7WRTmdpfDM5E7uXYTaGxgo,1357 +bandit/plugins/general_bad_file_permissions.py,sha256=8T59CP-aluBtXkQdyyQJljFiLvK4yVIy3fDSggw53Eg,3340 +bandit/plugins/general_bind_all_interfaces.py,sha256=Mn8YBkfF5Qwhx1QRMHB-5HNnzhR4neP0lI_6LyQr4Gg,1522 +bandit/plugins/general_hardcoded_password.py,sha256=YFk4-13a9duCNt5rZ0Vuj_4a1XOOFXYG7c_DgPIKpUg,8770 +bandit/plugins/general_hardcoded_tmp.py,sha256=OjDZgboZF186RK133GQksRqAkneBP14LxnBn88KSjjs,2301 +bandit/plugins/hashlib_insecure_functions.py,sha256=-cYJKULazbzqwOcq-uAGk5EvDMNTHc9BCubr3l4UHJY,4330 +bandit/plugins/huggingface_unsafe_download.py,sha256=ok-T2exvBg9AnGasmJESrJst0uFlvDarTVI2ap6FU-Y,5899 +bandit/plugins/injection_paramiko.py,sha256=bAbqH-4CHQY1ghQpjlck-Pl8DKq4G6jJoAQCY3PSzYw,2049 +bandit/plugins/injection_shell.py,sha256=ZsScLQAbyk0SQzw0-Pk7kzCxaEYtC8D_4VRzTc7cJ8k,26851 +bandit/plugins/injection_sql.py,sha256=Ub3E1in980NiAqHXj_XvD6ZZsd-rltZKqYhjDjDqtlU,4878 +bandit/plugins/injection_wildcard.py,sha256=GeHJchoDxULuaLeCxMyYuJrxVTC1vx8k6JSsXm5BDFM,5016 +bandit/plugins/insecure_ssl_tls.py,sha256=VrR9qyOyY7o1UTBw-Fw06GbE87SO4wD_j127erVfDLQ,10454 +bandit/plugins/jinja2_templates.py,sha256=5-0hPcJqm-THcZn44CSReq9_oy8Ym9QG_YN-vzv3hhg,5806 +bandit/plugins/logging_config_insecure_listen.py,sha256=UzDtLTiIwRnqpPjPIZbdtYb32BT5E5h2hhC2-m9kxGU,1944 +bandit/plugins/mako_templates.py,sha256=HBhxtofo1gGd8dKPxahJ1ELlv60NYrn0rcX4B-MYtpM,2549 +bandit/plugins/markupsafe_markup_xss.py,sha256=QTFwXe99MK26MtEEmn6tlNdy9ojQY0BMZNvKMZ3cAWg,3704 +bandit/plugins/pytorch_load.py,sha256=yDzFcn17OnkQSGn8fQ8ZzoQNL_tgUFn97dVFA-y1FeM,2672 +bandit/plugins/request_without_timeout.py,sha256=IJadPCwQVEAXZ3h3YscgvgDIzdrHM0_jozYiRN30kyE,3087 +bandit/plugins/snmp_security_check.py,sha256=tTdonRdKMKs5Rq4o4OWznW4_rjna2UhnStNLZTKG58I,3716 +bandit/plugins/ssh_no_host_key_verification.py,sha256=1Fqx5k5gtLvnWk4Gz7bQXwqx4TOxIzUGa-ouYBQGNsI,2732 +bandit/plugins/tarfile_unsafe_members.py,sha256=-VKsrS06IdH4NfbXTphi6d4AUtkjELJAuZIHfQyTKw8,3929 +bandit/plugins/trojansource.py,sha256=W-t2LRSYhoDEk9rlSnYHdPhgSpN1TExNnruMGMh22TY,2428 +bandit/plugins/try_except_continue.py,sha256=K-VrQS_YnifFwz5GC1LAUzGHTbbh9m-LHuDaJwgAS5o,3078 +bandit/plugins/try_except_pass.py,sha256=DwPiiziccoWtgE86aEmU9maKW1W8JuJxqOlnume1nis,2910 +bandit/plugins/weak_cryptographic_key.py,sha256=SGH3YM3LiBrcmuO0GjnQuZCVm42d2C68l1dGKtnwNb8,5544 +bandit/plugins/yaml_load.py,sha256=bOfCZBOcSXB3AAINJbuvcHkHebo-qyMyA4155Lgnx2g,2404 diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit-1.9.4.dist-info/REQUESTED b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit-1.9.4.dist-info/REQUESTED new file mode 100644 index 000000000..e69de29bb diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit-1.9.4.dist-info/WHEEL b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit-1.9.4.dist-info/WHEEL new file mode 100644 index 000000000..8acb95590 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit-1.9.4.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: setuptools (79.0.1) +Root-Is-Purelib: true +Tag: py3-none-any + diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit-1.9.4.dist-info/entry_points.txt b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit-1.9.4.dist-info/entry_points.txt new file mode 100644 index 000000000..8c71592c1 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit-1.9.4.dist-info/entry_points.txt @@ -0,0 +1,63 @@ +[bandit.blacklists] +calls = bandit.blacklists.calls:gen_blacklist +imports = bandit.blacklists.imports:gen_blacklist + +[bandit.formatters] +csv = bandit.formatters.csv:report +custom = bandit.formatters.custom:report +html = bandit.formatters.html:report +json = bandit.formatters.json:report +sarif = bandit.formatters.sarif:report +screen = bandit.formatters.screen:report +txt = bandit.formatters.text:report +xml = bandit.formatters.xml:report +yaml = bandit.formatters.yaml:report + +[bandit.plugins] +any_other_function_with_shell_equals_true = bandit.plugins.injection_shell:any_other_function_with_shell_equals_true +assert_used = bandit.plugins.asserts:assert_used +django_extra_used = bandit.plugins.django_sql_injection:django_extra_used +django_mark_safe = bandit.plugins.django_xss:django_mark_safe +django_rawsql_used = bandit.plugins.django_sql_injection:django_rawsql_used +exec_used = bandit.plugins.exec:exec_used +flask_debug_true = bandit.plugins.app_debug:flask_debug_true +hardcoded_bind_all_interfaces = bandit.plugins.general_bind_all_interfaces:hardcoded_bind_all_interfaces +hardcoded_password_default = bandit.plugins.general_hardcoded_password:hardcoded_password_default +hardcoded_password_funcarg = bandit.plugins.general_hardcoded_password:hardcoded_password_funcarg +hardcoded_password_string = bandit.plugins.general_hardcoded_password:hardcoded_password_string +hardcoded_sql_expressions = bandit.plugins.injection_sql:hardcoded_sql_expressions +hardcoded_tmp_directory = bandit.plugins.general_hardcoded_tmp:hardcoded_tmp_directory +hashlib_insecure_functions = bandit.plugins.hashlib_insecure_functions:hashlib +huggingface_unsafe_download = bandit.plugins.huggingface_unsafe_download:huggingface_unsafe_download +jinja2_autoescape_false = bandit.plugins.jinja2_templates:jinja2_autoescape_false +linux_commands_wildcard_injection = bandit.plugins.injection_wildcard:linux_commands_wildcard_injection +logging_config_insecure_listen = bandit.plugins.logging_config_insecure_listen:logging_config_insecure_listen +markupsafe_markup_xss = bandit.plugins.markupsafe_markup_xss:markupsafe_markup_xss +paramiko_calls = bandit.plugins.injection_paramiko:paramiko_calls +pytorch_load = bandit.plugins.pytorch_load:pytorch_load +request_with_no_cert_validation = bandit.plugins.crypto_request_no_cert_validation:request_with_no_cert_validation +request_without_timeout = bandit.plugins.request_without_timeout:request_without_timeout +set_bad_file_permissions = bandit.plugins.general_bad_file_permissions:set_bad_file_permissions +snmp_insecure_version = bandit.plugins.snmp_security_check:snmp_insecure_version_check +snmp_weak_cryptography = bandit.plugins.snmp_security_check:snmp_crypto_check +ssh_no_host_key_verification = bandit.plugins.ssh_no_host_key_verification:ssh_no_host_key_verification +ssl_with_bad_defaults = bandit.plugins.insecure_ssl_tls:ssl_with_bad_defaults +ssl_with_bad_version = bandit.plugins.insecure_ssl_tls:ssl_with_bad_version +ssl_with_no_version = bandit.plugins.insecure_ssl_tls:ssl_with_no_version +start_process_with_a_shell = bandit.plugins.injection_shell:start_process_with_a_shell +start_process_with_no_shell = bandit.plugins.injection_shell:start_process_with_no_shell +start_process_with_partial_path = bandit.plugins.injection_shell:start_process_with_partial_path +subprocess_popen_with_shell_equals_true = bandit.plugins.injection_shell:subprocess_popen_with_shell_equals_true +subprocess_without_shell_equals_true = bandit.plugins.injection_shell:subprocess_without_shell_equals_true +tarfile_unsafe_members = bandit.plugins.tarfile_unsafe_members:tarfile_unsafe_members +trojansource = bandit.plugins.trojansource:trojansource +try_except_continue = bandit.plugins.try_except_continue:try_except_continue +try_except_pass = bandit.plugins.try_except_pass:try_except_pass +use_of_mako_templates = bandit.plugins.mako_templates:use_of_mako_templates +weak_cryptographic_key = bandit.plugins.weak_cryptographic_key:weak_cryptographic_key +yaml_load = bandit.plugins.yaml_load:yaml_load + +[console_scripts] +bandit = bandit.cli.main:main +bandit-baseline = bandit.cli.baseline:main +bandit-config-generator = bandit.cli.config_generator:main diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit-1.9.4.dist-info/licenses/LICENSE b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit-1.9.4.dist-info/licenses/LICENSE new file mode 100644 index 000000000..67db85882 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit-1.9.4.dist-info/licenses/LICENSE @@ -0,0 +1,175 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit-1.9.4.dist-info/pbr.json b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit-1.9.4.dist-info/pbr.json new file mode 100644 index 000000000..0919b3f5b --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit-1.9.4.dist-info/pbr.json @@ -0,0 +1 @@ +{"git_version": "92ae8b8", "is_release": false} \ No newline at end of file diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit-1.9.4.dist-info/top_level.txt b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit-1.9.4.dist-info/top_level.txt new file mode 100644 index 000000000..4f97a523f --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit-1.9.4.dist-info/top_level.txt @@ -0,0 +1 @@ +bandit diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/__init__.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/__init__.py new file mode 100644 index 000000000..7c7bf00a8 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/__init__.py @@ -0,0 +1,20 @@ +# +# Copyright 2014 Hewlett-Packard Development Company, L.P. +# +# SPDX-License-Identifier: Apache-2.0 +from importlib import metadata + +from bandit.core import config # noqa +from bandit.core import context # noqa +from bandit.core import manager # noqa +from bandit.core import meta_ast # noqa +from bandit.core import node_visitor # noqa +from bandit.core import test_set # noqa +from bandit.core import tester # noqa +from bandit.core import utils # noqa +from bandit.core.constants import * # noqa +from bandit.core.issue import * # noqa +from bandit.core.test_properties import * # noqa + +__author__ = metadata.metadata("bandit")["Author"] +__version__ = metadata.version("bandit") diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/__main__.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/__main__.py new file mode 100644 index 000000000..f43c06a25 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/__main__.py @@ -0,0 +1,17 @@ +#!/usr/bin/env python +# SPDX-License-Identifier: Apache-2.0 +"""Bandit is a tool designed to find common security issues in Python code. + +Bandit is a tool designed to find common security issues in Python code. +To do this Bandit processes each file, builds an AST from it, and runs +appropriate plugins against the AST nodes. Once Bandit has finished +scanning all the files it generates a report. + +Bandit was originally developed within the OpenStack Security Project and +later rehomed to PyCQA. + +https://bandit.readthedocs.io/ +""" +from bandit.cli import main + +main.main() diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/blacklists/__init__.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/blacklists/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/blacklists/calls.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/blacklists/calls.py new file mode 100644 index 000000000..024e873a7 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/blacklists/calls.py @@ -0,0 +1,670 @@ +# +# Copyright 2016 Hewlett-Packard Development Company, L.P. +# +# SPDX-License-Identifier: Apache-2.0 +r""" +==================================================== +Blacklist various Python calls known to be dangerous +==================================================== + +This blacklist data checks for a number of Python calls known to have possible +security implications. The following blacklist tests are run against any +function calls encountered in the scanned code base, triggered by encountering +ast.Call nodes. + +B301: pickle +------------ + +Pickle and modules that wrap it can be unsafe when used to +deserialize untrusted data, possible security issue. + ++------+---------------------+------------------------------------+-----------+ +| ID | Name | Calls | Severity | ++======+=====================+====================================+===========+ +| B301 | pickle | - pickle.loads | Medium | +| | | - pickle.load | | +| | | - pickle.Unpickler | | +| | | - dill.loads | | +| | | - dill.load | | +| | | - dill.Unpickler | | +| | | - shelve.open | | +| | | - shelve.DbfilenameShelf | | +| | | - jsonpickle.decode | | +| | | - jsonpickle.unpickler.decode | | +| | | - jsonpickle.unpickler.Unpickler | | +| | | - pandas.read_pickle | | ++------+---------------------+------------------------------------+-----------+ + +B302: marshal +------------- + +Deserialization with the marshal module is possibly dangerous. + ++------+---------------------+------------------------------------+-----------+ +| ID | Name | Calls | Severity | ++======+=====================+====================================+===========+ +| B302 | marshal | - marshal.load | Medium | +| | | - marshal.loads | | ++------+---------------------+------------------------------------+-----------+ + +B303: md5 +--------- + +Use of insecure MD2, MD4, MD5, or SHA1 hash function. + ++------+---------------------+------------------------------------+-----------+ +| ID | Name | Calls | Severity | ++======+=====================+====================================+===========+ +| B303 | md5 | - hashlib.md5 | Medium | +| | | - hashlib.sha1 | | +| | | - Crypto.Hash.MD2.new | | +| | | - Crypto.Hash.MD4.new | | +| | | - Crypto.Hash.MD5.new | | +| | | - Crypto.Hash.SHA.new | | +| | | - Cryptodome.Hash.MD2.new | | +| | | - Cryptodome.Hash.MD4.new | | +| | | - Cryptodome.Hash.MD5.new | | +| | | - Cryptodome.Hash.SHA.new | | +| | | - cryptography.hazmat.primitives | | +| | | .hashes.MD5 | | +| | | - cryptography.hazmat.primitives | | +| | | .hashes.SHA1 | | ++------+---------------------+------------------------------------+-----------+ + +B304 - B305: ciphers and modes +------------------------------ + +Use of insecure cipher or cipher mode. Replace with a known secure cipher such +as AES. + ++------+---------------------+------------------------------------+-----------+ +| ID | Name | Calls | Severity | ++======+=====================+====================================+===========+ +| B304 | ciphers | - Crypto.Cipher.ARC2.new | High | +| | | - Crypto.Cipher.ARC4.new | | +| | | - Crypto.Cipher.Blowfish.new | | +| | | - Crypto.Cipher.DES.new | | +| | | - Crypto.Cipher.XOR.new | | +| | | - Cryptodome.Cipher.ARC2.new | | +| | | - Cryptodome.Cipher.ARC4.new | | +| | | - Cryptodome.Cipher.Blowfish.new | | +| | | - Cryptodome.Cipher.DES.new | | +| | | - Cryptodome.Cipher.XOR.new | | +| | | - cryptography.hazmat.primitives | | +| | | .ciphers.algorithms.ARC4 | | +| | | - cryptography.hazmat.primitives | | +| | | .ciphers.algorithms.Blowfish | | +| | | - cryptography.hazmat.primitives | | +| | | .ciphers.algorithms.IDEA | | +| | | - cryptography.hazmat.primitives | | +| | | .ciphers.algorithms.CAST5 | | +| | | - cryptography.hazmat.primitives | | +| | | .ciphers.algorithms.SEED | | +| | | - cryptography.hazmat.primitives | | +| | | .ciphers.algorithms.TripleDES | | ++------+---------------------+------------------------------------+-----------+ +| B305 | cipher_modes | - cryptography.hazmat.primitives | Medium | +| | | .ciphers.modes.ECB | | ++------+---------------------+------------------------------------+-----------+ + +B306: mktemp_q +-------------- + +Use of insecure and deprecated function (mktemp). + ++------+---------------------+------------------------------------+-----------+ +| ID | Name | Calls | Severity | ++======+=====================+====================================+===========+ +| B306 | mktemp_q | - tempfile.mktemp | Medium | ++------+---------------------+------------------------------------+-----------+ + +B307: eval +---------- + +Use of possibly insecure function - consider using safer ast.literal_eval. + ++------+---------------------+------------------------------------+-----------+ +| ID | Name | Calls | Severity | ++======+=====================+====================================+===========+ +| B307 | eval | - eval | Medium | ++------+---------------------+------------------------------------+-----------+ + +B308: mark_safe +--------------- + +Use of mark_safe() may expose cross-site scripting vulnerabilities and should +be reviewed. + ++------+---------------------+------------------------------------+-----------+ +| ID | Name | Calls | Severity | ++======+=====================+====================================+===========+ +| B308 | mark_safe | - django.utils.safestring.mark_safe| Medium | ++------+---------------------+------------------------------------+-----------+ + +B309: httpsconnection +--------------------- + +The check for this call has been removed. + +Use of HTTPSConnection on older versions of Python prior to 2.7.9 and 3.4.3 do +not provide security, see https://wiki.openstack.org/wiki/OSSN/OSSN-0033 + ++------+---------------------+------------------------------------+-----------+ +| ID | Name | Calls | Severity | ++======+=====================+====================================+===========+ +| B309 | httpsconnection | - httplib.HTTPSConnection | Medium | +| | | - http.client.HTTPSConnection | | +| | | - six.moves.http_client | | +| | | .HTTPSConnection | | ++------+---------------------+------------------------------------+-----------+ + +B310: urllib_urlopen +-------------------- + +Audit url open for permitted schemes. Allowing use of 'file:'' or custom +schemes is often unexpected. + ++------+---------------------+------------------------------------+-----------+ +| ID | Name | Calls | Severity | ++======+=====================+====================================+===========+ +| B310 | urllib_urlopen | - urllib.urlopen | Medium | +| | | - urllib.request.urlopen | | +| | | - urllib.urlretrieve | | +| | | - urllib.request.urlretrieve | | +| | | - urllib.URLopener | | +| | | - urllib.request.URLopener | | +| | | - urllib.FancyURLopener | | +| | | - urllib.request.FancyURLopener | | +| | | - urllib2.urlopen | | +| | | - urllib2.Request | | +| | | - six.moves.urllib.request.urlopen | | +| | | - six.moves.urllib.request | | +| | | .urlretrieve | | +| | | - six.moves.urllib.request | | +| | | .URLopener | | +| | | - six.moves.urllib.request | | +| | | .FancyURLopener | | ++------+---------------------+------------------------------------+-----------+ + +B311: random +------------ + +Standard pseudo-random generators are not suitable for security/cryptographic +purposes. Consider using the secrets module instead: +https://docs.python.org/library/secrets.html + ++------+---------------------+------------------------------------+-----------+ +| ID | Name | Calls | Severity | ++======+=====================+====================================+===========+ +| B311 | random | - random.Random | Low | +| | | - random.random | | +| | | - random.randrange | | +| | | - random.randint | | +| | | - random.choice | | +| | | - random.choices | | +| | | - random.uniform | | +| | | - random.triangular | | +| | | - random.randbytes | | +| | | - random.randrange | | +| | | - random.sample | | +| | | - random.getrandbits | | ++------+---------------------+------------------------------------+-----------+ + +B312: telnetlib +--------------- + +Telnet-related functions are being called. Telnet is considered insecure. Use +SSH or some other encrypted protocol. + ++------+---------------------+------------------------------------+-----------+ +| ID | Name | Calls | Severity | ++======+=====================+====================================+===========+ +| B312 | telnetlib | - telnetlib.\* | High | ++------+---------------------+------------------------------------+-----------+ + +B313 - B319: XML +---------------- + +Most of this is based off of Christian Heimes' work on defusedxml: +https://pypi.org/project/defusedxml/#defusedxml-sax + +Using various XLM methods to parse untrusted XML data is known to be vulnerable +to XML attacks. Methods should be replaced with their defusedxml equivalents. + ++------+---------------------+------------------------------------+-----------+ +| ID | Name | Calls | Severity | ++======+=====================+====================================+===========+ +| B313 | xml_bad_cElementTree| - xml.etree.cElementTree.parse | Medium | +| | | - xml.etree.cElementTree.iterparse | | +| | | - xml.etree.cElementTree.fromstring| | +| | | - xml.etree.cElementTree.XMLParser | | ++------+---------------------+------------------------------------+-----------+ +| B314 | xml_bad_ElementTree | - xml.etree.ElementTree.parse | Medium | +| | | - xml.etree.ElementTree.iterparse | | +| | | - xml.etree.ElementTree.fromstring | | +| | | - xml.etree.ElementTree.XMLParser | | ++------+---------------------+------------------------------------+-----------+ +| B315 | xml_bad_expatreader | - xml.sax.expatreader.create_parser| Medium | ++------+---------------------+------------------------------------+-----------+ +| B316 | xml_bad_expatbuilder| - xml.dom.expatbuilder.parse | Medium | +| | | - xml.dom.expatbuilder.parseString | | ++------+---------------------+------------------------------------+-----------+ +| B317 | xml_bad_sax | - xml.sax.parse | Medium | +| | | - xml.sax.parseString | | +| | | - xml.sax.make_parser | | ++------+---------------------+------------------------------------+-----------+ +| B318 | xml_bad_minidom | - xml.dom.minidom.parse | Medium | +| | | - xml.dom.minidom.parseString | | ++------+---------------------+------------------------------------+-----------+ +| B319 | xml_bad_pulldom | - xml.dom.pulldom.parse | Medium | +| | | - xml.dom.pulldom.parseString | | ++------+---------------------+------------------------------------+-----------+ + +B320: xml_bad_etree +------------------- + +The check for this call has been removed. + ++------+---------------------+------------------------------------+-----------+ +| ID | Name | Calls | Severity | ++======+=====================+====================================+===========+ +| B320 | xml_bad_etree | - lxml.etree.parse | Medium | +| | | - lxml.etree.fromstring | | +| | | - lxml.etree.RestrictedElement | | +| | | - lxml.etree.GlobalParserTLS | | +| | | - lxml.etree.getDefaultParser | | +| | | - lxml.etree.check_docinfo | | ++------+---------------------+------------------------------------+-----------+ + +B321: ftplib +------------ + +FTP-related functions are being called. FTP is considered insecure. Use +SSH/SFTP/SCP or some other encrypted protocol. + ++------+---------------------+------------------------------------+-----------+ +| ID | Name | Calls | Severity | ++======+=====================+====================================+===========+ +| B321 | ftplib | - ftplib.\* | High | ++------+---------------------+------------------------------------+-----------+ + +B322: input +----------- + +The check for this call has been removed. + +The input method in Python 2 will read from standard input, evaluate and +run the resulting string as python source code. This is similar, though in +many ways worse, than using eval. On Python 2, use raw_input instead, input +is safe in Python 3. + ++------+---------------------+------------------------------------+-----------+ +| ID | Name | Calls | Severity | ++======+=====================+====================================+===========+ +| B322 | input | - input | High | ++------+---------------------+------------------------------------+-----------+ + +B323: unverified_context +------------------------ + +By default, Python will create a secure, verified ssl context for use in such +classes as HTTPSConnection. However, it still allows using an insecure +context via the _create_unverified_context that reverts to the previous +behavior that does not validate certificates or perform hostname checks. + ++------+---------------------+------------------------------------+-----------+ +| ID | Name | Calls | Severity | ++======+=====================+====================================+===========+ +| B323 | unverified_context | - ssl._create_unverified_context | Medium | ++------+---------------------+------------------------------------+-----------+ + +B325: tempnam +-------------- + +The check for this call has been removed. + +Use of os.tempnam() and os.tmpnam() is vulnerable to symlink attacks. Consider +using tmpfile() instead. + +For further information: + https://docs.python.org/2.7/library/os.html#os.tempnam + https://docs.python.org/3/whatsnew/3.0.html?highlight=tempnam + https://bugs.python.org/issue17880 + ++------+---------------------+------------------------------------+-----------+ +| ID | Name | Calls | Severity | ++======+=====================+====================================+===========+ +| B325 | tempnam | - os.tempnam | Medium | +| | | - os.tmpnam | | ++------+---------------------+------------------------------------+-----------+ + +""" +from bandit.blacklists import utils +from bandit.core import issue + + +def gen_blacklist(): + """Generate a list of items to blacklist. + + Methods of this type, "bandit.blacklist" plugins, are used to build a list + of items that bandit's built in blacklisting tests will use to trigger + issues. They replace the older blacklist* test plugins and allow + blacklisted items to have a unique bandit ID for filtering and profile + usage. + + :return: a dictionary mapping node types to a list of blacklist data + """ + sets = [] + sets.append( + utils.build_conf_dict( + "pickle", + "B301", + issue.Cwe.DESERIALIZATION_OF_UNTRUSTED_DATA, + [ + "pickle.loads", + "pickle.load", + "pickle.Unpickler", + "dill.loads", + "dill.load", + "dill.Unpickler", + "shelve.open", + "shelve.DbfilenameShelf", + "jsonpickle.decode", + "jsonpickle.unpickler.decode", + "jsonpickle.unpickler.Unpickler", + "pandas.read_pickle", + ], + "Pickle and modules that wrap it can be unsafe when used to " + "deserialize untrusted data, possible security issue.", + ) + ) + + sets.append( + utils.build_conf_dict( + "marshal", + "B302", + issue.Cwe.DESERIALIZATION_OF_UNTRUSTED_DATA, + ["marshal.load", "marshal.loads"], + "Deserialization with the marshal module is possibly dangerous.", + ) + ) + + sets.append( + utils.build_conf_dict( + "md5", + "B303", + issue.Cwe.BROKEN_CRYPTO, + [ + "Crypto.Hash.MD2.new", + "Crypto.Hash.MD4.new", + "Crypto.Hash.MD5.new", + "Crypto.Hash.SHA.new", + "Cryptodome.Hash.MD2.new", + "Cryptodome.Hash.MD4.new", + "Cryptodome.Hash.MD5.new", + "Cryptodome.Hash.SHA.new", + "cryptography.hazmat.primitives.hashes.MD5", + "cryptography.hazmat.primitives.hashes.SHA1", + ], + "Use of insecure MD2, MD4, MD5, or SHA1 hash function.", + ) + ) + + sets.append( + utils.build_conf_dict( + "ciphers", + "B304", + issue.Cwe.BROKEN_CRYPTO, + [ + "Crypto.Cipher.ARC2.new", + "Crypto.Cipher.ARC4.new", + "Crypto.Cipher.Blowfish.new", + "Crypto.Cipher.DES.new", + "Crypto.Cipher.XOR.new", + "Cryptodome.Cipher.ARC2.new", + "Cryptodome.Cipher.ARC4.new", + "Cryptodome.Cipher.Blowfish.new", + "Cryptodome.Cipher.DES.new", + "Cryptodome.Cipher.XOR.new", + "cryptography.hazmat.primitives.ciphers.algorithms.ARC4", + "cryptography.hazmat.primitives.ciphers.algorithms.Blowfish", + "cryptography.hazmat.primitives.ciphers.algorithms.CAST5", + "cryptography.hazmat.primitives.ciphers.algorithms.IDEA", + "cryptography.hazmat.primitives.ciphers.algorithms.SEED", + "cryptography.hazmat.primitives.ciphers.algorithms.TripleDES", + ], + "Use of insecure cipher {name}. Replace with a known secure" + " cipher such as AES.", + "HIGH", + ) + ) + + sets.append( + utils.build_conf_dict( + "cipher_modes", + "B305", + issue.Cwe.BROKEN_CRYPTO, + ["cryptography.hazmat.primitives.ciphers.modes.ECB"], + "Use of insecure cipher mode {name}.", + ) + ) + + sets.append( + utils.build_conf_dict( + "mktemp_q", + "B306", + issue.Cwe.INSECURE_TEMP_FILE, + ["tempfile.mktemp"], + "Use of insecure and deprecated function (mktemp).", + ) + ) + + sets.append( + utils.build_conf_dict( + "eval", + "B307", + issue.Cwe.OS_COMMAND_INJECTION, + ["eval"], + "Use of possibly insecure function - consider using safer " + "ast.literal_eval.", + ) + ) + + sets.append( + utils.build_conf_dict( + "mark_safe", + "B308", + issue.Cwe.XSS, + ["django.utils.safestring.mark_safe"], + "Use of mark_safe() may expose cross-site scripting " + "vulnerabilities and should be reviewed.", + ) + ) + + # skipped B309 as the check for a call to httpsconnection has been removed + + sets.append( + utils.build_conf_dict( + "urllib_urlopen", + "B310", + issue.Cwe.PATH_TRAVERSAL, + [ + "urllib.request.urlopen", + "urllib.request.urlretrieve", + "urllib.request.URLopener", + "urllib.request.FancyURLopener", + "six.moves.urllib.request.urlopen", + "six.moves.urllib.request.urlretrieve", + "six.moves.urllib.request.URLopener", + "six.moves.urllib.request.FancyURLopener", + ], + "Audit url open for permitted schemes. Allowing use of file:/ or " + "custom schemes is often unexpected.", + ) + ) + + sets.append( + utils.build_conf_dict( + "random", + "B311", + issue.Cwe.INSUFFICIENT_RANDOM_VALUES, + [ + "random.Random", + "random.random", + "random.randrange", + "random.randint", + "random.choice", + "random.choices", + "random.uniform", + "random.triangular", + "random.randbytes", + "random.sample", + "random.randrange", + "random.getrandbits", + ], + "Standard pseudo-random generators are not suitable for " + "security/cryptographic purposes.", + "LOW", + ) + ) + + sets.append( + utils.build_conf_dict( + "telnetlib", + "B312", + issue.Cwe.CLEARTEXT_TRANSMISSION, + ["telnetlib.Telnet"], + "Telnet-related functions are being called. Telnet is considered " + "insecure. Use SSH or some other encrypted protocol.", + "HIGH", + ) + ) + + # Most of this is based off of Christian Heimes' work on defusedxml: + # https://pypi.org/project/defusedxml/#defusedxml-sax + + xml_msg = ( + "Using {name} to parse untrusted XML data is known to be " + "vulnerable to XML attacks. Replace {name} with its " + "defusedxml equivalent function or make sure " + "defusedxml.defuse_stdlib() is called" + ) + + sets.append( + utils.build_conf_dict( + "xml_bad_cElementTree", + "B313", + issue.Cwe.IMPROPER_INPUT_VALIDATION, + [ + "xml.etree.cElementTree.parse", + "xml.etree.cElementTree.iterparse", + "xml.etree.cElementTree.fromstring", + "xml.etree.cElementTree.XMLParser", + ], + xml_msg, + ) + ) + + sets.append( + utils.build_conf_dict( + "xml_bad_ElementTree", + "B314", + issue.Cwe.IMPROPER_INPUT_VALIDATION, + [ + "xml.etree.ElementTree.parse", + "xml.etree.ElementTree.iterparse", + "xml.etree.ElementTree.fromstring", + "xml.etree.ElementTree.XMLParser", + ], + xml_msg, + ) + ) + + sets.append( + utils.build_conf_dict( + "xml_bad_expatreader", + "B315", + issue.Cwe.IMPROPER_INPUT_VALIDATION, + ["xml.sax.expatreader.create_parser"], + xml_msg, + ) + ) + + sets.append( + utils.build_conf_dict( + "xml_bad_expatbuilder", + "B316", + issue.Cwe.IMPROPER_INPUT_VALIDATION, + ["xml.dom.expatbuilder.parse", "xml.dom.expatbuilder.parseString"], + xml_msg, + ) + ) + + sets.append( + utils.build_conf_dict( + "xml_bad_sax", + "B317", + issue.Cwe.IMPROPER_INPUT_VALIDATION, + ["xml.sax.parse", "xml.sax.parseString", "xml.sax.make_parser"], + xml_msg, + ) + ) + + sets.append( + utils.build_conf_dict( + "xml_bad_minidom", + "B318", + issue.Cwe.IMPROPER_INPUT_VALIDATION, + ["xml.dom.minidom.parse", "xml.dom.minidom.parseString"], + xml_msg, + ) + ) + + sets.append( + utils.build_conf_dict( + "xml_bad_pulldom", + "B319", + issue.Cwe.IMPROPER_INPUT_VALIDATION, + ["xml.dom.pulldom.parse", "xml.dom.pulldom.parseString"], + xml_msg, + ) + ) + + # skipped B320 as the check for a call to lxml.etree has been removed + + # end of XML tests + + sets.append( + utils.build_conf_dict( + "ftplib", + "B321", + issue.Cwe.CLEARTEXT_TRANSMISSION, + ["ftplib.FTP"], + "FTP-related functions are being called. FTP is considered " + "insecure. Use SSH/SFTP/SCP or some other encrypted protocol.", + "HIGH", + ) + ) + + # skipped B322 as the check for a call to input() has been removed + + sets.append( + utils.build_conf_dict( + "unverified_context", + "B323", + issue.Cwe.IMPROPER_CERT_VALIDATION, + ["ssl._create_unverified_context"], + "By default, Python will create a secure, verified ssl context for" + " use in such classes as HTTPSConnection. However, it still allows" + " using an insecure context via the _create_unverified_context " + "that reverts to the previous behavior that does not validate " + "certificates or perform hostname checks.", + ) + ) + + # skipped B324 (used in bandit/plugins/hashlib_new_insecure_functions.py) + + # skipped B325 as the check for a call to os.tempnam and os.tmpnam have + # been removed + + return {"Call": sets} diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/blacklists/imports.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/blacklists/imports.py new file mode 100644 index 000000000..b15155b65 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/blacklists/imports.py @@ -0,0 +1,425 @@ +# +# Copyright 2016 Hewlett-Packard Development Company, L.P. +# +# SPDX-License-Identifier: Apache-2.0 +r""" +====================================================== +Blacklist various Python imports known to be dangerous +====================================================== + +This blacklist data checks for a number of Python modules known to have +possible security implications. The following blacklist tests are run against +any import statements or calls encountered in the scanned code base. + +Note that the XML rules listed here are mostly based off of Christian Heimes' +work on defusedxml: https://pypi.org/project/defusedxml/ + +B401: import_telnetlib +---------------------- + +A telnet-related module is being imported. Telnet is considered insecure. Use +SSH or some other encrypted protocol. + ++------+---------------------+------------------------------------+-----------+ +| ID | Name | Imports | Severity | ++======+=====================+====================================+===========+ +| B401 | import_telnetlib | - telnetlib | high | ++------+---------------------+------------------------------------+-----------+ + +B402: import_ftplib +------------------- +A FTP-related module is being imported. FTP is considered insecure. Use +SSH/SFTP/SCP or some other encrypted protocol. + ++------+---------------------+------------------------------------+-----------+ +| ID | Name | Imports | Severity | ++======+=====================+====================================+===========+ +| B402 | import_ftplib | - ftplib | high | ++------+---------------------+------------------------------------+-----------+ + +B403: import_pickle +------------------- + +Consider possible security implications associated with these modules. + ++------+---------------------+------------------------------------+-----------+ +| ID | Name | Imports | Severity | ++======+=====================+====================================+===========+ +| B403 | import_pickle | - pickle | low | +| | | - cPickle | | +| | | - dill | | +| | | - shelve | | ++------+---------------------+------------------------------------+-----------+ + +B404: import_subprocess +----------------------- + +Consider possible security implications associated with these modules. + ++------+---------------------+------------------------------------+-----------+ +| ID | Name | Imports | Severity | ++======+=====================+====================================+===========+ +| B404 | import_subprocess | - subprocess | low | ++------+---------------------+------------------------------------+-----------+ + + +B405: import_xml_etree +---------------------- + +Using various methods to parse untrusted XML data is known to be vulnerable to +XML attacks. Replace vulnerable imports with the equivalent defusedxml package, +or make sure defusedxml.defuse_stdlib() is called. + ++------+---------------------+------------------------------------+-----------+ +| ID | Name | Imports | Severity | ++======+=====================+====================================+===========+ +| B405 | import_xml_etree | - xml.etree.cElementTree | low | +| | | - xml.etree.ElementTree | | ++------+---------------------+------------------------------------+-----------+ + +B406: import_xml_sax +-------------------- + +Using various methods to parse untrusted XML data is known to be vulnerable to +XML attacks. Replace vulnerable imports with the equivalent defusedxml package, +or make sure defusedxml.defuse_stdlib() is called. + ++------+---------------------+------------------------------------+-----------+ +| ID | Name | Imports | Severity | ++======+=====================+====================================+===========+ +| B406 | import_xml_sax | - xml.sax | low | ++------+---------------------+------------------------------------+-----------+ + +B407: import_xml_expat +---------------------- + +Using various methods to parse untrusted XML data is known to be vulnerable to +XML attacks. Replace vulnerable imports with the equivalent defusedxml package, +or make sure defusedxml.defuse_stdlib() is called. + ++------+---------------------+------------------------------------+-----------+ +| ID | Name | Imports | Severity | ++======+=====================+====================================+===========+ +| B407 | import_xml_expat | - xml.dom.expatbuilder | low | ++------+---------------------+------------------------------------+-----------+ + +B408: import_xml_minidom +------------------------ + +Using various methods to parse untrusted XML data is known to be vulnerable to +XML attacks. Replace vulnerable imports with the equivalent defusedxml package, +or make sure defusedxml.defuse_stdlib() is called. + + ++------+---------------------+------------------------------------+-----------+ +| ID | Name | Imports | Severity | ++======+=====================+====================================+===========+ +| B408 | import_xml_minidom | - xml.dom.minidom | low | ++------+---------------------+------------------------------------+-----------+ + +B409: import_xml_pulldom +------------------------ + +Using various methods to parse untrusted XML data is known to be vulnerable to +XML attacks. Replace vulnerable imports with the equivalent defusedxml package, +or make sure defusedxml.defuse_stdlib() is called. + ++------+---------------------+------------------------------------+-----------+ +| ID | Name | Imports | Severity | ++======+=====================+====================================+===========+ +| B409 | import_xml_pulldom | - xml.dom.pulldom | low | ++------+---------------------+------------------------------------+-----------+ + +B410: import_lxml +----------------- + +This import blacklist has been removed. The information here has been +left for historical purposes. + +Using various methods to parse untrusted XML data is known to be vulnerable to +XML attacks. Replace vulnerable imports with the equivalent defusedxml package. + ++------+---------------------+------------------------------------+-----------+ +| ID | Name | Imports | Severity | ++======+=====================+====================================+===========+ +| B410 | import_lxml | - lxml | low | ++------+---------------------+------------------------------------+-----------+ + +B411: import_xmlrpclib +---------------------- + +XMLRPC is particularly dangerous as it is also concerned with communicating +data over a network. Use defusedxml.xmlrpc.monkey_patch() function to +monkey-patch xmlrpclib and mitigate remote XML attacks. + ++------+---------------------+------------------------------------+-----------+ +| ID | Name | Imports | Severity | ++======+=====================+====================================+===========+ +| B411 | import_xmlrpclib | - xmlrpc | high | ++------+---------------------+------------------------------------+-----------+ + +B412: import_httpoxy +-------------------- +httpoxy is a set of vulnerabilities that affect application code running in +CGI, or CGI-like environments. The use of CGI for web applications should be +avoided to prevent this class of attack. More details are available +at https://httpoxy.org/. + ++------+---------------------+------------------------------------+-----------+ +| ID | Name | Imports | Severity | ++======+=====================+====================================+===========+ +| B412 | import_httpoxy | - wsgiref.handlers.CGIHandler | high | +| | | - twisted.web.twcgi.CGIScript | | ++------+---------------------+------------------------------------+-----------+ + +B413: import_pycrypto +--------------------- +pycrypto library is known to have publicly disclosed buffer overflow +vulnerability https://github.com/dlitz/pycrypto/issues/176. It is no longer +actively maintained and has been deprecated in favor of pyca/cryptography +library. + ++------+---------------------+------------------------------------+-----------+ +| ID | Name | Imports | Severity | ++======+=====================+====================================+===========+ +| B413 | import_pycrypto | - Crypto.Cipher | high | +| | | - Crypto.Hash | | +| | | - Crypto.IO | | +| | | - Crypto.Protocol | | +| | | - Crypto.PublicKey | | +| | | - Crypto.Random | | +| | | - Crypto.Signature | | +| | | - Crypto.Util | | ++------+---------------------+------------------------------------+-----------+ + +B414: import_pycryptodome +------------------------- +This import blacklist has been removed. The information here has been +left for historical purposes. + +pycryptodome is a direct fork of pycrypto that has not fully addressed +the issues inherent in PyCrypto. It seems to exist, mainly, as an API +compatible continuation of pycrypto and should be deprecated in favor +of pyca/cryptography which has more support among the Python community. + ++------+---------------------+------------------------------------+-----------+ +| ID | Name | Imports | Severity | ++======+=====================+====================================+===========+ +| B414 | import_pycryptodome | - Cryptodome.Cipher | high | +| | | - Cryptodome.Hash | | +| | | - Cryptodome.IO | | +| | | - Cryptodome.Protocol | | +| | | - Cryptodome.PublicKey | | +| | | - Cryptodome.Random | | +| | | - Cryptodome.Signature | | +| | | - Cryptodome.Util | | ++------+---------------------+------------------------------------+-----------+ + +B415: import_pyghmi +------------------- +An IPMI-related module is being imported. IPMI is considered insecure. Use +an encrypted protocol. + ++------+---------------------+------------------------------------+-----------+ +| ID | Name | Imports | Severity | ++======+=====================+====================================+===========+ +| B415 | import_pyghmi | - pyghmi | high | ++------+---------------------+------------------------------------+-----------+ + +""" +from bandit.blacklists import utils +from bandit.core import issue + + +def gen_blacklist(): + """Generate a list of items to blacklist. + + Methods of this type, "bandit.blacklist" plugins, are used to build a list + of items that bandit's built in blacklisting tests will use to trigger + issues. They replace the older blacklist* test plugins and allow + blacklisted items to have a unique bandit ID for filtering and profile + usage. + + :return: a dictionary mapping node types to a list of blacklist data + """ + sets = [] + sets.append( + utils.build_conf_dict( + "import_telnetlib", + "B401", + issue.Cwe.CLEARTEXT_TRANSMISSION, + ["telnetlib"], + "A telnet-related module is being imported. Telnet is " + "considered insecure. Use SSH or some other encrypted protocol.", + "HIGH", + ) + ) + + sets.append( + utils.build_conf_dict( + "import_ftplib", + "B402", + issue.Cwe.CLEARTEXT_TRANSMISSION, + ["ftplib"], + "A FTP-related module is being imported. FTP is considered " + "insecure. Use SSH/SFTP/SCP or some other encrypted protocol.", + "HIGH", + ) + ) + + sets.append( + utils.build_conf_dict( + "import_pickle", + "B403", + issue.Cwe.DESERIALIZATION_OF_UNTRUSTED_DATA, + ["pickle", "cPickle", "dill", "shelve"], + "Consider possible security implications associated with " + "{name} module.", + "LOW", + ) + ) + + sets.append( + utils.build_conf_dict( + "import_subprocess", + "B404", + issue.Cwe.OS_COMMAND_INJECTION, + ["subprocess"], + "Consider possible security implications associated with the " + "subprocess module.", + "LOW", + ) + ) + + # Most of this is based off of Christian Heimes' work on defusedxml: + # https://pypi.org/project/defusedxml/#defusedxml-sax + + xml_msg = ( + "Using {name} to parse untrusted XML data is known to be " + "vulnerable to XML attacks. Replace {name} with the equivalent " + "defusedxml package, or make sure defusedxml.defuse_stdlib() " + "is called." + ) + + sets.append( + utils.build_conf_dict( + "import_xml_etree", + "B405", + issue.Cwe.IMPROPER_INPUT_VALIDATION, + ["xml.etree.cElementTree", "xml.etree.ElementTree"], + xml_msg, + "LOW", + ) + ) + + sets.append( + utils.build_conf_dict( + "import_xml_sax", + "B406", + issue.Cwe.IMPROPER_INPUT_VALIDATION, + ["xml.sax"], + xml_msg, + "LOW", + ) + ) + + sets.append( + utils.build_conf_dict( + "import_xml_expat", + "B407", + issue.Cwe.IMPROPER_INPUT_VALIDATION, + ["xml.dom.expatbuilder"], + xml_msg, + "LOW", + ) + ) + + sets.append( + utils.build_conf_dict( + "import_xml_minidom", + "B408", + issue.Cwe.IMPROPER_INPUT_VALIDATION, + ["xml.dom.minidom"], + xml_msg, + "LOW", + ) + ) + + sets.append( + utils.build_conf_dict( + "import_xml_pulldom", + "B409", + issue.Cwe.IMPROPER_INPUT_VALIDATION, + ["xml.dom.pulldom"], + xml_msg, + "LOW", + ) + ) + + # skipped B410 as the check for import_lxml has been removed + + sets.append( + utils.build_conf_dict( + "import_xmlrpclib", + "B411", + issue.Cwe.IMPROPER_INPUT_VALIDATION, + ["xmlrpc"], + "Using {name} to parse untrusted XML data is known to be " + "vulnerable to XML attacks. Use defusedxml.xmlrpc.monkey_patch() " + "function to monkey-patch xmlrpclib and mitigate XML " + "vulnerabilities.", + "HIGH", + ) + ) + + sets.append( + utils.build_conf_dict( + "import_httpoxy", + "B412", + issue.Cwe.IMPROPER_ACCESS_CONTROL, + [ + "wsgiref.handlers.CGIHandler", + "twisted.web.twcgi.CGIScript", + "twisted.web.twcgi.CGIDirectory", + ], + "Consider possible security implications associated with " + "{name} module.", + "HIGH", + ) + ) + + sets.append( + utils.build_conf_dict( + "import_pycrypto", + "B413", + issue.Cwe.BROKEN_CRYPTO, + [ + "Crypto.Cipher", + "Crypto.Hash", + "Crypto.IO", + "Crypto.Protocol", + "Crypto.PublicKey", + "Crypto.Random", + "Crypto.Signature", + "Crypto.Util", + ], + "The pyCrypto library and its module {name} are no longer actively" + " maintained and have been deprecated. " + "Consider using pyca/cryptography library.", + "HIGH", + ) + ) + + sets.append( + utils.build_conf_dict( + "import_pyghmi", + "B415", + issue.Cwe.CLEARTEXT_TRANSMISSION, + ["pyghmi"], + "An IPMI-related module is being imported. IPMI is considered " + "insecure. Use an encrypted protocol.", + "HIGH", + ) + ) + + return {"Import": sets, "ImportFrom": sets, "Call": sets} diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/blacklists/utils.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/blacklists/utils.py new file mode 100644 index 000000000..fa4a5c9a5 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/blacklists/utils.py @@ -0,0 +1,17 @@ +# +# Copyright 2016 Hewlett-Packard Development Company, L.P. +# +# SPDX-License-Identifier: Apache-2.0 +r"""Utils module.""" + + +def build_conf_dict(name, bid, cwe, qualnames, message, level="MEDIUM"): + """Build and return a blacklist configuration dict.""" + return { + "name": name, + "id": bid, + "cwe": cwe, + "message": message, + "qualnames": qualnames, + "level": level, + } diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/cli/__init__.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/cli/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/cli/baseline.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/cli/baseline.py new file mode 100644 index 000000000..406c0c776 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/cli/baseline.py @@ -0,0 +1,252 @@ +# +# Copyright 2015 Hewlett-Packard Enterprise +# +# SPDX-License-Identifier: Apache-2.0 +# ############################################################################# +# Bandit Baseline is a tool that runs Bandit against a Git commit, and compares +# the current commit findings to the parent commit findings. +# To do this it checks out the parent commit, runs Bandit (with any provided +# filters or profiles), checks out the current commit, runs Bandit, and then +# reports on any new findings. +# ############################################################################# +"""Bandit is a tool designed to find common security issues in Python code.""" +import argparse +import contextlib +import logging +import os +import shutil +import subprocess # nosec: B404 +import sys +import tempfile + +try: + import git +except ImportError: + git = None + +bandit_args = sys.argv[1:] +baseline_tmp_file = "_bandit_baseline_run.json_" +current_commit = None +default_output_format = "terminal" +LOG = logging.getLogger(__name__) +repo = None +report_basename = "bandit_baseline_result" +valid_baseline_formats = ["txt", "html", "json"] + +"""baseline.py""" + + +def main(): + """Execute Bandit.""" + # our cleanup function needs this and can't be passed arguments + global current_commit + global repo + + parent_commit = None + output_format = None + repo = None + report_fname = None + + init_logger() + + output_format, repo, report_fname = initialize() + + if not repo: + sys.exit(2) + + # #################### Find current and parent commits #################### + try: + commit = repo.commit() + current_commit = commit.hexsha + LOG.info("Got current commit: [%s]", commit.name_rev) + + commit = commit.parents[0] + parent_commit = commit.hexsha + LOG.info("Got parent commit: [%s]", commit.name_rev) + + except git.GitCommandError: + LOG.error("Unable to get current or parent commit") + sys.exit(2) + except IndexError: + LOG.error("Parent commit not available") + sys.exit(2) + + # #################### Run Bandit against both commits #################### + output_type = ( + ["-f", "txt"] + if output_format == default_output_format + else ["-o", report_fname] + ) + + with baseline_setup() as t: + bandit_tmpfile = f"{t}/{baseline_tmp_file}" + + steps = [ + { + "message": "Getting Bandit baseline results", + "commit": parent_commit, + "args": bandit_args + ["-f", "json", "-o", bandit_tmpfile], + }, + { + "message": "Comparing Bandit results to baseline", + "commit": current_commit, + "args": bandit_args + ["-b", bandit_tmpfile] + output_type, + }, + ] + + return_code = None + + for step in steps: + repo.head.reset(commit=step["commit"], working_tree=True) + + LOG.info(step["message"]) + + bandit_command = ["bandit"] + step["args"] + + try: + output = subprocess.check_output(bandit_command) # nosec: B603 + except subprocess.CalledProcessError as e: + output = e.output + return_code = e.returncode + else: + return_code = 0 + output = output.decode("utf-8") # subprocess returns bytes + + if return_code not in [0, 1]: + LOG.error( + "Error running command: %s\nOutput: %s\n", + bandit_args, + output, + ) + + # #################### Output and exit #################################### + # print output or display message about written report + if output_format == default_output_format: + print(output) + else: + LOG.info("Successfully wrote %s", report_fname) + + # exit with the code the last Bandit run returned + sys.exit(return_code) + + +# #################### Clean up before exit ################################### +@contextlib.contextmanager +def baseline_setup(): + """Baseline setup by creating temp folder and resetting repo.""" + d = tempfile.mkdtemp() + yield d + shutil.rmtree(d, True) + + if repo: + repo.head.reset(commit=current_commit, working_tree=True) + + +# #################### Setup logging ########################################## +def init_logger(): + """Init logger.""" + LOG.handlers = [] + log_level = logging.INFO + log_format_string = "[%(levelname)7s ] %(message)s" + logging.captureWarnings(True) + LOG.setLevel(log_level) + handler = logging.StreamHandler(sys.stdout) + handler.setFormatter(logging.Formatter(log_format_string)) + LOG.addHandler(handler) + + +# #################### Perform initialization and validate assumptions ######## +def initialize(): + """Initialize arguments and output formats.""" + valid = True + + # #################### Parse Args ######################################### + parser = argparse.ArgumentParser( + description="Bandit Baseline - Generates Bandit results compared to " + "a baseline", + formatter_class=argparse.RawDescriptionHelpFormatter, + epilog="Additional Bandit arguments such as severity filtering (-ll) " + "can be added and will be passed to Bandit.", + ) + if sys.version_info >= (3, 14): + parser.suggest_on_error = True + parser.color = False + + parser.add_argument( + "targets", + metavar="targets", + type=str, + nargs="+", + help="source file(s) or directory(s) to be tested", + ) + + parser.add_argument( + "-f", + dest="output_format", + action="store", + default="terminal", + help="specify output format", + choices=valid_baseline_formats, + ) + + args, _ = parser.parse_known_args() + + # #################### Setup Output ####################################### + # set the output format, or use a default if not provided + output_format = ( + args.output_format if args.output_format else default_output_format + ) + + if output_format == default_output_format: + LOG.info("No output format specified, using %s", default_output_format) + + # set the report name based on the output format + report_fname = f"{report_basename}.{output_format}" + + # #################### Check Requirements ################################# + if git is None: + LOG.error("Git not available, reinstall with baseline extra") + valid = False + return (None, None, None) + + try: + repo = git.Repo(os.getcwd()) + + except git.exc.InvalidGitRepositoryError: + LOG.error("Bandit baseline must be called from a git project root") + valid = False + + except git.exc.GitCommandNotFound: + LOG.error("Git command not found") + valid = False + + else: + if repo.is_dirty(): + LOG.error( + "Current working directory is dirty and must be " "resolved" + ) + valid = False + + # if output format is specified, we need to be able to write the report + if output_format != default_output_format and os.path.exists(report_fname): + LOG.error("File %s already exists, aborting", report_fname) + valid = False + + # Bandit needs to be able to create this temp file + if os.path.exists(baseline_tmp_file): + LOG.error( + "Temporary file %s needs to be removed prior to running", + baseline_tmp_file, + ) + valid = False + + # we must validate -o is not provided, as it will mess up Bandit baseline + if "-o" in bandit_args: + LOG.error("Bandit baseline must not be called with the -o option") + valid = False + + return (output_format, repo, report_fname) if valid else (None, None, None) + + +if __name__ == "__main__": + main() diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/cli/config_generator.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/cli/config_generator.py new file mode 100644 index 000000000..7564db4f1 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/cli/config_generator.py @@ -0,0 +1,207 @@ +# Copyright 2015 Red Hat Inc. +# +# SPDX-License-Identifier: Apache-2.0 +"""Bandit is a tool designed to find common security issues in Python code.""" +import argparse +import importlib +import logging +import os +import sys + +import yaml + +from bandit.core import extension_loader + +PROG_NAME = "bandit_conf_generator" +LOG = logging.getLogger(__name__) + + +template = """ +### Bandit config file generated from: +# '{cli}' + +### This config may optionally select a subset of tests to run or skip by +### filling out the 'tests' and 'skips' lists given below. If no tests are +### specified for inclusion then it is assumed all tests are desired. The skips +### set will remove specific tests from the include set. This can be controlled +### using the -t/-s CLI options. Note that the same test ID should not appear +### in both 'tests' and 'skips', this would be nonsensical and is detected by +### Bandit at runtime. + +# Available tests: +{test_list} + +# (optional) list included test IDs here, eg '[B101, B406]': +{test} + +# (optional) list skipped test IDs here, eg '[B101, B406]': +{skip} + +### (optional) plugin settings - some test plugins require configuration data +### that may be given here, per-plugin. All bandit test plugins have a built in +### set of sensible defaults and these will be used if no configuration is +### provided. It is not necessary to provide settings for every (or any) plugin +### if the defaults are acceptable. + +{settings} +""" + + +def init_logger(): + """Init logger.""" + LOG.handlers = [] + log_level = logging.INFO + log_format_string = "[%(levelname)5s]: %(message)s" + logging.captureWarnings(True) + LOG.setLevel(log_level) + handler = logging.StreamHandler(sys.stdout) + handler.setFormatter(logging.Formatter(log_format_string)) + LOG.addHandler(handler) + + +def parse_args(): + """Parse arguments.""" + help_description = """Bandit Config Generator + + This tool is used to generate an optional profile. The profile may be used + to include or skip tests and override values for plugins. + + When used to store an output profile, this tool will output a template that + includes all plugins and their default settings. Any settings which aren't + being overridden can be safely removed from the profile and default values + will be used. Bandit will prefer settings from the profile over the built + in values.""" + + parser = argparse.ArgumentParser( + description=help_description, + formatter_class=argparse.RawTextHelpFormatter, + ) + if sys.version_info >= (3, 14): + parser.suggest_on_error = True + parser.color = False + + parser.add_argument( + "--show-defaults", + dest="show_defaults", + action="store_true", + help="show the default settings values for each " + "plugin but do not output a profile", + ) + parser.add_argument( + "-o", + "--out", + dest="output_file", + action="store", + help="output file to save profile", + ) + parser.add_argument( + "-t", + "--tests", + dest="tests", + action="store", + default=None, + type=str, + help="list of test names to run", + ) + parser.add_argument( + "-s", + "--skip", + dest="skips", + action="store", + default=None, + type=str, + help="list of test names to skip", + ) + args = parser.parse_args() + + if not args.output_file and not args.show_defaults: + parser.print_help() + parser.exit(1) + + return args + + +def get_config_settings(): + """Get configuration settings.""" + config = {} + for plugin in extension_loader.MANAGER.plugins: + fn_name = plugin.name + function = plugin.plugin + + # if a function takes config... + if hasattr(function, "_takes_config"): + fn_module = importlib.import_module(function.__module__) + + # call the config generator if it exists + if hasattr(fn_module, "gen_config"): + config[fn_name] = fn_module.gen_config(function._takes_config) + + return yaml.safe_dump(config, default_flow_style=False) + + +def main(): + """Config generator to write configuration file.""" + init_logger() + args = parse_args() + + yaml_settings = get_config_settings() + + if args.show_defaults: + print(yaml_settings) + + if args.output_file: + if os.path.exists(os.path.abspath(args.output_file)): + LOG.error("File %s already exists, exiting", args.output_file) + sys.exit(2) + + try: + with open(args.output_file, "w") as f: + skips = args.skips.split(",") if args.skips else [] + tests = args.tests.split(",") if args.tests else [] + + for skip in skips: + if not extension_loader.MANAGER.check_id(skip): + raise RuntimeError(f"unknown ID in skips: {skip}") + + for test in tests: + if not extension_loader.MANAGER.check_id(test): + raise RuntimeError(f"unknown ID in tests: {test}") + + tpl = "# {0} : {1}" + test_list = [ + tpl.format(t.plugin._test_id, t.name) + for t in extension_loader.MANAGER.plugins + ] + + others = [ + tpl.format(k, v["name"]) + for k, v in ( + extension_loader.MANAGER.blacklist_by_id.items() + ) + ] + test_list.extend(others) + test_list.sort() + + contents = template.format( + cli=" ".join(sys.argv), + settings=yaml_settings, + test_list="\n".join(test_list), + skip="skips: " + str(skips) if skips else "skips:", + test="tests: " + str(tests) if tests else "tests:", + ) + f.write(contents) + + except OSError: + LOG.error("Unable to open %s for writing", args.output_file) + + except Exception as e: + LOG.error("Error: %s", e) + + else: + LOG.info("Successfully wrote profile: %s", args.output_file) + + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/cli/main.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/cli/main.py new file mode 100644 index 000000000..d7dba2efa --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/cli/main.py @@ -0,0 +1,701 @@ +# +# Copyright 2014 Hewlett-Packard Development Company, L.P. +# +# SPDX-License-Identifier: Apache-2.0 +"""Bandit is a tool designed to find common security issues in Python code.""" +import argparse +import fnmatch +import logging +import os +import sys +import textwrap + +import bandit +from bandit.core import config as b_config +from bandit.core import constants +from bandit.core import manager as b_manager +from bandit.core import utils + +BASE_CONFIG = "bandit.yaml" +LOG = logging.getLogger() + + +def _init_logger(log_level=logging.INFO, log_format=None): + """Initialize the logger. + + :param debug: Whether to enable debug mode + :return: An instantiated logging instance + """ + LOG.handlers = [] + + if not log_format: + # default log format + log_format_string = constants.log_format_string + else: + log_format_string = log_format + + logging.captureWarnings(True) + + LOG.setLevel(log_level) + handler = logging.StreamHandler(sys.stderr) + handler.setFormatter(logging.Formatter(log_format_string)) + LOG.addHandler(handler) + LOG.debug("logging initialized") + + +def _get_options_from_ini(ini_path, target): + """Return a dictionary of config options or None if we can't load any.""" + ini_file = None + + if ini_path: + ini_file = ini_path + else: + bandit_files = [] + + for t in target: + for root, _, filenames in os.walk(t): + for filename in fnmatch.filter(filenames, ".bandit"): + bandit_files.append(os.path.join(root, filename)) + + if len(bandit_files) > 1: + LOG.error( + "Multiple .bandit files found - scan separately or " + "choose one with --ini\n\t%s", + ", ".join(bandit_files), + ) + sys.exit(2) + + elif len(bandit_files) == 1: + ini_file = bandit_files[0] + LOG.info("Found project level .bandit file: %s", bandit_files[0]) + + if ini_file: + return utils.parse_ini_file(ini_file) + else: + return None + + +def _init_extensions(): + from bandit.core import extension_loader as ext_loader + + return ext_loader.MANAGER + + +def _log_option_source(default_val, arg_val, ini_val, option_name): + """It's useful to show the source of each option.""" + # When default value is not defined, arg_val and ini_val is deterministic + if default_val is None: + if arg_val: + LOG.info("Using command line arg for %s", option_name) + return arg_val + elif ini_val: + LOG.info("Using ini file for %s", option_name) + return ini_val + else: + return None + # No value passed to command line and default value is used + elif default_val == arg_val: + return ini_val if ini_val else arg_val + # Certainly a value is passed to command line + else: + return arg_val + + +def _running_under_virtualenv(): + if hasattr(sys, "real_prefix"): + return True + elif sys.prefix != getattr(sys, "base_prefix", sys.prefix): + return True + + +def _get_profile(config, profile_name, config_path): + profile = {} + if profile_name: + profiles = config.get_option("profiles") or {} + profile = profiles.get(profile_name) + if profile is None: + raise utils.ProfileNotFound(config_path, profile_name) + LOG.debug("read in legacy profile '%s': %s", profile_name, profile) + else: + profile["include"] = set(config.get_option("tests") or []) + profile["exclude"] = set(config.get_option("skips") or []) + return profile + + +def _log_info(args, profile): + inc = ",".join([t for t in profile["include"]]) or "None" + exc = ",".join([t for t in profile["exclude"]]) or "None" + LOG.info("profile include tests: %s", inc) + LOG.info("profile exclude tests: %s", exc) + LOG.info("cli include tests: %s", args.tests) + LOG.info("cli exclude tests: %s", args.skips) + + +def main(): + """Bandit CLI.""" + # bring our logging stuff up as early as possible + debug = ( + logging.DEBUG + if "-d" in sys.argv or "--debug" in sys.argv + else logging.INFO + ) + _init_logger(debug) + extension_mgr = _init_extensions() + + baseline_formatters = [ + f.name + for f in filter( + lambda x: hasattr(x.plugin, "_accepts_baseline"), + extension_mgr.formatters, + ) + ] + + # now do normal startup + parser = argparse.ArgumentParser( + description="Bandit - a Python source code security analyzer", + formatter_class=argparse.RawDescriptionHelpFormatter, + ) + if sys.version_info >= (3, 14): + parser.suggest_on_error = True + parser.color = False + + parser.add_argument( + "targets", + metavar="targets", + type=str, + nargs="*", + help="source file(s) or directory(s) to be tested", + ) + parser.add_argument( + "-r", + "--recursive", + dest="recursive", + action="store_true", + help="find and process files in subdirectories", + ) + parser.add_argument( + "-a", + "--aggregate", + dest="agg_type", + action="store", + default="file", + type=str, + choices=["file", "vuln"], + help="aggregate output by vulnerability (default) or by filename", + ) + parser.add_argument( + "-n", + "--number", + dest="context_lines", + action="store", + default=3, + type=int, + help="maximum number of code lines to output for each issue", + ) + parser.add_argument( + "-c", + "--configfile", + dest="config_file", + action="store", + default=None, + type=str, + help="optional config file to use for selecting plugins and " + "overriding defaults", + ) + parser.add_argument( + "-p", + "--profile", + dest="profile", + action="store", + default=None, + type=str, + help="profile to use (defaults to executing all tests)", + ) + parser.add_argument( + "-t", + "--tests", + dest="tests", + action="store", + default=None, + type=str, + help="comma-separated list of test IDs to run", + ) + parser.add_argument( + "-s", + "--skip", + dest="skips", + action="store", + default=None, + type=str, + help="comma-separated list of test IDs to skip", + ) + severity_group = parser.add_mutually_exclusive_group(required=False) + severity_group.add_argument( + "-l", + "--level", + dest="severity", + action="count", + default=1, + help="report only issues of a given severity level or " + "higher (-l for LOW, -ll for MEDIUM, -lll for HIGH)", + ) + severity_group.add_argument( + "--severity-level", + dest="severity_string", + action="store", + help="report only issues of a given severity level or higher." + ' "all" and "low" are likely to produce the same results, but it' + " is possible for rules to be undefined which will" + ' not be listed in "low".', + choices=["all", "low", "medium", "high"], + ) + confidence_group = parser.add_mutually_exclusive_group(required=False) + confidence_group.add_argument( + "-i", + "--confidence", + dest="confidence", + action="count", + default=1, + help="report only issues of a given confidence level or " + "higher (-i for LOW, -ii for MEDIUM, -iii for HIGH)", + ) + confidence_group.add_argument( + "--confidence-level", + dest="confidence_string", + action="store", + help="report only issues of a given confidence level or higher." + ' "all" and "low" are likely to produce the same results, but it' + " is possible for rules to be undefined which will" + ' not be listed in "low".', + choices=["all", "low", "medium", "high"], + ) + output_format = ( + "screen" + if ( + sys.stdout.isatty() + and os.getenv("NO_COLOR") is None + and os.getenv("TERM") != "dumb" + ) + else "txt" + ) + parser.add_argument( + "-f", + "--format", + dest="output_format", + action="store", + default=output_format, + help="specify output format", + choices=sorted(extension_mgr.formatter_names), + ) + parser.add_argument( + "--msg-template", + action="store", + default=None, + help="specify output message template" + " (only usable with --format custom)," + " see CUSTOM FORMAT section" + " for list of available values", + ) + parser.add_argument( + "-o", + "--output", + dest="output_file", + action="store", + nargs="?", + type=argparse.FileType("w", encoding="utf-8"), + default=sys.stdout, + help="write report to filename", + ) + group = parser.add_mutually_exclusive_group(required=False) + group.add_argument( + "-v", + "--verbose", + dest="verbose", + action="store_true", + help="output extra information like excluded and included files", + ) + parser.add_argument( + "-d", + "--debug", + dest="debug", + action="store_true", + help="turn on debug mode", + ) + group.add_argument( + "-q", + "--quiet", + "--silent", + dest="quiet", + action="store_true", + help="only show output in the case of an error", + ) + parser.add_argument( + "--ignore-nosec", + dest="ignore_nosec", + action="store_true", + help="do not skip lines with # nosec comments", + ) + parser.add_argument( + "-x", + "--exclude", + dest="excluded_paths", + action="store", + default=",".join(constants.EXCLUDE), + help="comma-separated list of paths (glob patterns " + "supported) to exclude from scan " + "(note that these are in addition to the excluded " + "paths provided in the config file) (default: " + + ",".join(constants.EXCLUDE) + + ")", + ) + parser.add_argument( + "-b", + "--baseline", + dest="baseline", + action="store", + default=None, + help="path of a baseline report to compare against " + "(only JSON-formatted files are accepted)", + ) + parser.add_argument( + "--ini", + dest="ini_path", + action="store", + default=None, + help="path to a .bandit file that supplies command line arguments", + ) + parser.add_argument( + "--exit-zero", + action="store_true", + dest="exit_zero", + default=False, + help="exit with 0, " "even with results found", + ) + python_ver = sys.version.replace("\n", "") + parser.add_argument( + "--version", + action="version", + version=f"%(prog)s {bandit.__version__}\n" + f" python version = {python_ver}", + ) + + parser.set_defaults(debug=False) + parser.set_defaults(verbose=False) + parser.set_defaults(quiet=False) + parser.set_defaults(ignore_nosec=False) + + plugin_info = [ + f"{a[0]}\t{a[1].name}" for a in extension_mgr.plugins_by_id.items() + ] + blacklist_info = [] + for a in extension_mgr.blacklist.items(): + for b in a[1]: + blacklist_info.append(f"{b['id']}\t{b['name']}") + + plugin_list = "\n\t".join(sorted(set(plugin_info + blacklist_info))) + dedent_text = textwrap.dedent( + """ + CUSTOM FORMATTING + ----------------- + + Available tags: + + {abspath}, {relpath}, {line}, {col}, {test_id}, + {severity}, {msg}, {confidence}, {range} + + Example usage: + + Default template: + bandit -r examples/ --format custom --msg-template \\ + "{abspath}:{line}: {test_id}[bandit]: {severity}: {msg}" + + Provides same output as: + bandit -r examples/ --format custom + + Tags can also be formatted in python string.format() style: + bandit -r examples/ --format custom --msg-template \\ + "{relpath:20.20s}: {line:03}: {test_id:^8}: DEFECT: {msg:>20}" + + See python documentation for more information about formatting style: + https://docs.python.org/3/library/string.html + + The following tests were discovered and loaded: + ----------------------------------------------- + """ + ) + parser.epilog = dedent_text + f"\t{plugin_list}" + + # setup work - parse arguments, and initialize BanditManager + args = parser.parse_args() + # Check if `--msg-template` is not present without custom formatter + if args.output_format != "custom" and args.msg_template is not None: + parser.error("--msg-template can only be used with --format=custom") + + # Check if confidence or severity level have been specified with strings + if args.severity_string is not None: + if args.severity_string == "all": + args.severity = 1 + elif args.severity_string == "low": + args.severity = 2 + elif args.severity_string == "medium": + args.severity = 3 + elif args.severity_string == "high": + args.severity = 4 + # Other strings will be blocked by argparse + + if args.confidence_string is not None: + if args.confidence_string == "all": + args.confidence = 1 + elif args.confidence_string == "low": + args.confidence = 2 + elif args.confidence_string == "medium": + args.confidence = 3 + elif args.confidence_string == "high": + args.confidence = 4 + # Other strings will be blocked by argparse + + # Handle .bandit files in projects to pass cmdline args from file + ini_options = _get_options_from_ini(args.ini_path, args.targets) + if ini_options: + # prefer command line, then ini file + args.config_file = _log_option_source( + parser.get_default("configfile"), + args.config_file, + ini_options.get("configfile"), + "config file", + ) + + args.excluded_paths = _log_option_source( + parser.get_default("excluded_paths"), + args.excluded_paths, + ini_options.get("exclude"), + "excluded paths", + ) + + args.skips = _log_option_source( + parser.get_default("skips"), + args.skips, + ini_options.get("skips"), + "skipped tests", + ) + + args.tests = _log_option_source( + parser.get_default("tests"), + args.tests, + ini_options.get("tests"), + "selected tests", + ) + + ini_targets = ini_options.get("targets") + if ini_targets: + ini_targets = ini_targets.split(",") + + args.targets = _log_option_source( + parser.get_default("targets"), + args.targets, + ini_targets, + "selected targets", + ) + + # TODO(tmcpeak): any other useful options to pass from .bandit? + + args.recursive = _log_option_source( + parser.get_default("recursive"), + args.recursive, + ini_options.get("recursive"), + "recursive scan", + ) + + args.agg_type = _log_option_source( + parser.get_default("agg_type"), + args.agg_type, + ini_options.get("aggregate"), + "aggregate output type", + ) + + args.context_lines = _log_option_source( + parser.get_default("context_lines"), + args.context_lines, + int(ini_options.get("number") or 0) or None, + "max code lines output for issue", + ) + + args.profile = _log_option_source( + parser.get_default("profile"), + args.profile, + ini_options.get("profile"), + "profile", + ) + + args.severity = _log_option_source( + parser.get_default("severity"), + args.severity, + ini_options.get("level"), + "severity level", + ) + + args.confidence = _log_option_source( + parser.get_default("confidence"), + args.confidence, + ini_options.get("confidence"), + "confidence level", + ) + + args.output_format = _log_option_source( + parser.get_default("output_format"), + args.output_format, + ini_options.get("format"), + "output format", + ) + + args.msg_template = _log_option_source( + parser.get_default("msg_template"), + args.msg_template, + ini_options.get("msg-template"), + "output message template", + ) + + args.output_file = _log_option_source( + parser.get_default("output_file"), + args.output_file, + ini_options.get("output"), + "output file", + ) + + args.verbose = _log_option_source( + parser.get_default("verbose"), + args.verbose, + ini_options.get("verbose"), + "output extra information", + ) + + args.debug = _log_option_source( + parser.get_default("debug"), + args.debug, + ini_options.get("debug"), + "debug mode", + ) + + args.quiet = _log_option_source( + parser.get_default("quiet"), + args.quiet, + ini_options.get("quiet"), + "silent mode", + ) + + args.ignore_nosec = _log_option_source( + parser.get_default("ignore_nosec"), + args.ignore_nosec, + ini_options.get("ignore-nosec"), + "do not skip lines with # nosec", + ) + + args.baseline = _log_option_source( + parser.get_default("baseline"), + args.baseline, + ini_options.get("baseline"), + "path of a baseline report", + ) + + try: + b_conf = b_config.BanditConfig(config_file=args.config_file) + except utils.ConfigError as e: + LOG.error(e) + sys.exit(2) + + if not args.targets: + parser.print_usage() + sys.exit(2) + + # if the log format string was set in the options, reinitialize + if b_conf.get_option("log_format"): + log_format = b_conf.get_option("log_format") + _init_logger(log_level=logging.DEBUG, log_format=log_format) + + if args.quiet: + _init_logger(log_level=logging.WARN) + + try: + profile = _get_profile(b_conf, args.profile, args.config_file) + _log_info(args, profile) + + profile["include"].update(args.tests.split(",") if args.tests else []) + profile["exclude"].update(args.skips.split(",") if args.skips else []) + extension_mgr.validate_profile(profile) + + except (utils.ProfileNotFound, ValueError) as e: + LOG.error(e) + sys.exit(2) + + b_mgr = b_manager.BanditManager( + b_conf, + args.agg_type, + args.debug, + profile=profile, + verbose=args.verbose, + quiet=args.quiet, + ignore_nosec=args.ignore_nosec, + ) + + if args.baseline is not None: + try: + with open(args.baseline) as bl: + data = bl.read() + b_mgr.populate_baseline(data) + except OSError: + LOG.warning("Could not open baseline report: %s", args.baseline) + sys.exit(2) + + if args.output_format not in baseline_formatters: + LOG.warning( + "Baseline must be used with one of the following " + "formats: " + str(baseline_formatters) + ) + sys.exit(2) + + if args.output_format != "json": + if args.config_file: + LOG.info("using config: %s", args.config_file) + + LOG.info( + "running on Python %d.%d.%d", + sys.version_info.major, + sys.version_info.minor, + sys.version_info.micro, + ) + + # initiate file discovery step within Bandit Manager + b_mgr.discover_files(args.targets, args.recursive, args.excluded_paths) + + if not b_mgr.b_ts.tests: + LOG.error("No tests would be run, please check the profile.") + sys.exit(2) + + # initiate execution of tests within Bandit Manager + b_mgr.run_tests() + LOG.debug(b_mgr.b_ma) + LOG.debug(b_mgr.metrics) + + # trigger output of results by Bandit Manager + sev_level = constants.RANKING[args.severity - 1] + conf_level = constants.RANKING[args.confidence - 1] + b_mgr.output_results( + args.context_lines, + sev_level, + conf_level, + args.output_file, + args.output_format, + args.msg_template, + ) + + if ( + b_mgr.results_count(sev_filter=sev_level, conf_filter=conf_level) > 0 + and not args.exit_zero + ): + sys.exit(1) + else: + sys.exit(0) + + +if __name__ == "__main__": + main() diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/core/__init__.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/core/__init__.py new file mode 100644 index 000000000..2efdc4dc2 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/core/__init__.py @@ -0,0 +1,15 @@ +# +# Copyright 2014 Hewlett-Packard Development Company, L.P. +# +# SPDX-License-Identifier: Apache-2.0 +from bandit.core import config # noqa +from bandit.core import context # noqa +from bandit.core import manager # noqa +from bandit.core import meta_ast # noqa +from bandit.core import node_visitor # noqa +from bandit.core import test_set # noqa +from bandit.core import tester # noqa +from bandit.core import utils # noqa +from bandit.core.constants import * # noqa +from bandit.core.issue import * # noqa +from bandit.core.test_properties import * # noqa diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/core/blacklisting.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/core/blacklisting.py new file mode 100644 index 000000000..3d05fbaa9 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/core/blacklisting.py @@ -0,0 +1,72 @@ +# +# Copyright 2016 Hewlett-Packard Development Company, L.P. +# +# SPDX-License-Identifier: Apache-2.0 +import ast + +from bandit.core import issue + + +def report_issue(check, name): + return issue.Issue( + severity=check.get("level", "MEDIUM"), + confidence="HIGH", + cwe=check.get("cwe", issue.Cwe.NOTSET), + text=check["message"].replace("{name}", name), + ident=name, + test_id=check.get("id", "LEGACY"), + ) + + +def blacklist(context, config): + """Generic blacklist test, B001. + + This generic blacklist test will be called for any encountered node with + defined blacklist data available. This data is loaded via plugins using + the 'bandit.blacklists' entry point. Please see the documentation for more + details. Each blacklist datum has a unique bandit ID that may be used for + filtering purposes, or alternatively all blacklisting can be filtered using + the id of this built in test, 'B001'. + """ + blacklists = config + node_type = context.node.__class__.__name__ + + if node_type == "Call": + func = context.node.func + if isinstance(func, ast.Name) and func.id == "__import__": + if len(context.node.args): + if isinstance( + context.node.args[0], ast.Constant + ) and isinstance(context.node.args[0].value, str): + name = context.node.args[0].value + else: + # TODO(??): import through a variable, need symbol tab + name = "UNKNOWN" + else: + name = "" # handle '__import__()' + else: + name = context.call_function_name_qual + # In the case the Call is an importlib.import, treat the first + # argument name as an actual import module name. + # Will produce None if argument is not a literal or identifier + if name in ["importlib.import_module", "importlib.__import__"]: + if context.call_args_count > 0: + name = context.call_args[0] + else: + name = context.call_keywords["name"] + for check in blacklists[node_type]: + for qn in check["qualnames"]: + if name is not None and name == qn: + return report_issue(check, name) + + if node_type.startswith("Import"): + prefix = "" + if node_type == "ImportFrom": + if context.node.module is not None: + prefix = context.node.module + "." + + for check in blacklists[node_type]: + for name in context.node.names: + for qn in check["qualnames"]: + if (prefix + name.name).startswith(qn): + return report_issue(check, name.name) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/core/config.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/core/config.py new file mode 100644 index 000000000..dbc68fb7d --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/core/config.py @@ -0,0 +1,271 @@ +# +# Copyright 2014 Hewlett-Packard Development Company, L.P. +# +# SPDX-License-Identifier: Apache-2.0 +import logging +import sys + +import yaml + +if sys.version_info >= (3, 11): + import tomllib +else: + try: + import tomli as tomllib + except ImportError: + tomllib = None + +from bandit.core import constants +from bandit.core import extension_loader +from bandit.core import utils + +LOG = logging.getLogger(__name__) + + +class BanditConfig: + def __init__(self, config_file=None): + """Attempt to initialize a config dictionary from a yaml file. + + Error out if loading the yaml file fails for any reason. + :param config_file: The Bandit yaml config file + + :raises bandit.utils.ConfigError: If the config is invalid or + unreadable. + """ + self.config_file = config_file + self._config = {} + + if config_file: + try: + f = open(config_file, "rb") + except OSError: + raise utils.ConfigError( + "Could not read config file.", config_file + ) + + if config_file.endswith(".toml"): + if tomllib is None: + raise utils.ConfigError( + "toml parser not available, reinstall with toml extra", + config_file, + ) + + try: + with f: + self._config = ( + tomllib.load(f).get("tool", {}).get("bandit", {}) + ) + except tomllib.TOMLDecodeError as err: + LOG.error(err) + raise utils.ConfigError("Error parsing file.", config_file) + else: + try: + with f: + self._config = yaml.safe_load(f) + except yaml.YAMLError as err: + LOG.error(err) + raise utils.ConfigError("Error parsing file.", config_file) + + self.validate(config_file) + + # valid config must be a dict + if not isinstance(self._config, dict): + raise utils.ConfigError("Error parsing file.", config_file) + + self.convert_legacy_config() + + else: + # use sane defaults + self._config["plugin_name_pattern"] = "*.py" + self._config["include"] = ["*.py", "*.pyw"] + + self._init_settings() + + def get_option(self, option_string): + """Returns the option from the config specified by the option_string. + + '.' can be used to denote levels, for example to retrieve the options + from the 'a' profile you can use 'profiles.a' + :param option_string: The string specifying the option to retrieve + :return: The object specified by the option_string, or None if it can't + be found. + """ + option_levels = option_string.split(".") + cur_item = self._config + for level in option_levels: + if cur_item and (level in cur_item): + cur_item = cur_item[level] + else: + return None + + return cur_item + + def get_setting(self, setting_name): + if setting_name in self._settings: + return self._settings[setting_name] + else: + return None + + @property + def config(self): + """Property to return the config dictionary + + :return: Config dictionary + """ + return self._config + + def _init_settings(self): + """This function calls a set of other functions (one per setting) + + This function calls a set of other functions (one per setting) to build + out the _settings dictionary. Each other function will set values from + the config (if set), otherwise use defaults (from constants if + possible). + :return: - + """ + self._settings = {} + self._init_plugin_name_pattern() + + def _init_plugin_name_pattern(self): + """Sets settings['plugin_name_pattern'] from default or config file.""" + plugin_name_pattern = constants.plugin_name_pattern + if self.get_option("plugin_name_pattern"): + plugin_name_pattern = self.get_option("plugin_name_pattern") + self._settings["plugin_name_pattern"] = plugin_name_pattern + + def convert_legacy_config(self): + updated_profiles = self.convert_names_to_ids() + bad_calls, bad_imports = self.convert_legacy_blacklist_data() + + if updated_profiles: + self.convert_legacy_blacklist_tests( + updated_profiles, bad_calls, bad_imports + ) + self._config["profiles"] = updated_profiles + + def convert_names_to_ids(self): + """Convert test names to IDs, unknown names are left unchanged.""" + extman = extension_loader.MANAGER + + updated_profiles = {} + for name, profile in (self.get_option("profiles") or {}).items(): + # NOTE(tkelsey): can't use default of get() because value is + # sometimes explicitly 'None', for example when the list is given + # in yaml but not populated with any values. + include = { + (extman.get_test_id(i) or i) + for i in (profile.get("include") or []) + } + exclude = { + (extman.get_test_id(i) or i) + for i in (profile.get("exclude") or []) + } + updated_profiles[name] = {"include": include, "exclude": exclude} + return updated_profiles + + def convert_legacy_blacklist_data(self): + """Detect legacy blacklist data and convert it to new format.""" + bad_calls_list = [] + bad_imports_list = [] + + bad_calls = self.get_option("blacklist_calls") or {} + bad_calls = bad_calls.get("bad_name_sets", {}) + for item in bad_calls: + for key, val in item.items(): + val["name"] = key + val["message"] = val["message"].replace("{func}", "{name}") + bad_calls_list.append(val) + + bad_imports = self.get_option("blacklist_imports") or {} + bad_imports = bad_imports.get("bad_import_sets", {}) + for item in bad_imports: + for key, val in item.items(): + val["name"] = key + val["message"] = val["message"].replace("{module}", "{name}") + val["qualnames"] = val["imports"] + del val["imports"] + bad_imports_list.append(val) + + if bad_imports_list or bad_calls_list: + LOG.warning( + "Legacy blacklist data found in config, overriding " + "data plugins" + ) + return bad_calls_list, bad_imports_list + + @staticmethod + def convert_legacy_blacklist_tests(profiles, bad_imports, bad_calls): + """Detect old blacklist tests, convert to use new builtin.""" + + def _clean_set(name, data): + if name in data: + data.remove(name) + data.add("B001") + + for name, profile in profiles.items(): + blacklist = {} + include = profile["include"] + exclude = profile["exclude"] + + name = "blacklist_calls" + if name in include and name not in exclude: + blacklist.setdefault("Call", []).extend(bad_calls) + + _clean_set(name, include) + _clean_set(name, exclude) + + name = "blacklist_imports" + if name in include and name not in exclude: + blacklist.setdefault("Import", []).extend(bad_imports) + blacklist.setdefault("ImportFrom", []).extend(bad_imports) + blacklist.setdefault("Call", []).extend(bad_imports) + + _clean_set(name, include) + _clean_set(name, exclude) + _clean_set("blacklist_import_func", include) + _clean_set("blacklist_import_func", exclude) + + # This can happen with a legacy config that includes + # blacklist_calls but exclude blacklist_imports for example + if "B001" in include and "B001" in exclude: + exclude.remove("B001") + + profile["blacklist"] = blacklist + + def validate(self, path): + """Validate the config data.""" + legacy = False + message = ( + "Config file has an include or exclude reference " + "to legacy test '{0}' but no configuration data for " + "it. Configuration data is required for this test. " + "Please consider switching to the new config file " + "format, the tool 'bandit-config-generator' can help " + "you with this." + ) + + def _test(key, block, exclude, include): + if key in exclude or key in include: + if self._config.get(block) is None: + raise utils.ConfigError(message.format(key), path) + + if "profiles" in self._config: + legacy = True + for profile in self._config["profiles"].values(): + inc = profile.get("include") or set() + exc = profile.get("exclude") or set() + + _test("blacklist_imports", "blacklist_imports", inc, exc) + _test("blacklist_import_func", "blacklist_imports", inc, exc) + _test("blacklist_calls", "blacklist_calls", inc, exc) + + # show deprecation message + if legacy: + LOG.warning( + "Config file '%s' contains deprecated legacy config " + "data. Please consider upgrading to the new config " + "format. The tool 'bandit-config-generator' can help " + "you with this. Support for legacy configs will be " + "removed in a future bandit version.", + path, + ) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/core/constants.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/core/constants.py new file mode 100644 index 000000000..dd8ddeb9b --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/core/constants.py @@ -0,0 +1,40 @@ +# +# Copyright 2014 Hewlett-Packard Development Company, L.P. +# +# SPDX-License-Identifier: Apache-2.0 +# default plugin name pattern +plugin_name_pattern = "*.py" + +RANKING = ["UNDEFINED", "LOW", "MEDIUM", "HIGH"] +RANKING_VALUES = {"UNDEFINED": 1, "LOW": 3, "MEDIUM": 5, "HIGH": 10} +CRITERIA = [("SEVERITY", "UNDEFINED"), ("CONFIDENCE", "UNDEFINED")] + +# add each ranking to globals, to allow direct access in module name space +for rank in RANKING: + globals()[rank] = rank + +CONFIDENCE_DEFAULT = "UNDEFINED" + +# A list of values Python considers to be False. +# These can be useful in tests to check if a value is True or False. +# We don't handle the case of user-defined classes being false. +# These are only useful when we have a constant in code. If we +# have a variable we cannot determine if False. +# See https://docs.python.org/3/library/stdtypes.html#truth-value-testing +FALSE_VALUES = [None, False, "False", 0, 0.0, 0j, "", (), [], {}] + +# override with "log_format" option in config file +log_format_string = "[%(module)s]\t%(levelname)s\t%(message)s" + +# Directories to exclude by default +EXCLUDE = ( + ".svn", + "CVS", + ".bzr", + ".hg", + ".git", + "__pycache__", + ".tox", + ".eggs", + "*.egg", +) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/core/context.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/core/context.py new file mode 100644 index 000000000..8de21b26d --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/core/context.py @@ -0,0 +1,316 @@ +# +# Copyright 2014 Hewlett-Packard Development Company, L.P. +# +# SPDX-License-Identifier: Apache-2.0 +import ast + +from bandit.core import utils + + +class Context: + def __init__(self, context_object=None): + """Initialize the class with a context, empty dict otherwise + + :param context_object: The context object to create class from + :return: - + """ + if context_object is not None: + self._context = context_object + else: + self._context = dict() + + def __repr__(self): + """Generate representation of object for printing / interactive use + + Most likely only interested in non-default properties, so we return + the string version of _context. + + Example string returned: + , 'function': None, + 'name': 'socket', 'imports': set(['socket']), 'module': None, + 'filename': 'examples/binding.py', + 'call': <_ast.Call object at 0x110252510>, 'lineno': 3, + 'import_aliases': {}, 'qualname': 'socket.socket'}> + + :return: A string representation of the object + """ + return f"" + + @property + def call_args(self): + """Get a list of function args + + :return: A list of function args + """ + args = [] + if "call" in self._context and hasattr(self._context["call"], "args"): + for arg in self._context["call"].args: + if hasattr(arg, "attr"): + args.append(arg.attr) + else: + args.append(self._get_literal_value(arg)) + return args + + @property + def call_args_count(self): + """Get the number of args a function call has + + :return: The number of args a function call has or None + """ + if "call" in self._context and hasattr(self._context["call"], "args"): + return len(self._context["call"].args) + else: + return None + + @property + def call_function_name(self): + """Get the name (not FQ) of a function call + + :return: The name (not FQ) of a function call + """ + return self._context.get("name") + + @property + def call_function_name_qual(self): + """Get the FQ name of a function call + + :return: The FQ name of a function call + """ + return self._context.get("qualname") + + @property + def call_keywords(self): + """Get a dictionary of keyword parameters + + :return: A dictionary of keyword parameters for a call as strings + """ + if "call" in self._context and hasattr( + self._context["call"], "keywords" + ): + return_dict = {} + for li in self._context["call"].keywords: + if hasattr(li.value, "attr"): + return_dict[li.arg] = li.value.attr + else: + return_dict[li.arg] = self._get_literal_value(li.value) + return return_dict + else: + return None + + @property + def node(self): + """Get the raw AST node associated with the context + + :return: The raw AST node associated with the context + """ + return self._context.get("node") + + @property + def string_val(self): + """Get the value of a standalone unicode or string object + + :return: value of a standalone unicode or string object + """ + return self._context.get("str") + + @property + def bytes_val(self): + """Get the value of a standalone bytes object (py3 only) + + :return: value of a standalone bytes object + """ + return self._context.get("bytes") + + @property + def string_val_as_escaped_bytes(self): + """Get escaped value of the object. + + Turn the value of a string or bytes object into byte sequence with + unknown, control, and \\ characters escaped. + + This function should be used when looking for a known sequence in a + potentially badly encoded string in the code. + + :return: sequence of printable ascii bytes representing original string + """ + val = self.string_val + if val is not None: + # it's any of str or unicode in py2, or str in py3 + return val.encode("unicode_escape") + + val = self.bytes_val + if val is not None: + return utils.escaped_bytes_representation(val) + + return None + + @property + def statement(self): + """Get the raw AST for the current statement + + :return: The raw AST for the current statement + """ + return self._context.get("statement") + + @property + def function_def_defaults_qual(self): + """Get a list of fully qualified default values in a function def + + :return: List of defaults + """ + defaults = [] + if ( + "node" in self._context + and hasattr(self._context["node"], "args") + and hasattr(self._context["node"].args, "defaults") + ): + for default in self._context["node"].args.defaults: + defaults.append( + utils.get_qual_attr( + default, self._context["import_aliases"] + ) + ) + return defaults + + def _get_literal_value(self, literal): + """Utility function to turn AST literals into native Python types + + :param literal: The AST literal to convert + :return: The value of the AST literal + """ + if isinstance(literal, ast.Constant): + if isinstance(literal.value, bool): + literal_value = str(literal.value) + elif literal.value is None: + literal_value = str(literal.value) + else: + literal_value = literal.value + + elif isinstance(literal, ast.List): + return_list = list() + for li in literal.elts: + return_list.append(self._get_literal_value(li)) + literal_value = return_list + + elif isinstance(literal, ast.Tuple): + return_tuple = tuple() + for ti in literal.elts: + return_tuple += (self._get_literal_value(ti),) + literal_value = return_tuple + + elif isinstance(literal, ast.Set): + return_set = set() + for si in literal.elts: + return_set.add(self._get_literal_value(si)) + literal_value = return_set + + elif isinstance(literal, ast.Dict): + literal_value = dict(zip(literal.keys, literal.values)) + + elif isinstance(literal, ast.Name): + literal_value = literal.id + + else: + literal_value = None + + return literal_value + + def get_call_arg_value(self, argument_name): + """Gets the value of a named argument in a function call. + + :return: named argument value + """ + kwd_values = self.call_keywords + if kwd_values is not None and argument_name in kwd_values: + return kwd_values[argument_name] + + def check_call_arg_value(self, argument_name, argument_values=None): + """Checks for a value of a named argument in a function call. + + Returns none if the specified argument is not found. + :param argument_name: A string - name of the argument to look for + :param argument_values: the value, or list of values to test against + :return: Boolean True if argument found and matched, False if + found and not matched, None if argument not found at all + """ + arg_value = self.get_call_arg_value(argument_name) + if arg_value is not None: + if not isinstance(argument_values, list): + # if passed a single value, or a tuple, convert to a list + argument_values = list((argument_values,)) + for val in argument_values: + if arg_value == val: + return True + return False + else: + # argument name not found, return None to allow testing for this + # eventuality + return None + + def get_lineno_for_call_arg(self, argument_name): + """Get the line number for a specific named argument + + In case the call is split over multiple lines, get the correct one for + the argument. + :param argument_name: A string - name of the argument to look for + :return: Integer - the line number of the found argument, or -1 + """ + if hasattr(self.node, "keywords"): + for key in self.node.keywords: + if key.arg == argument_name: + return key.value.lineno + + def get_call_arg_at_position(self, position_num): + """Returns positional argument at the specified position (if it exists) + + :param position_num: The index of the argument to return the value for + :return: Value of the argument at the specified position if it exists + """ + max_args = self.call_args_count + if max_args and position_num < max_args: + arg = self._context["call"].args[position_num] + return getattr(arg, "attr", None) or self._get_literal_value(arg) + else: + return None + + def is_module_being_imported(self, module): + """Check for the specified module is currently being imported + + :param module: The module name to look for + :return: True if the module is found, False otherwise + """ + return self._context.get("module") == module + + def is_module_imported_exact(self, module): + """Check if a specified module has been imported; only exact matches. + + :param module: The module name to look for + :return: True if the module is found, False otherwise + """ + return module in self._context.get("imports", []) + + def is_module_imported_like(self, module): + """Check if a specified module has been imported + + Check if a specified module has been imported; specified module exists + as part of any import statement. + :param module: The module name to look for + :return: True if the module is found, False otherwise + """ + if "imports" in self._context: + for imp in self._context["imports"]: + if module in imp: + return True + return False + + @property + def filename(self): + return self._context.get("filename") + + @property + def file_data(self): + return self._context.get("file_data") + + @property + def import_aliases(self): + return self._context.get("import_aliases") diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/core/docs_utils.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/core/docs_utils.py new file mode 100644 index 000000000..5a5575b5e --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/core/docs_utils.py @@ -0,0 +1,54 @@ +# +# Copyright 2016 Hewlett-Packard Development Company, L.P. +# +# SPDX-License-Identifier: Apache-2.0 +import bandit + + +def get_url(bid): + # where our docs are hosted + base_url = f"https://bandit.readthedocs.io/en/{bandit.__version__}/" + + # NOTE(tkelsey): for some reason this import can't be found when stevedore + # loads up the formatter plugin that imports this file. It is available + # later though. + from bandit.core import extension_loader + + info = extension_loader.MANAGER.plugins_by_id.get(bid) + if info is not None: + return f"{base_url}plugins/{bid.lower()}_{info.plugin.__name__}.html" + + info = extension_loader.MANAGER.blacklist_by_id.get(bid) + if info is not None: + template = "blacklists/blacklist_{kind}.html#{id}-{name}" + info["name"] = info["name"].replace("_", "-") + + if info["id"].startswith("B3"): # B3XX + # Some of the links are combined, so we have exception cases + if info["id"] in ["B304", "B305"]: + info = info.copy() + info["id"] = "b304-b305" + info["name"] = "ciphers-and-modes" + elif info["id"] in [ + "B313", + "B314", + "B315", + "B316", + "B317", + "B318", + "B319", + "B320", + ]: + info = info.copy() + info["id"] = "b313-b320" + ext = template.format( + kind="calls", id=info["id"], name=info["name"] + ) + else: + ext = template.format( + kind="imports", id=info["id"], name=info["name"] + ) + + return base_url + ext.lower() + + return base_url # no idea, give the docs main page diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/core/extension_loader.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/core/extension_loader.py new file mode 100644 index 000000000..ec28a0ab9 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/core/extension_loader.py @@ -0,0 +1,114 @@ +# +# SPDX-License-Identifier: Apache-2.0 +import logging +import sys + +from stevedore import extension + +from bandit.core import utils + +LOG = logging.getLogger(__name__) + + +class Manager: + # These IDs are for bandit built in tests + builtin = ["B001"] # Built in blacklist test + + def __init__( + self, + formatters_namespace="bandit.formatters", + plugins_namespace="bandit.plugins", + blacklists_namespace="bandit.blacklists", + ): + # Cache the extension managers, loaded extensions, and extension names + self.load_formatters(formatters_namespace) + self.load_plugins(plugins_namespace) + self.load_blacklists(blacklists_namespace) + + def load_formatters(self, formatters_namespace): + self.formatters_mgr = extension.ExtensionManager( + namespace=formatters_namespace, + invoke_on_load=False, + verify_requirements=False, + ) + self.formatters = list(self.formatters_mgr) + self.formatter_names = self.formatters_mgr.names() + + def load_plugins(self, plugins_namespace): + self.plugins_mgr = extension.ExtensionManager( + namespace=plugins_namespace, + invoke_on_load=False, + verify_requirements=False, + ) + + def test_has_id(plugin): + if not hasattr(plugin.plugin, "_test_id"): + # logger not setup yet, so using print + print( + f"WARNING: Test '{plugin.name}' has no ID, skipping.", + file=sys.stderr, + ) + return False + return True + + self.plugins = list(filter(test_has_id, list(self.plugins_mgr))) + self.plugin_names = [plugin.name for plugin in self.plugins] + self.plugins_by_id = {p.plugin._test_id: p for p in self.plugins} + self.plugins_by_name = {p.name: p for p in self.plugins} + + def get_test_id(self, test_name): + if test_name in self.plugins_by_name: + return self.plugins_by_name[test_name].plugin._test_id + if test_name in self.blacklist_by_name: + return self.blacklist_by_name[test_name]["id"] + return None + + def load_blacklists(self, blacklist_namespace): + self.blacklists_mgr = extension.ExtensionManager( + namespace=blacklist_namespace, + invoke_on_load=False, + verify_requirements=False, + ) + self.blacklist = {} + blacklist = list(self.blacklists_mgr) + for item in blacklist: + for key, val in item.plugin().items(): + utils.check_ast_node(key) + self.blacklist.setdefault(key, []).extend(val) + + self.blacklist_by_id = {} + self.blacklist_by_name = {} + for val in self.blacklist.values(): + for b in val: + self.blacklist_by_id[b["id"]] = b + self.blacklist_by_name[b["name"]] = b + + def validate_profile(self, profile): + """Validate that everything in the configured profiles looks good.""" + for inc in profile["include"]: + if not self.check_id(inc): + LOG.warning(f"Unknown test found in profile: {inc}") + + for exc in profile["exclude"]: + if not self.check_id(exc): + LOG.warning(f"Unknown test found in profile: {exc}") + + union = set(profile["include"]) & set(profile["exclude"]) + if len(union) > 0: + raise ValueError( + f"Non-exclusive include/exclude test sets: {union}" + ) + + def check_id(self, test): + return ( + test in self.plugins_by_id + or test in self.blacklist_by_id + or test in self.builtin + ) + + +# Using entry-points and pkg_resources *can* be expensive. So let's load these +# once, store them on the object, and have a module global object for +# accessing them. After the first time this module is imported, it should save +# this attribute on the module and not have to reload the entry-points. +MANAGER = Manager() diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/core/issue.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/core/issue.py new file mode 100644 index 000000000..b2d901542 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/core/issue.py @@ -0,0 +1,245 @@ +# +# Copyright 2015 Hewlett-Packard Development Company, L.P. +# +# SPDX-License-Identifier: Apache-2.0 +import linecache + +from bandit.core import constants + + +class Cwe: + NOTSET = 0 + IMPROPER_INPUT_VALIDATION = 20 + PATH_TRAVERSAL = 22 + OS_COMMAND_INJECTION = 78 + XSS = 79 + BASIC_XSS = 80 + SQL_INJECTION = 89 + CODE_INJECTION = 94 + IMPROPER_WILDCARD_NEUTRALIZATION = 155 + HARD_CODED_PASSWORD = 259 + IMPROPER_ACCESS_CONTROL = 284 + IMPROPER_CERT_VALIDATION = 295 + CLEARTEXT_TRANSMISSION = 319 + INADEQUATE_ENCRYPTION_STRENGTH = 326 + BROKEN_CRYPTO = 327 + INSUFFICIENT_RANDOM_VALUES = 330 + INSECURE_TEMP_FILE = 377 + UNCONTROLLED_RESOURCE_CONSUMPTION = 400 + DOWNLOAD_OF_CODE_WITHOUT_INTEGRITY_CHECK = 494 + DESERIALIZATION_OF_UNTRUSTED_DATA = 502 + MULTIPLE_BINDS = 605 + IMPROPER_CHECK_OF_EXCEPT_COND = 703 + INCORRECT_PERMISSION_ASSIGNMENT = 732 + INAPPROPRIATE_ENCODING_FOR_OUTPUT_CONTEXT = 838 + + MITRE_URL_PATTERN = "https://cwe.mitre.org/data/definitions/%s.html" + + def __init__(self, id=NOTSET): + self.id = id + + def link(self): + if self.id == Cwe.NOTSET: + return "" + + return Cwe.MITRE_URL_PATTERN % str(self.id) + + def __str__(self): + if self.id == Cwe.NOTSET: + return "" + + return "CWE-%i (%s)" % (self.id, self.link()) + + def as_dict(self): + return ( + {"id": self.id, "link": self.link()} + if self.id != Cwe.NOTSET + else {} + ) + + def as_jsons(self): + return str(self.as_dict()) + + def from_dict(self, data): + if "id" in data: + self.id = int(data["id"]) + else: + self.id = Cwe.NOTSET + + def __eq__(self, other): + return self.id == other.id + + def __ne__(self, other): + return self.id != other.id + + def __hash__(self): + return id(self) + + +class Issue: + def __init__( + self, + severity, + cwe=0, + confidence=constants.CONFIDENCE_DEFAULT, + text="", + ident=None, + lineno=None, + test_id="", + col_offset=-1, + end_col_offset=0, + ): + self.severity = severity + self.cwe = Cwe(cwe) + self.confidence = confidence + if isinstance(text, bytes): + text = text.decode("utf-8") + self.text = text + self.ident = ident + self.fname = "" + self.fdata = None + self.test = "" + self.test_id = test_id + self.lineno = lineno + self.col_offset = col_offset + self.end_col_offset = end_col_offset + self.linerange = [] + + def __str__(self): + return ( + "Issue: '%s' from %s:%s: CWE: %s, Severity: %s Confidence: " + "%s at %s:%i:%i" + ) % ( + self.text, + self.test_id, + (self.ident or self.test), + str(self.cwe), + self.severity, + self.confidence, + self.fname, + self.lineno, + self.col_offset, + ) + + def __eq__(self, other): + # if the issue text, severity, confidence, and filename match, it's + # the same issue from our perspective + match_types = [ + "text", + "severity", + "cwe", + "confidence", + "fname", + "test", + "test_id", + ] + return all( + getattr(self, field) == getattr(other, field) + for field in match_types + ) + + def __ne__(self, other): + return not self.__eq__(other) + + def __hash__(self): + return id(self) + + def filter(self, severity, confidence): + """Utility to filter on confidence and severity + + This function determines whether an issue should be included by + comparing the severity and confidence rating of the issue to minimum + thresholds specified in 'severity' and 'confidence' respectively. + + Formatters should call manager.filter_results() directly. + + This will return false if either the confidence or severity of the + issue are lower than the given threshold values. + + :param severity: Severity threshold + :param confidence: Confidence threshold + :return: True/False depending on whether issue meets threshold + + """ + rank = constants.RANKING + return rank.index(self.severity) >= rank.index( + severity + ) and rank.index(self.confidence) >= rank.index(confidence) + + def get_code(self, max_lines=3, tabbed=False): + """Gets lines of code from a file the generated this issue. + + :param max_lines: Max lines of context to return + :param tabbed: Use tabbing in the output + :return: strings of code + """ + lines = [] + max_lines = max(max_lines, 1) + lmin = max(1, self.lineno - max_lines // 2) + lmax = lmin + len(self.linerange) + max_lines - 1 + + if self.fname == "": + self.fdata.seek(0) + for line_num in range(1, lmin): + self.fdata.readline() + + tmplt = "%i\t%s" if tabbed else "%i %s" + for line in range(lmin, lmax): + if self.fname == "": + text = self.fdata.readline() + else: + text = linecache.getline(self.fname, line) + + if isinstance(text, bytes): + text = text.decode("utf-8") + + if not len(text): + break + lines.append(tmplt % (line, text)) + return "".join(lines) + + def as_dict(self, with_code=True, max_lines=3): + """Convert the issue to a dict of values for outputting.""" + out = { + "filename": self.fname, + "test_name": self.test, + "test_id": self.test_id, + "issue_severity": self.severity, + "issue_cwe": self.cwe.as_dict(), + "issue_confidence": self.confidence, + "issue_text": self.text.encode("utf-8").decode("utf-8"), + "line_number": self.lineno, + "line_range": self.linerange, + "col_offset": self.col_offset, + "end_col_offset": self.end_col_offset, + } + + if with_code: + out["code"] = self.get_code(max_lines=max_lines) + return out + + def from_dict(self, data, with_code=True): + self.code = data["code"] + self.fname = data["filename"] + self.severity = data["issue_severity"] + self.cwe = cwe_from_dict(data["issue_cwe"]) + self.confidence = data["issue_confidence"] + self.text = data["issue_text"] + self.test = data["test_name"] + self.test_id = data["test_id"] + self.lineno = data["line_number"] + self.linerange = data["line_range"] + self.col_offset = data.get("col_offset", 0) + self.end_col_offset = data.get("end_col_offset", 0) + + +def cwe_from_dict(data): + cwe = Cwe() + cwe.from_dict(data) + return cwe + + +def issue_from_dict(data): + i = Issue(severity=data["issue_severity"]) + i.from_dict(data) + return i diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/core/manager.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/core/manager.py new file mode 100644 index 000000000..cc0e3458b --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/core/manager.py @@ -0,0 +1,499 @@ +# +# Copyright 2014 Hewlett-Packard Development Company, L.P. +# +# SPDX-License-Identifier: Apache-2.0 +import collections +import fnmatch +import io +import json +import logging +import os +import re +import sys +import tokenize +import traceback + +from rich import progress + +from bandit.core import constants as b_constants +from bandit.core import extension_loader +from bandit.core import issue +from bandit.core import meta_ast as b_meta_ast +from bandit.core import metrics +from bandit.core import node_visitor as b_node_visitor +from bandit.core import test_set as b_test_set + +LOG = logging.getLogger(__name__) +NOSEC_COMMENT = re.compile(r"#\s*nosec:?\s*(?P[^#]+)?#?") +NOSEC_COMMENT_TESTS = re.compile(r"(?:(B\d+|[a-z\d_]+),?)+", re.IGNORECASE) +PROGRESS_THRESHOLD = 50 + + +class BanditManager: + scope = [] + + def __init__( + self, + config, + agg_type, + debug=False, + verbose=False, + quiet=False, + profile=None, + ignore_nosec=False, + ): + """Get logger, config, AST handler, and result store ready + + :param config: config options object + :type config: bandit.core.BanditConfig + :param agg_type: aggregation type + :param debug: Whether to show debug messages or not + :param verbose: Whether to show verbose output + :param quiet: Whether to only show output in the case of an error + :param profile_name: Optional name of profile to use (from cmd line) + :param ignore_nosec: Whether to ignore #nosec or not + :return: + """ + self.debug = debug + self.verbose = verbose + self.quiet = quiet + if not profile: + profile = {} + self.ignore_nosec = ignore_nosec + self.b_conf = config + self.files_list = [] + self.excluded_files = [] + self.b_ma = b_meta_ast.BanditMetaAst() + self.skipped = [] + self.results = [] + self.baseline = [] + self.agg_type = agg_type + self.metrics = metrics.Metrics() + self.b_ts = b_test_set.BanditTestSet(config, profile) + self.scores = [] + + def get_skipped(self): + ret = [] + # "skip" is a tuple of name and reason, decode just the name + for skip in self.skipped: + if isinstance(skip[0], bytes): + ret.append((skip[0].decode("utf-8"), skip[1])) + else: + ret.append(skip) + return ret + + def get_issue_list( + self, sev_level=b_constants.LOW, conf_level=b_constants.LOW + ): + return self.filter_results(sev_level, conf_level) + + def populate_baseline(self, data): + """Populate a baseline set of issues from a JSON report + + This will populate a list of baseline issues discovered from a previous + run of bandit. Later this baseline can be used to filter out the result + set, see filter_results. + """ + items = [] + try: + jdata = json.loads(data) + items = [issue.issue_from_dict(j) for j in jdata["results"]] + except Exception as e: + LOG.warning("Failed to load baseline data: %s", e) + self.baseline = items + + def filter_results(self, sev_filter, conf_filter): + """Returns a list of results filtered by the baseline + + This works by checking the number of results returned from each file we + process. If the number of results is different to the number reported + for the same file in the baseline, then we return all results for the + file. We can't reliably return just the new results, as line numbers + will likely have changed. + + :param sev_filter: severity level filter to apply + :param conf_filter: confidence level filter to apply + """ + + results = [ + i for i in self.results if i.filter(sev_filter, conf_filter) + ] + + if not self.baseline: + return results + + unmatched = _compare_baseline_results(self.baseline, results) + # if it's a baseline we'll return a dictionary of issues and a list of + # candidate issues + return _find_candidate_matches(unmatched, results) + + def results_count( + self, sev_filter=b_constants.LOW, conf_filter=b_constants.LOW + ): + """Return the count of results + + :param sev_filter: Severity level to filter lower + :param conf_filter: Confidence level to filter + :return: Number of results in the set + """ + return len(self.get_issue_list(sev_filter, conf_filter)) + + def output_results( + self, + lines, + sev_level, + conf_level, + output_file, + output_format, + template=None, + ): + """Outputs results from the result store + + :param lines: How many surrounding lines to show per result + :param sev_level: Which severity levels to show (LOW, MEDIUM, HIGH) + :param conf_level: Which confidence levels to show (LOW, MEDIUM, HIGH) + :param output_file: File to store results + :param output_format: output format plugin name + :param template: Output template with non-terminal tags + (default: {abspath}:{line}: + {test_id}[bandit]: {severity}: {msg}) + :return: - + """ + try: + formatters_mgr = extension_loader.MANAGER.formatters_mgr + if output_format not in formatters_mgr: + output_format = ( + "screen" + if ( + sys.stdout.isatty() + and os.getenv("NO_COLOR") is None + and os.getenv("TERM") != "dumb" + ) + else "txt" + ) + + formatter = formatters_mgr[output_format] + report_func = formatter.plugin + if output_format == "custom": + report_func( + self, + fileobj=output_file, + sev_level=sev_level, + conf_level=conf_level, + template=template, + ) + else: + report_func( + self, + fileobj=output_file, + sev_level=sev_level, + conf_level=conf_level, + lines=lines, + ) + + except Exception as e: + raise RuntimeError( + f"Unable to output report using " + f"'{output_format}' formatter: {str(e)}" + ) + + def discover_files(self, targets, recursive=False, excluded_paths=""): + """Add tests directly and from a directory to the test set + + :param targets: The command line list of files and directories + :param recursive: True/False - whether to add all files from dirs + :return: + """ + # We'll maintain a list of files which are added, and ones which have + # been explicitly excluded + files_list = set() + excluded_files = set() + + excluded_path_globs = self.b_conf.get_option("exclude_dirs") or [] + included_globs = self.b_conf.get_option("include") or ["*.py"] + + # if there are command line provided exclusions add them to the list + if excluded_paths: + for path in excluded_paths.split(","): + if os.path.isdir(path): + path = os.path.join(path, "*") + + excluded_path_globs.append(path) + + # build list of files we will analyze + for fname in targets: + # if this is a directory and recursive is set, find all files + if os.path.isdir(fname): + if recursive: + new_files, newly_excluded = _get_files_from_dir( + fname, + included_globs=included_globs, + excluded_path_strings=excluded_path_globs, + ) + files_list.update(new_files) + excluded_files.update(newly_excluded) + else: + LOG.warning( + "Skipping directory (%s), use -r flag to " + "scan contents", + fname, + ) + + else: + # if the user explicitly mentions a file on command line, + # we'll scan it, regardless of whether it's in the included + # file types list + if _is_file_included( + fname, + included_globs, + excluded_path_globs, + enforce_glob=False, + ): + if fname != "-": + fname = os.path.join(".", fname) + files_list.add(fname) + else: + excluded_files.add(fname) + + self.files_list = sorted(files_list) + self.excluded_files = sorted(excluded_files) + + def run_tests(self): + """Runs through all files in the scope + + :return: - + """ + # if we have problems with a file, we'll remove it from the files_list + # and add it to the skipped list instead + new_files_list = list(self.files_list) + if ( + len(self.files_list) > PROGRESS_THRESHOLD + and LOG.getEffectiveLevel() <= logging.INFO + ): + files = progress.track(self.files_list) + else: + files = self.files_list + + for count, fname in enumerate(files): + LOG.debug("working on file : %s", fname) + + try: + if fname == "-": + open_fd = os.fdopen(sys.stdin.fileno(), "rb", 0) + fdata = io.BytesIO(open_fd.read()) + new_files_list = [ + "" if x == "-" else x for x in new_files_list + ] + self._parse_file("", fdata, new_files_list) + else: + with open(fname, "rb") as fdata: + self._parse_file(fname, fdata, new_files_list) + except OSError as e: + self.skipped.append((fname, e.strerror)) + new_files_list.remove(fname) + + # reflect any files which may have been skipped + self.files_list = new_files_list + + # do final aggregation of metrics + self.metrics.aggregate() + + def _parse_file(self, fname, fdata, new_files_list): + try: + # parse the current file + data = fdata.read() + lines = data.splitlines() + self.metrics.begin(fname) + self.metrics.count_locs(lines) + # nosec_lines is a dict of line number -> set of tests to ignore + # for the line + nosec_lines = dict() + try: + fdata.seek(0) + tokens = tokenize.tokenize(fdata.readline) + + if not self.ignore_nosec: + for toktype, tokval, (lineno, _), _, _ in tokens: + if toktype == tokenize.COMMENT: + nosec_lines[lineno] = _parse_nosec_comment(tokval) + + except tokenize.TokenError: + pass + score = self._execute_ast_visitor(fname, fdata, data, nosec_lines) + self.scores.append(score) + self.metrics.count_issues([score]) + except KeyboardInterrupt: + sys.exit(2) + except SyntaxError: + self.skipped.append( + (fname, "syntax error while parsing AST from file") + ) + new_files_list.remove(fname) + except Exception as e: + LOG.error( + "Exception occurred when executing tests against %s.", fname + ) + if not LOG.isEnabledFor(logging.DEBUG): + LOG.error( + 'Run "bandit --debug %s" to see the full traceback.', fname + ) + + self.skipped.append((fname, "exception while scanning file")) + new_files_list.remove(fname) + LOG.debug(" Exception string: %s", e) + LOG.debug(" Exception traceback: %s", traceback.format_exc()) + + def _execute_ast_visitor(self, fname, fdata, data, nosec_lines): + """Execute AST parse on each file + + :param fname: The name of the file being parsed + :param data: Original file contents + :param lines: The lines of code to process + :return: The accumulated test score + """ + score = [] + res = b_node_visitor.BanditNodeVisitor( + fname, + fdata, + self.b_ma, + self.b_ts, + self.debug, + nosec_lines, + self.metrics, + ) + + score = res.process(data) + self.results.extend(res.tester.results) + return score + + +def _get_files_from_dir( + files_dir, included_globs=None, excluded_path_strings=None +): + if not included_globs: + included_globs = ["*.py"] + if not excluded_path_strings: + excluded_path_strings = [] + + files_list = set() + excluded_files = set() + + for root, _, files in os.walk(files_dir): + for filename in files: + path = os.path.join(root, filename) + if _is_file_included(path, included_globs, excluded_path_strings): + files_list.add(path) + else: + excluded_files.add(path) + + return files_list, excluded_files + + +def _is_file_included( + path, included_globs, excluded_path_strings, enforce_glob=True +): + """Determine if a file should be included based on filename + + This utility function determines if a file should be included based + on the file name, a list of parsed extensions, excluded paths, and a flag + specifying whether extensions should be enforced. + + :param path: Full path of file to check + :param parsed_extensions: List of parsed extensions + :param excluded_paths: List of paths (globbing supported) from which we + should not include files + :param enforce_glob: Can set to false to bypass extension check + :return: Boolean indicating whether a file should be included + """ + return_value = False + + # if this is matches a glob of files we look at, and it isn't in an + # excluded path + if _matches_glob_list(path, included_globs) or not enforce_glob: + if not _matches_glob_list(path, excluded_path_strings) and not any( + x in path for x in excluded_path_strings + ): + return_value = True + + return return_value + + +def _matches_glob_list(filename, glob_list): + for glob in glob_list: + if fnmatch.fnmatch(filename, glob): + return True + return False + + +def _compare_baseline_results(baseline, results): + """Compare a baseline list of issues to list of results + + This function compares a baseline set of issues to a current set of issues + to find results that weren't present in the baseline. + + :param baseline: Baseline list of issues + :param results: Current list of issues + :return: List of unmatched issues + """ + return [a for a in results if a not in baseline] + + +def _find_candidate_matches(unmatched_issues, results_list): + """Returns a dictionary with issue candidates + + For example, let's say we find a new command injection issue in a file + which used to have two. Bandit can't tell which of the command injection + issues in the file are new, so it will show all three. The user should + be able to pick out the new one. + + :param unmatched_issues: List of issues that weren't present before + :param results_list: main list of current Bandit findings + :return: A dictionary with a list of candidates for each issue + """ + + issue_candidates = collections.OrderedDict() + + for unmatched in unmatched_issues: + issue_candidates[unmatched] = [ + i for i in results_list if unmatched == i + ] + + return issue_candidates + + +def _find_test_id_from_nosec_string(extman, match): + test_id = extman.check_id(match) + if test_id: + return match + # Finding by short_id didn't work, let's check the test name + test_id = extman.get_test_id(match) + if not test_id: + # Name and short id didn't work: + LOG.warning( + "Test in comment: %s is not a test name or id, ignoring", match + ) + return test_id # We want to return None or the string here regardless + + +def _parse_nosec_comment(comment): + found_no_sec_comment = NOSEC_COMMENT.search(comment) + if not found_no_sec_comment: + # there was no nosec comment + return None + + matches = found_no_sec_comment.groupdict() + nosec_tests = matches.get("tests", set()) + + # empty set indicates that there was a nosec comment without specific + # test ids or names + test_ids = set() + if nosec_tests: + extman = extension_loader.MANAGER + # lookup tests by short code or name + for test in NOSEC_COMMENT_TESTS.finditer(nosec_tests): + test_match = test.group(1) + test_id = _find_test_id_from_nosec_string(extman, test_match) + if test_id: + test_ids.add(test_id) + + return test_ids diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/core/meta_ast.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/core/meta_ast.py new file mode 100644 index 000000000..7bcd7f8ba --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/core/meta_ast.py @@ -0,0 +1,44 @@ +# +# Copyright 2014 Hewlett-Packard Development Company, L.P. +# +# SPDX-License-Identifier: Apache-2.0 +import collections +import logging + +LOG = logging.getLogger(__name__) + + +class BanditMetaAst: + nodes = collections.OrderedDict() + + def __init__(self): + pass + + def add_node(self, node, parent_id, depth): + """Add a node to the AST node collection + + :param node: The AST node to add + :param parent_id: The ID of the node's parent + :param depth: The depth of the node + :return: - + """ + node_id = hex(id(node)) + LOG.debug("adding node : %s [%s]", node_id, depth) + self.nodes[node_id] = { + "raw": node, + "parent_id": parent_id, + "depth": depth, + } + + def __str__(self): + """Dumps a listing of all of the nodes + + Dumps a listing of all of the nodes for debugging purposes + :return: - + """ + tmpstr = "" + for k, v in self.nodes.items(): + tmpstr += f"Node: {k}\n" + tmpstr += f"\t{str(v)}\n" + tmpstr += f"Length: {len(self.nodes)}\n" + return tmpstr diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/core/metrics.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/core/metrics.py new file mode 100644 index 000000000..c21229083 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/core/metrics.py @@ -0,0 +1,106 @@ +# +# Copyright 2015 Hewlett-Packard Development Company, L.P. +# +# SPDX-License-Identifier: Apache-2.0 +import collections + +from bandit.core import constants + + +class Metrics: + """Bandit metric gathering. + + This class is a singleton used to gather and process metrics collected when + processing a code base with bandit. Metric collection is stateful, that + is, an active metric block will be set when requested and all subsequent + operations will effect that metric block until it is replaced by a setting + a new one. + """ + + def __init__(self): + self.data = dict() + self.data["_totals"] = { + "loc": 0, + "nosec": 0, + "skipped_tests": 0, + } + + # initialize 0 totals for criteria and rank; this will be reset later + for rank in constants.RANKING: + for criteria in constants.CRITERIA: + self.data["_totals"][f"{criteria[0]}.{rank}"] = 0 + + def begin(self, fname): + """Begin a new metric block. + + This starts a new metric collection name "fname" and makes is active. + :param fname: the metrics unique name, normally the file name. + """ + self.data[fname] = { + "loc": 0, + "nosec": 0, + "skipped_tests": 0, + } + self.current = self.data[fname] + + def note_nosec(self, num=1): + """Note a "nosec" comment. + + Increment the currently active metrics nosec count. + :param num: number of nosecs seen, defaults to 1 + """ + self.current["nosec"] += num + + def note_skipped_test(self, num=1): + """Note a "nosec BXXX, BYYY, ..." comment. + + Increment the currently active metrics skipped_tests count. + :param num: number of skipped_tests seen, defaults to 1 + """ + self.current["skipped_tests"] += num + + def count_locs(self, lines): + """Count lines of code. + + We count lines that are not empty and are not comments. The result is + added to our currently active metrics loc count (normally this is 0). + + :param lines: lines in the file to process + """ + + def proc(line): + tmp = line.strip() + return bool(tmp and not tmp.startswith(b"#")) + + self.current["loc"] += sum(proc(line) for line in lines) + + def count_issues(self, scores): + self.current.update(self._get_issue_counts(scores)) + + def aggregate(self): + """Do final aggregation of metrics.""" + c = collections.Counter() + for fname in self.data: + c.update(self.data[fname]) + self.data["_totals"] = dict(c) + + @staticmethod + def _get_issue_counts(scores): + """Get issue counts aggregated by confidence/severity rankings. + + :param scores: list of scores to aggregate / count + :return: aggregated total (count) of issues identified + """ + issue_counts = {} + for score in scores: + for criteria, _ in constants.CRITERIA: + for i, rank in enumerate(constants.RANKING): + label = f"{criteria}.{rank}" + if label not in issue_counts: + issue_counts[label] = 0 + count = ( + score[criteria][i] + // constants.RANKING_VALUES[rank] + ) + issue_counts[label] += count + return issue_counts diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/core/node_visitor.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/core/node_visitor.py new file mode 100644 index 000000000..fcad0512c --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/core/node_visitor.py @@ -0,0 +1,297 @@ +# +# Copyright 2014 Hewlett-Packard Development Company, L.P. +# +# SPDX-License-Identifier: Apache-2.0 +import ast +import logging +import operator + +from bandit.core import constants +from bandit.core import tester as b_tester +from bandit.core import utils as b_utils + +LOG = logging.getLogger(__name__) + + +class BanditNodeVisitor: + def __init__( + self, fname, fdata, metaast, testset, debug, nosec_lines, metrics + ): + self.debug = debug + self.nosec_lines = nosec_lines + self.scores = { + "SEVERITY": [0] * len(constants.RANKING), + "CONFIDENCE": [0] * len(constants.RANKING), + } + self.depth = 0 + self.fname = fname + self.fdata = fdata + self.metaast = metaast + self.testset = testset + self.imports = set() + self.import_aliases = {} + self.tester = b_tester.BanditTester( + self.testset, self.debug, nosec_lines, metrics + ) + + # in some cases we can't determine a qualified name + try: + self.namespace = b_utils.get_module_qualname_from_path(fname) + except b_utils.InvalidModulePath: + LOG.warning( + "Unable to find qualified name for module: %s", self.fname + ) + self.namespace = "" + LOG.debug("Module qualified name: %s", self.namespace) + self.metrics = metrics + + def visit_ClassDef(self, node): + """Visitor for AST ClassDef node + + Add class name to current namespace for all descendants. + :param node: Node being inspected + :return: - + """ + # For all child nodes, add this class name to current namespace + self.namespace = b_utils.namespace_path_join(self.namespace, node.name) + + def visit_FunctionDef(self, node): + """Visitor for AST FunctionDef nodes + + add relevant information about the node to + the context for use in tests which inspect function definitions. + Add the function name to the current namespace for all descendants. + :param node: The node that is being inspected + :return: - + """ + + self.context["function"] = node + qualname = self.namespace + "." + b_utils.get_func_name(node) + name = qualname.split(".")[-1] + + self.context["qualname"] = qualname + self.context["name"] = name + + # For all child nodes and any tests run, add this function name to + # current namespace + self.namespace = b_utils.namespace_path_join(self.namespace, name) + self.update_scores(self.tester.run_tests(self.context, "FunctionDef")) + + def visit_Call(self, node): + """Visitor for AST Call nodes + + add relevant information about the node to + the context for use in tests which inspect function calls. + :param node: The node that is being inspected + :return: - + """ + + self.context["call"] = node + qualname = b_utils.get_call_name(node, self.import_aliases) + name = qualname.split(".")[-1] + + self.context["qualname"] = qualname + self.context["name"] = name + + self.update_scores(self.tester.run_tests(self.context, "Call")) + + def visit_Import(self, node): + """Visitor for AST Import nodes + + add relevant information about node to + the context for use in tests which inspect imports. + :param node: The node that is being inspected + :return: - + """ + for nodename in node.names: + if nodename.asname: + self.import_aliases[nodename.asname] = nodename.name + self.imports.add(nodename.name) + self.context["module"] = nodename.name + self.update_scores(self.tester.run_tests(self.context, "Import")) + + def visit_ImportFrom(self, node): + """Visitor for AST ImportFrom nodes + + add relevant information about node to + the context for use in tests which inspect imports. + :param node: The node that is being inspected + :return: - + """ + module = node.module + if module is None: + return self.visit_Import(node) + + for nodename in node.names: + # TODO(ljfisher) Names in import_aliases could be overridden + # by local definitions. If this occurs bandit will see the + # name in import_aliases instead of the local definition. + # We need better tracking of names. + if nodename.asname: + self.import_aliases[nodename.asname] = ( + module + "." + nodename.name + ) + else: + # Even if import is not aliased we need an entry that maps + # name to module.name. For example, with 'from a import b' + # b should be aliased to the qualified name a.b + self.import_aliases[nodename.name] = ( + module + "." + nodename.name + ) + self.imports.add(module + "." + nodename.name) + self.context["module"] = module + self.context["name"] = nodename.name + self.update_scores(self.tester.run_tests(self.context, "ImportFrom")) + + def visit_Constant(self, node): + """Visitor for AST Constant nodes + + call the appropriate method for the node type. + this maintains compatibility with <3.6 and 3.8+ + + This code is heavily influenced by Anthony Sottile (@asottile) here: + https://bugs.python.org/msg342486 + + :param node: The node that is being inspected + :return: - + """ + if isinstance(node.value, str): + self.visit_Str(node) + elif isinstance(node.value, bytes): + self.visit_Bytes(node) + + def visit_Str(self, node): + """Visitor for AST String nodes + + add relevant information about node to + the context for use in tests which inspect strings. + :param node: The node that is being inspected + :return: - + """ + self.context["str"] = node.value + if not isinstance(node._bandit_parent, ast.Expr): # docstring + self.context["linerange"] = b_utils.linerange(node._bandit_parent) + self.update_scores(self.tester.run_tests(self.context, "Str")) + + def visit_Bytes(self, node): + """Visitor for AST Bytes nodes + + add relevant information about node to + the context for use in tests which inspect strings. + :param node: The node that is being inspected + :return: - + """ + self.context["bytes"] = node.value + if not isinstance(node._bandit_parent, ast.Expr): # docstring + self.context["linerange"] = b_utils.linerange(node._bandit_parent) + self.update_scores(self.tester.run_tests(self.context, "Bytes")) + + def pre_visit(self, node): + self.context = {} + self.context["imports"] = self.imports + self.context["import_aliases"] = self.import_aliases + + if self.debug: + LOG.debug(ast.dump(node)) + self.metaast.add_node(node, "", self.depth) + + if hasattr(node, "lineno"): + self.context["lineno"] = node.lineno + + if hasattr(node, "col_offset"): + self.context["col_offset"] = node.col_offset + if hasattr(node, "end_col_offset"): + self.context["end_col_offset"] = node.end_col_offset + + self.context["node"] = node + self.context["linerange"] = b_utils.linerange(node) + self.context["filename"] = self.fname + self.context["file_data"] = self.fdata + + LOG.debug( + "entering: %s %s [%s]", hex(id(node)), type(node), self.depth + ) + self.depth += 1 + LOG.debug(self.context) + return True + + def visit(self, node): + name = node.__class__.__name__ + method = "visit_" + name + visitor = getattr(self, method, None) + if visitor is not None: + if self.debug: + LOG.debug("%s called (%s)", method, ast.dump(node)) + visitor(node) + else: + self.update_scores(self.tester.run_tests(self.context, name)) + + def post_visit(self, node): + self.depth -= 1 + LOG.debug("%s\texiting : %s", self.depth, hex(id(node))) + + # HACK(tkelsey): this is needed to clean up post-recursion stuff that + # gets setup in the visit methods for these node types. + if isinstance(node, (ast.FunctionDef, ast.ClassDef)): + self.namespace = b_utils.namespace_path_split(self.namespace)[0] + + def generic_visit(self, node): + """Drive the visitor.""" + for _, value in ast.iter_fields(node): + if isinstance(value, list): + max_idx = len(value) - 1 + for idx, item in enumerate(value): + if isinstance(item, ast.AST): + if idx < max_idx: + item._bandit_sibling = value[idx + 1] + else: + item._bandit_sibling = None + item._bandit_parent = node + + if self.pre_visit(item): + self.visit(item) + self.generic_visit(item) + self.post_visit(item) + + elif isinstance(value, ast.AST): + value._bandit_sibling = None + value._bandit_parent = node + if self.pre_visit(value): + self.visit(value) + self.generic_visit(value) + self.post_visit(value) + + def update_scores(self, scores): + """Score updater + + Since we moved from a single score value to a map of scores per + severity, this is needed to update the stored list. + :param score: The score list to update our scores with + """ + # we'll end up with something like: + # SEVERITY: {0, 0, 0, 10} where 10 is weighted by finding and level + for score_type in self.scores: + self.scores[score_type] = list( + map(operator.add, self.scores[score_type], scores[score_type]) + ) + + def process(self, data): + """Main process loop + + Build and process the AST + :param lines: lines code to process + :return score: the aggregated score for the current file + """ + f_ast = ast.parse(data) + self.generic_visit(f_ast) + # Run tests that do not require access to the AST, + # but only to the whole file source: + self.context = { + "file_data": self.fdata, + "filename": self.fname, + "lineno": 0, + "linerange": [0, 1], + "col_offset": 0, + } + self.update_scores(self.tester.run_tests(self.context, "File")) + return self.scores diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/core/test_properties.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/core/test_properties.py new file mode 100644 index 000000000..f6d4da1a7 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/core/test_properties.py @@ -0,0 +1,83 @@ +# +# Copyright 2014 Hewlett-Packard Development Company, L.P. +# +# SPDX-License-Identifier: Apache-2.0 +import logging + +from bandit.core import utils + +LOG = logging.getLogger(__name__) + + +def checks(*args): + """Decorator function to set checks to be run.""" + + def wrapper(func): + if not hasattr(func, "_checks"): + func._checks = [] + for arg in args: + if arg == "File": + func._checks.append("File") + else: + func._checks.append(utils.check_ast_node(arg)) + + LOG.debug("checks() decorator executed") + LOG.debug(" func._checks: %s", func._checks) + return func + + return wrapper + + +def takes_config(*args): + """Test function takes config + + Use of this delegate before a test function indicates that it should be + passed data from the config file. Passing a name parameter allows + aliasing tests and thus sharing config options. + """ + name = "" + + def _takes_config(func): + if not hasattr(func, "_takes_config"): + func._takes_config = name + return func + + if len(args) == 1 and callable(args[0]): + name = args[0].__name__ + return _takes_config(args[0]) + else: + name = args[0] + return _takes_config + + +def test_id(id_val): + """Test function identifier + + Use this decorator before a test function indicates its simple ID + """ + + def _has_id(func): + if not hasattr(func, "_test_id"): + func._test_id = id_val + return func + + return _has_id + + +def accepts_baseline(*args): + """Decorator to indicate formatter accepts baseline results + + Use of this decorator before a formatter indicates that it is able to deal + with baseline results. Specifically this means it has a way to display + candidate results and know when it should do so. + """ + + def wrapper(func): + if not hasattr(func, "_accepts_baseline"): + func._accepts_baseline = True + + LOG.debug("accepts_baseline() decorator executed on %s", func.__name__) + + return func + + return wrapper(args[0]) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/core/test_set.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/core/test_set.py new file mode 100644 index 000000000..1e7dd0d8c --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/core/test_set.py @@ -0,0 +1,114 @@ +# +# Copyright 2014 Hewlett-Packard Development Company, L.P. +# +# SPDX-License-Identifier: Apache-2.0 +import importlib +import logging + +from bandit.core import blacklisting +from bandit.core import extension_loader + +LOG = logging.getLogger(__name__) + + +class BanditTestSet: + def __init__(self, config, profile=None): + if not profile: + profile = {} + extman = extension_loader.MANAGER + filtering = self._get_filter(config, profile) + self.plugins = [ + p for p in extman.plugins if p.plugin._test_id in filtering + ] + self.plugins.extend(self._load_builtins(filtering, profile)) + self._load_tests(config, self.plugins) + + @staticmethod + def _get_filter(config, profile): + extman = extension_loader.MANAGER + + inc = set(profile.get("include", [])) + exc = set(profile.get("exclude", [])) + + all_blacklist_tests = set() + for _, tests in extman.blacklist.items(): + all_blacklist_tests.update(t["id"] for t in tests) + + # this block is purely for backwards compatibility, the rules are as + # follows: + # B001,B401 means B401 + # B401 means B401 + # B001 means all blacklist tests + if "B001" in inc: + if not inc.intersection(all_blacklist_tests): + inc.update(all_blacklist_tests) + inc.discard("B001") + if "B001" in exc: + if not exc.intersection(all_blacklist_tests): + exc.update(all_blacklist_tests) + exc.discard("B001") + + if inc: + filtered = inc + else: + filtered = set(extman.plugins_by_id.keys()) + filtered.update(extman.builtin) + filtered.update(all_blacklist_tests) + return filtered - exc + + def _load_builtins(self, filtering, profile): + """loads up builtin functions, so they can be filtered.""" + + class Wrapper: + def __init__(self, name, plugin): + self.name = name + self.plugin = plugin + + extman = extension_loader.MANAGER + blacklist = profile.get("blacklist") + if not blacklist: # not overridden by legacy data + blacklist = {} + for node, tests in extman.blacklist.items(): + values = [t for t in tests if t["id"] in filtering] + if values: + blacklist[node] = values + + if not blacklist: + return [] + + # this dresses up the blacklist to look like a plugin, but + # the '_checks' data comes from the blacklist information. + # the '_config' is the filtered blacklist data set. + blacklisting.blacklist._test_id = "B001" + blacklisting.blacklist._checks = blacklist.keys() + blacklisting.blacklist._config = blacklist + + return [Wrapper("blacklist", blacklisting.blacklist)] + + def _load_tests(self, config, plugins): + """Builds a dict mapping tests to node types.""" + self.tests = {} + for plugin in plugins: + if hasattr(plugin.plugin, "_takes_config"): + # TODO(??): config could come from profile ... + cfg = config.get_option(plugin.plugin._takes_config) + if cfg is None: + genner = importlib.import_module(plugin.plugin.__module__) + cfg = genner.gen_config(plugin.plugin._takes_config) + plugin.plugin._config = cfg + for check in plugin.plugin._checks: + self.tests.setdefault(check, []).append(plugin.plugin) + LOG.debug( + "added function %s (%s) targeting %s", + plugin.name, + plugin.plugin._test_id, + check, + ) + + def get_tests(self, checktype): + """Returns all tests that are of type checktype + + :param checktype: The type of test to filter on + :return: A list of tests which are of the specified type + """ + return self.tests.get(checktype) or [] diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/core/tester.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/core/tester.py new file mode 100644 index 000000000..32642a5f9 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/core/tester.py @@ -0,0 +1,168 @@ +# +# Copyright 2014 Hewlett-Packard Development Company, L.P. +# +# SPDX-License-Identifier: Apache-2.0 +import copy +import logging +import warnings + +from bandit.core import constants +from bandit.core import context as b_context +from bandit.core import utils + +warnings.formatwarning = utils.warnings_formatter +LOG = logging.getLogger(__name__) + + +class BanditTester: + def __init__(self, testset, debug, nosec_lines, metrics): + self.results = [] + self.testset = testset + self.last_result = None + self.debug = debug + self.nosec_lines = nosec_lines + self.metrics = metrics + + def run_tests(self, raw_context, checktype): + """Runs all tests for a certain type of check, for example + + Runs all tests for a certain type of check, for example 'functions' + store results in results. + + :param raw_context: Raw context dictionary + :param checktype: The type of checks to run + :return: a score based on the number and type of test results with + extra metrics about nosec comments + """ + + scores = { + "SEVERITY": [0] * len(constants.RANKING), + "CONFIDENCE": [0] * len(constants.RANKING), + } + + tests = self.testset.get_tests(checktype) + for test in tests: + name = test.__name__ + # execute test with an instance of the context class + temp_context = copy.copy(raw_context) + context = b_context.Context(temp_context) + try: + if hasattr(test, "_config"): + result = test(context, test._config) + else: + result = test(context) + + if result is not None: + nosec_tests_to_skip = self._get_nosecs_from_contexts( + temp_context, test_result=result + ) + + if isinstance(temp_context["filename"], bytes): + result.fname = temp_context["filename"].decode("utf-8") + else: + result.fname = temp_context["filename"] + result.fdata = temp_context["file_data"] + + if result.lineno is None: + result.lineno = temp_context["lineno"] + if result.linerange == []: + result.linerange = temp_context["linerange"] + if result.col_offset == -1: + result.col_offset = temp_context["col_offset"] + result.end_col_offset = temp_context.get( + "end_col_offset", 0 + ) + result.test = name + if result.test_id == "": + result.test_id = test._test_id + + # don't skip the test if there was no nosec comment + if nosec_tests_to_skip is not None: + # If the set is empty then it means that nosec was + # used without test number -> update nosecs counter. + # If the test id is in the set of tests to skip, + # log and increment the skip by test count. + if not nosec_tests_to_skip: + LOG.debug("skipped, nosec without test number") + self.metrics.note_nosec() + continue + if result.test_id in nosec_tests_to_skip: + LOG.debug( + f"skipped, nosec for test {result.test_id}" + ) + self.metrics.note_skipped_test() + continue + + self.results.append(result) + + LOG.debug("Issue identified by %s: %s", name, result) + sev = constants.RANKING.index(result.severity) + val = constants.RANKING_VALUES[result.severity] + scores["SEVERITY"][sev] += val + con = constants.RANKING.index(result.confidence) + val = constants.RANKING_VALUES[result.confidence] + scores["CONFIDENCE"][con] += val + else: + nosec_tests_to_skip = self._get_nosecs_from_contexts( + temp_context + ) + if ( + nosec_tests_to_skip + and test._test_id in nosec_tests_to_skip + ): + LOG.warning( + f"nosec encountered ({test._test_id}), but no " + f"failed test on file " + f"{temp_context['filename']}:" + f"{temp_context['lineno']}" + ) + + except Exception as e: + self.report_error(name, context, e) + if self.debug: + raise + LOG.debug("Returning scores: %s", scores) + return scores + + def _get_nosecs_from_contexts(self, context, test_result=None): + """Use context and optional test result to get set of tests to skip. + :param context: temp context + :param test_result: optional test result + :return: set of tests to skip for the line based on contexts + """ + nosec_tests_to_skip = set() + base_tests = ( + self.nosec_lines.get(test_result.lineno, None) + if test_result + else None + ) + context_tests = utils.get_nosec(self.nosec_lines, context) + + # if both are none there were no comments + # this is explicitly different from being empty. + # empty set indicates blanket nosec comment without + # individual test names or ids + if base_tests is None and context_tests is None: + nosec_tests_to_skip = None + + # combine tests from current line and context line + if base_tests is not None: + nosec_tests_to_skip.update(base_tests) + if context_tests is not None: + nosec_tests_to_skip.update(context_tests) + + return nosec_tests_to_skip + + @staticmethod + def report_error(test, context, error): + what = "Bandit internal error running: " + what += f"{test} " + what += "on file %s at line %i: " % ( + context._context["filename"], + context._context["lineno"], + ) + what += str(error) + import traceback + + what += traceback.format_exc() + LOG.error(what) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/core/utils.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/core/utils.py new file mode 100644 index 000000000..7feb214df --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/core/utils.py @@ -0,0 +1,398 @@ +# +# Copyright 2014 Hewlett-Packard Development Company, L.P. +# +# SPDX-License-Identifier: Apache-2.0 +import ast +import logging +import os.path +import sys + +try: + import configparser +except ImportError: + import ConfigParser as configparser + +LOG = logging.getLogger(__name__) + + +"""Various helper functions.""" + + +def _get_attr_qual_name(node, aliases): + """Get a the full name for the attribute node. + + This will resolve a pseudo-qualified name for the attribute + rooted at node as long as all the deeper nodes are Names or + Attributes. This will give you how the code referenced the name but + will not tell you what the name actually refers to. If we + encounter a node without a static name we punt with an + empty string. If this encounters something more complex, such as + foo.mylist[0](a,b) we just return empty string. + + :param node: AST Name or Attribute node + :param aliases: Import aliases dictionary + :returns: Qualified name referred to by the attribute or name. + """ + if isinstance(node, ast.Name): + if node.id in aliases: + return aliases[node.id] + return node.id + elif isinstance(node, ast.Attribute): + name = f"{_get_attr_qual_name(node.value, aliases)}.{node.attr}" + if name in aliases: + return aliases[name] + return name + else: + return "" + + +def get_call_name(node, aliases): + if isinstance(node.func, ast.Name): + if deepgetattr(node, "func.id") in aliases: + return aliases[deepgetattr(node, "func.id")] + return deepgetattr(node, "func.id") + elif isinstance(node.func, ast.Attribute): + return _get_attr_qual_name(node.func, aliases) + else: + return "" + + +def get_func_name(node): + return node.name # TODO(tkelsey): get that qualname using enclosing scope + + +def get_qual_attr(node, aliases): + if isinstance(node, ast.Attribute): + try: + val = deepgetattr(node, "value.id") + if val in aliases: + prefix = aliases[val] + else: + prefix = deepgetattr(node, "value.id") + except Exception: + # NOTE(tkelsey): degrade gracefully when we can't get the fully + # qualified name for an attr, just return its base name. + prefix = "" + + return f"{prefix}.{node.attr}" + else: + return "" # TODO(tkelsey): process other node types + + +def deepgetattr(obj, attr): + """Recurses through an attribute chain to get the ultimate value.""" + for key in attr.split("."): + obj = getattr(obj, key) + return obj + + +class InvalidModulePath(Exception): + pass + + +class ConfigError(Exception): + """Raised when the config file fails validation.""" + + def __init__(self, message, config_file): + self.config_file = config_file + self.message = f"{config_file} : {message}" + super().__init__(self.message) + + +class ProfileNotFound(Exception): + """Raised when chosen profile cannot be found.""" + + def __init__(self, config_file, profile): + self.config_file = config_file + self.profile = profile + message = "Unable to find profile ({}) in config file: {}".format( + self.profile, + self.config_file, + ) + super().__init__(message) + + +def warnings_formatter( + message, category=UserWarning, filename="", lineno=-1, line="" +): + """Monkey patch for warnings.warn to suppress cruft output.""" + return f"{message}\n" + + +def get_module_qualname_from_path(path): + """Get the module's qualified name by analysis of the path. + + Resolve the absolute pathname and eliminate symlinks. This could result in + an incorrect name if symlinks are used to restructure the python lib + directory. + + Starting from the right-most directory component look for __init__.py in + the directory component. If it exists then the directory name is part of + the module name. Move left to the subsequent directory components until a + directory is found without __init__.py. + + :param: Path to module file. Relative paths will be resolved relative to + current working directory. + :return: fully qualified module name + """ + + (head, tail) = os.path.split(path) + if head == "" or tail == "": + raise InvalidModulePath( + f'Invalid python file path: "{path}" Missing path or file name' + ) + + qname = [os.path.splitext(tail)[0]] + while head not in ["/", ".", ""]: + if os.path.isfile(os.path.join(head, "__init__.py")): + (head, tail) = os.path.split(head) + qname.insert(0, tail) + else: + break + + qualname = ".".join(qname) + return qualname + + +def namespace_path_join(base, name): + """Extend the current namespace path with an additional name + + Take a namespace path (i.e., package.module.class) and extends it + with an additional name (i.e., package.module.class.subclass). + This is similar to how os.path.join works. + + :param base: (String) The base namespace path. + :param name: (String) The new name to append to the base path. + :returns: (String) A new namespace path resulting from combination of + base and name. + """ + return f"{base}.{name}" + + +def namespace_path_split(path): + """Split the namespace path into a pair (head, tail). + + Tail will be the last namespace path component and head will + be everything leading up to that in the path. This is similar to + os.path.split. + + :param path: (String) A namespace path. + :returns: (String, String) A tuple where the first component is the base + path and the second is the last path component. + """ + return tuple(path.rsplit(".", 1)) + + +def escaped_bytes_representation(b): + """PY3 bytes need escaping for comparison with other strings. + + In practice it turns control characters into acceptable codepoints then + encodes them into bytes again to turn unprintable bytes into printable + escape sequences. + + This is safe to do for the whole range 0..255 and result matches + unicode_escape on a unicode string. + """ + return b.decode("unicode_escape").encode("unicode_escape") + + +def calc_linerange(node): + """Calculate linerange for subtree""" + if hasattr(node, "_bandit_linerange"): + return node._bandit_linerange + + lines_min = 9999999999 + lines_max = -1 + if hasattr(node, "lineno"): + lines_min = node.lineno + lines_max = node.lineno + for n in ast.iter_child_nodes(node): + lines_minmax = calc_linerange(n) + lines_min = min(lines_min, lines_minmax[0]) + lines_max = max(lines_max, lines_minmax[1]) + + node._bandit_linerange = (lines_min, lines_max) + + return (lines_min, lines_max) + + +def linerange(node): + """Get line number range from a node.""" + if hasattr(node, "lineno"): + return list(range(node.lineno, node.end_lineno + 1)) + else: + if hasattr(node, "_bandit_linerange_stripped"): + lines_minmax = node._bandit_linerange_stripped + return list(range(lines_minmax[0], lines_minmax[1] + 1)) + + strip = { + "body": None, + "orelse": None, + "handlers": None, + "finalbody": None, + } + for key in strip.keys(): + if hasattr(node, key): + strip[key] = getattr(node, key) + setattr(node, key, []) + + lines_min = 9999999999 + lines_max = -1 + if hasattr(node, "lineno"): + lines_min = node.lineno + lines_max = node.lineno + for n in ast.iter_child_nodes(node): + lines_minmax = calc_linerange(n) + lines_min = min(lines_min, lines_minmax[0]) + lines_max = max(lines_max, lines_minmax[1]) + + for key in strip.keys(): + if strip[key] is not None: + setattr(node, key, strip[key]) + + if lines_max == -1: + lines_min = 0 + lines_max = 1 + + node._bandit_linerange_stripped = (lines_min, lines_max) + + lines = list(range(lines_min, lines_max + 1)) + + """Try and work around a known Python bug with multi-line strings.""" + # deal with multiline strings lineno behavior (Python issue #16806) + if hasattr(node, "_bandit_sibling") and hasattr( + node._bandit_sibling, "lineno" + ): + start = min(lines) + delta = node._bandit_sibling.lineno - start + if delta > 1: + return list(range(start, node._bandit_sibling.lineno)) + return lines + + +def concat_string(node, stop=None): + """Builds a string from a ast.BinOp chain. + + This will build a string from a series of ast.Constant nodes wrapped in + ast.BinOp nodes. Something like "a" + "b" + "c" or "a %s" % val etc. + The provided node can be any participant in the BinOp chain. + + :param node: (ast.Constant or ast.BinOp) The node to process + :param stop: (ast.Constant or ast.BinOp) Optional base node to stop at + :returns: (Tuple) the root node of the expression, the string value + """ + + def _get(node, bits, stop=None): + if node != stop: + bits.append( + _get(node.left, bits, stop) + if isinstance(node.left, ast.BinOp) + else node.left + ) + bits.append( + _get(node.right, bits, stop) + if isinstance(node.right, ast.BinOp) + else node.right + ) + + bits = [node] + while isinstance(node._bandit_parent, ast.BinOp): + node = node._bandit_parent + if isinstance(node, ast.BinOp): + _get(node, bits, stop) + return ( + node, + " ".join( + [ + x.value + for x in bits + if isinstance(x, ast.Constant) and isinstance(x.value, str) + ] + ), + ) + + +def get_called_name(node): + """Get a function name from an ast.Call node. + + An ast.Call node representing a method call with present differently to one + wrapping a function call: thing.call() vs call(). This helper will grab the + unqualified call name correctly in either case. + + :param node: (ast.Call) the call node + :returns: (String) the function name + """ + func = node.func + try: + return func.attr if isinstance(func, ast.Attribute) else func.id + except AttributeError: + return "" + + +def get_path_for_function(f): + """Get the path of the file where the function is defined. + + :returns: the path, or None if one could not be found or f is not a real + function + """ + + if hasattr(f, "__module__"): + module_name = f.__module__ + elif hasattr(f, "im_func"): + module_name = f.im_func.__module__ + else: + LOG.warning("Cannot resolve file where %s is defined", f) + return None + + module = sys.modules[module_name] + if hasattr(module, "__file__"): + return module.__file__ + else: + LOG.warning("Cannot resolve file path for module %s", module_name) + return None + + +def parse_ini_file(f_loc): + config = configparser.ConfigParser() + try: + config.read(f_loc) + return {k: v for k, v in config.items("bandit")} + + except (configparser.Error, KeyError, TypeError): + LOG.warning( + "Unable to parse config file %s or missing [bandit] " "section", + f_loc, + ) + + return None + + +def check_ast_node(name): + "Check if the given name is that of a valid AST node." + try: + # These ast Node types were deprecated in Python 3.12 and removed + # in Python 3.14, but plugins may still check on them. + if sys.version_info >= (3, 12) and name in ( + "Num", + "Str", + "Ellipsis", + "NameConstant", + "Bytes", + ): + return name + + node = getattr(ast, name) + if issubclass(node, ast.AST): + return name + except AttributeError: # nosec(tkelsey): catching expected exception + pass + + raise TypeError(f"Error: {name} is not a valid node type in AST") + + +def get_nosec(nosec_lines, context): + for lineno in context["linerange"]: + nosec = nosec_lines.get(lineno, None) + if nosec is not None: + return nosec + return None diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/formatters/__init__.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/formatters/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/formatters/csv.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/formatters/csv.py new file mode 100644 index 000000000..6cde187f5 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/formatters/csv.py @@ -0,0 +1,82 @@ +# +# SPDX-License-Identifier: Apache-2.0 +r""" +============= +CSV Formatter +============= + +This formatter outputs the issues in a comma separated values format. + +:Example: + +.. code-block:: none + + filename,test_name,test_id,issue_severity,issue_confidence,issue_cwe, + issue_text,line_number,line_range,more_info + examples/yaml_load.py,blacklist_calls,B301,MEDIUM,HIGH, + https://cwe.mitre.org/data/definitions/20.html,"Use of unsafe yaml + load. Allows instantiation of arbitrary objects. Consider yaml.safe_load(). + ",5,[5],https://bandit.readthedocs.io/en/latest/ + +.. versionadded:: 0.11.0 + +.. versionchanged:: 1.5.0 + New field `more_info` added to output + +.. versionchanged:: 1.7.3 + New field `CWE` added to output + +""" +# Necessary for this formatter to work when imported on Python 2. Importing +# the standard library's csv module conflicts with the name of this module. +import csv +import logging +import sys + +from bandit.core import docs_utils + +LOG = logging.getLogger(__name__) + + +def report(manager, fileobj, sev_level, conf_level, lines=-1): + """Prints issues in CSV format + + :param manager: the bandit manager object + :param fileobj: The output file object, which may be sys.stdout + :param sev_level: Filtering severity level + :param conf_level: Filtering confidence level + :param lines: Number of lines to report, -1 for all + """ + + results = manager.get_issue_list( + sev_level=sev_level, conf_level=conf_level + ) + + with fileobj: + fieldnames = [ + "filename", + "test_name", + "test_id", + "issue_severity", + "issue_confidence", + "issue_cwe", + "issue_text", + "line_number", + "col_offset", + "end_col_offset", + "line_range", + "more_info", + ] + + writer = csv.DictWriter( + fileobj, fieldnames=fieldnames, extrasaction="ignore" + ) + writer.writeheader() + for result in results: + r = result.as_dict(with_code=False) + r["issue_cwe"] = r["issue_cwe"]["link"] + r["more_info"] = docs_utils.get_url(r["test_id"]) + writer.writerow(r) + + if fileobj.name != sys.stdout.name: + LOG.info("CSV output written to file: %s", fileobj.name) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/formatters/custom.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/formatters/custom.py new file mode 100644 index 000000000..e9381ea04 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/formatters/custom.py @@ -0,0 +1,161 @@ +# +# Copyright (c) 2017 Hewlett Packard Enterprise +# +# SPDX-License-Identifier: Apache-2.0 +""" +================ +Custom Formatter +================ + +This formatter outputs the issues in custom machine-readable format. + +default template: ``{abspath}:{line}: {test_id}[bandit]: {severity}: {msg}`` + +:Example: + +.. code-block:: none + + /usr/lib/python3.6/site-packages/openlp/core/utils/__init__.py:\ +405: B310[bandit]: MEDIUM: Audit url open for permitted schemes. \ +Allowing use of file:/ or custom schemes is often unexpected. + +.. versionadded:: 1.5.0 + +.. versionchanged:: 1.7.3 + New field `CWE` added to output + +""" +import logging +import os +import re +import string +import sys + +from bandit.core import test_properties + +LOG = logging.getLogger(__name__) + + +class SafeMapper(dict): + """Safe mapper to handle format key errors""" + + @classmethod # To prevent PEP8 warnings in the test suite + def __missing__(cls, key): + return "{%s}" % key + + +@test_properties.accepts_baseline +def report(manager, fileobj, sev_level, conf_level, template=None): + """Prints issues in custom format + + :param manager: the bandit manager object + :param fileobj: The output file object, which may be sys.stdout + :param sev_level: Filtering severity level + :param conf_level: Filtering confidence level + :param template: Output template with non-terminal tags + (default: '{abspath}:{line}: + {test_id}[bandit]: {severity}: {msg}') + """ + + machine_output = {"results": [], "errors": []} + for fname, reason in manager.get_skipped(): + machine_output["errors"].append({"filename": fname, "reason": reason}) + + results = manager.get_issue_list( + sev_level=sev_level, conf_level=conf_level + ) + + msg_template = template + if template is None: + msg_template = "{abspath}:{line}: {test_id}[bandit]: {severity}: {msg}" + + # Dictionary of non-terminal tags that will be expanded + tag_mapper = { + "abspath": lambda issue: os.path.abspath(issue.fname), + "relpath": lambda issue: os.path.relpath(issue.fname), + "line": lambda issue: issue.lineno, + "col": lambda issue: issue.col_offset, + "end_col": lambda issue: issue.end_col_offset, + "test_id": lambda issue: issue.test_id, + "severity": lambda issue: issue.severity, + "msg": lambda issue: issue.text, + "confidence": lambda issue: issue.confidence, + "range": lambda issue: issue.linerange, + "cwe": lambda issue: issue.cwe, + } + + # Create dictionary with tag sets to speed up search for similar tags + tag_sim_dict = {tag: set(tag) for tag, _ in tag_mapper.items()} + + # Parse the format_string template and check the validity of tags + try: + parsed_template_orig = list(string.Formatter().parse(msg_template)) + # of type (literal_text, field_name, fmt_spec, conversion) + + # Check the format validity only, ignore keys + string.Formatter().vformat(msg_template, (), SafeMapper(line=0)) + except ValueError as e: + LOG.error("Template is not in valid format: %s", e.args[0]) + sys.exit(2) + + tag_set = {t[1] for t in parsed_template_orig if t[1] is not None} + if not tag_set: + LOG.error("No tags were found in the template. Are you missing '{}'?") + sys.exit(2) + + def get_similar_tag(tag): + similarity_list = [ + (len(set(tag) & t_set), t) for t, t_set in tag_sim_dict.items() + ] + return sorted(similarity_list)[-1][1] + + tag_blacklist = [] + for tag in tag_set: + # check if the tag is in dictionary + if tag not in tag_mapper: + similar_tag = get_similar_tag(tag) + LOG.warning( + "Tag '%s' was not recognized and will be skipped, " + "did you mean to use '%s'?", + tag, + similar_tag, + ) + tag_blacklist += [tag] + + # Compose the message template back with the valid values only + msg_parsed_template_list = [] + for literal_text, field_name, fmt_spec, conversion in parsed_template_orig: + if literal_text: + # if there is '{' or '}', double it to prevent expansion + literal_text = re.sub("{", "{{", literal_text) + literal_text = re.sub("}", "}}", literal_text) + msg_parsed_template_list.append(literal_text) + + if field_name is not None: + if field_name in tag_blacklist: + msg_parsed_template_list.append(field_name) + continue + # Append the fmt_spec part + params = [field_name, fmt_spec, conversion] + markers = ["", ":", "!"] + msg_parsed_template_list.append( + ["{"] + + [f"{m + p}" if p else "" for m, p in zip(markers, params)] + + ["}"] + ) + + msg_parsed_template = ( + "".join([item for lst in msg_parsed_template_list for item in lst]) + + "\n" + ) + with fileobj: + for defect in results: + evaluated_tags = SafeMapper( + (k, v(defect)) for k, v in tag_mapper.items() + ) + output = msg_parsed_template.format(**evaluated_tags) + + fileobj.write(output) + + if fileobj.name != sys.stdout.name: + LOG.info("Result written to file: %s", fileobj.name) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/formatters/html.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/formatters/html.py new file mode 100644 index 000000000..fb09f835f --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/formatters/html.py @@ -0,0 +1,394 @@ +# Copyright (c) 2015 Rackspace, Inc. +# Copyright (c) 2015 Hewlett Packard Enterprise +# +# SPDX-License-Identifier: Apache-2.0 +r""" +============== +HTML formatter +============== + +This formatter outputs the issues as HTML. + +:Example: + +.. code-block:: html + + + + + + + + + Bandit Report + + + + + + + +

+
+
+ Metrics:
+
+ Total lines of code: 9
+ Total lines skipped (#nosec): 0 +
+
+ + + + +
+
+ +
+
+ yaml_load: Use of unsafe yaml load. Allows + instantiation of arbitrary objects. Consider yaml.safe_load().
+ Test ID: B506
+ Severity: MEDIUM
+ Confidence: HIGH
+ CWE: CWE-20 (https://cwe.mitre.org/data/definitions/20.html)
+ File: examples/yaml_load.py
+ More info: + https://bandit.readthedocs.io/en/latest/plugins/yaml_load.html +
+ +
+
+    5       ystr = yaml.dump({'a' : 1, 'b' : 2, 'c' : 3})
+    6       y = yaml.load(ystr)
+    7       yaml.dump(y)
+    
+
+ + +
+
+ +
+ + + + +.. versionadded:: 0.14.0 + +.. versionchanged:: 1.5.0 + New field `more_info` added to output + +.. versionchanged:: 1.7.3 + New field `CWE` added to output + +""" +import logging +import sys +from html import escape as html_escape + +from bandit.core import docs_utils +from bandit.core import test_properties +from bandit.formatters import utils + +LOG = logging.getLogger(__name__) + + +@test_properties.accepts_baseline +def report(manager, fileobj, sev_level, conf_level, lines=-1): + """Writes issues to 'fileobj' in HTML format + + :param manager: the bandit manager object + :param fileobj: The output file object, which may be sys.stdout + :param sev_level: Filtering severity level + :param conf_level: Filtering confidence level + :param lines: Number of lines to report, -1 for all + """ + + header_block = """ + + + + + + + + Bandit Report + + + + +""" + + report_block = """ + +{metrics} +{skipped} + +
+
+ {results} +
+ + + +""" + + issue_block = """ +
+
+ {test_name}: {test_text}
+ Test ID: {test_id}
+ Severity: {severity}
+ Confidence: {confidence}
+ CWE: CWE-{cwe.id}
+ File: {path}
+ Line number: {line_number}
+ More info: {url}
+{code} +{candidates} +
+
+""" + + code_block = """ +
+
+{code}
+
+
+""" + + candidate_block = """ +
+
+Candidates: +{candidate_list} +
+""" + + candidate_issue = """ +
+
+
{code}
+
+
+""" + + skipped_block = """ +
+
+
+Skipped files:

+{files_list} +
+
+""" + + metrics_block = """ +
+
+
+ Metrics:
+
+ Total lines of code: {loc}
+ Total lines skipped (#nosec): {nosec} +
+
+ +""" + + issues = manager.get_issue_list(sev_level=sev_level, conf_level=conf_level) + + baseline = not isinstance(issues, list) + + # build the skipped string to insert in the report + skipped_str = "".join( + f"{fname} reason: {reason}
" + for fname, reason in manager.get_skipped() + ) + if skipped_str: + skipped_text = skipped_block.format(files_list=skipped_str) + else: + skipped_text = "" + + # build the results string to insert in the report + results_str = "" + for index, issue in enumerate(issues): + if not baseline or len(issues[issue]) == 1: + candidates = "" + safe_code = html_escape( + issue.get_code(lines, True).strip("\n").lstrip(" ") + ) + code = code_block.format(code=safe_code) + else: + candidates_str = "" + code = "" + for candidate in issues[issue]: + candidate_code = html_escape( + candidate.get_code(lines, True).strip("\n").lstrip(" ") + ) + candidates_str += candidate_issue.format(code=candidate_code) + + candidates = candidate_block.format(candidate_list=candidates_str) + + url = docs_utils.get_url(issue.test_id) + results_str += issue_block.format( + issue_no=index, + issue_class=f"issue-sev-{issue.severity.lower()}", + test_name=issue.test, + test_id=issue.test_id, + test_text=issue.text, + severity=issue.severity, + confidence=issue.confidence, + cwe=issue.cwe, + cwe_link=issue.cwe.link(), + path=issue.fname, + code=code, + candidates=candidates, + url=url, + line_number=issue.lineno, + ) + + # build the metrics string to insert in the report + metrics_summary = metrics_block.format( + loc=manager.metrics.data["_totals"]["loc"], + nosec=manager.metrics.data["_totals"]["nosec"], + ) + + # build the report and output it + report_contents = report_block.format( + metrics=metrics_summary, skipped=skipped_text, results=results_str + ) + + with fileobj: + wrapped_file = utils.wrap_file_object(fileobj) + wrapped_file.write(header_block) + wrapped_file.write(report_contents) + + if fileobj.name != sys.stdout.name: + LOG.info("HTML output written to file: %s", fileobj.name) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/formatters/json.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/formatters/json.py new file mode 100644 index 000000000..3a954a4dd --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/formatters/json.py @@ -0,0 +1,155 @@ +# +# SPDX-License-Identifier: Apache-2.0 +r""" +============== +JSON formatter +============== + +This formatter outputs the issues in JSON. + +:Example: + +.. code-block:: javascript + + { + "errors": [], + "generated_at": "2015-12-16T22:27:34Z", + "metrics": { + "_totals": { + "CONFIDENCE.HIGH": 1, + "CONFIDENCE.LOW": 0, + "CONFIDENCE.MEDIUM": 0, + "CONFIDENCE.UNDEFINED": 0, + "SEVERITY.HIGH": 0, + "SEVERITY.LOW": 0, + "SEVERITY.MEDIUM": 1, + "SEVERITY.UNDEFINED": 0, + "loc": 5, + "nosec": 0 + }, + "examples/yaml_load.py": { + "CONFIDENCE.HIGH": 1, + "CONFIDENCE.LOW": 0, + "CONFIDENCE.MEDIUM": 0, + "CONFIDENCE.UNDEFINED": 0, + "SEVERITY.HIGH": 0, + "SEVERITY.LOW": 0, + "SEVERITY.MEDIUM": 1, + "SEVERITY.UNDEFINED": 0, + "loc": 5, + "nosec": 0 + } + }, + "results": [ + { + "code": "4 ystr = yaml.dump({'a' : 1, 'b' : 2, 'c' : 3})\n5 + y = yaml.load(ystr)\n6 yaml.dump(y)\n", + "filename": "examples/yaml_load.py", + "issue_confidence": "HIGH", + "issue_severity": "MEDIUM", + "issue_cwe": { + "id": 20, + "link": "https://cwe.mitre.org/data/definitions/20.html" + }, + "issue_text": "Use of unsafe yaml load. Allows instantiation of + arbitrary objects. Consider yaml.safe_load().\n", + "line_number": 5, + "line_range": [ + 5 + ], + "more_info": "https://bandit.readthedocs.io/en/latest/", + "test_name": "blacklist_calls", + "test_id": "B301" + } + ] + } + +.. versionadded:: 0.10.0 + +.. versionchanged:: 1.5.0 + New field `more_info` added to output + +.. versionchanged:: 1.7.3 + New field `CWE` added to output + +""" +# Necessary so we can import the standard library json module while continuing +# to name this file json.py. (Python 2 only) +import datetime +import json +import logging +import operator +import sys + +from bandit.core import docs_utils +from bandit.core import test_properties + +LOG = logging.getLogger(__name__) + + +@test_properties.accepts_baseline +def report(manager, fileobj, sev_level, conf_level, lines=-1): + """''Prints issues in JSON format + + :param manager: the bandit manager object + :param fileobj: The output file object, which may be sys.stdout + :param sev_level: Filtering severity level + :param conf_level: Filtering confidence level + :param lines: Number of lines to report, -1 for all + """ + + machine_output = {"results": [], "errors": []} + for fname, reason in manager.get_skipped(): + machine_output["errors"].append({"filename": fname, "reason": reason}) + + results = manager.get_issue_list( + sev_level=sev_level, conf_level=conf_level + ) + + baseline = not isinstance(results, list) + + if baseline: + collector = [] + for r in results: + d = r.as_dict(max_lines=lines) + d["more_info"] = docs_utils.get_url(d["test_id"]) + if len(results[r]) > 1: + d["candidates"] = [ + c.as_dict(max_lines=lines) for c in results[r] + ] + collector.append(d) + + else: + collector = [r.as_dict(max_lines=lines) for r in results] + for elem in collector: + elem["more_info"] = docs_utils.get_url(elem["test_id"]) + + itemgetter = operator.itemgetter + if manager.agg_type == "vuln": + machine_output["results"] = sorted( + collector, key=itemgetter("test_name") + ) + else: + machine_output["results"] = sorted( + collector, key=itemgetter("filename") + ) + + machine_output["metrics"] = manager.metrics.data + + # timezone agnostic format + TS_FORMAT = "%Y-%m-%dT%H:%M:%SZ" + + time_string = datetime.datetime.now(datetime.timezone.utc).strftime( + TS_FORMAT + ) + machine_output["generated_at"] = time_string + + result = json.dumps( + machine_output, sort_keys=True, indent=2, separators=(",", ": ") + ) + + with fileobj: + fileobj.write(result) + + if fileobj.name != sys.stdout.name: + LOG.info("JSON output written to file: %s", fileobj.name) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/formatters/sarif.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/formatters/sarif.py new file mode 100644 index 000000000..5b06ce71d --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/formatters/sarif.py @@ -0,0 +1,374 @@ +# Copyright (c) Microsoft. All Rights Reserved. +# +# SPDX-License-Identifier: Apache-2.0 +# +# Note: this code mostly incorporated from +# https://github.com/microsoft/bandit-sarif-formatter +# +r""" +=============== +SARIF formatter +=============== + +This formatter outputs the issues in SARIF formatted JSON. + +:Example: + +.. code-block:: javascript + + { + "runs": [ + { + "tool": { + "driver": { + "name": "Bandit", + "organization": "PyCQA", + "rules": [ + { + "id": "B101", + "name": "assert_used", + "properties": { + "tags": [ + "security", + "external/cwe/cwe-703" + ], + "precision": "high" + }, + "helpUri": "https://bandit.readthedocs.io/en/1.7.8/plugins/b101_assert_used.html" + } + ], + "version": "1.7.8", + "semanticVersion": "1.7.8" + } + }, + "invocations": [ + { + "executionSuccessful": true, + "endTimeUtc": "2024-03-05T03:28:48Z" + } + ], + "properties": { + "metrics": { + "_totals": { + "loc": 1, + "nosec": 0, + "skipped_tests": 0, + "SEVERITY.UNDEFINED": 0, + "CONFIDENCE.UNDEFINED": 0, + "SEVERITY.LOW": 1, + "CONFIDENCE.LOW": 0, + "SEVERITY.MEDIUM": 0, + "CONFIDENCE.MEDIUM": 0, + "SEVERITY.HIGH": 0, + "CONFIDENCE.HIGH": 1 + }, + "./examples/assert.py": { + "loc": 1, + "nosec": 0, + "skipped_tests": 0, + "SEVERITY.UNDEFINED": 0, + "SEVERITY.LOW": 1, + "SEVERITY.MEDIUM": 0, + "SEVERITY.HIGH": 0, + "CONFIDENCE.UNDEFINED": 0, + "CONFIDENCE.LOW": 0, + "CONFIDENCE.MEDIUM": 0, + "CONFIDENCE.HIGH": 1 + } + } + }, + "results": [ + { + "message": { + "text": "Use of assert detected. The enclosed code will be removed when compiling to optimised byte code." + }, + "level": "note", + "locations": [ + { + "physicalLocation": { + "region": { + "snippet": { + "text": "assert True\n" + }, + "endColumn": 11, + "endLine": 1, + "startColumn": 0, + "startLine": 1 + }, + "artifactLocation": { + "uri": "examples/assert.py" + }, + "contextRegion": { + "snippet": { + "text": "assert True\n" + }, + "endLine": 1, + "startLine": 1 + } + } + } + ], + "properties": { + "issue_confidence": "HIGH", + "issue_severity": "LOW" + }, + "ruleId": "B101", + "ruleIndex": 0 + } + ] + } + ], + "version": "2.1.0", + "$schema": "https://json.schemastore.org/sarif-2.1.0.json" + } + +.. versionadded:: 1.7.8 + +""" # noqa: E501 +import datetime +import logging +import pathlib +import sys +import urllib.parse as urlparse + +import sarif_om as om +from jschema_to_python.to_json import to_json + +import bandit +from bandit.core import docs_utils + +LOG = logging.getLogger(__name__) +SCHEMA_URI = "https://json.schemastore.org/sarif-2.1.0.json" +SCHEMA_VER = "2.1.0" +TS_FORMAT = "%Y-%m-%dT%H:%M:%SZ" + + +def report(manager, fileobj, sev_level, conf_level, lines=-1): + """Prints issues in SARIF format + + :param manager: the bandit manager object + :param fileobj: The output file object, which may be sys.stdout + :param sev_level: Filtering severity level + :param conf_level: Filtering confidence level + :param lines: Number of lines to report, -1 for all + """ + + log = om.SarifLog( + schema_uri=SCHEMA_URI, + version=SCHEMA_VER, + runs=[ + om.Run( + tool=om.Tool( + driver=om.ToolComponent( + name="Bandit", + organization=bandit.__author__, + semantic_version=bandit.__version__, + version=bandit.__version__, + ) + ), + invocations=[ + om.Invocation( + end_time_utc=datetime.datetime.now( + datetime.timezone.utc + ).strftime(TS_FORMAT), + execution_successful=True, + ) + ], + properties={"metrics": manager.metrics.data}, + ) + ], + ) + + run = log.runs[0] + invocation = run.invocations[0] + + skips = manager.get_skipped() + add_skipped_file_notifications(skips, invocation) + + issues = manager.get_issue_list(sev_level=sev_level, conf_level=conf_level) + + add_results(issues, run) + + serializedLog = to_json(log) + + with fileobj: + fileobj.write(serializedLog) + + if fileobj.name != sys.stdout.name: + LOG.info("SARIF output written to file: %s", fileobj.name) + + +def add_skipped_file_notifications(skips, invocation): + if skips is None or len(skips) == 0: + return + + if invocation.tool_configuration_notifications is None: + invocation.tool_configuration_notifications = [] + + for skip in skips: + (file_name, reason) = skip + + notification = om.Notification( + level="error", + message=om.Message(text=reason), + locations=[ + om.Location( + physical_location=om.PhysicalLocation( + artifact_location=om.ArtifactLocation( + uri=to_uri(file_name) + ) + ) + ) + ], + ) + + invocation.tool_configuration_notifications.append(notification) + + +def add_results(issues, run): + if run.results is None: + run.results = [] + + rules = {} + rule_indices = {} + for issue in issues: + result = create_result(issue, rules, rule_indices) + run.results.append(result) + + if len(rules) > 0: + run.tool.driver.rules = list(rules.values()) + + +def create_result(issue, rules, rule_indices): + issue_dict = issue.as_dict() + + rule, rule_index = create_or_find_rule(issue_dict, rules, rule_indices) + + physical_location = om.PhysicalLocation( + artifact_location=om.ArtifactLocation( + uri=to_uri(issue_dict["filename"]) + ) + ) + + add_region_and_context_region( + physical_location, + issue_dict["line_range"], + issue_dict["col_offset"], + issue_dict["end_col_offset"], + issue_dict["code"], + ) + + return om.Result( + rule_id=rule.id, + rule_index=rule_index, + message=om.Message(text=issue_dict["issue_text"]), + level=level_from_severity(issue_dict["issue_severity"]), + locations=[om.Location(physical_location=physical_location)], + properties={ + "issue_confidence": issue_dict["issue_confidence"], + "issue_severity": issue_dict["issue_severity"], + }, + ) + + +def level_from_severity(severity): + if severity == "HIGH": + return "error" + elif severity == "MEDIUM": + return "warning" + elif severity == "LOW": + return "note" + else: + return "warning" + + +def add_region_and_context_region( + physical_location, line_range, col_offset, end_col_offset, code +): + if code: + first_line_number, snippet_lines = parse_code(code) + snippet_line = snippet_lines[line_range[0] - first_line_number] + snippet = om.ArtifactContent(text=snippet_line) + else: + snippet = None + + physical_location.region = om.Region( + start_line=line_range[0], + end_line=line_range[1] if len(line_range) > 1 else line_range[0], + start_column=col_offset + 1, + end_column=end_col_offset + 1, + snippet=snippet, + ) + + if code: + physical_location.context_region = om.Region( + start_line=first_line_number, + end_line=first_line_number + len(snippet_lines) - 1, + snippet=om.ArtifactContent(text="".join(snippet_lines)), + ) + + +def parse_code(code): + code_lines = code.split("\n") + + # The last line from the split has nothing in it; it's an artifact of the + # last "real" line ending in a newline. Unless, of course, it doesn't: + last_line = code_lines[len(code_lines) - 1] + + last_real_line_ends_in_newline = False + if len(last_line) == 0: + code_lines.pop() + last_real_line_ends_in_newline = True + + snippet_lines = [] + first_line_number = 0 + first = True + for code_line in code_lines: + number_and_snippet_line = code_line.split(" ", 1) + if first: + first_line_number = int(number_and_snippet_line[0]) + first = False + + snippet_line = number_and_snippet_line[1] + "\n" + snippet_lines.append(snippet_line) + + if not last_real_line_ends_in_newline: + last_line = snippet_lines[len(snippet_lines) - 1] + snippet_lines[len(snippet_lines) - 1] = last_line[: len(last_line) - 1] + + return first_line_number, snippet_lines + + +def create_or_find_rule(issue_dict, rules, rule_indices): + rule_id = issue_dict["test_id"] + if rule_id in rules: + return rules[rule_id], rule_indices[rule_id] + + rule = om.ReportingDescriptor( + id=rule_id, + name=issue_dict["test_name"], + help_uri=docs_utils.get_url(rule_id), + properties={ + "tags": [ + "security", + f"external/cwe/cwe-{issue_dict['issue_cwe'].get('id')}", + ], + "precision": issue_dict["issue_confidence"].lower(), + }, + ) + + index = len(rules) + rules[rule_id] = rule + rule_indices[rule_id] = index + return rule, index + + +def to_uri(file_path): + pure_path = pathlib.PurePath(file_path) + if pure_path.is_absolute(): + return pure_path.as_uri() + else: + # Replace backslashes with slashes. + posix_path = pure_path.as_posix() + # %-encode special characters. + return urlparse.quote(posix_path) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/formatters/screen.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/formatters/screen.py new file mode 100644 index 000000000..7421c3ea8 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/formatters/screen.py @@ -0,0 +1,244 @@ +# Copyright (c) 2015 Hewlett Packard Enterprise +# +# SPDX-License-Identifier: Apache-2.0 +r""" +================ +Screen formatter +================ + +This formatter outputs the issues as color coded text to screen. + +:Example: + +.. code-block:: none + + >> Issue: [B506: yaml_load] Use of unsafe yaml load. Allows + instantiation of arbitrary objects. Consider yaml.safe_load(). + + Severity: Medium Confidence: High + CWE: CWE-20 (https://cwe.mitre.org/data/definitions/20.html) + More Info: https://bandit.readthedocs.io/en/latest/ + Location: examples/yaml_load.py:5 + 4 ystr = yaml.dump({'a' : 1, 'b' : 2, 'c' : 3}) + 5 y = yaml.load(ystr) + 6 yaml.dump(y) + +.. versionadded:: 0.9.0 + +.. versionchanged:: 1.5.0 + New field `more_info` added to output + +.. versionchanged:: 1.7.3 + New field `CWE` added to output + +""" +import datetime +import logging +import sys + +from bandit.core import constants +from bandit.core import docs_utils +from bandit.core import test_properties + +IS_WIN_PLATFORM = sys.platform.startswith("win32") +COLORAMA = False + +# This fixes terminal colors not displaying properly on Windows systems. +# Colorama will intercept any ANSI escape codes and convert them to the +# proper Windows console API calls to change text color. +if IS_WIN_PLATFORM: + try: + import colorama + except ImportError: + pass + else: + COLORAMA = True + + +LOG = logging.getLogger(__name__) + +COLOR = { + "DEFAULT": "\033[0m", + "HEADER": "\033[95m", + "LOW": "\033[94m", + "MEDIUM": "\033[93m", + "HIGH": "\033[91m", +} + + +def header(text, *args): + return f"{COLOR['HEADER']}{text % args}{COLOR['DEFAULT']}" + + +def get_verbose_details(manager): + bits = [] + bits.append(header("Files in scope (%i):", len(manager.files_list))) + tpl = "\t%s (score: {SEVERITY: %i, CONFIDENCE: %i})" + bits.extend( + [ + tpl % (item, sum(score["SEVERITY"]), sum(score["CONFIDENCE"])) + for (item, score) in zip(manager.files_list, manager.scores) + ] + ) + bits.append(header("Files excluded (%i):", len(manager.excluded_files))) + bits.extend([f"\t{fname}" for fname in manager.excluded_files]) + return "\n".join([str(bit) for bit in bits]) + + +def get_metrics(manager): + bits = [] + bits.append(header("\nRun metrics:")) + for criteria, _ in constants.CRITERIA: + bits.append(f"\tTotal issues (by {criteria.lower()}):") + for rank in constants.RANKING: + bits.append( + "\t\t%s: %s" + % ( + rank.capitalize(), + manager.metrics.data["_totals"][f"{criteria}.{rank}"], + ) + ) + return "\n".join([str(bit) for bit in bits]) + + +def _output_issue_str( + issue, indent, show_lineno=True, show_code=True, lines=-1 +): + # returns a list of lines that should be added to the existing lines list + bits = [] + bits.append( + "%s%s>> Issue: [%s:%s] %s" + % ( + indent, + COLOR[issue.severity], + issue.test_id, + issue.test, + issue.text, + ) + ) + + bits.append( + "%s Severity: %s Confidence: %s" + % ( + indent, + issue.severity.capitalize(), + issue.confidence.capitalize(), + ) + ) + + bits.append(f"{indent} CWE: {str(issue.cwe)}") + + bits.append(f"{indent} More Info: {docs_utils.get_url(issue.test_id)}") + + bits.append( + "%s Location: %s:%s:%s%s" + % ( + indent, + issue.fname, + issue.lineno if show_lineno else "", + issue.col_offset if show_lineno else "", + COLOR["DEFAULT"], + ) + ) + + if show_code: + bits.extend( + [indent + line for line in issue.get_code(lines, True).split("\n")] + ) + + return "\n".join([bit for bit in bits]) + + +def get_results(manager, sev_level, conf_level, lines): + bits = [] + issues = manager.get_issue_list(sev_level, conf_level) + baseline = not isinstance(issues, list) + candidate_indent = " " * 10 + + if not len(issues): + return "\tNo issues identified." + + for issue in issues: + # if not a baseline or only one candidate we know the issue + if not baseline or len(issues[issue]) == 1: + bits.append(_output_issue_str(issue, "", lines=lines)) + + # otherwise show the finding and the candidates + else: + bits.append( + _output_issue_str( + issue, "", show_lineno=False, show_code=False + ) + ) + + bits.append("\n-- Candidate Issues --") + for candidate in issues[issue]: + bits.append( + _output_issue_str(candidate, candidate_indent, lines=lines) + ) + bits.append("\n") + bits.append("-" * 50) + + return "\n".join([bit for bit in bits]) + + +def do_print(bits): + # needed so we can mock this stuff + print("\n".join([bit for bit in bits])) + + +@test_properties.accepts_baseline +def report(manager, fileobj, sev_level, conf_level, lines=-1): + """Prints discovered issues formatted for screen reading + + This makes use of VT100 terminal codes for colored text. + + :param manager: the bandit manager object + :param fileobj: The output file object, which may be sys.stdout + :param sev_level: Filtering severity level + :param conf_level: Filtering confidence level + :param lines: Number of lines to report, -1 for all + """ + + if IS_WIN_PLATFORM and COLORAMA: + colorama.init() + + bits = [] + if not manager.quiet or manager.results_count(sev_level, conf_level): + bits.append( + header( + "Run started:%s", datetime.datetime.now(datetime.timezone.utc) + ) + ) + + if manager.verbose: + bits.append(get_verbose_details(manager)) + + bits.append(header("\nTest results:")) + bits.append(get_results(manager, sev_level, conf_level, lines)) + bits.append(header("\nCode scanned:")) + bits.append( + "\tTotal lines of code: %i" + % (manager.metrics.data["_totals"]["loc"]) + ) + + bits.append( + "\tTotal lines skipped (#nosec): %i" + % (manager.metrics.data["_totals"]["nosec"]) + ) + + bits.append(get_metrics(manager)) + skipped = manager.get_skipped() + bits.append(header("Files skipped (%i):", len(skipped))) + bits.extend(["\t%s (%s)" % skip for skip in skipped]) + do_print(bits) + + if fileobj.name != sys.stdout.name: + LOG.info( + "Screen formatter output was not written to file: %s, " + "consider '-f txt'", + fileobj.name, + ) + + if IS_WIN_PLATFORM and COLORAMA: + colorama.deinit() diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/formatters/text.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/formatters/text.py new file mode 100644 index 000000000..932491805 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/formatters/text.py @@ -0,0 +1,200 @@ +# Copyright (c) 2015 Hewlett Packard Enterprise +# +# SPDX-License-Identifier: Apache-2.0 +r""" +============== +Text Formatter +============== + +This formatter outputs the issues as plain text. + +:Example: + +.. code-block:: none + + >> Issue: [B301:blacklist_calls] Use of unsafe yaml load. Allows + instantiation of arbitrary objects. Consider yaml.safe_load(). + + Severity: Medium Confidence: High + CWE: CWE-20 (https://cwe.mitre.org/data/definitions/20.html) + More Info: https://bandit.readthedocs.io/en/latest/ + Location: examples/yaml_load.py:5 + 4 ystr = yaml.dump({'a' : 1, 'b' : 2, 'c' : 3}) + 5 y = yaml.load(ystr) + 6 yaml.dump(y) + +.. versionadded:: 0.9.0 + +.. versionchanged:: 1.5.0 + New field `more_info` added to output + +.. versionchanged:: 1.7.3 + New field `CWE` added to output + +""" +import datetime +import logging +import sys + +from bandit.core import constants +from bandit.core import docs_utils +from bandit.core import test_properties +from bandit.formatters import utils + +LOG = logging.getLogger(__name__) + + +def get_verbose_details(manager): + bits = [] + bits.append(f"Files in scope ({len(manager.files_list)}):") + tpl = "\t%s (score: {SEVERITY: %i, CONFIDENCE: %i})" + bits.extend( + [ + tpl % (item, sum(score["SEVERITY"]), sum(score["CONFIDENCE"])) + for (item, score) in zip(manager.files_list, manager.scores) + ] + ) + bits.append(f"Files excluded ({len(manager.excluded_files)}):") + bits.extend([f"\t{fname}" for fname in manager.excluded_files]) + return "\n".join([bit for bit in bits]) + + +def get_metrics(manager): + bits = [] + bits.append("\nRun metrics:") + for criteria, _ in constants.CRITERIA: + bits.append(f"\tTotal issues (by {criteria.lower()}):") + for rank in constants.RANKING: + bits.append( + "\t\t%s: %s" + % ( + rank.capitalize(), + manager.metrics.data["_totals"][f"{criteria}.{rank}"], + ) + ) + return "\n".join([bit for bit in bits]) + + +def _output_issue_str( + issue, indent, show_lineno=True, show_code=True, lines=-1 +): + # returns a list of lines that should be added to the existing lines list + bits = [] + bits.append( + f"{indent}>> Issue: [{issue.test_id}:{issue.test}] {issue.text}" + ) + + bits.append( + "%s Severity: %s Confidence: %s" + % ( + indent, + issue.severity.capitalize(), + issue.confidence.capitalize(), + ) + ) + + bits.append(f"{indent} CWE: {str(issue.cwe)}") + + bits.append(f"{indent} More Info: {docs_utils.get_url(issue.test_id)}") + + bits.append( + "%s Location: %s:%s:%s" + % ( + indent, + issue.fname, + issue.lineno if show_lineno else "", + issue.col_offset if show_lineno else "", + ) + ) + + if show_code: + bits.extend( + [indent + line for line in issue.get_code(lines, True).split("\n")] + ) + + return "\n".join([bit for bit in bits]) + + +def get_results(manager, sev_level, conf_level, lines): + bits = [] + issues = manager.get_issue_list(sev_level, conf_level) + baseline = not isinstance(issues, list) + candidate_indent = " " * 10 + + if not len(issues): + return "\tNo issues identified." + + for issue in issues: + # if not a baseline or only one candidate we know the issue + if not baseline or len(issues[issue]) == 1: + bits.append(_output_issue_str(issue, "", lines=lines)) + + # otherwise show the finding and the candidates + else: + bits.append( + _output_issue_str( + issue, "", show_lineno=False, show_code=False + ) + ) + + bits.append("\n-- Candidate Issues --") + for candidate in issues[issue]: + bits.append( + _output_issue_str(candidate, candidate_indent, lines=lines) + ) + bits.append("\n") + bits.append("-" * 50) + return "\n".join([bit for bit in bits]) + + +@test_properties.accepts_baseline +def report(manager, fileobj, sev_level, conf_level, lines=-1): + """Prints discovered issues in the text format + + :param manager: the bandit manager object + :param fileobj: The output file object, which may be sys.stdout + :param sev_level: Filtering severity level + :param conf_level: Filtering confidence level + :param lines: Number of lines to report, -1 for all + """ + + bits = [] + + if not manager.quiet or manager.results_count(sev_level, conf_level): + bits.append( + f"Run started:{datetime.datetime.now(datetime.timezone.utc)}" + ) + + if manager.verbose: + bits.append(get_verbose_details(manager)) + + bits.append("\nTest results:") + bits.append(get_results(manager, sev_level, conf_level, lines)) + bits.append("\nCode scanned:") + bits.append( + "\tTotal lines of code: %i" + % (manager.metrics.data["_totals"]["loc"]) + ) + + bits.append( + "\tTotal lines skipped (#nosec): %i" + % (manager.metrics.data["_totals"]["nosec"]) + ) + bits.append( + "\tTotal potential issues skipped due to specifically being " + "disabled (e.g., #nosec BXXX): %i" + % (manager.metrics.data["_totals"]["skipped_tests"]) + ) + + skipped = manager.get_skipped() + bits.append(get_metrics(manager)) + bits.append(f"Files skipped ({len(skipped)}):") + bits.extend(["\t%s (%s)" % skip for skip in skipped]) + result = "\n".join([bit for bit in bits]) + "\n" + + with fileobj: + wrapped_file = utils.wrap_file_object(fileobj) + wrapped_file.write(result) + + if fileobj.name != sys.stdout.name: + LOG.info("Text output written to file: %s", fileobj.name) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/formatters/utils.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/formatters/utils.py new file mode 100644 index 000000000..ebe9f921a --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/formatters/utils.py @@ -0,0 +1,14 @@ +# Copyright (c) 2016 Rackspace, Inc. +# +# SPDX-License-Identifier: Apache-2.0 +"""Utility functions for formatting plugins for Bandit.""" +import io + + +def wrap_file_object(fileobj): + """If the fileobj passed in cannot handle text, use TextIOWrapper + to handle the conversion. + """ + if isinstance(fileobj, io.TextIOBase): + return fileobj + return io.TextIOWrapper(fileobj) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/formatters/xml.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/formatters/xml.py new file mode 100644 index 000000000..d2b2067ff --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/formatters/xml.py @@ -0,0 +1,97 @@ +# +# SPDX-License-Identifier: Apache-2.0 +r""" +============= +XML Formatter +============= + +This formatter outputs the issues as XML. + +:Example: + +.. code-block:: xml + + + Test ID: B301 + Severity: MEDIUM Confidence: HIGH + CWE: CWE-20 (https://cwe.mitre.org/data/definitions/20.html) Use of unsafe + yaml load. + Allows instantiation of arbitrary objects. Consider yaml.safe_load(). + + Location examples/yaml_load.py:5 + +.. versionadded:: 0.12.0 + +.. versionchanged:: 1.5.0 + New field `more_info` added to output + +.. versionchanged:: 1.7.3 + New field `CWE` added to output + +""" +import logging +import sys +from xml.etree import ElementTree as ET # nosec: B405 + +from bandit.core import docs_utils + +LOG = logging.getLogger(__name__) + + +def report(manager, fileobj, sev_level, conf_level, lines=-1): + """Prints issues in XML format + + :param manager: the bandit manager object + :param fileobj: The output file object, which may be sys.stdout + :param sev_level: Filtering severity level + :param conf_level: Filtering confidence level + :param lines: Number of lines to report, -1 for all + """ + + issues = manager.get_issue_list(sev_level=sev_level, conf_level=conf_level) + root = ET.Element("testsuite", name="bandit", tests=str(len(issues))) + + for issue in issues: + test = issue.test + testcase = ET.SubElement( + root, "testcase", classname=issue.fname, name=test + ) + + text = ( + "Test ID: %s Severity: %s Confidence: %s\nCWE: %s\n%s\n" + "Location %s:%s" + ) + text %= ( + issue.test_id, + issue.severity, + issue.confidence, + issue.cwe, + issue.text, + issue.fname, + issue.lineno, + ) + ET.SubElement( + testcase, + "error", + more_info=docs_utils.get_url(issue.test_id), + type=issue.severity, + message=issue.text, + ).text = text + + tree = ET.ElementTree(root) + + if fileobj.name == sys.stdout.name: + fileobj = sys.stdout.buffer + elif fileobj.mode == "w": + fileobj.close() + fileobj = open(fileobj.name, "wb") + + with fileobj: + tree.write(fileobj, encoding="utf-8", xml_declaration=True) + + if fileobj.name != sys.stdout.name: + LOG.info("XML output written to file: %s", fileobj.name) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/formatters/yaml.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/formatters/yaml.py new file mode 100644 index 000000000..421109078 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/formatters/yaml.py @@ -0,0 +1,126 @@ +# Copyright (c) 2017 VMware, Inc. +# +# SPDX-License-Identifier: Apache-2.0 +r""" +============== +YAML Formatter +============== + +This formatter outputs the issues in a yaml format. + +:Example: + +.. code-block:: none + + errors: [] + generated_at: '2017-03-09T22:29:30Z' + metrics: + _totals: + CONFIDENCE.HIGH: 1 + CONFIDENCE.LOW: 0 + CONFIDENCE.MEDIUM: 0 + CONFIDENCE.UNDEFINED: 0 + SEVERITY.HIGH: 0 + SEVERITY.LOW: 0 + SEVERITY.MEDIUM: 1 + SEVERITY.UNDEFINED: 0 + loc: 9 + nosec: 0 + examples/yaml_load.py: + CONFIDENCE.HIGH: 1 + CONFIDENCE.LOW: 0 + CONFIDENCE.MEDIUM: 0 + CONFIDENCE.UNDEFINED: 0 + SEVERITY.HIGH: 0 + SEVERITY.LOW: 0 + SEVERITY.MEDIUM: 1 + SEVERITY.UNDEFINED: 0 + loc: 9 + nosec: 0 + results: + - code: '5 ystr = yaml.dump({''a'' : 1, ''b'' : 2, ''c'' : 3})\n + 6 y = yaml.load(ystr)\n7 yaml.dump(y)\n' + filename: examples/yaml_load.py + issue_confidence: HIGH + issue_severity: MEDIUM + issue_text: Use of unsafe yaml load. Allows instantiation of arbitrary + objects. + Consider yaml.safe_load(). + line_number: 6 + line_range: + - 6 + more_info: https://bandit.readthedocs.io/en/latest/ + test_id: B506 + test_name: yaml_load + +.. versionadded:: 1.5.0 + +.. versionchanged:: 1.7.3 + New field `CWE` added to output + +""" +# Necessary for this formatter to work when imported on Python 2. Importing +# the standard library's yaml module conflicts with the name of this module. +import datetime +import logging +import operator +import sys + +import yaml + +from bandit.core import docs_utils + +LOG = logging.getLogger(__name__) + + +def report(manager, fileobj, sev_level, conf_level, lines=-1): + """Prints issues in YAML format + + :param manager: the bandit manager object + :param fileobj: The output file object, which may be sys.stdout + :param sev_level: Filtering severity level + :param conf_level: Filtering confidence level + :param lines: Number of lines to report, -1 for all + """ + + machine_output = {"results": [], "errors": []} + for fname, reason in manager.get_skipped(): + machine_output["errors"].append({"filename": fname, "reason": reason}) + + results = manager.get_issue_list( + sev_level=sev_level, conf_level=conf_level + ) + + collector = [r.as_dict(max_lines=lines) for r in results] + for elem in collector: + elem["more_info"] = docs_utils.get_url(elem["test_id"]) + + itemgetter = operator.itemgetter + if manager.agg_type == "vuln": + machine_output["results"] = sorted( + collector, key=itemgetter("test_name") + ) + else: + machine_output["results"] = sorted( + collector, key=itemgetter("filename") + ) + + machine_output["metrics"] = manager.metrics.data + + for result in machine_output["results"]: + if "code" in result: + code = result["code"].replace("\n", "\\n") + result["code"] = code + + # timezone agnostic format + TS_FORMAT = "%Y-%m-%dT%H:%M:%SZ" + + time_string = datetime.datetime.now(datetime.timezone.utc).strftime( + TS_FORMAT + ) + machine_output["generated_at"] = time_string + + yaml.safe_dump(machine_output, fileobj, default_flow_style=False) + + if fileobj.name != sys.stdout.name: + LOG.info("YAML output written to file: %s", fileobj.name) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/plugins/__init__.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/plugins/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/plugins/app_debug.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/plugins/app_debug.py new file mode 100644 index 000000000..1c41680ed --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/plugins/app_debug.py @@ -0,0 +1,63 @@ +# +# Copyright 2015 Hewlett-Packard Development Company, L.P. +# +# SPDX-License-Identifier: Apache-2.0 +r""" +====================================================== +B201: Test for use of flask app with debug set to true +====================================================== + +Running Flask applications in debug mode results in the Werkzeug debugger +being enabled. This includes a feature that allows arbitrary code execution. +Documentation for both Flask [1]_ and Werkzeug [2]_ strongly suggests that +debug mode should never be enabled on production systems. + +Operating a production server with debug mode enabled was the probable cause +of the Patreon breach in 2015 [3]_. + +:Example: + +.. code-block:: none + + >> Issue: A Flask app appears to be run with debug=False, which exposes + the Werkzeug debugger and allows the execution of arbitrary code. + Severity: High Confidence: High + CWE: CWE-94 (https://cwe.mitre.org/data/definitions/94.html) + Location: examples/flask_debug.py:10 + 9 #bad + 10 app.run(debug=False) + 11 + +.. seealso:: + + .. [1] https://flask.palletsprojects.com/en/1.1.x/quickstart/#debug-mode + .. [2] https://werkzeug.palletsprojects.com/en/1.0.x/debug/ + .. [3] https://labs.detectify.com/2015/10/02/how-patreon-got-hacked-publicly-exposed-werkzeug-debugger/ + .. https://cwe.mitre.org/data/definitions/94.html + +.. versionadded:: 0.15.0 + +.. versionchanged:: 1.7.3 + CWE information added + +""" # noqa: E501 +import bandit +from bandit.core import issue +from bandit.core import test_properties as test + + +@test.test_id("B201") +@test.checks("Call") +def flask_debug_true(context): + if context.is_module_imported_like("flask"): + if context.call_function_name_qual.endswith(".run"): + if context.check_call_arg_value("debug", "True"): + return bandit.Issue( + severity=bandit.HIGH, + confidence=bandit.MEDIUM, + cwe=issue.Cwe.CODE_INJECTION, + text="A Flask app appears to be run with debug=False, " + "which exposes the Werkzeug debugger and allows " + "the execution of arbitrary code.", + lineno=context.get_lineno_for_call_arg("debug"), + ) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/plugins/asserts.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/plugins/asserts.py new file mode 100644 index 000000000..b32007c65 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/plugins/asserts.py @@ -0,0 +1,83 @@ +# +# Copyright 2014 Hewlett-Packard Development Company, L.P. +# +# SPDX-License-Identifier: Apache-2.0 +r""" +============================ +B101: Test for use of assert +============================ + +This plugin test checks for the use of the Python ``assert`` keyword. It was +discovered that some projects used assert to enforce interface constraints. +However, assert is removed with compiling to optimised byte code (`python -O` +producing \*.opt-1.pyc files). This caused various protections to be removed. +Consider raising a semantically meaningful error or ``AssertionError`` instead. + +Please see +https://docs.python.org/3/reference/simple_stmts.html#the-assert-statement for +more info on ``assert``. + +**Config Options:** + +You can configure files that skip this check. This is often useful when you +use assert statements in test cases. + +.. code-block:: yaml + + assert_used: + skips: ['*_test.py', '*test_*.py'] + +:Example: + +.. code-block:: none + + >> Issue: Use of assert detected. The enclosed code will be removed when + compiling to optimised byte code. + Severity: Low Confidence: High + CWE: CWE-703 (https://cwe.mitre.org/data/definitions/703.html) + Location: ./examples/assert.py:1 + 1 assert logged_in + 2 display_assets() + +.. seealso:: + + - https://bugs.launchpad.net/juniperopenstack/+bug/1456193 + - https://bugs.launchpad.net/heat/+bug/1397883 + - https://docs.python.org/3/reference/simple_stmts.html#the-assert-statement + - https://cwe.mitre.org/data/definitions/703.html + +.. versionadded:: 0.11.0 + +.. versionchanged:: 1.7.3 + CWE information added + +""" +import fnmatch + +import bandit +from bandit.core import issue +from bandit.core import test_properties as test + + +def gen_config(name): + if name == "assert_used": + return {"skips": []} + + +@test.takes_config +@test.test_id("B101") +@test.checks("Assert") +def assert_used(context, config): + for skip in config.get("skips", []): + if fnmatch.fnmatch(context.filename, skip): + return None + + return bandit.Issue( + severity=bandit.LOW, + confidence=bandit.HIGH, + cwe=issue.Cwe.IMPROPER_CHECK_OF_EXCEPT_COND, + text=( + "Use of assert detected. The enclosed code " + "will be removed when compiling to optimised byte code." + ), + ) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/plugins/crypto_request_no_cert_validation.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/plugins/crypto_request_no_cert_validation.py new file mode 100644 index 000000000..11791ed1e --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/plugins/crypto_request_no_cert_validation.py @@ -0,0 +1,75 @@ +# +# Copyright 2014 Hewlett-Packard Development Company, L.P. +# +# SPDX-License-Identifier: Apache-2.0 +r""" +============================================= +B501: Test for missing certificate validation +============================================= + +Encryption in general is typically critical to the security of many +applications. Using TLS can greatly increase security by guaranteeing the +identity of the party you are communicating with. This is accomplished by one +or both parties presenting trusted certificates during the connection +initialization phase of TLS. + +When HTTPS request methods are used, certificates are validated automatically +which is the desired behavior. If certificate validation is explicitly turned +off Bandit will return a HIGH severity error. + + +:Example: + +.. code-block:: none + + >> Issue: [request_with_no_cert_validation] Call to requests with + verify=False disabling SSL certificate checks, security issue. + Severity: High Confidence: High + CWE: CWE-295 (https://cwe.mitre.org/data/definitions/295.html) + Location: examples/requests-ssl-verify-disabled.py:4 + 3 requests.get('https://gmail.com', verify=True) + 4 requests.get('https://gmail.com', verify=False) + 5 requests.post('https://gmail.com', verify=True) + +.. seealso:: + + - https://security.openstack.org/guidelines/dg_move-data-securely.html + - https://security.openstack.org/guidelines/dg_validate-certificates.html + - https://cwe.mitre.org/data/definitions/295.html + +.. versionadded:: 0.9.0 + +.. versionchanged:: 1.7.3 + CWE information added + +.. versionchanged:: 1.7.5 + Added check for httpx module + +""" +import bandit +from bandit.core import issue +from bandit.core import test_properties as test + + +@test.checks("Call") +@test.test_id("B501") +def request_with_no_cert_validation(context): + HTTP_VERBS = {"get", "options", "head", "post", "put", "patch", "delete"} + HTTPX_ATTRS = {"request", "stream", "Client", "AsyncClient"} | HTTP_VERBS + qualname = context.call_function_name_qual.split(".")[0] + + if ( + qualname == "requests" + and context.call_function_name in HTTP_VERBS + or qualname == "httpx" + and context.call_function_name in HTTPX_ATTRS + ): + if context.check_call_arg_value("verify", "False"): + return bandit.Issue( + severity=bandit.HIGH, + confidence=bandit.HIGH, + cwe=issue.Cwe.IMPROPER_CERT_VALIDATION, + text=f"Call to {qualname} with verify=False disabling SSL " + "certificate checks, security issue.", + lineno=context.get_lineno_for_call_arg("verify"), + ) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/plugins/django_sql_injection.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/plugins/django_sql_injection.py new file mode 100644 index 000000000..d27ba7d1d --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/plugins/django_sql_injection.py @@ -0,0 +1,155 @@ +# +# Copyright (C) 2018 [Victor Torre](https://github.com/ehooo) +# +# SPDX-License-Identifier: Apache-2.0 +import ast + +import bandit +from bandit.core import issue +from bandit.core import test_properties as test + + +def keywords2dict(keywords): + kwargs = {} + for node in keywords: + if isinstance(node, ast.keyword): + kwargs[node.arg] = node.value + return kwargs + + +@test.checks("Call") +@test.test_id("B610") +def django_extra_used(context): + """**B610: Potential SQL injection on extra function** + + :Example: + + .. code-block:: none + + >> Issue: [B610:django_extra_used] Use of extra potential SQL attack vector. + Severity: Medium Confidence: Medium + CWE: CWE-89 (https://cwe.mitre.org/data/definitions/89.html) + Location: examples/django_sql_injection_extra.py:29:0 + More Info: https://bandit.readthedocs.io/en/latest/plugins/b610_django_extra_used.html + 28 tables_str = 'django_content_type" WHERE "auth_user"."username"="admin' + 29 User.objects.all().extra(tables=[tables_str]).distinct() + + .. seealso:: + + - https://docs.djangoproject.com/en/dev/topics/security/\ +#sql-injection-protection + - https://cwe.mitre.org/data/definitions/89.html + + .. versionadded:: 1.5.0 + + .. versionchanged:: 1.7.3 + CWE information added + + """ # noqa: E501 + description = "Use of extra potential SQL attack vector." + if context.call_function_name == "extra": + kwargs = keywords2dict(context.node.keywords) + args = context.node.args + if args: + if len(args) >= 1: + kwargs["select"] = args[0] + if len(args) >= 2: + kwargs["where"] = args[1] + if len(args) >= 3: + kwargs["params"] = args[2] + if len(args) >= 4: + kwargs["tables"] = args[3] + if len(args) >= 5: + kwargs["order_by"] = args[4] + if len(args) >= 6: + kwargs["select_params"] = args[5] + insecure = False + for key in ["where", "tables"]: + if key in kwargs: + if isinstance(kwargs[key], ast.List): + for val in kwargs[key].elts: + if not ( + isinstance(val, ast.Constant) + and isinstance(val.value, str) + ): + insecure = True + break + else: + insecure = True + break + if not insecure and "select" in kwargs: + if isinstance(kwargs["select"], ast.Dict): + for k in kwargs["select"].keys: + if not ( + isinstance(k, ast.Constant) + and isinstance(k.value, str) + ): + insecure = True + break + if not insecure: + for v in kwargs["select"].values: + if not ( + isinstance(v, ast.Constant) + and isinstance(v.value, str) + ): + insecure = True + break + else: + insecure = True + + if insecure: + return bandit.Issue( + severity=bandit.MEDIUM, + confidence=bandit.MEDIUM, + cwe=issue.Cwe.SQL_INJECTION, + text=description, + ) + + +@test.checks("Call") +@test.test_id("B611") +def django_rawsql_used(context): + """**B611: Potential SQL injection on RawSQL function** + + :Example: + + .. code-block:: none + + >> Issue: [B611:django_rawsql_used] Use of RawSQL potential SQL attack vector. + Severity: Medium Confidence: Medium + CWE: CWE-89 (https://cwe.mitre.org/data/definitions/89.html) + Location: examples/django_sql_injection_raw.py:11:26 + More Info: https://bandit.readthedocs.io/en/latest/plugins/b611_django_rawsql_used.html + 10 ' WHERE "username"="admin" OR 1=%s --' + 11 User.objects.annotate(val=RawSQL(raw, [0])) + + .. seealso:: + + - https://docs.djangoproject.com/en/dev/topics/security/\ +#sql-injection-protection + - https://cwe.mitre.org/data/definitions/89.html + + .. versionadded:: 1.5.0 + + .. versionchanged:: 1.7.3 + CWE information added + + """ # noqa: E501 + description = "Use of RawSQL potential SQL attack vector." + if context.is_module_imported_like("django.db.models"): + if context.call_function_name == "RawSQL": + if context.node.args: + sql = context.node.args[0] + else: + kwargs = keywords2dict(context.node.keywords) + sql = kwargs["sql"] + + if not ( + isinstance(sql, ast.Constant) and isinstance(sql.value, str) + ): + return bandit.Issue( + severity=bandit.MEDIUM, + confidence=bandit.MEDIUM, + cwe=issue.Cwe.SQL_INJECTION, + text=description, + ) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/plugins/django_xss.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/plugins/django_xss.py new file mode 100644 index 000000000..1a0958a80 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/plugins/django_xss.py @@ -0,0 +1,287 @@ +# +# Copyright 2018 Victor Torre +# +# SPDX-License-Identifier: Apache-2.0 +import ast + +import bandit +from bandit.core import issue +from bandit.core import test_properties as test + + +class DeepAssignation: + def __init__(self, var_name, ignore_nodes=None): + self.var_name = var_name + self.ignore_nodes = ignore_nodes + + def is_assigned_in(self, items): + assigned = [] + for ast_inst in items: + new_assigned = self.is_assigned(ast_inst) + if new_assigned: + if isinstance(new_assigned, (list, tuple)): + assigned.extend(new_assigned) + else: + assigned.append(new_assigned) + return assigned + + def is_assigned(self, node): + assigned = False + if self.ignore_nodes: + if isinstance(self.ignore_nodes, (list, tuple, object)): + if isinstance(node, self.ignore_nodes): + return assigned + + if isinstance(node, ast.Expr): + assigned = self.is_assigned(node.value) + elif isinstance(node, ast.FunctionDef): + for name in node.args.args: + if isinstance(name, ast.Name): + if name.id == self.var_name.id: + # If is param the assignations are not affected + return assigned + assigned = self.is_assigned_in(node.body) + elif isinstance(node, ast.With): + for withitem in node.items: + var_id = getattr(withitem.optional_vars, "id", None) + if var_id == self.var_name.id: + assigned = node + else: + assigned = self.is_assigned_in(node.body) + elif isinstance(node, ast.Try): + assigned = [] + assigned.extend(self.is_assigned_in(node.body)) + assigned.extend(self.is_assigned_in(node.handlers)) + assigned.extend(self.is_assigned_in(node.orelse)) + assigned.extend(self.is_assigned_in(node.finalbody)) + elif isinstance(node, ast.ExceptHandler): + assigned = [] + assigned.extend(self.is_assigned_in(node.body)) + elif isinstance(node, (ast.If, ast.For, ast.While)): + assigned = [] + assigned.extend(self.is_assigned_in(node.body)) + assigned.extend(self.is_assigned_in(node.orelse)) + elif isinstance(node, ast.AugAssign): + if isinstance(node.target, ast.Name): + if node.target.id == self.var_name.id: + assigned = node.value + elif isinstance(node, ast.Assign) and node.targets: + target = node.targets[0] + if isinstance(target, ast.Name): + if target.id == self.var_name.id: + assigned = node.value + elif isinstance(target, ast.Tuple) and isinstance( + node.value, ast.Tuple + ): + pos = 0 + for name in target.elts: + if name.id == self.var_name.id: + assigned = node.value.elts[pos] + break + pos += 1 + return assigned + + +def evaluate_var(xss_var, parent, until, ignore_nodes=None): + secure = False + if isinstance(xss_var, ast.Name): + if isinstance(parent, ast.FunctionDef): + for name in parent.args.args: + if name.arg == xss_var.id: + return False # Params are not secure + + analyser = DeepAssignation(xss_var, ignore_nodes) + for node in parent.body: + if node.lineno >= until: + break + to = analyser.is_assigned(node) + if to: + if isinstance(to, ast.Constant) and isinstance(to.value, str): + secure = True + elif isinstance(to, ast.Name): + secure = evaluate_var(to, parent, to.lineno, ignore_nodes) + elif isinstance(to, ast.Call): + secure = evaluate_call(to, parent, ignore_nodes) + elif isinstance(to, (list, tuple)): + num_secure = 0 + for some_to in to: + if isinstance(some_to, ast.Constant) and isinstance( + some_to.value, str + ): + num_secure += 1 + elif isinstance(some_to, ast.Name): + if evaluate_var( + some_to, parent, node.lineno, ignore_nodes + ): + num_secure += 1 + else: + break + else: + break + if num_secure == len(to): + secure = True + else: + secure = False + break + else: + secure = False + break + return secure + + +def evaluate_call(call, parent, ignore_nodes=None): + secure = False + evaluate = False + if isinstance(call, ast.Call) and isinstance(call.func, ast.Attribute): + if ( + isinstance(call.func.value, ast.Constant) + and call.func.attr == "format" + ): + evaluate = True + if call.keywords: + evaluate = False # TODO(??) get support for this + + if evaluate: + args = list(call.args) + num_secure = 0 + for arg in args: + if isinstance(arg, ast.Constant) and isinstance(arg.value, str): + num_secure += 1 + elif isinstance(arg, ast.Name): + if evaluate_var(arg, parent, call.lineno, ignore_nodes): + num_secure += 1 + else: + break + elif isinstance(arg, ast.Call): + if evaluate_call(arg, parent, ignore_nodes): + num_secure += 1 + else: + break + elif isinstance(arg, ast.Starred) and isinstance( + arg.value, (ast.List, ast.Tuple) + ): + args.extend(arg.value.elts) + num_secure += 1 + else: + break + secure = num_secure == len(args) + + return secure + + +def transform2call(var): + if isinstance(var, ast.BinOp): + is_mod = isinstance(var.op, ast.Mod) + is_left_str = isinstance(var.left, ast.Constant) and isinstance( + var.left.value, str + ) + if is_mod and is_left_str: + new_call = ast.Call() + new_call.args = [] + new_call.args = [] + new_call.keywords = None + new_call.lineno = var.lineno + new_call.func = ast.Attribute() + new_call.func.value = var.left + new_call.func.attr = "format" + if isinstance(var.right, ast.Tuple): + new_call.args = var.right.elts + else: + new_call.args = [var.right] + return new_call + + +def check_risk(node): + description = "Potential XSS on mark_safe function." + xss_var = node.args[0] + + secure = False + + if isinstance(xss_var, ast.Name): + # Check if the var are secure + parent = node._bandit_parent + while not isinstance(parent, (ast.Module, ast.FunctionDef)): + parent = parent._bandit_parent + + is_param = False + if isinstance(parent, ast.FunctionDef): + for name in parent.args.args: + if name.arg == xss_var.id: + is_param = True + break + + if not is_param: + secure = evaluate_var(xss_var, parent, node.lineno) + elif isinstance(xss_var, ast.Call): + parent = node._bandit_parent + while not isinstance(parent, (ast.Module, ast.FunctionDef)): + parent = parent._bandit_parent + secure = evaluate_call(xss_var, parent) + elif isinstance(xss_var, ast.BinOp): + is_mod = isinstance(xss_var.op, ast.Mod) + is_left_str = isinstance(xss_var.left, ast.Constant) and isinstance( + xss_var.left.value, str + ) + if is_mod and is_left_str: + parent = node._bandit_parent + while not isinstance(parent, (ast.Module, ast.FunctionDef)): + parent = parent._bandit_parent + new_call = transform2call(xss_var) + secure = evaluate_call(new_call, parent) + + if not secure: + return bandit.Issue( + severity=bandit.MEDIUM, + confidence=bandit.HIGH, + cwe=issue.Cwe.BASIC_XSS, + text=description, + ) + + +@test.checks("Call") +@test.test_id("B703") +def django_mark_safe(context): + """**B703: Potential XSS on mark_safe function** + + :Example: + + .. code-block:: none + + >> Issue: [B703:django_mark_safe] Potential XSS on mark_safe function. + Severity: Medium Confidence: High + CWE: CWE-80 (https://cwe.mitre.org/data/definitions/80.html) + Location: examples/mark_safe_insecure.py:159:4 + More Info: https://bandit.readthedocs.io/en/latest/plugins/b703_django_mark_safe.html + 158 str_arg = 'could be insecure' + 159 safestring.mark_safe(str_arg) + + .. seealso:: + + - https://docs.djangoproject.com/en/dev/topics/security/\ +#cross-site-scripting-xss-protection + - https://docs.djangoproject.com/en/dev/ref/utils/\ +#module-django.utils.safestring + - https://docs.djangoproject.com/en/dev/ref/utils/\ +#django.utils.html.format_html + - https://cwe.mitre.org/data/definitions/80.html + + .. versionadded:: 1.5.0 + + .. versionchanged:: 1.7.3 + CWE information added + + """ # noqa: E501 + if context.is_module_imported_like("django.utils.safestring"): + affected_functions = [ + "mark_safe", + "SafeText", + "SafeUnicode", + "SafeString", + "SafeBytes", + ] + if context.call_function_name in affected_functions: + xss = context.node.args[0] + if not ( + isinstance(xss, ast.Constant) and isinstance(xss.value, str) + ): + return check_risk(context.node) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/plugins/exec.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/plugins/exec.py new file mode 100644 index 000000000..3e4624780 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/plugins/exec.py @@ -0,0 +1,55 @@ +# +# Copyright 2014 Hewlett-Packard Development Company, L.P. +# +# SPDX-License-Identifier: Apache-2.0 +r""" +============================== +B102: Test for the use of exec +============================== + +This plugin test checks for the use of Python's `exec` method or keyword. The +Python docs succinctly describe why the use of `exec` is risky. + +:Example: + +.. code-block:: none + + >> Issue: Use of exec detected. + Severity: Medium Confidence: High + CWE: CWE-78 (https://cwe.mitre.org/data/definitions/78.html) + Location: ./examples/exec.py:2 + 1 exec("do evil") + + +.. seealso:: + + - https://docs.python.org/3/library/functions.html#exec + - https://www.python.org/dev/peps/pep-0551/#background + - https://www.python.org/dev/peps/pep-0578/#suggested-audit-hook-locations + - https://cwe.mitre.org/data/definitions/78.html + +.. versionadded:: 0.9.0 + +.. versionchanged:: 1.7.3 + CWE information added + +""" +import bandit +from bandit.core import issue +from bandit.core import test_properties as test + + +def exec_issue(): + return bandit.Issue( + severity=bandit.MEDIUM, + confidence=bandit.HIGH, + cwe=issue.Cwe.OS_COMMAND_INJECTION, + text="Use of exec detected.", + ) + + +@test.checks("Call") +@test.test_id("B102") +def exec_used(context): + if context.call_function_name_qual == "exec": + return exec_issue() diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/plugins/general_bad_file_permissions.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/plugins/general_bad_file_permissions.py new file mode 100644 index 000000000..7d3fce4df --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/plugins/general_bad_file_permissions.py @@ -0,0 +1,99 @@ +# +# Copyright 2014 Hewlett-Packard Development Company, L.P. +# +# SPDX-License-Identifier: Apache-2.0 +r""" +================================================== +B103: Test for setting permissive file permissions +================================================== + +POSIX based operating systems utilize a permissions model to protect access to +parts of the file system. This model supports three roles "owner", "group" +and "world" each role may have a combination of "read", "write" or "execute" +flags sets. Python provides ``chmod`` to manipulate POSIX style permissions. + +This plugin test looks for the use of ``chmod`` and will alert when it is used +to set particularly permissive control flags. A MEDIUM warning is generated if +a file is set to group write or executable and a HIGH warning is reported if a +file is set world write or executable. Warnings are given with HIGH confidence. + +:Example: + +.. code-block:: none + + >> Issue: Probable insecure usage of temp file/directory. + Severity: Medium Confidence: Medium + CWE: CWE-732 (https://cwe.mitre.org/data/definitions/732.html) + Location: ./examples/os-chmod.py:15 + 14 os.chmod('/etc/hosts', 0o777) + 15 os.chmod('/tmp/oh_hai', 0x1ff) + 16 os.chmod('/etc/passwd', stat.S_IRWXU) + + >> Issue: Chmod setting a permissive mask 0777 on file (key_file). + Severity: High Confidence: High + CWE: CWE-732 (https://cwe.mitre.org/data/definitions/732.html) + Location: ./examples/os-chmod.py:17 + 16 os.chmod('/etc/passwd', stat.S_IRWXU) + 17 os.chmod(key_file, 0o777) + 18 + +.. seealso:: + + - https://security.openstack.org/guidelines/dg_apply-restrictive-file-permissions.html + - https://en.wikipedia.org/wiki/File_system_permissions + - https://security.openstack.org + - https://cwe.mitre.org/data/definitions/732.html + +.. versionadded:: 0.9.0 + +.. versionchanged:: 1.7.3 + CWE information added + +.. versionchanged:: 1.7.5 + Added checks for S_IWGRP and S_IXOTH + +""" # noqa: E501 +import stat + +import bandit +from bandit.core import issue +from bandit.core import test_properties as test + + +def _stat_is_dangerous(mode): + return ( + mode & stat.S_IWOTH + or mode & stat.S_IWGRP + or mode & stat.S_IXGRP + or mode & stat.S_IXOTH + ) + + +@test.checks("Call") +@test.test_id("B103") +def set_bad_file_permissions(context): + if "chmod" in context.call_function_name: + if context.call_args_count == 2: + mode = context.get_call_arg_at_position(1) + + if ( + mode is not None + and isinstance(mode, int) + and _stat_is_dangerous(mode) + ): + # world writable is an HIGH, group executable is a MEDIUM + if mode & stat.S_IWOTH: + sev_level = bandit.HIGH + else: + sev_level = bandit.MEDIUM + + filename = context.get_call_arg_at_position(0) + if filename is None: + filename = "NOT PARSED" + return bandit.Issue( + severity=sev_level, + confidence=bandit.HIGH, + cwe=issue.Cwe.INCORRECT_PERMISSION_ASSIGNMENT, + text="Chmod setting a permissive mask %s on file (%s)." + % (oct(mode), filename), + ) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/plugins/general_bind_all_interfaces.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/plugins/general_bind_all_interfaces.py new file mode 100644 index 000000000..58b840e86 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/plugins/general_bind_all_interfaces.py @@ -0,0 +1,52 @@ +# +# Copyright 2014 Hewlett-Packard Development Company, L.P. +# +# SPDX-License-Identifier: Apache-2.0 +r""" +======================================== +B104: Test for binding to all interfaces +======================================== + +Binding to all network interfaces can potentially open up a service to traffic +on unintended interfaces, that may not be properly documented or secured. This +plugin test looks for a string pattern "0.0.0.0" that may indicate a hardcoded +binding to all network interfaces. + +:Example: + +.. code-block:: none + + >> Issue: Possible binding to all interfaces. + Severity: Medium Confidence: Medium + CWE: CWE-605 (https://cwe.mitre.org/data/definitions/605.html) + Location: ./examples/binding.py:4 + 3 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + 4 s.bind(('0.0.0.0', 31137)) + 5 s.bind(('192.168.0.1', 8080)) + +.. seealso:: + + - https://nvd.nist.gov/vuln/detail/CVE-2018-1281 + - https://cwe.mitre.org/data/definitions/605.html + +.. versionadded:: 0.9.0 + +.. versionchanged:: 1.7.3 + CWE information added + +""" +import bandit +from bandit.core import issue +from bandit.core import test_properties as test + + +@test.checks("Str") +@test.test_id("B104") +def hardcoded_bind_all_interfaces(context): + if context.string_val == "0.0.0.0": # nosec: B104 + return bandit.Issue( + severity=bandit.MEDIUM, + confidence=bandit.MEDIUM, + cwe=issue.Cwe.MULTIPLE_BINDS, + text="Possible binding to all interfaces.", + ) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/plugins/general_hardcoded_password.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/plugins/general_hardcoded_password.py new file mode 100644 index 000000000..c83cf403c --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/plugins/general_hardcoded_password.py @@ -0,0 +1,282 @@ +# +# Copyright 2014 Hewlett-Packard Development Company, L.P. +# +# SPDX-License-Identifier: Apache-2.0 +import ast +import re + +import bandit +from bandit.core import issue +from bandit.core import test_properties as test + +RE_WORDS = "(pas+wo?r?d|pass(phrase)?|pwd|token|secrete?)" +RE_CANDIDATES = re.compile( + "(^{0}$|_{0}_|^{0}_|_{0}$)".format(RE_WORDS), re.IGNORECASE +) + + +def _report(value, lineno=None): + return bandit.Issue( + severity=bandit.LOW, + confidence=bandit.MEDIUM, + cwe=issue.Cwe.HARD_CODED_PASSWORD, + text=f"Possible hardcoded password: '{value}'", + lineno=lineno, + ) + + +@test.checks("Str") +@test.test_id("B105") +def hardcoded_password_string(context): + """**B105: Test for use of hard-coded password strings** + + The use of hard-coded passwords increases the possibility of password + guessing tremendously. This plugin test looks for all string literals and + checks the following conditions: + + - assigned to a variable that looks like a password + - assigned to a dict key that looks like a password + - assigned to a class attribute that looks like a password + - used in a comparison with a variable that looks like a password + + Variables are considered to look like a password if they have match any one + of: + + - "password" + - "pass" + - "passwd" + - "pwd" + - "secret" + - "token" + - "secrete" + + Note: this can be noisy and may generate false positives. + + **Config Options:** + + None + + :Example: + + .. code-block:: none + + >> Issue: Possible hardcoded password '(root)' + Severity: Low Confidence: Low + CWE: CWE-259 (https://cwe.mitre.org/data/definitions/259.html) + Location: ./examples/hardcoded-passwords.py:5 + 4 def someFunction2(password): + 5 if password == "root": + 6 print("OK, logged in") + + .. seealso:: + + - https://www.owasp.org/index.php/Use_of_hard-coded_password + - https://cwe.mitre.org/data/definitions/259.html + + .. versionadded:: 0.9.0 + + .. versionchanged:: 1.7.3 + CWE information added + + """ + node = context.node + if isinstance(node._bandit_parent, ast.Assign): + # looks for "candidate='some_string'" + for targ in node._bandit_parent.targets: + if isinstance(targ, ast.Name) and RE_CANDIDATES.search(targ.id): + return _report(node.value) + elif isinstance(targ, ast.Attribute) and RE_CANDIDATES.search( + targ.attr + ): + return _report(node.value) + + elif ( + isinstance(node._bandit_parent, ast.Dict) + and node in node._bandit_parent.keys + and RE_CANDIDATES.search(node.value) + ): + # looks for "{'candidate': 'some_string'}" + dict_node = node._bandit_parent + pos = dict_node.keys.index(node) + value_node = dict_node.values[pos] + if isinstance(value_node, ast.Constant): + return _report(value_node.value) + + elif isinstance( + node._bandit_parent, ast.Subscript + ) and RE_CANDIDATES.search(node.value): + # Py39+: looks for "dict[candidate]='some_string'" + # subscript -> index -> string + assign = node._bandit_parent._bandit_parent + if ( + isinstance(assign, ast.Assign) + and isinstance(assign.value, ast.Constant) + and isinstance(assign.value.value, str) + ): + return _report(assign.value.value) + + elif isinstance(node._bandit_parent, ast.Index) and RE_CANDIDATES.search( + node.value + ): + # looks for "dict[candidate]='some_string'" + # assign -> subscript -> index -> string + assign = node._bandit_parent._bandit_parent._bandit_parent + if ( + isinstance(assign, ast.Assign) + and isinstance(assign.value, ast.Constant) + and isinstance(assign.value.value, str) + ): + return _report(assign.value.value) + + elif isinstance(node._bandit_parent, ast.Compare): + # looks for "candidate == 'some_string'" + comp = node._bandit_parent + if isinstance(comp.left, ast.Name): + if RE_CANDIDATES.search(comp.left.id): + if isinstance( + comp.comparators[0], ast.Constant + ) and isinstance(comp.comparators[0].value, str): + return _report(comp.comparators[0].value) + elif isinstance(comp.left, ast.Attribute): + if RE_CANDIDATES.search(comp.left.attr): + if isinstance( + comp.comparators[0], ast.Constant + ) and isinstance(comp.comparators[0].value, str): + return _report(comp.comparators[0].value) + + +@test.checks("Call") +@test.test_id("B106") +def hardcoded_password_funcarg(context): + """**B106: Test for use of hard-coded password function arguments** + + The use of hard-coded passwords increases the possibility of password + guessing tremendously. This plugin test looks for all function calls being + passed a keyword argument that is a string literal. It checks that the + assigned local variable does not look like a password. + + Variables are considered to look like a password if they have match any one + of: + + - "password" + - "pass" + - "passwd" + - "pwd" + - "secret" + - "token" + - "secrete" + + Note: this can be noisy and may generate false positives. + + **Config Options:** + + None + + :Example: + + .. code-block:: none + + >> Issue: [B106:hardcoded_password_funcarg] Possible hardcoded + password: 'blerg' + Severity: Low Confidence: Medium + CWE: CWE-259 (https://cwe.mitre.org/data/definitions/259.html) + Location: ./examples/hardcoded-passwords.py:16 + 15 + 16 doLogin(password="blerg") + + .. seealso:: + + - https://www.owasp.org/index.php/Use_of_hard-coded_password + - https://cwe.mitre.org/data/definitions/259.html + + .. versionadded:: 0.9.0 + + .. versionchanged:: 1.7.3 + CWE information added + + """ + # looks for "function(candidate='some_string')" + for kw in context.node.keywords: + if ( + isinstance(kw.value, ast.Constant) + and isinstance(kw.value.value, str) + and RE_CANDIDATES.search(kw.arg) + ): + return _report(kw.value.value, lineno=kw.value.lineno) + + +@test.checks("FunctionDef") +@test.test_id("B107") +def hardcoded_password_default(context): + """**B107: Test for use of hard-coded password argument defaults** + + The use of hard-coded passwords increases the possibility of password + guessing tremendously. This plugin test looks for all function definitions + that specify a default string literal for some argument. It checks that + the argument does not look like a password. + + Variables are considered to look like a password if they have match any one + of: + + - "password" + - "pass" + - "passwd" + - "pwd" + - "secret" + - "token" + - "secrete" + + Note: this can be noisy and may generate false positives. We do not + report on None values which can be legitimately used as a default value, + when initializing a function or class. + + **Config Options:** + + None + + :Example: + + .. code-block:: none + + >> Issue: [B107:hardcoded_password_default] Possible hardcoded + password: 'Admin' + Severity: Low Confidence: Medium + CWE: CWE-259 (https://cwe.mitre.org/data/definitions/259.html) + Location: ./examples/hardcoded-passwords.py:1 + + 1 def someFunction(user, password="Admin"): + 2 print("Hi " + user) + + .. seealso:: + + - https://www.owasp.org/index.php/Use_of_hard-coded_password + - https://cwe.mitre.org/data/definitions/259.html + + .. versionadded:: 0.9.0 + + .. versionchanged:: 1.7.3 + CWE information added + + """ + # looks for "def function(candidate='some_string')" + + # this pads the list of default values with "None" if nothing is given + defs = [None] * ( + len(context.node.args.args) - len(context.node.args.defaults) + ) + defs.extend(context.node.args.defaults) + + # go through all (param, value)s and look for candidates + for key, val in zip(context.node.args.args, defs): + if isinstance(key, (ast.Name, ast.arg)): + # Skip if the default value is None + if val is None or ( + isinstance(val, ast.Constant) and val.value is None + ): + continue + if ( + isinstance(val, ast.Constant) + and isinstance(val.value, str) + and RE_CANDIDATES.search(key.arg) + ): + return _report(val.value) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/plugins/general_hardcoded_tmp.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/plugins/general_hardcoded_tmp.py new file mode 100644 index 000000000..ecf899527 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/plugins/general_hardcoded_tmp.py @@ -0,0 +1,79 @@ +# +# Copyright 2014 Hewlett-Packard Development Company, L.P. +# +# SPDX-License-Identifier: Apache-2.0 +r""" +=================================================== +B108: Test for insecure usage of tmp file/directory +=================================================== + +Safely creating a temporary file or directory means following a number of rules +(see the references for more details). This plugin test looks for strings +starting with (configurable) commonly used temporary paths, for example: + + - /tmp + - /var/tmp + - /dev/shm + +**Config Options:** + +This test plugin takes a similarly named config block, +`hardcoded_tmp_directory`. The config block provides a Python list, `tmp_dirs`, +that lists string fragments indicating possible temporary file paths. Any +string starting with one of these fragments will report a MEDIUM confidence +issue. + +.. code-block:: yaml + + hardcoded_tmp_directory: + tmp_dirs: ['/tmp', '/var/tmp', '/dev/shm'] + + +:Example: + +.. code-block: none + + >> Issue: Probable insecure usage of temp file/directory. + Severity: Medium Confidence: Medium + CWE: CWE-377 (https://cwe.mitre.org/data/definitions/377.html) + Location: ./examples/hardcoded-tmp.py:1 + 1 f = open('/tmp/abc', 'w') + 2 f.write('def') + +.. seealso:: + + - https://security.openstack.org/guidelines/dg_using-temporary-files-securely.html + - https://cwe.mitre.org/data/definitions/377.html + +.. versionadded:: 0.9.0 + +.. versionchanged:: 1.7.3 + CWE information added + +""" # noqa: E501 +import bandit +from bandit.core import issue +from bandit.core import test_properties as test + + +def gen_config(name): + if name == "hardcoded_tmp_directory": + return {"tmp_dirs": ["/tmp", "/var/tmp", "/dev/shm"]} # nosec: B108 + + +@test.takes_config +@test.checks("Str") +@test.test_id("B108") +def hardcoded_tmp_directory(context, config): + if config is not None and "tmp_dirs" in config: + tmp_dirs = config["tmp_dirs"] + else: + tmp_dirs = ["/tmp", "/var/tmp", "/dev/shm"] # nosec: B108 + + if any(context.string_val.startswith(s) for s in tmp_dirs): + return bandit.Issue( + severity=bandit.MEDIUM, + confidence=bandit.MEDIUM, + cwe=issue.Cwe.INSECURE_TEMP_FILE, + text="Probable insecure usage of temp file/directory.", + ) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/plugins/hashlib_insecure_functions.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/plugins/hashlib_insecure_functions.py new file mode 100644 index 000000000..4b63de1e9 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/plugins/hashlib_insecure_functions.py @@ -0,0 +1,121 @@ +# +# SPDX-License-Identifier: Apache-2.0 +r""" +====================================================================== +B324: Test use of insecure md4, md5, or sha1 hash functions in hashlib +====================================================================== + +This plugin checks for the usage of the insecure MD4, MD5, or SHA1 hash +functions in ``hashlib`` and ``crypt``. The ``hashlib.new`` function provides +the ability to construct a new hashing object using the named algorithm. This +can be used to create insecure hash functions like MD4 and MD5 if they are +passed as algorithm names to this function. + +This check does additional checking for usage of keyword usedforsecurity on all +function variations of hashlib. + +Similar to ``hashlib``, this plugin also checks for usage of one of the +``crypt`` module's weak hashes. ``crypt`` also permits MD5 among other weak +hash variants. + +:Example: + +.. code-block:: none + + >> Issue: [B324:hashlib] Use of weak MD4, MD5, or SHA1 hash for + security. Consider usedforsecurity=False + Severity: High Confidence: High + CWE: CWE-327 (https://cwe.mitre.org/data/definitions/327.html) + Location: examples/hashlib_new_insecure_functions.py:3:0 + More Info: https://bandit.readthedocs.io/en/latest/plugins/b324_hashlib.html + 2 + 3 hashlib.new('md5') + 4 + +.. seealso:: + + - https://cwe.mitre.org/data/definitions/327.html + +.. versionadded:: 1.5.0 + +.. versionchanged:: 1.7.3 + CWE information added + +.. versionchanged:: 1.7.6 + Added check for the crypt module weak hashes + +""" # noqa: E501 +import bandit +from bandit.core import issue +from bandit.core import test_properties as test + +WEAK_HASHES = ("md4", "md5", "sha", "sha1") +WEAK_CRYPT_HASHES = ("METHOD_CRYPT", "METHOD_MD5", "METHOD_BLOWFISH") + + +def _hashlib_func(context, func): + keywords = context.call_keywords + + if func in WEAK_HASHES: + if keywords.get("usedforsecurity", "True") == "True": + return bandit.Issue( + severity=bandit.HIGH, + confidence=bandit.HIGH, + cwe=issue.Cwe.BROKEN_CRYPTO, + text=f"Use of weak {func.upper()} hash for security. " + "Consider usedforsecurity=False", + lineno=context.node.lineno, + ) + elif func == "new": + args = context.call_args + name = args[0] if args else keywords.get("name", None) + if isinstance(name, str) and name.lower() in WEAK_HASHES: + if keywords.get("usedforsecurity", "True") == "True": + return bandit.Issue( + severity=bandit.HIGH, + confidence=bandit.HIGH, + cwe=issue.Cwe.BROKEN_CRYPTO, + text=f"Use of weak {name.upper()} hash for " + "security. Consider usedforsecurity=False", + lineno=context.node.lineno, + ) + + +def _crypt_crypt(context, func): + args = context.call_args + keywords = context.call_keywords + + if func == "crypt": + name = args[1] if len(args) > 1 else keywords.get("salt", None) + if isinstance(name, str) and name in WEAK_CRYPT_HASHES: + return bandit.Issue( + severity=bandit.MEDIUM, + confidence=bandit.HIGH, + cwe=issue.Cwe.BROKEN_CRYPTO, + text=f"Use of insecure crypt.{name.upper()} hash function.", + lineno=context.node.lineno, + ) + elif func == "mksalt": + name = args[0] if args else keywords.get("method", None) + if isinstance(name, str) and name in WEAK_CRYPT_HASHES: + return bandit.Issue( + severity=bandit.MEDIUM, + confidence=bandit.HIGH, + cwe=issue.Cwe.BROKEN_CRYPTO, + text=f"Use of insecure crypt.{name.upper()} hash function.", + lineno=context.node.lineno, + ) + + +@test.test_id("B324") +@test.checks("Call") +def hashlib(context): + if isinstance(context.call_function_name_qual, str): + qualname_list = context.call_function_name_qual.split(".") + func = qualname_list[-1] + + if "hashlib" in qualname_list: + return _hashlib_func(context, func) + + elif "crypt" in qualname_list and func in ("crypt", "mksalt"): + return _crypt_crypt(context, func) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/plugins/huggingface_unsafe_download.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/plugins/huggingface_unsafe_download.py new file mode 100644 index 000000000..d11c286c3 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/plugins/huggingface_unsafe_download.py @@ -0,0 +1,166 @@ +# SPDX-License-Identifier: Apache-2.0 +r""" +================================================ +B615: Test for unsafe Hugging Face Hub downloads +================================================ + +This plugin checks for unsafe downloads from Hugging Face Hub without proper +integrity verification. Downloading models, datasets, or files without +specifying a revision based on an immmutable revision (commit) can +lead to supply chain attacks where malicious actors could +replace model files and use an existing tag or branch name +to serve malicious content. + +The secure approach is to: + +1. Pin to specific revisions/commits when downloading models, files or datasets + +Common unsafe patterns: +- ``AutoModel.from_pretrained("org/model-name")`` +- ``AutoModel.from_pretrained("org/model-name", revision="main")`` +- ``AutoModel.from_pretrained("org/model-name", revision="v1.0.0")`` +- ``load_dataset("org/dataset-name")`` without revision +- ``load_dataset("org/dataset-name", revision="main")`` +- ``load_dataset("org/dataset-name", revision="v1.0")`` +- ``AutoTokenizer.from_pretrained("org/model-name")`` +- ``AutoTokenizer.from_pretrained("org/model-name", revision="main")`` +- ``AutoTokenizer.from_pretrained("org/model-name", revision="v3.3.0")`` +- ``hf_hub_download(repo_id="org/model_name", filename="file_name")`` +- ``hf_hub_download(repo_id="org/model_name", + filename="file_name", + revision="main" + )`` +- ``hf_hub_download(repo_id="org/model_name", + filename="file_name", + revision="v2.0.0" + )`` +- ``snapshot_download(repo_id="org/model_name")`` +- ``snapshot_download(repo_id="org/model_name", revision="main")`` +- ``snapshot_download(repo_id="org/model_name", revision="refs/pr/1")`` + + +:Example: + +.. code-block:: none + + >> Issue: Unsafe Hugging Face Hub download without revision pinning + Severity: Medium Confidence: High + CWE: CWE-494 (https://cwe.mitre.org/data/definitions/494.html) + Location: examples/huggingface_unsafe_download.py:8 + 7 # Unsafe: no revision specified + 8 model = AutoModel.from_pretrained("org/model_name") + 9 + +.. seealso:: + + - https://cwe.mitre.org/data/definitions/494.html + - https://huggingface.co/docs/huggingface_hub/en/guides/download + +.. versionadded:: 1.8.6 + +""" +import ast +import string + +import bandit +from bandit.core import issue +from bandit.core import test_properties as test + + +@test.checks("Call") +@test.test_id("B615") +def huggingface_unsafe_download(context): + """ + This plugin checks for unsafe artifact download from Hugging Face Hub + without immutable/reproducible revision pinning. + """ + # Check if any HuggingFace-related modules are imported + hf_modules = [ + "transformers", + "datasets", + "huggingface_hub", + ] + + # Check if any HF modules are imported + hf_imported = any( + context.is_module_imported_like(module) for module in hf_modules + ) + + if not hf_imported: + return + + qualname = context.call_function_name_qual + if not isinstance(qualname, str): + return + + unsafe_patterns = { + # transformers library patterns + "from_pretrained": ["transformers"], + # datasets library patterns + "load_dataset": ["datasets"], + # huggingface_hub patterns + "hf_hub_download": ["huggingface_hub"], + "snapshot_download": ["huggingface_hub"], + "repository_id": ["huggingface_hub"], + } + + qualname_parts = qualname.split(".") + func_name = qualname_parts[-1] + + if func_name not in unsafe_patterns: + return + + required_modules = unsafe_patterns[func_name] + if not any(module in qualname_parts for module in required_modules): + return + + # Check for revision parameter (the key security control). + # First, check the raw AST to see if a revision/commit_id keyword was + # passed as a non-literal expression (variable, attribute, subscript, + # function call, etc.). In those cases we cannot statically determine + # the value, so we give the user the benefit of the doubt. + call_node = context._context.get("call") + if call_node is not None: + for kw in getattr(call_node, "keywords", []): + if kw.arg in ("revision", "commit_id") and not isinstance( + kw.value, ast.Constant + ): + return + + revision_value = context.get_call_arg_value("revision") + commit_id_value = context.get_call_arg_value("commit_id") + + # Check if a revision or commit_id is specified + revision_to_check = revision_value or commit_id_value + + if revision_to_check is not None: + # Check if it's a secure revision (looks like a commit hash) + # Commit hashes: 40 chars (full SHA) or 7+ chars (short SHA) + if isinstance(revision_to_check, str): + # Remove quotes if present + revision_str = str(revision_to_check).strip("\"'") + + # Check if it looks like a commit hash (hexadecimal string) + # Must be at least 7 characters and all hexadecimal + is_hex = all(c in string.hexdigits for c in revision_str) + if len(revision_str) >= 7 and is_hex: + # This looks like a commit hash, which is secure + return + + # Edge case: check if this is a local path (starts with ./ or /) + first_arg = context.get_call_arg_at_position(0) + if first_arg and isinstance(first_arg, str): + if first_arg.startswith(("./", "/", "../")): + # Local paths are generally safer + return + + return bandit.Issue( + severity=bandit.MEDIUM, + confidence=bandit.HIGH, + text=( + f"Unsafe Hugging Face Hub download without revision pinning " + f"in {func_name}()" + ), + cwe=issue.Cwe.DOWNLOAD_OF_CODE_WITHOUT_INTEGRITY_CHECK, + lineno=context.get_lineno_for_call_arg(func_name), + ) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/plugins/injection_paramiko.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/plugins/injection_paramiko.py new file mode 100644 index 000000000..674fe0b9b --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/plugins/injection_paramiko.py @@ -0,0 +1,63 @@ +# +# Copyright 2014 Hewlett-Packard Development Company, L.P. +# +# SPDX-License-Identifier: Apache-2.0 +r""" +============================================== +B601: Test for shell injection within Paramiko +============================================== + +Paramiko is a Python library designed to work with the SSH2 protocol for secure +(encrypted and authenticated) connections to remote machines. It is intended to +run commands on a remote host. These commands are run within a shell on the +target and are thus vulnerable to various shell injection attacks. Bandit +reports a MEDIUM issue when it detects the use of Paramiko's "exec_command" +method advising the user to check inputs are correctly sanitized. + +:Example: + +.. code-block:: none + + >> Issue: Possible shell injection via Paramiko call, check inputs are + properly sanitized. + Severity: Medium Confidence: Medium + CWE: CWE-78 (https://cwe.mitre.org/data/definitions/78.html) + Location: ./examples/paramiko_injection.py:4 + 3 # this is not safe + 4 paramiko.exec_command('something; really; unsafe') + 5 + +.. seealso:: + + - https://security.openstack.org + - https://github.com/paramiko/paramiko + - https://www.owasp.org/index.php/Command_Injection + - https://cwe.mitre.org/data/definitions/78.html + +.. versionadded:: 0.12.0 + +.. versionchanged:: 1.7.3 + CWE information added + +""" +import bandit +from bandit.core import issue +from bandit.core import test_properties as test + + +@test.checks("Call") +@test.test_id("B601") +def paramiko_calls(context): + issue_text = ( + "Possible shell injection via Paramiko call, check inputs " + "are properly sanitized." + ) + for module in ["paramiko"]: + if context.is_module_imported_like(module): + if context.call_function_name in ["exec_command"]: + return bandit.Issue( + severity=bandit.MEDIUM, + confidence=bandit.MEDIUM, + cwe=issue.Cwe.OS_COMMAND_INJECTION, + text=issue_text, + ) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/plugins/injection_shell.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/plugins/injection_shell.py new file mode 100644 index 000000000..e318eb7b9 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/plugins/injection_shell.py @@ -0,0 +1,706 @@ +# +# Copyright 2014 Hewlett-Packard Development Company, L.P. +# +# SPDX-License-Identifier: Apache-2.0 +import ast +import re + +import bandit +from bandit.core import issue +from bandit.core import test_properties as test + +# yuck, regex: starts with a windows drive letter (eg C:) +# or one of our path delimiter characters (/, \, .) +full_path_match = re.compile(r"^(?:[A-Za-z](?=\:)|[\\\/\.])") + + +def _evaluate_shell_call(context): + no_formatting = isinstance( + context.node.args[0], ast.Constant + ) and isinstance(context.node.args[0].value, str) + + if no_formatting: + return bandit.LOW + else: + return bandit.HIGH + + +def gen_config(name): + if name == "shell_injection": + return { + # Start a process using the subprocess module, or one of its + # wrappers. + "subprocess": [ + "subprocess.Popen", + "subprocess.call", + "subprocess.check_call", + "subprocess.check_output", + "subprocess.run", + ], + # Start a process with a function vulnerable to shell injection. + "shell": [ + "os.system", + "os.popen", + "os.popen2", + "os.popen3", + "os.popen4", + "popen2.popen2", + "popen2.popen3", + "popen2.popen4", + "popen2.Popen3", + "popen2.Popen4", + "commands.getoutput", + "commands.getstatusoutput", + "subprocess.getoutput", + "subprocess.getstatusoutput", + ], + # Start a process with a function that is not vulnerable to shell + # injection. + "no_shell": [ + "os.execl", + "os.execle", + "os.execlp", + "os.execlpe", + "os.execv", + "os.execve", + "os.execvp", + "os.execvpe", + "os.spawnl", + "os.spawnle", + "os.spawnlp", + "os.spawnlpe", + "os.spawnv", + "os.spawnve", + "os.spawnvp", + "os.spawnvpe", + "os.startfile", + ], + } + + +def has_shell(context): + keywords = context.node.keywords + result = False + if "shell" in context.call_keywords: + for key in keywords: + if key.arg == "shell": + val = key.value + if isinstance(val, ast.Constant) and ( + isinstance(val.value, int) + or isinstance(val.value, float) + or isinstance(val.value, complex) + ): + result = bool(val.value) + elif isinstance(val, ast.List): + result = bool(val.elts) + elif isinstance(val, ast.Dict): + result = bool(val.keys) + elif isinstance(val, ast.Name) and val.id in ["False", "None"]: + result = False + elif isinstance(val, ast.Constant): + result = val.value + else: + result = True + return result + + +@test.takes_config("shell_injection") +@test.checks("Call") +@test.test_id("B602") +def subprocess_popen_with_shell_equals_true(context, config): + """**B602: Test for use of popen with shell equals true** + + Python possesses many mechanisms to invoke an external executable. However, + doing so may present a security issue if appropriate care is not taken to + sanitize any user provided or variable input. + + This plugin test is part of a family of tests built to check for process + spawning and warn appropriately. Specifically, this test looks for the + spawning of a subprocess using a command shell. This type of subprocess + invocation is dangerous as it is vulnerable to various shell injection + attacks. Great care should be taken to sanitize all input in order to + mitigate this risk. Calls of this type are identified by a parameter of + 'shell=True' being given. + + Additionally, this plugin scans the command string given and adjusts its + reported severity based on how it is presented. If the command string is a + simple static string containing no special shell characters, then the + resulting issue has low severity. If the string is static, but contains + shell formatting characters or wildcards, then the reported issue is + medium. Finally, if the string is computed using Python's string + manipulation or formatting operations, then the reported issue has high + severity. These severity levels reflect the likelihood that the code is + vulnerable to injection. + + See also: + + - :doc:`../plugins/linux_commands_wildcard_injection` + - :doc:`../plugins/subprocess_without_shell_equals_true` + - :doc:`../plugins/start_process_with_no_shell` + - :doc:`../plugins/start_process_with_a_shell` + - :doc:`../plugins/start_process_with_partial_path` + + **Config Options:** + + This plugin test shares a configuration with others in the same family, + namely `shell_injection`. This configuration is divided up into three + sections, `subprocess`, `shell` and `no_shell`. They each list Python calls + that spawn subprocesses, invoke commands within a shell, or invoke commands + without a shell (by replacing the calling process) respectively. + + This plugin specifically scans for methods listed in `subprocess` section + that have shell=True specified. + + .. code-block:: yaml + + shell_injection: + + # Start a process using the subprocess module, or one of its + wrappers. + subprocess: + - subprocess.Popen + - subprocess.call + + + :Example: + + .. code-block:: none + + >> Issue: subprocess call with shell=True seems safe, but may be + changed in the future, consider rewriting without shell + Severity: Low Confidence: High + CWE: CWE-78 (https://cwe.mitre.org/data/definitions/78.html) + Location: ./examples/subprocess_shell.py:21 + 20 subprocess.check_call(['/bin/ls', '-l'], shell=False) + 21 subprocess.check_call('/bin/ls -l', shell=True) + 22 + + >> Issue: call with shell=True contains special shell characters, + consider moving extra logic into Python code + Severity: Medium Confidence: High + CWE: CWE-78 (https://cwe.mitre.org/data/definitions/78.html) + Location: ./examples/subprocess_shell.py:26 + 25 + 26 subprocess.Popen('/bin/ls *', shell=True) + 27 subprocess.Popen('/bin/ls %s' % ('something',), shell=True) + + >> Issue: subprocess call with shell=True identified, security issue. + Severity: High Confidence: High + CWE: CWE-78 (https://cwe.mitre.org/data/definitions/78.html) + Location: ./examples/subprocess_shell.py:27 + 26 subprocess.Popen('/bin/ls *', shell=True) + 27 subprocess.Popen('/bin/ls %s' % ('something',), shell=True) + 28 subprocess.Popen('/bin/ls {}'.format('something'), shell=True) + + .. seealso:: + + - https://security.openstack.org + - https://docs.python.org/3/library/subprocess.html#frequently-used-arguments + - https://security.openstack.org/guidelines/dg_use-subprocess-securely.html + - https://security.openstack.org/guidelines/dg_avoid-shell-true.html + - https://cwe.mitre.org/data/definitions/78.html + + .. versionadded:: 0.9.0 + + .. versionchanged:: 1.7.3 + CWE information added + + """ # noqa: E501 + if config and context.call_function_name_qual in config["subprocess"]: + if has_shell(context): + if len(context.call_args) > 0: + sev = _evaluate_shell_call(context) + if sev == bandit.LOW: + return bandit.Issue( + severity=bandit.LOW, + confidence=bandit.HIGH, + cwe=issue.Cwe.OS_COMMAND_INJECTION, + text="subprocess call with shell=True seems safe, but " + "may be changed in the future, consider " + "rewriting without shell", + lineno=context.get_lineno_for_call_arg("shell"), + ) + else: + return bandit.Issue( + severity=bandit.HIGH, + confidence=bandit.HIGH, + cwe=issue.Cwe.OS_COMMAND_INJECTION, + text="subprocess call with shell=True identified, " + "security issue.", + lineno=context.get_lineno_for_call_arg("shell"), + ) + + +@test.takes_config("shell_injection") +@test.checks("Call") +@test.test_id("B603") +def subprocess_without_shell_equals_true(context, config): + """**B603: Test for use of subprocess without shell equals true** + + Python possesses many mechanisms to invoke an external executable. However, + doing so may present a security issue if appropriate care is not taken to + sanitize any user provided or variable input. + + This plugin test is part of a family of tests built to check for process + spawning and warn appropriately. Specifically, this test looks for the + spawning of a subprocess without the use of a command shell. This type of + subprocess invocation is not vulnerable to shell injection attacks, but + care should still be taken to ensure validity of input. + + Because this is a lesser issue than that described in + `subprocess_popen_with_shell_equals_true` a LOW severity warning is + reported. + + See also: + + - :doc:`../plugins/linux_commands_wildcard_injection` + - :doc:`../plugins/subprocess_popen_with_shell_equals_true` + - :doc:`../plugins/start_process_with_no_shell` + - :doc:`../plugins/start_process_with_a_shell` + - :doc:`../plugins/start_process_with_partial_path` + + **Config Options:** + + This plugin test shares a configuration with others in the same family, + namely `shell_injection`. This configuration is divided up into three + sections, `subprocess`, `shell` and `no_shell`. They each list Python calls + that spawn subprocesses, invoke commands within a shell, or invoke commands + without a shell (by replacing the calling process) respectively. + + This plugin specifically scans for methods listed in `subprocess` section + that have shell=False specified. + + .. code-block:: yaml + + shell_injection: + # Start a process using the subprocess module, or one of its + wrappers. + subprocess: + - subprocess.Popen + - subprocess.call + + :Example: + + .. code-block:: none + + >> Issue: subprocess call - check for execution of untrusted input. + Severity: Low Confidence: High + CWE: CWE-78 (https://cwe.mitre.org/data/definitions/78.html) + Location: ./examples/subprocess_shell.py:23 + 22 + 23 subprocess.check_output(['/bin/ls', '-l']) + 24 + + .. seealso:: + + - https://security.openstack.org + - https://docs.python.org/3/library/subprocess.html#frequently-used-arguments + - https://security.openstack.org/guidelines/dg_avoid-shell-true.html + - https://security.openstack.org/guidelines/dg_use-subprocess-securely.html + - https://cwe.mitre.org/data/definitions/78.html + + .. versionadded:: 0.9.0 + + .. versionchanged:: 1.7.3 + CWE information added + + """ # noqa: E501 + if config and context.call_function_name_qual in config["subprocess"]: + if not has_shell(context): + return bandit.Issue( + severity=bandit.LOW, + confidence=bandit.HIGH, + cwe=issue.Cwe.OS_COMMAND_INJECTION, + text="subprocess call - check for execution of untrusted " + "input.", + lineno=context.get_lineno_for_call_arg("shell"), + ) + + +@test.takes_config("shell_injection") +@test.checks("Call") +@test.test_id("B604") +def any_other_function_with_shell_equals_true(context, config): + """**B604: Test for any function with shell equals true** + + Python possesses many mechanisms to invoke an external executable. However, + doing so may present a security issue if appropriate care is not taken to + sanitize any user provided or variable input. + + This plugin test is part of a family of tests built to check for process + spawning and warn appropriately. Specifically, this plugin test + interrogates method calls for the presence of a keyword parameter `shell` + equalling true. It is related to detection of shell injection issues and is + intended to catch custom wrappers to vulnerable methods that may have been + created. + + See also: + + - :doc:`../plugins/linux_commands_wildcard_injection` + - :doc:`../plugins/subprocess_popen_with_shell_equals_true` + - :doc:`../plugins/subprocess_without_shell_equals_true` + - :doc:`../plugins/start_process_with_no_shell` + - :doc:`../plugins/start_process_with_a_shell` + - :doc:`../plugins/start_process_with_partial_path` + + **Config Options:** + + This plugin test shares a configuration with others in the same family, + namely `shell_injection`. This configuration is divided up into three + sections, `subprocess`, `shell` and `no_shell`. They each list Python calls + that spawn subprocesses, invoke commands within a shell, or invoke commands + without a shell (by replacing the calling process) respectively. + + Specifically, this plugin excludes those functions listed under the + subprocess section, these methods are tested in a separate specific test + plugin and this exclusion prevents duplicate issue reporting. + + .. code-block:: yaml + + shell_injection: + # Start a process using the subprocess module, or one of its + wrappers. + subprocess: [subprocess.Popen, subprocess.call, + subprocess.check_call, subprocess.check_output + execute_with_timeout] + + + :Example: + + .. code-block:: none + + >> Issue: Function call with shell=True parameter identified, possible + security issue. + Severity: Medium Confidence: High + CWE: CWE-78 (https://cwe.mitre.org/data/definitions/78.html) + Location: ./examples/subprocess_shell.py:9 + 8 pop('/bin/gcc --version', shell=True) + 9 Popen('/bin/gcc --version', shell=True) + 10 + + .. seealso:: + + - https://security.openstack.org/guidelines/dg_avoid-shell-true.html + - https://security.openstack.org/guidelines/dg_use-subprocess-securely.html + - https://cwe.mitre.org/data/definitions/78.html + + .. versionadded:: 0.9.0 + + .. versionchanged:: 1.7.3 + CWE information added + + """ # noqa: E501 + if config and context.call_function_name_qual not in config["subprocess"]: + if has_shell(context): + return bandit.Issue( + severity=bandit.MEDIUM, + confidence=bandit.LOW, + cwe=issue.Cwe.OS_COMMAND_INJECTION, + text="Function call with shell=True parameter identified, " + "possible security issue.", + lineno=context.get_lineno_for_call_arg("shell"), + ) + + +@test.takes_config("shell_injection") +@test.checks("Call") +@test.test_id("B605") +def start_process_with_a_shell(context, config): + """**B605: Test for starting a process with a shell** + + Python possesses many mechanisms to invoke an external executable. However, + doing so may present a security issue if appropriate care is not taken to + sanitize any user provided or variable input. + + This plugin test is part of a family of tests built to check for process + spawning and warn appropriately. Specifically, this test looks for the + spawning of a subprocess using a command shell. This type of subprocess + invocation is dangerous as it is vulnerable to various shell injection + attacks. Great care should be taken to sanitize all input in order to + mitigate this risk. Calls of this type are identified by the use of certain + commands which are known to use shells. Bandit will report a LOW + severity warning. + + See also: + + - :doc:`../plugins/linux_commands_wildcard_injection` + - :doc:`../plugins/subprocess_without_shell_equals_true` + - :doc:`../plugins/start_process_with_no_shell` + - :doc:`../plugins/start_process_with_partial_path` + - :doc:`../plugins/subprocess_popen_with_shell_equals_true` + + **Config Options:** + + This plugin test shares a configuration with others in the same family, + namely `shell_injection`. This configuration is divided up into three + sections, `subprocess`, `shell` and `no_shell`. They each list Python calls + that spawn subprocesses, invoke commands within a shell, or invoke commands + without a shell (by replacing the calling process) respectively. + + This plugin specifically scans for methods listed in `shell` section. + + .. code-block:: yaml + + shell_injection: + shell: + - os.system + - os.popen + - os.popen2 + - os.popen3 + - os.popen4 + - popen2.popen2 + - popen2.popen3 + - popen2.popen4 + - popen2.Popen3 + - popen2.Popen4 + - commands.getoutput + - commands.getstatusoutput + - subprocess.getoutput + - subprocess.getstatusoutput + + :Example: + + .. code-block:: none + + >> Issue: Starting a process with a shell: check for injection. + Severity: Low Confidence: Medium + CWE: CWE-78 (https://cwe.mitre.org/data/definitions/78.html) + Location: examples/os_system.py:3 + 2 + 3 os.system('/bin/echo hi') + + .. seealso:: + + - https://security.openstack.org + - https://docs.python.org/3/library/os.html#os.system + - https://docs.python.org/3/library/subprocess.html#frequently-used-arguments + - https://security.openstack.org/guidelines/dg_use-subprocess-securely.html + - https://cwe.mitre.org/data/definitions/78.html + + .. versionadded:: 0.10.0 + + .. versionchanged:: 1.7.3 + CWE information added + + """ # noqa: E501 + if config and context.call_function_name_qual in config["shell"]: + if len(context.call_args) > 0: + sev = _evaluate_shell_call(context) + if sev == bandit.LOW: + return bandit.Issue( + severity=bandit.LOW, + confidence=bandit.HIGH, + cwe=issue.Cwe.OS_COMMAND_INJECTION, + text="Starting a process with a shell: " + "Seems safe, but may be changed in the future, " + "consider rewriting without shell", + ) + else: + return bandit.Issue( + severity=bandit.HIGH, + confidence=bandit.HIGH, + cwe=issue.Cwe.OS_COMMAND_INJECTION, + text="Starting a process with a shell, possible injection" + " detected, security issue.", + ) + + +@test.takes_config("shell_injection") +@test.checks("Call") +@test.test_id("B606") +def start_process_with_no_shell(context, config): + """**B606: Test for starting a process with no shell** + + Python possesses many mechanisms to invoke an external executable. However, + doing so may present a security issue if appropriate care is not taken to + sanitize any user provided or variable input. + + This plugin test is part of a family of tests built to check for process + spawning and warn appropriately. Specifically, this test looks for the + spawning of a subprocess in a way that doesn't use a shell. Although this + is generally safe, it maybe useful for penetration testing workflows to + track where external system calls are used. As such a LOW severity message + is generated. + + See also: + + - :doc:`../plugins/linux_commands_wildcard_injection` + - :doc:`../plugins/subprocess_without_shell_equals_true` + - :doc:`../plugins/start_process_with_a_shell` + - :doc:`../plugins/start_process_with_partial_path` + - :doc:`../plugins/subprocess_popen_with_shell_equals_true` + + **Config Options:** + + This plugin test shares a configuration with others in the same family, + namely `shell_injection`. This configuration is divided up into three + sections, `subprocess`, `shell` and `no_shell`. They each list Python calls + that spawn subprocesses, invoke commands within a shell, or invoke commands + without a shell (by replacing the calling process) respectively. + + This plugin specifically scans for methods listed in `no_shell` section. + + .. code-block:: yaml + + shell_injection: + no_shell: + - os.execl + - os.execle + - os.execlp + - os.execlpe + - os.execv + - os.execve + - os.execvp + - os.execvpe + - os.spawnl + - os.spawnle + - os.spawnlp + - os.spawnlpe + - os.spawnv + - os.spawnve + - os.spawnvp + - os.spawnvpe + - os.startfile + + :Example: + + .. code-block:: none + + >> Issue: [start_process_with_no_shell] Starting a process without a + shell. + Severity: Low Confidence: Medium + CWE: CWE-78 (https://cwe.mitre.org/data/definitions/78.html) + Location: examples/os-spawn.py:8 + 7 os.spawnv(mode, path, args) + 8 os.spawnve(mode, path, args, env) + 9 os.spawnvp(mode, file, args) + + .. seealso:: + + - https://security.openstack.org + - https://docs.python.org/3/library/os.html#os.system + - https://docs.python.org/3/library/subprocess.html#frequently-used-arguments + - https://security.openstack.org/guidelines/dg_use-subprocess-securely.html + - https://cwe.mitre.org/data/definitions/78.html + + .. versionadded:: 0.10.0 + + .. versionchanged:: 1.7.3 + CWE information added + + """ # noqa: E501 + + if config and context.call_function_name_qual in config["no_shell"]: + return bandit.Issue( + severity=bandit.LOW, + confidence=bandit.MEDIUM, + cwe=issue.Cwe.OS_COMMAND_INJECTION, + text="Starting a process without a shell.", + ) + + +@test.takes_config("shell_injection") +@test.checks("Call") +@test.test_id("B607") +def start_process_with_partial_path(context, config): + """**B607: Test for starting a process with a partial path** + + Python possesses many mechanisms to invoke an external executable. If the + desired executable path is not fully qualified relative to the filesystem + root then this may present a potential security risk. + + In POSIX environments, the `PATH` environment variable is used to specify a + set of standard locations that will be searched for the first matching + named executable. While convenient, this behavior may allow a malicious + actor to exert control over a system. If they are able to adjust the + contents of the `PATH` variable, or manipulate the file system, then a + bogus executable may be discovered in place of the desired one. This + executable will be invoked with the user privileges of the Python process + that spawned it, potentially a highly privileged user. + + This test will scan the parameters of all configured Python methods, + looking for paths that do not start at the filesystem root, that is, do not + have a leading '/' character. + + **Config Options:** + + This plugin test shares a configuration with others in the same family, + namely `shell_injection`. This configuration is divided up into three + sections, `subprocess`, `shell` and `no_shell`. They each list Python calls + that spawn subprocesses, invoke commands within a shell, or invoke commands + without a shell (by replacing the calling process) respectively. + + This test will scan parameters of all methods in all sections. Note that + methods are fully qualified and de-aliased prior to checking. + + .. code-block:: yaml + + shell_injection: + # Start a process using the subprocess module, or one of its + wrappers. + subprocess: + - subprocess.Popen + - subprocess.call + + # Start a process with a function vulnerable to shell injection. + shell: + - os.system + - os.popen + - popen2.Popen3 + - popen2.Popen4 + - commands.getoutput + - commands.getstatusoutput + # Start a process with a function that is not vulnerable to shell + injection. + no_shell: + - os.execl + - os.execle + + + :Example: + + .. code-block:: none + + >> Issue: Starting a process with a partial executable path + Severity: Low Confidence: High + CWE: CWE-78 (https://cwe.mitre.org/data/definitions/78.html) + Location: ./examples/partial_path_process.py:3 + 2 from subprocess import Popen as pop + 3 pop('gcc --version', shell=False) + + .. seealso:: + + - https://security.openstack.org + - https://docs.python.org/3/library/os.html#process-management + - https://cwe.mitre.org/data/definitions/78.html + + .. versionadded:: 0.13.0 + + .. versionchanged:: 1.7.3 + CWE information added + + """ + + if config and len(context.call_args): + if ( + context.call_function_name_qual in config["subprocess"] + or context.call_function_name_qual in config["shell"] + or context.call_function_name_qual in config["no_shell"] + ): + node = context.node.args[0] + # some calls take an arg list, check the first part + if isinstance(node, ast.List) and node.elts: + node = node.elts[0] + + # make sure the param is a string literal and not a var name + if ( + isinstance(node, ast.Constant) + and isinstance(node.value, str) + and not full_path_match.match(node.value) + ): + return bandit.Issue( + severity=bandit.LOW, + confidence=bandit.HIGH, + cwe=issue.Cwe.OS_COMMAND_INJECTION, + text="Starting a process with a partial executable path", + ) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/plugins/injection_sql.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/plugins/injection_sql.py new file mode 100644 index 000000000..704022a91 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/plugins/injection_sql.py @@ -0,0 +1,143 @@ +# +# Copyright 2014 Hewlett-Packard Development Company, L.P. +# +# SPDX-License-Identifier: Apache-2.0 +r""" +============================ +B608: Test for SQL injection +============================ + +An SQL injection attack consists of insertion or "injection" of a SQL query via +the input data given to an application. It is a very common attack vector. This +plugin test looks for strings that resemble SQL statements that are involved in +some form of string building operation. For example: + + - "SELECT %s FROM derp;" % var + - "SELECT thing FROM " + tab + - "SELECT " + val + " FROM " + tab + ... + - "SELECT {} FROM derp;".format(var) + - f"SELECT foo FROM bar WHERE id = {product}" + +Unless care is taken to sanitize and control the input data when building such +SQL statement strings, an injection attack becomes possible. If strings of this +nature are discovered, a LOW confidence issue is reported. In order to boost +result confidence, this plugin test will also check to see if the discovered +string is in use with standard Python DBAPI calls `execute` or `executemany`. +If so, a MEDIUM issue is reported. For example: + + - cursor.execute("SELECT %s FROM derp;" % var) + +Use of str.replace in the string construction can also be dangerous. +For example: + +- "SELECT * FROM foo WHERE id = '[VALUE]'".replace("[VALUE]", identifier) + +However, such cases are always reported with LOW confidence to compensate +for false positives, since valid uses of str.replace can be common. + +:Example: + +.. code-block:: none + + >> Issue: Possible SQL injection vector through string-based query + construction. + Severity: Medium Confidence: Low + CWE: CWE-89 (https://cwe.mitre.org/data/definitions/89.html) + Location: ./examples/sql_statements.py:4 + 3 query = "DELETE FROM foo WHERE id = '%s'" % identifier + 4 query = "UPDATE foo SET value = 'b' WHERE id = '%s'" % identifier + 5 + +.. seealso:: + + - https://www.owasp.org/index.php/SQL_Injection + - https://security.openstack.org/guidelines/dg_parameterize-database-queries.html + - https://cwe.mitre.org/data/definitions/89.html + +.. versionadded:: 0.9.0 + +.. versionchanged:: 1.7.3 + CWE information added + +.. versionchanged:: 1.7.7 + Flag when str.replace is used in the string construction + +""" # noqa: E501 +import ast +import re + +import bandit +from bandit.core import issue +from bandit.core import test_properties as test +from bandit.core import utils + +SIMPLE_SQL_RE = re.compile( + r"(select\s.*from\s|" + r"delete\s+from\s|" + r"insert\s+into\s.*values[\s(]|" + r"update\s.*set\s)", + re.IGNORECASE | re.DOTALL, +) + + +def _check_string(data): + return SIMPLE_SQL_RE.search(data) is not None + + +def _evaluate_ast(node): + wrapper = None + statement = "" + str_replace = False + + if isinstance(node._bandit_parent, ast.BinOp): + out = utils.concat_string(node, node._bandit_parent) + wrapper = out[0]._bandit_parent + statement = out[1] + elif isinstance( + node._bandit_parent, ast.Attribute + ) and node._bandit_parent.attr in ("format", "replace"): + statement = node.value + # Hierarchy for "".format() is Wrapper -> Call -> Attribute -> Str + wrapper = node._bandit_parent._bandit_parent._bandit_parent + if node._bandit_parent.attr == "replace": + str_replace = True + elif hasattr(ast, "JoinedStr") and isinstance( + node._bandit_parent, ast.JoinedStr + ): + substrings = [ + child + for child in node._bandit_parent.values + if isinstance(child, ast.Constant) and isinstance(child.value, str) + ] + # JoinedStr consists of list of Constant and FormattedValue + # instances. Let's perform one test for the whole string + # and abandon all parts except the first one to raise one + # failed test instead of many for the same SQL statement. + if substrings and node == substrings[0]: + statement = "".join([str(child.value) for child in substrings]) + wrapper = node._bandit_parent._bandit_parent + + if isinstance(wrapper, ast.Call): # wrapped in "execute" call? + names = ["execute", "executemany"] + name = utils.get_called_name(wrapper) + return (name in names, statement, str_replace) + else: + return (False, statement, str_replace) + + +@test.checks("Str") +@test.test_id("B608") +def hardcoded_sql_expressions(context): + execute_call, statement, str_replace = _evaluate_ast(context.node) + if _check_string(statement): + return bandit.Issue( + severity=bandit.MEDIUM, + confidence=( + bandit.MEDIUM + if execute_call and not str_replace + else bandit.LOW + ), + cwe=issue.Cwe.SQL_INJECTION, + text="Possible SQL injection vector through string-based " + "query construction.", + ) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/plugins/injection_wildcard.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/plugins/injection_wildcard.py new file mode 100644 index 000000000..46f6b5b6c --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/plugins/injection_wildcard.py @@ -0,0 +1,144 @@ +# +# Copyright 2014 Hewlett-Packard Development Company, L.P. +# +# SPDX-License-Identifier: Apache-2.0 +r""" +======================================== +B609: Test for use of wildcard injection +======================================== + +Python provides a number of methods that emulate the behavior of standard Linux +command line utilities. Like their Linux counterparts, these commands may take +a wildcard "\*" character in place of a file system path. This is interpreted +to mean "any and all files or folders" and can be used to build partially +qualified paths, such as "/home/user/\*". + +The use of partially qualified paths may result in unintended consequences if +an unexpected file or symlink is placed into the path location given. This +becomes particularly dangerous when combined with commands used to manipulate +file permissions or copy data off of a system. + +This test plugin looks for usage of the following commands in conjunction with +wild card parameters: + +- 'chown' +- 'chmod' +- 'tar' +- 'rsync' + +As well as any method configured in the shell or subprocess injection test +configurations. + + +**Config Options:** + +This plugin test shares a configuration with others in the same family, namely +`shell_injection`. This configuration is divided up into three sections, +`subprocess`, `shell` and `no_shell`. They each list Python calls that spawn +subprocesses, invoke commands within a shell, or invoke commands without a +shell (by replacing the calling process) respectively. + +This test will scan parameters of all methods in all sections. Note that +methods are fully qualified and de-aliased prior to checking. + + +.. code-block:: yaml + + shell_injection: + # Start a process using the subprocess module, or one of its wrappers. + subprocess: + - subprocess.Popen + - subprocess.call + + # Start a process with a function vulnerable to shell injection. + shell: + - os.system + - os.popen + - popen2.Popen3 + - popen2.Popen4 + - commands.getoutput + - commands.getstatusoutput + # Start a process with a function that is not vulnerable to shell + injection. + no_shell: + - os.execl + - os.execle + + +:Example: + +.. code-block:: none + + >> Issue: Possible wildcard injection in call: subprocess.Popen + Severity: High Confidence: Medium + CWE-78 (https://cwe.mitre.org/data/definitions/78.html) + Location: ./examples/wildcard-injection.py:8 + 7 o.popen2('/bin/chmod *') + 8 subp.Popen('/bin/chown *', shell=True) + 9 + + >> Issue: subprocess call - check for execution of untrusted input. + Severity: Low Confidence: High + CWE-78 (https://cwe.mitre.org/data/definitions/78.html) + Location: ./examples/wildcard-injection.py:11 + 10 # Not vulnerable to wildcard injection + 11 subp.Popen('/bin/rsync *') + 12 subp.Popen("/bin/chmod *") + + +.. seealso:: + + - https://security.openstack.org + - https://en.wikipedia.org/wiki/Wildcard_character + - https://www.defensecode.com/public/DefenseCode_Unix_WildCards_Gone_Wild.txt + - https://cwe.mitre.org/data/definitions/78.html + +.. versionadded:: 0.9.0 + +.. versionchanged:: 1.7.3 + CWE information added + +""" +import bandit +from bandit.core import issue +from bandit.core import test_properties as test +from bandit.plugins import injection_shell # NOTE(tkelsey): shared config + +gen_config = injection_shell.gen_config + + +@test.takes_config("shell_injection") +@test.checks("Call") +@test.test_id("B609") +def linux_commands_wildcard_injection(context, config): + if not ("shell" in config and "subprocess" in config): + return + + vulnerable_funcs = ["chown", "chmod", "tar", "rsync"] + if context.call_function_name_qual in config["shell"] or ( + context.call_function_name_qual in config["subprocess"] + and context.check_call_arg_value("shell", "True") + ): + if context.call_args_count >= 1: + call_argument = context.get_call_arg_at_position(0) + argument_string = "" + if isinstance(call_argument, list): + for li in call_argument: + argument_string += f" {li}" + elif isinstance(call_argument, str): + argument_string = call_argument + + if argument_string != "": + for vulnerable_func in vulnerable_funcs: + if ( + vulnerable_func in argument_string + and "*" in argument_string + ): + return bandit.Issue( + severity=bandit.HIGH, + confidence=bandit.MEDIUM, + cwe=issue.Cwe.IMPROPER_WILDCARD_NEUTRALIZATION, + text="Possible wildcard injection in call: %s" + % context.call_function_name_qual, + lineno=context.get_lineno_for_call_arg("shell"), + ) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/plugins/insecure_ssl_tls.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/plugins/insecure_ssl_tls.py new file mode 100644 index 000000000..319abcf1f --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/plugins/insecure_ssl_tls.py @@ -0,0 +1,285 @@ +# +# Copyright 2014 Hewlett-Packard Development Company, L.P. +# +# SPDX-License-Identifier: Apache-2.0 +import bandit +from bandit.core import issue +from bandit.core import test_properties as test + + +def get_bad_proto_versions(config): + return config["bad_protocol_versions"] + + +def gen_config(name): + if name == "ssl_with_bad_version": + return { + "bad_protocol_versions": [ + "PROTOCOL_SSLv2", + "SSLv2_METHOD", + "SSLv23_METHOD", + "PROTOCOL_SSLv3", # strict option + "PROTOCOL_TLSv1", # strict option + "SSLv3_METHOD", # strict option + "TLSv1_METHOD", + "PROTOCOL_TLSv1_1", + "TLSv1_1_METHOD", + ] + } # strict option + + +@test.takes_config +@test.checks("Call") +@test.test_id("B502") +def ssl_with_bad_version(context, config): + """**B502: Test for SSL use with bad version used** + + Several highly publicized exploitable flaws have been discovered + in all versions of SSL and early versions of TLS. It is strongly + recommended that use of the following known broken protocol versions be + avoided: + + - SSL v2 + - SSL v3 + - TLS v1 + - TLS v1.1 + + This plugin test scans for calls to Python methods with parameters that + indicate the used broken SSL/TLS protocol versions. Currently, detection + supports methods using Python's native SSL/TLS support and the pyOpenSSL + module. A HIGH severity warning will be reported whenever known broken + protocol versions are detected. + + It is worth noting that native support for TLS 1.2 is only available in + more recent Python versions, specifically 2.7.9 and up, and 3.x + + A note on 'SSLv23': + + Amongst the available SSL/TLS versions provided by Python/pyOpenSSL there + exists the option to use SSLv23. This very poorly named option actually + means "use the highest version of SSL/TLS supported by both the server and + client". This may (and should be) a version well in advance of SSL v2 or + v3. Bandit can scan for the use of SSLv23 if desired, but its detection + does not necessarily indicate a problem. + + When using SSLv23 it is important to also provide flags to explicitly + exclude bad versions of SSL/TLS from the protocol versions considered. Both + the Python native and pyOpenSSL modules provide the ``OP_NO_SSLv2`` and + ``OP_NO_SSLv3`` flags for this purpose. + + **Config Options:** + + .. code-block:: yaml + + ssl_with_bad_version: + bad_protocol_versions: + - PROTOCOL_SSLv2 + - SSLv2_METHOD + - SSLv23_METHOD + - PROTOCOL_SSLv3 # strict option + - PROTOCOL_TLSv1 # strict option + - SSLv3_METHOD # strict option + - TLSv1_METHOD # strict option + + :Example: + + .. code-block:: none + + >> Issue: ssl.wrap_socket call with insecure SSL/TLS protocol version + identified, security issue. + Severity: High Confidence: High + CWE: CWE-327 (https://cwe.mitre.org/data/definitions/327.html) + Location: ./examples/ssl-insecure-version.py:13 + 12 # strict tests + 13 ssl.wrap_socket(ssl_version=ssl.PROTOCOL_SSLv3) + 14 ssl.wrap_socket(ssl_version=ssl.PROTOCOL_TLSv1) + + .. seealso:: + + - :func:`ssl_with_bad_defaults` + - :func:`ssl_with_no_version` + - https://heartbleed.com/ + - https://en.wikipedia.org/wiki/POODLE + - https://security.openstack.org/guidelines/dg_move-data-securely.html + - https://cwe.mitre.org/data/definitions/327.html + + .. versionadded:: 0.9.0 + + .. versionchanged:: 1.7.3 + CWE information added + + .. versionchanged:: 1.7.5 + Added TLS 1.1 + + """ + bad_ssl_versions = get_bad_proto_versions(config) + if context.call_function_name_qual == "ssl.wrap_socket": + if context.check_call_arg_value("ssl_version", bad_ssl_versions): + return bandit.Issue( + severity=bandit.HIGH, + confidence=bandit.HIGH, + cwe=issue.Cwe.BROKEN_CRYPTO, + text="ssl.wrap_socket call with insecure SSL/TLS protocol " + "version identified, security issue.", + lineno=context.get_lineno_for_call_arg("ssl_version"), + ) + elif context.call_function_name_qual == "pyOpenSSL.SSL.Context": + if context.check_call_arg_value("method", bad_ssl_versions): + return bandit.Issue( + severity=bandit.HIGH, + confidence=bandit.HIGH, + cwe=issue.Cwe.BROKEN_CRYPTO, + text="SSL.Context call with insecure SSL/TLS protocol " + "version identified, security issue.", + lineno=context.get_lineno_for_call_arg("method"), + ) + + elif ( + context.call_function_name_qual != "ssl.wrap_socket" + and context.call_function_name_qual != "pyOpenSSL.SSL.Context" + ): + if context.check_call_arg_value( + "method", bad_ssl_versions + ) or context.check_call_arg_value("ssl_version", bad_ssl_versions): + lineno = context.get_lineno_for_call_arg( + "method" + ) or context.get_lineno_for_call_arg("ssl_version") + return bandit.Issue( + severity=bandit.MEDIUM, + confidence=bandit.MEDIUM, + cwe=issue.Cwe.BROKEN_CRYPTO, + text="Function call with insecure SSL/TLS protocol " + "identified, possible security issue.", + lineno=lineno, + ) + + +@test.takes_config("ssl_with_bad_version") +@test.checks("FunctionDef") +@test.test_id("B503") +def ssl_with_bad_defaults(context, config): + """**B503: Test for SSL use with bad defaults specified** + + This plugin is part of a family of tests that detect the use of known bad + versions of SSL/TLS, please see :doc:`../plugins/ssl_with_bad_version` for + a complete discussion. Specifically, this plugin test scans for Python + methods with default parameter values that specify the use of broken + SSL/TLS protocol versions. Currently, detection supports methods using + Python's native SSL/TLS support and the pyOpenSSL module. A MEDIUM severity + warning will be reported whenever known broken protocol versions are + detected. + + **Config Options:** + + This test shares the configuration provided for the standard + :doc:`../plugins/ssl_with_bad_version` test, please refer to its + documentation. + + :Example: + + .. code-block:: none + + >> Issue: Function definition identified with insecure SSL/TLS protocol + version by default, possible security issue. + Severity: Medium Confidence: Medium + CWE: CWE-327 (https://cwe.mitre.org/data/definitions/327.html) + Location: ./examples/ssl-insecure-version.py:28 + 27 + 28 def open_ssl_socket(version=SSL.SSLv2_METHOD): + 29 pass + + .. seealso:: + + - :func:`ssl_with_bad_version` + - :func:`ssl_with_no_version` + - https://heartbleed.com/ + - https://en.wikipedia.org/wiki/POODLE + - https://security.openstack.org/guidelines/dg_move-data-securely.html + + .. versionadded:: 0.9.0 + + .. versionchanged:: 1.7.3 + CWE information added + + .. versionchanged:: 1.7.5 + Added TLS 1.1 + + """ + + bad_ssl_versions = get_bad_proto_versions(config) + for default in context.function_def_defaults_qual: + val = default.split(".")[-1] + if val in bad_ssl_versions: + return bandit.Issue( + severity=bandit.MEDIUM, + confidence=bandit.MEDIUM, + cwe=issue.Cwe.BROKEN_CRYPTO, + text="Function definition identified with insecure SSL/TLS " + "protocol version by default, possible security " + "issue.", + ) + + +@test.checks("Call") +@test.test_id("B504") +def ssl_with_no_version(context): + """**B504: Test for SSL use with no version specified** + + This plugin is part of a family of tests that detect the use of known bad + versions of SSL/TLS, please see :doc:`../plugins/ssl_with_bad_version` for + a complete discussion. Specifically, This plugin test scans for specific + methods in Python's native SSL/TLS support and the pyOpenSSL module that + configure the version of SSL/TLS protocol to use. These methods are known + to provide default value that maximize compatibility, but permit use of the + aforementioned broken protocol versions. A LOW severity warning will be + reported whenever this is detected. + + **Config Options:** + + This test shares the configuration provided for the standard + :doc:`../plugins/ssl_with_bad_version` test, please refer to its + documentation. + + :Example: + + .. code-block:: none + + >> Issue: ssl.wrap_socket call with no SSL/TLS protocol version + specified, the default SSLv23 could be insecure, possible security + issue. + Severity: Low Confidence: Medium + CWE: CWE-327 (https://cwe.mitre.org/data/definitions/327.html) + Location: ./examples/ssl-insecure-version.py:23 + 22 + 23 ssl.wrap_socket() + 24 + + .. seealso:: + + - :func:`ssl_with_bad_version` + - :func:`ssl_with_bad_defaults` + - https://heartbleed.com/ + - https://en.wikipedia.org/wiki/POODLE + - https://security.openstack.org/guidelines/dg_move-data-securely.html + + .. versionadded:: 0.9.0 + + .. versionchanged:: 1.7.3 + CWE information added + + """ + if context.call_function_name_qual == "ssl.wrap_socket": + if context.check_call_arg_value("ssl_version") is None: + # check_call_arg_value() returns False if the argument is found + # but does not match the supplied value (or the default None). + # It returns None if the arg_name passed doesn't exist. This + # tests for that (ssl_version is not specified). + return bandit.Issue( + severity=bandit.LOW, + confidence=bandit.MEDIUM, + cwe=issue.Cwe.BROKEN_CRYPTO, + text="ssl.wrap_socket call with no SSL/TLS protocol version " + "specified, the default SSLv23 could be insecure, " + "possible security issue.", + lineno=context.get_lineno_for_call_arg("ssl_version"), + ) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/plugins/jinja2_templates.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/plugins/jinja2_templates.py new file mode 100644 index 000000000..3374205fe --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/plugins/jinja2_templates.py @@ -0,0 +1,134 @@ +# +# Copyright 2014 Hewlett-Packard Development Company, L.P. +# +# SPDX-License-Identifier: Apache-2.0 +r""" +========================================== +B701: Test for not auto escaping in jinja2 +========================================== + +Jinja2 is a Python HTML templating system. It is typically used to build web +applications, though appears in other places well, notably the Ansible +automation system. When configuring the Jinja2 environment, the option to use +autoescaping on input can be specified. When autoescaping is enabled, Jinja2 +will filter input strings to escape any HTML content submitted via template +variables. Without escaping HTML input the application becomes vulnerable to +Cross Site Scripting (XSS) attacks. + +Unfortunately, autoescaping is False by default. Thus this plugin test will +warn on omission of an autoescape setting, as well as an explicit setting of +false. A HIGH severity warning is generated in either of these scenarios. + +:Example: + +.. code-block:: none + + >> Issue: Using jinja2 templates with autoescape=False is dangerous and can + lead to XSS. Use autoescape=True to mitigate XSS vulnerabilities. + Severity: High Confidence: High + CWE: CWE-94 (https://cwe.mitre.org/data/definitions/94.html) + Location: ./examples/jinja2_templating.py:11 + 10 templateEnv = jinja2.Environment(autoescape=False, + loader=templateLoader) + 11 Environment(loader=templateLoader, + 12 load=templateLoader, + 13 autoescape=False) + 14 + + >> Issue: By default, jinja2 sets autoescape to False. Consider using + autoescape=True or use the select_autoescape function to mitigate XSS + vulnerabilities. + Severity: High Confidence: High + CWE: CWE-94 (https://cwe.mitre.org/data/definitions/94.html) + Location: ./examples/jinja2_templating.py:15 + 14 + 15 Environment(loader=templateLoader, + 16 load=templateLoader) + 17 + 18 Environment(autoescape=select_autoescape(['html', 'htm', 'xml']), + 19 loader=templateLoader) + + +.. seealso:: + + - `OWASP XSS `__ + - https://realpython.com/primer-on-jinja-templating/ + - https://jinja.palletsprojects.com/en/2.11.x/api/#autoescaping + - https://security.openstack.org/guidelines/dg_cross-site-scripting-xss.html + - https://cwe.mitre.org/data/definitions/94.html + +.. versionadded:: 0.10.0 + +.. versionchanged:: 1.7.3 + CWE information added + +""" +import ast + +import bandit +from bandit.core import issue +from bandit.core import test_properties as test + + +@test.checks("Call") +@test.test_id("B701") +def jinja2_autoescape_false(context): + # check type just to be safe + if isinstance(context.call_function_name_qual, str): + qualname_list = context.call_function_name_qual.split(".") + func = qualname_list[-1] + if "jinja2" in qualname_list and func == "Environment": + for node in ast.walk(context.node): + if isinstance(node, ast.keyword): + # definite autoescape = False + if getattr(node, "arg", None) == "autoescape" and ( + getattr(node.value, "id", None) == "False" + or getattr(node.value, "value", None) is False + ): + return bandit.Issue( + severity=bandit.HIGH, + confidence=bandit.HIGH, + cwe=issue.Cwe.CODE_INJECTION, + text="Using jinja2 templates with autoescape=" + "False is dangerous and can lead to XSS. " + "Use autoescape=True or use the " + "select_autoescape function to mitigate XSS " + "vulnerabilities.", + ) + # found autoescape + if getattr(node, "arg", None) == "autoescape": + value = getattr(node, "value", None) + if ( + getattr(value, "id", None) == "True" + or getattr(value, "value", None) is True + ): + return + # Check if select_autoescape function is used. + elif isinstance(value, ast.Call) and ( + getattr(value.func, "attr", None) + == "select_autoescape" + or getattr(value.func, "id", None) + == "select_autoescape" + ): + return + else: + return bandit.Issue( + severity=bandit.HIGH, + confidence=bandit.MEDIUM, + cwe=issue.Cwe.CODE_INJECTION, + text="Using jinja2 templates with autoescape=" + "False is dangerous and can lead to XSS. " + "Ensure autoescape=True or use the " + "select_autoescape function to mitigate " + "XSS vulnerabilities.", + ) + # We haven't found a keyword named autoescape, indicating default + # behavior + return bandit.Issue( + severity=bandit.HIGH, + confidence=bandit.HIGH, + cwe=issue.Cwe.CODE_INJECTION, + text="By default, jinja2 sets autoescape to False. Consider " + "using autoescape=True or use the select_autoescape " + "function to mitigate XSS vulnerabilities.", + ) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/plugins/logging_config_insecure_listen.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/plugins/logging_config_insecure_listen.py new file mode 100644 index 000000000..96815f036 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/plugins/logging_config_insecure_listen.py @@ -0,0 +1,58 @@ +# Copyright (c) 2022 Rajesh Pangare +# +# SPDX-License-Identifier: Apache-2.0 +r""" +==================================================== +B612: Test for insecure use of logging.config.listen +==================================================== + +This plugin test checks for the unsafe usage of the +``logging.config.listen`` function. The logging.config.listen +function provides the ability to listen for external +configuration files on a socket server. Because portions of the +configuration are passed through eval(), use of this function +may open its users to a security risk. While the function only +binds to a socket on localhost, and so does not accept connections +from remote machines, there are scenarios where untrusted code +could be run under the account of the process which calls listen(). + +logging.config.listen provides the ability to verify bytes received +across the socket with signature verification or encryption/decryption. + +:Example: + +.. code-block:: none + + >> Issue: [B612:logging_config_listen] Use of insecure + logging.config.listen detected. + Severity: Medium Confidence: High + CWE: CWE-94 (https://cwe.mitre.org/data/definitions/94.html) + Location: examples/logging_config_insecure_listen.py:3:4 + 2 + 3 t = logging.config.listen(9999) + +.. seealso:: + + - https://docs.python.org/3/library/logging.config.html#logging.config.listen + +.. versionadded:: 1.7.5 + +""" +import bandit +from bandit.core import issue +from bandit.core import test_properties as test + + +@test.checks("Call") +@test.test_id("B612") +def logging_config_insecure_listen(context): + if ( + context.call_function_name_qual == "logging.config.listen" + and "verify" not in context.call_keywords + ): + return bandit.Issue( + severity=bandit.MEDIUM, + confidence=bandit.HIGH, + cwe=issue.Cwe.CODE_INJECTION, + text="Use of insecure logging.config.listen detected.", + ) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/plugins/mako_templates.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/plugins/mako_templates.py new file mode 100644 index 000000000..21e815105 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/plugins/mako_templates.py @@ -0,0 +1,69 @@ +# +# SPDX-License-Identifier: Apache-2.0 +r""" +==================================== +B702: Test for use of mako templates +==================================== + +Mako is a Python templating system often used to build web applications. It is +the default templating system used in Pylons and Pyramid. Unlike Jinja2 (an +alternative templating system), Mako has no environment wide variable escaping +mechanism. Because of this, all input variables must be carefully escaped +before use to prevent possible vulnerabilities to Cross Site Scripting (XSS) +attacks. + + +:Example: + +.. code-block:: none + + >> Issue: Mako templates allow HTML/JS rendering by default and are + inherently open to XSS attacks. Ensure variables in all templates are + properly sanitized via the 'n', 'h' or 'x' flags (depending on context). + For example, to HTML escape the variable 'data' do ${ data |h }. + Severity: Medium Confidence: High + CWE: CWE-80 (https://cwe.mitre.org/data/definitions/80.html) + Location: ./examples/mako_templating.py:10 + 9 + 10 mako.template.Template("hern") + 11 template.Template("hern") + + +.. seealso:: + + - https://www.makotemplates.org/ + - `OWASP XSS `__ + - https://security.openstack.org/guidelines/dg_cross-site-scripting-xss.html + - https://cwe.mitre.org/data/definitions/80.html + +.. versionadded:: 0.10.0 + +.. versionchanged:: 1.7.3 + CWE information added + +""" +import bandit +from bandit.core import issue +from bandit.core import test_properties as test + + +@test.checks("Call") +@test.test_id("B702") +def use_of_mako_templates(context): + # check type just to be safe + if isinstance(context.call_function_name_qual, str): + qualname_list = context.call_function_name_qual.split(".") + func = qualname_list[-1] + if "mako" in qualname_list and func == "Template": + # unlike Jinja2, mako does not have a template wide autoescape + # feature and thus each variable must be carefully sanitized. + return bandit.Issue( + severity=bandit.MEDIUM, + confidence=bandit.HIGH, + cwe=issue.Cwe.BASIC_XSS, + text="Mako templates allow HTML/JS rendering by default and " + "are inherently open to XSS attacks. Ensure variables " + "in all templates are properly sanitized via the 'n', " + "'h' or 'x' flags (depending on context). For example, " + "to HTML escape the variable 'data' do ${ data |h }.", + ) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/plugins/markupsafe_markup_xss.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/plugins/markupsafe_markup_xss.py new file mode 100644 index 000000000..7eae90509 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/plugins/markupsafe_markup_xss.py @@ -0,0 +1,118 @@ +# Copyright (c) 2025 David Salvisberg +# +# SPDX-License-Identifier: Apache-2.0 +r""" +============================================ +B704: Potential XSS on markupsafe.Markup use +============================================ + +``markupsafe.Markup`` does not perform any escaping, so passing dynamic +content, like f-strings, variables or interpolated strings will potentially +lead to XSS vulnerabilities, especially if that data was submitted by users. + +Instead you should interpolate the resulting ``markupsafe.Markup`` object, +which will perform escaping, or use ``markupsafe.escape``. + + +**Config Options:** + +This plugin allows you to specify additional callable that should be treated +like ``markupsafe.Markup``. By default we recognize ``flask.Markup`` as +an alias, but there are other subclasses or similar classes in the wild +that you may wish to treat the same. + +Additionally there is a whitelist for callable names, whose result may +be safely passed into ``markupsafe.Markup``. This is useful for escape +functions like e.g. ``bleach.clean`` which don't themselves return +``markupsafe.Markup``, so they need to be wrapped. Take care when using +this setting, since incorrect use may introduce false negatives. + +These two options can be set in a shared configuration section +`markupsafe_xss`. + + +.. code-block:: yaml + + markupsafe_xss: + # Recognize additional aliases + extend_markup_names: + - webhelpers.html.literal + - my_package.Markup + + # Allow the output of these functions to pass into Markup + allowed_calls: + - bleach.clean + - my_package.sanitize + + +:Example: + +.. code-block:: none + + >> Issue: [B704:markupsafe_markup_xss] Potential XSS with + ``markupsafe.Markup`` detected. Do not use ``Markup`` + on untrusted data. + Severity: Medium Confidence: High + CWE: CWE-79 (https://cwe.mitre.org/data/definitions/79.html) + Location: ./examples/markupsafe_markup_xss.py:5:0 + 4 content = "" + 5 Markup(f"unsafe {content}") + 6 flask.Markup("unsafe {}".format(content)) + +.. seealso:: + + - https://pypi.org/project/MarkupSafe/ + - https://markupsafe.palletsprojects.com/en/stable/escaping/#markupsafe.Markup + - https://cwe.mitre.org/data/definitions/79.html + +.. versionadded:: 1.8.3 + +""" +import ast + +import bandit +from bandit.core import issue +from bandit.core import test_properties as test +from bandit.core.utils import get_call_name + + +def gen_config(name): + if name == "markupsafe_xss": + return { + "extend_markup_names": [], + "allowed_calls": [], + } + + +@test.takes_config("markupsafe_xss") +@test.checks("Call") +@test.test_id("B704") +def markupsafe_markup_xss(context, config): + + qualname = context.call_function_name_qual + if qualname not in ("markupsafe.Markup", "flask.Markup"): + if qualname not in config.get("extend_markup_names", []): + # not a Markup call + return None + + args = context.node.args + if not args or isinstance(args[0], ast.Constant): + # both no arguments and a constant are fine + return None + + allowed_calls = config.get("allowed_calls", []) + if ( + allowed_calls + and isinstance(args[0], ast.Call) + and get_call_name(args[0], context.import_aliases) in allowed_calls + ): + # the argument contains a whitelisted call + return None + + return bandit.Issue( + severity=bandit.MEDIUM, + confidence=bandit.HIGH, + cwe=issue.Cwe.XSS, + text=f"Potential XSS with ``{qualname}`` detected. Do " + f"not use ``{context.call_function_name}`` on untrusted data.", + ) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/plugins/pytorch_load.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/plugins/pytorch_load.py new file mode 100644 index 000000000..667cbb0d1 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/plugins/pytorch_load.py @@ -0,0 +1,77 @@ +# Copyright (c) 2024 Stacklok, Inc. +# +# SPDX-License-Identifier: Apache-2.0 +r""" +================================== +B614: Test for unsafe PyTorch load +================================== + +This plugin checks for unsafe use of `torch.load` and +`torch.serialization.load`. Using `torch.load` or +`torch.serialization.load` with untrusted data can lead to arbitrary +code execution. There are two safe alternatives: + +1. Use `torch.load` with `weights_only=True` where only tensor data is + extracted, and no arbitrary Python objects are deserialized +2. Use the `safetensors` library from huggingface, which provides a safe + deserialization mechanism + +With `weights_only=True`, PyTorch enforces a strict type check, ensuring +that only torch.Tensor objects are loaded. + +:Example: + +.. code-block:: none + + >> Issue: Use of unsafe PyTorch load + Severity: Medium Confidence: High + CWE: CWE-502 (https://cwe.mitre.org/data/definitions/502.html) + Location: examples/pytorch_load_save.py:8 + 7 loaded_model.load_state_dict(torch.load('model_weights.pth')) + 8 another_model.load_state_dict(torch.load('model_weights.pth', + map_location='cpu')) + 9 + 10 print("Model loaded successfully!") + +.. seealso:: + + - https://cwe.mitre.org/data/definitions/502.html + - https://pytorch.org/docs/stable/generated/torch.load.html#torch.load + - https://github.com/huggingface/safetensors + +.. versionadded:: 1.7.10 + +""" +import bandit +from bandit.core import issue +from bandit.core import test_properties as test + + +@test.checks("Call") +@test.test_id("B614") +def pytorch_load(context): + """ + This plugin checks for unsafe use of `torch.load` and + `torch.serialization.load`. Using `torch.load` or + `torch.serialization.load` with untrusted data can lead to + arbitrary code execution. The safe alternative is to use + `weights_only=True` or the safetensors library. + """ + imported = context.is_module_imported_exact("torch") + qualname = context.call_function_name_qual + if not imported and isinstance(qualname, str): + return + + if qualname in {"torch.load", "torch.serialization.load"}: + # For torch.load, check if weights_only=True is specified + weights_only = context.get_call_arg_value("weights_only") + if weights_only == "True" or weights_only is True: + return + + return bandit.Issue( + severity=bandit.MEDIUM, + confidence=bandit.HIGH, + text="Use of unsafe PyTorch load", + cwe=issue.Cwe.DESERIALIZATION_OF_UNTRUSTED_DATA, + lineno=context.get_lineno_for_call_arg("load"), + ) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/plugins/request_without_timeout.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/plugins/request_without_timeout.py new file mode 100644 index 000000000..c6439001b --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/plugins/request_without_timeout.py @@ -0,0 +1,84 @@ +# SPDX-License-Identifier: Apache-2.0 +r""" +======================================= +B113: Test for missing requests timeout +======================================= + +This plugin test checks for ``requests`` or ``httpx`` calls without a timeout +specified. + +Nearly all production code should use this parameter in nearly all requests, +Failure to do so can cause your program to hang indefinitely. + +When request methods are used without the timeout parameter set, +Bandit will return a MEDIUM severity error. + + +:Example: + +.. code-block:: none + + >> Issue: [B113:request_without_timeout] Call to requests without timeout + Severity: Medium Confidence: Low + CWE: CWE-400 (https://cwe.mitre.org/data/definitions/400.html) + More Info: https://bandit.readthedocs.io/en/latest/plugins/b113_request_without_timeout.html + Location: examples/requests-missing-timeout.py:3:0 + 2 + 3 requests.get('https://gmail.com') + 4 requests.get('https://gmail.com', timeout=None) + + -------------------------------------------------- + >> Issue: [B113:request_without_timeout] Call to requests with timeout set to None + Severity: Medium Confidence: Low + CWE: CWE-400 (https://cwe.mitre.org/data/definitions/400.html) + More Info: https://bandit.readthedocs.io/en/latest/plugins/b113_request_without_timeout.html + Location: examples/requests-missing-timeout.py:4:0 + 3 requests.get('https://gmail.com') + 4 requests.get('https://gmail.com', timeout=None) + 5 requests.get('https://gmail.com', timeout=5) + +.. seealso:: + + - https://requests.readthedocs.io/en/latest/user/advanced/#timeouts + +.. versionadded:: 1.7.5 + +.. versionchanged:: 1.7.10 + Added check for httpx module + +""" # noqa: E501 +import bandit +from bandit.core import issue +from bandit.core import test_properties as test + + +@test.checks("Call") +@test.test_id("B113") +def request_without_timeout(context): + HTTP_VERBS = {"get", "options", "head", "post", "put", "patch", "delete"} + HTTPX_ATTRS = {"request", "stream", "Client", "AsyncClient"} | HTTP_VERBS + qualname = context.call_function_name_qual.split(".")[0] + + if qualname == "requests" and context.call_function_name in HTTP_VERBS: + # check for missing timeout + if context.check_call_arg_value("timeout") is None: + return bandit.Issue( + severity=bandit.MEDIUM, + confidence=bandit.LOW, + cwe=issue.Cwe.UNCONTROLLED_RESOURCE_CONSUMPTION, + text=f"Call to {qualname} without timeout", + ) + if ( + qualname == "requests" + and context.call_function_name in HTTP_VERBS + or qualname == "httpx" + and context.call_function_name in HTTPX_ATTRS + ): + # check for timeout=None + if context.check_call_arg_value("timeout", "None"): + return bandit.Issue( + severity=bandit.MEDIUM, + confidence=bandit.LOW, + cwe=issue.Cwe.UNCONTROLLED_RESOURCE_CONSUMPTION, + text=f"Call to {qualname} with timeout set to None", + ) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/plugins/snmp_security_check.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/plugins/snmp_security_check.py new file mode 100644 index 000000000..a915ed898 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/plugins/snmp_security_check.py @@ -0,0 +1,110 @@ +# +# Copyright (c) 2018 SolarWinds, Inc. +# +# SPDX-License-Identifier: Apache-2.0 +import bandit +from bandit.core import issue +from bandit.core import test_properties as test + + +@test.checks("Call") +@test.test_id("B508") +def snmp_insecure_version_check(context): + """**B508: Checking for insecure SNMP versions** + + This test is for checking for the usage of insecure SNMP version like + v1, v2c + + Please update your code to use more secure versions of SNMP. + + :Example: + + .. code-block:: none + + >> Issue: [B508:snmp_insecure_version_check] The use of SNMPv1 and + SNMPv2 is insecure. You should use SNMPv3 if able. + Severity: Medium Confidence: High + CWE: CWE-319 (https://cwe.mitre.org/data/definitions/319.html) + Location: examples/snmp.py:4:4 + More Info: https://bandit.readthedocs.io/en/latest/plugins/b508_snmp_insecure_version_check.html + 3 # SHOULD FAIL + 4 a = CommunityData('public', mpModel=0) + 5 # SHOULD FAIL + + .. seealso:: + + - http://snmplabs.com/pysnmp/examples/hlapi/asyncore/sync/manager/cmdgen/snmp-versions.html + - https://cwe.mitre.org/data/definitions/319.html + + .. versionadded:: 1.7.2 + + .. versionchanged:: 1.7.3 + CWE information added + + """ # noqa: E501 + + if context.call_function_name_qual == "pysnmp.hlapi.CommunityData": + # We called community data. Lets check our args + if context.check_call_arg_value( + "mpModel", 0 + ) or context.check_call_arg_value("mpModel", 1): + return bandit.Issue( + severity=bandit.MEDIUM, + confidence=bandit.HIGH, + cwe=issue.Cwe.CLEARTEXT_TRANSMISSION, + text="The use of SNMPv1 and SNMPv2 is insecure. " + "You should use SNMPv3 if able.", + lineno=context.get_lineno_for_call_arg("CommunityData"), + ) + + +@test.checks("Call") +@test.test_id("B509") +def snmp_crypto_check(context): + """**B509: Checking for weak cryptography** + + This test is for checking for the usage of insecure SNMP cryptography: + v3 using noAuthNoPriv. + + Please update your code to use more secure versions of SNMP. For example: + + Instead of: + `CommunityData('public', mpModel=0)` + + Use (Defaults to usmHMACMD5AuthProtocol and usmDESPrivProtocol + `UsmUserData("securityName", "authName", "privName")` + + :Example: + + .. code-block:: none + + >> Issue: [B509:snmp_crypto_check] You should not use SNMPv3 without encryption. noAuthNoPriv & authNoPriv is insecure + Severity: Medium CWE: CWE-319 (https://cwe.mitre.org/data/definitions/319.html) Confidence: High + Location: examples/snmp.py:6:11 + More Info: https://bandit.readthedocs.io/en/latest/plugins/b509_snmp_crypto_check.html + 5 # SHOULD FAIL + 6 insecure = UsmUserData("securityName") + 7 # SHOULD FAIL + + .. seealso:: + + - http://snmplabs.com/pysnmp/examples/hlapi/asyncore/sync/manager/cmdgen/snmp-versions.html + - https://cwe.mitre.org/data/definitions/319.html + + .. versionadded:: 1.7.2 + + .. versionchanged:: 1.7.3 + CWE information added + + """ # noqa: E501 + + if context.call_function_name_qual == "pysnmp.hlapi.UsmUserData": + if context.call_args_count < 3: + return bandit.Issue( + severity=bandit.MEDIUM, + confidence=bandit.HIGH, + cwe=issue.Cwe.CLEARTEXT_TRANSMISSION, + text="You should not use SNMPv3 without encryption. " + "noAuthNoPriv & authNoPriv is insecure", + lineno=context.get_lineno_for_call_arg("UsmUserData"), + ) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/plugins/ssh_no_host_key_verification.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/plugins/ssh_no_host_key_verification.py new file mode 100644 index 000000000..51be2eb4a --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/plugins/ssh_no_host_key_verification.py @@ -0,0 +1,76 @@ +# Copyright (c) 2018 VMware, Inc. +# +# SPDX-License-Identifier: Apache-2.0 +r""" +========================================== +B507: Test for missing host key validation +========================================== + +Encryption in general is typically critical to the security of many +applications. Using SSH can greatly increase security by guaranteeing the +identity of the party you are communicating with. This is accomplished by one +or both parties presenting trusted host keys during the connection +initialization phase of SSH. + +When paramiko methods are used, host keys are verified by default. If host key +verification is disabled, Bandit will return a HIGH severity error. + +:Example: + +.. code-block:: none + + >> Issue: [B507:ssh_no_host_key_verification] Paramiko call with policy set + to automatically trust the unknown host key. + Severity: High Confidence: Medium + CWE: CWE-295 (https://cwe.mitre.org/data/definitions/295.html) + Location: examples/no_host_key_verification.py:4 + 3 ssh_client = client.SSHClient() + 4 ssh_client.set_missing_host_key_policy(client.AutoAddPolicy) + 5 ssh_client.set_missing_host_key_policy(client.WarningPolicy) + + +.. versionadded:: 1.5.1 + +.. versionchanged:: 1.7.3 + CWE information added + +""" +import ast + +import bandit +from bandit.core import issue +from bandit.core import test_properties as test + + +@test.checks("Call") +@test.test_id("B507") +def ssh_no_host_key_verification(context): + if ( + context.is_module_imported_like("paramiko") + and context.call_function_name == "set_missing_host_key_policy" + and context.node.args + ): + policy_argument = context.node.args[0] + + policy_argument_value = None + if isinstance(policy_argument, ast.Attribute): + policy_argument_value = policy_argument.attr + elif isinstance(policy_argument, ast.Name): + policy_argument_value = policy_argument.id + elif isinstance(policy_argument, ast.Call): + if isinstance(policy_argument.func, ast.Attribute): + policy_argument_value = policy_argument.func.attr + elif isinstance(policy_argument.func, ast.Name): + policy_argument_value = policy_argument.func.id + + if policy_argument_value in ["AutoAddPolicy", "WarningPolicy"]: + return bandit.Issue( + severity=bandit.HIGH, + confidence=bandit.MEDIUM, + cwe=issue.Cwe.IMPROPER_CERT_VALIDATION, + text="Paramiko call with policy set to automatically trust " + "the unknown host key.", + lineno=context.get_lineno_for_call_arg( + "set_missing_host_key_policy" + ), + ) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/plugins/tarfile_unsafe_members.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/plugins/tarfile_unsafe_members.py new file mode 100644 index 000000000..499a66789 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/plugins/tarfile_unsafe_members.py @@ -0,0 +1,121 @@ +# +# SPDX-License-Identifier: Apache-2.0 +# +r""" +================================= +B202: Test for tarfile.extractall +================================= + +This plugin will look for usage of ``tarfile.extractall()`` + +Severity are set as follows: + +* ``tarfile.extractall(members=function(tarfile))`` - LOW +* ``tarfile.extractall(members=?)`` - member is not a function - MEDIUM +* ``tarfile.extractall()`` - members from the archive is trusted - HIGH + +Use ``tarfile.extractall(members=function_name)`` and define a function +that will inspect each member. Discard files that contain a directory +traversal sequences such as ``../`` or ``\..`` along with all special filetypes +unless you explicitly need them. + +:Example: + +.. code-block:: none + + >> Issue: [B202:tarfile_unsafe_members] tarfile.extractall used without + any validation. You should check members and discard dangerous ones + Severity: High Confidence: High + CWE: CWE-22 (https://cwe.mitre.org/data/definitions/22.html) + Location: examples/tarfile_extractall.py:8 + More Info: + https://bandit.readthedocs.io/en/latest/plugins/b202_tarfile_unsafe_members.html + 7 tar = tarfile.open(filename) + 8 tar.extractall(path=tempfile.mkdtemp()) + 9 tar.close() + + +.. seealso:: + + - https://docs.python.org/3/library/tarfile.html#tarfile.TarFile.extractall + - https://docs.python.org/3/library/tarfile.html#tarfile.TarInfo + +.. versionadded:: 1.7.5 + +.. versionchanged:: 1.7.8 + Added check for filter parameter + +""" +import ast + +import bandit +from bandit.core import issue +from bandit.core import test_properties as test + + +def exec_issue(level, members=""): + if level == bandit.LOW: + return bandit.Issue( + severity=bandit.LOW, + confidence=bandit.LOW, + cwe=issue.Cwe.PATH_TRAVERSAL, + text="Usage of tarfile.extractall(members=function(tarfile)). " + "Make sure your function properly discards dangerous members " + "{members}).".format(members=members), + ) + elif level == bandit.MEDIUM: + return bandit.Issue( + severity=bandit.MEDIUM, + confidence=bandit.MEDIUM, + cwe=issue.Cwe.PATH_TRAVERSAL, + text="Found tarfile.extractall(members=?) but couldn't " + "identify the type of members. " + "Check if the members were properly validated " + "{members}).".format(members=members), + ) + else: + return bandit.Issue( + severity=bandit.HIGH, + confidence=bandit.HIGH, + cwe=issue.Cwe.PATH_TRAVERSAL, + text="tarfile.extractall used without any validation. " + "Please check and discard dangerous members.", + ) + + +def get_members_value(context): + for keyword in context.node.keywords: + if keyword.arg == "members": + arg = keyword.value + if isinstance(arg, ast.Call): + return {"Function": arg.func.id} + else: + value = arg.id if isinstance(arg, ast.Name) else arg + return {"Other": value} + + +def is_filter_data(context): + for keyword in context.node.keywords: + if keyword.arg == "filter": + arg = keyword.value + return isinstance(arg, ast.Constant) and arg.value == "data" + + +@test.test_id("B202") +@test.checks("Call") +def tarfile_unsafe_members(context): + if all( + [ + context.is_module_imported_exact("tarfile"), + "extractall" in context.call_function_name, + ] + ): + if "filter" in context.call_keywords and is_filter_data(context): + return None + if "members" in context.call_keywords: + members = get_members_value(context) + if "Function" in members: + return exec_issue(bandit.LOW, members) + else: + return exec_issue(bandit.MEDIUM, members) + return exec_issue(bandit.HIGH) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/plugins/trojansource.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/plugins/trojansource.py new file mode 100644 index 000000000..68898ab2b --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/plugins/trojansource.py @@ -0,0 +1,82 @@ +# +# SPDX-License-Identifier: Apache-2.0 +r""" +===================================================== +B613: TrojanSource - Bidirectional control characters +===================================================== + +This plugin checks for the presence of unicode bidirectional control characters +in Python source files. Those characters can be embedded in comments and strings +to reorder source code characters in a way that changes its logic. + +:Example: + +.. code-block:: none + + >> Issue: [B613:trojansource] A Python source file contains bidirectional control characters ('\u202e'). + Severity: High Confidence: Medium + CWE: CWE-838 (https://cwe.mitre.org/data/definitions/838.html) + More Info: https://bandit.readthedocs.io/en/1.7.5/plugins/b113_trojansource.html + Location: examples/trojansource.py:4:25 + 3 access_level = "user" + 4 if access_level != 'none' and access_level != 'user': #check if admin + 5 print("You are an admin.\n") + +.. seealso:: + + - https://trojansource.codes/ + - https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-42574 + +.. versionadded:: 1.7.10 + +""" # noqa: E501 +from tokenize import detect_encoding + +import bandit +from bandit.core import issue +from bandit.core import test_properties as test + + +BIDI_CHARACTERS = ( + "\u202a", + "\u202b", + "\u202c", + "\u202d", + "\u202e", + "\u2066", + "\u2067", + "\u2068", + "\u2069", + "\u200f", +) + + +@test.test_id("B613") +@test.checks("File") +def trojansource(context): + src_data = context.file_data + src_data.seek(0) + encoding, _ = detect_encoding(src_data.readline) + src_data.seek(0) + for lineno, line in enumerate( + src_data.read().decode(encoding).splitlines(), start=1 + ): + for char in BIDI_CHARACTERS: + try: + col_offset = line.index(char) + 1 + except ValueError: + continue + text = ( + "A Python source file contains bidirectional" + " control characters (%r)." % char + ) + b_issue = bandit.Issue( + severity=bandit.HIGH, + confidence=bandit.MEDIUM, + cwe=issue.Cwe.INAPPROPRIATE_ENCODING_FOR_OUTPUT_CONTEXT, + text=text, + lineno=lineno, + col_offset=col_offset, + ) + b_issue.linerange = [lineno] + return b_issue diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/plugins/try_except_continue.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/plugins/try_except_continue.py new file mode 100644 index 000000000..c2e3ad493 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/plugins/try_except_continue.py @@ -0,0 +1,108 @@ +# Copyright 2016 IBM Corp. +# Copyright 2014 Hewlett-Packard Development Company, L.P. +# +# SPDX-License-Identifier: Apache-2.0 +r""" +============================================= +B112: Test for a continue in the except block +============================================= + +Errors in Python code bases are typically communicated using ``Exceptions``. +An exception object is 'raised' in the event of an error and can be 'caught' at +a later point in the program, typically some error handling or logging action +will then be performed. + +However, it is possible to catch an exception and silently ignore it while in +a loop. This is illustrated with the following example + +.. code-block:: python + + while keep_going: + try: + do_some_stuff() + except Exception: + continue + +This pattern is considered bad practice in general, but also represents a +potential security issue. A larger than normal volume of errors from a service +can indicate an attempt is being made to disrupt or interfere with it. Thus +errors should, at the very least, be logged. + +There are rare situations where it is desirable to suppress errors, but this is +typically done with specific exception types, rather than the base Exception +class (or no type). To accommodate this, the test may be configured to ignore +'try, except, continue' where the exception is typed. For example, the +following would not generate a warning if the configuration option +``checked_typed_exception`` is set to False: + +.. code-block:: python + + while keep_going: + try: + do_some_stuff() + except ZeroDivisionError: + continue + +**Config Options:** + +.. code-block:: yaml + + try_except_continue: + check_typed_exception: True + + +:Example: + +.. code-block:: none + + >> Issue: Try, Except, Continue detected. + Severity: Low Confidence: High + CWE: CWE-703 (https://cwe.mitre.org/data/definitions/703.html) + Location: ./examples/try_except_continue.py:5 + 4 a = i + 5 except: + 6 continue + +.. seealso:: + + - https://security.openstack.org + - https://cwe.mitre.org/data/definitions/703.html + +.. versionadded:: 1.0.0 + +.. versionchanged:: 1.7.3 + CWE information added + +""" +import ast + +import bandit +from bandit.core import issue +from bandit.core import test_properties as test + + +def gen_config(name): + if name == "try_except_continue": + return {"check_typed_exception": False} + + +@test.takes_config +@test.checks("ExceptHandler") +@test.test_id("B112") +def try_except_continue(context, config): + node = context.node + if len(node.body) == 1: + if ( + not config["check_typed_exception"] + and node.type is not None + and getattr(node.type, "id", None) != "Exception" + ): + return + + if isinstance(node.body[0], ast.Continue): + return bandit.Issue( + severity=bandit.LOW, + confidence=bandit.HIGH, + cwe=issue.Cwe.IMPROPER_CHECK_OF_EXCEPT_COND, + text=("Try, Except, Continue detected."), + ) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/plugins/try_except_pass.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/plugins/try_except_pass.py new file mode 100644 index 000000000..eda0ef800 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/plugins/try_except_pass.py @@ -0,0 +1,106 @@ +# +# Copyright 2014 Hewlett-Packard Development Company, L.P. +# +# SPDX-License-Identifier: Apache-2.0 +r""" +========================================= +B110: Test for a pass in the except block +========================================= + +Errors in Python code bases are typically communicated using ``Exceptions``. +An exception object is 'raised' in the event of an error and can be 'caught' at +a later point in the program, typically some error handling or logging action +will then be performed. + +However, it is possible to catch an exception and silently ignore it. This is +illustrated with the following example + +.. code-block:: python + + try: + do_some_stuff() + except Exception: + pass + +This pattern is considered bad practice in general, but also represents a +potential security issue. A larger than normal volume of errors from a service +can indicate an attempt is being made to disrupt or interfere with it. Thus +errors should, at the very least, be logged. + +There are rare situations where it is desirable to suppress errors, but this is +typically done with specific exception types, rather than the base Exception +class (or no type). To accommodate this, the test may be configured to ignore +'try, except, pass' where the exception is typed. For example, the following +would not generate a warning if the configuration option +``checked_typed_exception`` is set to False: + +.. code-block:: python + + try: + do_some_stuff() + except ZeroDivisionError: + pass + +**Config Options:** + +.. code-block:: yaml + + try_except_pass: + check_typed_exception: True + + +:Example: + +.. code-block:: none + + >> Issue: Try, Except, Pass detected. + Severity: Low Confidence: High + CWE: CWE-703 (https://cwe.mitre.org/data/definitions/703.html) + Location: ./examples/try_except_pass.py:4 + 3 a = 1 + 4 except: + 5 pass + +.. seealso:: + + - https://security.openstack.org + - https://cwe.mitre.org/data/definitions/703.html + +.. versionadded:: 0.13.0 + +.. versionchanged:: 1.7.3 + CWE information added + +""" +import ast + +import bandit +from bandit.core import issue +from bandit.core import test_properties as test + + +def gen_config(name): + if name == "try_except_pass": + return {"check_typed_exception": False} + + +@test.takes_config +@test.checks("ExceptHandler") +@test.test_id("B110") +def try_except_pass(context, config): + node = context.node + if len(node.body) == 1: + if ( + not config["check_typed_exception"] + and node.type is not None + and getattr(node.type, "id", None) != "Exception" + ): + return + + if isinstance(node.body[0], ast.Pass): + return bandit.Issue( + severity=bandit.LOW, + confidence=bandit.HIGH, + cwe=issue.Cwe.IMPROPER_CHECK_OF_EXCEPT_COND, + text=("Try, Except, Pass detected."), + ) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/plugins/weak_cryptographic_key.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/plugins/weak_cryptographic_key.py new file mode 100644 index 000000000..da73ced63 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/plugins/weak_cryptographic_key.py @@ -0,0 +1,165 @@ +# Copyright (c) 2015 VMware, Inc. +# +# SPDX-License-Identifier: Apache-2.0 +r""" +========================================= +B505: Test for weak cryptographic key use +========================================= + +As computational power increases, so does the ability to break ciphers with +smaller key lengths. The recommended key length size for RSA and DSA algorithms +is 2048 and higher. 1024 bits and below are now considered breakable. EC key +length sizes are recommended to be 224 and higher with 160 and below considered +breakable. This plugin test checks for use of any key less than those limits +and returns a high severity error if lower than the lower threshold and a +medium severity error for those lower than the higher threshold. + +:Example: + +.. code-block:: none + + >> Issue: DSA key sizes below 1024 bits are considered breakable. + Severity: High Confidence: High + CWE: CWE-326 (https://cwe.mitre.org/data/definitions/326.html) + Location: examples/weak_cryptographic_key_sizes.py:36 + 35 # Also incorrect: without keyword args + 36 dsa.generate_private_key(512, + 37 backends.default_backend()) + 38 rsa.generate_private_key(3, + +.. seealso:: + + - https://csrc.nist.gov/publications/detail/sp/800-131a/rev-2/final + - https://security.openstack.org/guidelines/dg_strong-crypto.html + - https://cwe.mitre.org/data/definitions/326.html + +.. versionadded:: 0.14.0 + +.. versionchanged:: 1.7.3 + CWE information added + +""" +import bandit +from bandit.core import issue +from bandit.core import test_properties as test + + +def gen_config(name): + if name == "weak_cryptographic_key": + return { + "weak_key_size_dsa_high": 1024, + "weak_key_size_dsa_medium": 2048, + "weak_key_size_rsa_high": 1024, + "weak_key_size_rsa_medium": 2048, + "weak_key_size_ec_high": 160, + "weak_key_size_ec_medium": 224, + } + + +def _classify_key_size(config, key_type, key_size): + if isinstance(key_size, str): + # size provided via a variable - can't process it at the moment + return + + key_sizes = { + "DSA": [ + (config["weak_key_size_dsa_high"], bandit.HIGH), + (config["weak_key_size_dsa_medium"], bandit.MEDIUM), + ], + "RSA": [ + (config["weak_key_size_rsa_high"], bandit.HIGH), + (config["weak_key_size_rsa_medium"], bandit.MEDIUM), + ], + "EC": [ + (config["weak_key_size_ec_high"], bandit.HIGH), + (config["weak_key_size_ec_medium"], bandit.MEDIUM), + ], + } + + for size, level in key_sizes[key_type]: + if key_size < size: + return bandit.Issue( + severity=level, + confidence=bandit.HIGH, + cwe=issue.Cwe.INADEQUATE_ENCRYPTION_STRENGTH, + text="%s key sizes below %d bits are considered breakable. " + % (key_type, size), + ) + + +def _weak_crypto_key_size_cryptography_io(context, config): + func_key_type = { + "cryptography.hazmat.primitives.asymmetric.dsa." + "generate_private_key": "DSA", + "cryptography.hazmat.primitives.asymmetric.rsa." + "generate_private_key": "RSA", + "cryptography.hazmat.primitives.asymmetric.ec." + "generate_private_key": "EC", + } + arg_position = { + "DSA": 0, + "RSA": 1, + "EC": 0, + } + key_type = func_key_type.get(context.call_function_name_qual) + if key_type in ["DSA", "RSA"]: + key_size = ( + context.get_call_arg_value("key_size") + or context.get_call_arg_at_position(arg_position[key_type]) + or 2048 + ) + return _classify_key_size(config, key_type, key_size) + elif key_type == "EC": + curve_key_sizes = { + "SECT571K1": 571, + "SECT571R1": 570, + "SECP521R1": 521, + "BrainpoolP512R1": 512, + "SECT409K1": 409, + "SECT409R1": 409, + "BrainpoolP384R1": 384, + "SECP384R1": 384, + "SECT283K1": 283, + "SECT283R1": 283, + "BrainpoolP256R1": 256, + "SECP256K1": 256, + "SECP256R1": 256, + "SECT233K1": 233, + "SECT233R1": 233, + "SECP224R1": 224, + "SECP192R1": 192, + "SECT163K1": 163, + "SECT163R2": 163, + } + curve = context.get_call_arg_value("curve") or ( + len(context.call_args) > arg_position[key_type] + and context.call_args[arg_position[key_type]] + ) + key_size = curve_key_sizes[curve] if curve in curve_key_sizes else 224 + return _classify_key_size(config, key_type, key_size) + + +def _weak_crypto_key_size_pycrypto(context, config): + func_key_type = { + "Crypto.PublicKey.DSA.generate": "DSA", + "Crypto.PublicKey.RSA.generate": "RSA", + "Cryptodome.PublicKey.DSA.generate": "DSA", + "Cryptodome.PublicKey.RSA.generate": "RSA", + } + key_type = func_key_type.get(context.call_function_name_qual) + if key_type: + key_size = ( + context.get_call_arg_value("bits") + or context.get_call_arg_at_position(0) + or 2048 + ) + return _classify_key_size(config, key_type, key_size) + + +@test.takes_config +@test.checks("Call") +@test.test_id("B505") +def weak_cryptographic_key(context, config): + return _weak_crypto_key_size_cryptography_io( + context, config + ) or _weak_crypto_key_size_pycrypto(context, config) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/plugins/yaml_load.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/plugins/yaml_load.py new file mode 100644 index 000000000..2304c1d7d --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bandit/plugins/yaml_load.py @@ -0,0 +1,76 @@ +# +# Copyright (c) 2016 Rackspace, Inc. +# +# SPDX-License-Identifier: Apache-2.0 +r""" +=============================== +B506: Test for use of yaml load +=============================== + +This plugin test checks for the unsafe usage of the ``yaml.load`` function from +the PyYAML package. The yaml.load function provides the ability to construct +an arbitrary Python object, which may be dangerous if you receive a YAML +document from an untrusted source. The function yaml.safe_load limits this +ability to simple Python objects like integers or lists. + +Please see +https://pyyaml.org/wiki/PyYAMLDocumentation#LoadingYAML for more information +on ``yaml.load`` and yaml.safe_load + +:Example: + +.. code-block:: none + + >> Issue: [yaml_load] Use of unsafe yaml load. Allows instantiation of + arbitrary objects. Consider yaml.safe_load(). + Severity: Medium Confidence: High + CWE: CWE-20 (https://cwe.mitre.org/data/definitions/20.html) + Location: examples/yaml_load.py:5 + 4 ystr = yaml.dump({'a' : 1, 'b' : 2, 'c' : 3}) + 5 y = yaml.load(ystr) + 6 yaml.dump(y) + +.. seealso:: + + - https://pyyaml.org/wiki/PyYAMLDocumentation#LoadingYAML + - https://cwe.mitre.org/data/definitions/20.html + +.. versionadded:: 1.0.0 + +.. versionchanged:: 1.7.3 + CWE information added + +""" +import bandit +from bandit.core import issue +from bandit.core import test_properties as test + + +@test.test_id("B506") +@test.checks("Call") +def yaml_load(context): + imported = context.is_module_imported_exact("yaml") + qualname = context.call_function_name_qual + if not imported and isinstance(qualname, str): + return + + qualname_list = qualname.split(".") + func = qualname_list[-1] + if all( + [ + "yaml" in qualname_list, + func == "load", + not context.check_call_arg_value("Loader", "SafeLoader"), + not context.check_call_arg_value("Loader", "CSafeLoader"), + not context.get_call_arg_at_position(1) == "SafeLoader", + not context.get_call_arg_at_position(1) == "CSafeLoader", + ] + ): + return bandit.Issue( + severity=bandit.MEDIUM, + confidence=bandit.HIGH, + cwe=issue.Cwe.IMPROPER_INPUT_VALIDATION, + text="Use of unsafe yaml load. Allows instantiation of" + " arbitrary objects. Consider yaml.safe_load().", + lineno=context.node.lineno, + ) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bcrypt-5.0.0.dist-info/INSTALLER b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bcrypt-5.0.0.dist-info/INSTALLER new file mode 100644 index 000000000..a1b589e38 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bcrypt-5.0.0.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bcrypt-5.0.0.dist-info/METADATA b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bcrypt-5.0.0.dist-info/METADATA new file mode 100644 index 000000000..629a99275 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bcrypt-5.0.0.dist-info/METADATA @@ -0,0 +1,343 @@ +Metadata-Version: 2.4 +Name: bcrypt +Version: 5.0.0 +Summary: Modern password hashing for your software and your servers +Author-email: The Python Cryptographic Authority developers +License: Apache-2.0 +Project-URL: homepage, https://github.com/pyca/bcrypt/ +Classifier: Development Status :: 5 - Production/Stable +Classifier: License :: OSI Approved :: Apache Software License +Classifier: Programming Language :: Python :: Implementation :: CPython +Classifier: Programming Language :: Python :: Implementation :: PyPy +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3 :: Only +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Programming Language :: Python :: 3.14 +Classifier: Programming Language :: Python :: Free Threading :: 3 - Stable +Requires-Python: >=3.8 +Description-Content-Type: text/x-rst +License-File: LICENSE +Provides-Extra: tests +Requires-Dist: pytest!=3.3.0,>=3.2.1; extra == "tests" +Provides-Extra: typecheck +Requires-Dist: mypy; extra == "typecheck" +Dynamic: license-file + +bcrypt +====== + +.. image:: https://img.shields.io/pypi/v/bcrypt.svg + :target: https://pypi.org/project/bcrypt/ + :alt: Latest Version + +.. image:: https://github.com/pyca/bcrypt/workflows/CI/badge.svg?branch=main + :target: https://github.com/pyca/bcrypt/actions?query=workflow%3ACI+branch%3Amain + +Acceptable password hashing for your software and your servers (but you should +really use argon2id or scrypt) + + +Installation +============ + +To install bcrypt, simply: + +.. code:: console + + $ pip install bcrypt + +Note that bcrypt should build very easily on Linux provided you have a C +compiler and a Rust compiler (the minimum supported Rust version is 1.56.0). + +For Debian and Ubuntu, the following command will ensure that the required dependencies are installed: + +.. code:: console + + $ sudo apt-get install build-essential cargo + +For Fedora and RHEL-derivatives, the following command will ensure that the required dependencies are installed: + +.. code:: console + + $ sudo yum install gcc cargo + +For Alpine, the following command will ensure that the required dependencies are installed: + +.. code:: console + + $ apk add --update musl-dev gcc cargo + + +Alternatives +============ + +While bcrypt remains an acceptable choice for password storage, depending on your specific use case you may also want to consider using scrypt (either via `standard library`_ or `cryptography`_) or argon2id via `argon2_cffi`_. + +Changelog +========= + +5.0.0 +----- + +* Bumped MSRV to 1.74. +* Added support for Python 3.14 and free-threaded Python 3.14. +* Added support for Windows on ARM. +* Passing ``hashpw`` a password longer than 72 bytes now raises a + ``ValueError``. Previously the password was silently truncated, following the + behavior of the original OpenBSD ``bcrypt`` implementation. + +4.3.0 +----- + +* Dropped support for Python 3.7. +* We now support free-threaded Python 3.13. +* We now support PyPy 3.11. +* We now publish wheels for free-threaded Python 3.13, for PyPy 3.11 on + ``manylinux``, and for ARMv7l on ``manylinux``. + +4.2.1 +----- + +* Bump Rust dependency versions - this should resolve crashes on Python 3.13 + free-threaded builds. +* We no longer build ``manylinux`` wheels for PyPy 3.9. + +4.2.0 +----- + +* Bump Rust dependency versions +* Removed the ``BCRYPT_ALLOW_RUST_163`` environment variable. + +4.1.3 +----- + +* Bump Rust dependency versions + +4.1.2 +----- + +* Publish both ``py37`` and ``py39`` wheels. This should resolve some errors + relating to initializing a module multiple times per process. + +4.1.1 +----- + +* Fixed the type signature on the ``kdf`` method. +* Fixed packaging bug on Windows. +* Fixed incompatibility with passlib package detection assumptions. + +4.1.0 +----- + +* Dropped support for Python 3.6. +* Bumped MSRV to 1.64. (Note: Rust 1.63 can be used by setting the ``BCRYPT_ALLOW_RUST_163`` environment variable) + +4.0.1 +----- + +* We now build PyPy ``manylinux`` wheels. +* Fixed a bug where passing an invalid ``salt`` to ``checkpw`` could result in + a ``pyo3_runtime.PanicException``. It now correctly raises a ``ValueError``. + +4.0.0 +----- + +* ``bcrypt`` is now implemented in Rust. Users building from source will need + to have a Rust compiler available. Nothing will change for users downloading + wheels. +* We no longer ship ``manylinux2010`` wheels. Users should upgrade to the latest + ``pip`` to ensure this doesn’t cause issues downloading wheels on their + platform. We now ship ``manylinux_2_28`` wheels for users on new enough platforms. +* ``NUL`` bytes are now allowed in inputs. + + +3.2.2 +----- + +* Fixed packaging of ``py.typed`` files in wheels so that ``mypy`` works. + +3.2.1 +----- + +* Added support for compilation on z/OS +* The next release of ``bcrypt`` with be 4.0 and it will require Rust at + compile time, for users building from source. There will be no additional + requirement for users who are installing from wheels. Users on most + platforms will be able to obtain a wheel by making sure they have an up to + date ``pip``. The minimum supported Rust version will be 1.56.0. +* This will be the final release for which we ship ``manylinux2010`` wheels. + Going forward the minimum supported manylinux ABI for our wheels will be + ``manylinux2014``. The vast majority of users will continue to receive + ``manylinux`` wheels provided they have an up to date ``pip``. + + +3.2.0 +----- + +* Added typehints for library functions. +* Dropped support for Python versions less than 3.6 (2.7, 3.4, 3.5). +* Shipped ``abi3`` Windows wheels (requires pip >= 20). + +3.1.7 +----- + +* Set a ``setuptools`` lower bound for PEP517 wheel building. +* We no longer distribute 32-bit ``manylinux1`` wheels. Continuing to produce + them was a maintenance burden. + +3.1.6 +----- + +* Added support for compilation on Haiku. + +3.1.5 +----- + +* Added support for compilation on AIX. +* Dropped Python 2.6 and 3.3 support. +* Switched to using ``abi3`` wheels for Python 3. If you are not getting a + wheel on a compatible platform please upgrade your ``pip`` version. + +3.1.4 +----- + +* Fixed compilation with mingw and on illumos. + +3.1.3 +----- +* Fixed a compilation issue on Solaris. +* Added a warning when using too few rounds with ``kdf``. + +3.1.2 +----- +* Fixed a compile issue affecting big endian platforms. +* Fixed invalid escape sequence warnings on Python 3.6. +* Fixed building in non-UTF8 environments on Python 2. + +3.1.1 +----- +* Resolved a ``UserWarning`` when used with ``cffi`` 1.8.3. + +3.1.0 +----- +* Added support for ``checkpw``, a convenience method for verifying a password. +* Ensure that you get a ``$2y$`` hash when you input a ``$2y$`` salt. +* Fixed a regression where ``$2a`` hashes were vulnerable to a wraparound bug. +* Fixed compilation under Alpine Linux. + +3.0.0 +----- +* Switched the C backend to code obtained from the OpenBSD project rather than + openwall. +* Added support for ``bcrypt_pbkdf`` via the ``kdf`` function. + +2.0.0 +----- +* Added support for an adjustible prefix when calling ``gensalt``. +* Switched to CFFI 1.0+ + +Usage +----- + +Password Hashing +~~~~~~~~~~~~~~~~ + +Hashing and then later checking that a password matches the previous hashed +password is very simple: + +.. code:: pycon + + >>> import bcrypt + >>> password = b"super secret password" + >>> # Hash a password for the first time, with a randomly-generated salt + >>> hashed = bcrypt.hashpw(password, bcrypt.gensalt()) + >>> # Check that an unhashed password matches one that has previously been + >>> # hashed + >>> if bcrypt.checkpw(password, hashed): + ... print("It Matches!") + ... else: + ... print("It Does not Match :(") + +KDF +~~~ + +As of 3.0.0 ``bcrypt`` now offers a ``kdf`` function which does ``bcrypt_pbkdf``. +This KDF is used in OpenSSH's newer encrypted private key format. + +.. code:: pycon + + >>> import bcrypt + >>> key = bcrypt.kdf( + ... password=b'password', + ... salt=b'salt', + ... desired_key_bytes=32, + ... rounds=100) + + +Adjustable Work Factor +~~~~~~~~~~~~~~~~~~~~~~ +One of bcrypt's features is an adjustable logarithmic work factor. To adjust +the work factor merely pass the desired number of rounds to +``bcrypt.gensalt(rounds=12)`` which defaults to 12): + +.. code:: pycon + + >>> import bcrypt + >>> password = b"super secret password" + >>> # Hash a password for the first time, with a certain number of rounds + >>> hashed = bcrypt.hashpw(password, bcrypt.gensalt(14)) + >>> # Check that a unhashed password matches one that has previously been + >>> # hashed + >>> if bcrypt.checkpw(password, hashed): + ... print("It Matches!") + ... else: + ... print("It Does not Match :(") + + +Adjustable Prefix +~~~~~~~~~~~~~~~~~ + +Another one of bcrypt's features is an adjustable prefix to let you define what +libraries you'll remain compatible with. To adjust this, pass either ``2a`` or +``2b`` (the default) to ``bcrypt.gensalt(prefix=b"2b")`` as a bytes object. + +As of 3.0.0 the ``$2y$`` prefix is still supported in ``hashpw`` but deprecated. + +Maximum Password Length +~~~~~~~~~~~~~~~~~~~~~~~ + +The bcrypt algorithm only handles passwords up to 72 characters, any characters +beyond that are ignored. To work around this, a common approach is to hash a +password with a cryptographic hash (such as ``sha256``) and then base64 +encode it to prevent NULL byte problems before hashing the result with +``bcrypt``: + +.. code:: pycon + + >>> password = b"an incredibly long password" * 10 + >>> hashed = bcrypt.hashpw( + ... base64.b64encode(hashlib.sha256(password).digest()), + ... bcrypt.gensalt() + ... ) + +Compatibility +------------- + +This library should be compatible with py-bcrypt and it will run on Python +3.8+ (including free-threaded builds), and PyPy 3. + +Security +-------- + +``bcrypt`` follows the `same security policy as cryptography`_, if you +identify a vulnerability, we ask you to contact us privately. + +.. _`same security policy as cryptography`: https://cryptography.io/en/latest/security.html +.. _`standard library`: https://docs.python.org/3/library/hashlib.html#hashlib.scrypt +.. _`argon2_cffi`: https://argon2-cffi.readthedocs.io +.. _`cryptography`: https://cryptography.io/en/latest/hazmat/primitives/key-derivation-functions/#cryptography.hazmat.primitives.kdf.scrypt.Scrypt diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bcrypt-5.0.0.dist-info/RECORD b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bcrypt-5.0.0.dist-info/RECORD new file mode 100644 index 000000000..738d9596c --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bcrypt-5.0.0.dist-info/RECORD @@ -0,0 +1,11 @@ +bcrypt-5.0.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +bcrypt-5.0.0.dist-info/METADATA,sha256=yV1BfLlI6udlVy23eNbzDa62DSEbUrlWvlLBCI6UAdI,10524 +bcrypt-5.0.0.dist-info/RECORD,, +bcrypt-5.0.0.dist-info/WHEEL,sha256=WieEZvWpc0Erab6-NfTu9412g-GcE58js6gvBn3Q7B4,111 +bcrypt-5.0.0.dist-info/licenses/LICENSE,sha256=gXPVwptPlW1TJ4HSuG5OMPg-a3h43OGMkZRR1rpwfJA,10850 +bcrypt-5.0.0.dist-info/top_level.txt,sha256=BkR_qBzDbSuycMzHWE1vzXrfYecAzUVmQs6G2CukqNI,7 +bcrypt/__init__.py,sha256=cv-NupIX6P7o6A4PK_F0ur6IZoDr3GnvyzFO9k16wKQ,1000 +bcrypt/__init__.pyi,sha256=ITUCB9mPVU8sKUbJQMDUH5YfQXZb1O55F9qvKZR_o8I,333 +bcrypt/__pycache__/__init__.cpython-312.pyc,, +bcrypt/_bcrypt.abi3.so,sha256=oFwJu4Gq44FqJDttx_oWpypfuUQ30BkCWzD2FhojdYw,631768 +bcrypt/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bcrypt-5.0.0.dist-info/WHEEL b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bcrypt-5.0.0.dist-info/WHEEL new file mode 100644 index 000000000..eb203c1a7 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bcrypt-5.0.0.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: setuptools (80.9.0) +Root-Is-Purelib: false +Tag: cp39-abi3-manylinux_2_34_x86_64 + diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bcrypt-5.0.0.dist-info/licenses/LICENSE b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bcrypt-5.0.0.dist-info/licenses/LICENSE new file mode 100644 index 000000000..11069edd7 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bcrypt-5.0.0.dist-info/licenses/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bcrypt-5.0.0.dist-info/top_level.txt b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bcrypt-5.0.0.dist-info/top_level.txt new file mode 100644 index 000000000..7f0b6e759 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bcrypt-5.0.0.dist-info/top_level.txt @@ -0,0 +1 @@ +bcrypt diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bcrypt/__init__.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bcrypt/__init__.py new file mode 100644 index 000000000..81a92fd42 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bcrypt/__init__.py @@ -0,0 +1,43 @@ +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from ._bcrypt import ( + __author__, + __copyright__, + __email__, + __license__, + __summary__, + __title__, + __uri__, + checkpw, + gensalt, + hashpw, + kdf, +) +from ._bcrypt import ( + __version_ex__ as __version__, +) + +__all__ = [ + "__author__", + "__copyright__", + "__email__", + "__license__", + "__summary__", + "__title__", + "__uri__", + "__version__", + "checkpw", + "gensalt", + "hashpw", + "kdf", +] diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bcrypt/__init__.pyi b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bcrypt/__init__.pyi new file mode 100644 index 000000000..12e4a2ef4 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bcrypt/__init__.pyi @@ -0,0 +1,10 @@ +def gensalt(rounds: int = 12, prefix: bytes = b"2b") -> bytes: ... +def hashpw(password: bytes, salt: bytes) -> bytes: ... +def checkpw(password: bytes, hashed_password: bytes) -> bool: ... +def kdf( + password: bytes, + salt: bytes, + desired_key_bytes: int, + rounds: int, + ignore_few_rounds: bool = False, +) -> bytes: ... diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bcrypt/_bcrypt.abi3.so b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bcrypt/_bcrypt.abi3.so new file mode 100755 index 000000000..4806fec6e Binary files /dev/null and b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bcrypt/_bcrypt.abi3.so differ diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bcrypt/py.typed b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/bcrypt/py.typed new file mode 100644 index 000000000..e69de29bb diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/blinker-1.9.0.dist-info/INSTALLER b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/blinker-1.9.0.dist-info/INSTALLER new file mode 100644 index 000000000..a1b589e38 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/blinker-1.9.0.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/blinker-1.9.0.dist-info/LICENSE.txt b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/blinker-1.9.0.dist-info/LICENSE.txt new file mode 100644 index 000000000..79c9825ad --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/blinker-1.9.0.dist-info/LICENSE.txt @@ -0,0 +1,20 @@ +Copyright 2010 Jason Kirtland + +Permission is hereby granted, free of charge, to any person obtaining a +copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be included +in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/blinker-1.9.0.dist-info/METADATA b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/blinker-1.9.0.dist-info/METADATA new file mode 100644 index 000000000..6d343f571 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/blinker-1.9.0.dist-info/METADATA @@ -0,0 +1,60 @@ +Metadata-Version: 2.3 +Name: blinker +Version: 1.9.0 +Summary: Fast, simple object-to-object and broadcast signaling +Author: Jason Kirtland +Maintainer-email: Pallets Ecosystem +Requires-Python: >=3.9 +Description-Content-Type: text/markdown +Classifier: Development Status :: 5 - Production/Stable +Classifier: License :: OSI Approved :: MIT License +Classifier: Programming Language :: Python +Classifier: Typing :: Typed +Project-URL: Chat, https://discord.gg/pallets +Project-URL: Documentation, https://blinker.readthedocs.io +Project-URL: Source, https://github.com/pallets-eco/blinker/ + +# Blinker + +Blinker provides a fast dispatching system that allows any number of +interested parties to subscribe to events, or "signals". + + +## Pallets Community Ecosystem + +> [!IMPORTANT]\ +> This project is part of the Pallets Community Ecosystem. Pallets is the open +> source organization that maintains Flask; Pallets-Eco enables community +> maintenance of related projects. If you are interested in helping maintain +> this project, please reach out on [the Pallets Discord server][discord]. +> +> [discord]: https://discord.gg/pallets + + +## Example + +Signal receivers can subscribe to specific senders or receive signals +sent by any sender. + +```pycon +>>> from blinker import signal +>>> started = signal('round-started') +>>> def each(round): +... print(f"Round {round}") +... +>>> started.connect(each) + +>>> def round_two(round): +... print("This is round two.") +... +>>> started.connect(round_two, sender=2) + +>>> for round in range(1, 4): +... started.send(round) +... +Round 1! +Round 2! +This is round two. +Round 3! +``` + diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/blinker-1.9.0.dist-info/RECORD b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/blinker-1.9.0.dist-info/RECORD new file mode 100644 index 000000000..7cfb7148a --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/blinker-1.9.0.dist-info/RECORD @@ -0,0 +1,12 @@ +blinker-1.9.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +blinker-1.9.0.dist-info/LICENSE.txt,sha256=nrc6HzhZekqhcCXSrhvjg5Ykx5XphdTw6Xac4p-spGc,1054 +blinker-1.9.0.dist-info/METADATA,sha256=uIRiM8wjjbHkCtbCyTvctU37IAZk0kEe5kxAld1dvzA,1633 +blinker-1.9.0.dist-info/RECORD,, +blinker-1.9.0.dist-info/WHEEL,sha256=CpUCUxeHQbRN5UGRQHYRJorO5Af-Qy_fHMctcQ8DSGI,82 +blinker/__init__.py,sha256=I2EdZqpy4LyjX17Hn1yzJGWCjeLaVaPzsMgHkLfj_cQ,317 +blinker/__pycache__/__init__.cpython-312.pyc,, +blinker/__pycache__/_utilities.cpython-312.pyc,, +blinker/__pycache__/base.cpython-312.pyc,, +blinker/_utilities.py,sha256=0J7eeXXTUx0Ivf8asfpx0ycVkp0Eqfqnj117x2mYX9E,1675 +blinker/base.py,sha256=QpDuvXXcwJF49lUBcH5BiST46Rz9wSG7VW_p7N_027M,19132 +blinker/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/blinker-1.9.0.dist-info/WHEEL b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/blinker-1.9.0.dist-info/WHEEL new file mode 100644 index 000000000..e3c6feefa --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/blinker-1.9.0.dist-info/WHEEL @@ -0,0 +1,4 @@ +Wheel-Version: 1.0 +Generator: flit 3.10.1 +Root-Is-Purelib: true +Tag: py3-none-any diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/blinker/__init__.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/blinker/__init__.py new file mode 100644 index 000000000..1772fa4a5 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/blinker/__init__.py @@ -0,0 +1,17 @@ +from __future__ import annotations + +from .base import ANY +from .base import default_namespace +from .base import NamedSignal +from .base import Namespace +from .base import Signal +from .base import signal + +__all__ = [ + "ANY", + "default_namespace", + "NamedSignal", + "Namespace", + "Signal", + "signal", +] diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/blinker/_utilities.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/blinker/_utilities.py new file mode 100644 index 000000000..000c902a2 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/blinker/_utilities.py @@ -0,0 +1,64 @@ +from __future__ import annotations + +import collections.abc as c +import inspect +import typing as t +from weakref import ref +from weakref import WeakMethod + +T = t.TypeVar("T") + + +class Symbol: + """A constant symbol, nicer than ``object()``. Repeated calls return the + same instance. + + >>> Symbol('foo') is Symbol('foo') + True + >>> Symbol('foo') + foo + """ + + symbols: t.ClassVar[dict[str, Symbol]] = {} + + def __new__(cls, name: str) -> Symbol: + if name in cls.symbols: + return cls.symbols[name] + + obj = super().__new__(cls) + cls.symbols[name] = obj + return obj + + def __init__(self, name: str) -> None: + self.name = name + + def __repr__(self) -> str: + return self.name + + def __getnewargs__(self) -> tuple[t.Any, ...]: + return (self.name,) + + +def make_id(obj: object) -> c.Hashable: + """Get a stable identifier for a receiver or sender, to be used as a dict + key or in a set. + """ + if inspect.ismethod(obj): + # The id of a bound method is not stable, but the id of the unbound + # function and instance are. + return id(obj.__func__), id(obj.__self__) + + if isinstance(obj, (str, int)): + # Instances with the same value always compare equal and have the same + # hash, even if the id may change. + return obj + + # Assume other types are not hashable but will always be the same instance. + return id(obj) + + +def make_ref(obj: T, callback: c.Callable[[ref[T]], None] | None = None) -> ref[T]: + if inspect.ismethod(obj): + return WeakMethod(obj, callback) # type: ignore[arg-type, return-value] + + return ref(obj, callback) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/blinker/base.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/blinker/base.py new file mode 100644 index 000000000..d051b94a3 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/blinker/base.py @@ -0,0 +1,512 @@ +from __future__ import annotations + +import collections.abc as c +import sys +import typing as t +import weakref +from collections import defaultdict +from contextlib import contextmanager +from functools import cached_property +from inspect import iscoroutinefunction + +from ._utilities import make_id +from ._utilities import make_ref +from ._utilities import Symbol + +F = t.TypeVar("F", bound=c.Callable[..., t.Any]) + +ANY = Symbol("ANY") +"""Symbol for "any sender".""" + +ANY_ID = 0 + + +class Signal: + """A notification emitter. + + :param doc: The docstring for the signal. + """ + + ANY = ANY + """An alias for the :data:`~blinker.ANY` sender symbol.""" + + set_class: type[set[t.Any]] = set + """The set class to use for tracking connected receivers and senders. + Python's ``set`` is unordered. If receivers must be dispatched in the order + they were connected, an ordered set implementation can be used. + + .. versionadded:: 1.7 + """ + + @cached_property + def receiver_connected(self) -> Signal: + """Emitted at the end of each :meth:`connect` call. + + The signal sender is the signal instance, and the :meth:`connect` + arguments are passed through: ``receiver``, ``sender``, and ``weak``. + + .. versionadded:: 1.2 + """ + return Signal(doc="Emitted after a receiver connects.") + + @cached_property + def receiver_disconnected(self) -> Signal: + """Emitted at the end of each :meth:`disconnect` call. + + The sender is the signal instance, and the :meth:`disconnect` arguments + are passed through: ``receiver`` and ``sender``. + + This signal is emitted **only** when :meth:`disconnect` is called + explicitly. This signal cannot be emitted by an automatic disconnect + when a weakly referenced receiver or sender goes out of scope, as the + instance is no longer be available to be used as the sender for this + signal. + + An alternative approach is available by subscribing to + :attr:`receiver_connected` and setting up a custom weakref cleanup + callback on weak receivers and senders. + + .. versionadded:: 1.2 + """ + return Signal(doc="Emitted after a receiver disconnects.") + + def __init__(self, doc: str | None = None) -> None: + if doc: + self.__doc__ = doc + + self.receivers: dict[ + t.Any, weakref.ref[c.Callable[..., t.Any]] | c.Callable[..., t.Any] + ] = {} + """The map of connected receivers. Useful to quickly check if any + receivers are connected to the signal: ``if s.receivers:``. The + structure and data is not part of the public API, but checking its + boolean value is. + """ + + self.is_muted: bool = False + self._by_receiver: dict[t.Any, set[t.Any]] = defaultdict(self.set_class) + self._by_sender: dict[t.Any, set[t.Any]] = defaultdict(self.set_class) + self._weak_senders: dict[t.Any, weakref.ref[t.Any]] = {} + + def connect(self, receiver: F, sender: t.Any = ANY, weak: bool = True) -> F: + """Connect ``receiver`` to be called when the signal is sent by + ``sender``. + + :param receiver: The callable to call when :meth:`send` is called with + the given ``sender``, passing ``sender`` as a positional argument + along with any extra keyword arguments. + :param sender: Any object or :data:`ANY`. ``receiver`` will only be + called when :meth:`send` is called with this sender. If ``ANY``, the + receiver will be called for any sender. A receiver may be connected + to multiple senders by calling :meth:`connect` multiple times. + :param weak: Track the receiver with a :mod:`weakref`. The receiver will + be automatically disconnected when it is garbage collected. When + connecting a receiver defined within a function, set to ``False``, + otherwise it will be disconnected when the function scope ends. + """ + receiver_id = make_id(receiver) + sender_id = ANY_ID if sender is ANY else make_id(sender) + + if weak: + self.receivers[receiver_id] = make_ref( + receiver, self._make_cleanup_receiver(receiver_id) + ) + else: + self.receivers[receiver_id] = receiver + + self._by_sender[sender_id].add(receiver_id) + self._by_receiver[receiver_id].add(sender_id) + + if sender is not ANY and sender_id not in self._weak_senders: + # store a cleanup for weakref-able senders + try: + self._weak_senders[sender_id] = make_ref( + sender, self._make_cleanup_sender(sender_id) + ) + except TypeError: + pass + + if "receiver_connected" in self.__dict__ and self.receiver_connected.receivers: + try: + self.receiver_connected.send( + self, receiver=receiver, sender=sender, weak=weak + ) + except TypeError: + # TODO no explanation or test for this + self.disconnect(receiver, sender) + raise + + return receiver + + def connect_via(self, sender: t.Any, weak: bool = False) -> c.Callable[[F], F]: + """Connect the decorated function to be called when the signal is sent + by ``sender``. + + The decorated function will be called when :meth:`send` is called with + the given ``sender``, passing ``sender`` as a positional argument along + with any extra keyword arguments. + + :param sender: Any object or :data:`ANY`. ``receiver`` will only be + called when :meth:`send` is called with this sender. If ``ANY``, the + receiver will be called for any sender. A receiver may be connected + to multiple senders by calling :meth:`connect` multiple times. + :param weak: Track the receiver with a :mod:`weakref`. The receiver will + be automatically disconnected when it is garbage collected. When + connecting a receiver defined within a function, set to ``False``, + otherwise it will be disconnected when the function scope ends.= + + .. versionadded:: 1.1 + """ + + def decorator(fn: F) -> F: + self.connect(fn, sender, weak) + return fn + + return decorator + + @contextmanager + def connected_to( + self, receiver: c.Callable[..., t.Any], sender: t.Any = ANY + ) -> c.Generator[None, None, None]: + """A context manager that temporarily connects ``receiver`` to the + signal while a ``with`` block executes. When the block exits, the + receiver is disconnected. Useful for tests. + + :param receiver: The callable to call when :meth:`send` is called with + the given ``sender``, passing ``sender`` as a positional argument + along with any extra keyword arguments. + :param sender: Any object or :data:`ANY`. ``receiver`` will only be + called when :meth:`send` is called with this sender. If ``ANY``, the + receiver will be called for any sender. + + .. versionadded:: 1.1 + """ + self.connect(receiver, sender=sender, weak=False) + + try: + yield None + finally: + self.disconnect(receiver) + + @contextmanager + def muted(self) -> c.Generator[None, None, None]: + """A context manager that temporarily disables the signal. No receivers + will be called if the signal is sent, until the ``with`` block exits. + Useful for tests. + """ + self.is_muted = True + + try: + yield None + finally: + self.is_muted = False + + def send( + self, + sender: t.Any | None = None, + /, + *, + _async_wrapper: c.Callable[ + [c.Callable[..., c.Coroutine[t.Any, t.Any, t.Any]]], c.Callable[..., t.Any] + ] + | None = None, + **kwargs: t.Any, + ) -> list[tuple[c.Callable[..., t.Any], t.Any]]: + """Call all receivers that are connected to the given ``sender`` + or :data:`ANY`. Each receiver is called with ``sender`` as a positional + argument along with any extra keyword arguments. Return a list of + ``(receiver, return value)`` tuples. + + The order receivers are called is undefined, but can be influenced by + setting :attr:`set_class`. + + If a receiver raises an exception, that exception will propagate up. + This makes debugging straightforward, with an assumption that correctly + implemented receivers will not raise. + + :param sender: Call receivers connected to this sender, in addition to + those connected to :data:`ANY`. + :param _async_wrapper: Will be called on any receivers that are async + coroutines to turn them into sync callables. For example, could run + the receiver with an event loop. + :param kwargs: Extra keyword arguments to pass to each receiver. + + .. versionchanged:: 1.7 + Added the ``_async_wrapper`` argument. + """ + if self.is_muted: + return [] + + results = [] + + for receiver in self.receivers_for(sender): + if iscoroutinefunction(receiver): + if _async_wrapper is None: + raise RuntimeError("Cannot send to a coroutine function.") + + result = _async_wrapper(receiver)(sender, **kwargs) + else: + result = receiver(sender, **kwargs) + + results.append((receiver, result)) + + return results + + async def send_async( + self, + sender: t.Any | None = None, + /, + *, + _sync_wrapper: c.Callable[ + [c.Callable[..., t.Any]], c.Callable[..., c.Coroutine[t.Any, t.Any, t.Any]] + ] + | None = None, + **kwargs: t.Any, + ) -> list[tuple[c.Callable[..., t.Any], t.Any]]: + """Await all receivers that are connected to the given ``sender`` + or :data:`ANY`. Each receiver is called with ``sender`` as a positional + argument along with any extra keyword arguments. Return a list of + ``(receiver, return value)`` tuples. + + The order receivers are called is undefined, but can be influenced by + setting :attr:`set_class`. + + If a receiver raises an exception, that exception will propagate up. + This makes debugging straightforward, with an assumption that correctly + implemented receivers will not raise. + + :param sender: Call receivers connected to this sender, in addition to + those connected to :data:`ANY`. + :param _sync_wrapper: Will be called on any receivers that are sync + callables to turn them into async coroutines. For example, + could call the receiver in a thread. + :param kwargs: Extra keyword arguments to pass to each receiver. + + .. versionadded:: 1.7 + """ + if self.is_muted: + return [] + + results = [] + + for receiver in self.receivers_for(sender): + if not iscoroutinefunction(receiver): + if _sync_wrapper is None: + raise RuntimeError("Cannot send to a non-coroutine function.") + + result = await _sync_wrapper(receiver)(sender, **kwargs) + else: + result = await receiver(sender, **kwargs) + + results.append((receiver, result)) + + return results + + def has_receivers_for(self, sender: t.Any) -> bool: + """Check if there is at least one receiver that will be called with the + given ``sender``. A receiver connected to :data:`ANY` will always be + called, regardless of sender. Does not check if weakly referenced + receivers are still live. See :meth:`receivers_for` for a stronger + search. + + :param sender: Check for receivers connected to this sender, in addition + to those connected to :data:`ANY`. + """ + if not self.receivers: + return False + + if self._by_sender[ANY_ID]: + return True + + if sender is ANY: + return False + + return make_id(sender) in self._by_sender + + def receivers_for( + self, sender: t.Any + ) -> c.Generator[c.Callable[..., t.Any], None, None]: + """Yield each receiver to be called for ``sender``, in addition to those + to be called for :data:`ANY`. Weakly referenced receivers that are not + live will be disconnected and skipped. + + :param sender: Yield receivers connected to this sender, in addition + to those connected to :data:`ANY`. + """ + # TODO: test receivers_for(ANY) + if not self.receivers: + return + + sender_id = make_id(sender) + + if sender_id in self._by_sender: + ids = self._by_sender[ANY_ID] | self._by_sender[sender_id] + else: + ids = self._by_sender[ANY_ID].copy() + + for receiver_id in ids: + receiver = self.receivers.get(receiver_id) + + if receiver is None: + continue + + if isinstance(receiver, weakref.ref): + strong = receiver() + + if strong is None: + self._disconnect(receiver_id, ANY_ID) + continue + + yield strong + else: + yield receiver + + def disconnect(self, receiver: c.Callable[..., t.Any], sender: t.Any = ANY) -> None: + """Disconnect ``receiver`` from being called when the signal is sent by + ``sender``. + + :param receiver: A connected receiver callable. + :param sender: Disconnect from only this sender. By default, disconnect + from all senders. + """ + sender_id: c.Hashable + + if sender is ANY: + sender_id = ANY_ID + else: + sender_id = make_id(sender) + + receiver_id = make_id(receiver) + self._disconnect(receiver_id, sender_id) + + if ( + "receiver_disconnected" in self.__dict__ + and self.receiver_disconnected.receivers + ): + self.receiver_disconnected.send(self, receiver=receiver, sender=sender) + + def _disconnect(self, receiver_id: c.Hashable, sender_id: c.Hashable) -> None: + if sender_id == ANY_ID: + if self._by_receiver.pop(receiver_id, None) is not None: + for bucket in self._by_sender.values(): + bucket.discard(receiver_id) + + self.receivers.pop(receiver_id, None) + else: + self._by_sender[sender_id].discard(receiver_id) + self._by_receiver[receiver_id].discard(sender_id) + + def _make_cleanup_receiver( + self, receiver_id: c.Hashable + ) -> c.Callable[[weakref.ref[c.Callable[..., t.Any]]], None]: + """Create a callback function to disconnect a weakly referenced + receiver when it is garbage collected. + """ + + def cleanup(ref: weakref.ref[c.Callable[..., t.Any]]) -> None: + # If the interpreter is shutting down, disconnecting can result in a + # weird ignored exception. Don't call it in that case. + if not sys.is_finalizing(): + self._disconnect(receiver_id, ANY_ID) + + return cleanup + + def _make_cleanup_sender( + self, sender_id: c.Hashable + ) -> c.Callable[[weakref.ref[t.Any]], None]: + """Create a callback function to disconnect all receivers for a weakly + referenced sender when it is garbage collected. + """ + assert sender_id != ANY_ID + + def cleanup(ref: weakref.ref[t.Any]) -> None: + self._weak_senders.pop(sender_id, None) + + for receiver_id in self._by_sender.pop(sender_id, ()): + self._by_receiver[receiver_id].discard(sender_id) + + return cleanup + + def _cleanup_bookkeeping(self) -> None: + """Prune unused sender/receiver bookkeeping. Not threadsafe. + + Connecting & disconnecting leaves behind a small amount of bookkeeping + data. Typical workloads using Blinker, for example in most web apps, + Flask, CLI scripts, etc., are not adversely affected by this + bookkeeping. + + With a long-running process performing dynamic signal routing with high + volume, e.g. connecting to function closures, senders are all unique + object instances. Doing all of this over and over may cause memory usage + to grow due to extraneous bookkeeping. (An empty ``set`` for each stale + sender/receiver pair.) + + This method will prune that bookkeeping away, with the caveat that such + pruning is not threadsafe. The risk is that cleanup of a fully + disconnected receiver/sender pair occurs while another thread is + connecting that same pair. If you are in the highly dynamic, unique + receiver/sender situation that has lead you to this method, that failure + mode is perhaps not a big deal for you. + """ + for mapping in (self._by_sender, self._by_receiver): + for ident, bucket in list(mapping.items()): + if not bucket: + mapping.pop(ident, None) + + def _clear_state(self) -> None: + """Disconnect all receivers and senders. Useful for tests.""" + self._weak_senders.clear() + self.receivers.clear() + self._by_sender.clear() + self._by_receiver.clear() + + +class NamedSignal(Signal): + """A named generic notification emitter. The name is not used by the signal + itself, but matches the key in the :class:`Namespace` that it belongs to. + + :param name: The name of the signal within the namespace. + :param doc: The docstring for the signal. + """ + + def __init__(self, name: str, doc: str | None = None) -> None: + super().__init__(doc) + + #: The name of this signal. + self.name: str = name + + def __repr__(self) -> str: + base = super().__repr__() + return f"{base[:-1]}; {self.name!r}>" # noqa: E702 + + +class Namespace(dict[str, NamedSignal]): + """A dict mapping names to signals.""" + + def signal(self, name: str, doc: str | None = None) -> NamedSignal: + """Return the :class:`NamedSignal` for the given ``name``, creating it + if required. Repeated calls with the same name return the same signal. + + :param name: The name of the signal. + :param doc: The docstring of the signal. + """ + if name not in self: + self[name] = NamedSignal(name, doc) + + return self[name] + + +class _PNamespaceSignal(t.Protocol): + def __call__(self, name: str, doc: str | None = None) -> NamedSignal: ... + + +default_namespace: Namespace = Namespace() +"""A default :class:`Namespace` for creating named signals. :func:`signal` +creates a :class:`NamedSignal` in this namespace. +""" + +signal: _PNamespaceSignal = default_namespace.signal +"""Return a :class:`NamedSignal` in :data:`default_namespace` with the given +``name``, creating it if required. Repeated calls with the same name return the +same signal. +""" diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/blinker/py.typed b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/blinker/py.typed new file mode 100644 index 000000000..e69de29bb diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/click-8.3.2.dist-info/INSTALLER b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/click-8.3.2.dist-info/INSTALLER new file mode 100644 index 000000000..a1b589e38 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/click-8.3.2.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/click-8.3.2.dist-info/METADATA b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/click-8.3.2.dist-info/METADATA new file mode 100644 index 000000000..00bad311c --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/click-8.3.2.dist-info/METADATA @@ -0,0 +1,84 @@ +Metadata-Version: 2.4 +Name: click +Version: 8.3.2 +Summary: Composable command line interface toolkit +Maintainer-email: Pallets +Requires-Python: >=3.10 +Description-Content-Type: text/markdown +License-Expression: BSD-3-Clause +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: Python +Classifier: Typing :: Typed +License-File: LICENSE.txt +Requires-Dist: colorama; platform_system == 'Windows' +Project-URL: Changes, https://click.palletsprojects.com/page/changes/ +Project-URL: Chat, https://discord.gg/pallets +Project-URL: Documentation, https://click.palletsprojects.com/ +Project-URL: Donate, https://palletsprojects.com/donate +Project-URL: Source, https://github.com/pallets/click/ + +
+ +# Click + +Click is a Python package for creating beautiful command line interfaces +in a composable way with as little code as necessary. It's the "Command +Line Interface Creation Kit". It's highly configurable but comes with +sensible defaults out of the box. + +It aims to make the process of writing command line tools quick and fun +while also preventing any frustration caused by the inability to +implement an intended CLI API. + +Click in three points: + +- Arbitrary nesting of commands +- Automatic help page generation +- Supports lazy loading of subcommands at runtime + + +## A Simple Example + +```python +import click + +@click.command() +@click.option("--count", default=1, help="Number of greetings.") +@click.option("--name", prompt="Your name", help="The person to greet.") +def hello(count, name): + """Simple program that greets NAME for a total of COUNT times.""" + for _ in range(count): + click.echo(f"Hello, {name}!") + +if __name__ == '__main__': + hello() +``` + +``` +$ python hello.py --count=3 +Your name: Click +Hello, Click! +Hello, Click! +Hello, Click! +``` + + +## Donate + +The Pallets organization develops and supports Click and other popular +packages. In order to grow the community of contributors and users, and +allow the maintainers to devote more time to the projects, [please +donate today][]. + +[please donate today]: https://palletsprojects.com/donate + +## Contributing + +See our [detailed contributing documentation][contrib] for many ways to +contribute, including reporting issues, requesting features, asking or answering +questions, and making PRs. + +[contrib]: https://palletsprojects.com/contributing/ + diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/click-8.3.2.dist-info/RECORD b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/click-8.3.2.dist-info/RECORD new file mode 100644 index 000000000..5bd5e90fd --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/click-8.3.2.dist-info/RECORD @@ -0,0 +1,40 @@ +click-8.3.2.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +click-8.3.2.dist-info/METADATA,sha256=yA3Hu5bMxtntTd4QrI8hTFAc58rHSPhDbP6bklbUQkA,2621 +click-8.3.2.dist-info/RECORD,, +click-8.3.2.dist-info/WHEEL,sha256=G2gURzTEtmeR8nrdXUJfNiB3VYVxigPQ-bEQujpNiNs,82 +click-8.3.2.dist-info/licenses/LICENSE.txt,sha256=morRBqOU6FO_4h9C9OctWSgZoigF2ZG18ydQKSkrZY0,1475 +click/__init__.py,sha256=6YyS1aeyknZ0LYweWozNZy0A9nZ_11wmYIhv3cbQrYo,4473 +click/__pycache__/__init__.cpython-312.pyc,, +click/__pycache__/_compat.cpython-312.pyc,, +click/__pycache__/_termui_impl.cpython-312.pyc,, +click/__pycache__/_textwrap.cpython-312.pyc,, +click/__pycache__/_utils.cpython-312.pyc,, +click/__pycache__/_winconsole.cpython-312.pyc,, +click/__pycache__/core.cpython-312.pyc,, +click/__pycache__/decorators.cpython-312.pyc,, +click/__pycache__/exceptions.cpython-312.pyc,, +click/__pycache__/formatting.cpython-312.pyc,, +click/__pycache__/globals.cpython-312.pyc,, +click/__pycache__/parser.cpython-312.pyc,, +click/__pycache__/shell_completion.cpython-312.pyc,, +click/__pycache__/termui.cpython-312.pyc,, +click/__pycache__/testing.cpython-312.pyc,, +click/__pycache__/types.cpython-312.pyc,, +click/__pycache__/utils.cpython-312.pyc,, +click/_compat.py,sha256=v3xBZkFbvA1BXPRkFfBJc6-pIwPI7345m-kQEnpVAs4,18693 +click/_termui_impl.py,sha256=rgCb3On8X5A4200rA5L6i13u5iapmFer7sru57Jy6zA,27093 +click/_textwrap.py,sha256=BOae0RQ6vg3FkNgSJyOoGzG1meGMxJ_ukWVZKx_v-0o,1400 +click/_utils.py,sha256=kZwtTf5gMuCilJJceS2iTCvRvCY-0aN5rJq8gKw7p8g,943 +click/_winconsole.py,sha256=_vxUuUaxwBhoR0vUWCNuHY8VUefiMdCIyU2SXPqoF-A,8465 +click/core.py,sha256=7db9qr_wqXbQriDHCDc26OK0MsaLCSt4yrz14Kn7AEQ,132905 +click/decorators.py,sha256=5P7abhJtAQYp_KHgjUvhMv464ERwOzrv2enNknlwHyQ,18461 +click/exceptions.py,sha256=8utf8w6V5hJXMnO_ic1FNrtbwuEn1NUu1aDwV8UqnG4,9954 +click/formatting.py,sha256=RVfwwr0rwWNpgGr8NaHodPzkIr7_tUyVh_nDdanLMNc,9730 +click/globals.py,sha256=gM-Nh6A4M0HB_SgkaF5M4ncGGMDHc_flHXu9_oh4GEU,1923 +click/parser.py,sha256=Q31pH0FlQZEq-UXE_ABRzlygEfvxPTuZbWNh4xfXmzw,19010 +click/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +click/shell_completion.py,sha256=Cc4GQUFuWpfQBa9sF5qXeeYI7n3tI_1k6ZdSn4BZbT0,20994 +click/termui.py,sha256=hqCEjNndU-nzW08nRAkBaVgfZp_FdCA9KxfIWlKYaMc,31037 +click/testing.py,sha256=LjNfHqNctxc3GfRkLgifO6gnRetblh8yGXzjw4FPFCQ,18978 +click/types.py,sha256=ek54BNSFwPKsqtfT7jsqcc4WHui8AIFVMKM4oVZIXhc,39927 +click/utils.py,sha256=gCUoewdAhA-QLBUUHxrLh4uj6m7T1WjZZMNPvR0I7YA,20257 diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/click-8.3.2.dist-info/WHEEL b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/click-8.3.2.dist-info/WHEEL new file mode 100644 index 000000000..d8b9936da --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/click-8.3.2.dist-info/WHEEL @@ -0,0 +1,4 @@ +Wheel-Version: 1.0 +Generator: flit 3.12.0 +Root-Is-Purelib: true +Tag: py3-none-any diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/click-8.3.2.dist-info/licenses/LICENSE.txt b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/click-8.3.2.dist-info/licenses/LICENSE.txt new file mode 100644 index 000000000..d12a84918 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/click-8.3.2.dist-info/licenses/LICENSE.txt @@ -0,0 +1,28 @@ +Copyright 2014 Pallets + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A +PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED +TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/click/__init__.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/click/__init__.py new file mode 100644 index 000000000..1aa547c57 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/click/__init__.py @@ -0,0 +1,123 @@ +""" +Click is a simple Python module inspired by the stdlib optparse to make +writing command line scripts fun. Unlike other modules, it's based +around a simple API that does not come with too much magic and is +composable. +""" + +from __future__ import annotations + +from .core import Argument as Argument +from .core import Command as Command +from .core import CommandCollection as CommandCollection +from .core import Context as Context +from .core import Group as Group +from .core import Option as Option +from .core import Parameter as Parameter +from .decorators import argument as argument +from .decorators import command as command +from .decorators import confirmation_option as confirmation_option +from .decorators import group as group +from .decorators import help_option as help_option +from .decorators import make_pass_decorator as make_pass_decorator +from .decorators import option as option +from .decorators import pass_context as pass_context +from .decorators import pass_obj as pass_obj +from .decorators import password_option as password_option +from .decorators import version_option as version_option +from .exceptions import Abort as Abort +from .exceptions import BadArgumentUsage as BadArgumentUsage +from .exceptions import BadOptionUsage as BadOptionUsage +from .exceptions import BadParameter as BadParameter +from .exceptions import ClickException as ClickException +from .exceptions import FileError as FileError +from .exceptions import MissingParameter as MissingParameter +from .exceptions import NoSuchOption as NoSuchOption +from .exceptions import UsageError as UsageError +from .formatting import HelpFormatter as HelpFormatter +from .formatting import wrap_text as wrap_text +from .globals import get_current_context as get_current_context +from .termui import clear as clear +from .termui import confirm as confirm +from .termui import echo_via_pager as echo_via_pager +from .termui import edit as edit +from .termui import getchar as getchar +from .termui import launch as launch +from .termui import pause as pause +from .termui import progressbar as progressbar +from .termui import prompt as prompt +from .termui import secho as secho +from .termui import style as style +from .termui import unstyle as unstyle +from .types import BOOL as BOOL +from .types import Choice as Choice +from .types import DateTime as DateTime +from .types import File as File +from .types import FLOAT as FLOAT +from .types import FloatRange as FloatRange +from .types import INT as INT +from .types import IntRange as IntRange +from .types import ParamType as ParamType +from .types import Path as Path +from .types import STRING as STRING +from .types import Tuple as Tuple +from .types import UNPROCESSED as UNPROCESSED +from .types import UUID as UUID +from .utils import echo as echo +from .utils import format_filename as format_filename +from .utils import get_app_dir as get_app_dir +from .utils import get_binary_stream as get_binary_stream +from .utils import get_text_stream as get_text_stream +from .utils import open_file as open_file + + +def __getattr__(name: str) -> object: + import warnings + + if name == "BaseCommand": + from .core import _BaseCommand + + warnings.warn( + "'BaseCommand' is deprecated and will be removed in Click 9.0. Use" + " 'Command' instead.", + DeprecationWarning, + stacklevel=2, + ) + return _BaseCommand + + if name == "MultiCommand": + from .core import _MultiCommand + + warnings.warn( + "'MultiCommand' is deprecated and will be removed in Click 9.0. Use" + " 'Group' instead.", + DeprecationWarning, + stacklevel=2, + ) + return _MultiCommand + + if name == "OptionParser": + from .parser import _OptionParser + + warnings.warn( + "'OptionParser' is deprecated and will be removed in Click 9.0. The" + " old parser is available in 'optparse'.", + DeprecationWarning, + stacklevel=2, + ) + return _OptionParser + + if name == "__version__": + import importlib.metadata + import warnings + + warnings.warn( + "The '__version__' attribute is deprecated and will be removed in" + " Click 9.1. Use feature detection or" + " 'importlib.metadata.version(\"click\")' instead.", + DeprecationWarning, + stacklevel=2, + ) + return importlib.metadata.version("click") + + raise AttributeError(name) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/click/_compat.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/click/_compat.py new file mode 100644 index 000000000..f2726b93a --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/click/_compat.py @@ -0,0 +1,622 @@ +from __future__ import annotations + +import codecs +import collections.abc as cabc +import io +import os +import re +import sys +import typing as t +from types import TracebackType +from weakref import WeakKeyDictionary + +CYGWIN = sys.platform.startswith("cygwin") +WIN = sys.platform.startswith("win") +auto_wrap_for_ansi: t.Callable[[t.TextIO], t.TextIO] | None = None +_ansi_re = re.compile(r"\033\[[;?0-9]*[a-zA-Z]") + + +def _make_text_stream( + stream: t.BinaryIO, + encoding: str | None, + errors: str | None, + force_readable: bool = False, + force_writable: bool = False, +) -> t.TextIO: + if encoding is None: + encoding = get_best_encoding(stream) + if errors is None: + errors = "replace" + return _NonClosingTextIOWrapper( + stream, + encoding, + errors, + line_buffering=True, + force_readable=force_readable, + force_writable=force_writable, + ) + + +def is_ascii_encoding(encoding: str) -> bool: + """Checks if a given encoding is ascii.""" + try: + return codecs.lookup(encoding).name == "ascii" + except LookupError: + return False + + +def get_best_encoding(stream: t.IO[t.Any]) -> str: + """Returns the default stream encoding if not found.""" + rv = getattr(stream, "encoding", None) or sys.getdefaultencoding() + if is_ascii_encoding(rv): + return "utf-8" + return rv + + +class _NonClosingTextIOWrapper(io.TextIOWrapper): + def __init__( + self, + stream: t.BinaryIO, + encoding: str | None, + errors: str | None, + force_readable: bool = False, + force_writable: bool = False, + **extra: t.Any, + ) -> None: + self._stream = stream = t.cast( + t.BinaryIO, _FixupStream(stream, force_readable, force_writable) + ) + super().__init__(stream, encoding, errors, **extra) + + def __del__(self) -> None: + try: + self.detach() + except Exception: + pass + + def isatty(self) -> bool: + # https://bitbucket.org/pypy/pypy/issue/1803 + return self._stream.isatty() + + +class _FixupStream: + """The new io interface needs more from streams than streams + traditionally implement. As such, this fix-up code is necessary in + some circumstances. + + The forcing of readable and writable flags are there because some tools + put badly patched objects on sys (one such offender are certain version + of jupyter notebook). + """ + + def __init__( + self, + stream: t.BinaryIO, + force_readable: bool = False, + force_writable: bool = False, + ): + self._stream = stream + self._force_readable = force_readable + self._force_writable = force_writable + + def __getattr__(self, name: str) -> t.Any: + return getattr(self._stream, name) + + def read1(self, size: int) -> bytes: + f = getattr(self._stream, "read1", None) + + if f is not None: + return t.cast(bytes, f(size)) + + return self._stream.read(size) + + def readable(self) -> bool: + if self._force_readable: + return True + x = getattr(self._stream, "readable", None) + if x is not None: + return t.cast(bool, x()) + try: + self._stream.read(0) + except Exception: + return False + return True + + def writable(self) -> bool: + if self._force_writable: + return True + x = getattr(self._stream, "writable", None) + if x is not None: + return t.cast(bool, x()) + try: + self._stream.write(b"") + except Exception: + try: + self._stream.write(b"") + except Exception: + return False + return True + + def seekable(self) -> bool: + x = getattr(self._stream, "seekable", None) + if x is not None: + return t.cast(bool, x()) + try: + self._stream.seek(self._stream.tell()) + except Exception: + return False + return True + + +def _is_binary_reader(stream: t.IO[t.Any], default: bool = False) -> bool: + try: + return isinstance(stream.read(0), bytes) + except Exception: + return default + # This happens in some cases where the stream was already + # closed. In this case, we assume the default. + + +def _is_binary_writer(stream: t.IO[t.Any], default: bool = False) -> bool: + try: + stream.write(b"") + except Exception: + try: + stream.write("") + return False + except Exception: + pass + return default + return True + + +def _find_binary_reader(stream: t.IO[t.Any]) -> t.BinaryIO | None: + # We need to figure out if the given stream is already binary. + # This can happen because the official docs recommend detaching + # the streams to get binary streams. Some code might do this, so + # we need to deal with this case explicitly. + if _is_binary_reader(stream, False): + return t.cast(t.BinaryIO, stream) + + buf = getattr(stream, "buffer", None) + + # Same situation here; this time we assume that the buffer is + # actually binary in case it's closed. + if buf is not None and _is_binary_reader(buf, True): + return t.cast(t.BinaryIO, buf) + + return None + + +def _find_binary_writer(stream: t.IO[t.Any]) -> t.BinaryIO | None: + # We need to figure out if the given stream is already binary. + # This can happen because the official docs recommend detaching + # the streams to get binary streams. Some code might do this, so + # we need to deal with this case explicitly. + if _is_binary_writer(stream, False): + return t.cast(t.BinaryIO, stream) + + buf = getattr(stream, "buffer", None) + + # Same situation here; this time we assume that the buffer is + # actually binary in case it's closed. + if buf is not None and _is_binary_writer(buf, True): + return t.cast(t.BinaryIO, buf) + + return None + + +def _stream_is_misconfigured(stream: t.TextIO) -> bool: + """A stream is misconfigured if its encoding is ASCII.""" + # If the stream does not have an encoding set, we assume it's set + # to ASCII. This appears to happen in certain unittest + # environments. It's not quite clear what the correct behavior is + # but this at least will force Click to recover somehow. + return is_ascii_encoding(getattr(stream, "encoding", None) or "ascii") + + +def _is_compat_stream_attr(stream: t.TextIO, attr: str, value: str | None) -> bool: + """A stream attribute is compatible if it is equal to the + desired value or the desired value is unset and the attribute + has a value. + """ + stream_value = getattr(stream, attr, None) + return stream_value == value or (value is None and stream_value is not None) + + +def _is_compatible_text_stream( + stream: t.TextIO, encoding: str | None, errors: str | None +) -> bool: + """Check if a stream's encoding and errors attributes are + compatible with the desired values. + """ + return _is_compat_stream_attr( + stream, "encoding", encoding + ) and _is_compat_stream_attr(stream, "errors", errors) + + +def _force_correct_text_stream( + text_stream: t.IO[t.Any], + encoding: str | None, + errors: str | None, + is_binary: t.Callable[[t.IO[t.Any], bool], bool], + find_binary: t.Callable[[t.IO[t.Any]], t.BinaryIO | None], + force_readable: bool = False, + force_writable: bool = False, +) -> t.TextIO: + if is_binary(text_stream, False): + binary_reader = t.cast(t.BinaryIO, text_stream) + else: + text_stream = t.cast(t.TextIO, text_stream) + # If the stream looks compatible, and won't default to a + # misconfigured ascii encoding, return it as-is. + if _is_compatible_text_stream(text_stream, encoding, errors) and not ( + encoding is None and _stream_is_misconfigured(text_stream) + ): + return text_stream + + # Otherwise, get the underlying binary reader. + possible_binary_reader = find_binary(text_stream) + + # If that's not possible, silently use the original reader + # and get mojibake instead of exceptions. + if possible_binary_reader is None: + return text_stream + + binary_reader = possible_binary_reader + + # Default errors to replace instead of strict in order to get + # something that works. + if errors is None: + errors = "replace" + + # Wrap the binary stream in a text stream with the correct + # encoding parameters. + return _make_text_stream( + binary_reader, + encoding, + errors, + force_readable=force_readable, + force_writable=force_writable, + ) + + +def _force_correct_text_reader( + text_reader: t.IO[t.Any], + encoding: str | None, + errors: str | None, + force_readable: bool = False, +) -> t.TextIO: + return _force_correct_text_stream( + text_reader, + encoding, + errors, + _is_binary_reader, + _find_binary_reader, + force_readable=force_readable, + ) + + +def _force_correct_text_writer( + text_writer: t.IO[t.Any], + encoding: str | None, + errors: str | None, + force_writable: bool = False, +) -> t.TextIO: + return _force_correct_text_stream( + text_writer, + encoding, + errors, + _is_binary_writer, + _find_binary_writer, + force_writable=force_writable, + ) + + +def get_binary_stdin() -> t.BinaryIO: + reader = _find_binary_reader(sys.stdin) + if reader is None: + raise RuntimeError("Was not able to determine binary stream for sys.stdin.") + return reader + + +def get_binary_stdout() -> t.BinaryIO: + writer = _find_binary_writer(sys.stdout) + if writer is None: + raise RuntimeError("Was not able to determine binary stream for sys.stdout.") + return writer + + +def get_binary_stderr() -> t.BinaryIO: + writer = _find_binary_writer(sys.stderr) + if writer is None: + raise RuntimeError("Was not able to determine binary stream for sys.stderr.") + return writer + + +def get_text_stdin(encoding: str | None = None, errors: str | None = None) -> t.TextIO: + rv = _get_windows_console_stream(sys.stdin, encoding, errors) + if rv is not None: + return rv + return _force_correct_text_reader(sys.stdin, encoding, errors, force_readable=True) + + +def get_text_stdout(encoding: str | None = None, errors: str | None = None) -> t.TextIO: + rv = _get_windows_console_stream(sys.stdout, encoding, errors) + if rv is not None: + return rv + return _force_correct_text_writer(sys.stdout, encoding, errors, force_writable=True) + + +def get_text_stderr(encoding: str | None = None, errors: str | None = None) -> t.TextIO: + rv = _get_windows_console_stream(sys.stderr, encoding, errors) + if rv is not None: + return rv + return _force_correct_text_writer(sys.stderr, encoding, errors, force_writable=True) + + +def _wrap_io_open( + file: str | os.PathLike[str] | int, + mode: str, + encoding: str | None, + errors: str | None, +) -> t.IO[t.Any]: + """Handles not passing ``encoding`` and ``errors`` in binary mode.""" + if "b" in mode: + return open(file, mode) + + return open(file, mode, encoding=encoding, errors=errors) + + +def open_stream( + filename: str | os.PathLike[str], + mode: str = "r", + encoding: str | None = None, + errors: str | None = "strict", + atomic: bool = False, +) -> tuple[t.IO[t.Any], bool]: + binary = "b" in mode + filename = os.fspath(filename) + + # Standard streams first. These are simple because they ignore the + # atomic flag. Use fsdecode to handle Path("-"). + if os.fsdecode(filename) == "-": + if any(m in mode for m in ["w", "a", "x"]): + if binary: + return get_binary_stdout(), False + return get_text_stdout(encoding=encoding, errors=errors), False + if binary: + return get_binary_stdin(), False + return get_text_stdin(encoding=encoding, errors=errors), False + + # Non-atomic writes directly go out through the regular open functions. + if not atomic: + return _wrap_io_open(filename, mode, encoding, errors), True + + # Some usability stuff for atomic writes + if "a" in mode: + raise ValueError( + "Appending to an existing file is not supported, because that" + " would involve an expensive `copy`-operation to a temporary" + " file. Open the file in normal `w`-mode and copy explicitly" + " if that's what you're after." + ) + if "x" in mode: + raise ValueError("Use the `overwrite`-parameter instead.") + if "w" not in mode: + raise ValueError("Atomic writes only make sense with `w`-mode.") + + # Atomic writes are more complicated. They work by opening a file + # as a proxy in the same folder and then using the fdopen + # functionality to wrap it in a Python file. Then we wrap it in an + # atomic file that moves the file over on close. + import errno + import random + + try: + perm: int | None = os.stat(filename).st_mode + except OSError: + perm = None + + flags = os.O_RDWR | os.O_CREAT | os.O_EXCL + + if binary: + flags |= getattr(os, "O_BINARY", 0) + + while True: + tmp_filename = os.path.join( + os.path.dirname(filename), + f".__atomic-write{random.randrange(1 << 32):08x}", + ) + try: + fd = os.open(tmp_filename, flags, 0o666 if perm is None else perm) + break + except OSError as e: + if e.errno == errno.EEXIST or ( + os.name == "nt" + and e.errno == errno.EACCES + and os.path.isdir(e.filename) + and os.access(e.filename, os.W_OK) + ): + continue + raise + + if perm is not None: + os.chmod(tmp_filename, perm) # in case perm includes bits in umask + + f = _wrap_io_open(fd, mode, encoding, errors) + af = _AtomicFile(f, tmp_filename, os.path.realpath(filename)) + return t.cast(t.IO[t.Any], af), True + + +class _AtomicFile: + def __init__(self, f: t.IO[t.Any], tmp_filename: str, real_filename: str) -> None: + self._f = f + self._tmp_filename = tmp_filename + self._real_filename = real_filename + self.closed = False + + @property + def name(self) -> str: + return self._real_filename + + def close(self, delete: bool = False) -> None: + if self.closed: + return + self._f.close() + os.replace(self._tmp_filename, self._real_filename) + self.closed = True + + def __getattr__(self, name: str) -> t.Any: + return getattr(self._f, name) + + def __enter__(self) -> _AtomicFile: + return self + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_value: BaseException | None, + tb: TracebackType | None, + ) -> None: + self.close(delete=exc_type is not None) + + def __repr__(self) -> str: + return repr(self._f) + + +def strip_ansi(value: str) -> str: + return _ansi_re.sub("", value) + + +def _is_jupyter_kernel_output(stream: t.IO[t.Any]) -> bool: + while isinstance(stream, (_FixupStream, _NonClosingTextIOWrapper)): + stream = stream._stream + + return stream.__class__.__module__.startswith("ipykernel.") + + +def should_strip_ansi( + stream: t.IO[t.Any] | None = None, color: bool | None = None +) -> bool: + if color is None: + if stream is None: + stream = sys.stdin + return not isatty(stream) and not _is_jupyter_kernel_output(stream) + return not color + + +# On Windows, wrap the output streams with colorama to support ANSI +# color codes. +# NOTE: double check is needed so mypy does not analyze this on Linux +if sys.platform.startswith("win") and WIN: + from ._winconsole import _get_windows_console_stream + + def _get_argv_encoding() -> str: + import locale + + return locale.getpreferredencoding() + + _ansi_stream_wrappers: cabc.MutableMapping[t.TextIO, t.TextIO] = WeakKeyDictionary() + + def auto_wrap_for_ansi(stream: t.TextIO, color: bool | None = None) -> t.TextIO: + """Support ANSI color and style codes on Windows by wrapping a + stream with colorama. + """ + try: + cached = _ansi_stream_wrappers.get(stream) + except Exception: + cached = None + + if cached is not None: + return cached + + import colorama + + strip = should_strip_ansi(stream, color) + ansi_wrapper = colorama.AnsiToWin32(stream, strip=strip) + rv = t.cast(t.TextIO, ansi_wrapper.stream) + _write = rv.write + + def _safe_write(s: str) -> int: + try: + return _write(s) + except BaseException: + ansi_wrapper.reset_all() + raise + + rv.write = _safe_write # type: ignore[method-assign] + + try: + _ansi_stream_wrappers[stream] = rv + except Exception: + pass + + return rv + +else: + + def _get_argv_encoding() -> str: + return getattr(sys.stdin, "encoding", None) or sys.getfilesystemencoding() + + def _get_windows_console_stream( + f: t.TextIO, encoding: str | None, errors: str | None + ) -> t.TextIO | None: + return None + + +def term_len(x: str) -> int: + return len(strip_ansi(x)) + + +def isatty(stream: t.IO[t.Any]) -> bool: + try: + return stream.isatty() + except Exception: + return False + + +def _make_cached_stream_func( + src_func: t.Callable[[], t.TextIO | None], + wrapper_func: t.Callable[[], t.TextIO], +) -> t.Callable[[], t.TextIO | None]: + cache: cabc.MutableMapping[t.TextIO, t.TextIO] = WeakKeyDictionary() + + def func() -> t.TextIO | None: + stream = src_func() + + if stream is None: + return None + + try: + rv = cache.get(stream) + except Exception: + rv = None + if rv is not None: + return rv + rv = wrapper_func() + try: + cache[stream] = rv + except Exception: + pass + return rv + + return func + + +_default_text_stdin = _make_cached_stream_func(lambda: sys.stdin, get_text_stdin) +_default_text_stdout = _make_cached_stream_func(lambda: sys.stdout, get_text_stdout) +_default_text_stderr = _make_cached_stream_func(lambda: sys.stderr, get_text_stderr) + + +binary_streams: cabc.Mapping[str, t.Callable[[], t.BinaryIO]] = { + "stdin": get_binary_stdin, + "stdout": get_binary_stdout, + "stderr": get_binary_stderr, +} + +text_streams: cabc.Mapping[str, t.Callable[[str | None, str | None], t.TextIO]] = { + "stdin": get_text_stdin, + "stdout": get_text_stdout, + "stderr": get_text_stderr, +} diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/click/_termui_impl.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/click/_termui_impl.py new file mode 100644 index 000000000..ee8225c4c --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/click/_termui_impl.py @@ -0,0 +1,852 @@ +""" +This module contains implementations for the termui module. To keep the +import time of Click down, some infrequently used functionality is +placed in this module and only imported as needed. +""" + +from __future__ import annotations + +import collections.abc as cabc +import contextlib +import math +import os +import shlex +import sys +import time +import typing as t +from gettext import gettext as _ +from io import StringIO +from pathlib import Path +from types import TracebackType + +from ._compat import _default_text_stdout +from ._compat import CYGWIN +from ._compat import get_best_encoding +from ._compat import isatty +from ._compat import open_stream +from ._compat import strip_ansi +from ._compat import term_len +from ._compat import WIN +from .exceptions import ClickException +from .utils import echo + +V = t.TypeVar("V") + +if os.name == "nt": + BEFORE_BAR = "\r" + AFTER_BAR = "\n" +else: + BEFORE_BAR = "\r\033[?25l" + AFTER_BAR = "\033[?25h\n" + + +class ProgressBar(t.Generic[V]): + def __init__( + self, + iterable: cabc.Iterable[V] | None, + length: int | None = None, + fill_char: str = "#", + empty_char: str = " ", + bar_template: str = "%(bar)s", + info_sep: str = " ", + hidden: bool = False, + show_eta: bool = True, + show_percent: bool | None = None, + show_pos: bool = False, + item_show_func: t.Callable[[V | None], str | None] | None = None, + label: str | None = None, + file: t.TextIO | None = None, + color: bool | None = None, + update_min_steps: int = 1, + width: int = 30, + ) -> None: + self.fill_char = fill_char + self.empty_char = empty_char + self.bar_template = bar_template + self.info_sep = info_sep + self.hidden = hidden + self.show_eta = show_eta + self.show_percent = show_percent + self.show_pos = show_pos + self.item_show_func = item_show_func + self.label: str = label or "" + + if file is None: + file = _default_text_stdout() + + # There are no standard streams attached to write to. For example, + # pythonw on Windows. + if file is None: + file = StringIO() + + self.file = file + self.color = color + self.update_min_steps = update_min_steps + self._completed_intervals = 0 + self.width: int = width + self.autowidth: bool = width == 0 + + if length is None: + from operator import length_hint + + length = length_hint(iterable, -1) + + if length == -1: + length = None + if iterable is None: + if length is None: + raise TypeError("iterable or length is required") + iterable = t.cast("cabc.Iterable[V]", range(length)) + self.iter: cabc.Iterable[V] = iter(iterable) + self.length = length + self.pos: int = 0 + self.avg: list[float] = [] + self.last_eta: float + self.start: float + self.start = self.last_eta = time.time() + self.eta_known: bool = False + self.finished: bool = False + self.max_width: int | None = None + self.entered: bool = False + self.current_item: V | None = None + self._is_atty = isatty(self.file) + self._last_line: str | None = None + + def __enter__(self) -> ProgressBar[V]: + self.entered = True + self.render_progress() + return self + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_value: BaseException | None, + tb: TracebackType | None, + ) -> None: + self.render_finish() + + def __iter__(self) -> cabc.Iterator[V]: + if not self.entered: + raise RuntimeError("You need to use progress bars in a with block.") + self.render_progress() + return self.generator() + + def __next__(self) -> V: + # Iteration is defined in terms of a generator function, + # returned by iter(self); use that to define next(). This works + # because `self.iter` is an iterable consumed by that generator, + # so it is re-entry safe. Calling `next(self.generator())` + # twice works and does "what you want". + return next(iter(self)) + + def render_finish(self) -> None: + if self.hidden or not self._is_atty: + return + self.file.write(AFTER_BAR) + self.file.flush() + + @property + def pct(self) -> float: + if self.finished: + return 1.0 + return min(self.pos / (float(self.length or 1) or 1), 1.0) + + @property + def time_per_iteration(self) -> float: + if not self.avg: + return 0.0 + return sum(self.avg) / float(len(self.avg)) + + @property + def eta(self) -> float: + if self.length is not None and not self.finished: + return self.time_per_iteration * (self.length - self.pos) + return 0.0 + + def format_eta(self) -> str: + if self.eta_known: + t = int(self.eta) + seconds = t % 60 + t //= 60 + minutes = t % 60 + t //= 60 + hours = t % 24 + t //= 24 + if t > 0: + return f"{t}d {hours:02}:{minutes:02}:{seconds:02}" + else: + return f"{hours:02}:{minutes:02}:{seconds:02}" + return "" + + def format_pos(self) -> str: + pos = str(self.pos) + if self.length is not None: + pos += f"/{self.length}" + return pos + + def format_pct(self) -> str: + return f"{int(self.pct * 100): 4}%"[1:] + + def format_bar(self) -> str: + if self.length is not None: + bar_length = int(self.pct * self.width) + bar = self.fill_char * bar_length + bar += self.empty_char * (self.width - bar_length) + elif self.finished: + bar = self.fill_char * self.width + else: + chars = list(self.empty_char * (self.width or 1)) + if self.time_per_iteration != 0: + chars[ + int( + (math.cos(self.pos * self.time_per_iteration) / 2.0 + 0.5) + * self.width + ) + ] = self.fill_char + bar = "".join(chars) + return bar + + def format_progress_line(self) -> str: + show_percent = self.show_percent + + info_bits = [] + if self.length is not None and show_percent is None: + show_percent = not self.show_pos + + if self.show_pos: + info_bits.append(self.format_pos()) + if show_percent: + info_bits.append(self.format_pct()) + if self.show_eta and self.eta_known and not self.finished: + info_bits.append(self.format_eta()) + if self.item_show_func is not None: + item_info = self.item_show_func(self.current_item) + if item_info is not None: + info_bits.append(item_info) + + return ( + self.bar_template + % { + "label": self.label, + "bar": self.format_bar(), + "info": self.info_sep.join(info_bits), + } + ).rstrip() + + def render_progress(self) -> None: + if self.hidden: + return + + if not self._is_atty: + # Only output the label once if the output is not a TTY. + if self._last_line != self.label: + self._last_line = self.label + echo(self.label, file=self.file, color=self.color) + return + + buf = [] + # Update width in case the terminal has been resized + if self.autowidth: + import shutil + + old_width = self.width + self.width = 0 + clutter_length = term_len(self.format_progress_line()) + new_width = max(0, shutil.get_terminal_size().columns - clutter_length) + if new_width < old_width and self.max_width is not None: + buf.append(BEFORE_BAR) + buf.append(" " * self.max_width) + self.max_width = new_width + self.width = new_width + + clear_width = self.width + if self.max_width is not None: + clear_width = self.max_width + + buf.append(BEFORE_BAR) + line = self.format_progress_line() + line_len = term_len(line) + if self.max_width is None or self.max_width < line_len: + self.max_width = line_len + + buf.append(line) + buf.append(" " * (clear_width - line_len)) + line = "".join(buf) + # Render the line only if it changed. + + if line != self._last_line: + self._last_line = line + echo(line, file=self.file, color=self.color, nl=False) + self.file.flush() + + def make_step(self, n_steps: int) -> None: + self.pos += n_steps + if self.length is not None and self.pos >= self.length: + self.finished = True + + if (time.time() - self.last_eta) < 1.0: + return + + self.last_eta = time.time() + + # self.avg is a rolling list of length <= 7 of steps where steps are + # defined as time elapsed divided by the total progress through + # self.length. + if self.pos: + step = (time.time() - self.start) / self.pos + else: + step = time.time() - self.start + + self.avg = self.avg[-6:] + [step] + + self.eta_known = self.length is not None + + def update(self, n_steps: int, current_item: V | None = None) -> None: + """Update the progress bar by advancing a specified number of + steps, and optionally set the ``current_item`` for this new + position. + + :param n_steps: Number of steps to advance. + :param current_item: Optional item to set as ``current_item`` + for the updated position. + + .. versionchanged:: 8.0 + Added the ``current_item`` optional parameter. + + .. versionchanged:: 8.0 + Only render when the number of steps meets the + ``update_min_steps`` threshold. + """ + if current_item is not None: + self.current_item = current_item + + self._completed_intervals += n_steps + + if self._completed_intervals >= self.update_min_steps: + self.make_step(self._completed_intervals) + self.render_progress() + self._completed_intervals = 0 + + def finish(self) -> None: + self.eta_known = False + self.current_item = None + self.finished = True + + def generator(self) -> cabc.Iterator[V]: + """Return a generator which yields the items added to the bar + during construction, and updates the progress bar *after* the + yielded block returns. + """ + # WARNING: the iterator interface for `ProgressBar` relies on + # this and only works because this is a simple generator which + # doesn't create or manage additional state. If this function + # changes, the impact should be evaluated both against + # `iter(bar)` and `next(bar)`. `next()` in particular may call + # `self.generator()` repeatedly, and this must remain safe in + # order for that interface to work. + if not self.entered: + raise RuntimeError("You need to use progress bars in a with block.") + + if not self._is_atty: + yield from self.iter + else: + for rv in self.iter: + self.current_item = rv + + # This allows show_item_func to be updated before the + # item is processed. Only trigger at the beginning of + # the update interval. + if self._completed_intervals == 0: + self.render_progress() + + yield rv + self.update(1) + + self.finish() + self.render_progress() + + +def pager(generator: cabc.Iterable[str], color: bool | None = None) -> None: + """Decide what method to use for paging through text.""" + stdout = _default_text_stdout() + + # There are no standard streams attached to write to. For example, + # pythonw on Windows. + if stdout is None: + stdout = StringIO() + + if not isatty(sys.stdin) or not isatty(stdout): + return _nullpager(stdout, generator, color) + + # Split and normalize the pager command into parts. + pager_cmd_parts = shlex.split(os.environ.get("PAGER", ""), posix=False) + if pager_cmd_parts: + if WIN: + if _tempfilepager(generator, pager_cmd_parts, color): + return + elif _pipepager(generator, pager_cmd_parts, color): + return + + if os.environ.get("TERM") in ("dumb", "emacs"): + return _nullpager(stdout, generator, color) + if (WIN or sys.platform.startswith("os2")) and _tempfilepager( + generator, ["more"], color + ): + return + if _pipepager(generator, ["less"], color): + return + + import tempfile + + fd, filename = tempfile.mkstemp() + os.close(fd) + try: + if _pipepager(generator, ["more"], color): + return + return _nullpager(stdout, generator, color) + finally: + os.unlink(filename) + + +def _pipepager( + generator: cabc.Iterable[str], cmd_parts: list[str], color: bool | None +) -> bool: + """Page through text by feeding it to another program. Invoking a + pager through this might support colors. + + Returns `True` if the command was found, `False` otherwise and thus another + pager should be attempted. + """ + # Split the command into the invoked CLI and its parameters. + if not cmd_parts: + return False + + import shutil + + cmd = cmd_parts[0] + cmd_params = cmd_parts[1:] + + cmd_filepath = shutil.which(cmd) + if not cmd_filepath: + return False + + # Produces a normalized absolute path string. + # multi-call binaries such as busybox derive their identity from the symlink + # less -> busybox. resolve() causes them to misbehave. (eg. less becomes busybox) + cmd_path = Path(cmd_filepath).absolute() + cmd_name = cmd_path.name + + import subprocess + + # Make a local copy of the environment to not affect the global one. + env = dict(os.environ) + + # If we're piping to less and the user hasn't decided on colors, we enable + # them by default we find the -R flag in the command line arguments. + if color is None and cmd_name == "less": + less_flags = f"{os.environ.get('LESS', '')}{' '.join(cmd_params)}" + if not less_flags: + env["LESS"] = "-R" + color = True + elif "r" in less_flags or "R" in less_flags: + color = True + + c = subprocess.Popen( + [str(cmd_path)] + cmd_params, + shell=False, + stdin=subprocess.PIPE, + env=env, + errors="replace", + text=True, + ) + assert c.stdin is not None + try: + for text in generator: + if not color: + text = strip_ansi(text) + + c.stdin.write(text) + except BrokenPipeError: + # In case the pager exited unexpectedly, ignore the broken pipe error. + pass + except Exception as e: + # In case there is an exception we want to close the pager immediately + # and let the caller handle it. + # Otherwise the pager will keep running, and the user may not notice + # the error message, or worse yet it may leave the terminal in a broken state. + c.terminate() + raise e + finally: + # We must close stdin and wait for the pager to exit before we continue + try: + c.stdin.close() + # Close implies flush, so it might throw a BrokenPipeError if the pager + # process exited already. + except BrokenPipeError: + pass + + # Less doesn't respect ^C, but catches it for its own UI purposes (aborting + # search or other commands inside less). + # + # That means when the user hits ^C, the parent process (click) terminates, + # but less is still alive, paging the output and messing up the terminal. + # + # If the user wants to make the pager exit on ^C, they should set + # `LESS='-K'`. It's not our decision to make. + while True: + try: + c.wait() + except KeyboardInterrupt: + pass + else: + break + + return True + + +def _tempfilepager( + generator: cabc.Iterable[str], cmd_parts: list[str], color: bool | None +) -> bool: + """Page through text by invoking a program on a temporary file. + + Returns `True` if the command was found, `False` otherwise and thus another + pager should be attempted. + """ + # Split the command into the invoked CLI and its parameters. + if not cmd_parts: + return False + + import shutil + + cmd = cmd_parts[0] + + cmd_filepath = shutil.which(cmd) + if not cmd_filepath: + return False + # Produces a normalized absolute path string. + # multi-call binaries such as busybox derive their identity from the symlink + # less -> busybox. resolve() causes them to misbehave. (eg. less becomes busybox) + cmd_path = Path(cmd_filepath).absolute() + + import subprocess + import tempfile + + fd, filename = tempfile.mkstemp() + # TODO: This never terminates if the passed generator never terminates. + text = "".join(generator) + if not color: + text = strip_ansi(text) + encoding = get_best_encoding(sys.stdout) + with open_stream(filename, "wb")[0] as f: + f.write(text.encode(encoding)) + try: + subprocess.call([str(cmd_path), filename]) + except OSError: + # Command not found + pass + finally: + os.close(fd) + os.unlink(filename) + + return True + + +def _nullpager( + stream: t.TextIO, generator: cabc.Iterable[str], color: bool | None +) -> None: + """Simply print unformatted text. This is the ultimate fallback.""" + for text in generator: + if not color: + text = strip_ansi(text) + stream.write(text) + + +class Editor: + def __init__( + self, + editor: str | None = None, + env: cabc.Mapping[str, str] | None = None, + require_save: bool = True, + extension: str = ".txt", + ) -> None: + self.editor = editor + self.env = env + self.require_save = require_save + self.extension = extension + + def get_editor(self) -> str: + if self.editor is not None: + return self.editor + for key in "VISUAL", "EDITOR": + rv = os.environ.get(key) + if rv: + return rv + if WIN: + return "notepad" + + from shutil import which + + for editor in "sensible-editor", "vim", "nano": + if which(editor) is not None: + return editor + return "vi" + + def edit_files(self, filenames: cabc.Iterable[str]) -> None: + import subprocess + + editor = self.get_editor() + environ: dict[str, str] | None = None + + if self.env: + environ = os.environ.copy() + environ.update(self.env) + + exc_filename = " ".join(f'"{filename}"' for filename in filenames) + + try: + c = subprocess.Popen( + args=f"{editor} {exc_filename}", env=environ, shell=True + ) + exit_code = c.wait() + if exit_code != 0: + raise ClickException( + _("{editor}: Editing failed").format(editor=editor) + ) + except OSError as e: + raise ClickException( + _("{editor}: Editing failed: {e}").format(editor=editor, e=e) + ) from e + + @t.overload + def edit(self, text: bytes | bytearray) -> bytes | None: ... + + # We cannot know whether or not the type expected is str or bytes when None + # is passed, so str is returned as that was what was done before. + @t.overload + def edit(self, text: str | None) -> str | None: ... + + def edit(self, text: str | bytes | bytearray | None) -> str | bytes | None: + import tempfile + + if text is None: + data: bytes | bytearray = b"" + elif isinstance(text, (bytes, bytearray)): + data = text + else: + if text and not text.endswith("\n"): + text += "\n" + + if WIN: + data = text.replace("\n", "\r\n").encode("utf-8-sig") + else: + data = text.encode("utf-8") + + fd, name = tempfile.mkstemp(prefix="editor-", suffix=self.extension) + f: t.BinaryIO + + try: + with os.fdopen(fd, "wb") as f: + f.write(data) + + # If the filesystem resolution is 1 second, like Mac OS + # 10.12 Extended, or 2 seconds, like FAT32, and the editor + # closes very fast, require_save can fail. Set the modified + # time to be 2 seconds in the past to work around this. + os.utime(name, (os.path.getatime(name), os.path.getmtime(name) - 2)) + # Depending on the resolution, the exact value might not be + # recorded, so get the new recorded value. + timestamp = os.path.getmtime(name) + + self.edit_files((name,)) + + if self.require_save and os.path.getmtime(name) == timestamp: + return None + + with open(name, "rb") as f: + rv = f.read() + + if isinstance(text, (bytes, bytearray)): + return rv + + return rv.decode("utf-8-sig").replace("\r\n", "\n") + finally: + os.unlink(name) + + +def open_url(url: str, wait: bool = False, locate: bool = False) -> int: + import subprocess + + def _unquote_file(url: str) -> str: + from urllib.parse import unquote + + if url.startswith("file://"): + url = unquote(url[7:]) + + return url + + if sys.platform == "darwin": + args = ["open"] + if wait: + args.append("-W") + if locate: + args.append("-R") + args.append(_unquote_file(url)) + null = open("/dev/null", "w") + try: + return subprocess.Popen(args, stderr=null).wait() + finally: + null.close() + elif WIN: + if locate: + url = _unquote_file(url) + args = ["explorer", f"/select,{url}"] + else: + args = ["start"] + if wait: + args.append("/WAIT") + args.append("") + args.append(url) + try: + return subprocess.call(args) + except OSError: + # Command not found + return 127 + elif CYGWIN: + if locate: + url = _unquote_file(url) + args = ["cygstart", os.path.dirname(url)] + else: + args = ["cygstart"] + if wait: + args.append("-w") + args.append(url) + try: + return subprocess.call(args) + except OSError: + # Command not found + return 127 + + try: + if locate: + url = os.path.dirname(_unquote_file(url)) or "." + else: + url = _unquote_file(url) + c = subprocess.Popen(["xdg-open", url]) + if wait: + return c.wait() + return 0 + except OSError: + if url.startswith(("http://", "https://")) and not locate and not wait: + import webbrowser + + webbrowser.open(url) + return 0 + return 1 + + +def _translate_ch_to_exc(ch: str) -> None: + if ch == "\x03": + raise KeyboardInterrupt() + + if ch == "\x04" and not WIN: # Unix-like, Ctrl+D + raise EOFError() + + if ch == "\x1a" and WIN: # Windows, Ctrl+Z + raise EOFError() + + return None + + +if sys.platform == "win32": + import msvcrt + + @contextlib.contextmanager + def raw_terminal() -> cabc.Iterator[int]: + yield -1 + + def getchar(echo: bool) -> str: + # The function `getch` will return a bytes object corresponding to + # the pressed character. Since Windows 10 build 1803, it will also + # return \x00 when called a second time after pressing a regular key. + # + # `getwch` does not share this probably-bugged behavior. Moreover, it + # returns a Unicode object by default, which is what we want. + # + # Either of these functions will return \x00 or \xe0 to indicate + # a special key, and you need to call the same function again to get + # the "rest" of the code. The fun part is that \u00e0 is + # "latin small letter a with grave", so if you type that on a French + # keyboard, you _also_ get a \xe0. + # E.g., consider the Up arrow. This returns \xe0 and then \x48. The + # resulting Unicode string reads as "a with grave" + "capital H". + # This is indistinguishable from when the user actually types + # "a with grave" and then "capital H". + # + # When \xe0 is returned, we assume it's part of a special-key sequence + # and call `getwch` again, but that means that when the user types + # the \u00e0 character, `getchar` doesn't return until a second + # character is typed. + # The alternative is returning immediately, but that would mess up + # cross-platform handling of arrow keys and others that start with + # \xe0. Another option is using `getch`, but then we can't reliably + # read non-ASCII characters, because return values of `getch` are + # limited to the current 8-bit codepage. + # + # Anyway, Click doesn't claim to do this Right(tm), and using `getwch` + # is doing the right thing in more situations than with `getch`. + + if echo: + func = t.cast(t.Callable[[], str], msvcrt.getwche) + else: + func = t.cast(t.Callable[[], str], msvcrt.getwch) + + rv = func() + + if rv in ("\x00", "\xe0"): + # \x00 and \xe0 are control characters that indicate special key, + # see above. + rv += func() + + _translate_ch_to_exc(rv) + return rv + +else: + import termios + import tty + + @contextlib.contextmanager + def raw_terminal() -> cabc.Iterator[int]: + f: t.TextIO | None + fd: int + + if not isatty(sys.stdin): + f = open("/dev/tty") + fd = f.fileno() + else: + fd = sys.stdin.fileno() + f = None + + try: + old_settings = termios.tcgetattr(fd) + + try: + tty.setraw(fd) + yield fd + finally: + termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) + sys.stdout.flush() + + if f is not None: + f.close() + except termios.error: + pass + + def getchar(echo: bool) -> str: + with raw_terminal() as fd: + ch = os.read(fd, 32).decode(get_best_encoding(sys.stdin), "replace") + + if echo and isatty(sys.stdout): + sys.stdout.write(ch) + + _translate_ch_to_exc(ch) + return ch diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/click/_textwrap.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/click/_textwrap.py new file mode 100644 index 000000000..97fbee3dc --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/click/_textwrap.py @@ -0,0 +1,51 @@ +from __future__ import annotations + +import collections.abc as cabc +import textwrap +from contextlib import contextmanager + + +class TextWrapper(textwrap.TextWrapper): + def _handle_long_word( + self, + reversed_chunks: list[str], + cur_line: list[str], + cur_len: int, + width: int, + ) -> None: + space_left = max(width - cur_len, 1) + + if self.break_long_words: + last = reversed_chunks[-1] + cut = last[:space_left] + res = last[space_left:] + cur_line.append(cut) + reversed_chunks[-1] = res + elif not cur_line: + cur_line.append(reversed_chunks.pop()) + + @contextmanager + def extra_indent(self, indent: str) -> cabc.Iterator[None]: + old_initial_indent = self.initial_indent + old_subsequent_indent = self.subsequent_indent + self.initial_indent += indent + self.subsequent_indent += indent + + try: + yield + finally: + self.initial_indent = old_initial_indent + self.subsequent_indent = old_subsequent_indent + + def indent_only(self, text: str) -> str: + rv = [] + + for idx, line in enumerate(text.splitlines()): + indent = self.initial_indent + + if idx > 0: + indent = self.subsequent_indent + + rv.append(f"{indent}{line}") + + return "\n".join(rv) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/click/_utils.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/click/_utils.py new file mode 100644 index 000000000..09fb00855 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/click/_utils.py @@ -0,0 +1,36 @@ +from __future__ import annotations + +import enum +import typing as t + + +class Sentinel(enum.Enum): + """Enum used to define sentinel values. + + .. seealso:: + + `PEP 661 - Sentinel Values `_. + """ + + UNSET = object() + FLAG_NEEDS_VALUE = object() + + def __repr__(self) -> str: + return f"{self.__class__.__name__}.{self.name}" + + +UNSET = Sentinel.UNSET +"""Sentinel used to indicate that a value is not set.""" + +FLAG_NEEDS_VALUE = Sentinel.FLAG_NEEDS_VALUE +"""Sentinel used to indicate an option was passed as a flag without a +value but is not a flag option. + +``Option.consume_value`` uses this to prompt or use the ``flag_value``. +""" + +T_UNSET = t.Literal[UNSET] # type: ignore[valid-type] +"""Type hint for the :data:`UNSET` sentinel value.""" + +T_FLAG_NEEDS_VALUE = t.Literal[FLAG_NEEDS_VALUE] # type: ignore[valid-type] +"""Type hint for the :data:`FLAG_NEEDS_VALUE` sentinel value.""" diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/click/_winconsole.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/click/_winconsole.py new file mode 100644 index 000000000..e56c7c6ae --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/click/_winconsole.py @@ -0,0 +1,296 @@ +# This module is based on the excellent work by Adam Bartoš who +# provided a lot of what went into the implementation here in +# the discussion to issue1602 in the Python bug tracker. +# +# There are some general differences in regards to how this works +# compared to the original patches as we do not need to patch +# the entire interpreter but just work in our little world of +# echo and prompt. +from __future__ import annotations + +import collections.abc as cabc +import io +import sys +import time +import typing as t +from ctypes import Array +from ctypes import byref +from ctypes import c_char +from ctypes import c_char_p +from ctypes import c_int +from ctypes import c_ssize_t +from ctypes import c_ulong +from ctypes import c_void_p +from ctypes import POINTER +from ctypes import py_object +from ctypes import Structure +from ctypes.wintypes import DWORD +from ctypes.wintypes import HANDLE +from ctypes.wintypes import LPCWSTR +from ctypes.wintypes import LPWSTR + +from ._compat import _NonClosingTextIOWrapper + +assert sys.platform == "win32" +import msvcrt # noqa: E402 +from ctypes import windll # noqa: E402 +from ctypes import WINFUNCTYPE # noqa: E402 + +c_ssize_p = POINTER(c_ssize_t) + +kernel32 = windll.kernel32 +GetStdHandle = kernel32.GetStdHandle +ReadConsoleW = kernel32.ReadConsoleW +WriteConsoleW = kernel32.WriteConsoleW +GetConsoleMode = kernel32.GetConsoleMode +GetLastError = kernel32.GetLastError +GetCommandLineW = WINFUNCTYPE(LPWSTR)(("GetCommandLineW", windll.kernel32)) +CommandLineToArgvW = WINFUNCTYPE(POINTER(LPWSTR), LPCWSTR, POINTER(c_int))( + ("CommandLineToArgvW", windll.shell32) +) +LocalFree = WINFUNCTYPE(c_void_p, c_void_p)(("LocalFree", windll.kernel32)) + +STDIN_HANDLE = GetStdHandle(-10) +STDOUT_HANDLE = GetStdHandle(-11) +STDERR_HANDLE = GetStdHandle(-12) + +PyBUF_SIMPLE = 0 +PyBUF_WRITABLE = 1 + +ERROR_SUCCESS = 0 +ERROR_NOT_ENOUGH_MEMORY = 8 +ERROR_OPERATION_ABORTED = 995 + +STDIN_FILENO = 0 +STDOUT_FILENO = 1 +STDERR_FILENO = 2 + +EOF = b"\x1a" +MAX_BYTES_WRITTEN = 32767 + +if t.TYPE_CHECKING: + try: + # Using `typing_extensions.Buffer` instead of `collections.abc` + # on Windows for some reason does not have `Sized` implemented. + from collections.abc import Buffer # type: ignore + except ImportError: + from typing_extensions import Buffer + +try: + from ctypes import pythonapi +except ImportError: + # On PyPy we cannot get buffers so our ability to operate here is + # severely limited. + get_buffer = None +else: + + class Py_buffer(Structure): + _fields_ = [ # noqa: RUF012 + ("buf", c_void_p), + ("obj", py_object), + ("len", c_ssize_t), + ("itemsize", c_ssize_t), + ("readonly", c_int), + ("ndim", c_int), + ("format", c_char_p), + ("shape", c_ssize_p), + ("strides", c_ssize_p), + ("suboffsets", c_ssize_p), + ("internal", c_void_p), + ] + + PyObject_GetBuffer = pythonapi.PyObject_GetBuffer + PyBuffer_Release = pythonapi.PyBuffer_Release + + def get_buffer(obj: Buffer, writable: bool = False) -> Array[c_char]: + buf = Py_buffer() + flags: int = PyBUF_WRITABLE if writable else PyBUF_SIMPLE + PyObject_GetBuffer(py_object(obj), byref(buf), flags) + + try: + buffer_type = c_char * buf.len + out: Array[c_char] = buffer_type.from_address(buf.buf) + return out + finally: + PyBuffer_Release(byref(buf)) + + +class _WindowsConsoleRawIOBase(io.RawIOBase): + def __init__(self, handle: int | None) -> None: + self.handle = handle + + def isatty(self) -> t.Literal[True]: + super().isatty() + return True + + +class _WindowsConsoleReader(_WindowsConsoleRawIOBase): + def readable(self) -> t.Literal[True]: + return True + + def readinto(self, b: Buffer) -> int: + bytes_to_be_read = len(b) + if not bytes_to_be_read: + return 0 + elif bytes_to_be_read % 2: + raise ValueError( + "cannot read odd number of bytes from UTF-16-LE encoded console" + ) + + buffer = get_buffer(b, writable=True) + code_units_to_be_read = bytes_to_be_read // 2 + code_units_read = c_ulong() + + rv = ReadConsoleW( + HANDLE(self.handle), + buffer, + code_units_to_be_read, + byref(code_units_read), + None, + ) + if GetLastError() == ERROR_OPERATION_ABORTED: + # wait for KeyboardInterrupt + time.sleep(0.1) + if not rv: + raise OSError(f"Windows error: {GetLastError()}") + + if buffer[0] == EOF: + return 0 + return 2 * code_units_read.value + + +class _WindowsConsoleWriter(_WindowsConsoleRawIOBase): + def writable(self) -> t.Literal[True]: + return True + + @staticmethod + def _get_error_message(errno: int) -> str: + if errno == ERROR_SUCCESS: + return "ERROR_SUCCESS" + elif errno == ERROR_NOT_ENOUGH_MEMORY: + return "ERROR_NOT_ENOUGH_MEMORY" + return f"Windows error {errno}" + + def write(self, b: Buffer) -> int: + bytes_to_be_written = len(b) + buf = get_buffer(b) + code_units_to_be_written = min(bytes_to_be_written, MAX_BYTES_WRITTEN) // 2 + code_units_written = c_ulong() + + WriteConsoleW( + HANDLE(self.handle), + buf, + code_units_to_be_written, + byref(code_units_written), + None, + ) + bytes_written = 2 * code_units_written.value + + if bytes_written == 0 and bytes_to_be_written > 0: + raise OSError(self._get_error_message(GetLastError())) + return bytes_written + + +class ConsoleStream: + def __init__(self, text_stream: t.TextIO, byte_stream: t.BinaryIO) -> None: + self._text_stream = text_stream + self.buffer = byte_stream + + @property + def name(self) -> str: + return self.buffer.name + + def write(self, x: t.AnyStr) -> int: + if isinstance(x, str): + return self._text_stream.write(x) + try: + self.flush() + except Exception: + pass + return self.buffer.write(x) + + def writelines(self, lines: cabc.Iterable[t.AnyStr]) -> None: + for line in lines: + self.write(line) + + def __getattr__(self, name: str) -> t.Any: + return getattr(self._text_stream, name) + + def isatty(self) -> bool: + return self.buffer.isatty() + + def __repr__(self) -> str: + return f"" + + +def _get_text_stdin(buffer_stream: t.BinaryIO) -> t.TextIO: + text_stream = _NonClosingTextIOWrapper( + io.BufferedReader(_WindowsConsoleReader(STDIN_HANDLE)), + "utf-16-le", + "strict", + line_buffering=True, + ) + return t.cast(t.TextIO, ConsoleStream(text_stream, buffer_stream)) + + +def _get_text_stdout(buffer_stream: t.BinaryIO) -> t.TextIO: + text_stream = _NonClosingTextIOWrapper( + io.BufferedWriter(_WindowsConsoleWriter(STDOUT_HANDLE)), + "utf-16-le", + "strict", + line_buffering=True, + ) + return t.cast(t.TextIO, ConsoleStream(text_stream, buffer_stream)) + + +def _get_text_stderr(buffer_stream: t.BinaryIO) -> t.TextIO: + text_stream = _NonClosingTextIOWrapper( + io.BufferedWriter(_WindowsConsoleWriter(STDERR_HANDLE)), + "utf-16-le", + "strict", + line_buffering=True, + ) + return t.cast(t.TextIO, ConsoleStream(text_stream, buffer_stream)) + + +_stream_factories: cabc.Mapping[int, t.Callable[[t.BinaryIO], t.TextIO]] = { + 0: _get_text_stdin, + 1: _get_text_stdout, + 2: _get_text_stderr, +} + + +def _is_console(f: t.TextIO) -> bool: + if not hasattr(f, "fileno"): + return False + + try: + fileno = f.fileno() + except (OSError, io.UnsupportedOperation): + return False + + handle = msvcrt.get_osfhandle(fileno) + return bool(GetConsoleMode(handle, byref(DWORD()))) + + +def _get_windows_console_stream( + f: t.TextIO, encoding: str | None, errors: str | None +) -> t.TextIO | None: + if ( + get_buffer is None + or encoding not in {"utf-16-le", None} + or errors not in {"strict", None} + or not _is_console(f) + ): + return None + + func = _stream_factories.get(f.fileno()) + if func is None: + return None + + b = getattr(f, "buffer", None) + + if b is None: + return None + + return func(b) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/click/core.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/click/core.py new file mode 100644 index 000000000..f0a624be3 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/click/core.py @@ -0,0 +1,3437 @@ +from __future__ import annotations + +import collections.abc as cabc +import enum +import errno +import inspect +import os +import sys +import typing as t +from collections import abc +from collections import Counter +from contextlib import AbstractContextManager +from contextlib import contextmanager +from contextlib import ExitStack +from functools import update_wrapper +from gettext import gettext as _ +from gettext import ngettext +from itertools import repeat +from types import TracebackType + +from . import types +from ._utils import FLAG_NEEDS_VALUE +from ._utils import UNSET +from .exceptions import Abort +from .exceptions import BadParameter +from .exceptions import ClickException +from .exceptions import Exit +from .exceptions import MissingParameter +from .exceptions import NoArgsIsHelpError +from .exceptions import UsageError +from .formatting import HelpFormatter +from .formatting import join_options +from .globals import pop_context +from .globals import push_context +from .parser import _OptionParser +from .parser import _split_opt +from .termui import confirm +from .termui import prompt +from .termui import style +from .utils import _detect_program_name +from .utils import _expand_args +from .utils import echo +from .utils import make_default_short_help +from .utils import make_str +from .utils import PacifyFlushWrapper + +if t.TYPE_CHECKING: + from .shell_completion import CompletionItem + +F = t.TypeVar("F", bound="t.Callable[..., t.Any]") +V = t.TypeVar("V") + + +def _complete_visible_commands( + ctx: Context, incomplete: str +) -> cabc.Iterator[tuple[str, Command]]: + """List all the subcommands of a group that start with the + incomplete value and aren't hidden. + + :param ctx: Invocation context for the group. + :param incomplete: Value being completed. May be empty. + """ + multi = t.cast(Group, ctx.command) + + for name in multi.list_commands(ctx): + if name.startswith(incomplete): + command = multi.get_command(ctx, name) + + if command is not None and not command.hidden: + yield name, command + + +def _check_nested_chain( + base_command: Group, cmd_name: str, cmd: Command, register: bool = False +) -> None: + if not base_command.chain or not isinstance(cmd, Group): + return + + if register: + message = ( + f"It is not possible to add the group {cmd_name!r} to another" + f" group {base_command.name!r} that is in chain mode." + ) + else: + message = ( + f"Found the group {cmd_name!r} as subcommand to another group " + f" {base_command.name!r} that is in chain mode. This is not supported." + ) + + raise RuntimeError(message) + + +def batch(iterable: cabc.Iterable[V], batch_size: int) -> list[tuple[V, ...]]: + return list(zip(*repeat(iter(iterable), batch_size), strict=False)) + + +@contextmanager +def augment_usage_errors( + ctx: Context, param: Parameter | None = None +) -> cabc.Iterator[None]: + """Context manager that attaches extra information to exceptions.""" + try: + yield + except BadParameter as e: + if e.ctx is None: + e.ctx = ctx + if param is not None and e.param is None: + e.param = param + raise + except UsageError as e: + if e.ctx is None: + e.ctx = ctx + raise + + +def iter_params_for_processing( + invocation_order: cabc.Sequence[Parameter], + declaration_order: cabc.Sequence[Parameter], +) -> list[Parameter]: + """Returns all declared parameters in the order they should be processed. + + The declared parameters are re-shuffled depending on the order in which + they were invoked, as well as the eagerness of each parameters. + + The invocation order takes precedence over the declaration order. I.e. the + order in which the user provided them to the CLI is respected. + + This behavior and its effect on callback evaluation is detailed at: + https://click.palletsprojects.com/en/stable/advanced/#callback-evaluation-order + """ + + def sort_key(item: Parameter) -> tuple[bool, float]: + try: + idx: float = invocation_order.index(item) + except ValueError: + idx = float("inf") + + return not item.is_eager, idx + + return sorted(declaration_order, key=sort_key) + + +class ParameterSource(enum.Enum): + """This is an :class:`~enum.Enum` that indicates the source of a + parameter's value. + + Use :meth:`click.Context.get_parameter_source` to get the + source for a parameter by name. + + .. versionchanged:: 8.0 + Use :class:`~enum.Enum` and drop the ``validate`` method. + + .. versionchanged:: 8.0 + Added the ``PROMPT`` value. + """ + + COMMANDLINE = enum.auto() + """The value was provided by the command line args.""" + ENVIRONMENT = enum.auto() + """The value was provided with an environment variable.""" + DEFAULT = enum.auto() + """Used the default specified by the parameter.""" + DEFAULT_MAP = enum.auto() + """Used a default provided by :attr:`Context.default_map`.""" + PROMPT = enum.auto() + """Used a prompt to confirm a default or provide a value.""" + + +class Context: + """The context is a special internal object that holds state relevant + for the script execution at every single level. It's normally invisible + to commands unless they opt-in to getting access to it. + + The context is useful as it can pass internal objects around and can + control special execution features such as reading data from + environment variables. + + A context can be used as context manager in which case it will call + :meth:`close` on teardown. + + :param command: the command class for this context. + :param parent: the parent context. + :param info_name: the info name for this invocation. Generally this + is the most descriptive name for the script or + command. For the toplevel script it is usually + the name of the script, for commands below it it's + the name of the script. + :param obj: an arbitrary object of user data. + :param auto_envvar_prefix: the prefix to use for automatic environment + variables. If this is `None` then reading + from environment variables is disabled. This + does not affect manually set environment + variables which are always read. + :param default_map: a dictionary (like object) with default values + for parameters. + :param terminal_width: the width of the terminal. The default is + inherit from parent context. If no context + defines the terminal width then auto + detection will be applied. + :param max_content_width: the maximum width for content rendered by + Click (this currently only affects help + pages). This defaults to 80 characters if + not overridden. In other words: even if the + terminal is larger than that, Click will not + format things wider than 80 characters by + default. In addition to that, formatters might + add some safety mapping on the right. + :param resilient_parsing: if this flag is enabled then Click will + parse without any interactivity or callback + invocation. Default values will also be + ignored. This is useful for implementing + things such as completion support. + :param allow_extra_args: if this is set to `True` then extra arguments + at the end will not raise an error and will be + kept on the context. The default is to inherit + from the command. + :param allow_interspersed_args: if this is set to `False` then options + and arguments cannot be mixed. The + default is to inherit from the command. + :param ignore_unknown_options: instructs click to ignore options it does + not know and keeps them for later + processing. + :param help_option_names: optionally a list of strings that define how + the default help parameter is named. The + default is ``['--help']``. + :param token_normalize_func: an optional function that is used to + normalize tokens (options, choices, + etc.). This for instance can be used to + implement case insensitive behavior. + :param color: controls if the terminal supports ANSI colors or not. The + default is autodetection. This is only needed if ANSI + codes are used in texts that Click prints which is by + default not the case. This for instance would affect + help output. + :param show_default: Show the default value for commands. If this + value is not set, it defaults to the value from the parent + context. ``Command.show_default`` overrides this default for the + specific command. + + .. versionchanged:: 8.2 + The ``protected_args`` attribute is deprecated and will be removed in + Click 9.0. ``args`` will contain remaining unparsed tokens. + + .. versionchanged:: 8.1 + The ``show_default`` parameter is overridden by + ``Command.show_default``, instead of the other way around. + + .. versionchanged:: 8.0 + The ``show_default`` parameter defaults to the value from the + parent context. + + .. versionchanged:: 7.1 + Added the ``show_default`` parameter. + + .. versionchanged:: 4.0 + Added the ``color``, ``ignore_unknown_options``, and + ``max_content_width`` parameters. + + .. versionchanged:: 3.0 + Added the ``allow_extra_args`` and ``allow_interspersed_args`` + parameters. + + .. versionchanged:: 2.0 + Added the ``resilient_parsing``, ``help_option_names``, and + ``token_normalize_func`` parameters. + """ + + #: The formatter class to create with :meth:`make_formatter`. + #: + #: .. versionadded:: 8.0 + formatter_class: type[HelpFormatter] = HelpFormatter + + def __init__( + self, + command: Command, + parent: Context | None = None, + info_name: str | None = None, + obj: t.Any | None = None, + auto_envvar_prefix: str | None = None, + default_map: cabc.MutableMapping[str, t.Any] | None = None, + terminal_width: int | None = None, + max_content_width: int | None = None, + resilient_parsing: bool = False, + allow_extra_args: bool | None = None, + allow_interspersed_args: bool | None = None, + ignore_unknown_options: bool | None = None, + help_option_names: list[str] | None = None, + token_normalize_func: t.Callable[[str], str] | None = None, + color: bool | None = None, + show_default: bool | None = None, + ) -> None: + #: the parent context or `None` if none exists. + self.parent = parent + #: the :class:`Command` for this context. + self.command = command + #: the descriptive information name + self.info_name = info_name + #: Map of parameter names to their parsed values. Parameters + #: with ``expose_value=False`` are not stored. + self.params: dict[str, t.Any] = {} + #: the leftover arguments. + self.args: list[str] = [] + #: protected arguments. These are arguments that are prepended + #: to `args` when certain parsing scenarios are encountered but + #: must be never propagated to another arguments. This is used + #: to implement nested parsing. + self._protected_args: list[str] = [] + #: the collected prefixes of the command's options. + self._opt_prefixes: set[str] = set(parent._opt_prefixes) if parent else set() + + if obj is None and parent is not None: + obj = parent.obj + + #: the user object stored. + self.obj: t.Any = obj + self._meta: dict[str, t.Any] = getattr(parent, "meta", {}) + + #: A dictionary (-like object) with defaults for parameters. + if ( + default_map is None + and info_name is not None + and parent is not None + and parent.default_map is not None + ): + default_map = parent.default_map.get(info_name) + + self.default_map: cabc.MutableMapping[str, t.Any] | None = default_map + + #: This flag indicates if a subcommand is going to be executed. A + #: group callback can use this information to figure out if it's + #: being executed directly or because the execution flow passes + #: onwards to a subcommand. By default it's None, but it can be + #: the name of the subcommand to execute. + #: + #: If chaining is enabled this will be set to ``'*'`` in case + #: any commands are executed. It is however not possible to + #: figure out which ones. If you require this knowledge you + #: should use a :func:`result_callback`. + self.invoked_subcommand: str | None = None + + if terminal_width is None and parent is not None: + terminal_width = parent.terminal_width + + #: The width of the terminal (None is autodetection). + self.terminal_width: int | None = terminal_width + + if max_content_width is None and parent is not None: + max_content_width = parent.max_content_width + + #: The maximum width of formatted content (None implies a sensible + #: default which is 80 for most things). + self.max_content_width: int | None = max_content_width + + if allow_extra_args is None: + allow_extra_args = command.allow_extra_args + + #: Indicates if the context allows extra args or if it should + #: fail on parsing. + #: + #: .. versionadded:: 3.0 + self.allow_extra_args = allow_extra_args + + if allow_interspersed_args is None: + allow_interspersed_args = command.allow_interspersed_args + + #: Indicates if the context allows mixing of arguments and + #: options or not. + #: + #: .. versionadded:: 3.0 + self.allow_interspersed_args: bool = allow_interspersed_args + + if ignore_unknown_options is None: + ignore_unknown_options = command.ignore_unknown_options + + #: Instructs click to ignore options that a command does not + #: understand and will store it on the context for later + #: processing. This is primarily useful for situations where you + #: want to call into external programs. Generally this pattern is + #: strongly discouraged because it's not possibly to losslessly + #: forward all arguments. + #: + #: .. versionadded:: 4.0 + self.ignore_unknown_options: bool = ignore_unknown_options + + if help_option_names is None: + if parent is not None: + help_option_names = parent.help_option_names + else: + help_option_names = ["--help"] + + #: The names for the help options. + self.help_option_names: list[str] = help_option_names + + if token_normalize_func is None and parent is not None: + token_normalize_func = parent.token_normalize_func + + #: An optional normalization function for tokens. This is + #: options, choices, commands etc. + self.token_normalize_func: t.Callable[[str], str] | None = token_normalize_func + + #: Indicates if resilient parsing is enabled. In that case Click + #: will do its best to not cause any failures and default values + #: will be ignored. Useful for completion. + self.resilient_parsing: bool = resilient_parsing + + # If there is no envvar prefix yet, but the parent has one and + # the command on this level has a name, we can expand the envvar + # prefix automatically. + if auto_envvar_prefix is None: + if ( + parent is not None + and parent.auto_envvar_prefix is not None + and self.info_name is not None + ): + auto_envvar_prefix = ( + f"{parent.auto_envvar_prefix}_{self.info_name.upper()}" + ) + else: + auto_envvar_prefix = auto_envvar_prefix.upper() + + if auto_envvar_prefix is not None: + auto_envvar_prefix = auto_envvar_prefix.replace("-", "_") + + self.auto_envvar_prefix: str | None = auto_envvar_prefix + + if color is None and parent is not None: + color = parent.color + + #: Controls if styling output is wanted or not. + self.color: bool | None = color + + if show_default is None and parent is not None: + show_default = parent.show_default + + #: Show option default values when formatting help text. + self.show_default: bool | None = show_default + + self._close_callbacks: list[t.Callable[[], t.Any]] = [] + self._depth = 0 + self._parameter_source: dict[str, ParameterSource] = {} + self._exit_stack = ExitStack() + + @property + def protected_args(self) -> list[str]: + import warnings + + warnings.warn( + "'protected_args' is deprecated and will be removed in Click 9.0." + " 'args' will contain remaining unparsed tokens.", + DeprecationWarning, + stacklevel=2, + ) + return self._protected_args + + def to_info_dict(self) -> dict[str, t.Any]: + """Gather information that could be useful for a tool generating + user-facing documentation. This traverses the entire CLI + structure. + + .. code-block:: python + + with Context(cli) as ctx: + info = ctx.to_info_dict() + + .. versionadded:: 8.0 + """ + return { + "command": self.command.to_info_dict(self), + "info_name": self.info_name, + "allow_extra_args": self.allow_extra_args, + "allow_interspersed_args": self.allow_interspersed_args, + "ignore_unknown_options": self.ignore_unknown_options, + "auto_envvar_prefix": self.auto_envvar_prefix, + } + + def __enter__(self) -> Context: + self._depth += 1 + push_context(self) + return self + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_value: BaseException | None, + tb: TracebackType | None, + ) -> bool | None: + self._depth -= 1 + exit_result: bool | None = None + if self._depth == 0: + exit_result = self._close_with_exception_info(exc_type, exc_value, tb) + pop_context() + + return exit_result + + @contextmanager + def scope(self, cleanup: bool = True) -> cabc.Iterator[Context]: + """This helper method can be used with the context object to promote + it to the current thread local (see :func:`get_current_context`). + The default behavior of this is to invoke the cleanup functions which + can be disabled by setting `cleanup` to `False`. The cleanup + functions are typically used for things such as closing file handles. + + If the cleanup is intended the context object can also be directly + used as a context manager. + + Example usage:: + + with ctx.scope(): + assert get_current_context() is ctx + + This is equivalent:: + + with ctx: + assert get_current_context() is ctx + + .. versionadded:: 5.0 + + :param cleanup: controls if the cleanup functions should be run or + not. The default is to run these functions. In + some situations the context only wants to be + temporarily pushed in which case this can be disabled. + Nested pushes automatically defer the cleanup. + """ + if not cleanup: + self._depth += 1 + try: + with self as rv: + yield rv + finally: + if not cleanup: + self._depth -= 1 + + @property + def meta(self) -> dict[str, t.Any]: + """This is a dictionary which is shared with all the contexts + that are nested. It exists so that click utilities can store some + state here if they need to. It is however the responsibility of + that code to manage this dictionary well. + + The keys are supposed to be unique dotted strings. For instance + module paths are a good choice for it. What is stored in there is + irrelevant for the operation of click. However what is important is + that code that places data here adheres to the general semantics of + the system. + + Example usage:: + + LANG_KEY = f'{__name__}.lang' + + def set_language(value): + ctx = get_current_context() + ctx.meta[LANG_KEY] = value + + def get_language(): + return get_current_context().meta.get(LANG_KEY, 'en_US') + + .. versionadded:: 5.0 + """ + return self._meta + + def make_formatter(self) -> HelpFormatter: + """Creates the :class:`~click.HelpFormatter` for the help and + usage output. + + To quickly customize the formatter class used without overriding + this method, set the :attr:`formatter_class` attribute. + + .. versionchanged:: 8.0 + Added the :attr:`formatter_class` attribute. + """ + return self.formatter_class( + width=self.terminal_width, max_width=self.max_content_width + ) + + def with_resource(self, context_manager: AbstractContextManager[V]) -> V: + """Register a resource as if it were used in a ``with`` + statement. The resource will be cleaned up when the context is + popped. + + Uses :meth:`contextlib.ExitStack.enter_context`. It calls the + resource's ``__enter__()`` method and returns the result. When + the context is popped, it closes the stack, which calls the + resource's ``__exit__()`` method. + + To register a cleanup function for something that isn't a + context manager, use :meth:`call_on_close`. Or use something + from :mod:`contextlib` to turn it into a context manager first. + + .. code-block:: python + + @click.group() + @click.option("--name") + @click.pass_context + def cli(ctx): + ctx.obj = ctx.with_resource(connect_db(name)) + + :param context_manager: The context manager to enter. + :return: Whatever ``context_manager.__enter__()`` returns. + + .. versionadded:: 8.0 + """ + return self._exit_stack.enter_context(context_manager) + + def call_on_close(self, f: t.Callable[..., t.Any]) -> t.Callable[..., t.Any]: + """Register a function to be called when the context tears down. + + This can be used to close resources opened during the script + execution. Resources that support Python's context manager + protocol which would be used in a ``with`` statement should be + registered with :meth:`with_resource` instead. + + :param f: The function to execute on teardown. + """ + return self._exit_stack.callback(f) + + def close(self) -> None: + """Invoke all close callbacks registered with + :meth:`call_on_close`, and exit all context managers entered + with :meth:`with_resource`. + """ + self._close_with_exception_info(None, None, None) + + def _close_with_exception_info( + self, + exc_type: type[BaseException] | None, + exc_value: BaseException | None, + tb: TracebackType | None, + ) -> bool | None: + """Unwind the exit stack by calling its :meth:`__exit__` providing the exception + information to allow for exception handling by the various resources registered + using :meth;`with_resource` + + :return: Whatever ``exit_stack.__exit__()`` returns. + """ + exit_result = self._exit_stack.__exit__(exc_type, exc_value, tb) + # In case the context is reused, create a new exit stack. + self._exit_stack = ExitStack() + + return exit_result + + @property + def command_path(self) -> str: + """The computed command path. This is used for the ``usage`` + information on the help page. It's automatically created by + combining the info names of the chain of contexts to the root. + """ + rv = "" + if self.info_name is not None: + rv = self.info_name + if self.parent is not None: + parent_command_path = [self.parent.command_path] + + if isinstance(self.parent.command, Command): + for param in self.parent.command.get_params(self): + parent_command_path.extend(param.get_usage_pieces(self)) + + rv = f"{' '.join(parent_command_path)} {rv}" + return rv.lstrip() + + def find_root(self) -> Context: + """Finds the outermost context.""" + node = self + while node.parent is not None: + node = node.parent + return node + + def find_object(self, object_type: type[V]) -> V | None: + """Finds the closest object of a given type.""" + node: Context | None = self + + while node is not None: + if isinstance(node.obj, object_type): + return node.obj + + node = node.parent + + return None + + def ensure_object(self, object_type: type[V]) -> V: + """Like :meth:`find_object` but sets the innermost object to a + new instance of `object_type` if it does not exist. + """ + rv = self.find_object(object_type) + if rv is None: + self.obj = rv = object_type() + return rv + + @t.overload + def lookup_default( + self, name: str, call: t.Literal[True] = True + ) -> t.Any | None: ... + + @t.overload + def lookup_default( + self, name: str, call: t.Literal[False] = ... + ) -> t.Any | t.Callable[[], t.Any] | None: ... + + def lookup_default(self, name: str, call: bool = True) -> t.Any | None: + """Get the default for a parameter from :attr:`default_map`. + + :param name: Name of the parameter. + :param call: If the default is a callable, call it. Disable to + return the callable instead. + + .. versionchanged:: 8.0 + Added the ``call`` parameter. + """ + if self.default_map is not None: + value = self.default_map.get(name) + + if call and callable(value): + return value() + + return value + + return None + + def fail(self, message: str) -> t.NoReturn: + """Aborts the execution of the program with a specific error + message. + + :param message: the error message to fail with. + """ + raise UsageError(message, self) + + def abort(self) -> t.NoReturn: + """Aborts the script.""" + raise Abort() + + def exit(self, code: int = 0) -> t.NoReturn: + """Exits the application with a given exit code. + + .. versionchanged:: 8.2 + Callbacks and context managers registered with :meth:`call_on_close` + and :meth:`with_resource` are closed before exiting. + """ + self.close() + raise Exit(code) + + def get_usage(self) -> str: + """Helper method to get formatted usage string for the current + context and command. + """ + return self.command.get_usage(self) + + def get_help(self) -> str: + """Helper method to get formatted help page for the current + context and command. + """ + return self.command.get_help(self) + + def _make_sub_context(self, command: Command) -> Context: + """Create a new context of the same type as this context, but + for a new command. + + :meta private: + """ + return type(self)(command, info_name=command.name, parent=self) + + @t.overload + def invoke( + self, callback: t.Callable[..., V], /, *args: t.Any, **kwargs: t.Any + ) -> V: ... + + @t.overload + def invoke(self, callback: Command, /, *args: t.Any, **kwargs: t.Any) -> t.Any: ... + + def invoke( + self, callback: Command | t.Callable[..., V], /, *args: t.Any, **kwargs: t.Any + ) -> t.Any | V: + """Invokes a command callback in exactly the way it expects. There + are two ways to invoke this method: + + 1. the first argument can be a callback and all other arguments and + keyword arguments are forwarded directly to the function. + 2. the first argument is a click command object. In that case all + arguments are forwarded as well but proper click parameters + (options and click arguments) must be keyword arguments and Click + will fill in defaults. + + .. versionchanged:: 8.0 + All ``kwargs`` are tracked in :attr:`params` so they will be + passed if :meth:`forward` is called at multiple levels. + + .. versionchanged:: 3.2 + A new context is created, and missing arguments use default values. + """ + if isinstance(callback, Command): + other_cmd = callback + + if other_cmd.callback is None: + raise TypeError( + "The given command does not have a callback that can be invoked." + ) + else: + callback = t.cast("t.Callable[..., V]", other_cmd.callback) + + ctx = self._make_sub_context(other_cmd) + + for param in other_cmd.params: + if param.name not in kwargs and param.expose_value: + default_value = param.get_default(ctx) + # We explicitly hide the :attr:`UNSET` value to the user, as we + # choose to make it an implementation detail. And because ``invoke`` + # has been designed as part of Click public API, we return ``None`` + # instead. Refs: + # https://github.com/pallets/click/issues/3066 + # https://github.com/pallets/click/issues/3065 + # https://github.com/pallets/click/pull/3068 + if default_value is UNSET: + default_value = None + kwargs[param.name] = param.type_cast_value( # type: ignore + ctx, default_value + ) + + # Track all kwargs as params, so that forward() will pass + # them on in subsequent calls. + ctx.params.update(kwargs) + else: + ctx = self + + with augment_usage_errors(self): + with ctx: + return callback(*args, **kwargs) + + def forward(self, cmd: Command, /, *args: t.Any, **kwargs: t.Any) -> t.Any: + """Similar to :meth:`invoke` but fills in default keyword + arguments from the current context if the other command expects + it. This cannot invoke callbacks directly, only other commands. + + .. versionchanged:: 8.0 + All ``kwargs`` are tracked in :attr:`params` so they will be + passed if ``forward`` is called at multiple levels. + """ + # Can only forward to other commands, not direct callbacks. + if not isinstance(cmd, Command): + raise TypeError("Callback is not a command.") + + for param in self.params: + if param not in kwargs: + kwargs[param] = self.params[param] + + return self.invoke(cmd, *args, **kwargs) + + def set_parameter_source(self, name: str, source: ParameterSource) -> None: + """Set the source of a parameter. This indicates the location + from which the value of the parameter was obtained. + + :param name: The name of the parameter. + :param source: A member of :class:`~click.core.ParameterSource`. + """ + self._parameter_source[name] = source + + def get_parameter_source(self, name: str) -> ParameterSource | None: + """Get the source of a parameter. This indicates the location + from which the value of the parameter was obtained. + + This can be useful for determining when a user specified a value + on the command line that is the same as the default value. It + will be :attr:`~click.core.ParameterSource.DEFAULT` only if the + value was actually taken from the default. + + :param name: The name of the parameter. + :rtype: ParameterSource + + .. versionchanged:: 8.0 + Returns ``None`` if the parameter was not provided from any + source. + """ + return self._parameter_source.get(name) + + +class Command: + """Commands are the basic building block of command line interfaces in + Click. A basic command handles command line parsing and might dispatch + more parsing to commands nested below it. + + :param name: the name of the command to use unless a group overrides it. + :param context_settings: an optional dictionary with defaults that are + passed to the context object. + :param callback: the callback to invoke. This is optional. + :param params: the parameters to register with this command. This can + be either :class:`Option` or :class:`Argument` objects. + :param help: the help string to use for this command. + :param epilog: like the help string but it's printed at the end of the + help page after everything else. + :param short_help: the short help to use for this command. This is + shown on the command listing of the parent command. + :param add_help_option: by default each command registers a ``--help`` + option. This can be disabled by this parameter. + :param no_args_is_help: this controls what happens if no arguments are + provided. This option is disabled by default. + If enabled this will add ``--help`` as argument + if no arguments are passed + :param hidden: hide this command from help outputs. + :param deprecated: If ``True`` or non-empty string, issues a message + indicating that the command is deprecated and highlights + its deprecation in --help. The message can be customized + by using a string as the value. + + .. versionchanged:: 8.2 + This is the base class for all commands, not ``BaseCommand``. + ``deprecated`` can be set to a string as well to customize the + deprecation message. + + .. versionchanged:: 8.1 + ``help``, ``epilog``, and ``short_help`` are stored unprocessed, + all formatting is done when outputting help text, not at init, + and is done even if not using the ``@command`` decorator. + + .. versionchanged:: 8.0 + Added a ``repr`` showing the command name. + + .. versionchanged:: 7.1 + Added the ``no_args_is_help`` parameter. + + .. versionchanged:: 2.0 + Added the ``context_settings`` parameter. + """ + + #: The context class to create with :meth:`make_context`. + #: + #: .. versionadded:: 8.0 + context_class: type[Context] = Context + + #: the default for the :attr:`Context.allow_extra_args` flag. + allow_extra_args = False + + #: the default for the :attr:`Context.allow_interspersed_args` flag. + allow_interspersed_args = True + + #: the default for the :attr:`Context.ignore_unknown_options` flag. + ignore_unknown_options = False + + def __init__( + self, + name: str | None, + context_settings: cabc.MutableMapping[str, t.Any] | None = None, + callback: t.Callable[..., t.Any] | None = None, + params: list[Parameter] | None = None, + help: str | None = None, + epilog: str | None = None, + short_help: str | None = None, + options_metavar: str | None = "[OPTIONS]", + add_help_option: bool = True, + no_args_is_help: bool = False, + hidden: bool = False, + deprecated: bool | str = False, + ) -> None: + #: the name the command thinks it has. Upon registering a command + #: on a :class:`Group` the group will default the command name + #: with this information. You should instead use the + #: :class:`Context`\'s :attr:`~Context.info_name` attribute. + self.name = name + + if context_settings is None: + context_settings = {} + + #: an optional dictionary with defaults passed to the context. + self.context_settings: cabc.MutableMapping[str, t.Any] = context_settings + + #: the callback to execute when the command fires. This might be + #: `None` in which case nothing happens. + self.callback = callback + #: the list of parameters for this command in the order they + #: should show up in the help page and execute. Eager parameters + #: will automatically be handled before non eager ones. + self.params: list[Parameter] = params or [] + self.help = help + self.epilog = epilog + self.options_metavar = options_metavar + self.short_help = short_help + self.add_help_option = add_help_option + self._help_option = None + self.no_args_is_help = no_args_is_help + self.hidden = hidden + self.deprecated = deprecated + + def to_info_dict(self, ctx: Context) -> dict[str, t.Any]: + return { + "name": self.name, + "params": [param.to_info_dict() for param in self.get_params(ctx)], + "help": self.help, + "epilog": self.epilog, + "short_help": self.short_help, + "hidden": self.hidden, + "deprecated": self.deprecated, + } + + def __repr__(self) -> str: + return f"<{self.__class__.__name__} {self.name}>" + + def get_usage(self, ctx: Context) -> str: + """Formats the usage line into a string and returns it. + + Calls :meth:`format_usage` internally. + """ + formatter = ctx.make_formatter() + self.format_usage(ctx, formatter) + return formatter.getvalue().rstrip("\n") + + def get_params(self, ctx: Context) -> list[Parameter]: + params = self.params + help_option = self.get_help_option(ctx) + + if help_option is not None: + params = [*params, help_option] + + if __debug__: + import warnings + + opts = [opt for param in params for opt in param.opts] + opts_counter = Counter(opts) + duplicate_opts = (opt for opt, count in opts_counter.items() if count > 1) + + for duplicate_opt in duplicate_opts: + warnings.warn( + ( + f"The parameter {duplicate_opt} is used more than once. " + "Remove its duplicate as parameters should be unique." + ), + stacklevel=3, + ) + + return params + + def format_usage(self, ctx: Context, formatter: HelpFormatter) -> None: + """Writes the usage line into the formatter. + + This is a low-level method called by :meth:`get_usage`. + """ + pieces = self.collect_usage_pieces(ctx) + formatter.write_usage(ctx.command_path, " ".join(pieces)) + + def collect_usage_pieces(self, ctx: Context) -> list[str]: + """Returns all the pieces that go into the usage line and returns + it as a list of strings. + """ + rv = [self.options_metavar] if self.options_metavar else [] + + for param in self.get_params(ctx): + rv.extend(param.get_usage_pieces(ctx)) + + return rv + + def get_help_option_names(self, ctx: Context) -> list[str]: + """Returns the names for the help option.""" + all_names = set(ctx.help_option_names) + for param in self.params: + all_names.difference_update(param.opts) + all_names.difference_update(param.secondary_opts) + return list(all_names) + + def get_help_option(self, ctx: Context) -> Option | None: + """Returns the help option object. + + Skipped if :attr:`add_help_option` is ``False``. + + .. versionchanged:: 8.1.8 + The help option is now cached to avoid creating it multiple times. + """ + help_option_names = self.get_help_option_names(ctx) + + if not help_option_names or not self.add_help_option: + return None + + # Cache the help option object in private _help_option attribute to + # avoid creating it multiple times. Not doing this will break the + # callback odering by iter_params_for_processing(), which relies on + # object comparison. + if self._help_option is None: + # Avoid circular import. + from .decorators import help_option + + # Apply help_option decorator and pop resulting option + help_option(*help_option_names)(self) + self._help_option = self.params.pop() # type: ignore[assignment] + + return self._help_option + + def make_parser(self, ctx: Context) -> _OptionParser: + """Creates the underlying option parser for this command.""" + parser = _OptionParser(ctx) + for param in self.get_params(ctx): + param.add_to_parser(parser, ctx) + return parser + + def get_help(self, ctx: Context) -> str: + """Formats the help into a string and returns it. + + Calls :meth:`format_help` internally. + """ + formatter = ctx.make_formatter() + self.format_help(ctx, formatter) + return formatter.getvalue().rstrip("\n") + + def get_short_help_str(self, limit: int = 45) -> str: + """Gets short help for the command or makes it by shortening the + long help string. + """ + if self.short_help: + text = inspect.cleandoc(self.short_help) + elif self.help: + text = make_default_short_help(self.help, limit) + else: + text = "" + + if self.deprecated: + deprecated_message = ( + f"(DEPRECATED: {self.deprecated})" + if isinstance(self.deprecated, str) + else "(DEPRECATED)" + ) + text = _("{text} {deprecated_message}").format( + text=text, deprecated_message=deprecated_message + ) + + return text.strip() + + def format_help(self, ctx: Context, formatter: HelpFormatter) -> None: + """Writes the help into the formatter if it exists. + + This is a low-level method called by :meth:`get_help`. + + This calls the following methods: + + - :meth:`format_usage` + - :meth:`format_help_text` + - :meth:`format_options` + - :meth:`format_epilog` + """ + self.format_usage(ctx, formatter) + self.format_help_text(ctx, formatter) + self.format_options(ctx, formatter) + self.format_epilog(ctx, formatter) + + def format_help_text(self, ctx: Context, formatter: HelpFormatter) -> None: + """Writes the help text to the formatter if it exists.""" + if self.help is not None: + # truncate the help text to the first form feed + text = inspect.cleandoc(self.help).partition("\f")[0] + else: + text = "" + + if self.deprecated: + deprecated_message = ( + f"(DEPRECATED: {self.deprecated})" + if isinstance(self.deprecated, str) + else "(DEPRECATED)" + ) + text = _("{text} {deprecated_message}").format( + text=text, deprecated_message=deprecated_message + ) + + if text: + formatter.write_paragraph() + + with formatter.indentation(): + formatter.write_text(text) + + def format_options(self, ctx: Context, formatter: HelpFormatter) -> None: + """Writes all the options into the formatter if they exist.""" + opts = [] + for param in self.get_params(ctx): + rv = param.get_help_record(ctx) + if rv is not None: + opts.append(rv) + + if opts: + with formatter.section(_("Options")): + formatter.write_dl(opts) + + def format_epilog(self, ctx: Context, formatter: HelpFormatter) -> None: + """Writes the epilog into the formatter if it exists.""" + if self.epilog: + epilog = inspect.cleandoc(self.epilog) + formatter.write_paragraph() + + with formatter.indentation(): + formatter.write_text(epilog) + + def make_context( + self, + info_name: str | None, + args: list[str], + parent: Context | None = None, + **extra: t.Any, + ) -> Context: + """This function when given an info name and arguments will kick + off the parsing and create a new :class:`Context`. It does not + invoke the actual command callback though. + + To quickly customize the context class used without overriding + this method, set the :attr:`context_class` attribute. + + :param info_name: the info name for this invocation. Generally this + is the most descriptive name for the script or + command. For the toplevel script it's usually + the name of the script, for commands below it's + the name of the command. + :param args: the arguments to parse as list of strings. + :param parent: the parent context if available. + :param extra: extra keyword arguments forwarded to the context + constructor. + + .. versionchanged:: 8.0 + Added the :attr:`context_class` attribute. + """ + for key, value in self.context_settings.items(): + if key not in extra: + extra[key] = value + + ctx = self.context_class(self, info_name=info_name, parent=parent, **extra) + + with ctx.scope(cleanup=False): + self.parse_args(ctx, args) + return ctx + + def parse_args(self, ctx: Context, args: list[str]) -> list[str]: + if not args and self.no_args_is_help and not ctx.resilient_parsing: + raise NoArgsIsHelpError(ctx) + + parser = self.make_parser(ctx) + opts, args, param_order = parser.parse_args(args=args) + + for param in iter_params_for_processing(param_order, self.get_params(ctx)): + _, args = param.handle_parse_result(ctx, opts, args) + + # We now have all parameters' values into `ctx.params`, but the data may contain + # the `UNSET` sentinel. + # Convert `UNSET` to `None` to ensure that the user doesn't see `UNSET`. + # + # Waiting until after the initial parse to convert allows us to treat `UNSET` + # more like a missing value when multiple params use the same name. + # Refs: + # https://github.com/pallets/click/issues/3071 + # https://github.com/pallets/click/pull/3079 + for name, value in ctx.params.items(): + if value is UNSET: + ctx.params[name] = None + + if args and not ctx.allow_extra_args and not ctx.resilient_parsing: + ctx.fail( + ngettext( + "Got unexpected extra argument ({args})", + "Got unexpected extra arguments ({args})", + len(args), + ).format(args=" ".join(map(str, args))) + ) + + ctx.args = args + ctx._opt_prefixes.update(parser._opt_prefixes) + return args + + def invoke(self, ctx: Context) -> t.Any: + """Given a context, this invokes the attached callback (if it exists) + in the right way. + """ + if self.deprecated: + extra_message = ( + f" {self.deprecated}" if isinstance(self.deprecated, str) else "" + ) + message = _( + "DeprecationWarning: The command {name!r} is deprecated.{extra_message}" + ).format(name=self.name, extra_message=extra_message) + echo(style(message, fg="red"), err=True) + + if self.callback is not None: + return ctx.invoke(self.callback, **ctx.params) + + def shell_complete(self, ctx: Context, incomplete: str) -> list[CompletionItem]: + """Return a list of completions for the incomplete value. Looks + at the names of options and chained multi-commands. + + Any command could be part of a chained multi-command, so sibling + commands are valid at any point during command completion. + + :param ctx: Invocation context for this command. + :param incomplete: Value being completed. May be empty. + + .. versionadded:: 8.0 + """ + from click.shell_completion import CompletionItem + + results: list[CompletionItem] = [] + + if incomplete and not incomplete[0].isalnum(): + for param in self.get_params(ctx): + if ( + not isinstance(param, Option) + or param.hidden + or ( + not param.multiple + and ctx.get_parameter_source(param.name) # type: ignore + is ParameterSource.COMMANDLINE + ) + ): + continue + + results.extend( + CompletionItem(name, help=param.help) + for name in [*param.opts, *param.secondary_opts] + if name.startswith(incomplete) + ) + + while ctx.parent is not None: + ctx = ctx.parent + + if isinstance(ctx.command, Group) and ctx.command.chain: + results.extend( + CompletionItem(name, help=command.get_short_help_str()) + for name, command in _complete_visible_commands(ctx, incomplete) + if name not in ctx._protected_args + ) + + return results + + @t.overload + def main( + self, + args: cabc.Sequence[str] | None = None, + prog_name: str | None = None, + complete_var: str | None = None, + standalone_mode: t.Literal[True] = True, + **extra: t.Any, + ) -> t.NoReturn: ... + + @t.overload + def main( + self, + args: cabc.Sequence[str] | None = None, + prog_name: str | None = None, + complete_var: str | None = None, + standalone_mode: bool = ..., + **extra: t.Any, + ) -> t.Any: ... + + def main( + self, + args: cabc.Sequence[str] | None = None, + prog_name: str | None = None, + complete_var: str | None = None, + standalone_mode: bool = True, + windows_expand_args: bool = True, + **extra: t.Any, + ) -> t.Any: + """This is the way to invoke a script with all the bells and + whistles as a command line application. This will always terminate + the application after a call. If this is not wanted, ``SystemExit`` + needs to be caught. + + This method is also available by directly calling the instance of + a :class:`Command`. + + :param args: the arguments that should be used for parsing. If not + provided, ``sys.argv[1:]`` is used. + :param prog_name: the program name that should be used. By default + the program name is constructed by taking the file + name from ``sys.argv[0]``. + :param complete_var: the environment variable that controls the + bash completion support. The default is + ``"__COMPLETE"`` with prog_name in + uppercase. + :param standalone_mode: the default behavior is to invoke the script + in standalone mode. Click will then + handle exceptions and convert them into + error messages and the function will never + return but shut down the interpreter. If + this is set to `False` they will be + propagated to the caller and the return + value of this function is the return value + of :meth:`invoke`. + :param windows_expand_args: Expand glob patterns, user dir, and + env vars in command line args on Windows. + :param extra: extra keyword arguments are forwarded to the context + constructor. See :class:`Context` for more information. + + .. versionchanged:: 8.0.1 + Added the ``windows_expand_args`` parameter to allow + disabling command line arg expansion on Windows. + + .. versionchanged:: 8.0 + When taking arguments from ``sys.argv`` on Windows, glob + patterns, user dir, and env vars are expanded. + + .. versionchanged:: 3.0 + Added the ``standalone_mode`` parameter. + """ + if args is None: + args = sys.argv[1:] + + if os.name == "nt" and windows_expand_args: + args = _expand_args(args) + else: + args = list(args) + + if prog_name is None: + prog_name = _detect_program_name() + + # Process shell completion requests and exit early. + self._main_shell_completion(extra, prog_name, complete_var) + + try: + try: + with self.make_context(prog_name, args, **extra) as ctx: + rv = self.invoke(ctx) + if not standalone_mode: + return rv + # it's not safe to `ctx.exit(rv)` here! + # note that `rv` may actually contain data like "1" which + # has obvious effects + # more subtle case: `rv=[None, None]` can come out of + # chained commands which all returned `None` -- so it's not + # even always obvious that `rv` indicates success/failure + # by its truthiness/falsiness + ctx.exit() + except (EOFError, KeyboardInterrupt) as e: + echo(file=sys.stderr) + raise Abort() from e + except ClickException as e: + if not standalone_mode: + raise + e.show() + sys.exit(e.exit_code) + except OSError as e: + if e.errno == errno.EPIPE: + sys.stdout = t.cast(t.TextIO, PacifyFlushWrapper(sys.stdout)) + sys.stderr = t.cast(t.TextIO, PacifyFlushWrapper(sys.stderr)) + sys.exit(1) + else: + raise + except Exit as e: + if standalone_mode: + sys.exit(e.exit_code) + else: + # in non-standalone mode, return the exit code + # note that this is only reached if `self.invoke` above raises + # an Exit explicitly -- thus bypassing the check there which + # would return its result + # the results of non-standalone execution may therefore be + # somewhat ambiguous: if there are codepaths which lead to + # `ctx.exit(1)` and to `return 1`, the caller won't be able to + # tell the difference between the two + return e.exit_code + except Abort: + if not standalone_mode: + raise + echo(_("Aborted!"), file=sys.stderr) + sys.exit(1) + + def _main_shell_completion( + self, + ctx_args: cabc.MutableMapping[str, t.Any], + prog_name: str, + complete_var: str | None = None, + ) -> None: + """Check if the shell is asking for tab completion, process + that, then exit early. Called from :meth:`main` before the + program is invoked. + + :param prog_name: Name of the executable in the shell. + :param complete_var: Name of the environment variable that holds + the completion instruction. Defaults to + ``_{PROG_NAME}_COMPLETE``. + + .. versionchanged:: 8.2.0 + Dots (``.``) in ``prog_name`` are replaced with underscores (``_``). + """ + if complete_var is None: + complete_name = prog_name.replace("-", "_").replace(".", "_") + complete_var = f"_{complete_name}_COMPLETE".upper() + + instruction = os.environ.get(complete_var) + + if not instruction: + return + + from .shell_completion import shell_complete + + rv = shell_complete(self, ctx_args, prog_name, complete_var, instruction) + sys.exit(rv) + + def __call__(self, *args: t.Any, **kwargs: t.Any) -> t.Any: + """Alias for :meth:`main`.""" + return self.main(*args, **kwargs) + + +class _FakeSubclassCheck(type): + def __subclasscheck__(cls, subclass: type) -> bool: + return issubclass(subclass, cls.__bases__[0]) + + def __instancecheck__(cls, instance: t.Any) -> bool: + return isinstance(instance, cls.__bases__[0]) + + +class _BaseCommand(Command, metaclass=_FakeSubclassCheck): + """ + .. deprecated:: 8.2 + Will be removed in Click 9.0. Use ``Command`` instead. + """ + + +class Group(Command): + """A group is a command that nests other commands (or more groups). + + :param name: The name of the group command. + :param commands: Map names to :class:`Command` objects. Can be a list, which + will use :attr:`Command.name` as the keys. + :param invoke_without_command: Invoke the group's callback even if a + subcommand is not given. + :param no_args_is_help: If no arguments are given, show the group's help and + exit. Defaults to the opposite of ``invoke_without_command``. + :param subcommand_metavar: How to represent the subcommand argument in help. + The default will represent whether ``chain`` is set or not. + :param chain: Allow passing more than one subcommand argument. After parsing + a command's arguments, if any arguments remain another command will be + matched, and so on. + :param result_callback: A function to call after the group's and + subcommand's callbacks. The value returned by the subcommand is passed. + If ``chain`` is enabled, the value will be a list of values returned by + all the commands. If ``invoke_without_command`` is enabled, the value + will be the value returned by the group's callback, or an empty list if + ``chain`` is enabled. + :param kwargs: Other arguments passed to :class:`Command`. + + .. versionchanged:: 8.0 + The ``commands`` argument can be a list of command objects. + + .. versionchanged:: 8.2 + Merged with and replaces the ``MultiCommand`` base class. + """ + + allow_extra_args = True + allow_interspersed_args = False + + #: If set, this is used by the group's :meth:`command` decorator + #: as the default :class:`Command` class. This is useful to make all + #: subcommands use a custom command class. + #: + #: .. versionadded:: 8.0 + command_class: type[Command] | None = None + + #: If set, this is used by the group's :meth:`group` decorator + #: as the default :class:`Group` class. This is useful to make all + #: subgroups use a custom group class. + #: + #: If set to the special value :class:`type` (literally + #: ``group_class = type``), this group's class will be used as the + #: default class. This makes a custom group class continue to make + #: custom groups. + #: + #: .. versionadded:: 8.0 + group_class: type[Group] | type[type] | None = None + # Literal[type] isn't valid, so use Type[type] + + def __init__( + self, + name: str | None = None, + commands: cabc.MutableMapping[str, Command] + | cabc.Sequence[Command] + | None = None, + invoke_without_command: bool = False, + no_args_is_help: bool | None = None, + subcommand_metavar: str | None = None, + chain: bool = False, + result_callback: t.Callable[..., t.Any] | None = None, + **kwargs: t.Any, + ) -> None: + super().__init__(name, **kwargs) + + if commands is None: + commands = {} + elif isinstance(commands, abc.Sequence): + commands = {c.name: c for c in commands if c.name is not None} + + #: The registered subcommands by their exported names. + self.commands: cabc.MutableMapping[str, Command] = commands + + if no_args_is_help is None: + no_args_is_help = not invoke_without_command + + self.no_args_is_help = no_args_is_help + self.invoke_without_command = invoke_without_command + + if subcommand_metavar is None: + if chain: + subcommand_metavar = "COMMAND1 [ARGS]... [COMMAND2 [ARGS]...]..." + else: + subcommand_metavar = "COMMAND [ARGS]..." + + self.subcommand_metavar = subcommand_metavar + self.chain = chain + # The result callback that is stored. This can be set or + # overridden with the :func:`result_callback` decorator. + self._result_callback = result_callback + + if self.chain: + for param in self.params: + if isinstance(param, Argument) and not param.required: + raise RuntimeError( + "A group in chain mode cannot have optional arguments." + ) + + def to_info_dict(self, ctx: Context) -> dict[str, t.Any]: + info_dict = super().to_info_dict(ctx) + commands = {} + + for name in self.list_commands(ctx): + command = self.get_command(ctx, name) + + if command is None: + continue + + sub_ctx = ctx._make_sub_context(command) + + with sub_ctx.scope(cleanup=False): + commands[name] = command.to_info_dict(sub_ctx) + + info_dict.update(commands=commands, chain=self.chain) + return info_dict + + def add_command(self, cmd: Command, name: str | None = None) -> None: + """Registers another :class:`Command` with this group. If the name + is not provided, the name of the command is used. + """ + name = name or cmd.name + if name is None: + raise TypeError("Command has no name.") + _check_nested_chain(self, name, cmd, register=True) + self.commands[name] = cmd + + @t.overload + def command(self, __func: t.Callable[..., t.Any]) -> Command: ... + + @t.overload + def command( + self, *args: t.Any, **kwargs: t.Any + ) -> t.Callable[[t.Callable[..., t.Any]], Command]: ... + + def command( + self, *args: t.Any, **kwargs: t.Any + ) -> t.Callable[[t.Callable[..., t.Any]], Command] | Command: + """A shortcut decorator for declaring and attaching a command to + the group. This takes the same arguments as :func:`command` and + immediately registers the created command with this group by + calling :meth:`add_command`. + + To customize the command class used, set the + :attr:`command_class` attribute. + + .. versionchanged:: 8.1 + This decorator can be applied without parentheses. + + .. versionchanged:: 8.0 + Added the :attr:`command_class` attribute. + """ + from .decorators import command + + func: t.Callable[..., t.Any] | None = None + + if args and callable(args[0]): + assert len(args) == 1 and not kwargs, ( + "Use 'command(**kwargs)(callable)' to provide arguments." + ) + (func,) = args + args = () + + if self.command_class and kwargs.get("cls") is None: + kwargs["cls"] = self.command_class + + def decorator(f: t.Callable[..., t.Any]) -> Command: + cmd: Command = command(*args, **kwargs)(f) + self.add_command(cmd) + return cmd + + if func is not None: + return decorator(func) + + return decorator + + @t.overload + def group(self, __func: t.Callable[..., t.Any]) -> Group: ... + + @t.overload + def group( + self, *args: t.Any, **kwargs: t.Any + ) -> t.Callable[[t.Callable[..., t.Any]], Group]: ... + + def group( + self, *args: t.Any, **kwargs: t.Any + ) -> t.Callable[[t.Callable[..., t.Any]], Group] | Group: + """A shortcut decorator for declaring and attaching a group to + the group. This takes the same arguments as :func:`group` and + immediately registers the created group with this group by + calling :meth:`add_command`. + + To customize the group class used, set the :attr:`group_class` + attribute. + + .. versionchanged:: 8.1 + This decorator can be applied without parentheses. + + .. versionchanged:: 8.0 + Added the :attr:`group_class` attribute. + """ + from .decorators import group + + func: t.Callable[..., t.Any] | None = None + + if args and callable(args[0]): + assert len(args) == 1 and not kwargs, ( + "Use 'group(**kwargs)(callable)' to provide arguments." + ) + (func,) = args + args = () + + if self.group_class is not None and kwargs.get("cls") is None: + if self.group_class is type: + kwargs["cls"] = type(self) + else: + kwargs["cls"] = self.group_class + + def decorator(f: t.Callable[..., t.Any]) -> Group: + cmd: Group = group(*args, **kwargs)(f) + self.add_command(cmd) + return cmd + + if func is not None: + return decorator(func) + + return decorator + + def result_callback(self, replace: bool = False) -> t.Callable[[F], F]: + """Adds a result callback to the command. By default if a + result callback is already registered this will chain them but + this can be disabled with the `replace` parameter. The result + callback is invoked with the return value of the subcommand + (or the list of return values from all subcommands if chaining + is enabled) as well as the parameters as they would be passed + to the main callback. + + Example:: + + @click.group() + @click.option('-i', '--input', default=23) + def cli(input): + return 42 + + @cli.result_callback() + def process_result(result, input): + return result + input + + :param replace: if set to `True` an already existing result + callback will be removed. + + .. versionchanged:: 8.0 + Renamed from ``resultcallback``. + + .. versionadded:: 3.0 + """ + + def decorator(f: F) -> F: + old_callback = self._result_callback + + if old_callback is None or replace: + self._result_callback = f + return f + + def function(value: t.Any, /, *args: t.Any, **kwargs: t.Any) -> t.Any: + inner = old_callback(value, *args, **kwargs) + return f(inner, *args, **kwargs) + + self._result_callback = rv = update_wrapper(t.cast(F, function), f) + return rv # type: ignore[return-value] + + return decorator + + def get_command(self, ctx: Context, cmd_name: str) -> Command | None: + """Given a context and a command name, this returns a :class:`Command` + object if it exists or returns ``None``. + """ + return self.commands.get(cmd_name) + + def list_commands(self, ctx: Context) -> list[str]: + """Returns a list of subcommand names in the order they should appear.""" + return sorted(self.commands) + + def collect_usage_pieces(self, ctx: Context) -> list[str]: + rv = super().collect_usage_pieces(ctx) + rv.append(self.subcommand_metavar) + return rv + + def format_options(self, ctx: Context, formatter: HelpFormatter) -> None: + super().format_options(ctx, formatter) + self.format_commands(ctx, formatter) + + def format_commands(self, ctx: Context, formatter: HelpFormatter) -> None: + """Extra format methods for multi methods that adds all the commands + after the options. + """ + commands = [] + for subcommand in self.list_commands(ctx): + cmd = self.get_command(ctx, subcommand) + # What is this, the tool lied about a command. Ignore it + if cmd is None: + continue + if cmd.hidden: + continue + + commands.append((subcommand, cmd)) + + # allow for 3 times the default spacing + if len(commands): + limit = formatter.width - 6 - max(len(cmd[0]) for cmd in commands) + + rows = [] + for subcommand, cmd in commands: + help = cmd.get_short_help_str(limit) + rows.append((subcommand, help)) + + if rows: + with formatter.section(_("Commands")): + formatter.write_dl(rows) + + def parse_args(self, ctx: Context, args: list[str]) -> list[str]: + if not args and self.no_args_is_help and not ctx.resilient_parsing: + raise NoArgsIsHelpError(ctx) + + rest = super().parse_args(ctx, args) + + if self.chain: + ctx._protected_args = rest + ctx.args = [] + elif rest: + ctx._protected_args, ctx.args = rest[:1], rest[1:] + + return ctx.args + + def invoke(self, ctx: Context) -> t.Any: + def _process_result(value: t.Any) -> t.Any: + if self._result_callback is not None: + value = ctx.invoke(self._result_callback, value, **ctx.params) + return value + + if not ctx._protected_args: + if self.invoke_without_command: + # No subcommand was invoked, so the result callback is + # invoked with the group return value for regular + # groups, or an empty list for chained groups. + with ctx: + rv = super().invoke(ctx) + return _process_result([] if self.chain else rv) + ctx.fail(_("Missing command.")) + + # Fetch args back out + args = [*ctx._protected_args, *ctx.args] + ctx.args = [] + ctx._protected_args = [] + + # If we're not in chain mode, we only allow the invocation of a + # single command but we also inform the current context about the + # name of the command to invoke. + if not self.chain: + # Make sure the context is entered so we do not clean up + # resources until the result processor has worked. + with ctx: + cmd_name, cmd, args = self.resolve_command(ctx, args) + assert cmd is not None + ctx.invoked_subcommand = cmd_name + super().invoke(ctx) + sub_ctx = cmd.make_context(cmd_name, args, parent=ctx) + with sub_ctx: + return _process_result(sub_ctx.command.invoke(sub_ctx)) + + # In chain mode we create the contexts step by step, but after the + # base command has been invoked. Because at that point we do not + # know the subcommands yet, the invoked subcommand attribute is + # set to ``*`` to inform the command that subcommands are executed + # but nothing else. + with ctx: + ctx.invoked_subcommand = "*" if args else None + super().invoke(ctx) + + # Otherwise we make every single context and invoke them in a + # chain. In that case the return value to the result processor + # is the list of all invoked subcommand's results. + contexts = [] + while args: + cmd_name, cmd, args = self.resolve_command(ctx, args) + assert cmd is not None + sub_ctx = cmd.make_context( + cmd_name, + args, + parent=ctx, + allow_extra_args=True, + allow_interspersed_args=False, + ) + contexts.append(sub_ctx) + args, sub_ctx.args = sub_ctx.args, [] + + rv = [] + for sub_ctx in contexts: + with sub_ctx: + rv.append(sub_ctx.command.invoke(sub_ctx)) + return _process_result(rv) + + def resolve_command( + self, ctx: Context, args: list[str] + ) -> tuple[str | None, Command | None, list[str]]: + cmd_name = make_str(args[0]) + original_cmd_name = cmd_name + + # Get the command + cmd = self.get_command(ctx, cmd_name) + + # If we can't find the command but there is a normalization + # function available, we try with that one. + if cmd is None and ctx.token_normalize_func is not None: + cmd_name = ctx.token_normalize_func(cmd_name) + cmd = self.get_command(ctx, cmd_name) + + # If we don't find the command we want to show an error message + # to the user that it was not provided. However, there is + # something else we should do: if the first argument looks like + # an option we want to kick off parsing again for arguments to + # resolve things like --help which now should go to the main + # place. + if cmd is None and not ctx.resilient_parsing: + if _split_opt(cmd_name)[0]: + self.parse_args(ctx, args) + ctx.fail(_("No such command {name!r}.").format(name=original_cmd_name)) + return cmd_name if cmd else None, cmd, args[1:] + + def shell_complete(self, ctx: Context, incomplete: str) -> list[CompletionItem]: + """Return a list of completions for the incomplete value. Looks + at the names of options, subcommands, and chained + multi-commands. + + :param ctx: Invocation context for this command. + :param incomplete: Value being completed. May be empty. + + .. versionadded:: 8.0 + """ + from click.shell_completion import CompletionItem + + results = [ + CompletionItem(name, help=command.get_short_help_str()) + for name, command in _complete_visible_commands(ctx, incomplete) + ] + results.extend(super().shell_complete(ctx, incomplete)) + return results + + +class _MultiCommand(Group, metaclass=_FakeSubclassCheck): + """ + .. deprecated:: 8.2 + Will be removed in Click 9.0. Use ``Group`` instead. + """ + + +class CommandCollection(Group): + """A :class:`Group` that looks up subcommands on other groups. If a command + is not found on this group, each registered source is checked in order. + Parameters on a source are not added to this group, and a source's callback + is not invoked when invoking its commands. In other words, this "flattens" + commands in many groups into this one group. + + :param name: The name of the group command. + :param sources: A list of :class:`Group` objects to look up commands from. + :param kwargs: Other arguments passed to :class:`Group`. + + .. versionchanged:: 8.2 + This is a subclass of ``Group``. Commands are looked up first on this + group, then each of its sources. + """ + + def __init__( + self, + name: str | None = None, + sources: list[Group] | None = None, + **kwargs: t.Any, + ) -> None: + super().__init__(name, **kwargs) + #: The list of registered groups. + self.sources: list[Group] = sources or [] + + def add_source(self, group: Group) -> None: + """Add a group as a source of commands.""" + self.sources.append(group) + + def get_command(self, ctx: Context, cmd_name: str) -> Command | None: + rv = super().get_command(ctx, cmd_name) + + if rv is not None: + return rv + + for source in self.sources: + rv = source.get_command(ctx, cmd_name) + + if rv is not None: + if self.chain: + _check_nested_chain(self, cmd_name, rv) + + return rv + + return None + + def list_commands(self, ctx: Context) -> list[str]: + rv: set[str] = set(super().list_commands(ctx)) + + for source in self.sources: + rv.update(source.list_commands(ctx)) + + return sorted(rv) + + +def _check_iter(value: t.Any) -> cabc.Iterator[t.Any]: + """Check if the value is iterable but not a string. Raises a type + error, or return an iterator over the value. + """ + if isinstance(value, str): + raise TypeError + + return iter(value) + + +class Parameter: + r"""A parameter to a command comes in two versions: they are either + :class:`Option`\s or :class:`Argument`\s. Other subclasses are currently + not supported by design as some of the internals for parsing are + intentionally not finalized. + + Some settings are supported by both options and arguments. + + :param param_decls: the parameter declarations for this option or + argument. This is a list of flags or argument + names. + :param type: the type that should be used. Either a :class:`ParamType` + or a Python type. The latter is converted into the former + automatically if supported. + :param required: controls if this is optional or not. + :param default: the default value if omitted. This can also be a callable, + in which case it's invoked when the default is needed + without any arguments. + :param callback: A function to further process or validate the value + after type conversion. It is called as ``f(ctx, param, value)`` + and must return the value. It is called for all sources, + including prompts. + :param nargs: the number of arguments to match. If not ``1`` the return + value is a tuple instead of single value. The default for + nargs is ``1`` (except if the type is a tuple, then it's + the arity of the tuple). If ``nargs=-1``, all remaining + parameters are collected. + :param metavar: how the value is represented in the help page. + :param expose_value: if this is `True` then the value is passed onwards + to the command callback and stored on the context, + otherwise it's skipped. + :param is_eager: eager values are processed before non eager ones. This + should not be set for arguments or it will inverse the + order of processing. + :param envvar: environment variable(s) that are used to provide a default value for + this parameter. This can be a string or a sequence of strings. If a sequence is + given, only the first non-empty environment variable is used for the parameter. + :param shell_complete: A function that returns custom shell + completions. Used instead of the param's type completion if + given. Takes ``ctx, param, incomplete`` and must return a list + of :class:`~click.shell_completion.CompletionItem` or a list of + strings. + :param deprecated: If ``True`` or non-empty string, issues a message + indicating that the argument is deprecated and highlights + its deprecation in --help. The message can be customized + by using a string as the value. A deprecated parameter + cannot be required, a ValueError will be raised otherwise. + + .. versionchanged:: 8.2.0 + Introduction of ``deprecated``. + + .. versionchanged:: 8.2 + Adding duplicate parameter names to a :class:`~click.core.Command` will + result in a ``UserWarning`` being shown. + + .. versionchanged:: 8.2 + Adding duplicate parameter names to a :class:`~click.core.Command` will + result in a ``UserWarning`` being shown. + + .. versionchanged:: 8.0 + ``process_value`` validates required parameters and bounded + ``nargs``, and invokes the parameter callback before returning + the value. This allows the callback to validate prompts. + ``full_process_value`` is removed. + + .. versionchanged:: 8.0 + ``autocompletion`` is renamed to ``shell_complete`` and has new + semantics described above. The old name is deprecated and will + be removed in 8.1, until then it will be wrapped to match the + new requirements. + + .. versionchanged:: 8.0 + For ``multiple=True, nargs>1``, the default must be a list of + tuples. + + .. versionchanged:: 8.0 + Setting a default is no longer required for ``nargs>1``, it will + default to ``None``. ``multiple=True`` or ``nargs=-1`` will + default to ``()``. + + .. versionchanged:: 7.1 + Empty environment variables are ignored rather than taking the + empty string value. This makes it possible for scripts to clear + variables if they can't unset them. + + .. versionchanged:: 2.0 + Changed signature for parameter callback to also be passed the + parameter. The old callback format will still work, but it will + raise a warning to give you a chance to migrate the code easier. + """ + + param_type_name = "parameter" + + def __init__( + self, + param_decls: cabc.Sequence[str] | None = None, + type: types.ParamType | t.Any | None = None, + required: bool = False, + # XXX The default historically embed two concepts: + # - the declaration of a Parameter object carrying the default (handy to + # arbitrage the default value of coupled Parameters sharing the same + # self.name, like flag options), + # - and the actual value of the default. + # It is confusing and is the source of many issues discussed in: + # https://github.com/pallets/click/pull/3030 + # In the future, we might think of splitting it in two, not unlike + # Option.is_flag and Option.flag_value: we could have something like + # Parameter.is_default and Parameter.default_value. + default: t.Any | t.Callable[[], t.Any] | None = UNSET, + callback: t.Callable[[Context, Parameter, t.Any], t.Any] | None = None, + nargs: int | None = None, + multiple: bool = False, + metavar: str | None = None, + expose_value: bool = True, + is_eager: bool = False, + envvar: str | cabc.Sequence[str] | None = None, + shell_complete: t.Callable[ + [Context, Parameter, str], list[CompletionItem] | list[str] + ] + | None = None, + deprecated: bool | str = False, + ) -> None: + self.name: str | None + self.opts: list[str] + self.secondary_opts: list[str] + self.name, self.opts, self.secondary_opts = self._parse_decls( + param_decls or (), expose_value + ) + self.type: types.ParamType = types.convert_type(type, default) + + # Default nargs to what the type tells us if we have that + # information available. + if nargs is None: + if self.type.is_composite: + nargs = self.type.arity + else: + nargs = 1 + + self.required = required + self.callback = callback + self.nargs = nargs + self.multiple = multiple + self.expose_value = expose_value + self.default: t.Any | t.Callable[[], t.Any] | None = default + self.is_eager = is_eager + self.metavar = metavar + self.envvar = envvar + self._custom_shell_complete = shell_complete + self.deprecated = deprecated + + if __debug__: + if self.type.is_composite and nargs != self.type.arity: + raise ValueError( + f"'nargs' must be {self.type.arity} (or None) for" + f" type {self.type!r}, but it was {nargs}." + ) + + if required and deprecated: + raise ValueError( + f"The {self.param_type_name} '{self.human_readable_name}' " + "is deprecated and still required. A deprecated " + f"{self.param_type_name} cannot be required." + ) + + def to_info_dict(self) -> dict[str, t.Any]: + """Gather information that could be useful for a tool generating + user-facing documentation. + + Use :meth:`click.Context.to_info_dict` to traverse the entire + CLI structure. + + .. versionchanged:: 8.3.0 + Returns ``None`` for the :attr:`default` if it was not set. + + .. versionadded:: 8.0 + """ + return { + "name": self.name, + "param_type_name": self.param_type_name, + "opts": self.opts, + "secondary_opts": self.secondary_opts, + "type": self.type.to_info_dict(), + "required": self.required, + "nargs": self.nargs, + "multiple": self.multiple, + # We explicitly hide the :attr:`UNSET` value to the user, as we choose to + # make it an implementation detail. And because ``to_info_dict`` has been + # designed for documentation purposes, we return ``None`` instead. + "default": self.default if self.default is not UNSET else None, + "envvar": self.envvar, + } + + def __repr__(self) -> str: + return f"<{self.__class__.__name__} {self.name}>" + + def _parse_decls( + self, decls: cabc.Sequence[str], expose_value: bool + ) -> tuple[str | None, list[str], list[str]]: + raise NotImplementedError() + + @property + def human_readable_name(self) -> str: + """Returns the human readable name of this parameter. This is the + same as the name for options, but the metavar for arguments. + """ + return self.name # type: ignore + + def make_metavar(self, ctx: Context) -> str: + if self.metavar is not None: + return self.metavar + + metavar = self.type.get_metavar(param=self, ctx=ctx) + + if metavar is None: + metavar = self.type.name.upper() + + if self.nargs != 1: + metavar += "..." + + return metavar + + @t.overload + def get_default( + self, ctx: Context, call: t.Literal[True] = True + ) -> t.Any | None: ... + + @t.overload + def get_default( + self, ctx: Context, call: bool = ... + ) -> t.Any | t.Callable[[], t.Any] | None: ... + + def get_default( + self, ctx: Context, call: bool = True + ) -> t.Any | t.Callable[[], t.Any] | None: + """Get the default for the parameter. Tries + :meth:`Context.lookup_default` first, then the local default. + + :param ctx: Current context. + :param call: If the default is a callable, call it. Disable to + return the callable instead. + + .. versionchanged:: 8.0.2 + Type casting is no longer performed when getting a default. + + .. versionchanged:: 8.0.1 + Type casting can fail in resilient parsing mode. Invalid + defaults will not prevent showing help text. + + .. versionchanged:: 8.0 + Looks at ``ctx.default_map`` first. + + .. versionchanged:: 8.0 + Added the ``call`` parameter. + """ + name = self.name + value = ctx.lookup_default(name, call=False) if name is not None else None + + if value is None and not ( + ctx.default_map is not None and name is not None and name in ctx.default_map + ): + value = self.default + + if call and callable(value): + value = value() + + return value + + def add_to_parser(self, parser: _OptionParser, ctx: Context) -> None: + raise NotImplementedError() + + def consume_value( + self, ctx: Context, opts: cabc.Mapping[str, t.Any] + ) -> tuple[t.Any, ParameterSource]: + """Returns the parameter value produced by the parser. + + If the parser did not produce a value from user input, the value is either + sourced from the environment variable, the default map, or the parameter's + default value. In that order of precedence. + + If no value is found, an internal sentinel value is returned. + + :meta private: + """ + # Collect from the parse the value passed by the user to the CLI. + value = opts.get(self.name, UNSET) # type: ignore + # If the value is set, it means it was sourced from the command line by the + # parser, otherwise it left unset by default. + source = ( + ParameterSource.COMMANDLINE + if value is not UNSET + else ParameterSource.DEFAULT + ) + + if value is UNSET: + envvar_value = self.value_from_envvar(ctx) + if envvar_value is not None: + value = envvar_value + source = ParameterSource.ENVIRONMENT + + if value is UNSET: + default_map_value = ctx.lookup_default(self.name) # type: ignore[arg-type] + if default_map_value is not None or ( + ctx.default_map is not None and self.name in ctx.default_map + ): + value = default_map_value + source = ParameterSource.DEFAULT_MAP + + if value is UNSET: + default_value = self.get_default(ctx) + if default_value is not UNSET: + value = default_value + source = ParameterSource.DEFAULT + + return value, source + + def type_cast_value(self, ctx: Context, value: t.Any) -> t.Any: + """Convert and validate a value against the parameter's + :attr:`type`, :attr:`multiple`, and :attr:`nargs`. + """ + if value is None: + if self.multiple or self.nargs == -1: + return () + else: + return value + + def check_iter(value: t.Any) -> cabc.Iterator[t.Any]: + try: + return _check_iter(value) + except TypeError: + # This should only happen when passing in args manually, + # the parser should construct an iterable when parsing + # the command line. + raise BadParameter( + _("Value must be an iterable."), ctx=ctx, param=self + ) from None + + # Define the conversion function based on nargs and type. + + if self.nargs == 1 or self.type.is_composite: + + def convert(value: t.Any) -> t.Any: + return self.type(value, param=self, ctx=ctx) + + elif self.nargs == -1: + + def convert(value: t.Any) -> t.Any: # tuple[t.Any, ...] + return tuple(self.type(x, self, ctx) for x in check_iter(value)) + + else: # nargs > 1 + + def convert(value: t.Any) -> t.Any: # tuple[t.Any, ...] + value = tuple(check_iter(value)) + + if len(value) != self.nargs: + raise BadParameter( + ngettext( + "Takes {nargs} values but 1 was given.", + "Takes {nargs} values but {len} were given.", + len(value), + ).format(nargs=self.nargs, len=len(value)), + ctx=ctx, + param=self, + ) + + return tuple(self.type(x, self, ctx) for x in value) + + if self.multiple: + return tuple(convert(x) for x in check_iter(value)) + + return convert(value) + + def value_is_missing(self, value: t.Any) -> bool: + """A value is considered missing if: + + - it is :attr:`UNSET`, + - or if it is an empty sequence while the parameter is suppose to have + non-single value (i.e. :attr:`nargs` is not ``1`` or :attr:`multiple` is + set). + + :meta private: + """ + if value is UNSET: + return True + + if (self.nargs != 1 or self.multiple) and value == (): + return True + + return False + + def process_value(self, ctx: Context, value: t.Any) -> t.Any: + """Process the value of this parameter: + + 1. Type cast the value using :meth:`type_cast_value`. + 2. Check if the value is missing (see: :meth:`value_is_missing`), and raise + :exc:`MissingParameter` if it is required. + 3. If a :attr:`callback` is set, call it to have the value replaced by the + result of the callback. If the value was not set, the callback receive + ``None``. This keep the legacy behavior as it was before the introduction of + the :attr:`UNSET` sentinel. + + :meta private: + """ + # shelter `type_cast_value` from ever seeing an `UNSET` value by handling the + # cases in which `UNSET` gets special treatment explicitly at this layer + # + # Refs: + # https://github.com/pallets/click/issues/3069 + if value is UNSET: + if self.multiple or self.nargs == -1: + value = () + else: + value = self.type_cast_value(ctx, value) + + if self.required and self.value_is_missing(value): + raise MissingParameter(ctx=ctx, param=self) + + if self.callback is not None: + # Legacy case: UNSET is not exposed directly to the callback, but converted + # to None. + if value is UNSET: + value = None + + # Search for parameters with UNSET values in the context. + unset_keys = {k: None for k, v in ctx.params.items() if v is UNSET} + # No UNSET values, call the callback as usual. + if not unset_keys: + value = self.callback(ctx, self, value) + + # Legacy case: provide a temporarily manipulated context to the callback + # to hide UNSET values as None. + # + # Refs: + # https://github.com/pallets/click/issues/3136 + # https://github.com/pallets/click/pull/3137 + else: + # Add another layer to the context stack to clearly hint that the + # context is temporarily modified. + with ctx: + # Update the context parameters to replace UNSET with None. + ctx.params.update(unset_keys) + # Feed these fake context parameters to the callback. + value = self.callback(ctx, self, value) + # Restore the UNSET values in the context parameters. + ctx.params.update( + { + k: UNSET + for k in unset_keys + # Only restore keys that are present and still None, in case + # the callback modified other parameters. + if k in ctx.params and ctx.params[k] is None + } + ) + + return value + + def resolve_envvar_value(self, ctx: Context) -> str | None: + """Returns the value found in the environment variable(s) attached to this + parameter. + + Environment variables values are `always returned as strings + `_. + + This method returns ``None`` if: + + - the :attr:`envvar` property is not set on the :class:`Parameter`, + - the environment variable is not found in the environment, + - the variable is found in the environment but its value is empty (i.e. the + environment variable is present but has an empty string). + + If :attr:`envvar` is setup with multiple environment variables, + then only the first non-empty value is returned. + + .. caution:: + + The raw value extracted from the environment is not normalized and is + returned as-is. Any normalization or reconciliation is performed later by + the :class:`Parameter`'s :attr:`type`. + + :meta private: + """ + if not self.envvar: + return None + + if isinstance(self.envvar, str): + rv = os.environ.get(self.envvar) + + if rv: + return rv + else: + for envvar in self.envvar: + rv = os.environ.get(envvar) + + # Return the first non-empty value of the list of environment variables. + if rv: + return rv + # Else, absence of value is interpreted as an environment variable that + # is not set, so proceed to the next one. + + return None + + def value_from_envvar(self, ctx: Context) -> str | cabc.Sequence[str] | None: + """Process the raw environment variable string for this parameter. + + Returns the string as-is or splits it into a sequence of strings if the + parameter is expecting multiple values (i.e. its :attr:`nargs` property is set + to a value other than ``1``). + + :meta private: + """ + rv = self.resolve_envvar_value(ctx) + + if rv is not None and self.nargs != 1: + return self.type.split_envvar_value(rv) + + return rv + + def handle_parse_result( + self, ctx: Context, opts: cabc.Mapping[str, t.Any], args: list[str] + ) -> tuple[t.Any, list[str]]: + """Process the value produced by the parser from user input. + + Always process the value through the Parameter's :attr:`type`, wherever it + comes from. + + If the parameter is deprecated, this method warn the user about it. But only if + the value has been explicitly set by the user (and as such, is not coming from + a default). + + :meta private: + """ + with augment_usage_errors(ctx, param=self): + value, source = self.consume_value(ctx, opts) + + ctx.set_parameter_source(self.name, source) # type: ignore + + # Display a deprecation warning if necessary. + if ( + self.deprecated + and value is not UNSET + and source not in (ParameterSource.DEFAULT, ParameterSource.DEFAULT_MAP) + ): + extra_message = ( + f" {self.deprecated}" if isinstance(self.deprecated, str) else "" + ) + message = _( + "DeprecationWarning: The {param_type} {name!r} is deprecated." + "{extra_message}" + ).format( + param_type=self.param_type_name, + name=self.human_readable_name, + extra_message=extra_message, + ) + echo(style(message, fg="red"), err=True) + + # Process the value through the parameter's type. + try: + value = self.process_value(ctx, value) + except Exception: + if not ctx.resilient_parsing: + raise + # In resilient parsing mode, we do not want to fail the command if the + # value is incompatible with the parameter type, so we reset the value + # to UNSET, which will be interpreted as a missing value. + value = UNSET + + # Add parameter's value to the context. + if ( + self.expose_value + # We skip adding the value if it was previously set by another parameter + # targeting the same variable name. This prevents parameters competing for + # the same name to override each other. + and (self.name not in ctx.params or ctx.params[self.name] is UNSET) + ): + # Click is logically enforcing that the name is None if the parameter is + # not to be exposed. We still assert it here to please the type checker. + assert self.name is not None, ( + f"{self!r} parameter's name should not be None when exposing value." + ) + ctx.params[self.name] = value + + return value, args + + def get_help_record(self, ctx: Context) -> tuple[str, str] | None: + pass + + def get_usage_pieces(self, ctx: Context) -> list[str]: + return [] + + def get_error_hint(self, ctx: Context) -> str: + """Get a stringified version of the param for use in error messages to + indicate which param caused the error. + """ + hint_list = self.opts or [self.human_readable_name] + return " / ".join(f"'{x}'" for x in hint_list) + + def shell_complete(self, ctx: Context, incomplete: str) -> list[CompletionItem]: + """Return a list of completions for the incomplete value. If a + ``shell_complete`` function was given during init, it is used. + Otherwise, the :attr:`type` + :meth:`~click.types.ParamType.shell_complete` function is used. + + :param ctx: Invocation context for this command. + :param incomplete: Value being completed. May be empty. + + .. versionadded:: 8.0 + """ + if self._custom_shell_complete is not None: + results = self._custom_shell_complete(ctx, self, incomplete) + + if results and isinstance(results[0], str): + from click.shell_completion import CompletionItem + + results = [CompletionItem(c) for c in results] + + return t.cast("list[CompletionItem]", results) + + return self.type.shell_complete(ctx, self, incomplete) + + +class Option(Parameter): + """Options are usually optional values on the command line and + have some extra features that arguments don't have. + + All other parameters are passed onwards to the parameter constructor. + + :param show_default: Show the default value for this option in its + help text. Values are not shown by default, unless + :attr:`Context.show_default` is ``True``. If this value is a + string, it shows that string in parentheses instead of the + actual value. This is particularly useful for dynamic options. + For single option boolean flags, the default remains hidden if + its value is ``False``. + :param show_envvar: Controls if an environment variable should be + shown on the help page and error messages. + Normally, environment variables are not shown. + :param prompt: If set to ``True`` or a non empty string then the + user will be prompted for input. If set to ``True`` the prompt + will be the option name capitalized. A deprecated option cannot be + prompted. + :param confirmation_prompt: Prompt a second time to confirm the + value if it was prompted for. Can be set to a string instead of + ``True`` to customize the message. + :param prompt_required: If set to ``False``, the user will be + prompted for input only when the option was specified as a flag + without a value. + :param hide_input: If this is ``True`` then the input on the prompt + will be hidden from the user. This is useful for password input. + :param is_flag: forces this option to act as a flag. The default is + auto detection. + :param flag_value: which value should be used for this flag if it's + enabled. This is set to a boolean automatically if + the option string contains a slash to mark two options. + :param multiple: if this is set to `True` then the argument is accepted + multiple times and recorded. This is similar to ``nargs`` + in how it works but supports arbitrary number of + arguments. + :param count: this flag makes an option increment an integer. + :param allow_from_autoenv: if this is enabled then the value of this + parameter will be pulled from an environment + variable in case a prefix is defined on the + context. + :param help: the help string. + :param hidden: hide this option from help outputs. + :param attrs: Other command arguments described in :class:`Parameter`. + + .. versionchanged:: 8.2 + ``envvar`` used with ``flag_value`` will always use the ``flag_value``, + previously it would use the value of the environment variable. + + .. versionchanged:: 8.1 + Help text indentation is cleaned here instead of only in the + ``@option`` decorator. + + .. versionchanged:: 8.1 + The ``show_default`` parameter overrides + ``Context.show_default``. + + .. versionchanged:: 8.1 + The default of a single option boolean flag is not shown if the + default value is ``False``. + + .. versionchanged:: 8.0.1 + ``type`` is detected from ``flag_value`` if given. + """ + + param_type_name = "option" + + def __init__( + self, + param_decls: cabc.Sequence[str] | None = None, + show_default: bool | str | None = None, + prompt: bool | str = False, + confirmation_prompt: bool | str = False, + prompt_required: bool = True, + hide_input: bool = False, + is_flag: bool | None = None, + flag_value: t.Any = UNSET, + multiple: bool = False, + count: bool = False, + allow_from_autoenv: bool = True, + type: types.ParamType | t.Any | None = None, + help: str | None = None, + hidden: bool = False, + show_choices: bool = True, + show_envvar: bool = False, + deprecated: bool | str = False, + **attrs: t.Any, + ) -> None: + if help: + help = inspect.cleandoc(help) + + super().__init__( + param_decls, type=type, multiple=multiple, deprecated=deprecated, **attrs + ) + + if prompt is True: + if self.name is None: + raise TypeError("'name' is required with 'prompt=True'.") + + prompt_text: str | None = self.name.replace("_", " ").capitalize() + elif prompt is False: + prompt_text = None + else: + prompt_text = prompt + + if deprecated: + deprecated_message = ( + f"(DEPRECATED: {deprecated})" + if isinstance(deprecated, str) + else "(DEPRECATED)" + ) + help = help + deprecated_message if help is not None else deprecated_message + + self.prompt = prompt_text + self.confirmation_prompt = confirmation_prompt + self.prompt_required = prompt_required + self.hide_input = hide_input + self.hidden = hidden + + # The _flag_needs_value property tells the parser that this option is a flag + # that cannot be used standalone and needs a value. With this information, the + # parser can determine whether to consider the next user-provided argument in + # the CLI as a value for this flag or as a new option. + # If prompt is enabled but not required, then it opens the possibility for the + # option to gets its value from the user. + self._flag_needs_value = self.prompt is not None and not self.prompt_required + + # Auto-detect if this is a flag or not. + if is_flag is None: + # Implicitly a flag because flag_value was set. + if flag_value is not UNSET: + is_flag = True + # Not a flag, but when used as a flag it shows a prompt. + elif self._flag_needs_value: + is_flag = False + # Implicitly a flag because secondary options names were given. + elif self.secondary_opts: + is_flag = True + + # The option is explicitly not a flag, but to determine whether or not it needs + # value, we need to check if `flag_value` or `default` was set. Either one is + # sufficient. + # Ref: https://github.com/pallets/click/issues/3084 + elif is_flag is False and not self._flag_needs_value: + self._flag_needs_value = flag_value is not UNSET or self.default is UNSET + + if is_flag: + # Set missing default for flags if not explicitly required or prompted. + if self.default is UNSET and not self.required and not self.prompt: + if multiple: + self.default = () + + # Auto-detect the type of the flag based on the flag_value. + if type is None: + # A flag without a flag_value is a boolean flag. + if flag_value is UNSET: + self.type: types.ParamType = types.BoolParamType() + # If the flag value is a boolean, use BoolParamType. + elif isinstance(flag_value, bool): + self.type = types.BoolParamType() + # Otherwise, guess the type from the flag value. + else: + self.type = types.convert_type(None, flag_value) + + self.is_flag: bool = bool(is_flag) + self.is_bool_flag: bool = bool( + is_flag and isinstance(self.type, types.BoolParamType) + ) + self.flag_value: t.Any = flag_value + + # Set boolean flag default to False if unset and not required. + if self.is_bool_flag: + if self.default is UNSET and not self.required: + self.default = False + + # The alignement of default to the flag_value is resolved lazily in + # get_default() to prevent callable flag_values (like classes) from + # being instantiated. Refs: + # https://github.com/pallets/click/issues/3121 + # https://github.com/pallets/click/issues/3024#issuecomment-3146199461 + # https://github.com/pallets/click/pull/3030/commits/06847da + + # Set the default flag_value if it is not set. + if self.flag_value is UNSET: + if self.is_flag: + self.flag_value = True + else: + self.flag_value = None + + # Counting. + self.count = count + if count: + if type is None: + self.type = types.IntRange(min=0) + if self.default is UNSET: + self.default = 0 + + self.allow_from_autoenv = allow_from_autoenv + self.help = help + self.show_default = show_default + self.show_choices = show_choices + self.show_envvar = show_envvar + + if __debug__: + if deprecated and prompt: + raise ValueError("`deprecated` options cannot use `prompt`.") + + if self.nargs == -1: + raise TypeError("nargs=-1 is not supported for options.") + + if not self.is_bool_flag and self.secondary_opts: + raise TypeError("Secondary flag is not valid for non-boolean flag.") + + if self.is_bool_flag and self.hide_input and self.prompt is not None: + raise TypeError( + "'prompt' with 'hide_input' is not valid for boolean flag." + ) + + if self.count: + if self.multiple: + raise TypeError("'count' is not valid with 'multiple'.") + + if self.is_flag: + raise TypeError("'count' is not valid with 'is_flag'.") + + def to_info_dict(self) -> dict[str, t.Any]: + """ + .. versionchanged:: 8.3.0 + Returns ``None`` for the :attr:`flag_value` if it was not set. + """ + info_dict = super().to_info_dict() + info_dict.update( + help=self.help, + prompt=self.prompt, + is_flag=self.is_flag, + # We explicitly hide the :attr:`UNSET` value to the user, as we choose to + # make it an implementation detail. And because ``to_info_dict`` has been + # designed for documentation purposes, we return ``None`` instead. + flag_value=self.flag_value if self.flag_value is not UNSET else None, + count=self.count, + hidden=self.hidden, + ) + return info_dict + + def get_default( + self, ctx: Context, call: bool = True + ) -> t.Any | t.Callable[[], t.Any] | None: + value = super().get_default(ctx, call=False) + + # Lazily resolve default=True to flag_value. Doing this here + # (instead of eagerly in __init__) prevents callable flag_values + # (like classes) from being instantiated by the callable check below. + # https://github.com/pallets/click/issues/3121 + if value is True and self.is_flag: + value = self.flag_value + elif call and callable(value): + value = value() + + return value + + def get_error_hint(self, ctx: Context) -> str: + result = super().get_error_hint(ctx) + if self.show_envvar and self.envvar is not None: + result += f" (env var: '{self.envvar}')" + return result + + def _parse_decls( + self, decls: cabc.Sequence[str], expose_value: bool + ) -> tuple[str | None, list[str], list[str]]: + opts = [] + secondary_opts = [] + name = None + possible_names = [] + + for decl in decls: + if decl.isidentifier(): + if name is not None: + raise TypeError(f"Name '{name}' defined twice") + name = decl + else: + split_char = ";" if decl[:1] == "/" else "/" + if split_char in decl: + first, second = decl.split(split_char, 1) + first = first.rstrip() + if first: + possible_names.append(_split_opt(first)) + opts.append(first) + second = second.lstrip() + if second: + secondary_opts.append(second.lstrip()) + if first == second: + raise ValueError( + f"Boolean option {decl!r} cannot use the" + " same flag for true/false." + ) + else: + possible_names.append(_split_opt(decl)) + opts.append(decl) + + if name is None and possible_names: + possible_names.sort(key=lambda x: -len(x[0])) # group long options first + name = possible_names[0][1].replace("-", "_").lower() + if not name.isidentifier(): + name = None + + if name is None: + if not expose_value: + return None, opts, secondary_opts + raise TypeError( + f"Could not determine name for option with declarations {decls!r}" + ) + + if not opts and not secondary_opts: + raise TypeError( + f"No options defined but a name was passed ({name})." + " Did you mean to declare an argument instead? Did" + f" you mean to pass '--{name}'?" + ) + + return name, opts, secondary_opts + + def add_to_parser(self, parser: _OptionParser, ctx: Context) -> None: + if self.multiple: + action = "append" + elif self.count: + action = "count" + else: + action = "store" + + if self.is_flag: + action = f"{action}_const" + + if self.is_bool_flag and self.secondary_opts: + parser.add_option( + obj=self, opts=self.opts, dest=self.name, action=action, const=True + ) + parser.add_option( + obj=self, + opts=self.secondary_opts, + dest=self.name, + action=action, + const=False, + ) + else: + parser.add_option( + obj=self, + opts=self.opts, + dest=self.name, + action=action, + const=self.flag_value, + ) + else: + parser.add_option( + obj=self, + opts=self.opts, + dest=self.name, + action=action, + nargs=self.nargs, + ) + + def get_help_record(self, ctx: Context) -> tuple[str, str] | None: + if self.hidden: + return None + + any_prefix_is_slash = False + + def _write_opts(opts: cabc.Sequence[str]) -> str: + nonlocal any_prefix_is_slash + + rv, any_slashes = join_options(opts) + + if any_slashes: + any_prefix_is_slash = True + + if not self.is_flag and not self.count: + rv += f" {self.make_metavar(ctx=ctx)}" + + return rv + + rv = [_write_opts(self.opts)] + + if self.secondary_opts: + rv.append(_write_opts(self.secondary_opts)) + + help = self.help or "" + + extra = self.get_help_extra(ctx) + extra_items = [] + if "envvars" in extra: + extra_items.append( + _("env var: {var}").format(var=", ".join(extra["envvars"])) + ) + if "default" in extra: + extra_items.append(_("default: {default}").format(default=extra["default"])) + if "range" in extra: + extra_items.append(extra["range"]) + if "required" in extra: + extra_items.append(_(extra["required"])) + + if extra_items: + extra_str = "; ".join(extra_items) + help = f"{help} [{extra_str}]" if help else f"[{extra_str}]" + + return ("; " if any_prefix_is_slash else " / ").join(rv), help + + def get_help_extra(self, ctx: Context) -> types.OptionHelpExtra: + extra: types.OptionHelpExtra = {} + + if self.show_envvar: + envvar = self.envvar + + if envvar is None: + if ( + self.allow_from_autoenv + and ctx.auto_envvar_prefix is not None + and self.name is not None + ): + envvar = f"{ctx.auto_envvar_prefix}_{self.name.upper()}" + + if envvar is not None: + if isinstance(envvar, str): + extra["envvars"] = (envvar,) + else: + extra["envvars"] = tuple(str(d) for d in envvar) + + # Temporarily enable resilient parsing to avoid type casting + # failing for the default. Might be possible to extend this to + # help formatting in general. + resilient = ctx.resilient_parsing + ctx.resilient_parsing = True + + try: + default_value = self.get_default(ctx, call=False) + finally: + ctx.resilient_parsing = resilient + + show_default = False + show_default_is_str = False + + if self.show_default is not None: + if isinstance(self.show_default, str): + show_default_is_str = show_default = True + else: + show_default = self.show_default + elif ctx.show_default is not None: + show_default = ctx.show_default + + if show_default_is_str or ( + show_default and (default_value not in (None, UNSET)) + ): + if show_default_is_str: + default_string = f"({self.show_default})" + elif isinstance(default_value, (list, tuple)): + default_string = ", ".join(str(d) for d in default_value) + elif isinstance(default_value, enum.Enum): + default_string = default_value.name + elif inspect.isfunction(default_value): + default_string = _("(dynamic)") + elif self.is_bool_flag and self.secondary_opts: + # For boolean flags that have distinct True/False opts, + # use the opt without prefix instead of the value. + default_string = _split_opt( + (self.opts if default_value else self.secondary_opts)[0] + )[1] + elif self.is_bool_flag and not self.secondary_opts and not default_value: + default_string = "" + elif default_value == "": + default_string = '""' + else: + default_string = str(default_value) + + if default_string: + extra["default"] = default_string + + if ( + isinstance(self.type, types._NumberRangeBase) + # skip count with default range type + and not (self.count and self.type.min == 0 and self.type.max is None) + ): + range_str = self.type._describe_range() + + if range_str: + extra["range"] = range_str + + if self.required: + extra["required"] = "required" + + return extra + + def prompt_for_value(self, ctx: Context) -> t.Any: + """This is an alternative flow that can be activated in the full + value processing if a value does not exist. It will prompt the + user until a valid value exists and then returns the processed + value as result. + """ + assert self.prompt is not None + + # Calculate the default before prompting anything to lock in the value before + # attempting any user interaction. + default = self.get_default(ctx) + + # A boolean flag can use a simplified [y/n] confirmation prompt. + if self.is_bool_flag: + # If we have no boolean default, we force the user to explicitly provide + # one. + if default in (UNSET, None): + default = None + # Nothing prevent you to declare an option that is simultaneously: + # 1) auto-detected as a boolean flag, + # 2) allowed to prompt, and + # 3) still declare a non-boolean default. + # This forced casting into a boolean is necessary to align any non-boolean + # default to the prompt, which is going to be a [y/n]-style confirmation + # because the option is still a boolean flag. That way, instead of [y/n], + # we get [Y/n] or [y/N] depending on the truthy value of the default. + # Refs: https://github.com/pallets/click/pull/3030#discussion_r2289180249 + else: + default = bool(default) + return confirm(self.prompt, default) + + # If show_default is set to True/False, provide this to `prompt` as well. For + # non-bool values of `show_default`, we use `prompt`'s default behavior + prompt_kwargs: t.Any = {} + if isinstance(self.show_default, bool): + prompt_kwargs["show_default"] = self.show_default + + return prompt( + self.prompt, + # Use ``None`` to inform the prompt() function to reiterate until a valid + # value is provided by the user if we have no default. + default=None if default is UNSET else default, + type=self.type, + hide_input=self.hide_input, + show_choices=self.show_choices, + confirmation_prompt=self.confirmation_prompt, + value_proc=lambda x: self.process_value(ctx, x), + **prompt_kwargs, + ) + + def resolve_envvar_value(self, ctx: Context) -> str | None: + """:class:`Option` resolves its environment variable the same way as + :func:`Parameter.resolve_envvar_value`, but it also supports + :attr:`Context.auto_envvar_prefix`. If we could not find an environment from + the :attr:`envvar` property, we fallback on :attr:`Context.auto_envvar_prefix` + to build dynamiccaly the environment variable name using the + :python:`{ctx.auto_envvar_prefix}_{self.name.upper()}` template. + + :meta private: + """ + rv = super().resolve_envvar_value(ctx) + + if rv is not None: + return rv + + if ( + self.allow_from_autoenv + and ctx.auto_envvar_prefix is not None + and self.name is not None + ): + envvar = f"{ctx.auto_envvar_prefix}_{self.name.upper()}" + rv = os.environ.get(envvar) + + if rv: + return rv + + return None + + def value_from_envvar(self, ctx: Context) -> t.Any: + """For :class:`Option`, this method processes the raw environment variable + string the same way as :func:`Parameter.value_from_envvar` does. + + But in the case of non-boolean flags, the value is analyzed to determine if the + flag is activated or not, and returns a boolean of its activation, or the + :attr:`flag_value` if the latter is set. + + This method also takes care of repeated options (i.e. options with + :attr:`multiple` set to ``True``). + + :meta private: + """ + rv = self.resolve_envvar_value(ctx) + + # Absent environment variable or an empty string is interpreted as unset. + if rv is None: + return None + + # Non-boolean flags are more liberal in what they accept. But a flag being a + # flag, its envvar value still needs to be analyzed to determine if the flag is + # activated or not. + if self.is_flag and not self.is_bool_flag: + # If the flag_value is set and match the envvar value, return it + # directly. + if self.flag_value is not UNSET and rv == self.flag_value: + return self.flag_value + # Analyze the envvar value as a boolean to know if the flag is + # activated or not. + return types.BoolParamType.str_to_bool(rv) + + # Split the envvar value if it is allowed to be repeated. + value_depth = (self.nargs != 1) + bool(self.multiple) + if value_depth > 0: + multi_rv = self.type.split_envvar_value(rv) + if self.multiple and self.nargs != 1: + multi_rv = batch(multi_rv, self.nargs) # type: ignore[assignment] + + return multi_rv + + return rv + + def consume_value( + self, ctx: Context, opts: cabc.Mapping[str, Parameter] + ) -> tuple[t.Any, ParameterSource]: + """For :class:`Option`, the value can be collected from an interactive prompt + if the option is a flag that needs a value (and the :attr:`prompt` property is + set). + + Additionally, this method handles flag option that are activated without a + value, in which case the :attr:`flag_value` is returned. + + :meta private: + """ + value, source = super().consume_value(ctx, opts) + + # The parser will emit a sentinel value if the option is allowed to as a flag + # without a value. + if value is FLAG_NEEDS_VALUE: + # If the option allows for a prompt, we start an interaction with the user. + if self.prompt is not None and not ctx.resilient_parsing: + value = self.prompt_for_value(ctx) + source = ParameterSource.PROMPT + # Else the flag takes its flag_value as value. + else: + value = self.flag_value + source = ParameterSource.COMMANDLINE + + # A flag which is activated always returns the flag value, unless the value + # comes from the explicitly sets default. + elif ( + self.is_flag + and value is True + and not self.is_bool_flag + and source not in (ParameterSource.DEFAULT, ParameterSource.DEFAULT_MAP) + ): + value = self.flag_value + + # Re-interpret a multiple option which has been sent as-is by the parser. + # Here we replace each occurrence of value-less flags (marked by the + # FLAG_NEEDS_VALUE sentinel) with the flag_value. + elif ( + self.multiple + and value is not UNSET + and source not in (ParameterSource.DEFAULT, ParameterSource.DEFAULT_MAP) + and any(v is FLAG_NEEDS_VALUE for v in value) + ): + value = [self.flag_value if v is FLAG_NEEDS_VALUE else v for v in value] + source = ParameterSource.COMMANDLINE + + # The value wasn't set, or used the param's default, prompt for one to the user + # if prompting is enabled. + elif ( + ( + value is UNSET + or source in (ParameterSource.DEFAULT, ParameterSource.DEFAULT_MAP) + ) + and self.prompt is not None + and (self.required or self.prompt_required) + and not ctx.resilient_parsing + ): + value = self.prompt_for_value(ctx) + source = ParameterSource.PROMPT + + return value, source + + def process_value(self, ctx: Context, value: t.Any) -> t.Any: + # process_value has to be overridden on Options in order to capture + # `value == UNSET` cases before `type_cast_value()` gets called. + # + # Refs: + # https://github.com/pallets/click/issues/3069 + if self.is_flag and not self.required and self.is_bool_flag and value is UNSET: + value = False + + if self.callback is not None: + value = self.callback(ctx, self, value) + + return value + + # in the normal case, rely on Parameter.process_value + return super().process_value(ctx, value) + + +class Argument(Parameter): + """Arguments are positional parameters to a command. They generally + provide fewer features than options but can have infinite ``nargs`` + and are required by default. + + All parameters are passed onwards to the constructor of :class:`Parameter`. + """ + + param_type_name = "argument" + + def __init__( + self, + param_decls: cabc.Sequence[str], + required: bool | None = None, + **attrs: t.Any, + ) -> None: + # Auto-detect the requirement status of the argument if not explicitly set. + if required is None: + # The argument gets automatically required if it has no explicit default + # value set and is setup to match at least one value. + if attrs.get("default", UNSET) is UNSET: + required = attrs.get("nargs", 1) > 0 + # If the argument has a default value, it is not required. + else: + required = False + + if "multiple" in attrs: + raise TypeError("__init__() got an unexpected keyword argument 'multiple'.") + + super().__init__(param_decls, required=required, **attrs) + + @property + def human_readable_name(self) -> str: + if self.metavar is not None: + return self.metavar + return self.name.upper() # type: ignore + + def make_metavar(self, ctx: Context) -> str: + if self.metavar is not None: + return self.metavar + var = self.type.get_metavar(param=self, ctx=ctx) + if not var: + var = self.name.upper() # type: ignore + if self.deprecated: + var += "!" + if not self.required: + var = f"[{var}]" + if self.nargs != 1: + var += "..." + return var + + def _parse_decls( + self, decls: cabc.Sequence[str], expose_value: bool + ) -> tuple[str | None, list[str], list[str]]: + if not decls: + if not expose_value: + return None, [], [] + raise TypeError("Argument is marked as exposed, but does not have a name.") + if len(decls) == 1: + name = arg = decls[0] + name = name.replace("-", "_").lower() + else: + raise TypeError( + "Arguments take exactly one parameter declaration, got" + f" {len(decls)}: {decls}." + ) + return name, [arg], [] + + def get_usage_pieces(self, ctx: Context) -> list[str]: + return [self.make_metavar(ctx)] + + def get_error_hint(self, ctx: Context) -> str: + return f"'{self.make_metavar(ctx)}'" + + def add_to_parser(self, parser: _OptionParser, ctx: Context) -> None: + parser.add_argument(dest=self.name, nargs=self.nargs, obj=self) + + +def __getattr__(name: str) -> object: + import warnings + + if name == "BaseCommand": + warnings.warn( + "'BaseCommand' is deprecated and will be removed in Click 9.0. Use" + " 'Command' instead.", + DeprecationWarning, + stacklevel=2, + ) + return _BaseCommand + + if name == "MultiCommand": + warnings.warn( + "'MultiCommand' is deprecated and will be removed in Click 9.0. Use" + " 'Group' instead.", + DeprecationWarning, + stacklevel=2, + ) + return _MultiCommand + + raise AttributeError(name) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/click/decorators.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/click/decorators.py new file mode 100644 index 000000000..21f4c3422 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/click/decorators.py @@ -0,0 +1,551 @@ +from __future__ import annotations + +import inspect +import typing as t +from functools import update_wrapper +from gettext import gettext as _ + +from .core import Argument +from .core import Command +from .core import Context +from .core import Group +from .core import Option +from .core import Parameter +from .globals import get_current_context +from .utils import echo + +if t.TYPE_CHECKING: + import typing_extensions as te + + P = te.ParamSpec("P") + +R = t.TypeVar("R") +T = t.TypeVar("T") +_AnyCallable = t.Callable[..., t.Any] +FC = t.TypeVar("FC", bound="_AnyCallable | Command") + + +def pass_context(f: t.Callable[te.Concatenate[Context, P], R]) -> t.Callable[P, R]: + """Marks a callback as wanting to receive the current context + object as first argument. + """ + + def new_func(*args: P.args, **kwargs: P.kwargs) -> R: + return f(get_current_context(), *args, **kwargs) + + return update_wrapper(new_func, f) + + +def pass_obj(f: t.Callable[te.Concatenate[T, P], R]) -> t.Callable[P, R]: + """Similar to :func:`pass_context`, but only pass the object on the + context onwards (:attr:`Context.obj`). This is useful if that object + represents the state of a nested system. + """ + + def new_func(*args: P.args, **kwargs: P.kwargs) -> R: + return f(get_current_context().obj, *args, **kwargs) + + return update_wrapper(new_func, f) + + +def make_pass_decorator( + object_type: type[T], ensure: bool = False +) -> t.Callable[[t.Callable[te.Concatenate[T, P], R]], t.Callable[P, R]]: + """Given an object type this creates a decorator that will work + similar to :func:`pass_obj` but instead of passing the object of the + current context, it will find the innermost context of type + :func:`object_type`. + + This generates a decorator that works roughly like this:: + + from functools import update_wrapper + + def decorator(f): + @pass_context + def new_func(ctx, *args, **kwargs): + obj = ctx.find_object(object_type) + return ctx.invoke(f, obj, *args, **kwargs) + return update_wrapper(new_func, f) + return decorator + + :param object_type: the type of the object to pass. + :param ensure: if set to `True`, a new object will be created and + remembered on the context if it's not there yet. + """ + + def decorator(f: t.Callable[te.Concatenate[T, P], R]) -> t.Callable[P, R]: + def new_func(*args: P.args, **kwargs: P.kwargs) -> R: + ctx = get_current_context() + + obj: T | None + if ensure: + obj = ctx.ensure_object(object_type) + else: + obj = ctx.find_object(object_type) + + if obj is None: + raise RuntimeError( + "Managed to invoke callback without a context" + f" object of type {object_type.__name__!r}" + " existing." + ) + + return ctx.invoke(f, obj, *args, **kwargs) + + return update_wrapper(new_func, f) + + return decorator + + +def pass_meta_key( + key: str, *, doc_description: str | None = None +) -> t.Callable[[t.Callable[te.Concatenate[T, P], R]], t.Callable[P, R]]: + """Create a decorator that passes a key from + :attr:`click.Context.meta` as the first argument to the decorated + function. + + :param key: Key in ``Context.meta`` to pass. + :param doc_description: Description of the object being passed, + inserted into the decorator's docstring. Defaults to "the 'key' + key from Context.meta". + + .. versionadded:: 8.0 + """ + + def decorator(f: t.Callable[te.Concatenate[T, P], R]) -> t.Callable[P, R]: + def new_func(*args: P.args, **kwargs: P.kwargs) -> R: + ctx = get_current_context() + obj = ctx.meta[key] + return ctx.invoke(f, obj, *args, **kwargs) + + return update_wrapper(new_func, f) + + if doc_description is None: + doc_description = f"the {key!r} key from :attr:`click.Context.meta`" + + decorator.__doc__ = ( + f"Decorator that passes {doc_description} as the first argument" + " to the decorated function." + ) + return decorator + + +CmdType = t.TypeVar("CmdType", bound=Command) + + +# variant: no call, directly as decorator for a function. +@t.overload +def command(name: _AnyCallable) -> Command: ... + + +# variant: with positional name and with positional or keyword cls argument: +# @command(namearg, CommandCls, ...) or @command(namearg, cls=CommandCls, ...) +@t.overload +def command( + name: str | None, + cls: type[CmdType], + **attrs: t.Any, +) -> t.Callable[[_AnyCallable], CmdType]: ... + + +# variant: name omitted, cls _must_ be a keyword argument, @command(cls=CommandCls, ...) +@t.overload +def command( + name: None = None, + *, + cls: type[CmdType], + **attrs: t.Any, +) -> t.Callable[[_AnyCallable], CmdType]: ... + + +# variant: with optional string name, no cls argument provided. +@t.overload +def command( + name: str | None = ..., cls: None = None, **attrs: t.Any +) -> t.Callable[[_AnyCallable], Command]: ... + + +def command( + name: str | _AnyCallable | None = None, + cls: type[CmdType] | None = None, + **attrs: t.Any, +) -> Command | t.Callable[[_AnyCallable], Command | CmdType]: + r"""Creates a new :class:`Command` and uses the decorated function as + callback. This will also automatically attach all decorated + :func:`option`\s and :func:`argument`\s as parameters to the command. + + The name of the command defaults to the name of the function, converted to + lowercase, with underscores ``_`` replaced by dashes ``-``, and the suffixes + ``_command``, ``_cmd``, ``_group``, and ``_grp`` are removed. For example, + ``init_data_command`` becomes ``init-data``. + + All keyword arguments are forwarded to the underlying command class. + For the ``params`` argument, any decorated params are appended to + the end of the list. + + Once decorated the function turns into a :class:`Command` instance + that can be invoked as a command line utility or be attached to a + command :class:`Group`. + + :param name: The name of the command. Defaults to modifying the function's + name as described above. + :param cls: The command class to create. Defaults to :class:`Command`. + + .. versionchanged:: 8.2 + The suffixes ``_command``, ``_cmd``, ``_group``, and ``_grp`` are + removed when generating the name. + + .. versionchanged:: 8.1 + This decorator can be applied without parentheses. + + .. versionchanged:: 8.1 + The ``params`` argument can be used. Decorated params are + appended to the end of the list. + """ + + func: t.Callable[[_AnyCallable], t.Any] | None = None + + if callable(name): + func = name + name = None + assert cls is None, "Use 'command(cls=cls)(callable)' to specify a class." + assert not attrs, "Use 'command(**kwargs)(callable)' to provide arguments." + + if cls is None: + cls = t.cast("type[CmdType]", Command) + + def decorator(f: _AnyCallable) -> CmdType: + if isinstance(f, Command): + raise TypeError("Attempted to convert a callback into a command twice.") + + attr_params = attrs.pop("params", None) + params = attr_params if attr_params is not None else [] + + try: + decorator_params = f.__click_params__ # type: ignore + except AttributeError: + pass + else: + del f.__click_params__ # type: ignore + params.extend(reversed(decorator_params)) + + if attrs.get("help") is None: + attrs["help"] = f.__doc__ + + if t.TYPE_CHECKING: + assert cls is not None + assert not callable(name) + + if name is not None: + cmd_name = name + else: + cmd_name = f.__name__.lower().replace("_", "-") + cmd_left, sep, suffix = cmd_name.rpartition("-") + + if sep and suffix in {"command", "cmd", "group", "grp"}: + cmd_name = cmd_left + + cmd = cls(name=cmd_name, callback=f, params=params, **attrs) + cmd.__doc__ = f.__doc__ + return cmd + + if func is not None: + return decorator(func) + + return decorator + + +GrpType = t.TypeVar("GrpType", bound=Group) + + +# variant: no call, directly as decorator for a function. +@t.overload +def group(name: _AnyCallable) -> Group: ... + + +# variant: with positional name and with positional or keyword cls argument: +# @group(namearg, GroupCls, ...) or @group(namearg, cls=GroupCls, ...) +@t.overload +def group( + name: str | None, + cls: type[GrpType], + **attrs: t.Any, +) -> t.Callable[[_AnyCallable], GrpType]: ... + + +# variant: name omitted, cls _must_ be a keyword argument, @group(cmd=GroupCls, ...) +@t.overload +def group( + name: None = None, + *, + cls: type[GrpType], + **attrs: t.Any, +) -> t.Callable[[_AnyCallable], GrpType]: ... + + +# variant: with optional string name, no cls argument provided. +@t.overload +def group( + name: str | None = ..., cls: None = None, **attrs: t.Any +) -> t.Callable[[_AnyCallable], Group]: ... + + +def group( + name: str | _AnyCallable | None = None, + cls: type[GrpType] | None = None, + **attrs: t.Any, +) -> Group | t.Callable[[_AnyCallable], Group | GrpType]: + """Creates a new :class:`Group` with a function as callback. This + works otherwise the same as :func:`command` just that the `cls` + parameter is set to :class:`Group`. + + .. versionchanged:: 8.1 + This decorator can be applied without parentheses. + """ + if cls is None: + cls = t.cast("type[GrpType]", Group) + + if callable(name): + return command(cls=cls, **attrs)(name) + + return command(name, cls, **attrs) + + +def _param_memo(f: t.Callable[..., t.Any], param: Parameter) -> None: + if isinstance(f, Command): + f.params.append(param) + else: + if not hasattr(f, "__click_params__"): + f.__click_params__ = [] # type: ignore + + f.__click_params__.append(param) # type: ignore + + +def argument( + *param_decls: str, cls: type[Argument] | None = None, **attrs: t.Any +) -> t.Callable[[FC], FC]: + """Attaches an argument to the command. All positional arguments are + passed as parameter declarations to :class:`Argument`; all keyword + arguments are forwarded unchanged (except ``cls``). + This is equivalent to creating an :class:`Argument` instance manually + and attaching it to the :attr:`Command.params` list. + + For the default argument class, refer to :class:`Argument` and + :class:`Parameter` for descriptions of parameters. + + :param cls: the argument class to instantiate. This defaults to + :class:`Argument`. + :param param_decls: Passed as positional arguments to the constructor of + ``cls``. + :param attrs: Passed as keyword arguments to the constructor of ``cls``. + """ + if cls is None: + cls = Argument + + def decorator(f: FC) -> FC: + _param_memo(f, cls(param_decls, **attrs)) + return f + + return decorator + + +def option( + *param_decls: str, cls: type[Option] | None = None, **attrs: t.Any +) -> t.Callable[[FC], FC]: + """Attaches an option to the command. All positional arguments are + passed as parameter declarations to :class:`Option`; all keyword + arguments are forwarded unchanged (except ``cls``). + This is equivalent to creating an :class:`Option` instance manually + and attaching it to the :attr:`Command.params` list. + + For the default option class, refer to :class:`Option` and + :class:`Parameter` for descriptions of parameters. + + :param cls: the option class to instantiate. This defaults to + :class:`Option`. + :param param_decls: Passed as positional arguments to the constructor of + ``cls``. + :param attrs: Passed as keyword arguments to the constructor of ``cls``. + """ + if cls is None: + cls = Option + + def decorator(f: FC) -> FC: + _param_memo(f, cls(param_decls, **attrs)) + return f + + return decorator + + +def confirmation_option(*param_decls: str, **kwargs: t.Any) -> t.Callable[[FC], FC]: + """Add a ``--yes`` option which shows a prompt before continuing if + not passed. If the prompt is declined, the program will exit. + + :param param_decls: One or more option names. Defaults to the single + value ``"--yes"``. + :param kwargs: Extra arguments are passed to :func:`option`. + """ + + def callback(ctx: Context, param: Parameter, value: bool) -> None: + if not value: + ctx.abort() + + if not param_decls: + param_decls = ("--yes",) + + kwargs.setdefault("is_flag", True) + kwargs.setdefault("callback", callback) + kwargs.setdefault("expose_value", False) + kwargs.setdefault("prompt", "Do you want to continue?") + kwargs.setdefault("help", "Confirm the action without prompting.") + return option(*param_decls, **kwargs) + + +def password_option(*param_decls: str, **kwargs: t.Any) -> t.Callable[[FC], FC]: + """Add a ``--password`` option which prompts for a password, hiding + input and asking to enter the value again for confirmation. + + :param param_decls: One or more option names. Defaults to the single + value ``"--password"``. + :param kwargs: Extra arguments are passed to :func:`option`. + """ + if not param_decls: + param_decls = ("--password",) + + kwargs.setdefault("prompt", True) + kwargs.setdefault("confirmation_prompt", True) + kwargs.setdefault("hide_input", True) + return option(*param_decls, **kwargs) + + +def version_option( + version: str | None = None, + *param_decls: str, + package_name: str | None = None, + prog_name: str | None = None, + message: str | None = None, + **kwargs: t.Any, +) -> t.Callable[[FC], FC]: + """Add a ``--version`` option which immediately prints the version + number and exits the program. + + If ``version`` is not provided, Click will try to detect it using + :func:`importlib.metadata.version` to get the version for the + ``package_name``. + + If ``package_name`` is not provided, Click will try to detect it by + inspecting the stack frames. This will be used to detect the + version, so it must match the name of the installed package. + + :param version: The version number to show. If not provided, Click + will try to detect it. + :param param_decls: One or more option names. Defaults to the single + value ``"--version"``. + :param package_name: The package name to detect the version from. If + not provided, Click will try to detect it. + :param prog_name: The name of the CLI to show in the message. If not + provided, it will be detected from the command. + :param message: The message to show. The values ``%(prog)s``, + ``%(package)s``, and ``%(version)s`` are available. Defaults to + ``"%(prog)s, version %(version)s"``. + :param kwargs: Extra arguments are passed to :func:`option`. + :raise RuntimeError: ``version`` could not be detected. + + .. versionchanged:: 8.0 + Add the ``package_name`` parameter, and the ``%(package)s`` + value for messages. + + .. versionchanged:: 8.0 + Use :mod:`importlib.metadata` instead of ``pkg_resources``. The + version is detected based on the package name, not the entry + point name. The Python package name must match the installed + package name, or be passed with ``package_name=``. + """ + if message is None: + message = _("%(prog)s, version %(version)s") + + if version is None and package_name is None: + frame = inspect.currentframe() + f_back = frame.f_back if frame is not None else None + f_globals = f_back.f_globals if f_back is not None else None + # break reference cycle + # https://docs.python.org/3/library/inspect.html#the-interpreter-stack + del frame + + if f_globals is not None: + package_name = f_globals.get("__name__") + + if package_name == "__main__": + package_name = f_globals.get("__package__") + + if package_name: + package_name = package_name.partition(".")[0] + + def callback(ctx: Context, param: Parameter, value: bool) -> None: + if not value or ctx.resilient_parsing: + return + + nonlocal prog_name + nonlocal version + + if prog_name is None: + prog_name = ctx.find_root().info_name + + if version is None and package_name is not None: + import importlib.metadata + + try: + version = importlib.metadata.version(package_name) + except importlib.metadata.PackageNotFoundError: + raise RuntimeError( + f"{package_name!r} is not installed. Try passing" + " 'package_name' instead." + ) from None + + if version is None: + raise RuntimeError( + f"Could not determine the version for {package_name!r} automatically." + ) + + echo( + message % {"prog": prog_name, "package": package_name, "version": version}, + color=ctx.color, + ) + ctx.exit() + + if not param_decls: + param_decls = ("--version",) + + kwargs.setdefault("is_flag", True) + kwargs.setdefault("expose_value", False) + kwargs.setdefault("is_eager", True) + kwargs.setdefault("help", _("Show the version and exit.")) + kwargs["callback"] = callback + return option(*param_decls, **kwargs) + + +def help_option(*param_decls: str, **kwargs: t.Any) -> t.Callable[[FC], FC]: + """Pre-configured ``--help`` option which immediately prints the help page + and exits the program. + + :param param_decls: One or more option names. Defaults to the single + value ``"--help"``. + :param kwargs: Extra arguments are passed to :func:`option`. + """ + + def show_help(ctx: Context, param: Parameter, value: bool) -> None: + """Callback that print the help page on ```` and exits.""" + if value and not ctx.resilient_parsing: + echo(ctx.get_help(), color=ctx.color) + ctx.exit() + + if not param_decls: + param_decls = ("--help",) + + kwargs.setdefault("is_flag", True) + kwargs.setdefault("expose_value", False) + kwargs.setdefault("is_eager", True) + kwargs.setdefault("help", _("Show this message and exit.")) + kwargs.setdefault("callback", show_help) + + return option(*param_decls, **kwargs) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/click/exceptions.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/click/exceptions.py new file mode 100644 index 000000000..4d782ee36 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/click/exceptions.py @@ -0,0 +1,308 @@ +from __future__ import annotations + +import collections.abc as cabc +import typing as t +from gettext import gettext as _ +from gettext import ngettext + +from ._compat import get_text_stderr +from .globals import resolve_color_default +from .utils import echo +from .utils import format_filename + +if t.TYPE_CHECKING: + from .core import Command + from .core import Context + from .core import Parameter + + +def _join_param_hints(param_hint: cabc.Sequence[str] | str | None) -> str | None: + if param_hint is not None and not isinstance(param_hint, str): + return " / ".join(repr(x) for x in param_hint) + + return param_hint + + +class ClickException(Exception): + """An exception that Click can handle and show to the user.""" + + #: The exit code for this exception. + exit_code = 1 + + def __init__(self, message: str) -> None: + super().__init__(message) + # The context will be removed by the time we print the message, so cache + # the color settings here to be used later on (in `show`) + self.show_color: bool | None = resolve_color_default() + self.message = message + + def format_message(self) -> str: + return self.message + + def __str__(self) -> str: + return self.message + + def show(self, file: t.IO[t.Any] | None = None) -> None: + if file is None: + file = get_text_stderr() + + echo( + _("Error: {message}").format(message=self.format_message()), + file=file, + color=self.show_color, + ) + + +class UsageError(ClickException): + """An internal exception that signals a usage error. This typically + aborts any further handling. + + :param message: the error message to display. + :param ctx: optionally the context that caused this error. Click will + fill in the context automatically in some situations. + """ + + exit_code = 2 + + def __init__(self, message: str, ctx: Context | None = None) -> None: + super().__init__(message) + self.ctx = ctx + self.cmd: Command | None = self.ctx.command if self.ctx else None + + def show(self, file: t.IO[t.Any] | None = None) -> None: + if file is None: + file = get_text_stderr() + color = None + hint = "" + if ( + self.ctx is not None + and self.ctx.command.get_help_option(self.ctx) is not None + ): + hint = _("Try '{command} {option}' for help.").format( + command=self.ctx.command_path, option=self.ctx.help_option_names[0] + ) + hint = f"{hint}\n" + if self.ctx is not None: + color = self.ctx.color + echo(f"{self.ctx.get_usage()}\n{hint}", file=file, color=color) + echo( + _("Error: {message}").format(message=self.format_message()), + file=file, + color=color, + ) + + +class BadParameter(UsageError): + """An exception that formats out a standardized error message for a + bad parameter. This is useful when thrown from a callback or type as + Click will attach contextual information to it (for instance, which + parameter it is). + + .. versionadded:: 2.0 + + :param param: the parameter object that caused this error. This can + be left out, and Click will attach this info itself + if possible. + :param param_hint: a string that shows up as parameter name. This + can be used as alternative to `param` in cases + where custom validation should happen. If it is + a string it's used as such, if it's a list then + each item is quoted and separated. + """ + + def __init__( + self, + message: str, + ctx: Context | None = None, + param: Parameter | None = None, + param_hint: cabc.Sequence[str] | str | None = None, + ) -> None: + super().__init__(message, ctx) + self.param = param + self.param_hint = param_hint + + def format_message(self) -> str: + if self.param_hint is not None: + param_hint = self.param_hint + elif self.param is not None: + param_hint = self.param.get_error_hint(self.ctx) # type: ignore + else: + return _("Invalid value: {message}").format(message=self.message) + + return _("Invalid value for {param_hint}: {message}").format( + param_hint=_join_param_hints(param_hint), message=self.message + ) + + +class MissingParameter(BadParameter): + """Raised if click required an option or argument but it was not + provided when invoking the script. + + .. versionadded:: 4.0 + + :param param_type: a string that indicates the type of the parameter. + The default is to inherit the parameter type from + the given `param`. Valid values are ``'parameter'``, + ``'option'`` or ``'argument'``. + """ + + def __init__( + self, + message: str | None = None, + ctx: Context | None = None, + param: Parameter | None = None, + param_hint: cabc.Sequence[str] | str | None = None, + param_type: str | None = None, + ) -> None: + super().__init__(message or "", ctx, param, param_hint) + self.param_type = param_type + + def format_message(self) -> str: + if self.param_hint is not None: + param_hint: cabc.Sequence[str] | str | None = self.param_hint + elif self.param is not None: + param_hint = self.param.get_error_hint(self.ctx) # type: ignore + else: + param_hint = None + + param_hint = _join_param_hints(param_hint) + param_hint = f" {param_hint}" if param_hint else "" + + param_type = self.param_type + if param_type is None and self.param is not None: + param_type = self.param.param_type_name + + msg = self.message + if self.param is not None: + msg_extra = self.param.type.get_missing_message( + param=self.param, ctx=self.ctx + ) + if msg_extra: + if msg: + msg += f". {msg_extra}" + else: + msg = msg_extra + + msg = f" {msg}" if msg else "" + + # Translate param_type for known types. + if param_type == "argument": + missing = _("Missing argument") + elif param_type == "option": + missing = _("Missing option") + elif param_type == "parameter": + missing = _("Missing parameter") + else: + missing = _("Missing {param_type}").format(param_type=param_type) + + return f"{missing}{param_hint}.{msg}" + + def __str__(self) -> str: + if not self.message: + param_name = self.param.name if self.param else None + return _("Missing parameter: {param_name}").format(param_name=param_name) + else: + return self.message + + +class NoSuchOption(UsageError): + """Raised if click attempted to handle an option that does not + exist. + + .. versionadded:: 4.0 + """ + + def __init__( + self, + option_name: str, + message: str | None = None, + possibilities: cabc.Sequence[str] | None = None, + ctx: Context | None = None, + ) -> None: + if message is None: + message = _("No such option: {name}").format(name=option_name) + + super().__init__(message, ctx) + self.option_name = option_name + self.possibilities = possibilities + + def format_message(self) -> str: + if not self.possibilities: + return self.message + + possibility_str = ", ".join(sorted(self.possibilities)) + suggest = ngettext( + "Did you mean {possibility}?", + "(Possible options: {possibilities})", + len(self.possibilities), + ).format(possibility=possibility_str, possibilities=possibility_str) + return f"{self.message} {suggest}" + + +class BadOptionUsage(UsageError): + """Raised if an option is generally supplied but the use of the option + was incorrect. This is for instance raised if the number of arguments + for an option is not correct. + + .. versionadded:: 4.0 + + :param option_name: the name of the option being used incorrectly. + """ + + def __init__( + self, option_name: str, message: str, ctx: Context | None = None + ) -> None: + super().__init__(message, ctx) + self.option_name = option_name + + +class BadArgumentUsage(UsageError): + """Raised if an argument is generally supplied but the use of the argument + was incorrect. This is for instance raised if the number of values + for an argument is not correct. + + .. versionadded:: 6.0 + """ + + +class NoArgsIsHelpError(UsageError): + def __init__(self, ctx: Context) -> None: + self.ctx: Context + super().__init__(ctx.get_help(), ctx=ctx) + + def show(self, file: t.IO[t.Any] | None = None) -> None: + echo(self.format_message(), file=file, err=True, color=self.ctx.color) + + +class FileError(ClickException): + """Raised if a file cannot be opened.""" + + def __init__(self, filename: str, hint: str | None = None) -> None: + if hint is None: + hint = _("unknown error") + + super().__init__(hint) + self.ui_filename: str = format_filename(filename) + self.filename = filename + + def format_message(self) -> str: + return _("Could not open file {filename!r}: {message}").format( + filename=self.ui_filename, message=self.message + ) + + +class Abort(RuntimeError): + """An internal signalling exception that signals Click to abort.""" + + +class Exit(RuntimeError): + """An exception that indicates that the application should exit with some + status code. + + :param code: the status code to exit with. + """ + + __slots__ = ("exit_code",) + + def __init__(self, code: int = 0) -> None: + self.exit_code: int = code diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/click/formatting.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/click/formatting.py new file mode 100644 index 000000000..0b64f831b --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/click/formatting.py @@ -0,0 +1,301 @@ +from __future__ import annotations + +import collections.abc as cabc +from contextlib import contextmanager +from gettext import gettext as _ + +from ._compat import term_len +from .parser import _split_opt + +# Can force a width. This is used by the test system +FORCED_WIDTH: int | None = None + + +def measure_table(rows: cabc.Iterable[tuple[str, str]]) -> tuple[int, ...]: + widths: dict[int, int] = {} + + for row in rows: + for idx, col in enumerate(row): + widths[idx] = max(widths.get(idx, 0), term_len(col)) + + return tuple(y for x, y in sorted(widths.items())) + + +def iter_rows( + rows: cabc.Iterable[tuple[str, str]], col_count: int +) -> cabc.Iterator[tuple[str, ...]]: + for row in rows: + yield row + ("",) * (col_count - len(row)) + + +def wrap_text( + text: str, + width: int = 78, + initial_indent: str = "", + subsequent_indent: str = "", + preserve_paragraphs: bool = False, +) -> str: + """A helper function that intelligently wraps text. By default, it + assumes that it operates on a single paragraph of text but if the + `preserve_paragraphs` parameter is provided it will intelligently + handle paragraphs (defined by two empty lines). + + If paragraphs are handled, a paragraph can be prefixed with an empty + line containing the ``\\b`` character (``\\x08``) to indicate that + no rewrapping should happen in that block. + + :param text: the text that should be rewrapped. + :param width: the maximum width for the text. + :param initial_indent: the initial indent that should be placed on the + first line as a string. + :param subsequent_indent: the indent string that should be placed on + each consecutive line. + :param preserve_paragraphs: if this flag is set then the wrapping will + intelligently handle paragraphs. + """ + from ._textwrap import TextWrapper + + text = text.expandtabs() + wrapper = TextWrapper( + width, + initial_indent=initial_indent, + subsequent_indent=subsequent_indent, + replace_whitespace=False, + ) + if not preserve_paragraphs: + return wrapper.fill(text) + + p: list[tuple[int, bool, str]] = [] + buf: list[str] = [] + indent = None + + def _flush_par() -> None: + if not buf: + return + if buf[0].strip() == "\b": + p.append((indent or 0, True, "\n".join(buf[1:]))) + else: + p.append((indent or 0, False, " ".join(buf))) + del buf[:] + + for line in text.splitlines(): + if not line: + _flush_par() + indent = None + else: + if indent is None: + orig_len = term_len(line) + line = line.lstrip() + indent = orig_len - term_len(line) + buf.append(line) + _flush_par() + + rv = [] + for indent, raw, text in p: + with wrapper.extra_indent(" " * indent): + if raw: + rv.append(wrapper.indent_only(text)) + else: + rv.append(wrapper.fill(text)) + + return "\n\n".join(rv) + + +class HelpFormatter: + """This class helps with formatting text-based help pages. It's + usually just needed for very special internal cases, but it's also + exposed so that developers can write their own fancy outputs. + + At present, it always writes into memory. + + :param indent_increment: the additional increment for each level. + :param width: the width for the text. This defaults to the terminal + width clamped to a maximum of 78. + """ + + def __init__( + self, + indent_increment: int = 2, + width: int | None = None, + max_width: int | None = None, + ) -> None: + self.indent_increment = indent_increment + if max_width is None: + max_width = 80 + if width is None: + import shutil + + width = FORCED_WIDTH + if width is None: + width = max(min(shutil.get_terminal_size().columns, max_width) - 2, 50) + self.width = width + self.current_indent: int = 0 + self.buffer: list[str] = [] + + def write(self, string: str) -> None: + """Writes a unicode string into the internal buffer.""" + self.buffer.append(string) + + def indent(self) -> None: + """Increases the indentation.""" + self.current_indent += self.indent_increment + + def dedent(self) -> None: + """Decreases the indentation.""" + self.current_indent -= self.indent_increment + + def write_usage(self, prog: str, args: str = "", prefix: str | None = None) -> None: + """Writes a usage line into the buffer. + + :param prog: the program name. + :param args: whitespace separated list of arguments. + :param prefix: The prefix for the first line. Defaults to + ``"Usage: "``. + """ + if prefix is None: + prefix = f"{_('Usage:')} " + + usage_prefix = f"{prefix:>{self.current_indent}}{prog} " + text_width = self.width - self.current_indent + + if text_width >= (term_len(usage_prefix) + 20): + # The arguments will fit to the right of the prefix. + indent = " " * term_len(usage_prefix) + self.write( + wrap_text( + args, + text_width, + initial_indent=usage_prefix, + subsequent_indent=indent, + ) + ) + else: + # The prefix is too long, put the arguments on the next line. + self.write(usage_prefix) + self.write("\n") + indent = " " * (max(self.current_indent, term_len(prefix)) + 4) + self.write( + wrap_text( + args, text_width, initial_indent=indent, subsequent_indent=indent + ) + ) + + self.write("\n") + + def write_heading(self, heading: str) -> None: + """Writes a heading into the buffer.""" + self.write(f"{'':>{self.current_indent}}{heading}:\n") + + def write_paragraph(self) -> None: + """Writes a paragraph into the buffer.""" + if self.buffer: + self.write("\n") + + def write_text(self, text: str) -> None: + """Writes re-indented text into the buffer. This rewraps and + preserves paragraphs. + """ + indent = " " * self.current_indent + self.write( + wrap_text( + text, + self.width, + initial_indent=indent, + subsequent_indent=indent, + preserve_paragraphs=True, + ) + ) + self.write("\n") + + def write_dl( + self, + rows: cabc.Sequence[tuple[str, str]], + col_max: int = 30, + col_spacing: int = 2, + ) -> None: + """Writes a definition list into the buffer. This is how options + and commands are usually formatted. + + :param rows: a list of two item tuples for the terms and values. + :param col_max: the maximum width of the first column. + :param col_spacing: the number of spaces between the first and + second column. + """ + rows = list(rows) + widths = measure_table(rows) + if len(widths) != 2: + raise TypeError("Expected two columns for definition list") + + first_col = min(widths[0], col_max) + col_spacing + + for first, second in iter_rows(rows, len(widths)): + self.write(f"{'':>{self.current_indent}}{first}") + if not second: + self.write("\n") + continue + if term_len(first) <= first_col - col_spacing: + self.write(" " * (first_col - term_len(first))) + else: + self.write("\n") + self.write(" " * (first_col + self.current_indent)) + + text_width = max(self.width - first_col - 2, 10) + wrapped_text = wrap_text(second, text_width, preserve_paragraphs=True) + lines = wrapped_text.splitlines() + + if lines: + self.write(f"{lines[0]}\n") + + for line in lines[1:]: + self.write(f"{'':>{first_col + self.current_indent}}{line}\n") + else: + self.write("\n") + + @contextmanager + def section(self, name: str) -> cabc.Iterator[None]: + """Helpful context manager that writes a paragraph, a heading, + and the indents. + + :param name: the section name that is written as heading. + """ + self.write_paragraph() + self.write_heading(name) + self.indent() + try: + yield + finally: + self.dedent() + + @contextmanager + def indentation(self) -> cabc.Iterator[None]: + """A context manager that increases the indentation.""" + self.indent() + try: + yield + finally: + self.dedent() + + def getvalue(self) -> str: + """Returns the buffer contents.""" + return "".join(self.buffer) + + +def join_options(options: cabc.Sequence[str]) -> tuple[str, bool]: + """Given a list of option strings this joins them in the most appropriate + way and returns them in the form ``(formatted_string, + any_prefix_is_slash)`` where the second item in the tuple is a flag that + indicates if any of the option prefixes was a slash. + """ + rv = [] + any_prefix_is_slash = False + + for opt in options: + prefix = _split_opt(opt)[0] + + if prefix == "/": + any_prefix_is_slash = True + + rv.append((len(prefix), opt)) + + rv.sort(key=lambda x: x[0]) + return ", ".join(x[1] for x in rv), any_prefix_is_slash diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/click/globals.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/click/globals.py new file mode 100644 index 000000000..a2f91723d --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/click/globals.py @@ -0,0 +1,67 @@ +from __future__ import annotations + +import typing as t +from threading import local + +if t.TYPE_CHECKING: + from .core import Context + +_local = local() + + +@t.overload +def get_current_context(silent: t.Literal[False] = False) -> Context: ... + + +@t.overload +def get_current_context(silent: bool = ...) -> Context | None: ... + + +def get_current_context(silent: bool = False) -> Context | None: + """Returns the current click context. This can be used as a way to + access the current context object from anywhere. This is a more implicit + alternative to the :func:`pass_context` decorator. This function is + primarily useful for helpers such as :func:`echo` which might be + interested in changing its behavior based on the current context. + + To push the current context, :meth:`Context.scope` can be used. + + .. versionadded:: 5.0 + + :param silent: if set to `True` the return value is `None` if no context + is available. The default behavior is to raise a + :exc:`RuntimeError`. + """ + try: + return t.cast("Context", _local.stack[-1]) + except (AttributeError, IndexError) as e: + if not silent: + raise RuntimeError("There is no active click context.") from e + + return None + + +def push_context(ctx: Context) -> None: + """Pushes a new context to the current stack.""" + _local.__dict__.setdefault("stack", []).append(ctx) + + +def pop_context() -> None: + """Removes the top level from the stack.""" + _local.stack.pop() + + +def resolve_color_default(color: bool | None = None) -> bool | None: + """Internal helper to get the default value of the color flag. If a + value is passed it's returned unchanged, otherwise it's looked up from + the current context. + """ + if color is not None: + return color + + ctx = get_current_context(silent=True) + + if ctx is not None: + return ctx.color + + return None diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/click/parser.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/click/parser.py new file mode 100644 index 000000000..1ea1f7166 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/click/parser.py @@ -0,0 +1,532 @@ +""" +This module started out as largely a copy paste from the stdlib's +optparse module with the features removed that we do not need from +optparse because we implement them in Click on a higher level (for +instance type handling, help formatting and a lot more). + +The plan is to remove more and more from here over time. + +The reason this is a different module and not optparse from the stdlib +is that there are differences in 2.x and 3.x about the error messages +generated and optparse in the stdlib uses gettext for no good reason +and might cause us issues. + +Click uses parts of optparse written by Gregory P. Ward and maintained +by the Python Software Foundation. This is limited to code in parser.py. + +Copyright 2001-2006 Gregory P. Ward. All rights reserved. +Copyright 2002-2006 Python Software Foundation. All rights reserved. +""" + +# This code uses parts of optparse written by Gregory P. Ward and +# maintained by the Python Software Foundation. +# Copyright 2001-2006 Gregory P. Ward +# Copyright 2002-2006 Python Software Foundation +from __future__ import annotations + +import collections.abc as cabc +import typing as t +from collections import deque +from gettext import gettext as _ +from gettext import ngettext + +from ._utils import FLAG_NEEDS_VALUE +from ._utils import UNSET +from .exceptions import BadArgumentUsage +from .exceptions import BadOptionUsage +from .exceptions import NoSuchOption +from .exceptions import UsageError + +if t.TYPE_CHECKING: + from ._utils import T_FLAG_NEEDS_VALUE + from ._utils import T_UNSET + from .core import Argument as CoreArgument + from .core import Context + from .core import Option as CoreOption + from .core import Parameter as CoreParameter + +V = t.TypeVar("V") + + +def _unpack_args( + args: cabc.Sequence[str], nargs_spec: cabc.Sequence[int] +) -> tuple[cabc.Sequence[str | cabc.Sequence[str | None] | None], list[str]]: + """Given an iterable of arguments and an iterable of nargs specifications, + it returns a tuple with all the unpacked arguments at the first index + and all remaining arguments as the second. + + The nargs specification is the number of arguments that should be consumed + or `-1` to indicate that this position should eat up all the remainders. + + Missing items are filled with ``UNSET``. + """ + args = deque(args) + nargs_spec = deque(nargs_spec) + rv: list[str | tuple[str | T_UNSET, ...] | T_UNSET] = [] + spos: int | None = None + + def _fetch(c: deque[V]) -> V | T_UNSET: + try: + if spos is None: + return c.popleft() + else: + return c.pop() + except IndexError: + return UNSET + + while nargs_spec: + nargs = _fetch(nargs_spec) + + if nargs is None: + continue + + if nargs == 1: + rv.append(_fetch(args)) # type: ignore[arg-type] + elif nargs > 1: + x = [_fetch(args) for _ in range(nargs)] + + # If we're reversed, we're pulling in the arguments in reverse, + # so we need to turn them around. + if spos is not None: + x.reverse() + + rv.append(tuple(x)) + elif nargs < 0: + if spos is not None: + raise TypeError("Cannot have two nargs < 0") + + spos = len(rv) + rv.append(UNSET) + + # spos is the position of the wildcard (star). If it's not `None`, + # we fill it with the remainder. + if spos is not None: + rv[spos] = tuple(args) + args = [] + rv[spos + 1 :] = reversed(rv[spos + 1 :]) + + return tuple(rv), list(args) + + +def _split_opt(opt: str) -> tuple[str, str]: + first = opt[:1] + if first.isalnum(): + return "", opt + if opt[1:2] == first: + return opt[:2], opt[2:] + return first, opt[1:] + + +def _normalize_opt(opt: str, ctx: Context | None) -> str: + if ctx is None or ctx.token_normalize_func is None: + return opt + prefix, opt = _split_opt(opt) + return f"{prefix}{ctx.token_normalize_func(opt)}" + + +class _Option: + def __init__( + self, + obj: CoreOption, + opts: cabc.Sequence[str], + dest: str | None, + action: str | None = None, + nargs: int = 1, + const: t.Any | None = None, + ): + self._short_opts = [] + self._long_opts = [] + self.prefixes: set[str] = set() + + for opt in opts: + prefix, value = _split_opt(opt) + if not prefix: + raise ValueError(f"Invalid start character for option ({opt})") + self.prefixes.add(prefix[0]) + if len(prefix) == 1 and len(value) == 1: + self._short_opts.append(opt) + else: + self._long_opts.append(opt) + self.prefixes.add(prefix) + + if action is None: + action = "store" + + self.dest = dest + self.action = action + self.nargs = nargs + self.const = const + self.obj = obj + + @property + def takes_value(self) -> bool: + return self.action in ("store", "append") + + def process(self, value: t.Any, state: _ParsingState) -> None: + if self.action == "store": + state.opts[self.dest] = value # type: ignore + elif self.action == "store_const": + state.opts[self.dest] = self.const # type: ignore + elif self.action == "append": + state.opts.setdefault(self.dest, []).append(value) # type: ignore + elif self.action == "append_const": + state.opts.setdefault(self.dest, []).append(self.const) # type: ignore + elif self.action == "count": + state.opts[self.dest] = state.opts.get(self.dest, 0) + 1 # type: ignore + else: + raise ValueError(f"unknown action '{self.action}'") + state.order.append(self.obj) + + +class _Argument: + def __init__(self, obj: CoreArgument, dest: str | None, nargs: int = 1): + self.dest = dest + self.nargs = nargs + self.obj = obj + + def process( + self, + value: str | cabc.Sequence[str | None] | None | T_UNSET, + state: _ParsingState, + ) -> None: + if self.nargs > 1: + assert isinstance(value, cabc.Sequence) + holes = sum(1 for x in value if x is UNSET) + if holes == len(value): + value = UNSET + elif holes != 0: + raise BadArgumentUsage( + _("Argument {name!r} takes {nargs} values.").format( + name=self.dest, nargs=self.nargs + ) + ) + + # We failed to collect any argument value so we consider the argument as unset. + if value == (): + value = UNSET + + state.opts[self.dest] = value # type: ignore + state.order.append(self.obj) + + +class _ParsingState: + def __init__(self, rargs: list[str]) -> None: + self.opts: dict[str, t.Any] = {} + self.largs: list[str] = [] + self.rargs = rargs + self.order: list[CoreParameter] = [] + + +class _OptionParser: + """The option parser is an internal class that is ultimately used to + parse options and arguments. It's modelled after optparse and brings + a similar but vastly simplified API. It should generally not be used + directly as the high level Click classes wrap it for you. + + It's not nearly as extensible as optparse or argparse as it does not + implement features that are implemented on a higher level (such as + types or defaults). + + :param ctx: optionally the :class:`~click.Context` where this parser + should go with. + + .. deprecated:: 8.2 + Will be removed in Click 9.0. + """ + + def __init__(self, ctx: Context | None = None) -> None: + #: The :class:`~click.Context` for this parser. This might be + #: `None` for some advanced use cases. + self.ctx = ctx + #: This controls how the parser deals with interspersed arguments. + #: If this is set to `False`, the parser will stop on the first + #: non-option. Click uses this to implement nested subcommands + #: safely. + self.allow_interspersed_args: bool = True + #: This tells the parser how to deal with unknown options. By + #: default it will error out (which is sensible), but there is a + #: second mode where it will ignore it and continue processing + #: after shifting all the unknown options into the resulting args. + self.ignore_unknown_options: bool = False + + if ctx is not None: + self.allow_interspersed_args = ctx.allow_interspersed_args + self.ignore_unknown_options = ctx.ignore_unknown_options + + self._short_opt: dict[str, _Option] = {} + self._long_opt: dict[str, _Option] = {} + self._opt_prefixes = {"-", "--"} + self._args: list[_Argument] = [] + + def add_option( + self, + obj: CoreOption, + opts: cabc.Sequence[str], + dest: str | None, + action: str | None = None, + nargs: int = 1, + const: t.Any | None = None, + ) -> None: + """Adds a new option named `dest` to the parser. The destination + is not inferred (unlike with optparse) and needs to be explicitly + provided. Action can be any of ``store``, ``store_const``, + ``append``, ``append_const`` or ``count``. + + The `obj` can be used to identify the option in the order list + that is returned from the parser. + """ + opts = [_normalize_opt(opt, self.ctx) for opt in opts] + option = _Option(obj, opts, dest, action=action, nargs=nargs, const=const) + self._opt_prefixes.update(option.prefixes) + for opt in option._short_opts: + self._short_opt[opt] = option + for opt in option._long_opts: + self._long_opt[opt] = option + + def add_argument(self, obj: CoreArgument, dest: str | None, nargs: int = 1) -> None: + """Adds a positional argument named `dest` to the parser. + + The `obj` can be used to identify the option in the order list + that is returned from the parser. + """ + self._args.append(_Argument(obj, dest=dest, nargs=nargs)) + + def parse_args( + self, args: list[str] + ) -> tuple[dict[str, t.Any], list[str], list[CoreParameter]]: + """Parses positional arguments and returns ``(values, args, order)`` + for the parsed options and arguments as well as the leftover + arguments if there are any. The order is a list of objects as they + appear on the command line. If arguments appear multiple times they + will be memorized multiple times as well. + """ + state = _ParsingState(args) + try: + self._process_args_for_options(state) + self._process_args_for_args(state) + except UsageError: + if self.ctx is None or not self.ctx.resilient_parsing: + raise + return state.opts, state.largs, state.order + + def _process_args_for_args(self, state: _ParsingState) -> None: + pargs, args = _unpack_args( + state.largs + state.rargs, [x.nargs for x in self._args] + ) + + for idx, arg in enumerate(self._args): + arg.process(pargs[idx], state) + + state.largs = args + state.rargs = [] + + def _process_args_for_options(self, state: _ParsingState) -> None: + while state.rargs: + arg = state.rargs.pop(0) + arglen = len(arg) + # Double dashes always handled explicitly regardless of what + # prefixes are valid. + if arg == "--": + return + elif arg[:1] in self._opt_prefixes and arglen > 1: + self._process_opts(arg, state) + elif self.allow_interspersed_args: + state.largs.append(arg) + else: + state.rargs.insert(0, arg) + return + + # Say this is the original argument list: + # [arg0, arg1, ..., arg(i-1), arg(i), arg(i+1), ..., arg(N-1)] + # ^ + # (we are about to process arg(i)). + # + # Then rargs is [arg(i), ..., arg(N-1)] and largs is a *subset* of + # [arg0, ..., arg(i-1)] (any options and their arguments will have + # been removed from largs). + # + # The while loop will usually consume 1 or more arguments per pass. + # If it consumes 1 (eg. arg is an option that takes no arguments), + # then after _process_arg() is done the situation is: + # + # largs = subset of [arg0, ..., arg(i)] + # rargs = [arg(i+1), ..., arg(N-1)] + # + # If allow_interspersed_args is false, largs will always be + # *empty* -- still a subset of [arg0, ..., arg(i-1)], but + # not a very interesting subset! + + def _match_long_opt( + self, opt: str, explicit_value: str | None, state: _ParsingState + ) -> None: + if opt not in self._long_opt: + from difflib import get_close_matches + + possibilities = get_close_matches(opt, self._long_opt) + raise NoSuchOption(opt, possibilities=possibilities, ctx=self.ctx) + + option = self._long_opt[opt] + if option.takes_value: + # At this point it's safe to modify rargs by injecting the + # explicit value, because no exception is raised in this + # branch. This means that the inserted value will be fully + # consumed. + if explicit_value is not None: + state.rargs.insert(0, explicit_value) + + value = self._get_value_from_state(opt, option, state) + + elif explicit_value is not None: + raise BadOptionUsage( + opt, _("Option {name!r} does not take a value.").format(name=opt) + ) + + else: + value = UNSET + + option.process(value, state) + + def _match_short_opt(self, arg: str, state: _ParsingState) -> None: + stop = False + i = 1 + prefix = arg[0] + unknown_options = [] + + for ch in arg[1:]: + opt = _normalize_opt(f"{prefix}{ch}", self.ctx) + option = self._short_opt.get(opt) + i += 1 + + if not option: + if self.ignore_unknown_options: + unknown_options.append(ch) + continue + raise NoSuchOption(opt, ctx=self.ctx) + if option.takes_value: + # Any characters left in arg? Pretend they're the + # next arg, and stop consuming characters of arg. + if i < len(arg): + state.rargs.insert(0, arg[i:]) + stop = True + + value = self._get_value_from_state(opt, option, state) + + else: + value = UNSET + + option.process(value, state) + + if stop: + break + + # If we got any unknown options we recombine the string of the + # remaining options and re-attach the prefix, then report that + # to the state as new larg. This way there is basic combinatorics + # that can be achieved while still ignoring unknown arguments. + if self.ignore_unknown_options and unknown_options: + state.largs.append(f"{prefix}{''.join(unknown_options)}") + + def _get_value_from_state( + self, option_name: str, option: _Option, state: _ParsingState + ) -> str | cabc.Sequence[str] | T_FLAG_NEEDS_VALUE: + nargs = option.nargs + + value: str | cabc.Sequence[str] | T_FLAG_NEEDS_VALUE + + if len(state.rargs) < nargs: + if option.obj._flag_needs_value: + # Option allows omitting the value. + value = FLAG_NEEDS_VALUE + else: + raise BadOptionUsage( + option_name, + ngettext( + "Option {name!r} requires an argument.", + "Option {name!r} requires {nargs} arguments.", + nargs, + ).format(name=option_name, nargs=nargs), + ) + elif nargs == 1: + next_rarg = state.rargs[0] + + if ( + option.obj._flag_needs_value + and isinstance(next_rarg, str) + and next_rarg[:1] in self._opt_prefixes + and len(next_rarg) > 1 + ): + # The next arg looks like the start of an option, don't + # use it as the value if omitting the value is allowed. + value = FLAG_NEEDS_VALUE + else: + value = state.rargs.pop(0) + else: + value = tuple(state.rargs[:nargs]) + del state.rargs[:nargs] + + return value + + def _process_opts(self, arg: str, state: _ParsingState) -> None: + explicit_value = None + # Long option handling happens in two parts. The first part is + # supporting explicitly attached values. In any case, we will try + # to long match the option first. + if "=" in arg: + long_opt, explicit_value = arg.split("=", 1) + else: + long_opt = arg + norm_long_opt = _normalize_opt(long_opt, self.ctx) + + # At this point we will match the (assumed) long option through + # the long option matching code. Note that this allows options + # like "-foo" to be matched as long options. + try: + self._match_long_opt(norm_long_opt, explicit_value, state) + except NoSuchOption: + # At this point the long option matching failed, and we need + # to try with short options. However there is a special rule + # which says, that if we have a two character options prefix + # (applies to "--foo" for instance), we do not dispatch to the + # short option code and will instead raise the no option + # error. + if arg[:2] not in self._opt_prefixes: + self._match_short_opt(arg, state) + return + + if not self.ignore_unknown_options: + raise + + state.largs.append(arg) + + +def __getattr__(name: str) -> object: + import warnings + + if name in { + "OptionParser", + "Argument", + "Option", + "split_opt", + "normalize_opt", + "ParsingState", + }: + warnings.warn( + f"'parser.{name}' is deprecated and will be removed in Click 9.0." + " The old parser is available in 'optparse'.", + DeprecationWarning, + stacklevel=2, + ) + return globals()[f"_{name}"] + + if name == "split_arg_string": + from .shell_completion import split_arg_string + + warnings.warn( + "Importing 'parser.split_arg_string' is deprecated, it will only be" + " available in 'shell_completion' in Click 9.0.", + DeprecationWarning, + stacklevel=2, + ) + return split_arg_string + + raise AttributeError(name) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/click/py.typed b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/click/py.typed new file mode 100644 index 000000000..e69de29bb diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/click/shell_completion.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/click/shell_completion.py new file mode 100644 index 000000000..8f1564c49 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/click/shell_completion.py @@ -0,0 +1,667 @@ +from __future__ import annotations + +import collections.abc as cabc +import os +import re +import typing as t +from gettext import gettext as _ + +from .core import Argument +from .core import Command +from .core import Context +from .core import Group +from .core import Option +from .core import Parameter +from .core import ParameterSource +from .utils import echo + + +def shell_complete( + cli: Command, + ctx_args: cabc.MutableMapping[str, t.Any], + prog_name: str, + complete_var: str, + instruction: str, +) -> int: + """Perform shell completion for the given CLI program. + + :param cli: Command being called. + :param ctx_args: Extra arguments to pass to + ``cli.make_context``. + :param prog_name: Name of the executable in the shell. + :param complete_var: Name of the environment variable that holds + the completion instruction. + :param instruction: Value of ``complete_var`` with the completion + instruction and shell, in the form ``instruction_shell``. + :return: Status code to exit with. + """ + shell, _, instruction = instruction.partition("_") + comp_cls = get_completion_class(shell) + + if comp_cls is None: + return 1 + + comp = comp_cls(cli, ctx_args, prog_name, complete_var) + + if instruction == "source": + echo(comp.source()) + return 0 + + if instruction == "complete": + echo(comp.complete()) + return 0 + + return 1 + + +class CompletionItem: + """Represents a completion value and metadata about the value. The + default metadata is ``type`` to indicate special shell handling, + and ``help`` if a shell supports showing a help string next to the + value. + + Arbitrary parameters can be passed when creating the object, and + accessed using ``item.attr``. If an attribute wasn't passed, + accessing it returns ``None``. + + :param value: The completion suggestion. + :param type: Tells the shell script to provide special completion + support for the type. Click uses ``"dir"`` and ``"file"``. + :param help: String shown next to the value if supported. + :param kwargs: Arbitrary metadata. The built-in implementations + don't use this, but custom type completions paired with custom + shell support could use it. + """ + + __slots__ = ("value", "type", "help", "_info") + + def __init__( + self, + value: t.Any, + type: str = "plain", + help: str | None = None, + **kwargs: t.Any, + ) -> None: + self.value: t.Any = value + self.type: str = type + self.help: str | None = help + self._info = kwargs + + def __getattr__(self, name: str) -> t.Any: + return self._info.get(name) + + +# Only Bash >= 4.4 has the nosort option. +_SOURCE_BASH = """\ +%(complete_func)s() { + local IFS=$'\\n' + local response + + response=$(env COMP_WORDS="${COMP_WORDS[*]}" COMP_CWORD=$COMP_CWORD \ +%(complete_var)s=bash_complete $1) + + for completion in $response; do + IFS=',' read type value <<< "$completion" + + if [[ $type == 'dir' ]]; then + COMPREPLY=() + compopt -o dirnames + elif [[ $type == 'file' ]]; then + COMPREPLY=() + compopt -o default + elif [[ $type == 'plain' ]]; then + COMPREPLY+=($value) + fi + done + + return 0 +} + +%(complete_func)s_setup() { + complete -o nosort -F %(complete_func)s %(prog_name)s +} + +%(complete_func)s_setup; +""" + +# See ZshComplete.format_completion below, and issue #2703, before +# changing this script. +# +# (TL;DR: _describe is picky about the format, but this Zsh script snippet +# is already widely deployed. So freeze this script, and use clever-ish +# handling of colons in ZshComplet.format_completion.) +_SOURCE_ZSH = """\ +#compdef %(prog_name)s + +%(complete_func)s() { + local -a completions + local -a completions_with_descriptions + local -a response + (( ! $+commands[%(prog_name)s] )) && return 1 + + response=("${(@f)$(env COMP_WORDS="${words[*]}" COMP_CWORD=$((CURRENT-1)) \ +%(complete_var)s=zsh_complete %(prog_name)s)}") + + for type key descr in ${response}; do + if [[ "$type" == "plain" ]]; then + if [[ "$descr" == "_" ]]; then + completions+=("$key") + else + completions_with_descriptions+=("$key":"$descr") + fi + elif [[ "$type" == "dir" ]]; then + _path_files -/ + elif [[ "$type" == "file" ]]; then + _path_files -f + fi + done + + if [ -n "$completions_with_descriptions" ]; then + _describe -V unsorted completions_with_descriptions -U + fi + + if [ -n "$completions" ]; then + compadd -U -V unsorted -a completions + fi +} + +if [[ $zsh_eval_context[-1] == loadautofunc ]]; then + # autoload from fpath, call function directly + %(complete_func)s "$@" +else + # eval/source/. command, register function for later + compdef %(complete_func)s %(prog_name)s +fi +""" + +_SOURCE_FISH = """\ +function %(complete_func)s; + set -l response (env %(complete_var)s=fish_complete COMP_WORDS=(commandline -cp) \ +COMP_CWORD=(commandline -t) %(prog_name)s); + + for completion in $response; + set -l metadata (string split "," $completion); + + if test $metadata[1] = "dir"; + __fish_complete_directories $metadata[2]; + else if test $metadata[1] = "file"; + __fish_complete_path $metadata[2]; + else if test $metadata[1] = "plain"; + echo $metadata[2]; + end; + end; +end; + +complete --no-files --command %(prog_name)s --arguments \ +"(%(complete_func)s)"; +""" + + +class ShellComplete: + """Base class for providing shell completion support. A subclass for + a given shell will override attributes and methods to implement the + completion instructions (``source`` and ``complete``). + + :param cli: Command being called. + :param prog_name: Name of the executable in the shell. + :param complete_var: Name of the environment variable that holds + the completion instruction. + + .. versionadded:: 8.0 + """ + + name: t.ClassVar[str] + """Name to register the shell as with :func:`add_completion_class`. + This is used in completion instructions (``{name}_source`` and + ``{name}_complete``). + """ + + source_template: t.ClassVar[str] + """Completion script template formatted by :meth:`source`. This must + be provided by subclasses. + """ + + def __init__( + self, + cli: Command, + ctx_args: cabc.MutableMapping[str, t.Any], + prog_name: str, + complete_var: str, + ) -> None: + self.cli = cli + self.ctx_args = ctx_args + self.prog_name = prog_name + self.complete_var = complete_var + + @property + def func_name(self) -> str: + """The name of the shell function defined by the completion + script. + """ + safe_name = re.sub(r"\W*", "", self.prog_name.replace("-", "_"), flags=re.ASCII) + return f"_{safe_name}_completion" + + def source_vars(self) -> dict[str, t.Any]: + """Vars for formatting :attr:`source_template`. + + By default this provides ``complete_func``, ``complete_var``, + and ``prog_name``. + """ + return { + "complete_func": self.func_name, + "complete_var": self.complete_var, + "prog_name": self.prog_name, + } + + def source(self) -> str: + """Produce the shell script that defines the completion + function. By default this ``%``-style formats + :attr:`source_template` with the dict returned by + :meth:`source_vars`. + """ + return self.source_template % self.source_vars() + + def get_completion_args(self) -> tuple[list[str], str]: + """Use the env vars defined by the shell script to return a + tuple of ``args, incomplete``. This must be implemented by + subclasses. + """ + raise NotImplementedError + + def get_completions(self, args: list[str], incomplete: str) -> list[CompletionItem]: + """Determine the context and last complete command or parameter + from the complete args. Call that object's ``shell_complete`` + method to get the completions for the incomplete value. + + :param args: List of complete args before the incomplete value. + :param incomplete: Value being completed. May be empty. + """ + ctx = _resolve_context(self.cli, self.ctx_args, self.prog_name, args) + obj, incomplete = _resolve_incomplete(ctx, args, incomplete) + return obj.shell_complete(ctx, incomplete) + + def format_completion(self, item: CompletionItem) -> str: + """Format a completion item into the form recognized by the + shell script. This must be implemented by subclasses. + + :param item: Completion item to format. + """ + raise NotImplementedError + + def complete(self) -> str: + """Produce the completion data to send back to the shell. + + By default this calls :meth:`get_completion_args`, gets the + completions, then calls :meth:`format_completion` for each + completion. + """ + args, incomplete = self.get_completion_args() + completions = self.get_completions(args, incomplete) + out = [self.format_completion(item) for item in completions] + return "\n".join(out) + + +class BashComplete(ShellComplete): + """Shell completion for Bash.""" + + name = "bash" + source_template = _SOURCE_BASH + + @staticmethod + def _check_version() -> None: + import shutil + import subprocess + + bash_exe = shutil.which("bash") + + if bash_exe is None: + match = None + else: + output = subprocess.run( + [bash_exe, "--norc", "-c", 'echo "${BASH_VERSION}"'], + stdout=subprocess.PIPE, + ) + match = re.search(r"^(\d+)\.(\d+)\.\d+", output.stdout.decode()) + + if match is not None: + major, minor = match.groups() + + if major < "4" or major == "4" and minor < "4": + echo( + _( + "Shell completion is not supported for Bash" + " versions older than 4.4." + ), + err=True, + ) + else: + echo( + _("Couldn't detect Bash version, shell completion is not supported."), + err=True, + ) + + def source(self) -> str: + self._check_version() + return super().source() + + def get_completion_args(self) -> tuple[list[str], str]: + cwords = split_arg_string(os.environ["COMP_WORDS"]) + cword = int(os.environ["COMP_CWORD"]) + args = cwords[1:cword] + + try: + incomplete = cwords[cword] + except IndexError: + incomplete = "" + + return args, incomplete + + def format_completion(self, item: CompletionItem) -> str: + return f"{item.type},{item.value}" + + +class ZshComplete(ShellComplete): + """Shell completion for Zsh.""" + + name = "zsh" + source_template = _SOURCE_ZSH + + def get_completion_args(self) -> tuple[list[str], str]: + cwords = split_arg_string(os.environ["COMP_WORDS"]) + cword = int(os.environ["COMP_CWORD"]) + args = cwords[1:cword] + + try: + incomplete = cwords[cword] + except IndexError: + incomplete = "" + + return args, incomplete + + def format_completion(self, item: CompletionItem) -> str: + help_ = item.help or "_" + # The zsh completion script uses `_describe` on items with help + # texts (which splits the item help from the item value at the + # first unescaped colon) and `compadd` on items without help + # text (which uses the item value as-is and does not support + # colon escaping). So escape colons in the item value if and + # only if the item help is not the sentinel "_" value, as used + # by the completion script. + # + # (The zsh completion script is potentially widely deployed, and + # thus harder to fix than this method.) + # + # See issue #1812 and issue #2703 for further context. + value = item.value.replace(":", r"\:") if help_ != "_" else item.value + return f"{item.type}\n{value}\n{help_}" + + +class FishComplete(ShellComplete): + """Shell completion for Fish.""" + + name = "fish" + source_template = _SOURCE_FISH + + def get_completion_args(self) -> tuple[list[str], str]: + cwords = split_arg_string(os.environ["COMP_WORDS"]) + incomplete = os.environ["COMP_CWORD"] + if incomplete: + incomplete = split_arg_string(incomplete)[0] + args = cwords[1:] + + # Fish stores the partial word in both COMP_WORDS and + # COMP_CWORD, remove it from complete args. + if incomplete and args and args[-1] == incomplete: + args.pop() + + return args, incomplete + + def format_completion(self, item: CompletionItem) -> str: + if item.help: + return f"{item.type},{item.value}\t{item.help}" + + return f"{item.type},{item.value}" + + +ShellCompleteType = t.TypeVar("ShellCompleteType", bound="type[ShellComplete]") + + +_available_shells: dict[str, type[ShellComplete]] = { + "bash": BashComplete, + "fish": FishComplete, + "zsh": ZshComplete, +} + + +def add_completion_class( + cls: ShellCompleteType, name: str | None = None +) -> ShellCompleteType: + """Register a :class:`ShellComplete` subclass under the given name. + The name will be provided by the completion instruction environment + variable during completion. + + :param cls: The completion class that will handle completion for the + shell. + :param name: Name to register the class under. Defaults to the + class's ``name`` attribute. + """ + if name is None: + name = cls.name + + _available_shells[name] = cls + + return cls + + +def get_completion_class(shell: str) -> type[ShellComplete] | None: + """Look up a registered :class:`ShellComplete` subclass by the name + provided by the completion instruction environment variable. If the + name isn't registered, returns ``None``. + + :param shell: Name the class is registered under. + """ + return _available_shells.get(shell) + + +def split_arg_string(string: str) -> list[str]: + """Split an argument string as with :func:`shlex.split`, but don't + fail if the string is incomplete. Ignores a missing closing quote or + incomplete escape sequence and uses the partial token as-is. + + .. code-block:: python + + split_arg_string("example 'my file") + ["example", "my file"] + + split_arg_string("example my\\") + ["example", "my"] + + :param string: String to split. + + .. versionchanged:: 8.2 + Moved to ``shell_completion`` from ``parser``. + """ + import shlex + + lex = shlex.shlex(string, posix=True) + lex.whitespace_split = True + lex.commenters = "" + out = [] + + try: + for token in lex: + out.append(token) + except ValueError: + # Raised when end-of-string is reached in an invalid state. Use + # the partial token as-is. The quote or escape character is in + # lex.state, not lex.token. + out.append(lex.token) + + return out + + +def _is_incomplete_argument(ctx: Context, param: Parameter) -> bool: + """Determine if the given parameter is an argument that can still + accept values. + + :param ctx: Invocation context for the command represented by the + parsed complete args. + :param param: Argument object being checked. + """ + if not isinstance(param, Argument): + return False + + assert param.name is not None + # Will be None if expose_value is False. + value = ctx.params.get(param.name) + return ( + param.nargs == -1 + or ctx.get_parameter_source(param.name) is not ParameterSource.COMMANDLINE + or ( + param.nargs > 1 + and isinstance(value, (tuple, list)) + and len(value) < param.nargs + ) + ) + + +def _start_of_option(ctx: Context, value: str) -> bool: + """Check if the value looks like the start of an option.""" + if not value: + return False + + c = value[0] + return c in ctx._opt_prefixes + + +def _is_incomplete_option(ctx: Context, args: list[str], param: Parameter) -> bool: + """Determine if the given parameter is an option that needs a value. + + :param args: List of complete args before the incomplete value. + :param param: Option object being checked. + """ + if not isinstance(param, Option): + return False + + if param.is_flag or param.count: + return False + + last_option = None + + for index, arg in enumerate(reversed(args)): + if index + 1 > param.nargs: + break + + if _start_of_option(ctx, arg): + last_option = arg + break + + return last_option is not None and last_option in param.opts + + +def _resolve_context( + cli: Command, + ctx_args: cabc.MutableMapping[str, t.Any], + prog_name: str, + args: list[str], +) -> Context: + """Produce the context hierarchy starting with the command and + traversing the complete arguments. This only follows the commands, + it doesn't trigger input prompts or callbacks. + + :param cli: Command being called. + :param prog_name: Name of the executable in the shell. + :param args: List of complete args before the incomplete value. + """ + ctx_args["resilient_parsing"] = True + with cli.make_context(prog_name, args.copy(), **ctx_args) as ctx: + args = ctx._protected_args + ctx.args + + while args: + command = ctx.command + + if isinstance(command, Group): + if not command.chain: + name, cmd, args = command.resolve_command(ctx, args) + + if cmd is None: + return ctx + + with cmd.make_context( + name, args, parent=ctx, resilient_parsing=True + ) as sub_ctx: + ctx = sub_ctx + args = ctx._protected_args + ctx.args + else: + sub_ctx = ctx + + while args: + name, cmd, args = command.resolve_command(ctx, args) + + if cmd is None: + return ctx + + with cmd.make_context( + name, + args, + parent=ctx, + allow_extra_args=True, + allow_interspersed_args=False, + resilient_parsing=True, + ) as sub_sub_ctx: + sub_ctx = sub_sub_ctx + args = sub_ctx.args + + ctx = sub_ctx + args = [*sub_ctx._protected_args, *sub_ctx.args] + else: + break + + return ctx + + +def _resolve_incomplete( + ctx: Context, args: list[str], incomplete: str +) -> tuple[Command | Parameter, str]: + """Find the Click object that will handle the completion of the + incomplete value. Return the object and the incomplete value. + + :param ctx: Invocation context for the command represented by + the parsed complete args. + :param args: List of complete args before the incomplete value. + :param incomplete: Value being completed. May be empty. + """ + # Different shells treat an "=" between a long option name and + # value differently. Might keep the value joined, return the "=" + # as a separate item, or return the split name and value. Always + # split and discard the "=" to make completion easier. + if incomplete == "=": + incomplete = "" + elif "=" in incomplete and _start_of_option(ctx, incomplete): + name, _, incomplete = incomplete.partition("=") + args.append(name) + + # The "--" marker tells Click to stop treating values as options + # even if they start with the option character. If it hasn't been + # given and the incomplete arg looks like an option, the current + # command will provide option name completions. + if "--" not in args and _start_of_option(ctx, incomplete): + return ctx.command, incomplete + + params = ctx.command.get_params(ctx) + + # If the last complete arg is an option name with an incomplete + # value, the option will provide value completions. + for param in params: + if _is_incomplete_option(ctx, args, param): + return param, incomplete + + # It's not an option name or value. The first argument without a + # parsed value will provide value completions. + for param in params: + if _is_incomplete_argument(ctx, param): + return param, incomplete + + # There were no unparsed arguments, the command may be a group that + # will provide command name completions. + return ctx.command, incomplete diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/click/termui.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/click/termui.py new file mode 100644 index 000000000..2e98a0771 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/click/termui.py @@ -0,0 +1,883 @@ +from __future__ import annotations + +import collections.abc as cabc +import inspect +import io +import itertools +import sys +import typing as t +from contextlib import AbstractContextManager +from gettext import gettext as _ + +from ._compat import isatty +from ._compat import strip_ansi +from .exceptions import Abort +from .exceptions import UsageError +from .globals import resolve_color_default +from .types import Choice +from .types import convert_type +from .types import ParamType +from .utils import echo +from .utils import LazyFile + +if t.TYPE_CHECKING: + from ._termui_impl import ProgressBar + +V = t.TypeVar("V") + +# The prompt functions to use. The doc tools currently override these +# functions to customize how they work. +visible_prompt_func: t.Callable[[str], str] = input + +_ansi_colors = { + "black": 30, + "red": 31, + "green": 32, + "yellow": 33, + "blue": 34, + "magenta": 35, + "cyan": 36, + "white": 37, + "reset": 39, + "bright_black": 90, + "bright_red": 91, + "bright_green": 92, + "bright_yellow": 93, + "bright_blue": 94, + "bright_magenta": 95, + "bright_cyan": 96, + "bright_white": 97, +} +_ansi_reset_all = "\033[0m" + + +def hidden_prompt_func(prompt: str) -> str: + import getpass + + return getpass.getpass(prompt) + + +def _build_prompt( + text: str, + suffix: str, + show_default: bool = False, + default: t.Any | None = None, + show_choices: bool = True, + type: ParamType | None = None, +) -> str: + prompt = text + if type is not None and show_choices and isinstance(type, Choice): + prompt += f" ({', '.join(map(str, type.choices))})" + if default is not None and show_default: + prompt = f"{prompt} [{_format_default(default)}]" + return f"{prompt}{suffix}" + + +def _format_default(default: t.Any) -> t.Any: + if isinstance(default, (io.IOBase, LazyFile)) and hasattr(default, "name"): + return default.name + + return default + + +def prompt( + text: str, + default: t.Any | None = None, + hide_input: bool = False, + confirmation_prompt: bool | str = False, + type: ParamType | t.Any | None = None, + value_proc: t.Callable[[str], t.Any] | None = None, + prompt_suffix: str = ": ", + show_default: bool = True, + err: bool = False, + show_choices: bool = True, +) -> t.Any: + """Prompts a user for input. This is a convenience function that can + be used to prompt a user for input later. + + If the user aborts the input by sending an interrupt signal, this + function will catch it and raise a :exc:`Abort` exception. + + :param text: the text to show for the prompt. + :param default: the default value to use if no input happens. If this + is not given it will prompt until it's aborted. + :param hide_input: if this is set to true then the input value will + be hidden. + :param confirmation_prompt: Prompt a second time to confirm the + value. Can be set to a string instead of ``True`` to customize + the message. + :param type: the type to use to check the value against. + :param value_proc: if this parameter is provided it's a function that + is invoked instead of the type conversion to + convert a value. + :param prompt_suffix: a suffix that should be added to the prompt. + :param show_default: shows or hides the default value in the prompt. + :param err: if set to true the file defaults to ``stderr`` instead of + ``stdout``, the same as with echo. + :param show_choices: Show or hide choices if the passed type is a Choice. + For example if type is a Choice of either day or week, + show_choices is true and text is "Group by" then the + prompt will be "Group by (day, week): ". + + .. versionchanged:: 8.3.1 + A space is no longer appended to the prompt. + + .. versionadded:: 8.0 + ``confirmation_prompt`` can be a custom string. + + .. versionadded:: 7.0 + Added the ``show_choices`` parameter. + + .. versionadded:: 6.0 + Added unicode support for cmd.exe on Windows. + + .. versionadded:: 4.0 + Added the `err` parameter. + + """ + + def prompt_func(text: str) -> str: + f = hidden_prompt_func if hide_input else visible_prompt_func + try: + # Write the prompt separately so that we get nice + # coloring through colorama on Windows + echo(text[:-1], nl=False, err=err) + # Echo the last character to stdout to work around an issue where + # readline causes backspace to clear the whole line. + return f(text[-1:]) + except (KeyboardInterrupt, EOFError): + # getpass doesn't print a newline if the user aborts input with ^C. + # Allegedly this behavior is inherited from getpass(3). + # A doc bug has been filed at https://bugs.python.org/issue24711 + if hide_input: + echo(None, err=err) + raise Abort() from None + + if value_proc is None: + value_proc = convert_type(type, default) + + prompt = _build_prompt( + text, prompt_suffix, show_default, default, show_choices, type + ) + + if confirmation_prompt: + if confirmation_prompt is True: + confirmation_prompt = _("Repeat for confirmation") + + confirmation_prompt = _build_prompt(confirmation_prompt, prompt_suffix) + + while True: + while True: + value = prompt_func(prompt) + if value: + break + elif default is not None: + value = default + break + try: + result = value_proc(value) + except UsageError as e: + if hide_input: + echo(_("Error: The value you entered was invalid."), err=err) + else: + echo(_("Error: {e.message}").format(e=e), err=err) + continue + if not confirmation_prompt: + return result + while True: + value2 = prompt_func(confirmation_prompt) + is_empty = not value and not value2 + if value2 or is_empty: + break + if value == value2: + return result + echo(_("Error: The two entered values do not match."), err=err) + + +def confirm( + text: str, + default: bool | None = False, + abort: bool = False, + prompt_suffix: str = ": ", + show_default: bool = True, + err: bool = False, +) -> bool: + """Prompts for confirmation (yes/no question). + + If the user aborts the input by sending a interrupt signal this + function will catch it and raise a :exc:`Abort` exception. + + :param text: the question to ask. + :param default: The default value to use when no input is given. If + ``None``, repeat until input is given. + :param abort: if this is set to `True` a negative answer aborts the + exception by raising :exc:`Abort`. + :param prompt_suffix: a suffix that should be added to the prompt. + :param show_default: shows or hides the default value in the prompt. + :param err: if set to true the file defaults to ``stderr`` instead of + ``stdout``, the same as with echo. + + .. versionchanged:: 8.3.1 + A space is no longer appended to the prompt. + + .. versionchanged:: 8.0 + Repeat until input is given if ``default`` is ``None``. + + .. versionadded:: 4.0 + Added the ``err`` parameter. + """ + prompt = _build_prompt( + text, + prompt_suffix, + show_default, + "y/n" if default is None else ("Y/n" if default else "y/N"), + ) + + while True: + try: + # Write the prompt separately so that we get nice + # coloring through colorama on Windows + echo(prompt[:-1], nl=False, err=err) + # Echo the last character to stdout to work around an issue where + # readline causes backspace to clear the whole line. + value = visible_prompt_func(prompt[-1:]).lower().strip() + except (KeyboardInterrupt, EOFError): + raise Abort() from None + if value in ("y", "yes"): + rv = True + elif value in ("n", "no"): + rv = False + elif default is not None and value == "": + rv = default + else: + echo(_("Error: invalid input"), err=err) + continue + break + if abort and not rv: + raise Abort() + return rv + + +def echo_via_pager( + text_or_generator: cabc.Iterable[str] | t.Callable[[], cabc.Iterable[str]] | str, + color: bool | None = None, +) -> None: + """This function takes a text and shows it via an environment specific + pager on stdout. + + .. versionchanged:: 3.0 + Added the `color` flag. + + :param text_or_generator: the text to page, or alternatively, a + generator emitting the text to page. + :param color: controls if the pager supports ANSI colors or not. The + default is autodetection. + """ + color = resolve_color_default(color) + + if inspect.isgeneratorfunction(text_or_generator): + i = t.cast("t.Callable[[], cabc.Iterable[str]]", text_or_generator)() + elif isinstance(text_or_generator, str): + i = [text_or_generator] + else: + i = iter(t.cast("cabc.Iterable[str]", text_or_generator)) + + # convert every element of i to a text type if necessary + text_generator = (el if isinstance(el, str) else str(el) for el in i) + + from ._termui_impl import pager + + return pager(itertools.chain(text_generator, "\n"), color) + + +@t.overload +def progressbar( + *, + length: int, + label: str | None = None, + hidden: bool = False, + show_eta: bool = True, + show_percent: bool | None = None, + show_pos: bool = False, + fill_char: str = "#", + empty_char: str = "-", + bar_template: str = "%(label)s [%(bar)s] %(info)s", + info_sep: str = " ", + width: int = 36, + file: t.TextIO | None = None, + color: bool | None = None, + update_min_steps: int = 1, +) -> ProgressBar[int]: ... + + +@t.overload +def progressbar( + iterable: cabc.Iterable[V] | None = None, + length: int | None = None, + label: str | None = None, + hidden: bool = False, + show_eta: bool = True, + show_percent: bool | None = None, + show_pos: bool = False, + item_show_func: t.Callable[[V | None], str | None] | None = None, + fill_char: str = "#", + empty_char: str = "-", + bar_template: str = "%(label)s [%(bar)s] %(info)s", + info_sep: str = " ", + width: int = 36, + file: t.TextIO | None = None, + color: bool | None = None, + update_min_steps: int = 1, +) -> ProgressBar[V]: ... + + +def progressbar( + iterable: cabc.Iterable[V] | None = None, + length: int | None = None, + label: str | None = None, + hidden: bool = False, + show_eta: bool = True, + show_percent: bool | None = None, + show_pos: bool = False, + item_show_func: t.Callable[[V | None], str | None] | None = None, + fill_char: str = "#", + empty_char: str = "-", + bar_template: str = "%(label)s [%(bar)s] %(info)s", + info_sep: str = " ", + width: int = 36, + file: t.TextIO | None = None, + color: bool | None = None, + update_min_steps: int = 1, +) -> ProgressBar[V]: + """This function creates an iterable context manager that can be used + to iterate over something while showing a progress bar. It will + either iterate over the `iterable` or `length` items (that are counted + up). While iteration happens, this function will print a rendered + progress bar to the given `file` (defaults to stdout) and will attempt + to calculate remaining time and more. By default, this progress bar + will not be rendered if the file is not a terminal. + + The context manager creates the progress bar. When the context + manager is entered the progress bar is already created. With every + iteration over the progress bar, the iterable passed to the bar is + advanced and the bar is updated. When the context manager exits, + a newline is printed and the progress bar is finalized on screen. + + Note: The progress bar is currently designed for use cases where the + total progress can be expected to take at least several seconds. + Because of this, the ProgressBar class object won't display + progress that is considered too fast, and progress where the time + between steps is less than a second. + + No printing must happen or the progress bar will be unintentionally + destroyed. + + Example usage:: + + with progressbar(items) as bar: + for item in bar: + do_something_with(item) + + Alternatively, if no iterable is specified, one can manually update the + progress bar through the `update()` method instead of directly + iterating over the progress bar. The update method accepts the number + of steps to increment the bar with:: + + with progressbar(length=chunks.total_bytes) as bar: + for chunk in chunks: + process_chunk(chunk) + bar.update(chunks.bytes) + + The ``update()`` method also takes an optional value specifying the + ``current_item`` at the new position. This is useful when used + together with ``item_show_func`` to customize the output for each + manual step:: + + with click.progressbar( + length=total_size, + label='Unzipping archive', + item_show_func=lambda a: a.filename + ) as bar: + for archive in zip_file: + archive.extract() + bar.update(archive.size, archive) + + :param iterable: an iterable to iterate over. If not provided the length + is required. + :param length: the number of items to iterate over. By default the + progressbar will attempt to ask the iterator about its + length, which might or might not work. If an iterable is + also provided this parameter can be used to override the + length. If an iterable is not provided the progress bar + will iterate over a range of that length. + :param label: the label to show next to the progress bar. + :param hidden: hide the progressbar. Defaults to ``False``. When no tty is + detected, it will only print the progressbar label. Setting this to + ``False`` also disables that. + :param show_eta: enables or disables the estimated time display. This is + automatically disabled if the length cannot be + determined. + :param show_percent: enables or disables the percentage display. The + default is `True` if the iterable has a length or + `False` if not. + :param show_pos: enables or disables the absolute position display. The + default is `False`. + :param item_show_func: A function called with the current item which + can return a string to show next to the progress bar. If the + function returns ``None`` nothing is shown. The current item can + be ``None``, such as when entering and exiting the bar. + :param fill_char: the character to use to show the filled part of the + progress bar. + :param empty_char: the character to use to show the non-filled part of + the progress bar. + :param bar_template: the format string to use as template for the bar. + The parameters in it are ``label`` for the label, + ``bar`` for the progress bar and ``info`` for the + info section. + :param info_sep: the separator between multiple info items (eta etc.) + :param width: the width of the progress bar in characters, 0 means full + terminal width + :param file: The file to write to. If this is not a terminal then + only the label is printed. + :param color: controls if the terminal supports ANSI colors or not. The + default is autodetection. This is only needed if ANSI + codes are included anywhere in the progress bar output + which is not the case by default. + :param update_min_steps: Render only when this many updates have + completed. This allows tuning for very fast iterators. + + .. versionadded:: 8.2 + The ``hidden`` argument. + + .. versionchanged:: 8.0 + Output is shown even if execution time is less than 0.5 seconds. + + .. versionchanged:: 8.0 + ``item_show_func`` shows the current item, not the previous one. + + .. versionchanged:: 8.0 + Labels are echoed if the output is not a TTY. Reverts a change + in 7.0 that removed all output. + + .. versionadded:: 8.0 + The ``update_min_steps`` parameter. + + .. versionadded:: 4.0 + The ``color`` parameter and ``update`` method. + + .. versionadded:: 2.0 + """ + from ._termui_impl import ProgressBar + + color = resolve_color_default(color) + return ProgressBar( + iterable=iterable, + length=length, + hidden=hidden, + show_eta=show_eta, + show_percent=show_percent, + show_pos=show_pos, + item_show_func=item_show_func, + fill_char=fill_char, + empty_char=empty_char, + bar_template=bar_template, + info_sep=info_sep, + file=file, + label=label, + width=width, + color=color, + update_min_steps=update_min_steps, + ) + + +def clear() -> None: + """Clears the terminal screen. This will have the effect of clearing + the whole visible space of the terminal and moving the cursor to the + top left. This does not do anything if not connected to a terminal. + + .. versionadded:: 2.0 + """ + if not isatty(sys.stdout): + return + + # ANSI escape \033[2J clears the screen, \033[1;1H moves the cursor + echo("\033[2J\033[1;1H", nl=False) + + +def _interpret_color(color: int | tuple[int, int, int] | str, offset: int = 0) -> str: + if isinstance(color, int): + return f"{38 + offset};5;{color:d}" + + if isinstance(color, (tuple, list)): + r, g, b = color + return f"{38 + offset};2;{r:d};{g:d};{b:d}" + + return str(_ansi_colors[color] + offset) + + +def style( + text: t.Any, + fg: int | tuple[int, int, int] | str | None = None, + bg: int | tuple[int, int, int] | str | None = None, + bold: bool | None = None, + dim: bool | None = None, + underline: bool | None = None, + overline: bool | None = None, + italic: bool | None = None, + blink: bool | None = None, + reverse: bool | None = None, + strikethrough: bool | None = None, + reset: bool = True, +) -> str: + """Styles a text with ANSI styles and returns the new string. By + default the styling is self contained which means that at the end + of the string a reset code is issued. This can be prevented by + passing ``reset=False``. + + Examples:: + + click.echo(click.style('Hello World!', fg='green')) + click.echo(click.style('ATTENTION!', blink=True)) + click.echo(click.style('Some things', reverse=True, fg='cyan')) + click.echo(click.style('More colors', fg=(255, 12, 128), bg=117)) + + Supported color names: + + * ``black`` (might be a gray) + * ``red`` + * ``green`` + * ``yellow`` (might be an orange) + * ``blue`` + * ``magenta`` + * ``cyan`` + * ``white`` (might be light gray) + * ``bright_black`` + * ``bright_red`` + * ``bright_green`` + * ``bright_yellow`` + * ``bright_blue`` + * ``bright_magenta`` + * ``bright_cyan`` + * ``bright_white`` + * ``reset`` (reset the color code only) + + If the terminal supports it, color may also be specified as: + + - An integer in the interval [0, 255]. The terminal must support + 8-bit/256-color mode. + - An RGB tuple of three integers in [0, 255]. The terminal must + support 24-bit/true-color mode. + + See https://en.wikipedia.org/wiki/ANSI_color and + https://gist.github.com/XVilka/8346728 for more information. + + :param text: the string to style with ansi codes. + :param fg: if provided this will become the foreground color. + :param bg: if provided this will become the background color. + :param bold: if provided this will enable or disable bold mode. + :param dim: if provided this will enable or disable dim mode. This is + badly supported. + :param underline: if provided this will enable or disable underline. + :param overline: if provided this will enable or disable overline. + :param italic: if provided this will enable or disable italic. + :param blink: if provided this will enable or disable blinking. + :param reverse: if provided this will enable or disable inverse + rendering (foreground becomes background and the + other way round). + :param strikethrough: if provided this will enable or disable + striking through text. + :param reset: by default a reset-all code is added at the end of the + string which means that styles do not carry over. This + can be disabled to compose styles. + + .. versionchanged:: 8.0 + A non-string ``message`` is converted to a string. + + .. versionchanged:: 8.0 + Added support for 256 and RGB color codes. + + .. versionchanged:: 8.0 + Added the ``strikethrough``, ``italic``, and ``overline`` + parameters. + + .. versionchanged:: 7.0 + Added support for bright colors. + + .. versionadded:: 2.0 + """ + if not isinstance(text, str): + text = str(text) + + bits = [] + + if fg: + try: + bits.append(f"\033[{_interpret_color(fg)}m") + except KeyError: + raise TypeError(f"Unknown color {fg!r}") from None + + if bg: + try: + bits.append(f"\033[{_interpret_color(bg, 10)}m") + except KeyError: + raise TypeError(f"Unknown color {bg!r}") from None + + if bold is not None: + bits.append(f"\033[{1 if bold else 22}m") + if dim is not None: + bits.append(f"\033[{2 if dim else 22}m") + if underline is not None: + bits.append(f"\033[{4 if underline else 24}m") + if overline is not None: + bits.append(f"\033[{53 if overline else 55}m") + if italic is not None: + bits.append(f"\033[{3 if italic else 23}m") + if blink is not None: + bits.append(f"\033[{5 if blink else 25}m") + if reverse is not None: + bits.append(f"\033[{7 if reverse else 27}m") + if strikethrough is not None: + bits.append(f"\033[{9 if strikethrough else 29}m") + bits.append(text) + if reset: + bits.append(_ansi_reset_all) + return "".join(bits) + + +def unstyle(text: str) -> str: + """Removes ANSI styling information from a string. Usually it's not + necessary to use this function as Click's echo function will + automatically remove styling if necessary. + + .. versionadded:: 2.0 + + :param text: the text to remove style information from. + """ + return strip_ansi(text) + + +def secho( + message: t.Any | None = None, + file: t.IO[t.AnyStr] | None = None, + nl: bool = True, + err: bool = False, + color: bool | None = None, + **styles: t.Any, +) -> None: + """This function combines :func:`echo` and :func:`style` into one + call. As such the following two calls are the same:: + + click.secho('Hello World!', fg='green') + click.echo(click.style('Hello World!', fg='green')) + + All keyword arguments are forwarded to the underlying functions + depending on which one they go with. + + Non-string types will be converted to :class:`str`. However, + :class:`bytes` are passed directly to :meth:`echo` without applying + style. If you want to style bytes that represent text, call + :meth:`bytes.decode` first. + + .. versionchanged:: 8.0 + A non-string ``message`` is converted to a string. Bytes are + passed through without style applied. + + .. versionadded:: 2.0 + """ + if message is not None and not isinstance(message, (bytes, bytearray)): + message = style(message, **styles) + + return echo(message, file=file, nl=nl, err=err, color=color) + + +@t.overload +def edit( + text: bytes | bytearray, + editor: str | None = None, + env: cabc.Mapping[str, str] | None = None, + require_save: bool = False, + extension: str = ".txt", +) -> bytes | None: ... + + +@t.overload +def edit( + text: str, + editor: str | None = None, + env: cabc.Mapping[str, str] | None = None, + require_save: bool = True, + extension: str = ".txt", +) -> str | None: ... + + +@t.overload +def edit( + text: None = None, + editor: str | None = None, + env: cabc.Mapping[str, str] | None = None, + require_save: bool = True, + extension: str = ".txt", + filename: str | cabc.Iterable[str] | None = None, +) -> None: ... + + +def edit( + text: str | bytes | bytearray | None = None, + editor: str | None = None, + env: cabc.Mapping[str, str] | None = None, + require_save: bool = True, + extension: str = ".txt", + filename: str | cabc.Iterable[str] | None = None, +) -> str | bytes | bytearray | None: + r"""Edits the given text in the defined editor. If an editor is given + (should be the full path to the executable but the regular operating + system search path is used for finding the executable) it overrides + the detected editor. Optionally, some environment variables can be + used. If the editor is closed without changes, `None` is returned. In + case a file is edited directly the return value is always `None` and + `require_save` and `extension` are ignored. + + If the editor cannot be opened a :exc:`UsageError` is raised. + + Note for Windows: to simplify cross-platform usage, the newlines are + automatically converted from POSIX to Windows and vice versa. As such, + the message here will have ``\n`` as newline markers. + + :param text: the text to edit. + :param editor: optionally the editor to use. Defaults to automatic + detection. + :param env: environment variables to forward to the editor. + :param require_save: if this is true, then not saving in the editor + will make the return value become `None`. + :param extension: the extension to tell the editor about. This defaults + to `.txt` but changing this might change syntax + highlighting. + :param filename: if provided it will edit this file instead of the + provided text contents. It will not use a temporary + file as an indirection in that case. If the editor supports + editing multiple files at once, a sequence of files may be + passed as well. Invoke `click.file` once per file instead + if multiple files cannot be managed at once or editing the + files serially is desired. + + .. versionchanged:: 8.2.0 + ``filename`` now accepts any ``Iterable[str]`` in addition to a ``str`` + if the ``editor`` supports editing multiple files at once. + + """ + from ._termui_impl import Editor + + ed = Editor(editor=editor, env=env, require_save=require_save, extension=extension) + + if filename is None: + return ed.edit(text) + + if isinstance(filename, str): + filename = (filename,) + + ed.edit_files(filenames=filename) + return None + + +def launch(url: str, wait: bool = False, locate: bool = False) -> int: + """This function launches the given URL (or filename) in the default + viewer application for this file type. If this is an executable, it + might launch the executable in a new session. The return value is + the exit code of the launched application. Usually, ``0`` indicates + success. + + Examples:: + + click.launch('https://click.palletsprojects.com/') + click.launch('/my/downloaded/file', locate=True) + + .. versionadded:: 2.0 + + :param url: URL or filename of the thing to launch. + :param wait: Wait for the program to exit before returning. This + only works if the launched program blocks. In particular, + ``xdg-open`` on Linux does not block. + :param locate: if this is set to `True` then instead of launching the + application associated with the URL it will attempt to + launch a file manager with the file located. This + might have weird effects if the URL does not point to + the filesystem. + """ + from ._termui_impl import open_url + + return open_url(url, wait=wait, locate=locate) + + +# If this is provided, getchar() calls into this instead. This is used +# for unittesting purposes. +_getchar: t.Callable[[bool], str] | None = None + + +def getchar(echo: bool = False) -> str: + """Fetches a single character from the terminal and returns it. This + will always return a unicode character and under certain rare + circumstances this might return more than one character. The + situations which more than one character is returned is when for + whatever reason multiple characters end up in the terminal buffer or + standard input was not actually a terminal. + + Note that this will always read from the terminal, even if something + is piped into the standard input. + + Note for Windows: in rare cases when typing non-ASCII characters, this + function might wait for a second character and then return both at once. + This is because certain Unicode characters look like special-key markers. + + .. versionadded:: 2.0 + + :param echo: if set to `True`, the character read will also show up on + the terminal. The default is to not show it. + """ + global _getchar + + if _getchar is None: + from ._termui_impl import getchar as f + + _getchar = f + + return _getchar(echo) + + +def raw_terminal() -> AbstractContextManager[int]: + from ._termui_impl import raw_terminal as f + + return f() + + +def pause(info: str | None = None, err: bool = False) -> None: + """This command stops execution and waits for the user to press any + key to continue. This is similar to the Windows batch "pause" + command. If the program is not run through a terminal, this command + will instead do nothing. + + .. versionadded:: 2.0 + + .. versionadded:: 4.0 + Added the `err` parameter. + + :param info: The message to print before pausing. Defaults to + ``"Press any key to continue..."``. + :param err: if set to message goes to ``stderr`` instead of + ``stdout``, the same as with echo. + """ + if not isatty(sys.stdin) or not isatty(sys.stdout): + return + + if info is None: + info = _("Press any key to continue...") + + try: + if info: + echo(info, nl=False, err=err) + try: + getchar() + except (KeyboardInterrupt, EOFError): + pass + finally: + if info: + echo(err=err) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/click/testing.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/click/testing.py new file mode 100644 index 000000000..ebfd54dc7 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/click/testing.py @@ -0,0 +1,574 @@ +from __future__ import annotations + +import collections.abc as cabc +import contextlib +import io +import os +import shlex +import sys +import tempfile +import typing as t +from types import TracebackType + +from . import _compat +from . import formatting +from . import termui +from . import utils +from ._compat import _find_binary_reader + +if t.TYPE_CHECKING: + from _typeshed import ReadableBuffer + + from .core import Command + + +class EchoingStdin: + def __init__(self, input: t.BinaryIO, output: t.BinaryIO) -> None: + self._input = input + self._output = output + self._paused = False + + def __getattr__(self, x: str) -> t.Any: + return getattr(self._input, x) + + def _echo(self, rv: bytes) -> bytes: + if not self._paused: + self._output.write(rv) + + return rv + + def read(self, n: int = -1) -> bytes: + return self._echo(self._input.read(n)) + + def read1(self, n: int = -1) -> bytes: + return self._echo(self._input.read1(n)) # type: ignore + + def readline(self, n: int = -1) -> bytes: + return self._echo(self._input.readline(n)) + + def readlines(self) -> list[bytes]: + return [self._echo(x) for x in self._input.readlines()] + + def __iter__(self) -> cabc.Iterator[bytes]: + return iter(self._echo(x) for x in self._input) + + def __repr__(self) -> str: + return repr(self._input) + + +@contextlib.contextmanager +def _pause_echo(stream: EchoingStdin | None) -> cabc.Iterator[None]: + if stream is None: + yield + else: + stream._paused = True + yield + stream._paused = False + + +class BytesIOCopy(io.BytesIO): + """Patch ``io.BytesIO`` to let the written stream be copied to another. + + .. versionadded:: 8.2 + """ + + def __init__(self, copy_to: io.BytesIO) -> None: + super().__init__() + self.copy_to = copy_to + + def flush(self) -> None: + super().flush() + self.copy_to.flush() + + def write(self, b: ReadableBuffer) -> int: + self.copy_to.write(b) + return super().write(b) + + +class StreamMixer: + """Mixes `` and `` streams. + + The result is available in the ``output`` attribute. + + .. versionadded:: 8.2 + """ + + def __init__(self) -> None: + self.output: io.BytesIO = io.BytesIO() + self.stdout: io.BytesIO = BytesIOCopy(copy_to=self.output) + self.stderr: io.BytesIO = BytesIOCopy(copy_to=self.output) + + +class _NamedTextIOWrapper(io.TextIOWrapper): + def __init__( + self, buffer: t.BinaryIO, name: str, mode: str, **kwargs: t.Any + ) -> None: + super().__init__(buffer, **kwargs) + self._name = name + self._mode = mode + + def close(self) -> None: + """ + The buffer this object contains belongs to some other object, so + prevent the default __del__ implementation from closing that buffer. + + .. versionadded:: 8.3.2 + """ + ... + + @property + def name(self) -> str: + return self._name + + @property + def mode(self) -> str: + return self._mode + + +def make_input_stream( + input: str | bytes | t.IO[t.Any] | None, charset: str +) -> t.BinaryIO: + # Is already an input stream. + if hasattr(input, "read"): + rv = _find_binary_reader(t.cast("t.IO[t.Any]", input)) + + if rv is not None: + return rv + + raise TypeError("Could not find binary reader for input stream.") + + if input is None: + input = b"" + elif isinstance(input, str): + input = input.encode(charset) + + return io.BytesIO(input) + + +class Result: + """Holds the captured result of an invoked CLI script. + + :param runner: The runner that created the result + :param stdout_bytes: The standard output as bytes. + :param stderr_bytes: The standard error as bytes. + :param output_bytes: A mix of ``stdout_bytes`` and ``stderr_bytes``, as the + user would see it in its terminal. + :param return_value: The value returned from the invoked command. + :param exit_code: The exit code as integer. + :param exception: The exception that happened if one did. + :param exc_info: Exception information (exception type, exception instance, + traceback type). + + .. versionchanged:: 8.2 + ``stderr_bytes`` no longer optional, ``output_bytes`` introduced and + ``mix_stderr`` has been removed. + + .. versionadded:: 8.0 + Added ``return_value``. + """ + + def __init__( + self, + runner: CliRunner, + stdout_bytes: bytes, + stderr_bytes: bytes, + output_bytes: bytes, + return_value: t.Any, + exit_code: int, + exception: BaseException | None, + exc_info: tuple[type[BaseException], BaseException, TracebackType] + | None = None, + ): + self.runner = runner + self.stdout_bytes = stdout_bytes + self.stderr_bytes = stderr_bytes + self.output_bytes = output_bytes + self.return_value = return_value + self.exit_code = exit_code + self.exception = exception + self.exc_info = exc_info + + @property + def output(self) -> str: + """The terminal output as unicode string, as the user would see it. + + .. versionchanged:: 8.2 + No longer a proxy for ``self.stdout``. Now has its own independent stream + that is mixing `` and ``, in the order they were written. + """ + return self.output_bytes.decode(self.runner.charset, "replace").replace( + "\r\n", "\n" + ) + + @property + def stdout(self) -> str: + """The standard output as unicode string.""" + return self.stdout_bytes.decode(self.runner.charset, "replace").replace( + "\r\n", "\n" + ) + + @property + def stderr(self) -> str: + """The standard error as unicode string. + + .. versionchanged:: 8.2 + No longer raise an exception, always returns the `` string. + """ + return self.stderr_bytes.decode(self.runner.charset, "replace").replace( + "\r\n", "\n" + ) + + def __repr__(self) -> str: + exc_str = repr(self.exception) if self.exception else "okay" + return f"<{type(self).__name__} {exc_str}>" + + +class CliRunner: + """The CLI runner provides functionality to invoke a Click command line + script for unittesting purposes in a isolated environment. This only + works in single-threaded systems without any concurrency as it changes the + global interpreter state. + + :param charset: the character set for the input and output data. + :param env: a dictionary with environment variables for overriding. + :param echo_stdin: if this is set to `True`, then reading from `` writes + to ``. This is useful for showing examples in + some circumstances. Note that regular prompts + will automatically echo the input. + :param catch_exceptions: Whether to catch any exceptions other than + ``SystemExit`` when running :meth:`~CliRunner.invoke`. + + .. versionchanged:: 8.2 + Added the ``catch_exceptions`` parameter. + + .. versionchanged:: 8.2 + ``mix_stderr`` parameter has been removed. + """ + + def __init__( + self, + charset: str = "utf-8", + env: cabc.Mapping[str, str | None] | None = None, + echo_stdin: bool = False, + catch_exceptions: bool = True, + ) -> None: + self.charset = charset + self.env: cabc.Mapping[str, str | None] = env or {} + self.echo_stdin = echo_stdin + self.catch_exceptions = catch_exceptions + + def get_default_prog_name(self, cli: Command) -> str: + """Given a command object it will return the default program name + for it. The default is the `name` attribute or ``"root"`` if not + set. + """ + return cli.name or "root" + + def make_env( + self, overrides: cabc.Mapping[str, str | None] | None = None + ) -> cabc.Mapping[str, str | None]: + """Returns the environment overrides for invoking a script.""" + rv = dict(self.env) + if overrides: + rv.update(overrides) + return rv + + @contextlib.contextmanager + def isolation( + self, + input: str | bytes | t.IO[t.Any] | None = None, + env: cabc.Mapping[str, str | None] | None = None, + color: bool = False, + ) -> cabc.Iterator[tuple[io.BytesIO, io.BytesIO, io.BytesIO]]: + """A context manager that sets up the isolation for invoking of a + command line tool. This sets up `` with the given input data + and `os.environ` with the overrides from the given dictionary. + This also rebinds some internals in Click to be mocked (like the + prompt functionality). + + This is automatically done in the :meth:`invoke` method. + + :param input: the input stream to put into `sys.stdin`. + :param env: the environment overrides as dictionary. + :param color: whether the output should contain color codes. The + application can still override this explicitly. + + .. versionadded:: 8.2 + An additional output stream is returned, which is a mix of + `` and `` streams. + + .. versionchanged:: 8.2 + Always returns the `` stream. + + .. versionchanged:: 8.0 + `` is opened with ``errors="backslashreplace"`` + instead of the default ``"strict"``. + + .. versionchanged:: 4.0 + Added the ``color`` parameter. + """ + bytes_input = make_input_stream(input, self.charset) + echo_input = None + + old_stdin = sys.stdin + old_stdout = sys.stdout + old_stderr = sys.stderr + old_forced_width = formatting.FORCED_WIDTH + formatting.FORCED_WIDTH = 80 + + env = self.make_env(env) + + stream_mixer = StreamMixer() + + if self.echo_stdin: + bytes_input = echo_input = t.cast( + t.BinaryIO, EchoingStdin(bytes_input, stream_mixer.stdout) + ) + + sys.stdin = text_input = _NamedTextIOWrapper( + bytes_input, encoding=self.charset, name="", mode="r" + ) + + if self.echo_stdin: + # Force unbuffered reads, otherwise TextIOWrapper reads a + # large chunk which is echoed early. + text_input._CHUNK_SIZE = 1 # type: ignore + + sys.stdout = _NamedTextIOWrapper( + stream_mixer.stdout, encoding=self.charset, name="", mode="w" + ) + + sys.stderr = _NamedTextIOWrapper( + stream_mixer.stderr, + encoding=self.charset, + name="", + mode="w", + errors="backslashreplace", + ) + + @_pause_echo(echo_input) # type: ignore + def visible_input(prompt: str | None = None) -> str: + sys.stdout.write(prompt or "") + try: + val = next(text_input).rstrip("\r\n") + except StopIteration as e: + raise EOFError() from e + sys.stdout.write(f"{val}\n") + sys.stdout.flush() + return val + + @_pause_echo(echo_input) # type: ignore + def hidden_input(prompt: str | None = None) -> str: + sys.stdout.write(f"{prompt or ''}\n") + sys.stdout.flush() + try: + return next(text_input).rstrip("\r\n") + except StopIteration as e: + raise EOFError() from e + + @_pause_echo(echo_input) # type: ignore + def _getchar(echo: bool) -> str: + char = sys.stdin.read(1) + + if echo: + sys.stdout.write(char) + + sys.stdout.flush() + return char + + default_color = color + + def should_strip_ansi( + stream: t.IO[t.Any] | None = None, color: bool | None = None + ) -> bool: + if color is None: + return not default_color + return not color + + old_visible_prompt_func = termui.visible_prompt_func + old_hidden_prompt_func = termui.hidden_prompt_func + old__getchar_func = termui._getchar + old_should_strip_ansi = utils.should_strip_ansi # type: ignore + old__compat_should_strip_ansi = _compat.should_strip_ansi + termui.visible_prompt_func = visible_input + termui.hidden_prompt_func = hidden_input + termui._getchar = _getchar + utils.should_strip_ansi = should_strip_ansi # type: ignore + _compat.should_strip_ansi = should_strip_ansi + + old_env = {} + try: + for key, value in env.items(): + old_env[key] = os.environ.get(key) + if value is None: + try: + del os.environ[key] + except Exception: + pass + else: + os.environ[key] = value + yield (stream_mixer.stdout, stream_mixer.stderr, stream_mixer.output) + finally: + for key, value in old_env.items(): + if value is None: + try: + del os.environ[key] + except Exception: + pass + else: + os.environ[key] = value + sys.stdout = old_stdout + sys.stderr = old_stderr + sys.stdin = old_stdin + termui.visible_prompt_func = old_visible_prompt_func + termui.hidden_prompt_func = old_hidden_prompt_func + termui._getchar = old__getchar_func + utils.should_strip_ansi = old_should_strip_ansi # type: ignore + _compat.should_strip_ansi = old__compat_should_strip_ansi + formatting.FORCED_WIDTH = old_forced_width + + def invoke( + self, + cli: Command, + args: str | cabc.Sequence[str] | None = None, + input: str | bytes | t.IO[t.Any] | None = None, + env: cabc.Mapping[str, str | None] | None = None, + catch_exceptions: bool | None = None, + color: bool = False, + **extra: t.Any, + ) -> Result: + """Invokes a command in an isolated environment. The arguments are + forwarded directly to the command line script, the `extra` keyword + arguments are passed to the :meth:`~clickpkg.Command.main` function of + the command. + + This returns a :class:`Result` object. + + :param cli: the command to invoke + :param args: the arguments to invoke. It may be given as an iterable + or a string. When given as string it will be interpreted + as a Unix shell command. More details at + :func:`shlex.split`. + :param input: the input data for `sys.stdin`. + :param env: the environment overrides. + :param catch_exceptions: Whether to catch any other exceptions than + ``SystemExit``. If :data:`None`, the value + from :class:`CliRunner` is used. + :param extra: the keyword arguments to pass to :meth:`main`. + :param color: whether the output should contain color codes. The + application can still override this explicitly. + + .. versionadded:: 8.2 + The result object has the ``output_bytes`` attribute with + the mix of ``stdout_bytes`` and ``stderr_bytes``, as the user would + see it in its terminal. + + .. versionchanged:: 8.2 + The result object always returns the ``stderr_bytes`` stream. + + .. versionchanged:: 8.0 + The result object has the ``return_value`` attribute with + the value returned from the invoked command. + + .. versionchanged:: 4.0 + Added the ``color`` parameter. + + .. versionchanged:: 3.0 + Added the ``catch_exceptions`` parameter. + + .. versionchanged:: 3.0 + The result object has the ``exc_info`` attribute with the + traceback if available. + """ + exc_info = None + if catch_exceptions is None: + catch_exceptions = self.catch_exceptions + + with self.isolation(input=input, env=env, color=color) as outstreams: + return_value = None + exception: BaseException | None = None + exit_code = 0 + + if isinstance(args, str): + args = shlex.split(args) + + try: + prog_name = extra.pop("prog_name") + except KeyError: + prog_name = self.get_default_prog_name(cli) + + try: + return_value = cli.main(args=args or (), prog_name=prog_name, **extra) + except SystemExit as e: + exc_info = sys.exc_info() + e_code = t.cast("int | t.Any | None", e.code) + + if e_code is None: + e_code = 0 + + if e_code != 0: + exception = e + + if not isinstance(e_code, int): + sys.stdout.write(str(e_code)) + sys.stdout.write("\n") + e_code = 1 + + exit_code = e_code + + except Exception as e: + if not catch_exceptions: + raise + exception = e + exit_code = 1 + exc_info = sys.exc_info() + finally: + sys.stdout.flush() + sys.stderr.flush() + stdout = outstreams[0].getvalue() + stderr = outstreams[1].getvalue() + output = outstreams[2].getvalue() + + return Result( + runner=self, + stdout_bytes=stdout, + stderr_bytes=stderr, + output_bytes=output, + return_value=return_value, + exit_code=exit_code, + exception=exception, + exc_info=exc_info, # type: ignore + ) + + @contextlib.contextmanager + def isolated_filesystem( + self, temp_dir: str | os.PathLike[str] | None = None + ) -> cabc.Iterator[str]: + """A context manager that creates a temporary directory and + changes the current working directory to it. This isolates tests + that affect the contents of the CWD to prevent them from + interfering with each other. + + :param temp_dir: Create the temporary directory under this + directory. If given, the created directory is not removed + when exiting. + + .. versionchanged:: 8.0 + Added the ``temp_dir`` parameter. + """ + cwd = os.getcwd() + dt = tempfile.mkdtemp(dir=temp_dir) + os.chdir(dt) + + try: + yield dt + finally: + os.chdir(cwd) + + if temp_dir is None: + import shutil + + try: + shutil.rmtree(dt) + except OSError: + pass diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/click/types.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/click/types.py new file mode 100644 index 000000000..e71c1c21e --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/click/types.py @@ -0,0 +1,1209 @@ +from __future__ import annotations + +import collections.abc as cabc +import enum +import os +import stat +import sys +import typing as t +from datetime import datetime +from gettext import gettext as _ +from gettext import ngettext + +from ._compat import _get_argv_encoding +from ._compat import open_stream +from .exceptions import BadParameter +from .utils import format_filename +from .utils import LazyFile +from .utils import safecall + +if t.TYPE_CHECKING: + import typing_extensions as te + + from .core import Context + from .core import Parameter + from .shell_completion import CompletionItem + +ParamTypeValue = t.TypeVar("ParamTypeValue") + + +class ParamType: + """Represents the type of a parameter. Validates and converts values + from the command line or Python into the correct type. + + To implement a custom type, subclass and implement at least the + following: + + - The :attr:`name` class attribute must be set. + - Calling an instance of the type with ``None`` must return + ``None``. This is already implemented by default. + - :meth:`convert` must convert string values to the correct type. + - :meth:`convert` must accept values that are already the correct + type. + - It must be able to convert a value if the ``ctx`` and ``param`` + arguments are ``None``. This can occur when converting prompt + input. + """ + + is_composite: t.ClassVar[bool] = False + arity: t.ClassVar[int] = 1 + + #: the descriptive name of this type + name: str + + #: if a list of this type is expected and the value is pulled from a + #: string environment variable, this is what splits it up. `None` + #: means any whitespace. For all parameters the general rule is that + #: whitespace splits them up. The exception are paths and files which + #: are split by ``os.path.pathsep`` by default (":" on Unix and ";" on + #: Windows). + envvar_list_splitter: t.ClassVar[str | None] = None + + def to_info_dict(self) -> dict[str, t.Any]: + """Gather information that could be useful for a tool generating + user-facing documentation. + + Use :meth:`click.Context.to_info_dict` to traverse the entire + CLI structure. + + .. versionadded:: 8.0 + """ + # The class name without the "ParamType" suffix. + param_type = type(self).__name__.partition("ParamType")[0] + param_type = param_type.partition("ParameterType")[0] + + # Custom subclasses might not remember to set a name. + if hasattr(self, "name"): + name = self.name + else: + name = param_type + + return {"param_type": param_type, "name": name} + + def __call__( + self, + value: t.Any, + param: Parameter | None = None, + ctx: Context | None = None, + ) -> t.Any: + if value is not None: + return self.convert(value, param, ctx) + + def get_metavar(self, param: Parameter, ctx: Context) -> str | None: + """Returns the metavar default for this param if it provides one.""" + + def get_missing_message(self, param: Parameter, ctx: Context | None) -> str | None: + """Optionally might return extra information about a missing + parameter. + + .. versionadded:: 2.0 + """ + + def convert( + self, value: t.Any, param: Parameter | None, ctx: Context | None + ) -> t.Any: + """Convert the value to the correct type. This is not called if + the value is ``None`` (the missing value). + + This must accept string values from the command line, as well as + values that are already the correct type. It may also convert + other compatible types. + + The ``param`` and ``ctx`` arguments may be ``None`` in certain + situations, such as when converting prompt input. + + If the value cannot be converted, call :meth:`fail` with a + descriptive message. + + :param value: The value to convert. + :param param: The parameter that is using this type to convert + its value. May be ``None``. + :param ctx: The current context that arrived at this value. May + be ``None``. + """ + return value + + def split_envvar_value(self, rv: str) -> cabc.Sequence[str]: + """Given a value from an environment variable this splits it up + into small chunks depending on the defined envvar list splitter. + + If the splitter is set to `None`, which means that whitespace splits, + then leading and trailing whitespace is ignored. Otherwise, leading + and trailing splitters usually lead to empty items being included. + """ + return (rv or "").split(self.envvar_list_splitter) + + def fail( + self, + message: str, + param: Parameter | None = None, + ctx: Context | None = None, + ) -> t.NoReturn: + """Helper method to fail with an invalid value message.""" + raise BadParameter(message, ctx=ctx, param=param) + + def shell_complete( + self, ctx: Context, param: Parameter, incomplete: str + ) -> list[CompletionItem]: + """Return a list of + :class:`~click.shell_completion.CompletionItem` objects for the + incomplete value. Most types do not provide completions, but + some do, and this allows custom types to provide custom + completions as well. + + :param ctx: Invocation context for this command. + :param param: The parameter that is requesting completion. + :param incomplete: Value being completed. May be empty. + + .. versionadded:: 8.0 + """ + return [] + + +class CompositeParamType(ParamType): + is_composite = True + + @property + def arity(self) -> int: # type: ignore + raise NotImplementedError() + + +class FuncParamType(ParamType): + def __init__(self, func: t.Callable[[t.Any], t.Any]) -> None: + self.name: str = func.__name__ + self.func = func + + def to_info_dict(self) -> dict[str, t.Any]: + info_dict = super().to_info_dict() + info_dict["func"] = self.func + return info_dict + + def convert( + self, value: t.Any, param: Parameter | None, ctx: Context | None + ) -> t.Any: + try: + return self.func(value) + except ValueError: + try: + value = str(value) + except UnicodeError: + value = value.decode("utf-8", "replace") + + self.fail(value, param, ctx) + + +class UnprocessedParamType(ParamType): + name = "text" + + def convert( + self, value: t.Any, param: Parameter | None, ctx: Context | None + ) -> t.Any: + return value + + def __repr__(self) -> str: + return "UNPROCESSED" + + +class StringParamType(ParamType): + name = "text" + + def convert( + self, value: t.Any, param: Parameter | None, ctx: Context | None + ) -> t.Any: + if isinstance(value, bytes): + enc = _get_argv_encoding() + try: + value = value.decode(enc) + except UnicodeError: + fs_enc = sys.getfilesystemencoding() + if fs_enc != enc: + try: + value = value.decode(fs_enc) + except UnicodeError: + value = value.decode("utf-8", "replace") + else: + value = value.decode("utf-8", "replace") + return value + return str(value) + + def __repr__(self) -> str: + return "STRING" + + +class Choice(ParamType, t.Generic[ParamTypeValue]): + """The choice type allows a value to be checked against a fixed set + of supported values. + + You may pass any iterable value which will be converted to a tuple + and thus will only be iterated once. + + The resulting value will always be one of the originally passed choices. + See :meth:`normalize_choice` for more info on the mapping of strings + to choices. See :ref:`choice-opts` for an example. + + :param case_sensitive: Set to false to make choices case + insensitive. Defaults to true. + + .. versionchanged:: 8.2.0 + Non-``str`` ``choices`` are now supported. It can additionally be any + iterable. Before you were not recommended to pass anything but a list or + tuple. + + .. versionadded:: 8.2.0 + Choice normalization can be overridden via :meth:`normalize_choice`. + """ + + name = "choice" + + def __init__( + self, choices: cabc.Iterable[ParamTypeValue], case_sensitive: bool = True + ) -> None: + self.choices: cabc.Sequence[ParamTypeValue] = tuple(choices) + self.case_sensitive = case_sensitive + + def to_info_dict(self) -> dict[str, t.Any]: + info_dict = super().to_info_dict() + info_dict["choices"] = self.choices + info_dict["case_sensitive"] = self.case_sensitive + return info_dict + + def _normalized_mapping( + self, ctx: Context | None = None + ) -> cabc.Mapping[ParamTypeValue, str]: + """ + Returns mapping where keys are the original choices and the values are + the normalized values that are accepted via the command line. + + This is a simple wrapper around :meth:`normalize_choice`, use that + instead which is supported. + """ + return { + choice: self.normalize_choice( + choice=choice, + ctx=ctx, + ) + for choice in self.choices + } + + def normalize_choice(self, choice: ParamTypeValue, ctx: Context | None) -> str: + """ + Normalize a choice value, used to map a passed string to a choice. + Each choice must have a unique normalized value. + + By default uses :meth:`Context.token_normalize_func` and if not case + sensitive, convert it to a casefolded value. + + .. versionadded:: 8.2.0 + """ + normed_value = choice.name if isinstance(choice, enum.Enum) else str(choice) + + if ctx is not None and ctx.token_normalize_func is not None: + normed_value = ctx.token_normalize_func(normed_value) + + if not self.case_sensitive: + normed_value = normed_value.casefold() + + return normed_value + + def get_metavar(self, param: Parameter, ctx: Context) -> str | None: + if param.param_type_name == "option" and not param.show_choices: # type: ignore + choice_metavars = [ + convert_type(type(choice)).name.upper() for choice in self.choices + ] + choices_str = "|".join([*dict.fromkeys(choice_metavars)]) + else: + choices_str = "|".join( + [str(i) for i in self._normalized_mapping(ctx=ctx).values()] + ) + + # Use curly braces to indicate a required argument. + if param.required and param.param_type_name == "argument": + return f"{{{choices_str}}}" + + # Use square braces to indicate an option or optional argument. + return f"[{choices_str}]" + + def get_missing_message(self, param: Parameter, ctx: Context | None) -> str: + """ + Message shown when no choice is passed. + + .. versionchanged:: 8.2.0 Added ``ctx`` argument. + """ + return _("Choose from:\n\t{choices}").format( + choices=",\n\t".join(self._normalized_mapping(ctx=ctx).values()) + ) + + def convert( + self, value: t.Any, param: Parameter | None, ctx: Context | None + ) -> ParamTypeValue: + """ + For a given value from the parser, normalize it and find its + matching normalized value in the list of choices. Then return the + matched "original" choice. + """ + normed_value = self.normalize_choice(choice=value, ctx=ctx) + normalized_mapping = self._normalized_mapping(ctx=ctx) + + try: + return next( + original + for original, normalized in normalized_mapping.items() + if normalized == normed_value + ) + except StopIteration: + self.fail( + self.get_invalid_choice_message(value=value, ctx=ctx), + param=param, + ctx=ctx, + ) + + def get_invalid_choice_message(self, value: t.Any, ctx: Context | None) -> str: + """Get the error message when the given choice is invalid. + + :param value: The invalid value. + + .. versionadded:: 8.2 + """ + choices_str = ", ".join(map(repr, self._normalized_mapping(ctx=ctx).values())) + return ngettext( + "{value!r} is not {choice}.", + "{value!r} is not one of {choices}.", + len(self.choices), + ).format(value=value, choice=choices_str, choices=choices_str) + + def __repr__(self) -> str: + return f"Choice({list(self.choices)})" + + def shell_complete( + self, ctx: Context, param: Parameter, incomplete: str + ) -> list[CompletionItem]: + """Complete choices that start with the incomplete value. + + :param ctx: Invocation context for this command. + :param param: The parameter that is requesting completion. + :param incomplete: Value being completed. May be empty. + + .. versionadded:: 8.0 + """ + from click.shell_completion import CompletionItem + + str_choices = map(str, self.choices) + + if self.case_sensitive: + matched = (c for c in str_choices if c.startswith(incomplete)) + else: + incomplete = incomplete.lower() + matched = (c for c in str_choices if c.lower().startswith(incomplete)) + + return [CompletionItem(c) for c in matched] + + +class DateTime(ParamType): + """The DateTime type converts date strings into `datetime` objects. + + The format strings which are checked are configurable, but default to some + common (non-timezone aware) ISO 8601 formats. + + When specifying *DateTime* formats, you should only pass a list or a tuple. + Other iterables, like generators, may lead to surprising results. + + The format strings are processed using ``datetime.strptime``, and this + consequently defines the format strings which are allowed. + + Parsing is tried using each format, in order, and the first format which + parses successfully is used. + + :param formats: A list or tuple of date format strings, in the order in + which they should be tried. Defaults to + ``'%Y-%m-%d'``, ``'%Y-%m-%dT%H:%M:%S'``, + ``'%Y-%m-%d %H:%M:%S'``. + """ + + name = "datetime" + + def __init__(self, formats: cabc.Sequence[str] | None = None): + self.formats: cabc.Sequence[str] = formats or [ + "%Y-%m-%d", + "%Y-%m-%dT%H:%M:%S", + "%Y-%m-%d %H:%M:%S", + ] + + def to_info_dict(self) -> dict[str, t.Any]: + info_dict = super().to_info_dict() + info_dict["formats"] = self.formats + return info_dict + + def get_metavar(self, param: Parameter, ctx: Context) -> str | None: + return f"[{'|'.join(self.formats)}]" + + def _try_to_convert_date(self, value: t.Any, format: str) -> datetime | None: + try: + return datetime.strptime(value, format) + except ValueError: + return None + + def convert( + self, value: t.Any, param: Parameter | None, ctx: Context | None + ) -> t.Any: + if isinstance(value, datetime): + return value + + for format in self.formats: + converted = self._try_to_convert_date(value, format) + + if converted is not None: + return converted + + formats_str = ", ".join(map(repr, self.formats)) + self.fail( + ngettext( + "{value!r} does not match the format {format}.", + "{value!r} does not match the formats {formats}.", + len(self.formats), + ).format(value=value, format=formats_str, formats=formats_str), + param, + ctx, + ) + + def __repr__(self) -> str: + return "DateTime" + + +class _NumberParamTypeBase(ParamType): + _number_class: t.ClassVar[type[t.Any]] + + def convert( + self, value: t.Any, param: Parameter | None, ctx: Context | None + ) -> t.Any: + try: + return self._number_class(value) + except ValueError: + self.fail( + _("{value!r} is not a valid {number_type}.").format( + value=value, number_type=self.name + ), + param, + ctx, + ) + + +class _NumberRangeBase(_NumberParamTypeBase): + def __init__( + self, + min: float | None = None, + max: float | None = None, + min_open: bool = False, + max_open: bool = False, + clamp: bool = False, + ) -> None: + self.min = min + self.max = max + self.min_open = min_open + self.max_open = max_open + self.clamp = clamp + + def to_info_dict(self) -> dict[str, t.Any]: + info_dict = super().to_info_dict() + info_dict.update( + min=self.min, + max=self.max, + min_open=self.min_open, + max_open=self.max_open, + clamp=self.clamp, + ) + return info_dict + + def convert( + self, value: t.Any, param: Parameter | None, ctx: Context | None + ) -> t.Any: + import operator + + rv = super().convert(value, param, ctx) + lt_min: bool = self.min is not None and ( + operator.le if self.min_open else operator.lt + )(rv, self.min) + gt_max: bool = self.max is not None and ( + operator.ge if self.max_open else operator.gt + )(rv, self.max) + + if self.clamp: + if lt_min: + return self._clamp(self.min, 1, self.min_open) # type: ignore + + if gt_max: + return self._clamp(self.max, -1, self.max_open) # type: ignore + + if lt_min or gt_max: + self.fail( + _("{value} is not in the range {range}.").format( + value=rv, range=self._describe_range() + ), + param, + ctx, + ) + + return rv + + def _clamp(self, bound: float, dir: t.Literal[1, -1], open: bool) -> float: + """Find the valid value to clamp to bound in the given + direction. + + :param bound: The boundary value. + :param dir: 1 or -1 indicating the direction to move. + :param open: If true, the range does not include the bound. + """ + raise NotImplementedError + + def _describe_range(self) -> str: + """Describe the range for use in help text.""" + if self.min is None: + op = "<" if self.max_open else "<=" + return f"x{op}{self.max}" + + if self.max is None: + op = ">" if self.min_open else ">=" + return f"x{op}{self.min}" + + lop = "<" if self.min_open else "<=" + rop = "<" if self.max_open else "<=" + return f"{self.min}{lop}x{rop}{self.max}" + + def __repr__(self) -> str: + clamp = " clamped" if self.clamp else "" + return f"<{type(self).__name__} {self._describe_range()}{clamp}>" + + +class IntParamType(_NumberParamTypeBase): + name = "integer" + _number_class = int + + def __repr__(self) -> str: + return "INT" + + +class IntRange(_NumberRangeBase, IntParamType): + """Restrict an :data:`click.INT` value to a range of accepted + values. See :ref:`ranges`. + + If ``min`` or ``max`` are not passed, any value is accepted in that + direction. If ``min_open`` or ``max_open`` are enabled, the + corresponding boundary is not included in the range. + + If ``clamp`` is enabled, a value outside the range is clamped to the + boundary instead of failing. + + .. versionchanged:: 8.0 + Added the ``min_open`` and ``max_open`` parameters. + """ + + name = "integer range" + + def _clamp( # type: ignore + self, bound: int, dir: t.Literal[1, -1], open: bool + ) -> int: + if not open: + return bound + + return bound + dir + + +class FloatParamType(_NumberParamTypeBase): + name = "float" + _number_class = float + + def __repr__(self) -> str: + return "FLOAT" + + +class FloatRange(_NumberRangeBase, FloatParamType): + """Restrict a :data:`click.FLOAT` value to a range of accepted + values. See :ref:`ranges`. + + If ``min`` or ``max`` are not passed, any value is accepted in that + direction. If ``min_open`` or ``max_open`` are enabled, the + corresponding boundary is not included in the range. + + If ``clamp`` is enabled, a value outside the range is clamped to the + boundary instead of failing. This is not supported if either + boundary is marked ``open``. + + .. versionchanged:: 8.0 + Added the ``min_open`` and ``max_open`` parameters. + """ + + name = "float range" + + def __init__( + self, + min: float | None = None, + max: float | None = None, + min_open: bool = False, + max_open: bool = False, + clamp: bool = False, + ) -> None: + super().__init__( + min=min, max=max, min_open=min_open, max_open=max_open, clamp=clamp + ) + + if (min_open or max_open) and clamp: + raise TypeError("Clamping is not supported for open bounds.") + + def _clamp(self, bound: float, dir: t.Literal[1, -1], open: bool) -> float: + if not open: + return bound + + # Could use math.nextafter here, but clamping an + # open float range doesn't seem to be particularly useful. It's + # left up to the user to write a callback to do it if needed. + raise RuntimeError("Clamping is not supported for open bounds.") + + +class BoolParamType(ParamType): + name = "boolean" + + bool_states: dict[str, bool] = { + "1": True, + "0": False, + "yes": True, + "no": False, + "true": True, + "false": False, + "on": True, + "off": False, + "t": True, + "f": False, + "y": True, + "n": False, + # Absence of value is considered False. + "": False, + } + """A mapping of string values to boolean states. + + Mapping is inspired by :py:attr:`configparser.ConfigParser.BOOLEAN_STATES` + and extends it. + + .. caution:: + String values are lower-cased, as the ``str_to_bool`` comparison function + below is case-insensitive. + + .. warning:: + The mapping is not exhaustive, and does not cover all possible boolean strings + representations. It will remains as it is to avoid endless bikeshedding. + + Future work my be considered to make this mapping user-configurable from public + API. + """ + + @staticmethod + def str_to_bool(value: str | bool) -> bool | None: + """Convert a string to a boolean value. + + If the value is already a boolean, it is returned as-is. If the value is a + string, it is stripped of whitespaces and lower-cased, then checked against + the known boolean states pre-defined in the `BoolParamType.bool_states` mapping + above. + + Returns `None` if the value does not match any known boolean state. + """ + if isinstance(value, bool): + return value + return BoolParamType.bool_states.get(value.strip().lower()) + + def convert( + self, value: t.Any, param: Parameter | None, ctx: Context | None + ) -> bool: + normalized = self.str_to_bool(value) + if normalized is None: + self.fail( + _( + "{value!r} is not a valid boolean. Recognized values: {states}" + ).format(value=value, states=", ".join(sorted(self.bool_states))), + param, + ctx, + ) + return normalized + + def __repr__(self) -> str: + return "BOOL" + + +class UUIDParameterType(ParamType): + name = "uuid" + + def convert( + self, value: t.Any, param: Parameter | None, ctx: Context | None + ) -> t.Any: + import uuid + + if isinstance(value, uuid.UUID): + return value + + value = value.strip() + + try: + return uuid.UUID(value) + except ValueError: + self.fail( + _("{value!r} is not a valid UUID.").format(value=value), param, ctx + ) + + def __repr__(self) -> str: + return "UUID" + + +class File(ParamType): + """Declares a parameter to be a file for reading or writing. The file + is automatically closed once the context tears down (after the command + finished working). + + Files can be opened for reading or writing. The special value ``-`` + indicates stdin or stdout depending on the mode. + + By default, the file is opened for reading text data, but it can also be + opened in binary mode or for writing. The encoding parameter can be used + to force a specific encoding. + + The `lazy` flag controls if the file should be opened immediately or upon + first IO. The default is to be non-lazy for standard input and output + streams as well as files opened for reading, `lazy` otherwise. When opening a + file lazily for reading, it is still opened temporarily for validation, but + will not be held open until first IO. lazy is mainly useful when opening + for writing to avoid creating the file until it is needed. + + Files can also be opened atomically in which case all writes go into a + separate file in the same folder and upon completion the file will + be moved over to the original location. This is useful if a file + regularly read by other users is modified. + + See :ref:`file-args` for more information. + + .. versionchanged:: 2.0 + Added the ``atomic`` parameter. + """ + + name = "filename" + envvar_list_splitter: t.ClassVar[str] = os.path.pathsep + + def __init__( + self, + mode: str = "r", + encoding: str | None = None, + errors: str | None = "strict", + lazy: bool | None = None, + atomic: bool = False, + ) -> None: + self.mode = mode + self.encoding = encoding + self.errors = errors + self.lazy = lazy + self.atomic = atomic + + def to_info_dict(self) -> dict[str, t.Any]: + info_dict = super().to_info_dict() + info_dict.update(mode=self.mode, encoding=self.encoding) + return info_dict + + def resolve_lazy_flag(self, value: str | os.PathLike[str]) -> bool: + if self.lazy is not None: + return self.lazy + if os.fspath(value) == "-": + return False + elif "w" in self.mode: + return True + return False + + def convert( + self, + value: str | os.PathLike[str] | t.IO[t.Any], + param: Parameter | None, + ctx: Context | None, + ) -> t.IO[t.Any]: + if _is_file_like(value): + return value + + value = t.cast("str | os.PathLike[str]", value) + + try: + lazy = self.resolve_lazy_flag(value) + + if lazy: + lf = LazyFile( + value, self.mode, self.encoding, self.errors, atomic=self.atomic + ) + + if ctx is not None: + ctx.call_on_close(lf.close_intelligently) + + return t.cast("t.IO[t.Any]", lf) + + f, should_close = open_stream( + value, self.mode, self.encoding, self.errors, atomic=self.atomic + ) + + # If a context is provided, we automatically close the file + # at the end of the context execution (or flush out). If a + # context does not exist, it's the caller's responsibility to + # properly close the file. This for instance happens when the + # type is used with prompts. + if ctx is not None: + if should_close: + ctx.call_on_close(safecall(f.close)) + else: + ctx.call_on_close(safecall(f.flush)) + + return f + except OSError as e: + self.fail(f"'{format_filename(value)}': {e.strerror}", param, ctx) + + def shell_complete( + self, ctx: Context, param: Parameter, incomplete: str + ) -> list[CompletionItem]: + """Return a special completion marker that tells the completion + system to use the shell to provide file path completions. + + :param ctx: Invocation context for this command. + :param param: The parameter that is requesting completion. + :param incomplete: Value being completed. May be empty. + + .. versionadded:: 8.0 + """ + from click.shell_completion import CompletionItem + + return [CompletionItem(incomplete, type="file")] + + +def _is_file_like(value: t.Any) -> te.TypeGuard[t.IO[t.Any]]: + return hasattr(value, "read") or hasattr(value, "write") + + +class Path(ParamType): + """The ``Path`` type is similar to the :class:`File` type, but + returns the filename instead of an open file. Various checks can be + enabled to validate the type of file and permissions. + + :param exists: The file or directory needs to exist for the value to + be valid. If this is not set to ``True``, and the file does not + exist, then all further checks are silently skipped. + :param file_okay: Allow a file as a value. + :param dir_okay: Allow a directory as a value. + :param readable: if true, a readable check is performed. + :param writable: if true, a writable check is performed. + :param executable: if true, an executable check is performed. + :param resolve_path: Make the value absolute and resolve any + symlinks. A ``~`` is not expanded, as this is supposed to be + done by the shell only. + :param allow_dash: Allow a single dash as a value, which indicates + a standard stream (but does not open it). Use + :func:`~click.open_file` to handle opening this value. + :param path_type: Convert the incoming path value to this type. If + ``None``, keep Python's default, which is ``str``. Useful to + convert to :class:`pathlib.Path`. + + .. versionchanged:: 8.1 + Added the ``executable`` parameter. + + .. versionchanged:: 8.0 + Allow passing ``path_type=pathlib.Path``. + + .. versionchanged:: 6.0 + Added the ``allow_dash`` parameter. + """ + + envvar_list_splitter: t.ClassVar[str] = os.path.pathsep + + def __init__( + self, + exists: bool = False, + file_okay: bool = True, + dir_okay: bool = True, + writable: bool = False, + readable: bool = True, + resolve_path: bool = False, + allow_dash: bool = False, + path_type: type[t.Any] | None = None, + executable: bool = False, + ): + self.exists = exists + self.file_okay = file_okay + self.dir_okay = dir_okay + self.readable = readable + self.writable = writable + self.executable = executable + self.resolve_path = resolve_path + self.allow_dash = allow_dash + self.type = path_type + + if self.file_okay and not self.dir_okay: + self.name: str = _("file") + elif self.dir_okay and not self.file_okay: + self.name = _("directory") + else: + self.name = _("path") + + def to_info_dict(self) -> dict[str, t.Any]: + info_dict = super().to_info_dict() + info_dict.update( + exists=self.exists, + file_okay=self.file_okay, + dir_okay=self.dir_okay, + writable=self.writable, + readable=self.readable, + allow_dash=self.allow_dash, + ) + return info_dict + + def coerce_path_result( + self, value: str | os.PathLike[str] + ) -> str | bytes | os.PathLike[str]: + if self.type is not None and not isinstance(value, self.type): + if self.type is str: + return os.fsdecode(value) + elif self.type is bytes: + return os.fsencode(value) + else: + return t.cast("os.PathLike[str]", self.type(value)) + + return value + + def convert( + self, + value: str | os.PathLike[str], + param: Parameter | None, + ctx: Context | None, + ) -> str | bytes | os.PathLike[str]: + rv = value + + is_dash = self.file_okay and self.allow_dash and rv in (b"-", "-") + + if not is_dash: + if self.resolve_path: + rv = os.path.realpath(rv) + + try: + st = os.stat(rv) + except OSError: + if not self.exists: + return self.coerce_path_result(rv) + self.fail( + _("{name} {filename!r} does not exist.").format( + name=self.name.title(), filename=format_filename(value) + ), + param, + ctx, + ) + + if not self.file_okay and stat.S_ISREG(st.st_mode): + self.fail( + _("{name} {filename!r} is a file.").format( + name=self.name.title(), filename=format_filename(value) + ), + param, + ctx, + ) + if not self.dir_okay and stat.S_ISDIR(st.st_mode): + self.fail( + _("{name} {filename!r} is a directory.").format( + name=self.name.title(), filename=format_filename(value) + ), + param, + ctx, + ) + + if self.readable and not os.access(rv, os.R_OK): + self.fail( + _("{name} {filename!r} is not readable.").format( + name=self.name.title(), filename=format_filename(value) + ), + param, + ctx, + ) + + if self.writable and not os.access(rv, os.W_OK): + self.fail( + _("{name} {filename!r} is not writable.").format( + name=self.name.title(), filename=format_filename(value) + ), + param, + ctx, + ) + + if self.executable and not os.access(value, os.X_OK): + self.fail( + _("{name} {filename!r} is not executable.").format( + name=self.name.title(), filename=format_filename(value) + ), + param, + ctx, + ) + + return self.coerce_path_result(rv) + + def shell_complete( + self, ctx: Context, param: Parameter, incomplete: str + ) -> list[CompletionItem]: + """Return a special completion marker that tells the completion + system to use the shell to provide path completions for only + directories or any paths. + + :param ctx: Invocation context for this command. + :param param: The parameter that is requesting completion. + :param incomplete: Value being completed. May be empty. + + .. versionadded:: 8.0 + """ + from click.shell_completion import CompletionItem + + type = "dir" if self.dir_okay and not self.file_okay else "file" + return [CompletionItem(incomplete, type=type)] + + +class Tuple(CompositeParamType): + """The default behavior of Click is to apply a type on a value directly. + This works well in most cases, except for when `nargs` is set to a fixed + count and different types should be used for different items. In this + case the :class:`Tuple` type can be used. This type can only be used + if `nargs` is set to a fixed number. + + For more information see :ref:`tuple-type`. + + This can be selected by using a Python tuple literal as a type. + + :param types: a list of types that should be used for the tuple items. + """ + + def __init__(self, types: cabc.Sequence[type[t.Any] | ParamType]) -> None: + self.types: cabc.Sequence[ParamType] = [convert_type(ty) for ty in types] + + def to_info_dict(self) -> dict[str, t.Any]: + info_dict = super().to_info_dict() + info_dict["types"] = [t.to_info_dict() for t in self.types] + return info_dict + + @property + def name(self) -> str: # type: ignore + return f"<{' '.join(ty.name for ty in self.types)}>" + + @property + def arity(self) -> int: # type: ignore + return len(self.types) + + def convert( + self, value: t.Any, param: Parameter | None, ctx: Context | None + ) -> t.Any: + len_type = len(self.types) + len_value = len(value) + + if len_value != len_type: + self.fail( + ngettext( + "{len_type} values are required, but {len_value} was given.", + "{len_type} values are required, but {len_value} were given.", + len_value, + ).format(len_type=len_type, len_value=len_value), + param=param, + ctx=ctx, + ) + + return tuple( + ty(x, param, ctx) for ty, x in zip(self.types, value, strict=False) + ) + + +def convert_type(ty: t.Any | None, default: t.Any | None = None) -> ParamType: + """Find the most appropriate :class:`ParamType` for the given Python + type. If the type isn't provided, it can be inferred from a default + value. + """ + guessed_type = False + + if ty is None and default is not None: + if isinstance(default, (tuple, list)): + # If the default is empty, ty will remain None and will + # return STRING. + if default: + item = default[0] + + # A tuple of tuples needs to detect the inner types. + # Can't call convert recursively because that would + # incorrectly unwind the tuple to a single type. + if isinstance(item, (tuple, list)): + ty = tuple(map(type, item)) + else: + ty = type(item) + else: + ty = type(default) + + guessed_type = True + + if isinstance(ty, tuple): + return Tuple(ty) + + if isinstance(ty, ParamType): + return ty + + if ty is str or ty is None: + return STRING + + if ty is int: + return INT + + if ty is float: + return FLOAT + + if ty is bool: + return BOOL + + if guessed_type: + return STRING + + if __debug__: + try: + if issubclass(ty, ParamType): + raise AssertionError( + f"Attempted to use an uninstantiated parameter type ({ty})." + ) + except TypeError: + # ty is an instance (correct), so issubclass fails. + pass + + return FuncParamType(ty) + + +#: A dummy parameter type that just does nothing. From a user's +#: perspective this appears to just be the same as `STRING` but +#: internally no string conversion takes place if the input was bytes. +#: This is usually useful when working with file paths as they can +#: appear in bytes and unicode. +#: +#: For path related uses the :class:`Path` type is a better choice but +#: there are situations where an unprocessed type is useful which is why +#: it is is provided. +#: +#: .. versionadded:: 4.0 +UNPROCESSED = UnprocessedParamType() + +#: A unicode string parameter type which is the implicit default. This +#: can also be selected by using ``str`` as type. +STRING = StringParamType() + +#: An integer parameter. This can also be selected by using ``int`` as +#: type. +INT = IntParamType() + +#: A floating point value parameter. This can also be selected by using +#: ``float`` as type. +FLOAT = FloatParamType() + +#: A boolean parameter. This is the default for boolean flags. This can +#: also be selected by using ``bool`` as a type. +BOOL = BoolParamType() + +#: A UUID parameter. +UUID = UUIDParameterType() + + +class OptionHelpExtra(t.TypedDict, total=False): + envvars: tuple[str, ...] + default: str + range: str + required: str diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/click/utils.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/click/utils.py new file mode 100644 index 000000000..beae26f76 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/click/utils.py @@ -0,0 +1,627 @@ +from __future__ import annotations + +import collections.abc as cabc +import os +import re +import sys +import typing as t +from functools import update_wrapper +from types import ModuleType +from types import TracebackType + +from ._compat import _default_text_stderr +from ._compat import _default_text_stdout +from ._compat import _find_binary_writer +from ._compat import auto_wrap_for_ansi +from ._compat import binary_streams +from ._compat import open_stream +from ._compat import should_strip_ansi +from ._compat import strip_ansi +from ._compat import text_streams +from ._compat import WIN +from .globals import resolve_color_default + +if t.TYPE_CHECKING: + import typing_extensions as te + + P = te.ParamSpec("P") + +R = t.TypeVar("R") + + +def _posixify(name: str) -> str: + return "-".join(name.split()).lower() + + +def safecall(func: t.Callable[P, R]) -> t.Callable[P, R | None]: + """Wraps a function so that it swallows exceptions.""" + + def wrapper(*args: P.args, **kwargs: P.kwargs) -> R | None: + try: + return func(*args, **kwargs) + except Exception: + pass + return None + + return update_wrapper(wrapper, func) + + +def make_str(value: t.Any) -> str: + """Converts a value into a valid string.""" + if isinstance(value, bytes): + try: + return value.decode(sys.getfilesystemencoding()) + except UnicodeError: + return value.decode("utf-8", "replace") + return str(value) + + +def make_default_short_help(help: str, max_length: int = 45) -> str: + """Returns a condensed version of help string.""" + # Consider only the first paragraph. + paragraph_end = help.find("\n\n") + + if paragraph_end != -1: + help = help[:paragraph_end] + + # Collapse newlines, tabs, and spaces. + words = help.split() + + if not words: + return "" + + # The first paragraph started with a "no rewrap" marker, ignore it. + if words[0] == "\b": + words = words[1:] + + total_length = 0 + last_index = len(words) - 1 + + for i, word in enumerate(words): + total_length += len(word) + (i > 0) + + if total_length > max_length: # too long, truncate + break + + if word[-1] == ".": # sentence end, truncate without "..." + return " ".join(words[: i + 1]) + + if total_length == max_length and i != last_index: + break # not at sentence end, truncate with "..." + else: + return " ".join(words) # no truncation needed + + # Account for the length of the suffix. + total_length += len("...") + + # remove words until the length is short enough + while i > 0: + total_length -= len(words[i]) + (i > 0) + + if total_length <= max_length: + break + + i -= 1 + + return " ".join(words[:i]) + "..." + + +class LazyFile: + """A lazy file works like a regular file but it does not fully open + the file but it does perform some basic checks early to see if the + filename parameter does make sense. This is useful for safely opening + files for writing. + """ + + def __init__( + self, + filename: str | os.PathLike[str], + mode: str = "r", + encoding: str | None = None, + errors: str | None = "strict", + atomic: bool = False, + ): + self.name: str = os.fspath(filename) + self.mode = mode + self.encoding = encoding + self.errors = errors + self.atomic = atomic + self._f: t.IO[t.Any] | None + self.should_close: bool + + if self.name == "-": + self._f, self.should_close = open_stream(filename, mode, encoding, errors) + else: + if "r" in mode: + # Open and close the file in case we're opening it for + # reading so that we can catch at least some errors in + # some cases early. + open(filename, mode).close() + self._f = None + self.should_close = True + + def __getattr__(self, name: str) -> t.Any: + return getattr(self.open(), name) + + def __repr__(self) -> str: + if self._f is not None: + return repr(self._f) + return f"" + + def open(self) -> t.IO[t.Any]: + """Opens the file if it's not yet open. This call might fail with + a :exc:`FileError`. Not handling this error will produce an error + that Click shows. + """ + if self._f is not None: + return self._f + try: + rv, self.should_close = open_stream( + self.name, self.mode, self.encoding, self.errors, atomic=self.atomic + ) + except OSError as e: + from .exceptions import FileError + + raise FileError(self.name, hint=e.strerror) from e + self._f = rv + return rv + + def close(self) -> None: + """Closes the underlying file, no matter what.""" + if self._f is not None: + self._f.close() + + def close_intelligently(self) -> None: + """This function only closes the file if it was opened by the lazy + file wrapper. For instance this will never close stdin. + """ + if self.should_close: + self.close() + + def __enter__(self) -> LazyFile: + return self + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_value: BaseException | None, + tb: TracebackType | None, + ) -> None: + self.close_intelligently() + + def __iter__(self) -> cabc.Iterator[t.AnyStr]: + self.open() + return iter(self._f) # type: ignore + + +class KeepOpenFile: + def __init__(self, file: t.IO[t.Any]) -> None: + self._file: t.IO[t.Any] = file + + def __getattr__(self, name: str) -> t.Any: + return getattr(self._file, name) + + def __enter__(self) -> KeepOpenFile: + return self + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_value: BaseException | None, + tb: TracebackType | None, + ) -> None: + pass + + def __repr__(self) -> str: + return repr(self._file) + + def __iter__(self) -> cabc.Iterator[t.AnyStr]: + return iter(self._file) + + +def echo( + message: t.Any | None = None, + file: t.IO[t.Any] | None = None, + nl: bool = True, + err: bool = False, + color: bool | None = None, +) -> None: + """Print a message and newline to stdout or a file. This should be + used instead of :func:`print` because it provides better support + for different data, files, and environments. + + Compared to :func:`print`, this does the following: + + - Ensures that the output encoding is not misconfigured on Linux. + - Supports Unicode in the Windows console. + - Supports writing to binary outputs, and supports writing bytes + to text outputs. + - Supports colors and styles on Windows. + - Removes ANSI color and style codes if the output does not look + like an interactive terminal. + - Always flushes the output. + + :param message: The string or bytes to output. Other objects are + converted to strings. + :param file: The file to write to. Defaults to ``stdout``. + :param err: Write to ``stderr`` instead of ``stdout``. + :param nl: Print a newline after the message. Enabled by default. + :param color: Force showing or hiding colors and other styles. By + default Click will remove color if the output does not look like + an interactive terminal. + + .. versionchanged:: 6.0 + Support Unicode output on the Windows console. Click does not + modify ``sys.stdout``, so ``sys.stdout.write()`` and ``print()`` + will still not support Unicode. + + .. versionchanged:: 4.0 + Added the ``color`` parameter. + + .. versionadded:: 3.0 + Added the ``err`` parameter. + + .. versionchanged:: 2.0 + Support colors on Windows if colorama is installed. + """ + if file is None: + if err: + file = _default_text_stderr() + else: + file = _default_text_stdout() + + # There are no standard streams attached to write to. For example, + # pythonw on Windows. + if file is None: + return + + # Convert non bytes/text into the native string type. + if message is not None and not isinstance(message, (str, bytes, bytearray)): + out: str | bytes | bytearray | None = str(message) + else: + out = message + + if nl: + out = out or "" + if isinstance(out, str): + out += "\n" + else: + out += b"\n" + + if not out: + file.flush() + return + + # If there is a message and the value looks like bytes, we manually + # need to find the binary stream and write the message in there. + # This is done separately so that most stream types will work as you + # would expect. Eg: you can write to StringIO for other cases. + if isinstance(out, (bytes, bytearray)): + binary_file = _find_binary_writer(file) + + if binary_file is not None: + file.flush() + binary_file.write(out) + binary_file.flush() + return + + # ANSI style code support. For no message or bytes, nothing happens. + # When outputting to a file instead of a terminal, strip codes. + else: + color = resolve_color_default(color) + + if should_strip_ansi(file, color): + out = strip_ansi(out) + elif WIN: + if auto_wrap_for_ansi is not None: + file = auto_wrap_for_ansi(file, color) # type: ignore + elif not color: + out = strip_ansi(out) + + file.write(out) # type: ignore + file.flush() + + +def get_binary_stream(name: t.Literal["stdin", "stdout", "stderr"]) -> t.BinaryIO: + """Returns a system stream for byte processing. + + :param name: the name of the stream to open. Valid names are ``'stdin'``, + ``'stdout'`` and ``'stderr'`` + """ + opener = binary_streams.get(name) + if opener is None: + raise TypeError(f"Unknown standard stream '{name}'") + return opener() + + +def get_text_stream( + name: t.Literal["stdin", "stdout", "stderr"], + encoding: str | None = None, + errors: str | None = "strict", +) -> t.TextIO: + """Returns a system stream for text processing. This usually returns + a wrapped stream around a binary stream returned from + :func:`get_binary_stream` but it also can take shortcuts for already + correctly configured streams. + + :param name: the name of the stream to open. Valid names are ``'stdin'``, + ``'stdout'`` and ``'stderr'`` + :param encoding: overrides the detected default encoding. + :param errors: overrides the default error mode. + """ + opener = text_streams.get(name) + if opener is None: + raise TypeError(f"Unknown standard stream '{name}'") + return opener(encoding, errors) + + +def open_file( + filename: str | os.PathLike[str], + mode: str = "r", + encoding: str | None = None, + errors: str | None = "strict", + lazy: bool = False, + atomic: bool = False, +) -> t.IO[t.Any]: + """Open a file, with extra behavior to handle ``'-'`` to indicate + a standard stream, lazy open on write, and atomic write. Similar to + the behavior of the :class:`~click.File` param type. + + If ``'-'`` is given to open ``stdout`` or ``stdin``, the stream is + wrapped so that using it in a context manager will not close it. + This makes it possible to use the function without accidentally + closing a standard stream: + + .. code-block:: python + + with open_file(filename) as f: + ... + + :param filename: The name or Path of the file to open, or ``'-'`` for + ``stdin``/``stdout``. + :param mode: The mode in which to open the file. + :param encoding: The encoding to decode or encode a file opened in + text mode. + :param errors: The error handling mode. + :param lazy: Wait to open the file until it is accessed. For read + mode, the file is temporarily opened to raise access errors + early, then closed until it is read again. + :param atomic: Write to a temporary file and replace the given file + on close. + + .. versionadded:: 3.0 + """ + if lazy: + return t.cast( + "t.IO[t.Any]", LazyFile(filename, mode, encoding, errors, atomic=atomic) + ) + + f, should_close = open_stream(filename, mode, encoding, errors, atomic=atomic) + + if not should_close: + f = t.cast("t.IO[t.Any]", KeepOpenFile(f)) + + return f + + +def format_filename( + filename: str | bytes | os.PathLike[str] | os.PathLike[bytes], + shorten: bool = False, +) -> str: + """Format a filename as a string for display. Ensures the filename can be + displayed by replacing any invalid bytes or surrogate escapes in the name + with the replacement character ``�``. + + Invalid bytes or surrogate escapes will raise an error when written to a + stream with ``errors="strict"``. This will typically happen with ``stdout`` + when the locale is something like ``en_GB.UTF-8``. + + Many scenarios *are* safe to write surrogates though, due to PEP 538 and + PEP 540, including: + + - Writing to ``stderr``, which uses ``errors="backslashreplace"``. + - The system has ``LANG=C.UTF-8``, ``C``, or ``POSIX``. Python opens + stdout and stderr with ``errors="surrogateescape"``. + - None of ``LANG/LC_*`` are set. Python assumes ``LANG=C.UTF-8``. + - Python is started in UTF-8 mode with ``PYTHONUTF8=1`` or ``-X utf8``. + Python opens stdout and stderr with ``errors="surrogateescape"``. + + :param filename: formats a filename for UI display. This will also convert + the filename into unicode without failing. + :param shorten: this optionally shortens the filename to strip of the + path that leads up to it. + """ + if shorten: + filename = os.path.basename(filename) + else: + filename = os.fspath(filename) + + if isinstance(filename, bytes): + filename = filename.decode(sys.getfilesystemencoding(), "replace") + else: + filename = filename.encode("utf-8", "surrogateescape").decode( + "utf-8", "replace" + ) + + return filename + + +def get_app_dir(app_name: str, roaming: bool = True, force_posix: bool = False) -> str: + r"""Returns the config folder for the application. The default behavior + is to return whatever is most appropriate for the operating system. + + To give you an idea, for an app called ``"Foo Bar"``, something like + the following folders could be returned: + + Mac OS X: + ``~/Library/Application Support/Foo Bar`` + Mac OS X (POSIX): + ``~/.foo-bar`` + Unix: + ``~/.config/foo-bar`` + Unix (POSIX): + ``~/.foo-bar`` + Windows (roaming): + ``C:\Users\\AppData\Roaming\Foo Bar`` + Windows (not roaming): + ``C:\Users\\AppData\Local\Foo Bar`` + + .. versionadded:: 2.0 + + :param app_name: the application name. This should be properly capitalized + and can contain whitespace. + :param roaming: controls if the folder should be roaming or not on Windows. + Has no effect otherwise. + :param force_posix: if this is set to `True` then on any POSIX system the + folder will be stored in the home folder with a leading + dot instead of the XDG config home or darwin's + application support folder. + """ + if WIN: + key = "APPDATA" if roaming else "LOCALAPPDATA" + folder = os.environ.get(key) + if folder is None: + folder = os.path.expanduser("~") + return os.path.join(folder, app_name) + if force_posix: + return os.path.join(os.path.expanduser(f"~/.{_posixify(app_name)}")) + if sys.platform == "darwin": + return os.path.join( + os.path.expanduser("~/Library/Application Support"), app_name + ) + return os.path.join( + os.environ.get("XDG_CONFIG_HOME", os.path.expanduser("~/.config")), + _posixify(app_name), + ) + + +class PacifyFlushWrapper: + """This wrapper is used to catch and suppress BrokenPipeErrors resulting + from ``.flush()`` being called on broken pipe during the shutdown/final-GC + of the Python interpreter. Notably ``.flush()`` is always called on + ``sys.stdout`` and ``sys.stderr``. So as to have minimal impact on any + other cleanup code, and the case where the underlying file is not a broken + pipe, all calls and attributes are proxied. + """ + + def __init__(self, wrapped: t.IO[t.Any]) -> None: + self.wrapped = wrapped + + def flush(self) -> None: + try: + self.wrapped.flush() + except OSError as e: + import errno + + if e.errno != errno.EPIPE: + raise + + def __getattr__(self, attr: str) -> t.Any: + return getattr(self.wrapped, attr) + + +def _detect_program_name( + path: str | None = None, _main: ModuleType | None = None +) -> str: + """Determine the command used to run the program, for use in help + text. If a file or entry point was executed, the file name is + returned. If ``python -m`` was used to execute a module or package, + ``python -m name`` is returned. + + This doesn't try to be too precise, the goal is to give a concise + name for help text. Files are only shown as their name without the + path. ``python`` is only shown for modules, and the full path to + ``sys.executable`` is not shown. + + :param path: The Python file being executed. Python puts this in + ``sys.argv[0]``, which is used by default. + :param _main: The ``__main__`` module. This should only be passed + during internal testing. + + .. versionadded:: 8.0 + Based on command args detection in the Werkzeug reloader. + + :meta private: + """ + if _main is None: + _main = sys.modules["__main__"] + + if not path: + path = sys.argv[0] + + # The value of __package__ indicates how Python was called. It may + # not exist if a setuptools script is installed as an egg. It may be + # set incorrectly for entry points created with pip on Windows. + # It is set to "" inside a Shiv or PEX zipapp. + if getattr(_main, "__package__", None) in {None, ""} or ( + os.name == "nt" + and _main.__package__ == "" + and not os.path.exists(path) + and os.path.exists(f"{path}.exe") + ): + # Executed a file, like "python app.py". + return os.path.basename(path) + + # Executed a module, like "python -m example". + # Rewritten by Python from "-m script" to "/path/to/script.py". + # Need to look at main module to determine how it was executed. + py_module = t.cast(str, _main.__package__) + name = os.path.splitext(os.path.basename(path))[0] + + # A submodule like "example.cli". + if name != "__main__": + py_module = f"{py_module}.{name}" + + return f"python -m {py_module.lstrip('.')}" + + +def _expand_args( + args: cabc.Iterable[str], + *, + user: bool = True, + env: bool = True, + glob_recursive: bool = True, +) -> list[str]: + """Simulate Unix shell expansion with Python functions. + + See :func:`glob.glob`, :func:`os.path.expanduser`, and + :func:`os.path.expandvars`. + + This is intended for use on Windows, where the shell does not do any + expansion. It may not exactly match what a Unix shell would do. + + :param args: List of command line arguments to expand. + :param user: Expand user home directory. + :param env: Expand environment variables. + :param glob_recursive: ``**`` matches directories recursively. + + .. versionchanged:: 8.1 + Invalid glob patterns are treated as empty expansions rather + than raising an error. + + .. versionadded:: 8.0 + + :meta private: + """ + from glob import glob + + out = [] + + for arg in args: + if user: + arg = os.path.expanduser(arg) + + if env: + arg = os.path.expandvars(arg) + + try: + matches = glob(arg, recursive=glob_recursive) + except re.error: + matches = [] + + if not matches: + out.append(arg) + else: + out.extend(matches) + + return out diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/__init__.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/__init__.py new file mode 100644 index 000000000..d30fd742a --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/__init__.py @@ -0,0 +1,72 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +# Copyright (C) 2003-2007, 2009, 2011 Nominum, Inc. +# +# Permission to use, copy, modify, and distribute this software and its +# documentation for any purpose with or without fee is hereby granted, +# provided that the above copyright notice and this permission notice +# appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +"""dnspython DNS toolkit""" + +__all__ = [ + "asyncbackend", + "asyncquery", + "asyncresolver", + "btree", + "btreezone", + "dnssec", + "dnssecalgs", + "dnssectypes", + "e164", + "edns", + "entropy", + "exception", + "flags", + "immutable", + "inet", + "ipv4", + "ipv6", + "message", + "name", + "namedict", + "node", + "opcode", + "query", + "quic", + "rcode", + "rdata", + "rdataclass", + "rdataset", + "rdatatype", + "renderer", + "resolver", + "reversename", + "rrset", + "serial", + "set", + "tokenizer", + "transaction", + "tsig", + "tsigkeyring", + "ttl", + "rdtypes", + "update", + "version", + "versioned", + "wire", + "xfr", + "zone", + "zonetypes", + "zonefile", +] + +from dns.version import version as __version__ # noqa diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/_asyncbackend.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/_asyncbackend.py new file mode 100644 index 000000000..23455db37 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/_asyncbackend.py @@ -0,0 +1,100 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +# This is a nullcontext for both sync and async. 3.7 has a nullcontext, +# but it is only for sync use. + + +class NullContext: + def __init__(self, enter_result=None): + self.enter_result = enter_result + + def __enter__(self): + return self.enter_result + + def __exit__(self, exc_type, exc_value, traceback): + pass + + async def __aenter__(self): + return self.enter_result + + async def __aexit__(self, exc_type, exc_value, traceback): + pass + + +# These are declared here so backends can import them without creating +# circular dependencies with dns.asyncbackend. + + +class Socket: # pragma: no cover + def __init__(self, family: int, type: int): + self.family = family + self.type = type + + async def close(self): + pass + + async def getpeername(self): + raise NotImplementedError + + async def getsockname(self): + raise NotImplementedError + + async def getpeercert(self, timeout): + raise NotImplementedError + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc_value, traceback): + await self.close() + + +class DatagramSocket(Socket): # pragma: no cover + async def sendto(self, what, destination, timeout): + raise NotImplementedError + + async def recvfrom(self, size, timeout): + raise NotImplementedError + + +class StreamSocket(Socket): # pragma: no cover + async def sendall(self, what, timeout): + raise NotImplementedError + + async def recv(self, size, timeout): + raise NotImplementedError + + +class NullTransport: + async def connect_tcp(self, host, port, timeout, local_address): + raise NotImplementedError + + +class Backend: # pragma: no cover + def name(self) -> str: + return "unknown" + + async def make_socket( + self, + af, + socktype, + proto=0, + source=None, + destination=None, + timeout=None, + ssl_context=None, + server_hostname=None, + ): + raise NotImplementedError + + def datagram_connection_required(self): + return False + + async def sleep(self, interval): + raise NotImplementedError + + def get_transport_class(self): + raise NotImplementedError + + async def wait_for(self, awaitable, timeout): + raise NotImplementedError diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/_asyncio_backend.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/_asyncio_backend.py new file mode 100644 index 000000000..303908ceb --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/_asyncio_backend.py @@ -0,0 +1,276 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +"""asyncio library query support""" + +import asyncio +import socket +import sys + +import dns._asyncbackend +import dns._features +import dns.exception +import dns.inet + +_is_win32 = sys.platform == "win32" + + +def _get_running_loop(): + try: + return asyncio.get_running_loop() + except AttributeError: # pragma: no cover + return asyncio.get_event_loop() + + +class _DatagramProtocol: + def __init__(self): + self.transport = None + self.recvfrom = None + + def connection_made(self, transport): + self.transport = transport + + def datagram_received(self, data, addr): + if self.recvfrom and not self.recvfrom.done(): + self.recvfrom.set_result((data, addr)) + + def error_received(self, exc): # pragma: no cover + if self.recvfrom and not self.recvfrom.done(): + self.recvfrom.set_exception(exc) + + def connection_lost(self, exc): + if self.recvfrom and not self.recvfrom.done(): + if exc is None: + # EOF we triggered. Is there a better way to do this? + try: + raise EOFError("EOF") + except EOFError as e: + self.recvfrom.set_exception(e) + else: + self.recvfrom.set_exception(exc) + + def close(self): + if self.transport is not None: + self.transport.close() + + +async def _maybe_wait_for(awaitable, timeout): + if timeout is not None: + try: + return await asyncio.wait_for(awaitable, timeout) + except asyncio.TimeoutError: + raise dns.exception.Timeout(timeout=timeout) + else: + return await awaitable + + +class DatagramSocket(dns._asyncbackend.DatagramSocket): + def __init__(self, family, transport, protocol): + super().__init__(family, socket.SOCK_DGRAM) + self.transport = transport + self.protocol = protocol + + async def sendto(self, what, destination, timeout): # pragma: no cover + # no timeout for asyncio sendto + self.transport.sendto(what, destination) + return len(what) + + async def recvfrom(self, size, timeout): + # ignore size as there's no way I know to tell protocol about it + done = _get_running_loop().create_future() + try: + assert self.protocol.recvfrom is None + self.protocol.recvfrom = done + await _maybe_wait_for(done, timeout) + return done.result() + finally: + self.protocol.recvfrom = None + + async def close(self): + self.protocol.close() + + async def getpeername(self): + return self.transport.get_extra_info("peername") + + async def getsockname(self): + return self.transport.get_extra_info("sockname") + + async def getpeercert(self, timeout): + raise NotImplementedError + + +class StreamSocket(dns._asyncbackend.StreamSocket): + def __init__(self, af, reader, writer): + super().__init__(af, socket.SOCK_STREAM) + self.reader = reader + self.writer = writer + + async def sendall(self, what, timeout): + self.writer.write(what) + return await _maybe_wait_for(self.writer.drain(), timeout) + + async def recv(self, size, timeout): + return await _maybe_wait_for(self.reader.read(size), timeout) + + async def close(self): + self.writer.close() + + async def getpeername(self): + return self.writer.get_extra_info("peername") + + async def getsockname(self): + return self.writer.get_extra_info("sockname") + + async def getpeercert(self, timeout): + return self.writer.get_extra_info("peercert") + + +if dns._features.have("doh"): + import anyio + import httpcore + import httpcore._backends.anyio + import httpx + + _CoreAsyncNetworkBackend = httpcore.AsyncNetworkBackend + _CoreAnyIOStream = httpcore._backends.anyio.AnyIOStream # pyright: ignore + + from dns.query import _compute_times, _expiration_for_this_attempt, _remaining + + class _NetworkBackend(_CoreAsyncNetworkBackend): + def __init__(self, resolver, local_port, bootstrap_address, family): + super().__init__() + self._local_port = local_port + self._resolver = resolver + self._bootstrap_address = bootstrap_address + self._family = family + if local_port != 0: + raise NotImplementedError( + "the asyncio transport for HTTPX cannot set the local port" + ) + + async def connect_tcp( + self, host, port, timeout=None, local_address=None, socket_options=None + ): # pylint: disable=signature-differs + addresses = [] + _, expiration = _compute_times(timeout) + if dns.inet.is_address(host): + addresses.append(host) + elif self._bootstrap_address is not None: + addresses.append(self._bootstrap_address) + else: + timeout = _remaining(expiration) + family = self._family + if local_address: + family = dns.inet.af_for_address(local_address) + answers = await self._resolver.resolve_name( + host, family=family, lifetime=timeout + ) + addresses = answers.addresses() + for address in addresses: + try: + attempt_expiration = _expiration_for_this_attempt(2.0, expiration) + timeout = _remaining(attempt_expiration) + with anyio.fail_after(timeout): + stream = await anyio.connect_tcp( + remote_host=address, + remote_port=port, + local_host=local_address, + ) + return _CoreAnyIOStream(stream) + except Exception: + pass + raise httpcore.ConnectError + + async def connect_unix_socket( + self, path, timeout=None, socket_options=None + ): # pylint: disable=signature-differs + raise NotImplementedError + + async def sleep(self, seconds): # pylint: disable=signature-differs + await anyio.sleep(seconds) + + class _HTTPTransport(httpx.AsyncHTTPTransport): + def __init__( + self, + *args, + local_port=0, + bootstrap_address=None, + resolver=None, + family=socket.AF_UNSPEC, + **kwargs, + ): + if resolver is None and bootstrap_address is None: + # pylint: disable=import-outside-toplevel,redefined-outer-name + import dns.asyncresolver + + resolver = dns.asyncresolver.Resolver() + super().__init__(*args, **kwargs) + self._pool._network_backend = _NetworkBackend( + resolver, local_port, bootstrap_address, family + ) + +else: + _HTTPTransport = dns._asyncbackend.NullTransport # type: ignore + + +class Backend(dns._asyncbackend.Backend): + def name(self): + return "asyncio" + + async def make_socket( + self, + af, + socktype, + proto=0, + source=None, + destination=None, + timeout=None, + ssl_context=None, + server_hostname=None, + ): + loop = _get_running_loop() + if socktype == socket.SOCK_DGRAM: + if _is_win32 and source is None: + # Win32 wants explicit binding before recvfrom(). This is the + # proper fix for [#637]. + source = (dns.inet.any_for_af(af), 0) + transport, protocol = await loop.create_datagram_endpoint( + _DatagramProtocol, # pyright: ignore + source, + family=af, + proto=proto, + remote_addr=destination, + ) + return DatagramSocket(af, transport, protocol) + elif socktype == socket.SOCK_STREAM: + if destination is None: + # This shouldn't happen, but we check to make code analysis software + # happier. + raise ValueError("destination required for stream sockets") + (r, w) = await _maybe_wait_for( + asyncio.open_connection( + destination[0], + destination[1], + ssl=ssl_context, + family=af, + proto=proto, + local_addr=source, + server_hostname=server_hostname, + ), + timeout, + ) + return StreamSocket(af, r, w) + raise NotImplementedError( + "unsupported socket " + f"type {socktype}" + ) # pragma: no cover + + async def sleep(self, interval): + await asyncio.sleep(interval) + + def datagram_connection_required(self): + return False + + def get_transport_class(self): + return _HTTPTransport + + async def wait_for(self, awaitable, timeout): + return await _maybe_wait_for(awaitable, timeout) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/_ddr.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/_ddr.py new file mode 100644 index 000000000..bf5c11eb6 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/_ddr.py @@ -0,0 +1,154 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license +# +# Support for Discovery of Designated Resolvers + +import socket +import time +from urllib.parse import urlparse + +import dns.asyncbackend +import dns.inet +import dns.name +import dns.nameserver +import dns.query +import dns.rdtypes.svcbbase + +# The special name of the local resolver when using DDR +_local_resolver_name = dns.name.from_text("_dns.resolver.arpa") + + +# +# Processing is split up into I/O independent and I/O dependent parts to +# make supporting sync and async versions easy. +# + + +class _SVCBInfo: + def __init__(self, bootstrap_address, port, hostname, nameservers): + self.bootstrap_address = bootstrap_address + self.port = port + self.hostname = hostname + self.nameservers = nameservers + + def ddr_check_certificate(self, cert): + """Verify that the _SVCBInfo's address is in the cert's subjectAltName (SAN)""" + for name, value in cert["subjectAltName"]: + if name == "IP Address" and value == self.bootstrap_address: + return True + return False + + def make_tls_context(self): + ssl = dns.query.ssl + ctx = ssl.create_default_context() + ctx.minimum_version = ssl.TLSVersion.TLSv1_2 + return ctx + + def ddr_tls_check_sync(self, lifetime): + ctx = self.make_tls_context() + expiration = time.time() + lifetime + with socket.create_connection( + (self.bootstrap_address, self.port), lifetime + ) as s: + with ctx.wrap_socket(s, server_hostname=self.hostname) as ts: + ts.settimeout(dns.query._remaining(expiration)) + ts.do_handshake() + cert = ts.getpeercert() + return self.ddr_check_certificate(cert) + + async def ddr_tls_check_async(self, lifetime, backend=None): + if backend is None: + backend = dns.asyncbackend.get_default_backend() + ctx = self.make_tls_context() + expiration = time.time() + lifetime + async with await backend.make_socket( + dns.inet.af_for_address(self.bootstrap_address), + socket.SOCK_STREAM, + 0, + None, + (self.bootstrap_address, self.port), + lifetime, + ctx, + self.hostname, + ) as ts: + cert = await ts.getpeercert(dns.query._remaining(expiration)) + return self.ddr_check_certificate(cert) + + +def _extract_nameservers_from_svcb(answer): + bootstrap_address = answer.nameserver + if not dns.inet.is_address(bootstrap_address): + return [] + infos = [] + for rr in answer.rrset.processing_order(): + nameservers = [] + param = rr.params.get(dns.rdtypes.svcbbase.ParamKey.ALPN) + if param is None: + continue + alpns = set(param.ids) + host = rr.target.to_text(omit_final_dot=True) + port = None + param = rr.params.get(dns.rdtypes.svcbbase.ParamKey.PORT) + if param is not None: + port = param.port + # For now we ignore address hints and address resolution and always use the + # bootstrap address + if b"h2" in alpns: + param = rr.params.get(dns.rdtypes.svcbbase.ParamKey.DOHPATH) + if param is None or not param.value.endswith(b"{?dns}"): + continue + path = param.value[:-6].decode() + if not path.startswith("/"): + path = "/" + path + if port is None: + port = 443 + url = f"https://{host}:{port}{path}" + # check the URL + try: + urlparse(url) + nameservers.append(dns.nameserver.DoHNameserver(url, bootstrap_address)) + except Exception: + # continue processing other ALPN types + pass + if b"dot" in alpns: + if port is None: + port = 853 + nameservers.append( + dns.nameserver.DoTNameserver(bootstrap_address, port, host) + ) + if b"doq" in alpns: + if port is None: + port = 853 + nameservers.append( + dns.nameserver.DoQNameserver(bootstrap_address, port, True, host) + ) + if len(nameservers) > 0: + infos.append(_SVCBInfo(bootstrap_address, port, host, nameservers)) + return infos + + +def _get_nameservers_sync(answer, lifetime): + """Return a list of TLS-validated resolver nameservers extracted from an SVCB + answer.""" + nameservers = [] + infos = _extract_nameservers_from_svcb(answer) + for info in infos: + try: + if info.ddr_tls_check_sync(lifetime): + nameservers.extend(info.nameservers) + except Exception: + pass + return nameservers + + +async def _get_nameservers_async(answer, lifetime): + """Return a list of TLS-validated resolver nameservers extracted from an SVCB + answer.""" + nameservers = [] + infos = _extract_nameservers_from_svcb(answer) + for info in infos: + try: + if await info.ddr_tls_check_async(lifetime): + nameservers.extend(info.nameservers) + except Exception: + pass + return nameservers diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/_features.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/_features.py new file mode 100644 index 000000000..65a9a2a35 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/_features.py @@ -0,0 +1,95 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +import importlib.metadata +import itertools +import string +from typing import Dict, List, Tuple + + +def _tuple_from_text(version: str) -> Tuple: + text_parts = version.split(".") + int_parts = [] + for text_part in text_parts: + digit_prefix = "".join( + itertools.takewhile(lambda x: x in string.digits, text_part) + ) + try: + int_parts.append(int(digit_prefix)) + except Exception: + break + return tuple(int_parts) + + +def _version_check( + requirement: str, +) -> bool: + """Is the requirement fulfilled? + + The requirement must be of the form + + package>=version + """ + package, minimum = requirement.split(">=") + try: + version = importlib.metadata.version(package) + # This shouldn't happen, but it apparently can. + if version is None: + return False + except Exception: + return False + t_version = _tuple_from_text(version) + t_minimum = _tuple_from_text(minimum) + if t_version < t_minimum: + return False + return True + + +_cache: Dict[str, bool] = {} + + +def have(feature: str) -> bool: + """Is *feature* available? + + This tests if all optional packages needed for the + feature are available and recent enough. + + Returns ``True`` if the feature is available, + and ``False`` if it is not or if metadata is + missing. + """ + value = _cache.get(feature) + if value is not None: + return value + requirements = _requirements.get(feature) + if requirements is None: + # we make a cache entry here for consistency not performance + _cache[feature] = False + return False + ok = True + for requirement in requirements: + if not _version_check(requirement): + ok = False + break + _cache[feature] = ok + return ok + + +def force(feature: str, enabled: bool) -> None: + """Force the status of *feature* to be *enabled*. + + This method is provided as a workaround for any cases + where importlib.metadata is ineffective, or for testing. + """ + _cache[feature] = enabled + + +_requirements: Dict[str, List[str]] = { + ### BEGIN generated requirements + "dnssec": ["cryptography>=45"], + "doh": ["httpcore>=1.0.0", "httpx>=0.28.0", "h2>=4.2.0"], + "doq": ["aioquic>=1.2.0"], + "idna": ["idna>=3.10"], + "trio": ["trio>=0.30"], + "wmi": ["wmi>=1.5.1"], + ### END generated requirements +} diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/_immutable_ctx.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/_immutable_ctx.py new file mode 100644 index 000000000..b3d72deef --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/_immutable_ctx.py @@ -0,0 +1,76 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +# This implementation of the immutable decorator requires python >= +# 3.7, and is significantly more storage efficient when making classes +# with slots immutable. It's also faster. + +import contextvars +import inspect + +_in__init__ = contextvars.ContextVar("_immutable_in__init__", default=False) + + +class _Immutable: + """Immutable mixin class""" + + # We set slots to the empty list to say "we don't have any attributes". + # We do this so that if we're mixed in with a class with __slots__, we + # don't cause a __dict__ to be added which would waste space. + + __slots__ = () + + def __setattr__(self, name, value): + if _in__init__.get() is not self: + raise TypeError("object doesn't support attribute assignment") + else: + super().__setattr__(name, value) + + def __delattr__(self, name): + if _in__init__.get() is not self: + raise TypeError("object doesn't support attribute assignment") + else: + super().__delattr__(name) + + +def _immutable_init(f): + def nf(*args, **kwargs): + previous = _in__init__.set(args[0]) + try: + # call the actual __init__ + f(*args, **kwargs) + finally: + _in__init__.reset(previous) + + nf.__signature__ = inspect.signature(f) # pyright: ignore + return nf + + +def immutable(cls): + if _Immutable in cls.__mro__: + # Some ancestor already has the mixin, so just make sure we keep + # following the __init__ protocol. + cls.__init__ = _immutable_init(cls.__init__) + if hasattr(cls, "__setstate__"): + cls.__setstate__ = _immutable_init(cls.__setstate__) + ncls = cls + else: + # Mixin the Immutable class and follow the __init__ protocol. + class ncls(_Immutable, cls): + # We have to do the __slots__ declaration here too! + __slots__ = () + + @_immutable_init + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + + if hasattr(cls, "__setstate__"): + + @_immutable_init + def __setstate__(self, *args, **kwargs): + super().__setstate__(*args, **kwargs) + + # make ncls have the same name and module as cls + ncls.__name__ = cls.__name__ + ncls.__qualname__ = cls.__qualname__ + ncls.__module__ = cls.__module__ + return ncls diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/_no_ssl.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/_no_ssl.py new file mode 100644 index 000000000..edb452de1 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/_no_ssl.py @@ -0,0 +1,61 @@ +import enum +from typing import Any + +CERT_NONE = 0 + + +class TLSVersion(enum.IntEnum): + TLSv1_2 = 12 + + +class WantReadException(Exception): + pass + + +class WantWriteException(Exception): + pass + + +class SSLWantReadError(Exception): + pass + + +class SSLWantWriteError(Exception): + pass + + +class SSLContext: + def __init__(self) -> None: + self.minimum_version: Any = TLSVersion.TLSv1_2 + self.check_hostname: bool = False + self.verify_mode: int = CERT_NONE + + def wrap_socket(self, *args, **kwargs) -> "SSLSocket": # type: ignore + raise Exception("no ssl support") # pylint: disable=broad-exception-raised + + def set_alpn_protocols(self, *args, **kwargs): # type: ignore + raise Exception("no ssl support") # pylint: disable=broad-exception-raised + + +class SSLSocket: + def pending(self) -> bool: + raise Exception("no ssl support") # pylint: disable=broad-exception-raised + + def do_handshake(self) -> None: + raise Exception("no ssl support") # pylint: disable=broad-exception-raised + + def settimeout(self, value: Any) -> None: + pass + + def getpeercert(self) -> Any: + raise Exception("no ssl support") # pylint: disable=broad-exception-raised + + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + return False + + +def create_default_context(*args, **kwargs) -> SSLContext: # type: ignore + raise Exception("no ssl support") # pylint: disable=broad-exception-raised diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/_tls_util.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/_tls_util.py new file mode 100644 index 000000000..10ddf7279 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/_tls_util.py @@ -0,0 +1,19 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +import os +from typing import Tuple + + +def convert_verify_to_cafile_and_capath( + verify: bool | str, +) -> Tuple[str | None, str | None]: + cafile: str | None = None + capath: str | None = None + if isinstance(verify, str): + if os.path.isfile(verify): + cafile = verify + elif os.path.isdir(verify): + capath = verify + else: + raise ValueError("invalid verify string") + return cafile, capath diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/_trio_backend.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/_trio_backend.py new file mode 100644 index 000000000..bde7e8bab --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/_trio_backend.py @@ -0,0 +1,255 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +"""trio async I/O library query support""" + +import socket + +import trio +import trio.socket # type: ignore + +import dns._asyncbackend +import dns._features +import dns.exception +import dns.inet + +if not dns._features.have("trio"): + raise ImportError("trio not found or too old") + + +def _maybe_timeout(timeout): + if timeout is not None: + return trio.move_on_after(timeout) + else: + return dns._asyncbackend.NullContext() + + +# for brevity +_lltuple = dns.inet.low_level_address_tuple + +# pylint: disable=redefined-outer-name + + +class DatagramSocket(dns._asyncbackend.DatagramSocket): + def __init__(self, sock): + super().__init__(sock.family, socket.SOCK_DGRAM) + self.socket = sock + + async def sendto(self, what, destination, timeout): + with _maybe_timeout(timeout): + if destination is None: + return await self.socket.send(what) + else: + return await self.socket.sendto(what, destination) + raise dns.exception.Timeout( + timeout=timeout + ) # pragma: no cover lgtm[py/unreachable-statement] + + async def recvfrom(self, size, timeout): + with _maybe_timeout(timeout): + return await self.socket.recvfrom(size) + raise dns.exception.Timeout(timeout=timeout) # lgtm[py/unreachable-statement] + + async def close(self): + self.socket.close() + + async def getpeername(self): + return self.socket.getpeername() + + async def getsockname(self): + return self.socket.getsockname() + + async def getpeercert(self, timeout): + raise NotImplementedError + + +class StreamSocket(dns._asyncbackend.StreamSocket): + def __init__(self, family, stream, tls=False): + super().__init__(family, socket.SOCK_STREAM) + self.stream = stream + self.tls = tls + + async def sendall(self, what, timeout): + with _maybe_timeout(timeout): + return await self.stream.send_all(what) + raise dns.exception.Timeout(timeout=timeout) # lgtm[py/unreachable-statement] + + async def recv(self, size, timeout): + with _maybe_timeout(timeout): + return await self.stream.receive_some(size) + raise dns.exception.Timeout(timeout=timeout) # lgtm[py/unreachable-statement] + + async def close(self): + await self.stream.aclose() + + async def getpeername(self): + if self.tls: + return self.stream.transport_stream.socket.getpeername() + else: + return self.stream.socket.getpeername() + + async def getsockname(self): + if self.tls: + return self.stream.transport_stream.socket.getsockname() + else: + return self.stream.socket.getsockname() + + async def getpeercert(self, timeout): + if self.tls: + with _maybe_timeout(timeout): + await self.stream.do_handshake() + return self.stream.getpeercert() + else: + raise NotImplementedError + + +if dns._features.have("doh"): + import httpcore + import httpcore._backends.trio + import httpx + + _CoreAsyncNetworkBackend = httpcore.AsyncNetworkBackend + _CoreTrioStream = httpcore._backends.trio.TrioStream + + from dns.query import _compute_times, _expiration_for_this_attempt, _remaining + + class _NetworkBackend(_CoreAsyncNetworkBackend): + def __init__(self, resolver, local_port, bootstrap_address, family): + super().__init__() + self._local_port = local_port + self._resolver = resolver + self._bootstrap_address = bootstrap_address + self._family = family + + async def connect_tcp( + self, host, port, timeout=None, local_address=None, socket_options=None + ): # pylint: disable=signature-differs + addresses = [] + _, expiration = _compute_times(timeout) + if dns.inet.is_address(host): + addresses.append(host) + elif self._bootstrap_address is not None: + addresses.append(self._bootstrap_address) + else: + timeout = _remaining(expiration) + family = self._family + if local_address: + family = dns.inet.af_for_address(local_address) + answers = await self._resolver.resolve_name( + host, family=family, lifetime=timeout + ) + addresses = answers.addresses() + for address in addresses: + try: + af = dns.inet.af_for_address(address) + if local_address is not None or self._local_port != 0: + source = (local_address, self._local_port) + else: + source = None + destination = (address, port) + attempt_expiration = _expiration_for_this_attempt(2.0, expiration) + timeout = _remaining(attempt_expiration) + sock = await Backend().make_socket( + af, socket.SOCK_STREAM, 0, source, destination, timeout + ) + assert isinstance(sock, StreamSocket) + return _CoreTrioStream(sock.stream) + except Exception: + continue + raise httpcore.ConnectError + + async def connect_unix_socket( + self, path, timeout=None, socket_options=None + ): # pylint: disable=signature-differs + raise NotImplementedError + + async def sleep(self, seconds): # pylint: disable=signature-differs + await trio.sleep(seconds) + + class _HTTPTransport(httpx.AsyncHTTPTransport): + def __init__( + self, + *args, + local_port=0, + bootstrap_address=None, + resolver=None, + family=socket.AF_UNSPEC, + **kwargs, + ): + if resolver is None and bootstrap_address is None: + # pylint: disable=import-outside-toplevel,redefined-outer-name + import dns.asyncresolver + + resolver = dns.asyncresolver.Resolver() + super().__init__(*args, **kwargs) + self._pool._network_backend = _NetworkBackend( + resolver, local_port, bootstrap_address, family + ) + +else: + _HTTPTransport = dns._asyncbackend.NullTransport # type: ignore + + +class Backend(dns._asyncbackend.Backend): + def name(self): + return "trio" + + async def make_socket( + self, + af, + socktype, + proto=0, + source=None, + destination=None, + timeout=None, + ssl_context=None, + server_hostname=None, + ): + s = trio.socket.socket(af, socktype, proto) + stream = None + try: + if source: + await s.bind(_lltuple(source, af)) + if socktype == socket.SOCK_STREAM or destination is not None: + connected = False + with _maybe_timeout(timeout): + assert destination is not None + await s.connect(_lltuple(destination, af)) + connected = True + if not connected: + raise dns.exception.Timeout( + timeout=timeout + ) # lgtm[py/unreachable-statement] + except Exception: # pragma: no cover + s.close() + raise + if socktype == socket.SOCK_DGRAM: + return DatagramSocket(s) + elif socktype == socket.SOCK_STREAM: + stream = trio.SocketStream(s) + tls = False + if ssl_context: + tls = True + try: + stream = trio.SSLStream( + stream, ssl_context, server_hostname=server_hostname + ) + except Exception: # pragma: no cover + await stream.aclose() + raise + return StreamSocket(af, stream, tls) + raise NotImplementedError( + "unsupported socket " + f"type {socktype}" + ) # pragma: no cover + + async def sleep(self, interval): + await trio.sleep(interval) + + def get_transport_class(self): + return _HTTPTransport + + async def wait_for(self, awaitable, timeout): + with _maybe_timeout(timeout): + return await awaitable + raise dns.exception.Timeout( + timeout=timeout + ) # pragma: no cover lgtm[py/unreachable-statement] diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/asyncbackend.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/asyncbackend.py new file mode 100644 index 000000000..0ec58b062 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/asyncbackend.py @@ -0,0 +1,101 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +from typing import Dict + +import dns.exception + +# pylint: disable=unused-import +from dns._asyncbackend import ( # noqa: F401 lgtm[py/unused-import] + Backend, + DatagramSocket, + Socket, + StreamSocket, +) + +# pylint: enable=unused-import + +_default_backend = None + +_backends: Dict[str, Backend] = {} + +# Allow sniffio import to be disabled for testing purposes +_no_sniffio = False + + +class AsyncLibraryNotFoundError(dns.exception.DNSException): + pass + + +def get_backend(name: str) -> Backend: + """Get the specified asynchronous backend. + + *name*, a ``str``, the name of the backend. Currently the "trio" + and "asyncio" backends are available. + + Raises NotImplementedError if an unknown backend name is specified. + """ + # pylint: disable=import-outside-toplevel,redefined-outer-name + backend = _backends.get(name) + if backend: + return backend + if name == "trio": + import dns._trio_backend + + backend = dns._trio_backend.Backend() + elif name == "asyncio": + import dns._asyncio_backend + + backend = dns._asyncio_backend.Backend() + else: + raise NotImplementedError(f"unimplemented async backend {name}") + _backends[name] = backend + return backend + + +def sniff() -> str: + """Attempt to determine the in-use asynchronous I/O library by using + the ``sniffio`` module if it is available. + + Returns the name of the library, or raises AsyncLibraryNotFoundError + if the library cannot be determined. + """ + # pylint: disable=import-outside-toplevel + try: + if _no_sniffio: + raise ImportError + import sniffio + + try: + return sniffio.current_async_library() + except sniffio.AsyncLibraryNotFoundError: + raise AsyncLibraryNotFoundError("sniffio cannot determine async library") + except ImportError: + import asyncio + + try: + asyncio.get_running_loop() + return "asyncio" + except RuntimeError: + raise AsyncLibraryNotFoundError("no async library detected") + + +def get_default_backend() -> Backend: + """Get the default backend, initializing it if necessary.""" + if _default_backend: + return _default_backend + + return set_default_backend(sniff()) + + +def set_default_backend(name: str) -> Backend: + """Set the default backend. + + It's not normally necessary to call this method, as + ``get_default_backend()`` will initialize the backend + appropriately in many cases. If ``sniffio`` is not installed, or + in testing situations, this function allows the backend to be set + explicitly. + """ + global _default_backend + _default_backend = get_backend(name) + return _default_backend diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/asyncquery.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/asyncquery.py new file mode 100644 index 000000000..bb7704582 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/asyncquery.py @@ -0,0 +1,953 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +# Copyright (C) 2003-2017 Nominum, Inc. +# +# Permission to use, copy, modify, and distribute this software and its +# documentation for any purpose with or without fee is hereby granted, +# provided that the above copyright notice and this permission notice +# appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +"""Talk to a DNS server.""" + +import base64 +import contextlib +import random +import socket +import struct +import time +import urllib.parse +from typing import Any, Dict, Optional, Tuple, cast + +import dns.asyncbackend +import dns.exception +import dns.inet +import dns.message +import dns.name +import dns.quic +import dns.rdatatype +import dns.transaction +import dns.tsig +import dns.xfr +from dns._asyncbackend import NullContext +from dns.query import ( + BadResponse, + HTTPVersion, + NoDOH, + NoDOQ, + UDPMode, + _check_status, + _compute_times, + _matches_destination, + _remaining, + have_doh, + make_ssl_context, +) + +try: + import ssl +except ImportError: + import dns._no_ssl as ssl # type: ignore + +if have_doh: + import httpx + +# for brevity +_lltuple = dns.inet.low_level_address_tuple + + +def _source_tuple(af, address, port): + # Make a high level source tuple, or return None if address and port + # are both None + if address or port: + if address is None: + if af == socket.AF_INET: + address = "0.0.0.0" + elif af == socket.AF_INET6: + address = "::" + else: + raise NotImplementedError(f"unknown address family {af}") + return (address, port) + else: + return None + + +def _timeout(expiration, now=None): + if expiration is not None: + if not now: + now = time.time() + return max(expiration - now, 0) + else: + return None + + +async def send_udp( + sock: dns.asyncbackend.DatagramSocket, + what: dns.message.Message | bytes, + destination: Any, + expiration: float | None = None, +) -> Tuple[int, float]: + """Send a DNS message to the specified UDP socket. + + *sock*, a ``dns.asyncbackend.DatagramSocket``. + + *what*, a ``bytes`` or ``dns.message.Message``, the message to send. + + *destination*, a destination tuple appropriate for the address family + of the socket, specifying where to send the query. + + *expiration*, a ``float`` or ``None``, the absolute time at which + a timeout exception should be raised. If ``None``, no timeout will + occur. The expiration value is meaningless for the asyncio backend, as + asyncio's transport sendto() never blocks. + + Returns an ``(int, float)`` tuple of bytes sent and the sent time. + """ + + if isinstance(what, dns.message.Message): + what = what.to_wire() + sent_time = time.time() + n = await sock.sendto(what, destination, _timeout(expiration, sent_time)) + return (n, sent_time) + + +async def receive_udp( + sock: dns.asyncbackend.DatagramSocket, + destination: Any | None = None, + expiration: float | None = None, + ignore_unexpected: bool = False, + one_rr_per_rrset: bool = False, + keyring: Dict[dns.name.Name, dns.tsig.Key] | None = None, + request_mac: bytes | None = b"", + ignore_trailing: bool = False, + raise_on_truncation: bool = False, + ignore_errors: bool = False, + query: dns.message.Message | None = None, +) -> Any: + """Read a DNS message from a UDP socket. + + *sock*, a ``dns.asyncbackend.DatagramSocket``. + + See :py:func:`dns.query.receive_udp()` for the documentation of the other + parameters, and exceptions. + + Returns a ``(dns.message.Message, float, tuple)`` tuple of the received message, the + received time, and the address where the message arrived from. + """ + + wire = b"" + while True: + (wire, from_address) = await sock.recvfrom(65535, _timeout(expiration)) + if not _matches_destination( + sock.family, from_address, destination, ignore_unexpected + ): + continue + received_time = time.time() + try: + r = dns.message.from_wire( + wire, + keyring=keyring, + request_mac=request_mac, + one_rr_per_rrset=one_rr_per_rrset, + ignore_trailing=ignore_trailing, + raise_on_truncation=raise_on_truncation, + ) + except dns.message.Truncated as e: + # See the comment in query.py for details. + if ( + ignore_errors + and query is not None + and not query.is_response(e.message()) + ): + continue + else: + raise + except Exception: + if ignore_errors: + continue + else: + raise + if ignore_errors and query is not None and not query.is_response(r): + continue + return (r, received_time, from_address) + + +async def udp( + q: dns.message.Message, + where: str, + timeout: float | None = None, + port: int = 53, + source: str | None = None, + source_port: int = 0, + ignore_unexpected: bool = False, + one_rr_per_rrset: bool = False, + ignore_trailing: bool = False, + raise_on_truncation: bool = False, + sock: dns.asyncbackend.DatagramSocket | None = None, + backend: dns.asyncbackend.Backend | None = None, + ignore_errors: bool = False, +) -> dns.message.Message: + """Return the response obtained after sending a query via UDP. + + *sock*, a ``dns.asyncbackend.DatagramSocket``, or ``None``, + the socket to use for the query. If ``None``, the default, a + socket is created. Note that if a socket is provided, the + *source*, *source_port*, and *backend* are ignored. + + *backend*, a ``dns.asyncbackend.Backend``, or ``None``. If ``None``, + the default, then dnspython will use the default backend. + + See :py:func:`dns.query.udp()` for the documentation of the other + parameters, exceptions, and return type of this method. + """ + wire = q.to_wire() + (begin_time, expiration) = _compute_times(timeout) + af = dns.inet.af_for_address(where) + destination = _lltuple((where, port), af) + if sock: + cm: contextlib.AbstractAsyncContextManager = NullContext(sock) + else: + if not backend: + backend = dns.asyncbackend.get_default_backend() + stuple = _source_tuple(af, source, source_port) + if backend.datagram_connection_required(): + dtuple = (where, port) + else: + dtuple = None + cm = await backend.make_socket(af, socket.SOCK_DGRAM, 0, stuple, dtuple) + async with cm as s: + await send_udp(s, wire, destination, expiration) # pyright: ignore + (r, received_time, _) = await receive_udp( + s, # pyright: ignore + destination, + expiration, + ignore_unexpected, + one_rr_per_rrset, + q.keyring, + q.mac, + ignore_trailing, + raise_on_truncation, + ignore_errors, + q, + ) + r.time = received_time - begin_time + # We don't need to check q.is_response() if we are in ignore_errors mode + # as receive_udp() will have checked it. + if not (ignore_errors or q.is_response(r)): + raise BadResponse + return r + + +async def udp_with_fallback( + q: dns.message.Message, + where: str, + timeout: float | None = None, + port: int = 53, + source: str | None = None, + source_port: int = 0, + ignore_unexpected: bool = False, + one_rr_per_rrset: bool = False, + ignore_trailing: bool = False, + udp_sock: dns.asyncbackend.DatagramSocket | None = None, + tcp_sock: dns.asyncbackend.StreamSocket | None = None, + backend: dns.asyncbackend.Backend | None = None, + ignore_errors: bool = False, +) -> Tuple[dns.message.Message, bool]: + """Return the response to the query, trying UDP first and falling back + to TCP if UDP results in a truncated response. + + *udp_sock*, a ``dns.asyncbackend.DatagramSocket``, or ``None``, + the socket to use for the UDP query. If ``None``, the default, a + socket is created. Note that if a socket is provided the *source*, + *source_port*, and *backend* are ignored for the UDP query. + + *tcp_sock*, a ``dns.asyncbackend.StreamSocket``, or ``None``, the + socket to use for the TCP query. If ``None``, the default, a + socket is created. Note that if a socket is provided *where*, + *source*, *source_port*, and *backend* are ignored for the TCP query. + + *backend*, a ``dns.asyncbackend.Backend``, or ``None``. If ``None``, + the default, then dnspython will use the default backend. + + See :py:func:`dns.query.udp_with_fallback()` for the documentation + of the other parameters, exceptions, and return type of this + method. + """ + try: + response = await udp( + q, + where, + timeout, + port, + source, + source_port, + ignore_unexpected, + one_rr_per_rrset, + ignore_trailing, + True, + udp_sock, + backend, + ignore_errors, + ) + return (response, False) + except dns.message.Truncated: + response = await tcp( + q, + where, + timeout, + port, + source, + source_port, + one_rr_per_rrset, + ignore_trailing, + tcp_sock, + backend, + ) + return (response, True) + + +async def send_tcp( + sock: dns.asyncbackend.StreamSocket, + what: dns.message.Message | bytes, + expiration: float | None = None, +) -> Tuple[int, float]: + """Send a DNS message to the specified TCP socket. + + *sock*, a ``dns.asyncbackend.StreamSocket``. + + See :py:func:`dns.query.send_tcp()` for the documentation of the other + parameters, exceptions, and return type of this method. + """ + + if isinstance(what, dns.message.Message): + tcpmsg = what.to_wire(prepend_length=True) + else: + # copying the wire into tcpmsg is inefficient, but lets us + # avoid writev() or doing a short write that would get pushed + # onto the net + tcpmsg = len(what).to_bytes(2, "big") + what + sent_time = time.time() + await sock.sendall(tcpmsg, _timeout(expiration, sent_time)) + return (len(tcpmsg), sent_time) + + +async def _read_exactly(sock, count, expiration): + """Read the specified number of bytes from stream. Keep trying until we + either get the desired amount, or we hit EOF. + """ + s = b"" + while count > 0: + n = await sock.recv(count, _timeout(expiration)) + if n == b"": + raise EOFError("EOF") + count = count - len(n) + s = s + n + return s + + +async def receive_tcp( + sock: dns.asyncbackend.StreamSocket, + expiration: float | None = None, + one_rr_per_rrset: bool = False, + keyring: Dict[dns.name.Name, dns.tsig.Key] | None = None, + request_mac: bytes | None = b"", + ignore_trailing: bool = False, +) -> Tuple[dns.message.Message, float]: + """Read a DNS message from a TCP socket. + + *sock*, a ``dns.asyncbackend.StreamSocket``. + + See :py:func:`dns.query.receive_tcp()` for the documentation of the other + parameters, exceptions, and return type of this method. + """ + + ldata = await _read_exactly(sock, 2, expiration) + (l,) = struct.unpack("!H", ldata) + wire = await _read_exactly(sock, l, expiration) + received_time = time.time() + r = dns.message.from_wire( + wire, + keyring=keyring, + request_mac=request_mac, + one_rr_per_rrset=one_rr_per_rrset, + ignore_trailing=ignore_trailing, + ) + return (r, received_time) + + +async def tcp( + q: dns.message.Message, + where: str, + timeout: float | None = None, + port: int = 53, + source: str | None = None, + source_port: int = 0, + one_rr_per_rrset: bool = False, + ignore_trailing: bool = False, + sock: dns.asyncbackend.StreamSocket | None = None, + backend: dns.asyncbackend.Backend | None = None, +) -> dns.message.Message: + """Return the response obtained after sending a query via TCP. + + *sock*, a ``dns.asyncbacket.StreamSocket``, or ``None``, the + socket to use for the query. If ``None``, the default, a socket + is created. Note that if a socket is provided + *where*, *port*, *source*, *source_port*, and *backend* are ignored. + + *backend*, a ``dns.asyncbackend.Backend``, or ``None``. If ``None``, + the default, then dnspython will use the default backend. + + See :py:func:`dns.query.tcp()` for the documentation of the other + parameters, exceptions, and return type of this method. + """ + + wire = q.to_wire() + (begin_time, expiration) = _compute_times(timeout) + if sock: + # Verify that the socket is connected, as if it's not connected, + # it's not writable, and the polling in send_tcp() will time out or + # hang forever. + await sock.getpeername() + cm: contextlib.AbstractAsyncContextManager = NullContext(sock) + else: + # These are simple (address, port) pairs, not family-dependent tuples + # you pass to low-level socket code. + af = dns.inet.af_for_address(where) + stuple = _source_tuple(af, source, source_port) + dtuple = (where, port) + if not backend: + backend = dns.asyncbackend.get_default_backend() + cm = await backend.make_socket( + af, socket.SOCK_STREAM, 0, stuple, dtuple, timeout + ) + async with cm as s: + await send_tcp(s, wire, expiration) # pyright: ignore + (r, received_time) = await receive_tcp( + s, # pyright: ignore + expiration, + one_rr_per_rrset, + q.keyring, + q.mac, + ignore_trailing, + ) + r.time = received_time - begin_time + if not q.is_response(r): + raise BadResponse + return r + + +async def tls( + q: dns.message.Message, + where: str, + timeout: float | None = None, + port: int = 853, + source: str | None = None, + source_port: int = 0, + one_rr_per_rrset: bool = False, + ignore_trailing: bool = False, + sock: dns.asyncbackend.StreamSocket | None = None, + backend: dns.asyncbackend.Backend | None = None, + ssl_context: ssl.SSLContext | None = None, + server_hostname: str | None = None, + verify: bool | str = True, +) -> dns.message.Message: + """Return the response obtained after sending a query via TLS. + + *sock*, an ``asyncbackend.StreamSocket``, or ``None``, the socket + to use for the query. If ``None``, the default, a socket is + created. Note that if a socket is provided, it must be a + connected SSL stream socket, and *where*, *port*, + *source*, *source_port*, *backend*, *ssl_context*, and *server_hostname* + are ignored. + + *backend*, a ``dns.asyncbackend.Backend``, or ``None``. If ``None``, + the default, then dnspython will use the default backend. + + See :py:func:`dns.query.tls()` for the documentation of the other + parameters, exceptions, and return type of this method. + """ + (begin_time, expiration) = _compute_times(timeout) + if sock: + cm: contextlib.AbstractAsyncContextManager = NullContext(sock) + else: + if ssl_context is None: + ssl_context = make_ssl_context(verify, server_hostname is not None, ["dot"]) + af = dns.inet.af_for_address(where) + stuple = _source_tuple(af, source, source_port) + dtuple = (where, port) + if not backend: + backend = dns.asyncbackend.get_default_backend() + cm = await backend.make_socket( + af, + socket.SOCK_STREAM, + 0, + stuple, + dtuple, + timeout, + ssl_context, + server_hostname, + ) + async with cm as s: + timeout = _timeout(expiration) + response = await tcp( + q, + where, + timeout, + port, + source, + source_port, + one_rr_per_rrset, + ignore_trailing, + s, + backend, + ) + end_time = time.time() + response.time = end_time - begin_time + return response + + +def _maybe_get_resolver( + resolver: Optional["dns.asyncresolver.Resolver"], # pyright: ignore +) -> "dns.asyncresolver.Resolver": # pyright: ignore + # We need a separate method for this to avoid overriding the global + # variable "dns" with the as-yet undefined local variable "dns" + # in https(). + if resolver is None: + # pylint: disable=import-outside-toplevel,redefined-outer-name + import dns.asyncresolver + + resolver = dns.asyncresolver.Resolver() + return resolver + + +async def https( + q: dns.message.Message, + where: str, + timeout: float | None = None, + port: int = 443, + source: str | None = None, + source_port: int = 0, # pylint: disable=W0613 + one_rr_per_rrset: bool = False, + ignore_trailing: bool = False, + client: Optional["httpx.AsyncClient|dns.quic.AsyncQuicConnection"] = None, + path: str = "/dns-query", + post: bool = True, + verify: bool | str | ssl.SSLContext = True, + bootstrap_address: str | None = None, + resolver: Optional["dns.asyncresolver.Resolver"] = None, # pyright: ignore + family: int = socket.AF_UNSPEC, + http_version: HTTPVersion = HTTPVersion.DEFAULT, +) -> dns.message.Message: + """Return the response obtained after sending a query via DNS-over-HTTPS. + + *client*, a ``httpx.AsyncClient``. If provided, the client to use for + the query. + + Unlike the other dnspython async functions, a backend cannot be provided + in this function because httpx always auto-detects the async backend. + + See :py:func:`dns.query.https()` for the documentation of the other + parameters, exceptions, and return type of this method. + """ + + try: + af = dns.inet.af_for_address(where) + except ValueError: + af = None + # we bind url and then override as pyright can't figure out all paths bind. + url = where + if af is not None and dns.inet.is_address(where): + if af == socket.AF_INET: + url = f"https://{where}:{port}{path}" + elif af == socket.AF_INET6: + url = f"https://[{where}]:{port}{path}" + + extensions = {} + if bootstrap_address is None: + # pylint: disable=possibly-used-before-assignment + parsed = urllib.parse.urlparse(url) + if parsed.hostname is None: + raise ValueError("no hostname in URL") + if dns.inet.is_address(parsed.hostname): + bootstrap_address = parsed.hostname + extensions["sni_hostname"] = parsed.hostname + if parsed.port is not None: + port = parsed.port + + if http_version == HTTPVersion.H3 or ( + http_version == HTTPVersion.DEFAULT and not have_doh + ): + if bootstrap_address is None: + resolver = _maybe_get_resolver(resolver) + assert parsed.hostname is not None # pyright: ignore + answers = await resolver.resolve_name( # pyright: ignore + parsed.hostname, family # pyright: ignore + ) + bootstrap_address = random.choice(list(answers.addresses())) + if client and not isinstance( + client, dns.quic.AsyncQuicConnection + ): # pyright: ignore + raise ValueError("client parameter must be a dns.quic.AsyncQuicConnection.") + assert client is None or isinstance(client, dns.quic.AsyncQuicConnection) + return await _http3( + q, + bootstrap_address, + url, + timeout, + port, + source, + source_port, + one_rr_per_rrset, + ignore_trailing, + verify=verify, + post=post, + connection=client, + ) + + if not have_doh: + raise NoDOH # pragma: no cover + # pylint: disable=possibly-used-before-assignment + if client and not isinstance(client, httpx.AsyncClient): # pyright: ignore + raise ValueError("client parameter must be an httpx.AsyncClient") + # pylint: enable=possibly-used-before-assignment + + wire = q.to_wire() + headers = {"accept": "application/dns-message"} + + h1 = http_version in (HTTPVersion.H1, HTTPVersion.DEFAULT) + h2 = http_version in (HTTPVersion.H2, HTTPVersion.DEFAULT) + + backend = dns.asyncbackend.get_default_backend() + + if source is None: + local_address = None + local_port = 0 + else: + local_address = source + local_port = source_port + + if client: + cm: contextlib.AbstractAsyncContextManager = NullContext(client) + else: + transport = backend.get_transport_class()( + local_address=local_address, + http1=h1, + http2=h2, + verify=verify, + local_port=local_port, + bootstrap_address=bootstrap_address, + resolver=resolver, + family=family, + ) + + cm = httpx.AsyncClient( # pyright: ignore + http1=h1, http2=h2, verify=verify, transport=transport # type: ignore + ) + + async with cm as the_client: + # see https://tools.ietf.org/html/rfc8484#section-4.1.1 for DoH + # GET and POST examples + if post: + headers.update( + { + "content-type": "application/dns-message", + "content-length": str(len(wire)), + } + ) + response = await backend.wait_for( + the_client.post( # pyright: ignore + url, + headers=headers, + content=wire, + extensions=extensions, + ), + timeout, + ) + else: + wire = base64.urlsafe_b64encode(wire).rstrip(b"=") + twire = wire.decode() # httpx does a repr() if we give it bytes + response = await backend.wait_for( + the_client.get( # pyright: ignore + url, + headers=headers, + params={"dns": twire}, + extensions=extensions, + ), + timeout, + ) + + # see https://tools.ietf.org/html/rfc8484#section-4.2.1 for info about DoH + # status codes + if response.status_code < 200 or response.status_code > 299: + raise ValueError( + f"{where} responded with status code {response.status_code}" + f"\nResponse body: {response.content!r}" + ) + r = dns.message.from_wire( + response.content, + keyring=q.keyring, + request_mac=q.request_mac, + one_rr_per_rrset=one_rr_per_rrset, + ignore_trailing=ignore_trailing, + ) + r.time = response.elapsed.total_seconds() + if not q.is_response(r): + raise BadResponse + return r + + +async def _http3( + q: dns.message.Message, + where: str, + url: str, + timeout: float | None = None, + port: int = 443, + source: str | None = None, + source_port: int = 0, + one_rr_per_rrset: bool = False, + ignore_trailing: bool = False, + verify: bool | str | ssl.SSLContext = True, + backend: dns.asyncbackend.Backend | None = None, + post: bool = True, + connection: dns.quic.AsyncQuicConnection | None = None, +) -> dns.message.Message: + if not dns.quic.have_quic: + raise NoDOH("DNS-over-HTTP3 is not available.") # pragma: no cover + + url_parts = urllib.parse.urlparse(url) + hostname = url_parts.hostname + assert hostname is not None + if url_parts.port is not None: + port = url_parts.port + + q.id = 0 + wire = q.to_wire() + the_connection: dns.quic.AsyncQuicConnection + if connection: + cfactory = dns.quic.null_factory + mfactory = dns.quic.null_factory + else: + (cfactory, mfactory) = dns.quic.factories_for_backend(backend) + + async with cfactory() as context: + async with mfactory( + context, verify_mode=verify, server_name=hostname, h3=True + ) as the_manager: + if connection: + the_connection = connection + else: + the_connection = the_manager.connect( # pyright: ignore + where, port, source, source_port + ) + (start, expiration) = _compute_times(timeout) + stream = await the_connection.make_stream(timeout) # pyright: ignore + async with stream: + # note that send_h3() does not need await + stream.send_h3(url, wire, post) + wire = await stream.receive(_remaining(expiration)) + _check_status(stream.headers(), where, wire) + finish = time.time() + r = dns.message.from_wire( + wire, + keyring=q.keyring, + request_mac=q.request_mac, + one_rr_per_rrset=one_rr_per_rrset, + ignore_trailing=ignore_trailing, + ) + r.time = max(finish - start, 0.0) + if not q.is_response(r): + raise BadResponse + return r + + +async def quic( + q: dns.message.Message, + where: str, + timeout: float | None = None, + port: int = 853, + source: str | None = None, + source_port: int = 0, + one_rr_per_rrset: bool = False, + ignore_trailing: bool = False, + connection: dns.quic.AsyncQuicConnection | None = None, + verify: bool | str = True, + backend: dns.asyncbackend.Backend | None = None, + hostname: str | None = None, + server_hostname: str | None = None, +) -> dns.message.Message: + """Return the response obtained after sending an asynchronous query via + DNS-over-QUIC. + + *backend*, a ``dns.asyncbackend.Backend``, or ``None``. If ``None``, + the default, then dnspython will use the default backend. + + See :py:func:`dns.query.quic()` for the documentation of the other + parameters, exceptions, and return type of this method. + """ + + if not dns.quic.have_quic: + raise NoDOQ("DNS-over-QUIC is not available.") # pragma: no cover + + if server_hostname is not None and hostname is None: + hostname = server_hostname + + q.id = 0 + wire = q.to_wire() + the_connection: dns.quic.AsyncQuicConnection + if connection: + cfactory = dns.quic.null_factory + mfactory = dns.quic.null_factory + the_connection = connection + else: + (cfactory, mfactory) = dns.quic.factories_for_backend(backend) + + async with cfactory() as context: + async with mfactory( + context, + verify_mode=verify, + server_name=server_hostname, + ) as the_manager: + if not connection: + the_connection = the_manager.connect( # pyright: ignore + where, port, source, source_port + ) + (start, expiration) = _compute_times(timeout) + stream = await the_connection.make_stream(timeout) # pyright: ignore + async with stream: + await stream.send(wire, True) + wire = await stream.receive(_remaining(expiration)) + finish = time.time() + r = dns.message.from_wire( + wire, + keyring=q.keyring, + request_mac=q.request_mac, + one_rr_per_rrset=one_rr_per_rrset, + ignore_trailing=ignore_trailing, + ) + r.time = max(finish - start, 0.0) + if not q.is_response(r): + raise BadResponse + return r + + +async def _inbound_xfr( + txn_manager: dns.transaction.TransactionManager, + s: dns.asyncbackend.Socket, + query: dns.message.Message, + serial: int | None, + timeout: float | None, + expiration: float, +) -> Any: + """Given a socket, does the zone transfer.""" + rdtype = query.question[0].rdtype + is_ixfr = rdtype == dns.rdatatype.IXFR + origin = txn_manager.from_wire_origin() + wire = query.to_wire() + is_udp = s.type == socket.SOCK_DGRAM + if is_udp: + udp_sock = cast(dns.asyncbackend.DatagramSocket, s) + await udp_sock.sendto(wire, None, _timeout(expiration)) + else: + tcp_sock = cast(dns.asyncbackend.StreamSocket, s) + tcpmsg = struct.pack("!H", len(wire)) + wire + await tcp_sock.sendall(tcpmsg, expiration) + with dns.xfr.Inbound(txn_manager, rdtype, serial, is_udp) as inbound: + done = False + tsig_ctx = None + r: dns.message.Message | None = None + while not done: + (_, mexpiration) = _compute_times(timeout) + if mexpiration is None or ( + expiration is not None and mexpiration > expiration + ): + mexpiration = expiration + if is_udp: + timeout = _timeout(mexpiration) + (rwire, _) = await udp_sock.recvfrom(65535, timeout) # pyright: ignore + else: + ldata = await _read_exactly(tcp_sock, 2, mexpiration) # pyright: ignore + (l,) = struct.unpack("!H", ldata) + rwire = await _read_exactly(tcp_sock, l, mexpiration) # pyright: ignore + r = dns.message.from_wire( + rwire, + keyring=query.keyring, + request_mac=query.mac, + xfr=True, + origin=origin, + tsig_ctx=tsig_ctx, + multi=(not is_udp), + one_rr_per_rrset=is_ixfr, + ) + done = inbound.process_message(r) + yield r + tsig_ctx = r.tsig_ctx + if query.keyring and r is not None and not r.had_tsig: + raise dns.exception.FormError("missing TSIG") + + +async def inbound_xfr( + where: str, + txn_manager: dns.transaction.TransactionManager, + query: dns.message.Message | None = None, + port: int = 53, + timeout: float | None = None, + lifetime: float | None = None, + source: str | None = None, + source_port: int = 0, + udp_mode: UDPMode = UDPMode.NEVER, + backend: dns.asyncbackend.Backend | None = None, +) -> None: + """Conduct an inbound transfer and apply it via a transaction from the + txn_manager. + + *backend*, a ``dns.asyncbackend.Backend``, or ``None``. If ``None``, + the default, then dnspython will use the default backend. + + See :py:func:`dns.query.inbound_xfr()` for the documentation of + the other parameters, exceptions, and return type of this method. + """ + if query is None: + (query, serial) = dns.xfr.make_query(txn_manager) + else: + serial = dns.xfr.extract_serial_from_query(query) + af = dns.inet.af_for_address(where) + stuple = _source_tuple(af, source, source_port) + dtuple = (where, port) + if not backend: + backend = dns.asyncbackend.get_default_backend() + (_, expiration) = _compute_times(lifetime) + if query.question[0].rdtype == dns.rdatatype.IXFR and udp_mode != UDPMode.NEVER: + s = await backend.make_socket( + af, socket.SOCK_DGRAM, 0, stuple, dtuple, _timeout(expiration) + ) + async with s: + try: + async for _ in _inbound_xfr( # pyright: ignore + txn_manager, + s, + query, + serial, + timeout, + expiration, # pyright: ignore + ): + pass + return + except dns.xfr.UseTCP: + if udp_mode == UDPMode.ONLY: + raise + + s = await backend.make_socket( + af, socket.SOCK_STREAM, 0, stuple, dtuple, _timeout(expiration) + ) + async with s: + async for _ in _inbound_xfr( # pyright: ignore + txn_manager, s, query, serial, timeout, expiration # pyright: ignore + ): + pass diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/asyncresolver.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/asyncresolver.py new file mode 100644 index 000000000..6f8c69fd3 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/asyncresolver.py @@ -0,0 +1,478 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +# Copyright (C) 2003-2017 Nominum, Inc. +# +# Permission to use, copy, modify, and distribute this software and its +# documentation for any purpose with or without fee is hereby granted, +# provided that the above copyright notice and this permission notice +# appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +"""Asynchronous DNS stub resolver.""" + +import socket +import time +from typing import Any, Dict, List + +import dns._ddr +import dns.asyncbackend +import dns.asyncquery +import dns.exception +import dns.inet +import dns.name +import dns.nameserver +import dns.query +import dns.rdataclass +import dns.rdatatype +import dns.resolver # lgtm[py/import-and-import-from] +import dns.reversename + +# import some resolver symbols for brevity +from dns.resolver import NXDOMAIN, NoAnswer, NoRootSOA, NotAbsolute + +# for indentation purposes below +_udp = dns.asyncquery.udp +_tcp = dns.asyncquery.tcp + + +class Resolver(dns.resolver.BaseResolver): + """Asynchronous DNS stub resolver.""" + + async def resolve( + self, + qname: dns.name.Name | str, + rdtype: dns.rdatatype.RdataType | str = dns.rdatatype.A, + rdclass: dns.rdataclass.RdataClass | str = dns.rdataclass.IN, + tcp: bool = False, + source: str | None = None, + raise_on_no_answer: bool = True, + source_port: int = 0, + lifetime: float | None = None, + search: bool | None = None, + backend: dns.asyncbackend.Backend | None = None, + ) -> dns.resolver.Answer: + """Query nameservers asynchronously to find the answer to the question. + + *backend*, a ``dns.asyncbackend.Backend``, or ``None``. If ``None``, + the default, then dnspython will use the default backend. + + See :py:func:`dns.resolver.Resolver.resolve()` for the + documentation of the other parameters, exceptions, and return + type of this method. + """ + + resolution = dns.resolver._Resolution( + self, qname, rdtype, rdclass, tcp, raise_on_no_answer, search + ) + if not backend: + backend = dns.asyncbackend.get_default_backend() + start = time.time() + while True: + (request, answer) = resolution.next_request() + # Note we need to say "if answer is not None" and not just + # "if answer" because answer implements __len__, and python + # will call that. We want to return if we have an answer + # object, including in cases where its length is 0. + if answer is not None: + # cache hit! + return answer + assert request is not None # needed for type checking + done = False + while not done: + (nameserver, tcp, backoff) = resolution.next_nameserver() + if backoff: + await backend.sleep(backoff) + timeout = self._compute_timeout(start, lifetime, resolution.errors) + try: + response = await nameserver.async_query( + request, + timeout=timeout, + source=source, + source_port=source_port, + max_size=tcp, + backend=backend, + ) + except Exception as ex: + (_, done) = resolution.query_result(None, ex) + continue + (answer, done) = resolution.query_result(response, None) + # Note we need to say "if answer is not None" and not just + # "if answer" because answer implements __len__, and python + # will call that. We want to return if we have an answer + # object, including in cases where its length is 0. + if answer is not None: + return answer + + async def resolve_address( + self, ipaddr: str, *args: Any, **kwargs: Any + ) -> dns.resolver.Answer: + """Use an asynchronous resolver to run a reverse query for PTR + records. + + This utilizes the resolve() method to perform a PTR lookup on the + specified IP address. + + *ipaddr*, a ``str``, the IPv4 or IPv6 address you want to get + the PTR record for. + + All other arguments that can be passed to the resolve() function + except for rdtype and rdclass are also supported by this + function. + + """ + # We make a modified kwargs for type checking happiness, as otherwise + # we get a legit warning about possibly having rdtype and rdclass + # in the kwargs more than once. + modified_kwargs: Dict[str, Any] = {} + modified_kwargs.update(kwargs) + modified_kwargs["rdtype"] = dns.rdatatype.PTR + modified_kwargs["rdclass"] = dns.rdataclass.IN + return await self.resolve( + dns.reversename.from_address(ipaddr), *args, **modified_kwargs + ) + + async def resolve_name( + self, + name: dns.name.Name | str, + family: int = socket.AF_UNSPEC, + **kwargs: Any, + ) -> dns.resolver.HostAnswers: + """Use an asynchronous resolver to query for address records. + + This utilizes the resolve() method to perform A and/or AAAA lookups on + the specified name. + + *qname*, a ``dns.name.Name`` or ``str``, the name to resolve. + + *family*, an ``int``, the address family. If socket.AF_UNSPEC + (the default), both A and AAAA records will be retrieved. + + All other arguments that can be passed to the resolve() function + except for rdtype and rdclass are also supported by this + function. + """ + # We make a modified kwargs for type checking happiness, as otherwise + # we get a legit warning about possibly having rdtype and rdclass + # in the kwargs more than once. + modified_kwargs: Dict[str, Any] = {} + modified_kwargs.update(kwargs) + modified_kwargs.pop("rdtype", None) + modified_kwargs["rdclass"] = dns.rdataclass.IN + + if family == socket.AF_INET: + v4 = await self.resolve(name, dns.rdatatype.A, **modified_kwargs) + return dns.resolver.HostAnswers.make(v4=v4) + elif family == socket.AF_INET6: + v6 = await self.resolve(name, dns.rdatatype.AAAA, **modified_kwargs) + return dns.resolver.HostAnswers.make(v6=v6) + elif family != socket.AF_UNSPEC: + raise NotImplementedError(f"unknown address family {family}") + + raise_on_no_answer = modified_kwargs.pop("raise_on_no_answer", True) + lifetime = modified_kwargs.pop("lifetime", None) + start = time.time() + v6 = await self.resolve( + name, + dns.rdatatype.AAAA, + raise_on_no_answer=False, + lifetime=self._compute_timeout(start, lifetime), + **modified_kwargs, + ) + # Note that setting name ensures we query the same name + # for A as we did for AAAA. (This is just in case search lists + # are active by default in the resolver configuration and + # we might be talking to a server that says NXDOMAIN when it + # wants to say NOERROR no data. + name = v6.qname + v4 = await self.resolve( + name, + dns.rdatatype.A, + raise_on_no_answer=False, + lifetime=self._compute_timeout(start, lifetime), + **modified_kwargs, + ) + answers = dns.resolver.HostAnswers.make( + v6=v6, v4=v4, add_empty=not raise_on_no_answer + ) + if not answers: + raise NoAnswer(response=v6.response) + return answers + + # pylint: disable=redefined-outer-name + + async def canonical_name(self, name: dns.name.Name | str) -> dns.name.Name: + """Determine the canonical name of *name*. + + The canonical name is the name the resolver uses for queries + after all CNAME and DNAME renamings have been applied. + + *name*, a ``dns.name.Name`` or ``str``, the query name. + + This method can raise any exception that ``resolve()`` can + raise, other than ``dns.resolver.NoAnswer`` and + ``dns.resolver.NXDOMAIN``. + + Returns a ``dns.name.Name``. + """ + try: + answer = await self.resolve(name, raise_on_no_answer=False) + canonical_name = answer.canonical_name + except dns.resolver.NXDOMAIN as e: + canonical_name = e.canonical_name + return canonical_name + + async def try_ddr(self, lifetime: float = 5.0) -> None: + """Try to update the resolver's nameservers using Discovery of Designated + Resolvers (DDR). If successful, the resolver will subsequently use + DNS-over-HTTPS or DNS-over-TLS for future queries. + + *lifetime*, a float, is the maximum time to spend attempting DDR. The default + is 5 seconds. + + If the SVCB query is successful and results in a non-empty list of nameservers, + then the resolver's nameservers are set to the returned servers in priority + order. + + The current implementation does not use any address hints from the SVCB record, + nor does it resolve addresses for the SCVB target name, rather it assumes that + the bootstrap nameserver will always be one of the addresses and uses it. + A future revision to the code may offer fuller support. The code verifies that + the bootstrap nameserver is in the Subject Alternative Name field of the + TLS certficate. + """ + try: + expiration = time.time() + lifetime + answer = await self.resolve( + dns._ddr._local_resolver_name, "svcb", lifetime=lifetime + ) + timeout = dns.query._remaining(expiration) + nameservers = await dns._ddr._get_nameservers_async(answer, timeout) + if len(nameservers) > 0: + self.nameservers = nameservers + except Exception: + pass + + +default_resolver = None + + +def get_default_resolver() -> Resolver: + """Get the default asynchronous resolver, initializing it if necessary.""" + if default_resolver is None: + reset_default_resolver() + assert default_resolver is not None + return default_resolver + + +def reset_default_resolver() -> None: + """Re-initialize default asynchronous resolver. + + Note that the resolver configuration (i.e. /etc/resolv.conf on UNIX + systems) will be re-read immediately. + """ + + global default_resolver + default_resolver = Resolver() + + +async def resolve( + qname: dns.name.Name | str, + rdtype: dns.rdatatype.RdataType | str = dns.rdatatype.A, + rdclass: dns.rdataclass.RdataClass | str = dns.rdataclass.IN, + tcp: bool = False, + source: str | None = None, + raise_on_no_answer: bool = True, + source_port: int = 0, + lifetime: float | None = None, + search: bool | None = None, + backend: dns.asyncbackend.Backend | None = None, +) -> dns.resolver.Answer: + """Query nameservers asynchronously to find the answer to the question. + + This is a convenience function that uses the default resolver + object to make the query. + + See :py:func:`dns.asyncresolver.Resolver.resolve` for more + information on the parameters. + """ + + return await get_default_resolver().resolve( + qname, + rdtype, + rdclass, + tcp, + source, + raise_on_no_answer, + source_port, + lifetime, + search, + backend, + ) + + +async def resolve_address( + ipaddr: str, *args: Any, **kwargs: Any +) -> dns.resolver.Answer: + """Use a resolver to run a reverse query for PTR records. + + See :py:func:`dns.asyncresolver.Resolver.resolve_address` for more + information on the parameters. + """ + + return await get_default_resolver().resolve_address(ipaddr, *args, **kwargs) + + +async def resolve_name( + name: dns.name.Name | str, family: int = socket.AF_UNSPEC, **kwargs: Any +) -> dns.resolver.HostAnswers: + """Use a resolver to asynchronously query for address records. + + See :py:func:`dns.asyncresolver.Resolver.resolve_name` for more + information on the parameters. + """ + + return await get_default_resolver().resolve_name(name, family, **kwargs) + + +async def canonical_name(name: dns.name.Name | str) -> dns.name.Name: + """Determine the canonical name of *name*. + + See :py:func:`dns.resolver.Resolver.canonical_name` for more + information on the parameters and possible exceptions. + """ + + return await get_default_resolver().canonical_name(name) + + +async def try_ddr(timeout: float = 5.0) -> None: + """Try to update the default resolver's nameservers using Discovery of Designated + Resolvers (DDR). If successful, the resolver will subsequently use + DNS-over-HTTPS or DNS-over-TLS for future queries. + + See :py:func:`dns.resolver.Resolver.try_ddr` for more information. + """ + return await get_default_resolver().try_ddr(timeout) + + +async def zone_for_name( + name: dns.name.Name | str, + rdclass: dns.rdataclass.RdataClass = dns.rdataclass.IN, + tcp: bool = False, + resolver: Resolver | None = None, + backend: dns.asyncbackend.Backend | None = None, +) -> dns.name.Name: + """Find the name of the zone which contains the specified name. + + See :py:func:`dns.resolver.Resolver.zone_for_name` for more + information on the parameters and possible exceptions. + """ + + if isinstance(name, str): + name = dns.name.from_text(name, dns.name.root) + if resolver is None: + resolver = get_default_resolver() + if not name.is_absolute(): + raise NotAbsolute(name) + while True: + try: + answer = await resolver.resolve( + name, dns.rdatatype.SOA, rdclass, tcp, backend=backend + ) + assert answer.rrset is not None + if answer.rrset.name == name: + return name + # otherwise we were CNAMEd or DNAMEd and need to look higher + except (NXDOMAIN, NoAnswer): + pass + try: + name = name.parent() + except dns.name.NoParent: # pragma: no cover + raise NoRootSOA + + +async def make_resolver_at( + where: dns.name.Name | str, + port: int = 53, + family: int = socket.AF_UNSPEC, + resolver: Resolver | None = None, +) -> Resolver: + """Make a stub resolver using the specified destination as the full resolver. + + *where*, a ``dns.name.Name`` or ``str`` the domain name or IP address of the + full resolver. + + *port*, an ``int``, the port to use. If not specified, the default is 53. + + *family*, an ``int``, the address family to use. This parameter is used if + *where* is not an address. The default is ``socket.AF_UNSPEC`` in which case + the first address returned by ``resolve_name()`` will be used, otherwise the + first address of the specified family will be used. + + *resolver*, a ``dns.asyncresolver.Resolver`` or ``None``, the resolver to use for + resolution of hostnames. If not specified, the default resolver will be used. + + Returns a ``dns.resolver.Resolver`` or raises an exception. + """ + if resolver is None: + resolver = get_default_resolver() + nameservers: List[str | dns.nameserver.Nameserver] = [] + if isinstance(where, str) and dns.inet.is_address(where): + nameservers.append(dns.nameserver.Do53Nameserver(where, port)) + else: + answers = await resolver.resolve_name(where, family) + for address in answers.addresses(): + nameservers.append(dns.nameserver.Do53Nameserver(address, port)) + res = Resolver(configure=False) + res.nameservers = nameservers + return res + + +async def resolve_at( + where: dns.name.Name | str, + qname: dns.name.Name | str, + rdtype: dns.rdatatype.RdataType | str = dns.rdatatype.A, + rdclass: dns.rdataclass.RdataClass | str = dns.rdataclass.IN, + tcp: bool = False, + source: str | None = None, + raise_on_no_answer: bool = True, + source_port: int = 0, + lifetime: float | None = None, + search: bool | None = None, + backend: dns.asyncbackend.Backend | None = None, + port: int = 53, + family: int = socket.AF_UNSPEC, + resolver: Resolver | None = None, +) -> dns.resolver.Answer: + """Query nameservers to find the answer to the question. + + This is a convenience function that calls ``dns.asyncresolver.make_resolver_at()`` + to make a resolver, and then uses it to resolve the query. + + See ``dns.asyncresolver.Resolver.resolve`` for more information on the resolution + parameters, and ``dns.asyncresolver.make_resolver_at`` for information about the + resolver parameters *where*, *port*, *family*, and *resolver*. + + If making more than one query, it is more efficient to call + ``dns.asyncresolver.make_resolver_at()`` and then use that resolver for the queries + instead of calling ``resolve_at()`` multiple times. + """ + res = await make_resolver_at(where, port, family, resolver) + return await res.resolve( + qname, + rdtype, + rdclass, + tcp, + source, + raise_on_no_answer, + source_port, + lifetime, + search, + backend, + ) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/btree.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/btree.py new file mode 100644 index 000000000..12da9f56e --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/btree.py @@ -0,0 +1,850 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +""" +A BTree in the style of Cormen, Leiserson, and Rivest's "Algorithms" book, with +copy-on-write node updates, cursors, and optional space optimization for mostly-in-order +insertion. +""" + +from collections.abc import MutableMapping, MutableSet +from typing import Any, Callable, Generic, Optional, Tuple, TypeVar, cast + +DEFAULT_T = 127 + +KT = TypeVar("KT") # the type of a key in Element + + +class Element(Generic[KT]): + """All items stored in the BTree are Elements.""" + + def key(self) -> KT: + """The key for this element; the returned type must implement comparison.""" + raise NotImplementedError # pragma: no cover + + +ET = TypeVar("ET", bound=Element) # the type of a value in a _KV + + +def _MIN(t: int) -> int: + """The minimum number of keys in a non-root node for a BTree with the specified + ``t`` + """ + return t - 1 + + +def _MAX(t: int) -> int: + """The maximum number of keys in node for a BTree with the specified ``t``""" + return 2 * t - 1 + + +class _Creator: + """A _Creator class instance is used as a unique id for the BTree which created + a node. + + We use a dedicated creator rather than just a BTree reference to avoid circularity + that would complicate GC. + """ + + def __str__(self): # pragma: no cover + return f"{id(self):x}" + + +class _Node(Generic[KT, ET]): + """A Node in the BTree. + + A Node (leaf or internal) of the BTree. + """ + + __slots__ = ["t", "creator", "is_leaf", "elts", "children"] + + def __init__(self, t: int, creator: _Creator, is_leaf: bool): + assert t >= 3 + self.t = t + self.creator = creator + self.is_leaf = is_leaf + self.elts: list[ET] = [] + self.children: list[_Node[KT, ET]] = [] + + def is_maximal(self) -> bool: + """Does this node have the maximal number of keys?""" + assert len(self.elts) <= _MAX(self.t) + return len(self.elts) == _MAX(self.t) + + def is_minimal(self) -> bool: + """Does this node have the minimal number of keys?""" + assert len(self.elts) >= _MIN(self.t) + return len(self.elts) == _MIN(self.t) + + def search_in_node(self, key: KT) -> tuple[int, bool]: + """Get the index of the ``Element`` matching ``key`` or the index of its + least successor. + + Returns a tuple of the index and an ``equal`` boolean that is ``True`` iff. + the key was found. + """ + l = len(self.elts) + if l > 0 and key > self.elts[l - 1].key(): + # This is optimizing near in-order insertion. + return l, False + l = 0 + i = len(self.elts) + r = i - 1 + equal = False + while l <= r: + m = (l + r) // 2 + k = self.elts[m].key() + if key == k: + i = m + equal = True + break + elif key < k: + i = m + r = m - 1 + else: + l = m + 1 + return i, equal + + def maybe_cow_child(self, index: int) -> "_Node[KT, ET]": + assert not self.is_leaf + child = self.children[index] + cloned = child.maybe_cow(self.creator) + if cloned: + self.children[index] = cloned + return cloned + else: + return child + + def _get_node(self, key: KT) -> Tuple[Optional["_Node[KT, ET]"], int]: + """Get the node associated with key and its index, doing + copy-on-write if we have to descend. + + Returns a tuple of the node and the index, or the tuple ``(None, 0)`` + if the key was not found. + """ + i, equal = self.search_in_node(key) + if equal: + return (self, i) + elif self.is_leaf: + return (None, 0) + else: + child = self.maybe_cow_child(i) + return child._get_node(key) + + def get(self, key: KT) -> ET | None: + """Get the element associated with *key* or return ``None``""" + i, equal = self.search_in_node(key) + if equal: + return self.elts[i] + elif self.is_leaf: + return None + else: + return self.children[i].get(key) + + def optimize_in_order_insertion(self, index: int) -> None: + """Try to minimize the number of Nodes in a BTree where the insertion + is done in-order or close to it, by stealing as much as we can from our + right sibling. + + If we don't do this, then an in-order insertion will produce a BTree + where most of the nodes are minimal. + """ + if index == 0: + return + left = self.children[index - 1] + if len(left.elts) == _MAX(self.t): + return + left = self.maybe_cow_child(index - 1) + while len(left.elts) < _MAX(self.t): + if not left.try_right_steal(self, index - 1): + break + + def insert_nonfull(self, element: ET, in_order: bool) -> ET | None: + assert not self.is_maximal() + while True: + key = element.key() + i, equal = self.search_in_node(key) + if equal: + # replace + old = self.elts[i] + self.elts[i] = element + return old + elif self.is_leaf: + self.elts.insert(i, element) + return None + else: + child = self.maybe_cow_child(i) + if child.is_maximal(): + self.adopt(*child.split()) + # Splitting might result in our target moving to us, so + # search again. + continue + oelt = child.insert_nonfull(element, in_order) + if in_order: + self.optimize_in_order_insertion(i) + return oelt + + def split(self) -> tuple["_Node[KT, ET]", ET, "_Node[KT, ET]"]: + """Split a maximal node into two minimal ones and a central element.""" + assert self.is_maximal() + right = self.__class__(self.t, self.creator, self.is_leaf) + right.elts = list(self.elts[_MIN(self.t) + 1 :]) + middle = self.elts[_MIN(self.t)] + self.elts = list(self.elts[: _MIN(self.t)]) + if not self.is_leaf: + right.children = list(self.children[_MIN(self.t) + 1 :]) + self.children = list(self.children[: _MIN(self.t) + 1]) + return self, middle, right + + def try_left_steal(self, parent: "_Node[KT, ET]", index: int) -> bool: + """Try to steal from this Node's left sibling for balancing purposes. + + Returns ``True`` if the theft was successful, or ``False`` if not. + """ + if index != 0: + left = parent.children[index - 1] + if not left.is_minimal(): + left = parent.maybe_cow_child(index - 1) + elt = parent.elts[index - 1] + parent.elts[index - 1] = left.elts.pop() + self.elts.insert(0, elt) + if not left.is_leaf: + assert not self.is_leaf + child = left.children.pop() + self.children.insert(0, child) + return True + return False + + def try_right_steal(self, parent: "_Node[KT, ET]", index: int) -> bool: + """Try to steal from this Node's right sibling for balancing purposes. + + Returns ``True`` if the theft was successful, or ``False`` if not. + """ + if index + 1 < len(parent.children): + right = parent.children[index + 1] + if not right.is_minimal(): + right = parent.maybe_cow_child(index + 1) + elt = parent.elts[index] + parent.elts[index] = right.elts.pop(0) + self.elts.append(elt) + if not right.is_leaf: + assert not self.is_leaf + child = right.children.pop(0) + self.children.append(child) + return True + return False + + def adopt(self, left: "_Node[KT, ET]", middle: ET, right: "_Node[KT, ET]") -> None: + """Adopt left, middle, and right into our Node (which must not be maximal, + and which must not be a leaf). In the case were we are not the new root, + then the left child must already be in the Node.""" + assert not self.is_maximal() + assert not self.is_leaf + key = middle.key() + i, equal = self.search_in_node(key) + assert not equal + self.elts.insert(i, middle) + if len(self.children) == 0: + # We are the new root + self.children = [left, right] + else: + assert self.children[i] == left + self.children.insert(i + 1, right) + + def merge(self, parent: "_Node[KT, ET]", index: int) -> None: + """Merge this node's parent and its right sibling into this node.""" + right = parent.children.pop(index + 1) + self.elts.append(parent.elts.pop(index)) + self.elts.extend(right.elts) + if not self.is_leaf: + self.children.extend(right.children) + + def minimum(self) -> ET: + """The least element in this subtree.""" + if self.is_leaf: + return self.elts[0] + else: + return self.children[0].minimum() + + def maximum(self) -> ET: + """The greatest element in this subtree.""" + if self.is_leaf: + return self.elts[-1] + else: + return self.children[-1].maximum() + + def balance(self, parent: "_Node[KT, ET]", index: int) -> None: + """This Node is minimal, and we want to make it non-minimal so we can delete. + We try to steal from our siblings, and if that doesn't work we will merge + with one of them.""" + assert not parent.is_leaf + if self.try_left_steal(parent, index): + return + if self.try_right_steal(parent, index): + return + # Stealing didn't work, so both siblings must be minimal. + if index == 0: + # We are the left-most node so merge with our right sibling. + self.merge(parent, index) + else: + # Have our left sibling merge with us. This lets us only have "merge right" + # code. + left = parent.maybe_cow_child(index - 1) + left.merge(parent, index - 1) + + def delete( + self, key: KT, parent: Optional["_Node[KT, ET]"], exact: ET | None + ) -> ET | None: + """Delete an element matching *key* if it exists. If *exact* is not ``None`` + then it must be an exact match with that element. The Node must not be + minimal unless it is the root.""" + assert parent is None or not self.is_minimal() + i, equal = self.search_in_node(key) + original_key = None + if equal: + # Note we use "is" here as we meant "exactly this object". + if exact is not None and self.elts[i] is not exact: + raise ValueError("exact delete did not match existing elt") + if self.is_leaf: + return self.elts.pop(i) + # Note we need to ensure exact is None going forward as we've + # already checked exactness and are about to change our target key + # to the least successor. + exact = None + original_key = key + least_successor = self.children[i + 1].minimum() + key = least_successor.key() + i = i + 1 + if self.is_leaf: + # No match + if exact is not None: + raise ValueError("exact delete had no match") + return None + # recursively delete in the appropriate child + child = self.maybe_cow_child(i) + if child.is_minimal(): + child.balance(self, i) + # Things may have moved. + i, equal = self.search_in_node(key) + assert not equal + child = self.children[i] + assert not child.is_minimal() + elt = child.delete(key, self, exact) + if original_key is not None: + node, i = self._get_node(original_key) + assert node is not None + assert elt is not None + oelt = node.elts[i] + node.elts[i] = elt + elt = oelt + return elt + + def visit_in_order(self, visit: Callable[[ET], None]) -> None: + """Call *visit* on all of the elements in order.""" + for i, elt in enumerate(self.elts): + if not self.is_leaf: + self.children[i].visit_in_order(visit) + visit(elt) + if not self.is_leaf: + self.children[-1].visit_in_order(visit) + + def _visit_preorder_by_node(self, visit: Callable[["_Node[KT, ET]"], None]) -> None: + """Visit nodes in preorder. This method is only used for testing.""" + visit(self) + if not self.is_leaf: + for child in self.children: + child._visit_preorder_by_node(visit) + + def maybe_cow(self, creator: _Creator) -> Optional["_Node[KT, ET]"]: + """Return a clone of this Node if it was not created by *creator*, or ``None`` + otherwise (i.e. copy for copy-on-write if we haven't already copied it).""" + if self.creator is not creator: + return self.clone(creator) + else: + return None + + def clone(self, creator: _Creator) -> "_Node[KT, ET]": + """Make a shallow-copy duplicate of this node.""" + cloned = self.__class__(self.t, creator, self.is_leaf) + cloned.elts.extend(self.elts) + if not self.is_leaf: + cloned.children.extend(self.children) + return cloned + + def __str__(self): # pragma: no cover + if not self.is_leaf: + children = " " + " ".join([f"{id(c):x}" for c in self.children]) + else: + children = "" + return f"{id(self):x} {self.creator} {self.elts}{children}" + + +class Cursor(Generic[KT, ET]): + """A seekable cursor for a BTree. + + If you are going to use a cursor on a mutable BTree, you should use it + in a ``with`` block so that any mutations of the BTree automatically park + the cursor. + """ + + def __init__(self, btree: "BTree[KT, ET]"): + self.btree = btree + self.current_node: _Node | None = None + # The current index is the element index within the current node, or + # if there is no current node then it is 0 on the left boundary and 1 + # on the right boundary. + self.current_index: int = 0 + self.recurse = False + self.increasing = True + self.parents: list[tuple[_Node, int]] = [] + self.parked = False + self.parking_key: KT | None = None + self.parking_key_read = False + + def _seek_least(self) -> None: + # seek to the least value in the subtree beneath the current index of the + # current node + assert self.current_node is not None + while not self.current_node.is_leaf: + self.parents.append((self.current_node, self.current_index)) + self.current_node = self.current_node.children[self.current_index] + assert self.current_node is not None + self.current_index = 0 + + def _seek_greatest(self) -> None: + # seek to the greatest value in the subtree beneath the current index of the + # current node + assert self.current_node is not None + while not self.current_node.is_leaf: + self.parents.append((self.current_node, self.current_index)) + self.current_node = self.current_node.children[self.current_index] + assert self.current_node is not None + self.current_index = len(self.current_node.elts) + + def park(self): + """Park the cursor. + + A cursor must be "parked" before mutating the BTree to avoid undefined behavior. + Cursors created in a ``with`` block register with their BTree and will park + automatically. Note that a parked cursor may not observe some changes made when + it is parked; for example a cursor being iterated with next() will not see items + inserted before its current position. + """ + if not self.parked: + self.parked = True + + def _maybe_unpark(self): + if self.parked: + if self.parking_key is not None: + # remember our increasing hint, as seeking might change it + increasing = self.increasing + if self.parking_key_read: + # We've already returned the parking key, so we want to be before it + # if decreasing and after it if increasing. + before = not self.increasing + else: + # We haven't returned the parking key, so we've parked right + # after seeking or are on a boundary. Either way, the before + # hint we want is the value of self.increasing. + before = self.increasing + self.seek(self.parking_key, before) + self.increasing = increasing # might have been altered by seek() + self.parked = False + self.parking_key = None + + def prev(self) -> ET | None: + """Get the previous element, or return None if on the left boundary.""" + self._maybe_unpark() + self.parking_key = None + if self.current_node is None: + # on a boundary + if self.current_index == 0: + # left boundary, there is no prev + return None + else: + assert self.current_index == 1 + # right boundary; seek to the actual boundary + # so we can do a prev() + self.current_node = self.btree.root + self.current_index = len(self.btree.root.elts) + self._seek_greatest() + while True: + if self.recurse: + if not self.increasing: + # We only want to recurse if we are continuing in the decreasing + # direction. + self._seek_greatest() + self.recurse = False + self.increasing = False + self.current_index -= 1 + if self.current_index >= 0: + elt = self.current_node.elts[self.current_index] + if not self.current_node.is_leaf: + self.recurse = True + self.parking_key = elt.key() + self.parking_key_read = True + return elt + else: + if len(self.parents) > 0: + self.current_node, self.current_index = self.parents.pop() + else: + self.current_node = None + self.current_index = 0 + return None + + def next(self) -> ET | None: + """Get the next element, or return None if on the right boundary.""" + self._maybe_unpark() + self.parking_key = None + if self.current_node is None: + # on a boundary + if self.current_index == 1: + # right boundary, there is no next + return None + else: + assert self.current_index == 0 + # left boundary; seek to the actual boundary + # so we can do a next() + self.current_node = self.btree.root + self.current_index = 0 + self._seek_least() + while True: + if self.recurse: + if self.increasing: + # We only want to recurse if we are continuing in the increasing + # direction. + self._seek_least() + self.recurse = False + self.increasing = True + if self.current_index < len(self.current_node.elts): + elt = self.current_node.elts[self.current_index] + self.current_index += 1 + if not self.current_node.is_leaf: + self.recurse = True + self.parking_key = elt.key() + self.parking_key_read = True + return elt + else: + if len(self.parents) > 0: + self.current_node, self.current_index = self.parents.pop() + else: + self.current_node = None + self.current_index = 1 + return None + + def _adjust_for_before(self, before: bool, i: int) -> None: + if before: + self.current_index = i + else: + self.current_index = i + 1 + + def seek(self, key: KT, before: bool = True) -> None: + """Seek to the specified key. + + If *before* is ``True`` (the default) then the cursor is positioned just + before *key* if it exists, or before its least successor if it doesn't. A + subsequent next() will retrieve this value. If *before* is ``False``, then + the cursor is positioned just after *key* if it exists, or its greatest + precessessor if it doesn't. A subsequent prev() will return this value. + """ + self.current_node = self.btree.root + assert self.current_node is not None + self.recurse = False + self.parents = [] + self.increasing = before + self.parked = False + self.parking_key = key + self.parking_key_read = False + while not self.current_node.is_leaf: + i, equal = self.current_node.search_in_node(key) + if equal: + self._adjust_for_before(before, i) + if before: + self._seek_greatest() + else: + self._seek_least() + return + self.parents.append((self.current_node, i)) + self.current_node = self.current_node.children[i] + assert self.current_node is not None + i, equal = self.current_node.search_in_node(key) + if equal: + self._adjust_for_before(before, i) + else: + self.current_index = i + + def seek_first(self) -> None: + """Seek to the left boundary (i.e. just before the least element). + + A subsequent next() will return the least element if the BTree isn't empty.""" + self.current_node = None + self.current_index = 0 + self.recurse = False + self.increasing = True + self.parents = [] + self.parked = False + self.parking_key = None + + def seek_last(self) -> None: + """Seek to the right boundary (i.e. just after the greatest element). + + A subsequent prev() will return the greatest element if the BTree isn't empty. + """ + self.current_node = None + self.current_index = 1 + self.recurse = False + self.increasing = False + self.parents = [] + self.parked = False + self.parking_key = None + + def __enter__(self): + self.btree.register_cursor(self) + return self + + def __exit__(self, exc_type, exc_value, traceback): + self.btree.deregister_cursor(self) + return False + + +class Immutable(Exception): + """The BTree is immutable.""" + + +class BTree(Generic[KT, ET]): + """An in-memory BTree with copy-on-write and cursors.""" + + def __init__(self, *, t: int = DEFAULT_T, original: Optional["BTree"] = None): + """Create a BTree. + + If *original* is not ``None``, then the BTree is shallow-cloned from + *original* using copy-on-write. Otherwise a new BTree with the specified + *t* value is created. + + The BTree is not thread-safe. + """ + # We don't use a reference to ourselves as a creator as we don't want + # to prevent GC of old btrees. + self.creator = _Creator() + self._immutable = False + self.t: int + self.root: _Node + self.size: int + self.cursors: set[Cursor] = set() + if original is not None: + if not original._immutable: + raise ValueError("original BTree is not immutable") + self.t = original.t + self.root = original.root + self.size = original.size + else: + if t < 3: + raise ValueError("t must be >= 3") + self.t = t + self.root = _Node(self.t, self.creator, True) + self.size = 0 + + def make_immutable(self): + """Make the BTree immutable. + + Attempts to alter the BTree after making it immutable will raise an + Immutable exception. This operation cannot be undone. + """ + if not self._immutable: + self._immutable = True + + def _check_mutable_and_park(self) -> None: + if self._immutable: + raise Immutable + for cursor in self.cursors: + cursor.park() + + # Note that we don't use insert() and delete() but rather insert_element() and + # delete_key() so that BTreeDict can be a proper MutableMapping and supply the + # rest of the standard mapping API. + + def insert_element(self, elt: ET, in_order: bool = False) -> ET | None: + """Insert the element into the BTree. + + If *in_order* is ``True``, then extra work will be done to make left siblings + full, which optimizes storage space when the the elements are inserted in-order + or close to it. + + Returns the previously existing element at the element's key or ``None``. + """ + self._check_mutable_and_park() + cloned = self.root.maybe_cow(self.creator) + if cloned: + self.root = cloned + if self.root.is_maximal(): + old_root = self.root + self.root = _Node(self.t, self.creator, False) + self.root.adopt(*old_root.split()) + oelt = self.root.insert_nonfull(elt, in_order) + if oelt is None: + # We did not replace, so something was added. + self.size += 1 + return oelt + + def get_element(self, key: KT) -> ET | None: + """Get the element matching *key* from the BTree, or return ``None`` if it + does not exist. + """ + return self.root.get(key) + + def _delete(self, key: KT, exact: ET | None) -> ET | None: + self._check_mutable_and_park() + cloned = self.root.maybe_cow(self.creator) + if cloned: + self.root = cloned + elt = self.root.delete(key, None, exact) + if elt is not None: + # We deleted something + self.size -= 1 + if len(self.root.elts) == 0: + # The root is now empty. If there is a child, then collapse this root + # level and make the child the new root. + if not self.root.is_leaf: + assert len(self.root.children) == 1 + self.root = self.root.children[0] + return elt + + def delete_key(self, key: KT) -> ET | None: + """Delete the element matching *key* from the BTree. + + Returns the matching element or ``None`` if it does not exist. + """ + return self._delete(key, None) + + def delete_exact(self, element: ET) -> ET | None: + """Delete *element* from the BTree. + + Returns the matching element or ``None`` if it was not in the BTree. + """ + delt = self._delete(element.key(), element) + assert delt is element + return delt + + def __len__(self): + return self.size + + def visit_in_order(self, visit: Callable[[ET], None]) -> None: + """Call *visit*(element) on all elements in the tree in sorted order.""" + self.root.visit_in_order(visit) + + def _visit_preorder_by_node(self, visit: Callable[[_Node], None]) -> None: + self.root._visit_preorder_by_node(visit) + + def cursor(self) -> Cursor[KT, ET]: + """Create a cursor.""" + return Cursor(self) + + def register_cursor(self, cursor: Cursor) -> None: + """Register a cursor for the automatic parking service.""" + self.cursors.add(cursor) + + def deregister_cursor(self, cursor: Cursor) -> None: + """Deregister a cursor from the automatic parking service.""" + self.cursors.discard(cursor) + + def __copy__(self): + return self.__class__(original=self) + + def __iter__(self): + with self.cursor() as cursor: + while True: + elt = cursor.next() + if elt is None: + break + yield elt.key() + + +VT = TypeVar("VT") # the type of a value in a BTreeDict + + +class KV(Element, Generic[KT, VT]): + """The BTree element type used in a ``BTreeDict``.""" + + def __init__(self, key: KT, value: VT): + self._key = key + self._value = value + + def key(self) -> KT: + return self._key + + def value(self) -> VT: + return self._value + + def __str__(self): # pragma: no cover + return f"KV({self._key}, {self._value})" + + def __repr__(self): # pragma: no cover + return f"KV({self._key}, {self._value})" + + +class BTreeDict(Generic[KT, VT], BTree[KT, KV[KT, VT]], MutableMapping[KT, VT]): + """A MutableMapping implemented with a BTree. + + Unlike a normal Python dict, the BTreeDict may be mutated while iterating. + """ + + def __init__( + self, + *, + t: int = DEFAULT_T, + original: BTree | None = None, + in_order: bool = False, + ): + super().__init__(t=t, original=original) + self.in_order = in_order + + def __getitem__(self, key: KT) -> VT: + elt = self.get_element(key) + if elt is None: + raise KeyError + else: + return cast(KV, elt).value() + + def __setitem__(self, key: KT, value: VT) -> None: + elt = KV(key, value) + self.insert_element(elt, self.in_order) + + def __delitem__(self, key: KT) -> None: + if self.delete_key(key) is None: + raise KeyError + + +class Member(Element, Generic[KT]): + """The BTree element type used in a ``BTreeSet``.""" + + def __init__(self, key: KT): + self._key = key + + def key(self) -> KT: + return self._key + + +class BTreeSet(BTree, Generic[KT], MutableSet[KT]): + """A MutableSet implemented with a BTree. + + Unlike a normal Python set, the BTreeSet may be mutated while iterating. + """ + + def __init__( + self, + *, + t: int = DEFAULT_T, + original: BTree | None = None, + in_order: bool = False, + ): + super().__init__(t=t, original=original) + self.in_order = in_order + + def __contains__(self, key: Any) -> bool: + return self.get_element(key) is not None + + def add(self, value: KT) -> None: + elt = Member(value) + self.insert_element(elt, self.in_order) + + def discard(self, value: KT) -> None: + self.delete_key(value) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/btreezone.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/btreezone.py new file mode 100644 index 000000000..27b5bb6fe --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/btreezone.py @@ -0,0 +1,367 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +# A derivative of a dnspython VersionedZone and related classes, using a BTreeDict and +# a separate per-version delegation index. These additions let us +# +# 1) Do efficient CoW versioning (useful for future online updates). +# 2) Maintain sort order +# 3) Allow delegations to be found easily +# 4) Handle glue +# 5) Add Node flags ORIGIN, DELEGATION, and GLUE whenever relevant. The ORIGIN +# flag is set at the origin node, the DELEGATION FLAG is set at delegation +# points, and the GLUE flag is set on nodes beneath delegation points. + +import enum +from dataclasses import dataclass +from typing import Callable, MutableMapping, Tuple, cast + +import dns.btree +import dns.immutable +import dns.name +import dns.node +import dns.rdataclass +import dns.rdataset +import dns.rdatatype +import dns.versioned +import dns.zone + + +class NodeFlags(enum.IntFlag): + ORIGIN = 0x01 + DELEGATION = 0x02 + GLUE = 0x04 + + +class Node(dns.node.Node): + __slots__ = ["flags", "id"] + + def __init__(self, flags: NodeFlags | None = None): + super().__init__() + if flags is None: + # We allow optional flags rather than a default + # as pyright doesn't like assigning a literal 0 + # to flags. + flags = NodeFlags(0) + self.flags = flags + self.id = 0 + + def is_delegation(self): + return (self.flags & NodeFlags.DELEGATION) != 0 + + def is_glue(self): + return (self.flags & NodeFlags.GLUE) != 0 + + def is_origin(self): + return (self.flags & NodeFlags.ORIGIN) != 0 + + def is_origin_or_glue(self): + return (self.flags & (NodeFlags.ORIGIN | NodeFlags.GLUE)) != 0 + + +@dns.immutable.immutable +class ImmutableNode(Node): + def __init__(self, node: Node): + super().__init__() + self.id = node.id + self.rdatasets = tuple( # type: ignore + [dns.rdataset.ImmutableRdataset(rds) for rds in node.rdatasets] + ) + self.flags = node.flags + + def find_rdataset( + self, + rdclass: dns.rdataclass.RdataClass, + rdtype: dns.rdatatype.RdataType, + covers: dns.rdatatype.RdataType = dns.rdatatype.NONE, + create: bool = False, + ) -> dns.rdataset.Rdataset: + if create: + raise TypeError("immutable") + return super().find_rdataset(rdclass, rdtype, covers, False) + + def get_rdataset( + self, + rdclass: dns.rdataclass.RdataClass, + rdtype: dns.rdatatype.RdataType, + covers: dns.rdatatype.RdataType = dns.rdatatype.NONE, + create: bool = False, + ) -> dns.rdataset.Rdataset | None: + if create: + raise TypeError("immutable") + return super().get_rdataset(rdclass, rdtype, covers, False) + + def delete_rdataset( + self, + rdclass: dns.rdataclass.RdataClass, + rdtype: dns.rdatatype.RdataType, + covers: dns.rdatatype.RdataType = dns.rdatatype.NONE, + ) -> None: + raise TypeError("immutable") + + def replace_rdataset(self, replacement: dns.rdataset.Rdataset) -> None: + raise TypeError("immutable") + + def is_immutable(self) -> bool: + return True + + +class Delegations(dns.btree.BTreeSet[dns.name.Name]): + def get_delegation(self, name: dns.name.Name) -> Tuple[dns.name.Name | None, bool]: + """Get the delegation applicable to *name*, if it exists. + + If there delegation, then return a tuple consisting of the name of + the delegation point, and a boolean which is `True` if the name is a proper + subdomain of the delegation point, and `False` if it is equal to the delegation + point. + """ + cursor = self.cursor() + cursor.seek(name, before=False) + prev = cursor.prev() + if prev is None: + return None, False + cut = prev.key() + reln, _, _ = name.fullcompare(cut) + is_subdomain = reln == dns.name.NameRelation.SUBDOMAIN + if is_subdomain or reln == dns.name.NameRelation.EQUAL: + return cut, is_subdomain + else: + return None, False + + def is_glue(self, name: dns.name.Name) -> bool: + """Is *name* glue, i.e. is it beneath a delegation?""" + cursor = self.cursor() + cursor.seek(name, before=False) + cut, is_subdomain = self.get_delegation(name) + if cut is None: + return False + return is_subdomain + + +class WritableVersion(dns.zone.WritableVersion): + def __init__(self, zone: dns.zone.Zone, replacement: bool = False): + super().__init__(zone, True) + if not replacement: + assert isinstance(zone, dns.versioned.Zone) + version = zone._versions[-1] + self.nodes: dns.btree.BTreeDict[dns.name.Name, Node] = dns.btree.BTreeDict( + original=version.nodes # type: ignore + ) + self.delegations = Delegations(original=version.delegations) # type: ignore + else: + self.delegations = Delegations() + + def _is_origin(self, name: dns.name.Name) -> bool: + # Assumes name has already been validated (and thus adjusted to the right + # relativity too) + if self.zone.relativize: + return name == dns.name.empty + else: + return name == self.zone.origin + + def _maybe_cow_with_name( + self, name: dns.name.Name + ) -> Tuple[dns.node.Node, dns.name.Name]: + (node, name) = super()._maybe_cow_with_name(name) + node = cast(Node, node) + if self._is_origin(name): + node.flags |= NodeFlags.ORIGIN + elif self.delegations.is_glue(name): + node.flags |= NodeFlags.GLUE + return (node, name) + + def update_glue_flag(self, name: dns.name.Name, is_glue: bool) -> None: + cursor = self.nodes.cursor() # type: ignore + cursor.seek(name, False) + updates = [] + while True: + elt = cursor.next() + if elt is None: + break + ename = elt.key() + if not ename.is_subdomain(name): + break + node = cast(dns.node.Node, elt.value()) + if ename not in self.changed: + new_node = self.zone.node_factory() + new_node.id = self.id # type: ignore + new_node.rdatasets.extend(node.rdatasets) + self.changed.add(ename) + node = new_node + assert isinstance(node, Node) + if is_glue: + node.flags |= NodeFlags.GLUE + else: + node.flags &= ~NodeFlags.GLUE + # We don't update node here as any insertion could disturb the + # btree and invalidate our cursor. We could use the cursor in a + # with block and avoid this, but it would do a lot of parking and + # unparking so the deferred update mode may still be better. + updates.append((ename, node)) + for ename, node in updates: + self.nodes[ename] = node + + def delete_node(self, name: dns.name.Name) -> None: + name = self._validate_name(name) + node = self.nodes.get(name) + if node is not None: + if node.is_delegation(): # type: ignore + self.delegations.discard(name) + self.update_glue_flag(name, False) + del self.nodes[name] + self.changed.add(name) + + def put_rdataset( + self, name: dns.name.Name, rdataset: dns.rdataset.Rdataset + ) -> None: + (node, name) = self._maybe_cow_with_name(name) + if ( + rdataset.rdtype == dns.rdatatype.NS and not node.is_origin_or_glue() # type: ignore + ): + node.flags |= NodeFlags.DELEGATION # type: ignore + if name not in self.delegations: + self.delegations.add(name) + self.update_glue_flag(name, True) + node.replace_rdataset(rdataset) + + def delete_rdataset( + self, + name: dns.name.Name, + rdtype: dns.rdatatype.RdataType, + covers: dns.rdatatype.RdataType, + ) -> None: + (node, name) = self._maybe_cow_with_name(name) + if rdtype == dns.rdatatype.NS and name in self.delegations: # type: ignore + node.flags &= ~NodeFlags.DELEGATION # type: ignore + self.delegations.discard(name) # type: ignore + self.update_glue_flag(name, False) + node.delete_rdataset(self.zone.rdclass, rdtype, covers) + if len(node) == 0: + del self.nodes[name] + + +@dataclass(frozen=True) +class Bounds: + name: dns.name.Name + left: dns.name.Name + right: dns.name.Name | None + closest_encloser: dns.name.Name + is_equal: bool + is_delegation: bool + + def __str__(self): + if self.is_equal: + op = "=" + else: + op = "<" + if self.is_delegation: + zonecut = " zonecut" + else: + zonecut = "" + return ( + f"{self.left} {op} {self.name} < {self.right}{zonecut}; " + f"{self.closest_encloser}" + ) + + +@dns.immutable.immutable +class ImmutableVersion(dns.zone.Version): + def __init__(self, version: dns.zone.Version): + if not isinstance(version, WritableVersion): + raise ValueError( + "a dns.btreezone.ImmutableVersion requires a " + "dns.btreezone.WritableVersion" + ) + super().__init__(version.zone, True) + self.id = version.id + self.origin = version.origin + for name in version.changed: + node = version.nodes.get(name) + if node: + version.nodes[name] = ImmutableNode(node) + # the cast below is for mypy + self.nodes = cast(MutableMapping[dns.name.Name, dns.node.Node], version.nodes) + self.nodes.make_immutable() # type: ignore + self.delegations = version.delegations + self.delegations.make_immutable() + + def bounds(self, name: dns.name.Name | str) -> Bounds: + """Return the 'bounds' of *name* in its zone. + + The bounds information is useful when making an authoritative response, as + it can be used to determine whether the query name is at or beneath a delegation + point. The other data in the ``Bounds`` object is useful for making on-the-fly + DNSSEC signatures. + + The left bound of *name* is *name* itself if it is in the zone, or the greatest + predecessor which is in the zone. + + The right bound of *name* is the least successor of *name*, or ``None`` if + no name in the zone is greater than *name*. + + The closest encloser of *name* is *name* itself, if *name* is in the zone; + otherwise it is the name with the largest number of labels in common with + *name* that is in the zone, either explicitly or by the implied existence + of empty non-terminals. + + The bounds *is_equal* field is ``True`` if and only if *name* is equal to + its left bound. + + The bounds *is_delegation* field is ``True`` if and only if the left bound is a + delegation point. + """ + assert self.origin is not None + # validate the origin because we may need to relativize + origin = self.zone._validate_name(self.origin) + name = self.zone._validate_name(name) + cut, _ = self.delegations.get_delegation(name) + if cut is not None: + target = cut + is_delegation = True + else: + target = name + is_delegation = False + c = cast(dns.btree.BTreeDict, self.nodes).cursor() + c.seek(target, False) + left = c.prev() + assert left is not None + c.next() # skip over left + while True: + right = c.next() + if right is None or not right.value().is_glue(): + break + left_comparison = left.key().fullcompare(name) + if right is not None: + right_key = right.key() + right_comparison = right_key.fullcompare(name) + else: + right_comparison = ( + dns.name.NAMERELN_COMMONANCESTOR, + -1, + len(origin), + ) + right_key = None + closest_encloser = dns.name.Name( + name[-max(left_comparison[2], right_comparison[2]) :] + ) + return Bounds( + name, + left.key(), + right_key, + closest_encloser, + left_comparison[0] == dns.name.NameRelation.EQUAL, + is_delegation, + ) + + +class Zone(dns.versioned.Zone): + node_factory: Callable[[], dns.node.Node] = Node + map_factory: Callable[[], MutableMapping[dns.name.Name, dns.node.Node]] = cast( + Callable[[], MutableMapping[dns.name.Name, dns.node.Node]], + dns.btree.BTreeDict[dns.name.Name, Node], + ) + writable_version_factory: ( + Callable[[dns.zone.Zone, bool], dns.zone.Version] | None + ) = WritableVersion + immutable_version_factory: Callable[[dns.zone.Version], dns.zone.Version] | None = ( + ImmutableVersion + ) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/dnssec.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/dnssec.py new file mode 100644 index 000000000..6b166745f --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/dnssec.py @@ -0,0 +1,1242 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +# Copyright (C) 2003-2017 Nominum, Inc. +# +# Permission to use, copy, modify, and distribute this software and its +# documentation for any purpose with or without fee is hereby granted, +# provided that the above copyright notice and this permission notice +# appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +"""Common DNSSEC-related functions and constants.""" + +# pylint: disable=unused-import + +import base64 +import contextlib +import functools +import hashlib +import struct +import time +from datetime import datetime +from typing import Callable, Dict, List, Set, Tuple, Union, cast + +import dns._features +import dns.name +import dns.node +import dns.rdata +import dns.rdataclass +import dns.rdataset +import dns.rdatatype +import dns.rrset +import dns.transaction +import dns.zone +from dns.dnssectypes import Algorithm, DSDigest, NSEC3Hash +from dns.exception import AlgorithmKeyMismatch as AlgorithmKeyMismatch +from dns.exception import DeniedByPolicy, UnsupportedAlgorithm, ValidationFailure +from dns.rdtypes.ANY.CDNSKEY import CDNSKEY +from dns.rdtypes.ANY.CDS import CDS +from dns.rdtypes.ANY.DNSKEY import DNSKEY +from dns.rdtypes.ANY.DS import DS +from dns.rdtypes.ANY.NSEC import NSEC, Bitmap +from dns.rdtypes.ANY.NSEC3PARAM import NSEC3PARAM +from dns.rdtypes.ANY.RRSIG import RRSIG, sigtime_to_posixtime +from dns.rdtypes.dnskeybase import Flag + +PublicKey = Union[ + "GenericPublicKey", + "rsa.RSAPublicKey", + "ec.EllipticCurvePublicKey", + "ed25519.Ed25519PublicKey", + "ed448.Ed448PublicKey", +] + +PrivateKey = Union[ + "GenericPrivateKey", + "rsa.RSAPrivateKey", + "ec.EllipticCurvePrivateKey", + "ed25519.Ed25519PrivateKey", + "ed448.Ed448PrivateKey", +] + +RRsetSigner = Callable[[dns.transaction.Transaction, dns.rrset.RRset], None] + + +def algorithm_from_text(text: str) -> Algorithm: + """Convert text into a DNSSEC algorithm value. + + *text*, a ``str``, the text to convert to into an algorithm value. + + Returns an ``int``. + """ + + return Algorithm.from_text(text) + + +def algorithm_to_text(value: Algorithm | int) -> str: + """Convert a DNSSEC algorithm value to text + + *value*, a ``dns.dnssec.Algorithm``. + + Returns a ``str``, the name of a DNSSEC algorithm. + """ + + return Algorithm.to_text(value) + + +def to_timestamp(value: datetime | str | float | int) -> int: + """Convert various format to a timestamp""" + if isinstance(value, datetime): + return int(value.timestamp()) + elif isinstance(value, str): + return sigtime_to_posixtime(value) + elif isinstance(value, float): + return int(value) + elif isinstance(value, int): + return value + else: + raise TypeError("Unsupported timestamp type") + + +def key_id(key: DNSKEY | CDNSKEY) -> int: + """Return the key id (a 16-bit number) for the specified key. + + *key*, a ``dns.rdtypes.ANY.DNSKEY.DNSKEY`` + + Returns an ``int`` between 0 and 65535 + """ + + rdata = key.to_wire() + assert rdata is not None # for mypy + if key.algorithm == Algorithm.RSAMD5: + return (rdata[-3] << 8) + rdata[-2] + else: + total = 0 + for i in range(len(rdata) // 2): + total += (rdata[2 * i] << 8) + rdata[2 * i + 1] + if len(rdata) % 2 != 0: + total += rdata[len(rdata) - 1] << 8 + total += (total >> 16) & 0xFFFF + return total & 0xFFFF + + +class Policy: + def __init__(self): + pass + + def ok_to_sign(self, key: DNSKEY) -> bool: # pragma: no cover + return False + + def ok_to_validate(self, key: DNSKEY) -> bool: # pragma: no cover + return False + + def ok_to_create_ds(self, algorithm: DSDigest) -> bool: # pragma: no cover + return False + + def ok_to_validate_ds(self, algorithm: DSDigest) -> bool: # pragma: no cover + return False + + +class SimpleDeny(Policy): + def __init__(self, deny_sign, deny_validate, deny_create_ds, deny_validate_ds): + super().__init__() + self._deny_sign = deny_sign + self._deny_validate = deny_validate + self._deny_create_ds = deny_create_ds + self._deny_validate_ds = deny_validate_ds + + def ok_to_sign(self, key: DNSKEY) -> bool: + return key.algorithm not in self._deny_sign + + def ok_to_validate(self, key: DNSKEY) -> bool: + return key.algorithm not in self._deny_validate + + def ok_to_create_ds(self, algorithm: DSDigest) -> bool: + return algorithm not in self._deny_create_ds + + def ok_to_validate_ds(self, algorithm: DSDigest) -> bool: + return algorithm not in self._deny_validate_ds + + +rfc_8624_policy = SimpleDeny( + {Algorithm.RSAMD5, Algorithm.DSA, Algorithm.DSANSEC3SHA1, Algorithm.ECCGOST}, + {Algorithm.RSAMD5, Algorithm.DSA, Algorithm.DSANSEC3SHA1}, + {DSDigest.NULL, DSDigest.SHA1, DSDigest.GOST}, + {DSDigest.NULL}, +) + +allow_all_policy = SimpleDeny(set(), set(), set(), set()) + + +default_policy = rfc_8624_policy + + +def make_ds( + name: dns.name.Name | str, + key: dns.rdata.Rdata, + algorithm: DSDigest | str, + origin: dns.name.Name | None = None, + policy: Policy | None = None, + validating: bool = False, +) -> DS: + """Create a DS record for a DNSSEC key. + + *name*, a ``dns.name.Name`` or ``str``, the owner name of the DS record. + + *key*, a ``dns.rdtypes.ANY.DNSKEY.DNSKEY`` or ``dns.rdtypes.ANY.DNSKEY.CDNSKEY``, + the key the DS is about. + + *algorithm*, a ``str`` or ``int`` specifying the hash algorithm. + The currently supported hashes are "SHA1", "SHA256", and "SHA384". Case + does not matter for these strings. + + *origin*, a ``dns.name.Name`` or ``None``. If *key* is a relative name, + then it will be made absolute using the specified origin. + + *policy*, a ``dns.dnssec.Policy`` or ``None``. If ``None``, the default policy, + ``dns.dnssec.default_policy`` is used; this policy defaults to that of RFC 8624. + + *validating*, a ``bool``. If ``True``, then policy is checked in + validating mode, i.e. "Is it ok to validate using this digest algorithm?". + Otherwise the policy is checked in creating mode, i.e. "Is it ok to create a DS with + this digest algorithm?". + + Raises ``UnsupportedAlgorithm`` if the algorithm is unknown. + + Raises ``DeniedByPolicy`` if the algorithm is denied by policy. + + Returns a ``dns.rdtypes.ANY.DS.DS`` + """ + + if policy is None: + policy = default_policy + try: + if isinstance(algorithm, str): + algorithm = DSDigest[algorithm.upper()] + except Exception: + raise UnsupportedAlgorithm(f'unsupported algorithm "{algorithm}"') + if validating: + check = policy.ok_to_validate_ds + else: + check = policy.ok_to_create_ds + if not check(algorithm): + raise DeniedByPolicy + if not isinstance(key, DNSKEY | CDNSKEY): + raise ValueError("key is not a DNSKEY | CDNSKEY") + if algorithm == DSDigest.SHA1: + dshash = hashlib.sha1(usedforsecurity=False) + elif algorithm == DSDigest.SHA256: + dshash = hashlib.sha256() + elif algorithm == DSDigest.SHA384: + dshash = hashlib.sha384() + else: + raise UnsupportedAlgorithm(f'unsupported algorithm "{algorithm}"') + + if isinstance(name, str): + name = dns.name.from_text(name, origin) + wire = name.canonicalize().to_wire() + kwire = key.to_wire(origin=origin) + assert wire is not None and kwire is not None # for mypy + dshash.update(wire) + dshash.update(kwire) + digest = dshash.digest() + + dsrdata = struct.pack("!HBB", key_id(key), key.algorithm, algorithm) + digest + ds = dns.rdata.from_wire( + dns.rdataclass.IN, dns.rdatatype.DS, dsrdata, 0, len(dsrdata) + ) + return cast(DS, ds) + + +def make_cds( + name: dns.name.Name | str, + key: dns.rdata.Rdata, + algorithm: DSDigest | str, + origin: dns.name.Name | None = None, +) -> CDS: + """Create a CDS record for a DNSSEC key. + + *name*, a ``dns.name.Name`` or ``str``, the owner name of the DS record. + + *key*, a ``dns.rdtypes.ANY.DNSKEY.DNSKEY`` or ``dns.rdtypes.ANY.DNSKEY.CDNSKEY``, + the key the DS is about. + + *algorithm*, a ``str`` or ``int`` specifying the hash algorithm. + The currently supported hashes are "SHA1", "SHA256", and "SHA384". Case + does not matter for these strings. + + *origin*, a ``dns.name.Name`` or ``None``. If *key* is a relative name, + then it will be made absolute using the specified origin. + + Raises ``UnsupportedAlgorithm`` if the algorithm is unknown. + + Returns a ``dns.rdtypes.ANY.DS.CDS`` + """ + + ds = make_ds(name, key, algorithm, origin) + return CDS( + rdclass=ds.rdclass, + rdtype=dns.rdatatype.CDS, + key_tag=ds.key_tag, + algorithm=ds.algorithm, + digest_type=ds.digest_type, + digest=ds.digest, + ) + + +def _find_candidate_keys( + keys: Dict[dns.name.Name, dns.rdataset.Rdataset | dns.node.Node], rrsig: RRSIG +) -> List[DNSKEY] | None: + value = keys.get(rrsig.signer) + if isinstance(value, dns.node.Node): + rdataset = value.get_rdataset(dns.rdataclass.IN, dns.rdatatype.DNSKEY) + else: + rdataset = value + if rdataset is None: + return None + return [ + cast(DNSKEY, rd) + for rd in rdataset + if rd.algorithm == rrsig.algorithm + and key_id(rd) == rrsig.key_tag + and (rd.flags & Flag.ZONE) == Flag.ZONE # RFC 4034 2.1.1 + and rd.protocol == 3 # RFC 4034 2.1.2 + ] + + +def _get_rrname_rdataset( + rrset: dns.rrset.RRset | Tuple[dns.name.Name, dns.rdataset.Rdataset], +) -> Tuple[dns.name.Name, dns.rdataset.Rdataset]: + if isinstance(rrset, tuple): + return rrset[0], rrset[1] + else: + return rrset.name, rrset + + +def _validate_signature(sig: bytes, data: bytes, key: DNSKEY) -> None: + # pylint: disable=possibly-used-before-assignment + public_cls = get_algorithm_cls_from_dnskey(key).public_cls + try: + public_key = public_cls.from_dnskey(key) + except ValueError: + raise ValidationFailure("invalid public key") + public_key.verify(sig, data) + + +def _validate_rrsig( + rrset: dns.rrset.RRset | Tuple[dns.name.Name, dns.rdataset.Rdataset], + rrsig: RRSIG, + keys: Dict[dns.name.Name, dns.node.Node | dns.rdataset.Rdataset], + origin: dns.name.Name | None = None, + now: float | None = None, + policy: Policy | None = None, +) -> None: + """Validate an RRset against a single signature rdata, throwing an + exception if validation is not successful. + + *rrset*, the RRset to validate. This can be a + ``dns.rrset.RRset`` or a (``dns.name.Name``, ``dns.rdataset.Rdataset``) + tuple. + + *rrsig*, a ``dns.rdata.Rdata``, the signature to validate. + + *keys*, the key dictionary, used to find the DNSKEY associated + with a given name. The dictionary is keyed by a + ``dns.name.Name``, and has ``dns.node.Node`` or + ``dns.rdataset.Rdataset`` values. + + *origin*, a ``dns.name.Name`` or ``None``, the origin to use for relative + names. + + *now*, a ``float`` or ``None``, the time, in seconds since the epoch, to + use as the current time when validating. If ``None``, the actual current + time is used. + + *policy*, a ``dns.dnssec.Policy`` or ``None``. If ``None``, the default policy, + ``dns.dnssec.default_policy`` is used; this policy defaults to that of RFC 8624. + + Raises ``ValidationFailure`` if the signature is expired, not yet valid, + the public key is invalid, the algorithm is unknown, the verification + fails, etc. + + Raises ``UnsupportedAlgorithm`` if the algorithm is recognized by + dnspython but not implemented. + """ + + if policy is None: + policy = default_policy + + candidate_keys = _find_candidate_keys(keys, rrsig) + if candidate_keys is None: + raise ValidationFailure("unknown key") + + if now is None: + now = time.time() + if rrsig.expiration < now: + raise ValidationFailure("expired") + if rrsig.inception > now: + raise ValidationFailure("not yet valid") + + data = _make_rrsig_signature_data(rrset, rrsig, origin) + + # pylint: disable=possibly-used-before-assignment + for candidate_key in candidate_keys: + if not policy.ok_to_validate(candidate_key): + continue + try: + _validate_signature(rrsig.signature, data, candidate_key) + return + except (InvalidSignature, ValidationFailure): + # this happens on an individual validation failure + continue + # nothing verified -- raise failure: + raise ValidationFailure("verify failure") + + +def _validate( + rrset: dns.rrset.RRset | Tuple[dns.name.Name, dns.rdataset.Rdataset], + rrsigset: dns.rrset.RRset | Tuple[dns.name.Name, dns.rdataset.Rdataset], + keys: Dict[dns.name.Name, dns.node.Node | dns.rdataset.Rdataset], + origin: dns.name.Name | None = None, + now: float | None = None, + policy: Policy | None = None, +) -> None: + """Validate an RRset against a signature RRset, throwing an exception + if none of the signatures validate. + + *rrset*, the RRset to validate. This can be a + ``dns.rrset.RRset`` or a (``dns.name.Name``, ``dns.rdataset.Rdataset``) + tuple. + + *rrsigset*, the signature RRset. This can be a + ``dns.rrset.RRset`` or a (``dns.name.Name``, ``dns.rdataset.Rdataset``) + tuple. + + *keys*, the key dictionary, used to find the DNSKEY associated + with a given name. The dictionary is keyed by a + ``dns.name.Name``, and has ``dns.node.Node`` or + ``dns.rdataset.Rdataset`` values. + + *origin*, a ``dns.name.Name``, the origin to use for relative names; + defaults to None. + + *now*, an ``int`` or ``None``, the time, in seconds since the epoch, to + use as the current time when validating. If ``None``, the actual current + time is used. + + *policy*, a ``dns.dnssec.Policy`` or ``None``. If ``None``, the default policy, + ``dns.dnssec.default_policy`` is used; this policy defaults to that of RFC 8624. + + Raises ``ValidationFailure`` if the signature is expired, not yet valid, + the public key is invalid, the algorithm is unknown, the verification + fails, etc. + """ + + if policy is None: + policy = default_policy + + if isinstance(origin, str): + origin = dns.name.from_text(origin, dns.name.root) + + if isinstance(rrset, tuple): + rrname = rrset[0] + else: + rrname = rrset.name + + if isinstance(rrsigset, tuple): + rrsigname = rrsigset[0] + rrsigrdataset = rrsigset[1] + else: + rrsigname = rrsigset.name + rrsigrdataset = rrsigset + + rrname = rrname.choose_relativity(origin) + rrsigname = rrsigname.choose_relativity(origin) + if rrname != rrsigname: + raise ValidationFailure("owner names do not match") + + for rrsig in rrsigrdataset: + if not isinstance(rrsig, RRSIG): + raise ValidationFailure("expected an RRSIG") + try: + _validate_rrsig(rrset, rrsig, keys, origin, now, policy) + return + except (ValidationFailure, UnsupportedAlgorithm): + pass + raise ValidationFailure("no RRSIGs validated") + + +def _sign( + rrset: dns.rrset.RRset | Tuple[dns.name.Name, dns.rdataset.Rdataset], + private_key: PrivateKey, + signer: dns.name.Name, + dnskey: DNSKEY, + inception: datetime | str | int | float | None = None, + expiration: datetime | str | int | float | None = None, + lifetime: int | None = None, + verify: bool = False, + policy: Policy | None = None, + origin: dns.name.Name | None = None, + deterministic: bool = True, +) -> RRSIG: + """Sign RRset using private key. + + *rrset*, the RRset to validate. This can be a + ``dns.rrset.RRset`` or a (``dns.name.Name``, ``dns.rdataset.Rdataset``) + tuple. + + *private_key*, the private key to use for signing, a + ``cryptography.hazmat.primitives.asymmetric`` private key class applicable + for DNSSEC. + + *signer*, a ``dns.name.Name``, the Signer's name. + + *dnskey*, a ``DNSKEY`` matching ``private_key``. + + *inception*, a ``datetime``, ``str``, ``int``, ``float`` or ``None``, the + signature inception time. If ``None``, the current time is used. If a ``str``, the + format is "YYYYMMDDHHMMSS" or alternatively the number of seconds since the UNIX + epoch in text form; this is the same the RRSIG rdata's text form. + Values of type `int` or `float` are interpreted as seconds since the UNIX epoch. + + *expiration*, a ``datetime``, ``str``, ``int``, ``float`` or ``None``, the signature + expiration time. If ``None``, the expiration time will be the inception time plus + the value of the *lifetime* parameter. See the description of *inception* above + for how the various parameter types are interpreted. + + *lifetime*, an ``int`` or ``None``, the signature lifetime in seconds. This + parameter is only meaningful if *expiration* is ``None``. + + *verify*, a ``bool``. If set to ``True``, the signer will verify signatures + after they are created; the default is ``False``. + + *policy*, a ``dns.dnssec.Policy`` or ``None``. If ``None``, the default policy, + ``dns.dnssec.default_policy`` is used; this policy defaults to that of RFC 8624. + + *origin*, a ``dns.name.Name`` or ``None``. If ``None``, the default, then all + names in the rrset (including its owner name) must be absolute; otherwise the + specified origin will be used to make names absolute when signing. + + *deterministic*, a ``bool``. If ``True``, the default, use deterministic + (reproducible) signatures when supported by the algorithm used for signing. + Currently, this only affects ECDSA. + + Raises ``DeniedByPolicy`` if the signature is denied by policy. + """ + + if policy is None: + policy = default_policy + if not policy.ok_to_sign(dnskey): + raise DeniedByPolicy + + if isinstance(rrset, tuple): + rdclass = rrset[1].rdclass + rdtype = rrset[1].rdtype + rrname = rrset[0] + original_ttl = rrset[1].ttl + else: + rdclass = rrset.rdclass + rdtype = rrset.rdtype + rrname = rrset.name + original_ttl = rrset.ttl + + if inception is not None: + rrsig_inception = to_timestamp(inception) + else: + rrsig_inception = int(time.time()) + + if expiration is not None: + rrsig_expiration = to_timestamp(expiration) + elif lifetime is not None: + rrsig_expiration = rrsig_inception + lifetime + else: + raise ValueError("expiration or lifetime must be specified") + + # Derelativize now because we need a correct labels length for the + # rrsig_template. + if origin is not None: + rrname = rrname.derelativize(origin) + labels = len(rrname) - 1 + + # Adjust labels appropriately for wildcards. + if rrname.is_wild(): + labels -= 1 + + rrsig_template = RRSIG( + rdclass=rdclass, + rdtype=dns.rdatatype.RRSIG, + type_covered=rdtype, + algorithm=dnskey.algorithm, + labels=labels, + original_ttl=original_ttl, + expiration=rrsig_expiration, + inception=rrsig_inception, + key_tag=key_id(dnskey), + signer=signer, + signature=b"", + ) + + data = _make_rrsig_signature_data(rrset, rrsig_template, origin) + + # pylint: disable=possibly-used-before-assignment + if isinstance(private_key, GenericPrivateKey): + signing_key = private_key + else: + try: + private_cls = get_algorithm_cls_from_dnskey(dnskey) + signing_key = private_cls(key=private_key) + except UnsupportedAlgorithm: + raise TypeError("Unsupported key algorithm") + + signature = signing_key.sign(data, verify, deterministic) + + return cast(RRSIG, rrsig_template.replace(signature=signature)) + + +def _make_rrsig_signature_data( + rrset: dns.rrset.RRset | Tuple[dns.name.Name, dns.rdataset.Rdataset], + rrsig: RRSIG, + origin: dns.name.Name | None = None, +) -> bytes: + """Create signature rdata. + + *rrset*, the RRset to sign/validate. This can be a + ``dns.rrset.RRset`` or a (``dns.name.Name``, ``dns.rdataset.Rdataset``) + tuple. + + *rrsig*, a ``dns.rdata.Rdata``, the signature to validate, or the + signature template used when signing. + + *origin*, a ``dns.name.Name`` or ``None``, the origin to use for relative + names. + + Raises ``UnsupportedAlgorithm`` if the algorithm is recognized by + dnspython but not implemented. + """ + + if isinstance(origin, str): + origin = dns.name.from_text(origin, dns.name.root) + + signer = rrsig.signer + if not signer.is_absolute(): + if origin is None: + raise ValidationFailure("relative RR name without an origin specified") + signer = signer.derelativize(origin) + + # For convenience, allow the rrset to be specified as a (name, + # rdataset) tuple as well as a proper rrset + rrname, rdataset = _get_rrname_rdataset(rrset) + + data = b"" + wire = rrsig.to_wire(origin=signer) + assert wire is not None # for mypy + data += wire[:18] + data += rrsig.signer.to_digestable(signer) + + # Derelativize the name before considering labels. + if not rrname.is_absolute(): + if origin is None: + raise ValidationFailure("relative RR name without an origin specified") + rrname = rrname.derelativize(origin) + + name_len = len(rrname) + if rrname.is_wild() and rrsig.labels != name_len - 2: + raise ValidationFailure("wild owner name has wrong label length") + if name_len - 1 < rrsig.labels: + raise ValidationFailure("owner name longer than RRSIG labels") + elif rrsig.labels < name_len - 1: + suffix = rrname.split(rrsig.labels + 1)[1] + rrname = dns.name.from_text("*", suffix) + rrnamebuf = rrname.to_digestable() + rrfixed = struct.pack("!HHI", rdataset.rdtype, rdataset.rdclass, rrsig.original_ttl) + rdatas = [rdata.to_digestable(origin) for rdata in rdataset] + for rdata in sorted(rdatas): + data += rrnamebuf + data += rrfixed + rrlen = struct.pack("!H", len(rdata)) + data += rrlen + data += rdata + + return data + + +def _make_dnskey( + public_key: PublicKey, + algorithm: int | str, + flags: int = Flag.ZONE, + protocol: int = 3, +) -> DNSKEY: + """Convert a public key to DNSKEY Rdata + + *public_key*, a ``PublicKey`` (``GenericPublicKey`` or + ``cryptography.hazmat.primitives.asymmetric``) to convert. + + *algorithm*, a ``str`` or ``int`` specifying the DNSKEY algorithm. + + *flags*: DNSKEY flags field as an integer. + + *protocol*: DNSKEY protocol field as an integer. + + Raises ``ValueError`` if the specified key algorithm parameters are not + unsupported, ``TypeError`` if the key type is unsupported, + `UnsupportedAlgorithm` if the algorithm is unknown and + `AlgorithmKeyMismatch` if the algorithm does not match the key type. + + Return DNSKEY ``Rdata``. + """ + + algorithm = Algorithm.make(algorithm) + + # pylint: disable=possibly-used-before-assignment + if isinstance(public_key, GenericPublicKey): + return public_key.to_dnskey(flags=flags, protocol=protocol) + else: + public_cls = get_algorithm_cls(algorithm).public_cls + return public_cls(key=public_key).to_dnskey(flags=flags, protocol=protocol) + + +def _make_cdnskey( + public_key: PublicKey, + algorithm: int | str, + flags: int = Flag.ZONE, + protocol: int = 3, +) -> CDNSKEY: + """Convert a public key to CDNSKEY Rdata + + *public_key*, the public key to convert, a + ``cryptography.hazmat.primitives.asymmetric`` public key class applicable + for DNSSEC. + + *algorithm*, a ``str`` or ``int`` specifying the DNSKEY algorithm. + + *flags*: DNSKEY flags field as an integer. + + *protocol*: DNSKEY protocol field as an integer. + + Raises ``ValueError`` if the specified key algorithm parameters are not + unsupported, ``TypeError`` if the key type is unsupported, + `UnsupportedAlgorithm` if the algorithm is unknown and + `AlgorithmKeyMismatch` if the algorithm does not match the key type. + + Return CDNSKEY ``Rdata``. + """ + + dnskey = _make_dnskey(public_key, algorithm, flags, protocol) + + return CDNSKEY( + rdclass=dnskey.rdclass, + rdtype=dns.rdatatype.CDNSKEY, + flags=dnskey.flags, + protocol=dnskey.protocol, + algorithm=dnskey.algorithm, + key=dnskey.key, + ) + + +def nsec3_hash( + domain: dns.name.Name | str, + salt: str | bytes | None, + iterations: int, + algorithm: int | str, +) -> str: + """ + Calculate the NSEC3 hash, according to + https://tools.ietf.org/html/rfc5155#section-5 + + *domain*, a ``dns.name.Name`` or ``str``, the name to hash. + + *salt*, a ``str``, ``bytes``, or ``None``, the hash salt. If a + string, it is decoded as a hex string. + + *iterations*, an ``int``, the number of iterations. + + *algorithm*, a ``str`` or ``int``, the hash algorithm. + The only defined algorithm is SHA1. + + Returns a ``str``, the encoded NSEC3 hash. + """ + + b32_conversion = str.maketrans( + "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567", "0123456789ABCDEFGHIJKLMNOPQRSTUV" + ) + + try: + if isinstance(algorithm, str): + algorithm = NSEC3Hash[algorithm.upper()] + except Exception: + raise ValueError("Wrong hash algorithm (only SHA1 is supported)") + + if algorithm != NSEC3Hash.SHA1: + raise ValueError("Wrong hash algorithm (only SHA1 is supported)") + + if salt is None: + salt_encoded = b"" + elif isinstance(salt, str): + if len(salt) % 2 == 0: + salt_encoded = bytes.fromhex(salt) + else: + raise ValueError("Invalid salt length") + else: + salt_encoded = salt + + if not isinstance(domain, dns.name.Name): + domain = dns.name.from_text(domain) + domain_encoded = domain.canonicalize().to_wire() + assert domain_encoded is not None + + digest = hashlib.sha1(domain_encoded + salt_encoded, usedforsecurity=False).digest() + for _ in range(iterations): + digest = hashlib.sha1(digest + salt_encoded, usedforsecurity = False).digest() + + output = base64.b32encode(digest).decode("utf-8") + output = output.translate(b32_conversion) + + return output + + +def make_ds_rdataset( + rrset: dns.rrset.RRset | Tuple[dns.name.Name, dns.rdataset.Rdataset], + algorithms: Set[DSDigest | str], + origin: dns.name.Name | None = None, +) -> dns.rdataset.Rdataset: + """Create a DS record from DNSKEY/CDNSKEY/CDS. + + *rrset*, the RRset to create DS Rdataset for. This can be a + ``dns.rrset.RRset`` or a (``dns.name.Name``, ``dns.rdataset.Rdataset``) + tuple. + + *algorithms*, a set of ``str`` or ``int`` specifying the hash algorithms. + The currently supported hashes are "SHA1", "SHA256", and "SHA384". Case + does not matter for these strings. If the RRset is a CDS, only digest + algorithms matching algorithms are accepted. + + *origin*, a ``dns.name.Name`` or ``None``. If `key` is a relative name, + then it will be made absolute using the specified origin. + + Raises ``UnsupportedAlgorithm`` if any of the algorithms are unknown and + ``ValueError`` if the given RRset is not usable. + + Returns a ``dns.rdataset.Rdataset`` + """ + + rrname, rdataset = _get_rrname_rdataset(rrset) + + if rdataset.rdtype not in ( + dns.rdatatype.DNSKEY, + dns.rdatatype.CDNSKEY, + dns.rdatatype.CDS, + ): + raise ValueError("rrset not a DNSKEY/CDNSKEY/CDS") + + _algorithms = set() + for algorithm in algorithms: + try: + if isinstance(algorithm, str): + algorithm = DSDigest[algorithm.upper()] + except Exception: + raise UnsupportedAlgorithm(f'unsupported algorithm "{algorithm}"') + _algorithms.add(algorithm) + + if rdataset.rdtype == dns.rdatatype.CDS: + res = [] + for rdata in cds_rdataset_to_ds_rdataset(rdataset): + if rdata.digest_type in _algorithms: + res.append(rdata) + if len(res) == 0: + raise ValueError("no acceptable CDS rdata found") + return dns.rdataset.from_rdata_list(rdataset.ttl, res) + + res = [] + for algorithm in _algorithms: + res.extend(dnskey_rdataset_to_cds_rdataset(rrname, rdataset, algorithm, origin)) + return dns.rdataset.from_rdata_list(rdataset.ttl, res) + + +def cds_rdataset_to_ds_rdataset( + rdataset: dns.rdataset.Rdataset, +) -> dns.rdataset.Rdataset: + """Create a CDS record from DS. + + *rdataset*, a ``dns.rdataset.Rdataset``, to create DS Rdataset for. + + Raises ``ValueError`` if the rdataset is not CDS. + + Returns a ``dns.rdataset.Rdataset`` + """ + + if rdataset.rdtype != dns.rdatatype.CDS: + raise ValueError("rdataset not a CDS") + res = [] + for rdata in rdataset: + res.append( + CDS( + rdclass=rdata.rdclass, + rdtype=dns.rdatatype.DS, + key_tag=rdata.key_tag, + algorithm=rdata.algorithm, + digest_type=rdata.digest_type, + digest=rdata.digest, + ) + ) + return dns.rdataset.from_rdata_list(rdataset.ttl, res) + + +def dnskey_rdataset_to_cds_rdataset( + name: dns.name.Name | str, + rdataset: dns.rdataset.Rdataset, + algorithm: DSDigest | str, + origin: dns.name.Name | None = None, +) -> dns.rdataset.Rdataset: + """Create a CDS record from DNSKEY/CDNSKEY. + + *name*, a ``dns.name.Name`` or ``str``, the owner name of the CDS record. + + *rdataset*, a ``dns.rdataset.Rdataset``, to create DS Rdataset for. + + *algorithm*, a ``str`` or ``int`` specifying the hash algorithm. + The currently supported hashes are "SHA1", "SHA256", and "SHA384". Case + does not matter for these strings. + + *origin*, a ``dns.name.Name`` or ``None``. If `key` is a relative name, + then it will be made absolute using the specified origin. + + Raises ``UnsupportedAlgorithm`` if the algorithm is unknown or + ``ValueError`` if the rdataset is not DNSKEY/CDNSKEY. + + Returns a ``dns.rdataset.Rdataset`` + """ + + if rdataset.rdtype not in (dns.rdatatype.DNSKEY, dns.rdatatype.CDNSKEY): + raise ValueError("rdataset not a DNSKEY/CDNSKEY") + res = [] + for rdata in rdataset: + res.append(make_cds(name, rdata, algorithm, origin)) + return dns.rdataset.from_rdata_list(rdataset.ttl, res) + + +def dnskey_rdataset_to_cdnskey_rdataset( + rdataset: dns.rdataset.Rdataset, +) -> dns.rdataset.Rdataset: + """Create a CDNSKEY record from DNSKEY. + + *rdataset*, a ``dns.rdataset.Rdataset``, to create CDNSKEY Rdataset for. + + Returns a ``dns.rdataset.Rdataset`` + """ + + if rdataset.rdtype != dns.rdatatype.DNSKEY: + raise ValueError("rdataset not a DNSKEY") + res = [] + for rdata in rdataset: + res.append( + CDNSKEY( + rdclass=rdataset.rdclass, + rdtype=rdataset.rdtype, + flags=rdata.flags, + protocol=rdata.protocol, + algorithm=rdata.algorithm, + key=rdata.key, + ) + ) + return dns.rdataset.from_rdata_list(rdataset.ttl, res) + + +def default_rrset_signer( + txn: dns.transaction.Transaction, + rrset: dns.rrset.RRset, + signer: dns.name.Name, + ksks: List[Tuple[PrivateKey, DNSKEY]], + zsks: List[Tuple[PrivateKey, DNSKEY]], + inception: datetime | str | int | float | None = None, + expiration: datetime | str | int | float | None = None, + lifetime: int | None = None, + policy: Policy | None = None, + origin: dns.name.Name | None = None, + deterministic: bool = True, +) -> None: + """Default RRset signer""" + + if rrset.rdtype in set( + [ + dns.rdatatype.RdataType.DNSKEY, + dns.rdatatype.RdataType.CDS, + dns.rdatatype.RdataType.CDNSKEY, + ] + ): + keys = ksks + else: + keys = zsks + + for private_key, dnskey in keys: + rrsig = sign( + rrset=rrset, + private_key=private_key, + dnskey=dnskey, + inception=inception, + expiration=expiration, + lifetime=lifetime, + signer=signer, + policy=policy, + origin=origin, + deterministic=deterministic, + ) + txn.add(rrset.name, rrset.ttl, rrsig) + + +def sign_zone( + zone: dns.zone.Zone, + txn: dns.transaction.Transaction | None = None, + keys: List[Tuple[PrivateKey, DNSKEY]] | None = None, + add_dnskey: bool = True, + dnskey_ttl: int | None = None, + inception: datetime | str | int | float | None = None, + expiration: datetime | str | int | float | None = None, + lifetime: int | None = None, + nsec3: NSEC3PARAM | None = None, + rrset_signer: RRsetSigner | None = None, + policy: Policy | None = None, + deterministic: bool = True, +) -> None: + """Sign zone. + + *zone*, a ``dns.zone.Zone``, the zone to sign. + + *txn*, a ``dns.transaction.Transaction``, an optional transaction to use for + signing. + + *keys*, a list of (``PrivateKey``, ``DNSKEY``) tuples, to use for signing. KSK/ZSK + roles are assigned automatically if the SEP flag is used, otherwise all RRsets are + signed by all keys. + + *add_dnskey*, a ``bool``. If ``True``, the default, all specified DNSKEYs are + automatically added to the zone on signing. + + *dnskey_ttl*, a``int``, specifies the TTL for DNSKEY RRs. If not specified the TTL + of the existing DNSKEY RRset used or the TTL of the SOA RRset. + + *inception*, a ``datetime``, ``str``, ``int``, ``float`` or ``None``, the signature + inception time. If ``None``, the current time is used. If a ``str``, the format is + "YYYYMMDDHHMMSS" or alternatively the number of seconds since the UNIX epoch in text + form; this is the same the RRSIG rdata's text form. Values of type `int` or `float` + are interpreted as seconds since the UNIX epoch. + + *expiration*, a ``datetime``, ``str``, ``int``, ``float`` or ``None``, the signature + expiration time. If ``None``, the expiration time will be the inception time plus + the value of the *lifetime* parameter. See the description of *inception* above for + how the various parameter types are interpreted. + + *lifetime*, an ``int`` or ``None``, the signature lifetime in seconds. This + parameter is only meaningful if *expiration* is ``None``. + + *nsec3*, a ``NSEC3PARAM`` Rdata, configures signing using NSEC3. Not yet + implemented. + + *rrset_signer*, a ``Callable``, an optional function for signing RRsets. The + function requires two arguments: transaction and RRset. If the not specified, + ``dns.dnssec.default_rrset_signer`` will be used. + + *deterministic*, a ``bool``. If ``True``, the default, use deterministic + (reproducible) signatures when supported by the algorithm used for signing. + Currently, this only affects ECDSA. + + Returns ``None``. + """ + + ksks = [] + zsks = [] + + # if we have both KSKs and ZSKs, split by SEP flag. if not, sign all + # records with all keys + if keys: + for key in keys: + if key[1].flags & Flag.SEP: + ksks.append(key) + else: + zsks.append(key) + if not ksks: + ksks = keys + if not zsks: + zsks = keys + else: + keys = [] + + if txn: + cm: contextlib.AbstractContextManager = contextlib.nullcontext(txn) + else: + cm = zone.writer() + + if zone.origin is None: + raise ValueError("no zone origin") + + with cm as _txn: + if add_dnskey: + if dnskey_ttl is None: + dnskey = _txn.get(zone.origin, dns.rdatatype.DNSKEY) + if dnskey: + dnskey_ttl = dnskey.ttl + else: + soa = _txn.get(zone.origin, dns.rdatatype.SOA) + dnskey_ttl = soa.ttl + for _, dnskey in keys: + _txn.add(zone.origin, dnskey_ttl, dnskey) + + if nsec3: + raise NotImplementedError("Signing with NSEC3 not yet implemented") + else: + _rrset_signer = rrset_signer or functools.partial( + default_rrset_signer, + signer=zone.origin, + ksks=ksks, + zsks=zsks, + inception=inception, + expiration=expiration, + lifetime=lifetime, + policy=policy, + origin=zone.origin, + deterministic=deterministic, + ) + return _sign_zone_nsec(zone, _txn, _rrset_signer) + + +def _sign_zone_nsec( + zone: dns.zone.Zone, + txn: dns.transaction.Transaction, + rrset_signer: RRsetSigner | None = None, +) -> None: + """NSEC zone signer""" + + def _txn_add_nsec( + txn: dns.transaction.Transaction, + name: dns.name.Name, + next_secure: dns.name.Name | None, + rdclass: dns.rdataclass.RdataClass, + ttl: int, + rrset_signer: RRsetSigner | None = None, + ) -> None: + """NSEC zone signer helper""" + mandatory_types = set( + [dns.rdatatype.RdataType.RRSIG, dns.rdatatype.RdataType.NSEC] + ) + node = txn.get_node(name) + if node and next_secure: + types = ( + set([rdataset.rdtype for rdataset in node.rdatasets]) | mandatory_types + ) + windows = Bitmap.from_rdtypes(list(types)) + rrset = dns.rrset.from_rdata( + name, + ttl, + NSEC( + rdclass=rdclass, + rdtype=dns.rdatatype.RdataType.NSEC, + next=next_secure, + windows=windows, + ), + ) + txn.add(rrset) + if rrset_signer: + rrset_signer(txn, rrset) + + rrsig_ttl = zone.get_soa(txn).minimum + delegation = None + last_secure = None + + for name in sorted(txn.iterate_names()): + if delegation and name.is_subdomain(delegation): + # names below delegations are not secure + continue + elif txn.get(name, dns.rdatatype.NS) and name != zone.origin: + # inside delegation + delegation = name + else: + # outside delegation + delegation = None + + if rrset_signer: + node = txn.get_node(name) + if node: + for rdataset in node.rdatasets: + if rdataset.rdtype == dns.rdatatype.RRSIG: + # do not sign RRSIGs + continue + elif delegation and rdataset.rdtype != dns.rdatatype.DS: + # do not sign delegations except DS records + continue + else: + rrset = dns.rrset.from_rdata(name, rdataset.ttl, *rdataset) + rrset_signer(txn, rrset) + + # We need "is not None" as the empty name is False because its length is 0. + if last_secure is not None: + _txn_add_nsec(txn, last_secure, name, zone.rdclass, rrsig_ttl, rrset_signer) + last_secure = name + + if last_secure: + _txn_add_nsec( + txn, last_secure, zone.origin, zone.rdclass, rrsig_ttl, rrset_signer + ) + + +def _need_pyca(*args, **kwargs): + raise ImportError( + "DNSSEC validation requires python cryptography" + ) # pragma: no cover + + +if dns._features.have("dnssec"): + from cryptography.exceptions import InvalidSignature + from cryptography.hazmat.primitives.asymmetric import ec # pylint: disable=W0611 + from cryptography.hazmat.primitives.asymmetric import ed448 # pylint: disable=W0611 + from cryptography.hazmat.primitives.asymmetric import rsa # pylint: disable=W0611 + from cryptography.hazmat.primitives.asymmetric import ( # pylint: disable=W0611 + ed25519, + ) + + from dns.dnssecalgs import ( # pylint: disable=C0412 + get_algorithm_cls, + get_algorithm_cls_from_dnskey, + ) + from dns.dnssecalgs.base import GenericPrivateKey, GenericPublicKey + + validate = _validate # type: ignore + validate_rrsig = _validate_rrsig # type: ignore + sign = _sign + make_dnskey = _make_dnskey + make_cdnskey = _make_cdnskey + _have_pyca = True +else: # pragma: no cover + validate = _need_pyca + validate_rrsig = _need_pyca + sign = _need_pyca + make_dnskey = _need_pyca + make_cdnskey = _need_pyca + _have_pyca = False + +### BEGIN generated Algorithm constants + +RSAMD5 = Algorithm.RSAMD5 +DH = Algorithm.DH +DSA = Algorithm.DSA +ECC = Algorithm.ECC +RSASHA1 = Algorithm.RSASHA1 +DSANSEC3SHA1 = Algorithm.DSANSEC3SHA1 +RSASHA1NSEC3SHA1 = Algorithm.RSASHA1NSEC3SHA1 +RSASHA256 = Algorithm.RSASHA256 +RSASHA512 = Algorithm.RSASHA512 +ECCGOST = Algorithm.ECCGOST +ECDSAP256SHA256 = Algorithm.ECDSAP256SHA256 +ECDSAP384SHA384 = Algorithm.ECDSAP384SHA384 +ED25519 = Algorithm.ED25519 +ED448 = Algorithm.ED448 +INDIRECT = Algorithm.INDIRECT +PRIVATEDNS = Algorithm.PRIVATEDNS +PRIVATEOID = Algorithm.PRIVATEOID + +### END generated Algorithm constants diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/dnssecalgs/__init__.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/dnssecalgs/__init__.py new file mode 100644 index 000000000..0810b19a6 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/dnssecalgs/__init__.py @@ -0,0 +1,124 @@ +from typing import Dict, Tuple, Type + +import dns._features +import dns.name +from dns.dnssecalgs.base import GenericPrivateKey +from dns.dnssectypes import Algorithm +from dns.exception import UnsupportedAlgorithm +from dns.rdtypes.ANY.DNSKEY import DNSKEY + +# pyright: reportPossiblyUnboundVariable=false + +if dns._features.have("dnssec"): + from dns.dnssecalgs.dsa import PrivateDSA, PrivateDSANSEC3SHA1 + from dns.dnssecalgs.ecdsa import PrivateECDSAP256SHA256, PrivateECDSAP384SHA384 + from dns.dnssecalgs.eddsa import PrivateED448, PrivateED25519 + from dns.dnssecalgs.rsa import ( + PrivateRSAMD5, + PrivateRSASHA1, + PrivateRSASHA1NSEC3SHA1, + PrivateRSASHA256, + PrivateRSASHA512, + ) + + _have_cryptography = True +else: + _have_cryptography = False + +AlgorithmPrefix = bytes | dns.name.Name | None + +algorithms: Dict[Tuple[Algorithm, AlgorithmPrefix], Type[GenericPrivateKey]] = {} +if _have_cryptography: + # pylint: disable=possibly-used-before-assignment + algorithms.update( + { + (Algorithm.RSAMD5, None): PrivateRSAMD5, + (Algorithm.DSA, None): PrivateDSA, + (Algorithm.RSASHA1, None): PrivateRSASHA1, + (Algorithm.DSANSEC3SHA1, None): PrivateDSANSEC3SHA1, + (Algorithm.RSASHA1NSEC3SHA1, None): PrivateRSASHA1NSEC3SHA1, + (Algorithm.RSASHA256, None): PrivateRSASHA256, + (Algorithm.RSASHA512, None): PrivateRSASHA512, + (Algorithm.ECDSAP256SHA256, None): PrivateECDSAP256SHA256, + (Algorithm.ECDSAP384SHA384, None): PrivateECDSAP384SHA384, + (Algorithm.ED25519, None): PrivateED25519, + (Algorithm.ED448, None): PrivateED448, + } + ) + + +def get_algorithm_cls( + algorithm: int | str, prefix: AlgorithmPrefix = None +) -> Type[GenericPrivateKey]: + """Get Private Key class from Algorithm. + + *algorithm*, a ``str`` or ``int`` specifying the DNSKEY algorithm. + + Raises ``UnsupportedAlgorithm`` if the algorithm is unknown. + + Returns a ``dns.dnssecalgs.GenericPrivateKey`` + """ + algorithm = Algorithm.make(algorithm) + cls = algorithms.get((algorithm, prefix)) + if cls: + return cls + raise UnsupportedAlgorithm( + f'algorithm "{Algorithm.to_text(algorithm)}" not supported by dnspython' + ) + + +def get_algorithm_cls_from_dnskey(dnskey: DNSKEY) -> Type[GenericPrivateKey]: + """Get Private Key class from DNSKEY. + + *dnskey*, a ``DNSKEY`` to get Algorithm class for. + + Raises ``UnsupportedAlgorithm`` if the algorithm is unknown. + + Returns a ``dns.dnssecalgs.GenericPrivateKey`` + """ + prefix: AlgorithmPrefix = None + if dnskey.algorithm == Algorithm.PRIVATEDNS: + prefix, _ = dns.name.from_wire(dnskey.key, 0) + elif dnskey.algorithm == Algorithm.PRIVATEOID: + length = int(dnskey.key[0]) + prefix = dnskey.key[0 : length + 1] + return get_algorithm_cls(dnskey.algorithm, prefix) + + +def register_algorithm_cls( + algorithm: int | str, + algorithm_cls: Type[GenericPrivateKey], + name: dns.name.Name | str | None = None, + oid: bytes | None = None, +) -> None: + """Register Algorithm Private Key class. + + *algorithm*, a ``str`` or ``int`` specifying the DNSKEY algorithm. + + *algorithm_cls*: A `GenericPrivateKey` class. + + *name*, an optional ``dns.name.Name`` or ``str``, for for PRIVATEDNS algorithms. + + *oid*: an optional BER-encoded `bytes` for PRIVATEOID algorithms. + + Raises ``ValueError`` if a name or oid is specified incorrectly. + """ + if not issubclass(algorithm_cls, GenericPrivateKey): + raise TypeError("Invalid algorithm class") + algorithm = Algorithm.make(algorithm) + prefix: AlgorithmPrefix = None + if algorithm == Algorithm.PRIVATEDNS: + if name is None: + raise ValueError("Name required for PRIVATEDNS algorithms") + if isinstance(name, str): + name = dns.name.from_text(name) + prefix = name + elif algorithm == Algorithm.PRIVATEOID: + if oid is None: + raise ValueError("OID required for PRIVATEOID algorithms") + prefix = bytes([len(oid)]) + oid + elif name: + raise ValueError("Name only supported for PRIVATEDNS algorithm") + elif oid: + raise ValueError("OID only supported for PRIVATEOID algorithm") + algorithms[(algorithm, prefix)] = algorithm_cls diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/dnssecalgs/base.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/dnssecalgs/base.py new file mode 100644 index 000000000..0334fe6b5 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/dnssecalgs/base.py @@ -0,0 +1,89 @@ +from abc import ABC, abstractmethod # pylint: disable=no-name-in-module +from typing import Any, Type + +import dns.rdataclass +import dns.rdatatype +from dns.dnssectypes import Algorithm +from dns.exception import AlgorithmKeyMismatch +from dns.rdtypes.ANY.DNSKEY import DNSKEY +from dns.rdtypes.dnskeybase import Flag + + +class GenericPublicKey(ABC): + algorithm: Algorithm + + @abstractmethod + def __init__(self, key: Any) -> None: + pass + + @abstractmethod + def verify(self, signature: bytes, data: bytes) -> None: + """Verify signed DNSSEC data""" + + @abstractmethod + def encode_key_bytes(self) -> bytes: + """Encode key as bytes for DNSKEY""" + + @classmethod + def _ensure_algorithm_key_combination(cls, key: DNSKEY) -> None: + if key.algorithm != cls.algorithm: + raise AlgorithmKeyMismatch + + def to_dnskey(self, flags: int = Flag.ZONE, protocol: int = 3) -> DNSKEY: + """Return public key as DNSKEY""" + return DNSKEY( + rdclass=dns.rdataclass.IN, + rdtype=dns.rdatatype.DNSKEY, + flags=flags, + protocol=protocol, + algorithm=self.algorithm, + key=self.encode_key_bytes(), + ) + + @classmethod + @abstractmethod + def from_dnskey(cls, key: DNSKEY) -> "GenericPublicKey": + """Create public key from DNSKEY""" + + @classmethod + @abstractmethod + def from_pem(cls, public_pem: bytes) -> "GenericPublicKey": + """Create public key from PEM-encoded SubjectPublicKeyInfo as specified + in RFC 5280""" + + @abstractmethod + def to_pem(self) -> bytes: + """Return public-key as PEM-encoded SubjectPublicKeyInfo as specified + in RFC 5280""" + + +class GenericPrivateKey(ABC): + public_cls: Type[GenericPublicKey] + + @abstractmethod + def __init__(self, key: Any) -> None: + pass + + @abstractmethod + def sign( + self, + data: bytes, + verify: bool = False, + deterministic: bool = True, + ) -> bytes: + """Sign DNSSEC data""" + + @abstractmethod + def public_key(self) -> "GenericPublicKey": + """Return public key instance""" + + @classmethod + @abstractmethod + def from_pem( + cls, private_pem: bytes, password: bytes | None = None + ) -> "GenericPrivateKey": + """Create private key from PEM-encoded PKCS#8""" + + @abstractmethod + def to_pem(self, password: bytes | None = None) -> bytes: + """Return private key as PEM-encoded PKCS#8""" diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/dnssecalgs/cryptography.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/dnssecalgs/cryptography.py new file mode 100644 index 000000000..a5dde6a4a --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/dnssecalgs/cryptography.py @@ -0,0 +1,68 @@ +from typing import Any, Type + +from cryptography.hazmat.primitives import serialization + +from dns.dnssecalgs.base import GenericPrivateKey, GenericPublicKey +from dns.exception import AlgorithmKeyMismatch + + +class CryptographyPublicKey(GenericPublicKey): + key: Any = None + key_cls: Any = None + + def __init__(self, key: Any) -> None: # pylint: disable=super-init-not-called + if self.key_cls is None: + raise TypeError("Undefined private key class") + if not isinstance( # pylint: disable=isinstance-second-argument-not-valid-type + key, self.key_cls + ): + raise AlgorithmKeyMismatch + self.key = key + + @classmethod + def from_pem(cls, public_pem: bytes) -> "GenericPublicKey": + key = serialization.load_pem_public_key(public_pem) + return cls(key=key) + + def to_pem(self) -> bytes: + return self.key.public_bytes( + encoding=serialization.Encoding.PEM, + format=serialization.PublicFormat.SubjectPublicKeyInfo, + ) + + +class CryptographyPrivateKey(GenericPrivateKey): + key: Any = None + key_cls: Any = None + public_cls: Type[CryptographyPublicKey] # pyright: ignore + + def __init__(self, key: Any) -> None: # pylint: disable=super-init-not-called + if self.key_cls is None: + raise TypeError("Undefined private key class") + if not isinstance( # pylint: disable=isinstance-second-argument-not-valid-type + key, self.key_cls + ): + raise AlgorithmKeyMismatch + self.key = key + + def public_key(self) -> "CryptographyPublicKey": + return self.public_cls(key=self.key.public_key()) + + @classmethod + def from_pem( + cls, private_pem: bytes, password: bytes | None = None + ) -> "GenericPrivateKey": + key = serialization.load_pem_private_key(private_pem, password=password) + return cls(key=key) + + def to_pem(self, password: bytes | None = None) -> bytes: + encryption_algorithm: serialization.KeySerializationEncryption + if password: + encryption_algorithm = serialization.BestAvailableEncryption(password) + else: + encryption_algorithm = serialization.NoEncryption() + return self.key.private_bytes( + encoding=serialization.Encoding.PEM, + format=serialization.PrivateFormat.PKCS8, + encryption_algorithm=encryption_algorithm, + ) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/dnssecalgs/dsa.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/dnssecalgs/dsa.py new file mode 100644 index 000000000..66eb1612f --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/dnssecalgs/dsa.py @@ -0,0 +1,108 @@ +import struct + +from cryptography.hazmat.backends import default_backend +from cryptography.hazmat.primitives import hashes +from cryptography.hazmat.primitives.asymmetric import dsa, utils + +from dns.dnssecalgs.cryptography import CryptographyPrivateKey, CryptographyPublicKey +from dns.dnssectypes import Algorithm +from dns.rdtypes.ANY.DNSKEY import DNSKEY + + +class PublicDSA(CryptographyPublicKey): + key: dsa.DSAPublicKey + key_cls = dsa.DSAPublicKey + algorithm = Algorithm.DSA + chosen_hash = hashes.SHA256() + + def verify(self, signature: bytes, data: bytes) -> None: + sig_r = signature[1:21] + sig_s = signature[21:] + sig = utils.encode_dss_signature( + int.from_bytes(sig_r, "big"), int.from_bytes(sig_s, "big") + ) + self.key.verify(sig, data, self.chosen_hash) + + def encode_key_bytes(self) -> bytes: + """Encode a public key per RFC 2536, section 2.""" + pn = self.key.public_numbers() + dsa_t = (self.key.key_size // 8 - 64) // 8 + if dsa_t > 8: + raise ValueError("unsupported DSA key size") + octets = 64 + dsa_t * 8 + res = struct.pack("!B", dsa_t) + res += pn.parameter_numbers.q.to_bytes(20, "big") + res += pn.parameter_numbers.p.to_bytes(octets, "big") + res += pn.parameter_numbers.g.to_bytes(octets, "big") + res += pn.y.to_bytes(octets, "big") + return res + + @classmethod + def from_dnskey(cls, key: DNSKEY) -> "PublicDSA": + cls._ensure_algorithm_key_combination(key) + keyptr = key.key + (t,) = struct.unpack("!B", keyptr[0:1]) + keyptr = keyptr[1:] + octets = 64 + t * 8 + dsa_q = keyptr[0:20] + keyptr = keyptr[20:] + dsa_p = keyptr[0:octets] + keyptr = keyptr[octets:] + dsa_g = keyptr[0:octets] + keyptr = keyptr[octets:] + dsa_y = keyptr[0:octets] + return cls( + key=dsa.DSAPublicNumbers( # type: ignore + int.from_bytes(dsa_y, "big"), + dsa.DSAParameterNumbers( + int.from_bytes(dsa_p, "big"), + int.from_bytes(dsa_q, "big"), + int.from_bytes(dsa_g, "big"), + ), + ).public_key(default_backend()), + ) + + +class PrivateDSA(CryptographyPrivateKey): + key: dsa.DSAPrivateKey + key_cls = dsa.DSAPrivateKey + public_cls = PublicDSA + + def sign( + self, + data: bytes, + verify: bool = False, + deterministic: bool = True, + ) -> bytes: + """Sign using a private key per RFC 2536, section 3.""" + public_dsa_key = self.key.public_key() + if public_dsa_key.key_size > 1024: + raise ValueError("DSA key size overflow") + der_signature = self.key.sign( + data, self.public_cls.chosen_hash # pyright: ignore + ) + dsa_r, dsa_s = utils.decode_dss_signature(der_signature) + dsa_t = (public_dsa_key.key_size // 8 - 64) // 8 + octets = 20 + signature = ( + struct.pack("!B", dsa_t) + + int.to_bytes(dsa_r, length=octets, byteorder="big") + + int.to_bytes(dsa_s, length=octets, byteorder="big") + ) + if verify: + self.public_key().verify(signature, data) + return signature + + @classmethod + def generate(cls, key_size: int) -> "PrivateDSA": + return cls( + key=dsa.generate_private_key(key_size=key_size), + ) + + +class PublicDSANSEC3SHA1(PublicDSA): + algorithm = Algorithm.DSANSEC3SHA1 + + +class PrivateDSANSEC3SHA1(PrivateDSA): + public_cls = PublicDSANSEC3SHA1 diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/dnssecalgs/ecdsa.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/dnssecalgs/ecdsa.py new file mode 100644 index 000000000..e3f3f061d --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/dnssecalgs/ecdsa.py @@ -0,0 +1,100 @@ +from cryptography.hazmat.backends import default_backend +from cryptography.hazmat.primitives import hashes +from cryptography.hazmat.primitives.asymmetric import ec, utils + +from dns.dnssecalgs.cryptography import CryptographyPrivateKey, CryptographyPublicKey +from dns.dnssectypes import Algorithm +from dns.rdtypes.ANY.DNSKEY import DNSKEY + + +class PublicECDSA(CryptographyPublicKey): + key: ec.EllipticCurvePublicKey + key_cls = ec.EllipticCurvePublicKey + algorithm: Algorithm + chosen_hash: hashes.HashAlgorithm + curve: ec.EllipticCurve + octets: int + + def verify(self, signature: bytes, data: bytes) -> None: + sig_r = signature[0 : self.octets] + sig_s = signature[self.octets :] + sig = utils.encode_dss_signature( + int.from_bytes(sig_r, "big"), int.from_bytes(sig_s, "big") + ) + self.key.verify(sig, data, ec.ECDSA(self.chosen_hash)) + + def encode_key_bytes(self) -> bytes: + """Encode a public key per RFC 6605, section 4.""" + pn = self.key.public_numbers() + return pn.x.to_bytes(self.octets, "big") + pn.y.to_bytes(self.octets, "big") + + @classmethod + def from_dnskey(cls, key: DNSKEY) -> "PublicECDSA": + cls._ensure_algorithm_key_combination(key) + ecdsa_x = key.key[0 : cls.octets] + ecdsa_y = key.key[cls.octets : cls.octets * 2] + return cls( + key=ec.EllipticCurvePublicNumbers( + curve=cls.curve, + x=int.from_bytes(ecdsa_x, "big"), + y=int.from_bytes(ecdsa_y, "big"), + ).public_key(default_backend()), + ) + + +class PrivateECDSA(CryptographyPrivateKey): + key: ec.EllipticCurvePrivateKey + key_cls = ec.EllipticCurvePrivateKey + public_cls = PublicECDSA + + def sign( + self, + data: bytes, + verify: bool = False, + deterministic: bool = True, + ) -> bytes: + """Sign using a private key per RFC 6605, section 4.""" + algorithm = ec.ECDSA( + self.public_cls.chosen_hash, # pyright: ignore + deterministic_signing=deterministic, + ) + der_signature = self.key.sign(data, algorithm) + dsa_r, dsa_s = utils.decode_dss_signature(der_signature) + signature = int.to_bytes( + dsa_r, length=self.public_cls.octets, byteorder="big" # pyright: ignore + ) + int.to_bytes( + dsa_s, length=self.public_cls.octets, byteorder="big" # pyright: ignore + ) + if verify: + self.public_key().verify(signature, data) + return signature + + @classmethod + def generate(cls) -> "PrivateECDSA": + return cls( + key=ec.generate_private_key( + curve=cls.public_cls.curve, backend=default_backend() # pyright: ignore + ), + ) + + +class PublicECDSAP256SHA256(PublicECDSA): + algorithm = Algorithm.ECDSAP256SHA256 + chosen_hash = hashes.SHA256() + curve = ec.SECP256R1() + octets = 32 + + +class PrivateECDSAP256SHA256(PrivateECDSA): + public_cls = PublicECDSAP256SHA256 + + +class PublicECDSAP384SHA384(PublicECDSA): + algorithm = Algorithm.ECDSAP384SHA384 + chosen_hash = hashes.SHA384() + curve = ec.SECP384R1() + octets = 48 + + +class PrivateECDSAP384SHA384(PrivateECDSA): + public_cls = PublicECDSAP384SHA384 diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/dnssecalgs/eddsa.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/dnssecalgs/eddsa.py new file mode 100644 index 000000000..1cbb40796 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/dnssecalgs/eddsa.py @@ -0,0 +1,70 @@ +from typing import Type + +from cryptography.hazmat.primitives import serialization +from cryptography.hazmat.primitives.asymmetric import ed448, ed25519 + +from dns.dnssecalgs.cryptography import CryptographyPrivateKey, CryptographyPublicKey +from dns.dnssectypes import Algorithm +from dns.rdtypes.ANY.DNSKEY import DNSKEY + + +class PublicEDDSA(CryptographyPublicKey): + def verify(self, signature: bytes, data: bytes) -> None: + self.key.verify(signature, data) + + def encode_key_bytes(self) -> bytes: + """Encode a public key per RFC 8080, section 3.""" + return self.key.public_bytes( + encoding=serialization.Encoding.Raw, format=serialization.PublicFormat.Raw + ) + + @classmethod + def from_dnskey(cls, key: DNSKEY) -> "PublicEDDSA": + cls._ensure_algorithm_key_combination(key) + return cls( + key=cls.key_cls.from_public_bytes(key.key), + ) + + +class PrivateEDDSA(CryptographyPrivateKey): + public_cls: Type[PublicEDDSA] # pyright: ignore + + def sign( + self, + data: bytes, + verify: bool = False, + deterministic: bool = True, + ) -> bytes: + """Sign using a private key per RFC 8080, section 4.""" + signature = self.key.sign(data) + if verify: + self.public_key().verify(signature, data) + return signature + + @classmethod + def generate(cls) -> "PrivateEDDSA": + return cls(key=cls.key_cls.generate()) + + +class PublicED25519(PublicEDDSA): + key: ed25519.Ed25519PublicKey + key_cls = ed25519.Ed25519PublicKey + algorithm = Algorithm.ED25519 + + +class PrivateED25519(PrivateEDDSA): + key: ed25519.Ed25519PrivateKey + key_cls = ed25519.Ed25519PrivateKey + public_cls = PublicED25519 + + +class PublicED448(PublicEDDSA): + key: ed448.Ed448PublicKey + key_cls = ed448.Ed448PublicKey + algorithm = Algorithm.ED448 + + +class PrivateED448(PrivateEDDSA): + key: ed448.Ed448PrivateKey + key_cls = ed448.Ed448PrivateKey + public_cls = PublicED448 diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/dnssecalgs/rsa.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/dnssecalgs/rsa.py new file mode 100644 index 000000000..e1554e17a --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/dnssecalgs/rsa.py @@ -0,0 +1,126 @@ +import math +import struct + +from cryptography.hazmat.backends import default_backend +from cryptography.hazmat.primitives import hashes +from cryptography.hazmat.primitives.asymmetric import padding, rsa + +from dns.dnssecalgs.cryptography import CryptographyPrivateKey, CryptographyPublicKey +from dns.dnssectypes import Algorithm +from dns.rdtypes.ANY.DNSKEY import DNSKEY + + +class PublicRSA(CryptographyPublicKey): + key: rsa.RSAPublicKey + key_cls = rsa.RSAPublicKey + algorithm: Algorithm + chosen_hash: hashes.HashAlgorithm + + def verify(self, signature: bytes, data: bytes) -> None: + self.key.verify(signature, data, padding.PKCS1v15(), self.chosen_hash) + + def encode_key_bytes(self) -> bytes: + """Encode a public key per RFC 3110, section 2.""" + pn = self.key.public_numbers() + _exp_len = math.ceil(int.bit_length(pn.e) / 8) + exp = int.to_bytes(pn.e, length=_exp_len, byteorder="big") + if _exp_len > 255: + exp_header = b"\0" + struct.pack("!H", _exp_len) + else: + exp_header = struct.pack("!B", _exp_len) + if pn.n.bit_length() < 512 or pn.n.bit_length() > 4096: + raise ValueError("unsupported RSA key length") + return exp_header + exp + pn.n.to_bytes((pn.n.bit_length() + 7) // 8, "big") + + @classmethod + def from_dnskey(cls, key: DNSKEY) -> "PublicRSA": + cls._ensure_algorithm_key_combination(key) + keyptr = key.key + (bytes_,) = struct.unpack("!B", keyptr[0:1]) + keyptr = keyptr[1:] + if bytes_ == 0: + (bytes_,) = struct.unpack("!H", keyptr[0:2]) + keyptr = keyptr[2:] + rsa_e = keyptr[0:bytes_] + rsa_n = keyptr[bytes_:] + return cls( + key=rsa.RSAPublicNumbers( + int.from_bytes(rsa_e, "big"), int.from_bytes(rsa_n, "big") + ).public_key(default_backend()) + ) + + +class PrivateRSA(CryptographyPrivateKey): + key: rsa.RSAPrivateKey + key_cls = rsa.RSAPrivateKey + public_cls = PublicRSA + default_public_exponent = 65537 + + def sign( + self, + data: bytes, + verify: bool = False, + deterministic: bool = True, + ) -> bytes: + """Sign using a private key per RFC 3110, section 3.""" + signature = self.key.sign( + data, padding.PKCS1v15(), self.public_cls.chosen_hash # pyright: ignore + ) + if verify: + self.public_key().verify(signature, data) + return signature + + @classmethod + def generate(cls, key_size: int) -> "PrivateRSA": + return cls( + key=rsa.generate_private_key( + public_exponent=cls.default_public_exponent, + key_size=key_size, + backend=default_backend(), + ) + ) + + +class PublicRSAMD5(PublicRSA): + algorithm = Algorithm.RSASHA256 + chosen_hash = hashes.SHA256() + + +class PrivateRSAMD5(PrivateRSA): + public_cls = PublicRSAMD5 + + +class PublicRSASHA1(PublicRSA): + algorithm = Algorithm.RSASHA1 + chosen_hash = hashes.SHA1() + + +class PrivateRSASHA1(PrivateRSA): + public_cls = PublicRSASHA1 + + +class PublicRSASHA1NSEC3SHA1(PublicRSA): + algorithm = Algorithm.RSASHA1NSEC3SHA1 + chosen_hash = hashes.SHA1() + + +class PrivateRSASHA1NSEC3SHA1(PrivateRSA): + public_cls = PublicRSASHA1NSEC3SHA1 + + +class PublicRSASHA256(PublicRSA): + algorithm = Algorithm.RSASHA256 + chosen_hash = hashes.SHA256() + + +class PrivateRSASHA256(PrivateRSA): + public_cls = PublicRSASHA256 + + +class PublicRSASHA512(PublicRSA): + algorithm = Algorithm.RSASHA512 + chosen_hash = hashes.SHA512() + + +class PrivateRSASHA512(PrivateRSA): + public_cls = PublicRSASHA512 diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/dnssectypes.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/dnssectypes.py new file mode 100644 index 000000000..02131e0ad --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/dnssectypes.py @@ -0,0 +1,71 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +# Copyright (C) 2003-2017 Nominum, Inc. +# +# Permission to use, copy, modify, and distribute this software and its +# documentation for any purpose with or without fee is hereby granted, +# provided that the above copyright notice and this permission notice +# appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +"""Common DNSSEC-related types.""" + +# This is a separate file to avoid import circularity between dns.dnssec and +# the implementations of the DS and DNSKEY types. + +import dns.enum + + +class Algorithm(dns.enum.IntEnum): + RSAMD5 = 1 + DH = 2 + DSA = 3 + ECC = 4 + RSASHA1 = 5 + DSANSEC3SHA1 = 6 + RSASHA1NSEC3SHA1 = 7 + RSASHA256 = 8 + RSASHA512 = 10 + ECCGOST = 12 + ECDSAP256SHA256 = 13 + ECDSAP384SHA384 = 14 + ED25519 = 15 + ED448 = 16 + INDIRECT = 252 + PRIVATEDNS = 253 + PRIVATEOID = 254 + + @classmethod + def _maximum(cls): + return 255 + + +class DSDigest(dns.enum.IntEnum): + """DNSSEC Delegation Signer Digest Algorithm""" + + NULL = 0 + SHA1 = 1 + SHA256 = 2 + GOST = 3 + SHA384 = 4 + + @classmethod + def _maximum(cls): + return 255 + + +class NSEC3Hash(dns.enum.IntEnum): + """NSEC3 hash algorithm""" + + SHA1 = 1 + + @classmethod + def _maximum(cls): + return 255 diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/e164.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/e164.py new file mode 100644 index 000000000..942d2c0fb --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/e164.py @@ -0,0 +1,116 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +# Copyright (C) 2006-2017 Nominum, Inc. +# +# Permission to use, copy, modify, and distribute this software and its +# documentation for any purpose with or without fee is hereby granted, +# provided that the above copyright notice and this permission notice +# appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +"""DNS E.164 helpers.""" + +from typing import Iterable + +import dns.exception +import dns.name +import dns.resolver + +#: The public E.164 domain. +public_enum_domain = dns.name.from_text("e164.arpa.") + + +def from_e164( + text: str, origin: dns.name.Name | None = public_enum_domain +) -> dns.name.Name: + """Convert an E.164 number in textual form into a Name object whose + value is the ENUM domain name for that number. + + Non-digits in the text are ignored, i.e. "16505551212", + "+1.650.555.1212" and "1 (650) 555-1212" are all the same. + + *text*, a ``str``, is an E.164 number in textual form. + + *origin*, a ``dns.name.Name``, the domain in which the number + should be constructed. The default is ``e164.arpa.``. + + Returns a ``dns.name.Name``. + """ + + parts = [d for d in text if d.isdigit()] + parts.reverse() + return dns.name.from_text(".".join(parts), origin=origin) + + +def to_e164( + name: dns.name.Name, + origin: dns.name.Name | None = public_enum_domain, + want_plus_prefix: bool = True, +) -> str: + """Convert an ENUM domain name into an E.164 number. + + Note that dnspython does not have any information about preferred + number formats within national numbering plans, so all numbers are + emitted as a simple string of digits, prefixed by a '+' (unless + *want_plus_prefix* is ``False``). + + *name* is a ``dns.name.Name``, the ENUM domain name. + + *origin* is a ``dns.name.Name``, a domain containing the ENUM + domain name. The name is relativized to this domain before being + converted to text. If ``None``, no relativization is done. + + *want_plus_prefix* is a ``bool``. If True, add a '+' to the beginning of + the returned number. + + Returns a ``str``. + + """ + if origin is not None: + name = name.relativize(origin) + dlabels = [d for d in name.labels if d.isdigit() and len(d) == 1] + if len(dlabels) != len(name.labels): + raise dns.exception.SyntaxError("non-digit labels in ENUM domain name") + dlabels.reverse() + text = b"".join(dlabels) + if want_plus_prefix: + text = b"+" + text + return text.decode() + + +def query( + number: str, + domains: Iterable[dns.name.Name | str], + resolver: dns.resolver.Resolver | None = None, +) -> dns.resolver.Answer: + """Look for NAPTR RRs for the specified number in the specified domains. + + e.g. lookup('16505551212', ['e164.dnspython.org.', 'e164.arpa.']) + + *number*, a ``str`` is the number to look for. + + *domains* is an iterable containing ``dns.name.Name`` values. + + *resolver*, a ``dns.resolver.Resolver``, is the resolver to use. If + ``None``, the default resolver is used. + """ + + if resolver is None: + resolver = dns.resolver.get_default_resolver() + e_nx = dns.resolver.NXDOMAIN() + for domain in domains: + if isinstance(domain, str): + domain = dns.name.from_text(domain) + qname = from_e164(number, domain) + try: + return resolver.resolve(qname, "NAPTR") + except dns.resolver.NXDOMAIN as e: + e_nx += e + raise e_nx diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/edns.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/edns.py new file mode 100644 index 000000000..eb985484b --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/edns.py @@ -0,0 +1,591 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +# Copyright (C) 2009-2017 Nominum, Inc. +# +# Permission to use, copy, modify, and distribute this software and its +# documentation for any purpose with or without fee is hereby granted, +# provided that the above copyright notice and this permission notice +# appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +"""EDNS Options""" + +import binascii +import math +import socket +import struct +from typing import Any, Dict + +import dns.enum +import dns.inet +import dns.ipv4 +import dns.ipv6 +import dns.name +import dns.rdata +import dns.wire + + +class OptionType(dns.enum.IntEnum): + """EDNS option type codes""" + + #: NSID + NSID = 3 + #: DAU + DAU = 5 + #: DHU + DHU = 6 + #: N3U + N3U = 7 + #: ECS (client-subnet) + ECS = 8 + #: EXPIRE + EXPIRE = 9 + #: COOKIE + COOKIE = 10 + #: KEEPALIVE + KEEPALIVE = 11 + #: PADDING + PADDING = 12 + #: CHAIN + CHAIN = 13 + #: EDE (extended-dns-error) + EDE = 15 + #: REPORTCHANNEL + REPORTCHANNEL = 18 + + @classmethod + def _maximum(cls): + return 65535 + + +class Option: + """Base class for all EDNS option types.""" + + def __init__(self, otype: OptionType | str): + """Initialize an option. + + *otype*, a ``dns.edns.OptionType``, is the option type. + """ + self.otype = OptionType.make(otype) + + def to_wire(self, file: Any | None = None) -> bytes | None: + """Convert an option to wire format. + + Returns a ``bytes`` or ``None``. + + """ + raise NotImplementedError # pragma: no cover + + def to_text(self) -> str: + raise NotImplementedError # pragma: no cover + + def to_generic(self) -> "GenericOption": + """Creates a dns.edns.GenericOption equivalent of this rdata. + + Returns a ``dns.edns.GenericOption``. + """ + wire = self.to_wire() + assert wire is not None # for mypy + return GenericOption(self.otype, wire) + + @classmethod + def from_wire_parser(cls, otype: OptionType, parser: "dns.wire.Parser") -> "Option": + """Build an EDNS option object from wire format. + + *otype*, a ``dns.edns.OptionType``, is the option type. + + *parser*, a ``dns.wire.Parser``, the parser, which should be + restructed to the option length. + + Returns a ``dns.edns.Option``. + """ + raise NotImplementedError # pragma: no cover + + def _cmp(self, other): + """Compare an EDNS option with another option of the same type. + + Returns < 0 if < *other*, 0 if == *other*, and > 0 if > *other*. + """ + wire = self.to_wire() + owire = other.to_wire() + if wire == owire: + return 0 + if wire > owire: + return 1 + return -1 + + def __eq__(self, other): + if not isinstance(other, Option): + return False + if self.otype != other.otype: + return False + return self._cmp(other) == 0 + + def __ne__(self, other): + if not isinstance(other, Option): + return True + if self.otype != other.otype: + return True + return self._cmp(other) != 0 + + def __lt__(self, other): + if not isinstance(other, Option) or self.otype != other.otype: + return NotImplemented + return self._cmp(other) < 0 + + def __le__(self, other): + if not isinstance(other, Option) or self.otype != other.otype: + return NotImplemented + return self._cmp(other) <= 0 + + def __ge__(self, other): + if not isinstance(other, Option) or self.otype != other.otype: + return NotImplemented + return self._cmp(other) >= 0 + + def __gt__(self, other): + if not isinstance(other, Option) or self.otype != other.otype: + return NotImplemented + return self._cmp(other) > 0 + + def __str__(self): + return self.to_text() + + +class GenericOption(Option): # lgtm[py/missing-equals] + """Generic Option Class + + This class is used for EDNS option types for which we have no better + implementation. + """ + + def __init__(self, otype: OptionType | str, data: bytes | str): + super().__init__(otype) + self.data = dns.rdata.Rdata._as_bytes(data, True) + + def to_wire(self, file: Any | None = None) -> bytes | None: + if file: + file.write(self.data) + return None + else: + return self.data + + def to_text(self) -> str: + return f"Generic {self.otype}" + + def to_generic(self) -> "GenericOption": + return self + + @classmethod + def from_wire_parser( + cls, otype: OptionType | str, parser: "dns.wire.Parser" + ) -> Option: + return cls(otype, parser.get_remaining()) + + +class ECSOption(Option): # lgtm[py/missing-equals] + """EDNS Client Subnet (ECS, RFC7871)""" + + def __init__(self, address: str, srclen: int | None = None, scopelen: int = 0): + """*address*, a ``str``, is the client address information. + + *srclen*, an ``int``, the source prefix length, which is the + leftmost number of bits of the address to be used for the + lookup. The default is 24 for IPv4 and 56 for IPv6. + + *scopelen*, an ``int``, the scope prefix length. This value + must be 0 in queries, and should be set in responses. + """ + + super().__init__(OptionType.ECS) + af = dns.inet.af_for_address(address) + + if af == socket.AF_INET6: + self.family = 2 + if srclen is None: + srclen = 56 + address = dns.rdata.Rdata._as_ipv6_address(address) + srclen = dns.rdata.Rdata._as_int(srclen, 0, 128) + scopelen = dns.rdata.Rdata._as_int(scopelen, 0, 128) + elif af == socket.AF_INET: + self.family = 1 + if srclen is None: + srclen = 24 + address = dns.rdata.Rdata._as_ipv4_address(address) + srclen = dns.rdata.Rdata._as_int(srclen, 0, 32) + scopelen = dns.rdata.Rdata._as_int(scopelen, 0, 32) + else: # pragma: no cover (this will never happen) + raise ValueError("Bad address family") + + assert srclen is not None + self.address = address + self.srclen = srclen + self.scopelen = scopelen + + addrdata = dns.inet.inet_pton(af, address) + nbytes = int(math.ceil(srclen / 8.0)) + + # Truncate to srclen and pad to the end of the last octet needed + # See RFC section 6 + self.addrdata = addrdata[:nbytes] + nbits = srclen % 8 + if nbits != 0: + last = struct.pack("B", ord(self.addrdata[-1:]) & (0xFF << (8 - nbits))) + self.addrdata = self.addrdata[:-1] + last + + def to_text(self) -> str: + return f"ECS {self.address}/{self.srclen} scope/{self.scopelen}" + + @staticmethod + def from_text(text: str) -> Option: + """Convert a string into a `dns.edns.ECSOption` + + *text*, a `str`, the text form of the option. + + Returns a `dns.edns.ECSOption`. + + Examples: + + >>> import dns.edns + >>> + >>> # basic example + >>> dns.edns.ECSOption.from_text('1.2.3.4/24') + >>> + >>> # also understands scope + >>> dns.edns.ECSOption.from_text('1.2.3.4/24/32') + >>> + >>> # IPv6 + >>> dns.edns.ECSOption.from_text('2001:4b98::1/64/64') + >>> + >>> # it understands results from `dns.edns.ECSOption.to_text()` + >>> dns.edns.ECSOption.from_text('ECS 1.2.3.4/24/32') + """ + optional_prefix = "ECS" + tokens = text.split() + ecs_text = None + if len(tokens) == 1: + ecs_text = tokens[0] + elif len(tokens) == 2: + if tokens[0] != optional_prefix: + raise ValueError(f'could not parse ECS from "{text}"') + ecs_text = tokens[1] + else: + raise ValueError(f'could not parse ECS from "{text}"') + n_slashes = ecs_text.count("/") + if n_slashes == 1: + address, tsrclen = ecs_text.split("/") + tscope = "0" + elif n_slashes == 2: + address, tsrclen, tscope = ecs_text.split("/") + else: + raise ValueError(f'could not parse ECS from "{text}"') + try: + scope = int(tscope) + except ValueError: + raise ValueError("invalid scope " + f'"{tscope}": scope must be an integer') + try: + srclen = int(tsrclen) + except ValueError: + raise ValueError( + "invalid srclen " + f'"{tsrclen}": srclen must be an integer' + ) + return ECSOption(address, srclen, scope) + + def to_wire(self, file: Any | None = None) -> bytes | None: + value = ( + struct.pack("!HBB", self.family, self.srclen, self.scopelen) + self.addrdata + ) + if file: + file.write(value) + return None + else: + return value + + @classmethod + def from_wire_parser( + cls, otype: OptionType | str, parser: "dns.wire.Parser" + ) -> Option: + family, src, scope = parser.get_struct("!HBB") + addrlen = int(math.ceil(src / 8.0)) + prefix = parser.get_bytes(addrlen) + if family == 1: + pad = 4 - addrlen + addr = dns.ipv4.inet_ntoa(prefix + b"\x00" * pad) + elif family == 2: + pad = 16 - addrlen + addr = dns.ipv6.inet_ntoa(prefix + b"\x00" * pad) + else: + raise ValueError("unsupported family") + + return cls(addr, src, scope) + + +class EDECode(dns.enum.IntEnum): + """Extended DNS Error (EDE) codes""" + + OTHER = 0 + UNSUPPORTED_DNSKEY_ALGORITHM = 1 + UNSUPPORTED_DS_DIGEST_TYPE = 2 + STALE_ANSWER = 3 + FORGED_ANSWER = 4 + DNSSEC_INDETERMINATE = 5 + DNSSEC_BOGUS = 6 + SIGNATURE_EXPIRED = 7 + SIGNATURE_NOT_YET_VALID = 8 + DNSKEY_MISSING = 9 + RRSIGS_MISSING = 10 + NO_ZONE_KEY_BIT_SET = 11 + NSEC_MISSING = 12 + CACHED_ERROR = 13 + NOT_READY = 14 + BLOCKED = 15 + CENSORED = 16 + FILTERED = 17 + PROHIBITED = 18 + STALE_NXDOMAIN_ANSWER = 19 + NOT_AUTHORITATIVE = 20 + NOT_SUPPORTED = 21 + NO_REACHABLE_AUTHORITY = 22 + NETWORK_ERROR = 23 + INVALID_DATA = 24 + + @classmethod + def _maximum(cls): + return 65535 + + +class EDEOption(Option): # lgtm[py/missing-equals] + """Extended DNS Error (EDE, RFC8914)""" + + _preserve_case = {"DNSKEY", "DS", "DNSSEC", "RRSIGs", "NSEC", "NXDOMAIN"} + + def __init__(self, code: EDECode | str, text: str | None = None): + """*code*, a ``dns.edns.EDECode`` or ``str``, the info code of the + extended error. + + *text*, a ``str`` or ``None``, specifying additional information about + the error. + """ + + super().__init__(OptionType.EDE) + + self.code = EDECode.make(code) + if text is not None and not isinstance(text, str): + raise ValueError("text must be string or None") + self.text = text + + def to_text(self) -> str: + output = f"EDE {self.code}" + if self.code in EDECode: + desc = EDECode.to_text(self.code) + desc = " ".join( + word if word in self._preserve_case else word.title() + for word in desc.split("_") + ) + output += f" ({desc})" + if self.text is not None: + output += f": {self.text}" + return output + + def to_wire(self, file: Any | None = None) -> bytes | None: + value = struct.pack("!H", self.code) + if self.text is not None: + value += self.text.encode("utf8") + + if file: + file.write(value) + return None + else: + return value + + @classmethod + def from_wire_parser( + cls, otype: OptionType | str, parser: "dns.wire.Parser" + ) -> Option: + code = EDECode.make(parser.get_uint16()) + text = parser.get_remaining() + + if text: + if text[-1] == 0: # text MAY be null-terminated + text = text[:-1] + btext = text.decode("utf8") + else: + btext = None + + return cls(code, btext) + + +class NSIDOption(Option): + def __init__(self, nsid: bytes): + super().__init__(OptionType.NSID) + self.nsid = nsid + + def to_wire(self, file: Any = None) -> bytes | None: + if file: + file.write(self.nsid) + return None + else: + return self.nsid + + def to_text(self) -> str: + if all(c >= 0x20 and c <= 0x7E for c in self.nsid): + # All ASCII printable, so it's probably a string. + value = self.nsid.decode() + else: + value = binascii.hexlify(self.nsid).decode() + return f"NSID {value}" + + @classmethod + def from_wire_parser( + cls, otype: OptionType | str, parser: dns.wire.Parser + ) -> Option: + return cls(parser.get_remaining()) + + +class CookieOption(Option): + def __init__(self, client: bytes, server: bytes): + super().__init__(OptionType.COOKIE) + self.client = client + self.server = server + if len(client) != 8: + raise ValueError("client cookie must be 8 bytes") + if len(server) != 0 and (len(server) < 8 or len(server) > 32): + raise ValueError("server cookie must be empty or between 8 and 32 bytes") + + def to_wire(self, file: Any = None) -> bytes | None: + if file: + file.write(self.client) + if len(self.server) > 0: + file.write(self.server) + return None + else: + return self.client + self.server + + def to_text(self) -> str: + client = binascii.hexlify(self.client).decode() + if len(self.server) > 0: + server = binascii.hexlify(self.server).decode() + else: + server = "" + return f"COOKIE {client}{server}" + + @classmethod + def from_wire_parser( + cls, otype: OptionType | str, parser: dns.wire.Parser + ) -> Option: + return cls(parser.get_bytes(8), parser.get_remaining()) + + +class ReportChannelOption(Option): + # RFC 9567 + def __init__(self, agent_domain: dns.name.Name): + super().__init__(OptionType.REPORTCHANNEL) + self.agent_domain = agent_domain + + def to_wire(self, file: Any = None) -> bytes | None: + return self.agent_domain.to_wire(file) + + def to_text(self) -> str: + return "REPORTCHANNEL " + self.agent_domain.to_text() + + @classmethod + def from_wire_parser( + cls, otype: OptionType | str, parser: dns.wire.Parser + ) -> Option: + return cls(parser.get_name()) + + +_type_to_class: Dict[OptionType, Any] = { + OptionType.ECS: ECSOption, + OptionType.EDE: EDEOption, + OptionType.NSID: NSIDOption, + OptionType.COOKIE: CookieOption, + OptionType.REPORTCHANNEL: ReportChannelOption, +} + + +def get_option_class(otype: OptionType) -> Any: + """Return the class for the specified option type. + + The GenericOption class is used if a more specific class is not + known. + """ + + cls = _type_to_class.get(otype) + if cls is None: + cls = GenericOption + return cls + + +def option_from_wire_parser( + otype: OptionType | str, parser: "dns.wire.Parser" +) -> Option: + """Build an EDNS option object from wire format. + + *otype*, an ``int``, is the option type. + + *parser*, a ``dns.wire.Parser``, the parser, which should be + restricted to the option length. + + Returns an instance of a subclass of ``dns.edns.Option``. + """ + otype = OptionType.make(otype) + cls = get_option_class(otype) + return cls.from_wire_parser(otype, parser) + + +def option_from_wire( + otype: OptionType | str, wire: bytes, current: int, olen: int +) -> Option: + """Build an EDNS option object from wire format. + + *otype*, an ``int``, is the option type. + + *wire*, a ``bytes``, is the wire-format message. + + *current*, an ``int``, is the offset in *wire* of the beginning + of the rdata. + + *olen*, an ``int``, is the length of the wire-format option data + + Returns an instance of a subclass of ``dns.edns.Option``. + """ + parser = dns.wire.Parser(wire, current) + with parser.restrict_to(olen): + return option_from_wire_parser(otype, parser) + + +def register_type(implementation: Any, otype: OptionType) -> None: + """Register the implementation of an option type. + + *implementation*, a ``class``, is a subclass of ``dns.edns.Option``. + + *otype*, an ``int``, is the option type. + """ + + _type_to_class[otype] = implementation + + +### BEGIN generated OptionType constants + +NSID = OptionType.NSID +DAU = OptionType.DAU +DHU = OptionType.DHU +N3U = OptionType.N3U +ECS = OptionType.ECS +EXPIRE = OptionType.EXPIRE +COOKIE = OptionType.COOKIE +KEEPALIVE = OptionType.KEEPALIVE +PADDING = OptionType.PADDING +CHAIN = OptionType.CHAIN +EDE = OptionType.EDE +REPORTCHANNEL = OptionType.REPORTCHANNEL + +### END generated OptionType constants diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/entropy.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/entropy.py new file mode 100644 index 000000000..f8faf202a --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/entropy.py @@ -0,0 +1,130 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +# Copyright (C) 2009-2017 Nominum, Inc. +# +# Permission to use, copy, modify, and distribute this software and its +# documentation for any purpose with or without fee is hereby granted, +# provided that the above copyright notice and this permission notice +# appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +import hashlib +import os +import random +import threading +import time +from typing import Any + + +class EntropyPool: + # This is an entropy pool for Python implementations that do not + # have a working SystemRandom. I'm not sure there are any, but + # leaving this code doesn't hurt anything as the library code + # is used if present. + + def __init__(self, seed: bytes | None = None): + self.pool_index = 0 + self.digest: bytearray | None = None + self.next_byte = 0 + self.lock = threading.Lock() + self.hash = hashlib.sha256() + self.hash_len = 32 + self.pool = bytearray(b"\0" * self.hash_len) + if seed is not None: + self._stir(seed) + self.seeded = True + self.seed_pid = os.getpid() + else: + self.seeded = False + self.seed_pid = 0 + + def _stir(self, entropy: bytes | bytearray) -> None: + for c in entropy: + if self.pool_index == self.hash_len: + self.pool_index = 0 + b = c & 0xFF + self.pool[self.pool_index] ^= b + self.pool_index += 1 + + def stir(self, entropy: bytes | bytearray) -> None: + with self.lock: + self._stir(entropy) + + def _maybe_seed(self) -> None: + if not self.seeded or self.seed_pid != os.getpid(): + try: + seed = os.urandom(16) + except Exception: # pragma: no cover + try: + with open("/dev/urandom", "rb", 0) as r: + seed = r.read(16) + except Exception: + seed = str(time.time()).encode() + self.seeded = True + self.seed_pid = os.getpid() + self.digest = None + seed = bytearray(seed) + self._stir(seed) + + def random_8(self) -> int: + with self.lock: + self._maybe_seed() + if self.digest is None or self.next_byte == self.hash_len: + self.hash.update(bytes(self.pool)) + self.digest = bytearray(self.hash.digest()) + self._stir(self.digest) + self.next_byte = 0 + value = self.digest[self.next_byte] + self.next_byte += 1 + return value + + def random_16(self) -> int: + return self.random_8() * 256 + self.random_8() + + def random_32(self) -> int: + return self.random_16() * 65536 + self.random_16() + + def random_between(self, first: int, last: int) -> int: + size = last - first + 1 + if size > 4294967296: + raise ValueError("too big") + if size > 65536: + rand = self.random_32 + max = 4294967295 + elif size > 256: + rand = self.random_16 + max = 65535 + else: + rand = self.random_8 + max = 255 + return first + size * rand() // (max + 1) + + +pool = EntropyPool() + +system_random: Any | None +try: + system_random = random.SystemRandom() +except Exception: # pragma: no cover + system_random = None + + +def random_16() -> int: + if system_random is not None: + return system_random.randrange(0, 65536) + else: + return pool.random_16() + + +def between(first: int, last: int) -> int: + if system_random is not None: + return system_random.randrange(first, last + 1) + else: + return pool.random_between(first, last) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/enum.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/enum.py new file mode 100644 index 000000000..822c9958f --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/enum.py @@ -0,0 +1,113 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +# Copyright (C) 2003-2017 Nominum, Inc. +# +# Permission to use, copy, modify, and distribute this software and its +# documentation for any purpose with or without fee is hereby granted, +# provided that the above copyright notice and this permission notice +# appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +import enum +from typing import Any, Type, TypeVar + +TIntEnum = TypeVar("TIntEnum", bound="IntEnum") + + +class IntEnum(enum.IntEnum): + @classmethod + def _missing_(cls, value): + cls._check_value(value) + val = int.__new__(cls, value) # pyright: ignore + val._name_ = cls._extra_to_text(value, None) or f"{cls._prefix()}{value}" + val._value_ = value # pyright: ignore + return val + + @classmethod + def _check_value(cls, value): + max = cls._maximum() + if not isinstance(value, int): + raise TypeError + if value < 0 or value > max: + name = cls._short_name() + raise ValueError(f"{name} must be an int between >= 0 and <= {max}") + + @classmethod + def from_text(cls: Type[TIntEnum], text: str) -> TIntEnum: + text = text.upper() + try: + return cls[text] + except KeyError: + pass + value = cls._extra_from_text(text) + if value: + return value + prefix = cls._prefix() + if text.startswith(prefix) and text[len(prefix) :].isdigit(): + value = int(text[len(prefix) :]) + cls._check_value(value) + return cls(value) + raise cls._unknown_exception_class() + + @classmethod + def to_text(cls: Type[TIntEnum], value: int) -> str: + cls._check_value(value) + try: + text = cls(value).name + except ValueError: + text = None + text = cls._extra_to_text(value, text) + if text is None: + text = f"{cls._prefix()}{value}" + return text + + @classmethod + def make(cls: Type[TIntEnum], value: int | str) -> TIntEnum: + """Convert text or a value into an enumerated type, if possible. + + *value*, the ``int`` or ``str`` to convert. + + Raises a class-specific exception if a ``str`` is provided that + cannot be converted. + + Raises ``ValueError`` if the value is out of range. + + Returns an enumeration from the calling class corresponding to the + value, if one is defined, or an ``int`` otherwise. + """ + + if isinstance(value, str): + return cls.from_text(value) + cls._check_value(value) + return cls(value) + + @classmethod + def _maximum(cls): + raise NotImplementedError # pragma: no cover + + @classmethod + def _short_name(cls): + return cls.__name__.lower() + + @classmethod + def _prefix(cls) -> str: + return "" + + @classmethod + def _extra_from_text(cls, text: str) -> Any | None: # pylint: disable=W0613 + return None + + @classmethod + def _extra_to_text(cls, value, current_text): # pylint: disable=W0613 + return current_text + + @classmethod + def _unknown_exception_class(cls) -> Type[Exception]: + return ValueError diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/exception.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/exception.py new file mode 100644 index 000000000..c3d42ffd3 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/exception.py @@ -0,0 +1,169 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +# Copyright (C) 2003-2017 Nominum, Inc. +# +# Permission to use, copy, modify, and distribute this software and its +# documentation for any purpose with or without fee is hereby granted, +# provided that the above copyright notice and this permission notice +# appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +"""Common DNS Exceptions. + +Dnspython modules may also define their own exceptions, which will +always be subclasses of ``DNSException``. +""" + + +from typing import Set + + +class DNSException(Exception): + """Abstract base class shared by all dnspython exceptions. + + It supports two basic modes of operation: + + a) Old/compatible mode is used if ``__init__`` was called with + empty *kwargs*. In compatible mode all *args* are passed + to the standard Python Exception class as before and all *args* are + printed by the standard ``__str__`` implementation. Class variable + ``msg`` (or doc string if ``msg`` is ``None``) is returned from ``str()`` + if *args* is empty. + + b) New/parametrized mode is used if ``__init__`` was called with + non-empty *kwargs*. + In the new mode *args* must be empty and all kwargs must match + those set in class variable ``supp_kwargs``. All kwargs are stored inside + ``self.kwargs`` and used in a new ``__str__`` implementation to construct + a formatted message based on the ``fmt`` class variable, a ``string``. + + In the simplest case it is enough to override the ``supp_kwargs`` + and ``fmt`` class variables to get nice parametrized messages. + """ + + msg: str | None = None # non-parametrized message + supp_kwargs: Set[str] = set() # accepted parameters for _fmt_kwargs (sanity check) + fmt: str | None = None # message parametrized with results from _fmt_kwargs + + def __init__(self, *args, **kwargs): + self._check_params(*args, **kwargs) + if kwargs: + # This call to a virtual method from __init__ is ok in our usage + self.kwargs = self._check_kwargs(**kwargs) # lgtm[py/init-calls-subclass] + self.msg = str(self) + else: + self.kwargs = dict() # defined but empty for old mode exceptions + if self.msg is None: + # doc string is better implicit message than empty string + self.msg = self.__doc__ + if args: + super().__init__(*args) + else: + super().__init__(self.msg) + + def _check_params(self, *args, **kwargs): + """Old exceptions supported only args and not kwargs. + + For sanity we do not allow to mix old and new behavior.""" + if args or kwargs: + assert bool(args) != bool( + kwargs + ), "keyword arguments are mutually exclusive with positional args" + + def _check_kwargs(self, **kwargs): + if kwargs: + assert ( + set(kwargs.keys()) == self.supp_kwargs + ), f"following set of keyword args is required: {self.supp_kwargs}" + return kwargs + + def _fmt_kwargs(self, **kwargs): + """Format kwargs before printing them. + + Resulting dictionary has to have keys necessary for str.format call + on fmt class variable. + """ + fmtargs = {} + for kw, data in kwargs.items(): + if isinstance(data, list | set): + # convert list of to list of str() + fmtargs[kw] = list(map(str, data)) + if len(fmtargs[kw]) == 1: + # remove list brackets [] from single-item lists + fmtargs[kw] = fmtargs[kw].pop() + else: + fmtargs[kw] = data + return fmtargs + + def __str__(self): + if self.kwargs and self.fmt: + # provide custom message constructed from keyword arguments + fmtargs = self._fmt_kwargs(**self.kwargs) + return self.fmt.format(**fmtargs) + else: + # print *args directly in the same way as old DNSException + return super().__str__() + + +class FormError(DNSException): + """DNS message is malformed.""" + + +class SyntaxError(DNSException): + """Text input is malformed.""" + + +class UnexpectedEnd(SyntaxError): + """Text input ended unexpectedly.""" + + +class TooBig(DNSException): + """The DNS message is too big.""" + + +class Timeout(DNSException): + """The DNS operation timed out.""" + + supp_kwargs = {"timeout"} + fmt = "The DNS operation timed out after {timeout:.3f} seconds" + + # We do this as otherwise mypy complains about unexpected keyword argument + # idna_exception + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + + +class UnsupportedAlgorithm(DNSException): + """The DNSSEC algorithm is not supported.""" + + +class AlgorithmKeyMismatch(UnsupportedAlgorithm): + """The DNSSEC algorithm is not supported for the given key type.""" + + +class ValidationFailure(DNSException): + """The DNSSEC signature is invalid.""" + + +class DeniedByPolicy(DNSException): + """Denied by DNSSEC policy.""" + + +class ExceptionWrapper: + def __init__(self, exception_class): + self.exception_class = exception_class + + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + if exc_type is not None and not isinstance(exc_val, self.exception_class): + raise self.exception_class(str(exc_val)) from exc_val + return False diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/flags.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/flags.py new file mode 100644 index 000000000..4c60be133 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/flags.py @@ -0,0 +1,123 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +# Copyright (C) 2001-2017 Nominum, Inc. +# +# Permission to use, copy, modify, and distribute this software and its +# documentation for any purpose with or without fee is hereby granted, +# provided that the above copyright notice and this permission notice +# appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +"""DNS Message Flags.""" + +import enum +from typing import Any + +# Standard DNS flags + + +class Flag(enum.IntFlag): + #: Query Response + QR = 0x8000 + #: Authoritative Answer + AA = 0x0400 + #: Truncated Response + TC = 0x0200 + #: Recursion Desired + RD = 0x0100 + #: Recursion Available + RA = 0x0080 + #: Authentic Data + AD = 0x0020 + #: Checking Disabled + CD = 0x0010 + + +# EDNS flags + + +class EDNSFlag(enum.IntFlag): + #: DNSSEC answer OK + DO = 0x8000 + + +def _from_text(text: str, enum_class: Any) -> int: + flags = 0 + tokens = text.split() + for t in tokens: + flags |= enum_class[t.upper()] + return flags + + +def _to_text(flags: int, enum_class: Any) -> str: + text_flags = [] + for k, v in enum_class.__members__.items(): + if flags & v != 0: + text_flags.append(k) + return " ".join(text_flags) + + +def from_text(text: str) -> int: + """Convert a space-separated list of flag text values into a flags + value. + + Returns an ``int`` + """ + + return _from_text(text, Flag) + + +def to_text(flags: int) -> str: + """Convert a flags value into a space-separated list of flag text + values. + + Returns a ``str``. + """ + + return _to_text(flags, Flag) + + +def edns_from_text(text: str) -> int: + """Convert a space-separated list of EDNS flag text values into a EDNS + flags value. + + Returns an ``int`` + """ + + return _from_text(text, EDNSFlag) + + +def edns_to_text(flags: int) -> str: + """Convert an EDNS flags value into a space-separated list of EDNS flag + text values. + + Returns a ``str``. + """ + + return _to_text(flags, EDNSFlag) + + +### BEGIN generated Flag constants + +QR = Flag.QR +AA = Flag.AA +TC = Flag.TC +RD = Flag.RD +RA = Flag.RA +AD = Flag.AD +CD = Flag.CD + +### END generated Flag constants + +### BEGIN generated EDNSFlag constants + +DO = EDNSFlag.DO + +### END generated EDNSFlag constants diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/grange.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/grange.py new file mode 100644 index 000000000..8d366dc8d --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/grange.py @@ -0,0 +1,72 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +# Copyright (C) 2012-2017 Nominum, Inc. +# +# Permission to use, copy, modify, and distribute this software and its +# documentation for any purpose with or without fee is hereby granted, +# provided that the above copyright notice and this permission notice +# appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +"""DNS GENERATE range conversion.""" + +from typing import Tuple + +import dns.exception + + +def from_text(text: str) -> Tuple[int, int, int]: + """Convert the text form of a range in a ``$GENERATE`` statement to an + integer. + + *text*, a ``str``, the textual range in ``$GENERATE`` form. + + Returns a tuple of three ``int`` values ``(start, stop, step)``. + """ + + start = -1 + stop = -1 + step = 1 + cur = "" + state = 0 + # state 0 1 2 + # x - y / z + + if text and text[0] == "-": + raise dns.exception.SyntaxError("Start cannot be a negative number") + + for c in text: + if c == "-" and state == 0: + start = int(cur) + cur = "" + state = 1 + elif c == "/": + stop = int(cur) + cur = "" + state = 2 + elif c.isdigit(): + cur += c + else: + raise dns.exception.SyntaxError(f"Could not parse {c}") + + if state == 0: + raise dns.exception.SyntaxError("no stop value specified") + elif state == 1: + stop = int(cur) + else: + assert state == 2 + step = int(cur) + + assert step >= 1 + assert start >= 0 + if start > stop: + raise dns.exception.SyntaxError("start must be <= stop") + + return (start, stop, step) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/immutable.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/immutable.py new file mode 100644 index 000000000..36b0362c7 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/immutable.py @@ -0,0 +1,68 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +import collections.abc +from typing import Any, Callable + +from dns._immutable_ctx import immutable + + +@immutable +class Dict(collections.abc.Mapping): # lgtm[py/missing-equals] + def __init__( + self, + dictionary: Any, + no_copy: bool = False, + map_factory: Callable[[], collections.abc.MutableMapping] = dict, + ): + """Make an immutable dictionary from the specified dictionary. + + If *no_copy* is `True`, then *dictionary* will be wrapped instead + of copied. Only set this if you are sure there will be no external + references to the dictionary. + """ + if no_copy and isinstance(dictionary, collections.abc.MutableMapping): + self._odict = dictionary + else: + self._odict = map_factory() + self._odict.update(dictionary) + self._hash = None + + def __getitem__(self, key): + return self._odict.__getitem__(key) + + def __hash__(self): # pylint: disable=invalid-hash-returned + if self._hash is None: + h = 0 + for key in sorted(self._odict.keys()): + h ^= hash(key) + object.__setattr__(self, "_hash", h) + # this does return an int, but pylint doesn't figure that out + return self._hash + + def __len__(self): + return len(self._odict) + + def __iter__(self): + return iter(self._odict) + + +def constify(o: Any) -> Any: + """ + Convert mutable types to immutable types. + """ + if isinstance(o, bytearray): + return bytes(o) + if isinstance(o, tuple): + try: + hash(o) + return o + except Exception: + return tuple(constify(elt) for elt in o) + if isinstance(o, list): + return tuple(constify(elt) for elt in o) + if isinstance(o, dict): + cdict = dict() + for k, v in o.items(): + cdict[k] = constify(v) + return Dict(cdict, True) + return o diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/inet.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/inet.py new file mode 100644 index 000000000..a721d9465 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/inet.py @@ -0,0 +1,195 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +# Copyright (C) 2003-2017 Nominum, Inc. +# +# Permission to use, copy, modify, and distribute this software and its +# documentation for any purpose with or without fee is hereby granted, +# provided that the above copyright notice and this permission notice +# appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +"""Generic Internet address helper functions.""" + +import socket +from typing import Any, Tuple + +import dns.ipv4 +import dns.ipv6 + +# We assume that AF_INET and AF_INET6 are always defined. We keep +# these here for the benefit of any old code (unlikely though that +# is!). +AF_INET = socket.AF_INET +AF_INET6 = socket.AF_INET6 + + +def inet_pton(family: int, text: str) -> bytes: + """Convert the textual form of a network address into its binary form. + + *family* is an ``int``, the address family. + + *text* is a ``str``, the textual address. + + Raises ``NotImplementedError`` if the address family specified is not + implemented. + + Returns a ``bytes``. + """ + + if family == AF_INET: + return dns.ipv4.inet_aton(text) + elif family == AF_INET6: + return dns.ipv6.inet_aton(text, True) + else: + raise NotImplementedError + + +def inet_ntop(family: int, address: bytes) -> str: + """Convert the binary form of a network address into its textual form. + + *family* is an ``int``, the address family. + + *address* is a ``bytes``, the network address in binary form. + + Raises ``NotImplementedError`` if the address family specified is not + implemented. + + Returns a ``str``. + """ + + if family == AF_INET: + return dns.ipv4.inet_ntoa(address) + elif family == AF_INET6: + return dns.ipv6.inet_ntoa(address) + else: + raise NotImplementedError + + +def af_for_address(text: str) -> int: + """Determine the address family of a textual-form network address. + + *text*, a ``str``, the textual address. + + Raises ``ValueError`` if the address family cannot be determined + from the input. + + Returns an ``int``. + """ + + try: + dns.ipv4.inet_aton(text) + return AF_INET + except Exception: + try: + dns.ipv6.inet_aton(text, True) + return AF_INET6 + except Exception: + raise ValueError + + +def is_multicast(text: str) -> bool: + """Is the textual-form network address a multicast address? + + *text*, a ``str``, the textual address. + + Raises ``ValueError`` if the address family cannot be determined + from the input. + + Returns a ``bool``. + """ + + try: + first = dns.ipv4.inet_aton(text)[0] + return first >= 224 and first <= 239 + except Exception: + try: + first = dns.ipv6.inet_aton(text, True)[0] + return first == 255 + except Exception: + raise ValueError + + +def is_address(text: str) -> bool: + """Is the specified string an IPv4 or IPv6 address? + + *text*, a ``str``, the textual address. + + Returns a ``bool``. + """ + + try: + dns.ipv4.inet_aton(text) + return True + except Exception: + try: + dns.ipv6.inet_aton(text, True) + return True + except Exception: + return False + + +def low_level_address_tuple(high_tuple: Tuple[str, int], af: int | None = None) -> Any: + """Given a "high-level" address tuple, i.e. + an (address, port) return the appropriate "low-level" address tuple + suitable for use in socket calls. + + If an *af* other than ``None`` is provided, it is assumed the + address in the high-level tuple is valid and has that af. If af + is ``None``, then af_for_address will be called. + """ + address, port = high_tuple + if af is None: + af = af_for_address(address) + if af == AF_INET: + return (address, port) + elif af == AF_INET6: + i = address.find("%") + if i < 0: + # no scope, shortcut! + return (address, port, 0, 0) + # try to avoid getaddrinfo() + addrpart = address[:i] + scope = address[i + 1 :] + if scope.isdigit(): + return (addrpart, port, 0, int(scope)) + try: + return (addrpart, port, 0, socket.if_nametoindex(scope)) + except AttributeError: # pragma: no cover (we can't really test this) + ai_flags = socket.AI_NUMERICHOST + ((*_, tup), *_) = socket.getaddrinfo(address, port, flags=ai_flags) + return tup + else: + raise NotImplementedError(f"unknown address family {af}") + + +def any_for_af(af): + """Return the 'any' address for the specified address family.""" + if af == socket.AF_INET: + return "127.0.0.1" + elif af == socket.AF_INET6: + return "::" + raise NotImplementedError(f"unknown address family {af}") + + +def canonicalize(text: str) -> str: + """Verify that *address* is a valid text form IPv4 or IPv6 address and return its + canonical text form. IPv6 addresses with scopes are rejected. + + *text*, a ``str``, the address in textual form. + + Raises ``ValueError`` if the text is not valid. + """ + try: + return dns.ipv6.canonicalize(text) + except Exception: + try: + return dns.ipv4.canonicalize(text) + except Exception: + raise ValueError diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/ipv4.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/ipv4.py new file mode 100644 index 000000000..a7161bc79 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/ipv4.py @@ -0,0 +1,76 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +# Copyright (C) 2003-2017 Nominum, Inc. +# +# Permission to use, copy, modify, and distribute this software and its +# documentation for any purpose with or without fee is hereby granted, +# provided that the above copyright notice and this permission notice +# appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +"""IPv4 helper functions.""" + +import struct + +import dns.exception + + +def inet_ntoa(address: bytes) -> str: + """Convert an IPv4 address in binary form to text form. + + *address*, a ``bytes``, the IPv4 address in binary form. + + Returns a ``str``. + """ + + if len(address) != 4: + raise dns.exception.SyntaxError + return f"{address[0]}.{address[1]}.{address[2]}.{address[3]}" + + +def inet_aton(text: str | bytes) -> bytes: + """Convert an IPv4 address in text form to binary form. + + *text*, a ``str`` or ``bytes``, the IPv4 address in textual form. + + Returns a ``bytes``. + """ + + if not isinstance(text, bytes): + btext = text.encode() + else: + btext = text + parts = btext.split(b".") + if len(parts) != 4: + raise dns.exception.SyntaxError + for part in parts: + if not part.isdigit(): + raise dns.exception.SyntaxError + if len(part) > 1 and part[0] == ord("0"): + # No leading zeros + raise dns.exception.SyntaxError + try: + b = [int(part) for part in parts] + return struct.pack("BBBB", *b) + except Exception: + raise dns.exception.SyntaxError + + +def canonicalize(text: str | bytes) -> str: + """Verify that *address* is a valid text form IPv4 address and return its + canonical text form. + + *text*, a ``str`` or ``bytes``, the IPv4 address in textual form. + + Raises ``dns.exception.SyntaxError`` if the text is not valid. + """ + # Note that inet_aton() only accepts canonial form, but we still run through + # inet_ntoa() to ensure the output is a str. + return inet_ntoa(inet_aton(text)) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/ipv6.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/ipv6.py new file mode 100644 index 000000000..eaa0f6c76 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/ipv6.py @@ -0,0 +1,217 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +# Copyright (C) 2003-2017 Nominum, Inc. +# +# Permission to use, copy, modify, and distribute this software and its +# documentation for any purpose with or without fee is hereby granted, +# provided that the above copyright notice and this permission notice +# appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +"""IPv6 helper functions.""" + +import binascii +import re +from typing import List + +import dns.exception +import dns.ipv4 + +_leading_zero = re.compile(r"0+([0-9a-f]+)") + + +def inet_ntoa(address: bytes) -> str: + """Convert an IPv6 address in binary form to text form. + + *address*, a ``bytes``, the IPv6 address in binary form. + + Raises ``ValueError`` if the address isn't 16 bytes long. + Returns a ``str``. + """ + + if len(address) != 16: + raise ValueError("IPv6 addresses are 16 bytes long") + hex = binascii.hexlify(address) + chunks = [] + i = 0 + l = len(hex) + while i < l: + chunk = hex[i : i + 4].decode() + # strip leading zeros. we do this with an re instead of + # with lstrip() because lstrip() didn't support chars until + # python 2.2.2 + m = _leading_zero.match(chunk) + if m is not None: + chunk = m.group(1) + chunks.append(chunk) + i += 4 + # + # Compress the longest subsequence of 0-value chunks to :: + # + best_start = 0 + best_len = 0 + start = -1 + last_was_zero = False + for i in range(8): + if chunks[i] != "0": + if last_was_zero: + end = i + current_len = end - start + if current_len > best_len: + best_start = start + best_len = current_len + last_was_zero = False + elif not last_was_zero: + start = i + last_was_zero = True + if last_was_zero: + end = 8 + current_len = end - start + if current_len > best_len: + best_start = start + best_len = current_len + if best_len > 1: + if best_start == 0 and (best_len == 6 or best_len == 5 and chunks[5] == "ffff"): + # We have an embedded IPv4 address + if best_len == 6: + prefix = "::" + else: + prefix = "::ffff:" + thex = prefix + dns.ipv4.inet_ntoa(address[12:]) + else: + thex = ( + ":".join(chunks[:best_start]) + + "::" + + ":".join(chunks[best_start + best_len :]) + ) + else: + thex = ":".join(chunks) + return thex + + +_v4_ending = re.compile(rb"(.*):(\d+\.\d+\.\d+\.\d+)$") +_colon_colon_start = re.compile(rb"::.*") +_colon_colon_end = re.compile(rb".*::$") + + +def inet_aton(text: str | bytes, ignore_scope: bool = False) -> bytes: + """Convert an IPv6 address in text form to binary form. + + *text*, a ``str`` or ``bytes``, the IPv6 address in textual form. + + *ignore_scope*, a ``bool``. If ``True``, a scope will be ignored. + If ``False``, the default, it is an error for a scope to be present. + + Returns a ``bytes``. + """ + + # + # Our aim here is not something fast; we just want something that works. + # + if not isinstance(text, bytes): + btext = text.encode() + else: + btext = text + + if ignore_scope: + parts = btext.split(b"%") + l = len(parts) + if l == 2: + btext = parts[0] + elif l > 2: + raise dns.exception.SyntaxError + + if btext == b"": + raise dns.exception.SyntaxError + elif btext.endswith(b":") and not btext.endswith(b"::"): + raise dns.exception.SyntaxError + elif btext.startswith(b":") and not btext.startswith(b"::"): + raise dns.exception.SyntaxError + elif btext == b"::": + btext = b"0::" + # + # Get rid of the icky dot-quad syntax if we have it. + # + m = _v4_ending.match(btext) + if m is not None: + b = dns.ipv4.inet_aton(m.group(2)) + btext = ( + f"{m.group(1).decode()}:{b[0]:02x}{b[1]:02x}:{b[2]:02x}{b[3]:02x}" + ).encode() + # + # Try to turn '::' into ':'; if no match try to + # turn '::' into ':' + # + m = _colon_colon_start.match(btext) + if m is not None: + btext = btext[1:] + else: + m = _colon_colon_end.match(btext) + if m is not None: + btext = btext[:-1] + # + # Now canonicalize into 8 chunks of 4 hex digits each + # + chunks = btext.split(b":") + l = len(chunks) + if l > 8: + raise dns.exception.SyntaxError + seen_empty = False + canonical: List[bytes] = [] + for c in chunks: + if c == b"": + if seen_empty: + raise dns.exception.SyntaxError + seen_empty = True + for _ in range(0, 8 - l + 1): + canonical.append(b"0000") + else: + lc = len(c) + if lc > 4: + raise dns.exception.SyntaxError + if lc != 4: + c = (b"0" * (4 - lc)) + c + canonical.append(c) + if l < 8 and not seen_empty: + raise dns.exception.SyntaxError + btext = b"".join(canonical) + + # + # Finally we can go to binary. + # + try: + return binascii.unhexlify(btext) + except (binascii.Error, TypeError): + raise dns.exception.SyntaxError + + +_mapped_prefix = b"\x00" * 10 + b"\xff\xff" + + +def is_mapped(address: bytes) -> bool: + """Is the specified address a mapped IPv4 address? + + *address*, a ``bytes`` is an IPv6 address in binary form. + + Returns a ``bool``. + """ + + return address.startswith(_mapped_prefix) + + +def canonicalize(text: str | bytes) -> str: + """Verify that *address* is a valid text form IPv6 address and return its + canonical text form. Addresses with scopes are rejected. + + *text*, a ``str`` or ``bytes``, the IPv6 address in textual form. + + Raises ``dns.exception.SyntaxError`` if the text is not valid. + """ + return inet_ntoa(inet_aton(text)) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/message.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/message.py new file mode 100644 index 000000000..bbfccfc7a --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/message.py @@ -0,0 +1,1954 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +# Copyright (C) 2001-2017 Nominum, Inc. +# +# Permission to use, copy, modify, and distribute this software and its +# documentation for any purpose with or without fee is hereby granted, +# provided that the above copyright notice and this permission notice +# appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +"""DNS Messages""" + +import contextlib +import enum +import io +import time +from typing import Any, Dict, List, Tuple, cast + +import dns.edns +import dns.entropy +import dns.enum +import dns.exception +import dns.flags +import dns.name +import dns.opcode +import dns.rcode +import dns.rdata +import dns.rdataclass +import dns.rdatatype +import dns.rdtypes.ANY.OPT +import dns.rdtypes.ANY.SOA +import dns.rdtypes.ANY.TSIG +import dns.renderer +import dns.rrset +import dns.tokenizer +import dns.tsig +import dns.ttl +import dns.wire + + +class ShortHeader(dns.exception.FormError): + """The DNS packet passed to from_wire() is too short.""" + + +class TrailingJunk(dns.exception.FormError): + """The DNS packet passed to from_wire() has extra junk at the end of it.""" + + +class UnknownHeaderField(dns.exception.DNSException): + """The header field name was not recognized when converting from text + into a message.""" + + +class BadEDNS(dns.exception.FormError): + """An OPT record occurred somewhere other than + the additional data section.""" + + +class BadTSIG(dns.exception.FormError): + """A TSIG record occurred somewhere other than the end of + the additional data section.""" + + +class UnknownTSIGKey(dns.exception.DNSException): + """A TSIG with an unknown key was received.""" + + +class Truncated(dns.exception.DNSException): + """The truncated flag is set.""" + + supp_kwargs = {"message"} + + # We do this as otherwise mypy complains about unexpected keyword argument + # idna_exception + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + + def message(self): + """As much of the message as could be processed. + + Returns a ``dns.message.Message``. + """ + return self.kwargs["message"] + + +class NotQueryResponse(dns.exception.DNSException): + """Message is not a response to a query.""" + + +class ChainTooLong(dns.exception.DNSException): + """The CNAME chain is too long.""" + + +class AnswerForNXDOMAIN(dns.exception.DNSException): + """The rcode is NXDOMAIN but an answer was found.""" + + +class NoPreviousName(dns.exception.SyntaxError): + """No previous name was known.""" + + +class MessageSection(dns.enum.IntEnum): + """Message sections""" + + QUESTION = 0 + ANSWER = 1 + AUTHORITY = 2 + ADDITIONAL = 3 + + @classmethod + def _maximum(cls): + return 3 + + +class MessageError: + def __init__(self, exception: Exception, offset: int): + self.exception = exception + self.offset = offset + + +DEFAULT_EDNS_PAYLOAD = 1232 +MAX_CHAIN = 16 + +IndexKeyType = Tuple[ + int, + dns.name.Name, + dns.rdataclass.RdataClass, + dns.rdatatype.RdataType, + dns.rdatatype.RdataType | None, + dns.rdataclass.RdataClass | None, +] +IndexType = Dict[IndexKeyType, dns.rrset.RRset] +SectionType = int | str | List[dns.rrset.RRset] + + +class Message: + """A DNS message.""" + + _section_enum = MessageSection + + def __init__(self, id: int | None = None): + if id is None: + self.id = dns.entropy.random_16() + else: + self.id = id + self.flags = 0 + self.sections: List[List[dns.rrset.RRset]] = [[], [], [], []] + self.opt: dns.rrset.RRset | None = None + self.request_payload = 0 + self.pad = 0 + self.keyring: Any = None + self.tsig: dns.rrset.RRset | None = None + self.want_tsig_sign = False + self.request_mac = b"" + self.xfr = False + self.origin: dns.name.Name | None = None + self.tsig_ctx: Any | None = None + self.index: IndexType = {} + self.errors: List[MessageError] = [] + self.time = 0.0 + self.wire: bytes | None = None + + @property + def question(self) -> List[dns.rrset.RRset]: + """The question section.""" + return self.sections[0] + + @question.setter + def question(self, v): + self.sections[0] = v + + @property + def answer(self) -> List[dns.rrset.RRset]: + """The answer section.""" + return self.sections[1] + + @answer.setter + def answer(self, v): + self.sections[1] = v + + @property + def authority(self) -> List[dns.rrset.RRset]: + """The authority section.""" + return self.sections[2] + + @authority.setter + def authority(self, v): + self.sections[2] = v + + @property + def additional(self) -> List[dns.rrset.RRset]: + """The additional data section.""" + return self.sections[3] + + @additional.setter + def additional(self, v): + self.sections[3] = v + + def __repr__(self): + return "" + + def __str__(self): + return self.to_text() + + def to_text( + self, + origin: dns.name.Name | None = None, + relativize: bool = True, + **kw: Dict[str, Any], + ) -> str: + """Convert the message to text. + + The *origin*, *relativize*, and any other keyword + arguments are passed to the RRset ``to_wire()`` method. + + Returns a ``str``. + """ + + s = io.StringIO() + s.write(f"id {self.id}\n") + s.write(f"opcode {dns.opcode.to_text(self.opcode())}\n") + s.write(f"rcode {dns.rcode.to_text(self.rcode())}\n") + s.write(f"flags {dns.flags.to_text(self.flags)}\n") + if self.edns >= 0: + s.write(f"edns {self.edns}\n") + if self.ednsflags != 0: + s.write(f"eflags {dns.flags.edns_to_text(self.ednsflags)}\n") + s.write(f"payload {self.payload}\n") + for opt in self.options: + s.write(f"option {opt.to_text()}\n") + for name, which in self._section_enum.__members__.items(): + s.write(f";{name}\n") + for rrset in self.section_from_number(which): + s.write(rrset.to_text(origin, relativize, **kw)) + s.write("\n") + if self.tsig is not None: + s.write(self.tsig.to_text(origin, relativize, **kw)) + s.write("\n") + # + # We strip off the final \n so the caller can print the result without + # doing weird things to get around eccentricities in Python print + # formatting + # + return s.getvalue()[:-1] + + def __eq__(self, other): + """Two messages are equal if they have the same content in the + header, question, answer, and authority sections. + + Returns a ``bool``. + """ + + if not isinstance(other, Message): + return False + if self.id != other.id: + return False + if self.flags != other.flags: + return False + for i, section in enumerate(self.sections): + other_section = other.sections[i] + for n in section: + if n not in other_section: + return False + for n in other_section: + if n not in section: + return False + return True + + def __ne__(self, other): + return not self.__eq__(other) + + def is_response(self, other: "Message") -> bool: + """Is *other*, also a ``dns.message.Message``, a response to this + message? + + Returns a ``bool``. + """ + + if ( + other.flags & dns.flags.QR == 0 + or self.id != other.id + or dns.opcode.from_flags(self.flags) != dns.opcode.from_flags(other.flags) + ): + return False + if other.rcode() in { + dns.rcode.FORMERR, + dns.rcode.SERVFAIL, + dns.rcode.NOTIMP, + dns.rcode.REFUSED, + }: + # We don't check the question section in these cases if + # the other question section is empty, even though they + # still really ought to have a question section. + if len(other.question) == 0: + return True + if dns.opcode.is_update(self.flags): + # This is assuming the "sender doesn't include anything + # from the update", but we don't care to check the other + # case, which is that all the sections are returned and + # identical. + return True + for n in self.question: + if n not in other.question: + return False + for n in other.question: + if n not in self.question: + return False + return True + + def section_number(self, section: List[dns.rrset.RRset]) -> int: + """Return the "section number" of the specified section for use + in indexing. + + *section* is one of the section attributes of this message. + + Raises ``ValueError`` if the section isn't known. + + Returns an ``int``. + """ + + for i, our_section in enumerate(self.sections): + if section is our_section: + return self._section_enum(i) + raise ValueError("unknown section") + + def section_from_number(self, number: int) -> List[dns.rrset.RRset]: + """Return the section list associated with the specified section + number. + + *number* is a section number `int` or the text form of a section + name. + + Raises ``ValueError`` if the section isn't known. + + Returns a ``list``. + """ + + section = self._section_enum.make(number) + return self.sections[section] + + def find_rrset( + self, + section: SectionType, + name: dns.name.Name, + rdclass: dns.rdataclass.RdataClass, + rdtype: dns.rdatatype.RdataType, + covers: dns.rdatatype.RdataType = dns.rdatatype.NONE, + deleting: dns.rdataclass.RdataClass | None = None, + create: bool = False, + force_unique: bool = False, + idna_codec: dns.name.IDNACodec | None = None, + ) -> dns.rrset.RRset: + """Find the RRset with the given attributes in the specified section. + + *section*, an ``int`` section number, a ``str`` section name, or one of + the section attributes of this message. This specifies the + the section of the message to search. For example:: + + my_message.find_rrset(my_message.answer, name, rdclass, rdtype) + my_message.find_rrset(dns.message.ANSWER, name, rdclass, rdtype) + my_message.find_rrset("ANSWER", name, rdclass, rdtype) + + *name*, a ``dns.name.Name`` or ``str``, the name of the RRset. + + *rdclass*, an ``int`` or ``str``, the class of the RRset. + + *rdtype*, an ``int`` or ``str``, the type of the RRset. + + *covers*, an ``int`` or ``str``, the covers value of the RRset. + The default is ``dns.rdatatype.NONE``. + + *deleting*, an ``int``, ``str``, or ``None``, the deleting value of the + RRset. The default is ``None``. + + *create*, a ``bool``. If ``True``, create the RRset if it is not found. + The created RRset is appended to *section*. + + *force_unique*, a ``bool``. If ``True`` and *create* is also ``True``, + create a new RRset regardless of whether a matching RRset exists + already. The default is ``False``. This is useful when creating + DDNS Update messages, as order matters for them. + + *idna_codec*, a ``dns.name.IDNACodec``, specifies the IDNA + encoder/decoder. If ``None``, the default IDNA 2003 encoder/decoder + is used. + + Raises ``KeyError`` if the RRset was not found and create was + ``False``. + + Returns a ``dns.rrset.RRset object``. + """ + + if isinstance(section, int): + section_number = section + section = self.section_from_number(section_number) + elif isinstance(section, str): + section_number = self._section_enum.from_text(section) + section = self.section_from_number(section_number) + else: + section_number = self.section_number(section) + if isinstance(name, str): + name = dns.name.from_text(name, idna_codec=idna_codec) + rdtype = dns.rdatatype.RdataType.make(rdtype) + rdclass = dns.rdataclass.RdataClass.make(rdclass) + covers = dns.rdatatype.RdataType.make(covers) + if deleting is not None: + deleting = dns.rdataclass.RdataClass.make(deleting) + key = (section_number, name, rdclass, rdtype, covers, deleting) + if not force_unique: + if self.index is not None: + rrset = self.index.get(key) + if rrset is not None: + return rrset + else: + for rrset in section: + if rrset.full_match(name, rdclass, rdtype, covers, deleting): + return rrset + if not create: + raise KeyError + rrset = dns.rrset.RRset(name, rdclass, rdtype, covers, deleting) + section.append(rrset) + if self.index is not None: + self.index[key] = rrset + return rrset + + def get_rrset( + self, + section: SectionType, + name: dns.name.Name, + rdclass: dns.rdataclass.RdataClass, + rdtype: dns.rdatatype.RdataType, + covers: dns.rdatatype.RdataType = dns.rdatatype.NONE, + deleting: dns.rdataclass.RdataClass | None = None, + create: bool = False, + force_unique: bool = False, + idna_codec: dns.name.IDNACodec | None = None, + ) -> dns.rrset.RRset | None: + """Get the RRset with the given attributes in the specified section. + + If the RRset is not found, None is returned. + + *section*, an ``int`` section number, a ``str`` section name, or one of + the section attributes of this message. This specifies the + the section of the message to search. For example:: + + my_message.get_rrset(my_message.answer, name, rdclass, rdtype) + my_message.get_rrset(dns.message.ANSWER, name, rdclass, rdtype) + my_message.get_rrset("ANSWER", name, rdclass, rdtype) + + *name*, a ``dns.name.Name`` or ``str``, the name of the RRset. + + *rdclass*, an ``int`` or ``str``, the class of the RRset. + + *rdtype*, an ``int`` or ``str``, the type of the RRset. + + *covers*, an ``int`` or ``str``, the covers value of the RRset. + The default is ``dns.rdatatype.NONE``. + + *deleting*, an ``int``, ``str``, or ``None``, the deleting value of the + RRset. The default is ``None``. + + *create*, a ``bool``. If ``True``, create the RRset if it is not found. + The created RRset is appended to *section*. + + *force_unique*, a ``bool``. If ``True`` and *create* is also ``True``, + create a new RRset regardless of whether a matching RRset exists + already. The default is ``False``. This is useful when creating + DDNS Update messages, as order matters for them. + + *idna_codec*, a ``dns.name.IDNACodec``, specifies the IDNA + encoder/decoder. If ``None``, the default IDNA 2003 encoder/decoder + is used. + + Returns a ``dns.rrset.RRset object`` or ``None``. + """ + + try: + rrset = self.find_rrset( + section, + name, + rdclass, + rdtype, + covers, + deleting, + create, + force_unique, + idna_codec, + ) + except KeyError: + rrset = None + return rrset + + def section_count(self, section: SectionType) -> int: + """Returns the number of records in the specified section. + + *section*, an ``int`` section number, a ``str`` section name, or one of + the section attributes of this message. This specifies the + the section of the message to count. For example:: + + my_message.section_count(my_message.answer) + my_message.section_count(dns.message.ANSWER) + my_message.section_count("ANSWER") + """ + + if isinstance(section, int): + section_number = section + section = self.section_from_number(section_number) + elif isinstance(section, str): + section_number = self._section_enum.from_text(section) + section = self.section_from_number(section_number) + else: + section_number = self.section_number(section) + count = sum(max(1, len(rrs)) for rrs in section) + if section_number == MessageSection.ADDITIONAL: + if self.opt is not None: + count += 1 + if self.tsig is not None: + count += 1 + return count + + def _compute_opt_reserve(self) -> int: + """Compute the size required for the OPT RR, padding excluded""" + if not self.opt: + return 0 + # 1 byte for the root name, 10 for the standard RR fields + size = 11 + # This would be more efficient if options had a size() method, but we won't + # worry about that for now. We also don't worry if there is an existing padding + # option, as it is unlikely and probably harmless, as the worst case is that we + # may add another, and this seems to be legal. + opt_rdata = cast(dns.rdtypes.ANY.OPT.OPT, self.opt[0]) + for option in opt_rdata.options: + wire = option.to_wire() + # We add 4 here to account for the option type and length + size += len(wire) + 4 + if self.pad: + # Padding will be added, so again add the option type and length. + size += 4 + return size + + def _compute_tsig_reserve(self) -> int: + """Compute the size required for the TSIG RR""" + # This would be more efficient if TSIGs had a size method, but we won't + # worry about for now. Also, we can't really cope with the potential + # compressibility of the TSIG owner name, so we estimate with the uncompressed + # size. We will disable compression when TSIG and padding are both is active + # so that the padding comes out right. + if not self.tsig: + return 0 + f = io.BytesIO() + self.tsig.to_wire(f) + return len(f.getvalue()) + + def to_wire( + self, + origin: dns.name.Name | None = None, + max_size: int = 0, + multi: bool = False, + tsig_ctx: Any | None = None, + prepend_length: bool = False, + prefer_truncation: bool = False, + **kw: Dict[str, Any], + ) -> bytes: + """Return a string containing the message in DNS compressed wire + format. + + Additional keyword arguments are passed to the RRset ``to_wire()`` + method. + + *origin*, a ``dns.name.Name`` or ``None``, the origin to be appended + to any relative names. If ``None``, and the message has an origin + attribute that is not ``None``, then it will be used. + + *max_size*, an ``int``, the maximum size of the wire format + output; default is 0, which means "the message's request + payload, if nonzero, or 65535". + + *multi*, a ``bool``, should be set to ``True`` if this message is + part of a multiple message sequence. + + *tsig_ctx*, a ``dns.tsig.HMACTSig`` or ``dns.tsig.GSSTSig`` object, the + ongoing TSIG context, used when signing zone transfers. + + *prepend_length*, a ``bool``, should be set to ``True`` if the caller + wants the message length prepended to the message itself. This is + useful for messages sent over TCP, TLS (DoT), or QUIC (DoQ). + + *prefer_truncation*, a ``bool``, should be set to ``True`` if the caller + wants the message to be truncated if it would otherwise exceed the + maximum length. If the truncation occurs before the additional section, + the TC bit will be set. + + Raises ``dns.exception.TooBig`` if *max_size* was exceeded. + + Returns a ``bytes``. + """ + + if origin is None and self.origin is not None: + origin = self.origin + if max_size == 0: + if self.request_payload != 0: + max_size = self.request_payload + else: + max_size = 65535 + if max_size < 512: + max_size = 512 + elif max_size > 65535: + max_size = 65535 + r = dns.renderer.Renderer(self.id, self.flags, max_size, origin) + opt_reserve = self._compute_opt_reserve() + r.reserve(opt_reserve) + tsig_reserve = self._compute_tsig_reserve() + r.reserve(tsig_reserve) + try: + for rrset in self.question: + r.add_question(rrset.name, rrset.rdtype, rrset.rdclass) + for rrset in self.answer: + r.add_rrset(dns.renderer.ANSWER, rrset, **kw) + for rrset in self.authority: + r.add_rrset(dns.renderer.AUTHORITY, rrset, **kw) + for rrset in self.additional: + r.add_rrset(dns.renderer.ADDITIONAL, rrset, **kw) + except dns.exception.TooBig: + if prefer_truncation: + if r.section < dns.renderer.ADDITIONAL: + r.flags |= dns.flags.TC + else: + raise + r.release_reserved() + if self.opt is not None: + r.add_opt(self.opt, self.pad, opt_reserve, tsig_reserve) + r.write_header() + if self.tsig is not None: + if self.want_tsig_sign: + (new_tsig, ctx) = dns.tsig.sign( + r.get_wire(), + self.keyring, + self.tsig[0], + int(time.time()), + self.request_mac, + tsig_ctx, + multi, + ) + self.tsig.clear() + self.tsig.add(new_tsig) + if multi: + self.tsig_ctx = ctx + r.add_rrset(dns.renderer.ADDITIONAL, self.tsig) + r.write_header() + wire = r.get_wire() + self.wire = wire + if prepend_length: + wire = len(wire).to_bytes(2, "big") + wire + return wire + + @staticmethod + def _make_tsig( + keyname, algorithm, time_signed, fudge, mac, original_id, error, other + ): + tsig = dns.rdtypes.ANY.TSIG.TSIG( + dns.rdataclass.ANY, + dns.rdatatype.TSIG, + algorithm, + time_signed, + fudge, + mac, + original_id, + error, + other, + ) + return dns.rrset.from_rdata(keyname, 0, tsig) + + def use_tsig( + self, + keyring: Any, + keyname: dns.name.Name | str | None = None, + fudge: int = 300, + original_id: int | None = None, + tsig_error: int = 0, + other_data: bytes = b"", + algorithm: dns.name.Name | str = dns.tsig.default_algorithm, + ) -> None: + """When sending, a TSIG signature using the specified key + should be added. + + *keyring*, a ``dict``, ``callable`` or ``dns.tsig.Key``, is either + the TSIG keyring or key to use. + + The format of a keyring dict is a mapping from TSIG key name, as + ``dns.name.Name`` to ``dns.tsig.Key`` or a TSIG secret, a ``bytes``. + If a ``dict`` *keyring* is specified but a *keyname* is not, the key + used will be the first key in the *keyring*. Note that the order of + keys in a dictionary is not defined, so applications should supply a + keyname when a ``dict`` keyring is used, unless they know the keyring + contains only one key. If a ``callable`` keyring is specified, the + callable will be called with the message and the keyname, and is + expected to return a key. + + *keyname*, a ``dns.name.Name``, ``str`` or ``None``, the name of + this TSIG key to use; defaults to ``None``. If *keyring* is a + ``dict``, the key must be defined in it. If *keyring* is a + ``dns.tsig.Key``, this is ignored. + + *fudge*, an ``int``, the TSIG time fudge. + + *original_id*, an ``int``, the TSIG original id. If ``None``, + the message's id is used. + + *tsig_error*, an ``int``, the TSIG error code. + + *other_data*, a ``bytes``, the TSIG other data. + + *algorithm*, a ``dns.name.Name`` or ``str``, the TSIG algorithm to use. This is + only used if *keyring* is a ``dict``, and the key entry is a ``bytes``. + """ + + if isinstance(keyring, dns.tsig.Key): + key = keyring + keyname = key.name + elif callable(keyring): + key = keyring(self, keyname) + else: + if isinstance(keyname, str): + keyname = dns.name.from_text(keyname) + if keyname is None: + keyname = next(iter(keyring)) + key = keyring[keyname] + if isinstance(key, bytes): + key = dns.tsig.Key(keyname, key, algorithm) + self.keyring = key + if original_id is None: + original_id = self.id + self.tsig = self._make_tsig( + keyname, + self.keyring.algorithm, + 0, + fudge, + b"\x00" * dns.tsig.mac_sizes[self.keyring.algorithm], + original_id, + tsig_error, + other_data, + ) + self.want_tsig_sign = True + + @property + def keyname(self) -> dns.name.Name | None: + if self.tsig: + return self.tsig.name + else: + return None + + @property + def keyalgorithm(self) -> dns.name.Name | None: + if self.tsig: + rdata = cast(dns.rdtypes.ANY.TSIG.TSIG, self.tsig[0]) + return rdata.algorithm + else: + return None + + @property + def mac(self) -> bytes | None: + if self.tsig: + rdata = cast(dns.rdtypes.ANY.TSIG.TSIG, self.tsig[0]) + return rdata.mac + else: + return None + + @property + def tsig_error(self) -> int | None: + if self.tsig: + rdata = cast(dns.rdtypes.ANY.TSIG.TSIG, self.tsig[0]) + return rdata.error + else: + return None + + @property + def had_tsig(self) -> bool: + return bool(self.tsig) + + @staticmethod + def _make_opt(flags=0, payload=DEFAULT_EDNS_PAYLOAD, options=None): + opt = dns.rdtypes.ANY.OPT.OPT(payload, dns.rdatatype.OPT, options or ()) + return dns.rrset.from_rdata(dns.name.root, int(flags), opt) + + def use_edns( + self, + edns: int | bool | None = 0, + ednsflags: int = 0, + payload: int = DEFAULT_EDNS_PAYLOAD, + request_payload: int | None = None, + options: List[dns.edns.Option] | None = None, + pad: int = 0, + ) -> None: + """Configure EDNS behavior. + + *edns*, an ``int``, is the EDNS level to use. Specifying ``None``, ``False``, + or ``-1`` means "do not use EDNS", and in this case the other parameters are + ignored. Specifying ``True`` is equivalent to specifying 0, i.e. "use EDNS0". + + *ednsflags*, an ``int``, the EDNS flag values. + + *payload*, an ``int``, is the EDNS sender's payload field, which is the maximum + size of UDP datagram the sender can handle. I.e. how big a response to this + message can be. + + *request_payload*, an ``int``, is the EDNS payload size to use when sending this + message. If not specified, defaults to the value of *payload*. + + *options*, a list of ``dns.edns.Option`` objects or ``None``, the EDNS options. + + *pad*, a non-negative ``int``. If 0, the default, do not pad; otherwise add + padding bytes to make the message size a multiple of *pad*. Note that if + padding is non-zero, an EDNS PADDING option will always be added to the + message. + """ + + if edns is None or edns is False: + edns = -1 + elif edns is True: + edns = 0 + if edns < 0: + self.opt = None + self.request_payload = 0 + else: + # make sure the EDNS version in ednsflags agrees with edns + ednsflags &= 0xFF00FFFF + ednsflags |= edns << 16 + if options is None: + options = [] + self.opt = self._make_opt(ednsflags, payload, options) + if request_payload is None: + request_payload = payload + self.request_payload = request_payload + if pad < 0: + raise ValueError("pad must be non-negative") + self.pad = pad + + @property + def edns(self) -> int: + if self.opt: + return (self.ednsflags & 0xFF0000) >> 16 + else: + return -1 + + @property + def ednsflags(self) -> int: + if self.opt: + return self.opt.ttl + else: + return 0 + + @ednsflags.setter + def ednsflags(self, v): + if self.opt: + self.opt.ttl = v + elif v: + self.opt = self._make_opt(v) + + @property + def payload(self) -> int: + if self.opt: + rdata = cast(dns.rdtypes.ANY.OPT.OPT, self.opt[0]) + return rdata.payload + else: + return 0 + + @property + def options(self) -> Tuple: + if self.opt: + rdata = cast(dns.rdtypes.ANY.OPT.OPT, self.opt[0]) + return rdata.options + else: + return () + + def want_dnssec(self, wanted: bool = True) -> None: + """Enable or disable 'DNSSEC desired' flag in requests. + + *wanted*, a ``bool``. If ``True``, then DNSSEC data is + desired in the response, EDNS is enabled if required, and then + the DO bit is set. If ``False``, the DO bit is cleared if + EDNS is enabled. + """ + + if wanted: + self.ednsflags |= dns.flags.DO + elif self.opt: + self.ednsflags &= ~int(dns.flags.DO) + + def rcode(self) -> dns.rcode.Rcode: + """Return the rcode. + + Returns a ``dns.rcode.Rcode``. + """ + return dns.rcode.from_flags(int(self.flags), int(self.ednsflags)) + + def set_rcode(self, rcode: dns.rcode.Rcode) -> None: + """Set the rcode. + + *rcode*, a ``dns.rcode.Rcode``, is the rcode to set. + """ + (value, evalue) = dns.rcode.to_flags(rcode) + self.flags &= 0xFFF0 + self.flags |= value + self.ednsflags &= 0x00FFFFFF + self.ednsflags |= evalue + + def opcode(self) -> dns.opcode.Opcode: + """Return the opcode. + + Returns a ``dns.opcode.Opcode``. + """ + return dns.opcode.from_flags(int(self.flags)) + + def set_opcode(self, opcode: dns.opcode.Opcode) -> None: + """Set the opcode. + + *opcode*, a ``dns.opcode.Opcode``, is the opcode to set. + """ + self.flags &= 0x87FF + self.flags |= dns.opcode.to_flags(opcode) + + def get_options(self, otype: dns.edns.OptionType) -> List[dns.edns.Option]: + """Return the list of options of the specified type.""" + return [option for option in self.options if option.otype == otype] + + def extended_errors(self) -> List[dns.edns.EDEOption]: + """Return the list of Extended DNS Error (EDE) options in the message""" + return cast(List[dns.edns.EDEOption], self.get_options(dns.edns.OptionType.EDE)) + + def _get_one_rr_per_rrset(self, value): + # What the caller picked is fine. + return value + + # pylint: disable=unused-argument + + def _parse_rr_header(self, section, name, rdclass, rdtype): + return (rdclass, rdtype, None, False) + + # pylint: enable=unused-argument + + def _parse_special_rr_header(self, section, count, position, name, rdclass, rdtype): + if rdtype == dns.rdatatype.OPT: + if ( + section != MessageSection.ADDITIONAL + or self.opt + or name != dns.name.root + ): + raise BadEDNS + elif rdtype == dns.rdatatype.TSIG: + if ( + section != MessageSection.ADDITIONAL + or rdclass != dns.rdatatype.ANY + or position != count - 1 + ): + raise BadTSIG + return (rdclass, rdtype, None, False) + + +class ChainingResult: + """The result of a call to dns.message.QueryMessage.resolve_chaining(). + + The ``answer`` attribute is the answer RRSet, or ``None`` if it doesn't + exist. + + The ``canonical_name`` attribute is the canonical name after all + chaining has been applied (this is the same name as ``rrset.name`` in cases + where rrset is not ``None``). + + The ``minimum_ttl`` attribute is the minimum TTL, i.e. the TTL to + use if caching the data. It is the smallest of all the CNAME TTLs + and either the answer TTL if it exists or the SOA TTL and SOA + minimum values for negative answers. + + The ``cnames`` attribute is a list of all the CNAME RRSets followed to + get to the canonical name. + """ + + def __init__( + self, + canonical_name: dns.name.Name, + answer: dns.rrset.RRset | None, + minimum_ttl: int, + cnames: List[dns.rrset.RRset], + ): + self.canonical_name = canonical_name + self.answer = answer + self.minimum_ttl = minimum_ttl + self.cnames = cnames + + +class QueryMessage(Message): + def resolve_chaining(self) -> ChainingResult: + """Follow the CNAME chain in the response to determine the answer + RRset. + + Raises ``dns.message.NotQueryResponse`` if the message is not + a response. + + Raises ``dns.message.ChainTooLong`` if the CNAME chain is too long. + + Raises ``dns.message.AnswerForNXDOMAIN`` if the rcode is NXDOMAIN + but an answer was found. + + Raises ``dns.exception.FormError`` if the question count is not 1. + + Returns a ChainingResult object. + """ + if self.flags & dns.flags.QR == 0: + raise NotQueryResponse + if len(self.question) != 1: + raise dns.exception.FormError + question = self.question[0] + qname = question.name + min_ttl = dns.ttl.MAX_TTL + answer = None + count = 0 + cnames = [] + while count < MAX_CHAIN: + try: + answer = self.find_rrset( + self.answer, qname, question.rdclass, question.rdtype + ) + min_ttl = min(min_ttl, answer.ttl) + break + except KeyError: + if question.rdtype != dns.rdatatype.CNAME: + try: + crrset = self.find_rrset( + self.answer, qname, question.rdclass, dns.rdatatype.CNAME + ) + cnames.append(crrset) + min_ttl = min(min_ttl, crrset.ttl) + for rd in crrset: + qname = rd.target + break + count += 1 + continue + except KeyError: + # Exit the chaining loop + break + else: + # Exit the chaining loop + break + if count >= MAX_CHAIN: + raise ChainTooLong + if self.rcode() == dns.rcode.NXDOMAIN and answer is not None: + raise AnswerForNXDOMAIN + if answer is None: + # Further minimize the TTL with NCACHE. + auname = qname + while True: + # Look for an SOA RR whose owner name is a superdomain + # of qname. + try: + srrset = self.find_rrset( + self.authority, auname, question.rdclass, dns.rdatatype.SOA + ) + srdata = cast(dns.rdtypes.ANY.SOA.SOA, srrset[0]) + min_ttl = min(min_ttl, srrset.ttl, srdata.minimum) + break + except KeyError: + try: + auname = auname.parent() + except dns.name.NoParent: + break + return ChainingResult(qname, answer, min_ttl, cnames) + + def canonical_name(self) -> dns.name.Name: + """Return the canonical name of the first name in the question + section. + + Raises ``dns.message.NotQueryResponse`` if the message is not + a response. + + Raises ``dns.message.ChainTooLong`` if the CNAME chain is too long. + + Raises ``dns.message.AnswerForNXDOMAIN`` if the rcode is NXDOMAIN + but an answer was found. + + Raises ``dns.exception.FormError`` if the question count is not 1. + """ + return self.resolve_chaining().canonical_name + + +def _maybe_import_update(): + # We avoid circular imports by doing this here. We do it in another + # function as doing it in _message_factory_from_opcode() makes "dns" + # a local symbol, and the first line fails :) + + # pylint: disable=redefined-outer-name,import-outside-toplevel,unused-import + import dns.update # noqa: F401 + + +def _message_factory_from_opcode(opcode): + if opcode == dns.opcode.QUERY: + return QueryMessage + elif opcode == dns.opcode.UPDATE: + _maybe_import_update() + return dns.update.UpdateMessage # pyright: ignore + else: + return Message + + +class _WireReader: + """Wire format reader. + + parser: the binary parser + message: The message object being built + initialize_message: Callback to set message parsing options + question_only: Are we only reading the question? + one_rr_per_rrset: Put each RR into its own RRset? + keyring: TSIG keyring + ignore_trailing: Ignore trailing junk at end of request? + multi: Is this message part of a multi-message sequence? + DNS dynamic updates. + continue_on_error: try to extract as much information as possible from + the message, accumulating MessageErrors in the *errors* attribute instead of + raising them. + """ + + def __init__( + self, + wire, + initialize_message, + question_only=False, + one_rr_per_rrset=False, + ignore_trailing=False, + keyring=None, + multi=False, + continue_on_error=False, + ): + self.parser = dns.wire.Parser(wire) + self.message = None + self.initialize_message = initialize_message + self.question_only = question_only + self.one_rr_per_rrset = one_rr_per_rrset + self.ignore_trailing = ignore_trailing + self.keyring = keyring + self.multi = multi + self.continue_on_error = continue_on_error + self.errors = [] + + def _get_question(self, section_number, qcount): + """Read the next *qcount* records from the wire data and add them to + the question section. + """ + assert self.message is not None + section = self.message.sections[section_number] + for _ in range(qcount): + qname = self.parser.get_name(self.message.origin) + (rdtype, rdclass) = self.parser.get_struct("!HH") + (rdclass, rdtype, _, _) = self.message._parse_rr_header( + section_number, qname, rdclass, rdtype + ) + self.message.find_rrset( + section, qname, rdclass, rdtype, create=True, force_unique=True + ) + + def _add_error(self, e): + self.errors.append(MessageError(e, self.parser.current)) + + def _get_section(self, section_number, count): + """Read the next I{count} records from the wire data and add them to + the specified section. + + section_number: the section of the message to which to add records + count: the number of records to read + """ + assert self.message is not None + section = self.message.sections[section_number] + force_unique = self.one_rr_per_rrset + for i in range(count): + rr_start = self.parser.current + absolute_name = self.parser.get_name() + if self.message.origin is not None: + name = absolute_name.relativize(self.message.origin) + else: + name = absolute_name + (rdtype, rdclass, ttl, rdlen) = self.parser.get_struct("!HHIH") + if rdtype in (dns.rdatatype.OPT, dns.rdatatype.TSIG): + ( + rdclass, + rdtype, + deleting, + empty, + ) = self.message._parse_special_rr_header( + section_number, count, i, name, rdclass, rdtype + ) + else: + (rdclass, rdtype, deleting, empty) = self.message._parse_rr_header( + section_number, name, rdclass, rdtype + ) + rdata_start = self.parser.current + try: + if empty: + if rdlen > 0: + raise dns.exception.FormError + rd = None + covers = dns.rdatatype.NONE + else: + with self.parser.restrict_to(rdlen): + rd = dns.rdata.from_wire_parser( + rdclass, # pyright: ignore + rdtype, + self.parser, + self.message.origin, + ) + covers = rd.covers() + if self.message.xfr and rdtype == dns.rdatatype.SOA: + force_unique = True + if rdtype == dns.rdatatype.OPT: + self.message.opt = dns.rrset.from_rdata(name, ttl, rd) + elif rdtype == dns.rdatatype.TSIG: + trd = cast(dns.rdtypes.ANY.TSIG.TSIG, rd) + if self.keyring is None or self.keyring is True: + raise UnknownTSIGKey("got signed message without keyring") + elif isinstance(self.keyring, dict): + key = self.keyring.get(absolute_name) + if isinstance(key, bytes): + key = dns.tsig.Key(absolute_name, key, trd.algorithm) + elif callable(self.keyring): + key = self.keyring(self.message, absolute_name) + else: + key = self.keyring + if key is None: + raise UnknownTSIGKey(f"key '{name}' unknown") + if key: + self.message.keyring = key + self.message.tsig_ctx = dns.tsig.validate( + self.parser.wire, + key, + absolute_name, + rd, + int(time.time()), + self.message.request_mac, + rr_start, + self.message.tsig_ctx, + self.multi, + ) + self.message.tsig = dns.rrset.from_rdata(absolute_name, 0, rd) + else: + rrset = self.message.find_rrset( + section, + name, + rdclass, # pyright: ignore + rdtype, + covers, + deleting, + True, + force_unique, + ) + if rd is not None: + if ttl > 0x7FFFFFFF: + ttl = 0 + rrset.add(rd, ttl) + except Exception as e: + if self.continue_on_error: + self._add_error(e) + self.parser.seek(rdata_start + rdlen) + else: + raise + + def read(self): + """Read a wire format DNS message and build a dns.message.Message + object.""" + + if self.parser.remaining() < 12: + raise ShortHeader + (id, flags, qcount, ancount, aucount, adcount) = self.parser.get_struct( + "!HHHHHH" + ) + factory = _message_factory_from_opcode(dns.opcode.from_flags(flags)) + self.message = factory(id=id) + self.message.flags = dns.flags.Flag(flags) + self.message.wire = self.parser.wire + self.initialize_message(self.message) + self.one_rr_per_rrset = self.message._get_one_rr_per_rrset( + self.one_rr_per_rrset + ) + try: + self._get_question(MessageSection.QUESTION, qcount) + if self.question_only: + return self.message + self._get_section(MessageSection.ANSWER, ancount) + self._get_section(MessageSection.AUTHORITY, aucount) + self._get_section(MessageSection.ADDITIONAL, adcount) + if not self.ignore_trailing and self.parser.remaining() != 0: + raise TrailingJunk + if self.multi and self.message.tsig_ctx and not self.message.had_tsig: + self.message.tsig_ctx.update(self.parser.wire) + except Exception as e: + if self.continue_on_error: + self._add_error(e) + else: + raise + return self.message + + +def from_wire( + wire: bytes, + keyring: Any | None = None, + request_mac: bytes | None = b"", + xfr: bool = False, + origin: dns.name.Name | None = None, + tsig_ctx: dns.tsig.HMACTSig | dns.tsig.GSSTSig | None = None, + multi: bool = False, + question_only: bool = False, + one_rr_per_rrset: bool = False, + ignore_trailing: bool = False, + raise_on_truncation: bool = False, + continue_on_error: bool = False, +) -> Message: + """Convert a DNS wire format message into a message object. + + *keyring*, a ``dns.tsig.Key``, ``dict``, ``bool``, or ``None``, the key or keyring + to use if the message is signed. If ``None`` or ``True``, then trying to decode + a message with a TSIG will fail as it cannot be validated. If ``False``, then + TSIG validation is disabled. + + *request_mac*, a ``bytes`` or ``None``. If the message is a response to a + TSIG-signed request, *request_mac* should be set to the MAC of that request. + + *xfr*, a ``bool``, should be set to ``True`` if this message is part of a zone + transfer. + + *origin*, a ``dns.name.Name`` or ``None``. If the message is part of a zone + transfer, *origin* should be the origin name of the zone. If not ``None``, names + will be relativized to the origin. + + *tsig_ctx*, a ``dns.tsig.HMACTSig`` or ``dns.tsig.GSSTSig`` object, the ongoing TSIG + context, used when validating zone transfers. + + *multi*, a ``bool``, should be set to ``True`` if this message is part of a multiple + message sequence. + + *question_only*, a ``bool``. If ``True``, read only up to the end of the question + section. + + *one_rr_per_rrset*, a ``bool``. If ``True``, put each RR into its own RRset. + + *ignore_trailing*, a ``bool``. If ``True``, ignore trailing junk at end of the + message. + + *raise_on_truncation*, a ``bool``. If ``True``, raise an exception if the TC bit is + set. + + *continue_on_error*, a ``bool``. If ``True``, try to continue parsing even if + errors occur. Erroneous rdata will be ignored. Errors will be accumulated as a + list of MessageError objects in the message's ``errors`` attribute. This option is + recommended only for DNS analysis tools, or for use in a server as part of an error + handling path. The default is ``False``. + + Raises ``dns.message.ShortHeader`` if the message is less than 12 octets long. + + Raises ``dns.message.TrailingJunk`` if there were octets in the message past the end + of the proper DNS message, and *ignore_trailing* is ``False``. + + Raises ``dns.message.BadEDNS`` if an OPT record was in the wrong section, or + occurred more than once. + + Raises ``dns.message.BadTSIG`` if a TSIG record was not the last record of the + additional data section. + + Raises ``dns.message.Truncated`` if the TC flag is set and *raise_on_truncation* is + ``True``. + + Returns a ``dns.message.Message``. + """ + + # We permit None for request_mac solely for backwards compatibility + if request_mac is None: + request_mac = b"" + + def initialize_message(message): + message.request_mac = request_mac + message.xfr = xfr + message.origin = origin + message.tsig_ctx = tsig_ctx + + reader = _WireReader( + wire, + initialize_message, + question_only, + one_rr_per_rrset, + ignore_trailing, + keyring, + multi, + continue_on_error, + ) + try: + m = reader.read() + except dns.exception.FormError: + if ( + reader.message + and (reader.message.flags & dns.flags.TC) + and raise_on_truncation + ): + raise Truncated(message=reader.message) + else: + raise + # Reading a truncated message might not have any errors, so we + # have to do this check here too. + if m.flags & dns.flags.TC and raise_on_truncation: + raise Truncated(message=m) + if continue_on_error: + m.errors = reader.errors + + return m + + +class _TextReader: + """Text format reader. + + tok: the tokenizer. + message: The message object being built. + DNS dynamic updates. + last_name: The most recently read name when building a message object. + one_rr_per_rrset: Put each RR into its own RRset? + origin: The origin for relative names + relativize: relativize names? + relativize_to: the origin to relativize to. + """ + + def __init__( + self, + text: str, + idna_codec: dns.name.IDNACodec | None, + one_rr_per_rrset: bool = False, + origin: dns.name.Name | None = None, + relativize: bool = True, + relativize_to: dns.name.Name | None = None, + ): + self.message: Message | None = None # mypy: ignore + self.tok = dns.tokenizer.Tokenizer(text, idna_codec=idna_codec) + self.last_name = None + self.one_rr_per_rrset = one_rr_per_rrset + self.origin = origin + self.relativize = relativize + self.relativize_to = relativize_to + self.id = None + self.edns = -1 + self.ednsflags = 0 + self.payload = DEFAULT_EDNS_PAYLOAD + self.rcode = None + self.opcode = dns.opcode.QUERY + self.flags = 0 + + def _header_line(self, _): + """Process one line from the text format header section.""" + + token = self.tok.get() + what = token.value + if what == "id": + self.id = self.tok.get_int() + elif what == "flags": + while True: + token = self.tok.get() + if not token.is_identifier(): + self.tok.unget(token) + break + self.flags = self.flags | dns.flags.from_text(token.value) + elif what == "edns": + self.edns = self.tok.get_int() + self.ednsflags = self.ednsflags | (self.edns << 16) + elif what == "eflags": + if self.edns < 0: + self.edns = 0 + while True: + token = self.tok.get() + if not token.is_identifier(): + self.tok.unget(token) + break + self.ednsflags = self.ednsflags | dns.flags.edns_from_text(token.value) + elif what == "payload": + self.payload = self.tok.get_int() + if self.edns < 0: + self.edns = 0 + elif what == "opcode": + text = self.tok.get_string() + self.opcode = dns.opcode.from_text(text) + self.flags = self.flags | dns.opcode.to_flags(self.opcode) + elif what == "rcode": + text = self.tok.get_string() + self.rcode = dns.rcode.from_text(text) + else: + raise UnknownHeaderField + self.tok.get_eol() + + def _question_line(self, section_number): + """Process one line from the text format question section.""" + + assert self.message is not None + section = self.message.sections[section_number] + token = self.tok.get(want_leading=True) + if not token.is_whitespace(): + self.last_name = self.tok.as_name( + token, self.message.origin, self.relativize, self.relativize_to + ) + name = self.last_name + if name is None: + raise NoPreviousName + token = self.tok.get() + if not token.is_identifier(): + raise dns.exception.SyntaxError + # Class + try: + rdclass = dns.rdataclass.from_text(token.value) + token = self.tok.get() + if not token.is_identifier(): + raise dns.exception.SyntaxError + except dns.exception.SyntaxError: + raise dns.exception.SyntaxError + except Exception: + rdclass = dns.rdataclass.IN + # Type + rdtype = dns.rdatatype.from_text(token.value) + (rdclass, rdtype, _, _) = self.message._parse_rr_header( + section_number, name, rdclass, rdtype + ) + self.message.find_rrset( + section, name, rdclass, rdtype, create=True, force_unique=True + ) + self.tok.get_eol() + + def _rr_line(self, section_number): + """Process one line from the text format answer, authority, or + additional data sections. + """ + + assert self.message is not None + section = self.message.sections[section_number] + # Name + token = self.tok.get(want_leading=True) + if not token.is_whitespace(): + self.last_name = self.tok.as_name( + token, self.message.origin, self.relativize, self.relativize_to + ) + name = self.last_name + if name is None: + raise NoPreviousName + token = self.tok.get() + if not token.is_identifier(): + raise dns.exception.SyntaxError + # TTL + try: + ttl = int(token.value, 0) + token = self.tok.get() + if not token.is_identifier(): + raise dns.exception.SyntaxError + except dns.exception.SyntaxError: + raise dns.exception.SyntaxError + except Exception: + ttl = 0 + # Class + try: + rdclass = dns.rdataclass.from_text(token.value) + token = self.tok.get() + if not token.is_identifier(): + raise dns.exception.SyntaxError + except dns.exception.SyntaxError: + raise dns.exception.SyntaxError + except Exception: + rdclass = dns.rdataclass.IN + # Type + rdtype = dns.rdatatype.from_text(token.value) + (rdclass, rdtype, deleting, empty) = self.message._parse_rr_header( + section_number, name, rdclass, rdtype + ) + token = self.tok.get() + if empty and not token.is_eol_or_eof(): + raise dns.exception.SyntaxError + if not empty and token.is_eol_or_eof(): + raise dns.exception.UnexpectedEnd + if not token.is_eol_or_eof(): + self.tok.unget(token) + rd = dns.rdata.from_text( + rdclass, + rdtype, + self.tok, + self.message.origin, + self.relativize, + self.relativize_to, + ) + covers = rd.covers() + else: + rd = None + covers = dns.rdatatype.NONE + rrset = self.message.find_rrset( + section, + name, + rdclass, + rdtype, + covers, + deleting, + True, + self.one_rr_per_rrset, + ) + if rd is not None: + rrset.add(rd, ttl) + + def _make_message(self): + factory = _message_factory_from_opcode(self.opcode) + message = factory(id=self.id) + message.flags = self.flags + if self.edns >= 0: + message.use_edns(self.edns, self.ednsflags, self.payload) + if self.rcode: + message.set_rcode(self.rcode) + if self.origin: + message.origin = self.origin + return message + + def read(self): + """Read a text format DNS message and build a dns.message.Message + object.""" + + line_method = self._header_line + section_number = None + while 1: + token = self.tok.get(True, True) + if token.is_eol_or_eof(): + break + if token.is_comment(): + u = token.value.upper() + if u == "HEADER": + line_method = self._header_line + + if self.message: + message = self.message + else: + # If we don't have a message, create one with the current + # opcode, so that we know which section names to parse. + message = self._make_message() + try: + section_number = message._section_enum.from_text(u) + # We found a section name. If we don't have a message, + # use the one we just created. + if not self.message: + self.message = message + self.one_rr_per_rrset = message._get_one_rr_per_rrset( + self.one_rr_per_rrset + ) + if section_number == MessageSection.QUESTION: + line_method = self._question_line + else: + line_method = self._rr_line + except Exception: + # It's just a comment. + pass + self.tok.get_eol() + continue + self.tok.unget(token) + line_method(section_number) + if not self.message: + self.message = self._make_message() + return self.message + + +def from_text( + text: str, + idna_codec: dns.name.IDNACodec | None = None, + one_rr_per_rrset: bool = False, + origin: dns.name.Name | None = None, + relativize: bool = True, + relativize_to: dns.name.Name | None = None, +) -> Message: + """Convert the text format message into a message object. + + The reader stops after reading the first blank line in the input to + facilitate reading multiple messages from a single file with + ``dns.message.from_file()``. + + *text*, a ``str``, the text format message. + + *idna_codec*, a ``dns.name.IDNACodec``, specifies the IDNA + encoder/decoder. If ``None``, the default IDNA 2003 encoder/decoder + is used. + + *one_rr_per_rrset*, a ``bool``. If ``True``, then each RR is put + into its own rrset. The default is ``False``. + + *origin*, a ``dns.name.Name`` (or ``None``), the + origin to use for relative names. + + *relativize*, a ``bool``. If true, name will be relativized. + + *relativize_to*, a ``dns.name.Name`` (or ``None``), the origin to use + when relativizing names. If not set, the *origin* value will be used. + + Raises ``dns.message.UnknownHeaderField`` if a header is unknown. + + Raises ``dns.exception.SyntaxError`` if the text is badly formed. + + Returns a ``dns.message.Message object`` + """ + + # 'text' can also be a file, but we don't publish that fact + # since it's an implementation detail. The official file + # interface is from_file(). + + reader = _TextReader( + text, idna_codec, one_rr_per_rrset, origin, relativize, relativize_to + ) + return reader.read() + + +def from_file( + f: Any, + idna_codec: dns.name.IDNACodec | None = None, + one_rr_per_rrset: bool = False, +) -> Message: + """Read the next text format message from the specified file. + + Message blocks are separated by a single blank line. + + *f*, a ``file`` or ``str``. If *f* is text, it is treated as the + pathname of a file to open. + + *idna_codec*, a ``dns.name.IDNACodec``, specifies the IDNA + encoder/decoder. If ``None``, the default IDNA 2003 encoder/decoder + is used. + + *one_rr_per_rrset*, a ``bool``. If ``True``, then each RR is put + into its own rrset. The default is ``False``. + + Raises ``dns.message.UnknownHeaderField`` if a header is unknown. + + Raises ``dns.exception.SyntaxError`` if the text is badly formed. + + Returns a ``dns.message.Message object`` + """ + + if isinstance(f, str): + cm: contextlib.AbstractContextManager = open(f, encoding="utf-8") + else: + cm = contextlib.nullcontext(f) + with cm as f: + return from_text(f, idna_codec, one_rr_per_rrset) + assert False # for mypy lgtm[py/unreachable-statement] + + +def make_query( + qname: dns.name.Name | str, + rdtype: dns.rdatatype.RdataType | str, + rdclass: dns.rdataclass.RdataClass | str = dns.rdataclass.IN, + use_edns: int | bool | None = None, + want_dnssec: bool = False, + ednsflags: int | None = None, + payload: int | None = None, + request_payload: int | None = None, + options: List[dns.edns.Option] | None = None, + idna_codec: dns.name.IDNACodec | None = None, + id: int | None = None, + flags: int = dns.flags.RD, + pad: int = 0, +) -> QueryMessage: + """Make a query message. + + The query name, type, and class may all be specified either + as objects of the appropriate type, or as strings. + + The query will have a randomly chosen query id, and its DNS flags + will be set to dns.flags.RD. + + qname, a ``dns.name.Name`` or ``str``, the query name. + + *rdtype*, an ``int`` or ``str``, the desired rdata type. + + *rdclass*, an ``int`` or ``str``, the desired rdata class; the default + is class IN. + + *use_edns*, an ``int``, ``bool`` or ``None``. The EDNS level to use; the + default is ``None``. If ``None``, EDNS will be enabled only if other + parameters (*ednsflags*, *payload*, *request_payload*, or *options*) are + set. + See the description of dns.message.Message.use_edns() for the possible + values for use_edns and their meanings. + + *want_dnssec*, a ``bool``. If ``True``, DNSSEC data is desired. + + *ednsflags*, an ``int``, the EDNS flag values. + + *payload*, an ``int``, is the EDNS sender's payload field, which is the + maximum size of UDP datagram the sender can handle. I.e. how big + a response to this message can be. + + *request_payload*, an ``int``, is the EDNS payload size to use when + sending this message. If not specified, defaults to the value of + *payload*. + + *options*, a list of ``dns.edns.Option`` objects or ``None``, the EDNS + options. + + *idna_codec*, a ``dns.name.IDNACodec``, specifies the IDNA + encoder/decoder. If ``None``, the default IDNA 2003 encoder/decoder + is used. + + *id*, an ``int`` or ``None``, the desired query id. The default is + ``None``, which generates a random query id. + + *flags*, an ``int``, the desired query flags. The default is + ``dns.flags.RD``. + + *pad*, a non-negative ``int``. If 0, the default, do not pad; otherwise add + padding bytes to make the message size a multiple of *pad*. Note that if + padding is non-zero, an EDNS PADDING option will always be added to the + message. + + Returns a ``dns.message.QueryMessage`` + """ + + if isinstance(qname, str): + qname = dns.name.from_text(qname, idna_codec=idna_codec) + rdtype = dns.rdatatype.RdataType.make(rdtype) + rdclass = dns.rdataclass.RdataClass.make(rdclass) + m = QueryMessage(id=id) + m.flags = dns.flags.Flag(flags) + m.find_rrset(m.question, qname, rdclass, rdtype, create=True, force_unique=True) + # only pass keywords on to use_edns if they have been set to a + # non-None value. Setting a field will turn EDNS on if it hasn't + # been configured. + kwargs: Dict[str, Any] = {} + if ednsflags is not None: + kwargs["ednsflags"] = ednsflags + if payload is not None: + kwargs["payload"] = payload + if request_payload is not None: + kwargs["request_payload"] = request_payload + if options is not None: + kwargs["options"] = options + if kwargs and use_edns is None: + use_edns = 0 + kwargs["edns"] = use_edns + kwargs["pad"] = pad + m.use_edns(**kwargs) + if want_dnssec: + m.want_dnssec(want_dnssec) + return m + + +class CopyMode(enum.Enum): + """ + How should sections be copied when making an update response? + """ + + NOTHING = 0 + QUESTION = 1 + EVERYTHING = 2 + + +def make_response( + query: Message, + recursion_available: bool = False, + our_payload: int = 8192, + fudge: int = 300, + tsig_error: int = 0, + pad: int | None = None, + copy_mode: CopyMode | None = None, +) -> Message: + """Make a message which is a response for the specified query. + The message returned is really a response skeleton; it has all of the infrastructure + required of a response, but none of the content. + + Response section(s) which are copied are shallow copies of the matching section(s) + in the query, so the query's RRsets should not be changed. + + *query*, a ``dns.message.Message``, the query to respond to. + + *recursion_available*, a ``bool``, should RA be set in the response? + + *our_payload*, an ``int``, the payload size to advertise in EDNS responses. + + *fudge*, an ``int``, the TSIG time fudge. + + *tsig_error*, an ``int``, the TSIG error. + + *pad*, a non-negative ``int`` or ``None``. If 0, the default, do not pad; otherwise + if not ``None`` add padding bytes to make the message size a multiple of *pad*. Note + that if padding is non-zero, an EDNS PADDING option will always be added to the + message. If ``None``, add padding following RFC 8467, namely if the request is + padded, pad the response to 468 otherwise do not pad. + + *copy_mode*, a ``dns.message.CopyMode`` or ``None``, determines how sections are + copied. The default, ``None`` copies sections according to the default for the + message's opcode, which is currently ``dns.message.CopyMode.QUESTION`` for all + opcodes. ``dns.message.CopyMode.QUESTION`` copies only the question section. + ``dns.message.CopyMode.EVERYTHING`` copies all sections other than OPT or TSIG + records, which are created appropriately if needed. ``dns.message.CopyMode.NOTHING`` + copies no sections; note that this mode is for server testing purposes and is + otherwise not recommended for use. In particular, ``dns.message.is_response()`` + will be ``False`` if you create a response this way and the rcode is not + ``FORMERR``, ``SERVFAIL``, ``NOTIMP``, or ``REFUSED``. + + Returns a ``dns.message.Message`` object whose specific class is appropriate for the + query. For example, if query is a ``dns.update.UpdateMessage``, the response will + be one too. + """ + + if query.flags & dns.flags.QR: + raise dns.exception.FormError("specified query message is not a query") + opcode = query.opcode() + factory = _message_factory_from_opcode(opcode) + response = factory(id=query.id) + response.flags = dns.flags.QR | (query.flags & dns.flags.RD) + if recursion_available: + response.flags |= dns.flags.RA + response.set_opcode(opcode) + if copy_mode is None: + copy_mode = CopyMode.QUESTION + if copy_mode != CopyMode.NOTHING: + response.question = list(query.question) + if copy_mode == CopyMode.EVERYTHING: + response.answer = list(query.answer) + response.authority = list(query.authority) + response.additional = list(query.additional) + if query.edns >= 0: + if pad is None: + # Set response padding per RFC 8467 + pad = 0 + for option in query.options: + if option.otype == dns.edns.OptionType.PADDING: + pad = 468 + response.use_edns(0, 0, our_payload, query.payload, pad=pad) + if query.had_tsig and query.keyring: + assert query.mac is not None + assert query.keyalgorithm is not None + response.use_tsig( + query.keyring, + query.keyname, + fudge, + None, + tsig_error, + b"", + query.keyalgorithm, + ) + response.request_mac = query.mac + return response + + +### BEGIN generated MessageSection constants + +QUESTION = MessageSection.QUESTION +ANSWER = MessageSection.ANSWER +AUTHORITY = MessageSection.AUTHORITY +ADDITIONAL = MessageSection.ADDITIONAL + +### END generated MessageSection constants diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/name.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/name.py new file mode 100644 index 000000000..45c8f454e --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/name.py @@ -0,0 +1,1289 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +# Copyright (C) 2001-2017 Nominum, Inc. +# +# Permission to use, copy, modify, and distribute this software and its +# documentation for any purpose with or without fee is hereby granted, +# provided that the above copyright notice and this permission notice +# appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +"""DNS Names.""" + +import copy +import encodings.idna # type: ignore +import functools +import struct +from typing import Any, Callable, Dict, Iterable, Optional, Tuple + +import dns._features +import dns.enum +import dns.exception +import dns.immutable +import dns.wire + +# Dnspython will never access idna if the import fails, but pyright can't figure +# that out, so... +# +# pyright: reportAttributeAccessIssue = false, reportPossiblyUnboundVariable = false + +if dns._features.have("idna"): + import idna # type: ignore + + have_idna_2008 = True +else: # pragma: no cover + have_idna_2008 = False + + +CompressType = Dict["Name", int] + + +class NameRelation(dns.enum.IntEnum): + """Name relation result from fullcompare().""" + + # This is an IntEnum for backwards compatibility in case anyone + # has hardwired the constants. + + #: The compared names have no relationship to each other. + NONE = 0 + #: the first name is a superdomain of the second. + SUPERDOMAIN = 1 + #: The first name is a subdomain of the second. + SUBDOMAIN = 2 + #: The compared names are equal. + EQUAL = 3 + #: The compared names have a common ancestor. + COMMONANCESTOR = 4 + + @classmethod + def _maximum(cls): + return cls.COMMONANCESTOR # pragma: no cover + + @classmethod + def _short_name(cls): + return cls.__name__ # pragma: no cover + + +# Backwards compatibility +NAMERELN_NONE = NameRelation.NONE +NAMERELN_SUPERDOMAIN = NameRelation.SUPERDOMAIN +NAMERELN_SUBDOMAIN = NameRelation.SUBDOMAIN +NAMERELN_EQUAL = NameRelation.EQUAL +NAMERELN_COMMONANCESTOR = NameRelation.COMMONANCESTOR + + +class EmptyLabel(dns.exception.SyntaxError): + """A DNS label is empty.""" + + +class BadEscape(dns.exception.SyntaxError): + """An escaped code in a text format of DNS name is invalid.""" + + +class BadPointer(dns.exception.FormError): + """A DNS compression pointer points forward instead of backward.""" + + +class BadLabelType(dns.exception.FormError): + """The label type in DNS name wire format is unknown.""" + + +class NeedAbsoluteNameOrOrigin(dns.exception.DNSException): + """An attempt was made to convert a non-absolute name to + wire when there was also a non-absolute (or missing) origin.""" + + +class NameTooLong(dns.exception.FormError): + """A DNS name is > 255 octets long.""" + + +class LabelTooLong(dns.exception.SyntaxError): + """A DNS label is > 63 octets long.""" + + +class AbsoluteConcatenation(dns.exception.DNSException): + """An attempt was made to append anything other than the + empty name to an absolute DNS name.""" + + +class NoParent(dns.exception.DNSException): + """An attempt was made to get the parent of the root name + or the empty name.""" + + +class NoIDNA2008(dns.exception.DNSException): + """IDNA 2008 processing was requested but the idna module is not + available.""" + + +class IDNAException(dns.exception.DNSException): + """IDNA processing raised an exception.""" + + supp_kwargs = {"idna_exception"} + fmt = "IDNA processing exception: {idna_exception}" + + # We do this as otherwise mypy complains about unexpected keyword argument + # idna_exception + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + + +class NeedSubdomainOfOrigin(dns.exception.DNSException): + """An absolute name was provided that is not a subdomain of the specified origin.""" + + +_escaped = b'"().;\\@$' +_escaped_text = '"().;\\@$' + + +def _escapify(label: bytes | str) -> str: + """Escape the characters in label which need it. + @returns: the escaped string + @rtype: string""" + if isinstance(label, bytes): + # Ordinary DNS label mode. Escape special characters and values + # < 0x20 or > 0x7f. + text = "" + for c in label: + if c in _escaped: + text += "\\" + chr(c) + elif c > 0x20 and c < 0x7F: + text += chr(c) + else: + text += f"\\{c:03d}" + return text + + # Unicode label mode. Escape only special characters and values < 0x20 + text = "" + for uc in label: + if uc in _escaped_text: + text += "\\" + uc + elif uc <= "\x20": + text += f"\\{ord(uc):03d}" + else: + text += uc + return text + + +class IDNACodec: + """Abstract base class for IDNA encoder/decoders.""" + + def __init__(self): + pass + + def is_idna(self, label: bytes) -> bool: + return label.lower().startswith(b"xn--") + + def encode(self, label: str) -> bytes: + raise NotImplementedError # pragma: no cover + + def decode(self, label: bytes) -> str: + # We do not apply any IDNA policy on decode. + if self.is_idna(label): + try: + slabel = label[4:].decode("punycode") + return _escapify(slabel) + except Exception as e: + raise IDNAException(idna_exception=e) + else: + return _escapify(label) + + +class IDNA2003Codec(IDNACodec): + """IDNA 2003 encoder/decoder.""" + + def __init__(self, strict_decode: bool = False): + """Initialize the IDNA 2003 encoder/decoder. + + *strict_decode* is a ``bool``. If `True`, then IDNA2003 checking + is done when decoding. This can cause failures if the name + was encoded with IDNA2008. The default is `False`. + """ + + super().__init__() + self.strict_decode = strict_decode + + def encode(self, label: str) -> bytes: + """Encode *label*.""" + + if label == "": + return b"" + try: + return encodings.idna.ToASCII(label) + except UnicodeError: + raise LabelTooLong + + def decode(self, label: bytes) -> str: + """Decode *label*.""" + if not self.strict_decode: + return super().decode(label) + if label == b"": + return "" + try: + return _escapify(encodings.idna.ToUnicode(label)) + except Exception as e: + raise IDNAException(idna_exception=e) + + +class IDNA2008Codec(IDNACodec): + """IDNA 2008 encoder/decoder.""" + + def __init__( + self, + uts_46: bool = False, + transitional: bool = False, + allow_pure_ascii: bool = False, + strict_decode: bool = False, + ): + """Initialize the IDNA 2008 encoder/decoder. + + *uts_46* is a ``bool``. If True, apply Unicode IDNA + compatibility processing as described in Unicode Technical + Standard #46 (https://unicode.org/reports/tr46/). + If False, do not apply the mapping. The default is False. + + *transitional* is a ``bool``: If True, use the + "transitional" mode described in Unicode Technical Standard + #46. The default is False. + + *allow_pure_ascii* is a ``bool``. If True, then a label which + consists of only ASCII characters is allowed. This is less + strict than regular IDNA 2008, but is also necessary for mixed + names, e.g. a name with starting with "_sip._tcp." and ending + in an IDN suffix which would otherwise be disallowed. The + default is False. + + *strict_decode* is a ``bool``: If True, then IDNA2008 checking + is done when decoding. This can cause failures if the name + was encoded with IDNA2003. The default is False. + """ + super().__init__() + self.uts_46 = uts_46 + self.transitional = transitional + self.allow_pure_ascii = allow_pure_ascii + self.strict_decode = strict_decode + + def encode(self, label: str) -> bytes: + if label == "": + return b"" + if self.allow_pure_ascii and is_all_ascii(label): + encoded = label.encode("ascii") + if len(encoded) > 63: + raise LabelTooLong + return encoded + if not have_idna_2008: + raise NoIDNA2008 + try: + if self.uts_46: + # pylint: disable=possibly-used-before-assignment + label = idna.uts46_remap(label, False, self.transitional) + return idna.alabel(label) + except idna.IDNAError as e: + if e.args[0] == "Label too long": + raise LabelTooLong + else: + raise IDNAException(idna_exception=e) + + def decode(self, label: bytes) -> str: + if not self.strict_decode: + return super().decode(label) + if label == b"": + return "" + if not have_idna_2008: + raise NoIDNA2008 + try: + ulabel = idna.ulabel(label) + if self.uts_46: + ulabel = idna.uts46_remap(ulabel, False, self.transitional) + return _escapify(ulabel) + except (idna.IDNAError, UnicodeError) as e: + raise IDNAException(idna_exception=e) + + +IDNA_2003_Practical = IDNA2003Codec(False) +IDNA_2003_Strict = IDNA2003Codec(True) +IDNA_2003 = IDNA_2003_Practical +IDNA_2008_Practical = IDNA2008Codec(True, False, True, False) +IDNA_2008_UTS_46 = IDNA2008Codec(True, False, False, False) +IDNA_2008_Strict = IDNA2008Codec(False, False, False, True) +IDNA_2008_Transitional = IDNA2008Codec(True, True, False, False) +IDNA_2008 = IDNA_2008_Practical + + +def _validate_labels(labels: Tuple[bytes, ...]) -> None: + """Check for empty labels in the middle of a label sequence, + labels that are too long, and for too many labels. + + Raises ``dns.name.NameTooLong`` if the name as a whole is too long. + + Raises ``dns.name.EmptyLabel`` if a label is empty (i.e. the root + label) and appears in a position other than the end of the label + sequence + + """ + + l = len(labels) + total = 0 + i = -1 + j = 0 + for label in labels: + ll = len(label) + total += ll + 1 + if ll > 63: + raise LabelTooLong + if i < 0 and label == b"": + i = j + j += 1 + if total > 255: + raise NameTooLong + if i >= 0 and i != l - 1: + raise EmptyLabel + + +def _maybe_convert_to_binary(label: bytes | str) -> bytes: + """If label is ``str``, convert it to ``bytes``. If it is already + ``bytes`` just return it. + + """ + + if isinstance(label, bytes): + return label + if isinstance(label, str): + return label.encode() + raise ValueError # pragma: no cover + + +@dns.immutable.immutable +class Name: + """A DNS name. + + The dns.name.Name class represents a DNS name as a tuple of + labels. Each label is a ``bytes`` in DNS wire format. Instances + of the class are immutable. + """ + + __slots__ = ["labels"] + + def __init__(self, labels: Iterable[bytes | str]): + """*labels* is any iterable whose values are ``str`` or ``bytes``.""" + + blabels = [_maybe_convert_to_binary(x) for x in labels] + self.labels = tuple(blabels) + _validate_labels(self.labels) + + def __copy__(self): + return Name(self.labels) + + def __deepcopy__(self, memo): + return Name(copy.deepcopy(self.labels, memo)) + + def __getstate__(self): + # Names can be pickled + return {"labels": self.labels} + + def __setstate__(self, state): + super().__setattr__("labels", state["labels"]) + _validate_labels(self.labels) + + def is_absolute(self) -> bool: + """Is the most significant label of this name the root label? + + Returns a ``bool``. + """ + + return len(self.labels) > 0 and self.labels[-1] == b"" + + def is_wild(self) -> bool: + """Is this name wild? (I.e. Is the least significant label '*'?) + + Returns a ``bool``. + """ + + return len(self.labels) > 0 and self.labels[0] == b"*" + + def __hash__(self) -> int: + """Return a case-insensitive hash of the name. + + Returns an ``int``. + """ + + h = 0 + for label in self.labels: + for c in label.lower(): + h += (h << 3) + c + return h + + def fullcompare(self, other: "Name") -> Tuple[NameRelation, int, int]: + """Compare two names, returning a 3-tuple + ``(relation, order, nlabels)``. + + *relation* describes the relation ship between the names, + and is one of: ``dns.name.NameRelation.NONE``, + ``dns.name.NameRelation.SUPERDOMAIN``, ``dns.name.NameRelation.SUBDOMAIN``, + ``dns.name.NameRelation.EQUAL``, or ``dns.name.NameRelation.COMMONANCESTOR``. + + *order* is < 0 if *self* < *other*, > 0 if *self* > *other*, and == + 0 if *self* == *other*. A relative name is always less than an + absolute name. If both names have the same relativity, then + the DNSSEC order relation is used to order them. + + *nlabels* is the number of significant labels that the two names + have in common. + + Here are some examples. Names ending in "." are absolute names, + those not ending in "." are relative names. + + ============= ============= =========== ===== ======= + self other relation order nlabels + ============= ============= =========== ===== ======= + www.example. www.example. equal 0 3 + www.example. example. subdomain > 0 2 + example. www.example. superdomain < 0 2 + example1.com. example2.com. common anc. < 0 2 + example1 example2. none < 0 0 + example1. example2 none > 0 0 + ============= ============= =========== ===== ======= + """ + + sabs = self.is_absolute() + oabs = other.is_absolute() + if sabs != oabs: + if sabs: + return (NameRelation.NONE, 1, 0) + else: + return (NameRelation.NONE, -1, 0) + l1 = len(self.labels) + l2 = len(other.labels) + ldiff = l1 - l2 + if ldiff < 0: + l = l1 + else: + l = l2 + + order = 0 + nlabels = 0 + namereln = NameRelation.NONE + while l > 0: + l -= 1 + l1 -= 1 + l2 -= 1 + label1 = self.labels[l1].lower() + label2 = other.labels[l2].lower() + if label1 < label2: + order = -1 + if nlabels > 0: + namereln = NameRelation.COMMONANCESTOR + return (namereln, order, nlabels) + elif label1 > label2: + order = 1 + if nlabels > 0: + namereln = NameRelation.COMMONANCESTOR + return (namereln, order, nlabels) + nlabels += 1 + order = ldiff + if ldiff < 0: + namereln = NameRelation.SUPERDOMAIN + elif ldiff > 0: + namereln = NameRelation.SUBDOMAIN + else: + namereln = NameRelation.EQUAL + return (namereln, order, nlabels) + + def is_subdomain(self, other: "Name") -> bool: + """Is self a subdomain of other? + + Note that the notion of subdomain includes equality, e.g. + "dnspython.org" is a subdomain of itself. + + Returns a ``bool``. + """ + + (nr, _, _) = self.fullcompare(other) + if nr == NameRelation.SUBDOMAIN or nr == NameRelation.EQUAL: + return True + return False + + def is_superdomain(self, other: "Name") -> bool: + """Is self a superdomain of other? + + Note that the notion of superdomain includes equality, e.g. + "dnspython.org" is a superdomain of itself. + + Returns a ``bool``. + """ + + (nr, _, _) = self.fullcompare(other) + if nr == NameRelation.SUPERDOMAIN or nr == NameRelation.EQUAL: + return True + return False + + def canonicalize(self) -> "Name": + """Return a name which is equal to the current name, but is in + DNSSEC canonical form. + """ + + return Name([x.lower() for x in self.labels]) + + def __eq__(self, other): + if isinstance(other, Name): + return self.fullcompare(other)[1] == 0 + else: + return False + + def __ne__(self, other): + if isinstance(other, Name): + return self.fullcompare(other)[1] != 0 + else: + return True + + def __lt__(self, other): + if isinstance(other, Name): + return self.fullcompare(other)[1] < 0 + else: + return NotImplemented + + def __le__(self, other): + if isinstance(other, Name): + return self.fullcompare(other)[1] <= 0 + else: + return NotImplemented + + def __ge__(self, other): + if isinstance(other, Name): + return self.fullcompare(other)[1] >= 0 + else: + return NotImplemented + + def __gt__(self, other): + if isinstance(other, Name): + return self.fullcompare(other)[1] > 0 + else: + return NotImplemented + + def __repr__(self): + return "" + + def __str__(self): + return self.to_text(False) + + def to_text(self, omit_final_dot: bool = False) -> str: + """Convert name to DNS text format. + + *omit_final_dot* is a ``bool``. If True, don't emit the final + dot (denoting the root label) for absolute names. The default + is False. + + Returns a ``str``. + """ + + if len(self.labels) == 0: + return "@" + if len(self.labels) == 1 and self.labels[0] == b"": + return "." + if omit_final_dot and self.is_absolute(): + l = self.labels[:-1] + else: + l = self.labels + s = ".".join(map(_escapify, l)) + return s + + def to_unicode( + self, omit_final_dot: bool = False, idna_codec: IDNACodec | None = None + ) -> str: + """Convert name to Unicode text format. + + IDN ACE labels are converted to Unicode. + + *omit_final_dot* is a ``bool``. If True, don't emit the final + dot (denoting the root label) for absolute names. The default + is False. + *idna_codec* specifies the IDNA encoder/decoder. If None, the + dns.name.IDNA_2003_Practical encoder/decoder is used. + The IDNA_2003_Practical decoder does + not impose any policy, it just decodes punycode, so if you + don't want checking for compliance, you can use this decoder + for IDNA2008 as well. + + Returns a ``str``. + """ + + if len(self.labels) == 0: + return "@" + if len(self.labels) == 1 and self.labels[0] == b"": + return "." + if omit_final_dot and self.is_absolute(): + l = self.labels[:-1] + else: + l = self.labels + if idna_codec is None: + idna_codec = IDNA_2003_Practical + return ".".join([idna_codec.decode(x) for x in l]) + + def to_digestable(self, origin: Optional["Name"] = None) -> bytes: + """Convert name to a format suitable for digesting in hashes. + + The name is canonicalized and converted to uncompressed wire + format. All names in wire format are absolute. If the name + is a relative name, then an origin must be supplied. + + *origin* is a ``dns.name.Name`` or ``None``. If the name is + relative and origin is not ``None``, then origin will be appended + to the name. + + Raises ``dns.name.NeedAbsoluteNameOrOrigin`` if the name is + relative and no origin was provided. + + Returns a ``bytes``. + """ + + digest = self.to_wire(origin=origin, canonicalize=True) + assert digest is not None + return digest + + def to_wire( + self, + file: Any | None = None, + compress: CompressType | None = None, + origin: Optional["Name"] = None, + canonicalize: bool = False, + ) -> bytes | None: + """Convert name to wire format, possibly compressing it. + + *file* is the file where the name is emitted (typically an + io.BytesIO file). If ``None`` (the default), a ``bytes`` + containing the wire name will be returned. + + *compress*, a ``dict``, is the compression table to use. If + ``None`` (the default), names will not be compressed. Note that + the compression code assumes that compression offset 0 is the + start of *file*, and thus compression will not be correct + if this is not the case. + + *origin* is a ``dns.name.Name`` or ``None``. If the name is + relative and origin is not ``None``, then *origin* will be appended + to it. + + *canonicalize*, a ``bool``, indicates whether the name should + be canonicalized; that is, converted to a format suitable for + digesting in hashes. + + Raises ``dns.name.NeedAbsoluteNameOrOrigin`` if the name is + relative and no origin was provided. + + Returns a ``bytes`` or ``None``. + """ + + if file is None: + out = bytearray() + for label in self.labels: + out.append(len(label)) + if canonicalize: + out += label.lower() + else: + out += label + if not self.is_absolute(): + if origin is None or not origin.is_absolute(): + raise NeedAbsoluteNameOrOrigin + for label in origin.labels: + out.append(len(label)) + if canonicalize: + out += label.lower() + else: + out += label + return bytes(out) + + labels: Iterable[bytes] + if not self.is_absolute(): + if origin is None or not origin.is_absolute(): + raise NeedAbsoluteNameOrOrigin + labels = list(self.labels) + labels.extend(list(origin.labels)) + else: + labels = self.labels + i = 0 + for label in labels: + n = Name(labels[i:]) + i += 1 + if compress is not None: + pos = compress.get(n) + else: + pos = None + if pos is not None: + value = 0xC000 + pos + s = struct.pack("!H", value) + file.write(s) + break + else: + if compress is not None and len(n) > 1: + pos = file.tell() + if pos <= 0x3FFF: + compress[n] = pos + l = len(label) + file.write(struct.pack("!B", l)) + if l > 0: + if canonicalize: + file.write(label.lower()) + else: + file.write(label) + return None + + def __len__(self) -> int: + """The length of the name (in labels). + + Returns an ``int``. + """ + + return len(self.labels) + + def __getitem__(self, index): + return self.labels[index] + + def __add__(self, other): + return self.concatenate(other) + + def __sub__(self, other): + return self.relativize(other) + + def split(self, depth: int) -> Tuple["Name", "Name"]: + """Split a name into a prefix and suffix names at the specified depth. + + *depth* is an ``int`` specifying the number of labels in the suffix + + Raises ``ValueError`` if *depth* was not >= 0 and <= the length of the + name. + + Returns the tuple ``(prefix, suffix)``. + """ + + l = len(self.labels) + if depth == 0: + return (self, dns.name.empty) + elif depth == l: + return (dns.name.empty, self) + elif depth < 0 or depth > l: + raise ValueError("depth must be >= 0 and <= the length of the name") + return (Name(self[:-depth]), Name(self[-depth:])) + + def concatenate(self, other: "Name") -> "Name": + """Return a new name which is the concatenation of self and other. + + Raises ``dns.name.AbsoluteConcatenation`` if the name is + absolute and *other* is not the empty name. + + Returns a ``dns.name.Name``. + """ + + if self.is_absolute() and len(other) > 0: + raise AbsoluteConcatenation + labels = list(self.labels) + labels.extend(list(other.labels)) + return Name(labels) + + def relativize(self, origin: "Name") -> "Name": + """If the name is a subdomain of *origin*, return a new name which is + the name relative to origin. Otherwise return the name. + + For example, relativizing ``www.dnspython.org.`` to origin + ``dnspython.org.`` returns the name ``www``. Relativizing ``example.`` + to origin ``dnspython.org.`` returns ``example.``. + + Returns a ``dns.name.Name``. + """ + + if origin is not None and self.is_subdomain(origin): + return Name(self[: -len(origin)]) + else: + return self + + def derelativize(self, origin: "Name") -> "Name": + """If the name is a relative name, return a new name which is the + concatenation of the name and origin. Otherwise return the name. + + For example, derelativizing ``www`` to origin ``dnspython.org.`` + returns the name ``www.dnspython.org.``. Derelativizing ``example.`` + to origin ``dnspython.org.`` returns ``example.``. + + Returns a ``dns.name.Name``. + """ + + if not self.is_absolute(): + return self.concatenate(origin) + else: + return self + + def choose_relativity( + self, origin: Optional["Name"] = None, relativize: bool = True + ) -> "Name": + """Return a name with the relativity desired by the caller. + + If *origin* is ``None``, then the name is returned. + Otherwise, if *relativize* is ``True`` the name is + relativized, and if *relativize* is ``False`` the name is + derelativized. + + Returns a ``dns.name.Name``. + """ + + if origin: + if relativize: + return self.relativize(origin) + else: + return self.derelativize(origin) + else: + return self + + def parent(self) -> "Name": + """Return the parent of the name. + + For example, the parent of ``www.dnspython.org.`` is ``dnspython.org``. + + Raises ``dns.name.NoParent`` if the name is either the root name or the + empty name, and thus has no parent. + + Returns a ``dns.name.Name``. + """ + + if self == root or self == empty: + raise NoParent + return Name(self.labels[1:]) + + def predecessor(self, origin: "Name", prefix_ok: bool = True) -> "Name": + """Return the maximal predecessor of *name* in the DNSSEC ordering in the zone + whose origin is *origin*, or return the longest name under *origin* if the + name is origin (i.e. wrap around to the longest name, which may still be + *origin* due to length considerations. + + The relativity of the name is preserved, so if this name is relative + then the method will return a relative name, and likewise if this name + is absolute then the predecessor will be absolute. + + *prefix_ok* indicates if prefixing labels is allowed, and + defaults to ``True``. Normally it is good to allow this, but if computing + a maximal predecessor at a zone cut point then ``False`` must be specified. + """ + return _handle_relativity_and_call( + _absolute_predecessor, self, origin, prefix_ok + ) + + def successor(self, origin: "Name", prefix_ok: bool = True) -> "Name": + """Return the minimal successor of *name* in the DNSSEC ordering in the zone + whose origin is *origin*, or return *origin* if the successor cannot be + computed due to name length limitations. + + Note that *origin* is returned in the "too long" cases because wrapping + around to the origin is how NSEC records express "end of the zone". + + The relativity of the name is preserved, so if this name is relative + then the method will return a relative name, and likewise if this name + is absolute then the successor will be absolute. + + *prefix_ok* indicates if prefixing a new minimal label is allowed, and + defaults to ``True``. Normally it is good to allow this, but if computing + a minimal successor at a zone cut point then ``False`` must be specified. + """ + return _handle_relativity_and_call(_absolute_successor, self, origin, prefix_ok) + + +#: The root name, '.' +root = Name([b""]) + +#: The empty name. +empty = Name([]) + + +def from_unicode( + text: str, origin: Name | None = root, idna_codec: IDNACodec | None = None +) -> Name: + """Convert unicode text into a Name object. + + Labels are encoded in IDN ACE form according to rules specified by + the IDNA codec. + + *text*, a ``str``, is the text to convert into a name. + + *origin*, a ``dns.name.Name``, specifies the origin to + append to non-absolute names. The default is the root name. + + *idna_codec*, a ``dns.name.IDNACodec``, specifies the IDNA + encoder/decoder. If ``None``, the default IDNA 2003 encoder/decoder + is used. + + Returns a ``dns.name.Name``. + """ + + if not isinstance(text, str): + raise ValueError("input to from_unicode() must be a unicode string") + if not (origin is None or isinstance(origin, Name)): + raise ValueError("origin must be a Name or None") + labels = [] + label = "" + escaping = False + edigits = 0 + total = 0 + if idna_codec is None: + idna_codec = IDNA_2003 + if text == "@": + text = "" + if text: + if text in [".", "\u3002", "\uff0e", "\uff61"]: + return Name([b""]) # no Unicode "u" on this constant! + for c in text: + if escaping: + if edigits == 0: + if c.isdigit(): + total = int(c) + edigits += 1 + else: + label += c + escaping = False + else: + if not c.isdigit(): + raise BadEscape + total *= 10 + total += int(c) + edigits += 1 + if edigits == 3: + escaping = False + label += chr(total) + elif c in [".", "\u3002", "\uff0e", "\uff61"]: + if len(label) == 0: + raise EmptyLabel + labels.append(idna_codec.encode(label)) + label = "" + elif c == "\\": + escaping = True + edigits = 0 + total = 0 + else: + label += c + if escaping: + raise BadEscape + if len(label) > 0: + labels.append(idna_codec.encode(label)) + else: + labels.append(b"") + + if (len(labels) == 0 or labels[-1] != b"") and origin is not None: + labels.extend(list(origin.labels)) + return Name(labels) + + +def is_all_ascii(text: str) -> bool: + for c in text: + if ord(c) > 0x7F: + return False + return True + + +def from_text( + text: bytes | str, + origin: Name | None = root, + idna_codec: IDNACodec | None = None, +) -> Name: + """Convert text into a Name object. + + *text*, a ``bytes`` or ``str``, is the text to convert into a name. + + *origin*, a ``dns.name.Name``, specifies the origin to + append to non-absolute names. The default is the root name. + + *idna_codec*, a ``dns.name.IDNACodec``, specifies the IDNA + encoder/decoder. If ``None``, the default IDNA 2003 encoder/decoder + is used. + + Returns a ``dns.name.Name``. + """ + + if isinstance(text, str): + if not is_all_ascii(text): + # Some codepoint in the input text is > 127, so IDNA applies. + return from_unicode(text, origin, idna_codec) + # The input is all ASCII, so treat this like an ordinary non-IDNA + # domain name. Note that "all ASCII" is about the input text, + # not the codepoints in the domain name. E.g. if text has value + # + # r'\150\151\152\153\154\155\156\157\158\159' + # + # then it's still "all ASCII" even though the domain name has + # codepoints > 127. + text = text.encode("ascii") + if not isinstance(text, bytes): + raise ValueError("input to from_text() must be a string") + if not (origin is None or isinstance(origin, Name)): + raise ValueError("origin must be a Name or None") + labels = [] + label = b"" + escaping = False + edigits = 0 + total = 0 + if text == b"@": + text = b"" + if text: + if text == b".": + return Name([b""]) + for c in text: + byte_ = struct.pack("!B", c) + if escaping: + if edigits == 0: + if byte_.isdigit(): + total = int(byte_) + edigits += 1 + else: + label += byte_ + escaping = False + else: + if not byte_.isdigit(): + raise BadEscape + total *= 10 + total += int(byte_) + edigits += 1 + if edigits == 3: + escaping = False + label += struct.pack("!B", total) + elif byte_ == b".": + if len(label) == 0: + raise EmptyLabel + labels.append(label) + label = b"" + elif byte_ == b"\\": + escaping = True + edigits = 0 + total = 0 + else: + label += byte_ + if escaping: + raise BadEscape + if len(label) > 0: + labels.append(label) + else: + labels.append(b"") + if (len(labels) == 0 or labels[-1] != b"") and origin is not None: + labels.extend(list(origin.labels)) + return Name(labels) + + +# we need 'dns.wire.Parser' quoted as dns.name and dns.wire depend on each other. + + +def from_wire_parser(parser: "dns.wire.Parser") -> Name: + """Convert possibly compressed wire format into a Name. + + *parser* is a dns.wire.Parser. + + Raises ``dns.name.BadPointer`` if a compression pointer did not + point backwards in the message. + + Raises ``dns.name.BadLabelType`` if an invalid label type was encountered. + + Returns a ``dns.name.Name`` + """ + + labels = [] + biggest_pointer = parser.current + with parser.restore_furthest(): + count = parser.get_uint8() + while count != 0: + if count < 64: + labels.append(parser.get_bytes(count)) + elif count >= 192: + current = (count & 0x3F) * 256 + parser.get_uint8() + if current >= biggest_pointer: + raise BadPointer + biggest_pointer = current + parser.seek(current) + else: + raise BadLabelType + count = parser.get_uint8() + labels.append(b"") + return Name(labels) + + +def from_wire(message: bytes, current: int) -> Tuple[Name, int]: + """Convert possibly compressed wire format into a Name. + + *message* is a ``bytes`` containing an entire DNS message in DNS + wire form. + + *current*, an ``int``, is the offset of the beginning of the name + from the start of the message + + Raises ``dns.name.BadPointer`` if a compression pointer did not + point backwards in the message. + + Raises ``dns.name.BadLabelType`` if an invalid label type was encountered. + + Returns a ``(dns.name.Name, int)`` tuple consisting of the name + that was read and the number of bytes of the wire format message + which were consumed reading it. + """ + + if not isinstance(message, bytes): + raise ValueError("input to from_wire() must be a byte string") + parser = dns.wire.Parser(message, current) + name = from_wire_parser(parser) + return (name, parser.current - current) + + +# RFC 4471 Support + +_MINIMAL_OCTET = b"\x00" +_MINIMAL_OCTET_VALUE = ord(_MINIMAL_OCTET) +_SUCCESSOR_PREFIX = Name([_MINIMAL_OCTET]) +_MAXIMAL_OCTET = b"\xff" +_MAXIMAL_OCTET_VALUE = ord(_MAXIMAL_OCTET) +_AT_SIGN_VALUE = ord("@") +_LEFT_SQUARE_BRACKET_VALUE = ord("[") + + +def _wire_length(labels): + return functools.reduce(lambda v, x: v + len(x) + 1, labels, 0) + + +def _pad_to_max_name(name): + needed = 255 - _wire_length(name.labels) + new_labels = [] + while needed > 64: + new_labels.append(_MAXIMAL_OCTET * 63) + needed -= 64 + if needed >= 2: + new_labels.append(_MAXIMAL_OCTET * (needed - 1)) + # Note we're already maximal in the needed == 1 case as while we'd like + # to add one more byte as a new label, we can't, as adding a new non-empty + # label requires at least 2 bytes. + new_labels = list(reversed(new_labels)) + new_labels.extend(name.labels) + return Name(new_labels) + + +def _pad_to_max_label(label, suffix_labels): + length = len(label) + # We have to subtract one here to account for the length byte of label. + remaining = 255 - _wire_length(suffix_labels) - length - 1 + if remaining <= 0: + # Shouldn't happen! + return label + needed = min(63 - length, remaining) + return label + _MAXIMAL_OCTET * needed + + +def _absolute_predecessor(name: Name, origin: Name, prefix_ok: bool) -> Name: + # This is the RFC 4471 predecessor algorithm using the "absolute method" of section + # 3.1.1. + # + # Our caller must ensure that the name and origin are absolute, and that name is a + # subdomain of origin. + if name == origin: + return _pad_to_max_name(name) + least_significant_label = name[0] + if least_significant_label == _MINIMAL_OCTET: + return name.parent() + least_octet = least_significant_label[-1] + suffix_labels = name.labels[1:] + if least_octet == _MINIMAL_OCTET_VALUE: + new_labels = [least_significant_label[:-1]] + else: + octets = bytearray(least_significant_label) + octet = octets[-1] + if octet == _LEFT_SQUARE_BRACKET_VALUE: + octet = _AT_SIGN_VALUE + else: + octet -= 1 + octets[-1] = octet + least_significant_label = bytes(octets) + new_labels = [_pad_to_max_label(least_significant_label, suffix_labels)] + new_labels.extend(suffix_labels) + name = Name(new_labels) + if prefix_ok: + return _pad_to_max_name(name) + else: + return name + + +def _absolute_successor(name: Name, origin: Name, prefix_ok: bool) -> Name: + # This is the RFC 4471 successor algorithm using the "absolute method" of section + # 3.1.2. + # + # Our caller must ensure that the name and origin are absolute, and that name is a + # subdomain of origin. + if prefix_ok: + # Try prefixing \000 as new label + try: + return _SUCCESSOR_PREFIX.concatenate(name) + except NameTooLong: + pass + while name != origin: + # Try extending the least significant label. + least_significant_label = name[0] + if len(least_significant_label) < 63: + # We may be able to extend the least label with a minimal additional byte. + # This is only "may" because we could have a maximal length name even though + # the least significant label isn't maximally long. + new_labels = [least_significant_label + _MINIMAL_OCTET] + new_labels.extend(name.labels[1:]) + try: + return dns.name.Name(new_labels) + except dns.name.NameTooLong: + pass + # We can't extend the label either, so we'll try to increment the least + # signficant non-maximal byte in it. + octets = bytearray(least_significant_label) + # We do this reversed iteration with an explicit indexing variable because + # if we find something to increment, we're going to want to truncate everything + # to the right of it. + for i in range(len(octets) - 1, -1, -1): + octet = octets[i] + if octet == _MAXIMAL_OCTET_VALUE: + # We can't increment this, so keep looking. + continue + # Finally, something we can increment. We have to apply a special rule for + # incrementing "@", sending it to "[", because RFC 4034 6.1 says that when + # comparing names, uppercase letters compare as if they were their + # lower-case equivalents. If we increment "@" to "A", then it would compare + # as "a", which is after "[", "\", "]", "^", "_", and "`", so we would have + # skipped the most minimal successor, namely "[". + if octet == _AT_SIGN_VALUE: + octet = _LEFT_SQUARE_BRACKET_VALUE + else: + octet += 1 + octets[i] = octet + # We can now truncate all of the maximal values we skipped (if any) + new_labels = [bytes(octets[: i + 1])] + new_labels.extend(name.labels[1:]) + # We haven't changed the length of the name, so the Name constructor will + # always work. + return Name(new_labels) + # We couldn't increment, so chop off the least significant label and try + # again. + name = name.parent() + + # We couldn't increment at all, so return the origin, as wrapping around is the + # DNSSEC way. + return origin + + +def _handle_relativity_and_call( + function: Callable[[Name, Name, bool], Name], + name: Name, + origin: Name, + prefix_ok: bool, +) -> Name: + # Make "name" absolute if needed, ensure that the origin is absolute, + # call function(), and then relativize the result if needed. + if not origin.is_absolute(): + raise NeedAbsoluteNameOrOrigin + relative = not name.is_absolute() + if relative: + name = name.derelativize(origin) + elif not name.is_subdomain(origin): + raise NeedSubdomainOfOrigin + result_name = function(name, origin, prefix_ok) + if relative: + result_name = result_name.relativize(origin) + return result_name diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/namedict.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/namedict.py new file mode 100644 index 000000000..ca8b19789 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/namedict.py @@ -0,0 +1,109 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +# Copyright (C) 2003-2017 Nominum, Inc. +# Copyright (C) 2016 Coresec Systems AB +# +# Permission to use, copy, modify, and distribute this software and its +# documentation for any purpose with or without fee is hereby granted, +# provided that the above copyright notice and this permission notice +# appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND CORESEC SYSTEMS AB DISCLAIMS ALL +# WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED +# WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL CORESEC +# SYSTEMS AB BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR +# CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS +# OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, +# NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION +# WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +"""DNS name dictionary""" + +# pylint seems to be confused about this one! +from collections.abc import MutableMapping # pylint: disable=no-name-in-module + +import dns.name + + +class NameDict(MutableMapping): + """A dictionary whose keys are dns.name.Name objects. + + In addition to being like a regular Python dictionary, this + dictionary can also get the deepest match for a given key. + """ + + __slots__ = ["max_depth", "max_depth_items", "__store"] + + def __init__(self, *args, **kwargs): + super().__init__() + self.__store = dict() + #: the maximum depth of the keys that have ever been added + self.max_depth = 0 + #: the number of items of maximum depth + self.max_depth_items = 0 + self.update(dict(*args, **kwargs)) + + def __update_max_depth(self, key): + if len(key) == self.max_depth: + self.max_depth_items = self.max_depth_items + 1 + elif len(key) > self.max_depth: + self.max_depth = len(key) + self.max_depth_items = 1 + + def __getitem__(self, key): + return self.__store[key] + + def __setitem__(self, key, value): + if not isinstance(key, dns.name.Name): + raise ValueError("NameDict key must be a name") + self.__store[key] = value + self.__update_max_depth(key) + + def __delitem__(self, key): + self.__store.pop(key) + if len(key) == self.max_depth: + self.max_depth_items = self.max_depth_items - 1 + if self.max_depth_items == 0: + self.max_depth = 0 + for k in self.__store: + self.__update_max_depth(k) + + def __iter__(self): + return iter(self.__store) + + def __len__(self): + return len(self.__store) + + def has_key(self, key): + return key in self.__store + + def get_deepest_match(self, name): + """Find the deepest match to *name* in the dictionary. + + The deepest match is the longest name in the dictionary which is + a superdomain of *name*. Note that *superdomain* includes matching + *name* itself. + + *name*, a ``dns.name.Name``, the name to find. + + Returns a ``(key, value)`` where *key* is the deepest + ``dns.name.Name``, and *value* is the value associated with *key*. + """ + + depth = len(name) + if depth > self.max_depth: + depth = self.max_depth + for i in range(-depth, 0): + n = dns.name.Name(name[i:]) + if n in self: + return (n, self[n]) + v = self[dns.name.empty] + return (dns.name.empty, v) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/nameserver.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/nameserver.py new file mode 100644 index 000000000..c9307d3e2 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/nameserver.py @@ -0,0 +1,361 @@ +from urllib.parse import urlparse + +import dns.asyncbackend +import dns.asyncquery +import dns.message +import dns.query + + +class Nameserver: + def __init__(self): + pass + + def __str__(self): + raise NotImplementedError + + def kind(self) -> str: + raise NotImplementedError + + def is_always_max_size(self) -> bool: + raise NotImplementedError + + def answer_nameserver(self) -> str: + raise NotImplementedError + + def answer_port(self) -> int: + raise NotImplementedError + + def query( + self, + request: dns.message.QueryMessage, + timeout: float, + source: str | None, + source_port: int, + max_size: bool, + one_rr_per_rrset: bool = False, + ignore_trailing: bool = False, + ) -> dns.message.Message: + raise NotImplementedError + + async def async_query( + self, + request: dns.message.QueryMessage, + timeout: float, + source: str | None, + source_port: int, + max_size: bool, + backend: dns.asyncbackend.Backend, + one_rr_per_rrset: bool = False, + ignore_trailing: bool = False, + ) -> dns.message.Message: + raise NotImplementedError + + +class AddressAndPortNameserver(Nameserver): + def __init__(self, address: str, port: int): + super().__init__() + self.address = address + self.port = port + + def kind(self) -> str: + raise NotImplementedError + + def is_always_max_size(self) -> bool: + return False + + def __str__(self): + ns_kind = self.kind() + return f"{ns_kind}:{self.address}@{self.port}" + + def answer_nameserver(self) -> str: + return self.address + + def answer_port(self) -> int: + return self.port + + +class Do53Nameserver(AddressAndPortNameserver): + def __init__(self, address: str, port: int = 53): + super().__init__(address, port) + + def kind(self): + return "Do53" + + def query( + self, + request: dns.message.QueryMessage, + timeout: float, + source: str | None, + source_port: int, + max_size: bool, + one_rr_per_rrset: bool = False, + ignore_trailing: bool = False, + ) -> dns.message.Message: + if max_size: + response = dns.query.tcp( + request, + self.address, + timeout=timeout, + port=self.port, + source=source, + source_port=source_port, + one_rr_per_rrset=one_rr_per_rrset, + ignore_trailing=ignore_trailing, + ) + else: + response = dns.query.udp( + request, + self.address, + timeout=timeout, + port=self.port, + source=source, + source_port=source_port, + raise_on_truncation=True, + one_rr_per_rrset=one_rr_per_rrset, + ignore_trailing=ignore_trailing, + ignore_errors=True, + ignore_unexpected=True, + ) + return response + + async def async_query( + self, + request: dns.message.QueryMessage, + timeout: float, + source: str | None, + source_port: int, + max_size: bool, + backend: dns.asyncbackend.Backend, + one_rr_per_rrset: bool = False, + ignore_trailing: bool = False, + ) -> dns.message.Message: + if max_size: + response = await dns.asyncquery.tcp( + request, + self.address, + timeout=timeout, + port=self.port, + source=source, + source_port=source_port, + backend=backend, + one_rr_per_rrset=one_rr_per_rrset, + ignore_trailing=ignore_trailing, + ) + else: + response = await dns.asyncquery.udp( + request, + self.address, + timeout=timeout, + port=self.port, + source=source, + source_port=source_port, + raise_on_truncation=True, + backend=backend, + one_rr_per_rrset=one_rr_per_rrset, + ignore_trailing=ignore_trailing, + ignore_errors=True, + ignore_unexpected=True, + ) + return response + + +class DoHNameserver(Nameserver): + def __init__( + self, + url: str, + bootstrap_address: str | None = None, + verify: bool | str = True, + want_get: bool = False, + http_version: dns.query.HTTPVersion = dns.query.HTTPVersion.DEFAULT, + ): + super().__init__() + self.url = url + self.bootstrap_address = bootstrap_address + self.verify = verify + self.want_get = want_get + self.http_version = http_version + + def kind(self): + return "DoH" + + def is_always_max_size(self) -> bool: + return True + + def __str__(self): + return self.url + + def answer_nameserver(self) -> str: + return self.url + + def answer_port(self) -> int: + port = urlparse(self.url).port + if port is None: + port = 443 + return port + + def query( + self, + request: dns.message.QueryMessage, + timeout: float, + source: str | None, + source_port: int, + max_size: bool = False, + one_rr_per_rrset: bool = False, + ignore_trailing: bool = False, + ) -> dns.message.Message: + return dns.query.https( + request, + self.url, + timeout=timeout, + source=source, + source_port=source_port, + bootstrap_address=self.bootstrap_address, + one_rr_per_rrset=one_rr_per_rrset, + ignore_trailing=ignore_trailing, + verify=self.verify, + post=(not self.want_get), + http_version=self.http_version, + ) + + async def async_query( + self, + request: dns.message.QueryMessage, + timeout: float, + source: str | None, + source_port: int, + max_size: bool, + backend: dns.asyncbackend.Backend, + one_rr_per_rrset: bool = False, + ignore_trailing: bool = False, + ) -> dns.message.Message: + return await dns.asyncquery.https( + request, + self.url, + timeout=timeout, + source=source, + source_port=source_port, + bootstrap_address=self.bootstrap_address, + one_rr_per_rrset=one_rr_per_rrset, + ignore_trailing=ignore_trailing, + verify=self.verify, + post=(not self.want_get), + http_version=self.http_version, + ) + + +class DoTNameserver(AddressAndPortNameserver): + def __init__( + self, + address: str, + port: int = 853, + hostname: str | None = None, + verify: bool | str = True, + ): + super().__init__(address, port) + self.hostname = hostname + self.verify = verify + + def kind(self): + return "DoT" + + def query( + self, + request: dns.message.QueryMessage, + timeout: float, + source: str | None, + source_port: int, + max_size: bool = False, + one_rr_per_rrset: bool = False, + ignore_trailing: bool = False, + ) -> dns.message.Message: + return dns.query.tls( + request, + self.address, + port=self.port, + timeout=timeout, + one_rr_per_rrset=one_rr_per_rrset, + ignore_trailing=ignore_trailing, + server_hostname=self.hostname, + verify=self.verify, + ) + + async def async_query( + self, + request: dns.message.QueryMessage, + timeout: float, + source: str | None, + source_port: int, + max_size: bool, + backend: dns.asyncbackend.Backend, + one_rr_per_rrset: bool = False, + ignore_trailing: bool = False, + ) -> dns.message.Message: + return await dns.asyncquery.tls( + request, + self.address, + port=self.port, + timeout=timeout, + one_rr_per_rrset=one_rr_per_rrset, + ignore_trailing=ignore_trailing, + server_hostname=self.hostname, + verify=self.verify, + ) + + +class DoQNameserver(AddressAndPortNameserver): + def __init__( + self, + address: str, + port: int = 853, + verify: bool | str = True, + server_hostname: str | None = None, + ): + super().__init__(address, port) + self.verify = verify + self.server_hostname = server_hostname + + def kind(self): + return "DoQ" + + def query( + self, + request: dns.message.QueryMessage, + timeout: float, + source: str | None, + source_port: int, + max_size: bool = False, + one_rr_per_rrset: bool = False, + ignore_trailing: bool = False, + ) -> dns.message.Message: + return dns.query.quic( + request, + self.address, + port=self.port, + timeout=timeout, + one_rr_per_rrset=one_rr_per_rrset, + ignore_trailing=ignore_trailing, + verify=self.verify, + server_hostname=self.server_hostname, + ) + + async def async_query( + self, + request: dns.message.QueryMessage, + timeout: float, + source: str | None, + source_port: int, + max_size: bool, + backend: dns.asyncbackend.Backend, + one_rr_per_rrset: bool = False, + ignore_trailing: bool = False, + ) -> dns.message.Message: + return await dns.asyncquery.quic( + request, + self.address, + port=self.port, + timeout=timeout, + one_rr_per_rrset=one_rr_per_rrset, + ignore_trailing=ignore_trailing, + verify=self.verify, + server_hostname=self.server_hostname, + ) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/node.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/node.py new file mode 100644 index 000000000..b2cbf1b2e --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/node.py @@ -0,0 +1,358 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +# Copyright (C) 2001-2017 Nominum, Inc. +# +# Permission to use, copy, modify, and distribute this software and its +# documentation for any purpose with or without fee is hereby granted, +# provided that the above copyright notice and this permission notice +# appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +"""DNS nodes. A node is a set of rdatasets.""" + +import enum +import io +from typing import Any, Dict + +import dns.immutable +import dns.name +import dns.rdataclass +import dns.rdataset +import dns.rdatatype +import dns.rrset + +_cname_types = { + dns.rdatatype.CNAME, +} + +# "neutral" types can coexist with a CNAME and thus are not "other data" +_neutral_types = { + dns.rdatatype.NSEC, # RFC 4035 section 2.5 + dns.rdatatype.NSEC3, # This is not likely to happen, but not impossible! + dns.rdatatype.KEY, # RFC 4035 section 2.5, RFC 3007 +} + + +def _matches_type_or_its_signature(rdtypes, rdtype, covers): + return rdtype in rdtypes or (rdtype == dns.rdatatype.RRSIG and covers in rdtypes) + + +@enum.unique +class NodeKind(enum.Enum): + """Rdatasets in nodes""" + + REGULAR = 0 # a.k.a "other data" + NEUTRAL = 1 + CNAME = 2 + + @classmethod + def classify( + cls, rdtype: dns.rdatatype.RdataType, covers: dns.rdatatype.RdataType + ) -> "NodeKind": + if _matches_type_or_its_signature(_cname_types, rdtype, covers): + return NodeKind.CNAME + elif _matches_type_or_its_signature(_neutral_types, rdtype, covers): + return NodeKind.NEUTRAL + else: + return NodeKind.REGULAR + + @classmethod + def classify_rdataset(cls, rdataset: dns.rdataset.Rdataset) -> "NodeKind": + return cls.classify(rdataset.rdtype, rdataset.covers) + + +class Node: + """A Node is a set of rdatasets. + + A node is either a CNAME node or an "other data" node. A CNAME + node contains only CNAME, KEY, NSEC, and NSEC3 rdatasets along with their + covering RRSIG rdatasets. An "other data" node contains any + rdataset other than a CNAME or RRSIG(CNAME) rdataset. When + changes are made to a node, the CNAME or "other data" state is + always consistent with the update, i.e. the most recent change + wins. For example, if you have a node which contains a CNAME + rdataset, and then add an MX rdataset to it, then the CNAME + rdataset will be deleted. Likewise if you have a node containing + an MX rdataset and add a CNAME rdataset, the MX rdataset will be + deleted. + """ + + __slots__ = ["rdatasets"] + + def __init__(self): + # the set of rdatasets, represented as a list. + self.rdatasets = [] + + def to_text(self, name: dns.name.Name, **kw: Dict[str, Any]) -> str: + """Convert a node to text format. + + Each rdataset at the node is printed. Any keyword arguments + to this method are passed on to the rdataset's to_text() method. + + *name*, a ``dns.name.Name``, the owner name of the + rdatasets. + + Returns a ``str``. + + """ + + s = io.StringIO() + for rds in self.rdatasets: + if len(rds) > 0: + s.write(rds.to_text(name, **kw)) # type: ignore[arg-type] + s.write("\n") + return s.getvalue()[:-1] + + def __repr__(self): + return "" + + def __eq__(self, other): + # + # This is inefficient. Good thing we don't need to do it much. + # + for rd in self.rdatasets: + if rd not in other.rdatasets: + return False + for rd in other.rdatasets: + if rd not in self.rdatasets: + return False + return True + + def __ne__(self, other): + return not self.__eq__(other) + + def __len__(self): + return len(self.rdatasets) + + def __iter__(self): + return iter(self.rdatasets) + + def _append_rdataset(self, rdataset): + """Append rdataset to the node with special handling for CNAME and + other data conditions. + + Specifically, if the rdataset being appended has ``NodeKind.CNAME``, + then all rdatasets other than KEY, NSEC, NSEC3, and their covering + RRSIGs are deleted. If the rdataset being appended has + ``NodeKind.REGULAR`` then CNAME and RRSIG(CNAME) are deleted. + """ + # Make having just one rdataset at the node fast. + if len(self.rdatasets) > 0: + kind = NodeKind.classify_rdataset(rdataset) + if kind == NodeKind.CNAME: + self.rdatasets = [ + rds + for rds in self.rdatasets + if NodeKind.classify_rdataset(rds) != NodeKind.REGULAR + ] + elif kind == NodeKind.REGULAR: + self.rdatasets = [ + rds + for rds in self.rdatasets + if NodeKind.classify_rdataset(rds) != NodeKind.CNAME + ] + # Otherwise the rdataset is NodeKind.NEUTRAL and we do not need to + # edit self.rdatasets. + self.rdatasets.append(rdataset) + + def find_rdataset( + self, + rdclass: dns.rdataclass.RdataClass, + rdtype: dns.rdatatype.RdataType, + covers: dns.rdatatype.RdataType = dns.rdatatype.NONE, + create: bool = False, + ) -> dns.rdataset.Rdataset: + """Find an rdataset matching the specified properties in the + current node. + + *rdclass*, a ``dns.rdataclass.RdataClass``, the class of the rdataset. + + *rdtype*, a ``dns.rdatatype.RdataType``, the type of the rdataset. + + *covers*, a ``dns.rdatatype.RdataType``, the covered type. + Usually this value is ``dns.rdatatype.NONE``, but if the + rdtype is ``dns.rdatatype.SIG`` or ``dns.rdatatype.RRSIG``, + then the covers value will be the rdata type the SIG/RRSIG + covers. The library treats the SIG and RRSIG types as if they + were a family of types, e.g. RRSIG(A), RRSIG(NS), RRSIG(SOA). + This makes RRSIGs much easier to work with than if RRSIGs + covering different rdata types were aggregated into a single + RRSIG rdataset. + + *create*, a ``bool``. If True, create the rdataset if it is not found. + + Raises ``KeyError`` if an rdataset of the desired type and class does + not exist and *create* is not ``True``. + + Returns a ``dns.rdataset.Rdataset``. + """ + + for rds in self.rdatasets: + if rds.match(rdclass, rdtype, covers): + return rds + if not create: + raise KeyError + rds = dns.rdataset.Rdataset(rdclass, rdtype, covers) + self._append_rdataset(rds) + return rds + + def get_rdataset( + self, + rdclass: dns.rdataclass.RdataClass, + rdtype: dns.rdatatype.RdataType, + covers: dns.rdatatype.RdataType = dns.rdatatype.NONE, + create: bool = False, + ) -> dns.rdataset.Rdataset | None: + """Get an rdataset matching the specified properties in the + current node. + + None is returned if an rdataset of the specified type and + class does not exist and *create* is not ``True``. + + *rdclass*, an ``int``, the class of the rdataset. + + *rdtype*, an ``int``, the type of the rdataset. + + *covers*, an ``int``, the covered type. Usually this value is + dns.rdatatype.NONE, but if the rdtype is dns.rdatatype.SIG or + dns.rdatatype.RRSIG, then the covers value will be the rdata + type the SIG/RRSIG covers. The library treats the SIG and RRSIG + types as if they were a family of + types, e.g. RRSIG(A), RRSIG(NS), RRSIG(SOA). This makes RRSIGs much + easier to work with than if RRSIGs covering different rdata + types were aggregated into a single RRSIG rdataset. + + *create*, a ``bool``. If True, create the rdataset if it is not found. + + Returns a ``dns.rdataset.Rdataset`` or ``None``. + """ + + try: + rds = self.find_rdataset(rdclass, rdtype, covers, create) + except KeyError: + rds = None + return rds + + def delete_rdataset( + self, + rdclass: dns.rdataclass.RdataClass, + rdtype: dns.rdatatype.RdataType, + covers: dns.rdatatype.RdataType = dns.rdatatype.NONE, + ) -> None: + """Delete the rdataset matching the specified properties in the + current node. + + If a matching rdataset does not exist, it is not an error. + + *rdclass*, an ``int``, the class of the rdataset. + + *rdtype*, an ``int``, the type of the rdataset. + + *covers*, an ``int``, the covered type. + """ + + rds = self.get_rdataset(rdclass, rdtype, covers) + if rds is not None: + self.rdatasets.remove(rds) + + def replace_rdataset(self, replacement: dns.rdataset.Rdataset) -> None: + """Replace an rdataset. + + It is not an error if there is no rdataset matching *replacement*. + + Ownership of the *replacement* object is transferred to the node; + in other words, this method does not store a copy of *replacement* + at the node, it stores *replacement* itself. + + *replacement*, a ``dns.rdataset.Rdataset``. + + Raises ``ValueError`` if *replacement* is not a + ``dns.rdataset.Rdataset``. + """ + + if not isinstance(replacement, dns.rdataset.Rdataset): + raise ValueError("replacement is not an rdataset") + if isinstance(replacement, dns.rrset.RRset): + # RRsets are not good replacements as the match() method + # is not compatible. + replacement = replacement.to_rdataset() + self.delete_rdataset( + replacement.rdclass, replacement.rdtype, replacement.covers + ) + self._append_rdataset(replacement) + + def classify(self) -> NodeKind: + """Classify a node. + + A node which contains a CNAME or RRSIG(CNAME) is a + ``NodeKind.CNAME`` node. + + A node which contains only "neutral" types, i.e. types allowed to + co-exist with a CNAME, is a ``NodeKind.NEUTRAL`` node. The neutral + types are NSEC, NSEC3, KEY, and their associated RRSIGS. An empty node + is also considered neutral. + + A node which contains some rdataset which is not a CNAME, RRSIG(CNAME), + or a neutral type is a a ``NodeKind.REGULAR`` node. Regular nodes are + also commonly referred to as "other data". + """ + for rdataset in self.rdatasets: + kind = NodeKind.classify(rdataset.rdtype, rdataset.covers) + if kind != NodeKind.NEUTRAL: + return kind + return NodeKind.NEUTRAL + + def is_immutable(self) -> bool: + return False + + +@dns.immutable.immutable +class ImmutableNode(Node): + def __init__(self, node): + super().__init__() + self.rdatasets = tuple( + [dns.rdataset.ImmutableRdataset(rds) for rds in node.rdatasets] + ) + + def find_rdataset( + self, + rdclass: dns.rdataclass.RdataClass, + rdtype: dns.rdatatype.RdataType, + covers: dns.rdatatype.RdataType = dns.rdatatype.NONE, + create: bool = False, + ) -> dns.rdataset.Rdataset: + if create: + raise TypeError("immutable") + return super().find_rdataset(rdclass, rdtype, covers, False) + + def get_rdataset( + self, + rdclass: dns.rdataclass.RdataClass, + rdtype: dns.rdatatype.RdataType, + covers: dns.rdatatype.RdataType = dns.rdatatype.NONE, + create: bool = False, + ) -> dns.rdataset.Rdataset | None: + if create: + raise TypeError("immutable") + return super().get_rdataset(rdclass, rdtype, covers, False) + + def delete_rdataset( + self, + rdclass: dns.rdataclass.RdataClass, + rdtype: dns.rdatatype.RdataType, + covers: dns.rdatatype.RdataType = dns.rdatatype.NONE, + ) -> None: + raise TypeError("immutable") + + def replace_rdataset(self, replacement: dns.rdataset.Rdataset) -> None: + raise TypeError("immutable") + + def is_immutable(self) -> bool: + return True diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/opcode.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/opcode.py new file mode 100644 index 000000000..3fa610d04 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/opcode.py @@ -0,0 +1,119 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +# Copyright (C) 2001-2017 Nominum, Inc. +# +# Permission to use, copy, modify, and distribute this software and its +# documentation for any purpose with or without fee is hereby granted, +# provided that the above copyright notice and this permission notice +# appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +"""DNS Opcodes.""" + +from typing import Type + +import dns.enum +import dns.exception + + +class Opcode(dns.enum.IntEnum): + #: Query + QUERY = 0 + #: Inverse Query (historical) + IQUERY = 1 + #: Server Status (unspecified and unimplemented anywhere) + STATUS = 2 + #: Notify + NOTIFY = 4 + #: Dynamic Update + UPDATE = 5 + + @classmethod + def _maximum(cls): + return 15 + + @classmethod + def _unknown_exception_class(cls) -> Type[Exception]: + return UnknownOpcode + + +class UnknownOpcode(dns.exception.DNSException): + """An DNS opcode is unknown.""" + + +def from_text(text: str) -> Opcode: + """Convert text into an opcode. + + *text*, a ``str``, the textual opcode + + Raises ``dns.opcode.UnknownOpcode`` if the opcode is unknown. + + Returns an ``int``. + """ + + return Opcode.from_text(text) + + +def from_flags(flags: int) -> Opcode: + """Extract an opcode from DNS message flags. + + *flags*, an ``int``, the DNS flags. + + Returns an ``int``. + """ + + return Opcode((flags & 0x7800) >> 11) + + +def to_flags(value: Opcode) -> int: + """Convert an opcode to a value suitable for ORing into DNS message + flags. + + *value*, an ``int``, the DNS opcode value. + + Returns an ``int``. + """ + + return (value << 11) & 0x7800 + + +def to_text(value: Opcode) -> str: + """Convert an opcode to text. + + *value*, an ``int`` the opcode value, + + Raises ``dns.opcode.UnknownOpcode`` if the opcode is unknown. + + Returns a ``str``. + """ + + return Opcode.to_text(value) + + +def is_update(flags: int) -> bool: + """Is the opcode in flags UPDATE? + + *flags*, an ``int``, the DNS message flags. + + Returns a ``bool``. + """ + + return from_flags(flags) == Opcode.UPDATE + + +### BEGIN generated Opcode constants + +QUERY = Opcode.QUERY +IQUERY = Opcode.IQUERY +STATUS = Opcode.STATUS +NOTIFY = Opcode.NOTIFY +UPDATE = Opcode.UPDATE + +### END generated Opcode constants diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/py.typed b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/py.typed new file mode 100644 index 000000000..e69de29bb diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/query.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/query.py new file mode 100644 index 000000000..17b1862db --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/query.py @@ -0,0 +1,1786 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +# Copyright (C) 2003-2017 Nominum, Inc. +# +# Permission to use, copy, modify, and distribute this software and its +# documentation for any purpose with or without fee is hereby granted, +# provided that the above copyright notice and this permission notice +# appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +"""Talk to a DNS server.""" + +import base64 +import contextlib +import enum +import errno +import os +import random +import selectors +import socket +import struct +import time +import urllib.parse +from typing import Any, Callable, Dict, Optional, Tuple, cast + +import dns._features +import dns._tls_util +import dns.exception +import dns.inet +import dns.message +import dns.name +import dns.quic +import dns.rdata +import dns.rdataclass +import dns.rdatatype +import dns.transaction +import dns.tsig +import dns.xfr + +try: + import ssl +except ImportError: + import dns._no_ssl as ssl # type: ignore + + +def _remaining(expiration): + if expiration is None: + return None + timeout = expiration - time.time() + if timeout <= 0.0: + raise dns.exception.Timeout + return timeout + + +def _expiration_for_this_attempt(timeout, expiration): + if expiration is None: + return None + return min(time.time() + timeout, expiration) + + +_have_httpx = dns._features.have("doh") +if _have_httpx: + import httpcore._backends.sync + import httpx + + _CoreNetworkBackend = httpcore.NetworkBackend + _CoreSyncStream = httpcore._backends.sync.SyncStream + + class _NetworkBackend(_CoreNetworkBackend): + def __init__(self, resolver, local_port, bootstrap_address, family): + super().__init__() + self._local_port = local_port + self._resolver = resolver + self._bootstrap_address = bootstrap_address + self._family = family + + def connect_tcp( + self, host, port, timeout=None, local_address=None, socket_options=None + ): # pylint: disable=signature-differs + addresses = [] + _, expiration = _compute_times(timeout) + if dns.inet.is_address(host): + addresses.append(host) + elif self._bootstrap_address is not None: + addresses.append(self._bootstrap_address) + else: + timeout = _remaining(expiration) + family = self._family + if local_address: + family = dns.inet.af_for_address(local_address) + answers = self._resolver.resolve_name( + host, family=family, lifetime=timeout + ) + addresses = answers.addresses() + for address in addresses: + af = dns.inet.af_for_address(address) + if local_address is not None or self._local_port != 0: + if local_address is None: + local_address = "0.0.0.0" + source = dns.inet.low_level_address_tuple( + (local_address, self._local_port), af + ) + else: + source = None + try: + sock = make_socket(af, socket.SOCK_STREAM, source) + attempt_expiration = _expiration_for_this_attempt(2.0, expiration) + _connect( + sock, + dns.inet.low_level_address_tuple((address, port), af), + attempt_expiration, + ) + return _CoreSyncStream(sock) + except Exception: + pass + raise httpcore.ConnectError + + def connect_unix_socket( + self, path, timeout=None, socket_options=None + ): # pylint: disable=signature-differs + raise NotImplementedError + + class _HTTPTransport(httpx.HTTPTransport): # pyright: ignore + def __init__( + self, + *args, + local_port=0, + bootstrap_address=None, + resolver=None, + family=socket.AF_UNSPEC, + **kwargs, + ): + if resolver is None and bootstrap_address is None: + # pylint: disable=import-outside-toplevel,redefined-outer-name + import dns.resolver + + resolver = dns.resolver.Resolver() + super().__init__(*args, **kwargs) + self._pool._network_backend = _NetworkBackend( + resolver, local_port, bootstrap_address, family + ) + +else: + + class _HTTPTransport: # type: ignore + def __init__( + self, + *args, + local_port=0, + bootstrap_address=None, + resolver=None, + family=socket.AF_UNSPEC, + **kwargs, + ): + pass + + def connect_tcp(self, host, port, timeout, local_address): + raise NotImplementedError + + +have_doh = _have_httpx + + +def default_socket_factory( + af: socket.AddressFamily | int, + kind: socket.SocketKind, + proto: int, +) -> socket.socket: + return socket.socket(af, kind, proto) + + +# Function used to create a socket. Can be overridden if needed in special +# situations. +socket_factory: Callable[ + [socket.AddressFamily | int, socket.SocketKind, int], socket.socket +] = default_socket_factory + + +class UnexpectedSource(dns.exception.DNSException): + """A DNS query response came from an unexpected address or port.""" + + +class BadResponse(dns.exception.FormError): + """A DNS query response does not respond to the question asked.""" + + +class NoDOH(dns.exception.DNSException): + """DNS over HTTPS (DOH) was requested but the httpx module is not + available.""" + + +class NoDOQ(dns.exception.DNSException): + """DNS over QUIC (DOQ) was requested but the aioquic module is not + available.""" + + +# for backwards compatibility +TransferError = dns.xfr.TransferError + + +def _compute_times(timeout): + now = time.time() + if timeout is None: + return (now, None) + else: + return (now, now + timeout) + + +def _wait_for(fd, readable, writable, _, expiration): + # Use the selected selector class to wait for any of the specified + # events. An "expiration" absolute time is converted into a relative + # timeout. + # + # The unused parameter is 'error', which is always set when + # selecting for read or write, and we have no error-only selects. + + if readable and isinstance(fd, ssl.SSLSocket) and fd.pending() > 0: + return True + with selectors.DefaultSelector() as sel: + events = 0 + if readable: + events |= selectors.EVENT_READ + if writable: + events |= selectors.EVENT_WRITE + if events: + sel.register(fd, events) # pyright: ignore + if expiration is None: + timeout = None + else: + timeout = expiration - time.time() + if timeout <= 0.0: + raise dns.exception.Timeout + if not sel.select(timeout): + raise dns.exception.Timeout + + +def _wait_for_readable(s, expiration): + _wait_for(s, True, False, True, expiration) + + +def _wait_for_writable(s, expiration): + _wait_for(s, False, True, True, expiration) + + +def _addresses_equal(af, a1, a2): + # Convert the first value of the tuple, which is a textual format + # address into binary form, so that we are not confused by different + # textual representations of the same address + try: + n1 = dns.inet.inet_pton(af, a1[0]) + n2 = dns.inet.inet_pton(af, a2[0]) + except dns.exception.SyntaxError: + return False + return n1 == n2 and a1[1:] == a2[1:] + + +def _matches_destination(af, from_address, destination, ignore_unexpected): + # Check that from_address is appropriate for a response to a query + # sent to destination. + if not destination: + return True + if _addresses_equal(af, from_address, destination) or ( + dns.inet.is_multicast(destination[0]) and from_address[1:] == destination[1:] + ): + return True + elif ignore_unexpected: + return False + raise UnexpectedSource( + f"got a response from {from_address} instead of " f"{destination}" + ) + + +def _destination_and_source( + where, port, source, source_port, where_must_be_address=True +): + # Apply defaults and compute destination and source tuples + # suitable for use in connect(), sendto(), or bind(). + af = None + destination = None + try: + af = dns.inet.af_for_address(where) + destination = where + except Exception: + if where_must_be_address: + raise + # URLs are ok so eat the exception + if source: + saf = dns.inet.af_for_address(source) + if af: + # We know the destination af, so source had better agree! + if saf != af: + raise ValueError( + "different address families for source and destination" + ) + else: + # We didn't know the destination af, but we know the source, + # so that's our af. + af = saf + if source_port and not source: + # Caller has specified a source_port but not an address, so we + # need to return a source, and we need to use the appropriate + # wildcard address as the address. + try: + source = dns.inet.any_for_af(af) + except Exception: + # we catch this and raise ValueError for backwards compatibility + raise ValueError("source_port specified but address family is unknown") + # Convert high-level (address, port) tuples into low-level address + # tuples. + if destination: + destination = dns.inet.low_level_address_tuple((destination, port), af) + if source: + source = dns.inet.low_level_address_tuple((source, source_port), af) + return (af, destination, source) + + +def make_socket( + af: socket.AddressFamily | int, + type: socket.SocketKind, + source: Any | None = None, +) -> socket.socket: + """Make a socket. + + This function uses the module's ``socket_factory`` to make a socket of the + specified address family and type. + + *af*, a ``socket.AddressFamily`` or ``int`` is the address family, either + ``socket.AF_INET`` or ``socket.AF_INET6``. + + *type*, a ``socket.SocketKind`` is the type of socket, e.g. ``socket.SOCK_DGRAM``, + a datagram socket, or ``socket.SOCK_STREAM``, a stream socket. Note that the + ``proto`` attribute of a socket is always zero with this API, so a datagram socket + will always be a UDP socket, and a stream socket will always be a TCP socket. + + *source* is the source address and port to bind to, if any. The default is + ``None`` which will bind to the wildcard address and a randomly chosen port. + If not ``None``, it should be a (low-level) address tuple appropriate for *af*. + """ + s = socket_factory(af, type, 0) + try: + s.setblocking(False) + if source is not None: + s.bind(source) + return s + except Exception: + s.close() + raise + + +def make_ssl_socket( + af: socket.AddressFamily | int, + type: socket.SocketKind, + ssl_context: ssl.SSLContext, + server_hostname: dns.name.Name | str | None = None, + source: Any | None = None, +) -> ssl.SSLSocket: + """Make a socket. + + This function uses the module's ``socket_factory`` to make a socket of the + specified address family and type. + + *af*, a ``socket.AddressFamily`` or ``int`` is the address family, either + ``socket.AF_INET`` or ``socket.AF_INET6``. + + *type*, a ``socket.SocketKind`` is the type of socket, e.g. ``socket.SOCK_DGRAM``, + a datagram socket, or ``socket.SOCK_STREAM``, a stream socket. Note that the + ``proto`` attribute of a socket is always zero with this API, so a datagram socket + will always be a UDP socket, and a stream socket will always be a TCP socket. + + If *ssl_context* is not ``None``, then it specifies the SSL context to use, + typically created with ``make_ssl_context()``. + + If *server_hostname* is not ``None``, then it is the hostname to use for server + certificate validation. A valid hostname must be supplied if *ssl_context* + requires hostname checking. + + *source* is the source address and port to bind to, if any. The default is + ``None`` which will bind to the wildcard address and a randomly chosen port. + If not ``None``, it should be a (low-level) address tuple appropriate for *af*. + """ + sock = make_socket(af, type, source) + if isinstance(server_hostname, dns.name.Name): + server_hostname = server_hostname.to_text() + # LGTM gets a false positive here, as our default context is OK + return ssl_context.wrap_socket( + sock, + do_handshake_on_connect=False, # lgtm[py/insecure-protocol] + server_hostname=server_hostname, + ) + + +# for backwards compatibility +def _make_socket( + af, + type, + source, + ssl_context, + server_hostname, +): + if ssl_context is not None: + return make_ssl_socket(af, type, ssl_context, server_hostname, source) + else: + return make_socket(af, type, source) + + +def _maybe_get_resolver( + resolver: Optional["dns.resolver.Resolver"], # pyright: ignore +) -> "dns.resolver.Resolver": # pyright: ignore + # We need a separate method for this to avoid overriding the global + # variable "dns" with the as-yet undefined local variable "dns" + # in https(). + if resolver is None: + # pylint: disable=import-outside-toplevel,redefined-outer-name + import dns.resolver + + resolver = dns.resolver.Resolver() + return resolver + + +class HTTPVersion(enum.IntEnum): + """Which version of HTTP should be used? + + DEFAULT will select the first version from the list [2, 1.1, 3] that + is available. + """ + + DEFAULT = 0 + HTTP_1 = 1 + H1 = 1 + HTTP_2 = 2 + H2 = 2 + HTTP_3 = 3 + H3 = 3 + + +def https( + q: dns.message.Message, + where: str, + timeout: float | None = None, + port: int = 443, + source: str | None = None, + source_port: int = 0, + one_rr_per_rrset: bool = False, + ignore_trailing: bool = False, + session: Any | None = None, + path: str = "/dns-query", + post: bool = True, + bootstrap_address: str | None = None, + verify: bool | str | ssl.SSLContext = True, + resolver: Optional["dns.resolver.Resolver"] = None, # pyright: ignore + family: int = socket.AF_UNSPEC, + http_version: HTTPVersion = HTTPVersion.DEFAULT, +) -> dns.message.Message: + """Return the response obtained after sending a query via DNS-over-HTTPS. + + *q*, a ``dns.message.Message``, the query to send. + + *where*, a ``str``, the nameserver IP address or the full URL. If an IP address is + given, the URL will be constructed using the following schema: + https://:/. + + *timeout*, a ``float`` or ``None``, the number of seconds to wait before the query + times out. If ``None``, the default, wait forever. + + *port*, a ``int``, the port to send the query to. The default is 443. + + *source*, a ``str`` containing an IPv4 or IPv6 address, specifying the source + address. The default is the wildcard address. + + *source_port*, an ``int``, the port from which to send the message. The default is + 0. + + *one_rr_per_rrset*, a ``bool``. If ``True``, put each RR into its own RRset. + + *ignore_trailing*, a ``bool``. If ``True``, ignore trailing junk at end of the + received message. + + *session*, an ``httpx.Client``. If provided, the client session to use to send the + queries. + + *path*, a ``str``. If *where* is an IP address, then *path* will be used to + construct the URL to send the DNS query to. + + *post*, a ``bool``. If ``True``, the default, POST method will be used. + + *bootstrap_address*, a ``str``, the IP address to use to bypass resolution. + + *verify*, a ``bool`` or ``str``. If a ``True``, then TLS certificate verification + of the server is done using the default CA bundle; if ``False``, then no + verification is done; if a `str` then it specifies the path to a certificate file or + directory which will be used for verification. + + *resolver*, a ``dns.resolver.Resolver`` or ``None``, the resolver to use for + resolution of hostnames in URLs. If not specified, a new resolver with a default + configuration will be used; note this is *not* the default resolver as that resolver + might have been configured to use DoH causing a chicken-and-egg problem. This + parameter only has an effect if the HTTP library is httpx. + + *family*, an ``int``, the address family. If socket.AF_UNSPEC (the default), both A + and AAAA records will be retrieved. + + *http_version*, a ``dns.query.HTTPVersion``, indicating which HTTP version to use. + + Returns a ``dns.message.Message``. + """ + + (af, _, the_source) = _destination_and_source( + where, port, source, source_port, False + ) + # we bind url and then override as pyright can't figure out all paths bind. + url = where + if af is not None and dns.inet.is_address(where): + if af == socket.AF_INET: + url = f"https://{where}:{port}{path}" + elif af == socket.AF_INET6: + url = f"https://[{where}]:{port}{path}" + + extensions = {} + if bootstrap_address is None: + # pylint: disable=possibly-used-before-assignment + parsed = urllib.parse.urlparse(url) + if parsed.hostname is None: + raise ValueError("no hostname in URL") + if dns.inet.is_address(parsed.hostname): + bootstrap_address = parsed.hostname + extensions["sni_hostname"] = parsed.hostname + if parsed.port is not None: + port = parsed.port + + if http_version == HTTPVersion.H3 or ( + http_version == HTTPVersion.DEFAULT and not have_doh + ): + if bootstrap_address is None: + resolver = _maybe_get_resolver(resolver) + assert parsed.hostname is not None # pyright: ignore + answers = resolver.resolve_name(parsed.hostname, family) # pyright: ignore + bootstrap_address = random.choice(list(answers.addresses())) + if session and not isinstance( + session, dns.quic.SyncQuicConnection + ): # pyright: ignore + raise ValueError("session parameter must be a dns.quic.SyncQuicConnection.") + return _http3( + q, + bootstrap_address, + url, # pyright: ignore + timeout, + port, + source, + source_port, + one_rr_per_rrset, + ignore_trailing, + verify=verify, + post=post, + connection=session, + ) + + if not have_doh: + raise NoDOH # pragma: no cover + if session and not isinstance(session, httpx.Client): # pyright: ignore + raise ValueError("session parameter must be an httpx.Client") + + wire = q.to_wire() + headers = {"accept": "application/dns-message"} + + h1 = http_version in (HTTPVersion.H1, HTTPVersion.DEFAULT) + h2 = http_version in (HTTPVersion.H2, HTTPVersion.DEFAULT) + + # set source port and source address + + if the_source is None: + local_address = None + local_port = 0 + else: + local_address = the_source[0] + local_port = the_source[1] + + if session: + cm: contextlib.AbstractContextManager = contextlib.nullcontext(session) + else: + transport = _HTTPTransport( + local_address=local_address, + http1=h1, + http2=h2, + verify=verify, + local_port=local_port, + bootstrap_address=bootstrap_address, + resolver=resolver, + family=family, # pyright: ignore + ) + + cm = httpx.Client( # type: ignore + http1=h1, http2=h2, verify=verify, transport=transport # type: ignore + ) + with cm as session: + # see https://tools.ietf.org/html/rfc8484#section-4.1.1 for DoH + # GET and POST examples + assert session is not None + if post: + headers.update( + { + "content-type": "application/dns-message", + "content-length": str(len(wire)), + } + ) + response = session.post( + url, + headers=headers, + content=wire, + timeout=timeout, + extensions=extensions, + ) + else: + wire = base64.urlsafe_b64encode(wire).rstrip(b"=") + twire = wire.decode() # httpx does a repr() if we give it bytes + response = session.get( + url, + headers=headers, + timeout=timeout, + params={"dns": twire}, + extensions=extensions, + ) + + # see https://tools.ietf.org/html/rfc8484#section-4.2.1 for info about DoH + # status codes + if response.status_code < 200 or response.status_code > 299: + raise ValueError( + f"{where} responded with status code {response.status_code}" + f"\nResponse body: {response.content}" + ) + r = dns.message.from_wire( + response.content, + keyring=q.keyring, + request_mac=q.request_mac, + one_rr_per_rrset=one_rr_per_rrset, + ignore_trailing=ignore_trailing, + ) + r.time = response.elapsed.total_seconds() + if not q.is_response(r): + raise BadResponse + return r + + +def _find_header(headers: dns.quic.Headers, name: bytes) -> bytes: + if headers is None: + raise KeyError + for header, value in headers: + if header == name: + return value + raise KeyError + + +def _check_status(headers: dns.quic.Headers, peer: str, wire: bytes) -> None: + value = _find_header(headers, b":status") + if value is None: + raise SyntaxError("no :status header in response") + status = int(value) + if status < 0: + raise SyntaxError("status is negative") + if status < 200 or status > 299: + error = "" + if len(wire) > 0: + try: + error = ": " + wire.decode() + except Exception: + pass + raise ValueError(f"{peer} responded with status code {status}{error}") + + +def _http3( + q: dns.message.Message, + where: str, + url: str, + timeout: float | None = None, + port: int = 443, + source: str | None = None, + source_port: int = 0, + one_rr_per_rrset: bool = False, + ignore_trailing: bool = False, + verify: bool | str | ssl.SSLContext = True, + post: bool = True, + connection: dns.quic.SyncQuicConnection | None = None, +) -> dns.message.Message: + if not dns.quic.have_quic: + raise NoDOH("DNS-over-HTTP3 is not available.") # pragma: no cover + + url_parts = urllib.parse.urlparse(url) + hostname = url_parts.hostname + assert hostname is not None + if url_parts.port is not None: + port = url_parts.port + + q.id = 0 + wire = q.to_wire() + the_connection: dns.quic.SyncQuicConnection + the_manager: dns.quic.SyncQuicManager + if connection: + manager: contextlib.AbstractContextManager = contextlib.nullcontext(None) + else: + manager = dns.quic.SyncQuicManager( + verify_mode=verify, server_name=hostname, h3=True # pyright: ignore + ) + the_manager = manager # for type checking happiness + + with manager: + if connection: + the_connection = connection + else: + the_connection = the_manager.connect( # pyright: ignore + where, port, source, source_port + ) + (start, expiration) = _compute_times(timeout) + with the_connection.make_stream(timeout) as stream: # pyright: ignore + stream.send_h3(url, wire, post) + wire = stream.receive(_remaining(expiration)) + _check_status(stream.headers(), where, wire) + finish = time.time() + r = dns.message.from_wire( + wire, + keyring=q.keyring, + request_mac=q.request_mac, + one_rr_per_rrset=one_rr_per_rrset, + ignore_trailing=ignore_trailing, + ) + r.time = max(finish - start, 0.0) + if not q.is_response(r): + raise BadResponse + return r + + +def _udp_recv(sock, max_size, expiration): + """Reads a datagram from the socket. + A Timeout exception will be raised if the operation is not completed + by the expiration time. + """ + while True: + try: + return sock.recvfrom(max_size) + except BlockingIOError: + _wait_for_readable(sock, expiration) + + +def _udp_send(sock, data, destination, expiration): + """Sends the specified datagram to destination over the socket. + A Timeout exception will be raised if the operation is not completed + by the expiration time. + """ + while True: + try: + if destination: + return sock.sendto(data, destination) + else: + return sock.send(data) + except BlockingIOError: # pragma: no cover + _wait_for_writable(sock, expiration) + + +def send_udp( + sock: Any, + what: dns.message.Message | bytes, + destination: Any, + expiration: float | None = None, +) -> Tuple[int, float]: + """Send a DNS message to the specified UDP socket. + + *sock*, a ``socket``. + + *what*, a ``bytes`` or ``dns.message.Message``, the message to send. + + *destination*, a destination tuple appropriate for the address family + of the socket, specifying where to send the query. + + *expiration*, a ``float`` or ``None``, the absolute time at which + a timeout exception should be raised. If ``None``, no timeout will + occur. + + Returns an ``(int, float)`` tuple of bytes sent and the sent time. + """ + + if isinstance(what, dns.message.Message): + what = what.to_wire() + sent_time = time.time() + n = _udp_send(sock, what, destination, expiration) + return (n, sent_time) + + +def receive_udp( + sock: Any, + destination: Any | None = None, + expiration: float | None = None, + ignore_unexpected: bool = False, + one_rr_per_rrset: bool = False, + keyring: Dict[dns.name.Name, dns.tsig.Key] | None = None, + request_mac: bytes | None = b"", + ignore_trailing: bool = False, + raise_on_truncation: bool = False, + ignore_errors: bool = False, + query: dns.message.Message | None = None, +) -> Any: + """Read a DNS message from a UDP socket. + + *sock*, a ``socket``. + + *destination*, a destination tuple appropriate for the address family + of the socket, specifying where the message is expected to arrive from. + When receiving a response, this would be where the associated query was + sent. + + *expiration*, a ``float`` or ``None``, the absolute time at which + a timeout exception should be raised. If ``None``, no timeout will + occur. + + *ignore_unexpected*, a ``bool``. If ``True``, ignore responses from + unexpected sources. + + *one_rr_per_rrset*, a ``bool``. If ``True``, put each RR into its own + RRset. + + *keyring*, a ``dict``, the keyring to use for TSIG. + + *request_mac*, a ``bytes`` or ``None``, the MAC of the request (for TSIG). + + *ignore_trailing*, a ``bool``. If ``True``, ignore trailing + junk at end of the received message. + + *raise_on_truncation*, a ``bool``. If ``True``, raise an exception if + the TC bit is set. + + Raises if the message is malformed, if network errors occur, of if + there is a timeout. + + If *destination* is not ``None``, returns a ``(dns.message.Message, float)`` + tuple of the received message and the received time. + + If *destination* is ``None``, returns a + ``(dns.message.Message, float, tuple)`` + tuple of the received message, the received time, and the address where + the message arrived from. + + *ignore_errors*, a ``bool``. If various format errors or response + mismatches occur, ignore them and keep listening for a valid response. + The default is ``False``. + + *query*, a ``dns.message.Message`` or ``None``. If not ``None`` and + *ignore_errors* is ``True``, check that the received message is a response + to this query, and if not keep listening for a valid response. + """ + + wire = b"" + while True: + (wire, from_address) = _udp_recv(sock, 65535, expiration) + if not _matches_destination( + sock.family, from_address, destination, ignore_unexpected + ): + continue + received_time = time.time() + try: + r = dns.message.from_wire( + wire, + keyring=keyring, + request_mac=request_mac, + one_rr_per_rrset=one_rr_per_rrset, + ignore_trailing=ignore_trailing, + raise_on_truncation=raise_on_truncation, + ) + except dns.message.Truncated as e: + # If we got Truncated and not FORMERR, we at least got the header with TC + # set, and very likely the question section, so we'll re-raise if the + # message seems to be a response as we need to know when truncation happens. + # We need to check that it seems to be a response as we don't want a random + # injected message with TC set to cause us to bail out. + if ( + ignore_errors + and query is not None + and not query.is_response(e.message()) + ): + continue + else: + raise + except Exception: + if ignore_errors: + continue + else: + raise + if ignore_errors and query is not None and not query.is_response(r): + continue + if destination: + return (r, received_time) + else: + return (r, received_time, from_address) + + +def udp( + q: dns.message.Message, + where: str, + timeout: float | None = None, + port: int = 53, + source: str | None = None, + source_port: int = 0, + ignore_unexpected: bool = False, + one_rr_per_rrset: bool = False, + ignore_trailing: bool = False, + raise_on_truncation: bool = False, + sock: Any | None = None, + ignore_errors: bool = False, +) -> dns.message.Message: + """Return the response obtained after sending a query via UDP. + + *q*, a ``dns.message.Message``, the query to send + + *where*, a ``str`` containing an IPv4 or IPv6 address, where + to send the message. + + *timeout*, a ``float`` or ``None``, the number of seconds to wait before the + query times out. If ``None``, the default, wait forever. + + *port*, an ``int``, the port send the message to. The default is 53. + + *source*, a ``str`` containing an IPv4 or IPv6 address, specifying + the source address. The default is the wildcard address. + + *source_port*, an ``int``, the port from which to send the message. + The default is 0. + + *ignore_unexpected*, a ``bool``. If ``True``, ignore responses from + unexpected sources. + + *one_rr_per_rrset*, a ``bool``. If ``True``, put each RR into its own + RRset. + + *ignore_trailing*, a ``bool``. If ``True``, ignore trailing + junk at end of the received message. + + *raise_on_truncation*, a ``bool``. If ``True``, raise an exception if + the TC bit is set. + + *sock*, a ``socket.socket``, or ``None``, the socket to use for the + query. If ``None``, the default, a socket is created. Note that + if a socket is provided, it must be a nonblocking datagram socket, + and the *source* and *source_port* are ignored. + + *ignore_errors*, a ``bool``. If various format errors or response + mismatches occur, ignore them and keep listening for a valid response. + The default is ``False``. + + Returns a ``dns.message.Message``. + """ + + wire = q.to_wire() + (af, destination, source) = _destination_and_source( + where, port, source, source_port, True + ) + (begin_time, expiration) = _compute_times(timeout) + if sock: + cm: contextlib.AbstractContextManager = contextlib.nullcontext(sock) + else: + assert af is not None + cm = make_socket(af, socket.SOCK_DGRAM, source) + with cm as s: + send_udp(s, wire, destination, expiration) + (r, received_time) = receive_udp( + s, + destination, + expiration, + ignore_unexpected, + one_rr_per_rrset, + q.keyring, + q.mac, + ignore_trailing, + raise_on_truncation, + ignore_errors, + q, + ) + r.time = received_time - begin_time + # We don't need to check q.is_response() if we are in ignore_errors mode + # as receive_udp() will have checked it. + if not (ignore_errors or q.is_response(r)): + raise BadResponse + return r + assert ( + False # help mypy figure out we can't get here lgtm[py/unreachable-statement] + ) + + +def udp_with_fallback( + q: dns.message.Message, + where: str, + timeout: float | None = None, + port: int = 53, + source: str | None = None, + source_port: int = 0, + ignore_unexpected: bool = False, + one_rr_per_rrset: bool = False, + ignore_trailing: bool = False, + udp_sock: Any | None = None, + tcp_sock: Any | None = None, + ignore_errors: bool = False, +) -> Tuple[dns.message.Message, bool]: + """Return the response to the query, trying UDP first and falling back + to TCP if UDP results in a truncated response. + + *q*, a ``dns.message.Message``, the query to send + + *where*, a ``str`` containing an IPv4 or IPv6 address, where to send the message. + + *timeout*, a ``float`` or ``None``, the number of seconds to wait before the query + times out. If ``None``, the default, wait forever. + + *port*, an ``int``, the port send the message to. The default is 53. + + *source*, a ``str`` containing an IPv4 or IPv6 address, specifying the source + address. The default is the wildcard address. + + *source_port*, an ``int``, the port from which to send the message. The default is + 0. + + *ignore_unexpected*, a ``bool``. If ``True``, ignore responses from unexpected + sources. + + *one_rr_per_rrset*, a ``bool``. If ``True``, put each RR into its own RRset. + + *ignore_trailing*, a ``bool``. If ``True``, ignore trailing junk at end of the + received message. + + *udp_sock*, a ``socket.socket``, or ``None``, the socket to use for the UDP query. + If ``None``, the default, a socket is created. Note that if a socket is provided, + it must be a nonblocking datagram socket, and the *source* and *source_port* are + ignored for the UDP query. + + *tcp_sock*, a ``socket.socket``, or ``None``, the connected socket to use for the + TCP query. If ``None``, the default, a socket is created. Note that if a socket is + provided, it must be a nonblocking connected stream socket, and *where*, *source* + and *source_port* are ignored for the TCP query. + + *ignore_errors*, a ``bool``. If various format errors or response mismatches occur + while listening for UDP, ignore them and keep listening for a valid response. The + default is ``False``. + + Returns a (``dns.message.Message``, tcp) tuple where tcp is ``True`` if and only if + TCP was used. + """ + try: + response = udp( + q, + where, + timeout, + port, + source, + source_port, + ignore_unexpected, + one_rr_per_rrset, + ignore_trailing, + True, + udp_sock, + ignore_errors, + ) + return (response, False) + except dns.message.Truncated: + response = tcp( + q, + where, + timeout, + port, + source, + source_port, + one_rr_per_rrset, + ignore_trailing, + tcp_sock, + ) + return (response, True) + + +def _net_read(sock, count, expiration): + """Read the specified number of bytes from sock. Keep trying until we + either get the desired amount, or we hit EOF. + A Timeout exception will be raised if the operation is not completed + by the expiration time. + """ + s = b"" + while count > 0: + try: + n = sock.recv(count) + if n == b"": + raise EOFError("EOF") + count -= len(n) + s += n + except (BlockingIOError, ssl.SSLWantReadError): + _wait_for_readable(sock, expiration) + except ssl.SSLWantWriteError: # pragma: no cover + _wait_for_writable(sock, expiration) + return s + + +def _net_write(sock, data, expiration): + """Write the specified data to the socket. + A Timeout exception will be raised if the operation is not completed + by the expiration time. + """ + current = 0 + l = len(data) + while current < l: + try: + current += sock.send(data[current:]) + except (BlockingIOError, ssl.SSLWantWriteError): + _wait_for_writable(sock, expiration) + except ssl.SSLWantReadError: # pragma: no cover + _wait_for_readable(sock, expiration) + + +def send_tcp( + sock: Any, + what: dns.message.Message | bytes, + expiration: float | None = None, +) -> Tuple[int, float]: + """Send a DNS message to the specified TCP socket. + + *sock*, a ``socket``. + + *what*, a ``bytes`` or ``dns.message.Message``, the message to send. + + *expiration*, a ``float`` or ``None``, the absolute time at which + a timeout exception should be raised. If ``None``, no timeout will + occur. + + Returns an ``(int, float)`` tuple of bytes sent and the sent time. + """ + + if isinstance(what, dns.message.Message): + tcpmsg = what.to_wire(prepend_length=True) + else: + # copying the wire into tcpmsg is inefficient, but lets us + # avoid writev() or doing a short write that would get pushed + # onto the net + tcpmsg = len(what).to_bytes(2, "big") + what + sent_time = time.time() + _net_write(sock, tcpmsg, expiration) + return (len(tcpmsg), sent_time) + + +def receive_tcp( + sock: Any, + expiration: float | None = None, + one_rr_per_rrset: bool = False, + keyring: Dict[dns.name.Name, dns.tsig.Key] | None = None, + request_mac: bytes | None = b"", + ignore_trailing: bool = False, +) -> Tuple[dns.message.Message, float]: + """Read a DNS message from a TCP socket. + + *sock*, a ``socket``. + + *expiration*, a ``float`` or ``None``, the absolute time at which + a timeout exception should be raised. If ``None``, no timeout will + occur. + + *one_rr_per_rrset*, a ``bool``. If ``True``, put each RR into its own + RRset. + + *keyring*, a ``dict``, the keyring to use for TSIG. + + *request_mac*, a ``bytes`` or ``None``, the MAC of the request (for TSIG). + + *ignore_trailing*, a ``bool``. If ``True``, ignore trailing + junk at end of the received message. + + Raises if the message is malformed, if network errors occur, of if + there is a timeout. + + Returns a ``(dns.message.Message, float)`` tuple of the received message + and the received time. + """ + + ldata = _net_read(sock, 2, expiration) + (l,) = struct.unpack("!H", ldata) + wire = _net_read(sock, l, expiration) + received_time = time.time() + r = dns.message.from_wire( + wire, + keyring=keyring, + request_mac=request_mac, + one_rr_per_rrset=one_rr_per_rrset, + ignore_trailing=ignore_trailing, + ) + return (r, received_time) + + +def _connect(s, address, expiration): + err = s.connect_ex(address) + if err == 0: + return + if err in (errno.EINPROGRESS, errno.EWOULDBLOCK, errno.EALREADY): + _wait_for_writable(s, expiration) + err = s.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) + if err != 0: + raise OSError(err, os.strerror(err)) + + +def tcp( + q: dns.message.Message, + where: str, + timeout: float | None = None, + port: int = 53, + source: str | None = None, + source_port: int = 0, + one_rr_per_rrset: bool = False, + ignore_trailing: bool = False, + sock: Any | None = None, +) -> dns.message.Message: + """Return the response obtained after sending a query via TCP. + + *q*, a ``dns.message.Message``, the query to send + + *where*, a ``str`` containing an IPv4 or IPv6 address, where + to send the message. + + *timeout*, a ``float`` or ``None``, the number of seconds to wait before the + query times out. If ``None``, the default, wait forever. + + *port*, an ``int``, the port send the message to. The default is 53. + + *source*, a ``str`` containing an IPv4 or IPv6 address, specifying + the source address. The default is the wildcard address. + + *source_port*, an ``int``, the port from which to send the message. + The default is 0. + + *one_rr_per_rrset*, a ``bool``. If ``True``, put each RR into its own + RRset. + + *ignore_trailing*, a ``bool``. If ``True``, ignore trailing + junk at end of the received message. + + *sock*, a ``socket.socket``, or ``None``, the connected socket to use for the + query. If ``None``, the default, a socket is created. Note that + if a socket is provided, it must be a nonblocking connected stream + socket, and *where*, *port*, *source* and *source_port* are ignored. + + Returns a ``dns.message.Message``. + """ + + wire = q.to_wire() + (begin_time, expiration) = _compute_times(timeout) + if sock: + cm: contextlib.AbstractContextManager = contextlib.nullcontext(sock) + else: + (af, destination, source) = _destination_and_source( + where, port, source, source_port, True + ) + assert af is not None + cm = make_socket(af, socket.SOCK_STREAM, source) + with cm as s: + if not sock: + # pylint: disable=possibly-used-before-assignment + _connect(s, destination, expiration) # pyright: ignore + send_tcp(s, wire, expiration) + (r, received_time) = receive_tcp( + s, expiration, one_rr_per_rrset, q.keyring, q.mac, ignore_trailing + ) + r.time = received_time - begin_time + if not q.is_response(r): + raise BadResponse + return r + assert ( + False # help mypy figure out we can't get here lgtm[py/unreachable-statement] + ) + + +def _tls_handshake(s, expiration): + while True: + try: + s.do_handshake() + return + except ssl.SSLWantReadError: + _wait_for_readable(s, expiration) + except ssl.SSLWantWriteError: # pragma: no cover + _wait_for_writable(s, expiration) + + +def make_ssl_context( + verify: bool | str = True, + check_hostname: bool = True, + alpns: list[str] | None = None, +) -> ssl.SSLContext: + """Make an SSL context + + If *verify* is ``True``, the default, then certificate verification will occur using + the standard CA roots. If *verify* is ``False``, then certificate verification will + be disabled. If *verify* is a string which is a valid pathname, then if the + pathname is a regular file, the CA roots will be taken from the file, otherwise if + the pathname is a directory roots will be taken from the directory. + + If *check_hostname* is ``True``, the default, then the hostname of the server must + be specified when connecting and the server's certificate must authorize the + hostname. If ``False``, then hostname checking is disabled. + + *aplns* is ``None`` or a list of TLS ALPN (Application Layer Protocol Negotiation) + strings to use in negotiation. For DNS-over-TLS, the right value is `["dot"]`. + """ + cafile, capath = dns._tls_util.convert_verify_to_cafile_and_capath(verify) + ssl_context = ssl.create_default_context(cafile=cafile, capath=capath) + # the pyright ignores below are because it gets confused between the + # _no_ssl compatibility types and the real ones. + ssl_context.minimum_version = ssl.TLSVersion.TLSv1_2 # type: ignore + ssl_context.check_hostname = check_hostname + if verify is False: + ssl_context.verify_mode = ssl.CERT_NONE # type: ignore + if alpns is not None: + ssl_context.set_alpn_protocols(alpns) + return ssl_context # type: ignore + + +# for backwards compatibility +def _make_dot_ssl_context( + server_hostname: str | None, verify: bool | str +) -> ssl.SSLContext: + return make_ssl_context(verify, server_hostname is not None, ["dot"]) + + +def tls( + q: dns.message.Message, + where: str, + timeout: float | None = None, + port: int = 853, + source: str | None = None, + source_port: int = 0, + one_rr_per_rrset: bool = False, + ignore_trailing: bool = False, + sock: ssl.SSLSocket | None = None, + ssl_context: ssl.SSLContext | None = None, + server_hostname: str | None = None, + verify: bool | str = True, +) -> dns.message.Message: + """Return the response obtained after sending a query via TLS. + + *q*, a ``dns.message.Message``, the query to send + + *where*, a ``str`` containing an IPv4 or IPv6 address, where + to send the message. + + *timeout*, a ``float`` or ``None``, the number of seconds to wait before the + query times out. If ``None``, the default, wait forever. + + *port*, an ``int``, the port send the message to. The default is 853. + + *source*, a ``str`` containing an IPv4 or IPv6 address, specifying + the source address. The default is the wildcard address. + + *source_port*, an ``int``, the port from which to send the message. + The default is 0. + + *one_rr_per_rrset*, a ``bool``. If ``True``, put each RR into its own + RRset. + + *ignore_trailing*, a ``bool``. If ``True``, ignore trailing + junk at end of the received message. + + *sock*, an ``ssl.SSLSocket``, or ``None``, the socket to use for + the query. If ``None``, the default, a socket is created. Note + that if a socket is provided, it must be a nonblocking connected + SSL stream socket, and *where*, *port*, *source*, *source_port*, + and *ssl_context* are ignored. + + *ssl_context*, an ``ssl.SSLContext``, the context to use when establishing + a TLS connection. If ``None``, the default, creates one with the default + configuration. + + *server_hostname*, a ``str`` containing the server's hostname. The + default is ``None``, which means that no hostname is known, and if an + SSL context is created, hostname checking will be disabled. + + *verify*, a ``bool`` or ``str``. If a ``True``, then TLS certificate verification + of the server is done using the default CA bundle; if ``False``, then no + verification is done; if a `str` then it specifies the path to a certificate file or + directory which will be used for verification. + + Returns a ``dns.message.Message``. + + """ + + if sock: + # + # If a socket was provided, there's no special TLS handling needed. + # + return tcp( + q, + where, + timeout, + port, + source, + source_port, + one_rr_per_rrset, + ignore_trailing, + sock, + ) + + wire = q.to_wire() + (begin_time, expiration) = _compute_times(timeout) + (af, destination, source) = _destination_and_source( + where, port, source, source_port, True + ) + assert af is not None # where must be an address + if ssl_context is None: + ssl_context = make_ssl_context(verify, server_hostname is not None, ["dot"]) + + with make_ssl_socket( + af, + socket.SOCK_STREAM, + ssl_context=ssl_context, + server_hostname=server_hostname, + source=source, + ) as s: + _connect(s, destination, expiration) + _tls_handshake(s, expiration) + send_tcp(s, wire, expiration) + (r, received_time) = receive_tcp( + s, expiration, one_rr_per_rrset, q.keyring, q.mac, ignore_trailing + ) + r.time = received_time - begin_time + if not q.is_response(r): + raise BadResponse + return r + assert ( + False # help mypy figure out we can't get here lgtm[py/unreachable-statement] + ) + + +def quic( + q: dns.message.Message, + where: str, + timeout: float | None = None, + port: int = 853, + source: str | None = None, + source_port: int = 0, + one_rr_per_rrset: bool = False, + ignore_trailing: bool = False, + connection: dns.quic.SyncQuicConnection | None = None, + verify: bool | str = True, + hostname: str | None = None, + server_hostname: str | None = None, +) -> dns.message.Message: + """Return the response obtained after sending a query via DNS-over-QUIC. + + *q*, a ``dns.message.Message``, the query to send. + + *where*, a ``str``, the nameserver IP address. + + *timeout*, a ``float`` or ``None``, the number of seconds to wait before the query + times out. If ``None``, the default, wait forever. + + *port*, a ``int``, the port to send the query to. The default is 853. + + *source*, a ``str`` containing an IPv4 or IPv6 address, specifying the source + address. The default is the wildcard address. + + *source_port*, an ``int``, the port from which to send the message. The default is + 0. + + *one_rr_per_rrset*, a ``bool``. If ``True``, put each RR into its own RRset. + + *ignore_trailing*, a ``bool``. If ``True``, ignore trailing junk at end of the + received message. + + *connection*, a ``dns.quic.SyncQuicConnection``. If provided, the connection to use + to send the query. + + *verify*, a ``bool`` or ``str``. If a ``True``, then TLS certificate verification + of the server is done using the default CA bundle; if ``False``, then no + verification is done; if a `str` then it specifies the path to a certificate file or + directory which will be used for verification. + + *hostname*, a ``str`` containing the server's hostname or ``None``. The default is + ``None``, which means that no hostname is known, and if an SSL context is created, + hostname checking will be disabled. This value is ignored if *url* is not + ``None``. + + *server_hostname*, a ``str`` or ``None``. This item is for backwards compatibility + only, and has the same meaning as *hostname*. + + Returns a ``dns.message.Message``. + """ + + if not dns.quic.have_quic: + raise NoDOQ("DNS-over-QUIC is not available.") # pragma: no cover + + if server_hostname is not None and hostname is None: + hostname = server_hostname + + q.id = 0 + wire = q.to_wire() + the_connection: dns.quic.SyncQuicConnection + the_manager: dns.quic.SyncQuicManager + if connection: + manager: contextlib.AbstractContextManager = contextlib.nullcontext(None) + the_connection = connection + else: + manager = dns.quic.SyncQuicManager( + verify_mode=verify, server_name=hostname # pyright: ignore + ) + the_manager = manager # for type checking happiness + + with manager: + if not connection: + the_connection = the_manager.connect( # pyright: ignore + where, port, source, source_port + ) + (start, expiration) = _compute_times(timeout) + with the_connection.make_stream(timeout) as stream: # pyright: ignore + stream.send(wire, True) + wire = stream.receive(_remaining(expiration)) + finish = time.time() + r = dns.message.from_wire( + wire, + keyring=q.keyring, + request_mac=q.request_mac, + one_rr_per_rrset=one_rr_per_rrset, + ignore_trailing=ignore_trailing, + ) + r.time = max(finish - start, 0.0) + if not q.is_response(r): + raise BadResponse + return r + + +class UDPMode(enum.IntEnum): + """How should UDP be used in an IXFR from :py:func:`inbound_xfr()`? + + NEVER means "never use UDP; always use TCP" + TRY_FIRST means "try to use UDP but fall back to TCP if needed" + ONLY means "raise ``dns.xfr.UseTCP`` if trying UDP does not succeed" + """ + + NEVER = 0 + TRY_FIRST = 1 + ONLY = 2 + + +def _inbound_xfr( + txn_manager: dns.transaction.TransactionManager, + s: socket.socket | ssl.SSLSocket, + query: dns.message.Message, + serial: int | None, + timeout: float | None, + expiration: float | None, +) -> Any: + """Given a socket, does the zone transfer.""" + rdtype = query.question[0].rdtype + is_ixfr = rdtype == dns.rdatatype.IXFR + origin = txn_manager.from_wire_origin() + wire = query.to_wire() + is_udp = isinstance(s, socket.socket) and s.type == socket.SOCK_DGRAM + if is_udp: + _udp_send(s, wire, None, expiration) + else: + tcpmsg = struct.pack("!H", len(wire)) + wire + _net_write(s, tcpmsg, expiration) + with dns.xfr.Inbound(txn_manager, rdtype, serial, is_udp) as inbound: + done = False + tsig_ctx = None + r: dns.message.Message | None = None + while not done: + (_, mexpiration) = _compute_times(timeout) + if mexpiration is None or ( + expiration is not None and mexpiration > expiration + ): + mexpiration = expiration + if is_udp: + (rwire, _) = _udp_recv(s, 65535, mexpiration) + else: + ldata = _net_read(s, 2, mexpiration) + (l,) = struct.unpack("!H", ldata) + rwire = _net_read(s, l, mexpiration) + r = dns.message.from_wire( + rwire, + keyring=query.keyring, + request_mac=query.mac, + xfr=True, + origin=origin, + tsig_ctx=tsig_ctx, + multi=(not is_udp), + one_rr_per_rrset=is_ixfr, + ) + done = inbound.process_message(r) + yield r + tsig_ctx = r.tsig_ctx + if query.keyring and r is not None and not r.had_tsig: + raise dns.exception.FormError("missing TSIG") + + +def xfr( + where: str, + zone: dns.name.Name | str, + rdtype: dns.rdatatype.RdataType | str = dns.rdatatype.AXFR, + rdclass: dns.rdataclass.RdataClass | str = dns.rdataclass.IN, + timeout: float | None = None, + port: int = 53, + keyring: Dict[dns.name.Name, dns.tsig.Key] | None = None, + keyname: dns.name.Name | str | None = None, + relativize: bool = True, + lifetime: float | None = None, + source: str | None = None, + source_port: int = 0, + serial: int = 0, + use_udp: bool = False, + keyalgorithm: dns.name.Name | str = dns.tsig.default_algorithm, +) -> Any: + """Return a generator for the responses to a zone transfer. + + *where*, a ``str`` containing an IPv4 or IPv6 address, where + to send the message. + + *zone*, a ``dns.name.Name`` or ``str``, the name of the zone to transfer. + + *rdtype*, an ``int`` or ``str``, the type of zone transfer. The + default is ``dns.rdatatype.AXFR``. ``dns.rdatatype.IXFR`` can be + used to do an incremental transfer instead. + + *rdclass*, an ``int`` or ``str``, the class of the zone transfer. + The default is ``dns.rdataclass.IN``. + + *timeout*, a ``float``, the number of seconds to wait for each + response message. If None, the default, wait forever. + + *port*, an ``int``, the port send the message to. The default is 53. + + *keyring*, a ``dict``, the keyring to use for TSIG. + + *keyname*, a ``dns.name.Name`` or ``str``, the name of the TSIG + key to use. + + *relativize*, a ``bool``. If ``True``, all names in the zone will be + relativized to the zone origin. It is essential that the + relativize setting matches the one specified to + ``dns.zone.from_xfr()`` if using this generator to make a zone. + + *lifetime*, a ``float``, the total number of seconds to spend + doing the transfer. If ``None``, the default, then there is no + limit on the time the transfer may take. + + *source*, a ``str`` containing an IPv4 or IPv6 address, specifying + the source address. The default is the wildcard address. + + *source_port*, an ``int``, the port from which to send the message. + The default is 0. + + *serial*, an ``int``, the SOA serial number to use as the base for + an IXFR diff sequence (only meaningful if *rdtype* is + ``dns.rdatatype.IXFR``). + + *use_udp*, a ``bool``. If ``True``, use UDP (only meaningful for IXFR). + + *keyalgorithm*, a ``dns.name.Name`` or ``str``, the TSIG algorithm to use. + + Raises on errors, and so does the generator. + + Returns a generator of ``dns.message.Message`` objects. + """ + + class DummyTransactionManager(dns.transaction.TransactionManager): + def __init__(self, origin, relativize): + self.info = (origin, relativize, dns.name.empty if relativize else origin) + + def origin_information(self): + return self.info + + def get_class(self) -> dns.rdataclass.RdataClass: + raise NotImplementedError # pragma: no cover + + def reader(self): + raise NotImplementedError # pragma: no cover + + def writer(self, replacement: bool = False) -> dns.transaction.Transaction: + class DummyTransaction: + def nop(self, *args, **kw): + pass + + def __getattr__(self, _): + return self.nop + + return cast(dns.transaction.Transaction, DummyTransaction()) + + if isinstance(zone, str): + zone = dns.name.from_text(zone) + rdtype = dns.rdatatype.RdataType.make(rdtype) + q = dns.message.make_query(zone, rdtype, rdclass) + if rdtype == dns.rdatatype.IXFR: + rrset = q.find_rrset( + q.authority, zone, dns.rdataclass.IN, dns.rdatatype.SOA, create=True + ) + soa = dns.rdata.from_text("IN", "SOA", f". . {serial} 0 0 0 0") + rrset.add(soa, 0) + if keyring is not None: + q.use_tsig(keyring, keyname, algorithm=keyalgorithm) + (af, destination, source) = _destination_and_source( + where, port, source, source_port, True + ) + assert af is not None + (_, expiration) = _compute_times(lifetime) + tm = DummyTransactionManager(zone, relativize) + if use_udp and rdtype != dns.rdatatype.IXFR: + raise ValueError("cannot do a UDP AXFR") + sock_type = socket.SOCK_DGRAM if use_udp else socket.SOCK_STREAM + with make_socket(af, sock_type, source) as s: + _connect(s, destination, expiration) + yield from _inbound_xfr(tm, s, q, serial, timeout, expiration) + + +def inbound_xfr( + where: str, + txn_manager: dns.transaction.TransactionManager, + query: dns.message.Message | None = None, + port: int = 53, + timeout: float | None = None, + lifetime: float | None = None, + source: str | None = None, + source_port: int = 0, + udp_mode: UDPMode = UDPMode.NEVER, +) -> None: + """Conduct an inbound transfer and apply it via a transaction from the + txn_manager. + + *where*, a ``str`` containing an IPv4 or IPv6 address, where + to send the message. + + *txn_manager*, a ``dns.transaction.TransactionManager``, the txn_manager + for this transfer (typically a ``dns.zone.Zone``). + + *query*, the query to send. If not supplied, a default query is + constructed using information from the *txn_manager*. + + *port*, an ``int``, the port send the message to. The default is 53. + + *timeout*, a ``float``, the number of seconds to wait for each + response message. If None, the default, wait forever. + + *lifetime*, a ``float``, the total number of seconds to spend + doing the transfer. If ``None``, the default, then there is no + limit on the time the transfer may take. + + *source*, a ``str`` containing an IPv4 or IPv6 address, specifying + the source address. The default is the wildcard address. + + *source_port*, an ``int``, the port from which to send the message. + The default is 0. + + *udp_mode*, a ``dns.query.UDPMode``, determines how UDP is used + for IXFRs. The default is ``dns.query.UDPMode.NEVER``, i.e. only use + TCP. Other possibilities are ``dns.query.UDPMode.TRY_FIRST``, which + means "try UDP but fallback to TCP if needed", and + ``dns.query.UDPMode.ONLY``, which means "try UDP and raise + ``dns.xfr.UseTCP`` if it does not succeed. + + Raises on errors. + """ + if query is None: + (query, serial) = dns.xfr.make_query(txn_manager) + else: + serial = dns.xfr.extract_serial_from_query(query) + + (af, destination, source) = _destination_and_source( + where, port, source, source_port, True + ) + assert af is not None + (_, expiration) = _compute_times(lifetime) + if query.question[0].rdtype == dns.rdatatype.IXFR and udp_mode != UDPMode.NEVER: + with make_socket(af, socket.SOCK_DGRAM, source) as s: + _connect(s, destination, expiration) + try: + for _ in _inbound_xfr( + txn_manager, s, query, serial, timeout, expiration + ): + pass + return + except dns.xfr.UseTCP: + if udp_mode == UDPMode.ONLY: + raise + + with make_socket(af, socket.SOCK_STREAM, source) as s: + _connect(s, destination, expiration) + for _ in _inbound_xfr(txn_manager, s, query, serial, timeout, expiration): + pass diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/quic/__init__.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/quic/__init__.py new file mode 100644 index 000000000..7c2a699ca --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/quic/__init__.py @@ -0,0 +1,78 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +from typing import Any, Dict, List, Tuple + +import dns._features +import dns.asyncbackend + +if dns._features.have("doq"): + from dns._asyncbackend import NullContext + from dns.quic._asyncio import AsyncioQuicConnection as AsyncioQuicConnection + from dns.quic._asyncio import AsyncioQuicManager + from dns.quic._asyncio import AsyncioQuicStream as AsyncioQuicStream + from dns.quic._common import AsyncQuicConnection # pyright: ignore + from dns.quic._common import AsyncQuicManager as AsyncQuicManager + from dns.quic._sync import SyncQuicConnection # pyright: ignore + from dns.quic._sync import SyncQuicStream # pyright: ignore + from dns.quic._sync import SyncQuicManager as SyncQuicManager + + have_quic = True + + def null_factory( + *args, # pylint: disable=unused-argument + **kwargs, # pylint: disable=unused-argument + ): + return NullContext(None) + + def _asyncio_manager_factory( + context, *args, **kwargs # pylint: disable=unused-argument + ): + return AsyncioQuicManager(*args, **kwargs) + + # We have a context factory and a manager factory as for trio we need to have + # a nursery. + + _async_factories: Dict[str, Tuple[Any, Any]] = { + "asyncio": (null_factory, _asyncio_manager_factory) + } + + if dns._features.have("trio"): + import trio + + # pylint: disable=ungrouped-imports + from dns.quic._trio import TrioQuicConnection as TrioQuicConnection + from dns.quic._trio import TrioQuicManager + from dns.quic._trio import TrioQuicStream as TrioQuicStream + + def _trio_context_factory(): + return trio.open_nursery() + + def _trio_manager_factory(context, *args, **kwargs): + return TrioQuicManager(context, *args, **kwargs) + + _async_factories["trio"] = (_trio_context_factory, _trio_manager_factory) + + def factories_for_backend(backend=None): + if backend is None: + backend = dns.asyncbackend.get_default_backend() + return _async_factories[backend.name()] + +else: # pragma: no cover + have_quic = False + + class AsyncQuicStream: # type: ignore + pass + + class AsyncQuicConnection: # type: ignore + async def make_stream(self) -> Any: + raise NotImplementedError + + class SyncQuicStream: # type: ignore + pass + + class SyncQuicConnection: # type: ignore + def make_stream(self) -> Any: + raise NotImplementedError + + +Headers = List[Tuple[bytes, bytes]] diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/quic/_asyncio.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/quic/_asyncio.py new file mode 100644 index 000000000..0a177b676 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/quic/_asyncio.py @@ -0,0 +1,276 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +import asyncio +import socket +import ssl +import struct +import time + +import aioquic.h3.connection # type: ignore +import aioquic.h3.events # type: ignore +import aioquic.quic.configuration # type: ignore +import aioquic.quic.connection # type: ignore +import aioquic.quic.events # type: ignore + +import dns.asyncbackend +import dns.exception +import dns.inet +from dns.quic._common import ( + QUIC_MAX_DATAGRAM, + AsyncQuicConnection, + AsyncQuicManager, + BaseQuicStream, + UnexpectedEOF, +) + + +class AsyncioQuicStream(BaseQuicStream): + def __init__(self, connection, stream_id): + super().__init__(connection, stream_id) + self._wake_up = asyncio.Condition() + + async def _wait_for_wake_up(self): + async with self._wake_up: + await self._wake_up.wait() + + async def wait_for(self, amount, expiration): + while True: + timeout = self._timeout_from_expiration(expiration) + if self._buffer.have(amount): + return + self._expecting = amount + try: + await asyncio.wait_for(self._wait_for_wake_up(), timeout) + except TimeoutError: + raise dns.exception.Timeout + self._expecting = 0 + + async def wait_for_end(self, expiration): + while True: + timeout = self._timeout_from_expiration(expiration) + if self._buffer.seen_end(): + return + try: + await asyncio.wait_for(self._wait_for_wake_up(), timeout) + except TimeoutError: + raise dns.exception.Timeout + + async def receive(self, timeout=None): + expiration = self._expiration_from_timeout(timeout) + if self._connection.is_h3(): + await self.wait_for_end(expiration) + return self._buffer.get_all() + else: + await self.wait_for(2, expiration) + (size,) = struct.unpack("!H", self._buffer.get(2)) + await self.wait_for(size, expiration) + return self._buffer.get(size) + + async def send(self, datagram, is_end=False): + data = self._encapsulate(datagram) + await self._connection.write(self._stream_id, data, is_end) + + async def _add_input(self, data, is_end): + if self._common_add_input(data, is_end): + async with self._wake_up: + self._wake_up.notify() + + async def close(self): + self._close() + + # Streams are async context managers + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc_val, exc_tb): + await self.close() + async with self._wake_up: + self._wake_up.notify() + return False + + +class AsyncioQuicConnection(AsyncQuicConnection): + def __init__(self, connection, address, port, source, source_port, manager=None): + super().__init__(connection, address, port, source, source_port, manager) + self._socket = None + self._handshake_complete = asyncio.Event() + self._socket_created = asyncio.Event() + self._wake_timer = asyncio.Condition() + self._receiver_task = None + self._sender_task = None + self._wake_pending = False + + async def _receiver(self): + try: + af = dns.inet.af_for_address(self._address) + backend = dns.asyncbackend.get_backend("asyncio") + # Note that peer is a low-level address tuple, but make_socket() wants + # a high-level address tuple, so we convert. + self._socket = await backend.make_socket( + af, socket.SOCK_DGRAM, 0, self._source, (self._peer[0], self._peer[1]) + ) + self._socket_created.set() + async with self._socket: + while not self._done: + (datagram, address) = await self._socket.recvfrom( + QUIC_MAX_DATAGRAM, None + ) + if address[0] != self._peer[0] or address[1] != self._peer[1]: + continue + self._connection.receive_datagram(datagram, address, time.time()) + # Wake up the timer in case the sender is sleeping, as there may be + # stuff to send now. + await self._wakeup() + except Exception: + pass + finally: + self._done = True + await self._wakeup() + self._handshake_complete.set() + + async def _wakeup(self): + self._wake_pending = True + async with self._wake_timer: + self._wake_timer.notify_all() + + async def _wait_for_wake_timer(self): + async with self._wake_timer: + if not self._wake_pending: + await self._wake_timer.wait() + self._wake_pending = False + + async def _sender(self): + await self._socket_created.wait() + while not self._done: + datagrams = self._connection.datagrams_to_send(time.time()) + for datagram, address in datagrams: + assert address == self._peer + assert self._socket is not None + await self._socket.sendto(datagram, self._peer, None) + (expiration, interval) = self._get_timer_values() + try: + await asyncio.wait_for(self._wait_for_wake_timer(), interval) + except Exception: + pass + self._handle_timer(expiration) + await self._handle_events() + + async def _handle_events(self): + count = 0 + while True: + event = self._connection.next_event() + if event is None: + return + if isinstance(event, aioquic.quic.events.StreamDataReceived): + if self.is_h3(): + assert self._h3_conn is not None + h3_events = self._h3_conn.handle_event(event) + for h3_event in h3_events: + if isinstance(h3_event, aioquic.h3.events.HeadersReceived): + stream = self._streams.get(event.stream_id) + if stream: + if stream._headers is None: + stream._headers = h3_event.headers + elif stream._trailers is None: + stream._trailers = h3_event.headers + if h3_event.stream_ended: + await stream._add_input(b"", True) + elif isinstance(h3_event, aioquic.h3.events.DataReceived): + stream = self._streams.get(event.stream_id) + if stream: + await stream._add_input( + h3_event.data, h3_event.stream_ended + ) + else: + stream = self._streams.get(event.stream_id) + if stream: + await stream._add_input(event.data, event.end_stream) + elif isinstance(event, aioquic.quic.events.HandshakeCompleted): + self._handshake_complete.set() + elif isinstance(event, aioquic.quic.events.ConnectionTerminated): + self._done = True + if self._receiver_task is not None: + self._receiver_task.cancel() + elif isinstance(event, aioquic.quic.events.StreamReset): + stream = self._streams.get(event.stream_id) + if stream: + await stream._add_input(b"", True) + + count += 1 + if count > 10: + # yield + count = 0 + await asyncio.sleep(0) + + async def write(self, stream, data, is_end=False): + self._connection.send_stream_data(stream, data, is_end) + await self._wakeup() + + def run(self): + if self._closed: + return + self._receiver_task = asyncio.Task(self._receiver()) + self._sender_task = asyncio.Task(self._sender()) + + async def make_stream(self, timeout=None): + try: + await asyncio.wait_for(self._handshake_complete.wait(), timeout) + except TimeoutError: + raise dns.exception.Timeout + if self._done: + raise UnexpectedEOF + stream_id = self._connection.get_next_available_stream_id(False) + stream = AsyncioQuicStream(self, stream_id) + self._streams[stream_id] = stream + return stream + + async def close(self): + if not self._closed: + if self._manager is not None: + self._manager.closed(self._peer[0], self._peer[1]) + self._closed = True + self._connection.close() + # sender might be blocked on this, so set it + self._socket_created.set() + await self._wakeup() + try: + if self._receiver_task is not None: + await self._receiver_task + except asyncio.CancelledError: + pass + try: + if self._sender_task is not None: + await self._sender_task + except asyncio.CancelledError: + pass + if self._socket is not None: + await self._socket.close() + + +class AsyncioQuicManager(AsyncQuicManager): + def __init__( + self, conf=None, verify_mode=ssl.CERT_REQUIRED, server_name=None, h3=False + ): + super().__init__(conf, verify_mode, AsyncioQuicConnection, server_name, h3) + + def connect( + self, address, port=853, source=None, source_port=0, want_session_ticket=True + ): + (connection, start) = self._connect( + address, port, source, source_port, want_session_ticket + ) + if start: + connection.run() + return connection + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc_val, exc_tb): + # Copy the iterator into a list as exiting things will mutate the connections + # table. + connections = list(self._connections.values()) + for connection in connections: + await connection.close() + return False diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/quic/_common.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/quic/_common.py new file mode 100644 index 000000000..ba9d24544 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/quic/_common.py @@ -0,0 +1,344 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +import base64 +import copy +import functools +import socket +import struct +import time +import urllib.parse +from typing import Any + +import aioquic.h3.connection # type: ignore +import aioquic.quic.configuration # type: ignore +import aioquic.quic.connection # type: ignore + +import dns._tls_util +import dns.inet + +QUIC_MAX_DATAGRAM = 2048 +MAX_SESSION_TICKETS = 8 +# If we hit the max sessions limit we will delete this many of the oldest connections. +# The value must be a integer > 0 and <= MAX_SESSION_TICKETS. +SESSIONS_TO_DELETE = MAX_SESSION_TICKETS // 4 + + +class UnexpectedEOF(Exception): + pass + + +class Buffer: + def __init__(self): + self._buffer = b"" + self._seen_end = False + + def put(self, data, is_end): + if self._seen_end: + return + self._buffer += data + if is_end: + self._seen_end = True + + def have(self, amount): + if len(self._buffer) >= amount: + return True + if self._seen_end: + raise UnexpectedEOF + return False + + def seen_end(self): + return self._seen_end + + def get(self, amount): + assert self.have(amount) + data = self._buffer[:amount] + self._buffer = self._buffer[amount:] + return data + + def get_all(self): + assert self.seen_end() + data = self._buffer + self._buffer = b"" + return data + + +class BaseQuicStream: + def __init__(self, connection, stream_id): + self._connection = connection + self._stream_id = stream_id + self._buffer = Buffer() + self._expecting = 0 + self._headers = None + self._trailers = None + + def id(self): + return self._stream_id + + def headers(self): + return self._headers + + def trailers(self): + return self._trailers + + def _expiration_from_timeout(self, timeout): + if timeout is not None: + expiration = time.time() + timeout + else: + expiration = None + return expiration + + def _timeout_from_expiration(self, expiration): + if expiration is not None: + timeout = max(expiration - time.time(), 0.0) + else: + timeout = None + return timeout + + # Subclass must implement receive() as sync / async and which returns a message + # or raises. + + # Subclass must implement send() as sync / async and which takes a message and + # an EOF indicator. + + def send_h3(self, url, datagram, post=True): + if not self._connection.is_h3(): + raise SyntaxError("cannot send H3 to a non-H3 connection") + url_parts = urllib.parse.urlparse(url) + path = url_parts.path.encode() + if post: + method = b"POST" + else: + method = b"GET" + path += b"?dns=" + base64.urlsafe_b64encode(datagram).rstrip(b"=") + headers = [ + (b":method", method), + (b":scheme", url_parts.scheme.encode()), + (b":authority", url_parts.netloc.encode()), + (b":path", path), + (b"accept", b"application/dns-message"), + ] + if post: + headers.extend( + [ + (b"content-type", b"application/dns-message"), + (b"content-length", str(len(datagram)).encode()), + ] + ) + self._connection.send_headers(self._stream_id, headers, not post) + if post: + self._connection.send_data(self._stream_id, datagram, True) + + def _encapsulate(self, datagram): + if self._connection.is_h3(): + return datagram + l = len(datagram) + return struct.pack("!H", l) + datagram + + def _common_add_input(self, data, is_end): + self._buffer.put(data, is_end) + try: + return ( + self._expecting > 0 and self._buffer.have(self._expecting) + ) or self._buffer.seen_end + except UnexpectedEOF: + return True + + def _close(self): + self._connection.close_stream(self._stream_id) + self._buffer.put(b"", True) # send EOF in case we haven't seen it. + + +class BaseQuicConnection: + def __init__( + self, + connection, + address, + port, + source=None, + source_port=0, + manager=None, + ): + self._done = False + self._connection = connection + self._address = address + self._port = port + self._closed = False + self._manager = manager + self._streams = {} + if manager is not None and manager.is_h3(): + self._h3_conn = aioquic.h3.connection.H3Connection(connection, False) + else: + self._h3_conn = None + self._af = dns.inet.af_for_address(address) + self._peer = dns.inet.low_level_address_tuple((address, port)) + if source is None and source_port != 0: + if self._af == socket.AF_INET: + source = "0.0.0.0" + elif self._af == socket.AF_INET6: + source = "::" + else: + raise NotImplementedError + if source: + self._source = (source, source_port) + else: + self._source = None + + def is_h3(self): + return self._h3_conn is not None + + def close_stream(self, stream_id): + del self._streams[stream_id] + + def send_headers(self, stream_id, headers, is_end=False): + assert self._h3_conn is not None + self._h3_conn.send_headers(stream_id, headers, is_end) + + def send_data(self, stream_id, data, is_end=False): + assert self._h3_conn is not None + self._h3_conn.send_data(stream_id, data, is_end) + + def _get_timer_values(self, closed_is_special=True): + now = time.time() + expiration = self._connection.get_timer() + if expiration is None: + expiration = now + 3600 # arbitrary "big" value + interval = max(expiration - now, 0) + if self._closed and closed_is_special: + # lower sleep interval to avoid a race in the closing process + # which can lead to higher latency closing due to sleeping when + # we have events. + interval = min(interval, 0.05) + return (expiration, interval) + + def _handle_timer(self, expiration): + now = time.time() + if expiration <= now: + self._connection.handle_timer(now) + + +class AsyncQuicConnection(BaseQuicConnection): + async def make_stream(self, timeout: float | None = None) -> Any: + pass + + +class BaseQuicManager: + def __init__( + self, conf, verify_mode, connection_factory, server_name=None, h3=False + ): + self._connections = {} + self._connection_factory = connection_factory + self._session_tickets = {} + self._tokens = {} + self._h3 = h3 + if conf is None: + verify_path = None + if isinstance(verify_mode, str): + verify_path = verify_mode + verify_mode = True + if h3: + alpn_protocols = ["h3"] + else: + alpn_protocols = ["doq", "doq-i03"] + conf = aioquic.quic.configuration.QuicConfiguration( + alpn_protocols=alpn_protocols, + verify_mode=verify_mode, + server_name=server_name, + ) + if verify_path is not None: + cafile, capath = dns._tls_util.convert_verify_to_cafile_and_capath( + verify_path + ) + conf.load_verify_locations(cafile=cafile, capath=capath) + self._conf = conf + + def _connect( + self, + address, + port=853, + source=None, + source_port=0, + want_session_ticket=True, + want_token=True, + ): + connection = self._connections.get((address, port)) + if connection is not None: + return (connection, False) + conf = self._conf + if want_session_ticket: + try: + session_ticket = self._session_tickets.pop((address, port)) + # We found a session ticket, so make a configuration that uses it. + conf = copy.copy(conf) + conf.session_ticket = session_ticket + except KeyError: + # No session ticket. + pass + # Whether or not we found a session ticket, we want a handler to save + # one. + session_ticket_handler = functools.partial( + self.save_session_ticket, address, port + ) + else: + session_ticket_handler = None + if want_token: + try: + token = self._tokens.pop((address, port)) + # We found a token, so make a configuration that uses it. + conf = copy.copy(conf) + conf.token = token + except KeyError: + # No token + pass + # Whether or not we found a token, we want a handler to save # one. + token_handler = functools.partial(self.save_token, address, port) + else: + token_handler = None + + qconn = aioquic.quic.connection.QuicConnection( + configuration=conf, + session_ticket_handler=session_ticket_handler, + token_handler=token_handler, + ) + lladdress = dns.inet.low_level_address_tuple((address, port)) + qconn.connect(lladdress, time.time()) + connection = self._connection_factory( + qconn, address, port, source, source_port, self + ) + self._connections[(address, port)] = connection + return (connection, True) + + def closed(self, address, port): + try: + del self._connections[(address, port)] + except KeyError: + pass + + def is_h3(self): + return self._h3 + + def save_session_ticket(self, address, port, ticket): + # We rely on dictionaries keys() being in insertion order here. We + # can't just popitem() as that would be LIFO which is the opposite of + # what we want. + l = len(self._session_tickets) + if l >= MAX_SESSION_TICKETS: + keys_to_delete = list(self._session_tickets.keys())[0:SESSIONS_TO_DELETE] + for key in keys_to_delete: + del self._session_tickets[key] + self._session_tickets[(address, port)] = ticket + + def save_token(self, address, port, token): + # We rely on dictionaries keys() being in insertion order here. We + # can't just popitem() as that would be LIFO which is the opposite of + # what we want. + l = len(self._tokens) + if l >= MAX_SESSION_TICKETS: + keys_to_delete = list(self._tokens.keys())[0:SESSIONS_TO_DELETE] + for key in keys_to_delete: + del self._tokens[key] + self._tokens[(address, port)] = token + + +class AsyncQuicManager(BaseQuicManager): + def connect(self, address, port=853, source=None, source_port=0): + raise NotImplementedError diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/quic/_sync.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/quic/_sync.py new file mode 100644 index 000000000..18f9d05bb --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/quic/_sync.py @@ -0,0 +1,306 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +import selectors +import socket +import ssl +import struct +import threading +import time + +import aioquic.h3.connection # type: ignore +import aioquic.h3.events # type: ignore +import aioquic.quic.configuration # type: ignore +import aioquic.quic.connection # type: ignore +import aioquic.quic.events # type: ignore + +import dns.exception +import dns.inet +from dns.quic._common import ( + QUIC_MAX_DATAGRAM, + BaseQuicConnection, + BaseQuicManager, + BaseQuicStream, + UnexpectedEOF, +) + +# Function used to create a socket. Can be overridden if needed in special +# situations. +socket_factory = socket.socket + + +class SyncQuicStream(BaseQuicStream): + def __init__(self, connection, stream_id): + super().__init__(connection, stream_id) + self._wake_up = threading.Condition() + self._lock = threading.Lock() + + def wait_for(self, amount, expiration): + while True: + timeout = self._timeout_from_expiration(expiration) + with self._lock: + if self._buffer.have(amount): + return + self._expecting = amount + with self._wake_up: + if not self._wake_up.wait(timeout): + raise dns.exception.Timeout + self._expecting = 0 + + def wait_for_end(self, expiration): + while True: + timeout = self._timeout_from_expiration(expiration) + with self._lock: + if self._buffer.seen_end(): + return + with self._wake_up: + if not self._wake_up.wait(timeout): + raise dns.exception.Timeout + + def receive(self, timeout=None): + expiration = self._expiration_from_timeout(timeout) + if self._connection.is_h3(): + self.wait_for_end(expiration) + with self._lock: + return self._buffer.get_all() + else: + self.wait_for(2, expiration) + with self._lock: + (size,) = struct.unpack("!H", self._buffer.get(2)) + self.wait_for(size, expiration) + with self._lock: + return self._buffer.get(size) + + def send(self, datagram, is_end=False): + data = self._encapsulate(datagram) + self._connection.write(self._stream_id, data, is_end) + + def _add_input(self, data, is_end): + if self._common_add_input(data, is_end): + with self._wake_up: + self._wake_up.notify() + + def close(self): + with self._lock: + self._close() + + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + self.close() + with self._wake_up: + self._wake_up.notify() + return False + + +class SyncQuicConnection(BaseQuicConnection): + def __init__(self, connection, address, port, source, source_port, manager): + super().__init__(connection, address, port, source, source_port, manager) + self._socket = socket_factory(self._af, socket.SOCK_DGRAM, 0) + if self._source is not None: + try: + self._socket.bind( + dns.inet.low_level_address_tuple(self._source, self._af) + ) + except Exception: + self._socket.close() + raise + self._socket.connect(self._peer) + (self._send_wakeup, self._receive_wakeup) = socket.socketpair() + self._receive_wakeup.setblocking(False) + self._socket.setblocking(False) + self._handshake_complete = threading.Event() + self._worker_thread = None + self._lock = threading.Lock() + + def _read(self): + count = 0 + while count < 10: + count += 1 + try: + datagram = self._socket.recv(QUIC_MAX_DATAGRAM) + except BlockingIOError: + return + with self._lock: + self._connection.receive_datagram(datagram, self._peer, time.time()) + + def _drain_wakeup(self): + while True: + try: + self._receive_wakeup.recv(32) + except BlockingIOError: + return + + def _worker(self): + try: + with selectors.DefaultSelector() as sel: + sel.register(self._socket, selectors.EVENT_READ, self._read) + sel.register( + self._receive_wakeup, selectors.EVENT_READ, self._drain_wakeup + ) + while not self._done: + (expiration, interval) = self._get_timer_values(False) + items = sel.select(interval) + for key, _ in items: + key.data() + with self._lock: + self._handle_timer(expiration) + self._handle_events() + with self._lock: + datagrams = self._connection.datagrams_to_send(time.time()) + for datagram, _ in datagrams: + try: + self._socket.send(datagram) + except BlockingIOError: + # we let QUIC handle any lossage + pass + except Exception: + # Eat all exceptions as we have no way to pass them back to the + # caller currently. It might be nice to fix this in the future. + pass + finally: + with self._lock: + self._done = True + self._socket.close() + # Ensure anyone waiting for this gets woken up. + self._handshake_complete.set() + + def _handle_events(self): + while True: + with self._lock: + event = self._connection.next_event() + if event is None: + return + if isinstance(event, aioquic.quic.events.StreamDataReceived): + if self.is_h3(): + assert self._h3_conn is not None + h3_events = self._h3_conn.handle_event(event) + for h3_event in h3_events: + if isinstance(h3_event, aioquic.h3.events.HeadersReceived): + with self._lock: + stream = self._streams.get(event.stream_id) + if stream: + if stream._headers is None: + stream._headers = h3_event.headers + elif stream._trailers is None: + stream._trailers = h3_event.headers + if h3_event.stream_ended: + stream._add_input(b"", True) + elif isinstance(h3_event, aioquic.h3.events.DataReceived): + with self._lock: + stream = self._streams.get(event.stream_id) + if stream: + stream._add_input(h3_event.data, h3_event.stream_ended) + else: + with self._lock: + stream = self._streams.get(event.stream_id) + if stream: + stream._add_input(event.data, event.end_stream) + elif isinstance(event, aioquic.quic.events.HandshakeCompleted): + self._handshake_complete.set() + elif isinstance(event, aioquic.quic.events.ConnectionTerminated): + with self._lock: + self._done = True + elif isinstance(event, aioquic.quic.events.StreamReset): + with self._lock: + stream = self._streams.get(event.stream_id) + if stream: + stream._add_input(b"", True) + + def write(self, stream, data, is_end=False): + with self._lock: + self._connection.send_stream_data(stream, data, is_end) + self._send_wakeup.send(b"\x01") + + def send_headers(self, stream_id, headers, is_end=False): + with self._lock: + super().send_headers(stream_id, headers, is_end) + if is_end: + self._send_wakeup.send(b"\x01") + + def send_data(self, stream_id, data, is_end=False): + with self._lock: + super().send_data(stream_id, data, is_end) + if is_end: + self._send_wakeup.send(b"\x01") + + def run(self): + if self._closed: + return + self._worker_thread = threading.Thread(target=self._worker) + self._worker_thread.start() + + def make_stream(self, timeout=None): + if not self._handshake_complete.wait(timeout): + raise dns.exception.Timeout + with self._lock: + if self._done: + raise UnexpectedEOF + stream_id = self._connection.get_next_available_stream_id(False) + stream = SyncQuicStream(self, stream_id) + self._streams[stream_id] = stream + return stream + + def close_stream(self, stream_id): + with self._lock: + super().close_stream(stream_id) + + def close(self): + with self._lock: + if self._closed: + return + if self._manager is not None: + self._manager.closed(self._peer[0], self._peer[1]) + self._closed = True + self._connection.close() + self._send_wakeup.send(b"\x01") + if self._worker_thread is not None: + self._worker_thread.join() + + +class SyncQuicManager(BaseQuicManager): + def __init__( + self, conf=None, verify_mode=ssl.CERT_REQUIRED, server_name=None, h3=False + ): + super().__init__(conf, verify_mode, SyncQuicConnection, server_name, h3) + self._lock = threading.Lock() + + def connect( + self, + address, + port=853, + source=None, + source_port=0, + want_session_ticket=True, + want_token=True, + ): + with self._lock: + (connection, start) = self._connect( + address, port, source, source_port, want_session_ticket, want_token + ) + if start: + connection.run() + return connection + + def closed(self, address, port): + with self._lock: + super().closed(address, port) + + def save_session_ticket(self, address, port, ticket): + with self._lock: + super().save_session_ticket(address, port, ticket) + + def save_token(self, address, port, token): + with self._lock: + super().save_token(address, port, token) + + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + # Copy the iterator into a list as exiting things will mutate the connections + # table. + connections = list(self._connections.values()) + for connection in connections: + connection.close() + return False diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/quic/_trio.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/quic/_trio.py new file mode 100644 index 000000000..046e6aab6 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/quic/_trio.py @@ -0,0 +1,250 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +import socket +import ssl +import struct +import time + +import aioquic.h3.connection # type: ignore +import aioquic.h3.events # type: ignore +import aioquic.quic.configuration # type: ignore +import aioquic.quic.connection # type: ignore +import aioquic.quic.events # type: ignore +import trio + +import dns.exception +import dns.inet +from dns._asyncbackend import NullContext +from dns.quic._common import ( + QUIC_MAX_DATAGRAM, + AsyncQuicConnection, + AsyncQuicManager, + BaseQuicStream, + UnexpectedEOF, +) + + +class TrioQuicStream(BaseQuicStream): + def __init__(self, connection, stream_id): + super().__init__(connection, stream_id) + self._wake_up = trio.Condition() + + async def wait_for(self, amount): + while True: + if self._buffer.have(amount): + return + self._expecting = amount + async with self._wake_up: + await self._wake_up.wait() + self._expecting = 0 + + async def wait_for_end(self): + while True: + if self._buffer.seen_end(): + return + async with self._wake_up: + await self._wake_up.wait() + + async def receive(self, timeout=None): + if timeout is None: + context = NullContext(None) + else: + context = trio.move_on_after(timeout) + with context: + if self._connection.is_h3(): + await self.wait_for_end() + return self._buffer.get_all() + else: + await self.wait_for(2) + (size,) = struct.unpack("!H", self._buffer.get(2)) + await self.wait_for(size) + return self._buffer.get(size) + raise dns.exception.Timeout + + async def send(self, datagram, is_end=False): + data = self._encapsulate(datagram) + await self._connection.write(self._stream_id, data, is_end) + + async def _add_input(self, data, is_end): + if self._common_add_input(data, is_end): + async with self._wake_up: + self._wake_up.notify() + + async def close(self): + self._close() + + # Streams are async context managers + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc_val, exc_tb): + await self.close() + async with self._wake_up: + self._wake_up.notify() + return False + + +class TrioQuicConnection(AsyncQuicConnection): + def __init__(self, connection, address, port, source, source_port, manager=None): + super().__init__(connection, address, port, source, source_port, manager) + self._socket = trio.socket.socket(self._af, socket.SOCK_DGRAM, 0) + self._handshake_complete = trio.Event() + self._run_done = trio.Event() + self._worker_scope = None + self._send_pending = False + + async def _worker(self): + try: + if self._source: + await self._socket.bind( + dns.inet.low_level_address_tuple(self._source, self._af) + ) + await self._socket.connect(self._peer) + while not self._done: + (expiration, interval) = self._get_timer_values(False) + if self._send_pending: + # Do not block forever if sends are pending. Even though we + # have a wake-up mechanism if we've already started the blocking + # read, the possibility of context switching in send means that + # more writes can happen while we have no wake up context, so + # we need self._send_pending to avoid (effectively) a "lost wakeup" + # race. + interval = 0.0 + with trio.CancelScope( + deadline=trio.current_time() + interval # pyright: ignore + ) as self._worker_scope: + datagram = await self._socket.recv(QUIC_MAX_DATAGRAM) + self._connection.receive_datagram(datagram, self._peer, time.time()) + self._worker_scope = None + self._handle_timer(expiration) + await self._handle_events() + # We clear this now, before sending anything, as sending can cause + # context switches that do more sends. We want to know if that + # happens so we don't block a long time on the recv() above. + self._send_pending = False + datagrams = self._connection.datagrams_to_send(time.time()) + for datagram, _ in datagrams: + await self._socket.send(datagram) + finally: + self._done = True + self._socket.close() + self._handshake_complete.set() + + async def _handle_events(self): + count = 0 + while True: + event = self._connection.next_event() + if event is None: + return + if isinstance(event, aioquic.quic.events.StreamDataReceived): + if self.is_h3(): + assert self._h3_conn is not None + h3_events = self._h3_conn.handle_event(event) + for h3_event in h3_events: + if isinstance(h3_event, aioquic.h3.events.HeadersReceived): + stream = self._streams.get(event.stream_id) + if stream: + if stream._headers is None: + stream._headers = h3_event.headers + elif stream._trailers is None: + stream._trailers = h3_event.headers + if h3_event.stream_ended: + await stream._add_input(b"", True) + elif isinstance(h3_event, aioquic.h3.events.DataReceived): + stream = self._streams.get(event.stream_id) + if stream: + await stream._add_input( + h3_event.data, h3_event.stream_ended + ) + else: + stream = self._streams.get(event.stream_id) + if stream: + await stream._add_input(event.data, event.end_stream) + elif isinstance(event, aioquic.quic.events.HandshakeCompleted): + self._handshake_complete.set() + elif isinstance(event, aioquic.quic.events.ConnectionTerminated): + self._done = True + self._socket.close() + elif isinstance(event, aioquic.quic.events.StreamReset): + stream = self._streams.get(event.stream_id) + if stream: + await stream._add_input(b"", True) + count += 1 + if count > 10: + # yield + count = 0 + await trio.sleep(0) + + async def write(self, stream, data, is_end=False): + self._connection.send_stream_data(stream, data, is_end) + self._send_pending = True + if self._worker_scope is not None: + self._worker_scope.cancel() + + async def run(self): + if self._closed: + return + async with trio.open_nursery() as nursery: + nursery.start_soon(self._worker) + self._run_done.set() + + async def make_stream(self, timeout=None): + if timeout is None: + context = NullContext(None) + else: + context = trio.move_on_after(timeout) + with context: + await self._handshake_complete.wait() + if self._done: + raise UnexpectedEOF + stream_id = self._connection.get_next_available_stream_id(False) + stream = TrioQuicStream(self, stream_id) + self._streams[stream_id] = stream + return stream + raise dns.exception.Timeout + + async def close(self): + if not self._closed: + if self._manager is not None: + self._manager.closed(self._peer[0], self._peer[1]) + self._closed = True + self._connection.close() + self._send_pending = True + if self._worker_scope is not None: + self._worker_scope.cancel() + await self._run_done.wait() + + +class TrioQuicManager(AsyncQuicManager): + def __init__( + self, + nursery, + conf=None, + verify_mode=ssl.CERT_REQUIRED, + server_name=None, + h3=False, + ): + super().__init__(conf, verify_mode, TrioQuicConnection, server_name, h3) + self._nursery = nursery + + def connect( + self, address, port=853, source=None, source_port=0, want_session_ticket=True + ): + (connection, start) = self._connect( + address, port, source, source_port, want_session_ticket + ) + if start: + self._nursery.start_soon(connection.run) + return connection + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc_val, exc_tb): + # Copy the iterator into a list as exiting things will mutate the connections + # table. + connections = list(self._connections.values()) + for connection in connections: + await connection.close() + return False diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rcode.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rcode.py new file mode 100644 index 000000000..7bb8467e2 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rcode.py @@ -0,0 +1,168 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +# Copyright (C) 2001-2017 Nominum, Inc. +# +# Permission to use, copy, modify, and distribute this software and its +# documentation for any purpose with or without fee is hereby granted, +# provided that the above copyright notice and this permission notice +# appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +"""DNS Result Codes.""" + +from typing import Tuple, Type + +import dns.enum +import dns.exception + + +class Rcode(dns.enum.IntEnum): + #: No error + NOERROR = 0 + #: Format error + FORMERR = 1 + #: Server failure + SERVFAIL = 2 + #: Name does not exist ("Name Error" in RFC 1025 terminology). + NXDOMAIN = 3 + #: Not implemented + NOTIMP = 4 + #: Refused + REFUSED = 5 + #: Name exists. + YXDOMAIN = 6 + #: RRset exists. + YXRRSET = 7 + #: RRset does not exist. + NXRRSET = 8 + #: Not authoritative. + NOTAUTH = 9 + #: Name not in zone. + NOTZONE = 10 + #: DSO-TYPE Not Implemented + DSOTYPENI = 11 + #: Bad EDNS version. + BADVERS = 16 + #: TSIG Signature Failure + BADSIG = 16 + #: Key not recognized. + BADKEY = 17 + #: Signature out of time window. + BADTIME = 18 + #: Bad TKEY Mode. + BADMODE = 19 + #: Duplicate key name. + BADNAME = 20 + #: Algorithm not supported. + BADALG = 21 + #: Bad Truncation + BADTRUNC = 22 + #: Bad/missing Server Cookie + BADCOOKIE = 23 + + @classmethod + def _maximum(cls): + return 4095 + + @classmethod + def _unknown_exception_class(cls) -> Type[Exception]: + return UnknownRcode + + +class UnknownRcode(dns.exception.DNSException): + """A DNS rcode is unknown.""" + + +def from_text(text: str) -> Rcode: + """Convert text into an rcode. + + *text*, a ``str``, the textual rcode or an integer in textual form. + + Raises ``dns.rcode.UnknownRcode`` if the rcode mnemonic is unknown. + + Returns a ``dns.rcode.Rcode``. + """ + + return Rcode.from_text(text) + + +def from_flags(flags: int, ednsflags: int) -> Rcode: + """Return the rcode value encoded by flags and ednsflags. + + *flags*, an ``int``, the DNS flags field. + + *ednsflags*, an ``int``, the EDNS flags field. + + Raises ``ValueError`` if rcode is < 0 or > 4095 + + Returns a ``dns.rcode.Rcode``. + """ + + value = (flags & 0x000F) | ((ednsflags >> 20) & 0xFF0) + return Rcode.make(value) + + +def to_flags(value: Rcode) -> Tuple[int, int]: + """Return a (flags, ednsflags) tuple which encodes the rcode. + + *value*, a ``dns.rcode.Rcode``, the rcode. + + Raises ``ValueError`` if rcode is < 0 or > 4095. + + Returns an ``(int, int)`` tuple. + """ + + if value < 0 or value > 4095: + raise ValueError("rcode must be >= 0 and <= 4095") + v = value & 0xF + ev = (value & 0xFF0) << 20 + return (v, ev) + + +def to_text(value: Rcode, tsig: bool = False) -> str: + """Convert rcode into text. + + *value*, a ``dns.rcode.Rcode``, the rcode. + + Raises ``ValueError`` if rcode is < 0 or > 4095. + + Returns a ``str``. + """ + + if tsig and value == Rcode.BADVERS: + return "BADSIG" + return Rcode.to_text(value) + + +### BEGIN generated Rcode constants + +NOERROR = Rcode.NOERROR +FORMERR = Rcode.FORMERR +SERVFAIL = Rcode.SERVFAIL +NXDOMAIN = Rcode.NXDOMAIN +NOTIMP = Rcode.NOTIMP +REFUSED = Rcode.REFUSED +YXDOMAIN = Rcode.YXDOMAIN +YXRRSET = Rcode.YXRRSET +NXRRSET = Rcode.NXRRSET +NOTAUTH = Rcode.NOTAUTH +NOTZONE = Rcode.NOTZONE +DSOTYPENI = Rcode.DSOTYPENI +BADVERS = Rcode.BADVERS +BADSIG = Rcode.BADSIG +BADKEY = Rcode.BADKEY +BADTIME = Rcode.BADTIME +BADMODE = Rcode.BADMODE +BADNAME = Rcode.BADNAME +BADALG = Rcode.BADALG +BADTRUNC = Rcode.BADTRUNC +BADCOOKIE = Rcode.BADCOOKIE + +### END generated Rcode constants diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdata.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdata.py new file mode 100644 index 000000000..c4522e683 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdata.py @@ -0,0 +1,935 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +# Copyright (C) 2001-2017 Nominum, Inc. +# +# Permission to use, copy, modify, and distribute this software and its +# documentation for any purpose with or without fee is hereby granted, +# provided that the above copyright notice and this permission notice +# appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +"""DNS rdata.""" + +import base64 +import binascii +import inspect +import io +import ipaddress +import itertools +import random +from importlib import import_module +from typing import Any, Dict, Tuple + +import dns.exception +import dns.immutable +import dns.ipv4 +import dns.ipv6 +import dns.name +import dns.rdataclass +import dns.rdatatype +import dns.tokenizer +import dns.ttl +import dns.wire + +_chunksize = 32 + +# We currently allow comparisons for rdata with relative names for backwards +# compatibility, but in the future we will not, as these kinds of comparisons +# can lead to subtle bugs if code is not carefully written. +# +# This switch allows the future behavior to be turned on so code can be +# tested with it. +_allow_relative_comparisons = True + + +class NoRelativeRdataOrdering(dns.exception.DNSException): + """An attempt was made to do an ordered comparison of one or more + rdata with relative names. The only reliable way of sorting rdata + is to use non-relativized rdata. + + """ + + +def _wordbreak(data, chunksize=_chunksize, separator=b" "): + """Break a binary string into chunks of chunksize characters separated by + a space. + """ + + if not chunksize: + return data.decode() + return separator.join( + [data[i : i + chunksize] for i in range(0, len(data), chunksize)] + ).decode() + + +# pylint: disable=unused-argument + + +def _hexify(data, chunksize=_chunksize, separator=b" ", **kw): + """Convert a binary string into its hex encoding, broken up into chunks + of chunksize characters separated by a separator. + """ + + return _wordbreak(binascii.hexlify(data), chunksize, separator) + + +def _base64ify(data, chunksize=_chunksize, separator=b" ", **kw): + """Convert a binary string into its base64 encoding, broken up into chunks + of chunksize characters separated by a separator. + """ + + return _wordbreak(base64.b64encode(data), chunksize, separator) + + +# pylint: enable=unused-argument + +__escaped = b'"\\' + + +def _escapify(qstring): + """Escape the characters in a quoted string which need it.""" + + if isinstance(qstring, str): + qstring = qstring.encode() + if not isinstance(qstring, bytearray): + qstring = bytearray(qstring) + + text = "" + for c in qstring: + if c in __escaped: + text += "\\" + chr(c) + elif c >= 0x20 and c < 0x7F: + text += chr(c) + else: + text += f"\\{c:03d}" + return text + + +def _truncate_bitmap(what): + """Determine the index of greatest byte that isn't all zeros, and + return the bitmap that contains all the bytes less than that index. + """ + + for i in range(len(what) - 1, -1, -1): + if what[i] != 0: + return what[0 : i + 1] + return what[0:1] + + +# So we don't have to edit all the rdata classes... +_constify = dns.immutable.constify + + +@dns.immutable.immutable +class Rdata: + """Base class for all DNS rdata types.""" + + __slots__ = ["rdclass", "rdtype", "rdcomment"] + + def __init__( + self, + rdclass: dns.rdataclass.RdataClass, + rdtype: dns.rdatatype.RdataType, + ) -> None: + """Initialize an rdata. + + *rdclass*, an ``int`` is the rdataclass of the Rdata. + + *rdtype*, an ``int`` is the rdatatype of the Rdata. + """ + + self.rdclass = self._as_rdataclass(rdclass) + self.rdtype = self._as_rdatatype(rdtype) + self.rdcomment = None + + def _get_all_slots(self): + return itertools.chain.from_iterable( + getattr(cls, "__slots__", []) for cls in self.__class__.__mro__ + ) + + def __getstate__(self): + # We used to try to do a tuple of all slots here, but it + # doesn't work as self._all_slots isn't available at + # __setstate__() time. Before that we tried to store a tuple + # of __slots__, but that didn't work as it didn't store the + # slots defined by ancestors. This older way didn't fail + # outright, but ended up with partially broken objects, e.g. + # if you unpickled an A RR it wouldn't have rdclass and rdtype + # attributes, and would compare badly. + state = {} + for slot in self._get_all_slots(): + state[slot] = getattr(self, slot) + return state + + def __setstate__(self, state): + for slot, val in state.items(): + object.__setattr__(self, slot, val) + if not hasattr(self, "rdcomment"): + # Pickled rdata from 2.0.x might not have a rdcomment, so add + # it if needed. + object.__setattr__(self, "rdcomment", None) + + def covers(self) -> dns.rdatatype.RdataType: + """Return the type a Rdata covers. + + DNS SIG/RRSIG rdatas apply to a specific type; this type is + returned by the covers() function. If the rdata type is not + SIG or RRSIG, dns.rdatatype.NONE is returned. This is useful when + creating rdatasets, allowing the rdataset to contain only RRSIGs + of a particular type, e.g. RRSIG(NS). + + Returns a ``dns.rdatatype.RdataType``. + """ + + return dns.rdatatype.NONE + + def extended_rdatatype(self) -> int: + """Return a 32-bit type value, the least significant 16 bits of + which are the ordinary DNS type, and the upper 16 bits of which are + the "covered" type, if any. + + Returns an ``int``. + """ + + return self.covers() << 16 | self.rdtype + + def to_text( + self, + origin: dns.name.Name | None = None, + relativize: bool = True, + **kw: Dict[str, Any], + ) -> str: + """Convert an rdata to text format. + + Returns a ``str``. + """ + + raise NotImplementedError # pragma: no cover + + def _to_wire( + self, + file: Any, + compress: dns.name.CompressType | None = None, + origin: dns.name.Name | None = None, + canonicalize: bool = False, + ) -> None: + raise NotImplementedError # pragma: no cover + + def to_wire( + self, + file: Any | None = None, + compress: dns.name.CompressType | None = None, + origin: dns.name.Name | None = None, + canonicalize: bool = False, + ) -> bytes | None: + """Convert an rdata to wire format. + + Returns a ``bytes`` if no output file was specified, or ``None`` otherwise. + """ + + if file: + # We call _to_wire() and then return None explicitly instead of + # of just returning the None from _to_wire() as mypy's func-returns-value + # unhelpfully errors out with "error: "_to_wire" of "Rdata" does not return + # a value (it only ever returns None)" + self._to_wire(file, compress, origin, canonicalize) + return None + else: + f = io.BytesIO() + self._to_wire(f, compress, origin, canonicalize) + return f.getvalue() + + def to_generic(self, origin: dns.name.Name | None = None) -> "GenericRdata": + """Creates a dns.rdata.GenericRdata equivalent of this rdata. + + Returns a ``dns.rdata.GenericRdata``. + """ + wire = self.to_wire(origin=origin) + assert wire is not None # for type checkers + return GenericRdata(self.rdclass, self.rdtype, wire) + + def to_digestable(self, origin: dns.name.Name | None = None) -> bytes: + """Convert rdata to a format suitable for digesting in hashes. This + is also the DNSSEC canonical form. + + Returns a ``bytes``. + """ + wire = self.to_wire(origin=origin, canonicalize=True) + assert wire is not None # for mypy + return wire + + def __repr__(self): + covers = self.covers() + if covers == dns.rdatatype.NONE: + ctext = "" + else: + ctext = "(" + dns.rdatatype.to_text(covers) + ")" + return ( + "" + ) + + def __str__(self): + return self.to_text() + + def _cmp(self, other): + """Compare an rdata with another rdata of the same rdtype and + rdclass. + + For rdata with only absolute names: + Return < 0 if self < other in the DNSSEC ordering, 0 if self + == other, and > 0 if self > other. + For rdata with at least one relative names: + The rdata sorts before any rdata with only absolute names. + When compared with another relative rdata, all names are + made absolute as if they were relative to the root, as the + proper origin is not available. While this creates a stable + ordering, it is NOT guaranteed to be the DNSSEC ordering. + In the future, all ordering comparisons for rdata with + relative names will be disallowed. + """ + # the next two lines are for type checkers, so they are bound + our = b"" + their = b"" + try: + our = self.to_digestable() + our_relative = False + except dns.name.NeedAbsoluteNameOrOrigin: + if _allow_relative_comparisons: + our = self.to_digestable(dns.name.root) + our_relative = True + try: + their = other.to_digestable() + their_relative = False + except dns.name.NeedAbsoluteNameOrOrigin: + if _allow_relative_comparisons: + their = other.to_digestable(dns.name.root) + their_relative = True + if _allow_relative_comparisons: + if our_relative != their_relative: + # For the purpose of comparison, all rdata with at least one + # relative name is less than an rdata with only absolute names. + if our_relative: + return -1 + else: + return 1 + elif our_relative or their_relative: + raise NoRelativeRdataOrdering + if our == their: + return 0 + elif our > their: + return 1 + else: + return -1 + + def __eq__(self, other): + if not isinstance(other, Rdata): + return False + if self.rdclass != other.rdclass or self.rdtype != other.rdtype: + return False + our_relative = False + their_relative = False + try: + our = self.to_digestable() + except dns.name.NeedAbsoluteNameOrOrigin: + our = self.to_digestable(dns.name.root) + our_relative = True + try: + their = other.to_digestable() + except dns.name.NeedAbsoluteNameOrOrigin: + their = other.to_digestable(dns.name.root) + their_relative = True + if our_relative != their_relative: + return False + return our == their + + def __ne__(self, other): + if not isinstance(other, Rdata): + return True + if self.rdclass != other.rdclass or self.rdtype != other.rdtype: + return True + return not self.__eq__(other) + + def __lt__(self, other): + if ( + not isinstance(other, Rdata) + or self.rdclass != other.rdclass + or self.rdtype != other.rdtype + ): + return NotImplemented + return self._cmp(other) < 0 + + def __le__(self, other): + if ( + not isinstance(other, Rdata) + or self.rdclass != other.rdclass + or self.rdtype != other.rdtype + ): + return NotImplemented + return self._cmp(other) <= 0 + + def __ge__(self, other): + if ( + not isinstance(other, Rdata) + or self.rdclass != other.rdclass + or self.rdtype != other.rdtype + ): + return NotImplemented + return self._cmp(other) >= 0 + + def __gt__(self, other): + if ( + not isinstance(other, Rdata) + or self.rdclass != other.rdclass + or self.rdtype != other.rdtype + ): + return NotImplemented + return self._cmp(other) > 0 + + def __hash__(self): + return hash(self.to_digestable(dns.name.root)) + + @classmethod + def from_text( + cls, + rdclass: dns.rdataclass.RdataClass, + rdtype: dns.rdatatype.RdataType, + tok: dns.tokenizer.Tokenizer, + origin: dns.name.Name | None = None, + relativize: bool = True, + relativize_to: dns.name.Name | None = None, + ) -> "Rdata": + raise NotImplementedError # pragma: no cover + + @classmethod + def from_wire_parser( + cls, + rdclass: dns.rdataclass.RdataClass, + rdtype: dns.rdatatype.RdataType, + parser: dns.wire.Parser, + origin: dns.name.Name | None = None, + ) -> "Rdata": + raise NotImplementedError # pragma: no cover + + def replace(self, **kwargs: Any) -> "Rdata": + """ + Create a new Rdata instance based on the instance replace was + invoked on. It is possible to pass different parameters to + override the corresponding properties of the base Rdata. + + Any field specific to the Rdata type can be replaced, but the + *rdtype* and *rdclass* fields cannot. + + Returns an instance of the same Rdata subclass as *self*. + """ + + # Get the constructor parameters. + parameters = inspect.signature(self.__init__).parameters # type: ignore + + # Ensure that all of the arguments correspond to valid fields. + # Don't allow rdclass or rdtype to be changed, though. + for key in kwargs: + if key == "rdcomment": + continue + if key not in parameters: + raise AttributeError( + f"'{self.__class__.__name__}' object has no attribute '{key}'" + ) + if key in ("rdclass", "rdtype"): + raise AttributeError( + f"Cannot overwrite '{self.__class__.__name__}' attribute '{key}'" + ) + + # Construct the parameter list. For each field, use the value in + # kwargs if present, and the current value otherwise. + args = (kwargs.get(key, getattr(self, key)) for key in parameters) + + # Create, validate, and return the new object. + rd = self.__class__(*args) + # The comment is not set in the constructor, so give it special + # handling. + rdcomment = kwargs.get("rdcomment", self.rdcomment) + if rdcomment is not None: + object.__setattr__(rd, "rdcomment", rdcomment) + return rd + + # Type checking and conversion helpers. These are class methods as + # they don't touch object state and may be useful to others. + + @classmethod + def _as_rdataclass(cls, value): + return dns.rdataclass.RdataClass.make(value) + + @classmethod + def _as_rdatatype(cls, value): + return dns.rdatatype.RdataType.make(value) + + @classmethod + def _as_bytes( + cls, + value: Any, + encode: bool = False, + max_length: int | None = None, + empty_ok: bool = True, + ) -> bytes: + if encode and isinstance(value, str): + bvalue = value.encode() + elif isinstance(value, bytearray): + bvalue = bytes(value) + elif isinstance(value, bytes): + bvalue = value + else: + raise ValueError("not bytes") + if max_length is not None and len(bvalue) > max_length: + raise ValueError("too long") + if not empty_ok and len(bvalue) == 0: + raise ValueError("empty bytes not allowed") + return bvalue + + @classmethod + def _as_name(cls, value): + # Note that proper name conversion (e.g. with origin and IDNA + # awareness) is expected to be done via from_text. This is just + # a simple thing for people invoking the constructor directly. + if isinstance(value, str): + return dns.name.from_text(value) + elif not isinstance(value, dns.name.Name): + raise ValueError("not a name") + return value + + @classmethod + def _as_uint8(cls, value): + if not isinstance(value, int): + raise ValueError("not an integer") + if value < 0 or value > 255: + raise ValueError("not a uint8") + return value + + @classmethod + def _as_uint16(cls, value): + if not isinstance(value, int): + raise ValueError("not an integer") + if value < 0 or value > 65535: + raise ValueError("not a uint16") + return value + + @classmethod + def _as_uint32(cls, value): + if not isinstance(value, int): + raise ValueError("not an integer") + if value < 0 or value > 4294967295: + raise ValueError("not a uint32") + return value + + @classmethod + def _as_uint48(cls, value): + if not isinstance(value, int): + raise ValueError("not an integer") + if value < 0 or value > 281474976710655: + raise ValueError("not a uint48") + return value + + @classmethod + def _as_int(cls, value, low=None, high=None): + if not isinstance(value, int): + raise ValueError("not an integer") + if low is not None and value < low: + raise ValueError("value too small") + if high is not None and value > high: + raise ValueError("value too large") + return value + + @classmethod + def _as_ipv4_address(cls, value): + if isinstance(value, str): + return dns.ipv4.canonicalize(value) + elif isinstance(value, bytes): + return dns.ipv4.inet_ntoa(value) + elif isinstance(value, ipaddress.IPv4Address): + return dns.ipv4.inet_ntoa(value.packed) + else: + raise ValueError("not an IPv4 address") + + @classmethod + def _as_ipv6_address(cls, value): + if isinstance(value, str): + return dns.ipv6.canonicalize(value) + elif isinstance(value, bytes): + return dns.ipv6.inet_ntoa(value) + elif isinstance(value, ipaddress.IPv6Address): + return dns.ipv6.inet_ntoa(value.packed) + else: + raise ValueError("not an IPv6 address") + + @classmethod + def _as_bool(cls, value): + if isinstance(value, bool): + return value + else: + raise ValueError("not a boolean") + + @classmethod + def _as_ttl(cls, value): + if isinstance(value, int): + return cls._as_int(value, 0, dns.ttl.MAX_TTL) + elif isinstance(value, str): + return dns.ttl.from_text(value) + else: + raise ValueError("not a TTL") + + @classmethod + def _as_tuple(cls, value, as_value): + try: + # For user convenience, if value is a singleton of the list + # element type, wrap it in a tuple. + return (as_value(value),) + except Exception: + # Otherwise, check each element of the iterable *value* + # against *as_value*. + return tuple(as_value(v) for v in value) + + # Processing order + + @classmethod + def _processing_order(cls, iterable): + items = list(iterable) + random.shuffle(items) + return items + + +@dns.immutable.immutable +class GenericRdata(Rdata): + """Generic Rdata Class + + This class is used for rdata types for which we have no better + implementation. It implements the DNS "unknown RRs" scheme. + """ + + __slots__ = ["data"] + + def __init__( + self, + rdclass: dns.rdataclass.RdataClass, + rdtype: dns.rdatatype.RdataType, + data: bytes, + ) -> None: + super().__init__(rdclass, rdtype) + self.data = data + + def to_text( + self, + origin: dns.name.Name | None = None, + relativize: bool = True, + **kw: Dict[str, Any], + ) -> str: + return rf"\# {len(self.data)} " + _hexify(self.data, **kw) # pyright: ignore + + @classmethod + def from_text( + cls, rdclass, rdtype, tok, origin=None, relativize=True, relativize_to=None + ): + token = tok.get() + if not token.is_identifier() or token.value != r"\#": + raise dns.exception.SyntaxError(r"generic rdata does not start with \#") + length = tok.get_int() + hex = tok.concatenate_remaining_identifiers(True).encode() + data = binascii.unhexlify(hex) + if len(data) != length: + raise dns.exception.SyntaxError("generic rdata hex data has wrong length") + return cls(rdclass, rdtype, data) + + def _to_wire(self, file, compress=None, origin=None, canonicalize=False): + file.write(self.data) + + def to_generic(self, origin: dns.name.Name | None = None) -> "GenericRdata": + return self + + @classmethod + def from_wire_parser(cls, rdclass, rdtype, parser, origin=None): + return cls(rdclass, rdtype, parser.get_remaining()) + + +_rdata_classes: Dict[Tuple[dns.rdataclass.RdataClass, dns.rdatatype.RdataType], Any] = ( + {} +) +_module_prefix = "dns.rdtypes" +_dynamic_load_allowed = True + + +def get_rdata_class(rdclass, rdtype, use_generic=True): + cls = _rdata_classes.get((rdclass, rdtype)) + if not cls: + cls = _rdata_classes.get((dns.rdataclass.ANY, rdtype)) + if not cls and _dynamic_load_allowed: + rdclass_text = dns.rdataclass.to_text(rdclass) + rdtype_text = dns.rdatatype.to_text(rdtype) + rdtype_text = rdtype_text.replace("-", "_") + try: + mod = import_module( + ".".join([_module_prefix, rdclass_text, rdtype_text]) + ) + cls = getattr(mod, rdtype_text) + _rdata_classes[(rdclass, rdtype)] = cls + except ImportError: + try: + mod = import_module(".".join([_module_prefix, "ANY", rdtype_text])) + cls = getattr(mod, rdtype_text) + _rdata_classes[(dns.rdataclass.ANY, rdtype)] = cls + _rdata_classes[(rdclass, rdtype)] = cls + except ImportError: + pass + if not cls and use_generic: + cls = GenericRdata + _rdata_classes[(rdclass, rdtype)] = cls + return cls + + +def load_all_types(disable_dynamic_load=True): + """Load all rdata types for which dnspython has a non-generic implementation. + + Normally dnspython loads DNS rdatatype implementations on demand, but in some + specialized cases loading all types at an application-controlled time is preferred. + + If *disable_dynamic_load*, a ``bool``, is ``True`` then dnspython will not attempt + to use its dynamic loading mechanism if an unknown type is subsequently encountered, + and will simply use the ``GenericRdata`` class. + """ + # Load class IN and ANY types. + for rdtype in dns.rdatatype.RdataType: + get_rdata_class(dns.rdataclass.IN, rdtype, False) + # Load the one non-ANY implementation we have in CH. Everything + # else in CH is an ANY type, and we'll discover those on demand but won't + # have to import anything. + get_rdata_class(dns.rdataclass.CH, dns.rdatatype.A, False) + if disable_dynamic_load: + # Now disable dynamic loading so any subsequent unknown type immediately becomes + # GenericRdata without a load attempt. + global _dynamic_load_allowed + _dynamic_load_allowed = False + + +def from_text( + rdclass: dns.rdataclass.RdataClass | str, + rdtype: dns.rdatatype.RdataType | str, + tok: dns.tokenizer.Tokenizer | str, + origin: dns.name.Name | None = None, + relativize: bool = True, + relativize_to: dns.name.Name | None = None, + idna_codec: dns.name.IDNACodec | None = None, +) -> Rdata: + """Build an rdata object from text format. + + This function attempts to dynamically load a class which + implements the specified rdata class and type. If there is no + class-and-type-specific implementation, the GenericRdata class + is used. + + Once a class is chosen, its from_text() class method is called + with the parameters to this function. + + If *tok* is a ``str``, then a tokenizer is created and the string + is used as its input. + + *rdclass*, a ``dns.rdataclass.RdataClass`` or ``str``, the rdataclass. + + *rdtype*, a ``dns.rdatatype.RdataType`` or ``str``, the rdatatype. + + *tok*, a ``dns.tokenizer.Tokenizer`` or a ``str``. + + *origin*, a ``dns.name.Name`` (or ``None``), the + origin to use for relative names. + + *relativize*, a ``bool``. If true, name will be relativized. + + *relativize_to*, a ``dns.name.Name`` (or ``None``), the origin to use + when relativizing names. If not set, the *origin* value will be used. + + *idna_codec*, a ``dns.name.IDNACodec``, specifies the IDNA + encoder/decoder to use if a tokenizer needs to be created. If + ``None``, the default IDNA 2003 encoder/decoder is used. If a + tokenizer is not created, then the codec associated with the tokenizer + is the one that is used. + + Returns an instance of the chosen Rdata subclass. + + """ + if isinstance(tok, str): + tok = dns.tokenizer.Tokenizer(tok, idna_codec=idna_codec) + if not isinstance(tok, dns.tokenizer.Tokenizer): + raise ValueError("tok must be a string or a Tokenizer") + rdclass = dns.rdataclass.RdataClass.make(rdclass) + rdtype = dns.rdatatype.RdataType.make(rdtype) + cls = get_rdata_class(rdclass, rdtype) + assert cls is not None # for type checkers + with dns.exception.ExceptionWrapper(dns.exception.SyntaxError): + rdata = None + if cls != GenericRdata: + # peek at first token + token = tok.get() + tok.unget(token) + if token.is_identifier() and token.value == r"\#": + # + # Known type using the generic syntax. Extract the + # wire form from the generic syntax, and then run + # from_wire on it. + # + grdata = GenericRdata.from_text( + rdclass, rdtype, tok, origin, relativize, relativize_to + ) + rdata = from_wire( + rdclass, rdtype, grdata.data, 0, len(grdata.data), origin + ) + # + # If this comparison isn't equal, then there must have been + # compressed names in the wire format, which is an error, + # there being no reasonable context to decompress with. + # + rwire = rdata.to_wire() + if rwire != grdata.data: + raise dns.exception.SyntaxError( + "compressed data in " + "generic syntax form " + "of known rdatatype" + ) + if rdata is None: + rdata = cls.from_text( + rdclass, rdtype, tok, origin, relativize, relativize_to + ) + token = tok.get_eol_as_token() + if token.comment is not None: + object.__setattr__(rdata, "rdcomment", token.comment) + return rdata + + +def from_wire_parser( + rdclass: dns.rdataclass.RdataClass | str, + rdtype: dns.rdatatype.RdataType | str, + parser: dns.wire.Parser, + origin: dns.name.Name | None = None, +) -> Rdata: + """Build an rdata object from wire format + + This function attempts to dynamically load a class which + implements the specified rdata class and type. If there is no + class-and-type-specific implementation, the GenericRdata class + is used. + + Once a class is chosen, its from_wire() class method is called + with the parameters to this function. + + *rdclass*, a ``dns.rdataclass.RdataClass`` or ``str``, the rdataclass. + + *rdtype*, a ``dns.rdatatype.RdataType`` or ``str``, the rdatatype. + + *parser*, a ``dns.wire.Parser``, the parser, which should be + restricted to the rdata length. + + *origin*, a ``dns.name.Name`` (or ``None``). If not ``None``, + then names will be relativized to this origin. + + Returns an instance of the chosen Rdata subclass. + """ + + rdclass = dns.rdataclass.RdataClass.make(rdclass) + rdtype = dns.rdatatype.RdataType.make(rdtype) + cls = get_rdata_class(rdclass, rdtype) + assert cls is not None # for type checkers + with dns.exception.ExceptionWrapper(dns.exception.FormError): + return cls.from_wire_parser(rdclass, rdtype, parser, origin) + + +def from_wire( + rdclass: dns.rdataclass.RdataClass | str, + rdtype: dns.rdatatype.RdataType | str, + wire: bytes, + current: int, + rdlen: int, + origin: dns.name.Name | None = None, +) -> Rdata: + """Build an rdata object from wire format + + This function attempts to dynamically load a class which + implements the specified rdata class and type. If there is no + class-and-type-specific implementation, the GenericRdata class + is used. + + Once a class is chosen, its from_wire() class method is called + with the parameters to this function. + + *rdclass*, an ``int``, the rdataclass. + + *rdtype*, an ``int``, the rdatatype. + + *wire*, a ``bytes``, the wire-format message. + + *current*, an ``int``, the offset in wire of the beginning of + the rdata. + + *rdlen*, an ``int``, the length of the wire-format rdata + + *origin*, a ``dns.name.Name`` (or ``None``). If not ``None``, + then names will be relativized to this origin. + + Returns an instance of the chosen Rdata subclass. + """ + parser = dns.wire.Parser(wire, current) + with parser.restrict_to(rdlen): + return from_wire_parser(rdclass, rdtype, parser, origin) + + +class RdatatypeExists(dns.exception.DNSException): + """DNS rdatatype already exists.""" + + supp_kwargs = {"rdclass", "rdtype"} + fmt = ( + "The rdata type with class {rdclass:d} and rdtype {rdtype:d} " + + "already exists." + ) + + +def register_type( + implementation: Any, + rdtype: int, + rdtype_text: str, + is_singleton: bool = False, + rdclass: dns.rdataclass.RdataClass = dns.rdataclass.IN, +) -> None: + """Dynamically register a module to handle an rdatatype. + + *implementation*, a subclass of ``dns.rdata.Rdata`` implementing the type, + or a module containing such a class named by its text form. + + *rdtype*, an ``int``, the rdatatype to register. + + *rdtype_text*, a ``str``, the textual form of the rdatatype. + + *is_singleton*, a ``bool``, indicating if the type is a singleton (i.e. + RRsets of the type can have only one member.) + + *rdclass*, the rdataclass of the type, or ``dns.rdataclass.ANY`` if + it applies to all classes. + """ + + rdtype = dns.rdatatype.RdataType.make(rdtype) + existing_cls = get_rdata_class(rdclass, rdtype) + if existing_cls != GenericRdata or dns.rdatatype.is_metatype(rdtype): + raise RdatatypeExists(rdclass=rdclass, rdtype=rdtype) + if isinstance(implementation, type) and issubclass(implementation, Rdata): + impclass = implementation + else: + impclass = getattr(implementation, rdtype_text.replace("-", "_")) + _rdata_classes[(rdclass, rdtype)] = impclass + dns.rdatatype.register_type(rdtype, rdtype_text, is_singleton) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdataclass.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdataclass.py new file mode 100644 index 000000000..89b85a79c --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdataclass.py @@ -0,0 +1,118 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +# Copyright (C) 2001-2017 Nominum, Inc. +# +# Permission to use, copy, modify, and distribute this software and its +# documentation for any purpose with or without fee is hereby granted, +# provided that the above copyright notice and this permission notice +# appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +"""DNS Rdata Classes.""" + +import dns.enum +import dns.exception + + +class RdataClass(dns.enum.IntEnum): + """DNS Rdata Class""" + + RESERVED0 = 0 + IN = 1 + INTERNET = IN + CH = 3 + CHAOS = CH + HS = 4 + HESIOD = HS + NONE = 254 + ANY = 255 + + @classmethod + def _maximum(cls): + return 65535 + + @classmethod + def _short_name(cls): + return "class" + + @classmethod + def _prefix(cls): + return "CLASS" + + @classmethod + def _unknown_exception_class(cls): + return UnknownRdataclass + + +_metaclasses = {RdataClass.NONE, RdataClass.ANY} + + +class UnknownRdataclass(dns.exception.DNSException): + """A DNS class is unknown.""" + + +def from_text(text: str) -> RdataClass: + """Convert text into a DNS rdata class value. + + The input text can be a defined DNS RR class mnemonic or + instance of the DNS generic class syntax. + + For example, "IN" and "CLASS1" will both result in a value of 1. + + Raises ``dns.rdatatype.UnknownRdataclass`` if the class is unknown. + + Raises ``ValueError`` if the rdata class value is not >= 0 and <= 65535. + + Returns a ``dns.rdataclass.RdataClass``. + """ + + return RdataClass.from_text(text) + + +def to_text(value: RdataClass) -> str: + """Convert a DNS rdata class value to text. + + If the value has a known mnemonic, it will be used, otherwise the + DNS generic class syntax will be used. + + Raises ``ValueError`` if the rdata class value is not >= 0 and <= 65535. + + Returns a ``str``. + """ + + return RdataClass.to_text(value) + + +def is_metaclass(rdclass: RdataClass) -> bool: + """True if the specified class is a metaclass. + + The currently defined metaclasses are ANY and NONE. + + *rdclass* is a ``dns.rdataclass.RdataClass``. + """ + + if rdclass in _metaclasses: + return True + return False + + +### BEGIN generated RdataClass constants + +RESERVED0 = RdataClass.RESERVED0 +IN = RdataClass.IN +INTERNET = RdataClass.INTERNET +CH = RdataClass.CH +CHAOS = RdataClass.CHAOS +HS = RdataClass.HS +HESIOD = RdataClass.HESIOD +NONE = RdataClass.NONE +ANY = RdataClass.ANY + +### END generated RdataClass constants diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdataset.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdataset.py new file mode 100644 index 000000000..1edf67d74 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdataset.py @@ -0,0 +1,508 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +# Copyright (C) 2001-2017 Nominum, Inc. +# +# Permission to use, copy, modify, and distribute this software and its +# documentation for any purpose with or without fee is hereby granted, +# provided that the above copyright notice and this permission notice +# appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +"""DNS rdatasets (an rdataset is a set of rdatas of a given type and class)""" + +import io +import random +import struct +from typing import Any, Collection, Dict, List, cast + +import dns.exception +import dns.immutable +import dns.name +import dns.rdata +import dns.rdataclass +import dns.rdatatype +import dns.renderer +import dns.set +import dns.ttl + +# define SimpleSet here for backwards compatibility +SimpleSet = dns.set.Set + + +class DifferingCovers(dns.exception.DNSException): + """An attempt was made to add a DNS SIG/RRSIG whose covered type + is not the same as that of the other rdatas in the rdataset.""" + + +class IncompatibleTypes(dns.exception.DNSException): + """An attempt was made to add DNS RR data of an incompatible type.""" + + +class Rdataset(dns.set.Set): + """A DNS rdataset.""" + + __slots__ = ["rdclass", "rdtype", "covers", "ttl"] + + def __init__( + self, + rdclass: dns.rdataclass.RdataClass, + rdtype: dns.rdatatype.RdataType, + covers: dns.rdatatype.RdataType = dns.rdatatype.NONE, + ttl: int = 0, + ): + """Create a new rdataset of the specified class and type. + + *rdclass*, a ``dns.rdataclass.RdataClass``, the rdataclass. + + *rdtype*, an ``dns.rdatatype.RdataType``, the rdatatype. + + *covers*, an ``dns.rdatatype.RdataType``, the covered rdatatype. + + *ttl*, an ``int``, the TTL. + """ + + super().__init__() + self.rdclass = rdclass + self.rdtype: dns.rdatatype.RdataType = rdtype + self.covers: dns.rdatatype.RdataType = covers + self.ttl = ttl + + def _clone(self): + obj = cast(Rdataset, super()._clone()) + obj.rdclass = self.rdclass + obj.rdtype = self.rdtype + obj.covers = self.covers + obj.ttl = self.ttl + return obj + + def update_ttl(self, ttl: int) -> None: + """Perform TTL minimization. + + Set the TTL of the rdataset to be the lesser of the set's current + TTL or the specified TTL. If the set contains no rdatas, set the TTL + to the specified TTL. + + *ttl*, an ``int`` or ``str``. + """ + ttl = dns.ttl.make(ttl) + if len(self) == 0: + self.ttl = ttl + elif ttl < self.ttl: + self.ttl = ttl + + # pylint: disable=arguments-differ,arguments-renamed + def add( # pyright: ignore + self, rd: dns.rdata.Rdata, ttl: int | None = None + ) -> None: + """Add the specified rdata to the rdataset. + + If the optional *ttl* parameter is supplied, then + ``self.update_ttl(ttl)`` will be called prior to adding the rdata. + + *rd*, a ``dns.rdata.Rdata``, the rdata + + *ttl*, an ``int``, the TTL. + + Raises ``dns.rdataset.IncompatibleTypes`` if the type and class + do not match the type and class of the rdataset. + + Raises ``dns.rdataset.DifferingCovers`` if the type is a signature + type and the covered type does not match that of the rdataset. + """ + + # + # If we're adding a signature, do some special handling to + # check that the signature covers the same type as the + # other rdatas in this rdataset. If this is the first rdata + # in the set, initialize the covers field. + # + if self.rdclass != rd.rdclass or self.rdtype != rd.rdtype: + raise IncompatibleTypes + if ttl is not None: + self.update_ttl(ttl) + if self.rdtype == dns.rdatatype.RRSIG or self.rdtype == dns.rdatatype.SIG: + covers = rd.covers() + if len(self) == 0 and self.covers == dns.rdatatype.NONE: + self.covers = covers + elif self.covers != covers: + raise DifferingCovers + if dns.rdatatype.is_singleton(rd.rdtype) and len(self) > 0: + self.clear() + super().add(rd) + + def union_update(self, other): + self.update_ttl(other.ttl) + super().union_update(other) + + def intersection_update(self, other): + self.update_ttl(other.ttl) + super().intersection_update(other) + + def update(self, other): + """Add all rdatas in other to self. + + *other*, a ``dns.rdataset.Rdataset``, the rdataset from which + to update. + """ + + self.update_ttl(other.ttl) + super().update(other) + + def _rdata_repr(self): + def maybe_truncate(s): + if len(s) > 100: + return s[:100] + "..." + return s + + return "[" + ", ".join(f"<{maybe_truncate(str(rr))}>" for rr in self) + "]" + + def __repr__(self): + if self.covers == 0: + ctext = "" + else: + ctext = "(" + dns.rdatatype.to_text(self.covers) + ")" + return ( + "" + ) + + def __str__(self): + return self.to_text() + + def __eq__(self, other): + if not isinstance(other, Rdataset): + return False + if ( + self.rdclass != other.rdclass + or self.rdtype != other.rdtype + or self.covers != other.covers + ): + return False + return super().__eq__(other) + + def __ne__(self, other): + return not self.__eq__(other) + + def to_text( + self, + name: dns.name.Name | None = None, + origin: dns.name.Name | None = None, + relativize: bool = True, + override_rdclass: dns.rdataclass.RdataClass | None = None, + want_comments: bool = False, + **kw: Dict[str, Any], + ) -> str: + """Convert the rdataset into DNS zone file format. + + See ``dns.name.Name.choose_relativity`` for more information + on how *origin* and *relativize* determine the way names + are emitted. + + Any additional keyword arguments are passed on to the rdata + ``to_text()`` method. + + *name*, a ``dns.name.Name``. If name is not ``None``, emit RRs with + *name* as the owner name. + + *origin*, a ``dns.name.Name`` or ``None``, the origin for relative + names. + + *relativize*, a ``bool``. If ``True``, names will be relativized + to *origin*. + + *override_rdclass*, a ``dns.rdataclass.RdataClass`` or ``None``. + If not ``None``, use this class instead of the Rdataset's class. + + *want_comments*, a ``bool``. If ``True``, emit comments for rdata + which have them. The default is ``False``. + """ + + if name is not None: + name = name.choose_relativity(origin, relativize) + ntext = str(name) + pad = " " + else: + ntext = "" + pad = "" + s = io.StringIO() + if override_rdclass is not None: + rdclass = override_rdclass + else: + rdclass = self.rdclass + if len(self) == 0: + # + # Empty rdatasets are used for the question section, and in + # some dynamic updates, so we don't need to print out the TTL + # (which is meaningless anyway). + # + s.write( + f"{ntext}{pad}{dns.rdataclass.to_text(rdclass)} " + f"{dns.rdatatype.to_text(self.rdtype)}\n" + ) + else: + for rd in self: + extra = "" + if want_comments: + if rd.rdcomment: + extra = f" ;{rd.rdcomment}" + s.write( + f"{ntext}{pad}{self.ttl} " + f"{dns.rdataclass.to_text(rdclass)} " + f"{dns.rdatatype.to_text(self.rdtype)} " + f"{rd.to_text(origin=origin, relativize=relativize, **kw)}" + f"{extra}\n" + ) + # + # We strip off the final \n for the caller's convenience in printing + # + return s.getvalue()[:-1] + + def to_wire( + self, + name: dns.name.Name, + file: Any, + compress: dns.name.CompressType | None = None, + origin: dns.name.Name | None = None, + override_rdclass: dns.rdataclass.RdataClass | None = None, + want_shuffle: bool = True, + ) -> int: + """Convert the rdataset to wire format. + + *name*, a ``dns.name.Name`` is the owner name to use. + + *file* is the file where the name is emitted (typically a + BytesIO file). + + *compress*, a ``dict``, is the compression table to use. If + ``None`` (the default), names will not be compressed. + + *origin* is a ``dns.name.Name`` or ``None``. If the name is + relative and origin is not ``None``, then *origin* will be appended + to it. + + *override_rdclass*, an ``int``, is used as the class instead of the + class of the rdataset. This is useful when rendering rdatasets + associated with dynamic updates. + + *want_shuffle*, a ``bool``. If ``True``, then the order of the + Rdatas within the Rdataset will be shuffled before rendering. + + Returns an ``int``, the number of records emitted. + """ + + if override_rdclass is not None: + rdclass = override_rdclass + want_shuffle = False + else: + rdclass = self.rdclass + if len(self) == 0: + name.to_wire(file, compress, origin) + file.write(struct.pack("!HHIH", self.rdtype, rdclass, 0, 0)) + return 1 + else: + l: Rdataset | List[dns.rdata.Rdata] + if want_shuffle: + l = list(self) + random.shuffle(l) + else: + l = self + for rd in l: + name.to_wire(file, compress, origin) + file.write(struct.pack("!HHI", self.rdtype, rdclass, self.ttl)) + with dns.renderer.prefixed_length(file, 2): + rd.to_wire(file, compress, origin) + return len(self) + + def match( + self, + rdclass: dns.rdataclass.RdataClass, + rdtype: dns.rdatatype.RdataType, + covers: dns.rdatatype.RdataType, + ) -> bool: + """Returns ``True`` if this rdataset matches the specified class, + type, and covers. + """ + if self.rdclass == rdclass and self.rdtype == rdtype and self.covers == covers: + return True + return False + + def processing_order(self) -> List[dns.rdata.Rdata]: + """Return rdatas in a valid processing order according to the type's + specification. For example, MX records are in preference order from + lowest to highest preferences, with items of the same preference + shuffled. + + For types that do not define a processing order, the rdatas are + simply shuffled. + """ + if len(self) == 0: + return [] + else: + return self[0]._processing_order(iter(self)) # pyright: ignore + + +@dns.immutable.immutable +class ImmutableRdataset(Rdataset): # lgtm[py/missing-equals] + """An immutable DNS rdataset.""" + + _clone_class = Rdataset + + def __init__(self, rdataset: Rdataset): + """Create an immutable rdataset from the specified rdataset.""" + + super().__init__( + rdataset.rdclass, rdataset.rdtype, rdataset.covers, rdataset.ttl + ) + self.items = dns.immutable.Dict(rdataset.items) + + def update_ttl(self, ttl): + raise TypeError("immutable") + + def add(self, rd, ttl=None): + raise TypeError("immutable") + + def union_update(self, other): + raise TypeError("immutable") + + def intersection_update(self, other): + raise TypeError("immutable") + + def update(self, other): + raise TypeError("immutable") + + def __delitem__(self, i): + raise TypeError("immutable") + + # lgtm complains about these not raising ArithmeticError, but there is + # precedent for overrides of these methods in other classes to raise + # TypeError, and it seems like the better exception. + + def __ior__(self, other): # lgtm[py/unexpected-raise-in-special-method] + raise TypeError("immutable") + + def __iand__(self, other): # lgtm[py/unexpected-raise-in-special-method] + raise TypeError("immutable") + + def __iadd__(self, other): # lgtm[py/unexpected-raise-in-special-method] + raise TypeError("immutable") + + def __isub__(self, other): # lgtm[py/unexpected-raise-in-special-method] + raise TypeError("immutable") + + def clear(self): + raise TypeError("immutable") + + def __copy__(self): + return ImmutableRdataset(super().copy()) # pyright: ignore + + def copy(self): + return ImmutableRdataset(super().copy()) # pyright: ignore + + def union(self, other): + return ImmutableRdataset(super().union(other)) # pyright: ignore + + def intersection(self, other): + return ImmutableRdataset(super().intersection(other)) # pyright: ignore + + def difference(self, other): + return ImmutableRdataset(super().difference(other)) # pyright: ignore + + def symmetric_difference(self, other): + return ImmutableRdataset(super().symmetric_difference(other)) # pyright: ignore + + +def from_text_list( + rdclass: dns.rdataclass.RdataClass | str, + rdtype: dns.rdatatype.RdataType | str, + ttl: int, + text_rdatas: Collection[str], + idna_codec: dns.name.IDNACodec | None = None, + origin: dns.name.Name | None = None, + relativize: bool = True, + relativize_to: dns.name.Name | None = None, +) -> Rdataset: + """Create an rdataset with the specified class, type, and TTL, and with + the specified list of rdatas in text format. + + *idna_codec*, a ``dns.name.IDNACodec``, specifies the IDNA + encoder/decoder to use; if ``None``, the default IDNA 2003 + encoder/decoder is used. + + *origin*, a ``dns.name.Name`` (or ``None``), the + origin to use for relative names. + + *relativize*, a ``bool``. If true, name will be relativized. + + *relativize_to*, a ``dns.name.Name`` (or ``None``), the origin to use + when relativizing names. If not set, the *origin* value will be used. + + Returns a ``dns.rdataset.Rdataset`` object. + """ + + rdclass = dns.rdataclass.RdataClass.make(rdclass) + rdtype = dns.rdatatype.RdataType.make(rdtype) + r = Rdataset(rdclass, rdtype) + r.update_ttl(ttl) + for t in text_rdatas: + rd = dns.rdata.from_text( + r.rdclass, r.rdtype, t, origin, relativize, relativize_to, idna_codec + ) + r.add(rd) + return r + + +def from_text( + rdclass: dns.rdataclass.RdataClass | str, + rdtype: dns.rdatatype.RdataType | str, + ttl: int, + *text_rdatas: Any, +) -> Rdataset: + """Create an rdataset with the specified class, type, and TTL, and with + the specified rdatas in text format. + + Returns a ``dns.rdataset.Rdataset`` object. + """ + + return from_text_list(rdclass, rdtype, ttl, cast(Collection[str], text_rdatas)) + + +def from_rdata_list(ttl: int, rdatas: Collection[dns.rdata.Rdata]) -> Rdataset: + """Create an rdataset with the specified TTL, and with + the specified list of rdata objects. + + Returns a ``dns.rdataset.Rdataset`` object. + """ + + if len(rdatas) == 0: + raise ValueError("rdata list must not be empty") + r = None + for rd in rdatas: + if r is None: + r = Rdataset(rd.rdclass, rd.rdtype) + r.update_ttl(ttl) + r.add(rd) + assert r is not None + return r + + +def from_rdata(ttl: int, *rdatas: Any) -> Rdataset: + """Create an rdataset with the specified TTL, and with + the specified rdata objects. + + Returns a ``dns.rdataset.Rdataset`` object. + """ + + return from_rdata_list(ttl, cast(Collection[dns.rdata.Rdata], rdatas)) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdatatype.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdatatype.py new file mode 100644 index 000000000..211d810da --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdatatype.py @@ -0,0 +1,338 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +# Copyright (C) 2001-2017 Nominum, Inc. +# +# Permission to use, copy, modify, and distribute this software and its +# documentation for any purpose with or without fee is hereby granted, +# provided that the above copyright notice and this permission notice +# appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +"""DNS Rdata Types.""" + +from typing import Dict + +import dns.enum +import dns.exception + + +class RdataType(dns.enum.IntEnum): + """DNS Rdata Type""" + + TYPE0 = 0 + NONE = 0 + A = 1 + NS = 2 + MD = 3 + MF = 4 + CNAME = 5 + SOA = 6 + MB = 7 + MG = 8 + MR = 9 + NULL = 10 + WKS = 11 + PTR = 12 + HINFO = 13 + MINFO = 14 + MX = 15 + TXT = 16 + RP = 17 + AFSDB = 18 + X25 = 19 + ISDN = 20 + RT = 21 + NSAP = 22 + NSAP_PTR = 23 + SIG = 24 + KEY = 25 + PX = 26 + GPOS = 27 + AAAA = 28 + LOC = 29 + NXT = 30 + SRV = 33 + NAPTR = 35 + KX = 36 + CERT = 37 + A6 = 38 + DNAME = 39 + OPT = 41 + APL = 42 + DS = 43 + SSHFP = 44 + IPSECKEY = 45 + RRSIG = 46 + NSEC = 47 + DNSKEY = 48 + DHCID = 49 + NSEC3 = 50 + NSEC3PARAM = 51 + TLSA = 52 + SMIMEA = 53 + HIP = 55 + NINFO = 56 + CDS = 59 + CDNSKEY = 60 + OPENPGPKEY = 61 + CSYNC = 62 + ZONEMD = 63 + SVCB = 64 + HTTPS = 65 + DSYNC = 66 + SPF = 99 + UNSPEC = 103 + NID = 104 + L32 = 105 + L64 = 106 + LP = 107 + EUI48 = 108 + EUI64 = 109 + TKEY = 249 + TSIG = 250 + IXFR = 251 + AXFR = 252 + MAILB = 253 + MAILA = 254 + ANY = 255 + URI = 256 + CAA = 257 + AVC = 258 + AMTRELAY = 260 + RESINFO = 261 + WALLET = 262 + TA = 32768 + DLV = 32769 + + @classmethod + def _maximum(cls): + return 65535 + + @classmethod + def _short_name(cls): + return "type" + + @classmethod + def _prefix(cls): + return "TYPE" + + @classmethod + def _extra_from_text(cls, text): + if text.find("-") >= 0: + try: + return cls[text.replace("-", "_")] + except KeyError: # pragma: no cover + pass + return _registered_by_text.get(text) + + @classmethod + def _extra_to_text(cls, value, current_text): + if current_text is None: + return _registered_by_value.get(value) + if current_text.find("_") >= 0: + return current_text.replace("_", "-") + return current_text + + @classmethod + def _unknown_exception_class(cls): + return UnknownRdatatype + + +_registered_by_text: Dict[str, RdataType] = {} +_registered_by_value: Dict[RdataType, str] = {} + +_metatypes = {RdataType.OPT} + +_singletons = { + RdataType.SOA, + RdataType.NXT, + RdataType.DNAME, + RdataType.NSEC, + RdataType.CNAME, +} + + +class UnknownRdatatype(dns.exception.DNSException): + """DNS resource record type is unknown.""" + + +def from_text(text: str) -> RdataType: + """Convert text into a DNS rdata type value. + + The input text can be a defined DNS RR type mnemonic or + instance of the DNS generic type syntax. + + For example, "NS" and "TYPE2" will both result in a value of 2. + + Raises ``dns.rdatatype.UnknownRdatatype`` if the type is unknown. + + Raises ``ValueError`` if the rdata type value is not >= 0 and <= 65535. + + Returns a ``dns.rdatatype.RdataType``. + """ + + return RdataType.from_text(text) + + +def to_text(value: RdataType) -> str: + """Convert a DNS rdata type value to text. + + If the value has a known mnemonic, it will be used, otherwise the + DNS generic type syntax will be used. + + Raises ``ValueError`` if the rdata type value is not >= 0 and <= 65535. + + Returns a ``str``. + """ + + return RdataType.to_text(value) + + +def is_metatype(rdtype: RdataType) -> bool: + """True if the specified type is a metatype. + + *rdtype* is a ``dns.rdatatype.RdataType``. + + The currently defined metatypes are TKEY, TSIG, IXFR, AXFR, MAILA, + MAILB, ANY, and OPT. + + Returns a ``bool``. + """ + + return (256 > rdtype >= 128) or rdtype in _metatypes + + +def is_singleton(rdtype: RdataType) -> bool: + """Is the specified type a singleton type? + + Singleton types can only have a single rdata in an rdataset, or a single + RR in an RRset. + + The currently defined singleton types are CNAME, DNAME, NSEC, NXT, and + SOA. + + *rdtype* is an ``int``. + + Returns a ``bool``. + """ + + if rdtype in _singletons: + return True + return False + + +# pylint: disable=redefined-outer-name +def register_type( + rdtype: RdataType, rdtype_text: str, is_singleton: bool = False +) -> None: + """Dynamically register an rdatatype. + + *rdtype*, a ``dns.rdatatype.RdataType``, the rdatatype to register. + + *rdtype_text*, a ``str``, the textual form of the rdatatype. + + *is_singleton*, a ``bool``, indicating if the type is a singleton (i.e. + RRsets of the type can have only one member.) + """ + + _registered_by_text[rdtype_text] = rdtype + _registered_by_value[rdtype] = rdtype_text + if is_singleton: + _singletons.add(rdtype) + + +### BEGIN generated RdataType constants + +TYPE0 = RdataType.TYPE0 +NONE = RdataType.NONE +A = RdataType.A +NS = RdataType.NS +MD = RdataType.MD +MF = RdataType.MF +CNAME = RdataType.CNAME +SOA = RdataType.SOA +MB = RdataType.MB +MG = RdataType.MG +MR = RdataType.MR +NULL = RdataType.NULL +WKS = RdataType.WKS +PTR = RdataType.PTR +HINFO = RdataType.HINFO +MINFO = RdataType.MINFO +MX = RdataType.MX +TXT = RdataType.TXT +RP = RdataType.RP +AFSDB = RdataType.AFSDB +X25 = RdataType.X25 +ISDN = RdataType.ISDN +RT = RdataType.RT +NSAP = RdataType.NSAP +NSAP_PTR = RdataType.NSAP_PTR +SIG = RdataType.SIG +KEY = RdataType.KEY +PX = RdataType.PX +GPOS = RdataType.GPOS +AAAA = RdataType.AAAA +LOC = RdataType.LOC +NXT = RdataType.NXT +SRV = RdataType.SRV +NAPTR = RdataType.NAPTR +KX = RdataType.KX +CERT = RdataType.CERT +A6 = RdataType.A6 +DNAME = RdataType.DNAME +OPT = RdataType.OPT +APL = RdataType.APL +DS = RdataType.DS +SSHFP = RdataType.SSHFP +IPSECKEY = RdataType.IPSECKEY +RRSIG = RdataType.RRSIG +NSEC = RdataType.NSEC +DNSKEY = RdataType.DNSKEY +DHCID = RdataType.DHCID +NSEC3 = RdataType.NSEC3 +NSEC3PARAM = RdataType.NSEC3PARAM +TLSA = RdataType.TLSA +SMIMEA = RdataType.SMIMEA +HIP = RdataType.HIP +NINFO = RdataType.NINFO +CDS = RdataType.CDS +CDNSKEY = RdataType.CDNSKEY +OPENPGPKEY = RdataType.OPENPGPKEY +CSYNC = RdataType.CSYNC +ZONEMD = RdataType.ZONEMD +SVCB = RdataType.SVCB +HTTPS = RdataType.HTTPS +DSYNC = RdataType.DSYNC +SPF = RdataType.SPF +UNSPEC = RdataType.UNSPEC +NID = RdataType.NID +L32 = RdataType.L32 +L64 = RdataType.L64 +LP = RdataType.LP +EUI48 = RdataType.EUI48 +EUI64 = RdataType.EUI64 +TKEY = RdataType.TKEY +TSIG = RdataType.TSIG +IXFR = RdataType.IXFR +AXFR = RdataType.AXFR +MAILB = RdataType.MAILB +MAILA = RdataType.MAILA +ANY = RdataType.ANY +URI = RdataType.URI +CAA = RdataType.CAA +AVC = RdataType.AVC +AMTRELAY = RdataType.AMTRELAY +RESINFO = RdataType.RESINFO +WALLET = RdataType.WALLET +TA = RdataType.TA +DLV = RdataType.DLV + +### END generated RdataType constants diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/AFSDB.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/AFSDB.py new file mode 100644 index 000000000..06a3b9701 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/AFSDB.py @@ -0,0 +1,45 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. +# +# Permission to use, copy, modify, and distribute this software and its +# documentation for any purpose with or without fee is hereby granted, +# provided that the above copyright notice and this permission notice +# appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +import dns.immutable +import dns.rdtypes.mxbase + + +@dns.immutable.immutable +class AFSDB(dns.rdtypes.mxbase.UncompressedDowncasingMX): + """AFSDB record""" + + # Use the property mechanism to make "subtype" an alias for the + # "preference" attribute, and "hostname" an alias for the "exchange" + # attribute. + # + # This lets us inherit the UncompressedMX implementation but lets + # the caller use appropriate attribute names for the rdata type. + # + # We probably lose some performance vs. a cut-and-paste + # implementation, but this way we don't copy code, and that's + # good. + + @property + def subtype(self): + "the AFSDB subtype" + return self.preference + + @property + def hostname(self): + "the AFSDB hostname" + return self.exchange diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/AMTRELAY.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/AMTRELAY.py new file mode 100644 index 000000000..dc9fa8770 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/AMTRELAY.py @@ -0,0 +1,89 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +# Copyright (C) 2006, 2007, 2009-2011 Nominum, Inc. +# +# Permission to use, copy, modify, and distribute this software and its +# documentation for any purpose with or without fee is hereby granted, +# provided that the above copyright notice and this permission notice +# appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +import struct + +import dns.exception +import dns.immutable +import dns.rdata +import dns.rdtypes.util + + +class Relay(dns.rdtypes.util.Gateway): + name = "AMTRELAY relay" + + @property + def relay(self): + return self.gateway + + +@dns.immutable.immutable +class AMTRELAY(dns.rdata.Rdata): + """AMTRELAY record""" + + # see: RFC 8777 + + __slots__ = ["precedence", "discovery_optional", "relay_type", "relay"] + + def __init__( + self, rdclass, rdtype, precedence, discovery_optional, relay_type, relay + ): + super().__init__(rdclass, rdtype) + relay = Relay(relay_type, relay) + self.precedence = self._as_uint8(precedence) + self.discovery_optional = self._as_bool(discovery_optional) + self.relay_type = relay.type + self.relay = relay.relay + + def to_text(self, origin=None, relativize=True, **kw): + relay = Relay(self.relay_type, self.relay).to_text(origin, relativize) + return ( + f"{self.precedence} {self.discovery_optional:d} {self.relay_type} {relay}" + ) + + @classmethod + def from_text( + cls, rdclass, rdtype, tok, origin=None, relativize=True, relativize_to=None + ): + precedence = tok.get_uint8() + discovery_optional = tok.get_uint8() + if discovery_optional > 1: + raise dns.exception.SyntaxError("expecting 0 or 1") + discovery_optional = bool(discovery_optional) + relay_type = tok.get_uint8() + if relay_type > 0x7F: + raise dns.exception.SyntaxError("expecting an integer <= 127") + relay = Relay.from_text(relay_type, tok, origin, relativize, relativize_to) + return cls( + rdclass, rdtype, precedence, discovery_optional, relay_type, relay.relay + ) + + def _to_wire(self, file, compress=None, origin=None, canonicalize=False): + relay_type = self.relay_type | (self.discovery_optional << 7) + header = struct.pack("!BB", self.precedence, relay_type) + file.write(header) + Relay(self.relay_type, self.relay).to_wire(file, compress, origin, canonicalize) + + @classmethod + def from_wire_parser(cls, rdclass, rdtype, parser, origin=None): + (precedence, relay_type) = parser.get_struct("!BB") + discovery_optional = bool(relay_type >> 7) + relay_type &= 0x7F + relay = Relay.from_wire_parser(relay_type, parser, origin) + return cls( + rdclass, rdtype, precedence, discovery_optional, relay_type, relay.relay + ) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/AVC.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/AVC.py new file mode 100644 index 000000000..a27ae2d61 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/AVC.py @@ -0,0 +1,26 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +# Copyright (C) 2016 Nominum, Inc. +# +# Permission to use, copy, modify, and distribute this software and its +# documentation for any purpose with or without fee is hereby granted, +# provided that the above copyright notice and this permission notice +# appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +import dns.immutable +import dns.rdtypes.txtbase + + +@dns.immutable.immutable +class AVC(dns.rdtypes.txtbase.TXTBase): + """AVC record""" + + # See: IANA dns parameters for AVC diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/CAA.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/CAA.py new file mode 100644 index 000000000..8c62e6267 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/CAA.py @@ -0,0 +1,67 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. +# +# Permission to use, copy, modify, and distribute this software and its +# documentation for any purpose with or without fee is hereby granted, +# provided that the above copyright notice and this permission notice +# appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +import struct + +import dns.exception +import dns.immutable +import dns.rdata +import dns.tokenizer + + +@dns.immutable.immutable +class CAA(dns.rdata.Rdata): + """CAA (Certification Authority Authorization) record""" + + # see: RFC 6844 + + __slots__ = ["flags", "tag", "value"] + + def __init__(self, rdclass, rdtype, flags, tag, value): + super().__init__(rdclass, rdtype) + self.flags = self._as_uint8(flags) + self.tag = self._as_bytes(tag, True, 255) + if not tag.isalnum(): + raise ValueError("tag is not alphanumeric") + self.value = self._as_bytes(value) + + def to_text(self, origin=None, relativize=True, **kw): + return f'{self.flags} {dns.rdata._escapify(self.tag)} "{dns.rdata._escapify(self.value)}"' + + @classmethod + def from_text( + cls, rdclass, rdtype, tok, origin=None, relativize=True, relativize_to=None + ): + flags = tok.get_uint8() + tag = tok.get_string().encode() + value = tok.get_string().encode() + return cls(rdclass, rdtype, flags, tag, value) + + def _to_wire(self, file, compress=None, origin=None, canonicalize=False): + file.write(struct.pack("!B", self.flags)) + l = len(self.tag) + assert l < 256 + file.write(struct.pack("!B", l)) + file.write(self.tag) + file.write(self.value) + + @classmethod + def from_wire_parser(cls, rdclass, rdtype, parser, origin=None): + flags = parser.get_uint8() + tag = parser.get_counted_bytes() + value = parser.get_remaining() + return cls(rdclass, rdtype, flags, tag, value) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/CDNSKEY.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/CDNSKEY.py new file mode 100644 index 000000000..b613409f4 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/CDNSKEY.py @@ -0,0 +1,33 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +# Copyright (C) 2004-2007, 2009-2011 Nominum, Inc. +# +# Permission to use, copy, modify, and distribute this software and its +# documentation for any purpose with or without fee is hereby granted, +# provided that the above copyright notice and this permission notice +# appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +import dns.immutable +import dns.rdtypes.dnskeybase # lgtm[py/import-and-import-from] + +# pylint: disable=unused-import +from dns.rdtypes.dnskeybase import ( # noqa: F401 lgtm[py/unused-import] + REVOKE, + SEP, + ZONE, +) + +# pylint: enable=unused-import + + +@dns.immutable.immutable +class CDNSKEY(dns.rdtypes.dnskeybase.DNSKEYBase): + """CDNSKEY record""" diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/CDS.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/CDS.py new file mode 100644 index 000000000..8312b972a --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/CDS.py @@ -0,0 +1,29 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. +# +# Permission to use, copy, modify, and distribute this software and its +# documentation for any purpose with or without fee is hereby granted, +# provided that the above copyright notice and this permission notice +# appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +import dns.immutable +import dns.rdtypes.dsbase + + +@dns.immutable.immutable +class CDS(dns.rdtypes.dsbase.DSBase): + """CDS record""" + + _digest_length_by_type = { + **dns.rdtypes.dsbase.DSBase._digest_length_by_type, + 0: 1, # delete, RFC 8078 Sec. 4 (including Errata ID 5049) + } diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/CERT.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/CERT.py new file mode 100644 index 000000000..4d5e5bda1 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/CERT.py @@ -0,0 +1,113 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. +# +# Permission to use, copy, modify, and distribute this software and its +# documentation for any purpose with or without fee is hereby granted, +# provided that the above copyright notice and this permission notice +# appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +import base64 +import struct + +import dns.dnssectypes +import dns.exception +import dns.immutable +import dns.rdata +import dns.tokenizer + +_ctype_by_value = { + 1: "PKIX", + 2: "SPKI", + 3: "PGP", + 4: "IPKIX", + 5: "ISPKI", + 6: "IPGP", + 7: "ACPKIX", + 8: "IACPKIX", + 253: "URI", + 254: "OID", +} + +_ctype_by_name = { + "PKIX": 1, + "SPKI": 2, + "PGP": 3, + "IPKIX": 4, + "ISPKI": 5, + "IPGP": 6, + "ACPKIX": 7, + "IACPKIX": 8, + "URI": 253, + "OID": 254, +} + + +def _ctype_from_text(what): + v = _ctype_by_name.get(what) + if v is not None: + return v + return int(what) + + +def _ctype_to_text(what): + v = _ctype_by_value.get(what) + if v is not None: + return v + return str(what) + + +@dns.immutable.immutable +class CERT(dns.rdata.Rdata): + """CERT record""" + + # see RFC 4398 + + __slots__ = ["certificate_type", "key_tag", "algorithm", "certificate"] + + def __init__( + self, rdclass, rdtype, certificate_type, key_tag, algorithm, certificate + ): + super().__init__(rdclass, rdtype) + self.certificate_type = self._as_uint16(certificate_type) + self.key_tag = self._as_uint16(key_tag) + self.algorithm = self._as_uint8(algorithm) + self.certificate = self._as_bytes(certificate) + + def to_text(self, origin=None, relativize=True, **kw): + certificate_type = _ctype_to_text(self.certificate_type) + algorithm = dns.dnssectypes.Algorithm.to_text(self.algorithm) + certificate = dns.rdata._base64ify(self.certificate, **kw) # pyright: ignore + return f"{certificate_type} {self.key_tag} {algorithm} {certificate}" + + @classmethod + def from_text( + cls, rdclass, rdtype, tok, origin=None, relativize=True, relativize_to=None + ): + certificate_type = _ctype_from_text(tok.get_string()) + key_tag = tok.get_uint16() + algorithm = dns.dnssectypes.Algorithm.from_text(tok.get_string()) + b64 = tok.concatenate_remaining_identifiers().encode() + certificate = base64.b64decode(b64) + return cls(rdclass, rdtype, certificate_type, key_tag, algorithm, certificate) + + def _to_wire(self, file, compress=None, origin=None, canonicalize=False): + prefix = struct.pack( + "!HHB", self.certificate_type, self.key_tag, self.algorithm + ) + file.write(prefix) + file.write(self.certificate) + + @classmethod + def from_wire_parser(cls, rdclass, rdtype, parser, origin=None): + (certificate_type, key_tag, algorithm) = parser.get_struct("!HHB") + certificate = parser.get_remaining() + return cls(rdclass, rdtype, certificate_type, key_tag, algorithm, certificate) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/CNAME.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/CNAME.py new file mode 100644 index 000000000..665e407c9 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/CNAME.py @@ -0,0 +1,28 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. +# +# Permission to use, copy, modify, and distribute this software and its +# documentation for any purpose with or without fee is hereby granted, +# provided that the above copyright notice and this permission notice +# appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +import dns.immutable +import dns.rdtypes.nsbase + + +@dns.immutable.immutable +class CNAME(dns.rdtypes.nsbase.NSBase): + """CNAME record + + Note: although CNAME is officially a singleton type, dnspython allows + non-singleton CNAME rdatasets because such sets have been commonly + used by BIND and other nameservers for load balancing.""" diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/CSYNC.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/CSYNC.py new file mode 100644 index 000000000..103486d83 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/CSYNC.py @@ -0,0 +1,68 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +# Copyright (C) 2004-2007, 2009-2011, 2016 Nominum, Inc. +# +# Permission to use, copy, modify, and distribute this software and its +# documentation for any purpose with or without fee is hereby granted, +# provided that the above copyright notice and this permission notice +# appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +import struct + +import dns.exception +import dns.immutable +import dns.name +import dns.rdata +import dns.rdatatype +import dns.rdtypes.util + + +@dns.immutable.immutable +class Bitmap(dns.rdtypes.util.Bitmap): + type_name = "CSYNC" + + +@dns.immutable.immutable +class CSYNC(dns.rdata.Rdata): + """CSYNC record""" + + __slots__ = ["serial", "flags", "windows"] + + def __init__(self, rdclass, rdtype, serial, flags, windows): + super().__init__(rdclass, rdtype) + self.serial = self._as_uint32(serial) + self.flags = self._as_uint16(flags) + if not isinstance(windows, Bitmap): + windows = Bitmap(windows) + self.windows = tuple(windows.windows) + + def to_text(self, origin=None, relativize=True, **kw): + text = Bitmap(self.windows).to_text() + return f"{self.serial} {self.flags}{text}" + + @classmethod + def from_text( + cls, rdclass, rdtype, tok, origin=None, relativize=True, relativize_to=None + ): + serial = tok.get_uint32() + flags = tok.get_uint16() + bitmap = Bitmap.from_text(tok) + return cls(rdclass, rdtype, serial, flags, bitmap) + + def _to_wire(self, file, compress=None, origin=None, canonicalize=False): + file.write(struct.pack("!IH", self.serial, self.flags)) + Bitmap(self.windows).to_wire(file) + + @classmethod + def from_wire_parser(cls, rdclass, rdtype, parser, origin=None): + (serial, flags) = parser.get_struct("!IH") + bitmap = Bitmap.from_wire_parser(parser) + return cls(rdclass, rdtype, serial, flags, bitmap) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/DLV.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/DLV.py new file mode 100644 index 000000000..6c134f182 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/DLV.py @@ -0,0 +1,24 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +# Copyright (C) 2009-2011 Nominum, Inc. +# +# Permission to use, copy, modify, and distribute this software and its +# documentation for any purpose with or without fee is hereby granted, +# provided that the above copyright notice and this permission notice +# appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +import dns.immutable +import dns.rdtypes.dsbase + + +@dns.immutable.immutable +class DLV(dns.rdtypes.dsbase.DSBase): + """DLV record""" diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/DNAME.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/DNAME.py new file mode 100644 index 000000000..bbf9186c9 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/DNAME.py @@ -0,0 +1,27 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. +# +# Permission to use, copy, modify, and distribute this software and its +# documentation for any purpose with or without fee is hereby granted, +# provided that the above copyright notice and this permission notice +# appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +import dns.immutable +import dns.rdtypes.nsbase + + +@dns.immutable.immutable +class DNAME(dns.rdtypes.nsbase.UncompressedNS): + """DNAME record""" + + def _to_wire(self, file, compress=None, origin=None, canonicalize=False): + self.target.to_wire(file, None, origin, canonicalize) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/DNSKEY.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/DNSKEY.py new file mode 100644 index 000000000..6d961a9f5 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/DNSKEY.py @@ -0,0 +1,33 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +# Copyright (C) 2004-2007, 2009-2011 Nominum, Inc. +# +# Permission to use, copy, modify, and distribute this software and its +# documentation for any purpose with or without fee is hereby granted, +# provided that the above copyright notice and this permission notice +# appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +import dns.immutable +import dns.rdtypes.dnskeybase # lgtm[py/import-and-import-from] + +# pylint: disable=unused-import +from dns.rdtypes.dnskeybase import ( # noqa: F401 lgtm[py/unused-import] + REVOKE, + SEP, + ZONE, +) + +# pylint: enable=unused-import + + +@dns.immutable.immutable +class DNSKEY(dns.rdtypes.dnskeybase.DNSKEYBase): + """DNSKEY record""" diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/DS.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/DS.py new file mode 100644 index 000000000..58b3108da --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/DS.py @@ -0,0 +1,24 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. +# +# Permission to use, copy, modify, and distribute this software and its +# documentation for any purpose with or without fee is hereby granted, +# provided that the above copyright notice and this permission notice +# appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +import dns.immutable +import dns.rdtypes.dsbase + + +@dns.immutable.immutable +class DS(dns.rdtypes.dsbase.DSBase): + """DS record""" diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/DSYNC.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/DSYNC.py new file mode 100644 index 000000000..e8d1394af --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/DSYNC.py @@ -0,0 +1,72 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +import struct + +import dns.enum +import dns.exception +import dns.immutable +import dns.rdata +import dns.rdatatype +import dns.rdtypes.util + + +class UnknownScheme(dns.exception.DNSException): + """Unknown DSYNC scheme""" + + +class Scheme(dns.enum.IntEnum): + """DSYNC SCHEME""" + + NOTIFY = 1 + + @classmethod + def _maximum(cls): + return 255 + + @classmethod + def _unknown_exception_class(cls): + return UnknownScheme + + +@dns.immutable.immutable +class DSYNC(dns.rdata.Rdata): + """DSYNC record""" + + # see: draft-ietf-dnsop-generalized-notify + + __slots__ = ["rrtype", "scheme", "port", "target"] + + def __init__(self, rdclass, rdtype, rrtype, scheme, port, target): + super().__init__(rdclass, rdtype) + self.rrtype = self._as_rdatatype(rrtype) + self.scheme = Scheme.make(scheme) + self.port = self._as_uint16(port) + self.target = self._as_name(target) + + def to_text(self, origin=None, relativize=True, **kw): + target = self.target.choose_relativity(origin, relativize) + return ( + f"{dns.rdatatype.to_text(self.rrtype)} {Scheme.to_text(self.scheme)} " + f"{self.port} {target}" + ) + + @classmethod + def from_text( + cls, rdclass, rdtype, tok, origin=None, relativize=True, relativize_to=None + ): + rrtype = dns.rdatatype.from_text(tok.get_string()) + scheme = Scheme.make(tok.get_string()) + port = tok.get_uint16() + target = tok.get_name(origin, relativize, relativize_to) + return cls(rdclass, rdtype, rrtype, scheme, port, target) + + def _to_wire(self, file, compress=None, origin=None, canonicalize=False): + three_ints = struct.pack("!HBH", self.rrtype, self.scheme, self.port) + file.write(three_ints) + self.target.to_wire(file, None, origin, False) + + @classmethod + def from_wire_parser(cls, rdclass, rdtype, parser, origin=None): + (rrtype, scheme, port) = parser.get_struct("!HBH") + target = parser.get_name(origin) + return cls(rdclass, rdtype, rrtype, scheme, port, target) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/EUI48.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/EUI48.py new file mode 100644 index 000000000..c843be504 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/EUI48.py @@ -0,0 +1,30 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +# Copyright (C) 2015 Red Hat, Inc. +# Author: Petr Spacek +# +# Permission to use, copy, modify, and distribute this software and its +# documentation for any purpose with or without fee is hereby granted, +# provided that the above copyright notice and this permission notice +# appear in all copies. +# +# THE SOFTWARE IS PROVIDED 'AS IS' AND RED HAT DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +import dns.immutable +import dns.rdtypes.euibase + + +@dns.immutable.immutable +class EUI48(dns.rdtypes.euibase.EUIBase): + """EUI48 record""" + + # see: rfc7043.txt + + byte_len = 6 # 0123456789ab (in hex) + text_len = byte_len * 3 - 1 # 01-23-45-67-89-ab diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/EUI64.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/EUI64.py new file mode 100644 index 000000000..f6d7e257e --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/EUI64.py @@ -0,0 +1,30 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +# Copyright (C) 2015 Red Hat, Inc. +# Author: Petr Spacek +# +# Permission to use, copy, modify, and distribute this software and its +# documentation for any purpose with or without fee is hereby granted, +# provided that the above copyright notice and this permission notice +# appear in all copies. +# +# THE SOFTWARE IS PROVIDED 'AS IS' AND RED HAT DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +import dns.immutable +import dns.rdtypes.euibase + + +@dns.immutable.immutable +class EUI64(dns.rdtypes.euibase.EUIBase): + """EUI64 record""" + + # see: rfc7043.txt + + byte_len = 8 # 0123456789abcdef (in hex) + text_len = byte_len * 3 - 1 # 01-23-45-67-89-ab-cd-ef diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/GPOS.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/GPOS.py new file mode 100644 index 000000000..d79f4a066 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/GPOS.py @@ -0,0 +1,126 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. +# +# Permission to use, copy, modify, and distribute this software and its +# documentation for any purpose with or without fee is hereby granted, +# provided that the above copyright notice and this permission notice +# appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +import struct + +import dns.exception +import dns.immutable +import dns.rdata +import dns.tokenizer + + +def _validate_float_string(what): + if len(what) == 0: + raise dns.exception.FormError + if what[0] == b"-"[0] or what[0] == b"+"[0]: + what = what[1:] + if what.isdigit(): + return + try: + (left, right) = what.split(b".") + except ValueError: + raise dns.exception.FormError + if left == b"" and right == b"": + raise dns.exception.FormError + if not left == b"" and not left.decode().isdigit(): + raise dns.exception.FormError + if not right == b"" and not right.decode().isdigit(): + raise dns.exception.FormError + + +@dns.immutable.immutable +class GPOS(dns.rdata.Rdata): + """GPOS record""" + + # see: RFC 1712 + + __slots__ = ["latitude", "longitude", "altitude"] + + def __init__(self, rdclass, rdtype, latitude, longitude, altitude): + super().__init__(rdclass, rdtype) + if isinstance(latitude, float) or isinstance(latitude, int): + latitude = str(latitude) + if isinstance(longitude, float) or isinstance(longitude, int): + longitude = str(longitude) + if isinstance(altitude, float) or isinstance(altitude, int): + altitude = str(altitude) + latitude = self._as_bytes(latitude, True, 255) + longitude = self._as_bytes(longitude, True, 255) + altitude = self._as_bytes(altitude, True, 255) + _validate_float_string(latitude) + _validate_float_string(longitude) + _validate_float_string(altitude) + self.latitude = latitude + self.longitude = longitude + self.altitude = altitude + flat = self.float_latitude + if flat < -90.0 or flat > 90.0: + raise dns.exception.FormError("bad latitude") + flong = self.float_longitude + if flong < -180.0 or flong > 180.0: + raise dns.exception.FormError("bad longitude") + + def to_text(self, origin=None, relativize=True, **kw): + return ( + f"{self.latitude.decode()} {self.longitude.decode()} " + f"{self.altitude.decode()}" + ) + + @classmethod + def from_text( + cls, rdclass, rdtype, tok, origin=None, relativize=True, relativize_to=None + ): + latitude = tok.get_string() + longitude = tok.get_string() + altitude = tok.get_string() + return cls(rdclass, rdtype, latitude, longitude, altitude) + + def _to_wire(self, file, compress=None, origin=None, canonicalize=False): + l = len(self.latitude) + assert l < 256 + file.write(struct.pack("!B", l)) + file.write(self.latitude) + l = len(self.longitude) + assert l < 256 + file.write(struct.pack("!B", l)) + file.write(self.longitude) + l = len(self.altitude) + assert l < 256 + file.write(struct.pack("!B", l)) + file.write(self.altitude) + + @classmethod + def from_wire_parser(cls, rdclass, rdtype, parser, origin=None): + latitude = parser.get_counted_bytes() + longitude = parser.get_counted_bytes() + altitude = parser.get_counted_bytes() + return cls(rdclass, rdtype, latitude, longitude, altitude) + + @property + def float_latitude(self): + "latitude as a floating point value" + return float(self.latitude) + + @property + def float_longitude(self): + "longitude as a floating point value" + return float(self.longitude) + + @property + def float_altitude(self): + "altitude as a floating point value" + return float(self.altitude) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/HINFO.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/HINFO.py new file mode 100644 index 000000000..06ad3487c --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/HINFO.py @@ -0,0 +1,64 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. +# +# Permission to use, copy, modify, and distribute this software and its +# documentation for any purpose with or without fee is hereby granted, +# provided that the above copyright notice and this permission notice +# appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +import struct + +import dns.exception +import dns.immutable +import dns.rdata +import dns.tokenizer + + +@dns.immutable.immutable +class HINFO(dns.rdata.Rdata): + """HINFO record""" + + # see: RFC 1035 + + __slots__ = ["cpu", "os"] + + def __init__(self, rdclass, rdtype, cpu, os): + super().__init__(rdclass, rdtype) + self.cpu = self._as_bytes(cpu, True, 255) + self.os = self._as_bytes(os, True, 255) + + def to_text(self, origin=None, relativize=True, **kw): + return f'"{dns.rdata._escapify(self.cpu)}" "{dns.rdata._escapify(self.os)}"' + + @classmethod + def from_text( + cls, rdclass, rdtype, tok, origin=None, relativize=True, relativize_to=None + ): + cpu = tok.get_string(max_length=255) + os = tok.get_string(max_length=255) + return cls(rdclass, rdtype, cpu, os) + + def _to_wire(self, file, compress=None, origin=None, canonicalize=False): + l = len(self.cpu) + assert l < 256 + file.write(struct.pack("!B", l)) + file.write(self.cpu) + l = len(self.os) + assert l < 256 + file.write(struct.pack("!B", l)) + file.write(self.os) + + @classmethod + def from_wire_parser(cls, rdclass, rdtype, parser, origin=None): + cpu = parser.get_counted_bytes() + os = parser.get_counted_bytes() + return cls(rdclass, rdtype, cpu, os) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/HIP.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/HIP.py new file mode 100644 index 000000000..dc7948a1f --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/HIP.py @@ -0,0 +1,85 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +# Copyright (C) 2010, 2011 Nominum, Inc. +# +# Permission to use, copy, modify, and distribute this software and its +# documentation for any purpose with or without fee is hereby granted, +# provided that the above copyright notice and this permission notice +# appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +import base64 +import binascii +import struct + +import dns.exception +import dns.immutable +import dns.rdata +import dns.rdatatype + + +@dns.immutable.immutable +class HIP(dns.rdata.Rdata): + """HIP record""" + + # see: RFC 5205 + + __slots__ = ["hit", "algorithm", "key", "servers"] + + def __init__(self, rdclass, rdtype, hit, algorithm, key, servers): + super().__init__(rdclass, rdtype) + self.hit = self._as_bytes(hit, True, 255) + self.algorithm = self._as_uint8(algorithm) + self.key = self._as_bytes(key, True) + self.servers = self._as_tuple(servers, self._as_name) + + def to_text(self, origin=None, relativize=True, **kw): + hit = binascii.hexlify(self.hit).decode() + key = base64.b64encode(self.key).replace(b"\n", b"").decode() + text = "" + servers = [] + for server in self.servers: + servers.append(server.choose_relativity(origin, relativize)) + if len(servers) > 0: + text += " " + " ".join(x.to_unicode() for x in servers) + return f"{self.algorithm} {hit} {key}{text}" + + @classmethod + def from_text( + cls, rdclass, rdtype, tok, origin=None, relativize=True, relativize_to=None + ): + algorithm = tok.get_uint8() + hit = binascii.unhexlify(tok.get_string().encode()) + key = base64.b64decode(tok.get_string().encode()) + servers = [] + for token in tok.get_remaining(): + server = tok.as_name(token, origin, relativize, relativize_to) + servers.append(server) + return cls(rdclass, rdtype, hit, algorithm, key, servers) + + def _to_wire(self, file, compress=None, origin=None, canonicalize=False): + lh = len(self.hit) + lk = len(self.key) + file.write(struct.pack("!BBH", lh, self.algorithm, lk)) + file.write(self.hit) + file.write(self.key) + for server in self.servers: + server.to_wire(file, None, origin, False) + + @classmethod + def from_wire_parser(cls, rdclass, rdtype, parser, origin=None): + (lh, algorithm, lk) = parser.get_struct("!BBH") + hit = parser.get_bytes(lh) + key = parser.get_bytes(lk) + servers = [] + while parser.remaining() > 0: + server = parser.get_name(origin) + servers.append(server) + return cls(rdclass, rdtype, hit, algorithm, key, servers) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/ISDN.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/ISDN.py new file mode 100644 index 000000000..6428a0a82 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/ISDN.py @@ -0,0 +1,78 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. +# +# Permission to use, copy, modify, and distribute this software and its +# documentation for any purpose with or without fee is hereby granted, +# provided that the above copyright notice and this permission notice +# appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +import struct + +import dns.exception +import dns.immutable +import dns.rdata +import dns.tokenizer + + +@dns.immutable.immutable +class ISDN(dns.rdata.Rdata): + """ISDN record""" + + # see: RFC 1183 + + __slots__ = ["address", "subaddress"] + + def __init__(self, rdclass, rdtype, address, subaddress): + super().__init__(rdclass, rdtype) + self.address = self._as_bytes(address, True, 255) + self.subaddress = self._as_bytes(subaddress, True, 255) + + def to_text(self, origin=None, relativize=True, **kw): + if self.subaddress: + return ( + f'"{dns.rdata._escapify(self.address)}" ' + f'"{dns.rdata._escapify(self.subaddress)}"' + ) + else: + return f'"{dns.rdata._escapify(self.address)}"' + + @classmethod + def from_text( + cls, rdclass, rdtype, tok, origin=None, relativize=True, relativize_to=None + ): + address = tok.get_string() + tokens = tok.get_remaining(max_tokens=1) + if len(tokens) >= 1: + subaddress = tokens[0].unescape().value + else: + subaddress = "" + return cls(rdclass, rdtype, address, subaddress) + + def _to_wire(self, file, compress=None, origin=None, canonicalize=False): + l = len(self.address) + assert l < 256 + file.write(struct.pack("!B", l)) + file.write(self.address) + l = len(self.subaddress) + if l > 0: + assert l < 256 + file.write(struct.pack("!B", l)) + file.write(self.subaddress) + + @classmethod + def from_wire_parser(cls, rdclass, rdtype, parser, origin=None): + address = parser.get_counted_bytes() + if parser.remaining() > 0: + subaddress = parser.get_counted_bytes() + else: + subaddress = b"" + return cls(rdclass, rdtype, address, subaddress) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/L32.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/L32.py new file mode 100644 index 000000000..f51e5c790 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/L32.py @@ -0,0 +1,42 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +import struct + +import dns.immutable +import dns.ipv4 +import dns.rdata + + +@dns.immutable.immutable +class L32(dns.rdata.Rdata): + """L32 record""" + + # see: rfc6742.txt + + __slots__ = ["preference", "locator32"] + + def __init__(self, rdclass, rdtype, preference, locator32): + super().__init__(rdclass, rdtype) + self.preference = self._as_uint16(preference) + self.locator32 = self._as_ipv4_address(locator32) + + def to_text(self, origin=None, relativize=True, **kw): + return f"{self.preference} {self.locator32}" + + @classmethod + def from_text( + cls, rdclass, rdtype, tok, origin=None, relativize=True, relativize_to=None + ): + preference = tok.get_uint16() + nodeid = tok.get_identifier() + return cls(rdclass, rdtype, preference, nodeid) + + def _to_wire(self, file, compress=None, origin=None, canonicalize=False): + file.write(struct.pack("!H", self.preference)) + file.write(dns.ipv4.inet_aton(self.locator32)) + + @classmethod + def from_wire_parser(cls, rdclass, rdtype, parser, origin=None): + preference = parser.get_uint16() + locator32 = parser.get_remaining() + return cls(rdclass, rdtype, preference, locator32) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/L64.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/L64.py new file mode 100644 index 000000000..a47da19e1 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/L64.py @@ -0,0 +1,48 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +import struct + +import dns.immutable +import dns.rdata +import dns.rdtypes.util + + +@dns.immutable.immutable +class L64(dns.rdata.Rdata): + """L64 record""" + + # see: rfc6742.txt + + __slots__ = ["preference", "locator64"] + + def __init__(self, rdclass, rdtype, preference, locator64): + super().__init__(rdclass, rdtype) + self.preference = self._as_uint16(preference) + if isinstance(locator64, bytes): + if len(locator64) != 8: + raise ValueError("invalid locator64") + self.locator64 = dns.rdata._hexify(locator64, 4, b":") + else: + dns.rdtypes.util.parse_formatted_hex(locator64, 4, 4, ":") + self.locator64 = locator64 + + def to_text(self, origin=None, relativize=True, **kw): + return f"{self.preference} {self.locator64}" + + @classmethod + def from_text( + cls, rdclass, rdtype, tok, origin=None, relativize=True, relativize_to=None + ): + preference = tok.get_uint16() + locator64 = tok.get_identifier() + return cls(rdclass, rdtype, preference, locator64) + + def _to_wire(self, file, compress=None, origin=None, canonicalize=False): + file.write(struct.pack("!H", self.preference)) + file.write(dns.rdtypes.util.parse_formatted_hex(self.locator64, 4, 4, ":")) + + @classmethod + def from_wire_parser(cls, rdclass, rdtype, parser, origin=None): + preference = parser.get_uint16() + locator64 = parser.get_remaining() + return cls(rdclass, rdtype, preference, locator64) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/LOC.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/LOC.py new file mode 100644 index 000000000..6c7fe5e79 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/LOC.py @@ -0,0 +1,347 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. +# +# Permission to use, copy, modify, and distribute this software and its +# documentation for any purpose with or without fee is hereby granted, +# provided that the above copyright notice and this permission notice +# appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +import struct + +import dns.exception +import dns.immutable +import dns.rdata + +_pows = tuple(10**i for i in range(0, 11)) + +# default values are in centimeters +_default_size = 100.0 +_default_hprec = 1000000.0 +_default_vprec = 1000.0 + +# for use by from_wire() +_MAX_LATITUDE = 0x80000000 + 90 * 3600000 +_MIN_LATITUDE = 0x80000000 - 90 * 3600000 +_MAX_LONGITUDE = 0x80000000 + 180 * 3600000 +_MIN_LONGITUDE = 0x80000000 - 180 * 3600000 + + +def _exponent_of(what, desc): + if what == 0: + return 0 + exp = None + for i, pow in enumerate(_pows): + if what < pow: + exp = i - 1 + break + if exp is None or exp < 0: + raise dns.exception.SyntaxError(f"{desc} value out of bounds") + return exp + + +def _float_to_tuple(what): + if what < 0: + sign = -1 + what *= -1 + else: + sign = 1 + what = round(what * 3600000) + degrees = int(what // 3600000) + what -= degrees * 3600000 + minutes = int(what // 60000) + what -= minutes * 60000 + seconds = int(what // 1000) + what -= int(seconds * 1000) + what = int(what) + return (degrees, minutes, seconds, what, sign) + + +def _tuple_to_float(what): + value = float(what[0]) + value += float(what[1]) / 60.0 + value += float(what[2]) / 3600.0 + value += float(what[3]) / 3600000.0 + return float(what[4]) * value + + +def _encode_size(what, desc): + what = int(what) + exponent = _exponent_of(what, desc) & 0xF + base = what // pow(10, exponent) & 0xF + return base * 16 + exponent + + +def _decode_size(what, desc): + exponent = what & 0x0F + if exponent > 9: + raise dns.exception.FormError(f"bad {desc} exponent") + base = (what & 0xF0) >> 4 + if base > 9: + raise dns.exception.FormError(f"bad {desc} base") + return base * pow(10, exponent) + + +def _check_coordinate_list(value, low, high): + if value[0] < low or value[0] > high: + raise ValueError(f"not in range [{low}, {high}]") + if value[1] < 0 or value[1] > 59: + raise ValueError("bad minutes value") + if value[2] < 0 or value[2] > 59: + raise ValueError("bad seconds value") + if value[3] < 0 or value[3] > 999: + raise ValueError("bad milliseconds value") + if value[4] != 1 and value[4] != -1: + raise ValueError("bad hemisphere value") + + +@dns.immutable.immutable +class LOC(dns.rdata.Rdata): + """LOC record""" + + # see: RFC 1876 + + __slots__ = [ + "latitude", + "longitude", + "altitude", + "size", + "horizontal_precision", + "vertical_precision", + ] + + def __init__( + self, + rdclass, + rdtype, + latitude, + longitude, + altitude, + size=_default_size, + hprec=_default_hprec, + vprec=_default_vprec, + ): + """Initialize a LOC record instance. + + The parameters I{latitude} and I{longitude} may be either a 4-tuple + of integers specifying (degrees, minutes, seconds, milliseconds), + or they may be floating point values specifying the number of + degrees. The other parameters are floats. Size, horizontal precision, + and vertical precision are specified in centimeters.""" + + super().__init__(rdclass, rdtype) + if isinstance(latitude, int): + latitude = float(latitude) + if isinstance(latitude, float): + latitude = _float_to_tuple(latitude) + _check_coordinate_list(latitude, -90, 90) + self.latitude = tuple(latitude) # pyright: ignore + if isinstance(longitude, int): + longitude = float(longitude) + if isinstance(longitude, float): + longitude = _float_to_tuple(longitude) + _check_coordinate_list(longitude, -180, 180) + self.longitude = tuple(longitude) # pyright: ignore + self.altitude = float(altitude) + self.size = float(size) + self.horizontal_precision = float(hprec) + self.vertical_precision = float(vprec) + + def to_text(self, origin=None, relativize=True, **kw): + if self.latitude[4] > 0: + lat_hemisphere = "N" + else: + lat_hemisphere = "S" + if self.longitude[4] > 0: + long_hemisphere = "E" + else: + long_hemisphere = "W" + text = ( + f"{self.latitude[0]} {self.latitude[1]} " + f"{self.latitude[2]}.{self.latitude[3]:03d} {lat_hemisphere} " + f"{self.longitude[0]} {self.longitude[1]} " + f"{self.longitude[2]}.{self.longitude[3]:03d} {long_hemisphere} " + f"{(self.altitude / 100.0):0.2f}m" + ) + + # do not print default values + if ( + self.size != _default_size + or self.horizontal_precision != _default_hprec + or self.vertical_precision != _default_vprec + ): + text += ( + f" {self.size / 100.0:0.2f}m {self.horizontal_precision / 100.0:0.2f}m" + f" {self.vertical_precision / 100.0:0.2f}m" + ) + return text + + @classmethod + def from_text( + cls, rdclass, rdtype, tok, origin=None, relativize=True, relativize_to=None + ): + latitude = [0, 0, 0, 0, 1] + longitude = [0, 0, 0, 0, 1] + size = _default_size + hprec = _default_hprec + vprec = _default_vprec + + latitude[0] = tok.get_int() + t = tok.get_string() + if t.isdigit(): + latitude[1] = int(t) + t = tok.get_string() + if "." in t: + (seconds, milliseconds) = t.split(".") + if not seconds.isdigit(): + raise dns.exception.SyntaxError("bad latitude seconds value") + latitude[2] = int(seconds) + l = len(milliseconds) + if l == 0 or l > 3 or not milliseconds.isdigit(): + raise dns.exception.SyntaxError("bad latitude milliseconds value") + if l == 1: + m = 100 + elif l == 2: + m = 10 + else: + m = 1 + latitude[3] = m * int(milliseconds) + t = tok.get_string() + elif t.isdigit(): + latitude[2] = int(t) + t = tok.get_string() + if t == "S": + latitude[4] = -1 + elif t != "N": + raise dns.exception.SyntaxError("bad latitude hemisphere value") + + longitude[0] = tok.get_int() + t = tok.get_string() + if t.isdigit(): + longitude[1] = int(t) + t = tok.get_string() + if "." in t: + (seconds, milliseconds) = t.split(".") + if not seconds.isdigit(): + raise dns.exception.SyntaxError("bad longitude seconds value") + longitude[2] = int(seconds) + l = len(milliseconds) + if l == 0 or l > 3 or not milliseconds.isdigit(): + raise dns.exception.SyntaxError("bad longitude milliseconds value") + if l == 1: + m = 100 + elif l == 2: + m = 10 + else: + m = 1 + longitude[3] = m * int(milliseconds) + t = tok.get_string() + elif t.isdigit(): + longitude[2] = int(t) + t = tok.get_string() + if t == "W": + longitude[4] = -1 + elif t != "E": + raise dns.exception.SyntaxError("bad longitude hemisphere value") + + t = tok.get_string() + if t[-1] == "m": + t = t[0:-1] + altitude = float(t) * 100.0 # m -> cm + + tokens = tok.get_remaining(max_tokens=3) + if len(tokens) >= 1: + value = tokens[0].unescape().value + if value[-1] == "m": + value = value[0:-1] + size = float(value) * 100.0 # m -> cm + if len(tokens) >= 2: + value = tokens[1].unescape().value + if value[-1] == "m": + value = value[0:-1] + hprec = float(value) * 100.0 # m -> cm + if len(tokens) >= 3: + value = tokens[2].unescape().value + if value[-1] == "m": + value = value[0:-1] + vprec = float(value) * 100.0 # m -> cm + + # Try encoding these now so we raise if they are bad + _encode_size(size, "size") + _encode_size(hprec, "horizontal precision") + _encode_size(vprec, "vertical precision") + + return cls(rdclass, rdtype, latitude, longitude, altitude, size, hprec, vprec) + + def _to_wire(self, file, compress=None, origin=None, canonicalize=False): + milliseconds = ( + self.latitude[0] * 3600000 + + self.latitude[1] * 60000 + + self.latitude[2] * 1000 + + self.latitude[3] + ) * self.latitude[4] + latitude = 0x80000000 + milliseconds + milliseconds = ( + self.longitude[0] * 3600000 + + self.longitude[1] * 60000 + + self.longitude[2] * 1000 + + self.longitude[3] + ) * self.longitude[4] + longitude = 0x80000000 + milliseconds + altitude = int(self.altitude) + 10000000 + size = _encode_size(self.size, "size") + hprec = _encode_size(self.horizontal_precision, "horizontal precision") + vprec = _encode_size(self.vertical_precision, "vertical precision") + wire = struct.pack( + "!BBBBIII", 0, size, hprec, vprec, latitude, longitude, altitude + ) + file.write(wire) + + @classmethod + def from_wire_parser(cls, rdclass, rdtype, parser, origin=None): + ( + version, + size, + hprec, + vprec, + latitude, + longitude, + altitude, + ) = parser.get_struct("!BBBBIII") + if version != 0: + raise dns.exception.FormError("LOC version not zero") + if latitude < _MIN_LATITUDE or latitude > _MAX_LATITUDE: + raise dns.exception.FormError("bad latitude") + if latitude > 0x80000000: + latitude = (latitude - 0x80000000) / 3600000 + else: + latitude = -1 * (0x80000000 - latitude) / 3600000 + if longitude < _MIN_LONGITUDE or longitude > _MAX_LONGITUDE: + raise dns.exception.FormError("bad longitude") + if longitude > 0x80000000: + longitude = (longitude - 0x80000000) / 3600000 + else: + longitude = -1 * (0x80000000 - longitude) / 3600000 + altitude = float(altitude) - 10000000.0 + size = _decode_size(size, "size") + hprec = _decode_size(hprec, "horizontal precision") + vprec = _decode_size(vprec, "vertical precision") + return cls(rdclass, rdtype, latitude, longitude, altitude, size, hprec, vprec) + + @property + def float_latitude(self): + "latitude as a floating point value" + return _tuple_to_float(self.latitude) + + @property + def float_longitude(self): + "longitude as a floating point value" + return _tuple_to_float(self.longitude) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/LP.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/LP.py new file mode 100644 index 000000000..379c8627a --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/LP.py @@ -0,0 +1,42 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +import struct + +import dns.immutable +import dns.rdata + + +@dns.immutable.immutable +class LP(dns.rdata.Rdata): + """LP record""" + + # see: rfc6742.txt + + __slots__ = ["preference", "fqdn"] + + def __init__(self, rdclass, rdtype, preference, fqdn): + super().__init__(rdclass, rdtype) + self.preference = self._as_uint16(preference) + self.fqdn = self._as_name(fqdn) + + def to_text(self, origin=None, relativize=True, **kw): + fqdn = self.fqdn.choose_relativity(origin, relativize) + return f"{self.preference} {fqdn}" + + @classmethod + def from_text( + cls, rdclass, rdtype, tok, origin=None, relativize=True, relativize_to=None + ): + preference = tok.get_uint16() + fqdn = tok.get_name(origin, relativize, relativize_to) + return cls(rdclass, rdtype, preference, fqdn) + + def _to_wire(self, file, compress=None, origin=None, canonicalize=False): + file.write(struct.pack("!H", self.preference)) + self.fqdn.to_wire(file, compress, origin, canonicalize) + + @classmethod + def from_wire_parser(cls, rdclass, rdtype, parser, origin=None): + preference = parser.get_uint16() + fqdn = parser.get_name(origin) + return cls(rdclass, rdtype, preference, fqdn) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/MX.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/MX.py new file mode 100644 index 000000000..0c300c5aa --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/MX.py @@ -0,0 +1,24 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. +# +# Permission to use, copy, modify, and distribute this software and its +# documentation for any purpose with or without fee is hereby granted, +# provided that the above copyright notice and this permission notice +# appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +import dns.immutable +import dns.rdtypes.mxbase + + +@dns.immutable.immutable +class MX(dns.rdtypes.mxbase.MXBase): + """MX record""" diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/NID.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/NID.py new file mode 100644 index 000000000..fa0dad5cc --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/NID.py @@ -0,0 +1,48 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +import struct + +import dns.immutable +import dns.rdata +import dns.rdtypes.util + + +@dns.immutable.immutable +class NID(dns.rdata.Rdata): + """NID record""" + + # see: rfc6742.txt + + __slots__ = ["preference", "nodeid"] + + def __init__(self, rdclass, rdtype, preference, nodeid): + super().__init__(rdclass, rdtype) + self.preference = self._as_uint16(preference) + if isinstance(nodeid, bytes): + if len(nodeid) != 8: + raise ValueError("invalid nodeid") + self.nodeid = dns.rdata._hexify(nodeid, 4, b":") + else: + dns.rdtypes.util.parse_formatted_hex(nodeid, 4, 4, ":") + self.nodeid = nodeid + + def to_text(self, origin=None, relativize=True, **kw): + return f"{self.preference} {self.nodeid}" + + @classmethod + def from_text( + cls, rdclass, rdtype, tok, origin=None, relativize=True, relativize_to=None + ): + preference = tok.get_uint16() + nodeid = tok.get_identifier() + return cls(rdclass, rdtype, preference, nodeid) + + def _to_wire(self, file, compress=None, origin=None, canonicalize=False): + file.write(struct.pack("!H", self.preference)) + file.write(dns.rdtypes.util.parse_formatted_hex(self.nodeid, 4, 4, ":")) + + @classmethod + def from_wire_parser(cls, rdclass, rdtype, parser, origin=None): + preference = parser.get_uint16() + nodeid = parser.get_remaining() + return cls(rdclass, rdtype, preference, nodeid) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/NINFO.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/NINFO.py new file mode 100644 index 000000000..b177bddbd --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/NINFO.py @@ -0,0 +1,26 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +# Copyright (C) 2006, 2007, 2009-2011 Nominum, Inc. +# +# Permission to use, copy, modify, and distribute this software and its +# documentation for any purpose with or without fee is hereby granted, +# provided that the above copyright notice and this permission notice +# appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +import dns.immutable +import dns.rdtypes.txtbase + + +@dns.immutable.immutable +class NINFO(dns.rdtypes.txtbase.TXTBase): + """NINFO record""" + + # see: draft-reid-dnsext-zs-01 diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/NS.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/NS.py new file mode 100644 index 000000000..c3f34ce90 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/NS.py @@ -0,0 +1,24 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. +# +# Permission to use, copy, modify, and distribute this software and its +# documentation for any purpose with or without fee is hereby granted, +# provided that the above copyright notice and this permission notice +# appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +import dns.immutable +import dns.rdtypes.nsbase + + +@dns.immutable.immutable +class NS(dns.rdtypes.nsbase.NSBase): + """NS record""" diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/NSEC.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/NSEC.py new file mode 100644 index 000000000..3c78b7228 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/NSEC.py @@ -0,0 +1,67 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +# Copyright (C) 2004-2007, 2009-2011 Nominum, Inc. +# +# Permission to use, copy, modify, and distribute this software and its +# documentation for any purpose with or without fee is hereby granted, +# provided that the above copyright notice and this permission notice +# appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +import dns.exception +import dns.immutable +import dns.name +import dns.rdata +import dns.rdatatype +import dns.rdtypes.util + + +@dns.immutable.immutable +class Bitmap(dns.rdtypes.util.Bitmap): + type_name = "NSEC" + + +@dns.immutable.immutable +class NSEC(dns.rdata.Rdata): + """NSEC record""" + + __slots__ = ["next", "windows"] + + def __init__(self, rdclass, rdtype, next, windows): + super().__init__(rdclass, rdtype) + self.next = self._as_name(next) + if not isinstance(windows, Bitmap): + windows = Bitmap(windows) + self.windows = tuple(windows.windows) + + def to_text(self, origin=None, relativize=True, **kw): + next = self.next.choose_relativity(origin, relativize) + text = Bitmap(self.windows).to_text() + return f"{next}{text}" + + @classmethod + def from_text( + cls, rdclass, rdtype, tok, origin=None, relativize=True, relativize_to=None + ): + next = tok.get_name(origin, relativize, relativize_to) + windows = Bitmap.from_text(tok) + return cls(rdclass, rdtype, next, windows) + + def _to_wire(self, file, compress=None, origin=None, canonicalize=False): + # Note that NSEC downcasing, originally mandated by RFC 4034 + # section 6.2 was removed by RFC 6840 section 5.1. + self.next.to_wire(file, None, origin, False) + Bitmap(self.windows).to_wire(file) + + @classmethod + def from_wire_parser(cls, rdclass, rdtype, parser, origin=None): + next = parser.get_name(origin) + bitmap = Bitmap.from_wire_parser(parser) + return cls(rdclass, rdtype, next, bitmap) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/NSEC3.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/NSEC3.py new file mode 100644 index 000000000..689941876 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/NSEC3.py @@ -0,0 +1,120 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +# Copyright (C) 2004-2017 Nominum, Inc. +# +# Permission to use, copy, modify, and distribute this software and its +# documentation for any purpose with or without fee is hereby granted, +# provided that the above copyright notice and this permission notice +# appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +import base64 +import binascii +import struct + +import dns.exception +import dns.immutable +import dns.name +import dns.rdata +import dns.rdatatype +import dns.rdtypes.util + +b32_hex_to_normal = bytes.maketrans( + b"0123456789ABCDEFGHIJKLMNOPQRSTUV", b"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567" +) +b32_normal_to_hex = bytes.maketrans( + b"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567", b"0123456789ABCDEFGHIJKLMNOPQRSTUV" +) + +# hash algorithm constants +SHA1 = 1 + +# flag constants +OPTOUT = 1 + + +@dns.immutable.immutable +class Bitmap(dns.rdtypes.util.Bitmap): + type_name = "NSEC3" + + +@dns.immutable.immutable +class NSEC3(dns.rdata.Rdata): + """NSEC3 record""" + + __slots__ = ["algorithm", "flags", "iterations", "salt", "next", "windows"] + + def __init__( + self, rdclass, rdtype, algorithm, flags, iterations, salt, next, windows + ): + super().__init__(rdclass, rdtype) + self.algorithm = self._as_uint8(algorithm) + self.flags = self._as_uint8(flags) + self.iterations = self._as_uint16(iterations) + self.salt = self._as_bytes(salt, True, 255) + self.next = self._as_bytes(next, True, 255) + if not isinstance(windows, Bitmap): + windows = Bitmap(windows) + self.windows = tuple(windows.windows) + + def _next_text(self): + next = base64.b32encode(self.next).translate(b32_normal_to_hex).lower().decode() + next = next.rstrip("=") + return next + + def to_text(self, origin=None, relativize=True, **kw): + next = self._next_text() + if self.salt == b"": + salt = "-" + else: + salt = binascii.hexlify(self.salt).decode() + text = Bitmap(self.windows).to_text() + return f"{self.algorithm} {self.flags} {self.iterations} {salt} {next}{text}" + + @classmethod + def from_text( + cls, rdclass, rdtype, tok, origin=None, relativize=True, relativize_to=None + ): + algorithm = tok.get_uint8() + flags = tok.get_uint8() + iterations = tok.get_uint16() + salt = tok.get_string() + if salt == "-": + salt = b"" + else: + salt = binascii.unhexlify(salt.encode("ascii")) + next = tok.get_string().encode("ascii").upper().translate(b32_hex_to_normal) + if next.endswith(b"="): + raise binascii.Error("Incorrect padding") + if len(next) % 8 != 0: + next += b"=" * (8 - len(next) % 8) + next = base64.b32decode(next) + bitmap = Bitmap.from_text(tok) + return cls(rdclass, rdtype, algorithm, flags, iterations, salt, next, bitmap) + + def _to_wire(self, file, compress=None, origin=None, canonicalize=False): + l = len(self.salt) + file.write(struct.pack("!BBHB", self.algorithm, self.flags, self.iterations, l)) + file.write(self.salt) + l = len(self.next) + file.write(struct.pack("!B", l)) + file.write(self.next) + Bitmap(self.windows).to_wire(file) + + @classmethod + def from_wire_parser(cls, rdclass, rdtype, parser, origin=None): + (algorithm, flags, iterations) = parser.get_struct("!BBH") + salt = parser.get_counted_bytes() + next = parser.get_counted_bytes() + bitmap = Bitmap.from_wire_parser(parser) + return cls(rdclass, rdtype, algorithm, flags, iterations, salt, next, bitmap) + + def next_name(self, origin=None): + return dns.name.from_text(self._next_text(), origin) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/NSEC3PARAM.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/NSEC3PARAM.py new file mode 100644 index 000000000..e8678722c --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/NSEC3PARAM.py @@ -0,0 +1,69 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +# Copyright (C) 2004-2007, 2009-2011 Nominum, Inc. +# +# Permission to use, copy, modify, and distribute this software and its +# documentation for any purpose with or without fee is hereby granted, +# provided that the above copyright notice and this permission notice +# appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +import binascii +import struct + +import dns.exception +import dns.immutable +import dns.rdata + + +@dns.immutable.immutable +class NSEC3PARAM(dns.rdata.Rdata): + """NSEC3PARAM record""" + + __slots__ = ["algorithm", "flags", "iterations", "salt"] + + def __init__(self, rdclass, rdtype, algorithm, flags, iterations, salt): + super().__init__(rdclass, rdtype) + self.algorithm = self._as_uint8(algorithm) + self.flags = self._as_uint8(flags) + self.iterations = self._as_uint16(iterations) + self.salt = self._as_bytes(salt, True, 255) + + def to_text(self, origin=None, relativize=True, **kw): + if self.salt == b"": + salt = "-" + else: + salt = binascii.hexlify(self.salt).decode() + return f"{self.algorithm} {self.flags} {self.iterations} {salt}" + + @classmethod + def from_text( + cls, rdclass, rdtype, tok, origin=None, relativize=True, relativize_to=None + ): + algorithm = tok.get_uint8() + flags = tok.get_uint8() + iterations = tok.get_uint16() + salt = tok.get_string() + if salt == "-": + salt = "" + else: + salt = binascii.unhexlify(salt.encode()) + return cls(rdclass, rdtype, algorithm, flags, iterations, salt) + + def _to_wire(self, file, compress=None, origin=None, canonicalize=False): + l = len(self.salt) + file.write(struct.pack("!BBHB", self.algorithm, self.flags, self.iterations, l)) + file.write(self.salt) + + @classmethod + def from_wire_parser(cls, rdclass, rdtype, parser, origin=None): + (algorithm, flags, iterations) = parser.get_struct("!BBH") + salt = parser.get_counted_bytes() + return cls(rdclass, rdtype, algorithm, flags, iterations, salt) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/OPENPGPKEY.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/OPENPGPKEY.py new file mode 100644 index 000000000..ac1841cce --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/OPENPGPKEY.py @@ -0,0 +1,53 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +# Copyright (C) 2016 Nominum, Inc. +# +# Permission to use, copy, modify, and distribute this software and its +# documentation for any purpose with or without fee is hereby granted, +# provided that the above copyright notice and this permission notice +# appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +import base64 + +import dns.exception +import dns.immutable +import dns.rdata +import dns.tokenizer + + +@dns.immutable.immutable +class OPENPGPKEY(dns.rdata.Rdata): + """OPENPGPKEY record""" + + # see: RFC 7929 + + def __init__(self, rdclass, rdtype, key): + super().__init__(rdclass, rdtype) + self.key = self._as_bytes(key) + + def to_text(self, origin=None, relativize=True, **kw): + return dns.rdata._base64ify(self.key, chunksize=None, **kw) # pyright: ignore + + @classmethod + def from_text( + cls, rdclass, rdtype, tok, origin=None, relativize=True, relativize_to=None + ): + b64 = tok.concatenate_remaining_identifiers().encode() + key = base64.b64decode(b64) + return cls(rdclass, rdtype, key) + + def _to_wire(self, file, compress=None, origin=None, canonicalize=False): + file.write(self.key) + + @classmethod + def from_wire_parser(cls, rdclass, rdtype, parser, origin=None): + key = parser.get_remaining() + return cls(rdclass, rdtype, key) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/OPT.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/OPT.py new file mode 100644 index 000000000..d343dfa5d --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/OPT.py @@ -0,0 +1,77 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +# Copyright (C) 2001-2017 Nominum, Inc. +# +# Permission to use, copy, modify, and distribute this software and its +# documentation for any purpose with or without fee is hereby granted, +# provided that the above copyright notice and this permission notice +# appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +import struct + +import dns.edns +import dns.exception +import dns.immutable +import dns.rdata + +# We don't implement from_text, and that's ok. +# pylint: disable=abstract-method + + +@dns.immutable.immutable +class OPT(dns.rdata.Rdata): + """OPT record""" + + __slots__ = ["options"] + + def __init__(self, rdclass, rdtype, options): + """Initialize an OPT rdata. + + *rdclass*, an ``int`` is the rdataclass of the Rdata, + which is also the payload size. + + *rdtype*, an ``int`` is the rdatatype of the Rdata. + + *options*, a tuple of ``bytes`` + """ + + super().__init__(rdclass, rdtype) + + def as_option(option): + if not isinstance(option, dns.edns.Option): + raise ValueError("option is not a dns.edns.option") + return option + + self.options = self._as_tuple(options, as_option) + + def _to_wire(self, file, compress=None, origin=None, canonicalize=False): + for opt in self.options: + owire = opt.to_wire() + file.write(struct.pack("!HH", opt.otype, len(owire))) + file.write(owire) + + def to_text(self, origin=None, relativize=True, **kw): + return " ".join(opt.to_text() for opt in self.options) + + @classmethod + def from_wire_parser(cls, rdclass, rdtype, parser, origin=None): + options = [] + while parser.remaining() > 0: + (otype, olen) = parser.get_struct("!HH") + with parser.restrict_to(olen): + opt = dns.edns.option_from_wire_parser(otype, parser) + options.append(opt) + return cls(rdclass, rdtype, options) + + @property + def payload(self): + "payload size" + return self.rdclass diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/PTR.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/PTR.py new file mode 100644 index 000000000..98c361677 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/PTR.py @@ -0,0 +1,24 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. +# +# Permission to use, copy, modify, and distribute this software and its +# documentation for any purpose with or without fee is hereby granted, +# provided that the above copyright notice and this permission notice +# appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +import dns.immutable +import dns.rdtypes.nsbase + + +@dns.immutable.immutable +class PTR(dns.rdtypes.nsbase.NSBase): + """PTR record""" diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/RESINFO.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/RESINFO.py new file mode 100644 index 000000000..76c8ea2ac --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/RESINFO.py @@ -0,0 +1,24 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. +# +# Permission to use, copy, modify, and distribute this software and its +# documentation for any purpose with or without fee is hereby granted, +# provided that the above copyright notice and this permission notice +# appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +import dns.immutable +import dns.rdtypes.txtbase + + +@dns.immutable.immutable +class RESINFO(dns.rdtypes.txtbase.TXTBase): + """RESINFO record""" diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/RP.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/RP.py new file mode 100644 index 000000000..a66cfc50f --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/RP.py @@ -0,0 +1,58 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. +# +# Permission to use, copy, modify, and distribute this software and its +# documentation for any purpose with or without fee is hereby granted, +# provided that the above copyright notice and this permission notice +# appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +import dns.exception +import dns.immutable +import dns.name +import dns.rdata + + +@dns.immutable.immutable +class RP(dns.rdata.Rdata): + """RP record""" + + # see: RFC 1183 + + __slots__ = ["mbox", "txt"] + + def __init__(self, rdclass, rdtype, mbox, txt): + super().__init__(rdclass, rdtype) + self.mbox = self._as_name(mbox) + self.txt = self._as_name(txt) + + def to_text(self, origin=None, relativize=True, **kw): + mbox = self.mbox.choose_relativity(origin, relativize) + txt = self.txt.choose_relativity(origin, relativize) + return f"{str(mbox)} {str(txt)}" + + @classmethod + def from_text( + cls, rdclass, rdtype, tok, origin=None, relativize=True, relativize_to=None + ): + mbox = tok.get_name(origin, relativize, relativize_to) + txt = tok.get_name(origin, relativize, relativize_to) + return cls(rdclass, rdtype, mbox, txt) + + def _to_wire(self, file, compress=None, origin=None, canonicalize=False): + self.mbox.to_wire(file, None, origin, canonicalize) + self.txt.to_wire(file, None, origin, canonicalize) + + @classmethod + def from_wire_parser(cls, rdclass, rdtype, parser, origin=None): + mbox = parser.get_name(origin) + txt = parser.get_name(origin) + return cls(rdclass, rdtype, mbox, txt) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/RRSIG.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/RRSIG.py new file mode 100644 index 000000000..5556cbacc --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/RRSIG.py @@ -0,0 +1,155 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +# Copyright (C) 2004-2007, 2009-2011 Nominum, Inc. +# +# Permission to use, copy, modify, and distribute this software and its +# documentation for any purpose with or without fee is hereby granted, +# provided that the above copyright notice and this permission notice +# appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +import base64 +import calendar +import struct +import time + +import dns.dnssectypes +import dns.exception +import dns.immutable +import dns.rdata +import dns.rdatatype + + +class BadSigTime(dns.exception.DNSException): + """Time in DNS SIG or RRSIG resource record cannot be parsed.""" + + +def sigtime_to_posixtime(what): + if len(what) <= 10 and what.isdigit(): + return int(what) + if len(what) != 14: + raise BadSigTime + year = int(what[0:4]) + month = int(what[4:6]) + day = int(what[6:8]) + hour = int(what[8:10]) + minute = int(what[10:12]) + second = int(what[12:14]) + return calendar.timegm((year, month, day, hour, minute, second, 0, 0, 0)) + + +def posixtime_to_sigtime(what): + return time.strftime("%Y%m%d%H%M%S", time.gmtime(what)) + + +@dns.immutable.immutable +class RRSIG(dns.rdata.Rdata): + """RRSIG record""" + + __slots__ = [ + "type_covered", + "algorithm", + "labels", + "original_ttl", + "expiration", + "inception", + "key_tag", + "signer", + "signature", + ] + + def __init__( + self, + rdclass, + rdtype, + type_covered, + algorithm, + labels, + original_ttl, + expiration, + inception, + key_tag, + signer, + signature, + ): + super().__init__(rdclass, rdtype) + self.type_covered = self._as_rdatatype(type_covered) + self.algorithm = dns.dnssectypes.Algorithm.make(algorithm) + self.labels = self._as_uint8(labels) + self.original_ttl = self._as_ttl(original_ttl) + self.expiration = self._as_uint32(expiration) + self.inception = self._as_uint32(inception) + self.key_tag = self._as_uint16(key_tag) + self.signer = self._as_name(signer) + self.signature = self._as_bytes(signature) + + def covers(self): + return self.type_covered + + def to_text(self, origin=None, relativize=True, **kw): + return ( + f"{dns.rdatatype.to_text(self.type_covered)} " + f"{self.algorithm} {self.labels} {self.original_ttl} " + f"{posixtime_to_sigtime(self.expiration)} " + f"{posixtime_to_sigtime(self.inception)} " + f"{self.key_tag} " + f"{self.signer.choose_relativity(origin, relativize)} " + f"{dns.rdata._base64ify(self.signature, **kw)}" # pyright: ignore + ) + + @classmethod + def from_text( + cls, rdclass, rdtype, tok, origin=None, relativize=True, relativize_to=None + ): + type_covered = dns.rdatatype.from_text(tok.get_string()) + algorithm = dns.dnssectypes.Algorithm.from_text(tok.get_string()) + labels = tok.get_int() + original_ttl = tok.get_ttl() + expiration = sigtime_to_posixtime(tok.get_string()) + inception = sigtime_to_posixtime(tok.get_string()) + key_tag = tok.get_int() + signer = tok.get_name(origin, relativize, relativize_to) + b64 = tok.concatenate_remaining_identifiers().encode() + signature = base64.b64decode(b64) + return cls( + rdclass, + rdtype, + type_covered, + algorithm, + labels, + original_ttl, + expiration, + inception, + key_tag, + signer, + signature, + ) + + def _to_wire(self, file, compress=None, origin=None, canonicalize=False): + header = struct.pack( + "!HBBIIIH", + self.type_covered, + self.algorithm, + self.labels, + self.original_ttl, + self.expiration, + self.inception, + self.key_tag, + ) + file.write(header) + self.signer.to_wire(file, None, origin, canonicalize) + file.write(self.signature) + + @classmethod + def from_wire_parser(cls, rdclass, rdtype, parser, origin=None): + header = parser.get_struct("!HBBIIIH") + signer = parser.get_name(origin) + signature = parser.get_remaining() + return cls(rdclass, rdtype, *header, signer, signature) # pyright: ignore diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/RT.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/RT.py new file mode 100644 index 000000000..5a4d45cf1 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/RT.py @@ -0,0 +1,24 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. +# +# Permission to use, copy, modify, and distribute this software and its +# documentation for any purpose with or without fee is hereby granted, +# provided that the above copyright notice and this permission notice +# appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +import dns.immutable +import dns.rdtypes.mxbase + + +@dns.immutable.immutable +class RT(dns.rdtypes.mxbase.UncompressedDowncasingMX): + """RT record""" diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/SMIMEA.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/SMIMEA.py new file mode 100644 index 000000000..55d87bf85 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/SMIMEA.py @@ -0,0 +1,9 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +import dns.immutable +import dns.rdtypes.tlsabase + + +@dns.immutable.immutable +class SMIMEA(dns.rdtypes.tlsabase.TLSABase): + """SMIMEA record""" diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/SOA.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/SOA.py new file mode 100644 index 000000000..3c7cd8c92 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/SOA.py @@ -0,0 +1,78 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. +# +# Permission to use, copy, modify, and distribute this software and its +# documentation for any purpose with or without fee is hereby granted, +# provided that the above copyright notice and this permission notice +# appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +import struct + +import dns.exception +import dns.immutable +import dns.name +import dns.rdata + + +@dns.immutable.immutable +class SOA(dns.rdata.Rdata): + """SOA record""" + + # see: RFC 1035 + + __slots__ = ["mname", "rname", "serial", "refresh", "retry", "expire", "minimum"] + + def __init__( + self, rdclass, rdtype, mname, rname, serial, refresh, retry, expire, minimum + ): + super().__init__(rdclass, rdtype) + self.mname = self._as_name(mname) + self.rname = self._as_name(rname) + self.serial = self._as_uint32(serial) + self.refresh = self._as_ttl(refresh) + self.retry = self._as_ttl(retry) + self.expire = self._as_ttl(expire) + self.minimum = self._as_ttl(minimum) + + def to_text(self, origin=None, relativize=True, **kw): + mname = self.mname.choose_relativity(origin, relativize) + rname = self.rname.choose_relativity(origin, relativize) + return f"{mname} {rname} {self.serial} {self.refresh} {self.retry} {self.expire} {self.minimum}" + + @classmethod + def from_text( + cls, rdclass, rdtype, tok, origin=None, relativize=True, relativize_to=None + ): + mname = tok.get_name(origin, relativize, relativize_to) + rname = tok.get_name(origin, relativize, relativize_to) + serial = tok.get_uint32() + refresh = tok.get_ttl() + retry = tok.get_ttl() + expire = tok.get_ttl() + minimum = tok.get_ttl() + return cls( + rdclass, rdtype, mname, rname, serial, refresh, retry, expire, minimum + ) + + def _to_wire(self, file, compress=None, origin=None, canonicalize=False): + self.mname.to_wire(file, compress, origin, canonicalize) + self.rname.to_wire(file, compress, origin, canonicalize) + five_ints = struct.pack( + "!IIIII", self.serial, self.refresh, self.retry, self.expire, self.minimum + ) + file.write(five_ints) + + @classmethod + def from_wire_parser(cls, rdclass, rdtype, parser, origin=None): + mname = parser.get_name(origin) + rname = parser.get_name(origin) + return cls(rdclass, rdtype, mname, rname, *parser.get_struct("!IIIII")) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/SPF.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/SPF.py new file mode 100644 index 000000000..1df3b7055 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/SPF.py @@ -0,0 +1,26 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +# Copyright (C) 2006, 2007, 2009-2011 Nominum, Inc. +# +# Permission to use, copy, modify, and distribute this software and its +# documentation for any purpose with or without fee is hereby granted, +# provided that the above copyright notice and this permission notice +# appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +import dns.immutable +import dns.rdtypes.txtbase + + +@dns.immutable.immutable +class SPF(dns.rdtypes.txtbase.TXTBase): + """SPF record""" + + # see: RFC 4408 diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/SSHFP.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/SSHFP.py new file mode 100644 index 000000000..3f08f3a59 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/SSHFP.py @@ -0,0 +1,67 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +# Copyright (C) 2005-2007, 2009-2011 Nominum, Inc. +# +# Permission to use, copy, modify, and distribute this software and its +# documentation for any purpose with or without fee is hereby granted, +# provided that the above copyright notice and this permission notice +# appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +import binascii +import struct + +import dns.immutable +import dns.rdata +import dns.rdatatype + + +@dns.immutable.immutable +class SSHFP(dns.rdata.Rdata): + """SSHFP record""" + + # See RFC 4255 + + __slots__ = ["algorithm", "fp_type", "fingerprint"] + + def __init__(self, rdclass, rdtype, algorithm, fp_type, fingerprint): + super().__init__(rdclass, rdtype) + self.algorithm = self._as_uint8(algorithm) + self.fp_type = self._as_uint8(fp_type) + self.fingerprint = self._as_bytes(fingerprint, True) + + def to_text(self, origin=None, relativize=True, **kw): + kw = kw.copy() + chunksize = kw.pop("chunksize", 128) + fingerprint = dns.rdata._hexify( + self.fingerprint, chunksize=chunksize, **kw # pyright: ignore + ) + return f"{self.algorithm} {self.fp_type} {fingerprint}" + + @classmethod + def from_text( + cls, rdclass, rdtype, tok, origin=None, relativize=True, relativize_to=None + ): + algorithm = tok.get_uint8() + fp_type = tok.get_uint8() + fingerprint = tok.concatenate_remaining_identifiers().encode() + fingerprint = binascii.unhexlify(fingerprint) + return cls(rdclass, rdtype, algorithm, fp_type, fingerprint) + + def _to_wire(self, file, compress=None, origin=None, canonicalize=False): + header = struct.pack("!BB", self.algorithm, self.fp_type) + file.write(header) + file.write(self.fingerprint) + + @classmethod + def from_wire_parser(cls, rdclass, rdtype, parser, origin=None): + header = parser.get_struct("BB") + fingerprint = parser.get_remaining() + return cls(rdclass, rdtype, header[0], header[1], fingerprint) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/TKEY.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/TKEY.py new file mode 100644 index 000000000..f9189b16c --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/TKEY.py @@ -0,0 +1,135 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +# Copyright (C) 2004-2007, 2009-2011 Nominum, Inc. +# +# Permission to use, copy, modify, and distribute this software and its +# documentation for any purpose with or without fee is hereby granted, +# provided that the above copyright notice and this permission notice +# appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +import base64 +import struct + +import dns.exception +import dns.immutable +import dns.rdata + + +@dns.immutable.immutable +class TKEY(dns.rdata.Rdata): + """TKEY Record""" + + __slots__ = [ + "algorithm", + "inception", + "expiration", + "mode", + "error", + "key", + "other", + ] + + def __init__( + self, + rdclass, + rdtype, + algorithm, + inception, + expiration, + mode, + error, + key, + other=b"", + ): + super().__init__(rdclass, rdtype) + self.algorithm = self._as_name(algorithm) + self.inception = self._as_uint32(inception) + self.expiration = self._as_uint32(expiration) + self.mode = self._as_uint16(mode) + self.error = self._as_uint16(error) + self.key = self._as_bytes(key) + self.other = self._as_bytes(other) + + def to_text(self, origin=None, relativize=True, **kw): + _algorithm = self.algorithm.choose_relativity(origin, relativize) + key = dns.rdata._base64ify(self.key, 0) + other = "" + if len(self.other) > 0: + other = " " + dns.rdata._base64ify(self.other, 0) + return f"{_algorithm} {self.inception} {self.expiration} {self.mode} {self.error} {key}{other}" + + @classmethod + def from_text( + cls, rdclass, rdtype, tok, origin=None, relativize=True, relativize_to=None + ): + algorithm = tok.get_name(relativize=False) + inception = tok.get_uint32() + expiration = tok.get_uint32() + mode = tok.get_uint16() + error = tok.get_uint16() + key_b64 = tok.get_string().encode() + key = base64.b64decode(key_b64) + other_b64 = tok.concatenate_remaining_identifiers(True).encode() + other = base64.b64decode(other_b64) + + return cls( + rdclass, rdtype, algorithm, inception, expiration, mode, error, key, other + ) + + def _to_wire(self, file, compress=None, origin=None, canonicalize=False): + self.algorithm.to_wire(file, compress, origin) + file.write( + struct.pack("!IIHH", self.inception, self.expiration, self.mode, self.error) + ) + file.write(struct.pack("!H", len(self.key))) + file.write(self.key) + file.write(struct.pack("!H", len(self.other))) + if len(self.other) > 0: + file.write(self.other) + + @classmethod + def from_wire_parser(cls, rdclass, rdtype, parser, origin=None): + algorithm = parser.get_name(origin) + inception, expiration, mode, error = parser.get_struct("!IIHH") + key = parser.get_counted_bytes(2) + other = parser.get_counted_bytes(2) + + return cls( + rdclass, rdtype, algorithm, inception, expiration, mode, error, key, other + ) + + # Constants for the mode field - from RFC 2930: + # 2.5 The Mode Field + # + # The mode field specifies the general scheme for key agreement or + # the purpose of the TKEY DNS message. Servers and resolvers + # supporting this specification MUST implement the Diffie-Hellman key + # agreement mode and the key deletion mode for queries. All other + # modes are OPTIONAL. A server supporting TKEY that receives a TKEY + # request with a mode it does not support returns the BADMODE error. + # The following values of the Mode octet are defined, available, or + # reserved: + # + # Value Description + # ----- ----------- + # 0 - reserved, see section 7 + # 1 server assignment + # 2 Diffie-Hellman exchange + # 3 GSS-API negotiation + # 4 resolver assignment + # 5 key deletion + # 6-65534 - available, see section 7 + # 65535 - reserved, see section 7 + SERVER_ASSIGNMENT = 1 + DIFFIE_HELLMAN_EXCHANGE = 2 + GSSAPI_NEGOTIATION = 3 + RESOLVER_ASSIGNMENT = 4 + KEY_DELETION = 5 diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/TLSA.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/TLSA.py new file mode 100644 index 000000000..4dffc5534 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/TLSA.py @@ -0,0 +1,9 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +import dns.immutable +import dns.rdtypes.tlsabase + + +@dns.immutable.immutable +class TLSA(dns.rdtypes.tlsabase.TLSABase): + """TLSA record""" diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/TSIG.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/TSIG.py new file mode 100644 index 000000000..794238264 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/TSIG.py @@ -0,0 +1,160 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +# Copyright (C) 2001-2017 Nominum, Inc. +# +# Permission to use, copy, modify, and distribute this software and its +# documentation for any purpose with or without fee is hereby granted, +# provided that the above copyright notice and this permission notice +# appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +import base64 +import struct + +import dns.exception +import dns.immutable +import dns.rcode +import dns.rdata + + +@dns.immutable.immutable +class TSIG(dns.rdata.Rdata): + """TSIG record""" + + __slots__ = [ + "algorithm", + "time_signed", + "fudge", + "mac", + "original_id", + "error", + "other", + ] + + def __init__( + self, + rdclass, + rdtype, + algorithm, + time_signed, + fudge, + mac, + original_id, + error, + other, + ): + """Initialize a TSIG rdata. + + *rdclass*, an ``int`` is the rdataclass of the Rdata. + + *rdtype*, an ``int`` is the rdatatype of the Rdata. + + *algorithm*, a ``dns.name.Name``. + + *time_signed*, an ``int``. + + *fudge*, an ``int`. + + *mac*, a ``bytes`` + + *original_id*, an ``int`` + + *error*, an ``int`` + + *other*, a ``bytes`` + """ + + super().__init__(rdclass, rdtype) + self.algorithm = self._as_name(algorithm) + self.time_signed = self._as_uint48(time_signed) + self.fudge = self._as_uint16(fudge) + self.mac = self._as_bytes(mac) + self.original_id = self._as_uint16(original_id) + self.error = dns.rcode.Rcode.make(error) + self.other = self._as_bytes(other) + + def to_text(self, origin=None, relativize=True, **kw): + algorithm = self.algorithm.choose_relativity(origin, relativize) + error = dns.rcode.to_text(self.error, True) + text = ( + f"{algorithm} {self.time_signed} {self.fudge} " + + f"{len(self.mac)} {dns.rdata._base64ify(self.mac, 0)} " + + f"{self.original_id} {error} {len(self.other)}" + ) + if self.other: + text += f" {dns.rdata._base64ify(self.other, 0)}" + return text + + @classmethod + def from_text( + cls, rdclass, rdtype, tok, origin=None, relativize=True, relativize_to=None + ): + algorithm = tok.get_name(relativize=False) + time_signed = tok.get_uint48() + fudge = tok.get_uint16() + mac_len = tok.get_uint16() + mac = base64.b64decode(tok.get_string()) + if len(mac) != mac_len: + raise SyntaxError("invalid MAC") + original_id = tok.get_uint16() + error = dns.rcode.from_text(tok.get_string()) + other_len = tok.get_uint16() + if other_len > 0: + other = base64.b64decode(tok.get_string()) + if len(other) != other_len: + raise SyntaxError("invalid other data") + else: + other = b"" + return cls( + rdclass, + rdtype, + algorithm, + time_signed, + fudge, + mac, + original_id, + error, + other, + ) + + def _to_wire(self, file, compress=None, origin=None, canonicalize=False): + self.algorithm.to_wire(file, None, origin, False) + file.write( + struct.pack( + "!HIHH", + (self.time_signed >> 32) & 0xFFFF, + self.time_signed & 0xFFFFFFFF, + self.fudge, + len(self.mac), + ) + ) + file.write(self.mac) + file.write(struct.pack("!HHH", self.original_id, self.error, len(self.other))) + file.write(self.other) + + @classmethod + def from_wire_parser(cls, rdclass, rdtype, parser, origin=None): + algorithm = parser.get_name() + time_signed = parser.get_uint48() + fudge = parser.get_uint16() + mac = parser.get_counted_bytes(2) + (original_id, error) = parser.get_struct("!HH") + other = parser.get_counted_bytes(2) + return cls( + rdclass, + rdtype, + algorithm, + time_signed, + fudge, + mac, + original_id, + error, + other, + ) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/TXT.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/TXT.py new file mode 100644 index 000000000..6d4dae27a --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/TXT.py @@ -0,0 +1,24 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. +# +# Permission to use, copy, modify, and distribute this software and its +# documentation for any purpose with or without fee is hereby granted, +# provided that the above copyright notice and this permission notice +# appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +import dns.immutable +import dns.rdtypes.txtbase + + +@dns.immutable.immutable +class TXT(dns.rdtypes.txtbase.TXTBase): + """TXT record""" diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/URI.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/URI.py new file mode 100644 index 000000000..021391d68 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/URI.py @@ -0,0 +1,79 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. +# Copyright (C) 2015 Red Hat, Inc. +# +# Permission to use, copy, modify, and distribute this software and its +# documentation for any purpose with or without fee is hereby granted, +# provided that the above copyright notice and this permission notice +# appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +import struct + +import dns.exception +import dns.immutable +import dns.name +import dns.rdata +import dns.rdtypes.util + + +@dns.immutable.immutable +class URI(dns.rdata.Rdata): + """URI record""" + + # see RFC 7553 + + __slots__ = ["priority", "weight", "target"] + + def __init__(self, rdclass, rdtype, priority, weight, target): + super().__init__(rdclass, rdtype) + self.priority = self._as_uint16(priority) + self.weight = self._as_uint16(weight) + self.target = self._as_bytes(target, True) + if len(self.target) == 0: + raise dns.exception.SyntaxError("URI target cannot be empty") + + def to_text(self, origin=None, relativize=True, **kw): + return f'{self.priority} {self.weight} "{self.target.decode()}"' + + @classmethod + def from_text( + cls, rdclass, rdtype, tok, origin=None, relativize=True, relativize_to=None + ): + priority = tok.get_uint16() + weight = tok.get_uint16() + target = tok.get().unescape() + if not (target.is_quoted_string() or target.is_identifier()): + raise dns.exception.SyntaxError("URI target must be a string") + return cls(rdclass, rdtype, priority, weight, target.value) + + def _to_wire(self, file, compress=None, origin=None, canonicalize=False): + two_ints = struct.pack("!HH", self.priority, self.weight) + file.write(two_ints) + file.write(self.target) + + @classmethod + def from_wire_parser(cls, rdclass, rdtype, parser, origin=None): + (priority, weight) = parser.get_struct("!HH") + target = parser.get_remaining() + if len(target) == 0: + raise dns.exception.FormError("URI target may not be empty") + return cls(rdclass, rdtype, priority, weight, target) + + def _processing_priority(self): + return self.priority + + def _processing_weight(self): + return self.weight + + @classmethod + def _processing_order(cls, iterable): + return dns.rdtypes.util.weighted_processing_order(iterable) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/WALLET.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/WALLET.py new file mode 100644 index 000000000..ff4647632 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/WALLET.py @@ -0,0 +1,9 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +import dns.immutable +import dns.rdtypes.txtbase + + +@dns.immutable.immutable +class WALLET(dns.rdtypes.txtbase.TXTBase): + """WALLET record""" diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/X25.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/X25.py new file mode 100644 index 000000000..2436ddb62 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/X25.py @@ -0,0 +1,57 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. +# +# Permission to use, copy, modify, and distribute this software and its +# documentation for any purpose with or without fee is hereby granted, +# provided that the above copyright notice and this permission notice +# appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +import struct + +import dns.exception +import dns.immutable +import dns.rdata +import dns.tokenizer + + +@dns.immutable.immutable +class X25(dns.rdata.Rdata): + """X25 record""" + + # see RFC 1183 + + __slots__ = ["address"] + + def __init__(self, rdclass, rdtype, address): + super().__init__(rdclass, rdtype) + self.address = self._as_bytes(address, True, 255) + + def to_text(self, origin=None, relativize=True, **kw): + return f'"{dns.rdata._escapify(self.address)}"' + + @classmethod + def from_text( + cls, rdclass, rdtype, tok, origin=None, relativize=True, relativize_to=None + ): + address = tok.get_string() + return cls(rdclass, rdtype, address) + + def _to_wire(self, file, compress=None, origin=None, canonicalize=False): + l = len(self.address) + assert l < 256 + file.write(struct.pack("!B", l)) + file.write(self.address) + + @classmethod + def from_wire_parser(cls, rdclass, rdtype, parser, origin=None): + address = parser.get_counted_bytes() + return cls(rdclass, rdtype, address) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/ZONEMD.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/ZONEMD.py new file mode 100644 index 000000000..acef4f277 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/ZONEMD.py @@ -0,0 +1,64 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +import binascii +import struct + +import dns.immutable +import dns.rdata +import dns.rdatatype +import dns.zonetypes + + +@dns.immutable.immutable +class ZONEMD(dns.rdata.Rdata): + """ZONEMD record""" + + # See RFC 8976 + + __slots__ = ["serial", "scheme", "hash_algorithm", "digest"] + + def __init__(self, rdclass, rdtype, serial, scheme, hash_algorithm, digest): + super().__init__(rdclass, rdtype) + self.serial = self._as_uint32(serial) + self.scheme = dns.zonetypes.DigestScheme.make(scheme) + self.hash_algorithm = dns.zonetypes.DigestHashAlgorithm.make(hash_algorithm) + self.digest = self._as_bytes(digest) + + if self.scheme == 0: # reserved, RFC 8976 Sec. 5.2 + raise ValueError("scheme 0 is reserved") + if self.hash_algorithm == 0: # reserved, RFC 8976 Sec. 5.3 + raise ValueError("hash_algorithm 0 is reserved") + + hasher = dns.zonetypes._digest_hashers.get(self.hash_algorithm) + if hasher and hasher().digest_size != len(self.digest): + raise ValueError("digest length inconsistent with hash algorithm") + + def to_text(self, origin=None, relativize=True, **kw): + kw = kw.copy() + chunksize = kw.pop("chunksize", 128) + digest = dns.rdata._hexify( + self.digest, chunksize=chunksize, **kw # pyright: ignore + ) + return f"{self.serial} {self.scheme} {self.hash_algorithm} {digest}" + + @classmethod + def from_text( + cls, rdclass, rdtype, tok, origin=None, relativize=True, relativize_to=None + ): + serial = tok.get_uint32() + scheme = tok.get_uint8() + hash_algorithm = tok.get_uint8() + digest = tok.concatenate_remaining_identifiers().encode() + digest = binascii.unhexlify(digest) + return cls(rdclass, rdtype, serial, scheme, hash_algorithm, digest) + + def _to_wire(self, file, compress=None, origin=None, canonicalize=False): + header = struct.pack("!IBB", self.serial, self.scheme, self.hash_algorithm) + file.write(header) + file.write(self.digest) + + @classmethod + def from_wire_parser(cls, rdclass, rdtype, parser, origin=None): + header = parser.get_struct("!IBB") + digest = parser.get_remaining() + return cls(rdclass, rdtype, header[0], header[1], header[2], digest) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/__init__.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/__init__.py new file mode 100644 index 000000000..cc39f8642 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/ANY/__init__.py @@ -0,0 +1,71 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. +# +# Permission to use, copy, modify, and distribute this software and its +# documentation for any purpose with or without fee is hereby granted, +# provided that the above copyright notice and this permission notice +# appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +"""Class ANY (generic) rdata type classes.""" + +__all__ = [ + "AFSDB", + "AMTRELAY", + "AVC", + "CAA", + "CDNSKEY", + "CDS", + "CERT", + "CNAME", + "CSYNC", + "DLV", + "DNAME", + "DNSKEY", + "DS", + "DSYNC", + "EUI48", + "EUI64", + "GPOS", + "HINFO", + "HIP", + "ISDN", + "L32", + "L64", + "LOC", + "LP", + "MX", + "NID", + "NINFO", + "NS", + "NSEC", + "NSEC3", + "NSEC3PARAM", + "OPENPGPKEY", + "OPT", + "PTR", + "RESINFO", + "RP", + "RRSIG", + "RT", + "SMIMEA", + "SOA", + "SPF", + "SSHFP", + "TKEY", + "TLSA", + "TSIG", + "TXT", + "URI", + "WALLET", + "X25", + "ZONEMD", +] diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/CH/A.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/CH/A.py new file mode 100644 index 000000000..e3e075211 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/CH/A.py @@ -0,0 +1,60 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. +# +# Permission to use, copy, modify, and distribute this software and its +# documentation for any purpose with or without fee is hereby granted, +# provided that the above copyright notice and this permission notice +# appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +import struct + +import dns.immutable +import dns.rdata +import dns.rdtypes.mxbase + + +@dns.immutable.immutable +class A(dns.rdata.Rdata): + """A record for Chaosnet""" + + # domain: the domain of the address + # address: the 16-bit address + + __slots__ = ["domain", "address"] + + def __init__(self, rdclass, rdtype, domain, address): + super().__init__(rdclass, rdtype) + self.domain = self._as_name(domain) + self.address = self._as_uint16(address) + + def to_text(self, origin=None, relativize=True, **kw): + domain = self.domain.choose_relativity(origin, relativize) + return f"{domain} {self.address:o}" + + @classmethod + def from_text( + cls, rdclass, rdtype, tok, origin=None, relativize=True, relativize_to=None + ): + domain = tok.get_name(origin, relativize, relativize_to) + address = tok.get_uint16(base=8) + return cls(rdclass, rdtype, domain, address) + + def _to_wire(self, file, compress=None, origin=None, canonicalize=False): + self.domain.to_wire(file, compress, origin, canonicalize) + pref = struct.pack("!H", self.address) + file.write(pref) + + @classmethod + def from_wire_parser(cls, rdclass, rdtype, parser, origin=None): + domain = parser.get_name(origin) + address = parser.get_uint16() + return cls(rdclass, rdtype, domain, address) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/CH/__init__.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/CH/__init__.py new file mode 100644 index 000000000..0760c26c2 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/CH/__init__.py @@ -0,0 +1,22 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. +# +# Permission to use, copy, modify, and distribute this software and its +# documentation for any purpose with or without fee is hereby granted, +# provided that the above copyright notice and this permission notice +# appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +"""Class CH rdata type classes.""" + +__all__ = [ + "A", +] diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/IN/A.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/IN/A.py new file mode 100644 index 000000000..e09d61108 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/IN/A.py @@ -0,0 +1,51 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. +# +# Permission to use, copy, modify, and distribute this software and its +# documentation for any purpose with or without fee is hereby granted, +# provided that the above copyright notice and this permission notice +# appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +import dns.exception +import dns.immutable +import dns.ipv4 +import dns.rdata +import dns.tokenizer + + +@dns.immutable.immutable +class A(dns.rdata.Rdata): + """A record.""" + + __slots__ = ["address"] + + def __init__(self, rdclass, rdtype, address): + super().__init__(rdclass, rdtype) + self.address = self._as_ipv4_address(address) + + def to_text(self, origin=None, relativize=True, **kw): + return self.address + + @classmethod + def from_text( + cls, rdclass, rdtype, tok, origin=None, relativize=True, relativize_to=None + ): + address = tok.get_identifier() + return cls(rdclass, rdtype, address) + + def _to_wire(self, file, compress=None, origin=None, canonicalize=False): + file.write(dns.ipv4.inet_aton(self.address)) + + @classmethod + def from_wire_parser(cls, rdclass, rdtype, parser, origin=None): + address = parser.get_remaining() + return cls(rdclass, rdtype, address) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/IN/AAAA.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/IN/AAAA.py new file mode 100644 index 000000000..0cd139e7b --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/IN/AAAA.py @@ -0,0 +1,51 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. +# +# Permission to use, copy, modify, and distribute this software and its +# documentation for any purpose with or without fee is hereby granted, +# provided that the above copyright notice and this permission notice +# appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +import dns.exception +import dns.immutable +import dns.ipv6 +import dns.rdata +import dns.tokenizer + + +@dns.immutable.immutable +class AAAA(dns.rdata.Rdata): + """AAAA record.""" + + __slots__ = ["address"] + + def __init__(self, rdclass, rdtype, address): + super().__init__(rdclass, rdtype) + self.address = self._as_ipv6_address(address) + + def to_text(self, origin=None, relativize=True, **kw): + return self.address + + @classmethod + def from_text( + cls, rdclass, rdtype, tok, origin=None, relativize=True, relativize_to=None + ): + address = tok.get_identifier() + return cls(rdclass, rdtype, address) + + def _to_wire(self, file, compress=None, origin=None, canonicalize=False): + file.write(dns.ipv6.inet_aton(self.address)) + + @classmethod + def from_wire_parser(cls, rdclass, rdtype, parser, origin=None): + address = parser.get_remaining() + return cls(rdclass, rdtype, address) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/IN/APL.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/IN/APL.py new file mode 100644 index 000000000..c4ce6e458 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/IN/APL.py @@ -0,0 +1,150 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +# Copyright (C) 2003-2017 Nominum, Inc. +# +# Permission to use, copy, modify, and distribute this software and its +# documentation for any purpose with or without fee is hereby granted, +# provided that the above copyright notice and this permission notice +# appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +import binascii +import codecs +import struct + +import dns.exception +import dns.immutable +import dns.ipv4 +import dns.ipv6 +import dns.rdata +import dns.tokenizer + + +@dns.immutable.immutable +class APLItem: + """An APL list item.""" + + __slots__ = ["family", "negation", "address", "prefix"] + + def __init__(self, family, negation, address, prefix): + self.family = dns.rdata.Rdata._as_uint16(family) + self.negation = dns.rdata.Rdata._as_bool(negation) + if self.family == 1: + self.address = dns.rdata.Rdata._as_ipv4_address(address) + self.prefix = dns.rdata.Rdata._as_int(prefix, 0, 32) + elif self.family == 2: + self.address = dns.rdata.Rdata._as_ipv6_address(address) + self.prefix = dns.rdata.Rdata._as_int(prefix, 0, 128) + else: + self.address = dns.rdata.Rdata._as_bytes(address, max_length=127) + self.prefix = dns.rdata.Rdata._as_uint8(prefix) + + def __str__(self): + if self.negation: + return f"!{self.family}:{self.address}/{self.prefix}" + else: + return f"{self.family}:{self.address}/{self.prefix}" + + def to_wire(self, file): + if self.family == 1: + address = dns.ipv4.inet_aton(self.address) + elif self.family == 2: + address = dns.ipv6.inet_aton(self.address) + else: + address = binascii.unhexlify(self.address) + # + # Truncate least significant zero bytes. + # + last = 0 + for i in range(len(address) - 1, -1, -1): + if address[i] != 0: + last = i + 1 + break + address = address[0:last] + l = len(address) + assert l < 128 + if self.negation: + l |= 0x80 + header = struct.pack("!HBB", self.family, self.prefix, l) + file.write(header) + file.write(address) + + +@dns.immutable.immutable +class APL(dns.rdata.Rdata): + """APL record.""" + + # see: RFC 3123 + + __slots__ = ["items"] + + def __init__(self, rdclass, rdtype, items): + super().__init__(rdclass, rdtype) + for item in items: + if not isinstance(item, APLItem): + raise ValueError("item not an APLItem") + self.items = tuple(items) + + def to_text(self, origin=None, relativize=True, **kw): + return " ".join(map(str, self.items)) + + @classmethod + def from_text( + cls, rdclass, rdtype, tok, origin=None, relativize=True, relativize_to=None + ): + items = [] + for token in tok.get_remaining(): + item = token.unescape().value + if item[0] == "!": + negation = True + item = item[1:] + else: + negation = False + (family, rest) = item.split(":", 1) + family = int(family) + (address, prefix) = rest.split("/", 1) + prefix = int(prefix) + item = APLItem(family, negation, address, prefix) + items.append(item) + + return cls(rdclass, rdtype, items) + + def _to_wire(self, file, compress=None, origin=None, canonicalize=False): + for item in self.items: + item.to_wire(file) + + @classmethod + def from_wire_parser(cls, rdclass, rdtype, parser, origin=None): + items = [] + while parser.remaining() > 0: + header = parser.get_struct("!HBB") + afdlen = header[2] + if afdlen > 127: + negation = True + afdlen -= 128 + else: + negation = False + address = parser.get_bytes(afdlen) + l = len(address) + if header[0] == 1: + if l < 4: + address += b"\x00" * (4 - l) + elif header[0] == 2: + if l < 16: + address += b"\x00" * (16 - l) + else: + # + # This isn't really right according to the RFC, but it + # seems better than throwing an exception + # + address = codecs.encode(address, "hex_codec") + item = APLItem(header[0], negation, address, header[1]) + items.append(item) + return cls(rdclass, rdtype, items) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/IN/DHCID.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/IN/DHCID.py new file mode 100644 index 000000000..8de8cdf16 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/IN/DHCID.py @@ -0,0 +1,54 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +# Copyright (C) 2006, 2007, 2009-2011 Nominum, Inc. +# +# Permission to use, copy, modify, and distribute this software and its +# documentation for any purpose with or without fee is hereby granted, +# provided that the above copyright notice and this permission notice +# appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +import base64 + +import dns.exception +import dns.immutable +import dns.rdata + + +@dns.immutable.immutable +class DHCID(dns.rdata.Rdata): + """DHCID record""" + + # see: RFC 4701 + + __slots__ = ["data"] + + def __init__(self, rdclass, rdtype, data): + super().__init__(rdclass, rdtype) + self.data = self._as_bytes(data) + + def to_text(self, origin=None, relativize=True, **kw): + return dns.rdata._base64ify(self.data, **kw) # pyright: ignore + + @classmethod + def from_text( + cls, rdclass, rdtype, tok, origin=None, relativize=True, relativize_to=None + ): + b64 = tok.concatenate_remaining_identifiers().encode() + data = base64.b64decode(b64) + return cls(rdclass, rdtype, data) + + def _to_wire(self, file, compress=None, origin=None, canonicalize=False): + file.write(self.data) + + @classmethod + def from_wire_parser(cls, rdclass, rdtype, parser, origin=None): + data = parser.get_remaining() + return cls(rdclass, rdtype, data) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/IN/HTTPS.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/IN/HTTPS.py new file mode 100644 index 000000000..15464cbda --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/IN/HTTPS.py @@ -0,0 +1,9 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +import dns.immutable +import dns.rdtypes.svcbbase + + +@dns.immutable.immutable +class HTTPS(dns.rdtypes.svcbbase.SVCBBase): + """HTTPS record""" diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/IN/IPSECKEY.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/IN/IPSECKEY.py new file mode 100644 index 000000000..aef93ae14 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/IN/IPSECKEY.py @@ -0,0 +1,87 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +# Copyright (C) 2006, 2007, 2009-2011 Nominum, Inc. +# +# Permission to use, copy, modify, and distribute this software and its +# documentation for any purpose with or without fee is hereby granted, +# provided that the above copyright notice and this permission notice +# appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +import base64 +import struct + +import dns.exception +import dns.immutable +import dns.rdata +import dns.rdtypes.util + + +class Gateway(dns.rdtypes.util.Gateway): + name = "IPSECKEY gateway" + + +@dns.immutable.immutable +class IPSECKEY(dns.rdata.Rdata): + """IPSECKEY record""" + + # see: RFC 4025 + + __slots__ = ["precedence", "gateway_type", "algorithm", "gateway", "key"] + + def __init__( + self, rdclass, rdtype, precedence, gateway_type, algorithm, gateway, key + ): + super().__init__(rdclass, rdtype) + gateway = Gateway(gateway_type, gateway) + self.precedence = self._as_uint8(precedence) + self.gateway_type = gateway.type + self.algorithm = self._as_uint8(algorithm) + self.gateway = gateway.gateway + self.key = self._as_bytes(key) + + def to_text(self, origin=None, relativize=True, **kw): + gateway = Gateway(self.gateway_type, self.gateway).to_text(origin, relativize) + key = dns.rdata._base64ify(self.key, **kw) # pyright: ignore + return f"{self.precedence} {self.gateway_type} {self.algorithm} {gateway} {key}" + + @classmethod + def from_text( + cls, rdclass, rdtype, tok, origin=None, relativize=True, relativize_to=None + ): + precedence = tok.get_uint8() + gateway_type = tok.get_uint8() + algorithm = tok.get_uint8() + gateway = Gateway.from_text( + gateway_type, tok, origin, relativize, relativize_to + ) + b64 = tok.concatenate_remaining_identifiers().encode() + key = base64.b64decode(b64) + return cls( + rdclass, rdtype, precedence, gateway_type, algorithm, gateway.gateway, key + ) + + def _to_wire(self, file, compress=None, origin=None, canonicalize=False): + header = struct.pack("!BBB", self.precedence, self.gateway_type, self.algorithm) + file.write(header) + Gateway(self.gateway_type, self.gateway).to_wire( + file, compress, origin, canonicalize + ) + file.write(self.key) + + @classmethod + def from_wire_parser(cls, rdclass, rdtype, parser, origin=None): + header = parser.get_struct("!BBB") + gateway_type = header[1] + gateway = Gateway.from_wire_parser(gateway_type, parser, origin) + key = parser.get_remaining() + return cls( + rdclass, rdtype, header[0], gateway_type, header[2], gateway.gateway, key + ) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/IN/KX.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/IN/KX.py new file mode 100644 index 000000000..6073df47b --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/IN/KX.py @@ -0,0 +1,24 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. +# +# Permission to use, copy, modify, and distribute this software and its +# documentation for any purpose with or without fee is hereby granted, +# provided that the above copyright notice and this permission notice +# appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +import dns.immutable +import dns.rdtypes.mxbase + + +@dns.immutable.immutable +class KX(dns.rdtypes.mxbase.UncompressedDowncasingMX): + """KX record""" diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/IN/NAPTR.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/IN/NAPTR.py new file mode 100644 index 000000000..98bbf4aba --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/IN/NAPTR.py @@ -0,0 +1,109 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. +# +# Permission to use, copy, modify, and distribute this software and its +# documentation for any purpose with or without fee is hereby granted, +# provided that the above copyright notice and this permission notice +# appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +import struct + +import dns.exception +import dns.immutable +import dns.name +import dns.rdata +import dns.rdtypes.util + + +def _write_string(file, s): + l = len(s) + assert l < 256 + file.write(struct.pack("!B", l)) + file.write(s) + + +@dns.immutable.immutable +class NAPTR(dns.rdata.Rdata): + """NAPTR record""" + + # see: RFC 3403 + + __slots__ = ["order", "preference", "flags", "service", "regexp", "replacement"] + + def __init__( + self, rdclass, rdtype, order, preference, flags, service, regexp, replacement + ): + super().__init__(rdclass, rdtype) + self.flags = self._as_bytes(flags, True, 255) + self.service = self._as_bytes(service, True, 255) + self.regexp = self._as_bytes(regexp, True, 255) + self.order = self._as_uint16(order) + self.preference = self._as_uint16(preference) + self.replacement = self._as_name(replacement) + + def to_text(self, origin=None, relativize=True, **kw): + replacement = self.replacement.choose_relativity(origin, relativize) + return ( + f"{self.order} {self.preference} " + f'"{dns.rdata._escapify(self.flags)}" ' + f'"{dns.rdata._escapify(self.service)}" ' + f'"{dns.rdata._escapify(self.regexp)}" ' + f"{replacement}" + ) + + @classmethod + def from_text( + cls, rdclass, rdtype, tok, origin=None, relativize=True, relativize_to=None + ): + order = tok.get_uint16() + preference = tok.get_uint16() + flags = tok.get_string() + service = tok.get_string() + regexp = tok.get_string() + replacement = tok.get_name(origin, relativize, relativize_to) + return cls( + rdclass, rdtype, order, preference, flags, service, regexp, replacement + ) + + def _to_wire(self, file, compress=None, origin=None, canonicalize=False): + two_ints = struct.pack("!HH", self.order, self.preference) + file.write(two_ints) + _write_string(file, self.flags) + _write_string(file, self.service) + _write_string(file, self.regexp) + self.replacement.to_wire(file, compress, origin, canonicalize) + + @classmethod + def from_wire_parser(cls, rdclass, rdtype, parser, origin=None): + (order, preference) = parser.get_struct("!HH") + strings = [] + for _ in range(3): + s = parser.get_counted_bytes() + strings.append(s) + replacement = parser.get_name(origin) + return cls( + rdclass, + rdtype, + order, + preference, + strings[0], + strings[1], + strings[2], + replacement, + ) + + def _processing_priority(self): + return (self.order, self.preference) + + @classmethod + def _processing_order(cls, iterable): + return dns.rdtypes.util.priority_processing_order(iterable) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/IN/NSAP.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/IN/NSAP.py new file mode 100644 index 000000000..d55edb737 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/IN/NSAP.py @@ -0,0 +1,60 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. +# +# Permission to use, copy, modify, and distribute this software and its +# documentation for any purpose with or without fee is hereby granted, +# provided that the above copyright notice and this permission notice +# appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +import binascii + +import dns.exception +import dns.immutable +import dns.rdata +import dns.tokenizer + + +@dns.immutable.immutable +class NSAP(dns.rdata.Rdata): + """NSAP record.""" + + # see: RFC 1706 + + __slots__ = ["address"] + + def __init__(self, rdclass, rdtype, address): + super().__init__(rdclass, rdtype) + self.address = self._as_bytes(address) + + def to_text(self, origin=None, relativize=True, **kw): + return f"0x{binascii.hexlify(self.address).decode()}" + + @classmethod + def from_text( + cls, rdclass, rdtype, tok, origin=None, relativize=True, relativize_to=None + ): + address = tok.get_string() + if address[0:2] != "0x": + raise dns.exception.SyntaxError("string does not start with 0x") + address = address[2:].replace(".", "") + if len(address) % 2 != 0: + raise dns.exception.SyntaxError("hexstring has odd length") + address = binascii.unhexlify(address.encode()) + return cls(rdclass, rdtype, address) + + def _to_wire(self, file, compress=None, origin=None, canonicalize=False): + file.write(self.address) + + @classmethod + def from_wire_parser(cls, rdclass, rdtype, parser, origin=None): + address = parser.get_remaining() + return cls(rdclass, rdtype, address) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/IN/NSAP_PTR.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/IN/NSAP_PTR.py new file mode 100644 index 000000000..ce1c66320 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/IN/NSAP_PTR.py @@ -0,0 +1,24 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. +# +# Permission to use, copy, modify, and distribute this software and its +# documentation for any purpose with or without fee is hereby granted, +# provided that the above copyright notice and this permission notice +# appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +import dns.immutable +import dns.rdtypes.nsbase + + +@dns.immutable.immutable +class NSAP_PTR(dns.rdtypes.nsbase.UncompressedNS): + """NSAP-PTR record""" diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/IN/PX.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/IN/PX.py new file mode 100644 index 000000000..20143bf6c --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/IN/PX.py @@ -0,0 +1,73 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. +# +# Permission to use, copy, modify, and distribute this software and its +# documentation for any purpose with or without fee is hereby granted, +# provided that the above copyright notice and this permission notice +# appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +import struct + +import dns.exception +import dns.immutable +import dns.name +import dns.rdata +import dns.rdtypes.util + + +@dns.immutable.immutable +class PX(dns.rdata.Rdata): + """PX record.""" + + # see: RFC 2163 + + __slots__ = ["preference", "map822", "mapx400"] + + def __init__(self, rdclass, rdtype, preference, map822, mapx400): + super().__init__(rdclass, rdtype) + self.preference = self._as_uint16(preference) + self.map822 = self._as_name(map822) + self.mapx400 = self._as_name(mapx400) + + def to_text(self, origin=None, relativize=True, **kw): + map822 = self.map822.choose_relativity(origin, relativize) + mapx400 = self.mapx400.choose_relativity(origin, relativize) + return f"{self.preference} {map822} {mapx400}" + + @classmethod + def from_text( + cls, rdclass, rdtype, tok, origin=None, relativize=True, relativize_to=None + ): + preference = tok.get_uint16() + map822 = tok.get_name(origin, relativize, relativize_to) + mapx400 = tok.get_name(origin, relativize, relativize_to) + return cls(rdclass, rdtype, preference, map822, mapx400) + + def _to_wire(self, file, compress=None, origin=None, canonicalize=False): + pref = struct.pack("!H", self.preference) + file.write(pref) + self.map822.to_wire(file, None, origin, canonicalize) + self.mapx400.to_wire(file, None, origin, canonicalize) + + @classmethod + def from_wire_parser(cls, rdclass, rdtype, parser, origin=None): + preference = parser.get_uint16() + map822 = parser.get_name(origin) + mapx400 = parser.get_name(origin) + return cls(rdclass, rdtype, preference, map822, mapx400) + + def _processing_priority(self): + return self.preference + + @classmethod + def _processing_order(cls, iterable): + return dns.rdtypes.util.priority_processing_order(iterable) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/IN/SRV.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/IN/SRV.py new file mode 100644 index 000000000..044c10e3a --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/IN/SRV.py @@ -0,0 +1,75 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. +# +# Permission to use, copy, modify, and distribute this software and its +# documentation for any purpose with or without fee is hereby granted, +# provided that the above copyright notice and this permission notice +# appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +import struct + +import dns.exception +import dns.immutable +import dns.name +import dns.rdata +import dns.rdtypes.util + + +@dns.immutable.immutable +class SRV(dns.rdata.Rdata): + """SRV record""" + + # see: RFC 2782 + + __slots__ = ["priority", "weight", "port", "target"] + + def __init__(self, rdclass, rdtype, priority, weight, port, target): + super().__init__(rdclass, rdtype) + self.priority = self._as_uint16(priority) + self.weight = self._as_uint16(weight) + self.port = self._as_uint16(port) + self.target = self._as_name(target) + + def to_text(self, origin=None, relativize=True, **kw): + target = self.target.choose_relativity(origin, relativize) + return f"{self.priority} {self.weight} {self.port} {target}" + + @classmethod + def from_text( + cls, rdclass, rdtype, tok, origin=None, relativize=True, relativize_to=None + ): + priority = tok.get_uint16() + weight = tok.get_uint16() + port = tok.get_uint16() + target = tok.get_name(origin, relativize, relativize_to) + return cls(rdclass, rdtype, priority, weight, port, target) + + def _to_wire(self, file, compress=None, origin=None, canonicalize=False): + three_ints = struct.pack("!HHH", self.priority, self.weight, self.port) + file.write(three_ints) + self.target.to_wire(file, compress, origin, canonicalize) + + @classmethod + def from_wire_parser(cls, rdclass, rdtype, parser, origin=None): + (priority, weight, port) = parser.get_struct("!HHH") + target = parser.get_name(origin) + return cls(rdclass, rdtype, priority, weight, port, target) + + def _processing_priority(self): + return self.priority + + def _processing_weight(self): + return self.weight + + @classmethod + def _processing_order(cls, iterable): + return dns.rdtypes.util.weighted_processing_order(iterable) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/IN/SVCB.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/IN/SVCB.py new file mode 100644 index 000000000..ff3e93277 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/IN/SVCB.py @@ -0,0 +1,9 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +import dns.immutable +import dns.rdtypes.svcbbase + + +@dns.immutable.immutable +class SVCB(dns.rdtypes.svcbbase.SVCBBase): + """SVCB record""" diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/IN/WKS.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/IN/WKS.py new file mode 100644 index 000000000..cc6c3733b --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/IN/WKS.py @@ -0,0 +1,100 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. +# +# Permission to use, copy, modify, and distribute this software and its +# documentation for any purpose with or without fee is hereby granted, +# provided that the above copyright notice and this permission notice +# appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +import socket +import struct + +import dns.immutable +import dns.ipv4 +import dns.rdata + +try: + _proto_tcp = socket.getprotobyname("tcp") + _proto_udp = socket.getprotobyname("udp") +except OSError: + # Fall back to defaults in case /etc/protocols is unavailable. + _proto_tcp = 6 + _proto_udp = 17 + + +@dns.immutable.immutable +class WKS(dns.rdata.Rdata): + """WKS record""" + + # see: RFC 1035 + + __slots__ = ["address", "protocol", "bitmap"] + + def __init__(self, rdclass, rdtype, address, protocol, bitmap): + super().__init__(rdclass, rdtype) + self.address = self._as_ipv4_address(address) + self.protocol = self._as_uint8(protocol) + self.bitmap = self._as_bytes(bitmap) + + def to_text(self, origin=None, relativize=True, **kw): + bits = [] + for i, byte in enumerate(self.bitmap): + for j in range(0, 8): + if byte & (0x80 >> j): + bits.append(str(i * 8 + j)) + text = " ".join(bits) + return f"{self.address} {self.protocol} {text}" + + @classmethod + def from_text( + cls, rdclass, rdtype, tok, origin=None, relativize=True, relativize_to=None + ): + address = tok.get_string() + protocol = tok.get_string() + if protocol.isdigit(): + protocol = int(protocol) + else: + protocol = socket.getprotobyname(protocol) + bitmap = bytearray() + for token in tok.get_remaining(): + value = token.unescape().value + if value.isdigit(): + serv = int(value) + else: + if protocol != _proto_udp and protocol != _proto_tcp: + raise NotImplementedError("protocol must be TCP or UDP") + if protocol == _proto_udp: + protocol_text = "udp" + else: + protocol_text = "tcp" + serv = socket.getservbyname(value, protocol_text) + i = serv // 8 + l = len(bitmap) + if l < i + 1: + for _ in range(l, i + 1): + bitmap.append(0) + bitmap[i] = bitmap[i] | (0x80 >> (serv % 8)) + bitmap = dns.rdata._truncate_bitmap(bitmap) + return cls(rdclass, rdtype, address, protocol, bitmap) + + def _to_wire(self, file, compress=None, origin=None, canonicalize=False): + file.write(dns.ipv4.inet_aton(self.address)) + protocol = struct.pack("!B", self.protocol) + file.write(protocol) + file.write(self.bitmap) + + @classmethod + def from_wire_parser(cls, rdclass, rdtype, parser, origin=None): + address = parser.get_bytes(4) + protocol = parser.get_uint8() + bitmap = parser.get_remaining() + return cls(rdclass, rdtype, address, protocol, bitmap) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/IN/__init__.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/IN/__init__.py new file mode 100644 index 000000000..dcec4dd24 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/IN/__init__.py @@ -0,0 +1,35 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. +# +# Permission to use, copy, modify, and distribute this software and its +# documentation for any purpose with or without fee is hereby granted, +# provided that the above copyright notice and this permission notice +# appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +"""Class IN rdata type classes.""" + +__all__ = [ + "A", + "AAAA", + "APL", + "DHCID", + "HTTPS", + "IPSECKEY", + "KX", + "NAPTR", + "NSAP", + "NSAP_PTR", + "PX", + "SRV", + "SVCB", + "WKS", +] diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/__init__.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/__init__.py new file mode 100644 index 000000000..3997f84c3 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/__init__.py @@ -0,0 +1,33 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. +# +# Permission to use, copy, modify, and distribute this software and its +# documentation for any purpose with or without fee is hereby granted, +# provided that the above copyright notice and this permission notice +# appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +"""DNS rdata type classes""" + +__all__ = [ + "ANY", + "IN", + "CH", + "dnskeybase", + "dsbase", + "euibase", + "mxbase", + "nsbase", + "svcbbase", + "tlsabase", + "txtbase", + "util", +] diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/dnskeybase.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/dnskeybase.py new file mode 100644 index 000000000..fb49f9220 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/dnskeybase.py @@ -0,0 +1,83 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +# Copyright (C) 2004-2007, 2009-2011 Nominum, Inc. +# +# Permission to use, copy, modify, and distribute this software and its +# documentation for any purpose with or without fee is hereby granted, +# provided that the above copyright notice and this permission notice +# appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +import base64 +import enum +import struct + +import dns.dnssectypes +import dns.exception +import dns.immutable +import dns.rdata + +# wildcard import +__all__ = ["SEP", "REVOKE", "ZONE"] # noqa: F822 + + +class Flag(enum.IntFlag): + SEP = 0x0001 + REVOKE = 0x0080 + ZONE = 0x0100 + + +@dns.immutable.immutable +class DNSKEYBase(dns.rdata.Rdata): + """Base class for rdata that is like a DNSKEY record""" + + __slots__ = ["flags", "protocol", "algorithm", "key"] + + def __init__(self, rdclass, rdtype, flags, protocol, algorithm, key): + super().__init__(rdclass, rdtype) + self.flags = Flag(self._as_uint16(flags)) + self.protocol = self._as_uint8(protocol) + self.algorithm = dns.dnssectypes.Algorithm.make(algorithm) + self.key = self._as_bytes(key) + + def to_text(self, origin=None, relativize=True, **kw): + key = dns.rdata._base64ify(self.key, **kw) # pyright: ignore + return f"{self.flags} {self.protocol} {self.algorithm} {key}" + + @classmethod + def from_text( + cls, rdclass, rdtype, tok, origin=None, relativize=True, relativize_to=None + ): + flags = tok.get_uint16() + protocol = tok.get_uint8() + algorithm = tok.get_string() + b64 = tok.concatenate_remaining_identifiers().encode() + key = base64.b64decode(b64) + return cls(rdclass, rdtype, flags, protocol, algorithm, key) + + def _to_wire(self, file, compress=None, origin=None, canonicalize=False): + header = struct.pack("!HBB", self.flags, self.protocol, self.algorithm) + file.write(header) + file.write(self.key) + + @classmethod + def from_wire_parser(cls, rdclass, rdtype, parser, origin=None): + header = parser.get_struct("!HBB") + key = parser.get_remaining() + return cls(rdclass, rdtype, header[0], header[1], header[2], key) + + +### BEGIN generated Flag constants + +SEP = Flag.SEP +REVOKE = Flag.REVOKE +ZONE = Flag.ZONE + +### END generated Flag constants diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/dsbase.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/dsbase.py new file mode 100644 index 000000000..8e05c2a75 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/dsbase.py @@ -0,0 +1,83 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +# Copyright (C) 2010, 2011 Nominum, Inc. +# +# Permission to use, copy, modify, and distribute this software and its +# documentation for any purpose with or without fee is hereby granted, +# provided that the above copyright notice and this permission notice +# appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +import binascii +import struct + +import dns.dnssectypes +import dns.immutable +import dns.rdata +import dns.rdatatype + + +@dns.immutable.immutable +class DSBase(dns.rdata.Rdata): + """Base class for rdata that is like a DS record""" + + __slots__ = ["key_tag", "algorithm", "digest_type", "digest"] + + # Digest types registry: + # https://www.iana.org/assignments/ds-rr-types/ds-rr-types.xhtml + _digest_length_by_type = { + 1: 20, # SHA-1, RFC 3658 Sec. 2.4 + 2: 32, # SHA-256, RFC 4509 Sec. 2.2 + 3: 32, # GOST R 34.11-94, RFC 5933 Sec. 4 in conjunction with RFC 4490 Sec. 2.1 + 4: 48, # SHA-384, RFC 6605 Sec. 2 + } + + def __init__(self, rdclass, rdtype, key_tag, algorithm, digest_type, digest): + super().__init__(rdclass, rdtype) + self.key_tag = self._as_uint16(key_tag) + self.algorithm = dns.dnssectypes.Algorithm.make(algorithm) + self.digest_type = dns.dnssectypes.DSDigest.make(self._as_uint8(digest_type)) + self.digest = self._as_bytes(digest) + try: + if len(self.digest) != self._digest_length_by_type[self.digest_type]: + raise ValueError("digest length inconsistent with digest type") + except KeyError: + if self.digest_type == 0: # reserved, RFC 3658 Sec. 2.4 + raise ValueError("digest type 0 is reserved") + + def to_text(self, origin=None, relativize=True, **kw): + kw = kw.copy() + chunksize = kw.pop("chunksize", 128) + digest = dns.rdata._hexify( + self.digest, chunksize=chunksize, **kw # pyright: ignore + ) + return f"{self.key_tag} {self.algorithm} {self.digest_type} {digest}" + + @classmethod + def from_text( + cls, rdclass, rdtype, tok, origin=None, relativize=True, relativize_to=None + ): + key_tag = tok.get_uint16() + algorithm = tok.get_string() + digest_type = tok.get_uint8() + digest = tok.concatenate_remaining_identifiers().encode() + digest = binascii.unhexlify(digest) + return cls(rdclass, rdtype, key_tag, algorithm, digest_type, digest) + + def _to_wire(self, file, compress=None, origin=None, canonicalize=False): + header = struct.pack("!HBB", self.key_tag, self.algorithm, self.digest_type) + file.write(header) + file.write(self.digest) + + @classmethod + def from_wire_parser(cls, rdclass, rdtype, parser, origin=None): + header = parser.get_struct("!HBB") + digest = parser.get_remaining() + return cls(rdclass, rdtype, header[0], header[1], header[2], digest) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/euibase.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/euibase.py new file mode 100644 index 000000000..4eb82eb5e --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/euibase.py @@ -0,0 +1,73 @@ +# Copyright (C) 2015 Red Hat, Inc. +# Author: Petr Spacek +# +# Permission to use, copy, modify, and distribute this software and its +# documentation for any purpose with or without fee is hereby granted, +# provided that the above copyright notice and this permission notice +# appear in all copies. +# +# THE SOFTWARE IS PROVIDED 'AS IS' AND RED HAT DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +import binascii + +import dns.exception +import dns.immutable +import dns.rdata + + +@dns.immutable.immutable +class EUIBase(dns.rdata.Rdata): + """EUIxx record""" + + # see: rfc7043.txt + + __slots__ = ["eui"] + # redefine these in subclasses + byte_len = 0 + text_len = 0 + # byte_len = 6 # 0123456789ab (in hex) + # text_len = byte_len * 3 - 1 # 01-23-45-67-89-ab + + def __init__(self, rdclass, rdtype, eui): + super().__init__(rdclass, rdtype) + self.eui = self._as_bytes(eui) + if len(self.eui) != self.byte_len: + raise dns.exception.FormError( + f"EUI{self.byte_len * 8} rdata has to have {self.byte_len} bytes" + ) + + def to_text(self, origin=None, relativize=True, **kw): + return dns.rdata._hexify(self.eui, chunksize=2, separator=b"-", **kw) + + @classmethod + def from_text( + cls, rdclass, rdtype, tok, origin=None, relativize=True, relativize_to=None + ): + text = tok.get_string() + if len(text) != cls.text_len: + raise dns.exception.SyntaxError( + f"Input text must have {cls.text_len} characters" + ) + for i in range(2, cls.byte_len * 3 - 1, 3): + if text[i] != "-": + raise dns.exception.SyntaxError(f"Dash expected at position {i}") + text = text.replace("-", "") + try: + data = binascii.unhexlify(text.encode()) + except (ValueError, TypeError) as ex: + raise dns.exception.SyntaxError(f"Hex decoding error: {str(ex)}") + return cls(rdclass, rdtype, data) + + def _to_wire(self, file, compress=None, origin=None, canonicalize=False): + file.write(self.eui) + + @classmethod + def from_wire_parser(cls, rdclass, rdtype, parser, origin=None): + eui = parser.get_bytes(cls.byte_len) + return cls(rdclass, rdtype, eui) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/mxbase.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/mxbase.py new file mode 100644 index 000000000..5d33e61f6 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/mxbase.py @@ -0,0 +1,87 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. +# +# Permission to use, copy, modify, and distribute this software and its +# documentation for any purpose with or without fee is hereby granted, +# provided that the above copyright notice and this permission notice +# appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +"""MX-like base classes.""" + +import struct + +import dns.exception +import dns.immutable +import dns.name +import dns.rdata +import dns.rdtypes.util + + +@dns.immutable.immutable +class MXBase(dns.rdata.Rdata): + """Base class for rdata that is like an MX record.""" + + __slots__ = ["preference", "exchange"] + + def __init__(self, rdclass, rdtype, preference, exchange): + super().__init__(rdclass, rdtype) + self.preference = self._as_uint16(preference) + self.exchange = self._as_name(exchange) + + def to_text(self, origin=None, relativize=True, **kw): + exchange = self.exchange.choose_relativity(origin, relativize) + return f"{self.preference} {exchange}" + + @classmethod + def from_text( + cls, rdclass, rdtype, tok, origin=None, relativize=True, relativize_to=None + ): + preference = tok.get_uint16() + exchange = tok.get_name(origin, relativize, relativize_to) + return cls(rdclass, rdtype, preference, exchange) + + def _to_wire(self, file, compress=None, origin=None, canonicalize=False): + pref = struct.pack("!H", self.preference) + file.write(pref) + self.exchange.to_wire(file, compress, origin, canonicalize) + + @classmethod + def from_wire_parser(cls, rdclass, rdtype, parser, origin=None): + preference = parser.get_uint16() + exchange = parser.get_name(origin) + return cls(rdclass, rdtype, preference, exchange) + + def _processing_priority(self): + return self.preference + + @classmethod + def _processing_order(cls, iterable): + return dns.rdtypes.util.priority_processing_order(iterable) + + +@dns.immutable.immutable +class UncompressedMX(MXBase): + """Base class for rdata that is like an MX record, but whose name + is not compressed when converted to DNS wire format, and whose + digestable form is not downcased.""" + + def _to_wire(self, file, compress=None, origin=None, canonicalize=False): + super()._to_wire(file, None, origin, False) + + +@dns.immutable.immutable +class UncompressedDowncasingMX(MXBase): + """Base class for rdata that is like an MX record, but whose name + is not compressed when convert to DNS wire format.""" + + def _to_wire(self, file, compress=None, origin=None, canonicalize=False): + super()._to_wire(file, None, origin, canonicalize) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/nsbase.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/nsbase.py new file mode 100644 index 000000000..904224f0e --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/nsbase.py @@ -0,0 +1,63 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. +# +# Permission to use, copy, modify, and distribute this software and its +# documentation for any purpose with or without fee is hereby granted, +# provided that the above copyright notice and this permission notice +# appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +"""NS-like base classes.""" + +import dns.exception +import dns.immutable +import dns.name +import dns.rdata + + +@dns.immutable.immutable +class NSBase(dns.rdata.Rdata): + """Base class for rdata that is like an NS record.""" + + __slots__ = ["target"] + + def __init__(self, rdclass, rdtype, target): + super().__init__(rdclass, rdtype) + self.target = self._as_name(target) + + def to_text(self, origin=None, relativize=True, **kw): + target = self.target.choose_relativity(origin, relativize) + return str(target) + + @classmethod + def from_text( + cls, rdclass, rdtype, tok, origin=None, relativize=True, relativize_to=None + ): + target = tok.get_name(origin, relativize, relativize_to) + return cls(rdclass, rdtype, target) + + def _to_wire(self, file, compress=None, origin=None, canonicalize=False): + self.target.to_wire(file, compress, origin, canonicalize) + + @classmethod + def from_wire_parser(cls, rdclass, rdtype, parser, origin=None): + target = parser.get_name(origin) + return cls(rdclass, rdtype, target) + + +@dns.immutable.immutable +class UncompressedNS(NSBase): + """Base class for rdata that is like an NS record, but whose name + is not compressed when convert to DNS wire format, and whose + digestable form is not downcased.""" + + def _to_wire(self, file, compress=None, origin=None, canonicalize=False): + self.target.to_wire(file, None, origin, False) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/svcbbase.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/svcbbase.py new file mode 100644 index 000000000..7338b664d --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/svcbbase.py @@ -0,0 +1,587 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +import base64 +import enum +import struct +from typing import Any, Dict + +import dns.enum +import dns.exception +import dns.immutable +import dns.ipv4 +import dns.ipv6 +import dns.name +import dns.rdata +import dns.rdtypes.util +import dns.renderer +import dns.tokenizer +import dns.wire + +# Until there is an RFC, this module is experimental and may be changed in +# incompatible ways. + + +class UnknownParamKey(dns.exception.DNSException): + """Unknown SVCB ParamKey""" + + +class ParamKey(dns.enum.IntEnum): + """SVCB ParamKey""" + + MANDATORY = 0 + ALPN = 1 + NO_DEFAULT_ALPN = 2 + PORT = 3 + IPV4HINT = 4 + ECH = 5 + IPV6HINT = 6 + DOHPATH = 7 + OHTTP = 8 + + @classmethod + def _maximum(cls): + return 65535 + + @classmethod + def _short_name(cls): + return "SVCBParamKey" + + @classmethod + def _prefix(cls): + return "KEY" + + @classmethod + def _unknown_exception_class(cls): + return UnknownParamKey + + +class Emptiness(enum.IntEnum): + NEVER = 0 + ALWAYS = 1 + ALLOWED = 2 + + +def _validate_key(key): + force_generic = False + if isinstance(key, bytes): + # We decode to latin-1 so we get 0-255 as valid and do NOT interpret + # UTF-8 sequences + key = key.decode("latin-1") + if isinstance(key, str): + if key.lower().startswith("key"): + force_generic = True + if key[3:].startswith("0") and len(key) != 4: + # key has leading zeros + raise ValueError("leading zeros in key") + key = key.replace("-", "_") + return (ParamKey.make(key), force_generic) + + +def key_to_text(key): + return ParamKey.to_text(key).replace("_", "-").lower() + + +# Like rdata escapify, but escapes ',' too. + +_escaped = b'",\\' + + +def _escapify(qstring): + text = "" + for c in qstring: + if c in _escaped: + text += "\\" + chr(c) + elif c >= 0x20 and c < 0x7F: + text += chr(c) + else: + text += f"\\{c:03d}" + return text + + +def _unescape(value: str) -> bytes: + if value == "": + return b"" + unescaped = b"" + l = len(value) + i = 0 + while i < l: + c = value[i] + i += 1 + if c == "\\": + if i >= l: # pragma: no cover (can't happen via tokenizer get()) + raise dns.exception.UnexpectedEnd + c = value[i] + i += 1 + if c.isdigit(): + if i >= l: + raise dns.exception.UnexpectedEnd + c2 = value[i] + i += 1 + if i >= l: + raise dns.exception.UnexpectedEnd + c3 = value[i] + i += 1 + if not (c2.isdigit() and c3.isdigit()): + raise dns.exception.SyntaxError + codepoint = int(c) * 100 + int(c2) * 10 + int(c3) + if codepoint > 255: + raise dns.exception.SyntaxError + unescaped += b"%c" % (codepoint) + continue + unescaped += c.encode() + return unescaped + + +def _split(value): + l = len(value) + i = 0 + items = [] + unescaped = b"" + while i < l: + c = value[i] + i += 1 + if c == ord("\\"): + if i >= l: # pragma: no cover (can't happen via tokenizer get()) + raise dns.exception.UnexpectedEnd + c = value[i] + i += 1 + unescaped += b"%c" % (c) + elif c == ord(","): + items.append(unescaped) + unescaped = b"" + else: + unescaped += b"%c" % (c) + items.append(unescaped) + return items + + +@dns.immutable.immutable +class Param: + """Abstract base class for SVCB parameters""" + + @classmethod + def emptiness(cls) -> Emptiness: + return Emptiness.NEVER + + +@dns.immutable.immutable +class GenericParam(Param): + """Generic SVCB parameter""" + + def __init__(self, value): + self.value = dns.rdata.Rdata._as_bytes(value, True) + + @classmethod + def emptiness(cls): + return Emptiness.ALLOWED + + @classmethod + def from_value(cls, value): + if value is None or len(value) == 0: + return None + else: + return cls(_unescape(value)) + + def to_text(self): + return '"' + dns.rdata._escapify(self.value) + '"' + + @classmethod + def from_wire_parser(cls, parser, origin=None): # pylint: disable=W0613 + value = parser.get_bytes(parser.remaining()) + if len(value) == 0: + return None + else: + return cls(value) + + def to_wire(self, file, origin=None): # pylint: disable=W0613 + file.write(self.value) + + +@dns.immutable.immutable +class MandatoryParam(Param): + def __init__(self, keys): + # check for duplicates + keys = sorted([_validate_key(key)[0] for key in keys]) + prior_k = None + for k in keys: + if k == prior_k: + raise ValueError(f"duplicate key {k:d}") + prior_k = k + if k == ParamKey.MANDATORY: + raise ValueError("listed the mandatory key as mandatory") + self.keys = tuple(keys) + + @classmethod + def from_value(cls, value): + keys = [k.encode() for k in value.split(",")] + return cls(keys) + + def to_text(self): + return '"' + ",".join([key_to_text(key) for key in self.keys]) + '"' + + @classmethod + def from_wire_parser(cls, parser, origin=None): # pylint: disable=W0613 + keys = [] + last_key = -1 + while parser.remaining() > 0: + key = parser.get_uint16() + if key < last_key: + raise dns.exception.FormError("manadatory keys not ascending") + last_key = key + keys.append(key) + return cls(keys) + + def to_wire(self, file, origin=None): # pylint: disable=W0613 + for key in self.keys: + file.write(struct.pack("!H", key)) + + +@dns.immutable.immutable +class ALPNParam(Param): + def __init__(self, ids): + self.ids = dns.rdata.Rdata._as_tuple( + ids, lambda x: dns.rdata.Rdata._as_bytes(x, True, 255, False) + ) + + @classmethod + def from_value(cls, value): + return cls(_split(_unescape(value))) + + def to_text(self): + value = ",".join([_escapify(id) for id in self.ids]) + return '"' + dns.rdata._escapify(value.encode()) + '"' + + @classmethod + def from_wire_parser(cls, parser, origin=None): # pylint: disable=W0613 + ids = [] + while parser.remaining() > 0: + id = parser.get_counted_bytes() + ids.append(id) + return cls(ids) + + def to_wire(self, file, origin=None): # pylint: disable=W0613 + for id in self.ids: + file.write(struct.pack("!B", len(id))) + file.write(id) + + +@dns.immutable.immutable +class NoDefaultALPNParam(Param): + # We don't ever expect to instantiate this class, but we need + # a from_value() and a from_wire_parser(), so we just return None + # from the class methods when things are OK. + + @classmethod + def emptiness(cls): + return Emptiness.ALWAYS + + @classmethod + def from_value(cls, value): + if value is None or value == "": + return None + else: + raise ValueError("no-default-alpn with non-empty value") + + def to_text(self): + raise NotImplementedError # pragma: no cover + + @classmethod + def from_wire_parser(cls, parser, origin=None): # pylint: disable=W0613 + if parser.remaining() != 0: + raise dns.exception.FormError + return None + + def to_wire(self, file, origin=None): # pylint: disable=W0613 + raise NotImplementedError # pragma: no cover + + +@dns.immutable.immutable +class PortParam(Param): + def __init__(self, port): + self.port = dns.rdata.Rdata._as_uint16(port) + + @classmethod + def from_value(cls, value): + value = int(value) + return cls(value) + + def to_text(self): + return f'"{self.port}"' + + @classmethod + def from_wire_parser(cls, parser, origin=None): # pylint: disable=W0613 + port = parser.get_uint16() + return cls(port) + + def to_wire(self, file, origin=None): # pylint: disable=W0613 + file.write(struct.pack("!H", self.port)) + + +@dns.immutable.immutable +class IPv4HintParam(Param): + def __init__(self, addresses): + self.addresses = dns.rdata.Rdata._as_tuple( + addresses, dns.rdata.Rdata._as_ipv4_address + ) + + @classmethod + def from_value(cls, value): + addresses = value.split(",") + return cls(addresses) + + def to_text(self): + return '"' + ",".join(self.addresses) + '"' + + @classmethod + def from_wire_parser(cls, parser, origin=None): # pylint: disable=W0613 + addresses = [] + while parser.remaining() > 0: + ip = parser.get_bytes(4) + addresses.append(dns.ipv4.inet_ntoa(ip)) + return cls(addresses) + + def to_wire(self, file, origin=None): # pylint: disable=W0613 + for address in self.addresses: + file.write(dns.ipv4.inet_aton(address)) + + +@dns.immutable.immutable +class IPv6HintParam(Param): + def __init__(self, addresses): + self.addresses = dns.rdata.Rdata._as_tuple( + addresses, dns.rdata.Rdata._as_ipv6_address + ) + + @classmethod + def from_value(cls, value): + addresses = value.split(",") + return cls(addresses) + + def to_text(self): + return '"' + ",".join(self.addresses) + '"' + + @classmethod + def from_wire_parser(cls, parser, origin=None): # pylint: disable=W0613 + addresses = [] + while parser.remaining() > 0: + ip = parser.get_bytes(16) + addresses.append(dns.ipv6.inet_ntoa(ip)) + return cls(addresses) + + def to_wire(self, file, origin=None): # pylint: disable=W0613 + for address in self.addresses: + file.write(dns.ipv6.inet_aton(address)) + + +@dns.immutable.immutable +class ECHParam(Param): + def __init__(self, ech): + self.ech = dns.rdata.Rdata._as_bytes(ech, True) + + @classmethod + def from_value(cls, value): + if "\\" in value: + raise ValueError("escape in ECH value") + value = base64.b64decode(value.encode()) + return cls(value) + + def to_text(self): + b64 = base64.b64encode(self.ech).decode("ascii") + return f'"{b64}"' + + @classmethod + def from_wire_parser(cls, parser, origin=None): # pylint: disable=W0613 + value = parser.get_bytes(parser.remaining()) + return cls(value) + + def to_wire(self, file, origin=None): # pylint: disable=W0613 + file.write(self.ech) + + +@dns.immutable.immutable +class OHTTPParam(Param): + # We don't ever expect to instantiate this class, but we need + # a from_value() and a from_wire_parser(), so we just return None + # from the class methods when things are OK. + + @classmethod + def emptiness(cls): + return Emptiness.ALWAYS + + @classmethod + def from_value(cls, value): + if value is None or value == "": + return None + else: + raise ValueError("ohttp with non-empty value") + + def to_text(self): + raise NotImplementedError # pragma: no cover + + @classmethod + def from_wire_parser(cls, parser, origin=None): # pylint: disable=W0613 + if parser.remaining() != 0: + raise dns.exception.FormError + return None + + def to_wire(self, file, origin=None): # pylint: disable=W0613 + raise NotImplementedError # pragma: no cover + + +_class_for_key: Dict[ParamKey, Any] = { + ParamKey.MANDATORY: MandatoryParam, + ParamKey.ALPN: ALPNParam, + ParamKey.NO_DEFAULT_ALPN: NoDefaultALPNParam, + ParamKey.PORT: PortParam, + ParamKey.IPV4HINT: IPv4HintParam, + ParamKey.ECH: ECHParam, + ParamKey.IPV6HINT: IPv6HintParam, + ParamKey.OHTTP: OHTTPParam, +} + + +def _validate_and_define(params, key, value): + (key, force_generic) = _validate_key(_unescape(key)) + if key in params: + raise SyntaxError(f'duplicate key "{key:d}"') + cls = _class_for_key.get(key, GenericParam) + emptiness = cls.emptiness() + if value is None: + if emptiness == Emptiness.NEVER: + raise SyntaxError("value cannot be empty") + value = cls.from_value(value) + else: + if force_generic: + value = cls.from_wire_parser(dns.wire.Parser(_unescape(value))) + else: + value = cls.from_value(value) + params[key] = value + + +@dns.immutable.immutable +class SVCBBase(dns.rdata.Rdata): + """Base class for SVCB-like records""" + + # see: draft-ietf-dnsop-svcb-https-11 + + __slots__ = ["priority", "target", "params"] + + def __init__(self, rdclass, rdtype, priority, target, params): + super().__init__(rdclass, rdtype) + self.priority = self._as_uint16(priority) + self.target = self._as_name(target) + for k, v in params.items(): + k = ParamKey.make(k) + if not isinstance(v, Param) and v is not None: + raise ValueError(f"{k:d} not a Param") + self.params = dns.immutable.Dict(params) + # Make sure any parameter listed as mandatory is present in the + # record. + mandatory = params.get(ParamKey.MANDATORY) + if mandatory: + for key in mandatory.keys: + # Note we have to say "not in" as we have None as a value + # so a get() and a not None test would be wrong. + if key not in params: + raise ValueError(f"key {key:d} declared mandatory but not present") + # The no-default-alpn parameter requires the alpn parameter. + if ParamKey.NO_DEFAULT_ALPN in params: + if ParamKey.ALPN not in params: + raise ValueError("no-default-alpn present, but alpn missing") + + def to_text(self, origin=None, relativize=True, **kw): + target = self.target.choose_relativity(origin, relativize) + params = [] + for key in sorted(self.params.keys()): + value = self.params[key] + if value is None: + params.append(key_to_text(key)) + else: + kv = key_to_text(key) + "=" + value.to_text() + params.append(kv) + if len(params) > 0: + space = " " + else: + space = "" + return f"{self.priority} {target}{space}{' '.join(params)}" + + @classmethod + def from_text( + cls, rdclass, rdtype, tok, origin=None, relativize=True, relativize_to=None + ): + priority = tok.get_uint16() + target = tok.get_name(origin, relativize, relativize_to) + if priority == 0: + token = tok.get() + if not token.is_eol_or_eof(): + raise SyntaxError("parameters in AliasMode") + tok.unget(token) + params = {} + while True: + token = tok.get() + if token.is_eol_or_eof(): + tok.unget(token) + break + if token.ttype != dns.tokenizer.IDENTIFIER: + raise SyntaxError("parameter is not an identifier") + equals = token.value.find("=") + if equals == len(token.value) - 1: + # 'key=', so next token should be a quoted string without + # any intervening whitespace. + key = token.value[:-1] + token = tok.get(want_leading=True) + if token.ttype != dns.tokenizer.QUOTED_STRING: + raise SyntaxError("whitespace after =") + value = token.value + elif equals > 0: + # key=value + key = token.value[:equals] + value = token.value[equals + 1 :] + elif equals == 0: + # =key + raise SyntaxError('parameter cannot start with "="') + else: + # key + key = token.value + value = None + _validate_and_define(params, key, value) + return cls(rdclass, rdtype, priority, target, params) + + def _to_wire(self, file, compress=None, origin=None, canonicalize=False): + file.write(struct.pack("!H", self.priority)) + self.target.to_wire(file, None, origin, False) + for key in sorted(self.params): + file.write(struct.pack("!H", key)) + value = self.params[key] + with dns.renderer.prefixed_length(file, 2): + # Note that we're still writing a length of zero if the value is None + if value is not None: + value.to_wire(file, origin) + + @classmethod + def from_wire_parser(cls, rdclass, rdtype, parser, origin=None): + priority = parser.get_uint16() + target = parser.get_name(origin) + if priority == 0 and parser.remaining() != 0: + raise dns.exception.FormError("parameters in AliasMode") + params = {} + prior_key = -1 + while parser.remaining() > 0: + key = parser.get_uint16() + if key < prior_key: + raise dns.exception.FormError("keys not in order") + prior_key = key + vlen = parser.get_uint16() + pkey = ParamKey.make(key) + pcls = _class_for_key.get(pkey, GenericParam) + with parser.restrict_to(vlen): + value = pcls.from_wire_parser(parser, origin) + params[pkey] = value + return cls(rdclass, rdtype, priority, target, params) + + def _processing_priority(self): + return self.priority + + @classmethod + def _processing_order(cls, iterable): + return dns.rdtypes.util.priority_processing_order(iterable) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/tlsabase.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/tlsabase.py new file mode 100644 index 000000000..ddc196f1f --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/tlsabase.py @@ -0,0 +1,69 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +# Copyright (C) 2005-2007, 2009-2011 Nominum, Inc. +# +# Permission to use, copy, modify, and distribute this software and its +# documentation for any purpose with or without fee is hereby granted, +# provided that the above copyright notice and this permission notice +# appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +import binascii +import struct + +import dns.immutable +import dns.rdata +import dns.rdatatype + + +@dns.immutable.immutable +class TLSABase(dns.rdata.Rdata): + """Base class for TLSA and SMIMEA records""" + + # see: RFC 6698 + + __slots__ = ["usage", "selector", "mtype", "cert"] + + def __init__(self, rdclass, rdtype, usage, selector, mtype, cert): + super().__init__(rdclass, rdtype) + self.usage = self._as_uint8(usage) + self.selector = self._as_uint8(selector) + self.mtype = self._as_uint8(mtype) + self.cert = self._as_bytes(cert) + + def to_text(self, origin=None, relativize=True, **kw): + kw = kw.copy() + chunksize = kw.pop("chunksize", 128) + cert = dns.rdata._hexify( + self.cert, chunksize=chunksize, **kw # pyright: ignore + ) + return f"{self.usage} {self.selector} {self.mtype} {cert}" + + @classmethod + def from_text( + cls, rdclass, rdtype, tok, origin=None, relativize=True, relativize_to=None + ): + usage = tok.get_uint8() + selector = tok.get_uint8() + mtype = tok.get_uint8() + cert = tok.concatenate_remaining_identifiers().encode() + cert = binascii.unhexlify(cert) + return cls(rdclass, rdtype, usage, selector, mtype, cert) + + def _to_wire(self, file, compress=None, origin=None, canonicalize=False): + header = struct.pack("!BBB", self.usage, self.selector, self.mtype) + file.write(header) + file.write(self.cert) + + @classmethod + def from_wire_parser(cls, rdclass, rdtype, parser, origin=None): + header = parser.get_struct("BBB") + cert = parser.get_remaining() + return cls(rdclass, rdtype, header[0], header[1], header[2], cert) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/txtbase.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/txtbase.py new file mode 100644 index 000000000..5e5b24f5d --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/txtbase.py @@ -0,0 +1,109 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +# Copyright (C) 2006-2017 Nominum, Inc. +# +# Permission to use, copy, modify, and distribute this software and its +# documentation for any purpose with or without fee is hereby granted, +# provided that the above copyright notice and this permission notice +# appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +"""TXT-like base class.""" + +from typing import Any, Dict, Iterable, Tuple + +import dns.exception +import dns.immutable +import dns.name +import dns.rdata +import dns.rdataclass +import dns.rdatatype +import dns.renderer +import dns.tokenizer + + +@dns.immutable.immutable +class TXTBase(dns.rdata.Rdata): + """Base class for rdata that is like a TXT record (see RFC 1035).""" + + __slots__ = ["strings"] + + def __init__( + self, + rdclass: dns.rdataclass.RdataClass, + rdtype: dns.rdatatype.RdataType, + strings: Iterable[bytes | str], + ): + """Initialize a TXT-like rdata. + + *rdclass*, an ``int`` is the rdataclass of the Rdata. + + *rdtype*, an ``int`` is the rdatatype of the Rdata. + + *strings*, a tuple of ``bytes`` + """ + super().__init__(rdclass, rdtype) + self.strings: Tuple[bytes] = self._as_tuple( + strings, lambda x: self._as_bytes(x, True, 255) + ) + if len(self.strings) == 0: + raise ValueError("the list of strings must not be empty") + + def to_text( + self, + origin: dns.name.Name | None = None, + relativize: bool = True, + **kw: Dict[str, Any], + ) -> str: + txt = "" + prefix = "" + for s in self.strings: + txt += f'{prefix}"{dns.rdata._escapify(s)}"' + prefix = " " + return txt + + @classmethod + def from_text( + cls, + rdclass: dns.rdataclass.RdataClass, + rdtype: dns.rdatatype.RdataType, + tok: dns.tokenizer.Tokenizer, + origin: dns.name.Name | None = None, + relativize: bool = True, + relativize_to: dns.name.Name | None = None, + ) -> dns.rdata.Rdata: + strings = [] + for token in tok.get_remaining(): + token = token.unescape_to_bytes() + # The 'if' below is always true in the current code, but we + # are leaving this check in in case things change some day. + if not ( + token.is_quoted_string() or token.is_identifier() + ): # pragma: no cover + raise dns.exception.SyntaxError("expected a string") + if len(token.value) > 255: + raise dns.exception.SyntaxError("string too long") + strings.append(token.value) + if len(strings) == 0: + raise dns.exception.UnexpectedEnd + return cls(rdclass, rdtype, strings) + + def _to_wire(self, file, compress=None, origin=None, canonicalize=False): + for s in self.strings: + with dns.renderer.prefixed_length(file, 1): + file.write(s) + + @classmethod + def from_wire_parser(cls, rdclass, rdtype, parser, origin=None): + strings = [] + while parser.remaining() > 0: + s = parser.get_counted_bytes() + strings.append(s) + return cls(rdclass, rdtype, strings) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/util.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/util.py new file mode 100644 index 000000000..c17b154b8 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rdtypes/util.py @@ -0,0 +1,269 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +# Copyright (C) 2006, 2007, 2009-2011 Nominum, Inc. +# +# Permission to use, copy, modify, and distribute this software and its +# documentation for any purpose with or without fee is hereby granted, +# provided that the above copyright notice and this permission notice +# appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +import collections +import random +import struct +from typing import Any, Iterable, List, Tuple + +import dns.exception +import dns.ipv4 +import dns.ipv6 +import dns.name +import dns.rdata +import dns.rdatatype +import dns.tokenizer +import dns.wire + + +class Gateway: + """A helper class for the IPSECKEY gateway and AMTRELAY relay fields""" + + name = "" + + def __init__(self, type: Any, gateway: str | dns.name.Name | None = None): + self.type = dns.rdata.Rdata._as_uint8(type) + self.gateway = gateway + self._check() + + @classmethod + def _invalid_type(cls, gateway_type): + return f"invalid {cls.name} type: {gateway_type}" + + def _check(self): + if self.type == 0: + if self.gateway not in (".", None): + raise SyntaxError(f"invalid {self.name} for type 0") + self.gateway = None + elif self.type == 1: + # check that it's OK + assert isinstance(self.gateway, str) + dns.ipv4.inet_aton(self.gateway) + elif self.type == 2: + # check that it's OK + assert isinstance(self.gateway, str) + dns.ipv6.inet_aton(self.gateway) + elif self.type == 3: + if not isinstance(self.gateway, dns.name.Name): + raise SyntaxError(f"invalid {self.name}; not a name") + else: + raise SyntaxError(self._invalid_type(self.type)) + + def to_text(self, origin=None, relativize=True): + if self.type == 0: + return "." + elif self.type in (1, 2): + return self.gateway + elif self.type == 3: + assert isinstance(self.gateway, dns.name.Name) + return str(self.gateway.choose_relativity(origin, relativize)) + else: + raise ValueError(self._invalid_type(self.type)) # pragma: no cover + + @classmethod + def from_text( + cls, gateway_type, tok, origin=None, relativize=True, relativize_to=None + ): + if gateway_type in (0, 1, 2): + gateway = tok.get_string() + elif gateway_type == 3: + gateway = tok.get_name(origin, relativize, relativize_to) + else: + raise dns.exception.SyntaxError( + cls._invalid_type(gateway_type) + ) # pragma: no cover + return cls(gateway_type, gateway) + + # pylint: disable=unused-argument + def to_wire(self, file, compress=None, origin=None, canonicalize=False): + if self.type == 0: + pass + elif self.type == 1: + assert isinstance(self.gateway, str) + file.write(dns.ipv4.inet_aton(self.gateway)) + elif self.type == 2: + assert isinstance(self.gateway, str) + file.write(dns.ipv6.inet_aton(self.gateway)) + elif self.type == 3: + assert isinstance(self.gateway, dns.name.Name) + self.gateway.to_wire(file, None, origin, False) + else: + raise ValueError(self._invalid_type(self.type)) # pragma: no cover + + # pylint: enable=unused-argument + + @classmethod + def from_wire_parser(cls, gateway_type, parser, origin=None): + if gateway_type == 0: + gateway = None + elif gateway_type == 1: + gateway = dns.ipv4.inet_ntoa(parser.get_bytes(4)) + elif gateway_type == 2: + gateway = dns.ipv6.inet_ntoa(parser.get_bytes(16)) + elif gateway_type == 3: + gateway = parser.get_name(origin) + else: + raise dns.exception.FormError(cls._invalid_type(gateway_type)) + return cls(gateway_type, gateway) + + +class Bitmap: + """A helper class for the NSEC/NSEC3/CSYNC type bitmaps""" + + type_name = "" + + def __init__(self, windows: Iterable[Tuple[int, bytes]] | None = None): + last_window = -1 + if windows is None: + windows = [] + self.windows = windows + for window, bitmap in self.windows: + if not isinstance(window, int): + raise ValueError(f"bad {self.type_name} window type") + if window <= last_window: + raise ValueError(f"bad {self.type_name} window order") + if window > 256: + raise ValueError(f"bad {self.type_name} window number") + last_window = window + if not isinstance(bitmap, bytes): + raise ValueError(f"bad {self.type_name} octets type") + if len(bitmap) == 0 or len(bitmap) > 32: + raise ValueError(f"bad {self.type_name} octets") + + def to_text(self) -> str: + text = "" + for window, bitmap in self.windows: + bits = [] + for i, byte in enumerate(bitmap): + for j in range(0, 8): + if byte & (0x80 >> j): + rdtype = dns.rdatatype.RdataType.make(window * 256 + i * 8 + j) + bits.append(dns.rdatatype.to_text(rdtype)) + text += " " + " ".join(bits) + return text + + @classmethod + def from_text(cls, tok: "dns.tokenizer.Tokenizer") -> "Bitmap": + rdtypes = [] + for token in tok.get_remaining(): + rdtype = dns.rdatatype.from_text(token.unescape().value) + if rdtype == 0: + raise dns.exception.SyntaxError(f"{cls.type_name} with bit 0") + rdtypes.append(rdtype) + return cls.from_rdtypes(rdtypes) + + @classmethod + def from_rdtypes(cls, rdtypes: List[dns.rdatatype.RdataType]) -> "Bitmap": + rdtypes = sorted(rdtypes) + window = 0 + octets = 0 + prior_rdtype = 0 + bitmap = bytearray(b"\0" * 32) + windows = [] + for rdtype in rdtypes: + if rdtype == prior_rdtype: + continue + prior_rdtype = rdtype + new_window = rdtype // 256 + if new_window != window: + if octets != 0: + windows.append((window, bytes(bitmap[0:octets]))) + bitmap = bytearray(b"\0" * 32) + window = new_window + offset = rdtype % 256 + byte = offset // 8 + bit = offset % 8 + octets = byte + 1 + bitmap[byte] = bitmap[byte] | (0x80 >> bit) + if octets != 0: + windows.append((window, bytes(bitmap[0:octets]))) + return cls(windows) + + def to_wire(self, file: Any) -> None: + for window, bitmap in self.windows: + file.write(struct.pack("!BB", window, len(bitmap))) + file.write(bitmap) + + @classmethod + def from_wire_parser(cls, parser: "dns.wire.Parser") -> "Bitmap": + windows = [] + while parser.remaining() > 0: + window = parser.get_uint8() + bitmap = parser.get_counted_bytes() + windows.append((window, bitmap)) + return cls(windows) + + +def _priority_table(items): + by_priority = collections.defaultdict(list) + for rdata in items: + by_priority[rdata._processing_priority()].append(rdata) + return by_priority + + +def priority_processing_order(iterable): + items = list(iterable) + if len(items) == 1: + return items + by_priority = _priority_table(items) + ordered = [] + for k in sorted(by_priority.keys()): + rdatas = by_priority[k] + random.shuffle(rdatas) + ordered.extend(rdatas) + return ordered + + +_no_weight = 0.1 + + +def weighted_processing_order(iterable): + items = list(iterable) + if len(items) == 1: + return items + by_priority = _priority_table(items) + ordered = [] + for k in sorted(by_priority.keys()): + rdatas = by_priority[k] + total = sum(rdata._processing_weight() or _no_weight for rdata in rdatas) + while len(rdatas) > 1: + r = random.uniform(0, total) + for n, rdata in enumerate(rdatas): # noqa: B007 + weight = rdata._processing_weight() or _no_weight + if weight > r: + break + r -= weight + total -= weight # pyright: ignore[reportPossiblyUnboundVariable] + # pylint: disable=undefined-loop-variable + ordered.append(rdata) # pyright: ignore[reportPossiblyUnboundVariable] + del rdatas[n] # pyright: ignore[reportPossiblyUnboundVariable] + ordered.append(rdatas[0]) + return ordered + + +def parse_formatted_hex(formatted, num_chunks, chunk_size, separator): + if len(formatted) != num_chunks * (chunk_size + 1) - 1: + raise ValueError("invalid formatted hex string") + value = b"" + for _ in range(num_chunks): + chunk = formatted[0:chunk_size] + value += int(chunk, 16).to_bytes(chunk_size // 2, "big") + formatted = formatted[chunk_size:] + if len(formatted) > 0 and formatted[0] != separator: + raise ValueError("invalid formatted hex string") + formatted = formatted[1:] + return value diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/renderer.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/renderer.py new file mode 100644 index 000000000..cc912b29d --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/renderer.py @@ -0,0 +1,355 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +# Copyright (C) 2001-2017 Nominum, Inc. +# +# Permission to use, copy, modify, and distribute this software and its +# documentation for any purpose with or without fee is hereby granted, +# provided that the above copyright notice and this permission notice +# appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +"""Help for building DNS wire format messages""" + +import contextlib +import io +import random +import struct +import time + +import dns.edns +import dns.exception +import dns.rdataclass +import dns.rdatatype +import dns.tsig + +# Note we can't import dns.message for cicularity reasons + +QUESTION = 0 +ANSWER = 1 +AUTHORITY = 2 +ADDITIONAL = 3 + + +@contextlib.contextmanager +def prefixed_length(output, length_length): + output.write(b"\00" * length_length) + start = output.tell() + yield + end = output.tell() + length = end - start + if length > 0: + try: + output.seek(start - length_length) + try: + output.write(length.to_bytes(length_length, "big")) + except OverflowError: + raise dns.exception.FormError + finally: + output.seek(end) + + +class Renderer: + """Helper class for building DNS wire-format messages. + + Most applications can use the higher-level L{dns.message.Message} + class and its to_wire() method to generate wire-format messages. + This class is for those applications which need finer control + over the generation of messages. + + Typical use:: + + r = dns.renderer.Renderer(id=1, flags=0x80, max_size=512) + r.add_question(qname, qtype, qclass) + r.add_rrset(dns.renderer.ANSWER, rrset_1) + r.add_rrset(dns.renderer.ANSWER, rrset_2) + r.add_rrset(dns.renderer.AUTHORITY, ns_rrset) + r.add_rrset(dns.renderer.ADDITIONAL, ad_rrset_1) + r.add_rrset(dns.renderer.ADDITIONAL, ad_rrset_2) + r.add_edns(0, 0, 4096) + r.write_header() + r.add_tsig(keyname, secret, 300, 1, 0, '', request_mac) + wire = r.get_wire() + + If padding is going to be used, then the OPT record MUST be + written after everything else in the additional section except for + the TSIG (if any). + + output, an io.BytesIO, where rendering is written + + id: the message id + + flags: the message flags + + max_size: the maximum size of the message + + origin: the origin to use when rendering relative names + + compress: the compression table + + section: an int, the section currently being rendered + + counts: list of the number of RRs in each section + + mac: the MAC of the rendered message (if TSIG was used) + """ + + def __init__(self, id=None, flags=0, max_size=65535, origin=None): + """Initialize a new renderer.""" + + self.output = io.BytesIO() + if id is None: + self.id = random.randint(0, 65535) + else: + self.id = id + self.flags = flags + self.max_size = max_size + self.origin = origin + self.compress = {} + self.section = QUESTION + self.counts = [0, 0, 0, 0] + self.output.write(b"\x00" * 12) + self.mac = "" + self.reserved = 0 + self.was_padded = False + + def _rollback(self, where): + """Truncate the output buffer at offset *where*, and remove any + compression table entries that pointed beyond the truncation + point. + """ + + self.output.seek(where) + self.output.truncate() + keys_to_delete = [] + for k, v in self.compress.items(): + if v >= where: + keys_to_delete.append(k) + for k in keys_to_delete: + del self.compress[k] + + def _set_section(self, section): + """Set the renderer's current section. + + Sections must be rendered order: QUESTION, ANSWER, AUTHORITY, + ADDITIONAL. Sections may be empty. + + Raises dns.exception.FormError if an attempt was made to set + a section value less than the current section. + """ + + if self.section != section: + if self.section > section: + raise dns.exception.FormError + self.section = section + + @contextlib.contextmanager + def _track_size(self): + start = self.output.tell() + yield start + if self.output.tell() > self.max_size: + self._rollback(start) + raise dns.exception.TooBig + + @contextlib.contextmanager + def _temporarily_seek_to(self, where): + current = self.output.tell() + try: + self.output.seek(where) + yield + finally: + self.output.seek(current) + + def add_question(self, qname, rdtype, rdclass=dns.rdataclass.IN): + """Add a question to the message.""" + + self._set_section(QUESTION) + with self._track_size(): + qname.to_wire(self.output, self.compress, self.origin) + self.output.write(struct.pack("!HH", rdtype, rdclass)) + self.counts[QUESTION] += 1 + + def add_rrset(self, section, rrset, **kw): + """Add the rrset to the specified section. + + Any keyword arguments are passed on to the rdataset's to_wire() + routine. + """ + + self._set_section(section) + with self._track_size(): + n = rrset.to_wire(self.output, self.compress, self.origin, **kw) + self.counts[section] += n + + def add_rdataset(self, section, name, rdataset, **kw): + """Add the rdataset to the specified section, using the specified + name as the owner name. + + Any keyword arguments are passed on to the rdataset's to_wire() + routine. + """ + + self._set_section(section) + with self._track_size(): + n = rdataset.to_wire(name, self.output, self.compress, self.origin, **kw) + self.counts[section] += n + + def add_opt(self, opt, pad=0, opt_size=0, tsig_size=0): + """Add *opt* to the additional section, applying padding if desired. The + padding will take the specified precomputed OPT size and TSIG size into + account. + + Note that we don't have reliable way of knowing how big a GSS-TSIG digest + might be, so we we might not get an even multiple of the pad in that case.""" + if pad: + ttl = opt.ttl + assert opt_size >= 11 + opt_rdata = opt[0] + size_without_padding = self.output.tell() + opt_size + tsig_size + remainder = size_without_padding % pad + if remainder: + pad = b"\x00" * (pad - remainder) + else: + pad = b"" + options = list(opt_rdata.options) + options.append(dns.edns.GenericOption(dns.edns.OptionType.PADDING, pad)) + opt = dns.message.Message._make_opt( # pyright: ignore + ttl, opt_rdata.rdclass, options + ) + self.was_padded = True + self.add_rrset(ADDITIONAL, opt) + + def add_edns(self, edns, ednsflags, payload, options=None): + """Add an EDNS OPT record to the message.""" + + # make sure the EDNS version in ednsflags agrees with edns + ednsflags &= 0xFF00FFFF + ednsflags |= edns << 16 + opt = dns.message.Message._make_opt( # pyright: ignore + ednsflags, payload, options + ) + self.add_opt(opt) + + def add_tsig( + self, + keyname, + secret, + fudge, + id, + tsig_error, + other_data, + request_mac, + algorithm=dns.tsig.default_algorithm, + ): + """Add a TSIG signature to the message.""" + + s = self.output.getvalue() + + if isinstance(secret, dns.tsig.Key): + key = secret + else: + key = dns.tsig.Key(keyname, secret, algorithm) + tsig = dns.message.Message._make_tsig( # pyright: ignore + keyname, algorithm, 0, fudge, b"", id, tsig_error, other_data + ) + (tsig, _) = dns.tsig.sign(s, key, tsig[0], int(time.time()), request_mac) + self._write_tsig(tsig, keyname) + + def add_multi_tsig( + self, + ctx, + keyname, + secret, + fudge, + id, + tsig_error, + other_data, + request_mac, + algorithm=dns.tsig.default_algorithm, + ): + """Add a TSIG signature to the message. Unlike add_tsig(), this can be + used for a series of consecutive DNS envelopes, e.g. for a zone + transfer over TCP [RFC2845, 4.4]. + + For the first message in the sequence, give ctx=None. For each + subsequent message, give the ctx that was returned from the + add_multi_tsig() call for the previous message.""" + + s = self.output.getvalue() + + if isinstance(secret, dns.tsig.Key): + key = secret + else: + key = dns.tsig.Key(keyname, secret, algorithm) + tsig = dns.message.Message._make_tsig( # pyright: ignore + keyname, algorithm, 0, fudge, b"", id, tsig_error, other_data + ) + (tsig, ctx) = dns.tsig.sign( + s, key, tsig[0], int(time.time()), request_mac, ctx, True + ) + self._write_tsig(tsig, keyname) + return ctx + + def _write_tsig(self, tsig, keyname): + if self.was_padded: + compress = None + else: + compress = self.compress + self._set_section(ADDITIONAL) + with self._track_size(): + keyname.to_wire(self.output, compress, self.origin) + self.output.write( + struct.pack("!HHI", dns.rdatatype.TSIG, dns.rdataclass.ANY, 0) + ) + with prefixed_length(self.output, 2): + tsig.to_wire(self.output) + + self.counts[ADDITIONAL] += 1 + with self._temporarily_seek_to(10): + self.output.write(struct.pack("!H", self.counts[ADDITIONAL])) + + def write_header(self): + """Write the DNS message header. + + Writing the DNS message header is done after all sections + have been rendered, but before the optional TSIG signature + is added. + """ + + with self._temporarily_seek_to(0): + self.output.write( + struct.pack( + "!HHHHHH", + self.id, + self.flags, + self.counts[0], + self.counts[1], + self.counts[2], + self.counts[3], + ) + ) + + def get_wire(self): + """Return the wire format message.""" + + return self.output.getvalue() + + def reserve(self, size: int) -> None: + """Reserve *size* bytes.""" + if size < 0: + raise ValueError("reserved amount must be non-negative") + if size > self.max_size: + raise ValueError("cannot reserve more than the maximum size") + self.reserved += size + self.max_size -= size + + def release_reserved(self) -> None: + """Release the reserved bytes.""" + self.max_size += self.reserved + self.reserved = 0 diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/resolver.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/resolver.py new file mode 100644 index 000000000..923bb4b46 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/resolver.py @@ -0,0 +1,2068 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +# Copyright (C) 2003-2017 Nominum, Inc. +# +# Permission to use, copy, modify, and distribute this software and its +# documentation for any purpose with or without fee is hereby granted, +# provided that the above copyright notice and this permission notice +# appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +"""DNS stub resolver.""" + +import contextlib +import random +import socket +import sys +import threading +import time +import warnings +from typing import Any, Dict, Iterator, List, Sequence, Tuple, cast +from urllib.parse import urlparse + +import dns._ddr +import dns.edns +import dns.exception +import dns.flags +import dns.inet +import dns.ipv4 +import dns.ipv6 +import dns.message +import dns.name +import dns.nameserver +import dns.query +import dns.rcode +import dns.rdata +import dns.rdataclass +import dns.rdatatype +import dns.rdtypes.ANY.PTR +import dns.rdtypes.svcbbase +import dns.reversename +import dns.tsig + +if sys.platform == "win32": # pragma: no cover + import dns.win32util + + +class NXDOMAIN(dns.exception.DNSException): + """The DNS query name does not exist.""" + + supp_kwargs = {"qnames", "responses"} + fmt = None # we have our own __str__ implementation + + # pylint: disable=arguments-differ + + # We do this as otherwise mypy complains about unexpected keyword argument + # idna_exception + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + + def _check_kwargs(self, qnames, responses=None): # pyright: ignore + if not isinstance(qnames, list | tuple | set): + raise AttributeError("qnames must be a list, tuple or set") + if len(qnames) == 0: + raise AttributeError("qnames must contain at least one element") + if responses is None: + responses = {} + elif not isinstance(responses, dict): + raise AttributeError("responses must be a dict(qname=response)") + kwargs = dict(qnames=qnames, responses=responses) + return kwargs + + def __str__(self) -> str: + if "qnames" not in self.kwargs: + return super().__str__() + qnames = self.kwargs["qnames"] + if len(qnames) > 1: + msg = "None of DNS query names exist" + else: + msg = "The DNS query name does not exist" + qnames = ", ".join(map(str, qnames)) + return f"{msg}: {qnames}" + + @property + def canonical_name(self): + """Return the unresolved canonical name.""" + if "qnames" not in self.kwargs: + raise TypeError("parametrized exception required") + for qname in self.kwargs["qnames"]: + response = self.kwargs["responses"][qname] + try: + cname = response.canonical_name() + if cname != qname: + return cname + except Exception: # pragma: no cover + # We can just eat this exception as it means there was + # something wrong with the response. + pass + return self.kwargs["qnames"][0] + + def __add__(self, e_nx): + """Augment by results from another NXDOMAIN exception.""" + qnames0 = list(self.kwargs.get("qnames", [])) + responses0 = dict(self.kwargs.get("responses", {})) + responses1 = e_nx.kwargs.get("responses", {}) + for qname1 in e_nx.kwargs.get("qnames", []): + if qname1 not in qnames0: + qnames0.append(qname1) + if qname1 in responses1: + responses0[qname1] = responses1[qname1] + return NXDOMAIN(qnames=qnames0, responses=responses0) + + def qnames(self): + """All of the names that were tried. + + Returns a list of ``dns.name.Name``. + """ + return self.kwargs["qnames"] + + def responses(self): + """A map from queried names to their NXDOMAIN responses. + + Returns a dict mapping a ``dns.name.Name`` to a + ``dns.message.Message``. + """ + return self.kwargs["responses"] + + def response(self, qname): + """The response for query *qname*. + + Returns a ``dns.message.Message``. + """ + return self.kwargs["responses"][qname] + + +class YXDOMAIN(dns.exception.DNSException): + """The DNS query name is too long after DNAME substitution.""" + + +ErrorTuple = Tuple[ + str | None, + bool, + int, + Exception | str, + dns.message.Message | None, +] + + +def _errors_to_text(errors: List[ErrorTuple]) -> List[str]: + """Turn a resolution errors trace into a list of text.""" + texts = [] + for err in errors: + texts.append(f"Server {err[0]} answered {err[3]}") + return texts + + +class LifetimeTimeout(dns.exception.Timeout): + """The resolution lifetime expired.""" + + msg = "The resolution lifetime expired." + fmt = f"{msg[:-1]} after {{timeout:.3f}} seconds: {{errors}}" + supp_kwargs = {"timeout", "errors"} + + # We do this as otherwise mypy complains about unexpected keyword argument + # idna_exception + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + + def _fmt_kwargs(self, **kwargs): + srv_msgs = _errors_to_text(kwargs["errors"]) + return super()._fmt_kwargs( + timeout=kwargs["timeout"], errors="; ".join(srv_msgs) + ) + + +# We added more detail to resolution timeouts, but they are still +# subclasses of dns.exception.Timeout for backwards compatibility. We also +# keep dns.resolver.Timeout defined for backwards compatibility. +Timeout = LifetimeTimeout + + +class NoAnswer(dns.exception.DNSException): + """The DNS response does not contain an answer to the question.""" + + fmt = "The DNS response does not contain an answer to the question: {query}" + supp_kwargs = {"response"} + + # We do this as otherwise mypy complains about unexpected keyword argument + # idna_exception + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + + def _fmt_kwargs(self, **kwargs): + return super()._fmt_kwargs(query=kwargs["response"].question) + + def response(self): + return self.kwargs["response"] + + +class NoNameservers(dns.exception.DNSException): + """All nameservers failed to answer the query. + + errors: list of servers and respective errors + The type of errors is + [(server IP address, any object convertible to string)]. + Non-empty errors list will add explanatory message () + """ + + msg = "All nameservers failed to answer the query." + fmt = f"{msg[:-1]} {{query}}: {{errors}}" + supp_kwargs = {"request", "errors"} + + # We do this as otherwise mypy complains about unexpected keyword argument + # idna_exception + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + + def _fmt_kwargs(self, **kwargs): + srv_msgs = _errors_to_text(kwargs["errors"]) + return super()._fmt_kwargs( + query=kwargs["request"].question, errors="; ".join(srv_msgs) + ) + + +class NotAbsolute(dns.exception.DNSException): + """An absolute domain name is required but a relative name was provided.""" + + +class NoRootSOA(dns.exception.DNSException): + """There is no SOA RR at the DNS root name. This should never happen!""" + + +class NoMetaqueries(dns.exception.DNSException): + """DNS metaqueries are not allowed.""" + + +class NoResolverConfiguration(dns.exception.DNSException): + """Resolver configuration could not be read or specified no nameservers.""" + + +class Answer: + """DNS stub resolver answer. + + Instances of this class bundle up the result of a successful DNS + resolution. + + For convenience, the answer object implements much of the sequence + protocol, forwarding to its ``rrset`` attribute. E.g. + ``for a in answer`` is equivalent to ``for a in answer.rrset``. + ``answer[i]`` is equivalent to ``answer.rrset[i]``, and + ``answer[i:j]`` is equivalent to ``answer.rrset[i:j]``. + + Note that CNAMEs or DNAMEs in the response may mean that answer + RRset's name might not be the query name. + """ + + def __init__( + self, + qname: dns.name.Name, + rdtype: dns.rdatatype.RdataType, + rdclass: dns.rdataclass.RdataClass, + response: dns.message.QueryMessage, + nameserver: str | None = None, + port: int | None = None, + ) -> None: + self.qname = qname + self.rdtype = rdtype + self.rdclass = rdclass + self.response = response + self.nameserver = nameserver + self.port = port + self.chaining_result = response.resolve_chaining() + # Copy some attributes out of chaining_result for backwards + # compatibility and convenience. + self.canonical_name = self.chaining_result.canonical_name + self.rrset = self.chaining_result.answer + self.expiration = time.time() + self.chaining_result.minimum_ttl + + def __getattr__(self, attr): # pragma: no cover + if self.rrset is not None: + if attr == "name": + return self.rrset.name + elif attr == "ttl": + return self.rrset.ttl + elif attr == "covers": + return self.rrset.covers + elif attr == "rdclass": + return self.rrset.rdclass + elif attr == "rdtype": + return self.rrset.rdtype + else: + raise AttributeError(attr) + + def __len__(self) -> int: + return self.rrset is not None and len(self.rrset) or 0 + + def __iter__(self) -> Iterator[Any]: + return self.rrset is not None and iter(self.rrset) or iter(tuple()) + + def __getitem__(self, i): + if self.rrset is None: + raise IndexError + return self.rrset[i] + + def __delitem__(self, i): + if self.rrset is None: + raise IndexError + del self.rrset[i] + + +class Answers(dict): + """A dict of DNS stub resolver answers, indexed by type.""" + + +class EmptyHostAnswers(dns.exception.DNSException): + """The HostAnswers has no addresses""" + + +class HostAnswers(Answers): + """A dict of DNS stub resolver answers to a host name lookup, indexed by + type. + """ + + @classmethod + def make( + cls, + v6: Answer | None = None, + v4: Answer | None = None, + add_empty: bool = True, + ) -> "HostAnswers": + answers = HostAnswers() + if v6 is not None and (add_empty or v6.rrset): + answers[dns.rdatatype.AAAA] = v6 + if v4 is not None and (add_empty or v4.rrset): + answers[dns.rdatatype.A] = v4 + return answers + + # Returns pairs of (address, family) from this result, potentially + # filtering by address family. + def addresses_and_families( + self, family: int = socket.AF_UNSPEC + ) -> Iterator[Tuple[str, int]]: + if family == socket.AF_UNSPEC: + yield from self.addresses_and_families(socket.AF_INET6) + yield from self.addresses_and_families(socket.AF_INET) + return + elif family == socket.AF_INET6: + answer = self.get(dns.rdatatype.AAAA) + elif family == socket.AF_INET: + answer = self.get(dns.rdatatype.A) + else: # pragma: no cover + raise NotImplementedError(f"unknown address family {family}") + if answer: + for rdata in answer: + yield (rdata.address, family) + + # Returns addresses from this result, potentially filtering by + # address family. + def addresses(self, family: int = socket.AF_UNSPEC) -> Iterator[str]: + return (pair[0] for pair in self.addresses_and_families(family)) + + # Returns the canonical name from this result. + def canonical_name(self) -> dns.name.Name: + answer = self.get(dns.rdatatype.AAAA, self.get(dns.rdatatype.A)) + if answer is None: + raise EmptyHostAnswers + return answer.canonical_name + + +class CacheStatistics: + """Cache Statistics""" + + def __init__(self, hits: int = 0, misses: int = 0) -> None: + self.hits = hits + self.misses = misses + + def reset(self) -> None: + self.hits = 0 + self.misses = 0 + + def clone(self) -> "CacheStatistics": + return CacheStatistics(self.hits, self.misses) + + +class CacheBase: + def __init__(self) -> None: + self.lock = threading.Lock() + self.statistics = CacheStatistics() + + def reset_statistics(self) -> None: + """Reset all statistics to zero.""" + with self.lock: + self.statistics.reset() + + def hits(self) -> int: + """How many hits has the cache had?""" + with self.lock: + return self.statistics.hits + + def misses(self) -> int: + """How many misses has the cache had?""" + with self.lock: + return self.statistics.misses + + def get_statistics_snapshot(self) -> CacheStatistics: + """Return a consistent snapshot of all the statistics. + + If running with multiple threads, it's better to take a + snapshot than to call statistics methods such as hits() and + misses() individually. + """ + with self.lock: + return self.statistics.clone() + + +CacheKey = Tuple[dns.name.Name, dns.rdatatype.RdataType, dns.rdataclass.RdataClass] + + +class Cache(CacheBase): + """Simple thread-safe DNS answer cache.""" + + def __init__(self, cleaning_interval: float = 300.0) -> None: + """*cleaning_interval*, a ``float`` is the number of seconds between + periodic cleanings. + """ + + super().__init__() + self.data: Dict[CacheKey, Answer] = {} + self.cleaning_interval = cleaning_interval + self.next_cleaning: float = time.time() + self.cleaning_interval + + def _maybe_clean(self) -> None: + """Clean the cache if it's time to do so.""" + + now = time.time() + if self.next_cleaning <= now: + keys_to_delete = [] + for k, v in self.data.items(): + if v.expiration <= now: + keys_to_delete.append(k) + for k in keys_to_delete: + del self.data[k] + now = time.time() + self.next_cleaning = now + self.cleaning_interval + + def get(self, key: CacheKey) -> Answer | None: + """Get the answer associated with *key*. + + Returns None if no answer is cached for the key. + + *key*, a ``(dns.name.Name, dns.rdatatype.RdataType, dns.rdataclass.RdataClass)`` + tuple whose values are the query name, rdtype, and rdclass respectively. + + Returns a ``dns.resolver.Answer`` or ``None``. + """ + + with self.lock: + self._maybe_clean() + v = self.data.get(key) + if v is None or v.expiration <= time.time(): + self.statistics.misses += 1 + return None + self.statistics.hits += 1 + return v + + def put(self, key: CacheKey, value: Answer) -> None: + """Associate key and value in the cache. + + *key*, a ``(dns.name.Name, dns.rdatatype.RdataType, dns.rdataclass.RdataClass)`` + tuple whose values are the query name, rdtype, and rdclass respectively. + + *value*, a ``dns.resolver.Answer``, the answer. + """ + + with self.lock: + self._maybe_clean() + self.data[key] = value + + def flush(self, key: CacheKey | None = None) -> None: + """Flush the cache. + + If *key* is not ``None``, only that item is flushed. Otherwise the entire cache + is flushed. + + *key*, a ``(dns.name.Name, dns.rdatatype.RdataType, dns.rdataclass.RdataClass)`` + tuple whose values are the query name, rdtype, and rdclass respectively. + """ + + with self.lock: + if key is not None: + if key in self.data: + del self.data[key] + else: + self.data = {} + self.next_cleaning = time.time() + self.cleaning_interval + + +class LRUCacheNode: + """LRUCache node.""" + + def __init__(self, key, value): + self.key = key + self.value = value + self.hits = 0 + self.prev = self + self.next = self + + def link_after(self, node: "LRUCacheNode") -> None: + self.prev = node + self.next = node.next + node.next.prev = self + node.next = self + + def unlink(self) -> None: + self.next.prev = self.prev + self.prev.next = self.next + + +class LRUCache(CacheBase): + """Thread-safe, bounded, least-recently-used DNS answer cache. + + This cache is better than the simple cache (above) if you're + running a web crawler or other process that does a lot of + resolutions. The LRUCache has a maximum number of nodes, and when + it is full, the least-recently used node is removed to make space + for a new one. + """ + + def __init__(self, max_size: int = 100000) -> None: + """*max_size*, an ``int``, is the maximum number of nodes to cache; + it must be greater than 0. + """ + + super().__init__() + self.data: Dict[CacheKey, LRUCacheNode] = {} + self.set_max_size(max_size) + self.sentinel: LRUCacheNode = LRUCacheNode(None, None) + self.sentinel.prev = self.sentinel + self.sentinel.next = self.sentinel + + def set_max_size(self, max_size: int) -> None: + if max_size < 1: + max_size = 1 + self.max_size = max_size + + def get(self, key: CacheKey) -> Answer | None: + """Get the answer associated with *key*. + + Returns None if no answer is cached for the key. + + *key*, a ``(dns.name.Name, dns.rdatatype.RdataType, dns.rdataclass.RdataClass)`` + tuple whose values are the query name, rdtype, and rdclass respectively. + + Returns a ``dns.resolver.Answer`` or ``None``. + """ + + with self.lock: + node = self.data.get(key) + if node is None: + self.statistics.misses += 1 + return None + # Unlink because we're either going to move the node to the front + # of the LRU list or we're going to free it. + node.unlink() + if node.value.expiration <= time.time(): + del self.data[node.key] + self.statistics.misses += 1 + return None + node.link_after(self.sentinel) + self.statistics.hits += 1 + node.hits += 1 + return node.value + + def get_hits_for_key(self, key: CacheKey) -> int: + """Return the number of cache hits associated with the specified key.""" + with self.lock: + node = self.data.get(key) + if node is None or node.value.expiration <= time.time(): + return 0 + else: + return node.hits + + def put(self, key: CacheKey, value: Answer) -> None: + """Associate key and value in the cache. + + *key*, a ``(dns.name.Name, dns.rdatatype.RdataType, dns.rdataclass.RdataClass)`` + tuple whose values are the query name, rdtype, and rdclass respectively. + + *value*, a ``dns.resolver.Answer``, the answer. + """ + + with self.lock: + node = self.data.get(key) + if node is not None: + node.unlink() + del self.data[node.key] + while len(self.data) >= self.max_size: + gnode = self.sentinel.prev + gnode.unlink() + del self.data[gnode.key] + node = LRUCacheNode(key, value) + node.link_after(self.sentinel) + self.data[key] = node + + def flush(self, key: CacheKey | None = None) -> None: + """Flush the cache. + + If *key* is not ``None``, only that item is flushed. Otherwise the entire cache + is flushed. + + *key*, a ``(dns.name.Name, dns.rdatatype.RdataType, dns.rdataclass.RdataClass)`` + tuple whose values are the query name, rdtype, and rdclass respectively. + """ + + with self.lock: + if key is not None: + node = self.data.get(key) + if node is not None: + node.unlink() + del self.data[node.key] + else: + gnode = self.sentinel.next + while gnode != self.sentinel: + next = gnode.next + gnode.unlink() + gnode = next + self.data = {} + + +class _Resolution: + """Helper class for dns.resolver.Resolver.resolve(). + + All of the "business logic" of resolution is encapsulated in this + class, allowing us to have multiple resolve() implementations + using different I/O schemes without copying all of the + complicated logic. + + This class is a "friend" to dns.resolver.Resolver and manipulates + resolver data structures directly. + """ + + def __init__( + self, + resolver: "BaseResolver", + qname: dns.name.Name | str, + rdtype: dns.rdatatype.RdataType | str, + rdclass: dns.rdataclass.RdataClass | str, + tcp: bool, + raise_on_no_answer: bool, + search: bool | None, + ) -> None: + if isinstance(qname, str): + qname = dns.name.from_text(qname, None) + rdtype = dns.rdatatype.RdataType.make(rdtype) + if dns.rdatatype.is_metatype(rdtype): + raise NoMetaqueries + rdclass = dns.rdataclass.RdataClass.make(rdclass) + if dns.rdataclass.is_metaclass(rdclass): + raise NoMetaqueries + self.resolver = resolver + self.qnames_to_try = resolver._get_qnames_to_try(qname, search) + self.qnames = self.qnames_to_try[:] + self.rdtype = rdtype + self.rdclass = rdclass + self.tcp = tcp + self.raise_on_no_answer = raise_on_no_answer + self.nxdomain_responses: Dict[dns.name.Name, dns.message.QueryMessage] = {} + # Initialize other things to help analysis tools + self.qname = dns.name.empty + self.nameservers: List[dns.nameserver.Nameserver] = [] + self.current_nameservers: List[dns.nameserver.Nameserver] = [] + self.errors: List[ErrorTuple] = [] + self.nameserver: dns.nameserver.Nameserver | None = None + self.tcp_attempt = False + self.retry_with_tcp = False + self.request: dns.message.QueryMessage | None = None + self.backoff = 0.0 + + def next_request( + self, + ) -> Tuple[dns.message.QueryMessage | None, Answer | None]: + """Get the next request to send, and check the cache. + + Returns a (request, answer) tuple. At most one of request or + answer will not be None. + """ + + # We return a tuple instead of Union[Message,Answer] as it lets + # the caller avoid isinstance(). + + while len(self.qnames) > 0: + self.qname = self.qnames.pop(0) + + # Do we know the answer? + if self.resolver.cache: + answer = self.resolver.cache.get( + (self.qname, self.rdtype, self.rdclass) + ) + if answer is not None: + if answer.rrset is None and self.raise_on_no_answer: + raise NoAnswer(response=answer.response) + else: + return (None, answer) + answer = self.resolver.cache.get( + (self.qname, dns.rdatatype.ANY, self.rdclass) + ) + if answer is not None and answer.response.rcode() == dns.rcode.NXDOMAIN: + # cached NXDOMAIN; record it and continue to next + # name. + self.nxdomain_responses[self.qname] = answer.response + continue + + # Build the request + request = dns.message.make_query(self.qname, self.rdtype, self.rdclass) + if self.resolver.keyname is not None: + request.use_tsig( + self.resolver.keyring, + self.resolver.keyname, + algorithm=self.resolver.keyalgorithm, + ) + request.use_edns( + self.resolver.edns, + self.resolver.ednsflags, + self.resolver.payload, + options=self.resolver.ednsoptions, + ) + if self.resolver.flags is not None: + request.flags = self.resolver.flags + + self.nameservers = self.resolver._enrich_nameservers( + self.resolver._nameservers, + self.resolver.nameserver_ports, + self.resolver.port, + ) + if self.resolver.rotate: + random.shuffle(self.nameservers) + self.current_nameservers = self.nameservers[:] + self.errors = [] + self.nameserver = None + self.tcp_attempt = False + self.retry_with_tcp = False + self.request = request + self.backoff = 0.10 + + return (request, None) + + # + # We've tried everything and only gotten NXDOMAINs. (We know + # it's only NXDOMAINs as anything else would have returned + # before now.) + # + raise NXDOMAIN(qnames=self.qnames_to_try, responses=self.nxdomain_responses) + + def next_nameserver(self) -> Tuple[dns.nameserver.Nameserver, bool, float]: + if self.retry_with_tcp: + assert self.nameserver is not None + assert not self.nameserver.is_always_max_size() + self.tcp_attempt = True + self.retry_with_tcp = False + return (self.nameserver, True, 0) + + backoff = 0.0 + if not self.current_nameservers: + if len(self.nameservers) == 0: + # Out of things to try! + raise NoNameservers(request=self.request, errors=self.errors) + self.current_nameservers = self.nameservers[:] + backoff = self.backoff + self.backoff = min(self.backoff * 2, 2) + + self.nameserver = self.current_nameservers.pop(0) + self.tcp_attempt = self.tcp or self.nameserver.is_always_max_size() + return (self.nameserver, self.tcp_attempt, backoff) + + def query_result( + self, response: dns.message.Message | None, ex: Exception | None + ) -> Tuple[Answer | None, bool]: + # + # returns an (answer: Answer, end_loop: bool) tuple. + # + assert self.nameserver is not None + if ex: + # Exception during I/O or from_wire() + assert response is None + self.errors.append( + ( + str(self.nameserver), + self.tcp_attempt, + self.nameserver.answer_port(), + ex, + response, + ) + ) + if ( + isinstance(ex, dns.exception.FormError) + or isinstance(ex, EOFError) + or isinstance(ex, OSError) + or isinstance(ex, NotImplementedError) + ): + # This nameserver is no good, take it out of the mix. + self.nameservers.remove(self.nameserver) + elif isinstance(ex, dns.message.Truncated): + if self.tcp_attempt: + # Truncation with TCP is no good! + self.nameservers.remove(self.nameserver) + else: + self.retry_with_tcp = True + return (None, False) + # We got an answer! + assert response is not None + assert isinstance(response, dns.message.QueryMessage) + rcode = response.rcode() + if rcode == dns.rcode.NOERROR: + try: + answer = Answer( + self.qname, + self.rdtype, + self.rdclass, + response, + self.nameserver.answer_nameserver(), + self.nameserver.answer_port(), + ) + except Exception as e: + self.errors.append( + ( + str(self.nameserver), + self.tcp_attempt, + self.nameserver.answer_port(), + e, + response, + ) + ) + # The nameserver is no good, take it out of the mix. + self.nameservers.remove(self.nameserver) + return (None, False) + if self.resolver.cache: + self.resolver.cache.put((self.qname, self.rdtype, self.rdclass), answer) + if answer.rrset is None and self.raise_on_no_answer: + raise NoAnswer(response=answer.response) + return (answer, True) + elif rcode == dns.rcode.NXDOMAIN: + # Further validate the response by making an Answer, even + # if we aren't going to cache it. + try: + answer = Answer( + self.qname, dns.rdatatype.ANY, dns.rdataclass.IN, response + ) + except Exception as e: + self.errors.append( + ( + str(self.nameserver), + self.tcp_attempt, + self.nameserver.answer_port(), + e, + response, + ) + ) + # The nameserver is no good, take it out of the mix. + self.nameservers.remove(self.nameserver) + return (None, False) + self.nxdomain_responses[self.qname] = response + if self.resolver.cache: + self.resolver.cache.put( + (self.qname, dns.rdatatype.ANY, self.rdclass), answer + ) + # Make next_nameserver() return None, so caller breaks its + # inner loop and calls next_request(). + return (None, True) + elif rcode == dns.rcode.YXDOMAIN: + yex = YXDOMAIN() + self.errors.append( + ( + str(self.nameserver), + self.tcp_attempt, + self.nameserver.answer_port(), + yex, + response, + ) + ) + raise yex + else: + # + # We got a response, but we're not happy with the + # rcode in it. + # + if rcode != dns.rcode.SERVFAIL or not self.resolver.retry_servfail: + self.nameservers.remove(self.nameserver) + self.errors.append( + ( + str(self.nameserver), + self.tcp_attempt, + self.nameserver.answer_port(), + dns.rcode.to_text(rcode), + response, + ) + ) + return (None, False) + + +class BaseResolver: + """DNS stub resolver.""" + + # We initialize in reset() + # + # pylint: disable=attribute-defined-outside-init + + domain: dns.name.Name + nameserver_ports: Dict[str, int] + port: int + search: List[dns.name.Name] + use_search_by_default: bool + timeout: float + lifetime: float + keyring: Any | None + keyname: dns.name.Name | str | None + keyalgorithm: dns.name.Name | str + edns: int + ednsflags: int + ednsoptions: List[dns.edns.Option] | None + payload: int + cache: Any + flags: int | None + retry_servfail: bool + rotate: bool + ndots: int | None + _nameservers: Sequence[str | dns.nameserver.Nameserver] + + def __init__( + self, filename: str = "/etc/resolv.conf", configure: bool = True + ) -> None: + """*filename*, a ``str`` or file object, specifying a file + in standard /etc/resolv.conf format. This parameter is meaningful + only when *configure* is true and the platform is POSIX. + + *configure*, a ``bool``. If True (the default), the resolver + instance is configured in the normal fashion for the operating + system the resolver is running on. (I.e. by reading a + /etc/resolv.conf file on POSIX systems and from the registry + on Windows systems.) + """ + + self.reset() + if configure: + if sys.platform == "win32": # pragma: no cover + self.read_registry() + elif filename: + self.read_resolv_conf(filename) + + def reset(self) -> None: + """Reset all resolver configuration to the defaults.""" + + self.domain = dns.name.Name(dns.name.from_text(socket.gethostname())[1:]) + if len(self.domain) == 0: # pragma: no cover + self.domain = dns.name.root + self._nameservers = [] + self.nameserver_ports = {} + self.port = 53 + self.search = [] + self.use_search_by_default = False + self.timeout = 2.0 + self.lifetime = 5.0 + self.keyring = None + self.keyname = None + self.keyalgorithm = dns.tsig.default_algorithm + self.edns = -1 + self.ednsflags = 0 + self.ednsoptions = None + self.payload = 0 + self.cache = None + self.flags = None + self.retry_servfail = False + self.rotate = False + self.ndots = None + + def read_resolv_conf(self, f: Any) -> None: + """Process *f* as a file in the /etc/resolv.conf format. If f is + a ``str``, it is used as the name of the file to open; otherwise it + is treated as the file itself. + + Interprets the following items: + + - nameserver - name server IP address + + - domain - local domain name + + - search - search list for host-name lookup + + - options - supported options are rotate, timeout, edns0, and ndots + + """ + + nameservers = [] + if isinstance(f, str): + try: + cm: contextlib.AbstractContextManager = open(f, encoding="utf-8") + except OSError: + # /etc/resolv.conf doesn't exist, can't be read, etc. + raise NoResolverConfiguration(f"cannot open {f}") + else: + cm = contextlib.nullcontext(f) + with cm as f: + for l in f: + if len(l) == 0 or l[0] == "#" or l[0] == ";": + continue + tokens = l.split() + + # Any line containing less than 2 tokens is malformed + if len(tokens) < 2: + continue + + if tokens[0] == "nameserver": + nameservers.append(tokens[1]) + elif tokens[0] == "domain": + self.domain = dns.name.from_text(tokens[1]) + # domain and search are exclusive + self.search = [] + elif tokens[0] == "search": + # the last search wins + self.search = [] + for suffix in tokens[1:]: + self.search.append(dns.name.from_text(suffix)) + # We don't set domain as it is not used if + # len(self.search) > 0 + elif tokens[0] == "options": + for opt in tokens[1:]: + if opt == "rotate": + self.rotate = True + elif opt == "edns0": + self.use_edns() + elif "timeout" in opt: + try: + self.timeout = int(opt.split(":")[1]) + except (ValueError, IndexError): + pass + elif "ndots" in opt: + try: + self.ndots = int(opt.split(":")[1]) + except (ValueError, IndexError): + pass + if len(nameservers) == 0: + raise NoResolverConfiguration("no nameservers") + # Assigning directly instead of appending means we invoke the + # setter logic, with additonal checking and enrichment. + self.nameservers = nameservers + + def read_registry(self) -> None: # pragma: no cover + """Extract resolver configuration from the Windows registry.""" + try: + info = dns.win32util.get_dns_info() # type: ignore + if info.domain is not None: + self.domain = info.domain + self.nameservers = info.nameservers + self.search = info.search + except AttributeError: + raise NotImplementedError + + def _compute_timeout( + self, + start: float, + lifetime: float | None = None, + errors: List[ErrorTuple] | None = None, + ) -> float: + lifetime = self.lifetime if lifetime is None else lifetime + now = time.time() + duration = now - start + if errors is None: + errors = [] + if duration < 0: + if duration < -1: + # Time going backwards is bad. Just give up. + raise LifetimeTimeout(timeout=duration, errors=errors) + else: + # Time went backwards, but only a little. This can + # happen, e.g. under vmware with older linux kernels. + # Pretend it didn't happen. + duration = 0 + if duration >= lifetime: + raise LifetimeTimeout(timeout=duration, errors=errors) + return min(lifetime - duration, self.timeout) + + def _get_qnames_to_try( + self, qname: dns.name.Name, search: bool | None + ) -> List[dns.name.Name]: + # This is a separate method so we can unit test the search + # rules without requiring the Internet. + if search is None: + search = self.use_search_by_default + qnames_to_try = [] + if qname.is_absolute(): + qnames_to_try.append(qname) + else: + abs_qname = qname.concatenate(dns.name.root) + if search: + if len(self.search) > 0: + # There is a search list, so use it exclusively + search_list = self.search[:] + elif self.domain != dns.name.root and self.domain is not None: + # We have some notion of a domain that isn't the root, so + # use it as the search list. + search_list = [self.domain] + else: + search_list = [] + # Figure out the effective ndots (default is 1) + if self.ndots is None: + ndots = 1 + else: + ndots = self.ndots + for suffix in search_list: + qnames_to_try.append(qname + suffix) + if len(qname) > ndots: + # The name has at least ndots dots, so we should try an + # absolute query first. + qnames_to_try.insert(0, abs_qname) + else: + # The name has less than ndots dots, so we should search + # first, then try the absolute name. + qnames_to_try.append(abs_qname) + else: + qnames_to_try.append(abs_qname) + return qnames_to_try + + def use_tsig( + self, + keyring: Any, + keyname: dns.name.Name | str | None = None, + algorithm: dns.name.Name | str = dns.tsig.default_algorithm, + ) -> None: + """Add a TSIG signature to each query. + + The parameters are passed to ``dns.message.Message.use_tsig()``; + see its documentation for details. + """ + + self.keyring = keyring + self.keyname = keyname + self.keyalgorithm = algorithm + + def use_edns( + self, + edns: int | bool | None = 0, + ednsflags: int = 0, + payload: int = dns.message.DEFAULT_EDNS_PAYLOAD, + options: List[dns.edns.Option] | None = None, + ) -> None: + """Configure EDNS behavior. + + *edns*, an ``int``, is the EDNS level to use. Specifying + ``None``, ``False``, or ``-1`` means "do not use EDNS", and in this case + the other parameters are ignored. Specifying ``True`` is + equivalent to specifying 0, i.e. "use EDNS0". + + *ednsflags*, an ``int``, the EDNS flag values. + + *payload*, an ``int``, is the EDNS sender's payload field, which is the + maximum size of UDP datagram the sender can handle. I.e. how big + a response to this message can be. + + *options*, a list of ``dns.edns.Option`` objects or ``None``, the EDNS + options. + """ + + if edns is None or edns is False: + edns = -1 + elif edns is True: + edns = 0 + self.edns = edns + self.ednsflags = ednsflags + self.payload = payload + self.ednsoptions = options + + def set_flags(self, flags: int) -> None: + """Overrides the default flags with your own. + + *flags*, an ``int``, the message flags to use. + """ + + self.flags = flags + + @classmethod + def _enrich_nameservers( + cls, + nameservers: Sequence[str | dns.nameserver.Nameserver], + nameserver_ports: Dict[str, int], + default_port: int, + ) -> List[dns.nameserver.Nameserver]: + enriched_nameservers = [] + if isinstance(nameservers, list | tuple): + for nameserver in nameservers: + enriched_nameserver: dns.nameserver.Nameserver + if isinstance(nameserver, dns.nameserver.Nameserver): + enriched_nameserver = nameserver + elif dns.inet.is_address(nameserver): + port = nameserver_ports.get(nameserver, default_port) + enriched_nameserver = dns.nameserver.Do53Nameserver( + nameserver, port + ) + else: + try: + if urlparse(nameserver).scheme != "https": + raise NotImplementedError + except Exception: + raise ValueError( + f"nameserver {nameserver} is not a " + "dns.nameserver.Nameserver instance or text form, " + "IP address, nor a valid https URL" + ) + enriched_nameserver = dns.nameserver.DoHNameserver(nameserver) + enriched_nameservers.append(enriched_nameserver) + else: + raise ValueError( + f"nameservers must be a list or tuple (not a {type(nameservers)})" + ) + return enriched_nameservers + + @property + def nameservers( + self, + ) -> Sequence[str | dns.nameserver.Nameserver]: + return self._nameservers + + @nameservers.setter + def nameservers( + self, nameservers: Sequence[str | dns.nameserver.Nameserver] + ) -> None: + """ + *nameservers*, a ``list`` or ``tuple`` of nameservers, where a nameserver is either + a string interpretable as a nameserver, or a ``dns.nameserver.Nameserver`` + instance. + + Raises ``ValueError`` if *nameservers* is not a list of nameservers. + """ + # We just call _enrich_nameservers() for checking + self._enrich_nameservers(nameservers, self.nameserver_ports, self.port) + self._nameservers = nameservers + + +class Resolver(BaseResolver): + """DNS stub resolver.""" + + def resolve( + self, + qname: dns.name.Name | str, + rdtype: dns.rdatatype.RdataType | str = dns.rdatatype.A, + rdclass: dns.rdataclass.RdataClass | str = dns.rdataclass.IN, + tcp: bool = False, + source: str | None = None, + raise_on_no_answer: bool = True, + source_port: int = 0, + lifetime: float | None = None, + search: bool | None = None, + ) -> Answer: # pylint: disable=arguments-differ + """Query nameservers to find the answer to the question. + + The *qname*, *rdtype*, and *rdclass* parameters may be objects + of the appropriate type, or strings that can be converted into objects + of the appropriate type. + + *qname*, a ``dns.name.Name`` or ``str``, the query name. + + *rdtype*, an ``int`` or ``str``, the query type. + + *rdclass*, an ``int`` or ``str``, the query class. + + *tcp*, a ``bool``. If ``True``, use TCP to make the query. + + *source*, a ``str`` or ``None``. If not ``None``, bind to this IP + address when making queries. + + *raise_on_no_answer*, a ``bool``. If ``True``, raise + ``dns.resolver.NoAnswer`` if there's no answer to the question. + + *source_port*, an ``int``, the port from which to send the message. + + *lifetime*, a ``float``, how many seconds a query should run + before timing out. + + *search*, a ``bool`` or ``None``, determines whether the + search list configured in the system's resolver configuration + are used for relative names, and whether the resolver's domain + may be added to relative names. The default is ``None``, + which causes the value of the resolver's + ``use_search_by_default`` attribute to be used. + + Raises ``dns.resolver.LifetimeTimeout`` if no answers could be found + in the specified lifetime. + + Raises ``dns.resolver.NXDOMAIN`` if the query name does not exist. + + Raises ``dns.resolver.YXDOMAIN`` if the query name is too long after + DNAME substitution. + + Raises ``dns.resolver.NoAnswer`` if *raise_on_no_answer* is + ``True`` and the query name exists but has no RRset of the + desired type and class. + + Raises ``dns.resolver.NoNameservers`` if no non-broken + nameservers are available to answer the question. + + Returns a ``dns.resolver.Answer`` instance. + + """ + + resolution = _Resolution( + self, qname, rdtype, rdclass, tcp, raise_on_no_answer, search + ) + start = time.time() + while True: + (request, answer) = resolution.next_request() + # Note we need to say "if answer is not None" and not just + # "if answer" because answer implements __len__, and python + # will call that. We want to return if we have an answer + # object, including in cases where its length is 0. + if answer is not None: + # cache hit! + return answer + assert request is not None # needed for type checking + done = False + while not done: + (nameserver, tcp, backoff) = resolution.next_nameserver() + if backoff: + time.sleep(backoff) + timeout = self._compute_timeout(start, lifetime, resolution.errors) + try: + response = nameserver.query( + request, + timeout=timeout, + source=source, + source_port=source_port, + max_size=tcp, + ) + except Exception as ex: + (_, done) = resolution.query_result(None, ex) + continue + (answer, done) = resolution.query_result(response, None) + # Note we need to say "if answer is not None" and not just + # "if answer" because answer implements __len__, and python + # will call that. We want to return if we have an answer + # object, including in cases where its length is 0. + if answer is not None: + return answer + + def query( + self, + qname: dns.name.Name | str, + rdtype: dns.rdatatype.RdataType | str = dns.rdatatype.A, + rdclass: dns.rdataclass.RdataClass | str = dns.rdataclass.IN, + tcp: bool = False, + source: str | None = None, + raise_on_no_answer: bool = True, + source_port: int = 0, + lifetime: float | None = None, + ) -> Answer: # pragma: no cover + """Query nameservers to find the answer to the question. + + This method calls resolve() with ``search=True``, and is + provided for backwards compatibility with prior versions of + dnspython. See the documentation for the resolve() method for + further details. + """ + warnings.warn( + "please use dns.resolver.Resolver.resolve() instead", + DeprecationWarning, + stacklevel=2, + ) + return self.resolve( + qname, + rdtype, + rdclass, + tcp, + source, + raise_on_no_answer, + source_port, + lifetime, + True, + ) + + def resolve_address(self, ipaddr: str, *args: Any, **kwargs: Any) -> Answer: + """Use a resolver to run a reverse query for PTR records. + + This utilizes the resolve() method to perform a PTR lookup on the + specified IP address. + + *ipaddr*, a ``str``, the IPv4 or IPv6 address you want to get + the PTR record for. + + All other arguments that can be passed to the resolve() function + except for rdtype and rdclass are also supported by this + function. + """ + # We make a modified kwargs for type checking happiness, as otherwise + # we get a legit warning about possibly having rdtype and rdclass + # in the kwargs more than once. + modified_kwargs: Dict[str, Any] = {} + modified_kwargs.update(kwargs) + modified_kwargs["rdtype"] = dns.rdatatype.PTR + modified_kwargs["rdclass"] = dns.rdataclass.IN + return self.resolve( + dns.reversename.from_address(ipaddr), *args, **modified_kwargs + ) + + def resolve_name( + self, + name: dns.name.Name | str, + family: int = socket.AF_UNSPEC, + **kwargs: Any, + ) -> HostAnswers: + """Use a resolver to query for address records. + + This utilizes the resolve() method to perform A and/or AAAA lookups on + the specified name. + + *qname*, a ``dns.name.Name`` or ``str``, the name to resolve. + + *family*, an ``int``, the address family. If socket.AF_UNSPEC + (the default), both A and AAAA records will be retrieved. + + All other arguments that can be passed to the resolve() function + except for rdtype and rdclass are also supported by this + function. + """ + # We make a modified kwargs for type checking happiness, as otherwise + # we get a legit warning about possibly having rdtype and rdclass + # in the kwargs more than once. + modified_kwargs: Dict[str, Any] = {} + modified_kwargs.update(kwargs) + modified_kwargs.pop("rdtype", None) + modified_kwargs["rdclass"] = dns.rdataclass.IN + + if family == socket.AF_INET: + v4 = self.resolve(name, dns.rdatatype.A, **modified_kwargs) + return HostAnswers.make(v4=v4) + elif family == socket.AF_INET6: + v6 = self.resolve(name, dns.rdatatype.AAAA, **modified_kwargs) + return HostAnswers.make(v6=v6) + elif family != socket.AF_UNSPEC: # pragma: no cover + raise NotImplementedError(f"unknown address family {family}") + + raise_on_no_answer = modified_kwargs.pop("raise_on_no_answer", True) + lifetime = modified_kwargs.pop("lifetime", None) + start = time.time() + v6 = self.resolve( + name, + dns.rdatatype.AAAA, + raise_on_no_answer=False, + lifetime=self._compute_timeout(start, lifetime), + **modified_kwargs, + ) + # Note that setting name ensures we query the same name + # for A as we did for AAAA. (This is just in case search lists + # are active by default in the resolver configuration and + # we might be talking to a server that says NXDOMAIN when it + # wants to say NOERROR no data. + name = v6.qname + v4 = self.resolve( + name, + dns.rdatatype.A, + raise_on_no_answer=False, + lifetime=self._compute_timeout(start, lifetime), + **modified_kwargs, + ) + answers = HostAnswers.make(v6=v6, v4=v4, add_empty=not raise_on_no_answer) + if not answers: + raise NoAnswer(response=v6.response) + return answers + + # pylint: disable=redefined-outer-name + + def canonical_name(self, name: dns.name.Name | str) -> dns.name.Name: + """Determine the canonical name of *name*. + + The canonical name is the name the resolver uses for queries + after all CNAME and DNAME renamings have been applied. + + *name*, a ``dns.name.Name`` or ``str``, the query name. + + This method can raise any exception that ``resolve()`` can + raise, other than ``dns.resolver.NoAnswer`` and + ``dns.resolver.NXDOMAIN``. + + Returns a ``dns.name.Name``. + """ + try: + answer = self.resolve(name, raise_on_no_answer=False) + canonical_name = answer.canonical_name + except NXDOMAIN as e: + canonical_name = e.canonical_name + return canonical_name + + # pylint: enable=redefined-outer-name + + def try_ddr(self, lifetime: float = 5.0) -> None: + """Try to update the resolver's nameservers using Discovery of Designated + Resolvers (DDR). If successful, the resolver will subsequently use + DNS-over-HTTPS or DNS-over-TLS for future queries. + + *lifetime*, a float, is the maximum time to spend attempting DDR. The default + is 5 seconds. + + If the SVCB query is successful and results in a non-empty list of nameservers, + then the resolver's nameservers are set to the returned servers in priority + order. + + The current implementation does not use any address hints from the SVCB record, + nor does it resolve addresses for the SCVB target name, rather it assumes that + the bootstrap nameserver will always be one of the addresses and uses it. + A future revision to the code may offer fuller support. The code verifies that + the bootstrap nameserver is in the Subject Alternative Name field of the + TLS certficate. + """ + try: + expiration = time.time() + lifetime + answer = self.resolve( + dns._ddr._local_resolver_name, "SVCB", lifetime=lifetime + ) + timeout = dns.query._remaining(expiration) + nameservers = dns._ddr._get_nameservers_sync(answer, timeout) + if len(nameservers) > 0: + self.nameservers = nameservers + except Exception: # pragma: no cover + pass + + +#: The default resolver. +default_resolver: Resolver | None = None + + +def get_default_resolver() -> Resolver: + """Get the default resolver, initializing it if necessary.""" + if default_resolver is None: + reset_default_resolver() + assert default_resolver is not None + return default_resolver + + +def reset_default_resolver() -> None: + """Re-initialize default resolver. + + Note that the resolver configuration (i.e. /etc/resolv.conf on UNIX + systems) will be re-read immediately. + """ + + global default_resolver + default_resolver = Resolver() + + +def resolve( + qname: dns.name.Name | str, + rdtype: dns.rdatatype.RdataType | str = dns.rdatatype.A, + rdclass: dns.rdataclass.RdataClass | str = dns.rdataclass.IN, + tcp: bool = False, + source: str | None = None, + raise_on_no_answer: bool = True, + source_port: int = 0, + lifetime: float | None = None, + search: bool | None = None, +) -> Answer: # pragma: no cover + """Query nameservers to find the answer to the question. + + This is a convenience function that uses the default resolver + object to make the query. + + See ``dns.resolver.Resolver.resolve`` for more information on the + parameters. + """ + + return get_default_resolver().resolve( + qname, + rdtype, + rdclass, + tcp, + source, + raise_on_no_answer, + source_port, + lifetime, + search, + ) + + +def query( + qname: dns.name.Name | str, + rdtype: dns.rdatatype.RdataType | str = dns.rdatatype.A, + rdclass: dns.rdataclass.RdataClass | str = dns.rdataclass.IN, + tcp: bool = False, + source: str | None = None, + raise_on_no_answer: bool = True, + source_port: int = 0, + lifetime: float | None = None, +) -> Answer: # pragma: no cover + """Query nameservers to find the answer to the question. + + This method calls resolve() with ``search=True``, and is + provided for backwards compatibility with prior versions of + dnspython. See the documentation for the resolve() method for + further details. + """ + warnings.warn( + "please use dns.resolver.resolve() instead", DeprecationWarning, stacklevel=2 + ) + return resolve( + qname, + rdtype, + rdclass, + tcp, + source, + raise_on_no_answer, + source_port, + lifetime, + True, + ) + + +def resolve_address(ipaddr: str, *args: Any, **kwargs: Any) -> Answer: + """Use a resolver to run a reverse query for PTR records. + + See ``dns.resolver.Resolver.resolve_address`` for more information on the + parameters. + """ + + return get_default_resolver().resolve_address(ipaddr, *args, **kwargs) + + +def resolve_name( + name: dns.name.Name | str, family: int = socket.AF_UNSPEC, **kwargs: Any +) -> HostAnswers: + """Use a resolver to query for address records. + + See ``dns.resolver.Resolver.resolve_name`` for more information on the + parameters. + """ + + return get_default_resolver().resolve_name(name, family, **kwargs) + + +def canonical_name(name: dns.name.Name | str) -> dns.name.Name: + """Determine the canonical name of *name*. + + See ``dns.resolver.Resolver.canonical_name`` for more information on the + parameters and possible exceptions. + """ + + return get_default_resolver().canonical_name(name) + + +def try_ddr(lifetime: float = 5.0) -> None: # pragma: no cover + """Try to update the default resolver's nameservers using Discovery of Designated + Resolvers (DDR). If successful, the resolver will subsequently use + DNS-over-HTTPS or DNS-over-TLS for future queries. + + See :py:func:`dns.resolver.Resolver.try_ddr` for more information. + """ + return get_default_resolver().try_ddr(lifetime) + + +def zone_for_name( + name: dns.name.Name | str, + rdclass: dns.rdataclass.RdataClass = dns.rdataclass.IN, + tcp: bool = False, + resolver: Resolver | None = None, + lifetime: float | None = None, +) -> dns.name.Name: # pyright: ignore[reportReturnType] + """Find the name of the zone which contains the specified name. + + *name*, an absolute ``dns.name.Name`` or ``str``, the query name. + + *rdclass*, an ``int``, the query class. + + *tcp*, a ``bool``. If ``True``, use TCP to make the query. + + *resolver*, a ``dns.resolver.Resolver`` or ``None``, the resolver to use. + If ``None``, the default, then the default resolver is used. + + *lifetime*, a ``float``, the total time to allow for the queries needed + to determine the zone. If ``None``, the default, then only the individual + query limits of the resolver apply. + + Raises ``dns.resolver.NoRootSOA`` if there is no SOA RR at the DNS + root. (This is only likely to happen if you're using non-default + root servers in your network and they are misconfigured.) + + Raises ``dns.resolver.LifetimeTimeout`` if the answer could not be + found in the allotted lifetime. + + Returns a ``dns.name.Name``. + """ + + if isinstance(name, str): + name = dns.name.from_text(name, dns.name.root) + if resolver is None: + resolver = get_default_resolver() + if not name.is_absolute(): + raise NotAbsolute(name) + start = time.time() + expiration: float | None + if lifetime is not None: + expiration = start + lifetime + else: + expiration = None + while 1: + try: + rlifetime: float | None + if expiration is not None: + rlifetime = expiration - time.time() + if rlifetime <= 0: + rlifetime = 0 + else: + rlifetime = None + answer = resolver.resolve( + name, dns.rdatatype.SOA, rdclass, tcp, lifetime=rlifetime + ) + assert answer.rrset is not None + if answer.rrset.name == name: + return name + # otherwise we were CNAMEd or DNAMEd and need to look higher + except (NXDOMAIN, NoAnswer) as e: + if isinstance(e, NXDOMAIN): + response = e.responses().get(name) + else: + response = e.response() # pylint: disable=no-value-for-parameter + if response: + for rrs in response.authority: + if rrs.rdtype == dns.rdatatype.SOA and rrs.rdclass == rdclass: + (nr, _, _) = rrs.name.fullcompare(name) + if nr == dns.name.NAMERELN_SUPERDOMAIN: + # We're doing a proper superdomain check as + # if the name were equal we ought to have gotten + # it in the answer section! We are ignoring the + # possibility that the authority is insane and + # is including multiple SOA RRs for different + # authorities. + return rrs.name + # we couldn't extract anything useful from the response (e.g. it's + # a type 3 NXDOMAIN) + try: + name = name.parent() + except dns.name.NoParent: + raise NoRootSOA + + +def make_resolver_at( + where: dns.name.Name | str, + port: int = 53, + family: int = socket.AF_UNSPEC, + resolver: Resolver | None = None, +) -> Resolver: + """Make a stub resolver using the specified destination as the full resolver. + + *where*, a ``dns.name.Name`` or ``str`` the domain name or IP address of the + full resolver. + + *port*, an ``int``, the port to use. If not specified, the default is 53. + + *family*, an ``int``, the address family to use. This parameter is used if + *where* is not an address. The default is ``socket.AF_UNSPEC`` in which case + the first address returned by ``resolve_name()`` will be used, otherwise the + first address of the specified family will be used. + + *resolver*, a ``dns.resolver.Resolver`` or ``None``, the resolver to use for + resolution of hostnames. If not specified, the default resolver will be used. + + Returns a ``dns.resolver.Resolver`` or raises an exception. + """ + if resolver is None: + resolver = get_default_resolver() + nameservers: List[str | dns.nameserver.Nameserver] = [] + if isinstance(where, str) and dns.inet.is_address(where): + nameservers.append(dns.nameserver.Do53Nameserver(where, port)) + else: + for address in resolver.resolve_name(where, family).addresses(): + nameservers.append(dns.nameserver.Do53Nameserver(address, port)) + res = Resolver(configure=False) + res.nameservers = nameservers + return res + + +def resolve_at( + where: dns.name.Name | str, + qname: dns.name.Name | str, + rdtype: dns.rdatatype.RdataType | str = dns.rdatatype.A, + rdclass: dns.rdataclass.RdataClass | str = dns.rdataclass.IN, + tcp: bool = False, + source: str | None = None, + raise_on_no_answer: bool = True, + source_port: int = 0, + lifetime: float | None = None, + search: bool | None = None, + port: int = 53, + family: int = socket.AF_UNSPEC, + resolver: Resolver | None = None, +) -> Answer: + """Query nameservers to find the answer to the question. + + This is a convenience function that calls ``dns.resolver.make_resolver_at()`` to + make a resolver, and then uses it to resolve the query. + + See ``dns.resolver.Resolver.resolve`` for more information on the resolution + parameters, and ``dns.resolver.make_resolver_at`` for information about the resolver + parameters *where*, *port*, *family*, and *resolver*. + + If making more than one query, it is more efficient to call + ``dns.resolver.make_resolver_at()`` and then use that resolver for the queries + instead of calling ``resolve_at()`` multiple times. + """ + return make_resolver_at(where, port, family, resolver).resolve( + qname, + rdtype, + rdclass, + tcp, + source, + raise_on_no_answer, + source_port, + lifetime, + search, + ) + + +# +# Support for overriding the system resolver for all python code in the +# running process. +# + +_protocols_for_socktype: Dict[Any, List[Any]] = { + socket.SOCK_DGRAM: [socket.SOL_UDP], + socket.SOCK_STREAM: [socket.SOL_TCP], +} + +_resolver: Resolver | None = None +_original_getaddrinfo = socket.getaddrinfo +_original_getnameinfo = socket.getnameinfo +_original_getfqdn = socket.getfqdn +_original_gethostbyname = socket.gethostbyname +_original_gethostbyname_ex = socket.gethostbyname_ex +_original_gethostbyaddr = socket.gethostbyaddr + + +def _getaddrinfo( + host=None, service=None, family=socket.AF_UNSPEC, socktype=0, proto=0, flags=0 +): + if flags & socket.AI_NUMERICHOST != 0: + # Short circuit directly into the system's getaddrinfo(). We're + # not adding any value in this case, and this avoids infinite loops + # because dns.query.* needs to call getaddrinfo() for IPv6 scoping + # reasons. We will also do this short circuit below if we + # discover that the host is an address literal. + return _original_getaddrinfo(host, service, family, socktype, proto, flags) + if flags & (socket.AI_ADDRCONFIG | socket.AI_V4MAPPED) != 0: + # Not implemented. We raise a gaierror as opposed to a + # NotImplementedError as it helps callers handle errors more + # appropriately. [Issue #316] + # + # We raise EAI_FAIL as opposed to EAI_SYSTEM because there is + # no EAI_SYSTEM on Windows [Issue #416]. We didn't go for + # EAI_BADFLAGS as the flags aren't bad, we just don't + # implement them. + raise socket.gaierror( + socket.EAI_FAIL, "Non-recoverable failure in name resolution" + ) + if host is None and service is None: + raise socket.gaierror(socket.EAI_NONAME, "Name or service not known") + addrs = [] + canonical_name = None # pylint: disable=redefined-outer-name + # Is host None or an address literal? If so, use the system's + # getaddrinfo(). + if host is None: + return _original_getaddrinfo(host, service, family, socktype, proto, flags) + try: + # We don't care about the result of af_for_address(), we're just + # calling it so it raises an exception if host is not an IPv4 or + # IPv6 address. + dns.inet.af_for_address(host) + return _original_getaddrinfo(host, service, family, socktype, proto, flags) + except Exception: + pass + # Something needs resolution! + try: + assert _resolver is not None + answers = _resolver.resolve_name(host, family) + addrs = answers.addresses_and_families() + canonical_name = answers.canonical_name().to_text(True) + except NXDOMAIN: + raise socket.gaierror(socket.EAI_NONAME, "Name or service not known") + except Exception: + # We raise EAI_AGAIN here as the failure may be temporary + # (e.g. a timeout) and EAI_SYSTEM isn't defined on Windows. + # [Issue #416] + raise socket.gaierror(socket.EAI_AGAIN, "Temporary failure in name resolution") + port = None + try: + # Is it a port literal? + if service is None: + port = 0 + else: + port = int(service) + except Exception: + if flags & socket.AI_NUMERICSERV == 0: + try: + port = socket.getservbyname(service) # pyright: ignore + except Exception: + pass + if port is None: + raise socket.gaierror(socket.EAI_NONAME, "Name or service not known") + tuples = [] + if socktype == 0: + socktypes = [socket.SOCK_DGRAM, socket.SOCK_STREAM] + else: + socktypes = [socktype] + if flags & socket.AI_CANONNAME != 0: + cname = canonical_name + else: + cname = "" + for addr, af in addrs: + for socktype in socktypes: + for sockproto in _protocols_for_socktype[socktype]: + proto = int(sockproto) + addr_tuple = dns.inet.low_level_address_tuple((addr, port), af) + tuples.append((af, socktype, proto, cname, addr_tuple)) + if len(tuples) == 0: + raise socket.gaierror(socket.EAI_NONAME, "Name or service not known") + return tuples + + +def _getnameinfo(sockaddr, flags=0): + host = sockaddr[0] + port = sockaddr[1] + if len(sockaddr) == 4: + scope = sockaddr[3] + family = socket.AF_INET6 + else: + scope = None + family = socket.AF_INET + tuples = _getaddrinfo(host, port, family, socket.SOCK_STREAM, socket.SOL_TCP, 0) + if len(tuples) > 1: + raise OSError("sockaddr resolved to multiple addresses") + addr = tuples[0][4][0] + if flags & socket.NI_DGRAM: + pname = "udp" + else: + pname = "tcp" + assert isinstance(addr, str) + qname = dns.reversename.from_address(addr) + if flags & socket.NI_NUMERICHOST == 0: + try: + assert _resolver is not None + answer = _resolver.resolve(qname, "PTR") + assert answer.rrset is not None + rdata = cast(dns.rdtypes.ANY.PTR.PTR, answer.rrset[0]) + hostname = rdata.target.to_text(True) + except (NXDOMAIN, NoAnswer): + if flags & socket.NI_NAMEREQD: + raise socket.gaierror(socket.EAI_NONAME, "Name or service not known") + hostname = addr + if scope is not None: + hostname += "%" + str(scope) + else: + hostname = addr + if scope is not None: + hostname += "%" + str(scope) + if flags & socket.NI_NUMERICSERV: + service = str(port) + else: + service = socket.getservbyport(port, pname) + return (hostname, service) + + +def _getfqdn(name=None): + if name is None: + name = socket.gethostname() + try: + (name, _, _) = _gethostbyaddr(name) + # Python's version checks aliases too, but our gethostbyname + # ignores them, so we do so here as well. + except Exception: # pragma: no cover + pass + return name + + +def _gethostbyname(name): + return _gethostbyname_ex(name)[2][0] + + +def _gethostbyname_ex(name): + aliases = [] + addresses = [] + tuples = _getaddrinfo( + name, 0, socket.AF_INET, socket.SOCK_STREAM, socket.SOL_TCP, socket.AI_CANONNAME + ) + canonical = tuples[0][3] + for item in tuples: + addresses.append(item[4][0]) + # XXX we just ignore aliases + return (canonical, aliases, addresses) + + +def _gethostbyaddr(ip): + try: + dns.ipv6.inet_aton(ip) + sockaddr = (ip, 80, 0, 0) + family = socket.AF_INET6 + except Exception: + try: + dns.ipv4.inet_aton(ip) + except Exception: + raise socket.gaierror(socket.EAI_NONAME, "Name or service not known") + sockaddr = (ip, 80) + family = socket.AF_INET + (name, _) = _getnameinfo(sockaddr, socket.NI_NAMEREQD) + aliases = [] + addresses = [] + tuples = _getaddrinfo( + name, 0, family, socket.SOCK_STREAM, socket.SOL_TCP, socket.AI_CANONNAME + ) + canonical = tuples[0][3] + # We only want to include an address from the tuples if it's the + # same as the one we asked about. We do this comparison in binary + # to avoid any differences in text representations. + bin_ip = dns.inet.inet_pton(family, ip) + for item in tuples: + addr = item[4][0] + assert isinstance(addr, str) + bin_addr = dns.inet.inet_pton(family, addr) + if bin_ip == bin_addr: + addresses.append(addr) + # XXX we just ignore aliases + return (canonical, aliases, addresses) + + +def override_system_resolver(resolver: Resolver | None = None) -> None: + """Override the system resolver routines in the socket module with + versions which use dnspython's resolver. + + This can be useful in testing situations where you want to control + the resolution behavior of python code without having to change + the system's resolver settings (e.g. /etc/resolv.conf). + + The resolver to use may be specified; if it's not, the default + resolver will be used. + + resolver, a ``dns.resolver.Resolver`` or ``None``, the resolver to use. + """ + + if resolver is None: + resolver = get_default_resolver() + global _resolver + _resolver = resolver + socket.getaddrinfo = _getaddrinfo + socket.getnameinfo = _getnameinfo + socket.getfqdn = _getfqdn + socket.gethostbyname = _gethostbyname + socket.gethostbyname_ex = _gethostbyname_ex + socket.gethostbyaddr = _gethostbyaddr + + +def restore_system_resolver() -> None: + """Undo the effects of prior override_system_resolver().""" + + global _resolver + _resolver = None + socket.getaddrinfo = _original_getaddrinfo + socket.getnameinfo = _original_getnameinfo + socket.getfqdn = _original_getfqdn + socket.gethostbyname = _original_gethostbyname + socket.gethostbyname_ex = _original_gethostbyname_ex + socket.gethostbyaddr = _original_gethostbyaddr diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/reversename.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/reversename.py new file mode 100644 index 000000000..60a4e839a --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/reversename.py @@ -0,0 +1,106 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +# Copyright (C) 2006-2017 Nominum, Inc. +# +# Permission to use, copy, modify, and distribute this software and its +# documentation for any purpose with or without fee is hereby granted, +# provided that the above copyright notice and this permission notice +# appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +"""DNS Reverse Map Names.""" + +import binascii + +import dns.exception +import dns.ipv4 +import dns.ipv6 +import dns.name + +ipv4_reverse_domain = dns.name.from_text("in-addr.arpa.") +ipv6_reverse_domain = dns.name.from_text("ip6.arpa.") + + +def from_address( + text: str, + v4_origin: dns.name.Name = ipv4_reverse_domain, + v6_origin: dns.name.Name = ipv6_reverse_domain, +) -> dns.name.Name: + """Convert an IPv4 or IPv6 address in textual form into a Name object whose + value is the reverse-map domain name of the address. + + *text*, a ``str``, is an IPv4 or IPv6 address in textual form + (e.g. '127.0.0.1', '::1') + + *v4_origin*, a ``dns.name.Name`` to append to the labels corresponding to + the address if the address is an IPv4 address, instead of the default + (in-addr.arpa.) + + *v6_origin*, a ``dns.name.Name`` to append to the labels corresponding to + the address if the address is an IPv6 address, instead of the default + (ip6.arpa.) + + Raises ``dns.exception.SyntaxError`` if the address is badly formed. + + Returns a ``dns.name.Name``. + """ + + try: + v6 = dns.ipv6.inet_aton(text) + if dns.ipv6.is_mapped(v6): + parts = [str(byte) for byte in v6[12:]] + origin = v4_origin + else: + parts = [x for x in str(binascii.hexlify(v6).decode())] + origin = v6_origin + except Exception: + parts = [str(byte) for byte in dns.ipv4.inet_aton(text)] + origin = v4_origin + return dns.name.from_text(".".join(reversed(parts)), origin=origin) + + +def to_address( + name: dns.name.Name, + v4_origin: dns.name.Name = ipv4_reverse_domain, + v6_origin: dns.name.Name = ipv6_reverse_domain, +) -> str: + """Convert a reverse map domain name into textual address form. + + *name*, a ``dns.name.Name``, an IPv4 or IPv6 address in reverse-map name + form. + + *v4_origin*, a ``dns.name.Name`` representing the top-level domain for + IPv4 addresses, instead of the default (in-addr.arpa.) + + *v6_origin*, a ``dns.name.Name`` representing the top-level domain for + IPv4 addresses, instead of the default (ip6.arpa.) + + Raises ``dns.exception.SyntaxError`` if the name does not have a + reverse-map form. + + Returns a ``str``. + """ + + if name.is_subdomain(v4_origin): + name = name.relativize(v4_origin) + text = b".".join(reversed(name.labels)) + # run through inet_ntoa() to check syntax and make pretty. + return dns.ipv4.inet_ntoa(dns.ipv4.inet_aton(text)) + elif name.is_subdomain(v6_origin): + name = name.relativize(v6_origin) + labels = list(reversed(name.labels)) + parts = [] + for i in range(0, len(labels), 4): + parts.append(b"".join(labels[i : i + 4])) + text = b":".join(parts) + # run through inet_ntoa() to check syntax and make pretty. + return dns.ipv6.inet_ntoa(dns.ipv6.inet_aton(text)) + else: + raise dns.exception.SyntaxError("unknown reverse-map address family") diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rrset.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rrset.py new file mode 100644 index 000000000..271ddbe86 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/rrset.py @@ -0,0 +1,287 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +# Copyright (C) 2003-2017 Nominum, Inc. +# +# Permission to use, copy, modify, and distribute this software and its +# documentation for any purpose with or without fee is hereby granted, +# provided that the above copyright notice and this permission notice +# appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +"""DNS RRsets (an RRset is a named rdataset)""" + +from typing import Any, Collection, Dict, cast + +import dns.name +import dns.rdata +import dns.rdataclass +import dns.rdataset +import dns.rdatatype +import dns.renderer + + +class RRset(dns.rdataset.Rdataset): + """A DNS RRset (named rdataset). + + RRset inherits from Rdataset, and RRsets can be treated as + Rdatasets in most cases. There are, however, a few notable + exceptions. RRsets have different to_wire() and to_text() method + arguments, reflecting the fact that RRsets always have an owner + name. + """ + + __slots__ = ["name", "deleting"] + + def __init__( + self, + name: dns.name.Name, + rdclass: dns.rdataclass.RdataClass, + rdtype: dns.rdatatype.RdataType, + covers: dns.rdatatype.RdataType = dns.rdatatype.NONE, + deleting: dns.rdataclass.RdataClass | None = None, + ): + """Create a new RRset.""" + + super().__init__(rdclass, rdtype, covers) + self.name = name + self.deleting = deleting + + def _clone(self): + obj = cast(RRset, super()._clone()) + obj.name = self.name + obj.deleting = self.deleting + return obj + + def __repr__(self): + if self.covers == 0: + ctext = "" + else: + ctext = "(" + dns.rdatatype.to_text(self.covers) + ")" + if self.deleting is not None: + dtext = " delete=" + dns.rdataclass.to_text(self.deleting) + else: + dtext = "" + return ( + "" + ) + + def __str__(self): + return self.to_text() + + def __eq__(self, other): + if isinstance(other, RRset): + if self.name != other.name: + return False + elif not isinstance(other, dns.rdataset.Rdataset): + return False + return super().__eq__(other) + + def match(self, *args: Any, **kwargs: Any) -> bool: # type: ignore[override] + """Does this rrset match the specified attributes? + + Behaves as :py:func:`full_match()` if the first argument is a + ``dns.name.Name``, and as :py:func:`dns.rdataset.Rdataset.match()` + otherwise. + + (This behavior fixes a design mistake where the signature of this + method became incompatible with that of its superclass. The fix + makes RRsets matchable as Rdatasets while preserving backwards + compatibility.) + """ + if isinstance(args[0], dns.name.Name): + return self.full_match(*args, **kwargs) # type: ignore[arg-type] + else: + return super().match(*args, **kwargs) # type: ignore[arg-type] + + def full_match( + self, + name: dns.name.Name, + rdclass: dns.rdataclass.RdataClass, + rdtype: dns.rdatatype.RdataType, + covers: dns.rdatatype.RdataType, + deleting: dns.rdataclass.RdataClass | None = None, + ) -> bool: + """Returns ``True`` if this rrset matches the specified name, class, + type, covers, and deletion state. + """ + if not super().match(rdclass, rdtype, covers): + return False + if self.name != name or self.deleting != deleting: + return False + return True + + # pylint: disable=arguments-differ + + def to_text( # type: ignore[override] + self, + origin: dns.name.Name | None = None, + relativize: bool = True, + **kw: Dict[str, Any], + ) -> str: + """Convert the RRset into DNS zone file format. + + See ``dns.name.Name.choose_relativity`` for more information + on how *origin* and *relativize* determine the way names + are emitted. + + Any additional keyword arguments are passed on to the rdata + ``to_text()`` method. + + *origin*, a ``dns.name.Name`` or ``None``, the origin for relative + names. + + *relativize*, a ``bool``. If ``True``, names will be relativized + to *origin*. + """ + + return super().to_text( + self.name, origin, relativize, self.deleting, **kw # type: ignore + ) + + def to_wire( # type: ignore[override] + self, + file: Any, + compress: dns.name.CompressType | None = None, # type: ignore + origin: dns.name.Name | None = None, + **kw: Dict[str, Any], + ) -> int: + """Convert the RRset to wire format. + + All keyword arguments are passed to ``dns.rdataset.to_wire()``; see + that function for details. + + Returns an ``int``, the number of records emitted. + """ + + return super().to_wire( + self.name, file, compress, origin, self.deleting, **kw # type:ignore + ) + + # pylint: enable=arguments-differ + + def to_rdataset(self) -> dns.rdataset.Rdataset: + """Convert an RRset into an Rdataset. + + Returns a ``dns.rdataset.Rdataset``. + """ + return dns.rdataset.from_rdata_list(self.ttl, list(self)) + + +def from_text_list( + name: dns.name.Name | str, + ttl: int, + rdclass: dns.rdataclass.RdataClass | str, + rdtype: dns.rdatatype.RdataType | str, + text_rdatas: Collection[str], + idna_codec: dns.name.IDNACodec | None = None, + origin: dns.name.Name | None = None, + relativize: bool = True, + relativize_to: dns.name.Name | None = None, +) -> RRset: + """Create an RRset with the specified name, TTL, class, and type, and with + the specified list of rdatas in text format. + + *idna_codec*, a ``dns.name.IDNACodec``, specifies the IDNA + encoder/decoder to use; if ``None``, the default IDNA 2003 + encoder/decoder is used. + + *origin*, a ``dns.name.Name`` (or ``None``), the + origin to use for relative names. + + *relativize*, a ``bool``. If true, name will be relativized. + + *relativize_to*, a ``dns.name.Name`` (or ``None``), the origin to use + when relativizing names. If not set, the *origin* value will be used. + + Returns a ``dns.rrset.RRset`` object. + """ + + if isinstance(name, str): + name = dns.name.from_text(name, None, idna_codec=idna_codec) + rdclass = dns.rdataclass.RdataClass.make(rdclass) + rdtype = dns.rdatatype.RdataType.make(rdtype) + r = RRset(name, rdclass, rdtype) + r.update_ttl(ttl) + for t in text_rdatas: + rd = dns.rdata.from_text( + r.rdclass, r.rdtype, t, origin, relativize, relativize_to, idna_codec + ) + r.add(rd) + return r + + +def from_text( + name: dns.name.Name | str, + ttl: int, + rdclass: dns.rdataclass.RdataClass | str, + rdtype: dns.rdatatype.RdataType | str, + *text_rdatas: Any, +) -> RRset: + """Create an RRset with the specified name, TTL, class, and type and with + the specified rdatas in text format. + + Returns a ``dns.rrset.RRset`` object. + """ + + return from_text_list( + name, ttl, rdclass, rdtype, cast(Collection[str], text_rdatas) + ) + + +def from_rdata_list( + name: dns.name.Name | str, + ttl: int, + rdatas: Collection[dns.rdata.Rdata], + idna_codec: dns.name.IDNACodec | None = None, +) -> RRset: + """Create an RRset with the specified name and TTL, and with + the specified list of rdata objects. + + *idna_codec*, a ``dns.name.IDNACodec``, specifies the IDNA + encoder/decoder to use; if ``None``, the default IDNA 2003 + encoder/decoder is used. + + Returns a ``dns.rrset.RRset`` object. + + """ + + if isinstance(name, str): + name = dns.name.from_text(name, None, idna_codec=idna_codec) + + if len(rdatas) == 0: + raise ValueError("rdata list must not be empty") + r = None + for rd in rdatas: + if r is None: + r = RRset(name, rd.rdclass, rd.rdtype) + r.update_ttl(ttl) + r.add(rd) + assert r is not None + return r + + +def from_rdata(name: dns.name.Name | str, ttl: int, *rdatas: Any) -> RRset: + """Create an RRset with the specified name and TTL, and with + the specified rdata objects. + + Returns a ``dns.rrset.RRset`` object. + """ + + return from_rdata_list(name, ttl, cast(Collection[dns.rdata.Rdata], rdatas)) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/serial.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/serial.py new file mode 100644 index 000000000..3417299be --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/serial.py @@ -0,0 +1,118 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +"""Serial Number Arthimetic from RFC 1982""" + + +class Serial: + def __init__(self, value: int, bits: int = 32): + self.value = value % 2**bits + self.bits = bits + + def __repr__(self): + return f"dns.serial.Serial({self.value}, {self.bits})" + + def __eq__(self, other): + if isinstance(other, int): + other = Serial(other, self.bits) + elif not isinstance(other, Serial) or other.bits != self.bits: + return NotImplemented + return self.value == other.value + + def __ne__(self, other): + if isinstance(other, int): + other = Serial(other, self.bits) + elif not isinstance(other, Serial) or other.bits != self.bits: + return NotImplemented + return self.value != other.value + + def __lt__(self, other): + if isinstance(other, int): + other = Serial(other, self.bits) + elif not isinstance(other, Serial) or other.bits != self.bits: + return NotImplemented + if self.value < other.value and other.value - self.value < 2 ** (self.bits - 1): + return True + elif self.value > other.value and self.value - other.value > 2 ** ( + self.bits - 1 + ): + return True + else: + return False + + def __le__(self, other): + return self == other or self < other + + def __gt__(self, other): + if isinstance(other, int): + other = Serial(other, self.bits) + elif not isinstance(other, Serial) or other.bits != self.bits: + return NotImplemented + if self.value < other.value and other.value - self.value > 2 ** (self.bits - 1): + return True + elif self.value > other.value and self.value - other.value < 2 ** ( + self.bits - 1 + ): + return True + else: + return False + + def __ge__(self, other): + return self == other or self > other + + def __add__(self, other): + v = self.value + if isinstance(other, Serial): + delta = other.value + elif isinstance(other, int): + delta = other + else: + raise ValueError + if abs(delta) > (2 ** (self.bits - 1) - 1): + raise ValueError + v += delta + v = v % 2**self.bits + return Serial(v, self.bits) + + def __iadd__(self, other): + v = self.value + if isinstance(other, Serial): + delta = other.value + elif isinstance(other, int): + delta = other + else: + raise ValueError + if abs(delta) > (2 ** (self.bits - 1) - 1): + raise ValueError + v += delta + v = v % 2**self.bits + self.value = v + return self + + def __sub__(self, other): + v = self.value + if isinstance(other, Serial): + delta = other.value + elif isinstance(other, int): + delta = other + else: + raise ValueError + if abs(delta) > (2 ** (self.bits - 1) - 1): + raise ValueError + v -= delta + v = v % 2**self.bits + return Serial(v, self.bits) + + def __isub__(self, other): + v = self.value + if isinstance(other, Serial): + delta = other.value + elif isinstance(other, int): + delta = other + else: + raise ValueError + if abs(delta) > (2 ** (self.bits - 1) - 1): + raise ValueError + v -= delta + v = v % 2**self.bits + self.value = v + return self diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/set.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/set.py new file mode 100644 index 000000000..ae8f0dd50 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/set.py @@ -0,0 +1,308 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +# Copyright (C) 2003-2017 Nominum, Inc. +# +# Permission to use, copy, modify, and distribute this software and its +# documentation for any purpose with or without fee is hereby granted, +# provided that the above copyright notice and this permission notice +# appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +import itertools + + +class Set: + """A simple set class. + + This class was originally used to deal with python not having a set class, and + originally the class used lists in its implementation. The ordered and indexable + nature of RRsets and Rdatasets is unfortunately widely used in dnspython + applications, so for backwards compatibility sets continue to be a custom class, now + based on an ordered dictionary. + """ + + __slots__ = ["items"] + + def __init__(self, items=None): + """Initialize the set. + + *items*, an iterable or ``None``, the initial set of items. + """ + + self.items = dict() + if items is not None: + for item in items: + # This is safe for how we use set, but if other code + # subclasses it could be a legitimate issue. + self.add(item) # lgtm[py/init-calls-subclass] + + def __repr__(self): + return f"dns.set.Set({repr(list(self.items.keys()))})" # pragma: no cover + + def add(self, item): + """Add an item to the set.""" + + if item not in self.items: + self.items[item] = None + + def remove(self, item): + """Remove an item from the set.""" + + try: + del self.items[item] + except KeyError: + raise ValueError + + def discard(self, item): + """Remove an item from the set if present.""" + + self.items.pop(item, None) + + def pop(self): + """Remove an arbitrary item from the set.""" + (k, _) = self.items.popitem() + return k + + def _clone(self) -> "Set": + """Make a (shallow) copy of the set. + + There is a 'clone protocol' that subclasses of this class + should use. To make a copy, first call your super's _clone() + method, and use the object returned as the new instance. Then + make shallow copies of the attributes defined in the subclass. + + This protocol allows us to write the set algorithms that + return new instances (e.g. union) once, and keep using them in + subclasses. + """ + + if hasattr(self, "_clone_class"): + cls = self._clone_class # type: ignore + else: + cls = self.__class__ + obj = cls.__new__(cls) + obj.items = dict() + obj.items.update(self.items) + return obj + + def __copy__(self): + """Make a (shallow) copy of the set.""" + + return self._clone() + + def copy(self): + """Make a (shallow) copy of the set.""" + + return self._clone() + + def union_update(self, other): + """Update the set, adding any elements from other which are not + already in the set. + """ + + if not isinstance(other, Set): + raise ValueError("other must be a Set instance") + if self is other: # lgtm[py/comparison-using-is] + return + for item in other.items: + self.add(item) + + def intersection_update(self, other): + """Update the set, removing any elements from other which are not + in both sets. + """ + + if not isinstance(other, Set): + raise ValueError("other must be a Set instance") + if self is other: # lgtm[py/comparison-using-is] + return + # we make a copy of the list so that we can remove items from + # the list without breaking the iterator. + for item in list(self.items): + if item not in other.items: + del self.items[item] + + def difference_update(self, other): + """Update the set, removing any elements from other which are in + the set. + """ + + if not isinstance(other, Set): + raise ValueError("other must be a Set instance") + if self is other: # lgtm[py/comparison-using-is] + self.items.clear() + else: + for item in other.items: + self.discard(item) + + def symmetric_difference_update(self, other): + """Update the set, retaining only elements unique to both sets.""" + + if not isinstance(other, Set): + raise ValueError("other must be a Set instance") + if self is other: # lgtm[py/comparison-using-is] + self.items.clear() + else: + overlap = self.intersection(other) + self.union_update(other) + self.difference_update(overlap) + + def union(self, other): + """Return a new set which is the union of ``self`` and ``other``. + + Returns the same Set type as this set. + """ + + obj = self._clone() + obj.union_update(other) + return obj + + def intersection(self, other): + """Return a new set which is the intersection of ``self`` and + ``other``. + + Returns the same Set type as this set. + """ + + obj = self._clone() + obj.intersection_update(other) + return obj + + def difference(self, other): + """Return a new set which ``self`` - ``other``, i.e. the items + in ``self`` which are not also in ``other``. + + Returns the same Set type as this set. + """ + + obj = self._clone() + obj.difference_update(other) + return obj + + def symmetric_difference(self, other): + """Return a new set which (``self`` - ``other``) | (``other`` + - ``self), ie: the items in either ``self`` or ``other`` which + are not contained in their intersection. + + Returns the same Set type as this set. + """ + + obj = self._clone() + obj.symmetric_difference_update(other) + return obj + + def __or__(self, other): + return self.union(other) + + def __and__(self, other): + return self.intersection(other) + + def __add__(self, other): + return self.union(other) + + def __sub__(self, other): + return self.difference(other) + + def __xor__(self, other): + return self.symmetric_difference(other) + + def __ior__(self, other): + self.union_update(other) + return self + + def __iand__(self, other): + self.intersection_update(other) + return self + + def __iadd__(self, other): + self.union_update(other) + return self + + def __isub__(self, other): + self.difference_update(other) + return self + + def __ixor__(self, other): + self.symmetric_difference_update(other) + return self + + def update(self, other): + """Update the set, adding any elements from other which are not + already in the set. + + *other*, the collection of items with which to update the set, which + may be any iterable type. + """ + + for item in other: + self.add(item) + + def clear(self): + """Make the set empty.""" + self.items.clear() + + def __eq__(self, other): + return self.items == other.items + + def __ne__(self, other): + return not self.__eq__(other) + + def __len__(self): + return len(self.items) + + def __iter__(self): + return iter(self.items) + + def __getitem__(self, i): + if isinstance(i, slice): + return list(itertools.islice(self.items, i.start, i.stop, i.step)) + else: + return next(itertools.islice(self.items, i, i + 1)) + + def __delitem__(self, i): + if isinstance(i, slice): + for elt in list(self[i]): + del self.items[elt] + else: + del self.items[self[i]] + + def issubset(self, other): + """Is this set a subset of *other*? + + Returns a ``bool``. + """ + + if not isinstance(other, Set): + raise ValueError("other must be a Set instance") + for item in self.items: + if item not in other.items: + return False + return True + + def issuperset(self, other): + """Is this set a superset of *other*? + + Returns a ``bool``. + """ + + if not isinstance(other, Set): + raise ValueError("other must be a Set instance") + for item in other.items: + if item not in self.items: + return False + return True + + def isdisjoint(self, other): + if not isinstance(other, Set): + raise ValueError("other must be a Set instance") + for item in other.items: + if item in self.items: + return False + return True diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/tokenizer.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/tokenizer.py new file mode 100644 index 000000000..86ae3e2d7 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/tokenizer.py @@ -0,0 +1,706 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +# Copyright (C) 2003-2017 Nominum, Inc. +# +# Permission to use, copy, modify, and distribute this software and its +# documentation for any purpose with or without fee is hereby granted, +# provided that the above copyright notice and this permission notice +# appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +"""Tokenize DNS zone file format""" + +import io +import sys +from typing import Any, List, Tuple + +import dns.exception +import dns.name +import dns.ttl + +_DELIMITERS = {" ", "\t", "\n", ";", "(", ")", '"'} +_QUOTING_DELIMITERS = {'"'} + +EOF = 0 +EOL = 1 +WHITESPACE = 2 +IDENTIFIER = 3 +QUOTED_STRING = 4 +COMMENT = 5 +DELIMITER = 6 + + +class UngetBufferFull(dns.exception.DNSException): + """An attempt was made to unget a token when the unget buffer was full.""" + + +class Token: + """A DNS zone file format token. + + ttype: The token type + value: The token value + has_escape: Does the token value contain escapes? + """ + + def __init__( + self, + ttype: int, + value: Any = "", + has_escape: bool = False, + comment: str | None = None, + ): + """Initialize a token instance.""" + + self.ttype = ttype + self.value = value + self.has_escape = has_escape + self.comment = comment + + def is_eof(self) -> bool: + return self.ttype == EOF + + def is_eol(self) -> bool: + return self.ttype == EOL + + def is_whitespace(self) -> bool: + return self.ttype == WHITESPACE + + def is_identifier(self) -> bool: + return self.ttype == IDENTIFIER + + def is_quoted_string(self) -> bool: + return self.ttype == QUOTED_STRING + + def is_comment(self) -> bool: + return self.ttype == COMMENT + + def is_delimiter(self) -> bool: # pragma: no cover (we don't return delimiters yet) + return self.ttype == DELIMITER + + def is_eol_or_eof(self) -> bool: + return self.ttype == EOL or self.ttype == EOF + + def __eq__(self, other): + if not isinstance(other, Token): + return False + return self.ttype == other.ttype and self.value == other.value + + def __ne__(self, other): + if not isinstance(other, Token): + return True + return self.ttype != other.ttype or self.value != other.value + + def __str__(self): + return f'{self.ttype} "{self.value}"' + + def unescape(self) -> "Token": + if not self.has_escape: + return self + unescaped = "" + l = len(self.value) + i = 0 + while i < l: + c = self.value[i] + i += 1 + if c == "\\": + if i >= l: # pragma: no cover (can't happen via get()) + raise dns.exception.UnexpectedEnd + c = self.value[i] + i += 1 + if c.isdigit(): + if i >= l: + raise dns.exception.UnexpectedEnd + c2 = self.value[i] + i += 1 + if i >= l: + raise dns.exception.UnexpectedEnd + c3 = self.value[i] + i += 1 + if not (c2.isdigit() and c3.isdigit()): + raise dns.exception.SyntaxError + codepoint = int(c) * 100 + int(c2) * 10 + int(c3) + if codepoint > 255: + raise dns.exception.SyntaxError + c = chr(codepoint) + unescaped += c + return Token(self.ttype, unescaped) + + def unescape_to_bytes(self) -> "Token": + # We used to use unescape() for TXT-like records, but this + # caused problems as we'd process DNS escapes into Unicode code + # points instead of byte values, and then a to_text() of the + # processed data would not equal the original input. For + # example, \226 in the TXT record would have a to_text() of + # \195\162 because we applied UTF-8 encoding to Unicode code + # point 226. + # + # We now apply escapes while converting directly to bytes, + # avoiding this double encoding. + # + # This code also handles cases where the unicode input has + # non-ASCII code-points in it by converting it to UTF-8. TXT + # records aren't defined for Unicode, but this is the best we + # can do to preserve meaning. For example, + # + # foo\u200bbar + # + # (where \u200b is Unicode code point 0x200b) will be treated + # as if the input had been the UTF-8 encoding of that string, + # namely: + # + # foo\226\128\139bar + # + unescaped = b"" + l = len(self.value) + i = 0 + while i < l: + c = self.value[i] + i += 1 + if c == "\\": + if i >= l: # pragma: no cover (can't happen via get()) + raise dns.exception.UnexpectedEnd + c = self.value[i] + i += 1 + if c.isdigit(): + if i >= l: + raise dns.exception.UnexpectedEnd + c2 = self.value[i] + i += 1 + if i >= l: + raise dns.exception.UnexpectedEnd + c3 = self.value[i] + i += 1 + if not (c2.isdigit() and c3.isdigit()): + raise dns.exception.SyntaxError + codepoint = int(c) * 100 + int(c2) * 10 + int(c3) + if codepoint > 255: + raise dns.exception.SyntaxError + unescaped += b"%c" % (codepoint) + else: + # Note that as mentioned above, if c is a Unicode + # code point outside of the ASCII range, then this + # += is converting that code point to its UTF-8 + # encoding and appending multiple bytes to + # unescaped. + unescaped += c.encode() + else: + unescaped += c.encode() + return Token(self.ttype, bytes(unescaped)) + + +class Tokenizer: + """A DNS zone file format tokenizer. + + A token object is basically a (type, value) tuple. The valid + types are EOF, EOL, WHITESPACE, IDENTIFIER, QUOTED_STRING, + COMMENT, and DELIMITER. + + file: The file to tokenize + + ungotten_char: The most recently ungotten character, or None. + + ungotten_token: The most recently ungotten token, or None. + + multiline: The current multiline level. This value is increased + by one every time a '(' delimiter is read, and decreased by one every time + a ')' delimiter is read. + + quoting: This variable is true if the tokenizer is currently + reading a quoted string. + + eof: This variable is true if the tokenizer has encountered EOF. + + delimiters: The current delimiter dictionary. + + line_number: The current line number + + filename: A filename that will be returned by the where() method. + + idna_codec: A dns.name.IDNACodec, specifies the IDNA + encoder/decoder. If None, the default IDNA 2003 + encoder/decoder is used. + """ + + def __init__( + self, + f: Any = sys.stdin, + filename: str | None = None, + idna_codec: dns.name.IDNACodec | None = None, + ): + """Initialize a tokenizer instance. + + f: The file to tokenize. The default is sys.stdin. + This parameter may also be a string, in which case the tokenizer + will take its input from the contents of the string. + + filename: the name of the filename that the where() method + will return. + + idna_codec: A dns.name.IDNACodec, specifies the IDNA + encoder/decoder. If None, the default IDNA 2003 + encoder/decoder is used. + """ + + if isinstance(f, str): + f = io.StringIO(f) + if filename is None: + filename = "" + elif isinstance(f, bytes): + f = io.StringIO(f.decode()) + if filename is None: + filename = "" + else: + if filename is None: + if f is sys.stdin: + filename = "" + else: + filename = "" + self.file = f + self.ungotten_char: str | None = None + self.ungotten_token: Token | None = None + self.multiline = 0 + self.quoting = False + self.eof = False + self.delimiters = _DELIMITERS + self.line_number = 1 + assert filename is not None + self.filename = filename + if idna_codec is None: + self.idna_codec: dns.name.IDNACodec = dns.name.IDNA_2003 + else: + self.idna_codec = idna_codec + + def _get_char(self) -> str: + """Read a character from input.""" + + if self.ungotten_char is None: + if self.eof: + c = "" + else: + c = self.file.read(1) + if c == "": + self.eof = True + elif c == "\n": + self.line_number += 1 + else: + c = self.ungotten_char + self.ungotten_char = None + return c + + def where(self) -> Tuple[str, int]: + """Return the current location in the input. + + Returns a (string, int) tuple. The first item is the filename of + the input, the second is the current line number. + """ + + return (self.filename, self.line_number) + + def _unget_char(self, c: str) -> None: + """Unget a character. + + The unget buffer for characters is only one character large; it is + an error to try to unget a character when the unget buffer is not + empty. + + c: the character to unget + raises UngetBufferFull: there is already an ungotten char + """ + + if self.ungotten_char is not None: + # this should never happen! + raise UngetBufferFull # pragma: no cover + self.ungotten_char = c + + def skip_whitespace(self) -> int: + """Consume input until a non-whitespace character is encountered. + + The non-whitespace character is then ungotten, and the number of + whitespace characters consumed is returned. + + If the tokenizer is in multiline mode, then newlines are whitespace. + + Returns the number of characters skipped. + """ + + skipped = 0 + while True: + c = self._get_char() + if c != " " and c != "\t": + if (c != "\n") or not self.multiline: + self._unget_char(c) + return skipped + skipped += 1 + + def get(self, want_leading: bool = False, want_comment: bool = False) -> Token: + """Get the next token. + + want_leading: If True, return a WHITESPACE token if the + first character read is whitespace. The default is False. + + want_comment: If True, return a COMMENT token if the + first token read is a comment. The default is False. + + Raises dns.exception.UnexpectedEnd: input ended prematurely + + Raises dns.exception.SyntaxError: input was badly formed + + Returns a Token. + """ + + if self.ungotten_token is not None: + utoken = self.ungotten_token + self.ungotten_token = None + if utoken.is_whitespace(): + if want_leading: + return utoken + elif utoken.is_comment(): + if want_comment: + return utoken + else: + return utoken + skipped = self.skip_whitespace() + if want_leading and skipped > 0: + return Token(WHITESPACE, " ") + token = "" + ttype = IDENTIFIER + has_escape = False + while True: + c = self._get_char() + if c == "" or c in self.delimiters: + if c == "" and self.quoting: + raise dns.exception.UnexpectedEnd + if token == "" and ttype != QUOTED_STRING: + if c == "(": + self.multiline += 1 + self.skip_whitespace() + continue + elif c == ")": + if self.multiline <= 0: + raise dns.exception.SyntaxError + self.multiline -= 1 + self.skip_whitespace() + continue + elif c == '"': + if not self.quoting: + self.quoting = True + self.delimiters = _QUOTING_DELIMITERS + ttype = QUOTED_STRING + continue + else: + self.quoting = False + self.delimiters = _DELIMITERS + self.skip_whitespace() + continue + elif c == "\n": + return Token(EOL, "\n") + elif c == ";": + while 1: + c = self._get_char() + if c == "\n" or c == "": + break + token += c + if want_comment: + self._unget_char(c) + return Token(COMMENT, token) + elif c == "": + if self.multiline: + raise dns.exception.SyntaxError( + "unbalanced parentheses" + ) + return Token(EOF, comment=token) + elif self.multiline: + self.skip_whitespace() + token = "" + continue + else: + return Token(EOL, "\n", comment=token) + else: + # This code exists in case we ever want a + # delimiter to be returned. It never produces + # a token currently. + token = c + ttype = DELIMITER + else: + self._unget_char(c) + break + elif self.quoting and c == "\n": + raise dns.exception.SyntaxError("newline in quoted string") + elif c == "\\": + # + # It's an escape. Put it and the next character into + # the token; it will be checked later for goodness. + # + token += c + has_escape = True + c = self._get_char() + if c == "" or (c == "\n" and not self.quoting): + raise dns.exception.UnexpectedEnd + token += c + if token == "" and ttype != QUOTED_STRING: + if self.multiline: + raise dns.exception.SyntaxError("unbalanced parentheses") + ttype = EOF + return Token(ttype, token, has_escape) + + def unget(self, token: Token) -> None: + """Unget a token. + + The unget buffer for tokens is only one token large; it is + an error to try to unget a token when the unget buffer is not + empty. + + token: the token to unget + + Raises UngetBufferFull: there is already an ungotten token + """ + + if self.ungotten_token is not None: + raise UngetBufferFull + self.ungotten_token = token + + def next(self): + """Return the next item in an iteration. + + Returns a Token. + """ + + token = self.get() + if token.is_eof(): + raise StopIteration + return token + + __next__ = next + + def __iter__(self): + return self + + # Helpers + + def get_int(self, base: int = 10) -> int: + """Read the next token and interpret it as an unsigned integer. + + Raises dns.exception.SyntaxError if not an unsigned integer. + + Returns an int. + """ + + token = self.get().unescape() + if not token.is_identifier(): + raise dns.exception.SyntaxError("expecting an identifier") + if not token.value.isdigit(): + raise dns.exception.SyntaxError("expecting an integer") + return int(token.value, base) + + def get_uint8(self) -> int: + """Read the next token and interpret it as an 8-bit unsigned + integer. + + Raises dns.exception.SyntaxError if not an 8-bit unsigned integer. + + Returns an int. + """ + + value = self.get_int() + if value < 0 or value > 255: + raise dns.exception.SyntaxError(f"{value} is not an unsigned 8-bit integer") + return value + + def get_uint16(self, base: int = 10) -> int: + """Read the next token and interpret it as a 16-bit unsigned + integer. + + Raises dns.exception.SyntaxError if not a 16-bit unsigned integer. + + Returns an int. + """ + + value = self.get_int(base=base) + if value < 0 or value > 65535: + if base == 8: + raise dns.exception.SyntaxError( + f"{value:o} is not an octal unsigned 16-bit integer" + ) + else: + raise dns.exception.SyntaxError( + f"{value} is not an unsigned 16-bit integer" + ) + return value + + def get_uint32(self, base: int = 10) -> int: + """Read the next token and interpret it as a 32-bit unsigned + integer. + + Raises dns.exception.SyntaxError if not a 32-bit unsigned integer. + + Returns an int. + """ + + value = self.get_int(base=base) + if value < 0 or value > 4294967295: + raise dns.exception.SyntaxError( + f"{value} is not an unsigned 32-bit integer" + ) + return value + + def get_uint48(self, base: int = 10) -> int: + """Read the next token and interpret it as a 48-bit unsigned + integer. + + Raises dns.exception.SyntaxError if not a 48-bit unsigned integer. + + Returns an int. + """ + + value = self.get_int(base=base) + if value < 0 or value > 281474976710655: + raise dns.exception.SyntaxError( + f"{value} is not an unsigned 48-bit integer" + ) + return value + + def get_string(self, max_length: int | None = None) -> str: + """Read the next token and interpret it as a string. + + Raises dns.exception.SyntaxError if not a string. + Raises dns.exception.SyntaxError if token value length + exceeds max_length (if specified). + + Returns a string. + """ + + token = self.get().unescape() + if not (token.is_identifier() or token.is_quoted_string()): + raise dns.exception.SyntaxError("expecting a string") + if max_length and len(token.value) > max_length: + raise dns.exception.SyntaxError("string too long") + return token.value + + def get_identifier(self) -> str: + """Read the next token, which should be an identifier. + + Raises dns.exception.SyntaxError if not an identifier. + + Returns a string. + """ + + token = self.get().unescape() + if not token.is_identifier(): + raise dns.exception.SyntaxError("expecting an identifier") + return token.value + + def get_remaining(self, max_tokens: int | None = None) -> List[Token]: + """Return the remaining tokens on the line, until an EOL or EOF is seen. + + max_tokens: If not None, stop after this number of tokens. + + Returns a list of tokens. + """ + + tokens = [] + while True: + token = self.get() + if token.is_eol_or_eof(): + self.unget(token) + break + tokens.append(token) + if len(tokens) == max_tokens: + break + return tokens + + def concatenate_remaining_identifiers(self, allow_empty: bool = False) -> str: + """Read the remaining tokens on the line, which should be identifiers. + + Raises dns.exception.SyntaxError if there are no remaining tokens, + unless `allow_empty=True` is given. + + Raises dns.exception.SyntaxError if a token is seen that is not an + identifier. + + Returns a string containing a concatenation of the remaining + identifiers. + """ + s = "" + while True: + token = self.get().unescape() + if token.is_eol_or_eof(): + self.unget(token) + break + if not token.is_identifier(): + raise dns.exception.SyntaxError + s += token.value + if not (allow_empty or s): + raise dns.exception.SyntaxError("expecting another identifier") + return s + + def as_name( + self, + token: Token, + origin: dns.name.Name | None = None, + relativize: bool = False, + relativize_to: dns.name.Name | None = None, + ) -> dns.name.Name: + """Try to interpret the token as a DNS name. + + Raises dns.exception.SyntaxError if not a name. + + Returns a dns.name.Name. + """ + if not token.is_identifier(): + raise dns.exception.SyntaxError("expecting an identifier") + name = dns.name.from_text(token.value, origin, self.idna_codec) + return name.choose_relativity(relativize_to or origin, relativize) + + def get_name( + self, + origin: dns.name.Name | None = None, + relativize: bool = False, + relativize_to: dns.name.Name | None = None, + ) -> dns.name.Name: + """Read the next token and interpret it as a DNS name. + + Raises dns.exception.SyntaxError if not a name. + + Returns a dns.name.Name. + """ + + token = self.get() + return self.as_name(token, origin, relativize, relativize_to) + + def get_eol_as_token(self) -> Token: + """Read the next token and raise an exception if it isn't EOL or + EOF. + + Returns a string. + """ + + token = self.get() + if not token.is_eol_or_eof(): + raise dns.exception.SyntaxError( + f'expected EOL or EOF, got {token.ttype} "{token.value}"' + ) + return token + + def get_eol(self) -> str: + return self.get_eol_as_token().value + + def get_ttl(self) -> int: + """Read the next token and interpret it as a DNS TTL. + + Raises dns.exception.SyntaxError or dns.ttl.BadTTL if not an + identifier or badly formed. + + Returns an int. + """ + + token = self.get().unescape() + if not token.is_identifier(): + raise dns.exception.SyntaxError("expecting an identifier") + return dns.ttl.from_text(token.value) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/transaction.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/transaction.py new file mode 100644 index 000000000..9ecd73772 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/transaction.py @@ -0,0 +1,651 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +import collections +from typing import Any, Callable, Iterator, List, Tuple + +import dns.exception +import dns.name +import dns.node +import dns.rdata +import dns.rdataclass +import dns.rdataset +import dns.rdatatype +import dns.rrset +import dns.serial +import dns.ttl + + +class TransactionManager: + def reader(self) -> "Transaction": + """Begin a read-only transaction.""" + raise NotImplementedError # pragma: no cover + + def writer(self, replacement: bool = False) -> "Transaction": + """Begin a writable transaction. + + *replacement*, a ``bool``. If `True`, the content of the + transaction completely replaces any prior content. If False, + the default, then the content of the transaction updates the + existing content. + """ + raise NotImplementedError # pragma: no cover + + def origin_information( + self, + ) -> Tuple[dns.name.Name | None, bool, dns.name.Name | None]: + """Returns a tuple + + (absolute_origin, relativize, effective_origin) + + giving the absolute name of the default origin for any + relative domain names, the "effective origin", and whether + names should be relativized. The "effective origin" is the + absolute origin if relativize is False, and the empty name if + relativize is true. (The effective origin is provided even + though it can be computed from the absolute_origin and + relativize setting because it avoids a lot of code + duplication.) + + If the returned names are `None`, then no origin information is + available. + + This information is used by code working with transactions to + allow it to coordinate relativization. The transaction code + itself takes what it gets (i.e. does not change name + relativity). + + """ + raise NotImplementedError # pragma: no cover + + def get_class(self) -> dns.rdataclass.RdataClass: + """The class of the transaction manager.""" + raise NotImplementedError # pragma: no cover + + def from_wire_origin(self) -> dns.name.Name | None: + """Origin to use in from_wire() calls.""" + (absolute_origin, relativize, _) = self.origin_information() + if relativize: + return absolute_origin + else: + return None + + +class DeleteNotExact(dns.exception.DNSException): + """Existing data did not match data specified by an exact delete.""" + + +class ReadOnly(dns.exception.DNSException): + """Tried to write to a read-only transaction.""" + + +class AlreadyEnded(dns.exception.DNSException): + """Tried to use an already-ended transaction.""" + + +def _ensure_immutable_rdataset(rdataset): + if rdataset is None or isinstance(rdataset, dns.rdataset.ImmutableRdataset): + return rdataset + return dns.rdataset.ImmutableRdataset(rdataset) + + +def _ensure_immutable_node(node): + if node is None or node.is_immutable(): + return node + return dns.node.ImmutableNode(node) + + +CheckPutRdatasetType = Callable[ + ["Transaction", dns.name.Name, dns.rdataset.Rdataset], None +] +CheckDeleteRdatasetType = Callable[ + ["Transaction", dns.name.Name, dns.rdatatype.RdataType, dns.rdatatype.RdataType], + None, +] +CheckDeleteNameType = Callable[["Transaction", dns.name.Name], None] + + +class Transaction: + def __init__( + self, + manager: TransactionManager, + replacement: bool = False, + read_only: bool = False, + ): + self.manager = manager + self.replacement = replacement + self.read_only = read_only + self._ended = False + self._check_put_rdataset: List[CheckPutRdatasetType] = [] + self._check_delete_rdataset: List[CheckDeleteRdatasetType] = [] + self._check_delete_name: List[CheckDeleteNameType] = [] + + # + # This is the high level API + # + # Note that we currently use non-immutable types in the return type signature to + # avoid covariance problems, e.g. if the caller has a List[Rdataset], mypy will be + # unhappy if we return an ImmutableRdataset. + + def get( + self, + name: dns.name.Name | str | None, + rdtype: dns.rdatatype.RdataType | str, + covers: dns.rdatatype.RdataType | str = dns.rdatatype.NONE, + ) -> dns.rdataset.Rdataset: + """Return the rdataset associated with *name*, *rdtype*, and *covers*, + or `None` if not found. + + Note that the returned rdataset is immutable. + """ + self._check_ended() + if isinstance(name, str): + name = dns.name.from_text(name, None) + rdtype = dns.rdatatype.RdataType.make(rdtype) + covers = dns.rdatatype.RdataType.make(covers) + rdataset = self._get_rdataset(name, rdtype, covers) + return _ensure_immutable_rdataset(rdataset) + + def get_node(self, name: dns.name.Name) -> dns.node.Node | None: + """Return the node at *name*, if any. + + Returns an immutable node or ``None``. + """ + return _ensure_immutable_node(self._get_node(name)) + + def _check_read_only(self) -> None: + if self.read_only: + raise ReadOnly + + def add(self, *args: Any) -> None: + """Add records. + + The arguments may be: + + - rrset + + - name, rdataset... + + - name, ttl, rdata... + """ + self._check_ended() + self._check_read_only() + self._add(False, args) + + def replace(self, *args: Any) -> None: + """Replace the existing rdataset at the name with the specified + rdataset, or add the specified rdataset if there was no existing + rdataset. + + The arguments may be: + + - rrset + + - name, rdataset... + + - name, ttl, rdata... + + Note that if you want to replace the entire node, you should do + a delete of the name followed by one or more calls to add() or + replace(). + """ + self._check_ended() + self._check_read_only() + self._add(True, args) + + def delete(self, *args: Any) -> None: + """Delete records. + + It is not an error if some of the records are not in the existing + set. + + The arguments may be: + + - rrset + + - name + + - name, rdatatype, [covers] + + - name, rdataset... + + - name, rdata... + """ + self._check_ended() + self._check_read_only() + self._delete(False, args) + + def delete_exact(self, *args: Any) -> None: + """Delete records. + + The arguments may be: + + - rrset + + - name + + - name, rdatatype, [covers] + + - name, rdataset... + + - name, rdata... + + Raises dns.transaction.DeleteNotExact if some of the records + are not in the existing set. + + """ + self._check_ended() + self._check_read_only() + self._delete(True, args) + + def name_exists(self, name: dns.name.Name | str) -> bool: + """Does the specified name exist?""" + self._check_ended() + if isinstance(name, str): + name = dns.name.from_text(name, None) + return self._name_exists(name) + + def update_serial( + self, + value: int = 1, + relative: bool = True, + name: dns.name.Name = dns.name.empty, + ) -> None: + """Update the serial number. + + *value*, an `int`, is an increment if *relative* is `True`, or the + actual value to set if *relative* is `False`. + + Raises `KeyError` if there is no SOA rdataset at *name*. + + Raises `ValueError` if *value* is negative or if the increment is + so large that it would cause the new serial to be less than the + prior value. + """ + self._check_ended() + if value < 0: + raise ValueError("negative update_serial() value") + if isinstance(name, str): + name = dns.name.from_text(name, None) + rdataset = self._get_rdataset(name, dns.rdatatype.SOA, dns.rdatatype.NONE) + if rdataset is None or len(rdataset) == 0: + raise KeyError + if relative: + serial = dns.serial.Serial(rdataset[0].serial) + value + else: + serial = dns.serial.Serial(value) + serial = serial.value # convert back to int + if serial == 0: + serial = 1 + rdata = rdataset[0].replace(serial=serial) + new_rdataset = dns.rdataset.from_rdata(rdataset.ttl, rdata) + self.replace(name, new_rdataset) + + def __iter__(self): + self._check_ended() + return self._iterate_rdatasets() + + def changed(self) -> bool: + """Has this transaction changed anything? + + For read-only transactions, the result is always `False`. + + For writable transactions, the result is `True` if at some time + during the life of the transaction, the content was changed. + """ + self._check_ended() + return self._changed() + + def commit(self) -> None: + """Commit the transaction. + + Normally transactions are used as context managers and commit + or rollback automatically, but it may be done explicitly if needed. + A ``dns.transaction.Ended`` exception will be raised if you try + to use a transaction after it has been committed or rolled back. + + Raises an exception if the commit fails (in which case the transaction + is also rolled back. + """ + self._end(True) + + def rollback(self) -> None: + """Rollback the transaction. + + Normally transactions are used as context managers and commit + or rollback automatically, but it may be done explicitly if needed. + A ``dns.transaction.AlreadyEnded`` exception will be raised if you try + to use a transaction after it has been committed or rolled back. + + Rollback cannot otherwise fail. + """ + self._end(False) + + def check_put_rdataset(self, check: CheckPutRdatasetType) -> None: + """Call *check* before putting (storing) an rdataset. + + The function is called with the transaction, the name, and the rdataset. + + The check function may safely make non-mutating transaction method + calls, but behavior is undefined if mutating transaction methods are + called. The check function should raise an exception if it objects to + the put, and otherwise should return ``None``. + """ + self._check_put_rdataset.append(check) + + def check_delete_rdataset(self, check: CheckDeleteRdatasetType) -> None: + """Call *check* before deleting an rdataset. + + The function is called with the transaction, the name, the rdatatype, + and the covered rdatatype. + + The check function may safely make non-mutating transaction method + calls, but behavior is undefined if mutating transaction methods are + called. The check function should raise an exception if it objects to + the put, and otherwise should return ``None``. + """ + self._check_delete_rdataset.append(check) + + def check_delete_name(self, check: CheckDeleteNameType) -> None: + """Call *check* before putting (storing) an rdataset. + + The function is called with the transaction and the name. + + The check function may safely make non-mutating transaction method + calls, but behavior is undefined if mutating transaction methods are + called. The check function should raise an exception if it objects to + the put, and otherwise should return ``None``. + """ + self._check_delete_name.append(check) + + def iterate_rdatasets( + self, + ) -> Iterator[Tuple[dns.name.Name, dns.rdataset.Rdataset]]: + """Iterate all the rdatasets in the transaction, returning + (`dns.name.Name`, `dns.rdataset.Rdataset`) tuples. + + Note that as is usual with python iterators, adding or removing items + while iterating will invalidate the iterator and may raise `RuntimeError` + or fail to iterate over all entries.""" + self._check_ended() + return self._iterate_rdatasets() + + def iterate_names(self) -> Iterator[dns.name.Name]: + """Iterate all the names in the transaction. + + Note that as is usual with python iterators, adding or removing names + while iterating will invalidate the iterator and may raise `RuntimeError` + or fail to iterate over all entries.""" + self._check_ended() + return self._iterate_names() + + # + # Helper methods + # + + def _raise_if_not_empty(self, method, args): + if len(args) != 0: + raise TypeError(f"extra parameters to {method}") + + def _rdataset_from_args(self, method, deleting, args): + try: + arg = args.popleft() + if isinstance(arg, dns.rrset.RRset): + rdataset = arg.to_rdataset() + elif isinstance(arg, dns.rdataset.Rdataset): + rdataset = arg + else: + if deleting: + ttl = 0 + else: + if isinstance(arg, int): + ttl = arg + if ttl > dns.ttl.MAX_TTL: + raise ValueError(f"{method}: TTL value too big") + else: + raise TypeError(f"{method}: expected a TTL") + arg = args.popleft() + if isinstance(arg, dns.rdata.Rdata): + rdataset = dns.rdataset.from_rdata(ttl, arg) + else: + raise TypeError(f"{method}: expected an Rdata") + return rdataset + except IndexError: + if deleting: + return None + else: + # reraise + raise TypeError(f"{method}: expected more arguments") + + def _add(self, replace, args): + if replace: + method = "replace()" + else: + method = "add()" + try: + args = collections.deque(args) + arg = args.popleft() + if isinstance(arg, str): + arg = dns.name.from_text(arg, None) + if isinstance(arg, dns.name.Name): + name = arg + rdataset = self._rdataset_from_args(method, False, args) + elif isinstance(arg, dns.rrset.RRset): + rrset = arg + name = rrset.name + # rrsets are also rdatasets, but they don't print the + # same and can't be stored in nodes, so convert. + rdataset = rrset.to_rdataset() + else: + raise TypeError( + f"{method} requires a name or RRset as the first argument" + ) + assert rdataset is not None # for type checkers + if rdataset.rdclass != self.manager.get_class(): + raise ValueError(f"{method} has objects of wrong RdataClass") + if rdataset.rdtype == dns.rdatatype.SOA: + (_, _, origin) = self._origin_information() + if name != origin: + raise ValueError(f"{method} has non-origin SOA") + self._raise_if_not_empty(method, args) + if not replace: + existing = self._get_rdataset(name, rdataset.rdtype, rdataset.covers) + if existing is not None: + if isinstance(existing, dns.rdataset.ImmutableRdataset): + trds = dns.rdataset.Rdataset( + existing.rdclass, existing.rdtype, existing.covers + ) + trds.update(existing) + existing = trds + rdataset = existing.union(rdataset) + self._checked_put_rdataset(name, rdataset) + except IndexError: + raise TypeError(f"not enough parameters to {method}") + + def _delete(self, exact, args): + if exact: + method = "delete_exact()" + else: + method = "delete()" + try: + args = collections.deque(args) + arg = args.popleft() + if isinstance(arg, str): + arg = dns.name.from_text(arg, None) + if isinstance(arg, dns.name.Name): + name = arg + if len(args) > 0 and ( + isinstance(args[0], int) or isinstance(args[0], str) + ): + # deleting by type and (optionally) covers + rdtype = dns.rdatatype.RdataType.make(args.popleft()) + if len(args) > 0: + covers = dns.rdatatype.RdataType.make(args.popleft()) + else: + covers = dns.rdatatype.NONE + self._raise_if_not_empty(method, args) + existing = self._get_rdataset(name, rdtype, covers) + if existing is None: + if exact: + raise DeleteNotExact(f"{method}: missing rdataset") + else: + self._checked_delete_rdataset(name, rdtype, covers) + return + else: + rdataset = self._rdataset_from_args(method, True, args) + elif isinstance(arg, dns.rrset.RRset): + rdataset = arg # rrsets are also rdatasets + name = rdataset.name + else: + raise TypeError( + f"{method} requires a name or RRset as the first argument" + ) + self._raise_if_not_empty(method, args) + if rdataset: + if rdataset.rdclass != self.manager.get_class(): + raise ValueError(f"{method} has objects of wrong RdataClass") + existing = self._get_rdataset(name, rdataset.rdtype, rdataset.covers) + if existing is not None: + if exact: + intersection = existing.intersection(rdataset) + if intersection != rdataset: + raise DeleteNotExact(f"{method}: missing rdatas") + rdataset = existing.difference(rdataset) + if len(rdataset) == 0: + self._checked_delete_rdataset( + name, rdataset.rdtype, rdataset.covers + ) + else: + self._checked_put_rdataset(name, rdataset) + elif exact: + raise DeleteNotExact(f"{method}: missing rdataset") + else: + if exact and not self._name_exists(name): + raise DeleteNotExact(f"{method}: name not known") + self._checked_delete_name(name) + except IndexError: + raise TypeError(f"not enough parameters to {method}") + + def _check_ended(self): + if self._ended: + raise AlreadyEnded + + def _end(self, commit): + self._check_ended() + try: + self._end_transaction(commit) + finally: + self._ended = True + + def _checked_put_rdataset(self, name, rdataset): + for check in self._check_put_rdataset: + check(self, name, rdataset) + self._put_rdataset(name, rdataset) + + def _checked_delete_rdataset(self, name, rdtype, covers): + for check in self._check_delete_rdataset: + check(self, name, rdtype, covers) + self._delete_rdataset(name, rdtype, covers) + + def _checked_delete_name(self, name): + for check in self._check_delete_name: + check(self, name) + self._delete_name(name) + + # + # Transactions are context managers. + # + + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + if not self._ended: + if exc_type is None: + self.commit() + else: + self.rollback() + return False + + # + # This is the low level API, which must be implemented by subclasses + # of Transaction. + # + + def _get_rdataset(self, name, rdtype, covers): + """Return the rdataset associated with *name*, *rdtype*, and *covers*, + or `None` if not found. + """ + raise NotImplementedError # pragma: no cover + + def _put_rdataset(self, name, rdataset): + """Store the rdataset.""" + raise NotImplementedError # pragma: no cover + + def _delete_name(self, name): + """Delete all data associated with *name*. + + It is not an error if the name does not exist. + """ + raise NotImplementedError # pragma: no cover + + def _delete_rdataset(self, name, rdtype, covers): + """Delete all data associated with *name*, *rdtype*, and *covers*. + + It is not an error if the rdataset does not exist. + """ + raise NotImplementedError # pragma: no cover + + def _name_exists(self, name): + """Does name exist? + + Returns a bool. + """ + raise NotImplementedError # pragma: no cover + + def _changed(self): + """Has this transaction changed anything?""" + raise NotImplementedError # pragma: no cover + + def _end_transaction(self, commit): + """End the transaction. + + *commit*, a bool. If ``True``, commit the transaction, otherwise + roll it back. + + If committing and the commit fails, then roll back and raise an + exception. + """ + raise NotImplementedError # pragma: no cover + + def _set_origin(self, origin): + """Set the origin. + + This method is called when reading a possibly relativized + source, and an origin setting operation occurs (e.g. $ORIGIN + in a zone file). + """ + raise NotImplementedError # pragma: no cover + + def _iterate_rdatasets(self): + """Return an iterator that yields (name, rdataset) tuples.""" + raise NotImplementedError # pragma: no cover + + def _iterate_names(self): + """Return an iterator that yields a name.""" + raise NotImplementedError # pragma: no cover + + def _get_node(self, name): + """Return the node at *name*, if any. + + Returns a node or ``None``. + """ + raise NotImplementedError # pragma: no cover + + # + # Low-level API with a default implementation, in case a subclass needs + # to override. + # + + def _origin_information(self): + # This is only used by _add() + return self.manager.origin_information() diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/tsig.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/tsig.py new file mode 100644 index 000000000..333f9aa47 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/tsig.py @@ -0,0 +1,359 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +# Copyright (C) 2001-2007, 2009-2011 Nominum, Inc. +# +# Permission to use, copy, modify, and distribute this software and its +# documentation for any purpose with or without fee is hereby granted, +# provided that the above copyright notice and this permission notice +# appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +"""DNS TSIG support.""" + +import base64 +import hashlib +import hmac +import struct + +import dns.exception +import dns.name +import dns.rcode +import dns.rdataclass +import dns.rdatatype + + +class BadTime(dns.exception.DNSException): + """The current time is not within the TSIG's validity time.""" + + +class BadSignature(dns.exception.DNSException): + """The TSIG signature fails to verify.""" + + +class BadKey(dns.exception.DNSException): + """The TSIG record owner name does not match the key.""" + + +class BadAlgorithm(dns.exception.DNSException): + """The TSIG algorithm does not match the key.""" + + +class PeerError(dns.exception.DNSException): + """Base class for all TSIG errors generated by the remote peer""" + + +class PeerBadKey(PeerError): + """The peer didn't know the key we used""" + + +class PeerBadSignature(PeerError): + """The peer didn't like the signature we sent""" + + +class PeerBadTime(PeerError): + """The peer didn't like the time we sent""" + + +class PeerBadTruncation(PeerError): + """The peer didn't like amount of truncation in the TSIG we sent""" + + +# TSIG Algorithms + +HMAC_MD5 = dns.name.from_text("HMAC-MD5.SIG-ALG.REG.INT") +HMAC_SHA1 = dns.name.from_text("hmac-sha1") +HMAC_SHA224 = dns.name.from_text("hmac-sha224") +HMAC_SHA256 = dns.name.from_text("hmac-sha256") +HMAC_SHA256_128 = dns.name.from_text("hmac-sha256-128") +HMAC_SHA384 = dns.name.from_text("hmac-sha384") +HMAC_SHA384_192 = dns.name.from_text("hmac-sha384-192") +HMAC_SHA512 = dns.name.from_text("hmac-sha512") +HMAC_SHA512_256 = dns.name.from_text("hmac-sha512-256") +GSS_TSIG = dns.name.from_text("gss-tsig") + +default_algorithm = HMAC_SHA256 + +mac_sizes = { + HMAC_SHA1: 20, + HMAC_SHA224: 28, + HMAC_SHA256: 32, + HMAC_SHA256_128: 16, + HMAC_SHA384: 48, + HMAC_SHA384_192: 24, + HMAC_SHA512: 64, + HMAC_SHA512_256: 32, + HMAC_MD5: 16, + GSS_TSIG: 128, # This is what we assume to be the worst case! +} + + +class GSSTSig: + """ + GSS-TSIG TSIG implementation. This uses the GSS-API context established + in the TKEY message handshake to sign messages using GSS-API message + integrity codes, per the RFC. + + In order to avoid a direct GSSAPI dependency, the keyring holds a ref + to the GSSAPI object required, rather than the key itself. + """ + + def __init__(self, gssapi_context): + self.gssapi_context = gssapi_context + self.data = b"" + self.name = "gss-tsig" + + def update(self, data): + self.data += data + + def sign(self): + # defer to the GSSAPI function to sign + return self.gssapi_context.get_signature(self.data) + + def verify(self, expected): + try: + # defer to the GSSAPI function to verify + return self.gssapi_context.verify_signature(self.data, expected) + except Exception: + # note the usage of a bare exception + raise BadSignature + + +class GSSTSigAdapter: + def __init__(self, keyring): + self.keyring = keyring + + def __call__(self, message, keyname): + if keyname in self.keyring: + key = self.keyring[keyname] + if isinstance(key, Key) and key.algorithm == GSS_TSIG: + if message: + GSSTSigAdapter.parse_tkey_and_step(key, message, keyname) + return key + else: + return None + + @classmethod + def parse_tkey_and_step(cls, key, message, keyname): + # if the message is a TKEY type, absorb the key material + # into the context using step(); this is used to allow the + # client to complete the GSSAPI negotiation before attempting + # to verify the signed response to a TKEY message exchange + try: + rrset = message.find_rrset( + message.answer, keyname, dns.rdataclass.ANY, dns.rdatatype.TKEY + ) + if rrset: + token = rrset[0].key + gssapi_context = key.secret + return gssapi_context.step(token) + except KeyError: + pass + + +class HMACTSig: + """ + HMAC TSIG implementation. This uses the HMAC python module to handle the + sign/verify operations. + """ + + _hashes = { + HMAC_SHA1: hashlib.sha1, + HMAC_SHA224: hashlib.sha224, + HMAC_SHA256: hashlib.sha256, + HMAC_SHA256_128: (hashlib.sha256, 128), + HMAC_SHA384: hashlib.sha384, + HMAC_SHA384_192: (hashlib.sha384, 192), + HMAC_SHA512: hashlib.sha512, + HMAC_SHA512_256: (hashlib.sha512, 256), + HMAC_MD5: hashlib.md5, + } + + def __init__(self, key, algorithm): + try: + hashinfo = self._hashes[algorithm] + except KeyError: + raise NotImplementedError(f"TSIG algorithm {algorithm} is not supported") + + # create the HMAC context + if isinstance(hashinfo, tuple): + self.hmac_context = hmac.new(key, digestmod=hashinfo[0]) + self.size = hashinfo[1] + else: + self.hmac_context = hmac.new(key, digestmod=hashinfo) + self.size = None + self.name = self.hmac_context.name + if self.size: + self.name += f"-{self.size}" + + def update(self, data): + return self.hmac_context.update(data) + + def sign(self): + # defer to the HMAC digest() function for that digestmod + digest = self.hmac_context.digest() + if self.size: + digest = digest[: (self.size // 8)] + return digest + + def verify(self, expected): + # re-digest and compare the results + mac = self.sign() + if not hmac.compare_digest(mac, expected): + raise BadSignature + + +def _digest(wire, key, rdata, time=None, request_mac=None, ctx=None, multi=None): + """Return a context containing the TSIG rdata for the input parameters + @rtype: dns.tsig.HMACTSig or dns.tsig.GSSTSig object + @raises ValueError: I{other_data} is too long + @raises NotImplementedError: I{algorithm} is not supported + """ + + first = not (ctx and multi) + if first: + ctx = get_context(key) + if request_mac: + ctx.update(struct.pack("!H", len(request_mac))) + ctx.update(request_mac) + assert ctx is not None # for type checkers + ctx.update(struct.pack("!H", rdata.original_id)) + ctx.update(wire[2:]) + if first: + ctx.update(key.name.to_digestable()) + ctx.update(struct.pack("!H", dns.rdataclass.ANY)) + ctx.update(struct.pack("!I", 0)) + if time is None: + time = rdata.time_signed + upper_time = (time >> 32) & 0xFFFF + lower_time = time & 0xFFFFFFFF + time_encoded = struct.pack("!HIH", upper_time, lower_time, rdata.fudge) + other_len = len(rdata.other) + if other_len > 65535: + raise ValueError("TSIG Other Data is > 65535 bytes") + if first: + ctx.update(key.algorithm.to_digestable() + time_encoded) + ctx.update(struct.pack("!HH", rdata.error, other_len) + rdata.other) + else: + ctx.update(time_encoded) + return ctx + + +def _maybe_start_digest(key, mac, multi): + """If this is the first message in a multi-message sequence, + start a new context. + @rtype: dns.tsig.HMACTSig or dns.tsig.GSSTSig object + """ + if multi: + ctx = get_context(key) + ctx.update(struct.pack("!H", len(mac))) + ctx.update(mac) + return ctx + else: + return None + + +def sign(wire, key, rdata, time=None, request_mac=None, ctx=None, multi=False): + """Return a (tsig_rdata, mac, ctx) tuple containing the HMAC TSIG rdata + for the input parameters, the HMAC MAC calculated by applying the + TSIG signature algorithm, and the TSIG digest context. + @rtype: (string, dns.tsig.HMACTSig or dns.tsig.GSSTSig object) + @raises ValueError: I{other_data} is too long + @raises NotImplementedError: I{algorithm} is not supported + """ + + ctx = _digest(wire, key, rdata, time, request_mac, ctx, multi) + mac = ctx.sign() + tsig = rdata.replace(time_signed=time, mac=mac) + + return (tsig, _maybe_start_digest(key, mac, multi)) + + +def validate( + wire, key, owner, rdata, now, request_mac, tsig_start, ctx=None, multi=False +): + """Validate the specified TSIG rdata against the other input parameters. + + @raises FormError: The TSIG is badly formed. + @raises BadTime: There is too much time skew between the client and the + server. + @raises BadSignature: The TSIG signature did not validate + @rtype: dns.tsig.HMACTSig or dns.tsig.GSSTSig object""" + + (adcount,) = struct.unpack("!H", wire[10:12]) + if adcount == 0: + raise dns.exception.FormError + adcount -= 1 + new_wire = wire[0:10] + struct.pack("!H", adcount) + wire[12:tsig_start] + if rdata.error != 0: + if rdata.error == dns.rcode.BADSIG: + raise PeerBadSignature + elif rdata.error == dns.rcode.BADKEY: + raise PeerBadKey + elif rdata.error == dns.rcode.BADTIME: + raise PeerBadTime + elif rdata.error == dns.rcode.BADTRUNC: + raise PeerBadTruncation + else: + raise PeerError(f"unknown TSIG error code {rdata.error}") + if abs(rdata.time_signed - now) > rdata.fudge: + raise BadTime + if key.name != owner: + raise BadKey + if key.algorithm != rdata.algorithm: + raise BadAlgorithm + ctx = _digest(new_wire, key, rdata, None, request_mac, ctx, multi) + ctx.verify(rdata.mac) + return _maybe_start_digest(key, rdata.mac, multi) + + +def get_context(key): + """Returns an HMAC context for the specified key. + + @rtype: HMAC context + @raises NotImplementedError: I{algorithm} is not supported + """ + + if key.algorithm == GSS_TSIG: + return GSSTSig(key.secret) + else: + return HMACTSig(key.secret, key.algorithm) + + +class Key: + def __init__( + self, + name: dns.name.Name | str, + secret: bytes | str, + algorithm: dns.name.Name | str = default_algorithm, + ): + if isinstance(name, str): + name = dns.name.from_text(name) + self.name = name + if isinstance(secret, str): + secret = base64.decodebytes(secret.encode()) + self.secret = secret + if isinstance(algorithm, str): + algorithm = dns.name.from_text(algorithm) + self.algorithm = algorithm + + def __eq__(self, other): + return ( + isinstance(other, Key) + and self.name == other.name + and self.secret == other.secret + and self.algorithm == other.algorithm + ) + + def __repr__(self): + r = f" Dict[dns.name.Name, Any]: + """Convert a dictionary containing (textual DNS name, base64 secret) + pairs into a binary keyring which has (dns.name.Name, bytes) pairs, or + a dictionary containing (textual DNS name, (algorithm, base64 secret)) + pairs into a binary keyring which has (dns.name.Name, dns.tsig.Key) pairs. + @rtype: dict""" + + keyring: Dict[dns.name.Name, Any] = {} + for name, value in textring.items(): + kname = dns.name.from_text(name) + if isinstance(value, str): + keyring[kname] = dns.tsig.Key(kname, value).secret + else: + (algorithm, secret) = value + keyring[kname] = dns.tsig.Key(kname, secret, algorithm) + return keyring + + +def to_text(keyring: Dict[dns.name.Name, Any]) -> Dict[str, Any]: + """Convert a dictionary containing (dns.name.Name, dns.tsig.Key) pairs + into a text keyring which has (textual DNS name, (textual algorithm, + base64 secret)) pairs, or a dictionary containing (dns.name.Name, bytes) + pairs into a text keyring which has (textual DNS name, base64 secret) pairs. + @rtype: dict""" + + textring = {} + + def b64encode(secret): + return base64.encodebytes(secret).decode().rstrip() + + for name, key in keyring.items(): + tname = name.to_text() + if isinstance(key, bytes): + textring[tname] = b64encode(key) + else: + if isinstance(key.secret, bytes): + text_secret = b64encode(key.secret) + else: + text_secret = str(key.secret) + + textring[tname] = (key.algorithm.to_text(), text_secret) + return textring diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/ttl.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/ttl.py new file mode 100644 index 000000000..16289cd05 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/ttl.py @@ -0,0 +1,90 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +# Copyright (C) 2003-2017 Nominum, Inc. +# +# Permission to use, copy, modify, and distribute this software and its +# documentation for any purpose with or without fee is hereby granted, +# provided that the above copyright notice and this permission notice +# appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +"""DNS TTL conversion.""" + +import dns.exception + +# Technically TTLs are supposed to be between 0 and 2**31 - 1, with values +# greater than that interpreted as 0, but we do not impose this policy here +# as values > 2**31 - 1 occur in real world data. +# +# We leave it to applications to impose tighter bounds if desired. +MAX_TTL = 2**32 - 1 + + +class BadTTL(dns.exception.SyntaxError): + """DNS TTL value is not well-formed.""" + + +def from_text(text: str) -> int: + """Convert the text form of a TTL to an integer. + + The BIND 8 units syntax for TTLs (e.g. '1w6d4h3m10s') is supported. + + *text*, a ``str``, the textual TTL. + + Raises ``dns.ttl.BadTTL`` if the TTL is not well-formed. + + Returns an ``int``. + """ + + if text.isdigit(): + total = int(text) + elif len(text) == 0: + raise BadTTL + else: + total = 0 + current = 0 + need_digit = True + for c in text: + if c.isdigit(): + current *= 10 + current += int(c) + need_digit = False + else: + if need_digit: + raise BadTTL + c = c.lower() + if c == "w": + total += current * 604800 + elif c == "d": + total += current * 86400 + elif c == "h": + total += current * 3600 + elif c == "m": + total += current * 60 + elif c == "s": + total += current + else: + raise BadTTL(f"unknown unit '{c}'") + current = 0 + need_digit = True + if not current == 0: + raise BadTTL("trailing integer") + if total < 0 or total > MAX_TTL: + raise BadTTL("TTL should be between 0 and 2**32 - 1 (inclusive)") + return total + + +def make(value: int | str) -> int: + if isinstance(value, int): + return value + elif isinstance(value, str): + return from_text(value) + else: + raise ValueError("cannot convert value to TTL") diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/update.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/update.py new file mode 100644 index 000000000..0e4aee411 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/update.py @@ -0,0 +1,389 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. +# +# Permission to use, copy, modify, and distribute this software and its +# documentation for any purpose with or without fee is hereby granted, +# provided that the above copyright notice and this permission notice +# appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +"""DNS Dynamic Update Support""" + +from typing import Any, List + +import dns.enum +import dns.exception +import dns.message +import dns.name +import dns.opcode +import dns.rdata +import dns.rdataclass +import dns.rdataset +import dns.rdatatype +import dns.rrset +import dns.tsig + + +class UpdateSection(dns.enum.IntEnum): + """Update sections""" + + ZONE = 0 + PREREQ = 1 + UPDATE = 2 + ADDITIONAL = 3 + + @classmethod + def _maximum(cls): + return 3 + + +class UpdateMessage(dns.message.Message): # lgtm[py/missing-equals] + # ignore the mypy error here as we mean to use a different enum + _section_enum = UpdateSection # type: ignore + + def __init__( + self, + zone: dns.name.Name | str | None = None, + rdclass: dns.rdataclass.RdataClass = dns.rdataclass.IN, + keyring: Any | None = None, + keyname: dns.name.Name | None = None, + keyalgorithm: dns.name.Name | str = dns.tsig.default_algorithm, + id: int | None = None, + ): + """Initialize a new DNS Update object. + + See the documentation of the Message class for a complete + description of the keyring dictionary. + + *zone*, a ``dns.name.Name``, ``str``, or ``None``, the zone + which is being updated. ``None`` should only be used by dnspython's + message constructors, as a zone is required for the convenience + methods like ``add()``, ``replace()``, etc. + + *rdclass*, an ``int`` or ``str``, the class of the zone. + + The *keyring*, *keyname*, and *keyalgorithm* parameters are passed to + ``use_tsig()``; see its documentation for details. + """ + super().__init__(id=id) + self.flags |= dns.opcode.to_flags(dns.opcode.UPDATE) + if isinstance(zone, str): + zone = dns.name.from_text(zone) + self.origin = zone + rdclass = dns.rdataclass.RdataClass.make(rdclass) + self.zone_rdclass = rdclass + if self.origin: + self.find_rrset( + self.zone, + self.origin, + rdclass, + dns.rdatatype.SOA, + create=True, + force_unique=True, + ) + if keyring is not None: + self.use_tsig(keyring, keyname, algorithm=keyalgorithm) + + @property + def zone(self) -> List[dns.rrset.RRset]: + """The zone section.""" + return self.sections[0] + + @zone.setter + def zone(self, v): + self.sections[0] = v + + @property + def prerequisite(self) -> List[dns.rrset.RRset]: + """The prerequisite section.""" + return self.sections[1] + + @prerequisite.setter + def prerequisite(self, v): + self.sections[1] = v + + @property + def update(self) -> List[dns.rrset.RRset]: + """The update section.""" + return self.sections[2] + + @update.setter + def update(self, v): + self.sections[2] = v + + def _add_rr(self, name, ttl, rd, deleting=None, section=None): + """Add a single RR to the update section.""" + + if section is None: + section = self.update + covers = rd.covers() + rrset = self.find_rrset( + section, name, self.zone_rdclass, rd.rdtype, covers, deleting, True, True + ) + rrset.add(rd, ttl) + + def _add(self, replace, section, name, *args): + """Add records. + + *replace* is the replacement mode. If ``False``, + RRs are added to an existing RRset; if ``True``, the RRset + is replaced with the specified contents. The second + argument is the section to add to. The third argument + is always a name. The other arguments can be: + + - rdataset... + + - ttl, rdata... + + - ttl, rdtype, string... + """ + + if isinstance(name, str): + name = dns.name.from_text(name, None) + if isinstance(args[0], dns.rdataset.Rdataset): + for rds in args: + if replace: + self.delete(name, rds.rdtype) + for rd in rds: + self._add_rr(name, rds.ttl, rd, section=section) + else: + args = list(args) + ttl = int(args.pop(0)) + if isinstance(args[0], dns.rdata.Rdata): + if replace: + self.delete(name, args[0].rdtype) + for rd in args: + self._add_rr(name, ttl, rd, section=section) + else: + rdtype = dns.rdatatype.RdataType.make(args.pop(0)) + if replace: + self.delete(name, rdtype) + for s in args: + rd = dns.rdata.from_text(self.zone_rdclass, rdtype, s, self.origin) + self._add_rr(name, ttl, rd, section=section) + + def add(self, name: dns.name.Name | str, *args: Any) -> None: + """Add records. + + The first argument is always a name. The other + arguments can be: + + - rdataset... + + - ttl, rdata... + + - ttl, rdtype, string... + """ + + self._add(False, self.update, name, *args) + + def delete(self, name: dns.name.Name | str, *args: Any) -> None: + """Delete records. + + The first argument is always a name. The other + arguments can be: + + - *empty* + + - rdataset... + + - rdata... + + - rdtype, [string...] + """ + + if isinstance(name, str): + name = dns.name.from_text(name, None) + if len(args) == 0: + self.find_rrset( + self.update, + name, + dns.rdataclass.ANY, + dns.rdatatype.ANY, + dns.rdatatype.NONE, + dns.rdataclass.ANY, + True, + True, + ) + elif isinstance(args[0], dns.rdataset.Rdataset): + for rds in args: + for rd in rds: + self._add_rr(name, 0, rd, dns.rdataclass.NONE) + else: + largs = list(args) + if isinstance(largs[0], dns.rdata.Rdata): + for rd in largs: + self._add_rr(name, 0, rd, dns.rdataclass.NONE) + else: + rdtype = dns.rdatatype.RdataType.make(largs.pop(0)) + if len(largs) == 0: + self.find_rrset( + self.update, + name, + self.zone_rdclass, + rdtype, + dns.rdatatype.NONE, + dns.rdataclass.ANY, + True, + True, + ) + else: + for s in largs: + rd = dns.rdata.from_text( + self.zone_rdclass, + rdtype, + s, # type: ignore[arg-type] + self.origin, + ) + self._add_rr(name, 0, rd, dns.rdataclass.NONE) + + def replace(self, name: dns.name.Name | str, *args: Any) -> None: + """Replace records. + + The first argument is always a name. The other + arguments can be: + + - rdataset... + + - ttl, rdata... + + - ttl, rdtype, string... + + Note that if you want to replace the entire node, you should do + a delete of the name followed by one or more calls to add. + """ + + self._add(True, self.update, name, *args) + + def present(self, name: dns.name.Name | str, *args: Any) -> None: + """Require that an owner name (and optionally an rdata type, + or specific rdataset) exists as a prerequisite to the + execution of the update. + + The first argument is always a name. + The other arguments can be: + + - rdataset... + + - rdata... + + - rdtype, string... + """ + + if isinstance(name, str): + name = dns.name.from_text(name, None) + if len(args) == 0: + self.find_rrset( + self.prerequisite, + name, + dns.rdataclass.ANY, + dns.rdatatype.ANY, + dns.rdatatype.NONE, + None, + True, + True, + ) + elif ( + isinstance(args[0], dns.rdataset.Rdataset) + or isinstance(args[0], dns.rdata.Rdata) + or len(args) > 1 + ): + if not isinstance(args[0], dns.rdataset.Rdataset): + # Add a 0 TTL + largs = list(args) + largs.insert(0, 0) # type: ignore[arg-type] + self._add(False, self.prerequisite, name, *largs) + else: + self._add(False, self.prerequisite, name, *args) + else: + rdtype = dns.rdatatype.RdataType.make(args[0]) + self.find_rrset( + self.prerequisite, + name, + dns.rdataclass.ANY, + rdtype, + dns.rdatatype.NONE, + None, + True, + True, + ) + + def absent( + self, + name: dns.name.Name | str, + rdtype: dns.rdatatype.RdataType | str | None = None, + ) -> None: + """Require that an owner name (and optionally an rdata type) does + not exist as a prerequisite to the execution of the update.""" + + if isinstance(name, str): + name = dns.name.from_text(name, None) + if rdtype is None: + self.find_rrset( + self.prerequisite, + name, + dns.rdataclass.NONE, + dns.rdatatype.ANY, + dns.rdatatype.NONE, + None, + True, + True, + ) + else: + rdtype = dns.rdatatype.RdataType.make(rdtype) + self.find_rrset( + self.prerequisite, + name, + dns.rdataclass.NONE, + rdtype, + dns.rdatatype.NONE, + None, + True, + True, + ) + + def _get_one_rr_per_rrset(self, value): + # Updates are always one_rr_per_rrset + return True + + def _parse_rr_header(self, section, name, rdclass, rdtype): # pyright: ignore + deleting = None + empty = False + if section == UpdateSection.ZONE: + if ( + dns.rdataclass.is_metaclass(rdclass) + or rdtype != dns.rdatatype.SOA + or self.zone + ): + raise dns.exception.FormError + else: + if not self.zone: + raise dns.exception.FormError + if rdclass in (dns.rdataclass.ANY, dns.rdataclass.NONE): + deleting = rdclass + rdclass = self.zone[0].rdclass + empty = ( + deleting == dns.rdataclass.ANY or section == UpdateSection.PREREQ + ) + return (rdclass, rdtype, deleting, empty) + + +# backwards compatibility +Update = UpdateMessage + +### BEGIN generated UpdateSection constants + +ZONE = UpdateSection.ZONE +PREREQ = UpdateSection.PREREQ +UPDATE = UpdateSection.UPDATE +ADDITIONAL = UpdateSection.ADDITIONAL + +### END generated UpdateSection constants diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/version.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/version.py new file mode 100644 index 000000000..e11dd29c2 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/version.py @@ -0,0 +1,42 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +# Copyright (C) 2003-2017 Nominum, Inc. +# +# Permission to use, copy, modify, and distribute this software and its +# documentation for any purpose with or without fee is hereby granted, +# provided that the above copyright notice and this permission notice +# appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +"""dnspython release version information.""" + +#: MAJOR +MAJOR = 2 +#: MINOR +MINOR = 8 +#: MICRO +MICRO = 0 +#: RELEASELEVEL +RELEASELEVEL = 0x0F +#: SERIAL +SERIAL = 0 + +if RELEASELEVEL == 0x0F: # pragma: no cover lgtm[py/unreachable-statement] + #: version + version = f"{MAJOR}.{MINOR}.{MICRO}" # lgtm[py/unreachable-statement] +elif RELEASELEVEL == 0x00: # pragma: no cover lgtm[py/unreachable-statement] + version = f"{MAJOR}.{MINOR}.{MICRO}dev{SERIAL}" # lgtm[py/unreachable-statement] +elif RELEASELEVEL == 0x0C: # pragma: no cover lgtm[py/unreachable-statement] + version = f"{MAJOR}.{MINOR}.{MICRO}rc{SERIAL}" # lgtm[py/unreachable-statement] +else: # pragma: no cover lgtm[py/unreachable-statement] + version = f"{MAJOR}.{MINOR}.{MICRO}{RELEASELEVEL:x}{SERIAL}" # lgtm[py/unreachable-statement] + +#: hexversion +hexversion = MAJOR << 24 | MINOR << 16 | MICRO << 8 | RELEASELEVEL << 4 | SERIAL diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/versioned.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/versioned.py new file mode 100644 index 000000000..3644711eb --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/versioned.py @@ -0,0 +1,320 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +"""DNS Versioned Zones.""" + +import collections +import threading +from typing import Callable, Deque, Set, cast + +import dns.exception +import dns.name +import dns.node +import dns.rdataclass +import dns.rdataset +import dns.rdatatype +import dns.rdtypes.ANY.SOA +import dns.zone + + +class UseTransaction(dns.exception.DNSException): + """To alter a versioned zone, use a transaction.""" + + +# Backwards compatibility +Node = dns.zone.VersionedNode +ImmutableNode = dns.zone.ImmutableVersionedNode +Version = dns.zone.Version +WritableVersion = dns.zone.WritableVersion +ImmutableVersion = dns.zone.ImmutableVersion +Transaction = dns.zone.Transaction + + +class Zone(dns.zone.Zone): # lgtm[py/missing-equals] + __slots__ = [ + "_versions", + "_versions_lock", + "_write_txn", + "_write_waiters", + "_write_event", + "_pruning_policy", + "_readers", + ] + + node_factory: Callable[[], dns.node.Node] = Node + + def __init__( + self, + origin: dns.name.Name | str | None, + rdclass: dns.rdataclass.RdataClass = dns.rdataclass.IN, + relativize: bool = True, + pruning_policy: Callable[["Zone", Version], bool | None] | None = None, + ): + """Initialize a versioned zone object. + + *origin* is the origin of the zone. It may be a ``dns.name.Name``, + a ``str``, or ``None``. If ``None``, then the zone's origin will + be set by the first ``$ORIGIN`` line in a zone file. + + *rdclass*, an ``int``, the zone's rdata class; the default is class IN. + + *relativize*, a ``bool``, determine's whether domain names are + relativized to the zone's origin. The default is ``True``. + + *pruning policy*, a function taking a ``Zone`` and a ``Version`` and returning + a ``bool``, or ``None``. Should the version be pruned? If ``None``, + the default policy, which retains one version is used. + """ + super().__init__(origin, rdclass, relativize) + self._versions: Deque[Version] = collections.deque() + self._version_lock = threading.Lock() + if pruning_policy is None: + self._pruning_policy = self._default_pruning_policy + else: + self._pruning_policy = pruning_policy + self._write_txn: Transaction | None = None + self._write_event: threading.Event | None = None + self._write_waiters: Deque[threading.Event] = collections.deque() + self._readers: Set[Transaction] = set() + self._commit_version_unlocked( + None, WritableVersion(self, replacement=True), origin + ) + + def reader( + self, id: int | None = None, serial: int | None = None + ) -> Transaction: # pylint: disable=arguments-differ + if id is not None and serial is not None: + raise ValueError("cannot specify both id and serial") + with self._version_lock: + if id is not None: + version = None + for v in reversed(self._versions): + if v.id == id: + version = v + break + if version is None: + raise KeyError("version not found") + elif serial is not None: + if self.relativize: + oname = dns.name.empty + else: + assert self.origin is not None + oname = self.origin + version = None + for v in reversed(self._versions): + n = v.nodes.get(oname) + if n: + rds = n.get_rdataset(self.rdclass, dns.rdatatype.SOA) + if rds is None: + continue + soa = cast(dns.rdtypes.ANY.SOA.SOA, rds[0]) + if rds and soa.serial == serial: + version = v + break + if version is None: + raise KeyError("serial not found") + else: + version = self._versions[-1] + txn = Transaction(self, False, version) + self._readers.add(txn) + return txn + + def writer(self, replacement: bool = False) -> Transaction: + event = None + while True: + with self._version_lock: + # Checking event == self._write_event ensures that either + # no one was waiting before we got lucky and found no write + # txn, or we were the one who was waiting and got woken up. + # This prevents "taking cuts" when creating a write txn. + if self._write_txn is None and event == self._write_event: + # Creating the transaction defers version setup + # (i.e. copying the nodes dictionary) until we + # give up the lock, so that we hold the lock as + # short a time as possible. This is why we call + # _setup_version() below. + self._write_txn = Transaction( + self, replacement, make_immutable=True + ) + # give up our exclusive right to make a Transaction + self._write_event = None + break + # Someone else is writing already, so we will have to + # wait, but we want to do the actual wait outside the + # lock. + event = threading.Event() + self._write_waiters.append(event) + # wait (note we gave up the lock!) + # + # We only wake one sleeper at a time, so it's important + # that no event waiter can exit this method (e.g. via + # cancellation) without returning a transaction or waking + # someone else up. + # + # This is not a problem with Threading module threads as + # they cannot be canceled, but could be an issue with trio + # tasks when we do the async version of writer(). + # I.e. we'd need to do something like: + # + # try: + # event.wait() + # except trio.Cancelled: + # with self._version_lock: + # self._maybe_wakeup_one_waiter_unlocked() + # raise + # + event.wait() + # Do the deferred version setup. + self._write_txn._setup_version() + return self._write_txn + + def _maybe_wakeup_one_waiter_unlocked(self): + if len(self._write_waiters) > 0: + self._write_event = self._write_waiters.popleft() + self._write_event.set() + + # pylint: disable=unused-argument + def _default_pruning_policy(self, zone, version): + return True + + # pylint: enable=unused-argument + + def _prune_versions_unlocked(self): + assert len(self._versions) > 0 + # Don't ever prune a version greater than or equal to one that + # a reader has open. This pins versions in memory while the + # reader is open, and importantly lets the reader open a txn on + # a successor version (e.g. if generating an IXFR). + # + # Note our definition of least_kept also ensures we do not try to + # delete the greatest version. + if len(self._readers) > 0: + least_kept = min(txn.version.id for txn in self._readers) # pyright: ignore + else: + least_kept = self._versions[-1].id + while self._versions[0].id < least_kept and self._pruning_policy( + self, self._versions[0] + ): + self._versions.popleft() + + def set_max_versions(self, max_versions: int | None) -> None: + """Set a pruning policy that retains up to the specified number + of versions + """ + if max_versions is not None and max_versions < 1: + raise ValueError("max versions must be at least 1") + if max_versions is None: + # pylint: disable=unused-argument + def policy(zone, _): # pyright: ignore + return False + + else: + + def policy(zone, _): + return len(zone._versions) > max_versions + + self.set_pruning_policy(policy) + + def set_pruning_policy( + self, policy: Callable[["Zone", Version], bool | None] | None + ) -> None: + """Set the pruning policy for the zone. + + The *policy* function takes a `Version` and returns `True` if + the version should be pruned, and `False` otherwise. `None` + may also be specified for policy, in which case the default policy + is used. + + Pruning checking proceeds from the least version and the first + time the function returns `False`, the checking stops. I.e. the + retained versions are always a consecutive sequence. + """ + if policy is None: + policy = self._default_pruning_policy + with self._version_lock: + self._pruning_policy = policy + self._prune_versions_unlocked() + + def _end_read(self, txn): + with self._version_lock: + self._readers.remove(txn) + self._prune_versions_unlocked() + + def _end_write_unlocked(self, txn): + assert self._write_txn == txn + self._write_txn = None + self._maybe_wakeup_one_waiter_unlocked() + + def _end_write(self, txn): + with self._version_lock: + self._end_write_unlocked(txn) + + def _commit_version_unlocked(self, txn, version, origin): + self._versions.append(version) + self._prune_versions_unlocked() + self.nodes = version.nodes + if self.origin is None: + self.origin = origin + # txn can be None in __init__ when we make the empty version. + if txn is not None: + self._end_write_unlocked(txn) + + def _commit_version(self, txn, version, origin): + with self._version_lock: + self._commit_version_unlocked(txn, version, origin) + + def _get_next_version_id(self): + if len(self._versions) > 0: + id = self._versions[-1].id + 1 + else: + id = 1 + return id + + def find_node( + self, name: dns.name.Name | str, create: bool = False + ) -> dns.node.Node: + if create: + raise UseTransaction + return super().find_node(name) + + def delete_node(self, name: dns.name.Name | str) -> None: + raise UseTransaction + + def find_rdataset( + self, + name: dns.name.Name | str, + rdtype: dns.rdatatype.RdataType | str, + covers: dns.rdatatype.RdataType | str = dns.rdatatype.NONE, + create: bool = False, + ) -> dns.rdataset.Rdataset: + if create: + raise UseTransaction + rdataset = super().find_rdataset(name, rdtype, covers) + return dns.rdataset.ImmutableRdataset(rdataset) + + def get_rdataset( + self, + name: dns.name.Name | str, + rdtype: dns.rdatatype.RdataType | str, + covers: dns.rdatatype.RdataType | str = dns.rdatatype.NONE, + create: bool = False, + ) -> dns.rdataset.Rdataset | None: + if create: + raise UseTransaction + rdataset = super().get_rdataset(name, rdtype, covers) + if rdataset is not None: + return dns.rdataset.ImmutableRdataset(rdataset) + else: + return None + + def delete_rdataset( + self, + name: dns.name.Name | str, + rdtype: dns.rdatatype.RdataType | str, + covers: dns.rdatatype.RdataType | str = dns.rdatatype.NONE, + ) -> None: + raise UseTransaction + + def replace_rdataset( + self, name: dns.name.Name | str, replacement: dns.rdataset.Rdataset + ) -> None: + raise UseTransaction diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/win32util.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/win32util.py new file mode 100644 index 000000000..2d77b4cb6 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/win32util.py @@ -0,0 +1,438 @@ +import sys + +import dns._features + +# pylint: disable=W0612,W0613,C0301 + +if sys.platform == "win32": + import ctypes + import ctypes.wintypes as wintypes + import winreg # pylint: disable=import-error + from enum import IntEnum + + import dns.name + + # Keep pylint quiet on non-windows. + try: + _ = WindowsError # pylint: disable=used-before-assignment + except NameError: + WindowsError = Exception + + class ConfigMethod(IntEnum): + Registry = 1 + WMI = 2 + Win32 = 3 + + class DnsInfo: + def __init__(self): + self.domain = None + self.nameservers = [] + self.search = [] + + _config_method = ConfigMethod.Registry + + if dns._features.have("wmi"): + import threading + + import pythoncom # pylint: disable=import-error + import wmi # pylint: disable=import-error + + # Prefer WMI by default if wmi is installed. + _config_method = ConfigMethod.WMI + + class _WMIGetter(threading.Thread): + # pylint: disable=possibly-used-before-assignment + def __init__(self): + super().__init__() + self.info = DnsInfo() + + def run(self): + pythoncom.CoInitialize() + try: + system = wmi.WMI() + for interface in system.Win32_NetworkAdapterConfiguration(): + if interface.IPEnabled and interface.DNSServerSearchOrder: + self.info.nameservers = list(interface.DNSServerSearchOrder) + if interface.DNSDomain: + self.info.domain = _config_domain(interface.DNSDomain) + if interface.DNSDomainSuffixSearchOrder: + self.info.search = [ + _config_domain(x) + for x in interface.DNSDomainSuffixSearchOrder + ] + break + finally: + pythoncom.CoUninitialize() + + def get(self): + # We always run in a separate thread to avoid any issues with + # the COM threading model. + self.start() + self.join() + return self.info + + else: + + class _WMIGetter: # type: ignore + pass + + def _config_domain(domain): + # Sometimes DHCP servers add a '.' prefix to the default domain, and + # Windows just stores such values in the registry (see #687). + # Check for this and fix it. + if domain.startswith("."): + domain = domain[1:] + return dns.name.from_text(domain) + + class _RegistryGetter: + def __init__(self): + self.info = DnsInfo() + + def _split(self, text): + # The windows registry has used both " " and "," as a delimiter, and while + # it is currently using "," in Windows 10 and later, updates can seemingly + # leave a space in too, e.g. "a, b". So we just convert all commas to + # spaces, and use split() in its default configuration, which splits on + # all whitespace and ignores empty strings. + return text.replace(",", " ").split() + + def _config_nameservers(self, nameservers): + for ns in self._split(nameservers): + if ns not in self.info.nameservers: + self.info.nameservers.append(ns) + + def _config_search(self, search): + for s in self._split(search): + s = _config_domain(s) + if s not in self.info.search: + self.info.search.append(s) + + def _config_fromkey(self, key, always_try_domain): + try: + servers, _ = winreg.QueryValueEx(key, "NameServer") + except WindowsError: + servers = None + if servers: + self._config_nameservers(servers) + if servers or always_try_domain: + try: + dom, _ = winreg.QueryValueEx(key, "Domain") + if dom: + self.info.domain = _config_domain(dom) + except WindowsError: + pass + else: + try: + servers, _ = winreg.QueryValueEx(key, "DhcpNameServer") + except WindowsError: + servers = None + if servers: + self._config_nameservers(servers) + try: + dom, _ = winreg.QueryValueEx(key, "DhcpDomain") + if dom: + self.info.domain = _config_domain(dom) + except WindowsError: + pass + try: + search, _ = winreg.QueryValueEx(key, "SearchList") + except WindowsError: + search = None + if search is None: + try: + search, _ = winreg.QueryValueEx(key, "DhcpSearchList") + except WindowsError: + search = None + if search: + self._config_search(search) + + def _is_nic_enabled(self, lm, guid): + # Look in the Windows Registry to determine whether the network + # interface corresponding to the given guid is enabled. + # + # (Code contributed by Paul Marks, thanks!) + # + try: + # This hard-coded location seems to be consistent, at least + # from Windows 2000 through Vista. + connection_key = winreg.OpenKey( + lm, + r"SYSTEM\CurrentControlSet\Control\Network" + r"\{4D36E972-E325-11CE-BFC1-08002BE10318}" + rf"\{guid}\Connection", + ) + + try: + # The PnpInstanceID points to a key inside Enum + (pnp_id, ttype) = winreg.QueryValueEx( + connection_key, "PnpInstanceID" + ) + + if ttype != winreg.REG_SZ: + raise ValueError # pragma: no cover + + device_key = winreg.OpenKey( + lm, rf"SYSTEM\CurrentControlSet\Enum\{pnp_id}" + ) + + try: + # Get ConfigFlags for this device + (flags, ttype) = winreg.QueryValueEx(device_key, "ConfigFlags") + + if ttype != winreg.REG_DWORD: + raise ValueError # pragma: no cover + + # Based on experimentation, bit 0x1 indicates that the + # device is disabled. + # + # XXXRTH I suspect we really want to & with 0x03 so + # that CONFIGFLAGS_REMOVED devices are also ignored, + # but we're shifting to WMI as ConfigFlags is not + # supposed to be used. + return not flags & 0x1 + + finally: + device_key.Close() + finally: + connection_key.Close() + except Exception: # pragma: no cover + return False + + def get(self): + """Extract resolver configuration from the Windows registry.""" + + lm = winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE) + try: + tcp_params = winreg.OpenKey( + lm, r"SYSTEM\CurrentControlSet\Services\Tcpip\Parameters" + ) + try: + self._config_fromkey(tcp_params, True) + finally: + tcp_params.Close() + interfaces = winreg.OpenKey( + lm, + r"SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\Interfaces", + ) + try: + i = 0 + while True: + try: + guid = winreg.EnumKey(interfaces, i) + i += 1 + key = winreg.OpenKey(interfaces, guid) + try: + if not self._is_nic_enabled(lm, guid): + continue + self._config_fromkey(key, False) + finally: + key.Close() + except OSError: + break + finally: + interfaces.Close() + finally: + lm.Close() + return self.info + + class _Win32Getter(_RegistryGetter): + + def get(self): + """Get the attributes using the Windows API.""" + # Load the IP Helper library + # # https://learn.microsoft.com/en-us/windows/win32/api/iphlpapi/nf-iphlpapi-getadaptersaddresses + IPHLPAPI = ctypes.WinDLL("Iphlpapi.dll") + + # Constants + AF_UNSPEC = 0 + ERROR_SUCCESS = 0 + GAA_FLAG_INCLUDE_PREFIX = 0x00000010 + AF_INET = 2 + AF_INET6 = 23 + IF_TYPE_SOFTWARE_LOOPBACK = 24 + + # Define necessary structures + class SOCKADDRV4(ctypes.Structure): + _fields_ = [ + ("sa_family", wintypes.USHORT), + ("sa_data", ctypes.c_ubyte * 14), + ] + + class SOCKADDRV6(ctypes.Structure): + _fields_ = [ + ("sa_family", wintypes.USHORT), + ("sa_data", ctypes.c_ubyte * 26), + ] + + class SOCKET_ADDRESS(ctypes.Structure): + _fields_ = [ + ("lpSockaddr", ctypes.POINTER(SOCKADDRV4)), + ("iSockaddrLength", wintypes.INT), + ] + + class IP_ADAPTER_DNS_SERVER_ADDRESS(ctypes.Structure): + pass # Forward declaration + + IP_ADAPTER_DNS_SERVER_ADDRESS._fields_ = [ + ("Length", wintypes.ULONG), + ("Reserved", wintypes.DWORD), + ("Next", ctypes.POINTER(IP_ADAPTER_DNS_SERVER_ADDRESS)), + ("Address", SOCKET_ADDRESS), + ] + + class IF_LUID(ctypes.Structure): + _fields_ = [("Value", ctypes.c_ulonglong)] + + class NET_IF_NETWORK_GUID(ctypes.Structure): + _fields_ = [("Value", ctypes.c_ubyte * 16)] + + class IP_ADAPTER_PREFIX_XP(ctypes.Structure): + pass # Left undefined here for simplicity + + class IP_ADAPTER_GATEWAY_ADDRESS_LH(ctypes.Structure): + pass # Left undefined here for simplicity + + class IP_ADAPTER_DNS_SUFFIX(ctypes.Structure): + _fields_ = [ + ("String", ctypes.c_wchar * 256), + ("Next", ctypes.POINTER(ctypes.c_void_p)), + ] + + class IP_ADAPTER_UNICAST_ADDRESS_LH(ctypes.Structure): + pass # Left undefined here for simplicity + + class IP_ADAPTER_MULTICAST_ADDRESS_XP(ctypes.Structure): + pass # Left undefined here for simplicity + + class IP_ADAPTER_ANYCAST_ADDRESS_XP(ctypes.Structure): + pass # Left undefined here for simplicity + + class IP_ADAPTER_DNS_SERVER_ADDRESS_XP(ctypes.Structure): + pass # Left undefined here for simplicity + + class IP_ADAPTER_ADDRESSES(ctypes.Structure): + pass # Forward declaration + + IP_ADAPTER_ADDRESSES._fields_ = [ + ("Length", wintypes.ULONG), + ("IfIndex", wintypes.DWORD), + ("Next", ctypes.POINTER(IP_ADAPTER_ADDRESSES)), + ("AdapterName", ctypes.c_char_p), + ("FirstUnicastAddress", ctypes.POINTER(SOCKET_ADDRESS)), + ("FirstAnycastAddress", ctypes.POINTER(SOCKET_ADDRESS)), + ("FirstMulticastAddress", ctypes.POINTER(SOCKET_ADDRESS)), + ( + "FirstDnsServerAddress", + ctypes.POINTER(IP_ADAPTER_DNS_SERVER_ADDRESS), + ), + ("DnsSuffix", wintypes.LPWSTR), + ("Description", wintypes.LPWSTR), + ("FriendlyName", wintypes.LPWSTR), + ("PhysicalAddress", ctypes.c_ubyte * 8), + ("PhysicalAddressLength", wintypes.ULONG), + ("Flags", wintypes.ULONG), + ("Mtu", wintypes.ULONG), + ("IfType", wintypes.ULONG), + ("OperStatus", ctypes.c_uint), + # Remaining fields removed for brevity + ] + + def format_ipv4(sockaddr_in): + return ".".join(map(str, sockaddr_in.sa_data[2:6])) + + def format_ipv6(sockaddr_in6): + # The sa_data is: + # + # USHORT sin6_port; + # ULONG sin6_flowinfo; + # IN6_ADDR sin6_addr; + # ULONG sin6_scope_id; + # + # which is 2 + 4 + 16 + 4 = 26 bytes, and we need the plus 6 below + # to be in the sin6_addr range. + parts = [ + sockaddr_in6.sa_data[i + 6] << 8 | sockaddr_in6.sa_data[i + 6 + 1] + for i in range(0, 16, 2) + ] + return ":".join(f"{part:04x}" for part in parts) + + buffer_size = ctypes.c_ulong(15000) + while True: + buffer = ctypes.create_string_buffer(buffer_size.value) + + ret_val = IPHLPAPI.GetAdaptersAddresses( + AF_UNSPEC, + GAA_FLAG_INCLUDE_PREFIX, + None, + buffer, + ctypes.byref(buffer_size), + ) + + if ret_val == ERROR_SUCCESS: + break + elif ret_val != 0x6F: # ERROR_BUFFER_OVERFLOW + print(f"Error retrieving adapter information: {ret_val}") + return + + adapter_addresses = ctypes.cast( + buffer, ctypes.POINTER(IP_ADAPTER_ADDRESSES) + ) + + current_adapter = adapter_addresses + while current_adapter: + + # Skip non-operational adapters. + oper_status = current_adapter.contents.OperStatus + if oper_status != 1: + current_adapter = current_adapter.contents.Next + continue + + # Exclude loopback adapters. + if current_adapter.contents.IfType == IF_TYPE_SOFTWARE_LOOPBACK: + current_adapter = current_adapter.contents.Next + continue + + # Get the domain from the DnsSuffix attribute. + dns_suffix = current_adapter.contents.DnsSuffix + if dns_suffix: + self.info.domain = dns.name.from_text(dns_suffix) + + current_dns_server = current_adapter.contents.FirstDnsServerAddress + while current_dns_server: + sockaddr = current_dns_server.contents.Address.lpSockaddr + sockaddr_family = sockaddr.contents.sa_family + + ip = None + if sockaddr_family == AF_INET: # IPv4 + ip = format_ipv4(sockaddr.contents) + elif sockaddr_family == AF_INET6: # IPv6 + sockaddr = ctypes.cast(sockaddr, ctypes.POINTER(SOCKADDRV6)) + ip = format_ipv6(sockaddr.contents) + + if ip: + if ip not in self.info.nameservers: + self.info.nameservers.append(ip) + + current_dns_server = current_dns_server.contents.Next + + current_adapter = current_adapter.contents.Next + + # Use the registry getter to get the search info, since it is set at the system level. + registry_getter = _RegistryGetter() + info = registry_getter.get() + self.info.search = info.search + return self.info + + def set_config_method(method: ConfigMethod) -> None: + global _config_method + _config_method = method + + def get_dns_info() -> DnsInfo: + """Extract resolver configuration.""" + if _config_method == ConfigMethod.Win32: + getter = _Win32Getter() + elif _config_method == ConfigMethod.WMI: + getter = _WMIGetter() + else: + getter = _RegistryGetter() + return getter.get() diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/wire.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/wire.py new file mode 100644 index 000000000..cd027fa16 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/wire.py @@ -0,0 +1,98 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +import contextlib +import struct +from typing import Iterator, Optional, Tuple + +import dns.exception +import dns.name + + +class Parser: + """Helper class for parsing DNS wire format.""" + + def __init__(self, wire: bytes, current: int = 0): + """Initialize a Parser + + *wire*, a ``bytes`` contains the data to be parsed, and possibly other data. + Typically it is the whole message or a slice of it. + + *current*, an `int`, the offset within *wire* where parsing should begin. + """ + self.wire = wire + self.current = 0 + self.end = len(self.wire) + if current: + self.seek(current) + self.furthest = current + + def remaining(self) -> int: + return self.end - self.current + + def get_bytes(self, size: int) -> bytes: + assert size >= 0 + if size > self.remaining(): + raise dns.exception.FormError + output = self.wire[self.current : self.current + size] + self.current += size + self.furthest = max(self.furthest, self.current) + return output + + def get_counted_bytes(self, length_size: int = 1) -> bytes: + length = int.from_bytes(self.get_bytes(length_size), "big") + return self.get_bytes(length) + + def get_remaining(self) -> bytes: + return self.get_bytes(self.remaining()) + + def get_uint8(self) -> int: + return struct.unpack("!B", self.get_bytes(1))[0] + + def get_uint16(self) -> int: + return struct.unpack("!H", self.get_bytes(2))[0] + + def get_uint32(self) -> int: + return struct.unpack("!I", self.get_bytes(4))[0] + + def get_uint48(self) -> int: + return int.from_bytes(self.get_bytes(6), "big") + + def get_struct(self, format: str) -> Tuple: + return struct.unpack(format, self.get_bytes(struct.calcsize(format))) + + def get_name(self, origin: Optional["dns.name.Name"] = None) -> "dns.name.Name": + name = dns.name.from_wire_parser(self) + if origin: + name = name.relativize(origin) + return name + + def seek(self, where: int) -> None: + # Note that seeking to the end is OK! (If you try to read + # after such a seek, you'll get an exception as expected.) + if where < 0 or where > self.end: + raise dns.exception.FormError + self.current = where + + @contextlib.contextmanager + def restrict_to(self, size: int) -> Iterator: + assert size >= 0 + if size > self.remaining(): + raise dns.exception.FormError + saved_end = self.end + try: + self.end = self.current + size + yield + # We make this check here and not in the finally as we + # don't want to raise if we're already raising for some + # other reason. + if self.current != self.end: + raise dns.exception.FormError + finally: + self.end = saved_end + + @contextlib.contextmanager + def restore_furthest(self) -> Iterator: + try: + yield None + finally: + self.current = self.furthest diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/xfr.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/xfr.py new file mode 100644 index 000000000..219fdc8ca --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/xfr.py @@ -0,0 +1,356 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +# Copyright (C) 2003-2017 Nominum, Inc. +# +# Permission to use, copy, modify, and distribute this software and its +# documentation for any purpose with or without fee is hereby granted, +# provided that the above copyright notice and this permission notice +# appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +from typing import Any, List, Tuple, cast + +import dns.edns +import dns.exception +import dns.message +import dns.name +import dns.rcode +import dns.rdata +import dns.rdataset +import dns.rdatatype +import dns.rdtypes +import dns.rdtypes.ANY +import dns.rdtypes.ANY.SMIMEA +import dns.rdtypes.ANY.SOA +import dns.rdtypes.svcbbase +import dns.serial +import dns.transaction +import dns.tsig +import dns.zone + + +class TransferError(dns.exception.DNSException): + """A zone transfer response got a non-zero rcode.""" + + def __init__(self, rcode): + message = f"Zone transfer error: {dns.rcode.to_text(rcode)}" + super().__init__(message) + self.rcode = rcode + + +class SerialWentBackwards(dns.exception.FormError): + """The current serial number is less than the serial we know.""" + + +class UseTCP(dns.exception.DNSException): + """This IXFR cannot be completed with UDP.""" + + +class Inbound: + """ + State machine for zone transfers. + """ + + def __init__( + self, + txn_manager: dns.transaction.TransactionManager, + rdtype: dns.rdatatype.RdataType = dns.rdatatype.AXFR, + serial: int | None = None, + is_udp: bool = False, + ): + """Initialize an inbound zone transfer. + + *txn_manager* is a :py:class:`dns.transaction.TransactionManager`. + + *rdtype* can be `dns.rdatatype.AXFR` or `dns.rdatatype.IXFR` + + *serial* is the base serial number for IXFRs, and is required in + that case. + + *is_udp*, a ``bool`` indidicates if UDP is being used for this + XFR. + """ + self.txn_manager = txn_manager + self.txn: dns.transaction.Transaction | None = None + self.rdtype = rdtype + if rdtype == dns.rdatatype.IXFR: + if serial is None: + raise ValueError("a starting serial must be supplied for IXFRs") + self.incremental = True + elif rdtype == dns.rdatatype.AXFR: + if is_udp: + raise ValueError("is_udp specified for AXFR") + self.incremental = False + else: + raise ValueError("rdtype is not IXFR or AXFR") + self.serial = serial + self.is_udp = is_udp + (_, _, self.origin) = txn_manager.origin_information() + self.soa_rdataset: dns.rdataset.Rdataset | None = None + self.done = False + self.expecting_SOA = False + self.delete_mode = False + + def process_message(self, message: dns.message.Message) -> bool: + """Process one message in the transfer. + + The message should have the same relativization as was specified when + the `dns.xfr.Inbound` was created. The message should also have been + created with `one_rr_per_rrset=True` because order matters. + + Returns `True` if the transfer is complete, and `False` otherwise. + """ + if self.txn is None: + self.txn = self.txn_manager.writer(not self.incremental) + rcode = message.rcode() + if rcode != dns.rcode.NOERROR: + raise TransferError(rcode) + # + # We don't require a question section, but if it is present is + # should be correct. + # + if len(message.question) > 0: + if message.question[0].name != self.origin: + raise dns.exception.FormError("wrong question name") + if message.question[0].rdtype != self.rdtype: + raise dns.exception.FormError("wrong question rdatatype") + answer_index = 0 + if self.soa_rdataset is None: + # + # This is the first message. We're expecting an SOA at + # the origin. + # + if not message.answer or message.answer[0].name != self.origin: + raise dns.exception.FormError("No answer or RRset not for zone origin") + rrset = message.answer[0] + rdataset = rrset + if rdataset.rdtype != dns.rdatatype.SOA: + raise dns.exception.FormError("first RRset is not an SOA") + answer_index = 1 + self.soa_rdataset = rdataset.copy() # pyright: ignore + if self.incremental: + assert self.soa_rdataset is not None + soa = cast(dns.rdtypes.ANY.SOA.SOA, self.soa_rdataset[0]) + if soa.serial == self.serial: + # + # We're already up-to-date. + # + self.done = True + elif dns.serial.Serial(soa.serial) < self.serial: + # It went backwards! + raise SerialWentBackwards + else: + if self.is_udp and len(message.answer[answer_index:]) == 0: + # + # There are no more records, so this is the + # "truncated" response. Say to use TCP + # + raise UseTCP + # + # Note we're expecting another SOA so we can detect + # if this IXFR response is an AXFR-style response. + # + self.expecting_SOA = True + # + # Process the answer section (other than the initial SOA in + # the first message). + # + for rrset in message.answer[answer_index:]: + name = rrset.name + rdataset = rrset + if self.done: + raise dns.exception.FormError("answers after final SOA") + assert self.txn is not None # for mypy + if rdataset.rdtype == dns.rdatatype.SOA and name == self.origin: + # + # Every time we see an origin SOA delete_mode inverts + # + if self.incremental: + self.delete_mode = not self.delete_mode + # + # If this SOA Rdataset is equal to the first we saw + # then we're finished. If this is an IXFR we also + # check that we're seeing the record in the expected + # part of the response. + # + if rdataset == self.soa_rdataset and ( + (not self.incremental) or self.delete_mode + ): + # + # This is the final SOA + # + soa = cast(dns.rdtypes.ANY.SOA.SOA, rdataset[0]) + if self.expecting_SOA: + # We got an empty IXFR sequence! + raise dns.exception.FormError("empty IXFR sequence") + if self.incremental and self.serial != soa.serial: + raise dns.exception.FormError("unexpected end of IXFR sequence") + self.txn.replace(name, rdataset) + self.txn.commit() + self.txn = None + self.done = True + else: + # + # This is not the final SOA + # + self.expecting_SOA = False + soa = cast(dns.rdtypes.ANY.SOA.SOA, rdataset[0]) + if self.incremental: + if self.delete_mode: + # This is the start of an IXFR deletion set + if soa.serial != self.serial: + raise dns.exception.FormError( + "IXFR base serial mismatch" + ) + else: + # This is the start of an IXFR addition set + self.serial = soa.serial + self.txn.replace(name, rdataset) + else: + # We saw a non-final SOA for the origin in an AXFR. + raise dns.exception.FormError("unexpected origin SOA in AXFR") + continue + if self.expecting_SOA: + # + # We made an IXFR request and are expecting another + # SOA RR, but saw something else, so this must be an + # AXFR response. + # + self.incremental = False + self.expecting_SOA = False + self.delete_mode = False + self.txn.rollback() + self.txn = self.txn_manager.writer(True) + # + # Note we are falling through into the code below + # so whatever rdataset this was gets written. + # + # Add or remove the data + if self.delete_mode: + self.txn.delete_exact(name, rdataset) + else: + self.txn.add(name, rdataset) + if self.is_udp and not self.done: + # + # This is a UDP IXFR and we didn't get to done, and we didn't + # get the proper "truncated" response + # + raise dns.exception.FormError("unexpected end of UDP IXFR") + return self.done + + # + # Inbounds are context managers. + # + + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + if self.txn: + self.txn.rollback() + return False + + +def make_query( + txn_manager: dns.transaction.TransactionManager, + serial: int | None = 0, + use_edns: int | bool | None = None, + ednsflags: int | None = None, + payload: int | None = None, + request_payload: int | None = None, + options: List[dns.edns.Option] | None = None, + keyring: Any = None, + keyname: dns.name.Name | None = None, + keyalgorithm: dns.name.Name | str = dns.tsig.default_algorithm, +) -> Tuple[dns.message.QueryMessage, int | None]: + """Make an AXFR or IXFR query. + + *txn_manager* is a ``dns.transaction.TransactionManager``, typically a + ``dns.zone.Zone``. + + *serial* is an ``int`` or ``None``. If 0, then IXFR will be + attempted using the most recent serial number from the + *txn_manager*; it is the caller's responsibility to ensure there + are no write transactions active that could invalidate the + retrieved serial. If a serial cannot be determined, AXFR will be + forced. Other integer values are the starting serial to use. + ``None`` forces an AXFR. + + Please see the documentation for :py:func:`dns.message.make_query` and + :py:func:`dns.message.Message.use_tsig` for details on the other parameters + to this function. + + Returns a `(query, serial)` tuple. + """ + (zone_origin, _, origin) = txn_manager.origin_information() + if zone_origin is None: + raise ValueError("no zone origin") + if serial is None: + rdtype = dns.rdatatype.AXFR + elif not isinstance(serial, int): + raise ValueError("serial is not an integer") + elif serial == 0: + with txn_manager.reader() as txn: + rdataset = txn.get(origin, "SOA") + if rdataset: + soa = cast(dns.rdtypes.ANY.SOA.SOA, rdataset[0]) + serial = soa.serial + rdtype = dns.rdatatype.IXFR + else: + serial = None + rdtype = dns.rdatatype.AXFR + elif serial > 0 and serial < 4294967296: + rdtype = dns.rdatatype.IXFR + else: + raise ValueError("serial out-of-range") + rdclass = txn_manager.get_class() + q = dns.message.make_query( + zone_origin, + rdtype, + rdclass, + use_edns, + False, + ednsflags, + payload, + request_payload, + options, + ) + if serial is not None: + rdata = dns.rdata.from_text(rdclass, "SOA", f". . {serial} 0 0 0 0") + rrset = q.find_rrset( + q.authority, zone_origin, rdclass, dns.rdatatype.SOA, create=True + ) + rrset.add(rdata, 0) + if keyring is not None: + q.use_tsig(keyring, keyname, algorithm=keyalgorithm) + return (q, serial) + + +def extract_serial_from_query(query: dns.message.Message) -> int | None: + """Extract the SOA serial number from query if it is an IXFR and return + it, otherwise return None. + + *query* is a dns.message.QueryMessage that is an IXFR or AXFR request. + + Raises if the query is not an IXFR or AXFR, or if an IXFR doesn't have + an appropriate SOA RRset in the authority section. + """ + if not isinstance(query, dns.message.QueryMessage): + raise ValueError("query not a QueryMessage") + question = query.question[0] + if question.rdtype == dns.rdatatype.AXFR: + return None + elif question.rdtype != dns.rdatatype.IXFR: + raise ValueError("query is not an AXFR or IXFR") + soa_rrset = query.find_rrset( + query.authority, question.name, question.rdclass, dns.rdatatype.SOA + ) + soa = cast(dns.rdtypes.ANY.SOA.SOA, soa_rrset[0]) + return soa.serial diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/zone.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/zone.py new file mode 100644 index 000000000..f916ffee5 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/zone.py @@ -0,0 +1,1462 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. +# +# Permission to use, copy, modify, and distribute this software and its +# documentation for any purpose with or without fee is hereby granted, +# provided that the above copyright notice and this permission notice +# appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +"""DNS Zones.""" + +import contextlib +import io +import os +import struct +from typing import ( + Any, + Callable, + Iterable, + Iterator, + List, + MutableMapping, + Set, + Tuple, + cast, +) + +import dns.exception +import dns.grange +import dns.immutable +import dns.name +import dns.node +import dns.rdata +import dns.rdataclass +import dns.rdataset +import dns.rdatatype +import dns.rdtypes.ANY.SOA +import dns.rdtypes.ANY.ZONEMD +import dns.rrset +import dns.tokenizer +import dns.transaction +import dns.ttl +import dns.zonefile +from dns.zonetypes import DigestHashAlgorithm, DigestScheme, _digest_hashers + + +class BadZone(dns.exception.DNSException): + """The DNS zone is malformed.""" + + +class NoSOA(BadZone): + """The DNS zone has no SOA RR at its origin.""" + + +class NoNS(BadZone): + """The DNS zone has no NS RRset at its origin.""" + + +class UnknownOrigin(BadZone): + """The DNS zone's origin is unknown.""" + + +class UnsupportedDigestScheme(dns.exception.DNSException): + """The zone digest's scheme is unsupported.""" + + +class UnsupportedDigestHashAlgorithm(dns.exception.DNSException): + """The zone digest's origin is unsupported.""" + + +class NoDigest(dns.exception.DNSException): + """The DNS zone has no ZONEMD RRset at its origin.""" + + +class DigestVerificationFailure(dns.exception.DNSException): + """The ZONEMD digest failed to verify.""" + + +def _validate_name( + name: dns.name.Name, + origin: dns.name.Name | None, + relativize: bool, +) -> dns.name.Name: + # This name validation code is shared by Zone and Version + if origin is None: + # This should probably never happen as other code (e.g. + # _rr_line) will notice the lack of an origin before us, but + # we check just in case! + raise KeyError("no zone origin is defined") + if name.is_absolute(): + if not name.is_subdomain(origin): + raise KeyError("name parameter must be a subdomain of the zone origin") + if relativize: + name = name.relativize(origin) + else: + # We have a relative name. Make sure that the derelativized name is + # not too long. + try: + abs_name = name.derelativize(origin) + except dns.name.NameTooLong: + # We map dns.name.NameTooLong to KeyError to be consistent with + # the other exceptions above. + raise KeyError("relative name too long for zone") + if not relativize: + # We have a relative name in a non-relative zone, so use the + # derelativized name. + name = abs_name + return name + + +class Zone(dns.transaction.TransactionManager): + """A DNS zone. + + A ``Zone`` is a mapping from names to nodes. The zone object may be + treated like a Python dictionary, e.g. ``zone[name]`` will retrieve + the node associated with that name. The *name* may be a + ``dns.name.Name object``, or it may be a string. In either case, + if the name is relative it is treated as relative to the origin of + the zone. + """ + + node_factory: Callable[[], dns.node.Node] = dns.node.Node + map_factory: Callable[[], MutableMapping[dns.name.Name, dns.node.Node]] = dict + # We only require the version types as "Version" to allow for flexibility, as + # only the version protocol matters + writable_version_factory: Callable[["Zone", bool], "Version"] | None = None + immutable_version_factory: Callable[["Version"], "Version"] | None = None + + __slots__ = ["rdclass", "origin", "nodes", "relativize"] + + def __init__( + self, + origin: dns.name.Name | str | None, + rdclass: dns.rdataclass.RdataClass = dns.rdataclass.IN, + relativize: bool = True, + ): + """Initialize a zone object. + + *origin* is the origin of the zone. It may be a ``dns.name.Name``, + a ``str``, or ``None``. If ``None``, then the zone's origin will + be set by the first ``$ORIGIN`` line in a zone file. + + *rdclass*, an ``int``, the zone's rdata class; the default is class IN. + + *relativize*, a ``bool``, determine's whether domain names are + relativized to the zone's origin. The default is ``True``. + """ + + if origin is not None: + if isinstance(origin, str): + origin = dns.name.from_text(origin) + elif not isinstance(origin, dns.name.Name): + raise ValueError("origin parameter must be convertible to a DNS name") + if not origin.is_absolute(): + raise ValueError("origin parameter must be an absolute name") + self.origin = origin + self.rdclass = rdclass + self.nodes: MutableMapping[dns.name.Name, dns.node.Node] = self.map_factory() + self.relativize = relativize + + def __eq__(self, other): + """Two zones are equal if they have the same origin, class, and + nodes. + + Returns a ``bool``. + """ + + if not isinstance(other, Zone): + return False + if ( + self.rdclass != other.rdclass + or self.origin != other.origin + or self.nodes != other.nodes + ): + return False + return True + + def __ne__(self, other): + """Are two zones not equal? + + Returns a ``bool``. + """ + + return not self.__eq__(other) + + def _validate_name(self, name: dns.name.Name | str) -> dns.name.Name: + # Note that any changes in this method should have corresponding changes + # made in the Version _validate_name() method. + if isinstance(name, str): + name = dns.name.from_text(name, None) + elif not isinstance(name, dns.name.Name): + raise KeyError("name parameter must be convertible to a DNS name") + return _validate_name(name, self.origin, self.relativize) + + def __getitem__(self, key): + key = self._validate_name(key) + return self.nodes[key] + + def __setitem__(self, key, value): + key = self._validate_name(key) + self.nodes[key] = value + + def __delitem__(self, key): + key = self._validate_name(key) + del self.nodes[key] + + def __iter__(self): + return self.nodes.__iter__() + + def keys(self): + return self.nodes.keys() + + def values(self): + return self.nodes.values() + + def items(self): + return self.nodes.items() + + def get(self, key): + key = self._validate_name(key) + return self.nodes.get(key) + + def __contains__(self, key): + key = self._validate_name(key) + return key in self.nodes + + def find_node( + self, name: dns.name.Name | str, create: bool = False + ) -> dns.node.Node: + """Find a node in the zone, possibly creating it. + + *name*: the name of the node to find. + The value may be a ``dns.name.Name`` or a ``str``. If absolute, the + name must be a subdomain of the zone's origin. If ``zone.relativize`` + is ``True``, then the name will be relativized. + + *create*, a ``bool``. If true, the node will be created if it does + not exist. + + Raises ``KeyError`` if the name is not known and create was + not specified, or if the name was not a subdomain of the origin. + + Returns a ``dns.node.Node``. + """ + + name = self._validate_name(name) + node = self.nodes.get(name) + if node is None: + if not create: + raise KeyError + node = self.node_factory() + self.nodes[name] = node + return node + + def get_node( + self, name: dns.name.Name | str, create: bool = False + ) -> dns.node.Node | None: + """Get a node in the zone, possibly creating it. + + This method is like ``find_node()``, except it returns None instead + of raising an exception if the node does not exist and creation + has not been requested. + + *name*: the name of the node to find. + The value may be a ``dns.name.Name`` or a ``str``. If absolute, the + name must be a subdomain of the zone's origin. If ``zone.relativize`` + is ``True``, then the name will be relativized. + + *create*, a ``bool``. If true, the node will be created if it does + not exist. + + Returns a ``dns.node.Node`` or ``None``. + """ + + try: + node = self.find_node(name, create) + except KeyError: + node = None + return node + + def delete_node(self, name: dns.name.Name | str) -> None: + """Delete the specified node if it exists. + + *name*: the name of the node to find. + The value may be a ``dns.name.Name`` or a ``str``. If absolute, the + name must be a subdomain of the zone's origin. If ``zone.relativize`` + is ``True``, then the name will be relativized. + + It is not an error if the node does not exist. + """ + + name = self._validate_name(name) + if name in self.nodes: + del self.nodes[name] + + def find_rdataset( + self, + name: dns.name.Name | str, + rdtype: dns.rdatatype.RdataType | str, + covers: dns.rdatatype.RdataType | str = dns.rdatatype.NONE, + create: bool = False, + ) -> dns.rdataset.Rdataset: + """Look for an rdataset with the specified name and type in the zone, + and return an rdataset encapsulating it. + + The rdataset returned is not a copy; changes to it will change + the zone. + + KeyError is raised if the name or type are not found. + + *name*: the name of the node to find. + The value may be a ``dns.name.Name`` or a ``str``. If absolute, the + name must be a subdomain of the zone's origin. If ``zone.relativize`` + is ``True``, then the name will be relativized. + + *rdtype*, a ``dns.rdatatype.RdataType`` or ``str``, the rdata type desired. + + *covers*, a ``dns.rdatatype.RdataType`` or ``str`` the covered type. + Usually this value is ``dns.rdatatype.NONE``, but if the + rdtype is ``dns.rdatatype.SIG`` or ``dns.rdatatype.RRSIG``, + then the covers value will be the rdata type the SIG/RRSIG + covers. The library treats the SIG and RRSIG types as if they + were a family of types, e.g. RRSIG(A), RRSIG(NS), RRSIG(SOA). + This makes RRSIGs much easier to work with than if RRSIGs + covering different rdata types were aggregated into a single + RRSIG rdataset. + + *create*, a ``bool``. If true, the node will be created if it does + not exist. + + Raises ``KeyError`` if the name is not known and create was + not specified, or if the name was not a subdomain of the origin. + + Returns a ``dns.rdataset.Rdataset``. + """ + + name = self._validate_name(name) + rdtype = dns.rdatatype.RdataType.make(rdtype) + covers = dns.rdatatype.RdataType.make(covers) + node = self.find_node(name, create) + return node.find_rdataset(self.rdclass, rdtype, covers, create) + + def get_rdataset( + self, + name: dns.name.Name | str, + rdtype: dns.rdatatype.RdataType | str, + covers: dns.rdatatype.RdataType | str = dns.rdatatype.NONE, + create: bool = False, + ) -> dns.rdataset.Rdataset | None: + """Look for an rdataset with the specified name and type in the zone. + + This method is like ``find_rdataset()``, except it returns None instead + of raising an exception if the rdataset does not exist and creation + has not been requested. + + The rdataset returned is not a copy; changes to it will change + the zone. + + *name*: the name of the node to find. + The value may be a ``dns.name.Name`` or a ``str``. If absolute, the + name must be a subdomain of the zone's origin. If ``zone.relativize`` + is ``True``, then the name will be relativized. + + *rdtype*, a ``dns.rdatatype.RdataType`` or ``str``, the rdata type desired. + + *covers*, a ``dns.rdatatype.RdataType`` or ``str``, the covered type. + Usually this value is ``dns.rdatatype.NONE``, but if the + rdtype is ``dns.rdatatype.SIG`` or ``dns.rdatatype.RRSIG``, + then the covers value will be the rdata type the SIG/RRSIG + covers. The library treats the SIG and RRSIG types as if they + were a family of types, e.g. RRSIG(A), RRSIG(NS), RRSIG(SOA). + This makes RRSIGs much easier to work with than if RRSIGs + covering different rdata types were aggregated into a single + RRSIG rdataset. + + *create*, a ``bool``. If true, the node will be created if it does + not exist. + + Raises ``KeyError`` if the name is not known and create was + not specified, or if the name was not a subdomain of the origin. + + Returns a ``dns.rdataset.Rdataset`` or ``None``. + """ + + try: + rdataset = self.find_rdataset(name, rdtype, covers, create) + except KeyError: + rdataset = None + return rdataset + + def delete_rdataset( + self, + name: dns.name.Name | str, + rdtype: dns.rdatatype.RdataType | str, + covers: dns.rdatatype.RdataType | str = dns.rdatatype.NONE, + ) -> None: + """Delete the rdataset matching *rdtype* and *covers*, if it + exists at the node specified by *name*. + + It is not an error if the node does not exist, or if there is no matching + rdataset at the node. + + If the node has no rdatasets after the deletion, it will itself be deleted. + + *name*: the name of the node to find. The value may be a ``dns.name.Name`` or a + ``str``. If absolute, the name must be a subdomain of the zone's origin. If + ``zone.relativize`` is ``True``, then the name will be relativized. + + *rdtype*, a ``dns.rdatatype.RdataType`` or ``str``, the rdata type desired. + + *covers*, a ``dns.rdatatype.RdataType`` or ``str`` or ``None``, the covered + type. Usually this value is ``dns.rdatatype.NONE``, but if the rdtype is + ``dns.rdatatype.SIG`` or ``dns.rdatatype.RRSIG``, then the covers value will be + the rdata type the SIG/RRSIG covers. The library treats the SIG and RRSIG types + as if they were a family of types, e.g. RRSIG(A), RRSIG(NS), RRSIG(SOA). This + makes RRSIGs much easier to work with than if RRSIGs covering different rdata + types were aggregated into a single RRSIG rdataset. + """ + + name = self._validate_name(name) + rdtype = dns.rdatatype.RdataType.make(rdtype) + covers = dns.rdatatype.RdataType.make(covers) + node = self.get_node(name) + if node is not None: + node.delete_rdataset(self.rdclass, rdtype, covers) + if len(node) == 0: + self.delete_node(name) + + def replace_rdataset( + self, name: dns.name.Name | str, replacement: dns.rdataset.Rdataset + ) -> None: + """Replace an rdataset at name. + + It is not an error if there is no rdataset matching I{replacement}. + + Ownership of the *replacement* object is transferred to the zone; + in other words, this method does not store a copy of *replacement* + at the node, it stores *replacement* itself. + + If the node does not exist, it is created. + + *name*: the name of the node to find. + The value may be a ``dns.name.Name`` or a ``str``. If absolute, the + name must be a subdomain of the zone's origin. If ``zone.relativize`` + is ``True``, then the name will be relativized. + + *replacement*, a ``dns.rdataset.Rdataset``, the replacement rdataset. + """ + + if replacement.rdclass != self.rdclass: + raise ValueError("replacement.rdclass != zone.rdclass") + node = self.find_node(name, True) + node.replace_rdataset(replacement) + + def find_rrset( + self, + name: dns.name.Name | str, + rdtype: dns.rdatatype.RdataType | str, + covers: dns.rdatatype.RdataType | str = dns.rdatatype.NONE, + ) -> dns.rrset.RRset: + """Look for an rdataset with the specified name and type in the zone, + and return an RRset encapsulating it. + + This method is less efficient than the similar + ``find_rdataset()`` because it creates an RRset instead of + returning the matching rdataset. It may be more convenient + for some uses since it returns an object which binds the owner + name to the rdataset. + + This method may not be used to create new nodes or rdatasets; + use ``find_rdataset`` instead. + + *name*: the name of the node to find. + The value may be a ``dns.name.Name`` or a ``str``. If absolute, the + name must be a subdomain of the zone's origin. If ``zone.relativize`` + is ``True``, then the name will be relativized. + + *rdtype*, a ``dns.rdatatype.RdataType`` or ``str``, the rdata type desired. + + *covers*, a ``dns.rdatatype.RdataType`` or ``str``, the covered type. + Usually this value is ``dns.rdatatype.NONE``, but if the + rdtype is ``dns.rdatatype.SIG`` or ``dns.rdatatype.RRSIG``, + then the covers value will be the rdata type the SIG/RRSIG + covers. The library treats the SIG and RRSIG types as if they + were a family of types, e.g. RRSIG(A), RRSIG(NS), RRSIG(SOA). + This makes RRSIGs much easier to work with than if RRSIGs + covering different rdata types were aggregated into a single + RRSIG rdataset. + + *create*, a ``bool``. If true, the node will be created if it does + not exist. + + Raises ``KeyError`` if the name is not known and create was + not specified, or if the name was not a subdomain of the origin. + + Returns a ``dns.rrset.RRset`` or ``None``. + """ + + vname = self._validate_name(name) + rdtype = dns.rdatatype.RdataType.make(rdtype) + covers = dns.rdatatype.RdataType.make(covers) + rdataset = self.nodes[vname].find_rdataset(self.rdclass, rdtype, covers) + rrset = dns.rrset.RRset(vname, self.rdclass, rdtype, covers) + rrset.update(rdataset) + return rrset + + def get_rrset( + self, + name: dns.name.Name | str, + rdtype: dns.rdatatype.RdataType | str, + covers: dns.rdatatype.RdataType | str = dns.rdatatype.NONE, + ) -> dns.rrset.RRset | None: + """Look for an rdataset with the specified name and type in the zone, + and return an RRset encapsulating it. + + This method is less efficient than the similar ``get_rdataset()`` + because it creates an RRset instead of returning the matching + rdataset. It may be more convenient for some uses since it + returns an object which binds the owner name to the rdataset. + + This method may not be used to create new nodes or rdatasets; + use ``get_rdataset()`` instead. + + *name*: the name of the node to find. + The value may be a ``dns.name.Name`` or a ``str``. If absolute, the + name must be a subdomain of the zone's origin. If ``zone.relativize`` + is ``True``, then the name will be relativized. + + *rdtype*, a ``dns.rdataset.Rdataset`` or ``str``, the rdata type desired. + + *covers*, a ``dns.rdataset.Rdataset`` or ``str``, the covered type. + Usually this value is ``dns.rdatatype.NONE``, but if the + rdtype is ``dns.rdatatype.SIG`` or ``dns.rdatatype.RRSIG``, + then the covers value will be the rdata type the SIG/RRSIG + covers. The library treats the SIG and RRSIG types as if they + were a family of types, e.g. RRSIG(A), RRSIG(NS), RRSIG(SOA). + This makes RRSIGs much easier to work with than if RRSIGs + covering different rdata types were aggregated into a single + RRSIG rdataset. + + *create*, a ``bool``. If true, the node will be created if it does + not exist. + + Returns a ``dns.rrset.RRset`` or ``None``. + """ + + try: + rrset = self.find_rrset(name, rdtype, covers) + except KeyError: + rrset = None + return rrset + + def iterate_rdatasets( + self, + rdtype: dns.rdatatype.RdataType | str = dns.rdatatype.ANY, + covers: dns.rdatatype.RdataType | str = dns.rdatatype.NONE, + ) -> Iterator[Tuple[dns.name.Name, dns.rdataset.Rdataset]]: + """Return a generator which yields (name, rdataset) tuples for + all rdatasets in the zone which have the specified *rdtype* + and *covers*. If *rdtype* is ``dns.rdatatype.ANY``, the default, + then all rdatasets will be matched. + + *rdtype*, a ``dns.rdataset.Rdataset`` or ``str``, the rdata type desired. + + *covers*, a ``dns.rdataset.Rdataset`` or ``str``, the covered type. + Usually this value is ``dns.rdatatype.NONE``, but if the + rdtype is ``dns.rdatatype.SIG`` or ``dns.rdatatype.RRSIG``, + then the covers value will be the rdata type the SIG/RRSIG + covers. The library treats the SIG and RRSIG types as if they + were a family of types, e.g. RRSIG(A), RRSIG(NS), RRSIG(SOA). + This makes RRSIGs much easier to work with than if RRSIGs + covering different rdata types were aggregated into a single + RRSIG rdataset. + """ + + rdtype = dns.rdatatype.RdataType.make(rdtype) + covers = dns.rdatatype.RdataType.make(covers) + for name, node in self.items(): + for rds in node: + if rdtype == dns.rdatatype.ANY or ( + rds.rdtype == rdtype and rds.covers == covers + ): + yield (name, rds) + + def iterate_rdatas( + self, + rdtype: dns.rdatatype.RdataType | str = dns.rdatatype.ANY, + covers: dns.rdatatype.RdataType | str = dns.rdatatype.NONE, + ) -> Iterator[Tuple[dns.name.Name, int, dns.rdata.Rdata]]: + """Return a generator which yields (name, ttl, rdata) tuples for + all rdatas in the zone which have the specified *rdtype* + and *covers*. If *rdtype* is ``dns.rdatatype.ANY``, the default, + then all rdatas will be matched. + + *rdtype*, a ``dns.rdataset.Rdataset`` or ``str``, the rdata type desired. + + *covers*, a ``dns.rdataset.Rdataset`` or ``str``, the covered type. + Usually this value is ``dns.rdatatype.NONE``, but if the + rdtype is ``dns.rdatatype.SIG`` or ``dns.rdatatype.RRSIG``, + then the covers value will be the rdata type the SIG/RRSIG + covers. The library treats the SIG and RRSIG types as if they + were a family of types, e.g. RRSIG(A), RRSIG(NS), RRSIG(SOA). + This makes RRSIGs much easier to work with than if RRSIGs + covering different rdata types were aggregated into a single + RRSIG rdataset. + """ + + rdtype = dns.rdatatype.RdataType.make(rdtype) + covers = dns.rdatatype.RdataType.make(covers) + for name, node in self.items(): + for rds in node: + if rdtype == dns.rdatatype.ANY or ( + rds.rdtype == rdtype and rds.covers == covers + ): + for rdata in rds: + yield (name, rds.ttl, rdata) + + def to_file( + self, + f: Any, + sorted: bool = True, + relativize: bool = True, + nl: str | None = None, + want_comments: bool = False, + want_origin: bool = False, + ) -> None: + """Write a zone to a file. + + *f*, a file or `str`. If *f* is a string, it is treated + as the name of a file to open. + + *sorted*, a ``bool``. If True, the default, then the file + will be written with the names sorted in DNSSEC order from + least to greatest. Otherwise the names will be written in + whatever order they happen to have in the zone's dictionary. + + *relativize*, a ``bool``. If True, the default, then domain + names in the output will be relativized to the zone's origin + if possible. + + *nl*, a ``str`` or None. The end of line string. If not + ``None``, the output will use the platform's native + end-of-line marker (i.e. LF on POSIX, CRLF on Windows). + + *want_comments*, a ``bool``. If ``True``, emit end-of-line comments + as part of writing the file. If ``False``, the default, do not + emit them. + + *want_origin*, a ``bool``. If ``True``, emit a $ORIGIN line at + the start of the file. If ``False``, the default, do not emit + one. + """ + + if isinstance(f, str): + cm: contextlib.AbstractContextManager = open(f, "wb") + else: + cm = contextlib.nullcontext(f) + with cm as f: + # must be in this way, f.encoding may contain None, or even + # attribute may not be there + file_enc = getattr(f, "encoding", None) + if file_enc is None: + file_enc = "utf-8" + + if nl is None: + # binary mode, '\n' is not enough + nl_b = os.linesep.encode(file_enc) + nl = "\n" + elif isinstance(nl, str): + nl_b = nl.encode(file_enc) + else: + nl_b = nl + nl = nl.decode() + + if want_origin: + assert self.origin is not None + l = "$ORIGIN " + self.origin.to_text() + l_b = l.encode(file_enc) + try: + f.write(l_b) + f.write(nl_b) + except TypeError: # textual mode + f.write(l) + f.write(nl) + + if sorted: + names = list(self.keys()) + names.sort() + else: + names = self.keys() + for n in names: + l = self[n].to_text( + n, + origin=self.origin, # pyright: ignore + relativize=relativize, # pyright: ignore + want_comments=want_comments, # pyright: ignore + ) + l_b = l.encode(file_enc) + + try: + f.write(l_b) + f.write(nl_b) + except TypeError: # textual mode + f.write(l) + f.write(nl) + + def to_text( + self, + sorted: bool = True, + relativize: bool = True, + nl: str | None = None, + want_comments: bool = False, + want_origin: bool = False, + ) -> str: + """Return a zone's text as though it were written to a file. + + *sorted*, a ``bool``. If True, the default, then the file + will be written with the names sorted in DNSSEC order from + least to greatest. Otherwise the names will be written in + whatever order they happen to have in the zone's dictionary. + + *relativize*, a ``bool``. If True, the default, then domain + names in the output will be relativized to the zone's origin + if possible. + + *nl*, a ``str`` or None. The end of line string. If not + ``None``, the output will use the platform's native + end-of-line marker (i.e. LF on POSIX, CRLF on Windows). + + *want_comments*, a ``bool``. If ``True``, emit end-of-line comments + as part of writing the file. If ``False``, the default, do not + emit them. + + *want_origin*, a ``bool``. If ``True``, emit a $ORIGIN line at + the start of the output. If ``False``, the default, do not emit + one. + + Returns a ``str``. + """ + temp_buffer = io.StringIO() + self.to_file(temp_buffer, sorted, relativize, nl, want_comments, want_origin) + return_value = temp_buffer.getvalue() + temp_buffer.close() + return return_value + + def check_origin(self) -> None: + """Do some simple checking of the zone's origin. + + Raises ``dns.zone.NoSOA`` if there is no SOA RRset. + + Raises ``dns.zone.NoNS`` if there is no NS RRset. + + Raises ``KeyError`` if there is no origin node. + """ + if self.relativize: + name = dns.name.empty + else: + assert self.origin is not None + name = self.origin + if self.get_rdataset(name, dns.rdatatype.SOA) is None: + raise NoSOA + if self.get_rdataset(name, dns.rdatatype.NS) is None: + raise NoNS + + def get_soa( + self, txn: dns.transaction.Transaction | None = None + ) -> dns.rdtypes.ANY.SOA.SOA: + """Get the zone SOA rdata. + + Raises ``dns.zone.NoSOA`` if there is no SOA RRset. + + Returns a ``dns.rdtypes.ANY.SOA.SOA`` Rdata. + """ + if self.relativize: + origin_name = dns.name.empty + else: + if self.origin is None: + # get_soa() has been called very early, and there must not be + # an SOA if there is no origin. + raise NoSOA + origin_name = self.origin + soa_rds: dns.rdataset.Rdataset | None + if txn: + soa_rds = txn.get(origin_name, dns.rdatatype.SOA) + else: + soa_rds = self.get_rdataset(origin_name, dns.rdatatype.SOA) + if soa_rds is None: + raise NoSOA + else: + soa = cast(dns.rdtypes.ANY.SOA.SOA, soa_rds[0]) + return soa + + def _compute_digest( + self, + hash_algorithm: DigestHashAlgorithm, + scheme: DigestScheme = DigestScheme.SIMPLE, + ) -> bytes: + hashinfo = _digest_hashers.get(hash_algorithm) + if not hashinfo: + raise UnsupportedDigestHashAlgorithm + if scheme != DigestScheme.SIMPLE: + raise UnsupportedDigestScheme + + if self.relativize: + origin_name = dns.name.empty + else: + assert self.origin is not None + origin_name = self.origin + hasher = hashinfo() + for name, node in sorted(self.items()): + rrnamebuf = name.to_digestable(self.origin) + for rdataset in sorted(node, key=lambda rds: (rds.rdtype, rds.covers)): + if name == origin_name and dns.rdatatype.ZONEMD in ( + rdataset.rdtype, + rdataset.covers, + ): + continue + rrfixed = struct.pack( + "!HHI", rdataset.rdtype, rdataset.rdclass, rdataset.ttl + ) + rdatas = [rdata.to_digestable(self.origin) for rdata in rdataset] + for rdata in sorted(rdatas): + rrlen = struct.pack("!H", len(rdata)) + hasher.update(rrnamebuf + rrfixed + rrlen + rdata) + return hasher.digest() + + def compute_digest( + self, + hash_algorithm: DigestHashAlgorithm, + scheme: DigestScheme = DigestScheme.SIMPLE, + ) -> dns.rdtypes.ANY.ZONEMD.ZONEMD: + serial = self.get_soa().serial + digest = self._compute_digest(hash_algorithm, scheme) + return dns.rdtypes.ANY.ZONEMD.ZONEMD( + self.rdclass, dns.rdatatype.ZONEMD, serial, scheme, hash_algorithm, digest + ) + + def verify_digest( + self, zonemd: dns.rdtypes.ANY.ZONEMD.ZONEMD | None = None + ) -> None: + digests: dns.rdataset.Rdataset | List[dns.rdtypes.ANY.ZONEMD.ZONEMD] + if zonemd: + digests = [zonemd] + else: + assert self.origin is not None + rds = self.get_rdataset(self.origin, dns.rdatatype.ZONEMD) + if rds is None: + raise NoDigest + digests = rds + for digest in digests: + try: + computed = self._compute_digest(digest.hash_algorithm, digest.scheme) + if computed == digest.digest: + return + except Exception: + pass + raise DigestVerificationFailure + + # TransactionManager methods + + def reader(self) -> "Transaction": + return Transaction(self, False, Version(self, 1, self.nodes, self.origin)) + + def writer(self, replacement: bool = False) -> "Transaction": + txn = Transaction(self, replacement) + txn._setup_version() + return txn + + def origin_information( + self, + ) -> Tuple[dns.name.Name | None, bool, dns.name.Name | None]: + effective: dns.name.Name | None + if self.relativize: + effective = dns.name.empty + else: + effective = self.origin + return (self.origin, self.relativize, effective) + + def get_class(self): + return self.rdclass + + # Transaction methods + + def _end_read(self, txn): + pass + + def _end_write(self, txn): + pass + + def _commit_version(self, txn, version, origin): + self.nodes = version.nodes + if self.origin is None: + self.origin = origin + + def _get_next_version_id(self) -> int: + # Versions are ephemeral and all have id 1 + return 1 + + +# These classes used to be in dns.versioned, but have moved here so we can use +# the copy-on-write transaction mechanism for both kinds of zones. In a +# regular zone, the version only exists during the transaction, and the nodes +# are regular dns.node.Nodes. + +# A node with a version id. + + +class VersionedNode(dns.node.Node): # lgtm[py/missing-equals] + __slots__ = ["id"] + + def __init__(self): + super().__init__() + # A proper id will get set by the Version + self.id = 0 + + +@dns.immutable.immutable +class ImmutableVersionedNode(VersionedNode): + def __init__(self, node): + super().__init__() + self.id = node.id + self.rdatasets = tuple( + [dns.rdataset.ImmutableRdataset(rds) for rds in node.rdatasets] + ) + + def find_rdataset( + self, + rdclass: dns.rdataclass.RdataClass, + rdtype: dns.rdatatype.RdataType, + covers: dns.rdatatype.RdataType = dns.rdatatype.NONE, + create: bool = False, + ) -> dns.rdataset.Rdataset: + if create: + raise TypeError("immutable") + return super().find_rdataset(rdclass, rdtype, covers, False) + + def get_rdataset( + self, + rdclass: dns.rdataclass.RdataClass, + rdtype: dns.rdatatype.RdataType, + covers: dns.rdatatype.RdataType = dns.rdatatype.NONE, + create: bool = False, + ) -> dns.rdataset.Rdataset | None: + if create: + raise TypeError("immutable") + return super().get_rdataset(rdclass, rdtype, covers, False) + + def delete_rdataset( + self, + rdclass: dns.rdataclass.RdataClass, + rdtype: dns.rdatatype.RdataType, + covers: dns.rdatatype.RdataType = dns.rdatatype.NONE, + ) -> None: + raise TypeError("immutable") + + def replace_rdataset(self, replacement: dns.rdataset.Rdataset) -> None: + raise TypeError("immutable") + + def is_immutable(self) -> bool: + return True + + +class Version: + def __init__( + self, + zone: Zone, + id: int, + nodes: MutableMapping[dns.name.Name, dns.node.Node] | None = None, + origin: dns.name.Name | None = None, + ): + self.zone = zone + self.id = id + if nodes is not None: + self.nodes = nodes + else: + self.nodes = zone.map_factory() + self.origin = origin + + def _validate_name(self, name: dns.name.Name) -> dns.name.Name: + return _validate_name(name, self.origin, self.zone.relativize) + + def get_node(self, name: dns.name.Name) -> dns.node.Node | None: + name = self._validate_name(name) + return self.nodes.get(name) + + def get_rdataset( + self, + name: dns.name.Name, + rdtype: dns.rdatatype.RdataType, + covers: dns.rdatatype.RdataType, + ) -> dns.rdataset.Rdataset | None: + node = self.get_node(name) + if node is None: + return None + return node.get_rdataset(self.zone.rdclass, rdtype, covers) + + def keys(self): + return self.nodes.keys() + + def items(self): + return self.nodes.items() + + +class WritableVersion(Version): + def __init__(self, zone: Zone, replacement: bool = False): + # The zone._versions_lock must be held by our caller in a versioned + # zone. + id = zone._get_next_version_id() + super().__init__(zone, id) + if not replacement: + # We copy the map, because that gives us a simple and thread-safe + # way of doing versions, and we have a garbage collector to help + # us. We only make new node objects if we actually change the + # node. + self.nodes.update(zone.nodes) + # We have to copy the zone origin as it may be None in the first + # version, and we don't want to mutate the zone until we commit. + self.origin = zone.origin + self.changed: Set[dns.name.Name] = set() + + def _maybe_cow_with_name( + self, name: dns.name.Name + ) -> Tuple[dns.node.Node, dns.name.Name]: + name = self._validate_name(name) + node = self.nodes.get(name) + if node is None or name not in self.changed: + new_node = self.zone.node_factory() + if hasattr(new_node, "id"): + # We keep doing this for backwards compatibility, as earlier + # code used new_node.id != self.id for the "do we need to CoW?" + # test. Now we use the changed set as this works with both + # regular zones and versioned zones. + # + # We ignore the mypy error as this is safe but it doesn't see it. + new_node.id = self.id # type: ignore + if node is not None: + # moo! copy on write! + new_node.rdatasets.extend(node.rdatasets) + self.nodes[name] = new_node + self.changed.add(name) + return (new_node, name) + else: + return (node, name) + + def _maybe_cow(self, name: dns.name.Name) -> dns.node.Node: + return self._maybe_cow_with_name(name)[0] + + def delete_node(self, name: dns.name.Name) -> None: + name = self._validate_name(name) + if name in self.nodes: + del self.nodes[name] + self.changed.add(name) + + def put_rdataset( + self, name: dns.name.Name, rdataset: dns.rdataset.Rdataset + ) -> None: + node = self._maybe_cow(name) + node.replace_rdataset(rdataset) + + def delete_rdataset( + self, + name: dns.name.Name, + rdtype: dns.rdatatype.RdataType, + covers: dns.rdatatype.RdataType, + ) -> None: + node = self._maybe_cow(name) + node.delete_rdataset(self.zone.rdclass, rdtype, covers) + if len(node) == 0: + del self.nodes[name] + + +@dns.immutable.immutable +class ImmutableVersion(Version): + def __init__(self, version: Version): + if not isinstance(version, WritableVersion): + raise ValueError( + "a dns.zone.ImmutableVersion requires a dns.zone.WritableVersion" + ) + # We tell super() that it's a replacement as we don't want it + # to copy the nodes, as we're about to do that with an + # immutable Dict. + super().__init__(version.zone, True) + # set the right id! + self.id = version.id + # keep the origin + self.origin = version.origin + # Make changed nodes immutable + for name in version.changed: + node = version.nodes.get(name) + # it might not exist if we deleted it in the version + if node: + version.nodes[name] = ImmutableVersionedNode(node) + # We're changing the type of the nodes dictionary here on purpose, so + # we ignore the mypy error. + self.nodes = dns.immutable.Dict( + version.nodes, True, self.zone.map_factory + ) # type: ignore + + +class Transaction(dns.transaction.Transaction): + def __init__(self, zone, replacement, version=None, make_immutable=False): + read_only = version is not None + super().__init__(zone, replacement, read_only) + self.version = version + self.make_immutable = make_immutable + + @property + def zone(self): + return self.manager + + def _setup_version(self): + assert self.version is None + factory = self.manager.writable_version_factory # pyright: ignore + if factory is None: + factory = WritableVersion + self.version = factory(self.zone, self.replacement) # pyright: ignore + + def _get_rdataset(self, name, rdtype, covers): + assert self.version is not None + return self.version.get_rdataset(name, rdtype, covers) + + def _put_rdataset(self, name, rdataset): + assert not self.read_only + assert self.version is not None + self.version.put_rdataset(name, rdataset) + + def _delete_name(self, name): + assert not self.read_only + assert self.version is not None + self.version.delete_node(name) + + def _delete_rdataset(self, name, rdtype, covers): + assert not self.read_only + assert self.version is not None + self.version.delete_rdataset(name, rdtype, covers) + + def _name_exists(self, name): + assert self.version is not None + return self.version.get_node(name) is not None + + def _changed(self): + if self.read_only: + return False + else: + assert self.version is not None + return len(self.version.changed) > 0 + + def _end_transaction(self, commit): + assert self.zone is not None + assert self.version is not None + if self.read_only: + self.zone._end_read(self) # pyright: ignore + elif commit and len(self.version.changed) > 0: + if self.make_immutable: + factory = self.manager.immutable_version_factory # pyright: ignore + if factory is None: + factory = ImmutableVersion + version = factory(self.version) + else: + version = self.version + self.zone._commit_version( # pyright: ignore + self, version, self.version.origin + ) + + else: + # rollback + self.zone._end_write(self) # pyright: ignore + + def _set_origin(self, origin): + assert self.version is not None + if self.version.origin is None: + self.version.origin = origin + + def _iterate_rdatasets(self): + assert self.version is not None + for name, node in self.version.items(): + for rdataset in node: + yield (name, rdataset) + + def _iterate_names(self): + assert self.version is not None + return self.version.keys() + + def _get_node(self, name): + assert self.version is not None + return self.version.get_node(name) + + def _origin_information(self): + assert self.version is not None + (absolute, relativize, effective) = self.manager.origin_information() + if absolute is None and self.version.origin is not None: + # No origin has been committed yet, but we've learned one as part of + # this txn. Use it. + absolute = self.version.origin + if relativize: + effective = dns.name.empty + else: + effective = absolute + return (absolute, relativize, effective) + + +def _from_text( + text: Any, + origin: dns.name.Name | str | None = None, + rdclass: dns.rdataclass.RdataClass = dns.rdataclass.IN, + relativize: bool = True, + zone_factory: Any = Zone, + filename: str | None = None, + allow_include: bool = False, + check_origin: bool = True, + idna_codec: dns.name.IDNACodec | None = None, + allow_directives: bool | Iterable[str] = True, +) -> Zone: + # See the comments for the public APIs from_text() and from_file() for + # details. + + # 'text' can also be a file, but we don't publish that fact + # since it's an implementation detail. The official file + # interface is from_file(). + + if filename is None: + filename = "" + zone = zone_factory(origin, rdclass, relativize=relativize) + with zone.writer(True) as txn: + tok = dns.tokenizer.Tokenizer(text, filename, idna_codec=idna_codec) + reader = dns.zonefile.Reader( + tok, + rdclass, + txn, + allow_include=allow_include, + allow_directives=allow_directives, + ) + try: + reader.read() + except dns.zonefile.UnknownOrigin: + # for backwards compatibility + raise UnknownOrigin + # Now that we're done reading, do some basic checking of the zone. + if check_origin: + zone.check_origin() + return zone + + +def from_text( + text: str, + origin: dns.name.Name | str | None = None, + rdclass: dns.rdataclass.RdataClass = dns.rdataclass.IN, + relativize: bool = True, + zone_factory: Any = Zone, + filename: str | None = None, + allow_include: bool = False, + check_origin: bool = True, + idna_codec: dns.name.IDNACodec | None = None, + allow_directives: bool | Iterable[str] = True, +) -> Zone: + """Build a zone object from a zone file format string. + + *text*, a ``str``, the zone file format input. + + *origin*, a ``dns.name.Name``, a ``str``, or ``None``. The origin + of the zone; if not specified, the first ``$ORIGIN`` statement in the + zone file will determine the origin of the zone. + + *rdclass*, a ``dns.rdataclass.RdataClass``, the zone's rdata class; the default is + class IN. + + *relativize*, a ``bool``, determine's whether domain names are + relativized to the zone's origin. The default is ``True``. + + *zone_factory*, the zone factory to use or ``None``. If ``None``, then + ``dns.zone.Zone`` will be used. The value may be any class or callable + that returns a subclass of ``dns.zone.Zone``. + + *filename*, a ``str`` or ``None``, the filename to emit when + describing where an error occurred; the default is ``''``. + + *allow_include*, a ``bool``. If ``True``, the default, then ``$INCLUDE`` + directives are permitted. If ``False``, then encoutering a ``$INCLUDE`` + will raise a ``SyntaxError`` exception. + + *check_origin*, a ``bool``. If ``True``, the default, then sanity + checks of the origin node will be made by calling the zone's + ``check_origin()`` method. + + *idna_codec*, a ``dns.name.IDNACodec``, specifies the IDNA + encoder/decoder. If ``None``, the default IDNA 2003 encoder/decoder + is used. + + *allow_directives*, a ``bool`` or an iterable of `str`. If ``True``, the default, + then directives are permitted, and the *allow_include* parameter controls whether + ``$INCLUDE`` is permitted. If ``False`` or an empty iterable, then no directive + processing is done and any directive-like text will be treated as a regular owner + name. If a non-empty iterable, then only the listed directives (including the + ``$``) are allowed. + + Raises ``dns.zone.NoSOA`` if there is no SOA RRset. + + Raises ``dns.zone.NoNS`` if there is no NS RRset. + + Raises ``KeyError`` if there is no origin node. + + Returns a subclass of ``dns.zone.Zone``. + """ + return _from_text( + text, + origin, + rdclass, + relativize, + zone_factory, + filename, + allow_include, + check_origin, + idna_codec, + allow_directives, + ) + + +def from_file( + f: Any, + origin: dns.name.Name | str | None = None, + rdclass: dns.rdataclass.RdataClass = dns.rdataclass.IN, + relativize: bool = True, + zone_factory: Any = Zone, + filename: str | None = None, + allow_include: bool = True, + check_origin: bool = True, + idna_codec: dns.name.IDNACodec | None = None, + allow_directives: bool | Iterable[str] = True, +) -> Zone: + """Read a zone file and build a zone object. + + *f*, a file or ``str``. If *f* is a string, it is treated + as the name of a file to open. + + *origin*, a ``dns.name.Name``, a ``str``, or ``None``. The origin + of the zone; if not specified, the first ``$ORIGIN`` statement in the + zone file will determine the origin of the zone. + + *rdclass*, an ``int``, the zone's rdata class; the default is class IN. + + *relativize*, a ``bool``, determine's whether domain names are + relativized to the zone's origin. The default is ``True``. + + *zone_factory*, the zone factory to use or ``None``. If ``None``, then + ``dns.zone.Zone`` will be used. The value may be any class or callable + that returns a subclass of ``dns.zone.Zone``. + + *filename*, a ``str`` or ``None``, the filename to emit when + describing where an error occurred; the default is ``''``. + + *allow_include*, a ``bool``. If ``True``, the default, then ``$INCLUDE`` + directives are permitted. If ``False``, then encoutering a ``$INCLUDE`` + will raise a ``SyntaxError`` exception. + + *check_origin*, a ``bool``. If ``True``, the default, then sanity + checks of the origin node will be made by calling the zone's + ``check_origin()`` method. + + *idna_codec*, a ``dns.name.IDNACodec``, specifies the IDNA + encoder/decoder. If ``None``, the default IDNA 2003 encoder/decoder + is used. + + *allow_directives*, a ``bool`` or an iterable of `str`. If ``True``, the default, + then directives are permitted, and the *allow_include* parameter controls whether + ``$INCLUDE`` is permitted. If ``False`` or an empty iterable, then no directive + processing is done and any directive-like text will be treated as a regular owner + name. If a non-empty iterable, then only the listed directives (including the + ``$``) are allowed. + + Raises ``dns.zone.NoSOA`` if there is no SOA RRset. + + Raises ``dns.zone.NoNS`` if there is no NS RRset. + + Raises ``KeyError`` if there is no origin node. + + Returns a subclass of ``dns.zone.Zone``. + """ + + if isinstance(f, str): + if filename is None: + filename = f + cm: contextlib.AbstractContextManager = open(f, encoding="utf-8") + else: + cm = contextlib.nullcontext(f) + with cm as f: + return _from_text( + f, + origin, + rdclass, + relativize, + zone_factory, + filename, + allow_include, + check_origin, + idna_codec, + allow_directives, + ) + assert False # make mypy happy lgtm[py/unreachable-statement] + + +def from_xfr( + xfr: Any, + zone_factory: Any = Zone, + relativize: bool = True, + check_origin: bool = True, +) -> Zone: + """Convert the output of a zone transfer generator into a zone object. + + *xfr*, a generator of ``dns.message.Message`` objects, typically + ``dns.query.xfr()``. + + *relativize*, a ``bool``, determine's whether domain names are + relativized to the zone's origin. The default is ``True``. + It is essential that the relativize setting matches the one specified + to the generator. + + *check_origin*, a ``bool``. If ``True``, the default, then sanity + checks of the origin node will be made by calling the zone's + ``check_origin()`` method. + + Raises ``dns.zone.NoSOA`` if there is no SOA RRset. + + Raises ``dns.zone.NoNS`` if there is no NS RRset. + + Raises ``KeyError`` if there is no origin node. + + Raises ``ValueError`` if no messages are yielded by the generator. + + Returns a subclass of ``dns.zone.Zone``. + """ + + z = None + for r in xfr: + if z is None: + if relativize: + origin = r.origin + else: + origin = r.answer[0].name + rdclass = r.answer[0].rdclass + z = zone_factory(origin, rdclass, relativize=relativize) + for rrset in r.answer: + znode = z.nodes.get(rrset.name) + if not znode: + znode = z.node_factory() + z.nodes[rrset.name] = znode + zrds = znode.find_rdataset(rrset.rdclass, rrset.rdtype, rrset.covers, True) + zrds.update_ttl(rrset.ttl) + for rd in rrset: + zrds.add(rd) + if z is None: + raise ValueError("empty transfer") + if check_origin: + z.check_origin() + return z diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/zonefile.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/zonefile.py new file mode 100644 index 000000000..7a81454b6 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/zonefile.py @@ -0,0 +1,756 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. +# +# Permission to use, copy, modify, and distribute this software and its +# documentation for any purpose with or without fee is hereby granted, +# provided that the above copyright notice and this permission notice +# appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +"""DNS Zones.""" + +import re +import sys +from typing import Any, Iterable, List, Set, Tuple, cast + +import dns.exception +import dns.grange +import dns.name +import dns.node +import dns.rdata +import dns.rdataclass +import dns.rdatatype +import dns.rdtypes.ANY.SOA +import dns.rrset +import dns.tokenizer +import dns.transaction +import dns.ttl + + +class UnknownOrigin(dns.exception.DNSException): + """Unknown origin""" + + +class CNAMEAndOtherData(dns.exception.DNSException): + """A node has a CNAME and other data""" + + +def _check_cname_and_other_data(txn, name, rdataset): + rdataset_kind = dns.node.NodeKind.classify_rdataset(rdataset) + node = txn.get_node(name) + if node is None: + # empty nodes are neutral. + return + node_kind = node.classify() + if ( + node_kind == dns.node.NodeKind.CNAME + and rdataset_kind == dns.node.NodeKind.REGULAR + ): + raise CNAMEAndOtherData("rdataset type is not compatible with a CNAME node") + elif ( + node_kind == dns.node.NodeKind.REGULAR + and rdataset_kind == dns.node.NodeKind.CNAME + ): + raise CNAMEAndOtherData( + "CNAME rdataset is not compatible with a regular data node" + ) + # Otherwise at least one of the node and the rdataset is neutral, so + # adding the rdataset is ok + + +SavedStateType = Tuple[ + dns.tokenizer.Tokenizer, + dns.name.Name | None, # current_origin + dns.name.Name | None, # last_name + Any | None, # current_file + int, # last_ttl + bool, # last_ttl_known + int, # default_ttl + bool, +] # default_ttl_known + + +def _upper_dollarize(s): + s = s.upper() + if not s.startswith("$"): + s = "$" + s + return s + + +class Reader: + """Read a DNS zone file into a transaction.""" + + def __init__( + self, + tok: dns.tokenizer.Tokenizer, + rdclass: dns.rdataclass.RdataClass, + txn: dns.transaction.Transaction, + allow_include: bool = False, + allow_directives: bool | Iterable[str] = True, + force_name: dns.name.Name | None = None, + force_ttl: int | None = None, + force_rdclass: dns.rdataclass.RdataClass | None = None, + force_rdtype: dns.rdatatype.RdataType | None = None, + default_ttl: int | None = None, + ): + self.tok = tok + (self.zone_origin, self.relativize, _) = txn.manager.origin_information() + self.current_origin = self.zone_origin + self.last_ttl = 0 + self.last_ttl_known = False + if force_ttl is not None: + default_ttl = force_ttl + if default_ttl is None: + self.default_ttl = 0 + self.default_ttl_known = False + else: + self.default_ttl = default_ttl + self.default_ttl_known = True + self.last_name = self.current_origin + self.zone_rdclass = rdclass + self.txn = txn + self.saved_state: List[SavedStateType] = [] + self.current_file: Any | None = None + self.allowed_directives: Set[str] + if allow_directives is True: + self.allowed_directives = {"$GENERATE", "$ORIGIN", "$TTL"} + if allow_include: + self.allowed_directives.add("$INCLUDE") + elif allow_directives is False: + # allow_include was ignored in earlier releases if allow_directives was + # False, so we continue that. + self.allowed_directives = set() + else: + # Note that if directives are explicitly specified, then allow_include + # is ignored. + self.allowed_directives = set(_upper_dollarize(d) for d in allow_directives) + self.force_name = force_name + self.force_ttl = force_ttl + self.force_rdclass = force_rdclass + self.force_rdtype = force_rdtype + self.txn.check_put_rdataset(_check_cname_and_other_data) + + def _eat_line(self): + while 1: + token = self.tok.get() + if token.is_eol_or_eof(): + break + + def _get_identifier(self): + token = self.tok.get() + if not token.is_identifier(): + raise dns.exception.SyntaxError + return token + + def _rr_line(self): + """Process one line from a DNS zone file.""" + token = None + # Name + if self.force_name is not None: + name = self.force_name + else: + if self.current_origin is None: + raise UnknownOrigin + token = self.tok.get(want_leading=True) + if not token.is_whitespace(): + self.last_name = self.tok.as_name(token, self.current_origin) + else: + token = self.tok.get() + if token.is_eol_or_eof(): + # treat leading WS followed by EOL/EOF as if they were EOL/EOF. + return + self.tok.unget(token) + name = self.last_name + if name is None: + raise dns.exception.SyntaxError("the last used name is undefined") + assert self.zone_origin is not None + if not name.is_subdomain(self.zone_origin): + self._eat_line() + return + if self.relativize: + name = name.relativize(self.zone_origin) + + # TTL + if self.force_ttl is not None: + ttl = self.force_ttl + self.last_ttl = ttl + self.last_ttl_known = True + else: + token = self._get_identifier() + ttl = None + try: + ttl = dns.ttl.from_text(token.value) + self.last_ttl = ttl + self.last_ttl_known = True + token = None + except dns.ttl.BadTTL: + self.tok.unget(token) + + # Class + if self.force_rdclass is not None: + rdclass = self.force_rdclass + else: + token = self._get_identifier() + try: + rdclass = dns.rdataclass.from_text(token.value) + except dns.exception.SyntaxError: + raise + except Exception: + rdclass = self.zone_rdclass + self.tok.unget(token) + if rdclass != self.zone_rdclass: + raise dns.exception.SyntaxError("RR class is not zone's class") + + if ttl is None: + # support for syntax + token = self._get_identifier() + ttl = None + try: + ttl = dns.ttl.from_text(token.value) + self.last_ttl = ttl + self.last_ttl_known = True + token = None + except dns.ttl.BadTTL: + if self.default_ttl_known: + ttl = self.default_ttl + elif self.last_ttl_known: + ttl = self.last_ttl + self.tok.unget(token) + + # Type + if self.force_rdtype is not None: + rdtype = self.force_rdtype + else: + token = self._get_identifier() + try: + rdtype = dns.rdatatype.from_text(token.value) + except Exception: + raise dns.exception.SyntaxError(f"unknown rdatatype '{token.value}'") + + try: + rd = dns.rdata.from_text( + rdclass, + rdtype, + self.tok, + self.current_origin, + self.relativize, + self.zone_origin, + ) + except dns.exception.SyntaxError: + # Catch and reraise. + raise + except Exception: + # All exceptions that occur in the processing of rdata + # are treated as syntax errors. This is not strictly + # correct, but it is correct almost all of the time. + # We convert them to syntax errors so that we can emit + # helpful filename:line info. + (ty, va) = sys.exc_info()[:2] + raise dns.exception.SyntaxError(f"caught exception {str(ty)}: {str(va)}") + + if not self.default_ttl_known and rdtype == dns.rdatatype.SOA: + # The pre-RFC2308 and pre-BIND9 behavior inherits the zone default + # TTL from the SOA minttl if no $TTL statement is present before the + # SOA is parsed. + soa_rd = cast(dns.rdtypes.ANY.SOA.SOA, rd) + self.default_ttl = soa_rd.minimum + self.default_ttl_known = True + if ttl is None: + # if we didn't have a TTL on the SOA, set it! + ttl = soa_rd.minimum + + # TTL check. We had to wait until now to do this as the SOA RR's + # own TTL can be inferred from its minimum. + if ttl is None: + raise dns.exception.SyntaxError("Missing default TTL value") + + self.txn.add(name, ttl, rd) + + def _parse_modify(self, side: str) -> Tuple[str, str, int, int, str]: + # Here we catch everything in '{' '}' in a group so we can replace it + # with ''. + is_generate1 = re.compile(r"^.*\$({(\+|-?)(\d+),(\d+),(.)}).*$") + is_generate2 = re.compile(r"^.*\$({(\+|-?)(\d+)}).*$") + is_generate3 = re.compile(r"^.*\$({(\+|-?)(\d+),(\d+)}).*$") + # Sometimes there are modifiers in the hostname. These come after + # the dollar sign. They are in the form: ${offset[,width[,base]]}. + # Make names + mod = "" + sign = "+" + offset = "0" + width = "0" + base = "d" + g1 = is_generate1.match(side) + if g1: + mod, sign, offset, width, base = g1.groups() + if sign == "": + sign = "+" + else: + g2 = is_generate2.match(side) + if g2: + mod, sign, offset = g2.groups() + if sign == "": + sign = "+" + width = "0" + base = "d" + else: + g3 = is_generate3.match(side) + if g3: + mod, sign, offset, width = g3.groups() + if sign == "": + sign = "+" + base = "d" + + ioffset = int(offset) + iwidth = int(width) + + if sign not in ["+", "-"]: + raise dns.exception.SyntaxError(f"invalid offset sign {sign}") + if base not in ["d", "o", "x", "X", "n", "N"]: + raise dns.exception.SyntaxError(f"invalid type {base}") + + return mod, sign, ioffset, iwidth, base + + def _generate_line(self): + # range lhs [ttl] [class] type rhs [ comment ] + """Process one line containing the GENERATE statement from a DNS + zone file.""" + if self.current_origin is None: + raise UnknownOrigin + + token = self.tok.get() + # Range (required) + try: + start, stop, step = dns.grange.from_text(token.value) + token = self.tok.get() + if not token.is_identifier(): + raise dns.exception.SyntaxError + except Exception: + raise dns.exception.SyntaxError + + # lhs (required) + try: + lhs = token.value + token = self.tok.get() + if not token.is_identifier(): + raise dns.exception.SyntaxError + except Exception: + raise dns.exception.SyntaxError + + # TTL + try: + ttl = dns.ttl.from_text(token.value) + self.last_ttl = ttl + self.last_ttl_known = True + token = self.tok.get() + if not token.is_identifier(): + raise dns.exception.SyntaxError + except dns.ttl.BadTTL: + if not (self.last_ttl_known or self.default_ttl_known): + raise dns.exception.SyntaxError("Missing default TTL value") + if self.default_ttl_known: + ttl = self.default_ttl + elif self.last_ttl_known: + ttl = self.last_ttl + else: + # We don't go to the extra "look at the SOA" level of effort for + # $GENERATE, because the user really ought to have defined a TTL + # somehow! + raise dns.exception.SyntaxError("Missing default TTL value") + + # Class + try: + rdclass = dns.rdataclass.from_text(token.value) + token = self.tok.get() + if not token.is_identifier(): + raise dns.exception.SyntaxError + except dns.exception.SyntaxError: + raise dns.exception.SyntaxError + except Exception: + rdclass = self.zone_rdclass + if rdclass != self.zone_rdclass: + raise dns.exception.SyntaxError("RR class is not zone's class") + # Type + try: + rdtype = dns.rdatatype.from_text(token.value) + token = self.tok.get() + if not token.is_identifier(): + raise dns.exception.SyntaxError + except Exception: + raise dns.exception.SyntaxError(f"unknown rdatatype '{token.value}'") + + # rhs (required) + rhs = token.value + + def _calculate_index(counter: int, offset_sign: str, offset: int) -> int: + """Calculate the index from the counter and offset.""" + if offset_sign == "-": + offset *= -1 + return counter + offset + + def _format_index(index: int, base: str, width: int) -> str: + """Format the index with the given base, and zero-fill it + to the given width.""" + if base in ["d", "o", "x", "X"]: + return format(index, base).zfill(width) + + # base can only be n or N here + hexa = _format_index(index, "x", width) + nibbles = ".".join(hexa[::-1])[:width] + if base == "N": + nibbles = nibbles.upper() + return nibbles + + lmod, lsign, loffset, lwidth, lbase = self._parse_modify(lhs) + rmod, rsign, roffset, rwidth, rbase = self._parse_modify(rhs) + for i in range(start, stop + 1, step): + # +1 because bind is inclusive and python is exclusive + + lindex = _calculate_index(i, lsign, loffset) + rindex = _calculate_index(i, rsign, roffset) + + lzfindex = _format_index(lindex, lbase, lwidth) + rzfindex = _format_index(rindex, rbase, rwidth) + + name = lhs.replace(f"${lmod}", lzfindex) + rdata = rhs.replace(f"${rmod}", rzfindex) + + self.last_name = dns.name.from_text( + name, self.current_origin, self.tok.idna_codec + ) + name = self.last_name + assert self.zone_origin is not None + if not name.is_subdomain(self.zone_origin): + self._eat_line() + return + if self.relativize: + name = name.relativize(self.zone_origin) + + try: + rd = dns.rdata.from_text( + rdclass, + rdtype, + rdata, + self.current_origin, + self.relativize, + self.zone_origin, + ) + except dns.exception.SyntaxError: + # Catch and reraise. + raise + except Exception: + # All exceptions that occur in the processing of rdata + # are treated as syntax errors. This is not strictly + # correct, but it is correct almost all of the time. + # We convert them to syntax errors so that we can emit + # helpful filename:line info. + (ty, va) = sys.exc_info()[:2] + raise dns.exception.SyntaxError( + f"caught exception {str(ty)}: {str(va)}" + ) + + self.txn.add(name, ttl, rd) + + def read(self) -> None: + """Read a DNS zone file and build a zone object. + + @raises dns.zone.NoSOA: No SOA RR was found at the zone origin + @raises dns.zone.NoNS: No NS RRset was found at the zone origin + """ + + try: + while 1: + token = self.tok.get(True, True) + if token.is_eof(): + if self.current_file is not None: + self.current_file.close() + if len(self.saved_state) > 0: + ( + self.tok, + self.current_origin, + self.last_name, + self.current_file, + self.last_ttl, + self.last_ttl_known, + self.default_ttl, + self.default_ttl_known, + ) = self.saved_state.pop(-1) + continue + break + elif token.is_eol(): + continue + elif token.is_comment(): + self.tok.get_eol() + continue + elif token.value[0] == "$" and len(self.allowed_directives) > 0: + # Note that we only run directive processing code if at least + # one directive is allowed in order to be backwards compatible + c = token.value.upper() + if c not in self.allowed_directives: + raise dns.exception.SyntaxError( + f"zone file directive '{c}' is not allowed" + ) + if c == "$TTL": + token = self.tok.get() + if not token.is_identifier(): + raise dns.exception.SyntaxError("bad $TTL") + self.default_ttl = dns.ttl.from_text(token.value) + self.default_ttl_known = True + self.tok.get_eol() + elif c == "$ORIGIN": + self.current_origin = self.tok.get_name() + self.tok.get_eol() + if self.zone_origin is None: + self.zone_origin = self.current_origin + self.txn._set_origin(self.current_origin) + elif c == "$INCLUDE": + token = self.tok.get() + filename = token.value + token = self.tok.get() + new_origin: dns.name.Name | None + if token.is_identifier(): + new_origin = dns.name.from_text( + token.value, self.current_origin, self.tok.idna_codec + ) + self.tok.get_eol() + elif not token.is_eol_or_eof(): + raise dns.exception.SyntaxError("bad origin in $INCLUDE") + else: + new_origin = self.current_origin + self.saved_state.append( + ( + self.tok, + self.current_origin, + self.last_name, + self.current_file, + self.last_ttl, + self.last_ttl_known, + self.default_ttl, + self.default_ttl_known, + ) + ) + self.current_file = open(filename, encoding="utf-8") + self.tok = dns.tokenizer.Tokenizer(self.current_file, filename) + self.current_origin = new_origin + elif c == "$GENERATE": + self._generate_line() + else: + raise dns.exception.SyntaxError( + f"Unknown zone file directive '{c}'" + ) + continue + self.tok.unget(token) + self._rr_line() + except dns.exception.SyntaxError as detail: + (filename, line_number) = self.tok.where() + if detail is None: + detail = "syntax error" + ex = dns.exception.SyntaxError(f"{filename}:{line_number}: {detail}") + tb = sys.exc_info()[2] + raise ex.with_traceback(tb) from None + + +class RRsetsReaderTransaction(dns.transaction.Transaction): + def __init__(self, manager, replacement, read_only): + assert not read_only + super().__init__(manager, replacement, read_only) + self.rdatasets = {} + + def _get_rdataset(self, name, rdtype, covers): + return self.rdatasets.get((name, rdtype, covers)) + + def _get_node(self, name): + rdatasets = [] + for (rdataset_name, _, _), rdataset in self.rdatasets.items(): + if name == rdataset_name: + rdatasets.append(rdataset) + if len(rdatasets) == 0: + return None + node = dns.node.Node() + node.rdatasets = rdatasets + return node + + def _put_rdataset(self, name, rdataset): + self.rdatasets[(name, rdataset.rdtype, rdataset.covers)] = rdataset + + def _delete_name(self, name): + # First remove any changes involving the name + remove = [] + for key in self.rdatasets: + if key[0] == name: + remove.append(key) + if len(remove) > 0: + for key in remove: + del self.rdatasets[key] + + def _delete_rdataset(self, name, rdtype, covers): + try: + del self.rdatasets[(name, rdtype, covers)] + except KeyError: + pass + + def _name_exists(self, name): + for n, _, _ in self.rdatasets: + if n == name: + return True + return False + + def _changed(self): + return len(self.rdatasets) > 0 + + def _end_transaction(self, commit): + if commit and self._changed(): + rrsets = [] + for (name, _, _), rdataset in self.rdatasets.items(): + rrset = dns.rrset.RRset( + name, rdataset.rdclass, rdataset.rdtype, rdataset.covers + ) + rrset.update(rdataset) + rrsets.append(rrset) + self.manager.set_rrsets(rrsets) # pyright: ignore + + def _set_origin(self, origin): + pass + + def _iterate_rdatasets(self): + raise NotImplementedError # pragma: no cover + + def _iterate_names(self): + raise NotImplementedError # pragma: no cover + + +class RRSetsReaderManager(dns.transaction.TransactionManager): + def __init__( + self, + origin: dns.name.Name | None = dns.name.root, + relativize: bool = False, + rdclass: dns.rdataclass.RdataClass = dns.rdataclass.IN, + ): + self.origin = origin + self.relativize = relativize + self.rdclass = rdclass + self.rrsets: List[dns.rrset.RRset] = [] + + def reader(self): # pragma: no cover + raise NotImplementedError + + def writer(self, replacement=False): + assert replacement is True + return RRsetsReaderTransaction(self, True, False) + + def get_class(self): + return self.rdclass + + def origin_information(self): + if self.relativize: + effective = dns.name.empty + else: + effective = self.origin + return (self.origin, self.relativize, effective) + + def set_rrsets(self, rrsets: List[dns.rrset.RRset]) -> None: + self.rrsets = rrsets + + +def read_rrsets( + text: Any, + name: dns.name.Name | str | None = None, + ttl: int | None = None, + rdclass: dns.rdataclass.RdataClass | str | None = dns.rdataclass.IN, + default_rdclass: dns.rdataclass.RdataClass | str = dns.rdataclass.IN, + rdtype: dns.rdatatype.RdataType | str | None = None, + default_ttl: int | str | None = None, + idna_codec: dns.name.IDNACodec | None = None, + origin: dns.name.Name | str | None = dns.name.root, + relativize: bool = False, +) -> List[dns.rrset.RRset]: + """Read one or more rrsets from the specified text, possibly subject + to restrictions. + + *text*, a file object or a string, is the input to process. + + *name*, a string, ``dns.name.Name``, or ``None``, is the owner name of + the rrset. If not ``None``, then the owner name is "forced", and the + input must not specify an owner name. If ``None``, then any owner names + are allowed and must be present in the input. + + *ttl*, an ``int``, string, or None. If not ``None``, the the TTL is + forced to be the specified value and the input must not specify a TTL. + If ``None``, then a TTL may be specified in the input. If it is not + specified, then the *default_ttl* will be used. + + *rdclass*, a ``dns.rdataclass.RdataClass``, string, or ``None``. If + not ``None``, then the class is forced to the specified value, and the + input must not specify a class. If ``None``, then the input may specify + a class that matches *default_rdclass*. Note that it is not possible to + return rrsets with differing classes; specifying ``None`` for the class + simply allows the user to optionally type a class as that may be convenient + when cutting and pasting. + + *default_rdclass*, a ``dns.rdataclass.RdataClass`` or string. The class + of the returned rrsets. + + *rdtype*, a ``dns.rdatatype.RdataType``, string, or ``None``. If not + ``None``, then the type is forced to the specified value, and the + input must not specify a type. If ``None``, then a type must be present + for each RR. + + *default_ttl*, an ``int``, string, or ``None``. If not ``None``, then if + the TTL is not forced and is not specified, then this value will be used. + if ``None``, then if the TTL is not forced an error will occur if the TTL + is not specified. + + *idna_codec*, a ``dns.name.IDNACodec``, specifies the IDNA + encoder/decoder. If ``None``, the default IDNA 2003 encoder/decoder + is used. Note that codecs only apply to the owner name; dnspython does + not do IDNA for names in rdata, as there is no IDNA zonefile format. + + *origin*, a string, ``dns.name.Name``, or ``None``, is the origin for any + relative names in the input, and also the origin to relativize to if + *relativize* is ``True``. + + *relativize*, a bool. If ``True``, names are relativized to the *origin*; + if ``False`` then any relative names in the input are made absolute by + appending the *origin*. + """ + if isinstance(origin, str): + origin = dns.name.from_text(origin, dns.name.root, idna_codec) + if isinstance(name, str): + name = dns.name.from_text(name, origin, idna_codec) + if isinstance(ttl, str): + ttl = dns.ttl.from_text(ttl) + if isinstance(default_ttl, str): + default_ttl = dns.ttl.from_text(default_ttl) + if rdclass is not None: + rdclass = dns.rdataclass.RdataClass.make(rdclass) + else: + rdclass = None + default_rdclass = dns.rdataclass.RdataClass.make(default_rdclass) + if rdtype is not None: + rdtype = dns.rdatatype.RdataType.make(rdtype) + else: + rdtype = None + manager = RRSetsReaderManager(origin, relativize, default_rdclass) + with manager.writer(True) as txn: + tok = dns.tokenizer.Tokenizer(text, "", idna_codec=idna_codec) + reader = Reader( + tok, + default_rdclass, + txn, + allow_directives=False, + force_name=name, + force_ttl=ttl, + force_rdclass=rdclass, + force_rdtype=rdtype, + default_ttl=default_ttl, + ) + reader.read() + return manager.rrsets diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/zonetypes.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/zonetypes.py new file mode 100644 index 000000000..195ee2ec9 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dns/zonetypes.py @@ -0,0 +1,37 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +"""Common zone-related types.""" + +# This is a separate file to avoid import circularity between dns.zone and +# the implementation of the ZONEMD type. + +import hashlib + +import dns.enum + + +class DigestScheme(dns.enum.IntEnum): + """ZONEMD Scheme""" + + SIMPLE = 1 + + @classmethod + def _maximum(cls): + return 255 + + +class DigestHashAlgorithm(dns.enum.IntEnum): + """ZONEMD Hash Algorithm""" + + SHA384 = 1 + SHA512 = 2 + + @classmethod + def _maximum(cls): + return 255 + + +_digest_hashers = { + DigestHashAlgorithm.SHA384: hashlib.sha384, + DigestHashAlgorithm.SHA512: hashlib.sha512, +} diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dnspython-2.8.0.dist-info/INSTALLER b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dnspython-2.8.0.dist-info/INSTALLER new file mode 100644 index 000000000..a1b589e38 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dnspython-2.8.0.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dnspython-2.8.0.dist-info/METADATA b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dnspython-2.8.0.dist-info/METADATA new file mode 100644 index 000000000..eaaf09bba --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dnspython-2.8.0.dist-info/METADATA @@ -0,0 +1,149 @@ +Metadata-Version: 2.4 +Name: dnspython +Version: 2.8.0 +Summary: DNS toolkit +Project-URL: homepage, https://www.dnspython.org +Project-URL: repository, https://github.com/rthalley/dnspython.git +Project-URL: documentation, https://dnspython.readthedocs.io/en/stable/ +Project-URL: issues, https://github.com/rthalley/dnspython/issues +Author-email: Bob Halley +License: ISC +License-File: LICENSE +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: Intended Audience :: System Administrators +Classifier: License :: OSI Approved :: ISC License (ISCL) +Classifier: Operating System :: Microsoft :: Windows +Classifier: Operating System :: POSIX +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Topic :: Internet :: Name Service (DNS) +Classifier: Topic :: Software Development :: Libraries :: Python Modules +Requires-Python: >=3.10 +Provides-Extra: dev +Requires-Dist: black>=25.1.0; extra == 'dev' +Requires-Dist: coverage>=7.0; extra == 'dev' +Requires-Dist: flake8>=7; extra == 'dev' +Requires-Dist: hypercorn>=0.17.0; extra == 'dev' +Requires-Dist: mypy>=1.17; extra == 'dev' +Requires-Dist: pylint>=3; extra == 'dev' +Requires-Dist: pytest-cov>=6.2.0; extra == 'dev' +Requires-Dist: pytest>=8.4; extra == 'dev' +Requires-Dist: quart-trio>=0.12.0; extra == 'dev' +Requires-Dist: sphinx-rtd-theme>=3.0.0; extra == 'dev' +Requires-Dist: sphinx>=8.2.0; extra == 'dev' +Requires-Dist: twine>=6.1.0; extra == 'dev' +Requires-Dist: wheel>=0.45.0; extra == 'dev' +Provides-Extra: dnssec +Requires-Dist: cryptography>=45; extra == 'dnssec' +Provides-Extra: doh +Requires-Dist: h2>=4.2.0; extra == 'doh' +Requires-Dist: httpcore>=1.0.0; extra == 'doh' +Requires-Dist: httpx>=0.28.0; extra == 'doh' +Provides-Extra: doq +Requires-Dist: aioquic>=1.2.0; extra == 'doq' +Provides-Extra: idna +Requires-Dist: idna>=3.10; extra == 'idna' +Provides-Extra: trio +Requires-Dist: trio>=0.30; extra == 'trio' +Provides-Extra: wmi +Requires-Dist: wmi>=1.5.1; (platform_system == 'Windows') and extra == 'wmi' +Description-Content-Type: text/markdown + +# dnspython + +[![Build Status](https://github.com/rthalley/dnspython/actions/workflows/ci.yml/badge.svg)](https://github.com/rthalley/dnspython/actions/) +[![Documentation Status](https://readthedocs.org/projects/dnspython/badge/?version=latest)](https://dnspython.readthedocs.io/en/latest/?badge=latest) +[![PyPI version](https://badge.fury.io/py/dnspython.svg)](https://badge.fury.io/py/dnspython) +[![License: ISC](https://img.shields.io/badge/License-ISC-brightgreen.svg)](https://opensource.org/licenses/ISC) +[![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black) + +## INTRODUCTION + +`dnspython` is a DNS toolkit for Python. It supports almost all record types. It +can be used for queries, zone transfers, and dynamic updates. It supports +TSIG-authenticated messages and EDNS0. + +`dnspython` provides both high- and low-level access to DNS. The high-level +classes perform queries for data of a given name, type, and class, and return an +answer set. The low-level classes allow direct manipulation of DNS zones, +messages, names, and records. + +To see a few of the ways `dnspython` can be used, look in the `examples/` +directory. + +`dnspython` is a utility to work with DNS, `/etc/hosts` is thus not used. For +simple forward DNS lookups, it's better to use `socket.getaddrinfo()` or +`socket.gethostbyname()`. + +`dnspython` originated at Nominum where it was developed to facilitate the +testing of DNS software. + +## ABOUT THIS RELEASE + +This is of `dnspython` 2.8.0. +Please read +[What's New](https://dnspython.readthedocs.io/en/stable/whatsnew.html) for +information about the changes in this release. + +## INSTALLATION + +* Many distributions have dnspython packaged for you, so you should check there + first. +* To use a wheel downloaded from PyPi, run: + +``` + pip install dnspython +``` + +* To install from the source code, go into the top-level of the source code + and run: + +``` + pip install --upgrade pip build + python -m build + pip install dist/*.whl +``` + +* To install the latest from the main branch, run +`pip install git+https://github.com/rthalley/dnspython.git` + +`dnspython`'s default installation does not depend on any modules other than +those in the Python standard library. To use some features, additional modules +must be installed. For convenience, `pip` options are defined for the +requirements. + +If you want to use DNS-over-HTTPS, run +`pip install dnspython[doh]`. + +If you want to use DNSSEC functionality, run +`pip install dnspython[dnssec]`. + +If you want to use internationalized domain names (IDNA) +functionality, you must run +`pip install dnspython[idna]` + +If you want to use the Trio asynchronous I/O package, run +`pip install dnspython[trio]`. + +If you want to use WMI on Windows to determine the active DNS settings +instead of the default registry scanning method, run +`pip install dnspython[wmi]`. + +If you want to try the experimental DNS-over-QUIC code, run +`pip install dnspython[doq]`. + +Note that you can install any combination of the above, e.g.: +`pip install dnspython[doh,dnssec,idna]` + +### Notices + +Python 2.x support ended with the release of 1.16.0. `dnspython` supports Python 3.10 +and later. Future support is aligned with the lifetime of the Python 3 versions. + +Documentation has moved to +[dnspython.readthedocs.io](https://dnspython.readthedocs.io). diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dnspython-2.8.0.dist-info/RECORD b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dnspython-2.8.0.dist-info/RECORD new file mode 100644 index 000000000..a1aa73691 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dnspython-2.8.0.dist-info/RECORD @@ -0,0 +1,304 @@ +dns/__init__.py,sha256=2TTaN3FRnBIkYhrrkDUs7XYnu4h9zTlfOWdQ4nLuxnA,1693 +dns/__pycache__/__init__.cpython-312.pyc,, +dns/__pycache__/_asyncbackend.cpython-312.pyc,, +dns/__pycache__/_asyncio_backend.cpython-312.pyc,, +dns/__pycache__/_ddr.cpython-312.pyc,, +dns/__pycache__/_features.cpython-312.pyc,, +dns/__pycache__/_immutable_ctx.cpython-312.pyc,, +dns/__pycache__/_no_ssl.cpython-312.pyc,, +dns/__pycache__/_tls_util.cpython-312.pyc,, +dns/__pycache__/_trio_backend.cpython-312.pyc,, +dns/__pycache__/asyncbackend.cpython-312.pyc,, +dns/__pycache__/asyncquery.cpython-312.pyc,, +dns/__pycache__/asyncresolver.cpython-312.pyc,, +dns/__pycache__/btree.cpython-312.pyc,, +dns/__pycache__/btreezone.cpython-312.pyc,, +dns/__pycache__/dnssec.cpython-312.pyc,, +dns/__pycache__/dnssectypes.cpython-312.pyc,, +dns/__pycache__/e164.cpython-312.pyc,, +dns/__pycache__/edns.cpython-312.pyc,, +dns/__pycache__/entropy.cpython-312.pyc,, +dns/__pycache__/enum.cpython-312.pyc,, +dns/__pycache__/exception.cpython-312.pyc,, +dns/__pycache__/flags.cpython-312.pyc,, +dns/__pycache__/grange.cpython-312.pyc,, +dns/__pycache__/immutable.cpython-312.pyc,, +dns/__pycache__/inet.cpython-312.pyc,, +dns/__pycache__/ipv4.cpython-312.pyc,, +dns/__pycache__/ipv6.cpython-312.pyc,, +dns/__pycache__/message.cpython-312.pyc,, +dns/__pycache__/name.cpython-312.pyc,, +dns/__pycache__/namedict.cpython-312.pyc,, +dns/__pycache__/nameserver.cpython-312.pyc,, +dns/__pycache__/node.cpython-312.pyc,, +dns/__pycache__/opcode.cpython-312.pyc,, +dns/__pycache__/query.cpython-312.pyc,, +dns/__pycache__/rcode.cpython-312.pyc,, +dns/__pycache__/rdata.cpython-312.pyc,, +dns/__pycache__/rdataclass.cpython-312.pyc,, +dns/__pycache__/rdataset.cpython-312.pyc,, +dns/__pycache__/rdatatype.cpython-312.pyc,, +dns/__pycache__/renderer.cpython-312.pyc,, +dns/__pycache__/resolver.cpython-312.pyc,, +dns/__pycache__/reversename.cpython-312.pyc,, +dns/__pycache__/rrset.cpython-312.pyc,, +dns/__pycache__/serial.cpython-312.pyc,, +dns/__pycache__/set.cpython-312.pyc,, +dns/__pycache__/tokenizer.cpython-312.pyc,, +dns/__pycache__/transaction.cpython-312.pyc,, +dns/__pycache__/tsig.cpython-312.pyc,, +dns/__pycache__/tsigkeyring.cpython-312.pyc,, +dns/__pycache__/ttl.cpython-312.pyc,, +dns/__pycache__/update.cpython-312.pyc,, +dns/__pycache__/version.cpython-312.pyc,, +dns/__pycache__/versioned.cpython-312.pyc,, +dns/__pycache__/win32util.cpython-312.pyc,, +dns/__pycache__/wire.cpython-312.pyc,, +dns/__pycache__/xfr.cpython-312.pyc,, +dns/__pycache__/zone.cpython-312.pyc,, +dns/__pycache__/zonefile.cpython-312.pyc,, +dns/__pycache__/zonetypes.cpython-312.pyc,, +dns/_asyncbackend.py,sha256=bv-2iaDTEDH4Esx2tc2GeVCnaqHtsQqb3WWqoYZngzA,2403 +dns/_asyncio_backend.py,sha256=08Ezq3L8G190Sdr8qMgjwnWNhbyMa1MFB3pWYkGQ0a0,9147 +dns/_ddr.py,sha256=rHXKC8kncCTT9N4KBh1flicl79nyDjQ-DDvq30MJ3B8,5247 +dns/_features.py,sha256=VYTUetGL5x8IEtxMUQk9_ftat2cvyYJw8HfIfpMM8D8,2493 +dns/_immutable_ctx.py,sha256=Schj9tuGUAQ_QMh612H7Uq6XcvPo5AkVwoBxZJJ8liA,2478 +dns/_no_ssl.py,sha256=M8mj_xYkpsuhny_vHaTWCjI1pNvekYG6V52kdqFkUYY,1502 +dns/_tls_util.py,sha256=kcvrPdGnSGP1fP9sNKekBZ3j-599HwZkmAk6ybyCebM,528 +dns/_trio_backend.py,sha256=Tqzm46FuRSYkUJDYL8qp6Qk8hbc6ZxiLBc8z-NsTULg,8597 +dns/asyncbackend.py,sha256=82fXTFls_m7F_ekQbgUGOkoBbs4BI-GBLDZAWNGUvJ0,2796 +dns/asyncquery.py,sha256=34B1EIekX3oSg0jF8ZSqEiUbNZTsJa3r2oqC01OIY7U,32329 +dns/asyncresolver.py,sha256=TncJ7UukzA0vF79AwNa2gel0y9UO02tCdQf3zUHbygg,17728 +dns/btree.py,sha256=QPz4IzW_yTtSmz_DC6LKvZdJvTs50CQRKbAa0UAFMTs,30757 +dns/btreezone.py,sha256=H9orKjQaMhnPjtAhHpRZlV5wd91N17iuqOmTUVzv6sU,13082 +dns/dnssec.py,sha256=zXqhmUM4k6M-9YVR49crEI6Jc0zhZSk7NX9BWDafhTQ,41356 +dns/dnssecalgs/__init__.py,sha256=B4hebjElugf8zhCauhH6kvACqI50iYLSKxEqUfL6970,4350 +dns/dnssecalgs/__pycache__/__init__.cpython-312.pyc,, +dns/dnssecalgs/__pycache__/base.cpython-312.pyc,, +dns/dnssecalgs/__pycache__/cryptography.cpython-312.pyc,, +dns/dnssecalgs/__pycache__/dsa.cpython-312.pyc,, +dns/dnssecalgs/__pycache__/ecdsa.cpython-312.pyc,, +dns/dnssecalgs/__pycache__/eddsa.cpython-312.pyc,, +dns/dnssecalgs/__pycache__/rsa.cpython-312.pyc,, +dns/dnssecalgs/base.py,sha256=4Oq9EhKBEYupojZ3hENBiuq2Js3Spimy_NeDb9Rl1a8,2497 +dns/dnssecalgs/cryptography.py,sha256=utsBa_s8OOOKUeudvFullBNMRMjHmeoa66RNA6UiJMw,2428 +dns/dnssecalgs/dsa.py,sha256=ONilkD8Hhartj3Mwe7LKBT0vXS4E0KgfvTtV2ysZLhM,3605 +dns/dnssecalgs/ecdsa.py,sha256=TK8PclMAt7xVQTv6FIse9jZwXVCv_B-_AAgfhK0rTWQ,3283 +dns/dnssecalgs/eddsa.py,sha256=Yc0L9O2A_ySOSSalJiq5h7TU1LWtJgW1JIJWsGx96FI,2000 +dns/dnssecalgs/rsa.py,sha256=YOPPtpfOKdgBfBJvOcDofYTiC4mGmwCfqdYUvEbdHf8,3663 +dns/dnssectypes.py,sha256=CyeuGTS_rM3zXr8wD9qMT9jkzvVfTY2JWckUcogG83E,1799 +dns/e164.py,sha256=Sc-Ctv8lXpaDot_Su02wLFxLpxLReVW7_23YiGrnMC4,3937 +dns/edns.py,sha256=E5HRHMJNGGOyNvkR4iKY2jkaoQasa4K61Feuko9uY5s,17436 +dns/entropy.py,sha256=dSbsNoNVoypURvOu-clqMiD-dFQ-fsKOPYSHwoTjaec,4247 +dns/enum.py,sha256=PBphGzrIWOi8l3MgvkEMpsJapKIejkaQUqFuMWUcZXc,3685 +dns/exception.py,sha256=zEdlBUUsjb3dqk0etKxbFXUng0lLB7TPj7JFsNN7HzQ,5936 +dns/flags.py,sha256=cQ3kTFyvcKiWHAxI5AwchNqxVOrsIrgJ6brgrH42Wq8,2750 +dns/grange.py,sha256=ZqjNVDtb7i6E9D3ai6mcWR_nFNHyCXPp7j3dLFidtvY,2154 +dns/immutable.py,sha256=InrtpKvPxl-74oYbzsyneZwAuX78hUqeG22f2aniZbk,2017 +dns/inet.py,sha256=DbkUeb4PNLmxgUVPXX1GeWQH6e7a5WZ2AP_-befdg-o,5753 +dns/ipv4.py,sha256=dRiZRfyZAOlwlj3YlfbvZChRQAKstYh9k0ibNZwHu5U,2487 +dns/ipv6.py,sha256=GccOccOFZGFlwNFgV79GffZJv6u1GW28jM_amdiLqeM,6517 +dns/message.py,sha256=YVNQjYYFDSY6ttuwz_zvJnsCGuY1t11DdchsNlcBHG0,69152 +dns/name.py,sha256=rHvrUjhkCoR0_ANOH3fHJcY1swefx62SfBTDRvoGTsI,42910 +dns/namedict.py,sha256=hJRYpKeQv6Bd2LaUOPV0L_a0eXEIuqgggPXaH4c3Tow,4000 +dns/nameserver.py,sha256=LLOUGTjdAcj4cs-zAXeaH7Pf90IW0P64MQOrAb9PAPE,10007 +dns/node.py,sha256=Z2lzeqvPjqoR-Pbevp0OJqI_bGxwYzJIIevUccTElaM,12627 +dns/opcode.py,sha256=2EgPHQaGBRXN5q4C0KslagWbmWAbyT9Cw_cBj_sMXeA,2774 +dns/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +dns/query.py,sha256=85EWlMD1hDJO5xozZ7tFazMbZldpQ04L0sQFoQfBZiI,61686 +dns/quic/__init__.py,sha256=eqHPKj8SUk5rdeQxJSS-x3XSVqwcUPZlzTUio8mOpSg,2575 +dns/quic/__pycache__/__init__.cpython-312.pyc,, +dns/quic/__pycache__/_asyncio.cpython-312.pyc,, +dns/quic/__pycache__/_common.cpython-312.pyc,, +dns/quic/__pycache__/_sync.cpython-312.pyc,, +dns/quic/__pycache__/_trio.cpython-312.pyc,, +dns/quic/_asyncio.py,sha256=YgoU65THKtpHfV8UPAnNr-HkpbkR7XY01E7R3oh5apg,10314 +dns/quic/_common.py,sha256=M7lfxwUfr07fHkefo9BbRogQmwB_lEbittc7ZAQ_ulI,11087 +dns/quic/_sync.py,sha256=Ixj0BR6ngRWaKqTUiTrYbLw0rWVsUE6uJuNJB5oUlI0,10982 +dns/quic/_trio.py,sha256=NdClJJ80TY4kg8wM34JCfzX75fhhDb0vLy-WZkSyW6E,9452 +dns/rcode.py,sha256=A7UyvwbaFDz1PZaoYcAmXcerpZV-bRC2Zv3uJepiXa4,4181 +dns/rdata.py,sha256=7OAmPoSVEysCF84bjvaGXrfB1K69bpswaKtM1X89tXQ,31977 +dns/rdataclass.py,sha256=TK4W4ywB1L_X7EZqk2Gmwnu7vdQpolQF5DtQWyNk5xo,2984 +dns/rdataset.py,sha256=aoOatp7pbWhs2JieS0vcHnNc4dfwA0SBuvXAoqe3vxE,16627 +dns/rdatatype.py,sha256=W7r_B43ja4ZTHIJgqbb2eR99lXOYntf3ngGj396AvKg,7487 +dns/rdtypes/ANY/AFSDB.py,sha256=k75wMwreF1DAfDymu4lHh16BUx7ulVP3PLeQBZnkurY,1661 +dns/rdtypes/ANY/AMTRELAY.py,sha256=zE5xls02_NvbQwXUy-MnpV-uVVSJJuaKtZ86H8_X4ic,3355 +dns/rdtypes/ANY/AVC.py,sha256=SpsXYzlBirRWN0mGnQe0MdN6H8fvlgXPJX5PjOHnEak,1024 +dns/rdtypes/ANY/CAA.py,sha256=Hq1tHBrFW-BdxkjrGCq9u6ezaUHj6nFspBD5ClpkRYc,2456 +dns/rdtypes/ANY/CDNSKEY.py,sha256=bJAdrBMsFHIJz8TF1AxZoNbdxVWBCRTG-bR_uR_r_G4,1225 +dns/rdtypes/ANY/CDS.py,sha256=Y9nIRUCAabztVLbxm2SXAdYapFemCOUuGh5JqroCDUs,1163 +dns/rdtypes/ANY/CERT.py,sha256=OAYbtDdcwRhW8w_lbxHbgyWUHxYkTHV2zbiQff00X74,3547 +dns/rdtypes/ANY/CNAME.py,sha256=IHGGq2BDpeKUahTr1pvyBQgm0NGBI_vQ3Vs5mKTXO4w,1206 +dns/rdtypes/ANY/CSYNC.py,sha256=TnO2TjHfc9Cccfsz8dSsuH9Y53o-HllMVeU2DSAglrc,2431 +dns/rdtypes/ANY/DLV.py,sha256=J-pOrw5xXsDoaB9G0r6znlYXJtqtcqhsl1OXs6CPRU4,986 +dns/rdtypes/ANY/DNAME.py,sha256=yqXRtx4dAWwB4YCCv-qW6uaxeGhg2LPQ2uyKwWaMdXs,1150 +dns/rdtypes/ANY/DNSKEY.py,sha256=MD8HUVH5XXeAGOnFWg5aVz_w-2tXYwCeVXmzExhiIeQ,1223 +dns/rdtypes/ANY/DS.py,sha256=_gf8vk1O_uY8QXFjsfUw-bny-fm6e-QpCk3PT0JCyoM,995 +dns/rdtypes/ANY/DSYNC.py,sha256=q-26ceC4f2A2A6OmVaiOwDwAe_LAHvRsra1PZ4GyotA,2154 +dns/rdtypes/ANY/EUI48.py,sha256=x0BkK0sY_tgzuCwfDYpw6tyuChHjjtbRpAgYhO0Y44o,1151 +dns/rdtypes/ANY/EUI64.py,sha256=1jCff2-SXHJLDnNDnMW8Cd_o-ok0P3x6zKy_bcCU5h4,1161 +dns/rdtypes/ANY/GPOS.py,sha256=u4qwiDBVoC7bsKfxDKGbPjnOKddpdjy2p1AhziDWcPw,4439 +dns/rdtypes/ANY/HINFO.py,sha256=D2WvjTsvD_XqT8BepBIyjPL2iYGMgYqb1VQa9ApO0qE,2217 +dns/rdtypes/ANY/HIP.py,sha256=WSw31w96y1JM6ufasx7gRHUPTQuI5ejtyLxpD7vcINE,3216 +dns/rdtypes/ANY/ISDN.py,sha256=L4C2Rxrr4JJN17lmJRbZN8RhM_ujjwIskY_4V4Gd3r4,2723 +dns/rdtypes/ANY/L32.py,sha256=I0HcPHmvRUz2_yeDd0c5uueNKwcxmbz6V-7upNOc1GA,1302 +dns/rdtypes/ANY/L64.py,sha256=rbdYukNdezhQGH6vowKu1VbUWwi5cYSg_VbWEDWyYGA,1609 +dns/rdtypes/ANY/LOC.py,sha256=jxbB0bmbnMW8AVrElmoSW0SOmLPoEf5AwQLwUeAyMsY,11962 +dns/rdtypes/ANY/LP.py,sha256=X0xGo9vr1b3AQ8J8LPMyn_ooKRuEmjwdi7TGE2mqK_k,1332 +dns/rdtypes/ANY/MX.py,sha256=qQk83idY0-SbRMDmB15JOpJi7cSyiheF-ALUD0Ev19E,995 +dns/rdtypes/ANY/NID.py,sha256=8D8RDttb0BPObs0dXbFKajAhA05iZlqAq-51b6wusEI,1561 +dns/rdtypes/ANY/NINFO.py,sha256=bdL_-6Bejb2EH-xwR1rfSr_9E3SDXLTAnov7x2924FI,1041 +dns/rdtypes/ANY/NS.py,sha256=ThfaPalUlhbyZyNyvBM3k-7onl3eJKq5wCORrOGtkMM,995 +dns/rdtypes/ANY/NSEC.py,sha256=kicEYxcKaLBpV6C_M8cHdDaqBoiYl6EYtPvjyR6kExI,2465 +dns/rdtypes/ANY/NSEC3.py,sha256=NUG3AT626zu3My8QeNMiPVfpn3PRK9AGBkKW3cIZDzM,4250 +dns/rdtypes/ANY/NSEC3PARAM.py,sha256=-r5rBTMezSh7J9Wb7bWng_TXPKIETs2AXY4WFdhz7tM,2625 +dns/rdtypes/ANY/OPENPGPKEY.py,sha256=3LHryx1g0g-WrOI19PhGzGZG0anIJw2CCn93P4aT-Lk,1870 +dns/rdtypes/ANY/OPT.py,sha256=W36RslT_Psp95OPUC70knumOYjKpaRHvGT27I-NV2qc,2561 +dns/rdtypes/ANY/PTR.py,sha256=5HcR1D77Otyk91vVY4tmqrfZfSxSXWyWvwIW-rIH5gc,997 +dns/rdtypes/ANY/RESINFO.py,sha256=Kf2NcKbkeI5gFE1bJfQNqQCaitYyXfV_9nQYl1luUZ0,1008 +dns/rdtypes/ANY/RP.py,sha256=8doJlhjYDYiAT6KNF1mAaemJ20YJFUPvit8LOx4-I-U,2174 +dns/rdtypes/ANY/RRSIG.py,sha256=_ohbap8Dp_3VMU4w7ozVWGyFCtpm8A-l1F1wQiFZogA,4941 +dns/rdtypes/ANY/RT.py,sha256=2t9q3FZQ28iEyceeU25KU2Ur0T5JxELAu8BTwfOUgVw,1013 +dns/rdtypes/ANY/SMIMEA.py,sha256=6yjHuVDfIEodBU9wxbCGCDZ5cWYwyY6FCk-aq2VNU0s,222 +dns/rdtypes/ANY/SOA.py,sha256=tbbpP7RK2kpTTYCgdAWGCxlIMcX9U5MTOhz7vLP4p0I,3034 +dns/rdtypes/ANY/SPF.py,sha256=rA3Srs9ECQx-37lqm7Zf7aYmMpp_asv4tGS8_fSQ-CU,1022 +dns/rdtypes/ANY/SSHFP.py,sha256=F5vrZB-MAmeGJFAgEwRjXxgxerhoAd6kT9AcNNmkcF4,2550 +dns/rdtypes/ANY/TKEY.py,sha256=qvMJd0HGQF1wHGk1eWdITBVnAkj1oTHHbP5zSzV4cTc,4848 +dns/rdtypes/ANY/TLSA.py,sha256=cytzebS3W7FFr9qeJ9gFSHq_bOwUk9aRVlXWHfnVrRs,218 +dns/rdtypes/ANY/TSIG.py,sha256=4fNQJSNWZXUKZejCciwQuUJtTw2g-YbPmqHrEj_pitg,4750 +dns/rdtypes/ANY/TXT.py,sha256=F1U9gIAhwXIV4UVT7CwOCEn_su6G1nJIdgWJsLktk20,1000 +dns/rdtypes/ANY/URI.py,sha256=JyPYKh2RXzI34oABDiJ2oDh3TE_l-zmut4jBNA-ONt4,2913 +dns/rdtypes/ANY/WALLET.py,sha256=IaP2g7Nq26jWGKa8MVxvJjWXLQ0wrNR1IWJVyyMG8oU,219 +dns/rdtypes/ANY/X25.py,sha256=BzEM7uOY7CMAm7QN-dSLj-_LvgnnohwJDUjMstzwqYo,1942 +dns/rdtypes/ANY/ZONEMD.py,sha256=DjBYvHY13nF70uxTM77zf3R9n0Uy8Frbj1LuBXbC7jU,2389 +dns/rdtypes/ANY/__init__.py,sha256=2UKaYp81SLH6ofE021on9pR7jzmB47D1iXjQ3M7FXrw,1539 +dns/rdtypes/ANY/__pycache__/AFSDB.cpython-312.pyc,, +dns/rdtypes/ANY/__pycache__/AMTRELAY.cpython-312.pyc,, +dns/rdtypes/ANY/__pycache__/AVC.cpython-312.pyc,, +dns/rdtypes/ANY/__pycache__/CAA.cpython-312.pyc,, +dns/rdtypes/ANY/__pycache__/CDNSKEY.cpython-312.pyc,, +dns/rdtypes/ANY/__pycache__/CDS.cpython-312.pyc,, +dns/rdtypes/ANY/__pycache__/CERT.cpython-312.pyc,, +dns/rdtypes/ANY/__pycache__/CNAME.cpython-312.pyc,, +dns/rdtypes/ANY/__pycache__/CSYNC.cpython-312.pyc,, +dns/rdtypes/ANY/__pycache__/DLV.cpython-312.pyc,, +dns/rdtypes/ANY/__pycache__/DNAME.cpython-312.pyc,, +dns/rdtypes/ANY/__pycache__/DNSKEY.cpython-312.pyc,, +dns/rdtypes/ANY/__pycache__/DS.cpython-312.pyc,, +dns/rdtypes/ANY/__pycache__/DSYNC.cpython-312.pyc,, +dns/rdtypes/ANY/__pycache__/EUI48.cpython-312.pyc,, +dns/rdtypes/ANY/__pycache__/EUI64.cpython-312.pyc,, +dns/rdtypes/ANY/__pycache__/GPOS.cpython-312.pyc,, +dns/rdtypes/ANY/__pycache__/HINFO.cpython-312.pyc,, +dns/rdtypes/ANY/__pycache__/HIP.cpython-312.pyc,, +dns/rdtypes/ANY/__pycache__/ISDN.cpython-312.pyc,, +dns/rdtypes/ANY/__pycache__/L32.cpython-312.pyc,, +dns/rdtypes/ANY/__pycache__/L64.cpython-312.pyc,, +dns/rdtypes/ANY/__pycache__/LOC.cpython-312.pyc,, +dns/rdtypes/ANY/__pycache__/LP.cpython-312.pyc,, +dns/rdtypes/ANY/__pycache__/MX.cpython-312.pyc,, +dns/rdtypes/ANY/__pycache__/NID.cpython-312.pyc,, +dns/rdtypes/ANY/__pycache__/NINFO.cpython-312.pyc,, +dns/rdtypes/ANY/__pycache__/NS.cpython-312.pyc,, +dns/rdtypes/ANY/__pycache__/NSEC.cpython-312.pyc,, +dns/rdtypes/ANY/__pycache__/NSEC3.cpython-312.pyc,, +dns/rdtypes/ANY/__pycache__/NSEC3PARAM.cpython-312.pyc,, +dns/rdtypes/ANY/__pycache__/OPENPGPKEY.cpython-312.pyc,, +dns/rdtypes/ANY/__pycache__/OPT.cpython-312.pyc,, +dns/rdtypes/ANY/__pycache__/PTR.cpython-312.pyc,, +dns/rdtypes/ANY/__pycache__/RESINFO.cpython-312.pyc,, +dns/rdtypes/ANY/__pycache__/RP.cpython-312.pyc,, +dns/rdtypes/ANY/__pycache__/RRSIG.cpython-312.pyc,, +dns/rdtypes/ANY/__pycache__/RT.cpython-312.pyc,, +dns/rdtypes/ANY/__pycache__/SMIMEA.cpython-312.pyc,, +dns/rdtypes/ANY/__pycache__/SOA.cpython-312.pyc,, +dns/rdtypes/ANY/__pycache__/SPF.cpython-312.pyc,, +dns/rdtypes/ANY/__pycache__/SSHFP.cpython-312.pyc,, +dns/rdtypes/ANY/__pycache__/TKEY.cpython-312.pyc,, +dns/rdtypes/ANY/__pycache__/TLSA.cpython-312.pyc,, +dns/rdtypes/ANY/__pycache__/TSIG.cpython-312.pyc,, +dns/rdtypes/ANY/__pycache__/TXT.cpython-312.pyc,, +dns/rdtypes/ANY/__pycache__/URI.cpython-312.pyc,, +dns/rdtypes/ANY/__pycache__/WALLET.cpython-312.pyc,, +dns/rdtypes/ANY/__pycache__/X25.cpython-312.pyc,, +dns/rdtypes/ANY/__pycache__/ZONEMD.cpython-312.pyc,, +dns/rdtypes/ANY/__pycache__/__init__.cpython-312.pyc,, +dns/rdtypes/CH/A.py,sha256=Iq82L3RLM-OwB5hyvtX1Das9oToiZMzNgs979cAkDz8,2229 +dns/rdtypes/CH/__init__.py,sha256=GD9YeDKb9VBDo-J5rrChX1MWEGyQXuR9Htnbhg_iYLc,923 +dns/rdtypes/CH/__pycache__/A.cpython-312.pyc,, +dns/rdtypes/CH/__pycache__/__init__.cpython-312.pyc,, +dns/rdtypes/IN/A.py,sha256=FfFn3SqbpneL9Ky63COP50V2ZFxqS1ldCKJh39Enwug,1814 +dns/rdtypes/IN/AAAA.py,sha256=AxrOlYy-1TTTWeQypDKeXrDCrdHGor0EKCE4fxzSQGo,1820 +dns/rdtypes/IN/APL.py,sha256=4Kz56antsRGu-cfV2MCHN8rmVo90wnZXnLWA6uQpnk4,5081 +dns/rdtypes/IN/DHCID.py,sha256=x9vedfzJ3vvxPC1ihWTTcxXBMYL0Q24Wmj6O67aY5og,1875 +dns/rdtypes/IN/HTTPS.py,sha256=P-IjwcvDQMmtoBgsDHglXF7KgLX73G6jEDqCKsnaGpQ,220 +dns/rdtypes/IN/IPSECKEY.py,sha256=jMO-aGl1eglWDqMxAkM2BvKDjfe9O1X0avBoWCtWi30,3261 +dns/rdtypes/IN/KX.py,sha256=K1JwItL0n5G-YGFCjWeh0C9DyDD8G8VzicsBeQiNAv0,1013 +dns/rdtypes/IN/NAPTR.py,sha256=JhGpvtCn_qlNWWlW9ilrWh9PNElBgNq1SWJPqD3LRzA,3741 +dns/rdtypes/IN/NSAP.py,sha256=6YfWCVSIPTTBmRAzG8nVBj3LnohncXUhSFJHgp-TRdc,2163 +dns/rdtypes/IN/NSAP_PTR.py,sha256=iTxlV6fr_Y9lqivLLncSHxEhmFqz5UEElDW3HMBtuCU,1015 +dns/rdtypes/IN/PX.py,sha256=zRg_5eGQdpzCRUsXIccxJOs7xoTAn7i4PIrj0Zwv-1A,2748 +dns/rdtypes/IN/SRV.py,sha256=TVai6Rtfx0_73wH999uPGuz-p2m6BTVIleXy1Tlm5Dc,2759 +dns/rdtypes/IN/SVCB.py,sha256=HeFmi2v01F00Hott8FlvQ4R7aPxFmT7RF-gt45R5K_M,218 +dns/rdtypes/IN/WKS.py,sha256=4_dLY3Bh6ePkfgku11QzLJv74iSyoSpt8EflIp_AMNc,3644 +dns/rdtypes/IN/__init__.py,sha256=HbI8aw9HWroI6SgEvl8Sx6FdkDswCCXMbSRuJy5o8LQ,1083 +dns/rdtypes/IN/__pycache__/A.cpython-312.pyc,, +dns/rdtypes/IN/__pycache__/AAAA.cpython-312.pyc,, +dns/rdtypes/IN/__pycache__/APL.cpython-312.pyc,, +dns/rdtypes/IN/__pycache__/DHCID.cpython-312.pyc,, +dns/rdtypes/IN/__pycache__/HTTPS.cpython-312.pyc,, +dns/rdtypes/IN/__pycache__/IPSECKEY.cpython-312.pyc,, +dns/rdtypes/IN/__pycache__/KX.cpython-312.pyc,, +dns/rdtypes/IN/__pycache__/NAPTR.cpython-312.pyc,, +dns/rdtypes/IN/__pycache__/NSAP.cpython-312.pyc,, +dns/rdtypes/IN/__pycache__/NSAP_PTR.cpython-312.pyc,, +dns/rdtypes/IN/__pycache__/PX.cpython-312.pyc,, +dns/rdtypes/IN/__pycache__/SRV.cpython-312.pyc,, +dns/rdtypes/IN/__pycache__/SVCB.cpython-312.pyc,, +dns/rdtypes/IN/__pycache__/WKS.cpython-312.pyc,, +dns/rdtypes/IN/__pycache__/__init__.cpython-312.pyc,, +dns/rdtypes/__init__.py,sha256=NYizfGglJfhqt_GMtSSXf7YQXIEHHCiJ_Y_qaLVeiOI,1073 +dns/rdtypes/__pycache__/__init__.cpython-312.pyc,, +dns/rdtypes/__pycache__/dnskeybase.cpython-312.pyc,, +dns/rdtypes/__pycache__/dsbase.cpython-312.pyc,, +dns/rdtypes/__pycache__/euibase.cpython-312.pyc,, +dns/rdtypes/__pycache__/mxbase.cpython-312.pyc,, +dns/rdtypes/__pycache__/nsbase.cpython-312.pyc,, +dns/rdtypes/__pycache__/svcbbase.cpython-312.pyc,, +dns/rdtypes/__pycache__/tlsabase.cpython-312.pyc,, +dns/rdtypes/__pycache__/txtbase.cpython-312.pyc,, +dns/rdtypes/__pycache__/util.cpython-312.pyc,, +dns/rdtypes/dnskeybase.py,sha256=GXSOvGtiRjY3fhqlI_T-4ukF4JQvvh3sk7UF0vipmPc,2824 +dns/rdtypes/dsbase.py,sha256=elOLkRb45vYzyh36_1FSJWWO9AI2wnK3GpddmQNdj3Y,3423 +dns/rdtypes/euibase.py,sha256=2DluC_kTi2io2ICgzFEdSxKGPFx3ib3ZXnA6YaAhAp0,2675 +dns/rdtypes/mxbase.py,sha256=N_3EX_2BgY0wMdGADL6_5nxBRUdx4ZcdNIYfGg5rMP8,3190 +dns/rdtypes/nsbase.py,sha256=tueXVV6E8lelebOmrmoOPq47eeRvOpsxHVXH4cOFxcs,2323 +dns/rdtypes/svcbbase.py,sha256=0VnPpt7fSCNt_MtGnWOiYtkY-6jQRWIli8JTRROakys,17717 +dns/rdtypes/tlsabase.py,sha256=hHuRO_MQ5g_tWBIDyTNArAWwbUc-MdZlXcjQxy5defA,2588 +dns/rdtypes/txtbase.py,sha256=lEzlKS6dx6UnhgoBPGIzqC3G0e8iWBetrkDtkwM16Ic,3723 +dns/rdtypes/util.py,sha256=WjiRlxsu_sq40XpSdR6wN54WWavKe7PLh-V9UaNhk7A,9680 +dns/renderer.py,sha256=sj_m9NRJoY8gdQ9zOhSVu0pTAUyBtM5AGpfea83jGpQ,11500 +dns/resolver.py,sha256=FRa-pJApeV_DFgLEwiwZP-2g7RHAg0kVCbg9EdNYLnc,73967 +dns/reversename.py,sha256=pPDGRfg7iq09cjEhKLKEcahdoyViS0y0ORip--r5vk8,3845 +dns/rrset.py,sha256=f8avzbtBb-y93jdyhhTJ8EJx1zOTcNTK3DtiK84eGNY,9129 +dns/serial.py,sha256=-t5rPW-TcJwzBMfIJo7Tl-uDtaYtpqOfCVYx9dMaDCY,3606 +dns/set.py,sha256=hublMKCIhd9zp5Hz_fvQTwF-Ze28jn7mjqei6vTGWfs,9213 +dns/tokenizer.py,sha256=dqQvBF3oUjP7URC7ZzBuQVLMVXhvf1gJusIpkV-IQ6U,23490 +dns/transaction.py,sha256=HnHa4nKL_ddtuWH4FaiKPEt81ImELL1fumZb3ll4KbI,22579 +dns/tsig.py,sha256=mWjZGZL75atl-jf3va1FhP9LfLGWT5g9Y9DgsSan4Mo,11576 +dns/tsigkeyring.py,sha256=1xSBgaV1KLR_9FQGsGWbkBD3XJjK8IFQx-H_olH1qyQ,2650 +dns/ttl.py,sha256=Rl8UOKV0_QyZzOdQ-JoB7nSHvBFehZXe_M0cxIBVc3Y,2937 +dns/update.py,sha256=iqZEO-_U0ooAqLlIRo1OhAKI8d-jpwPhBy-vC8v1dtY,12236 +dns/version.py,sha256=d7ViavUC8gYfrWbeyH8WMAldyGk_WVF5_zkCmCJv0ZQ,1763 +dns/versioned.py,sha256=yJ76QfKdIEKBtKX_DLA_IZGUZoFB1id1mMKzIj2eRm8,11841 +dns/win32util.py,sha256=iz5Gw0CTHAIqumdE25xdYUbhhSFiaZTRM-HXskglB2o,16799 +dns/wire.py,sha256=hylnQ30yjA3UcJSElhSAqYKMt5HICYqQ_N5b71K2smA,3155 +dns/xfr.py,sha256=UE4xAyfRDNH14x4os8yC-4Tl8brc_kCpBLxT0h6x-AM,13637 +dns/zone.py,sha256=ZferSA6wMN46uuBNkrgbRcSM8FSCCxMrNiLT3WoISbw,53098 +dns/zonefile.py,sha256=Xz24A8wH97NoA_iTbastSzUZ-S-DmLFG0SgIfVzQinY,28517 +dns/zonetypes.py,sha256=HrQNZxZ_gWLWI9dskix71msi9wkYK5pgrBBbPb1T74Y,690 +dnspython-2.8.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +dnspython-2.8.0.dist-info/METADATA,sha256=dPdZU5uJ4pkVGy1pfGEjBzRbdm27fpQ1z4Y6Bpgf04U,5680 +dnspython-2.8.0.dist-info/RECORD,, +dnspython-2.8.0.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87 +dnspython-2.8.0.dist-info/licenses/LICENSE,sha256=w-o_9WVLMpwZ07xfdIGvYjw93tSmFFWFSZ-EOtPXQc0,1526 diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dnspython-2.8.0.dist-info/WHEEL b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dnspython-2.8.0.dist-info/WHEEL new file mode 100644 index 000000000..12228d414 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dnspython-2.8.0.dist-info/WHEEL @@ -0,0 +1,4 @@ +Wheel-Version: 1.0 +Generator: hatchling 1.27.0 +Root-Is-Purelib: true +Tag: py3-none-any diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dnspython-2.8.0.dist-info/licenses/LICENSE b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dnspython-2.8.0.dist-info/licenses/LICENSE new file mode 100644 index 000000000..390a726dc --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/dnspython-2.8.0.dist-info/licenses/LICENSE @@ -0,0 +1,35 @@ +ISC License + +Copyright (C) Dnspython Contributors + +Permission to use, copy, modify, and/or distribute this software for +any purpose with or without fee is hereby granted, provided that the +above copyright notice and this permission notice appear in all +copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL +WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE +AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL +DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR +PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER +TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. + + + +Copyright (C) 2001-2017 Nominum, Inc. +Copyright (C) Google Inc. + +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose with or without fee is hereby granted, +provided that the above copyright notice and this permission notice +appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/email_validator-2.3.0.dist-info/INSTALLER b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/email_validator-2.3.0.dist-info/INSTALLER new file mode 100644 index 000000000..a1b589e38 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/email_validator-2.3.0.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/email_validator-2.3.0.dist-info/METADATA b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/email_validator-2.3.0.dist-info/METADATA new file mode 100644 index 000000000..04cbc2a82 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/email_validator-2.3.0.dist-info/METADATA @@ -0,0 +1,466 @@ +Metadata-Version: 2.4 +Name: email-validator +Version: 2.3.0 +Summary: A robust email address syntax and deliverability validation library. +Home-page: https://github.com/JoshData/python-email-validator +Author: Joshua Tauberer +Author-email: jt@occams.info +License: Unlicense +Keywords: email address validator +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: The Unlicense (Unlicense) +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Topic :: Software Development :: Libraries :: Python Modules +Requires-Python: >=3.8 +Description-Content-Type: text/markdown +License-File: LICENSE +Requires-Dist: dnspython>=2.0.0 +Requires-Dist: idna>=2.0.0 +Dynamic: license-file + +email-validator: Validate Email Addresses +========================================= + +A robust email address syntax and deliverability validation library for +Python 3.8+ by [Joshua Tauberer](https://joshdata.me). + +This library validates that a string is of the form `name@example.com` +and optionally checks that the domain name is set up to receive email. +This is the sort of validation you would want when you are identifying +users by their email address like on a registration form. + +Key features: + +* Checks that an email address has the correct syntax --- great for + email-based registration/login forms or validating data. +* Gives friendly English error messages when validation fails that you + can display to end-users. +* Checks deliverability (optional): Does the domain name resolve? + (You can override the default DNS resolver to add query caching.) +* Supports internationalized domain names (like `@ツ.life`), + internationalized local parts (like `ツ@example.com`), + and optionally parses display names (e.g. `"My Name" `). +* Rejects addresses with invalid or unsafe Unicode characters, + obsolete email address syntax that you'd find unexpected, + special use domain names like `@localhost`, + and domains without a dot by default. + This is an opinionated library! +* Normalizes email addresses (important for internationalized + and quoted-string addresses! see below). +* Python type annotations are used. + +This is an opinionated library. You should definitely also consider using +the less-opinionated [pyIsEmail](https://github.com/michaelherold/pyIsEmail) +if it works better for you. + +[![Build Status](https://github.com/JoshData/python-email-validator/actions/workflows/test_and_build.yaml/badge.svg)](https://github.com/JoshData/python-email-validator/actions/workflows/test_and_build.yaml) + +View the [CHANGELOG / Release Notes](CHANGELOG.md) for the version history of changes in the library. Occasionally this README is ahead of the latest published package --- see the CHANGELOG for details. + +--- + +Installation +------------ + +This package [is on PyPI](https://pypi.org/project/email-validator/), so: + +```sh +pip install email-validator +``` + +(You might need to use `pip3` depending on your local environment.) + +Quick Start +----------- + +If you're validating a user's email address before creating a user +account in your application, you might do this: + +```python +from email_validator import validate_email, EmailNotValidError + +email = "my+address@example.org" + +try: + + # Check that the email address is valid. Turn on check_deliverability + # for first-time validations like on account creation pages (but not + # login pages). + emailinfo = validate_email(email, check_deliverability=False) + + # After this point, use only the normalized form of the email address, + # especially before going to a database query. + email = emailinfo.normalized + +except EmailNotValidError as e: + + # The exception message is human-readable explanation of why it's + # not a valid (or deliverable) email address. + print(str(e)) +``` + +This validates the address and gives you its normalized form. You should +**put the normalized form in your database** and always normalize before +checking if an address is in your database. When using this in a login form, +set `check_deliverability` to `False` to avoid unnecessary DNS queries. + +Usage +----- + +### Overview + +The module provides a function `validate_email(email_address)` which +takes an email address and: + +- Raises a `EmailNotValidError` with a helpful, human-readable error + message explaining why the email address is not valid, or +- Returns an object with a normalized form of the email address (which + you should use!) and other information about it. + +When an email address is not valid, `validate_email` raises either an +`EmailSyntaxError` if the form of the address is invalid or an +`EmailUndeliverableError` if the domain name fails DNS checks. Both +exception classes are subclasses of `EmailNotValidError`, which in turn +is a subclass of `ValueError`. + +But when an email address is valid, an object is returned containing +a normalized form of the email address (which you should use!) and +other information. + +The validator doesn't, by default, permit obsoleted forms of email addresses +that no one uses anymore even though they are still valid and deliverable, since +they will probably give you grief if you're using email for login. (See +later in the document about how to allow some obsolete forms.) + +The validator optionally checks that the domain name in the email address has +a DNS MX record indicating that it can receive email. (Except a Null MX record. +If there is no MX record, a fallback A/AAAA-record is permitted, unless +a reject-all SPF record is present.) DNS is slow and sometimes unavailable or +unreliable, so consider whether these checks are useful for your use case and +turn them off if they aren't. +There is nothing to be gained by trying to actually contact an SMTP server, so +that's not done here. For privacy, security, and practicality reasons, servers +are good at not giving away whether an address is +deliverable or not: email addresses that appear to accept mail at first +can bounce mail after a delay, and bounced mail may indicate a temporary +failure of a good email address (sometimes an intentional failure, like +greylisting). + +### Options + +The `validate_email` function also accepts the following keyword arguments +(defaults are as shown below): + +`check_deliverability=True`: If true, DNS queries are made to check that the domain name in the email address (the part after the @-sign) can receive mail, as described above. Set to `False` to skip this DNS-based check. It is recommended to pass `False` when performing validation for login pages (but not account creation pages) since re-validation of a previously validated domain in your database by querying DNS at every login is probably undesirable. You can also set `email_validator.CHECK_DELIVERABILITY` to `False` to turn this off for all calls by default. + +`dns_resolver=None`: Pass an instance of [dns.resolver.Resolver](https://dnspython.readthedocs.io/en/latest/resolver-class.html) to control the DNS resolver including setting a timeout and [a cache](https://dnspython.readthedocs.io/en/latest/resolver-caching.html). The `caching_resolver` function shown below is a helper function to construct a dns.resolver.Resolver with a [LRUCache](https://dnspython.readthedocs.io/en/latest/resolver-caching.html#dns.resolver.LRUCache). Reuse the same resolver instance across calls to `validate_email` to make use of the cache. + +`test_environment=False`: If `True`, DNS-based deliverability checks are disabled and `test` and `**.test` domain names are permitted (see below). You can also set `email_validator.TEST_ENVIRONMENT` to `True` to turn it on for all calls by default. + +`allow_smtputf8=True`: Set to `False` to prohibit internationalized addresses that would + require the + [SMTPUTF8](https://tools.ietf.org/html/rfc6531) extension. You can also set `email_validator.ALLOW_SMTPUTF8` to `False` to turn it off for all calls by default. + +`allow_quoted_local=False`: Set to `True` to allow obscure and potentially problematic email addresses in which the part of the address before the @-sign contains spaces, @-signs, or other surprising characters when the local part is surrounded in quotes (so-called quoted-string local parts). In the object returned by `validate_email`, the normalized local part removes any unnecessary backslash-escaping and even removes the surrounding quotes if the address would be valid without them. You can also set `email_validator.ALLOW_QUOTED_LOCAL` to `True` to turn this on for all calls by default. + +`allow_domain_literal=False`: Set to `True` to allow bracketed IPv4 and "IPv6:"-prefixed IPv6 addresses in the domain part of the email address. No deliverability checks are performed for these addresses. In the object returned by `validate_email`, the normalized domain will use the condensed IPv6 format, if applicable. The object's `domain_address` attribute will hold the parsed `ipaddress.IPv4Address` or `ipaddress.IPv6Address` object if applicable. You can also set `email_validator.ALLOW_DOMAIN_LITERAL` to `True` to turn this on for all calls by default. + +`allow_display_name=False`: Set to `True` to allow a display name and bracketed address in the input string, like `My Name `. It's implemented in the spirit but not the letter of RFC 5322 3.4, so it may be stricter or more relaxed than what you want. The display name, if present, is provided in the returned object's `display_name` field after being unquoted and unescaped. You can also set `email_validator.ALLOW_DISPLAY_NAME` to `True` to turn this on for all calls by default. + +`allow_empty_local=False`: Set to `True` to allow an empty local part (i.e. + `@example.com`), e.g. for validating Postfix aliases. + +`strict=False`: Set to `True` to perform additional syntax checks (currently only a local part length check). This should be used by mail service providers at address creation to ensure email addresses meet broad compatibility requirements. + +### DNS timeout and cache + +When validating many email addresses or to control the timeout (the default is 15 seconds), create a caching [dns.resolver.Resolver](https://dnspython.readthedocs.io/en/latest/resolver-class.html) to reuse in each call. The `caching_resolver` function returns one easily for you: + +```python +from email_validator import validate_email, caching_resolver + +resolver = caching_resolver(timeout=10) + +while True: + validate_email(email, dns_resolver=resolver) +``` + +### Test addresses + +This library rejects email addresses that use the [Special Use Domain Names](https://www.iana.org/assignments/special-use-domain-names/special-use-domain-names.xhtml) `invalid`, `localhost`, `test`, and some others by raising `EmailSyntaxError`. This is to protect your system from abuse: You probably don't want a user to be able to cause an email to be sent to `localhost` (although they might be able to still do so via a malicious MX record). However, in your non-production test environments you may want to use `@test` or `@myname.test` email addresses. There are three ways you can allow this: + +1. Add `test_environment=True` to the call to `validate_email` (see above). +2. Set `email_validator.TEST_ENVIRONMENT` to `True` globally. +3. Remove the special-use domain name that you want to use from `email_validator.SPECIAL_USE_DOMAIN_NAMES`, e.g.: + +```python +import email_validator +email_validator.SPECIAL_USE_DOMAIN_NAMES.remove("test") +``` + +It is tempting to use `@example.com/net/org` in tests. They are *not* in this library's `SPECIAL_USE_DOMAIN_NAMES` list so you can, but shouldn't, use them. These domains are reserved to IANA for use in documentation so there is no risk of accidentally emailing someone at those domains. But beware that this library will nevertheless reject these domain names if DNS-based deliverability checks are not disabled because these domains do not resolve to domains that accept email. In tests, consider using your own domain name or `@test` or `@myname.test` instead. + +Internationalized email addresses +--------------------------------- + +The email protocol SMTP and the domain name system DNS have historically +only allowed English (ASCII) characters in email addresses and domain names, +respectively. Each has adapted to internationalization in a separate +way, creating two separate aspects to email address internationalization. + +(If your mail submission library doesn't support Unicode at all, then +immediately prior to mail submission you must replace the email address with +its ASCII-ized form. This library gives you back the ASCII-ized form in the +`ascii_email` field in the returned object.) + +### Internationalized domain names (IDN) + +The first is [internationalized domain names (RFC +5891)](https://tools.ietf.org/html/rfc5891), a.k.a IDNA 2008. The DNS +system has not been updated with Unicode support. Instead, internationalized +domain names are converted into a special IDNA ASCII "[Punycode](https://www.rfc-editor.org/rfc/rfc3492.txt)" +form starting with `xn--`. When an email address has non-ASCII +characters in its domain part, the domain part is replaced with its IDNA +ASCII equivalent form in the process of mail transmission. Your mail +submission library probably does this for you transparently. ([Compliance +around the web is not very good though](http://archives.miloush.net/michkap/archive/2012/02/27/10273315.html).) This library conforms to IDNA 2008 +using the [idna](https://github.com/kjd/idna) module by Kim Davies. + +### Internationalized local parts + +The second sort of internationalization is internationalization in the +*local* part of the address (before the @-sign). In non-internationalized +email addresses, only English letters, numbers, and some punctuation +(`._!#$%&'^``*+-=~/?{|}`) are allowed. In internationalized email address +local parts, a wider range of Unicode characters are allowed. + +Email addresses with these non-ASCII characters require that your mail +submission library and all the mail servers along the route to the destination, +including your own outbound mail server, all support the +[SMTPUTF8 (RFC 6531)](https://tools.ietf.org/html/rfc6531) extension. +Support for SMTPUTF8 varies. If you know ahead of time that SMTPUTF8 is not +supported by your mail submission stack, then you must filter out addresses that +require SMTPUTF8 using the `allow_smtputf8=False` keyword argument (see above). +This will cause the validation function to raise a `EmailSyntaxError` if +delivery would require SMTPUTF8. If you do not set `allow_smtputf8=False`, +you can also check the value of the `smtputf8` field in the returned object. + +### Unsafe Unicode characters are rejected + +A surprisingly large number of Unicode characters are not safe to display, +especially when the email address is concatenated with other text, so this +library tries to protect you by not permitting reserved, non-, private use, +formatting (which can be used to alter the display order of characters), +whitespace, and control characters, and combining characters +as the first character of the local part and the domain name (so that they +cannot combine with something outside of the email address string or with +the @-sign). See https://qntm.org/safe and https://trojansource.codes/ +for relevant prior work. (Other than whitespace, these are checks that +you should be applying to nearly all user inputs in a security-sensitive +context.) This does not guard against the well known problem that many +Unicode characters look alike, which can be used to fool humans reading +displayed text. + + +Normalization +------------- + +### Unicode Normalization + +The use of Unicode in email addresses introduced a normalization +problem. Different Unicode strings can look identical and have the same +semantic meaning to the user. The `normalized` field returned on successful +validation provides the correctly normalized form of the given email +address. + +For example, the CJK fullwidth Latin letters are considered semantically +equivalent in domain names to their ASCII counterparts. This library +normalizes them to their ASCII counterparts (as required by IDNA): + +```python +emailinfo = validate_email("me@Domain.com") +print(emailinfo.normalized) +print(emailinfo.ascii_email) +# prints "me@domain.com" twice +``` + +Because an end-user might type their email address in different (but +equivalent) un-normalized forms at different times, you ought to +replace what they enter with the normalized form immediately prior to +going into your database (during account creation), querying your database +(during login), or sending outbound mail. + +The normalizations include lowercasing the domain part of the email +address (domain names are case-insensitive), [Unicode "NFC" +normalization](https://en.wikipedia.org/wiki/Unicode_equivalence) of the +whole address (which turns characters plus [combining +characters](https://en.wikipedia.org/wiki/Combining_character) into +precomposed characters where possible, replacement of [fullwidth and +halfwidth +characters](https://en.wikipedia.org/wiki/Halfwidth_and_fullwidth_forms) +in the domain part, possibly other +[UTS46](http://unicode.org/reports/tr46) mappings on the domain part, +and conversion from Punycode to Unicode characters. + +Normalization may change the characters in the email address and the +length of the email address, such that a string might be a valid address +before normalization but invalid after, or vice versa. This library only +permits addresses that are valid both before and after normalization. + +(See [RFC 6532 (internationalized email) section +3.1](https://tools.ietf.org/html/rfc6532#section-3.1) and [RFC 5895 +(IDNA 2008) section 2](http://www.ietf.org/rfc/rfc5895.txt).) + +### Other Normalization + +Normalization is also applied to quoted-string local parts and domain +literal IPv6 addresses if you have allowed them by the `allow_quoted_local` +and `allow_domain_literal` options. In quoted-string local parts, unnecessary +backslash escaping is removed and even the surrounding quotes are removed if +they are unnecessary. For IPv6 domain literals, the IPv6 address is +normalized to condensed form. [RFC 2142](https://datatracker.ietf.org/doc/html/rfc2142) +also requires lowercase normalization for some specific mailbox names like `postmaster@`. + + +Examples +-------- + +For the email address `test@joshdata.me`, the returned object is: + +```python +ValidatedEmail( + normalized='test@joshdata.me', + local_part='test', + domain='joshdata.me', + ascii_email='test@joshdata.me', + ascii_local_part='test', + ascii_domain='joshdata.me', + smtputf8=False) +``` + +For the fictitious but valid address `example@ツ.ⓁⒾⒻⒺ`, which has an +internationalized domain but ASCII local part, the returned object is: + +```python +ValidatedEmail( + normalized='example@ツ.life', + local_part='example', + domain='ツ.life', + ascii_email='example@xn--bdk.life', + ascii_local_part='example', + ascii_domain='xn--bdk.life', + smtputf8=False) + +``` + +Note that `normalized` and other fields provide a normalized form of the +email address, domain name, and (in other cases) local part (see earlier +discussion of normalization), which you should use in your database. + +Calling `validate_email` with the ASCII form of the above email address, +`example@xn--bdk.life`, returns the exact same information (i.e., the +`normalized` field always will contain Unicode characters, not Punycode). + +For the fictitious address `ツ-test@joshdata.me`, which has an +internationalized local part, the returned object is: + +```python +ValidatedEmail( + normalized='ツ-test@joshdata.me', + local_part='ツ-test', + domain='joshdata.me', + ascii_email=None, + ascii_local_part=None, + ascii_domain='joshdata.me', + smtputf8=True) +``` + +Now `smtputf8` is `True` and `ascii_email` is `None` because the local +part of the address is internationalized. The `local_part` and `normalized` fields +return the normalized form of the address. + +Return value +------------ + +When an email address passes validation, the fields in the returned object +are: + +| Field | Value | +| -----:|-------| +| `normalized` | The normalized form of the email address that you should put in your database. This combines the `local_part` and `domain` fields (see below). | +| `ascii_email` | If set, an ASCII-only form of the normalized email address by replacing the domain part with [IDNA](https://tools.ietf.org/html/rfc5891) [Punycode](https://www.rfc-editor.org/rfc/rfc3492.txt). This field will be present when an ASCII-only form of the email address exists (including if the email address is already ASCII). If the local part of the email address contains internationalized characters, `ascii_email` will be `None`. If set, it merely combines `ascii_local_part` and `ascii_domain`. | +| `local_part` | The normalized local part of the given email address (before the @-sign). Normalization includes Unicode NFC normalization and removing unnecessary quoted-string quotes and backslashes. If `allow_quoted_local` is True and the surrounding quotes are necessary, the quotes _will_ be present in this field. | +| `ascii_local_part` | If set, the local part, which is composed of ASCII characters only. | +| `domain` | The canonical internationalized Unicode form of the domain part of the email address. If the returned string contains non-ASCII characters, either the [SMTPUTF8](https://tools.ietf.org/html/rfc6531) feature of your mail relay will be required to transmit the message or else the email address's domain part must be converted to IDNA ASCII first: Use `ascii_domain` field instead. | +| `ascii_domain` | The [IDNA](https://tools.ietf.org/html/rfc5891) [Punycode](https://www.rfc-editor.org/rfc/rfc3492.txt)-encoded form of the domain part of the given email address, as it would be transmitted on the wire. | +| `domain_address` | If domain literals are allowed and if the email address contains one, an `ipaddress.IPv4Address` or `ipaddress.IPv6Address` object. | +| `display_name` | If no display name was present and angle brackets do not surround the address, this will be `None`; otherwise, it will be set to the display name, or the empty string if there were angle brackets but no display name. If the display name was quoted, it will be unquoted and unescaped. | +| `smtputf8` | A boolean indicating that the [SMTPUTF8](https://tools.ietf.org/html/rfc6531) feature of your mail relay will be required to transmit messages to this address because the local part of the address has non-ASCII characters (the local part cannot be IDNA-encoded). If `allow_smtputf8=False` is passed as an argument, this flag will always be false because an exception is raised if it would have been true. | +| `mx` | A list of (priority, domain) tuples of MX records specified in the DNS for the domain (see [RFC 5321 section 5](https://tools.ietf.org/html/rfc5321#section-5)). May be `None` if the deliverability check could not be completed because of a temporary issue like a timeout. | +| `mx_fallback_type` | `None` if an `MX` record is found. If no MX records are actually specified in DNS and instead are inferred, through an obsolete mechanism, from A or AAAA records, the value is the type of DNS record used instead (`A` or `AAAA`). May be `None` if the deliverability check could not be completed because of a temporary issue like a timeout. | +| `spf` | Any SPF record found while checking deliverability. Only set if the SPF record is queried. | + +Assumptions +----------- + +By design, this validator does not pass all email addresses that +strictly conform to the standards. Many email address forms are obsolete +or likely to cause trouble: + +* The validator assumes the email address is intended to be + usable on the public Internet. The domain part + of the email address must be a resolvable domain name + (see the deliverability checks described above). + Most [Special Use Domain Names](https://www.iana.org/assignments/special-use-domain-names/special-use-domain-names.xhtml) + and their subdomains, as well as + domain names without a `.`, are rejected as a syntax error + (except see the `test_environment` parameter above). +* Obsolete email syntaxes are rejected: + The unusual ["(comment)" syntax](https://github.com/JoshData/python-email-validator/issues/77) + is rejected. Extremely old obsolete syntaxes are + rejected. Quoted-string local parts and domain-literal addresses + are rejected by default, but there are options to allow them (see above). + No one uses these forms anymore, and I can't think of any reason why anyone + using this library would need to accept them. + +Testing +------- + +Tests can be run using + +```sh +pip install -r test_requirements.txt +make test +``` + +Tests run with mocked DNS responses. When adding or changing tests, temporarily turn on the `BUILD_MOCKED_DNS_RESPONSE_DATA` flag in `tests/mocked_dns_responses.py` to re-build the database of mocked responses from live queries. + +For Project Maintainers +----------------------- + +The package is distributed as a universal wheel and as a source package. + +To release: + +* Update CHANGELOG.md. +* Update the version number in `email_validator/version.py`. +* Make & push a commit with the new version number and make sure tests pass. +* Make a release at https://github.com/JoshData/python-email-validator/releases/new creating a new tag (or use command below). +* Publish a source and wheel distribution to pypi (see command below). + +```sh +git tag v$(cat email_validator/version.py | sed "s/.* = //" | sed 's/"//g') +git push --tags +./release_to_pypi.sh +``` + +License +------- + +This project is free of any copyright restrictions per the [Unlicense](https://unlicense.org/). (Prior to Feb. 4, 2024, the project was made available under the terms of the [CC0 1.0 Universal public domain dedication](http://creativecommons.org/publicdomain/zero/1.0/).) See [LICENSE](LICENSE) and [CONTRIBUTING.md](CONTRIBUTING.md). diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/email_validator-2.3.0.dist-info/RECORD b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/email_validator-2.3.0.dist-info/RECORD new file mode 100644 index 000000000..e604cbaeb --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/email_validator-2.3.0.dist-info/RECORD @@ -0,0 +1,28 @@ +../../../bin/email_validator,sha256=S-Tu1vcEeRpICQnal1MSHjMuWa5yDPiVjJGvyxpihCU,302 +email_validator-2.3.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +email_validator-2.3.0.dist-info/METADATA,sha256=Kpe4Hu_NhWvICwNG9H-i2AC5pDi_j5IxrgD-kx1cn7w,26006 +email_validator-2.3.0.dist-info/RECORD,, +email_validator-2.3.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +email_validator-2.3.0.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91 +email_validator-2.3.0.dist-info/entry_points.txt,sha256=zRM_6bNIUSHTbNx5u6M3nK1MAguvryrc9hICC6HyrBg,66 +email_validator-2.3.0.dist-info/licenses/LICENSE,sha256=ZyF5dS4QkTSj-yvdB4Cyn9t6A5dPD1hqE66tUSlWLUw,1212 +email_validator-2.3.0.dist-info/top_level.txt,sha256=fYDOSWFZke46ut7WqdOAJjjhlpPYAaOwOwIsh3s8oWI,16 +email_validator/__init__.py,sha256=g3oVBGdXGJATgBnVqt5Q7pUhXM9QrmOl5qWSu_RtWmQ,4381 +email_validator/__main__.py,sha256=uc6i2EMCK67cCgcHr5ZFG5LqB3khljmR7lNAYZGSUKY,2302 +email_validator/__pycache__/__init__.cpython-312.pyc,, +email_validator/__pycache__/__main__.cpython-312.pyc,, +email_validator/__pycache__/deliverability.cpython-312.pyc,, +email_validator/__pycache__/exceptions.cpython-312.pyc,, +email_validator/__pycache__/rfc_constants.cpython-312.pyc,, +email_validator/__pycache__/syntax.cpython-312.pyc,, +email_validator/__pycache__/types.cpython-312.pyc,, +email_validator/__pycache__/validate_email.cpython-312.pyc,, +email_validator/__pycache__/version.cpython-312.pyc,, +email_validator/deliverability.py,sha256=ZIjFkgWMzxYexanwKhrRHLTnjWMqlR5b0ltOnlA0u-E,7216 +email_validator/exceptions.py,sha256=Ry2j5FMpEe9JthmTF3zF5pGgWer-QmWc1m0szXAZ7fo,434 +email_validator/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +email_validator/rfc_constants.py,sha256=LhUiBZLBw_Nn-KHkH--nVwOWFlgz2aCuauj98ZSl-gk,3443 +email_validator/syntax.py,sha256=puufskeIG6_ORWb7fvRdV_Yczmk4bibNZPs9TjWE1K0,38971 +email_validator/types.py,sha256=mvmwN9R3lFx9Tv9wtWvDzxfit6mr_5wQmY2I0HjuqRk,5588 +email_validator/validate_email.py,sha256=bmrdQ9dGt1-Mk0rwDRrX-l6xbYhQ0US20Dz46Aatnkk,9928 +email_validator/version.py,sha256=CpK8IH_dCUAwg9tqv7zm9FxbBFkxCnED1JUiRe7cftU,22 diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/email_validator-2.3.0.dist-info/REQUESTED b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/email_validator-2.3.0.dist-info/REQUESTED new file mode 100644 index 000000000..e69de29bb diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/email_validator-2.3.0.dist-info/WHEEL b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/email_validator-2.3.0.dist-info/WHEEL new file mode 100644 index 000000000..e7fa31b6f --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/email_validator-2.3.0.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: setuptools (80.9.0) +Root-Is-Purelib: true +Tag: py3-none-any + diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/email_validator-2.3.0.dist-info/entry_points.txt b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/email_validator-2.3.0.dist-info/entry_points.txt new file mode 100644 index 000000000..03c6e2301 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/email_validator-2.3.0.dist-info/entry_points.txt @@ -0,0 +1,2 @@ +[console_scripts] +email_validator = email_validator.__main__:main diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/email_validator-2.3.0.dist-info/licenses/LICENSE b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/email_validator-2.3.0.dist-info/licenses/LICENSE new file mode 100644 index 000000000..122e7a71f --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/email_validator-2.3.0.dist-info/licenses/LICENSE @@ -0,0 +1,27 @@ +This is free and unencumbered software released into the public +domain. + +Anyone is free to copy, modify, publish, use, compile, sell, or +distribute this software, either in source code form or as a +compiled binary, for any purpose, commercial or non-commercial, +and by any means. + +In jurisdictions that recognize copyright laws, the author or +authors of this software dedicate any and all copyright +interest in the software to the public domain. We make this +dedication for the benefit of the public at large and to the +detriment of our heirs and successors. We intend this +dedication to be an overt act of relinquishment in perpetuity +of all present and future rights to this software under +copyright law. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR +ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF +CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +For more information, please refer to diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/email_validator-2.3.0.dist-info/top_level.txt b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/email_validator-2.3.0.dist-info/top_level.txt new file mode 100644 index 000000000..798fd5ef9 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/email_validator-2.3.0.dist-info/top_level.txt @@ -0,0 +1 @@ +email_validator diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/email_validator/__init__.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/email_validator/__init__.py new file mode 100644 index 000000000..38d074148 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/email_validator/__init__.py @@ -0,0 +1,103 @@ +from typing import TYPE_CHECKING + +# Export the main method, helper methods, and the public data types. +from .exceptions import EmailNotValidError, EmailSyntaxError, EmailUndeliverableError +from .types import ValidatedEmail +from .validate_email import validate_email +from .version import __version__ + +__all__ = ["validate_email", + "ValidatedEmail", "EmailNotValidError", + "EmailSyntaxError", "EmailUndeliverableError", + "caching_resolver", "__version__"] + +if TYPE_CHECKING: + from .deliverability import caching_resolver +else: + def caching_resolver(*args, **kwargs): + # Lazy load `deliverability` as it is slow to import (due to dns.resolver) + from .deliverability import caching_resolver + + return caching_resolver(*args, **kwargs) + + +# These global attributes are a part of the library's API and can be +# changed by library users. + +# Default values for keyword arguments. + +ALLOW_SMTPUTF8 = True +ALLOW_EMPTY_LOCAL = False +ALLOW_QUOTED_LOCAL = False +ALLOW_DOMAIN_LITERAL = False +ALLOW_DISPLAY_NAME = False +STRICT = False +GLOBALLY_DELIVERABLE = True +CHECK_DELIVERABILITY = True +TEST_ENVIRONMENT = False +DEFAULT_TIMEOUT = 15 # secs + +# IANA Special Use Domain Names +# Last Updated 2021-09-21 +# https://www.iana.org/assignments/special-use-domain-names/special-use-domain-names.txt +# +# The domain names without dots would be caught by the check that the domain +# name in an email address must have a period, but this list will also catch +# subdomains of these domains, which are also reserved. +SPECIAL_USE_DOMAIN_NAMES = [ + # The "arpa" entry here is consolidated from a lot of arpa subdomains + # for private address (i.e. non-routable IP addresses like 172.16.x.x) + # reverse mapping, plus some other subdomains. Although RFC 6761 says + # that application software should not treat these domains as special, + # they are private-use domains and so cannot have globally deliverable + # email addresses, which is an assumption of this library, and probably + # all of arpa is similarly special-use, so we reject it all. + "arpa", + + # RFC 6761 says applications "SHOULD NOT" treat the "example" domains + # as special, i.e. applications should accept these domains. + # + # The domain "example" alone fails our syntax validation because it + # lacks a dot (we assume no one has an email address on a TLD directly). + # "@example.com/net/org" will currently fail DNS-based deliverability + # checks because IANA publishes a NULL MX for these domains, and + # "@mail.example[.com/net/org]" and other subdomains will fail DNS- + # based deliverability checks because IANA does not publish MX or A + # DNS records for these subdomains. + # "example", # i.e. "wwww.example" + # "example.com", + # "example.net", + # "example.org", + + # RFC 6761 says that applications are permitted to treat this domain + # as special and that DNS should return an immediate negative response, + # so we also immediately reject this domain, which also follows the + # purpose of the domain. + "invalid", + + # RFC 6762 says that applications "may" treat ".local" as special and + # that "name resolution APIs and libraries SHOULD recognize these names + # as special," and since ".local" has no global definition, we reject + # it, as we expect email addresses to be gloally routable. + "local", + + # RFC 6761 says that applications (like this library) are permitted + # to treat "localhost" as special, and since it cannot have a globally + # deliverable email address, we reject it. + "localhost", + + # RFC 7686 says "applications that do not implement the Tor protocol + # SHOULD generate an error upon the use of .onion and SHOULD NOT + # perform a DNS lookup. + "onion", + + # Although RFC 6761 says that application software should not treat + # these domains as special, it also warns users that the address may + # resolve differently in different systems, and therefore it cannot + # have a globally routable email address, which is an assumption of + # this library, so we reject "@test" and "@*.test" addresses, unless + # the test_environment keyword argument is given, to allow their use + # in application-level test environments. These domains will generally + # fail deliverability checks because "test" is not an actual TLD. + "test", +] diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/email_validator/__main__.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/email_validator/__main__.py new file mode 100644 index 000000000..84d9fd477 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/email_validator/__main__.py @@ -0,0 +1,61 @@ +# A command-line tool for testing. +# +# Usage: +# +# python -m email_validator test@example.org +# python -m email_validator < LIST_OF_ADDRESSES.TXT +# +# Provide email addresses to validate either as a command-line argument +# or in STDIN separated by newlines. Validation errors will be printed for +# invalid email addresses. When passing an email address on the command +# line, if the email address is valid, information about it will be printed. +# When using STDIN, no output will be given for valid email addresses. +# +# Keyword arguments to validate_email can be set in environment variables +# of the same name but uppercase (see below). + +import json +import os +import sys +from typing import Any, Dict, Optional + +from .validate_email import validate_email, _Resolver +from .deliverability import caching_resolver +from .exceptions import EmailNotValidError + + +def main(dns_resolver: Optional[_Resolver] = None) -> None: + # The dns_resolver argument is for tests. + + # Set options from environment variables. + options: Dict[str, Any] = {} + for varname in ('ALLOW_SMTPUTF8', 'ALLOW_EMPTY_LOCAL', 'ALLOW_QUOTED_LOCAL', 'ALLOW_DOMAIN_LITERAL', + 'ALLOW_DISPLAY_NAME', + 'GLOBALLY_DELIVERABLE', 'CHECK_DELIVERABILITY', 'TEST_ENVIRONMENT'): + if varname in os.environ: + options[varname.lower()] = bool(os.environ[varname]) + for varname in ('DEFAULT_TIMEOUT',): + if varname in os.environ: + options[varname.lower()] = float(os.environ[varname]) + + if len(sys.argv) == 1: + # Validate the email addresses passed line-by-line on STDIN. + dns_resolver = dns_resolver or caching_resolver() + for line in sys.stdin: + email = line.strip() + try: + validate_email(email, dns_resolver=dns_resolver, **options) + except EmailNotValidError as e: + print(f"{email} {e}") + else: + # Validate the email address passed on the command line. + email = sys.argv[1] + try: + result = validate_email(email, dns_resolver=dns_resolver, **options) + print(json.dumps(result.as_dict(), indent=2, sort_keys=True, ensure_ascii=False)) + except EmailNotValidError as e: + print(e) + + +if __name__ == "__main__": + main() diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/email_validator/deliverability.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/email_validator/deliverability.py new file mode 100644 index 000000000..6100a3121 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/email_validator/deliverability.py @@ -0,0 +1,159 @@ +from typing import Any, List, Optional, Tuple, TypedDict + +import ipaddress + +from .exceptions import EmailUndeliverableError + +import dns.resolver +import dns.exception + + +def caching_resolver(*, timeout: Optional[int] = None, cache: Any = None, dns_resolver: Optional[dns.resolver.Resolver] = None) -> dns.resolver.Resolver: + if timeout is None: + from . import DEFAULT_TIMEOUT + timeout = DEFAULT_TIMEOUT + resolver = dns_resolver or dns.resolver.Resolver() + resolver.cache = cache or dns.resolver.LRUCache() + resolver.lifetime = timeout # timeout, in seconds + return resolver + + +DeliverabilityInfo = TypedDict("DeliverabilityInfo", { + "mx": List[Tuple[int, str]], + "mx_fallback_type": Optional[str], + "unknown-deliverability": str, +}, total=False) + + +def validate_email_deliverability(domain: str, domain_i18n: str, timeout: Optional[int] = None, dns_resolver: Optional[dns.resolver.Resolver] = None) -> DeliverabilityInfo: + # Check that the domain resolves to an MX record. If there is no MX record, + # try an A or AAAA record which is a deprecated fallback for deliverability. + # Raises an EmailUndeliverableError on failure. On success, returns a dict + # with deliverability information. + + # If no dns.resolver.Resolver was given, get dnspython's default resolver. + # Override the default resolver's timeout. This may affect other uses of + # dnspython in this process. + if dns_resolver is None: + from . import DEFAULT_TIMEOUT + if timeout is None: + timeout = DEFAULT_TIMEOUT + dns_resolver = dns.resolver.get_default_resolver() + dns_resolver.lifetime = timeout + elif timeout is not None: + raise ValueError("It's not valid to pass both timeout and dns_resolver.") + + deliverability_info: DeliverabilityInfo = {} + + try: + try: + # Try resolving for MX records (RFC 5321 Section 5). + response = dns_resolver.resolve(domain, "MX") + + # For reporting, put them in priority order and remove the trailing dot in the qnames. + mtas = sorted([(r.preference, str(r.exchange).rstrip('.')) for r in response]) + + # RFC 7505: Null MX (0, ".") records signify the domain does not accept email. + # Remove null MX records from the mtas list (but we've stripped trailing dots, + # so the 'exchange' is just "") so we can check if there are no non-null MX + # records remaining. + mtas = [(preference, exchange) for preference, exchange in mtas + if exchange != ""] + if len(mtas) == 0: # null MX only, if there were no MX records originally a NoAnswer exception would have occurred + raise EmailUndeliverableError(f"The domain name {domain_i18n} does not accept email.") + + deliverability_info["mx"] = mtas + deliverability_info["mx_fallback_type"] = None + + except dns.resolver.NoAnswer: + # If there was no MX record, fall back to an A or AAA record + # (RFC 5321 Section 5). Check A first since it's more common. + + # If the A/AAAA response has no Globally Reachable IP address, + # treat the response as if it were NoAnswer, i.e., the following + # address types are not allowed fallbacks: Private-Use, Loopback, + # Link-Local, and some other obscure ranges. See + # https://www.iana.org/assignments/iana-ipv4-special-registry/iana-ipv4-special-registry.xhtml + # https://www.iana.org/assignments/iana-ipv6-special-registry/iana-ipv6-special-registry.xhtml + # (Issue #134.) + def is_global_addr(address: Any) -> bool: + try: + ipaddr = ipaddress.ip_address(address) + except ValueError: + return False + return ipaddr.is_global + + try: + response = dns_resolver.resolve(domain, "A") + + if not any(is_global_addr(r.address) for r in response): + raise dns.resolver.NoAnswer # fall back to AAAA + + deliverability_info["mx"] = [(0, domain)] + deliverability_info["mx_fallback_type"] = "A" + + except dns.resolver.NoAnswer: + + # If there was no A record, fall back to an AAAA record. + # (It's unclear if SMTP servers actually do this.) + try: + response = dns_resolver.resolve(domain, "AAAA") + + if not any(is_global_addr(r.address) for r in response): + raise dns.resolver.NoAnswer + + deliverability_info["mx"] = [(0, domain)] + deliverability_info["mx_fallback_type"] = "AAAA" + + except dns.resolver.NoAnswer as e: + # If there was no MX, A, or AAAA record, then mail to + # this domain is not deliverable, although the domain + # name has other records (otherwise NXDOMAIN would + # have been raised). + raise EmailUndeliverableError(f"The domain name {domain_i18n} does not accept email.") from e + + # Check for a SPF (RFC 7208) reject-all record ("v=spf1 -all") which indicates + # no emails are sent from this domain (similar to a Null MX record + # but for sending rather than receiving). In combination with the + # absence of an MX record, this is probably a good sign that the + # domain is not used for email. + try: + response = dns_resolver.resolve(domain, "TXT") + for rec in response: + value = b"".join(rec.strings) + if value.startswith(b"v=spf1 "): + if value == b"v=spf1 -all": + raise EmailUndeliverableError(f"The domain name {domain_i18n} does not send email.") + except dns.resolver.NoAnswer: + # No TXT records means there is no SPF policy, so we cannot take any action. + pass + + except dns.resolver.NXDOMAIN as e: + # The domain name does not exist --- there are no records of any sort + # for the domain name. + raise EmailUndeliverableError(f"The domain name {domain_i18n} does not exist.") from e + + except dns.resolver.NoNameservers: + # All nameservers failed to answer the query. This might be a problem + # with local nameservers, maybe? We'll allow the domain to go through. + return { + "unknown-deliverability": "no_nameservers", + } + + except dns.exception.Timeout: + # A timeout could occur for various reasons, so don't treat it as a failure. + return { + "unknown-deliverability": "timeout", + } + + except EmailUndeliverableError: + # Don't let these get clobbered by the wider except block below. + raise + + except Exception as e: + # Unhandled conditions should not propagate. + raise EmailUndeliverableError( + "There was an error while checking if the domain name in the email address is deliverable: " + str(e) + ) from e + + return deliverability_info diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/email_validator/exceptions.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/email_validator/exceptions.py new file mode 100644 index 000000000..87ef13c5a --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/email_validator/exceptions.py @@ -0,0 +1,13 @@ +class EmailNotValidError(ValueError): + """Parent class of all exceptions raised by this module.""" + pass + + +class EmailSyntaxError(EmailNotValidError): + """Exception raised when an email address fails validation because of its form.""" + pass + + +class EmailUndeliverableError(EmailNotValidError): + """Exception raised when an email address fails validation because its domain name does not appear deliverable.""" + pass diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/email_validator/py.typed b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/email_validator/py.typed new file mode 100644 index 000000000..e69de29bb diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/email_validator/rfc_constants.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/email_validator/rfc_constants.py new file mode 100644 index 000000000..e93441b29 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/email_validator/rfc_constants.py @@ -0,0 +1,63 @@ +# These constants are defined by the email specifications. + +import re + +# Based on RFC 5322 3.2.3, these characters are permitted in email +# addresses (not taking into account internationalization) separated by dots: +ATEXT = r'a-zA-Z0-9_!#\$%&\'\*\+\-/=\?\^`\{\|\}~' +ATEXT_RE = re.compile('[.' + ATEXT + ']') # ATEXT plus dots +DOT_ATOM_TEXT = re.compile('[' + ATEXT + ']+(?:\\.[' + ATEXT + r']+)*\Z') + +# RFC 6531 3.3 extends the allowed characters in internationalized +# addresses to also include three specific ranges of UTF8 defined in +# RFC 3629 section 4, which appear to be the Unicode code points from +# U+0080 to U+10FFFF. +ATEXT_INTL = ATEXT + "\u0080-\U0010FFFF" +ATEXT_INTL_DOT_RE = re.compile('[.' + ATEXT_INTL + ']') # ATEXT_INTL plus dots +DOT_ATOM_TEXT_INTL = re.compile('[' + ATEXT_INTL + ']+(?:\\.[' + ATEXT_INTL + r']+)*\Z') + +# The domain part of the email address, after IDNA (ASCII) encoding, +# must also satisfy the requirements of RFC 952/RFC 1123 2.1 which +# restrict the allowed characters of hostnames further. +ATEXT_HOSTNAME_INTL = re.compile(r"[a-zA-Z0-9\-\." + "\u0080-\U0010FFFF" + "]") +HOSTNAME_LABEL = r'(?:(?:[a-zA-Z0-9][a-zA-Z0-9\-]*)?[a-zA-Z0-9])' +DOT_ATOM_TEXT_HOSTNAME = re.compile(HOSTNAME_LABEL + r'(?:\.' + HOSTNAME_LABEL + r')*\Z') +DOMAIN_NAME_REGEX = re.compile(r"[A-Za-z]\Z") # all TLDs currently end with a letter + +# Domain literal (RFC 5322 3.4.1) +DOMAIN_LITERAL_CHARS = re.compile(r"[\u0021-\u00FA\u005E-\u007E]") + +# Quoted-string local part (RFC 5321 4.1.2, internationalized by RFC 6531 3.3) +# The permitted characters in a quoted string are the characters in the range +# 32-126, except that quotes and (literal) backslashes can only appear when escaped +# by a backslash. When internationalized, UTF-8 strings are also permitted except +# the ASCII characters that are not previously permitted (see above). +# QUOTED_LOCAL_PART_ADDR = re.compile(r"^\"((?:[\u0020-\u0021\u0023-\u005B\u005D-\u007E]|\\[\u0020-\u007E])*)\"@(.*)") +QTEXT_INTL = re.compile(r"[\u0020-\u007E\u0080-\U0010FFFF]") + +# Length constants + +# RFC 3696 + errata 1003 + errata 1690 (https://www.rfc-editor.org/errata_search.php?rfc=3696&eid=1690) +# explains the maximum length of an email address is 254 octets based on RFC 5321 4.5.3.1.3. A +# maximum local part length is also given at RFC 5321 4.5.3.1.1. +# +# But RFC 5321 4.5.3.1 says that these (and other) limits are in a sense suggestions, and longer +# local parts have been seen in the wild. Consequntely, the local part length is only checked +# in "strict" mode. Although the email address maximum length is also somewhat of a suggestion, +# I don't like the idea of having no length checks performed, so I'm leaving that to always be +# checked. +EMAIL_MAX_LENGTH = 254 +LOCAL_PART_MAX_LENGTH = 64 + +# Although RFC 5321 4.5.3.1.2 gives a (suggested, see above) limit of 255 octets, RFC 1035 2.3.4 also +# imposes a length limit (255 octets). But per https://stackoverflow.com/questions/32290167/what-is-the-maximum-length-of-a-dns-name, +# two of those octets are taken up by the optional final dot and null root label. +DNS_LABEL_LENGTH_LIMIT = 63 # in "octets", RFC 1035 2.3.1 +DOMAIN_MAX_LENGTH = 253 # in "octets" as transmitted + +# RFC 2142 +CASE_INSENSITIVE_MAILBOX_NAMES = [ + 'info', 'marketing', 'sales', 'support', # section 3 + 'abuse', 'noc', 'security', # section 4 + 'postmaster', 'hostmaster', 'usenet', 'news', 'webmaster', 'www', 'uucp', 'ftp', # section 5 +] diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/email_validator/syntax.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/email_validator/syntax.py new file mode 100644 index 000000000..0b1c7b0eb --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/email_validator/syntax.py @@ -0,0 +1,822 @@ +from .exceptions import EmailSyntaxError +from .types import ValidatedEmail +from .rfc_constants import EMAIL_MAX_LENGTH, LOCAL_PART_MAX_LENGTH, DOMAIN_MAX_LENGTH, \ + DOT_ATOM_TEXT, DOT_ATOM_TEXT_INTL, ATEXT_RE, ATEXT_INTL_DOT_RE, ATEXT_HOSTNAME_INTL, QTEXT_INTL, \ + DNS_LABEL_LENGTH_LIMIT, DOT_ATOM_TEXT_HOSTNAME, DOMAIN_NAME_REGEX, DOMAIN_LITERAL_CHARS + +import re +import unicodedata +import idna # implements IDNA 2008; Python's codec is only IDNA 2003 +import ipaddress +from typing import Optional, Tuple, TypedDict, Union + + +def split_email(email: str) -> Tuple[Optional[str], str, str, bool]: + # Return the display name, unescaped local part, and domain part + # of the address, and whether the local part was quoted. If no + # display name was present and angle brackets do not surround + # the address, display name will be None; otherwise, it will be + # set to the display name or the empty string if there were + # angle brackets but no display name. + + # Typical email addresses have a single @-sign and no quote + # characters, but the awkward "quoted string" local part form + # (RFC 5321 4.1.2) allows @-signs and escaped quotes to appear + # in the local part if the local part is quoted. + + # A `display name ` format is also present in MIME messages + # (RFC 5322 3.4) and this format is also often recognized in + # mail UIs. It's not allowed in SMTP commands or in typical web + # login forms, but parsing it has been requested, so it's done + # here as a convenience. It's implemented in the spirit but not + # the letter of RFC 5322 3.4 because MIME messages allow newlines + # and comments as a part of the CFWS rule, but this is typically + # not allowed in mail UIs (although comment syntax was requested + # once too). + # + # Display names are either basic characters (the same basic characters + # permitted in email addresses, but periods are not allowed and spaces + # are allowed; see RFC 5322 Appendix A.1.2), or or a quoted string with + # the same rules as a quoted local part. (Multiple quoted strings might + # be allowed? Unclear.) Optional space (RFC 5322 3.4 CFWS) and then the + # email address follows in angle brackets. + # + # An initial quote is ambiguous between starting a display name or + # a quoted local part --- fun. + # + # We assume the input string is already stripped of leading and + # trailing CFWS. + + def split_string_at_unquoted_special(text: str, specials: Tuple[str, ...]) -> Tuple[str, str]: + # Split the string at the first character in specials (an @-sign + # or left angle bracket) that does not occur within quotes and + # is not followed by a Unicode combining character. + # If no special character is found, raise an error. + inside_quote = False + escaped = False + left_part = "" + for i, c in enumerate(text): + # < plus U+0338 (Combining Long Solidus Overlay) normalizes to + # ≮ U+226E (Not Less-Than), and it would be confusing to treat + # the < as the start of "" syntax in that case. Likewise, + # if anything combines with an @ or ", we should probably not + # treat it as a special character. + if unicodedata.normalize("NFC", text[i:])[0] != c: + left_part += c + + elif inside_quote: + left_part += c + if c == '\\' and not escaped: + escaped = True + elif c == '"' and not escaped: + # The only way to exit the quote is an unescaped quote. + inside_quote = False + escaped = False + else: + escaped = False + elif c == '"': + left_part += c + inside_quote = True + elif c in specials: + # When unquoted, stop before a special character. + break + else: + left_part += c + + # No special symbol found. The special symbols always + # include an at-sign, so this always indicates a missing + # at-sign. The other symbol is optional. + if len(left_part) == len(text): + # The full-width at-sign might occur in CJK contexts. + # We can't accept it because we only accept addresess + # that are actually valid. But if this is common we + # may want to consider accepting and normalizing full- + # width characters for the other special symbols (and + # full-width dot is already accepted in internationalized + # domains) with a new option. + # See https://news.ycombinator.com/item?id=42235268. + if "@" in text: + raise EmailSyntaxError("The email address has the \"full-width\" at-sign (@) character instead of a regular at-sign.") + + # Check another near-homoglyph for good measure because + # homoglyphs in place of required characters could be + # very confusing. We may want to consider checking for + # homoglyphs anywhere we look for a special symbol. + if "﹫" in text: + raise EmailSyntaxError('The email address has the "small commercial at" character instead of a regular at-sign.') + + raise EmailSyntaxError("An email address must have an @-sign.") + + # The right part is whatever is left. + right_part = text[len(left_part):] + + return left_part, right_part + + def unquote_quoted_string(text: str) -> Tuple[str, bool]: + # Remove surrounding quotes and unescape escaped backslashes + # and quotes. Escapes are parsed liberally. I think only + # backslashes and quotes can be escaped but we'll allow anything + # to be. + quoted = False + escaped = False + value = "" + for i, c in enumerate(text): + if quoted: + if escaped: + value += c + escaped = False + elif c == '\\': + escaped = True + elif c == '"': + if i != len(text) - 1: + raise EmailSyntaxError("Extra character(s) found after close quote: " + + ", ".join(safe_character_display(c) for c in text[i + 1:])) + break + else: + value += c + elif i == 0 and c == '"': + quoted = True + else: + value += c + + return value, quoted + + # Split the string at the first unquoted @-sign or left angle bracket. + left_part, right_part = split_string_at_unquoted_special(email, ("@", "<")) + + # If the right part starts with an angle bracket, + # then the left part is a display name and the rest + # of the right part up to the final right angle bracket + # is the email address, . + if right_part.startswith("<"): + # Remove space between the display name and angle bracket. + left_part = left_part.rstrip() + + # Unquote and unescape the display name. + display_name, display_name_quoted = unquote_quoted_string(left_part) + + # Check that only basic characters are present in a + # non-quoted display name. + if not display_name_quoted: + bad_chars = { + safe_character_display(c) + for c in display_name + if (not ATEXT_RE.match(c) and c != ' ') or c == '.' + } + if bad_chars: + raise EmailSyntaxError("The display name contains invalid characters when not quoted: " + ", ".join(sorted(bad_chars)) + ".") + + # Check for other unsafe characters. + check_unsafe_chars(display_name, allow_space=True) + + # Check that the right part ends with an angle bracket + # but allow spaces after it, I guess. + if ">" not in right_part: + raise EmailSyntaxError("An open angle bracket at the start of the email address has to be followed by a close angle bracket at the end.") + right_part = right_part.rstrip(" ") + if right_part[-1] != ">": + raise EmailSyntaxError("There can't be anything after the email address.") + + # Remove the initial and trailing angle brackets. + addr_spec = right_part[1:].rstrip(">") + + # Split the email address at the first unquoted @-sign. + local_part, domain_part = split_string_at_unquoted_special(addr_spec, ("@",)) + + # Otherwise there is no display name. The left part is the local + # part and the right part is the domain. + else: + display_name = None + local_part, domain_part = left_part, right_part + + if domain_part.startswith("@"): + domain_part = domain_part[1:] + + # Unquote the local part if it is quoted. + local_part, is_quoted_local_part = unquote_quoted_string(local_part) + + return display_name, local_part, domain_part, is_quoted_local_part + + +def get_length_reason(addr: str, limit: int) -> str: + """Helper function to return an error message related to invalid length.""" + diff = len(addr) - limit + suffix = "s" if diff > 1 else "" + return f"({diff} character{suffix} too many)" + + +def safe_character_display(c: str) -> str: + # Return safely displayable characters in quotes. + if c == '\\': + return f"\"{c}\"" # can't use repr because it escapes it + if unicodedata.category(c)[0] in ("L", "N", "P", "S"): + return repr(c) + + # Construct a hex string in case the unicode name doesn't exist. + if ord(c) < 0xFFFF: + h = f"U+{ord(c):04x}".upper() + else: + h = f"U+{ord(c):08x}".upper() + + # Return the character name or, if it has no name, the hex string. + return unicodedata.name(c, h) + + +class LocalPartValidationResult(TypedDict): + local_part: str + ascii_local_part: Optional[str] + smtputf8: bool + + +def validate_email_local_part(local: str, allow_smtputf8: bool = True, allow_empty_local: bool = False, + quoted_local_part: bool = False, strict: bool = False) -> LocalPartValidationResult: + """Validates the syntax of the local part of an email address.""" + + if len(local) == 0: + if not allow_empty_local: + raise EmailSyntaxError("There must be something before the @-sign.") + + # The caller allows an empty local part. Useful for validating certain + # Postfix aliases. + return { + "local_part": local, + "ascii_local_part": local, + "smtputf8": False, + } + + # Check the length of the local part by counting characters. + # (RFC 5321 4.5.3.1.1) + # We're checking the number of characters here. If the local part + # is ASCII-only, then that's the same as bytes (octets). If it's + # internationalized, then the UTF-8 encoding may be longer, but + # that may not be relevant. We will check the total address length + # instead. + if strict and len(local) > LOCAL_PART_MAX_LENGTH: + reason = get_length_reason(local, limit=LOCAL_PART_MAX_LENGTH) + raise EmailSyntaxError(f"The email address is too long before the @-sign {reason}.") + + # Check the local part against the non-internationalized regular expression. + # Most email addresses match this regex so it's probably fastest to check this first. + # (RFC 5322 3.2.3) + # All local parts matching the dot-atom rule are also valid as a quoted string + # so if it was originally quoted (quoted_local_part is True) and this regex matches, + # it's ok. + # (RFC 5321 4.1.2 / RFC 5322 3.2.4). + if DOT_ATOM_TEXT.match(local): + # It's valid. And since it's just the permitted ASCII characters, + # it's normalized and safe. If the local part was originally quoted, + # the quoting was unnecessary and it'll be returned as normalized to + # non-quoted form. + + # Return the local part and flag that SMTPUTF8 is not needed. + return { + "local_part": local, + "ascii_local_part": local, + "smtputf8": False, + } + + # The local part failed the basic dot-atom check. Try the extended character set + # for internationalized addresses. It's the same pattern but with additional + # characters permitted. + # RFC 6531 section 3.3. + valid: Optional[str] = None + requires_smtputf8 = False + if DOT_ATOM_TEXT_INTL.match(local): + # But international characters in the local part may not be permitted. + if not allow_smtputf8: + # Check for invalid characters against the non-internationalized + # permitted character set. + # (RFC 5322 3.2.3) + bad_chars = { + safe_character_display(c) + for c in local + if not ATEXT_RE.match(c) + } + if bad_chars: + raise EmailSyntaxError("Internationalized characters before the @-sign are not supported: " + ", ".join(sorted(bad_chars)) + ".") + + # Although the check above should always find something, fall back to this just in case. + raise EmailSyntaxError("Internationalized characters before the @-sign are not supported.") + + # It's valid. + valid = "dot-atom" + requires_smtputf8 = True + + # There are no dot-atom syntax restrictions on quoted local parts, so + # if it was originally quoted, it is probably valid. More characters + # are allowed, like @-signs, spaces, and quotes, and there are no + # restrictions on the placement of dots, as in dot-atom local parts. + elif quoted_local_part: + # Check for invalid characters in a quoted string local part. + # (RFC 5321 4.1.2. RFC 5322 lists additional permitted *obsolete* + # characters which are *not* allowed here. RFC 6531 section 3.3 + # extends the range to UTF8 strings.) + bad_chars = { + safe_character_display(c) + for c in local + if not QTEXT_INTL.match(c) + } + if bad_chars: + raise EmailSyntaxError("The email address contains invalid characters in quotes before the @-sign: " + ", ".join(sorted(bad_chars)) + ".") + + # See if any characters are outside of the ASCII range. + bad_chars = { + safe_character_display(c) + for c in local + if not (32 <= ord(c) <= 126) + } + if bad_chars: + requires_smtputf8 = True + + # International characters in the local part may not be permitted. + if not allow_smtputf8: + raise EmailSyntaxError("Internationalized characters before the @-sign are not supported: " + ", ".join(sorted(bad_chars)) + ".") + + # It's valid. + valid = "quoted" + + # If the local part matches the internationalized dot-atom form or was quoted, + # perform additional checks for Unicode strings. + if valid: + # Check that the local part is a valid, safe, and sensible Unicode string. + # Some of this may be redundant with the range U+0080 to U+10FFFF that is checked + # by DOT_ATOM_TEXT_INTL and QTEXT_INTL. Other characters may be permitted by the + # email specs, but they may not be valid, safe, or sensible Unicode strings. + # See the function for rationale. + check_unsafe_chars(local, allow_space=(valid == "quoted")) + + # Try encoding to UTF-8. Failure is possible with some characters like + # surrogate code points, but those are checked above. Still, we don't + # want to have an unhandled exception later. + try: + local.encode("utf8") + except ValueError as e: + raise EmailSyntaxError("The email address contains an invalid character.") from e + + # If this address passes only by the quoted string form, re-quote it + # and backslash-escape quotes and backslashes (removing any unnecessary + # escapes). Per RFC 5321 4.1.2, "all quoted forms MUST be treated as equivalent, + # and the sending system SHOULD transmit the form that uses the minimum quoting possible." + if valid == "quoted": + local = '"' + re.sub(r'(["\\])', r'\\\1', local) + '"' + + return { + "local_part": local, + "ascii_local_part": local if not requires_smtputf8 else None, + "smtputf8": requires_smtputf8, + } + + # It's not a valid local part. Let's find out why. + # (Since quoted local parts are all valid or handled above, these checks + # don't apply in those cases.) + + # Check for invalid characters. + # (RFC 5322 3.2.3, plus RFC 6531 3.3) + bad_chars = { + safe_character_display(c) + for c in local + if not ATEXT_INTL_DOT_RE.match(c) + } + if bad_chars: + raise EmailSyntaxError("The email address contains invalid characters before the @-sign: " + ", ".join(sorted(bad_chars)) + ".") + + # Check for dot errors imposted by the dot-atom rule. + # (RFC 5322 3.2.3) + check_dot_atom(local, 'An email address cannot start with a {}.', 'An email address cannot have a {} immediately before the @-sign.', is_hostname=False) + + # All of the reasons should already have been checked, but just in case + # we have a fallback message. + raise EmailSyntaxError("The email address contains invalid characters before the @-sign.") + + +def check_unsafe_chars(s: str, allow_space: bool = False) -> None: + # Check for unsafe characters or characters that would make the string + # invalid or non-sensible Unicode. + bad_chars = set() + for i, c in enumerate(s): + category = unicodedata.category(c) + if category[0] in ("L", "N", "P", "S"): + # Letters, numbers, punctuation, and symbols are permitted. + pass + elif category[0] == "M": + # Combining character in first position would combine with something + # outside of the email address if concatenated, so they are not safe. + # We also check if this occurs after the @-sign, which would not be + # sensible because it would modify the @-sign. + if i == 0: + bad_chars.add(c) + elif category == "Zs": + # Spaces outside of the ASCII range are not specifically disallowed in + # internationalized addresses as far as I can tell, but they violate + # the spirit of the non-internationalized specification that email + # addresses do not contain ASCII spaces when not quoted. Excluding + # ASCII spaces when not quoted is handled directly by the atom regex. + # + # In quoted-string local parts, spaces are explicitly permitted, and + # the ASCII space has category Zs, so we must allow it here, and we'll + # allow all Unicode spaces to be consistent. + if not allow_space: + bad_chars.add(c) + elif category[0] == "Z": + # The two line and paragraph separator characters (in categories Zl and Zp) + # are not specifically disallowed in internationalized addresses + # as far as I can tell, but they violate the spirit of the non-internationalized + # specification that email addresses do not contain line breaks when not quoted. + bad_chars.add(c) + elif category[0] == "C": + # Control, format, surrogate, private use, and unassigned code points (C) + # are all unsafe in various ways. Control and format characters can affect + # text rendering if the email address is concatenated with other text. + # Bidirectional format characters are unsafe, even if used properly, because + # they cause an email address to render as a different email address. + # Private use characters do not make sense for publicly deliverable + # email addresses. + bad_chars.add(c) + else: + # All categories should be handled above, but in case there is something new + # to the Unicode specification in the future, reject all other categories. + bad_chars.add(c) + if bad_chars: + raise EmailSyntaxError("The email address contains unsafe characters: " + + ", ".join(safe_character_display(c) for c in sorted(bad_chars)) + ".") + + +def check_dot_atom(label: str, start_descr: str, end_descr: str, is_hostname: bool) -> None: + # RFC 5322 3.2.3 + if label.endswith("."): + raise EmailSyntaxError(end_descr.format("period")) + if label.startswith("."): + raise EmailSyntaxError(start_descr.format("period")) + if ".." in label: + raise EmailSyntaxError("An email address cannot have two periods in a row.") + + if is_hostname: + # RFC 952 + if label.endswith("-"): + raise EmailSyntaxError(end_descr.format("hyphen")) + if label.startswith("-"): + raise EmailSyntaxError(start_descr.format("hyphen")) + if ".-" in label or "-." in label: + raise EmailSyntaxError("An email address cannot have a period and a hyphen next to each other.") + + +def uts46_valid_char(char: str) -> bool: + # By exhaustively searching for characters rejected by + # for c in (chr(i) for i in range(0x110000)): + # idna.uts46_remap(c, std3_rules=False, transitional=False) + # I found the following rules are pretty close. + c = ord(char) + if 0x80 <= c <= 0x9f: + # 8-bit ASCII range. + return False + elif ((0x2010 <= c <= 0x2060 and not (0x2024 <= c <= 0x2026) and not (0x2028 <= c <= 0x202E)) + or c in (0x00AD, 0x2064, 0xFF0E) + or 0x200B <= c <= 0x200D + or 0x1BCA0 <= c <= 0x1BCA3): + # Characters that are permitted but fall into one of the + # tests below. + return True + elif unicodedata.category(chr(c)) in ("Cf", "Cn", "Co", "Cs", "Zs", "Zl", "Zp"): + # There are a bunch of Zs characters including regular space + # that are allowed by UTS46 but are not allowed in domain + # names anyway. + # + # There are some Cn (unassigned) characters that the idna + # package doesn't reject but we can, I think. + return False + elif "002E" in unicodedata.decomposition(chr(c)).split(" "): + # Characters that decompose into a sequence with a dot. + return False + return True + + +class DomainNameValidationResult(TypedDict): + ascii_domain: str + domain: str + + +def validate_email_domain_name(domain: str, test_environment: bool = False, globally_deliverable: bool = True) -> DomainNameValidationResult: + """Validates the syntax of the domain part of an email address.""" + + # Check for invalid characters. + # (RFC 952 plus RFC 6531 section 3.3 for internationalized addresses) + bad_chars = { + safe_character_display(c) + for c in domain + if not ATEXT_HOSTNAME_INTL.match(c) + } + if bad_chars: + raise EmailSyntaxError("The part after the @-sign contains invalid characters: " + ", ".join(sorted(bad_chars)) + ".") + + # Check for unsafe characters. + # Some of this may be redundant with the range U+0080 to U+10FFFF that is checked + # by DOT_ATOM_TEXT_INTL. Other characters may be permitted by the email specs, but + # they may not be valid, safe, or sensible Unicode strings. + check_unsafe_chars(domain) + + # Reject characters that would be rejected by UTS-46 normalization next but + # with an error message under our control. + bad_chars = { + safe_character_display(c) for c in domain + if not uts46_valid_char(c) + } + if bad_chars: + raise EmailSyntaxError("The part after the @-sign contains invalid characters: " + ", ".join(sorted(bad_chars)) + ".") + + # Perform UTS-46 normalization, which includes casefolding, NFC normalization, + # and converting all label separators (the period/full stop, fullwidth full stop, + # ideographic full stop, and halfwidth ideographic full stop) to regular dots. + # It will also raise an exception if there is an invalid character in the input, + # such as "⒈" which is invalid because it would expand to include a dot and + # U+1FEF which normalizes to a backtick, which is not an allowed hostname character. + # Since several characters *are* normalized to a dot, this has to come before + # checks related to dots, like check_dot_atom which comes next. + original_domain = domain + try: + domain = idna.uts46_remap(domain, std3_rules=False, transitional=False) + except idna.IDNAError as e: + raise EmailSyntaxError(f"The part after the @-sign contains invalid characters ({e}).") from e + + # Check for invalid characters after Unicode normalization which are not caught + # by uts46_remap (see tests for examples). + bad_chars = { + safe_character_display(c) + for c in domain + if not ATEXT_HOSTNAME_INTL.match(c) + } + if bad_chars: + raise EmailSyntaxError("The part after the @-sign contains invalid characters after Unicode normalization: " + ", ".join(sorted(bad_chars)) + ".") + + # The domain part is made up dot-separated "labels." Each label must + # have at least one character and cannot start or end with dashes, which + # means there are some surprising restrictions on periods and dashes. + # Check that before we do IDNA encoding because the IDNA library gives + # unfriendly errors for these cases, but after UTS-46 normalization because + # it can insert periods and hyphens (from fullwidth characters). + # (RFC 952, RFC 1123 2.1, RFC 5322 3.2.3) + check_dot_atom(domain, 'An email address cannot have a {} immediately after the @-sign.', 'An email address cannot end with a {}.', is_hostname=True) + + # Check for RFC 5890's invalid R-LDH labels, which are labels that start + # with two characters other than "xn" and two dashes. + for label in domain.split("."): + if re.match(r"(?!xn)..--", label, re.I): + raise EmailSyntaxError("An email address cannot have two letters followed by two dashes immediately after the @-sign or after a period, except Punycode.") + + if DOT_ATOM_TEXT_HOSTNAME.match(domain): + # This is a valid non-internationalized domain. + ascii_domain = domain + else: + # If international characters are present in the domain name, convert + # the domain to IDNA ASCII. If internationalized characters are present, + # the MTA must either support SMTPUTF8 or the mail client must convert the + # domain name to IDNA before submission. + # + # For ASCII-only domains, the transformation does nothing and is safe to + # apply. However, to ensure we don't rely on the idna library for basic + # syntax checks, we don't use it if it's not needed. + # + # idna.encode also checks the domain name length after encoding but it + # doesn't give a nice error, so we call the underlying idna.alabel method + # directly. idna.alabel checks label length and doesn't give great messages, + # but we can't easily go to lower level methods. + try: + ascii_domain = ".".join( + idna.alabel(label).decode("ascii") + for label in domain.split(".") + ) + except idna.IDNAError as e: + # Some errors would have already been raised by idna.uts46_remap. + raise EmailSyntaxError(f"The part after the @-sign is invalid ({e}).") from e + + # Check the syntax of the string returned by idna.encode. + # It should never fail. + if not DOT_ATOM_TEXT_HOSTNAME.match(ascii_domain): + raise EmailSyntaxError("The email address contains invalid characters after the @-sign after IDNA encoding.") + + # Check the length of the domain name in bytes. + # (RFC 1035 2.3.4 and RFC 5321 4.5.3.1.2) + # We're checking the number of bytes ("octets") here, which can be much + # higher than the number of characters in internationalized domains, + # on the assumption that the domain may be transmitted without SMTPUTF8 + # as IDNA ASCII. (This is also checked by idna.encode, so this exception + # is never reached for internationalized domains.) + if len(ascii_domain) > DOMAIN_MAX_LENGTH: + if ascii_domain == original_domain: + reason = get_length_reason(ascii_domain, limit=DOMAIN_MAX_LENGTH) + raise EmailSyntaxError(f"The email address is too long after the @-sign {reason}.") + else: + diff = len(ascii_domain) - DOMAIN_MAX_LENGTH + s = "" if diff == 1 else "s" + raise EmailSyntaxError(f"The email address is too long after the @-sign ({diff} byte{s} too many after IDNA encoding).") + + # Also check the label length limit. + # (RFC 1035 2.3.1) + for label in ascii_domain.split("."): + if len(label) > DNS_LABEL_LENGTH_LIMIT: + reason = get_length_reason(label, limit=DNS_LABEL_LENGTH_LIMIT) + raise EmailSyntaxError(f"After the @-sign, periods cannot be separated by so many characters {reason}.") + + if globally_deliverable: + # All publicly deliverable addresses have domain names with at least + # one period, at least for gTLDs created since 2013 (per the ICANN Board + # New gTLD Program Committee, https://www.icann.org/en/announcements/details/new-gtld-dotless-domain-names-prohibited-30-8-2013-en). + # We'll consider the lack of a period a syntax error + # since that will match people's sense of what an email address looks + # like. We'll skip this in test environments to allow '@test' email + # addresses. + if "." not in ascii_domain and not (ascii_domain == "test" and test_environment): + raise EmailSyntaxError("The part after the @-sign is not valid. It should have a period.") + + # We also know that all TLDs currently end with a letter. + if not DOMAIN_NAME_REGEX.search(ascii_domain): + raise EmailSyntaxError("The part after the @-sign is not valid. It is not within a valid top-level domain.") + + # Check special-use and reserved domain names. + # Some might fail DNS-based deliverability checks, but that + # can be turned off, so we should fail them all sooner. + # See the references in __init__.py. + from . import SPECIAL_USE_DOMAIN_NAMES + for d in SPECIAL_USE_DOMAIN_NAMES: + # See the note near the definition of SPECIAL_USE_DOMAIN_NAMES. + if d == "test" and test_environment: + continue + + if ascii_domain == d or ascii_domain.endswith("." + d): + raise EmailSyntaxError("The part after the @-sign is a special-use or reserved name that cannot be used with email.") + + # We may have been given an IDNA ASCII domain to begin with. Check + # that the domain actually conforms to IDNA. It could look like IDNA + # but not be actual IDNA. For ASCII-only domains, the conversion out + # of IDNA just gives the same thing back. + # + # This gives us the canonical internationalized form of the domain, + # which we return to the caller as a part of the normalized email + # address. + try: + domain_i18n = idna.decode(ascii_domain.encode('ascii')) + except idna.IDNAError as e: + raise EmailSyntaxError(f"The part after the @-sign is not valid IDNA ({e}).") from e + + # Check that this normalized domain name has not somehow become + # an invalid domain name. All of the checks before this point + # using the idna package probably guarantee that we now have + # a valid international domain name in most respects. But it + # doesn't hurt to re-apply some tests to be sure. See the similar + # tests above. + + # Check for invalid and unsafe characters. We have no test + # case for this. + bad_chars = { + safe_character_display(c) + for c in domain_i18n + if not ATEXT_HOSTNAME_INTL.match(c) + } + if bad_chars: + raise EmailSyntaxError("The part after the @-sign contains invalid characters: " + ", ".join(sorted(bad_chars)) + ".") + check_unsafe_chars(domain_i18n) + + # Check that it can be encoded back to IDNA ASCII. We have no test + # case for this. + try: + idna.encode(domain_i18n) + except idna.IDNAError as e: + raise EmailSyntaxError(f"The part after the @-sign became invalid after normalizing to international characters ({e}).") from e + + # Return the IDNA ASCII-encoded form of the domain, which is how it + # would be transmitted on the wire (except when used with SMTPUTF8 + # possibly), as well as the canonical Unicode form of the domain, + # which is better for display purposes. This should also take care + # of RFC 6532 section 3.1's suggestion to apply Unicode NFC + # normalization to addresses. + return { + "ascii_domain": ascii_domain, + "domain": domain_i18n, + } + + +def validate_email_length(addrinfo: ValidatedEmail) -> None: + # There are three forms of the email address whose length must be checked: + # + # 1) The original email address string. Since callers may continue to use + # this string, even though we recommend using the normalized form, we + # should not pass validation when the original input is not valid. This + # form is checked first because it is the original input. + # 2) The normalized email address. We perform Unicode NFC normalization of + # the local part, we normalize the domain to internationalized characters + # (if originally IDNA ASCII) which also includes Unicode normalization, + # and we may remove quotes in quoted local parts. We recommend that + # callers use this string, so it must be valid. + # 3) The email address with the IDNA ASCII representation of the domain + # name, since this string may be used with email stacks that don't + # support UTF-8. Since this is the least likely to be used by callers, + # it is checked last. Note that ascii_email will only be set if the + # local part is ASCII, but conceivably the caller may combine a + # internationalized local part with an ASCII domain, so we check this + # on that combination also. Since we only return the normalized local + # part, we use that (and not the unnormalized local part). + # + # In all cases, the length is checked in UTF-8 because the SMTPUTF8 + # extension to SMTP validates the length in bytes. + + addresses_to_check = [ + (addrinfo.original, None), + (addrinfo.normalized, "after normalization"), + ((addrinfo.ascii_local_part or addrinfo.local_part or "") + "@" + addrinfo.ascii_domain, "when the part after the @-sign is converted to IDNA ASCII"), + ] + + for addr, reason in addresses_to_check: + addr_len = len(addr) + addr_utf8_len = len(addr.encode("utf8")) + diff = addr_utf8_len - EMAIL_MAX_LENGTH + if diff > 0: + if reason is None and addr_len == addr_utf8_len: + # If there is no normalization or transcoding, + # we can give a simple count of the number of + # characters over the limit. + reason = get_length_reason(addr, limit=EMAIL_MAX_LENGTH) + elif reason is None: + # If there is no normalization but there is + # some transcoding to UTF-8, we can compute + # the minimum number of characters over the + # limit by dividing the number of bytes over + # the limit by the maximum number of bytes + # per character. + mbpc = max(len(c.encode("utf8")) for c in addr) + mchars = max(1, diff // mbpc) + suffix = "s" if diff > 1 else "" + if mchars == diff: + reason = f"({diff} character{suffix} too many)" + else: + reason = f"({mchars}-{diff} character{suffix} too many)" + else: + # Since there is normalization, the number of + # characters in the input that need to change is + # impossible to know. + suffix = "s" if diff > 1 else "" + reason += f" ({diff} byte{suffix} too many)" + raise EmailSyntaxError(f"The email address is too long {reason}.") + + +class DomainLiteralValidationResult(TypedDict): + domain_address: Union[ipaddress.IPv4Address, ipaddress.IPv6Address] + domain: str + + +def validate_email_domain_literal(domain_literal: str) -> DomainLiteralValidationResult: + # This is obscure domain-literal syntax. Parse it and return + # a compressed/normalized address. + # RFC 5321 4.1.3 and RFC 5322 3.4.1. + + addr: Union[ipaddress.IPv4Address, ipaddress.IPv6Address] + + # Try to parse the domain literal as an IPv4 address. + # There is no tag for IPv4 addresses, so we can never + # be sure if the user intends an IPv4 address. + if re.match(r"^[0-9\.]+$", domain_literal): + try: + addr = ipaddress.IPv4Address(domain_literal) + except ValueError as e: + raise EmailSyntaxError(f"The address in brackets after the @-sign is not valid: It is not an IPv4 address ({e}) or is missing an address literal tag.") from e + + # Return the IPv4Address object and the domain back unchanged. + return { + "domain_address": addr, + "domain": f"[{addr}]", + } + + # If it begins with "IPv6:" it's an IPv6 address. + if domain_literal.startswith("IPv6:"): + try: + addr = ipaddress.IPv6Address(domain_literal[5:]) + except ValueError as e: + raise EmailSyntaxError(f"The IPv6 address in brackets after the @-sign is not valid ({e}).") from e + + # Return the IPv6Address object and construct a normalized + # domain literal. + return { + "domain_address": addr, + "domain": f"[IPv6:{addr.compressed}]", + } + + # Nothing else is valid. + + if ":" not in domain_literal: + raise EmailSyntaxError("The part after the @-sign in brackets is not an IPv4 address and has no address literal tag.") + + # The tag (the part before the colon) has character restrictions, + # but since it must come from a registry of tags (in which only "IPv6" is defined), + # there's no need to check the syntax of the tag. See RFC 5321 4.1.2. + + # Check for permitted ASCII characters. This actually doesn't matter + # since there will be an exception after anyway. + bad_chars = { + safe_character_display(c) + for c in domain_literal + if not DOMAIN_LITERAL_CHARS.match(c) + } + if bad_chars: + raise EmailSyntaxError("The part after the @-sign contains invalid characters in brackets: " + ", ".join(sorted(bad_chars)) + ".") + + # There are no other domain literal tags. + # https://www.iana.org/assignments/address-literal-tags/address-literal-tags.xhtml + raise EmailSyntaxError("The part after the @-sign contains an invalid address literal tag in brackets.") diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/email_validator/types.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/email_validator/types.py new file mode 100644 index 000000000..1df60ff90 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/email_validator/types.py @@ -0,0 +1,126 @@ +import warnings +from typing import Any, Dict, List, Optional, Tuple, Union + + +class ValidatedEmail: + """The validate_email function returns objects of this type holding the normalized form of the email address + and other information.""" + + """The email address that was passed to validate_email. (If passed as bytes, this will be a string.)""" + original: str + + """The normalized email address, which should always be used in preference to the original address. + The normalized address converts an IDNA ASCII domain name to Unicode, if possible, and performs + Unicode normalization on the local part and on the domain (if originally Unicode). It is the + concatenation of the local_part and domain attributes, separated by an @-sign.""" + normalized: str + + """The local part of the email address after Unicode normalization.""" + local_part: str + + """The domain part of the email address after Unicode normalization or conversion to + Unicode from IDNA ascii.""" + domain: str + + """If the domain part is a domain literal, the IPv4Address or IPv6Address object.""" + domain_address: object + + """If not None, a form of the email address that uses 7-bit ASCII characters only.""" + ascii_email: Optional[str] + + """If not None, the local part of the email address using 7-bit ASCII characters only.""" + ascii_local_part: Optional[str] + + """A form of the domain name that uses 7-bit ASCII characters only.""" + ascii_domain: str + + """If True, the SMTPUTF8 feature of your mail relay will be required to transmit messages + to this address. This flag is True just when ascii_local_part is missing. Otherwise it + is False.""" + smtputf8: bool + + """If a deliverability check is performed and if it succeeds, a list of (priority, domain) + tuples of MX records specified in the DNS for the domain.""" + mx: List[Tuple[int, str]] + + """If no MX records are actually specified in DNS and instead are inferred, through an obsolete + mechanism, from A or AAAA records, the value is the type of DNS record used instead (`A` or `AAAA`).""" + mx_fallback_type: Optional[str] + + """The display name in the original input text, unquoted and unescaped, or None.""" + display_name: Optional[str] + + def __repr__(self) -> str: + return f"" + + """For backwards compatibility, support old field names.""" + def __getattr__(self, key: str) -> str: + if key == "original_email": + return self.original + if key == "email": + return self.normalized + raise AttributeError(key) + + @property + def email(self) -> str: + warnings.warn("ValidatedEmail.email is deprecated and will be removed, use ValidatedEmail.normalized instead", DeprecationWarning) + return self.normalized + + """For backwards compatibility, some fields are also exposed through a dict-like interface. Note + that some of the names changed when they became attributes.""" + def __getitem__(self, key: str) -> Union[Optional[str], bool, List[Tuple[int, str]]]: + warnings.warn("dict-like access to the return value of validate_email is deprecated and may not be supported in the future.", DeprecationWarning, stacklevel=2) + if key == "email": + return self.normalized + if key == "email_ascii": + return self.ascii_email + if key == "local": + return self.local_part + if key == "domain": + return self.ascii_domain + if key == "domain_i18n": + return self.domain + if key == "smtputf8": + return self.smtputf8 + if key == "mx": + return self.mx + if key == "mx-fallback": + return self.mx_fallback_type + raise KeyError() + + """Tests use this.""" + def __eq__(self, other: object) -> bool: + if not isinstance(other, ValidatedEmail): + return False + return ( + self.normalized == other.normalized + and self.local_part == other.local_part + and self.domain == other.domain + and getattr(self, 'ascii_email', None) == getattr(other, 'ascii_email', None) + and getattr(self, 'ascii_local_part', None) == getattr(other, 'ascii_local_part', None) + and getattr(self, 'ascii_domain', None) == getattr(other, 'ascii_domain', None) + and self.smtputf8 == other.smtputf8 + and repr(sorted(self.mx) if getattr(self, 'mx', None) else None) + == repr(sorted(other.mx) if getattr(other, 'mx', None) else None) + and getattr(self, 'mx_fallback_type', None) == getattr(other, 'mx_fallback_type', None) + and getattr(self, 'display_name', None) == getattr(other, 'display_name', None) + ) + + """This helps producing the README.""" + def as_constructor(self) -> str: + return "ValidatedEmail(" \ + + ",".join(f"\n {key}={repr(getattr(self, key))}" + for key in ('normalized', 'local_part', 'domain', + 'ascii_email', 'ascii_local_part', 'ascii_domain', + 'smtputf8', 'mx', 'mx_fallback_type', + 'display_name') + if hasattr(self, key) + ) \ + + ")" + + """Convenience method for accessing ValidatedEmail as a dict""" + def as_dict(self) -> Dict[str, Any]: + d = self.__dict__ + if d.get('domain_address'): + d['domain_address'] = repr(d['domain_address']) + return d diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/email_validator/validate_email.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/email_validator/validate_email.py new file mode 100644 index 000000000..ae5d96352 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/email_validator/validate_email.py @@ -0,0 +1,209 @@ +from typing import Optional, Union, TYPE_CHECKING +import unicodedata + +from .exceptions import EmailSyntaxError +from .types import ValidatedEmail +from .syntax import split_email, validate_email_local_part, validate_email_domain_name, validate_email_domain_literal, validate_email_length +from .rfc_constants import CASE_INSENSITIVE_MAILBOX_NAMES + +if TYPE_CHECKING: + import dns.resolver + _Resolver = dns.resolver.Resolver +else: + _Resolver = object + + +def validate_email( + email: Union[str, bytes], + /, # prior arguments are positional-only + *, # subsequent arguments are keyword-only + allow_smtputf8: Optional[bool] = None, + allow_empty_local: Optional[bool] = None, + allow_quoted_local: Optional[bool] = None, + allow_domain_literal: Optional[bool] = None, + allow_display_name: Optional[bool] = None, + strict: Optional[bool] = None, + check_deliverability: Optional[bool] = None, + test_environment: Optional[bool] = None, + globally_deliverable: Optional[bool] = None, + timeout: Optional[int] = None, + dns_resolver: Optional[_Resolver] = None +) -> ValidatedEmail: + """ + Given an email address, and some options, returns a ValidatedEmail instance + with information about the address if it is valid or, if the address is not + valid, raises an EmailNotValidError. This is the main function of the module. + """ + + # Fill in default values of arguments. + from . import ALLOW_SMTPUTF8, ALLOW_EMPTY_LOCAL, ALLOW_QUOTED_LOCAL, ALLOW_DOMAIN_LITERAL, ALLOW_DISPLAY_NAME, \ + STRICT, GLOBALLY_DELIVERABLE, CHECK_DELIVERABILITY, TEST_ENVIRONMENT, DEFAULT_TIMEOUT + if allow_smtputf8 is None: + allow_smtputf8 = ALLOW_SMTPUTF8 + if allow_empty_local is None: + allow_empty_local = ALLOW_EMPTY_LOCAL + if allow_quoted_local is None: + allow_quoted_local = ALLOW_QUOTED_LOCAL + if allow_domain_literal is None: + allow_domain_literal = ALLOW_DOMAIN_LITERAL + if allow_display_name is None: + allow_display_name = ALLOW_DISPLAY_NAME + if strict is None: + strict = STRICT + if check_deliverability is None: + check_deliverability = CHECK_DELIVERABILITY + if test_environment is None: + test_environment = TEST_ENVIRONMENT + if globally_deliverable is None: + globally_deliverable = GLOBALLY_DELIVERABLE + if timeout is None and dns_resolver is None: + timeout = DEFAULT_TIMEOUT + + if isinstance(email, str): + pass + elif isinstance(email, bytes): + # Allow email to be a bytes instance as if it is what + # will be transmitted on the wire. But assume SMTPUTF8 + # is unavailable, so it must be ASCII. + try: + email = email.decode("ascii") + except ValueError as e: + raise EmailSyntaxError("The email address is not valid ASCII.") from e + else: + raise TypeError("email must be str or bytes") + + # Split the address into the display name (or None), the local part + # (before the @-sign), and the domain part (after the @-sign). + # Normally, there is only one @-sign. But the awkward "quoted string" + # local part form (RFC 5321 4.1.2) allows @-signs in the local + # part if the local part is quoted. + display_name, local_part, domain_part, is_quoted_local_part \ + = split_email(email) + + if display_name: + # UTS #39 3.3 Email Security Profiles for Identifiers requires + # display names (incorrectly called "quoted-string-part" there) + # to be NFC normalized. Since these are not a part of what we + # are really validating, we won't check that the input was NFC + # normalized, but we'll normalize in output. + display_name = unicodedata.normalize("NFC", display_name) + + # Collect return values in this instance. + ret = ValidatedEmail() + ret.original = ((local_part if not is_quoted_local_part + else ('"' + local_part + '"')) + + "@" + domain_part) # drop the display name, if any, for email length tests at the end + ret.display_name = display_name + + # Validate the email address's local part syntax and get a normalized form. + # If the original address was quoted and the decoded local part is a valid + # unquoted local part, then we'll get back a normalized (unescaped) local + # part. + local_part_info = validate_email_local_part(local_part, + allow_smtputf8=allow_smtputf8, + allow_empty_local=allow_empty_local, + quoted_local_part=is_quoted_local_part, + strict=strict) + ret.local_part = local_part_info["local_part"] + ret.ascii_local_part = local_part_info["ascii_local_part"] + ret.smtputf8 = local_part_info["smtputf8"] + + # RFC 6532 section 3.1 says that Unicode NFC normalization should be applied, + # so we'll return the NFC-normalized local part. Since the caller may use that + # string in place of the original string, ensure it is also valid. + # + # UTS #39 3.3 Email Security Profiles for Identifiers requires local parts + # to be NFKC normalized, which loses some information in characters that can + # be decomposed. We might want to consider applying NFKC normalization, but + # we can't make the change easily because it would break database lookups + # for any caller that put a normalized address from a previous version of + # this library. (UTS #39 seems to require that the *input* be NKFC normalized + # and has other requirements that are hard to check without additional Unicode + # data, and I don't know whether the rules really apply in the wild.) + normalized_local_part = unicodedata.normalize("NFC", ret.local_part) + if normalized_local_part != ret.local_part: + try: + validate_email_local_part(normalized_local_part, + allow_smtputf8=allow_smtputf8, + allow_empty_local=allow_empty_local, + quoted_local_part=is_quoted_local_part, + strict=strict) + except EmailSyntaxError as e: + raise EmailSyntaxError("After Unicode normalization: " + str(e)) from e + ret.local_part = normalized_local_part + + # If a quoted local part isn't allowed but is present, now raise an exception. + # This is done after any exceptions raised by validate_email_local_part so + # that mandatory checks have highest precedence. + if is_quoted_local_part and not allow_quoted_local: + raise EmailSyntaxError("Quoting the part before the @-sign is not allowed here.") + + # Some local parts are required to be case-insensitive, so we should normalize + # to lowercase. + # RFC 2142 + if ret.ascii_local_part is not None \ + and ret.ascii_local_part.lower() in CASE_INSENSITIVE_MAILBOX_NAMES \ + and ret.local_part is not None: + ret.ascii_local_part = ret.ascii_local_part.lower() + ret.local_part = ret.local_part.lower() + + # Validate the email address's domain part syntax and get a normalized form. + is_domain_literal = False + if len(domain_part) == 0: + raise EmailSyntaxError("There must be something after the @-sign.") + + elif domain_part.startswith("[") and domain_part.endswith("]"): + # Parse the address in the domain literal and get back a normalized domain. + domain_literal_info = validate_email_domain_literal(domain_part[1:-1]) + if not allow_domain_literal: + raise EmailSyntaxError("A bracketed IP address after the @-sign is not allowed here.") + ret.domain = domain_literal_info["domain"] + ret.ascii_domain = domain_literal_info["domain"] # Domain literals are always ASCII. + ret.domain_address = domain_literal_info["domain_address"] + is_domain_literal = True # Prevent deliverability checks. + + else: + # Check the syntax of the domain and get back a normalized + # internationalized and ASCII form. + domain_name_info = validate_email_domain_name(domain_part, test_environment=test_environment, globally_deliverable=globally_deliverable) + ret.domain = domain_name_info["domain"] + ret.ascii_domain = domain_name_info["ascii_domain"] + + # Construct the complete normalized form. + ret.normalized = ret.local_part + "@" + ret.domain + + # If the email address has an ASCII form, add it. + if not ret.smtputf8: + if not ret.ascii_domain: + raise Exception("Missing ASCII domain.") + ret.ascii_email = (ret.ascii_local_part or "") + "@" + ret.ascii_domain + else: + ret.ascii_email = None + + # Check the length of the address. + validate_email_length(ret) + + # Check that a display name is permitted. It's the last syntax check + # because we always check against optional parsing features last. + if display_name is not None and not allow_display_name: + raise EmailSyntaxError("A display name and angle brackets around the email address are not permitted here.") + + if check_deliverability and not test_environment: + # Validate the email address's deliverability using DNS + # and update the returned ValidatedEmail object with metadata. + + if is_domain_literal: + # There is nothing to check --- skip deliverability checks. + return ret + + # Lazy load `deliverability` as it is slow to import (due to dns.resolver) + from .deliverability import validate_email_deliverability + deliverability_info = validate_email_deliverability( + ret.ascii_domain, ret.domain, timeout, dns_resolver + ) + mx = deliverability_info.get("mx") + if mx is not None: + ret.mx = mx + ret.mx_fallback_type = deliverability_info.get("mx_fallback_type") + + return ret diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/email_validator/version.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/email_validator/version.py new file mode 100644 index 000000000..55e470907 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/email_validator/version.py @@ -0,0 +1 @@ +__version__ = "2.3.0" diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask-3.1.3.dist-info/INSTALLER b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask-3.1.3.dist-info/INSTALLER new file mode 100644 index 000000000..a1b589e38 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask-3.1.3.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask-3.1.3.dist-info/METADATA b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask-3.1.3.dist-info/METADATA new file mode 100644 index 000000000..9d8623c9a --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask-3.1.3.dist-info/METADATA @@ -0,0 +1,91 @@ +Metadata-Version: 2.4 +Name: Flask +Version: 3.1.3 +Summary: A simple framework for building complex web applications. +Maintainer-email: Pallets +Requires-Python: >=3.9 +Description-Content-Type: text/markdown +License-Expression: BSD-3-Clause +Classifier: Development Status :: 5 - Production/Stable +Classifier: Environment :: Web Environment +Classifier: Framework :: Flask +Classifier: Intended Audience :: Developers +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: Python +Classifier: Topic :: Internet :: WWW/HTTP :: Dynamic Content +Classifier: Topic :: Internet :: WWW/HTTP :: WSGI +Classifier: Topic :: Internet :: WWW/HTTP :: WSGI :: Application +Classifier: Topic :: Software Development :: Libraries :: Application Frameworks +Classifier: Typing :: Typed +License-File: LICENSE.txt +Requires-Dist: blinker>=1.9.0 +Requires-Dist: click>=8.1.3 +Requires-Dist: importlib-metadata>=3.6.0; python_version < '3.10' +Requires-Dist: itsdangerous>=2.2.0 +Requires-Dist: jinja2>=3.1.2 +Requires-Dist: markupsafe>=2.1.1 +Requires-Dist: werkzeug>=3.1.0 +Requires-Dist: asgiref>=3.2 ; extra == "async" +Requires-Dist: python-dotenv ; extra == "dotenv" +Project-URL: Changes, https://flask.palletsprojects.com/page/changes/ +Project-URL: Chat, https://discord.gg/pallets +Project-URL: Documentation, https://flask.palletsprojects.com/ +Project-URL: Donate, https://palletsprojects.com/donate +Project-URL: Source, https://github.com/pallets/flask/ +Provides-Extra: async +Provides-Extra: dotenv + +
+ +# Flask + +Flask is a lightweight [WSGI] web application framework. It is designed +to make getting started quick and easy, with the ability to scale up to +complex applications. It began as a simple wrapper around [Werkzeug] +and [Jinja], and has become one of the most popular Python web +application frameworks. + +Flask offers suggestions, but doesn't enforce any dependencies or +project layout. It is up to the developer to choose the tools and +libraries they want to use. There are many extensions provided by the +community that make adding new functionality easy. + +[WSGI]: https://wsgi.readthedocs.io/ +[Werkzeug]: https://werkzeug.palletsprojects.com/ +[Jinja]: https://jinja.palletsprojects.com/ + +## A Simple Example + +```python +# save this as app.py +from flask import Flask + +app = Flask(__name__) + +@app.route("/") +def hello(): + return "Hello, World!" +``` + +``` +$ flask run + * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit) +``` + +## Donate + +The Pallets organization develops and supports Flask and the libraries +it uses. In order to grow the community of contributors and users, and +allow the maintainers to devote more time to the projects, [please +donate today]. + +[please donate today]: https://palletsprojects.com/donate + +## Contributing + +See our [detailed contributing documentation][contrib] for many ways to +contribute, including reporting issues, requesting features, asking or answering +questions, and making PRs. + +[contrib]: https://palletsprojects.com/contributing/ + diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask-3.1.3.dist-info/RECORD b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask-3.1.3.dist-info/RECORD new file mode 100644 index 000000000..d540a575b --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask-3.1.3.dist-info/RECORD @@ -0,0 +1,58 @@ +../../../bin/flask,sha256=_FHwS16Y0aeIIGAjPyp9CwYFncxy2ie2lo4y7ARo2vM,287 +flask-3.1.3.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +flask-3.1.3.dist-info/METADATA,sha256=qmdg7W9UVwRHTXBzPkpjp_FIHjdpc-3IlqE9AqciTHw,3167 +flask-3.1.3.dist-info/RECORD,, +flask-3.1.3.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +flask-3.1.3.dist-info/WHEEL,sha256=G2gURzTEtmeR8nrdXUJfNiB3VYVxigPQ-bEQujpNiNs,82 +flask-3.1.3.dist-info/entry_points.txt,sha256=bBP7hTOS5fz9zLtC7sPofBZAlMkEvBxu7KqS6l5lvc4,40 +flask-3.1.3.dist-info/licenses/LICENSE.txt,sha256=SJqOEQhQntmKN7uYPhHg9-HTHwvY-Zp5yESOf_N9B-o,1475 +flask/__init__.py,sha256=mHvJN9Swtl1RDtjCqCIYyIniK_SZ_l_hqUynOzgpJ9o,2701 +flask/__main__.py,sha256=bYt9eEaoRQWdejEHFD8REx9jxVEdZptECFsV7F49Ink,30 +flask/__pycache__/__init__.cpython-312.pyc,, +flask/__pycache__/__main__.cpython-312.pyc,, +flask/__pycache__/app.cpython-312.pyc,, +flask/__pycache__/blueprints.cpython-312.pyc,, +flask/__pycache__/cli.cpython-312.pyc,, +flask/__pycache__/config.cpython-312.pyc,, +flask/__pycache__/ctx.cpython-312.pyc,, +flask/__pycache__/debughelpers.cpython-312.pyc,, +flask/__pycache__/globals.cpython-312.pyc,, +flask/__pycache__/helpers.cpython-312.pyc,, +flask/__pycache__/logging.cpython-312.pyc,, +flask/__pycache__/sessions.cpython-312.pyc,, +flask/__pycache__/signals.cpython-312.pyc,, +flask/__pycache__/templating.cpython-312.pyc,, +flask/__pycache__/testing.cpython-312.pyc,, +flask/__pycache__/typing.cpython-312.pyc,, +flask/__pycache__/views.cpython-312.pyc,, +flask/__pycache__/wrappers.cpython-312.pyc,, +flask/app.py,sha256=k7tW8LHRSldUi6zKsFKK7Axa_WL4zu1e2wPNthIsu7o,61719 +flask/blueprints.py,sha256=p5QE2lY18GItbdr_RKRpZ8Do17g0PvQGIgZkSUDhX2k,4541 +flask/cli.py,sha256=Pfh72-BxlvoH0QHCDOc1HvXG7Kq5Xetf3zzNz2kNSHk,37184 +flask/config.py,sha256=PiqF0DPam6HW0FH4CH1hpXTBe30NSzjPEOwrz1b6kt0,13219 +flask/ctx.py,sha256=oMe0TRsScW0qdaIqavVsk8P9qiEvAY5VHn1FAgkX8nk,15521 +flask/debughelpers.py,sha256=PGIDhStW_efRjpaa3zHIpo-htStJOR41Ip3OJWPYBwo,6080 +flask/globals.py,sha256=XdQZmStBmPIs8t93tjx6pO7Bm3gobAaONWkFcUHaGas,1713 +flask/helpers.py,sha256=rJZge7_J288J1UQv5-kNf4oEaw332PP8NTW0QRIBbXE,23517 +flask/json/__init__.py,sha256=hLNR898paqoefdeAhraa5wyJy-bmRB2k2dV4EgVy2Z8,5602 +flask/json/__pycache__/__init__.cpython-312.pyc,, +flask/json/__pycache__/provider.cpython-312.pyc,, +flask/json/__pycache__/tag.cpython-312.pyc,, +flask/json/provider.py,sha256=5imEzY5HjV2HoUVrQbJLqXCzMNpZXfD0Y1XqdLV2XBA,7672 +flask/json/tag.py,sha256=DhaNwuIOhdt2R74oOC9Y4Z8ZprxFYiRb5dUP5byyINw,9281 +flask/logging.py,sha256=8sM3WMTubi1cBb2c_lPkWpN0J8dMAqrgKRYLLi1dCVI,2377 +flask/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +flask/sansio/README.md,sha256=-0X1tECnilmz1cogx-YhNw5d7guK7GKrq_DEV2OzlU0,228 +flask/sansio/__pycache__/app.cpython-312.pyc,, +flask/sansio/__pycache__/blueprints.cpython-312.pyc,, +flask/sansio/__pycache__/scaffold.cpython-312.pyc,, +flask/sansio/app.py,sha256=whGURQDkN0jmhS4CHO7DQ96GGlZS0kETkKkAkoRjl4U,38106 +flask/sansio/blueprints.py,sha256=Tqe-7EkZ-tbWchm8iDoCfD848f0_3nLv6NNjeIPvHwM,24637 +flask/sansio/scaffold.py,sha256=wSASXYdFRWJmqcL0Xq-T7N-PDVUSiFGvjO9kPZg58bk,30371 +flask/sessions.py,sha256=eywRqmytTmYnX_EC78-YBGJoTc5XD_lRphQG5LbN1d0,14969 +flask/signals.py,sha256=V7lMUww7CqgJ2ThUBn1PiatZtQanOyt7OZpu2GZI-34,750 +flask/templating.py,sha256=vbIkwYAxsSEfDxQID1gKRvBQQcGWEuWYCnH0XK3EqOI,7678 +flask/testing.py,sha256=zzC7XxhBWOP9H697IV_4SG7Lg3Lzb5PWiyEP93_KQXE,10117 +flask/typing.py,sha256=L-L5t2jKgS0aOmVhioQ_ylqcgiVFnA6yxO-RLNhq-GU,3293 +flask/views.py,sha256=xzJx6oJqGElThtEghZN7ZQGMw5TDFyuRxUkecwRuAoA,6962 +flask/wrappers.py,sha256=jUkv4mVek2Iq4hwxd4RvqrIMb69Bv0PElDgWLmd5ORo,9406 diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask-3.1.3.dist-info/REQUESTED b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask-3.1.3.dist-info/REQUESTED new file mode 100644 index 000000000..e69de29bb diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask-3.1.3.dist-info/WHEEL b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask-3.1.3.dist-info/WHEEL new file mode 100644 index 000000000..d8b9936da --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask-3.1.3.dist-info/WHEEL @@ -0,0 +1,4 @@ +Wheel-Version: 1.0 +Generator: flit 3.12.0 +Root-Is-Purelib: true +Tag: py3-none-any diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask-3.1.3.dist-info/entry_points.txt b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask-3.1.3.dist-info/entry_points.txt new file mode 100644 index 000000000..eec6733e5 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask-3.1.3.dist-info/entry_points.txt @@ -0,0 +1,3 @@ +[console_scripts] +flask=flask.cli:main + diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask-3.1.3.dist-info/licenses/LICENSE.txt b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask-3.1.3.dist-info/licenses/LICENSE.txt new file mode 100644 index 000000000..9d227a0cc --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask-3.1.3.dist-info/licenses/LICENSE.txt @@ -0,0 +1,28 @@ +Copyright 2010 Pallets + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A +PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED +TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask/__init__.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask/__init__.py new file mode 100644 index 000000000..1fdc50cea --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask/__init__.py @@ -0,0 +1,61 @@ +from __future__ import annotations + +import typing as t + +from . import json as json +from .app import Flask as Flask +from .blueprints import Blueprint as Blueprint +from .config import Config as Config +from .ctx import after_this_request as after_this_request +from .ctx import copy_current_request_context as copy_current_request_context +from .ctx import has_app_context as has_app_context +from .ctx import has_request_context as has_request_context +from .globals import current_app as current_app +from .globals import g as g +from .globals import request as request +from .globals import session as session +from .helpers import abort as abort +from .helpers import flash as flash +from .helpers import get_flashed_messages as get_flashed_messages +from .helpers import get_template_attribute as get_template_attribute +from .helpers import make_response as make_response +from .helpers import redirect as redirect +from .helpers import send_file as send_file +from .helpers import send_from_directory as send_from_directory +from .helpers import stream_with_context as stream_with_context +from .helpers import url_for as url_for +from .json import jsonify as jsonify +from .signals import appcontext_popped as appcontext_popped +from .signals import appcontext_pushed as appcontext_pushed +from .signals import appcontext_tearing_down as appcontext_tearing_down +from .signals import before_render_template as before_render_template +from .signals import got_request_exception as got_request_exception +from .signals import message_flashed as message_flashed +from .signals import request_finished as request_finished +from .signals import request_started as request_started +from .signals import request_tearing_down as request_tearing_down +from .signals import template_rendered as template_rendered +from .templating import render_template as render_template +from .templating import render_template_string as render_template_string +from .templating import stream_template as stream_template +from .templating import stream_template_string as stream_template_string +from .wrappers import Request as Request +from .wrappers import Response as Response + +if not t.TYPE_CHECKING: + + def __getattr__(name: str) -> t.Any: + if name == "__version__": + import importlib.metadata + import warnings + + warnings.warn( + "The '__version__' attribute is deprecated and will be removed in" + " Flask 3.2. Use feature detection or" + " 'importlib.metadata.version(\"flask\")' instead.", + DeprecationWarning, + stacklevel=2, + ) + return importlib.metadata.version("flask") + + raise AttributeError(name) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask/__main__.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask/__main__.py new file mode 100644 index 000000000..4e28416e1 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask/__main__.py @@ -0,0 +1,3 @@ +from .cli import main + +main() diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask/app.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask/app.py new file mode 100644 index 000000000..c6af46e23 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask/app.py @@ -0,0 +1,1536 @@ +from __future__ import annotations + +import collections.abc as cabc +import os +import sys +import typing as t +import weakref +from datetime import timedelta +from inspect import iscoroutinefunction +from itertools import chain +from types import TracebackType +from urllib.parse import quote as _url_quote + +import click +from werkzeug.datastructures import Headers +from werkzeug.datastructures import ImmutableDict +from werkzeug.exceptions import BadRequestKeyError +from werkzeug.exceptions import HTTPException +from werkzeug.exceptions import InternalServerError +from werkzeug.routing import BuildError +from werkzeug.routing import MapAdapter +from werkzeug.routing import RequestRedirect +from werkzeug.routing import RoutingException +from werkzeug.routing import Rule +from werkzeug.serving import is_running_from_reloader +from werkzeug.wrappers import Response as BaseResponse +from werkzeug.wsgi import get_host + +from . import cli +from . import typing as ft +from .ctx import AppContext +from .ctx import RequestContext +from .globals import _cv_app +from .globals import _cv_request +from .globals import current_app +from .globals import g +from .globals import request +from .globals import request_ctx +from .globals import session +from .helpers import get_debug_flag +from .helpers import get_flashed_messages +from .helpers import get_load_dotenv +from .helpers import send_from_directory +from .sansio.app import App +from .sansio.scaffold import _sentinel +from .sessions import SecureCookieSessionInterface +from .sessions import SessionInterface +from .signals import appcontext_tearing_down +from .signals import got_request_exception +from .signals import request_finished +from .signals import request_started +from .signals import request_tearing_down +from .templating import Environment +from .wrappers import Request +from .wrappers import Response + +if t.TYPE_CHECKING: # pragma: no cover + from _typeshed.wsgi import StartResponse + from _typeshed.wsgi import WSGIEnvironment + + from .testing import FlaskClient + from .testing import FlaskCliRunner + from .typing import HeadersValue + +T_shell_context_processor = t.TypeVar( + "T_shell_context_processor", bound=ft.ShellContextProcessorCallable +) +T_teardown = t.TypeVar("T_teardown", bound=ft.TeardownCallable) +T_template_filter = t.TypeVar("T_template_filter", bound=ft.TemplateFilterCallable) +T_template_global = t.TypeVar("T_template_global", bound=ft.TemplateGlobalCallable) +T_template_test = t.TypeVar("T_template_test", bound=ft.TemplateTestCallable) + + +def _make_timedelta(value: timedelta | int | None) -> timedelta | None: + if value is None or isinstance(value, timedelta): + return value + + return timedelta(seconds=value) + + +class Flask(App): + """The flask object implements a WSGI application and acts as the central + object. It is passed the name of the module or package of the + application. Once it is created it will act as a central registry for + the view functions, the URL rules, template configuration and much more. + + The name of the package is used to resolve resources from inside the + package or the folder the module is contained in depending on if the + package parameter resolves to an actual python package (a folder with + an :file:`__init__.py` file inside) or a standard module (just a ``.py`` file). + + For more information about resource loading, see :func:`open_resource`. + + Usually you create a :class:`Flask` instance in your main module or + in the :file:`__init__.py` file of your package like this:: + + from flask import Flask + app = Flask(__name__) + + .. admonition:: About the First Parameter + + The idea of the first parameter is to give Flask an idea of what + belongs to your application. This name is used to find resources + on the filesystem, can be used by extensions to improve debugging + information and a lot more. + + So it's important what you provide there. If you are using a single + module, `__name__` is always the correct value. If you however are + using a package, it's usually recommended to hardcode the name of + your package there. + + For example if your application is defined in :file:`yourapplication/app.py` + you should create it with one of the two versions below:: + + app = Flask('yourapplication') + app = Flask(__name__.split('.')[0]) + + Why is that? The application will work even with `__name__`, thanks + to how resources are looked up. However it will make debugging more + painful. Certain extensions can make assumptions based on the + import name of your application. For example the Flask-SQLAlchemy + extension will look for the code in your application that triggered + an SQL query in debug mode. If the import name is not properly set + up, that debugging information is lost. (For example it would only + pick up SQL queries in `yourapplication.app` and not + `yourapplication.views.frontend`) + + .. versionadded:: 0.7 + The `static_url_path`, `static_folder`, and `template_folder` + parameters were added. + + .. versionadded:: 0.8 + The `instance_path` and `instance_relative_config` parameters were + added. + + .. versionadded:: 0.11 + The `root_path` parameter was added. + + .. versionadded:: 1.0 + The ``host_matching`` and ``static_host`` parameters were added. + + .. versionadded:: 1.0 + The ``subdomain_matching`` parameter was added. Subdomain + matching needs to be enabled manually now. Setting + :data:`SERVER_NAME` does not implicitly enable it. + + :param import_name: the name of the application package + :param static_url_path: can be used to specify a different path for the + static files on the web. Defaults to the name + of the `static_folder` folder. + :param static_folder: The folder with static files that is served at + ``static_url_path``. Relative to the application ``root_path`` + or an absolute path. Defaults to ``'static'``. + :param static_host: the host to use when adding the static route. + Defaults to None. Required when using ``host_matching=True`` + with a ``static_folder`` configured. + :param host_matching: set ``url_map.host_matching`` attribute. + Defaults to False. + :param subdomain_matching: consider the subdomain relative to + :data:`SERVER_NAME` when matching routes. Defaults to False. + :param template_folder: the folder that contains the templates that should + be used by the application. Defaults to + ``'templates'`` folder in the root path of the + application. + :param instance_path: An alternative instance path for the application. + By default the folder ``'instance'`` next to the + package or module is assumed to be the instance + path. + :param instance_relative_config: if set to ``True`` relative filenames + for loading the config are assumed to + be relative to the instance path instead + of the application root. + :param root_path: The path to the root of the application files. + This should only be set manually when it can't be detected + automatically, such as for namespace packages. + """ + + default_config = ImmutableDict( + { + "DEBUG": None, + "TESTING": False, + "PROPAGATE_EXCEPTIONS": None, + "SECRET_KEY": None, + "SECRET_KEY_FALLBACKS": None, + "PERMANENT_SESSION_LIFETIME": timedelta(days=31), + "USE_X_SENDFILE": False, + "TRUSTED_HOSTS": None, + "SERVER_NAME": None, + "APPLICATION_ROOT": "/", + "SESSION_COOKIE_NAME": "session", + "SESSION_COOKIE_DOMAIN": None, + "SESSION_COOKIE_PATH": None, + "SESSION_COOKIE_HTTPONLY": True, + "SESSION_COOKIE_SECURE": False, + "SESSION_COOKIE_PARTITIONED": False, + "SESSION_COOKIE_SAMESITE": None, + "SESSION_REFRESH_EACH_REQUEST": True, + "MAX_CONTENT_LENGTH": None, + "MAX_FORM_MEMORY_SIZE": 500_000, + "MAX_FORM_PARTS": 1_000, + "SEND_FILE_MAX_AGE_DEFAULT": None, + "TRAP_BAD_REQUEST_ERRORS": None, + "TRAP_HTTP_EXCEPTIONS": False, + "EXPLAIN_TEMPLATE_LOADING": False, + "PREFERRED_URL_SCHEME": "http", + "TEMPLATES_AUTO_RELOAD": None, + "MAX_COOKIE_SIZE": 4093, + "PROVIDE_AUTOMATIC_OPTIONS": True, + } + ) + + #: The class that is used for request objects. See :class:`~flask.Request` + #: for more information. + request_class: type[Request] = Request + + #: The class that is used for response objects. See + #: :class:`~flask.Response` for more information. + response_class: type[Response] = Response + + #: the session interface to use. By default an instance of + #: :class:`~flask.sessions.SecureCookieSessionInterface` is used here. + #: + #: .. versionadded:: 0.8 + session_interface: SessionInterface = SecureCookieSessionInterface() + + def __init__( + self, + import_name: str, + static_url_path: str | None = None, + static_folder: str | os.PathLike[str] | None = "static", + static_host: str | None = None, + host_matching: bool = False, + subdomain_matching: bool = False, + template_folder: str | os.PathLike[str] | None = "templates", + instance_path: str | None = None, + instance_relative_config: bool = False, + root_path: str | None = None, + ): + super().__init__( + import_name=import_name, + static_url_path=static_url_path, + static_folder=static_folder, + static_host=static_host, + host_matching=host_matching, + subdomain_matching=subdomain_matching, + template_folder=template_folder, + instance_path=instance_path, + instance_relative_config=instance_relative_config, + root_path=root_path, + ) + + #: The Click command group for registering CLI commands for this + #: object. The commands are available from the ``flask`` command + #: once the application has been discovered and blueprints have + #: been registered. + self.cli = cli.AppGroup() + + # Set the name of the Click group in case someone wants to add + # the app's commands to another CLI tool. + self.cli.name = self.name + + # Add a static route using the provided static_url_path, static_host, + # and static_folder if there is a configured static_folder. + # Note we do this without checking if static_folder exists. + # For one, it might be created while the server is running (e.g. during + # development). Also, Google App Engine stores static files somewhere + if self.has_static_folder: + assert bool(static_host) == host_matching, ( + "Invalid static_host/host_matching combination" + ) + # Use a weakref to avoid creating a reference cycle between the app + # and the view function (see #3761). + self_ref = weakref.ref(self) + self.add_url_rule( + f"{self.static_url_path}/", + endpoint="static", + host=static_host, + view_func=lambda **kw: self_ref().send_static_file(**kw), # type: ignore + ) + + def get_send_file_max_age(self, filename: str | None) -> int | None: + """Used by :func:`send_file` to determine the ``max_age`` cache + value for a given file path if it wasn't passed. + + By default, this returns :data:`SEND_FILE_MAX_AGE_DEFAULT` from + the configuration of :data:`~flask.current_app`. This defaults + to ``None``, which tells the browser to use conditional requests + instead of a timed cache, which is usually preferable. + + Note this is a duplicate of the same method in the Flask + class. + + .. versionchanged:: 2.0 + The default configuration is ``None`` instead of 12 hours. + + .. versionadded:: 0.9 + """ + value = current_app.config["SEND_FILE_MAX_AGE_DEFAULT"] + + if value is None: + return None + + if isinstance(value, timedelta): + return int(value.total_seconds()) + + return value # type: ignore[no-any-return] + + def send_static_file(self, filename: str) -> Response: + """The view function used to serve files from + :attr:`static_folder`. A route is automatically registered for + this view at :attr:`static_url_path` if :attr:`static_folder` is + set. + + Note this is a duplicate of the same method in the Flask + class. + + .. versionadded:: 0.5 + + """ + if not self.has_static_folder: + raise RuntimeError("'static_folder' must be set to serve static_files.") + + # send_file only knows to call get_send_file_max_age on the app, + # call it here so it works for blueprints too. + max_age = self.get_send_file_max_age(filename) + return send_from_directory( + t.cast(str, self.static_folder), filename, max_age=max_age + ) + + def open_resource( + self, resource: str, mode: str = "rb", encoding: str | None = None + ) -> t.IO[t.AnyStr]: + """Open a resource file relative to :attr:`root_path` for reading. + + For example, if the file ``schema.sql`` is next to the file + ``app.py`` where the ``Flask`` app is defined, it can be opened + with: + + .. code-block:: python + + with app.open_resource("schema.sql") as f: + conn.executescript(f.read()) + + :param resource: Path to the resource relative to :attr:`root_path`. + :param mode: Open the file in this mode. Only reading is supported, + valid values are ``"r"`` (or ``"rt"``) and ``"rb"``. + :param encoding: Open the file with this encoding when opening in text + mode. This is ignored when opening in binary mode. + + .. versionchanged:: 3.1 + Added the ``encoding`` parameter. + """ + if mode not in {"r", "rt", "rb"}: + raise ValueError("Resources can only be opened for reading.") + + path = os.path.join(self.root_path, resource) + + if mode == "rb": + return open(path, mode) # pyright: ignore + + return open(path, mode, encoding=encoding) + + def open_instance_resource( + self, resource: str, mode: str = "rb", encoding: str | None = "utf-8" + ) -> t.IO[t.AnyStr]: + """Open a resource file relative to the application's instance folder + :attr:`instance_path`. Unlike :meth:`open_resource`, files in the + instance folder can be opened for writing. + + :param resource: Path to the resource relative to :attr:`instance_path`. + :param mode: Open the file in this mode. + :param encoding: Open the file with this encoding when opening in text + mode. This is ignored when opening in binary mode. + + .. versionchanged:: 3.1 + Added the ``encoding`` parameter. + """ + path = os.path.join(self.instance_path, resource) + + if "b" in mode: + return open(path, mode) + + return open(path, mode, encoding=encoding) + + def create_jinja_environment(self) -> Environment: + """Create the Jinja environment based on :attr:`jinja_options` + and the various Jinja-related methods of the app. Changing + :attr:`jinja_options` after this will have no effect. Also adds + Flask-related globals and filters to the environment. + + .. versionchanged:: 0.11 + ``Environment.auto_reload`` set in accordance with + ``TEMPLATES_AUTO_RELOAD`` configuration option. + + .. versionadded:: 0.5 + """ + options = dict(self.jinja_options) + + if "autoescape" not in options: + options["autoescape"] = self.select_jinja_autoescape + + if "auto_reload" not in options: + auto_reload = self.config["TEMPLATES_AUTO_RELOAD"] + + if auto_reload is None: + auto_reload = self.debug + + options["auto_reload"] = auto_reload + + rv = self.jinja_environment(self, **options) + rv.globals.update( + url_for=self.url_for, + get_flashed_messages=get_flashed_messages, + config=self.config, + # request, session and g are normally added with the + # context processor for efficiency reasons but for imported + # templates we also want the proxies in there. + request=request, + session=session, + g=g, + ) + rv.policies["json.dumps_function"] = self.json.dumps + return rv + + def create_url_adapter(self, request: Request | None) -> MapAdapter | None: + """Creates a URL adapter for the given request. The URL adapter + is created at a point where the request context is not yet set + up so the request is passed explicitly. + + .. versionchanged:: 3.1 + If :data:`SERVER_NAME` is set, it does not restrict requests to + only that domain, for both ``subdomain_matching`` and + ``host_matching``. + + .. versionchanged:: 1.0 + :data:`SERVER_NAME` no longer implicitly enables subdomain + matching. Use :attr:`subdomain_matching` instead. + + .. versionchanged:: 0.9 + This can be called outside a request when the URL adapter is created + for an application context. + + .. versionadded:: 0.6 + """ + if request is not None: + if (trusted_hosts := self.config["TRUSTED_HOSTS"]) is not None: + request.trusted_hosts = trusted_hosts + + # Check trusted_hosts here until bind_to_environ does. + request.host = get_host(request.environ, request.trusted_hosts) # pyright: ignore + subdomain = None + server_name = self.config["SERVER_NAME"] + + if self.url_map.host_matching: + # Don't pass SERVER_NAME, otherwise it's used and the actual + # host is ignored, which breaks host matching. + server_name = None + elif not self.subdomain_matching: + # Werkzeug doesn't implement subdomain matching yet. Until then, + # disable it by forcing the current subdomain to the default, or + # the empty string. + subdomain = self.url_map.default_subdomain or "" + + return self.url_map.bind_to_environ( + request.environ, server_name=server_name, subdomain=subdomain + ) + + # Need at least SERVER_NAME to match/build outside a request. + if self.config["SERVER_NAME"] is not None: + return self.url_map.bind( + self.config["SERVER_NAME"], + script_name=self.config["APPLICATION_ROOT"], + url_scheme=self.config["PREFERRED_URL_SCHEME"], + ) + + return None + + def raise_routing_exception(self, request: Request) -> t.NoReturn: + """Intercept routing exceptions and possibly do something else. + + In debug mode, intercept a routing redirect and replace it with + an error if the body will be discarded. + + With modern Werkzeug this shouldn't occur, since it now uses a + 308 status which tells the browser to resend the method and + body. + + .. versionchanged:: 2.1 + Don't intercept 307 and 308 redirects. + + :meta private: + :internal: + """ + if ( + not self.debug + or not isinstance(request.routing_exception, RequestRedirect) + or request.routing_exception.code in {307, 308} + or request.method in {"GET", "HEAD", "OPTIONS"} + ): + raise request.routing_exception # type: ignore[misc] + + from .debughelpers import FormDataRoutingRedirect + + raise FormDataRoutingRedirect(request) + + def update_template_context(self, context: dict[str, t.Any]) -> None: + """Update the template context with some commonly used variables. + This injects request, session, config and g into the template + context as well as everything template context processors want + to inject. Note that the as of Flask 0.6, the original values + in the context will not be overridden if a context processor + decides to return a value with the same key. + + :param context: the context as a dictionary that is updated in place + to add extra variables. + """ + names: t.Iterable[str | None] = (None,) + + # A template may be rendered outside a request context. + if request: + names = chain(names, reversed(request.blueprints)) + + # The values passed to render_template take precedence. Keep a + # copy to re-apply after all context functions. + orig_ctx = context.copy() + + for name in names: + if name in self.template_context_processors: + for func in self.template_context_processors[name]: + context.update(self.ensure_sync(func)()) + + context.update(orig_ctx) + + def make_shell_context(self) -> dict[str, t.Any]: + """Returns the shell context for an interactive shell for this + application. This runs all the registered shell context + processors. + + .. versionadded:: 0.11 + """ + rv = {"app": self, "g": g} + for processor in self.shell_context_processors: + rv.update(processor()) + return rv + + def run( + self, + host: str | None = None, + port: int | None = None, + debug: bool | None = None, + load_dotenv: bool = True, + **options: t.Any, + ) -> None: + """Runs the application on a local development server. + + Do not use ``run()`` in a production setting. It is not intended to + meet security and performance requirements for a production server. + Instead, see :doc:`/deploying/index` for WSGI server recommendations. + + If the :attr:`debug` flag is set the server will automatically reload + for code changes and show a debugger in case an exception happened. + + If you want to run the application in debug mode, but disable the + code execution on the interactive debugger, you can pass + ``use_evalex=False`` as parameter. This will keep the debugger's + traceback screen active, but disable code execution. + + It is not recommended to use this function for development with + automatic reloading as this is badly supported. Instead you should + be using the :command:`flask` command line script's ``run`` support. + + .. admonition:: Keep in Mind + + Flask will suppress any server error with a generic error page + unless it is in debug mode. As such to enable just the + interactive debugger without the code reloading, you have to + invoke :meth:`run` with ``debug=False`` and ``use_reloader=False``. + Setting ``use_debugger`` to ``True`` without being in debug mode + won't catch any exceptions because there won't be any to + catch. + + :param host: the hostname to listen on. Set this to ``'0.0.0.0'`` to + have the server available externally as well. Defaults to + ``'127.0.0.1'`` or the host in the ``SERVER_NAME`` config variable + if present. + :param port: the port of the webserver. Defaults to ``5000`` or the + port defined in the ``SERVER_NAME`` config variable if present. + :param debug: if given, enable or disable debug mode. See + :attr:`debug`. + :param load_dotenv: Load the nearest :file:`.env` and :file:`.flaskenv` + files to set environment variables. Will also change the working + directory to the directory containing the first file found. + :param options: the options to be forwarded to the underlying Werkzeug + server. See :func:`werkzeug.serving.run_simple` for more + information. + + .. versionchanged:: 1.0 + If installed, python-dotenv will be used to load environment + variables from :file:`.env` and :file:`.flaskenv` files. + + The :envvar:`FLASK_DEBUG` environment variable will override :attr:`debug`. + + Threaded mode is enabled by default. + + .. versionchanged:: 0.10 + The default port is now picked from the ``SERVER_NAME`` + variable. + """ + # Ignore this call so that it doesn't start another server if + # the 'flask run' command is used. + if os.environ.get("FLASK_RUN_FROM_CLI") == "true": + if not is_running_from_reloader(): + click.secho( + " * Ignoring a call to 'app.run()' that would block" + " the current 'flask' CLI command.\n" + " Only call 'app.run()' in an 'if __name__ ==" + ' "__main__"\' guard.', + fg="red", + ) + + return + + if get_load_dotenv(load_dotenv): + cli.load_dotenv() + + # if set, env var overrides existing value + if "FLASK_DEBUG" in os.environ: + self.debug = get_debug_flag() + + # debug passed to method overrides all other sources + if debug is not None: + self.debug = bool(debug) + + server_name = self.config.get("SERVER_NAME") + sn_host = sn_port = None + + if server_name: + sn_host, _, sn_port = server_name.partition(":") + + if not host: + if sn_host: + host = sn_host + else: + host = "127.0.0.1" + + if port or port == 0: + port = int(port) + elif sn_port: + port = int(sn_port) + else: + port = 5000 + + options.setdefault("use_reloader", self.debug) + options.setdefault("use_debugger", self.debug) + options.setdefault("threaded", True) + + cli.show_server_banner(self.debug, self.name) + + from werkzeug.serving import run_simple + + try: + run_simple(t.cast(str, host), port, self, **options) + finally: + # reset the first request information if the development server + # reset normally. This makes it possible to restart the server + # without reloader and that stuff from an interactive shell. + self._got_first_request = False + + def test_client(self, use_cookies: bool = True, **kwargs: t.Any) -> FlaskClient: + """Creates a test client for this application. For information + about unit testing head over to :doc:`/testing`. + + Note that if you are testing for assertions or exceptions in your + application code, you must set ``app.testing = True`` in order for the + exceptions to propagate to the test client. Otherwise, the exception + will be handled by the application (not visible to the test client) and + the only indication of an AssertionError or other exception will be a + 500 status code response to the test client. See the :attr:`testing` + attribute. For example:: + + app.testing = True + client = app.test_client() + + The test client can be used in a ``with`` block to defer the closing down + of the context until the end of the ``with`` block. This is useful if + you want to access the context locals for testing:: + + with app.test_client() as c: + rv = c.get('/?vodka=42') + assert request.args['vodka'] == '42' + + Additionally, you may pass optional keyword arguments that will then + be passed to the application's :attr:`test_client_class` constructor. + For example:: + + from flask.testing import FlaskClient + + class CustomClient(FlaskClient): + def __init__(self, *args, **kwargs): + self._authentication = kwargs.pop("authentication") + super(CustomClient,self).__init__( *args, **kwargs) + + app.test_client_class = CustomClient + client = app.test_client(authentication='Basic ....') + + See :class:`~flask.testing.FlaskClient` for more information. + + .. versionchanged:: 0.4 + added support for ``with`` block usage for the client. + + .. versionadded:: 0.7 + The `use_cookies` parameter was added as well as the ability + to override the client to be used by setting the + :attr:`test_client_class` attribute. + + .. versionchanged:: 0.11 + Added `**kwargs` to support passing additional keyword arguments to + the constructor of :attr:`test_client_class`. + """ + cls = self.test_client_class + if cls is None: + from .testing import FlaskClient as cls + return cls( # type: ignore + self, self.response_class, use_cookies=use_cookies, **kwargs + ) + + def test_cli_runner(self, **kwargs: t.Any) -> FlaskCliRunner: + """Create a CLI runner for testing CLI commands. + See :ref:`testing-cli`. + + Returns an instance of :attr:`test_cli_runner_class`, by default + :class:`~flask.testing.FlaskCliRunner`. The Flask app object is + passed as the first argument. + + .. versionadded:: 1.0 + """ + cls = self.test_cli_runner_class + + if cls is None: + from .testing import FlaskCliRunner as cls + + return cls(self, **kwargs) # type: ignore + + def handle_http_exception( + self, e: HTTPException + ) -> HTTPException | ft.ResponseReturnValue: + """Handles an HTTP exception. By default this will invoke the + registered error handlers and fall back to returning the + exception as response. + + .. versionchanged:: 1.0.3 + ``RoutingException``, used internally for actions such as + slash redirects during routing, is not passed to error + handlers. + + .. versionchanged:: 1.0 + Exceptions are looked up by code *and* by MRO, so + ``HTTPException`` subclasses can be handled with a catch-all + handler for the base ``HTTPException``. + + .. versionadded:: 0.3 + """ + # Proxy exceptions don't have error codes. We want to always return + # those unchanged as errors + if e.code is None: + return e + + # RoutingExceptions are used internally to trigger routing + # actions, such as slash redirects raising RequestRedirect. They + # are not raised or handled in user code. + if isinstance(e, RoutingException): + return e + + handler = self._find_error_handler(e, request.blueprints) + if handler is None: + return e + return self.ensure_sync(handler)(e) # type: ignore[no-any-return] + + def handle_user_exception( + self, e: Exception + ) -> HTTPException | ft.ResponseReturnValue: + """This method is called whenever an exception occurs that + should be handled. A special case is :class:`~werkzeug + .exceptions.HTTPException` which is forwarded to the + :meth:`handle_http_exception` method. This function will either + return a response value or reraise the exception with the same + traceback. + + .. versionchanged:: 1.0 + Key errors raised from request data like ``form`` show the + bad key in debug mode rather than a generic bad request + message. + + .. versionadded:: 0.7 + """ + if isinstance(e, BadRequestKeyError) and ( + self.debug or self.config["TRAP_BAD_REQUEST_ERRORS"] + ): + e.show_exception = True + + if isinstance(e, HTTPException) and not self.trap_http_exception(e): + return self.handle_http_exception(e) + + handler = self._find_error_handler(e, request.blueprints) + + if handler is None: + raise + + return self.ensure_sync(handler)(e) # type: ignore[no-any-return] + + def handle_exception(self, e: Exception) -> Response: + """Handle an exception that did not have an error handler + associated with it, or that was raised from an error handler. + This always causes a 500 ``InternalServerError``. + + Always sends the :data:`got_request_exception` signal. + + If :data:`PROPAGATE_EXCEPTIONS` is ``True``, such as in debug + mode, the error will be re-raised so that the debugger can + display it. Otherwise, the original exception is logged, and + an :exc:`~werkzeug.exceptions.InternalServerError` is returned. + + If an error handler is registered for ``InternalServerError`` or + ``500``, it will be used. For consistency, the handler will + always receive the ``InternalServerError``. The original + unhandled exception is available as ``e.original_exception``. + + .. versionchanged:: 1.1.0 + Always passes the ``InternalServerError`` instance to the + handler, setting ``original_exception`` to the unhandled + error. + + .. versionchanged:: 1.1.0 + ``after_request`` functions and other finalization is done + even for the default 500 response when there is no handler. + + .. versionadded:: 0.3 + """ + exc_info = sys.exc_info() + got_request_exception.send(self, _async_wrapper=self.ensure_sync, exception=e) + propagate = self.config["PROPAGATE_EXCEPTIONS"] + + if propagate is None: + propagate = self.testing or self.debug + + if propagate: + # Re-raise if called with an active exception, otherwise + # raise the passed in exception. + if exc_info[1] is e: + raise + + raise e + + self.log_exception(exc_info) + server_error: InternalServerError | ft.ResponseReturnValue + server_error = InternalServerError(original_exception=e) + handler = self._find_error_handler(server_error, request.blueprints) + + if handler is not None: + server_error = self.ensure_sync(handler)(server_error) + + return self.finalize_request(server_error, from_error_handler=True) + + def log_exception( + self, + exc_info: (tuple[type, BaseException, TracebackType] | tuple[None, None, None]), + ) -> None: + """Logs an exception. This is called by :meth:`handle_exception` + if debugging is disabled and right before the handler is called. + The default implementation logs the exception as error on the + :attr:`logger`. + + .. versionadded:: 0.8 + """ + self.logger.error( + f"Exception on {request.path} [{request.method}]", exc_info=exc_info + ) + + def dispatch_request(self) -> ft.ResponseReturnValue: + """Does the request dispatching. Matches the URL and returns the + return value of the view or error handler. This does not have to + be a response object. In order to convert the return value to a + proper response object, call :func:`make_response`. + + .. versionchanged:: 0.7 + This no longer does the exception handling, this code was + moved to the new :meth:`full_dispatch_request`. + """ + req = request_ctx.request + if req.routing_exception is not None: + self.raise_routing_exception(req) + rule: Rule = req.url_rule # type: ignore[assignment] + # if we provide automatic options for this URL and the + # request came with the OPTIONS method, reply automatically + if ( + getattr(rule, "provide_automatic_options", False) + and req.method == "OPTIONS" + ): + return self.make_default_options_response() + # otherwise dispatch to the handler for that endpoint + view_args: dict[str, t.Any] = req.view_args # type: ignore[assignment] + return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args) # type: ignore[no-any-return] + + def full_dispatch_request(self) -> Response: + """Dispatches the request and on top of that performs request + pre and postprocessing as well as HTTP exception catching and + error handling. + + .. versionadded:: 0.7 + """ + self._got_first_request = True + + try: + request_started.send(self, _async_wrapper=self.ensure_sync) + rv = self.preprocess_request() + if rv is None: + rv = self.dispatch_request() + except Exception as e: + rv = self.handle_user_exception(e) + return self.finalize_request(rv) + + def finalize_request( + self, + rv: ft.ResponseReturnValue | HTTPException, + from_error_handler: bool = False, + ) -> Response: + """Given the return value from a view function this finalizes + the request by converting it into a response and invoking the + postprocessing functions. This is invoked for both normal + request dispatching as well as error handlers. + + Because this means that it might be called as a result of a + failure a special safe mode is available which can be enabled + with the `from_error_handler` flag. If enabled, failures in + response processing will be logged and otherwise ignored. + + :internal: + """ + response = self.make_response(rv) + try: + response = self.process_response(response) + request_finished.send( + self, _async_wrapper=self.ensure_sync, response=response + ) + except Exception: + if not from_error_handler: + raise + self.logger.exception( + "Request finalizing failed with an error while handling an error" + ) + return response + + def make_default_options_response(self) -> Response: + """This method is called to create the default ``OPTIONS`` response. + This can be changed through subclassing to change the default + behavior of ``OPTIONS`` responses. + + .. versionadded:: 0.7 + """ + adapter = request_ctx.url_adapter + methods = adapter.allowed_methods() # type: ignore[union-attr] + rv = self.response_class() + rv.allow.update(methods) + return rv + + def ensure_sync(self, func: t.Callable[..., t.Any]) -> t.Callable[..., t.Any]: + """Ensure that the function is synchronous for WSGI workers. + Plain ``def`` functions are returned as-is. ``async def`` + functions are wrapped to run and wait for the response. + + Override this method to change how the app runs async views. + + .. versionadded:: 2.0 + """ + if iscoroutinefunction(func): + return self.async_to_sync(func) + + return func + + def async_to_sync( + self, func: t.Callable[..., t.Coroutine[t.Any, t.Any, t.Any]] + ) -> t.Callable[..., t.Any]: + """Return a sync function that will run the coroutine function. + + .. code-block:: python + + result = app.async_to_sync(func)(*args, **kwargs) + + Override this method to change how the app converts async code + to be synchronously callable. + + .. versionadded:: 2.0 + """ + try: + from asgiref.sync import async_to_sync as asgiref_async_to_sync + except ImportError: + raise RuntimeError( + "Install Flask with the 'async' extra in order to use async views." + ) from None + + return asgiref_async_to_sync(func) + + def url_for( + self, + /, + endpoint: str, + *, + _anchor: str | None = None, + _method: str | None = None, + _scheme: str | None = None, + _external: bool | None = None, + **values: t.Any, + ) -> str: + """Generate a URL to the given endpoint with the given values. + + This is called by :func:`flask.url_for`, and can be called + directly as well. + + An *endpoint* is the name of a URL rule, usually added with + :meth:`@app.route() `, and usually the same name as the + view function. A route defined in a :class:`~flask.Blueprint` + will prepend the blueprint's name separated by a ``.`` to the + endpoint. + + In some cases, such as email messages, you want URLs to include + the scheme and domain, like ``https://example.com/hello``. When + not in an active request, URLs will be external by default, but + this requires setting :data:`SERVER_NAME` so Flask knows what + domain to use. :data:`APPLICATION_ROOT` and + :data:`PREFERRED_URL_SCHEME` should also be configured as + needed. This config is only used when not in an active request. + + Functions can be decorated with :meth:`url_defaults` to modify + keyword arguments before the URL is built. + + If building fails for some reason, such as an unknown endpoint + or incorrect values, the app's :meth:`handle_url_build_error` + method is called. If that returns a string, that is returned, + otherwise a :exc:`~werkzeug.routing.BuildError` is raised. + + :param endpoint: The endpoint name associated with the URL to + generate. If this starts with a ``.``, the current blueprint + name (if any) will be used. + :param _anchor: If given, append this as ``#anchor`` to the URL. + :param _method: If given, generate the URL associated with this + method for the endpoint. + :param _scheme: If given, the URL will have this scheme if it + is external. + :param _external: If given, prefer the URL to be internal + (False) or require it to be external (True). External URLs + include the scheme and domain. When not in an active + request, URLs are external by default. + :param values: Values to use for the variable parts of the URL + rule. Unknown keys are appended as query string arguments, + like ``?a=b&c=d``. + + .. versionadded:: 2.2 + Moved from ``flask.url_for``, which calls this method. + """ + req_ctx = _cv_request.get(None) + + if req_ctx is not None: + url_adapter = req_ctx.url_adapter + blueprint_name = req_ctx.request.blueprint + + # If the endpoint starts with "." and the request matches a + # blueprint, the endpoint is relative to the blueprint. + if endpoint[:1] == ".": + if blueprint_name is not None: + endpoint = f"{blueprint_name}{endpoint}" + else: + endpoint = endpoint[1:] + + # When in a request, generate a URL without scheme and + # domain by default, unless a scheme is given. + if _external is None: + _external = _scheme is not None + else: + app_ctx = _cv_app.get(None) + + # If called by helpers.url_for, an app context is active, + # use its url_adapter. Otherwise, app.url_for was called + # directly, build an adapter. + if app_ctx is not None: + url_adapter = app_ctx.url_adapter + else: + url_adapter = self.create_url_adapter(None) + + if url_adapter is None: + raise RuntimeError( + "Unable to build URLs outside an active request" + " without 'SERVER_NAME' configured. Also configure" + " 'APPLICATION_ROOT' and 'PREFERRED_URL_SCHEME' as" + " needed." + ) + + # When outside a request, generate a URL with scheme and + # domain by default. + if _external is None: + _external = True + + # It is an error to set _scheme when _external=False, in order + # to avoid accidental insecure URLs. + if _scheme is not None and not _external: + raise ValueError("When specifying '_scheme', '_external' must be True.") + + self.inject_url_defaults(endpoint, values) + + try: + rv = url_adapter.build( # type: ignore[union-attr] + endpoint, + values, + method=_method, + url_scheme=_scheme, + force_external=_external, + ) + except BuildError as error: + values.update( + _anchor=_anchor, _method=_method, _scheme=_scheme, _external=_external + ) + return self.handle_url_build_error(error, endpoint, values) + + if _anchor is not None: + _anchor = _url_quote(_anchor, safe="%!#$&'()*+,/:;=?@") + rv = f"{rv}#{_anchor}" + + return rv + + def make_response(self, rv: ft.ResponseReturnValue) -> Response: + """Convert the return value from a view function to an instance of + :attr:`response_class`. + + :param rv: the return value from the view function. The view function + must return a response. Returning ``None``, or the view ending + without returning, is not allowed. The following types are allowed + for ``view_rv``: + + ``str`` + A response object is created with the string encoded to UTF-8 + as the body. + + ``bytes`` + A response object is created with the bytes as the body. + + ``dict`` + A dictionary that will be jsonify'd before being returned. + + ``list`` + A list that will be jsonify'd before being returned. + + ``generator`` or ``iterator`` + A generator that returns ``str`` or ``bytes`` to be + streamed as the response. + + ``tuple`` + Either ``(body, status, headers)``, ``(body, status)``, or + ``(body, headers)``, where ``body`` is any of the other types + allowed here, ``status`` is a string or an integer, and + ``headers`` is a dictionary or a list of ``(key, value)`` + tuples. If ``body`` is a :attr:`response_class` instance, + ``status`` overwrites the exiting value and ``headers`` are + extended. + + :attr:`response_class` + The object is returned unchanged. + + other :class:`~werkzeug.wrappers.Response` class + The object is coerced to :attr:`response_class`. + + :func:`callable` + The function is called as a WSGI application. The result is + used to create a response object. + + .. versionchanged:: 2.2 + A generator will be converted to a streaming response. + A list will be converted to a JSON response. + + .. versionchanged:: 1.1 + A dict will be converted to a JSON response. + + .. versionchanged:: 0.9 + Previously a tuple was interpreted as the arguments for the + response object. + """ + + status: int | None = None + headers: HeadersValue | None = None + + # unpack tuple returns + if isinstance(rv, tuple): + len_rv = len(rv) + + # a 3-tuple is unpacked directly + if len_rv == 3: + rv, status, headers = rv # type: ignore[misc] + # decide if a 2-tuple has status or headers + elif len_rv == 2: + if isinstance(rv[1], (Headers, dict, tuple, list)): + rv, headers = rv # pyright: ignore + else: + rv, status = rv # type: ignore[assignment,misc] + # other sized tuples are not allowed + else: + raise TypeError( + "The view function did not return a valid response tuple." + " The tuple must have the form (body, status, headers)," + " (body, status), or (body, headers)." + ) + + # the body must not be None + if rv is None: + raise TypeError( + f"The view function for {request.endpoint!r} did not" + " return a valid response. The function either returned" + " None or ended without a return statement." + ) + + # make sure the body is an instance of the response class + if not isinstance(rv, self.response_class): + if isinstance(rv, (str, bytes, bytearray)) or isinstance(rv, cabc.Iterator): + # let the response class set the status and headers instead of + # waiting to do it manually, so that the class can handle any + # special logic + rv = self.response_class( + rv, # pyright: ignore + status=status, + headers=headers, # type: ignore[arg-type] + ) + status = headers = None + elif isinstance(rv, (dict, list)): + rv = self.json.response(rv) + elif isinstance(rv, BaseResponse) or callable(rv): + # evaluate a WSGI callable, or coerce a different response + # class to the correct type + try: + rv = self.response_class.force_type( + rv, # type: ignore[arg-type] + request.environ, + ) + except TypeError as e: + raise TypeError( + f"{e}\nThe view function did not return a valid" + " response. The return type must be a string," + " dict, list, tuple with headers or status," + " Response instance, or WSGI callable, but it" + f" was a {type(rv).__name__}." + ).with_traceback(sys.exc_info()[2]) from None + else: + raise TypeError( + "The view function did not return a valid" + " response. The return type must be a string," + " dict, list, tuple with headers or status," + " Response instance, or WSGI callable, but it was a" + f" {type(rv).__name__}." + ) + + rv = t.cast(Response, rv) + # prefer the status if it was provided + if status is not None: + if isinstance(status, (str, bytes, bytearray)): + rv.status = status + else: + rv.status_code = status + + # extend existing headers with provided headers + if headers: + rv.headers.update(headers) + + return rv + + def preprocess_request(self) -> ft.ResponseReturnValue | None: + """Called before the request is dispatched. Calls + :attr:`url_value_preprocessors` registered with the app and the + current blueprint (if any). Then calls :attr:`before_request_funcs` + registered with the app and the blueprint. + + If any :meth:`before_request` handler returns a non-None value, the + value is handled as if it was the return value from the view, and + further request handling is stopped. + """ + names = (None, *reversed(request.blueprints)) + + for name in names: + if name in self.url_value_preprocessors: + for url_func in self.url_value_preprocessors[name]: + url_func(request.endpoint, request.view_args) + + for name in names: + if name in self.before_request_funcs: + for before_func in self.before_request_funcs[name]: + rv = self.ensure_sync(before_func)() + + if rv is not None: + return rv # type: ignore[no-any-return] + + return None + + def process_response(self, response: Response) -> Response: + """Can be overridden in order to modify the response object + before it's sent to the WSGI server. By default this will + call all the :meth:`after_request` decorated functions. + + .. versionchanged:: 0.5 + As of Flask 0.5 the functions registered for after request + execution are called in reverse order of registration. + + :param response: a :attr:`response_class` object. + :return: a new response object or the same, has to be an + instance of :attr:`response_class`. + """ + ctx = request_ctx._get_current_object() # type: ignore[attr-defined] + + for func in ctx._after_request_functions: + response = self.ensure_sync(func)(response) + + for name in chain(request.blueprints, (None,)): + if name in self.after_request_funcs: + for func in reversed(self.after_request_funcs[name]): + response = self.ensure_sync(func)(response) + + if not self.session_interface.is_null_session(ctx._session): + self.session_interface.save_session(self, ctx._session, response) + + return response + + def do_teardown_request( + self, + exc: BaseException | None = _sentinel, # type: ignore[assignment] + ) -> None: + """Called after the request is dispatched and the response is + returned, right before the request context is popped. + + This calls all functions decorated with + :meth:`teardown_request`, and :meth:`Blueprint.teardown_request` + if a blueprint handled the request. Finally, the + :data:`request_tearing_down` signal is sent. + + This is called by + :meth:`RequestContext.pop() `, + which may be delayed during testing to maintain access to + resources. + + :param exc: An unhandled exception raised while dispatching the + request. Detected from the current exception information if + not passed. Passed to each teardown function. + + .. versionchanged:: 0.9 + Added the ``exc`` argument. + """ + if exc is _sentinel: + exc = sys.exc_info()[1] + + for name in chain(request.blueprints, (None,)): + if name in self.teardown_request_funcs: + for func in reversed(self.teardown_request_funcs[name]): + self.ensure_sync(func)(exc) + + request_tearing_down.send(self, _async_wrapper=self.ensure_sync, exc=exc) + + def do_teardown_appcontext( + self, + exc: BaseException | None = _sentinel, # type: ignore[assignment] + ) -> None: + """Called right before the application context is popped. + + When handling a request, the application context is popped + after the request context. See :meth:`do_teardown_request`. + + This calls all functions decorated with + :meth:`teardown_appcontext`. Then the + :data:`appcontext_tearing_down` signal is sent. + + This is called by + :meth:`AppContext.pop() `. + + .. versionadded:: 0.9 + """ + if exc is _sentinel: + exc = sys.exc_info()[1] + + for func in reversed(self.teardown_appcontext_funcs): + self.ensure_sync(func)(exc) + + appcontext_tearing_down.send(self, _async_wrapper=self.ensure_sync, exc=exc) + + def app_context(self) -> AppContext: + """Create an :class:`~flask.ctx.AppContext`. Use as a ``with`` + block to push the context, which will make :data:`current_app` + point at this application. + + An application context is automatically pushed by + :meth:`RequestContext.push() ` + when handling a request, and when running a CLI command. Use + this to manually create a context outside of these situations. + + :: + + with app.app_context(): + init_db() + + See :doc:`/appcontext`. + + .. versionadded:: 0.9 + """ + return AppContext(self) + + def request_context(self, environ: WSGIEnvironment) -> RequestContext: + """Create a :class:`~flask.ctx.RequestContext` representing a + WSGI environment. Use a ``with`` block to push the context, + which will make :data:`request` point at this request. + + See :doc:`/reqcontext`. + + Typically you should not call this from your own code. A request + context is automatically pushed by the :meth:`wsgi_app` when + handling a request. Use :meth:`test_request_context` to create + an environment and context instead of this method. + + :param environ: a WSGI environment + """ + return RequestContext(self, environ) + + def test_request_context(self, *args: t.Any, **kwargs: t.Any) -> RequestContext: + """Create a :class:`~flask.ctx.RequestContext` for a WSGI + environment created from the given values. This is mostly useful + during testing, where you may want to run a function that uses + request data without dispatching a full request. + + See :doc:`/reqcontext`. + + Use a ``with`` block to push the context, which will make + :data:`request` point at the request for the created + environment. :: + + with app.test_request_context(...): + generate_report() + + When using the shell, it may be easier to push and pop the + context manually to avoid indentation. :: + + ctx = app.test_request_context(...) + ctx.push() + ... + ctx.pop() + + Takes the same arguments as Werkzeug's + :class:`~werkzeug.test.EnvironBuilder`, with some defaults from + the application. See the linked Werkzeug docs for most of the + available arguments. Flask-specific behavior is listed here. + + :param path: URL path being requested. + :param base_url: Base URL where the app is being served, which + ``path`` is relative to. If not given, built from + :data:`PREFERRED_URL_SCHEME`, ``subdomain``, + :data:`SERVER_NAME`, and :data:`APPLICATION_ROOT`. + :param subdomain: Subdomain name to append to + :data:`SERVER_NAME`. + :param url_scheme: Scheme to use instead of + :data:`PREFERRED_URL_SCHEME`. + :param data: The request body, either as a string or a dict of + form keys and values. + :param json: If given, this is serialized as JSON and passed as + ``data``. Also defaults ``content_type`` to + ``application/json``. + :param args: other positional arguments passed to + :class:`~werkzeug.test.EnvironBuilder`. + :param kwargs: other keyword arguments passed to + :class:`~werkzeug.test.EnvironBuilder`. + """ + from .testing import EnvironBuilder + + builder = EnvironBuilder(self, *args, **kwargs) + + try: + return self.request_context(builder.get_environ()) + finally: + builder.close() + + def wsgi_app( + self, environ: WSGIEnvironment, start_response: StartResponse + ) -> cabc.Iterable[bytes]: + """The actual WSGI application. This is not implemented in + :meth:`__call__` so that middlewares can be applied without + losing a reference to the app object. Instead of doing this:: + + app = MyMiddleware(app) + + It's a better idea to do this instead:: + + app.wsgi_app = MyMiddleware(app.wsgi_app) + + Then you still have the original application object around and + can continue to call methods on it. + + .. versionchanged:: 0.7 + Teardown events for the request and app contexts are called + even if an unhandled error occurs. Other events may not be + called depending on when an error occurs during dispatch. + See :ref:`callbacks-and-errors`. + + :param environ: A WSGI environment. + :param start_response: A callable accepting a status code, + a list of headers, and an optional exception context to + start the response. + """ + ctx = self.request_context(environ) + error: BaseException | None = None + try: + try: + ctx.push() + response = self.full_dispatch_request() + except Exception as e: + error = e + response = self.handle_exception(e) + except: + error = sys.exc_info()[1] + raise + return response(environ, start_response) + finally: + if "werkzeug.debug.preserve_context" in environ: + environ["werkzeug.debug.preserve_context"](_cv_app.get()) + environ["werkzeug.debug.preserve_context"](_cv_request.get()) + + if error is not None and self.should_ignore_error(error): + error = None + + ctx.pop(error) + + def __call__( + self, environ: WSGIEnvironment, start_response: StartResponse + ) -> cabc.Iterable[bytes]: + """The WSGI server calls the Flask application object as the + WSGI application. This calls :meth:`wsgi_app`, which can be + wrapped to apply middleware. + """ + return self.wsgi_app(environ, start_response) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask/blueprints.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask/blueprints.py new file mode 100644 index 000000000..b6d4e4333 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask/blueprints.py @@ -0,0 +1,128 @@ +from __future__ import annotations + +import os +import typing as t +from datetime import timedelta + +from .cli import AppGroup +from .globals import current_app +from .helpers import send_from_directory +from .sansio.blueprints import Blueprint as SansioBlueprint +from .sansio.blueprints import BlueprintSetupState as BlueprintSetupState # noqa +from .sansio.scaffold import _sentinel + +if t.TYPE_CHECKING: # pragma: no cover + from .wrappers import Response + + +class Blueprint(SansioBlueprint): + def __init__( + self, + name: str, + import_name: str, + static_folder: str | os.PathLike[str] | None = None, + static_url_path: str | None = None, + template_folder: str | os.PathLike[str] | None = None, + url_prefix: str | None = None, + subdomain: str | None = None, + url_defaults: dict[str, t.Any] | None = None, + root_path: str | None = None, + cli_group: str | None = _sentinel, # type: ignore + ) -> None: + super().__init__( + name, + import_name, + static_folder, + static_url_path, + template_folder, + url_prefix, + subdomain, + url_defaults, + root_path, + cli_group, + ) + + #: The Click command group for registering CLI commands for this + #: object. The commands are available from the ``flask`` command + #: once the application has been discovered and blueprints have + #: been registered. + self.cli = AppGroup() + + # Set the name of the Click group in case someone wants to add + # the app's commands to another CLI tool. + self.cli.name = self.name + + def get_send_file_max_age(self, filename: str | None) -> int | None: + """Used by :func:`send_file` to determine the ``max_age`` cache + value for a given file path if it wasn't passed. + + By default, this returns :data:`SEND_FILE_MAX_AGE_DEFAULT` from + the configuration of :data:`~flask.current_app`. This defaults + to ``None``, which tells the browser to use conditional requests + instead of a timed cache, which is usually preferable. + + Note this is a duplicate of the same method in the Flask + class. + + .. versionchanged:: 2.0 + The default configuration is ``None`` instead of 12 hours. + + .. versionadded:: 0.9 + """ + value = current_app.config["SEND_FILE_MAX_AGE_DEFAULT"] + + if value is None: + return None + + if isinstance(value, timedelta): + return int(value.total_seconds()) + + return value # type: ignore[no-any-return] + + def send_static_file(self, filename: str) -> Response: + """The view function used to serve files from + :attr:`static_folder`. A route is automatically registered for + this view at :attr:`static_url_path` if :attr:`static_folder` is + set. + + Note this is a duplicate of the same method in the Flask + class. + + .. versionadded:: 0.5 + + """ + if not self.has_static_folder: + raise RuntimeError("'static_folder' must be set to serve static_files.") + + # send_file only knows to call get_send_file_max_age on the app, + # call it here so it works for blueprints too. + max_age = self.get_send_file_max_age(filename) + return send_from_directory( + t.cast(str, self.static_folder), filename, max_age=max_age + ) + + def open_resource( + self, resource: str, mode: str = "rb", encoding: str | None = "utf-8" + ) -> t.IO[t.AnyStr]: + """Open a resource file relative to :attr:`root_path` for reading. The + blueprint-relative equivalent of the app's :meth:`~.Flask.open_resource` + method. + + :param resource: Path to the resource relative to :attr:`root_path`. + :param mode: Open the file in this mode. Only reading is supported, + valid values are ``"r"`` (or ``"rt"``) and ``"rb"``. + :param encoding: Open the file with this encoding when opening in text + mode. This is ignored when opening in binary mode. + + .. versionchanged:: 3.1 + Added the ``encoding`` parameter. + """ + if mode not in {"r", "rt", "rb"}: + raise ValueError("Resources can only be opened for reading.") + + path = os.path.join(self.root_path, resource) + + if mode == "rb": + return open(path, mode) # pyright: ignore + + return open(path, mode, encoding=encoding) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask/cli.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask/cli.py new file mode 100644 index 000000000..ed11f256a --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask/cli.py @@ -0,0 +1,1135 @@ +from __future__ import annotations + +import ast +import collections.abc as cabc +import importlib.metadata +import inspect +import os +import platform +import re +import sys +import traceback +import typing as t +from functools import update_wrapper +from operator import itemgetter +from types import ModuleType + +import click +from click.core import ParameterSource +from werkzeug import run_simple +from werkzeug.serving import is_running_from_reloader +from werkzeug.utils import import_string + +from .globals import current_app +from .helpers import get_debug_flag +from .helpers import get_load_dotenv + +if t.TYPE_CHECKING: + import ssl + + from _typeshed.wsgi import StartResponse + from _typeshed.wsgi import WSGIApplication + from _typeshed.wsgi import WSGIEnvironment + + from .app import Flask + + +class NoAppException(click.UsageError): + """Raised if an application cannot be found or loaded.""" + + +def find_best_app(module: ModuleType) -> Flask: + """Given a module instance this tries to find the best possible + application in the module or raises an exception. + """ + from . import Flask + + # Search for the most common names first. + for attr_name in ("app", "application"): + app = getattr(module, attr_name, None) + + if isinstance(app, Flask): + return app + + # Otherwise find the only object that is a Flask instance. + matches = [v for v in module.__dict__.values() if isinstance(v, Flask)] + + if len(matches) == 1: + return matches[0] + elif len(matches) > 1: + raise NoAppException( + "Detected multiple Flask applications in module" + f" '{module.__name__}'. Use '{module.__name__}:name'" + " to specify the correct one." + ) + + # Search for app factory functions. + for attr_name in ("create_app", "make_app"): + app_factory = getattr(module, attr_name, None) + + if inspect.isfunction(app_factory): + try: + app = app_factory() + + if isinstance(app, Flask): + return app + except TypeError as e: + if not _called_with_wrong_args(app_factory): + raise + + raise NoAppException( + f"Detected factory '{attr_name}' in module '{module.__name__}'," + " but could not call it without arguments. Use" + f" '{module.__name__}:{attr_name}(args)'" + " to specify arguments." + ) from e + + raise NoAppException( + "Failed to find Flask application or factory in module" + f" '{module.__name__}'. Use '{module.__name__}:name'" + " to specify one." + ) + + +def _called_with_wrong_args(f: t.Callable[..., Flask]) -> bool: + """Check whether calling a function raised a ``TypeError`` because + the call failed or because something in the factory raised the + error. + + :param f: The function that was called. + :return: ``True`` if the call failed. + """ + tb = sys.exc_info()[2] + + try: + while tb is not None: + if tb.tb_frame.f_code is f.__code__: + # In the function, it was called successfully. + return False + + tb = tb.tb_next + + # Didn't reach the function. + return True + finally: + # Delete tb to break a circular reference. + # https://docs.python.org/2/library/sys.html#sys.exc_info + del tb + + +def find_app_by_string(module: ModuleType, app_name: str) -> Flask: + """Check if the given string is a variable name or a function. Call + a function to get the app instance, or return the variable directly. + """ + from . import Flask + + # Parse app_name as a single expression to determine if it's a valid + # attribute name or function call. + try: + expr = ast.parse(app_name.strip(), mode="eval").body + except SyntaxError: + raise NoAppException( + f"Failed to parse {app_name!r} as an attribute name or function call." + ) from None + + if isinstance(expr, ast.Name): + name = expr.id + args = [] + kwargs = {} + elif isinstance(expr, ast.Call): + # Ensure the function name is an attribute name only. + if not isinstance(expr.func, ast.Name): + raise NoAppException( + f"Function reference must be a simple name: {app_name!r}." + ) + + name = expr.func.id + + # Parse the positional and keyword arguments as literals. + try: + args = [ast.literal_eval(arg) for arg in expr.args] + kwargs = { + kw.arg: ast.literal_eval(kw.value) + for kw in expr.keywords + if kw.arg is not None + } + except ValueError: + # literal_eval gives cryptic error messages, show a generic + # message with the full expression instead. + raise NoAppException( + f"Failed to parse arguments as literal values: {app_name!r}." + ) from None + else: + raise NoAppException( + f"Failed to parse {app_name!r} as an attribute name or function call." + ) + + try: + attr = getattr(module, name) + except AttributeError as e: + raise NoAppException( + f"Failed to find attribute {name!r} in {module.__name__!r}." + ) from e + + # If the attribute is a function, call it with any args and kwargs + # to get the real application. + if inspect.isfunction(attr): + try: + app = attr(*args, **kwargs) + except TypeError as e: + if not _called_with_wrong_args(attr): + raise + + raise NoAppException( + f"The factory {app_name!r} in module" + f" {module.__name__!r} could not be called with the" + " specified arguments." + ) from e + else: + app = attr + + if isinstance(app, Flask): + return app + + raise NoAppException( + "A valid Flask application was not obtained from" + f" '{module.__name__}:{app_name}'." + ) + + +def prepare_import(path: str) -> str: + """Given a filename this will try to calculate the python path, add it + to the search path and return the actual module name that is expected. + """ + path = os.path.realpath(path) + + fname, ext = os.path.splitext(path) + if ext == ".py": + path = fname + + if os.path.basename(path) == "__init__": + path = os.path.dirname(path) + + module_name = [] + + # move up until outside package structure (no __init__.py) + while True: + path, name = os.path.split(path) + module_name.append(name) + + if not os.path.exists(os.path.join(path, "__init__.py")): + break + + if sys.path[0] != path: + sys.path.insert(0, path) + + return ".".join(module_name[::-1]) + + +@t.overload +def locate_app( + module_name: str, app_name: str | None, raise_if_not_found: t.Literal[True] = True +) -> Flask: ... + + +@t.overload +def locate_app( + module_name: str, app_name: str | None, raise_if_not_found: t.Literal[False] = ... +) -> Flask | None: ... + + +def locate_app( + module_name: str, app_name: str | None, raise_if_not_found: bool = True +) -> Flask | None: + try: + __import__(module_name) + except ImportError: + # Reraise the ImportError if it occurred within the imported module. + # Determine this by checking whether the trace has a depth > 1. + if sys.exc_info()[2].tb_next: # type: ignore[union-attr] + raise NoAppException( + f"While importing {module_name!r}, an ImportError was" + f" raised:\n\n{traceback.format_exc()}" + ) from None + elif raise_if_not_found: + raise NoAppException(f"Could not import {module_name!r}.") from None + else: + return None + + module = sys.modules[module_name] + + if app_name is None: + return find_best_app(module) + else: + return find_app_by_string(module, app_name) + + +def get_version(ctx: click.Context, param: click.Parameter, value: t.Any) -> None: + if not value or ctx.resilient_parsing: + return + + flask_version = importlib.metadata.version("flask") + werkzeug_version = importlib.metadata.version("werkzeug") + + click.echo( + f"Python {platform.python_version()}\n" + f"Flask {flask_version}\n" + f"Werkzeug {werkzeug_version}", + color=ctx.color, + ) + ctx.exit() + + +version_option = click.Option( + ["--version"], + help="Show the Flask version.", + expose_value=False, + callback=get_version, + is_flag=True, + is_eager=True, +) + + +class ScriptInfo: + """Helper object to deal with Flask applications. This is usually not + necessary to interface with as it's used internally in the dispatching + to click. In future versions of Flask this object will most likely play + a bigger role. Typically it's created automatically by the + :class:`FlaskGroup` but you can also manually create it and pass it + onwards as click object. + + .. versionchanged:: 3.1 + Added the ``load_dotenv_defaults`` parameter and attribute. + """ + + def __init__( + self, + app_import_path: str | None = None, + create_app: t.Callable[..., Flask] | None = None, + set_debug_flag: bool = True, + load_dotenv_defaults: bool = True, + ) -> None: + #: Optionally the import path for the Flask application. + self.app_import_path = app_import_path + #: Optionally a function that is passed the script info to create + #: the instance of the application. + self.create_app = create_app + #: A dictionary with arbitrary data that can be associated with + #: this script info. + self.data: dict[t.Any, t.Any] = {} + self.set_debug_flag = set_debug_flag + + self.load_dotenv_defaults = get_load_dotenv(load_dotenv_defaults) + """Whether default ``.flaskenv`` and ``.env`` files should be loaded. + + ``ScriptInfo`` doesn't load anything, this is for reference when doing + the load elsewhere during processing. + + .. versionadded:: 3.1 + """ + + self._loaded_app: Flask | None = None + + def load_app(self) -> Flask: + """Loads the Flask app (if not yet loaded) and returns it. Calling + this multiple times will just result in the already loaded app to + be returned. + """ + if self._loaded_app is not None: + return self._loaded_app + app: Flask | None = None + if self.create_app is not None: + app = self.create_app() + else: + if self.app_import_path: + path, name = ( + re.split(r":(?![\\/])", self.app_import_path, maxsplit=1) + [None] + )[:2] + import_name = prepare_import(path) + app = locate_app(import_name, name) + else: + for path in ("wsgi.py", "app.py"): + import_name = prepare_import(path) + app = locate_app(import_name, None, raise_if_not_found=False) + + if app is not None: + break + + if app is None: + raise NoAppException( + "Could not locate a Flask application. Use the" + " 'flask --app' option, 'FLASK_APP' environment" + " variable, or a 'wsgi.py' or 'app.py' file in the" + " current directory." + ) + + if self.set_debug_flag: + # Update the app's debug flag through the descriptor so that + # other values repopulate as well. + app.debug = get_debug_flag() + + self._loaded_app = app + return app + + +pass_script_info = click.make_pass_decorator(ScriptInfo, ensure=True) + +F = t.TypeVar("F", bound=t.Callable[..., t.Any]) + + +def with_appcontext(f: F) -> F: + """Wraps a callback so that it's guaranteed to be executed with the + script's application context. + + Custom commands (and their options) registered under ``app.cli`` or + ``blueprint.cli`` will always have an app context available, this + decorator is not required in that case. + + .. versionchanged:: 2.2 + The app context is active for subcommands as well as the + decorated callback. The app context is always available to + ``app.cli`` command and parameter callbacks. + """ + + @click.pass_context + def decorator(ctx: click.Context, /, *args: t.Any, **kwargs: t.Any) -> t.Any: + if not current_app: + app = ctx.ensure_object(ScriptInfo).load_app() + ctx.with_resource(app.app_context()) + + return ctx.invoke(f, *args, **kwargs) + + return update_wrapper(decorator, f) # type: ignore[return-value] + + +class AppGroup(click.Group): + """This works similar to a regular click :class:`~click.Group` but it + changes the behavior of the :meth:`command` decorator so that it + automatically wraps the functions in :func:`with_appcontext`. + + Not to be confused with :class:`FlaskGroup`. + """ + + def command( # type: ignore[override] + self, *args: t.Any, **kwargs: t.Any + ) -> t.Callable[[t.Callable[..., t.Any]], click.Command]: + """This works exactly like the method of the same name on a regular + :class:`click.Group` but it wraps callbacks in :func:`with_appcontext` + unless it's disabled by passing ``with_appcontext=False``. + """ + wrap_for_ctx = kwargs.pop("with_appcontext", True) + + def decorator(f: t.Callable[..., t.Any]) -> click.Command: + if wrap_for_ctx: + f = with_appcontext(f) + return super(AppGroup, self).command(*args, **kwargs)(f) # type: ignore[no-any-return] + + return decorator + + def group( # type: ignore[override] + self, *args: t.Any, **kwargs: t.Any + ) -> t.Callable[[t.Callable[..., t.Any]], click.Group]: + """This works exactly like the method of the same name on a regular + :class:`click.Group` but it defaults the group class to + :class:`AppGroup`. + """ + kwargs.setdefault("cls", AppGroup) + return super().group(*args, **kwargs) # type: ignore[no-any-return] + + +def _set_app(ctx: click.Context, param: click.Option, value: str | None) -> str | None: + if value is None: + return None + + info = ctx.ensure_object(ScriptInfo) + info.app_import_path = value + return value + + +# This option is eager so the app will be available if --help is given. +# --help is also eager, so --app must be before it in the param list. +# no_args_is_help bypasses eager processing, so this option must be +# processed manually in that case to ensure FLASK_APP gets picked up. +_app_option = click.Option( + ["-A", "--app"], + metavar="IMPORT", + help=( + "The Flask application or factory function to load, in the form 'module:name'." + " Module can be a dotted import or file path. Name is not required if it is" + " 'app', 'application', 'create_app', or 'make_app', and can be 'name(args)' to" + " pass arguments." + ), + is_eager=True, + expose_value=False, + callback=_set_app, +) + + +def _set_debug(ctx: click.Context, param: click.Option, value: bool) -> bool | None: + # If the flag isn't provided, it will default to False. Don't use + # that, let debug be set by env in that case. + source = ctx.get_parameter_source(param.name) # type: ignore[arg-type] + + if source is not None and source in ( + ParameterSource.DEFAULT, + ParameterSource.DEFAULT_MAP, + ): + return None + + # Set with env var instead of ScriptInfo.load so that it can be + # accessed early during a factory function. + os.environ["FLASK_DEBUG"] = "1" if value else "0" + return value + + +_debug_option = click.Option( + ["--debug/--no-debug"], + help="Set debug mode.", + expose_value=False, + callback=_set_debug, +) + + +def _env_file_callback( + ctx: click.Context, param: click.Option, value: str | None +) -> str | None: + try: + import dotenv # noqa: F401 + except ImportError: + # Only show an error if a value was passed, otherwise we still want to + # call load_dotenv and show a message without exiting. + if value is not None: + raise click.BadParameter( + "python-dotenv must be installed to load an env file.", + ctx=ctx, + param=param, + ) from None + + # Load if a value was passed, or we want to load default files, or both. + if value is not None or ctx.obj.load_dotenv_defaults: + load_dotenv(value, load_defaults=ctx.obj.load_dotenv_defaults) + + return value + + +# This option is eager so env vars are loaded as early as possible to be +# used by other options. +_env_file_option = click.Option( + ["-e", "--env-file"], + type=click.Path(exists=True, dir_okay=False), + help=( + "Load environment variables from this file, taking precedence over" + " those set by '.env' and '.flaskenv'. Variables set directly in the" + " environment take highest precedence. python-dotenv must be installed." + ), + is_eager=True, + expose_value=False, + callback=_env_file_callback, +) + + +class FlaskGroup(AppGroup): + """Special subclass of the :class:`AppGroup` group that supports + loading more commands from the configured Flask app. Normally a + developer does not have to interface with this class but there are + some very advanced use cases for which it makes sense to create an + instance of this. see :ref:`custom-scripts`. + + :param add_default_commands: if this is True then the default run and + shell commands will be added. + :param add_version_option: adds the ``--version`` option. + :param create_app: an optional callback that is passed the script info and + returns the loaded app. + :param load_dotenv: Load the nearest :file:`.env` and :file:`.flaskenv` + files to set environment variables. Will also change the working + directory to the directory containing the first file found. + :param set_debug_flag: Set the app's debug flag. + + .. versionchanged:: 3.1 + ``-e path`` takes precedence over default ``.env`` and ``.flaskenv`` files. + + .. versionchanged:: 2.2 + Added the ``-A/--app``, ``--debug/--no-debug``, ``-e/--env-file`` options. + + .. versionchanged:: 2.2 + An app context is pushed when running ``app.cli`` commands, so + ``@with_appcontext`` is no longer required for those commands. + + .. versionchanged:: 1.0 + If installed, python-dotenv will be used to load environment variables + from :file:`.env` and :file:`.flaskenv` files. + """ + + def __init__( + self, + add_default_commands: bool = True, + create_app: t.Callable[..., Flask] | None = None, + add_version_option: bool = True, + load_dotenv: bool = True, + set_debug_flag: bool = True, + **extra: t.Any, + ) -> None: + params: list[click.Parameter] = list(extra.pop("params", None) or ()) + # Processing is done with option callbacks instead of a group + # callback. This allows users to make a custom group callback + # without losing the behavior. --env-file must come first so + # that it is eagerly evaluated before --app. + params.extend((_env_file_option, _app_option, _debug_option)) + + if add_version_option: + params.append(version_option) + + if "context_settings" not in extra: + extra["context_settings"] = {} + + extra["context_settings"].setdefault("auto_envvar_prefix", "FLASK") + + super().__init__(params=params, **extra) + + self.create_app = create_app + self.load_dotenv = load_dotenv + self.set_debug_flag = set_debug_flag + + if add_default_commands: + self.add_command(run_command) + self.add_command(shell_command) + self.add_command(routes_command) + + self._loaded_plugin_commands = False + + def _load_plugin_commands(self) -> None: + if self._loaded_plugin_commands: + return + + if sys.version_info >= (3, 10): + from importlib import metadata + else: + # Use a backport on Python < 3.10. We technically have + # importlib.metadata on 3.8+, but the API changed in 3.10, + # so use the backport for consistency. + import importlib_metadata as metadata # pyright: ignore + + for ep in metadata.entry_points(group="flask.commands"): + self.add_command(ep.load(), ep.name) + + self._loaded_plugin_commands = True + + def get_command(self, ctx: click.Context, name: str) -> click.Command | None: + self._load_plugin_commands() + # Look up built-in and plugin commands, which should be + # available even if the app fails to load. + rv = super().get_command(ctx, name) + + if rv is not None: + return rv + + info = ctx.ensure_object(ScriptInfo) + + # Look up commands provided by the app, showing an error and + # continuing if the app couldn't be loaded. + try: + app = info.load_app() + except NoAppException as e: + click.secho(f"Error: {e.format_message()}\n", err=True, fg="red") + return None + + # Push an app context for the loaded app unless it is already + # active somehow. This makes the context available to parameter + # and command callbacks without needing @with_appcontext. + if not current_app or current_app._get_current_object() is not app: # type: ignore[attr-defined] + ctx.with_resource(app.app_context()) + + return app.cli.get_command(ctx, name) + + def list_commands(self, ctx: click.Context) -> list[str]: + self._load_plugin_commands() + # Start with the built-in and plugin commands. + rv = set(super().list_commands(ctx)) + info = ctx.ensure_object(ScriptInfo) + + # Add commands provided by the app, showing an error and + # continuing if the app couldn't be loaded. + try: + rv.update(info.load_app().cli.list_commands(ctx)) + except NoAppException as e: + # When an app couldn't be loaded, show the error message + # without the traceback. + click.secho(f"Error: {e.format_message()}\n", err=True, fg="red") + except Exception: + # When any other errors occurred during loading, show the + # full traceback. + click.secho(f"{traceback.format_exc()}\n", err=True, fg="red") + + return sorted(rv) + + def make_context( + self, + info_name: str | None, + args: list[str], + parent: click.Context | None = None, + **extra: t.Any, + ) -> click.Context: + # Set a flag to tell app.run to become a no-op. If app.run was + # not in a __name__ == __main__ guard, it would start the server + # when importing, blocking whatever command is being called. + os.environ["FLASK_RUN_FROM_CLI"] = "true" + + if "obj" not in extra and "obj" not in self.context_settings: + extra["obj"] = ScriptInfo( + create_app=self.create_app, + set_debug_flag=self.set_debug_flag, + load_dotenv_defaults=self.load_dotenv, + ) + + return super().make_context(info_name, args, parent=parent, **extra) + + def parse_args(self, ctx: click.Context, args: list[str]) -> list[str]: + if (not args and self.no_args_is_help) or ( + len(args) == 1 and args[0] in self.get_help_option_names(ctx) + ): + # Attempt to load --env-file and --app early in case they + # were given as env vars. Otherwise no_args_is_help will not + # see commands from app.cli. + _env_file_option.handle_parse_result(ctx, {}, []) + _app_option.handle_parse_result(ctx, {}, []) + + return super().parse_args(ctx, args) + + +def _path_is_ancestor(path: str, other: str) -> bool: + """Take ``other`` and remove the length of ``path`` from it. Then join it + to ``path``. If it is the original value, ``path`` is an ancestor of + ``other``.""" + return os.path.join(path, other[len(path) :].lstrip(os.sep)) == other + + +def load_dotenv( + path: str | os.PathLike[str] | None = None, load_defaults: bool = True +) -> bool: + """Load "dotenv" files to set environment variables. A given path takes + precedence over ``.env``, which takes precedence over ``.flaskenv``. After + loading and combining these files, values are only set if the key is not + already set in ``os.environ``. + + This is a no-op if `python-dotenv`_ is not installed. + + .. _python-dotenv: https://github.com/theskumar/python-dotenv#readme + + :param path: Load the file at this location. + :param load_defaults: Search for and load the default ``.flaskenv`` and + ``.env`` files. + :return: ``True`` if at least one env var was loaded. + + .. versionchanged:: 3.1 + Added the ``load_defaults`` parameter. A given path takes precedence + over default files. + + .. versionchanged:: 2.0 + The current directory is not changed to the location of the + loaded file. + + .. versionchanged:: 2.0 + When loading the env files, set the default encoding to UTF-8. + + .. versionchanged:: 1.1.0 + Returns ``False`` when python-dotenv is not installed, or when + the given path isn't a file. + + .. versionadded:: 1.0 + """ + try: + import dotenv + except ImportError: + if path or os.path.isfile(".env") or os.path.isfile(".flaskenv"): + click.secho( + " * Tip: There are .env files present. Install python-dotenv" + " to use them.", + fg="yellow", + err=True, + ) + + return False + + data: dict[str, str | None] = {} + + if load_defaults: + for default_name in (".flaskenv", ".env"): + if not (default_path := dotenv.find_dotenv(default_name, usecwd=True)): + continue + + data |= dotenv.dotenv_values(default_path, encoding="utf-8") + + if path is not None and os.path.isfile(path): + data |= dotenv.dotenv_values(path, encoding="utf-8") + + for key, value in data.items(): + if key in os.environ or value is None: + continue + + os.environ[key] = value + + return bool(data) # True if at least one env var was loaded. + + +def show_server_banner(debug: bool, app_import_path: str | None) -> None: + """Show extra startup messages the first time the server is run, + ignoring the reloader. + """ + if is_running_from_reloader(): + return + + if app_import_path is not None: + click.echo(f" * Serving Flask app '{app_import_path}'") + + if debug is not None: + click.echo(f" * Debug mode: {'on' if debug else 'off'}") + + +class CertParamType(click.ParamType): + """Click option type for the ``--cert`` option. Allows either an + existing file, the string ``'adhoc'``, or an import for a + :class:`~ssl.SSLContext` object. + """ + + name = "path" + + def __init__(self) -> None: + self.path_type = click.Path(exists=True, dir_okay=False, resolve_path=True) + + def convert( + self, value: t.Any, param: click.Parameter | None, ctx: click.Context | None + ) -> t.Any: + try: + import ssl + except ImportError: + raise click.BadParameter( + 'Using "--cert" requires Python to be compiled with SSL support.', + ctx, + param, + ) from None + + try: + return self.path_type(value, param, ctx) + except click.BadParameter: + value = click.STRING(value, param, ctx).lower() + + if value == "adhoc": + try: + import cryptography # noqa: F401 + except ImportError: + raise click.BadParameter( + "Using ad-hoc certificates requires the cryptography library.", + ctx, + param, + ) from None + + return value + + obj = import_string(value, silent=True) + + if isinstance(obj, ssl.SSLContext): + return obj + + raise + + +def _validate_key(ctx: click.Context, param: click.Parameter, value: t.Any) -> t.Any: + """The ``--key`` option must be specified when ``--cert`` is a file. + Modifies the ``cert`` param to be a ``(cert, key)`` pair if needed. + """ + cert = ctx.params.get("cert") + is_adhoc = cert == "adhoc" + + try: + import ssl + except ImportError: + is_context = False + else: + is_context = isinstance(cert, ssl.SSLContext) + + if value is not None: + if is_adhoc: + raise click.BadParameter( + 'When "--cert" is "adhoc", "--key" is not used.', ctx, param + ) + + if is_context: + raise click.BadParameter( + 'When "--cert" is an SSLContext object, "--key" is not used.', + ctx, + param, + ) + + if not cert: + raise click.BadParameter('"--cert" must also be specified.', ctx, param) + + ctx.params["cert"] = cert, value + + else: + if cert and not (is_adhoc or is_context): + raise click.BadParameter('Required when using "--cert".', ctx, param) + + return value + + +class SeparatedPathType(click.Path): + """Click option type that accepts a list of values separated by the + OS's path separator (``:``, ``;`` on Windows). Each value is + validated as a :class:`click.Path` type. + """ + + def convert( + self, value: t.Any, param: click.Parameter | None, ctx: click.Context | None + ) -> t.Any: + items = self.split_envvar_value(value) + # can't call no-arg super() inside list comprehension until Python 3.12 + super_convert = super().convert + return [super_convert(item, param, ctx) for item in items] + + +@click.command("run", short_help="Run a development server.") +@click.option("--host", "-h", default="127.0.0.1", help="The interface to bind to.") +@click.option("--port", "-p", default=5000, help="The port to bind to.") +@click.option( + "--cert", + type=CertParamType(), + help="Specify a certificate file to use HTTPS.", + is_eager=True, +) +@click.option( + "--key", + type=click.Path(exists=True, dir_okay=False, resolve_path=True), + callback=_validate_key, + expose_value=False, + help="The key file to use when specifying a certificate.", +) +@click.option( + "--reload/--no-reload", + default=None, + help="Enable or disable the reloader. By default the reloader " + "is active if debug is enabled.", +) +@click.option( + "--debugger/--no-debugger", + default=None, + help="Enable or disable the debugger. By default the debugger " + "is active if debug is enabled.", +) +@click.option( + "--with-threads/--without-threads", + default=True, + help="Enable or disable multithreading.", +) +@click.option( + "--extra-files", + default=None, + type=SeparatedPathType(), + help=( + "Extra files that trigger a reload on change. Multiple paths" + f" are separated by {os.path.pathsep!r}." + ), +) +@click.option( + "--exclude-patterns", + default=None, + type=SeparatedPathType(), + help=( + "Files matching these fnmatch patterns will not trigger a reload" + " on change. Multiple patterns are separated by" + f" {os.path.pathsep!r}." + ), +) +@pass_script_info +def run_command( + info: ScriptInfo, + host: str, + port: int, + reload: bool, + debugger: bool, + with_threads: bool, + cert: ssl.SSLContext | tuple[str, str | None] | t.Literal["adhoc"] | None, + extra_files: list[str] | None, + exclude_patterns: list[str] | None, +) -> None: + """Run a local development server. + + This server is for development purposes only. It does not provide + the stability, security, or performance of production WSGI servers. + + The reloader and debugger are enabled by default with the '--debug' + option. + """ + try: + app: WSGIApplication = info.load_app() # pyright: ignore + except Exception as e: + if is_running_from_reloader(): + # When reloading, print out the error immediately, but raise + # it later so the debugger or server can handle it. + traceback.print_exc() + err = e + + def app( + environ: WSGIEnvironment, start_response: StartResponse + ) -> cabc.Iterable[bytes]: + raise err from None + + else: + # When not reloading, raise the error immediately so the + # command fails. + raise e from None + + debug = get_debug_flag() + + if reload is None: + reload = debug + + if debugger is None: + debugger = debug + + show_server_banner(debug, info.app_import_path) + + run_simple( + host, + port, + app, + use_reloader=reload, + use_debugger=debugger, + threaded=with_threads, + ssl_context=cert, + extra_files=extra_files, + exclude_patterns=exclude_patterns, + ) + + +run_command.params.insert(0, _debug_option) + + +@click.command("shell", short_help="Run a shell in the app context.") +@with_appcontext +def shell_command() -> None: + """Run an interactive Python shell in the context of a given + Flask application. The application will populate the default + namespace of this shell according to its configuration. + + This is useful for executing small snippets of management code + without having to manually configure the application. + """ + import code + + banner = ( + f"Python {sys.version} on {sys.platform}\n" + f"App: {current_app.import_name}\n" + f"Instance: {current_app.instance_path}" + ) + ctx: dict[str, t.Any] = {} + + # Support the regular Python interpreter startup script if someone + # is using it. + startup = os.environ.get("PYTHONSTARTUP") + if startup and os.path.isfile(startup): + with open(startup) as f: + eval(compile(f.read(), startup, "exec"), ctx) + + ctx.update(current_app.make_shell_context()) + + # Site, customize, or startup script can set a hook to call when + # entering interactive mode. The default one sets up readline with + # tab and history completion. + interactive_hook = getattr(sys, "__interactivehook__", None) + + if interactive_hook is not None: + try: + import readline + from rlcompleter import Completer + except ImportError: + pass + else: + # rlcompleter uses __main__.__dict__ by default, which is + # flask.__main__. Use the shell context instead. + readline.set_completer(Completer(ctx).complete) + + interactive_hook() + + code.interact(banner=banner, local=ctx) + + +@click.command("routes", short_help="Show the routes for the app.") +@click.option( + "--sort", + "-s", + type=click.Choice(("endpoint", "methods", "domain", "rule", "match")), + default="endpoint", + help=( + "Method to sort routes by. 'match' is the order that Flask will match routes" + " when dispatching a request." + ), +) +@click.option("--all-methods", is_flag=True, help="Show HEAD and OPTIONS methods.") +@with_appcontext +def routes_command(sort: str, all_methods: bool) -> None: + """Show all registered routes with endpoints and methods.""" + rules = list(current_app.url_map.iter_rules()) + + if not rules: + click.echo("No routes were registered.") + return + + ignored_methods = set() if all_methods else {"HEAD", "OPTIONS"} + host_matching = current_app.url_map.host_matching + has_domain = any(rule.host if host_matching else rule.subdomain for rule in rules) + rows = [] + + for rule in rules: + row = [ + rule.endpoint, + ", ".join(sorted((rule.methods or set()) - ignored_methods)), + ] + + if has_domain: + row.append((rule.host if host_matching else rule.subdomain) or "") + + row.append(rule.rule) + rows.append(row) + + headers = ["Endpoint", "Methods"] + sorts = ["endpoint", "methods"] + + if has_domain: + headers.append("Host" if host_matching else "Subdomain") + sorts.append("domain") + + headers.append("Rule") + sorts.append("rule") + + try: + rows.sort(key=itemgetter(sorts.index(sort))) + except ValueError: + pass + + rows.insert(0, headers) + widths = [max(len(row[i]) for row in rows) for i in range(len(headers))] + rows.insert(1, ["-" * w for w in widths]) + template = " ".join(f"{{{i}:<{w}}}" for i, w in enumerate(widths)) + + for row in rows: + click.echo(template.format(*row)) + + +cli = FlaskGroup( + name="flask", + help="""\ +A general utility script for Flask applications. + +An application to load must be given with the '--app' option, +'FLASK_APP' environment variable, or with a 'wsgi.py' or 'app.py' file +in the current directory. +""", +) + + +def main() -> None: + cli.main() + + +if __name__ == "__main__": + main() diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask/config.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask/config.py new file mode 100644 index 000000000..34ef1a572 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask/config.py @@ -0,0 +1,367 @@ +from __future__ import annotations + +import errno +import json +import os +import types +import typing as t + +from werkzeug.utils import import_string + +if t.TYPE_CHECKING: + import typing_extensions as te + + from .sansio.app import App + + +T = t.TypeVar("T") + + +class ConfigAttribute(t.Generic[T]): + """Makes an attribute forward to the config""" + + def __init__( + self, name: str, get_converter: t.Callable[[t.Any], T] | None = None + ) -> None: + self.__name__ = name + self.get_converter = get_converter + + @t.overload + def __get__(self, obj: None, owner: None) -> te.Self: ... + + @t.overload + def __get__(self, obj: App, owner: type[App]) -> T: ... + + def __get__(self, obj: App | None, owner: type[App] | None = None) -> T | te.Self: + if obj is None: + return self + + rv = obj.config[self.__name__] + + if self.get_converter is not None: + rv = self.get_converter(rv) + + return rv # type: ignore[no-any-return] + + def __set__(self, obj: App, value: t.Any) -> None: + obj.config[self.__name__] = value + + +class Config(dict): # type: ignore[type-arg] + """Works exactly like a dict but provides ways to fill it from files + or special dictionaries. There are two common patterns to populate the + config. + + Either you can fill the config from a config file:: + + app.config.from_pyfile('yourconfig.cfg') + + Or alternatively you can define the configuration options in the + module that calls :meth:`from_object` or provide an import path to + a module that should be loaded. It is also possible to tell it to + use the same module and with that provide the configuration values + just before the call:: + + DEBUG = True + SECRET_KEY = 'development key' + app.config.from_object(__name__) + + In both cases (loading from any Python file or loading from modules), + only uppercase keys are added to the config. This makes it possible to use + lowercase values in the config file for temporary values that are not added + to the config or to define the config keys in the same file that implements + the application. + + Probably the most interesting way to load configurations is from an + environment variable pointing to a file:: + + app.config.from_envvar('YOURAPPLICATION_SETTINGS') + + In this case before launching the application you have to set this + environment variable to the file you want to use. On Linux and OS X + use the export statement:: + + export YOURAPPLICATION_SETTINGS='/path/to/config/file' + + On windows use `set` instead. + + :param root_path: path to which files are read relative from. When the + config object is created by the application, this is + the application's :attr:`~flask.Flask.root_path`. + :param defaults: an optional dictionary of default values + """ + + def __init__( + self, + root_path: str | os.PathLike[str], + defaults: dict[str, t.Any] | None = None, + ) -> None: + super().__init__(defaults or {}) + self.root_path = root_path + + def from_envvar(self, variable_name: str, silent: bool = False) -> bool: + """Loads a configuration from an environment variable pointing to + a configuration file. This is basically just a shortcut with nicer + error messages for this line of code:: + + app.config.from_pyfile(os.environ['YOURAPPLICATION_SETTINGS']) + + :param variable_name: name of the environment variable + :param silent: set to ``True`` if you want silent failure for missing + files. + :return: ``True`` if the file was loaded successfully. + """ + rv = os.environ.get(variable_name) + if not rv: + if silent: + return False + raise RuntimeError( + f"The environment variable {variable_name!r} is not set" + " and as such configuration could not be loaded. Set" + " this variable and make it point to a configuration" + " file" + ) + return self.from_pyfile(rv, silent=silent) + + def from_prefixed_env( + self, prefix: str = "FLASK", *, loads: t.Callable[[str], t.Any] = json.loads + ) -> bool: + """Load any environment variables that start with ``FLASK_``, + dropping the prefix from the env key for the config key. Values + are passed through a loading function to attempt to convert them + to more specific types than strings. + + Keys are loaded in :func:`sorted` order. + + The default loading function attempts to parse values as any + valid JSON type, including dicts and lists. + + Specific items in nested dicts can be set by separating the + keys with double underscores (``__``). If an intermediate key + doesn't exist, it will be initialized to an empty dict. + + :param prefix: Load env vars that start with this prefix, + separated with an underscore (``_``). + :param loads: Pass each string value to this function and use + the returned value as the config value. If any error is + raised it is ignored and the value remains a string. The + default is :func:`json.loads`. + + .. versionadded:: 2.1 + """ + prefix = f"{prefix}_" + + for key in sorted(os.environ): + if not key.startswith(prefix): + continue + + value = os.environ[key] + key = key.removeprefix(prefix) + + try: + value = loads(value) + except Exception: + # Keep the value as a string if loading failed. + pass + + if "__" not in key: + # A non-nested key, set directly. + self[key] = value + continue + + # Traverse nested dictionaries with keys separated by "__". + current = self + *parts, tail = key.split("__") + + for part in parts: + # If an intermediate dict does not exist, create it. + if part not in current: + current[part] = {} + + current = current[part] + + current[tail] = value + + return True + + def from_pyfile( + self, filename: str | os.PathLike[str], silent: bool = False + ) -> bool: + """Updates the values in the config from a Python file. This function + behaves as if the file was imported as module with the + :meth:`from_object` function. + + :param filename: the filename of the config. This can either be an + absolute filename or a filename relative to the + root path. + :param silent: set to ``True`` if you want silent failure for missing + files. + :return: ``True`` if the file was loaded successfully. + + .. versionadded:: 0.7 + `silent` parameter. + """ + filename = os.path.join(self.root_path, filename) + d = types.ModuleType("config") + d.__file__ = filename + try: + with open(filename, mode="rb") as config_file: + exec(compile(config_file.read(), filename, "exec"), d.__dict__) + except OSError as e: + if silent and e.errno in (errno.ENOENT, errno.EISDIR, errno.ENOTDIR): + return False + e.strerror = f"Unable to load configuration file ({e.strerror})" + raise + self.from_object(d) + return True + + def from_object(self, obj: object | str) -> None: + """Updates the values from the given object. An object can be of one + of the following two types: + + - a string: in this case the object with that name will be imported + - an actual object reference: that object is used directly + + Objects are usually either modules or classes. :meth:`from_object` + loads only the uppercase attributes of the module/class. A ``dict`` + object will not work with :meth:`from_object` because the keys of a + ``dict`` are not attributes of the ``dict`` class. + + Example of module-based configuration:: + + app.config.from_object('yourapplication.default_config') + from yourapplication import default_config + app.config.from_object(default_config) + + Nothing is done to the object before loading. If the object is a + class and has ``@property`` attributes, it needs to be + instantiated before being passed to this method. + + You should not use this function to load the actual configuration but + rather configuration defaults. The actual config should be loaded + with :meth:`from_pyfile` and ideally from a location not within the + package because the package might be installed system wide. + + See :ref:`config-dev-prod` for an example of class-based configuration + using :meth:`from_object`. + + :param obj: an import name or object + """ + if isinstance(obj, str): + obj = import_string(obj) + for key in dir(obj): + if key.isupper(): + self[key] = getattr(obj, key) + + def from_file( + self, + filename: str | os.PathLike[str], + load: t.Callable[[t.IO[t.Any]], t.Mapping[str, t.Any]], + silent: bool = False, + text: bool = True, + ) -> bool: + """Update the values in the config from a file that is loaded + using the ``load`` parameter. The loaded data is passed to the + :meth:`from_mapping` method. + + .. code-block:: python + + import json + app.config.from_file("config.json", load=json.load) + + import tomllib + app.config.from_file("config.toml", load=tomllib.load, text=False) + + :param filename: The path to the data file. This can be an + absolute path or relative to the config root path. + :param load: A callable that takes a file handle and returns a + mapping of loaded data from the file. + :type load: ``Callable[[Reader], Mapping]`` where ``Reader`` + implements a ``read`` method. + :param silent: Ignore the file if it doesn't exist. + :param text: Open the file in text or binary mode. + :return: ``True`` if the file was loaded successfully. + + .. versionchanged:: 2.3 + The ``text`` parameter was added. + + .. versionadded:: 2.0 + """ + filename = os.path.join(self.root_path, filename) + + try: + with open(filename, "r" if text else "rb") as f: + obj = load(f) + except OSError as e: + if silent and e.errno in (errno.ENOENT, errno.EISDIR): + return False + + e.strerror = f"Unable to load configuration file ({e.strerror})" + raise + + return self.from_mapping(obj) + + def from_mapping( + self, mapping: t.Mapping[str, t.Any] | None = None, **kwargs: t.Any + ) -> bool: + """Updates the config like :meth:`update` ignoring items with + non-upper keys. + + :return: Always returns ``True``. + + .. versionadded:: 0.11 + """ + mappings: dict[str, t.Any] = {} + if mapping is not None: + mappings.update(mapping) + mappings.update(kwargs) + for key, value in mappings.items(): + if key.isupper(): + self[key] = value + return True + + def get_namespace( + self, namespace: str, lowercase: bool = True, trim_namespace: bool = True + ) -> dict[str, t.Any]: + """Returns a dictionary containing a subset of configuration options + that match the specified namespace/prefix. Example usage:: + + app.config['IMAGE_STORE_TYPE'] = 'fs' + app.config['IMAGE_STORE_PATH'] = '/var/app/images' + app.config['IMAGE_STORE_BASE_URL'] = 'http://img.website.com' + image_store_config = app.config.get_namespace('IMAGE_STORE_') + + The resulting dictionary `image_store_config` would look like:: + + { + 'type': 'fs', + 'path': '/var/app/images', + 'base_url': 'http://img.website.com' + } + + This is often useful when configuration options map directly to + keyword arguments in functions or class constructors. + + :param namespace: a configuration namespace + :param lowercase: a flag indicating if the keys of the resulting + dictionary should be lowercase + :param trim_namespace: a flag indicating if the keys of the resulting + dictionary should not include the namespace + + .. versionadded:: 0.11 + """ + rv = {} + for k, v in self.items(): + if not k.startswith(namespace): + continue + if trim_namespace: + key = k[len(namespace) :] + else: + key = k + if lowercase: + key = key.lower() + rv[key] = v + return rv + + def __repr__(self) -> str: + return f"<{type(self).__name__} {dict.__repr__(self)}>" diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask/ctx.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask/ctx.py new file mode 100644 index 000000000..5f7b1f1db --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask/ctx.py @@ -0,0 +1,459 @@ +from __future__ import annotations + +import contextvars +import sys +import typing as t +from functools import update_wrapper +from types import TracebackType + +from werkzeug.exceptions import HTTPException + +from . import typing as ft +from .globals import _cv_app +from .globals import _cv_request +from .signals import appcontext_popped +from .signals import appcontext_pushed + +if t.TYPE_CHECKING: # pragma: no cover + from _typeshed.wsgi import WSGIEnvironment + + from .app import Flask + from .sessions import SessionMixin + from .wrappers import Request + + +# a singleton sentinel value for parameter defaults +_sentinel = object() + + +class _AppCtxGlobals: + """A plain object. Used as a namespace for storing data during an + application context. + + Creating an app context automatically creates this object, which is + made available as the :data:`g` proxy. + + .. describe:: 'key' in g + + Check whether an attribute is present. + + .. versionadded:: 0.10 + + .. describe:: iter(g) + + Return an iterator over the attribute names. + + .. versionadded:: 0.10 + """ + + # Define attr methods to let mypy know this is a namespace object + # that has arbitrary attributes. + + def __getattr__(self, name: str) -> t.Any: + try: + return self.__dict__[name] + except KeyError: + raise AttributeError(name) from None + + def __setattr__(self, name: str, value: t.Any) -> None: + self.__dict__[name] = value + + def __delattr__(self, name: str) -> None: + try: + del self.__dict__[name] + except KeyError: + raise AttributeError(name) from None + + def get(self, name: str, default: t.Any | None = None) -> t.Any: + """Get an attribute by name, or a default value. Like + :meth:`dict.get`. + + :param name: Name of attribute to get. + :param default: Value to return if the attribute is not present. + + .. versionadded:: 0.10 + """ + return self.__dict__.get(name, default) + + def pop(self, name: str, default: t.Any = _sentinel) -> t.Any: + """Get and remove an attribute by name. Like :meth:`dict.pop`. + + :param name: Name of attribute to pop. + :param default: Value to return if the attribute is not present, + instead of raising a ``KeyError``. + + .. versionadded:: 0.11 + """ + if default is _sentinel: + return self.__dict__.pop(name) + else: + return self.__dict__.pop(name, default) + + def setdefault(self, name: str, default: t.Any = None) -> t.Any: + """Get the value of an attribute if it is present, otherwise + set and return a default value. Like :meth:`dict.setdefault`. + + :param name: Name of attribute to get. + :param default: Value to set and return if the attribute is not + present. + + .. versionadded:: 0.11 + """ + return self.__dict__.setdefault(name, default) + + def __contains__(self, item: str) -> bool: + return item in self.__dict__ + + def __iter__(self) -> t.Iterator[str]: + return iter(self.__dict__) + + def __repr__(self) -> str: + ctx = _cv_app.get(None) + if ctx is not None: + return f"" + return object.__repr__(self) + + +def after_this_request( + f: ft.AfterRequestCallable[t.Any], +) -> ft.AfterRequestCallable[t.Any]: + """Executes a function after this request. This is useful to modify + response objects. The function is passed the response object and has + to return the same or a new one. + + Example:: + + @app.route('/') + def index(): + @after_this_request + def add_header(response): + response.headers['X-Foo'] = 'Parachute' + return response + return 'Hello World!' + + This is more useful if a function other than the view function wants to + modify a response. For instance think of a decorator that wants to add + some headers without converting the return value into a response object. + + .. versionadded:: 0.9 + """ + ctx = _cv_request.get(None) + + if ctx is None: + raise RuntimeError( + "'after_this_request' can only be used when a request" + " context is active, such as in a view function." + ) + + ctx._after_request_functions.append(f) + return f + + +F = t.TypeVar("F", bound=t.Callable[..., t.Any]) + + +def copy_current_request_context(f: F) -> F: + """A helper function that decorates a function to retain the current + request context. This is useful when working with greenlets. The moment + the function is decorated a copy of the request context is created and + then pushed when the function is called. The current session is also + included in the copied request context. + + Example:: + + import gevent + from flask import copy_current_request_context + + @app.route('/') + def index(): + @copy_current_request_context + def do_some_work(): + # do some work here, it can access flask.request or + # flask.session like you would otherwise in the view function. + ... + gevent.spawn(do_some_work) + return 'Regular response' + + .. versionadded:: 0.10 + """ + ctx = _cv_request.get(None) + + if ctx is None: + raise RuntimeError( + "'copy_current_request_context' can only be used when a" + " request context is active, such as in a view function." + ) + + ctx = ctx.copy() + + def wrapper(*args: t.Any, **kwargs: t.Any) -> t.Any: + with ctx: + return ctx.app.ensure_sync(f)(*args, **kwargs) + + return update_wrapper(wrapper, f) # type: ignore[return-value] + + +def has_request_context() -> bool: + """If you have code that wants to test if a request context is there or + not this function can be used. For instance, you may want to take advantage + of request information if the request object is available, but fail + silently if it is unavailable. + + :: + + class User(db.Model): + + def __init__(self, username, remote_addr=None): + self.username = username + if remote_addr is None and has_request_context(): + remote_addr = request.remote_addr + self.remote_addr = remote_addr + + Alternatively you can also just test any of the context bound objects + (such as :class:`request` or :class:`g`) for truthness:: + + class User(db.Model): + + def __init__(self, username, remote_addr=None): + self.username = username + if remote_addr is None and request: + remote_addr = request.remote_addr + self.remote_addr = remote_addr + + .. versionadded:: 0.7 + """ + return _cv_request.get(None) is not None + + +def has_app_context() -> bool: + """Works like :func:`has_request_context` but for the application + context. You can also just do a boolean check on the + :data:`current_app` object instead. + + .. versionadded:: 0.9 + """ + return _cv_app.get(None) is not None + + +class AppContext: + """The app context contains application-specific information. An app + context is created and pushed at the beginning of each request if + one is not already active. An app context is also pushed when + running CLI commands. + """ + + def __init__(self, app: Flask) -> None: + self.app = app + self.url_adapter = app.create_url_adapter(None) + self.g: _AppCtxGlobals = app.app_ctx_globals_class() + self._cv_tokens: list[contextvars.Token[AppContext]] = [] + + def push(self) -> None: + """Binds the app context to the current context.""" + self._cv_tokens.append(_cv_app.set(self)) + appcontext_pushed.send(self.app, _async_wrapper=self.app.ensure_sync) + + def pop(self, exc: BaseException | None = _sentinel) -> None: # type: ignore + """Pops the app context.""" + try: + if len(self._cv_tokens) == 1: + if exc is _sentinel: + exc = sys.exc_info()[1] + self.app.do_teardown_appcontext(exc) + finally: + ctx = _cv_app.get() + _cv_app.reset(self._cv_tokens.pop()) + + if ctx is not self: + raise AssertionError( + f"Popped wrong app context. ({ctx!r} instead of {self!r})" + ) + + appcontext_popped.send(self.app, _async_wrapper=self.app.ensure_sync) + + def __enter__(self) -> AppContext: + self.push() + return self + + def __exit__( + self, + exc_type: type | None, + exc_value: BaseException | None, + tb: TracebackType | None, + ) -> None: + self.pop(exc_value) + + +class RequestContext: + """The request context contains per-request information. The Flask + app creates and pushes it at the beginning of the request, then pops + it at the end of the request. It will create the URL adapter and + request object for the WSGI environment provided. + + Do not attempt to use this class directly, instead use + :meth:`~flask.Flask.test_request_context` and + :meth:`~flask.Flask.request_context` to create this object. + + When the request context is popped, it will evaluate all the + functions registered on the application for teardown execution + (:meth:`~flask.Flask.teardown_request`). + + The request context is automatically popped at the end of the + request. When using the interactive debugger, the context will be + restored so ``request`` is still accessible. Similarly, the test + client can preserve the context after the request ends. However, + teardown functions may already have closed some resources such as + database connections. + """ + + def __init__( + self, + app: Flask, + environ: WSGIEnvironment, + request: Request | None = None, + session: SessionMixin | None = None, + ) -> None: + self.app = app + if request is None: + request = app.request_class(environ) + request.json_module = app.json + self.request: Request = request + self.url_adapter = None + try: + self.url_adapter = app.create_url_adapter(self.request) + except HTTPException as e: + self.request.routing_exception = e + self.flashes: list[tuple[str, str]] | None = None + self._session: SessionMixin | None = session + # Functions that should be executed after the request on the response + # object. These will be called before the regular "after_request" + # functions. + self._after_request_functions: list[ft.AfterRequestCallable[t.Any]] = [] + + self._cv_tokens: list[ + tuple[contextvars.Token[RequestContext], AppContext | None] + ] = [] + + def copy(self) -> RequestContext: + """Creates a copy of this request context with the same request object. + This can be used to move a request context to a different greenlet. + Because the actual request object is the same this cannot be used to + move a request context to a different thread unless access to the + request object is locked. + + .. versionadded:: 0.10 + + .. versionchanged:: 1.1 + The current session object is used instead of reloading the original + data. This prevents `flask.session` pointing to an out-of-date object. + """ + return self.__class__( + self.app, + environ=self.request.environ, + request=self.request, + session=self._session, + ) + + def match_request(self) -> None: + """Can be overridden by a subclass to hook into the matching + of the request. + """ + try: + result = self.url_adapter.match(return_rule=True) # type: ignore + self.request.url_rule, self.request.view_args = result # type: ignore + except HTTPException as e: + self.request.routing_exception = e + + @property + def session(self) -> SessionMixin: + """The session data associated with this request. Not available until + this context has been pushed. Accessing this property, also accessed by + the :data:`~flask.session` proxy, sets :attr:`.SessionMixin.accessed`. + """ + assert self._session is not None, "The session has not yet been opened." + self._session.accessed = True + return self._session + + def push(self) -> None: + # Before we push the request context we have to ensure that there + # is an application context. + app_ctx = _cv_app.get(None) + + if app_ctx is None or app_ctx.app is not self.app: + app_ctx = self.app.app_context() + app_ctx.push() + else: + app_ctx = None + + self._cv_tokens.append((_cv_request.set(self), app_ctx)) + + # Open the session at the moment that the request context is available. + # This allows a custom open_session method to use the request context. + # Only open a new session if this is the first time the request was + # pushed, otherwise stream_with_context loses the session. + if self._session is None: + session_interface = self.app.session_interface + self._session = session_interface.open_session(self.app, self.request) + + if self._session is None: + self._session = session_interface.make_null_session(self.app) + + # Match the request URL after loading the session, so that the + # session is available in custom URL converters. + if self.url_adapter is not None: + self.match_request() + + def pop(self, exc: BaseException | None = _sentinel) -> None: # type: ignore + """Pops the request context and unbinds it by doing that. This will + also trigger the execution of functions registered by the + :meth:`~flask.Flask.teardown_request` decorator. + + .. versionchanged:: 0.9 + Added the `exc` argument. + """ + clear_request = len(self._cv_tokens) == 1 + + try: + if clear_request: + if exc is _sentinel: + exc = sys.exc_info()[1] + self.app.do_teardown_request(exc) + + request_close = getattr(self.request, "close", None) + if request_close is not None: + request_close() + finally: + ctx = _cv_request.get() + token, app_ctx = self._cv_tokens.pop() + _cv_request.reset(token) + + # get rid of circular dependencies at the end of the request + # so that we don't require the GC to be active. + if clear_request: + ctx.request.environ["werkzeug.request"] = None + + if app_ctx is not None: + app_ctx.pop(exc) + + if ctx is not self: + raise AssertionError( + f"Popped wrong request context. ({ctx!r} instead of {self!r})" + ) + + def __enter__(self) -> RequestContext: + self.push() + return self + + def __exit__( + self, + exc_type: type | None, + exc_value: BaseException | None, + tb: TracebackType | None, + ) -> None: + self.pop(exc_value) + + def __repr__(self) -> str: + return ( + f"<{type(self).__name__} {self.request.url!r}" + f" [{self.request.method}] of {self.app.name}>" + ) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask/debughelpers.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask/debughelpers.py new file mode 100644 index 000000000..2c8c4c483 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask/debughelpers.py @@ -0,0 +1,178 @@ +from __future__ import annotations + +import typing as t + +from jinja2.loaders import BaseLoader +from werkzeug.routing import RequestRedirect + +from .blueprints import Blueprint +from .globals import request_ctx +from .sansio.app import App + +if t.TYPE_CHECKING: + from .sansio.scaffold import Scaffold + from .wrappers import Request + + +class UnexpectedUnicodeError(AssertionError, UnicodeError): + """Raised in places where we want some better error reporting for + unexpected unicode or binary data. + """ + + +class DebugFilesKeyError(KeyError, AssertionError): + """Raised from request.files during debugging. The idea is that it can + provide a better error message than just a generic KeyError/BadRequest. + """ + + def __init__(self, request: Request, key: str) -> None: + form_matches = request.form.getlist(key) + buf = [ + f"You tried to access the file {key!r} in the request.files" + " dictionary but it does not exist. The mimetype for the" + f" request is {request.mimetype!r} instead of" + " 'multipart/form-data' which means that no file contents" + " were transmitted. To fix this error you should provide" + ' enctype="multipart/form-data" in your form.' + ] + if form_matches: + names = ", ".join(repr(x) for x in form_matches) + buf.append( + "\n\nThe browser instead transmitted some file names. " + f"This was submitted: {names}" + ) + self.msg = "".join(buf) + + def __str__(self) -> str: + return self.msg + + +class FormDataRoutingRedirect(AssertionError): + """This exception is raised in debug mode if a routing redirect + would cause the browser to drop the method or body. This happens + when method is not GET, HEAD or OPTIONS and the status code is not + 307 or 308. + """ + + def __init__(self, request: Request) -> None: + exc = request.routing_exception + assert isinstance(exc, RequestRedirect) + buf = [ + f"A request was sent to '{request.url}', but routing issued" + f" a redirect to the canonical URL '{exc.new_url}'." + ] + + if f"{request.base_url}/" == exc.new_url.partition("?")[0]: + buf.append( + " The URL was defined with a trailing slash. Flask" + " will redirect to the URL with a trailing slash if it" + " was accessed without one." + ) + + buf.append( + " Send requests to the canonical URL, or use 307 or 308 for" + " routing redirects. Otherwise, browsers will drop form" + " data.\n\n" + "This exception is only raised in debug mode." + ) + super().__init__("".join(buf)) + + +def attach_enctype_error_multidict(request: Request) -> None: + """Patch ``request.files.__getitem__`` to raise a descriptive error + about ``enctype=multipart/form-data``. + + :param request: The request to patch. + :meta private: + """ + oldcls = request.files.__class__ + + class newcls(oldcls): # type: ignore[valid-type, misc] + def __getitem__(self, key: str) -> t.Any: + try: + return super().__getitem__(key) + except KeyError as e: + if key not in request.form: + raise + + raise DebugFilesKeyError(request, key).with_traceback( + e.__traceback__ + ) from None + + newcls.__name__ = oldcls.__name__ + newcls.__module__ = oldcls.__module__ + request.files.__class__ = newcls + + +def _dump_loader_info(loader: BaseLoader) -> t.Iterator[str]: + yield f"class: {type(loader).__module__}.{type(loader).__name__}" + for key, value in sorted(loader.__dict__.items()): + if key.startswith("_"): + continue + if isinstance(value, (tuple, list)): + if not all(isinstance(x, str) for x in value): + continue + yield f"{key}:" + for item in value: + yield f" - {item}" + continue + elif not isinstance(value, (str, int, float, bool)): + continue + yield f"{key}: {value!r}" + + +def explain_template_loading_attempts( + app: App, + template: str, + attempts: list[ + tuple[ + BaseLoader, + Scaffold, + tuple[str, str | None, t.Callable[[], bool] | None] | None, + ] + ], +) -> None: + """This should help developers understand what failed""" + info = [f"Locating template {template!r}:"] + total_found = 0 + blueprint = None + if request_ctx and request_ctx.request.blueprint is not None: + blueprint = request_ctx.request.blueprint + + for idx, (loader, srcobj, triple) in enumerate(attempts): + if isinstance(srcobj, App): + src_info = f"application {srcobj.import_name!r}" + elif isinstance(srcobj, Blueprint): + src_info = f"blueprint {srcobj.name!r} ({srcobj.import_name})" + else: + src_info = repr(srcobj) + + info.append(f"{idx + 1:5}: trying loader of {src_info}") + + for line in _dump_loader_info(loader): + info.append(f" {line}") + + if triple is None: + detail = "no match" + else: + detail = f"found ({triple[1] or ''!r})" + total_found += 1 + info.append(f" -> {detail}") + + seems_fishy = False + if total_found == 0: + info.append("Error: the template could not be found.") + seems_fishy = True + elif total_found > 1: + info.append("Warning: multiple loaders returned a match for the template.") + seems_fishy = True + + if blueprint is not None and seems_fishy: + info.append( + " The template was looked up from an endpoint that belongs" + f" to the blueprint {blueprint!r}." + ) + info.append(" Maybe you did not place a template in the right folder?") + info.append(" See https://flask.palletsprojects.com/blueprints/#templates") + + app.logger.info("\n".join(info)) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask/globals.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask/globals.py new file mode 100644 index 000000000..e2c410cc5 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask/globals.py @@ -0,0 +1,51 @@ +from __future__ import annotations + +import typing as t +from contextvars import ContextVar + +from werkzeug.local import LocalProxy + +if t.TYPE_CHECKING: # pragma: no cover + from .app import Flask + from .ctx import _AppCtxGlobals + from .ctx import AppContext + from .ctx import RequestContext + from .sessions import SessionMixin + from .wrappers import Request + + +_no_app_msg = """\ +Working outside of application context. + +This typically means that you attempted to use functionality that needed +the current application. To solve this, set up an application context +with app.app_context(). See the documentation for more information.\ +""" +_cv_app: ContextVar[AppContext] = ContextVar("flask.app_ctx") +app_ctx: AppContext = LocalProxy( # type: ignore[assignment] + _cv_app, unbound_message=_no_app_msg +) +current_app: Flask = LocalProxy( # type: ignore[assignment] + _cv_app, "app", unbound_message=_no_app_msg +) +g: _AppCtxGlobals = LocalProxy( # type: ignore[assignment] + _cv_app, "g", unbound_message=_no_app_msg +) + +_no_req_msg = """\ +Working outside of request context. + +This typically means that you attempted to use functionality that needed +an active HTTP request. Consult the documentation on testing for +information about how to avoid this problem.\ +""" +_cv_request: ContextVar[RequestContext] = ContextVar("flask.request_ctx") +request_ctx: RequestContext = LocalProxy( # type: ignore[assignment] + _cv_request, unbound_message=_no_req_msg +) +request: Request = LocalProxy( # type: ignore[assignment] + _cv_request, "request", unbound_message=_no_req_msg +) +session: SessionMixin = LocalProxy( # type: ignore[assignment] + _cv_request, "session", unbound_message=_no_req_msg +) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask/helpers.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask/helpers.py new file mode 100644 index 000000000..5d412c90f --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask/helpers.py @@ -0,0 +1,641 @@ +from __future__ import annotations + +import importlib.util +import os +import sys +import typing as t +from datetime import datetime +from functools import cache +from functools import update_wrapper + +import werkzeug.utils +from werkzeug.exceptions import abort as _wz_abort +from werkzeug.utils import redirect as _wz_redirect +from werkzeug.wrappers import Response as BaseResponse + +from .globals import _cv_app +from .globals import _cv_request +from .globals import current_app +from .globals import request +from .globals import request_ctx +from .globals import session +from .signals import message_flashed + +if t.TYPE_CHECKING: # pragma: no cover + from .wrappers import Response + + +def get_debug_flag() -> bool: + """Get whether debug mode should be enabled for the app, indicated by the + :envvar:`FLASK_DEBUG` environment variable. The default is ``False``. + """ + val = os.environ.get("FLASK_DEBUG") + return bool(val and val.lower() not in {"0", "false", "no"}) + + +def get_load_dotenv(default: bool = True) -> bool: + """Get whether the user has disabled loading default dotenv files by + setting :envvar:`FLASK_SKIP_DOTENV`. The default is ``True``, load + the files. + + :param default: What to return if the env var isn't set. + """ + val = os.environ.get("FLASK_SKIP_DOTENV") + + if not val: + return default + + return val.lower() in ("0", "false", "no") + + +@t.overload +def stream_with_context( + generator_or_function: t.Iterator[t.AnyStr], +) -> t.Iterator[t.AnyStr]: ... + + +@t.overload +def stream_with_context( + generator_or_function: t.Callable[..., t.Iterator[t.AnyStr]], +) -> t.Callable[[t.Iterator[t.AnyStr]], t.Iterator[t.AnyStr]]: ... + + +def stream_with_context( + generator_or_function: t.Iterator[t.AnyStr] | t.Callable[..., t.Iterator[t.AnyStr]], +) -> t.Iterator[t.AnyStr] | t.Callable[[t.Iterator[t.AnyStr]], t.Iterator[t.AnyStr]]: + """Wrap a response generator function so that it runs inside the current + request context. This keeps :data:`request`, :data:`session`, and :data:`g` + available, even though at the point the generator runs the request context + will typically have ended. + + Use it as a decorator on a generator function: + + .. code-block:: python + + from flask import stream_with_context, request, Response + + @app.get("/stream") + def streamed_response(): + @stream_with_context + def generate(): + yield "Hello " + yield request.args["name"] + yield "!" + + return Response(generate()) + + Or use it as a wrapper around a created generator: + + .. code-block:: python + + from flask import stream_with_context, request, Response + + @app.get("/stream") + def streamed_response(): + def generate(): + yield "Hello " + yield request.args["name"] + yield "!" + + return Response(stream_with_context(generate())) + + .. versionadded:: 0.9 + """ + try: + gen = iter(generator_or_function) # type: ignore[arg-type] + except TypeError: + + def decorator(*args: t.Any, **kwargs: t.Any) -> t.Any: + gen = generator_or_function(*args, **kwargs) # type: ignore[operator] + return stream_with_context(gen) + + return update_wrapper(decorator, generator_or_function) # type: ignore[arg-type] + + def generator() -> t.Iterator[t.AnyStr]: + if (req_ctx := _cv_request.get(None)) is None: + raise RuntimeError( + "'stream_with_context' can only be used when a request" + " context is active, such as in a view function." + ) + + app_ctx = _cv_app.get() + # Setup code below will run the generator to this point, so that the + # current contexts are recorded. The contexts must be pushed after, + # otherwise their ContextVar will record the wrong event loop during + # async view functions. + yield None # type: ignore[misc] + + # Push the app context first, so that the request context does not + # automatically create and push a different app context. + with app_ctx, req_ctx: + try: + yield from gen + finally: + # Clean up in case the user wrapped a WSGI iterator. + if hasattr(gen, "close"): + gen.close() + + # Execute the generator to the sentinel value. This ensures the context is + # preserved in the generator's state. Further iteration will push the + # context and yield from the original iterator. + wrapped_g = generator() + next(wrapped_g) + return wrapped_g + + +def make_response(*args: t.Any) -> Response: + """Sometimes it is necessary to set additional headers in a view. Because + views do not have to return response objects but can return a value that + is converted into a response object by Flask itself, it becomes tricky to + add headers to it. This function can be called instead of using a return + and you will get a response object which you can use to attach headers. + + If view looked like this and you want to add a new header:: + + def index(): + return render_template('index.html', foo=42) + + You can now do something like this:: + + def index(): + response = make_response(render_template('index.html', foo=42)) + response.headers['X-Parachutes'] = 'parachutes are cool' + return response + + This function accepts the very same arguments you can return from a + view function. This for example creates a response with a 404 error + code:: + + response = make_response(render_template('not_found.html'), 404) + + The other use case of this function is to force the return value of a + view function into a response which is helpful with view + decorators:: + + response = make_response(view_function()) + response.headers['X-Parachutes'] = 'parachutes are cool' + + Internally this function does the following things: + + - if no arguments are passed, it creates a new response argument + - if one argument is passed, :meth:`flask.Flask.make_response` + is invoked with it. + - if more than one argument is passed, the arguments are passed + to the :meth:`flask.Flask.make_response` function as tuple. + + .. versionadded:: 0.6 + """ + if not args: + return current_app.response_class() + if len(args) == 1: + args = args[0] + return current_app.make_response(args) + + +def url_for( + endpoint: str, + *, + _anchor: str | None = None, + _method: str | None = None, + _scheme: str | None = None, + _external: bool | None = None, + **values: t.Any, +) -> str: + """Generate a URL to the given endpoint with the given values. + + This requires an active request or application context, and calls + :meth:`current_app.url_for() `. See that method + for full documentation. + + :param endpoint: The endpoint name associated with the URL to + generate. If this starts with a ``.``, the current blueprint + name (if any) will be used. + :param _anchor: If given, append this as ``#anchor`` to the URL. + :param _method: If given, generate the URL associated with this + method for the endpoint. + :param _scheme: If given, the URL will have this scheme if it is + external. + :param _external: If given, prefer the URL to be internal (False) or + require it to be external (True). External URLs include the + scheme and domain. When not in an active request, URLs are + external by default. + :param values: Values to use for the variable parts of the URL rule. + Unknown keys are appended as query string arguments, like + ``?a=b&c=d``. + + .. versionchanged:: 2.2 + Calls ``current_app.url_for``, allowing an app to override the + behavior. + + .. versionchanged:: 0.10 + The ``_scheme`` parameter was added. + + .. versionchanged:: 0.9 + The ``_anchor`` and ``_method`` parameters were added. + + .. versionchanged:: 0.9 + Calls ``app.handle_url_build_error`` on build errors. + """ + return current_app.url_for( + endpoint, + _anchor=_anchor, + _method=_method, + _scheme=_scheme, + _external=_external, + **values, + ) + + +def redirect( + location: str, code: int = 302, Response: type[BaseResponse] | None = None +) -> BaseResponse: + """Create a redirect response object. + + If :data:`~flask.current_app` is available, it will use its + :meth:`~flask.Flask.redirect` method, otherwise it will use + :func:`werkzeug.utils.redirect`. + + :param location: The URL to redirect to. + :param code: The status code for the redirect. + :param Response: The response class to use. Not used when + ``current_app`` is active, which uses ``app.response_class``. + + .. versionadded:: 2.2 + Calls ``current_app.redirect`` if available instead of always + using Werkzeug's default ``redirect``. + """ + if current_app: + return current_app.redirect(location, code=code) + + return _wz_redirect(location, code=code, Response=Response) + + +def abort(code: int | BaseResponse, *args: t.Any, **kwargs: t.Any) -> t.NoReturn: + """Raise an :exc:`~werkzeug.exceptions.HTTPException` for the given + status code. + + If :data:`~flask.current_app` is available, it will call its + :attr:`~flask.Flask.aborter` object, otherwise it will use + :func:`werkzeug.exceptions.abort`. + + :param code: The status code for the exception, which must be + registered in ``app.aborter``. + :param args: Passed to the exception. + :param kwargs: Passed to the exception. + + .. versionadded:: 2.2 + Calls ``current_app.aborter`` if available instead of always + using Werkzeug's default ``abort``. + """ + if current_app: + current_app.aborter(code, *args, **kwargs) + + _wz_abort(code, *args, **kwargs) + + +def get_template_attribute(template_name: str, attribute: str) -> t.Any: + """Loads a macro (or variable) a template exports. This can be used to + invoke a macro from within Python code. If you for example have a + template named :file:`_cider.html` with the following contents: + + .. sourcecode:: html+jinja + + {% macro hello(name) %}Hello {{ name }}!{% endmacro %} + + You can access this from Python code like this:: + + hello = get_template_attribute('_cider.html', 'hello') + return hello('World') + + .. versionadded:: 0.2 + + :param template_name: the name of the template + :param attribute: the name of the variable of macro to access + """ + return getattr(current_app.jinja_env.get_template(template_name).module, attribute) + + +def flash(message: str, category: str = "message") -> None: + """Flashes a message to the next request. In order to remove the + flashed message from the session and to display it to the user, + the template has to call :func:`get_flashed_messages`. + + .. versionchanged:: 0.3 + `category` parameter added. + + :param message: the message to be flashed. + :param category: the category for the message. The following values + are recommended: ``'message'`` for any kind of message, + ``'error'`` for errors, ``'info'`` for information + messages and ``'warning'`` for warnings. However any + kind of string can be used as category. + """ + # Original implementation: + # + # session.setdefault('_flashes', []).append((category, message)) + # + # This assumed that changes made to mutable structures in the session are + # always in sync with the session object, which is not true for session + # implementations that use external storage for keeping their keys/values. + flashes = session.get("_flashes", []) + flashes.append((category, message)) + session["_flashes"] = flashes + app = current_app._get_current_object() # type: ignore + message_flashed.send( + app, + _async_wrapper=app.ensure_sync, + message=message, + category=category, + ) + + +def get_flashed_messages( + with_categories: bool = False, category_filter: t.Iterable[str] = () +) -> list[str] | list[tuple[str, str]]: + """Pulls all flashed messages from the session and returns them. + Further calls in the same request to the function will return + the same messages. By default just the messages are returned, + but when `with_categories` is set to ``True``, the return value will + be a list of tuples in the form ``(category, message)`` instead. + + Filter the flashed messages to one or more categories by providing those + categories in `category_filter`. This allows rendering categories in + separate html blocks. The `with_categories` and `category_filter` + arguments are distinct: + + * `with_categories` controls whether categories are returned with message + text (``True`` gives a tuple, where ``False`` gives just the message text). + * `category_filter` filters the messages down to only those matching the + provided categories. + + See :doc:`/patterns/flashing` for examples. + + .. versionchanged:: 0.3 + `with_categories` parameter added. + + .. versionchanged:: 0.9 + `category_filter` parameter added. + + :param with_categories: set to ``True`` to also receive categories. + :param category_filter: filter of categories to limit return values. Only + categories in the list will be returned. + """ + flashes = request_ctx.flashes + if flashes is None: + flashes = session.pop("_flashes") if "_flashes" in session else [] + request_ctx.flashes = flashes + if category_filter: + flashes = list(filter(lambda f: f[0] in category_filter, flashes)) + if not with_categories: + return [x[1] for x in flashes] + return flashes + + +def _prepare_send_file_kwargs(**kwargs: t.Any) -> dict[str, t.Any]: + if kwargs.get("max_age") is None: + kwargs["max_age"] = current_app.get_send_file_max_age + + kwargs.update( + environ=request.environ, + use_x_sendfile=current_app.config["USE_X_SENDFILE"], + response_class=current_app.response_class, + _root_path=current_app.root_path, + ) + return kwargs + + +def send_file( + path_or_file: os.PathLike[t.AnyStr] | str | t.IO[bytes], + mimetype: str | None = None, + as_attachment: bool = False, + download_name: str | None = None, + conditional: bool = True, + etag: bool | str = True, + last_modified: datetime | int | float | None = None, + max_age: None | (int | t.Callable[[str | None], int | None]) = None, +) -> Response: + """Send the contents of a file to the client. + + The first argument can be a file path or a file-like object. Paths + are preferred in most cases because Werkzeug can manage the file and + get extra information from the path. Passing a file-like object + requires that the file is opened in binary mode, and is mostly + useful when building a file in memory with :class:`io.BytesIO`. + + Never pass file paths provided by a user. The path is assumed to be + trusted, so a user could craft a path to access a file you didn't + intend. Use :func:`send_from_directory` to safely serve + user-requested paths from within a directory. + + If the WSGI server sets a ``file_wrapper`` in ``environ``, it is + used, otherwise Werkzeug's built-in wrapper is used. Alternatively, + if the HTTP server supports ``X-Sendfile``, configuring Flask with + ``USE_X_SENDFILE = True`` will tell the server to send the given + path, which is much more efficient than reading it in Python. + + :param path_or_file: The path to the file to send, relative to the + current working directory if a relative path is given. + Alternatively, a file-like object opened in binary mode. Make + sure the file pointer is seeked to the start of the data. + :param mimetype: The MIME type to send for the file. If not + provided, it will try to detect it from the file name. + :param as_attachment: Indicate to a browser that it should offer to + save the file instead of displaying it. + :param download_name: The default name browsers will use when saving + the file. Defaults to the passed file name. + :param conditional: Enable conditional and range responses based on + request headers. Requires passing a file path and ``environ``. + :param etag: Calculate an ETag for the file, which requires passing + a file path. Can also be a string to use instead. + :param last_modified: The last modified time to send for the file, + in seconds. If not provided, it will try to detect it from the + file path. + :param max_age: How long the client should cache the file, in + seconds. If set, ``Cache-Control`` will be ``public``, otherwise + it will be ``no-cache`` to prefer conditional caching. + + .. versionchanged:: 2.0 + ``download_name`` replaces the ``attachment_filename`` + parameter. If ``as_attachment=False``, it is passed with + ``Content-Disposition: inline`` instead. + + .. versionchanged:: 2.0 + ``max_age`` replaces the ``cache_timeout`` parameter. + ``conditional`` is enabled and ``max_age`` is not set by + default. + + .. versionchanged:: 2.0 + ``etag`` replaces the ``add_etags`` parameter. It can be a + string to use instead of generating one. + + .. versionchanged:: 2.0 + Passing a file-like object that inherits from + :class:`~io.TextIOBase` will raise a :exc:`ValueError` rather + than sending an empty file. + + .. versionadded:: 2.0 + Moved the implementation to Werkzeug. This is now a wrapper to + pass some Flask-specific arguments. + + .. versionchanged:: 1.1 + ``filename`` may be a :class:`~os.PathLike` object. + + .. versionchanged:: 1.1 + Passing a :class:`~io.BytesIO` object supports range requests. + + .. versionchanged:: 1.0.3 + Filenames are encoded with ASCII instead of Latin-1 for broader + compatibility with WSGI servers. + + .. versionchanged:: 1.0 + UTF-8 filenames as specified in :rfc:`2231` are supported. + + .. versionchanged:: 0.12 + The filename is no longer automatically inferred from file + objects. If you want to use automatic MIME and etag support, + pass a filename via ``filename_or_fp`` or + ``attachment_filename``. + + .. versionchanged:: 0.12 + ``attachment_filename`` is preferred over ``filename`` for MIME + detection. + + .. versionchanged:: 0.9 + ``cache_timeout`` defaults to + :meth:`Flask.get_send_file_max_age`. + + .. versionchanged:: 0.7 + MIME guessing and etag support for file-like objects was + removed because it was unreliable. Pass a filename if you are + able to, otherwise attach an etag yourself. + + .. versionchanged:: 0.5 + The ``add_etags``, ``cache_timeout`` and ``conditional`` + parameters were added. The default behavior is to add etags. + + .. versionadded:: 0.2 + """ + return werkzeug.utils.send_file( # type: ignore[return-value] + **_prepare_send_file_kwargs( + path_or_file=path_or_file, + environ=request.environ, + mimetype=mimetype, + as_attachment=as_attachment, + download_name=download_name, + conditional=conditional, + etag=etag, + last_modified=last_modified, + max_age=max_age, + ) + ) + + +def send_from_directory( + directory: os.PathLike[str] | str, + path: os.PathLike[str] | str, + **kwargs: t.Any, +) -> Response: + """Send a file from within a directory using :func:`send_file`. + + .. code-block:: python + + @app.route("/uploads/") + def download_file(name): + return send_from_directory( + app.config['UPLOAD_FOLDER'], name, as_attachment=True + ) + + This is a secure way to serve files from a folder, such as static + files or uploads. Uses :func:`~werkzeug.security.safe_join` to + ensure the path coming from the client is not maliciously crafted to + point outside the specified directory. + + If the final path does not point to an existing regular file, + raises a 404 :exc:`~werkzeug.exceptions.NotFound` error. + + :param directory: The directory that ``path`` must be located under, + relative to the current application's root path. This *must not* + be a value provided by the client, otherwise it becomes insecure. + :param path: The path to the file to send, relative to + ``directory``. + :param kwargs: Arguments to pass to :func:`send_file`. + + .. versionchanged:: 2.0 + ``path`` replaces the ``filename`` parameter. + + .. versionadded:: 2.0 + Moved the implementation to Werkzeug. This is now a wrapper to + pass some Flask-specific arguments. + + .. versionadded:: 0.5 + """ + return werkzeug.utils.send_from_directory( # type: ignore[return-value] + directory, path, **_prepare_send_file_kwargs(**kwargs) + ) + + +def get_root_path(import_name: str) -> str: + """Find the root path of a package, or the path that contains a + module. If it cannot be found, returns the current working + directory. + + Not to be confused with the value returned by :func:`find_package`. + + :meta private: + """ + # Module already imported and has a file attribute. Use that first. + mod = sys.modules.get(import_name) + + if mod is not None and hasattr(mod, "__file__") and mod.__file__ is not None: + return os.path.dirname(os.path.abspath(mod.__file__)) + + # Next attempt: check the loader. + try: + spec = importlib.util.find_spec(import_name) + + if spec is None: + raise ValueError + except (ImportError, ValueError): + loader = None + else: + loader = spec.loader + + # Loader does not exist or we're referring to an unloaded main + # module or a main module without path (interactive sessions), go + # with the current working directory. + if loader is None: + return os.getcwd() + + if hasattr(loader, "get_filename"): + filepath = loader.get_filename(import_name) # pyright: ignore + else: + # Fall back to imports. + __import__(import_name) + mod = sys.modules[import_name] + filepath = getattr(mod, "__file__", None) + + # If we don't have a file path it might be because it is a + # namespace package. In this case pick the root path from the + # first module that is contained in the package. + if filepath is None: + raise RuntimeError( + "No root path can be found for the provided module" + f" {import_name!r}. This can happen because the module" + " came from an import hook that does not provide file" + " name information or because it's a namespace package." + " In this case the root path needs to be explicitly" + " provided." + ) + + # filepath is import_name.py for a module, or __init__.py for a package. + return os.path.dirname(os.path.abspath(filepath)) # type: ignore[no-any-return] + + +@cache +def _split_blueprint_path(name: str) -> list[str]: + out: list[str] = [name] + + if "." in name: + out.extend(_split_blueprint_path(name.rpartition(".")[0])) + + return out diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask/json/__init__.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask/json/__init__.py new file mode 100644 index 000000000..c0941d049 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask/json/__init__.py @@ -0,0 +1,170 @@ +from __future__ import annotations + +import json as _json +import typing as t + +from ..globals import current_app +from .provider import _default + +if t.TYPE_CHECKING: # pragma: no cover + from ..wrappers import Response + + +def dumps(obj: t.Any, **kwargs: t.Any) -> str: + """Serialize data as JSON. + + If :data:`~flask.current_app` is available, it will use its + :meth:`app.json.dumps() ` + method, otherwise it will use :func:`json.dumps`. + + :param obj: The data to serialize. + :param kwargs: Arguments passed to the ``dumps`` implementation. + + .. versionchanged:: 2.3 + The ``app`` parameter was removed. + + .. versionchanged:: 2.2 + Calls ``current_app.json.dumps``, allowing an app to override + the behavior. + + .. versionchanged:: 2.0.2 + :class:`decimal.Decimal` is supported by converting to a string. + + .. versionchanged:: 2.0 + ``encoding`` will be removed in Flask 2.1. + + .. versionchanged:: 1.0.3 + ``app`` can be passed directly, rather than requiring an app + context for configuration. + """ + if current_app: + return current_app.json.dumps(obj, **kwargs) + + kwargs.setdefault("default", _default) + return _json.dumps(obj, **kwargs) + + +def dump(obj: t.Any, fp: t.IO[str], **kwargs: t.Any) -> None: + """Serialize data as JSON and write to a file. + + If :data:`~flask.current_app` is available, it will use its + :meth:`app.json.dump() ` + method, otherwise it will use :func:`json.dump`. + + :param obj: The data to serialize. + :param fp: A file opened for writing text. Should use the UTF-8 + encoding to be valid JSON. + :param kwargs: Arguments passed to the ``dump`` implementation. + + .. versionchanged:: 2.3 + The ``app`` parameter was removed. + + .. versionchanged:: 2.2 + Calls ``current_app.json.dump``, allowing an app to override + the behavior. + + .. versionchanged:: 2.0 + Writing to a binary file, and the ``encoding`` argument, will be + removed in Flask 2.1. + """ + if current_app: + current_app.json.dump(obj, fp, **kwargs) + else: + kwargs.setdefault("default", _default) + _json.dump(obj, fp, **kwargs) + + +def loads(s: str | bytes, **kwargs: t.Any) -> t.Any: + """Deserialize data as JSON. + + If :data:`~flask.current_app` is available, it will use its + :meth:`app.json.loads() ` + method, otherwise it will use :func:`json.loads`. + + :param s: Text or UTF-8 bytes. + :param kwargs: Arguments passed to the ``loads`` implementation. + + .. versionchanged:: 2.3 + The ``app`` parameter was removed. + + .. versionchanged:: 2.2 + Calls ``current_app.json.loads``, allowing an app to override + the behavior. + + .. versionchanged:: 2.0 + ``encoding`` will be removed in Flask 2.1. The data must be a + string or UTF-8 bytes. + + .. versionchanged:: 1.0.3 + ``app`` can be passed directly, rather than requiring an app + context for configuration. + """ + if current_app: + return current_app.json.loads(s, **kwargs) + + return _json.loads(s, **kwargs) + + +def load(fp: t.IO[t.AnyStr], **kwargs: t.Any) -> t.Any: + """Deserialize data as JSON read from a file. + + If :data:`~flask.current_app` is available, it will use its + :meth:`app.json.load() ` + method, otherwise it will use :func:`json.load`. + + :param fp: A file opened for reading text or UTF-8 bytes. + :param kwargs: Arguments passed to the ``load`` implementation. + + .. versionchanged:: 2.3 + The ``app`` parameter was removed. + + .. versionchanged:: 2.2 + Calls ``current_app.json.load``, allowing an app to override + the behavior. + + .. versionchanged:: 2.2 + The ``app`` parameter will be removed in Flask 2.3. + + .. versionchanged:: 2.0 + ``encoding`` will be removed in Flask 2.1. The file must be text + mode, or binary mode with UTF-8 bytes. + """ + if current_app: + return current_app.json.load(fp, **kwargs) + + return _json.load(fp, **kwargs) + + +def jsonify(*args: t.Any, **kwargs: t.Any) -> Response: + """Serialize the given arguments as JSON, and return a + :class:`~flask.Response` object with the ``application/json`` + mimetype. A dict or list returned from a view will be converted to a + JSON response automatically without needing to call this. + + This requires an active request or application context, and calls + :meth:`app.json.response() `. + + In debug mode, the output is formatted with indentation to make it + easier to read. This may also be controlled by the provider. + + Either positional or keyword arguments can be given, not both. + If no arguments are given, ``None`` is serialized. + + :param args: A single value to serialize, or multiple values to + treat as a list to serialize. + :param kwargs: Treat as a dict to serialize. + + .. versionchanged:: 2.2 + Calls ``current_app.json.response``, allowing an app to override + the behavior. + + .. versionchanged:: 2.0.2 + :class:`decimal.Decimal` is supported by converting to a string. + + .. versionchanged:: 0.11 + Added support for serializing top-level arrays. This was a + security risk in ancient browsers. See :ref:`security-json`. + + .. versionadded:: 0.2 + """ + return current_app.json.response(*args, **kwargs) # type: ignore[return-value] diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask/json/provider.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask/json/provider.py new file mode 100644 index 000000000..ea7e4753f --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask/json/provider.py @@ -0,0 +1,215 @@ +from __future__ import annotations + +import dataclasses +import decimal +import json +import typing as t +import uuid +import weakref +from datetime import date + +from werkzeug.http import http_date + +if t.TYPE_CHECKING: # pragma: no cover + from werkzeug.sansio.response import Response + + from ..sansio.app import App + + +class JSONProvider: + """A standard set of JSON operations for an application. Subclasses + of this can be used to customize JSON behavior or use different + JSON libraries. + + To implement a provider for a specific library, subclass this base + class and implement at least :meth:`dumps` and :meth:`loads`. All + other methods have default implementations. + + To use a different provider, either subclass ``Flask`` and set + :attr:`~flask.Flask.json_provider_class` to a provider class, or set + :attr:`app.json ` to an instance of the class. + + :param app: An application instance. This will be stored as a + :class:`weakref.proxy` on the :attr:`_app` attribute. + + .. versionadded:: 2.2 + """ + + def __init__(self, app: App) -> None: + self._app: App = weakref.proxy(app) + + def dumps(self, obj: t.Any, **kwargs: t.Any) -> str: + """Serialize data as JSON. + + :param obj: The data to serialize. + :param kwargs: May be passed to the underlying JSON library. + """ + raise NotImplementedError + + def dump(self, obj: t.Any, fp: t.IO[str], **kwargs: t.Any) -> None: + """Serialize data as JSON and write to a file. + + :param obj: The data to serialize. + :param fp: A file opened for writing text. Should use the UTF-8 + encoding to be valid JSON. + :param kwargs: May be passed to the underlying JSON library. + """ + fp.write(self.dumps(obj, **kwargs)) + + def loads(self, s: str | bytes, **kwargs: t.Any) -> t.Any: + """Deserialize data as JSON. + + :param s: Text or UTF-8 bytes. + :param kwargs: May be passed to the underlying JSON library. + """ + raise NotImplementedError + + def load(self, fp: t.IO[t.AnyStr], **kwargs: t.Any) -> t.Any: + """Deserialize data as JSON read from a file. + + :param fp: A file opened for reading text or UTF-8 bytes. + :param kwargs: May be passed to the underlying JSON library. + """ + return self.loads(fp.read(), **kwargs) + + def _prepare_response_obj( + self, args: tuple[t.Any, ...], kwargs: dict[str, t.Any] + ) -> t.Any: + if args and kwargs: + raise TypeError("app.json.response() takes either args or kwargs, not both") + + if not args and not kwargs: + return None + + if len(args) == 1: + return args[0] + + return args or kwargs + + def response(self, *args: t.Any, **kwargs: t.Any) -> Response: + """Serialize the given arguments as JSON, and return a + :class:`~flask.Response` object with the ``application/json`` + mimetype. + + The :func:`~flask.json.jsonify` function calls this method for + the current application. + + Either positional or keyword arguments can be given, not both. + If no arguments are given, ``None`` is serialized. + + :param args: A single value to serialize, or multiple values to + treat as a list to serialize. + :param kwargs: Treat as a dict to serialize. + """ + obj = self._prepare_response_obj(args, kwargs) + return self._app.response_class(self.dumps(obj), mimetype="application/json") + + +def _default(o: t.Any) -> t.Any: + if isinstance(o, date): + return http_date(o) + + if isinstance(o, (decimal.Decimal, uuid.UUID)): + return str(o) + + if dataclasses and dataclasses.is_dataclass(o): + return dataclasses.asdict(o) # type: ignore[arg-type] + + if hasattr(o, "__html__"): + return str(o.__html__()) + + raise TypeError(f"Object of type {type(o).__name__} is not JSON serializable") + + +class DefaultJSONProvider(JSONProvider): + """Provide JSON operations using Python's built-in :mod:`json` + library. Serializes the following additional data types: + + - :class:`datetime.datetime` and :class:`datetime.date` are + serialized to :rfc:`822` strings. This is the same as the HTTP + date format. + - :class:`uuid.UUID` is serialized to a string. + - :class:`dataclasses.dataclass` is passed to + :func:`dataclasses.asdict`. + - :class:`~markupsafe.Markup` (or any object with a ``__html__`` + method) will call the ``__html__`` method to get a string. + """ + + default: t.Callable[[t.Any], t.Any] = staticmethod(_default) # type: ignore[assignment] + """Apply this function to any object that :meth:`json.dumps` does + not know how to serialize. It should return a valid JSON type or + raise a ``TypeError``. + """ + + ensure_ascii = True + """Replace non-ASCII characters with escape sequences. This may be + more compatible with some clients, but can be disabled for better + performance and size. + """ + + sort_keys = True + """Sort the keys in any serialized dicts. This may be useful for + some caching situations, but can be disabled for better performance. + When enabled, keys must all be strings, they are not converted + before sorting. + """ + + compact: bool | None = None + """If ``True``, or ``None`` out of debug mode, the :meth:`response` + output will not add indentation, newlines, or spaces. If ``False``, + or ``None`` in debug mode, it will use a non-compact representation. + """ + + mimetype = "application/json" + """The mimetype set in :meth:`response`.""" + + def dumps(self, obj: t.Any, **kwargs: t.Any) -> str: + """Serialize data as JSON to a string. + + Keyword arguments are passed to :func:`json.dumps`. Sets some + parameter defaults from the :attr:`default`, + :attr:`ensure_ascii`, and :attr:`sort_keys` attributes. + + :param obj: The data to serialize. + :param kwargs: Passed to :func:`json.dumps`. + """ + kwargs.setdefault("default", self.default) + kwargs.setdefault("ensure_ascii", self.ensure_ascii) + kwargs.setdefault("sort_keys", self.sort_keys) + return json.dumps(obj, **kwargs) + + def loads(self, s: str | bytes, **kwargs: t.Any) -> t.Any: + """Deserialize data as JSON from a string or bytes. + + :param s: Text or UTF-8 bytes. + :param kwargs: Passed to :func:`json.loads`. + """ + return json.loads(s, **kwargs) + + def response(self, *args: t.Any, **kwargs: t.Any) -> Response: + """Serialize the given arguments as JSON, and return a + :class:`~flask.Response` object with it. The response mimetype + will be "application/json" and can be changed with + :attr:`mimetype`. + + If :attr:`compact` is ``False`` or debug mode is enabled, the + output will be formatted to be easier to read. + + Either positional or keyword arguments can be given, not both. + If no arguments are given, ``None`` is serialized. + + :param args: A single value to serialize, or multiple values to + treat as a list to serialize. + :param kwargs: Treat as a dict to serialize. + """ + obj = self._prepare_response_obj(args, kwargs) + dump_args: dict[str, t.Any] = {} + + if (self.compact is None and self._app.debug) or self.compact is False: + dump_args.setdefault("indent", 2) + else: + dump_args.setdefault("separators", (",", ":")) + + return self._app.response_class( + f"{self.dumps(obj, **dump_args)}\n", mimetype=self.mimetype + ) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask/json/tag.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask/json/tag.py new file mode 100644 index 000000000..8dc3629bf --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask/json/tag.py @@ -0,0 +1,327 @@ +""" +Tagged JSON +~~~~~~~~~~~ + +A compact representation for lossless serialization of non-standard JSON +types. :class:`~flask.sessions.SecureCookieSessionInterface` uses this +to serialize the session data, but it may be useful in other places. It +can be extended to support other types. + +.. autoclass:: TaggedJSONSerializer + :members: + +.. autoclass:: JSONTag + :members: + +Let's see an example that adds support for +:class:`~collections.OrderedDict`. Dicts don't have an order in JSON, so +to handle this we will dump the items as a list of ``[key, value]`` +pairs. Subclass :class:`JSONTag` and give it the new key ``' od'`` to +identify the type. The session serializer processes dicts first, so +insert the new tag at the front of the order since ``OrderedDict`` must +be processed before ``dict``. + +.. code-block:: python + + from flask.json.tag import JSONTag + + class TagOrderedDict(JSONTag): + __slots__ = ('serializer',) + key = ' od' + + def check(self, value): + return isinstance(value, OrderedDict) + + def to_json(self, value): + return [[k, self.serializer.tag(v)] for k, v in iteritems(value)] + + def to_python(self, value): + return OrderedDict(value) + + app.session_interface.serializer.register(TagOrderedDict, index=0) +""" + +from __future__ import annotations + +import typing as t +from base64 import b64decode +from base64 import b64encode +from datetime import datetime +from uuid import UUID + +from markupsafe import Markup +from werkzeug.http import http_date +from werkzeug.http import parse_date + +from ..json import dumps +from ..json import loads + + +class JSONTag: + """Base class for defining type tags for :class:`TaggedJSONSerializer`.""" + + __slots__ = ("serializer",) + + #: The tag to mark the serialized object with. If empty, this tag is + #: only used as an intermediate step during tagging. + key: str = "" + + def __init__(self, serializer: TaggedJSONSerializer) -> None: + """Create a tagger for the given serializer.""" + self.serializer = serializer + + def check(self, value: t.Any) -> bool: + """Check if the given value should be tagged by this tag.""" + raise NotImplementedError + + def to_json(self, value: t.Any) -> t.Any: + """Convert the Python object to an object that is a valid JSON type. + The tag will be added later.""" + raise NotImplementedError + + def to_python(self, value: t.Any) -> t.Any: + """Convert the JSON representation back to the correct type. The tag + will already be removed.""" + raise NotImplementedError + + def tag(self, value: t.Any) -> dict[str, t.Any]: + """Convert the value to a valid JSON type and add the tag structure + around it.""" + return {self.key: self.to_json(value)} + + +class TagDict(JSONTag): + """Tag for 1-item dicts whose only key matches a registered tag. + + Internally, the dict key is suffixed with `__`, and the suffix is removed + when deserializing. + """ + + __slots__ = () + key = " di" + + def check(self, value: t.Any) -> bool: + return ( + isinstance(value, dict) + and len(value) == 1 + and next(iter(value)) in self.serializer.tags + ) + + def to_json(self, value: t.Any) -> t.Any: + key = next(iter(value)) + return {f"{key}__": self.serializer.tag(value[key])} + + def to_python(self, value: t.Any) -> t.Any: + key = next(iter(value)) + return {key[:-2]: value[key]} + + +class PassDict(JSONTag): + __slots__ = () + + def check(self, value: t.Any) -> bool: + return isinstance(value, dict) + + def to_json(self, value: t.Any) -> t.Any: + # JSON objects may only have string keys, so don't bother tagging the + # key here. + return {k: self.serializer.tag(v) for k, v in value.items()} + + tag = to_json + + +class TagTuple(JSONTag): + __slots__ = () + key = " t" + + def check(self, value: t.Any) -> bool: + return isinstance(value, tuple) + + def to_json(self, value: t.Any) -> t.Any: + return [self.serializer.tag(item) for item in value] + + def to_python(self, value: t.Any) -> t.Any: + return tuple(value) + + +class PassList(JSONTag): + __slots__ = () + + def check(self, value: t.Any) -> bool: + return isinstance(value, list) + + def to_json(self, value: t.Any) -> t.Any: + return [self.serializer.tag(item) for item in value] + + tag = to_json + + +class TagBytes(JSONTag): + __slots__ = () + key = " b" + + def check(self, value: t.Any) -> bool: + return isinstance(value, bytes) + + def to_json(self, value: t.Any) -> t.Any: + return b64encode(value).decode("ascii") + + def to_python(self, value: t.Any) -> t.Any: + return b64decode(value) + + +class TagMarkup(JSONTag): + """Serialize anything matching the :class:`~markupsafe.Markup` API by + having a ``__html__`` method to the result of that method. Always + deserializes to an instance of :class:`~markupsafe.Markup`.""" + + __slots__ = () + key = " m" + + def check(self, value: t.Any) -> bool: + return callable(getattr(value, "__html__", None)) + + def to_json(self, value: t.Any) -> t.Any: + return str(value.__html__()) + + def to_python(self, value: t.Any) -> t.Any: + return Markup(value) + + +class TagUUID(JSONTag): + __slots__ = () + key = " u" + + def check(self, value: t.Any) -> bool: + return isinstance(value, UUID) + + def to_json(self, value: t.Any) -> t.Any: + return value.hex + + def to_python(self, value: t.Any) -> t.Any: + return UUID(value) + + +class TagDateTime(JSONTag): + __slots__ = () + key = " d" + + def check(self, value: t.Any) -> bool: + return isinstance(value, datetime) + + def to_json(self, value: t.Any) -> t.Any: + return http_date(value) + + def to_python(self, value: t.Any) -> t.Any: + return parse_date(value) + + +class TaggedJSONSerializer: + """Serializer that uses a tag system to compactly represent objects that + are not JSON types. Passed as the intermediate serializer to + :class:`itsdangerous.Serializer`. + + The following extra types are supported: + + * :class:`dict` + * :class:`tuple` + * :class:`bytes` + * :class:`~markupsafe.Markup` + * :class:`~uuid.UUID` + * :class:`~datetime.datetime` + """ + + __slots__ = ("tags", "order") + + #: Tag classes to bind when creating the serializer. Other tags can be + #: added later using :meth:`~register`. + default_tags = [ + TagDict, + PassDict, + TagTuple, + PassList, + TagBytes, + TagMarkup, + TagUUID, + TagDateTime, + ] + + def __init__(self) -> None: + self.tags: dict[str, JSONTag] = {} + self.order: list[JSONTag] = [] + + for cls in self.default_tags: + self.register(cls) + + def register( + self, + tag_class: type[JSONTag], + force: bool = False, + index: int | None = None, + ) -> None: + """Register a new tag with this serializer. + + :param tag_class: tag class to register. Will be instantiated with this + serializer instance. + :param force: overwrite an existing tag. If false (default), a + :exc:`KeyError` is raised. + :param index: index to insert the new tag in the tag order. Useful when + the new tag is a special case of an existing tag. If ``None`` + (default), the tag is appended to the end of the order. + + :raise KeyError: if the tag key is already registered and ``force`` is + not true. + """ + tag = tag_class(self) + key = tag.key + + if key: + if not force and key in self.tags: + raise KeyError(f"Tag '{key}' is already registered.") + + self.tags[key] = tag + + if index is None: + self.order.append(tag) + else: + self.order.insert(index, tag) + + def tag(self, value: t.Any) -> t.Any: + """Convert a value to a tagged representation if necessary.""" + for tag in self.order: + if tag.check(value): + return tag.tag(value) + + return value + + def untag(self, value: dict[str, t.Any]) -> t.Any: + """Convert a tagged representation back to the original type.""" + if len(value) != 1: + return value + + key = next(iter(value)) + + if key not in self.tags: + return value + + return self.tags[key].to_python(value[key]) + + def _untag_scan(self, value: t.Any) -> t.Any: + if isinstance(value, dict): + # untag each item recursively + value = {k: self._untag_scan(v) for k, v in value.items()} + # untag the dict itself + value = self.untag(value) + elif isinstance(value, list): + # untag each item recursively + value = [self._untag_scan(item) for item in value] + + return value + + def dumps(self, value: t.Any) -> str: + """Tag the value and dump it to a compact JSON string.""" + return dumps(self.tag(value), separators=(",", ":")) + + def loads(self, value: str) -> t.Any: + """Load data from a JSON string and deserialized any tagged objects.""" + return self._untag_scan(loads(value)) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask/logging.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask/logging.py new file mode 100644 index 000000000..0cb8f4374 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask/logging.py @@ -0,0 +1,79 @@ +from __future__ import annotations + +import logging +import sys +import typing as t + +from werkzeug.local import LocalProxy + +from .globals import request + +if t.TYPE_CHECKING: # pragma: no cover + from .sansio.app import App + + +@LocalProxy +def wsgi_errors_stream() -> t.TextIO: + """Find the most appropriate error stream for the application. If a request + is active, log to ``wsgi.errors``, otherwise use ``sys.stderr``. + + If you configure your own :class:`logging.StreamHandler`, you may want to + use this for the stream. If you are using file or dict configuration and + can't import this directly, you can refer to it as + ``ext://flask.logging.wsgi_errors_stream``. + """ + if request: + return request.environ["wsgi.errors"] # type: ignore[no-any-return] + + return sys.stderr + + +def has_level_handler(logger: logging.Logger) -> bool: + """Check if there is a handler in the logging chain that will handle the + given logger's :meth:`effective level <~logging.Logger.getEffectiveLevel>`. + """ + level = logger.getEffectiveLevel() + current = logger + + while current: + if any(handler.level <= level for handler in current.handlers): + return True + + if not current.propagate: + break + + current = current.parent # type: ignore + + return False + + +#: Log messages to :func:`~flask.logging.wsgi_errors_stream` with the format +#: ``[%(asctime)s] %(levelname)s in %(module)s: %(message)s``. +default_handler = logging.StreamHandler(wsgi_errors_stream) # type: ignore +default_handler.setFormatter( + logging.Formatter("[%(asctime)s] %(levelname)s in %(module)s: %(message)s") +) + + +def create_logger(app: App) -> logging.Logger: + """Get the Flask app's logger and configure it if needed. + + The logger name will be the same as + :attr:`app.import_name `. + + When :attr:`~flask.Flask.debug` is enabled, set the logger level to + :data:`logging.DEBUG` if it is not set. + + If there is no handler for the logger's effective level, add a + :class:`~logging.StreamHandler` for + :func:`~flask.logging.wsgi_errors_stream` with a basic format. + """ + logger = logging.getLogger(app.name) + + if app.debug and not logger.level: + logger.setLevel(logging.DEBUG) + + if not has_level_handler(logger): + logger.addHandler(default_handler) + + return logger diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask/py.typed b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask/py.typed new file mode 100644 index 000000000..e69de29bb diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask/sansio/README.md b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask/sansio/README.md new file mode 100644 index 000000000..623ac1982 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask/sansio/README.md @@ -0,0 +1,6 @@ +# Sansio + +This folder contains code that can be used by alternative Flask +implementations, for example Quart. The code therefore cannot do any +IO, nor be part of a likely IO path. Finally this code cannot use the +Flask globals. diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask/sansio/app.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask/sansio/app.py new file mode 100644 index 000000000..58cb87306 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask/sansio/app.py @@ -0,0 +1,964 @@ +from __future__ import annotations + +import logging +import os +import sys +import typing as t +from datetime import timedelta +from itertools import chain + +from werkzeug.exceptions import Aborter +from werkzeug.exceptions import BadRequest +from werkzeug.exceptions import BadRequestKeyError +from werkzeug.routing import BuildError +from werkzeug.routing import Map +from werkzeug.routing import Rule +from werkzeug.sansio.response import Response +from werkzeug.utils import cached_property +from werkzeug.utils import redirect as _wz_redirect + +from .. import typing as ft +from ..config import Config +from ..config import ConfigAttribute +from ..ctx import _AppCtxGlobals +from ..helpers import _split_blueprint_path +from ..helpers import get_debug_flag +from ..json.provider import DefaultJSONProvider +from ..json.provider import JSONProvider +from ..logging import create_logger +from ..templating import DispatchingJinjaLoader +from ..templating import Environment +from .scaffold import _endpoint_from_view_func +from .scaffold import find_package +from .scaffold import Scaffold +from .scaffold import setupmethod + +if t.TYPE_CHECKING: # pragma: no cover + from werkzeug.wrappers import Response as BaseResponse + + from ..testing import FlaskClient + from ..testing import FlaskCliRunner + from .blueprints import Blueprint + +T_shell_context_processor = t.TypeVar( + "T_shell_context_processor", bound=ft.ShellContextProcessorCallable +) +T_teardown = t.TypeVar("T_teardown", bound=ft.TeardownCallable) +T_template_filter = t.TypeVar("T_template_filter", bound=ft.TemplateFilterCallable) +T_template_global = t.TypeVar("T_template_global", bound=ft.TemplateGlobalCallable) +T_template_test = t.TypeVar("T_template_test", bound=ft.TemplateTestCallable) + + +def _make_timedelta(value: timedelta | int | None) -> timedelta | None: + if value is None or isinstance(value, timedelta): + return value + + return timedelta(seconds=value) + + +class App(Scaffold): + """The flask object implements a WSGI application and acts as the central + object. It is passed the name of the module or package of the + application. Once it is created it will act as a central registry for + the view functions, the URL rules, template configuration and much more. + + The name of the package is used to resolve resources from inside the + package or the folder the module is contained in depending on if the + package parameter resolves to an actual python package (a folder with + an :file:`__init__.py` file inside) or a standard module (just a ``.py`` file). + + For more information about resource loading, see :func:`open_resource`. + + Usually you create a :class:`Flask` instance in your main module or + in the :file:`__init__.py` file of your package like this:: + + from flask import Flask + app = Flask(__name__) + + .. admonition:: About the First Parameter + + The idea of the first parameter is to give Flask an idea of what + belongs to your application. This name is used to find resources + on the filesystem, can be used by extensions to improve debugging + information and a lot more. + + So it's important what you provide there. If you are using a single + module, `__name__` is always the correct value. If you however are + using a package, it's usually recommended to hardcode the name of + your package there. + + For example if your application is defined in :file:`yourapplication/app.py` + you should create it with one of the two versions below:: + + app = Flask('yourapplication') + app = Flask(__name__.split('.')[0]) + + Why is that? The application will work even with `__name__`, thanks + to how resources are looked up. However it will make debugging more + painful. Certain extensions can make assumptions based on the + import name of your application. For example the Flask-SQLAlchemy + extension will look for the code in your application that triggered + an SQL query in debug mode. If the import name is not properly set + up, that debugging information is lost. (For example it would only + pick up SQL queries in `yourapplication.app` and not + `yourapplication.views.frontend`) + + .. versionadded:: 0.7 + The `static_url_path`, `static_folder`, and `template_folder` + parameters were added. + + .. versionadded:: 0.8 + The `instance_path` and `instance_relative_config` parameters were + added. + + .. versionadded:: 0.11 + The `root_path` parameter was added. + + .. versionadded:: 1.0 + The ``host_matching`` and ``static_host`` parameters were added. + + .. versionadded:: 1.0 + The ``subdomain_matching`` parameter was added. Subdomain + matching needs to be enabled manually now. Setting + :data:`SERVER_NAME` does not implicitly enable it. + + :param import_name: the name of the application package + :param static_url_path: can be used to specify a different path for the + static files on the web. Defaults to the name + of the `static_folder` folder. + :param static_folder: The folder with static files that is served at + ``static_url_path``. Relative to the application ``root_path`` + or an absolute path. Defaults to ``'static'``. + :param static_host: the host to use when adding the static route. + Defaults to None. Required when using ``host_matching=True`` + with a ``static_folder`` configured. + :param host_matching: set ``url_map.host_matching`` attribute. + Defaults to False. + :param subdomain_matching: consider the subdomain relative to + :data:`SERVER_NAME` when matching routes. Defaults to False. + :param template_folder: the folder that contains the templates that should + be used by the application. Defaults to + ``'templates'`` folder in the root path of the + application. + :param instance_path: An alternative instance path for the application. + By default the folder ``'instance'`` next to the + package or module is assumed to be the instance + path. + :param instance_relative_config: if set to ``True`` relative filenames + for loading the config are assumed to + be relative to the instance path instead + of the application root. + :param root_path: The path to the root of the application files. + This should only be set manually when it can't be detected + automatically, such as for namespace packages. + """ + + #: The class of the object assigned to :attr:`aborter`, created by + #: :meth:`create_aborter`. That object is called by + #: :func:`flask.abort` to raise HTTP errors, and can be + #: called directly as well. + #: + #: Defaults to :class:`werkzeug.exceptions.Aborter`. + #: + #: .. versionadded:: 2.2 + aborter_class = Aborter + + #: The class that is used for the Jinja environment. + #: + #: .. versionadded:: 0.11 + jinja_environment = Environment + + #: The class that is used for the :data:`~flask.g` instance. + #: + #: Example use cases for a custom class: + #: + #: 1. Store arbitrary attributes on flask.g. + #: 2. Add a property for lazy per-request database connectors. + #: 3. Return None instead of AttributeError on unexpected attributes. + #: 4. Raise exception if an unexpected attr is set, a "controlled" flask.g. + #: + #: In Flask 0.9 this property was called `request_globals_class` but it + #: was changed in 0.10 to :attr:`app_ctx_globals_class` because the + #: flask.g object is now application context scoped. + #: + #: .. versionadded:: 0.10 + app_ctx_globals_class = _AppCtxGlobals + + #: The class that is used for the ``config`` attribute of this app. + #: Defaults to :class:`~flask.Config`. + #: + #: Example use cases for a custom class: + #: + #: 1. Default values for certain config options. + #: 2. Access to config values through attributes in addition to keys. + #: + #: .. versionadded:: 0.11 + config_class = Config + + #: The testing flag. Set this to ``True`` to enable the test mode of + #: Flask extensions (and in the future probably also Flask itself). + #: For example this might activate test helpers that have an + #: additional runtime cost which should not be enabled by default. + #: + #: If this is enabled and PROPAGATE_EXCEPTIONS is not changed from the + #: default it's implicitly enabled. + #: + #: This attribute can also be configured from the config with the + #: ``TESTING`` configuration key. Defaults to ``False``. + testing = ConfigAttribute[bool]("TESTING") + + #: If a secret key is set, cryptographic components can use this to + #: sign cookies and other things. Set this to a complex random value + #: when you want to use the secure cookie for instance. + #: + #: This attribute can also be configured from the config with the + #: :data:`SECRET_KEY` configuration key. Defaults to ``None``. + secret_key = ConfigAttribute[t.Union[str, bytes, None]]("SECRET_KEY") + + #: A :class:`~datetime.timedelta` which is used to set the expiration + #: date of a permanent session. The default is 31 days which makes a + #: permanent session survive for roughly one month. + #: + #: This attribute can also be configured from the config with the + #: ``PERMANENT_SESSION_LIFETIME`` configuration key. Defaults to + #: ``timedelta(days=31)`` + permanent_session_lifetime = ConfigAttribute[timedelta]( + "PERMANENT_SESSION_LIFETIME", + get_converter=_make_timedelta, # type: ignore[arg-type] + ) + + json_provider_class: type[JSONProvider] = DefaultJSONProvider + """A subclass of :class:`~flask.json.provider.JSONProvider`. An + instance is created and assigned to :attr:`app.json` when creating + the app. + + The default, :class:`~flask.json.provider.DefaultJSONProvider`, uses + Python's built-in :mod:`json` library. A different provider can use + a different JSON library. + + .. versionadded:: 2.2 + """ + + #: Options that are passed to the Jinja environment in + #: :meth:`create_jinja_environment`. Changing these options after + #: the environment is created (accessing :attr:`jinja_env`) will + #: have no effect. + #: + #: .. versionchanged:: 1.1.0 + #: This is a ``dict`` instead of an ``ImmutableDict`` to allow + #: easier configuration. + #: + jinja_options: dict[str, t.Any] = {} + + #: The rule object to use for URL rules created. This is used by + #: :meth:`add_url_rule`. Defaults to :class:`werkzeug.routing.Rule`. + #: + #: .. versionadded:: 0.7 + url_rule_class = Rule + + #: The map object to use for storing the URL rules and routing + #: configuration parameters. Defaults to :class:`werkzeug.routing.Map`. + #: + #: .. versionadded:: 1.1.0 + url_map_class = Map + + #: The :meth:`test_client` method creates an instance of this test + #: client class. Defaults to :class:`~flask.testing.FlaskClient`. + #: + #: .. versionadded:: 0.7 + test_client_class: type[FlaskClient] | None = None + + #: The :class:`~click.testing.CliRunner` subclass, by default + #: :class:`~flask.testing.FlaskCliRunner` that is used by + #: :meth:`test_cli_runner`. Its ``__init__`` method should take a + #: Flask app object as the first argument. + #: + #: .. versionadded:: 1.0 + test_cli_runner_class: type[FlaskCliRunner] | None = None + + default_config: dict[str, t.Any] + response_class: type[Response] + + def __init__( + self, + import_name: str, + static_url_path: str | None = None, + static_folder: str | os.PathLike[str] | None = "static", + static_host: str | None = None, + host_matching: bool = False, + subdomain_matching: bool = False, + template_folder: str | os.PathLike[str] | None = "templates", + instance_path: str | None = None, + instance_relative_config: bool = False, + root_path: str | None = None, + ) -> None: + super().__init__( + import_name=import_name, + static_folder=static_folder, + static_url_path=static_url_path, + template_folder=template_folder, + root_path=root_path, + ) + + if instance_path is None: + instance_path = self.auto_find_instance_path() + elif not os.path.isabs(instance_path): + raise ValueError( + "If an instance path is provided it must be absolute." + " A relative path was given instead." + ) + + #: Holds the path to the instance folder. + #: + #: .. versionadded:: 0.8 + self.instance_path = instance_path + + #: The configuration dictionary as :class:`Config`. This behaves + #: exactly like a regular dictionary but supports additional methods + #: to load a config from files. + self.config = self.make_config(instance_relative_config) + + #: An instance of :attr:`aborter_class` created by + #: :meth:`make_aborter`. This is called by :func:`flask.abort` + #: to raise HTTP errors, and can be called directly as well. + #: + #: .. versionadded:: 2.2 + #: Moved from ``flask.abort``, which calls this object. + self.aborter = self.make_aborter() + + self.json: JSONProvider = self.json_provider_class(self) + """Provides access to JSON methods. Functions in ``flask.json`` + will call methods on this provider when the application context + is active. Used for handling JSON requests and responses. + + An instance of :attr:`json_provider_class`. Can be customized by + changing that attribute on a subclass, or by assigning to this + attribute afterwards. + + The default, :class:`~flask.json.provider.DefaultJSONProvider`, + uses Python's built-in :mod:`json` library. A different provider + can use a different JSON library. + + .. versionadded:: 2.2 + """ + + #: A list of functions that are called by + #: :meth:`handle_url_build_error` when :meth:`.url_for` raises a + #: :exc:`~werkzeug.routing.BuildError`. Each function is called + #: with ``error``, ``endpoint`` and ``values``. If a function + #: returns ``None`` or raises a ``BuildError``, it is skipped. + #: Otherwise, its return value is returned by ``url_for``. + #: + #: .. versionadded:: 0.9 + self.url_build_error_handlers: list[ + t.Callable[[Exception, str, dict[str, t.Any]], str] + ] = [] + + #: A list of functions that are called when the application context + #: is destroyed. Since the application context is also torn down + #: if the request ends this is the place to store code that disconnects + #: from databases. + #: + #: .. versionadded:: 0.9 + self.teardown_appcontext_funcs: list[ft.TeardownCallable] = [] + + #: A list of shell context processor functions that should be run + #: when a shell context is created. + #: + #: .. versionadded:: 0.11 + self.shell_context_processors: list[ft.ShellContextProcessorCallable] = [] + + #: Maps registered blueprint names to blueprint objects. The + #: dict retains the order the blueprints were registered in. + #: Blueprints can be registered multiple times, this dict does + #: not track how often they were attached. + #: + #: .. versionadded:: 0.7 + self.blueprints: dict[str, Blueprint] = {} + + #: a place where extensions can store application specific state. For + #: example this is where an extension could store database engines and + #: similar things. + #: + #: The key must match the name of the extension module. For example in + #: case of a "Flask-Foo" extension in `flask_foo`, the key would be + #: ``'foo'``. + #: + #: .. versionadded:: 0.7 + self.extensions: dict[str, t.Any] = {} + + #: The :class:`~werkzeug.routing.Map` for this instance. You can use + #: this to change the routing converters after the class was created + #: but before any routes are connected. Example:: + #: + #: from werkzeug.routing import BaseConverter + #: + #: class ListConverter(BaseConverter): + #: def to_python(self, value): + #: return value.split(',') + #: def to_url(self, values): + #: return ','.join(super(ListConverter, self).to_url(value) + #: for value in values) + #: + #: app = Flask(__name__) + #: app.url_map.converters['list'] = ListConverter + self.url_map = self.url_map_class(host_matching=host_matching) + + self.subdomain_matching = subdomain_matching + + # tracks internally if the application already handled at least one + # request. + self._got_first_request = False + + def _check_setup_finished(self, f_name: str) -> None: + if self._got_first_request: + raise AssertionError( + f"The setup method '{f_name}' can no longer be called" + " on the application. It has already handled its first" + " request, any changes will not be applied" + " consistently.\n" + "Make sure all imports, decorators, functions, etc." + " needed to set up the application are done before" + " running it." + ) + + @cached_property + def name(self) -> str: + """The name of the application. This is usually the import name + with the difference that it's guessed from the run file if the + import name is main. This name is used as a display name when + Flask needs the name of the application. It can be set and overridden + to change the value. + + .. versionadded:: 0.8 + """ + if self.import_name == "__main__": + fn: str | None = getattr(sys.modules["__main__"], "__file__", None) + if fn is None: + return "__main__" + return os.path.splitext(os.path.basename(fn))[0] + return self.import_name + + @cached_property + def logger(self) -> logging.Logger: + """A standard Python :class:`~logging.Logger` for the app, with + the same name as :attr:`name`. + + In debug mode, the logger's :attr:`~logging.Logger.level` will + be set to :data:`~logging.DEBUG`. + + If there are no handlers configured, a default handler will be + added. See :doc:`/logging` for more information. + + .. versionchanged:: 1.1.0 + The logger takes the same name as :attr:`name` rather than + hard-coding ``"flask.app"``. + + .. versionchanged:: 1.0.0 + Behavior was simplified. The logger is always named + ``"flask.app"``. The level is only set during configuration, + it doesn't check ``app.debug`` each time. Only one format is + used, not different ones depending on ``app.debug``. No + handlers are removed, and a handler is only added if no + handlers are already configured. + + .. versionadded:: 0.3 + """ + return create_logger(self) + + @cached_property + def jinja_env(self) -> Environment: + """The Jinja environment used to load templates. + + The environment is created the first time this property is + accessed. Changing :attr:`jinja_options` after that will have no + effect. + """ + return self.create_jinja_environment() + + def create_jinja_environment(self) -> Environment: + raise NotImplementedError() + + def make_config(self, instance_relative: bool = False) -> Config: + """Used to create the config attribute by the Flask constructor. + The `instance_relative` parameter is passed in from the constructor + of Flask (there named `instance_relative_config`) and indicates if + the config should be relative to the instance path or the root path + of the application. + + .. versionadded:: 0.8 + """ + root_path = self.root_path + if instance_relative: + root_path = self.instance_path + defaults = dict(self.default_config) + defaults["DEBUG"] = get_debug_flag() + return self.config_class(root_path, defaults) + + def make_aborter(self) -> Aborter: + """Create the object to assign to :attr:`aborter`. That object + is called by :func:`flask.abort` to raise HTTP errors, and can + be called directly as well. + + By default, this creates an instance of :attr:`aborter_class`, + which defaults to :class:`werkzeug.exceptions.Aborter`. + + .. versionadded:: 2.2 + """ + return self.aborter_class() + + def auto_find_instance_path(self) -> str: + """Tries to locate the instance path if it was not provided to the + constructor of the application class. It will basically calculate + the path to a folder named ``instance`` next to your main file or + the package. + + .. versionadded:: 0.8 + """ + prefix, package_path = find_package(self.import_name) + if prefix is None: + return os.path.join(package_path, "instance") + return os.path.join(prefix, "var", f"{self.name}-instance") + + def create_global_jinja_loader(self) -> DispatchingJinjaLoader: + """Creates the loader for the Jinja environment. Can be used to + override just the loader and keeping the rest unchanged. It's + discouraged to override this function. Instead one should override + the :meth:`jinja_loader` function instead. + + The global loader dispatches between the loaders of the application + and the individual blueprints. + + .. versionadded:: 0.7 + """ + return DispatchingJinjaLoader(self) + + def select_jinja_autoescape(self, filename: str | None) -> bool: + """Returns ``True`` if autoescaping should be active for the given + template name. If no template name is given, returns `True`. + + .. versionchanged:: 2.2 + Autoescaping is now enabled by default for ``.svg`` files. + + .. versionadded:: 0.5 + """ + if filename is None: + return True + return filename.endswith((".html", ".htm", ".xml", ".xhtml", ".svg")) + + @property + def debug(self) -> bool: + """Whether debug mode is enabled. When using ``flask run`` to start the + development server, an interactive debugger will be shown for unhandled + exceptions, and the server will be reloaded when code changes. This maps to the + :data:`DEBUG` config key. It may not behave as expected if set late. + + **Do not enable debug mode when deploying in production.** + + Default: ``False`` + """ + return self.config["DEBUG"] # type: ignore[no-any-return] + + @debug.setter + def debug(self, value: bool) -> None: + self.config["DEBUG"] = value + + if self.config["TEMPLATES_AUTO_RELOAD"] is None: + self.jinja_env.auto_reload = value + + @setupmethod + def register_blueprint(self, blueprint: Blueprint, **options: t.Any) -> None: + """Register a :class:`~flask.Blueprint` on the application. Keyword + arguments passed to this method will override the defaults set on the + blueprint. + + Calls the blueprint's :meth:`~flask.Blueprint.register` method after + recording the blueprint in the application's :attr:`blueprints`. + + :param blueprint: The blueprint to register. + :param url_prefix: Blueprint routes will be prefixed with this. + :param subdomain: Blueprint routes will match on this subdomain. + :param url_defaults: Blueprint routes will use these default values for + view arguments. + :param options: Additional keyword arguments are passed to + :class:`~flask.blueprints.BlueprintSetupState`. They can be + accessed in :meth:`~flask.Blueprint.record` callbacks. + + .. versionchanged:: 2.0.1 + The ``name`` option can be used to change the (pre-dotted) + name the blueprint is registered with. This allows the same + blueprint to be registered multiple times with unique names + for ``url_for``. + + .. versionadded:: 0.7 + """ + blueprint.register(self, options) + + def iter_blueprints(self) -> t.ValuesView[Blueprint]: + """Iterates over all blueprints by the order they were registered. + + .. versionadded:: 0.11 + """ + return self.blueprints.values() + + @setupmethod + def add_url_rule( + self, + rule: str, + endpoint: str | None = None, + view_func: ft.RouteCallable | None = None, + provide_automatic_options: bool | None = None, + **options: t.Any, + ) -> None: + if endpoint is None: + endpoint = _endpoint_from_view_func(view_func) # type: ignore + options["endpoint"] = endpoint + methods = options.pop("methods", None) + + # if the methods are not given and the view_func object knows its + # methods we can use that instead. If neither exists, we go with + # a tuple of only ``GET`` as default. + if methods is None: + methods = getattr(view_func, "methods", None) or ("GET",) + if isinstance(methods, str): + raise TypeError( + "Allowed methods must be a list of strings, for" + ' example: @app.route(..., methods=["POST"])' + ) + methods = {item.upper() for item in methods} + + # Methods that should always be added + required_methods: set[str] = set(getattr(view_func, "required_methods", ())) + + # starting with Flask 0.8 the view_func object can disable and + # force-enable the automatic options handling. + if provide_automatic_options is None: + provide_automatic_options = getattr( + view_func, "provide_automatic_options", None + ) + + if provide_automatic_options is None: + if "OPTIONS" not in methods and self.config["PROVIDE_AUTOMATIC_OPTIONS"]: + provide_automatic_options = True + required_methods.add("OPTIONS") + else: + provide_automatic_options = False + + # Add the required methods now. + methods |= required_methods + + rule_obj = self.url_rule_class(rule, methods=methods, **options) + rule_obj.provide_automatic_options = provide_automatic_options # type: ignore[attr-defined] + + self.url_map.add(rule_obj) + if view_func is not None: + old_func = self.view_functions.get(endpoint) + if old_func is not None and old_func != view_func: + raise AssertionError( + "View function mapping is overwriting an existing" + f" endpoint function: {endpoint}" + ) + self.view_functions[endpoint] = view_func + + @setupmethod + def template_filter( + self, name: str | None = None + ) -> t.Callable[[T_template_filter], T_template_filter]: + """A decorator that is used to register custom template filter. + You can specify a name for the filter, otherwise the function + name will be used. Example:: + + @app.template_filter() + def reverse(s): + return s[::-1] + + :param name: the optional name of the filter, otherwise the + function name will be used. + """ + + def decorator(f: T_template_filter) -> T_template_filter: + self.add_template_filter(f, name=name) + return f + + return decorator + + @setupmethod + def add_template_filter( + self, f: ft.TemplateFilterCallable, name: str | None = None + ) -> None: + """Register a custom template filter. Works exactly like the + :meth:`template_filter` decorator. + + :param name: the optional name of the filter, otherwise the + function name will be used. + """ + self.jinja_env.filters[name or f.__name__] = f + + @setupmethod + def template_test( + self, name: str | None = None + ) -> t.Callable[[T_template_test], T_template_test]: + """A decorator that is used to register custom template test. + You can specify a name for the test, otherwise the function + name will be used. Example:: + + @app.template_test() + def is_prime(n): + if n == 2: + return True + for i in range(2, int(math.ceil(math.sqrt(n))) + 1): + if n % i == 0: + return False + return True + + .. versionadded:: 0.10 + + :param name: the optional name of the test, otherwise the + function name will be used. + """ + + def decorator(f: T_template_test) -> T_template_test: + self.add_template_test(f, name=name) + return f + + return decorator + + @setupmethod + def add_template_test( + self, f: ft.TemplateTestCallable, name: str | None = None + ) -> None: + """Register a custom template test. Works exactly like the + :meth:`template_test` decorator. + + .. versionadded:: 0.10 + + :param name: the optional name of the test, otherwise the + function name will be used. + """ + self.jinja_env.tests[name or f.__name__] = f + + @setupmethod + def template_global( + self, name: str | None = None + ) -> t.Callable[[T_template_global], T_template_global]: + """A decorator that is used to register a custom template global function. + You can specify a name for the global function, otherwise the function + name will be used. Example:: + + @app.template_global() + def double(n): + return 2 * n + + .. versionadded:: 0.10 + + :param name: the optional name of the global function, otherwise the + function name will be used. + """ + + def decorator(f: T_template_global) -> T_template_global: + self.add_template_global(f, name=name) + return f + + return decorator + + @setupmethod + def add_template_global( + self, f: ft.TemplateGlobalCallable, name: str | None = None + ) -> None: + """Register a custom template global function. Works exactly like the + :meth:`template_global` decorator. + + .. versionadded:: 0.10 + + :param name: the optional name of the global function, otherwise the + function name will be used. + """ + self.jinja_env.globals[name or f.__name__] = f + + @setupmethod + def teardown_appcontext(self, f: T_teardown) -> T_teardown: + """Registers a function to be called when the application + context is popped. The application context is typically popped + after the request context for each request, at the end of CLI + commands, or after a manually pushed context ends. + + .. code-block:: python + + with app.app_context(): + ... + + When the ``with`` block exits (or ``ctx.pop()`` is called), the + teardown functions are called just before the app context is + made inactive. Since a request context typically also manages an + application context it would also be called when you pop a + request context. + + When a teardown function was called because of an unhandled + exception it will be passed an error object. If an + :meth:`errorhandler` is registered, it will handle the exception + and the teardown will not receive it. + + Teardown functions must avoid raising exceptions. If they + execute code that might fail they must surround that code with a + ``try``/``except`` block and log any errors. + + The return values of teardown functions are ignored. + + .. versionadded:: 0.9 + """ + self.teardown_appcontext_funcs.append(f) + return f + + @setupmethod + def shell_context_processor( + self, f: T_shell_context_processor + ) -> T_shell_context_processor: + """Registers a shell context processor function. + + .. versionadded:: 0.11 + """ + self.shell_context_processors.append(f) + return f + + def _find_error_handler( + self, e: Exception, blueprints: list[str] + ) -> ft.ErrorHandlerCallable | None: + """Return a registered error handler for an exception in this order: + blueprint handler for a specific code, app handler for a specific code, + blueprint handler for an exception class, app handler for an exception + class, or ``None`` if a suitable handler is not found. + """ + exc_class, code = self._get_exc_class_and_code(type(e)) + names = (*blueprints, None) + + for c in (code, None) if code is not None else (None,): + for name in names: + handler_map = self.error_handler_spec[name][c] + + if not handler_map: + continue + + for cls in exc_class.__mro__: + handler = handler_map.get(cls) + + if handler is not None: + return handler + return None + + def trap_http_exception(self, e: Exception) -> bool: + """Checks if an HTTP exception should be trapped or not. By default + this will return ``False`` for all exceptions except for a bad request + key error if ``TRAP_BAD_REQUEST_ERRORS`` is set to ``True``. It + also returns ``True`` if ``TRAP_HTTP_EXCEPTIONS`` is set to ``True``. + + This is called for all HTTP exceptions raised by a view function. + If it returns ``True`` for any exception the error handler for this + exception is not called and it shows up as regular exception in the + traceback. This is helpful for debugging implicitly raised HTTP + exceptions. + + .. versionchanged:: 1.0 + Bad request errors are not trapped by default in debug mode. + + .. versionadded:: 0.8 + """ + if self.config["TRAP_HTTP_EXCEPTIONS"]: + return True + + trap_bad_request = self.config["TRAP_BAD_REQUEST_ERRORS"] + + # if unset, trap key errors in debug mode + if ( + trap_bad_request is None + and self.debug + and isinstance(e, BadRequestKeyError) + ): + return True + + if trap_bad_request: + return isinstance(e, BadRequest) + + return False + + def should_ignore_error(self, error: BaseException | None) -> bool: + """This is called to figure out if an error should be ignored + or not as far as the teardown system is concerned. If this + function returns ``True`` then the teardown handlers will not be + passed the error. + + .. versionadded:: 0.10 + """ + return False + + def redirect(self, location: str, code: int = 302) -> BaseResponse: + """Create a redirect response object. + + This is called by :func:`flask.redirect`, and can be called + directly as well. + + :param location: The URL to redirect to. + :param code: The status code for the redirect. + + .. versionadded:: 2.2 + Moved from ``flask.redirect``, which calls this method. + """ + return _wz_redirect( + location, + code=code, + Response=self.response_class, # type: ignore[arg-type] + ) + + def inject_url_defaults(self, endpoint: str, values: dict[str, t.Any]) -> None: + """Injects the URL defaults for the given endpoint directly into + the values dictionary passed. This is used internally and + automatically called on URL building. + + .. versionadded:: 0.7 + """ + names: t.Iterable[str | None] = (None,) + + # url_for may be called outside a request context, parse the + # passed endpoint instead of using request.blueprints. + if "." in endpoint: + names = chain( + names, reversed(_split_blueprint_path(endpoint.rpartition(".")[0])) + ) + + for name in names: + if name in self.url_default_functions: + for func in self.url_default_functions[name]: + func(endpoint, values) + + def handle_url_build_error( + self, error: BuildError, endpoint: str, values: dict[str, t.Any] + ) -> str: + """Called by :meth:`.url_for` if a + :exc:`~werkzeug.routing.BuildError` was raised. If this returns + a value, it will be returned by ``url_for``, otherwise the error + will be re-raised. + + Each function in :attr:`url_build_error_handlers` is called with + ``error``, ``endpoint`` and ``values``. If a function returns + ``None`` or raises a ``BuildError``, it is skipped. Otherwise, + its return value is returned by ``url_for``. + + :param error: The active ``BuildError`` being handled. + :param endpoint: The endpoint being built. + :param values: The keyword arguments passed to ``url_for``. + """ + for handler in self.url_build_error_handlers: + try: + rv = handler(error, endpoint, values) + except BuildError as e: + # make error available outside except block + error = e + else: + if rv is not None: + return rv + + # Re-raise if called with an active exception, otherwise raise + # the passed in exception. + if error is sys.exc_info()[1]: + raise + + raise error diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask/sansio/blueprints.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask/sansio/blueprints.py new file mode 100644 index 000000000..4f912cca0 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask/sansio/blueprints.py @@ -0,0 +1,632 @@ +from __future__ import annotations + +import os +import typing as t +from collections import defaultdict +from functools import update_wrapper + +from .. import typing as ft +from .scaffold import _endpoint_from_view_func +from .scaffold import _sentinel +from .scaffold import Scaffold +from .scaffold import setupmethod + +if t.TYPE_CHECKING: # pragma: no cover + from .app import App + +DeferredSetupFunction = t.Callable[["BlueprintSetupState"], None] +T_after_request = t.TypeVar("T_after_request", bound=ft.AfterRequestCallable[t.Any]) +T_before_request = t.TypeVar("T_before_request", bound=ft.BeforeRequestCallable) +T_error_handler = t.TypeVar("T_error_handler", bound=ft.ErrorHandlerCallable) +T_teardown = t.TypeVar("T_teardown", bound=ft.TeardownCallable) +T_template_context_processor = t.TypeVar( + "T_template_context_processor", bound=ft.TemplateContextProcessorCallable +) +T_template_filter = t.TypeVar("T_template_filter", bound=ft.TemplateFilterCallable) +T_template_global = t.TypeVar("T_template_global", bound=ft.TemplateGlobalCallable) +T_template_test = t.TypeVar("T_template_test", bound=ft.TemplateTestCallable) +T_url_defaults = t.TypeVar("T_url_defaults", bound=ft.URLDefaultCallable) +T_url_value_preprocessor = t.TypeVar( + "T_url_value_preprocessor", bound=ft.URLValuePreprocessorCallable +) + + +class BlueprintSetupState: + """Temporary holder object for registering a blueprint with the + application. An instance of this class is created by the + :meth:`~flask.Blueprint.make_setup_state` method and later passed + to all register callback functions. + """ + + def __init__( + self, + blueprint: Blueprint, + app: App, + options: t.Any, + first_registration: bool, + ) -> None: + #: a reference to the current application + self.app = app + + #: a reference to the blueprint that created this setup state. + self.blueprint = blueprint + + #: a dictionary with all options that were passed to the + #: :meth:`~flask.Flask.register_blueprint` method. + self.options = options + + #: as blueprints can be registered multiple times with the + #: application and not everything wants to be registered + #: multiple times on it, this attribute can be used to figure + #: out if the blueprint was registered in the past already. + self.first_registration = first_registration + + subdomain = self.options.get("subdomain") + if subdomain is None: + subdomain = self.blueprint.subdomain + + #: The subdomain that the blueprint should be active for, ``None`` + #: otherwise. + self.subdomain = subdomain + + url_prefix = self.options.get("url_prefix") + if url_prefix is None: + url_prefix = self.blueprint.url_prefix + #: The prefix that should be used for all URLs defined on the + #: blueprint. + self.url_prefix = url_prefix + + self.name = self.options.get("name", blueprint.name) + self.name_prefix = self.options.get("name_prefix", "") + + #: A dictionary with URL defaults that is added to each and every + #: URL that was defined with the blueprint. + self.url_defaults = dict(self.blueprint.url_values_defaults) + self.url_defaults.update(self.options.get("url_defaults", ())) + + def add_url_rule( + self, + rule: str, + endpoint: str | None = None, + view_func: ft.RouteCallable | None = None, + **options: t.Any, + ) -> None: + """A helper method to register a rule (and optionally a view function) + to the application. The endpoint is automatically prefixed with the + blueprint's name. + """ + if self.url_prefix is not None: + if rule: + rule = "/".join((self.url_prefix.rstrip("/"), rule.lstrip("/"))) + else: + rule = self.url_prefix + options.setdefault("subdomain", self.subdomain) + if endpoint is None: + endpoint = _endpoint_from_view_func(view_func) # type: ignore + defaults = self.url_defaults + if "defaults" in options: + defaults = dict(defaults, **options.pop("defaults")) + + self.app.add_url_rule( + rule, + f"{self.name_prefix}.{self.name}.{endpoint}".lstrip("."), + view_func, + defaults=defaults, + **options, + ) + + +class Blueprint(Scaffold): + """Represents a blueprint, a collection of routes and other + app-related functions that can be registered on a real application + later. + + A blueprint is an object that allows defining application functions + without requiring an application object ahead of time. It uses the + same decorators as :class:`~flask.Flask`, but defers the need for an + application by recording them for later registration. + + Decorating a function with a blueprint creates a deferred function + that is called with :class:`~flask.blueprints.BlueprintSetupState` + when the blueprint is registered on an application. + + See :doc:`/blueprints` for more information. + + :param name: The name of the blueprint. Will be prepended to each + endpoint name. + :param import_name: The name of the blueprint package, usually + ``__name__``. This helps locate the ``root_path`` for the + blueprint. + :param static_folder: A folder with static files that should be + served by the blueprint's static route. The path is relative to + the blueprint's root path. Blueprint static files are disabled + by default. + :param static_url_path: The url to serve static files from. + Defaults to ``static_folder``. If the blueprint does not have + a ``url_prefix``, the app's static route will take precedence, + and the blueprint's static files won't be accessible. + :param template_folder: A folder with templates that should be added + to the app's template search path. The path is relative to the + blueprint's root path. Blueprint templates are disabled by + default. Blueprint templates have a lower precedence than those + in the app's templates folder. + :param url_prefix: A path to prepend to all of the blueprint's URLs, + to make them distinct from the rest of the app's routes. + :param subdomain: A subdomain that blueprint routes will match on by + default. + :param url_defaults: A dict of default values that blueprint routes + will receive by default. + :param root_path: By default, the blueprint will automatically set + this based on ``import_name``. In certain situations this + automatic detection can fail, so the path can be specified + manually instead. + + .. versionchanged:: 1.1.0 + Blueprints have a ``cli`` group to register nested CLI commands. + The ``cli_group`` parameter controls the name of the group under + the ``flask`` command. + + .. versionadded:: 0.7 + """ + + _got_registered_once = False + + def __init__( + self, + name: str, + import_name: str, + static_folder: str | os.PathLike[str] | None = None, + static_url_path: str | None = None, + template_folder: str | os.PathLike[str] | None = None, + url_prefix: str | None = None, + subdomain: str | None = None, + url_defaults: dict[str, t.Any] | None = None, + root_path: str | None = None, + cli_group: str | None = _sentinel, # type: ignore[assignment] + ): + super().__init__( + import_name=import_name, + static_folder=static_folder, + static_url_path=static_url_path, + template_folder=template_folder, + root_path=root_path, + ) + + if not name: + raise ValueError("'name' may not be empty.") + + if "." in name: + raise ValueError("'name' may not contain a dot '.' character.") + + self.name = name + self.url_prefix = url_prefix + self.subdomain = subdomain + self.deferred_functions: list[DeferredSetupFunction] = [] + + if url_defaults is None: + url_defaults = {} + + self.url_values_defaults = url_defaults + self.cli_group = cli_group + self._blueprints: list[tuple[Blueprint, dict[str, t.Any]]] = [] + + def _check_setup_finished(self, f_name: str) -> None: + if self._got_registered_once: + raise AssertionError( + f"The setup method '{f_name}' can no longer be called on the blueprint" + f" '{self.name}'. It has already been registered at least once, any" + " changes will not be applied consistently.\n" + "Make sure all imports, decorators, functions, etc. needed to set up" + " the blueprint are done before registering it." + ) + + @setupmethod + def record(self, func: DeferredSetupFunction) -> None: + """Registers a function that is called when the blueprint is + registered on the application. This function is called with the + state as argument as returned by the :meth:`make_setup_state` + method. + """ + self.deferred_functions.append(func) + + @setupmethod + def record_once(self, func: DeferredSetupFunction) -> None: + """Works like :meth:`record` but wraps the function in another + function that will ensure the function is only called once. If the + blueprint is registered a second time on the application, the + function passed is not called. + """ + + def wrapper(state: BlueprintSetupState) -> None: + if state.first_registration: + func(state) + + self.record(update_wrapper(wrapper, func)) + + def make_setup_state( + self, app: App, options: dict[str, t.Any], first_registration: bool = False + ) -> BlueprintSetupState: + """Creates an instance of :meth:`~flask.blueprints.BlueprintSetupState` + object that is later passed to the register callback functions. + Subclasses can override this to return a subclass of the setup state. + """ + return BlueprintSetupState(self, app, options, first_registration) + + @setupmethod + def register_blueprint(self, blueprint: Blueprint, **options: t.Any) -> None: + """Register a :class:`~flask.Blueprint` on this blueprint. Keyword + arguments passed to this method will override the defaults set + on the blueprint. + + .. versionchanged:: 2.0.1 + The ``name`` option can be used to change the (pre-dotted) + name the blueprint is registered with. This allows the same + blueprint to be registered multiple times with unique names + for ``url_for``. + + .. versionadded:: 2.0 + """ + if blueprint is self: + raise ValueError("Cannot register a blueprint on itself") + self._blueprints.append((blueprint, options)) + + def register(self, app: App, options: dict[str, t.Any]) -> None: + """Called by :meth:`Flask.register_blueprint` to register all + views and callbacks registered on the blueprint with the + application. Creates a :class:`.BlueprintSetupState` and calls + each :meth:`record` callback with it. + + :param app: The application this blueprint is being registered + with. + :param options: Keyword arguments forwarded from + :meth:`~Flask.register_blueprint`. + + .. versionchanged:: 2.3 + Nested blueprints now correctly apply subdomains. + + .. versionchanged:: 2.1 + Registering the same blueprint with the same name multiple + times is an error. + + .. versionchanged:: 2.0.1 + Nested blueprints are registered with their dotted name. + This allows different blueprints with the same name to be + nested at different locations. + + .. versionchanged:: 2.0.1 + The ``name`` option can be used to change the (pre-dotted) + name the blueprint is registered with. This allows the same + blueprint to be registered multiple times with unique names + for ``url_for``. + """ + name_prefix = options.get("name_prefix", "") + self_name = options.get("name", self.name) + name = f"{name_prefix}.{self_name}".lstrip(".") + + if name in app.blueprints: + bp_desc = "this" if app.blueprints[name] is self else "a different" + existing_at = f" '{name}'" if self_name != name else "" + + raise ValueError( + f"The name '{self_name}' is already registered for" + f" {bp_desc} blueprint{existing_at}. Use 'name=' to" + f" provide a unique name." + ) + + first_bp_registration = not any(bp is self for bp in app.blueprints.values()) + first_name_registration = name not in app.blueprints + + app.blueprints[name] = self + self._got_registered_once = True + state = self.make_setup_state(app, options, first_bp_registration) + + if self.has_static_folder: + state.add_url_rule( + f"{self.static_url_path}/", + view_func=self.send_static_file, # type: ignore[attr-defined] + endpoint="static", + ) + + # Merge blueprint data into parent. + if first_bp_registration or first_name_registration: + self._merge_blueprint_funcs(app, name) + + for deferred in self.deferred_functions: + deferred(state) + + cli_resolved_group = options.get("cli_group", self.cli_group) + + if self.cli.commands: + if cli_resolved_group is None: + app.cli.commands.update(self.cli.commands) + elif cli_resolved_group is _sentinel: + self.cli.name = name + app.cli.add_command(self.cli) + else: + self.cli.name = cli_resolved_group + app.cli.add_command(self.cli) + + for blueprint, bp_options in self._blueprints: + bp_options = bp_options.copy() + bp_url_prefix = bp_options.get("url_prefix") + bp_subdomain = bp_options.get("subdomain") + + if bp_subdomain is None: + bp_subdomain = blueprint.subdomain + + if state.subdomain is not None and bp_subdomain is not None: + bp_options["subdomain"] = bp_subdomain + "." + state.subdomain + elif bp_subdomain is not None: + bp_options["subdomain"] = bp_subdomain + elif state.subdomain is not None: + bp_options["subdomain"] = state.subdomain + + if bp_url_prefix is None: + bp_url_prefix = blueprint.url_prefix + + if state.url_prefix is not None and bp_url_prefix is not None: + bp_options["url_prefix"] = ( + state.url_prefix.rstrip("/") + "/" + bp_url_prefix.lstrip("/") + ) + elif bp_url_prefix is not None: + bp_options["url_prefix"] = bp_url_prefix + elif state.url_prefix is not None: + bp_options["url_prefix"] = state.url_prefix + + bp_options["name_prefix"] = name + blueprint.register(app, bp_options) + + def _merge_blueprint_funcs(self, app: App, name: str) -> None: + def extend( + bp_dict: dict[ft.AppOrBlueprintKey, list[t.Any]], + parent_dict: dict[ft.AppOrBlueprintKey, list[t.Any]], + ) -> None: + for key, values in bp_dict.items(): + key = name if key is None else f"{name}.{key}" + parent_dict[key].extend(values) + + for key, value in self.error_handler_spec.items(): + key = name if key is None else f"{name}.{key}" + value = defaultdict( + dict, + { + code: {exc_class: func for exc_class, func in code_values.items()} + for code, code_values in value.items() + }, + ) + app.error_handler_spec[key] = value + + for endpoint, func in self.view_functions.items(): + app.view_functions[endpoint] = func + + extend(self.before_request_funcs, app.before_request_funcs) + extend(self.after_request_funcs, app.after_request_funcs) + extend( + self.teardown_request_funcs, + app.teardown_request_funcs, + ) + extend(self.url_default_functions, app.url_default_functions) + extend(self.url_value_preprocessors, app.url_value_preprocessors) + extend(self.template_context_processors, app.template_context_processors) + + @setupmethod + def add_url_rule( + self, + rule: str, + endpoint: str | None = None, + view_func: ft.RouteCallable | None = None, + provide_automatic_options: bool | None = None, + **options: t.Any, + ) -> None: + """Register a URL rule with the blueprint. See :meth:`.Flask.add_url_rule` for + full documentation. + + The URL rule is prefixed with the blueprint's URL prefix. The endpoint name, + used with :func:`url_for`, is prefixed with the blueprint's name. + """ + if endpoint and "." in endpoint: + raise ValueError("'endpoint' may not contain a dot '.' character.") + + if view_func and hasattr(view_func, "__name__") and "." in view_func.__name__: + raise ValueError("'view_func' name may not contain a dot '.' character.") + + self.record( + lambda s: s.add_url_rule( + rule, + endpoint, + view_func, + provide_automatic_options=provide_automatic_options, + **options, + ) + ) + + @setupmethod + def app_template_filter( + self, name: str | None = None + ) -> t.Callable[[T_template_filter], T_template_filter]: + """Register a template filter, available in any template rendered by the + application. Equivalent to :meth:`.Flask.template_filter`. + + :param name: the optional name of the filter, otherwise the + function name will be used. + """ + + def decorator(f: T_template_filter) -> T_template_filter: + self.add_app_template_filter(f, name=name) + return f + + return decorator + + @setupmethod + def add_app_template_filter( + self, f: ft.TemplateFilterCallable, name: str | None = None + ) -> None: + """Register a template filter, available in any template rendered by the + application. Works like the :meth:`app_template_filter` decorator. Equivalent to + :meth:`.Flask.add_template_filter`. + + :param name: the optional name of the filter, otherwise the + function name will be used. + """ + + def register_template(state: BlueprintSetupState) -> None: + state.app.jinja_env.filters[name or f.__name__] = f + + self.record_once(register_template) + + @setupmethod + def app_template_test( + self, name: str | None = None + ) -> t.Callable[[T_template_test], T_template_test]: + """Register a template test, available in any template rendered by the + application. Equivalent to :meth:`.Flask.template_test`. + + .. versionadded:: 0.10 + + :param name: the optional name of the test, otherwise the + function name will be used. + """ + + def decorator(f: T_template_test) -> T_template_test: + self.add_app_template_test(f, name=name) + return f + + return decorator + + @setupmethod + def add_app_template_test( + self, f: ft.TemplateTestCallable, name: str | None = None + ) -> None: + """Register a template test, available in any template rendered by the + application. Works like the :meth:`app_template_test` decorator. Equivalent to + :meth:`.Flask.add_template_test`. + + .. versionadded:: 0.10 + + :param name: the optional name of the test, otherwise the + function name will be used. + """ + + def register_template(state: BlueprintSetupState) -> None: + state.app.jinja_env.tests[name or f.__name__] = f + + self.record_once(register_template) + + @setupmethod + def app_template_global( + self, name: str | None = None + ) -> t.Callable[[T_template_global], T_template_global]: + """Register a template global, available in any template rendered by the + application. Equivalent to :meth:`.Flask.template_global`. + + .. versionadded:: 0.10 + + :param name: the optional name of the global, otherwise the + function name will be used. + """ + + def decorator(f: T_template_global) -> T_template_global: + self.add_app_template_global(f, name=name) + return f + + return decorator + + @setupmethod + def add_app_template_global( + self, f: ft.TemplateGlobalCallable, name: str | None = None + ) -> None: + """Register a template global, available in any template rendered by the + application. Works like the :meth:`app_template_global` decorator. Equivalent to + :meth:`.Flask.add_template_global`. + + .. versionadded:: 0.10 + + :param name: the optional name of the global, otherwise the + function name will be used. + """ + + def register_template(state: BlueprintSetupState) -> None: + state.app.jinja_env.globals[name or f.__name__] = f + + self.record_once(register_template) + + @setupmethod + def before_app_request(self, f: T_before_request) -> T_before_request: + """Like :meth:`before_request`, but before every request, not only those handled + by the blueprint. Equivalent to :meth:`.Flask.before_request`. + """ + self.record_once( + lambda s: s.app.before_request_funcs.setdefault(None, []).append(f) + ) + return f + + @setupmethod + def after_app_request(self, f: T_after_request) -> T_after_request: + """Like :meth:`after_request`, but after every request, not only those handled + by the blueprint. Equivalent to :meth:`.Flask.after_request`. + """ + self.record_once( + lambda s: s.app.after_request_funcs.setdefault(None, []).append(f) + ) + return f + + @setupmethod + def teardown_app_request(self, f: T_teardown) -> T_teardown: + """Like :meth:`teardown_request`, but after every request, not only those + handled by the blueprint. Equivalent to :meth:`.Flask.teardown_request`. + """ + self.record_once( + lambda s: s.app.teardown_request_funcs.setdefault(None, []).append(f) + ) + return f + + @setupmethod + def app_context_processor( + self, f: T_template_context_processor + ) -> T_template_context_processor: + """Like :meth:`context_processor`, but for templates rendered by every view, not + only by the blueprint. Equivalent to :meth:`.Flask.context_processor`. + """ + self.record_once( + lambda s: s.app.template_context_processors.setdefault(None, []).append(f) + ) + return f + + @setupmethod + def app_errorhandler( + self, code: type[Exception] | int + ) -> t.Callable[[T_error_handler], T_error_handler]: + """Like :meth:`errorhandler`, but for every request, not only those handled by + the blueprint. Equivalent to :meth:`.Flask.errorhandler`. + """ + + def decorator(f: T_error_handler) -> T_error_handler: + def from_blueprint(state: BlueprintSetupState) -> None: + state.app.errorhandler(code)(f) + + self.record_once(from_blueprint) + return f + + return decorator + + @setupmethod + def app_url_value_preprocessor( + self, f: T_url_value_preprocessor + ) -> T_url_value_preprocessor: + """Like :meth:`url_value_preprocessor`, but for every request, not only those + handled by the blueprint. Equivalent to :meth:`.Flask.url_value_preprocessor`. + """ + self.record_once( + lambda s: s.app.url_value_preprocessors.setdefault(None, []).append(f) + ) + return f + + @setupmethod + def app_url_defaults(self, f: T_url_defaults) -> T_url_defaults: + """Like :meth:`url_defaults`, but for every request, not only those handled by + the blueprint. Equivalent to :meth:`.Flask.url_defaults`. + """ + self.record_once( + lambda s: s.app.url_default_functions.setdefault(None, []).append(f) + ) + return f diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask/sansio/scaffold.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask/sansio/scaffold.py new file mode 100644 index 000000000..0e96f15b7 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask/sansio/scaffold.py @@ -0,0 +1,792 @@ +from __future__ import annotations + +import importlib.util +import os +import pathlib +import sys +import typing as t +from collections import defaultdict +from functools import update_wrapper + +from jinja2 import BaseLoader +from jinja2 import FileSystemLoader +from werkzeug.exceptions import default_exceptions +from werkzeug.exceptions import HTTPException +from werkzeug.utils import cached_property + +from .. import typing as ft +from ..helpers import get_root_path +from ..templating import _default_template_ctx_processor + +if t.TYPE_CHECKING: # pragma: no cover + from click import Group + +# a singleton sentinel value for parameter defaults +_sentinel = object() + +F = t.TypeVar("F", bound=t.Callable[..., t.Any]) +T_after_request = t.TypeVar("T_after_request", bound=ft.AfterRequestCallable[t.Any]) +T_before_request = t.TypeVar("T_before_request", bound=ft.BeforeRequestCallable) +T_error_handler = t.TypeVar("T_error_handler", bound=ft.ErrorHandlerCallable) +T_teardown = t.TypeVar("T_teardown", bound=ft.TeardownCallable) +T_template_context_processor = t.TypeVar( + "T_template_context_processor", bound=ft.TemplateContextProcessorCallable +) +T_url_defaults = t.TypeVar("T_url_defaults", bound=ft.URLDefaultCallable) +T_url_value_preprocessor = t.TypeVar( + "T_url_value_preprocessor", bound=ft.URLValuePreprocessorCallable +) +T_route = t.TypeVar("T_route", bound=ft.RouteCallable) + + +def setupmethod(f: F) -> F: + f_name = f.__name__ + + def wrapper_func(self: Scaffold, *args: t.Any, **kwargs: t.Any) -> t.Any: + self._check_setup_finished(f_name) + return f(self, *args, **kwargs) + + return t.cast(F, update_wrapper(wrapper_func, f)) + + +class Scaffold: + """Common behavior shared between :class:`~flask.Flask` and + :class:`~flask.blueprints.Blueprint`. + + :param import_name: The import name of the module where this object + is defined. Usually :attr:`__name__` should be used. + :param static_folder: Path to a folder of static files to serve. + If this is set, a static route will be added. + :param static_url_path: URL prefix for the static route. + :param template_folder: Path to a folder containing template files. + for rendering. If this is set, a Jinja loader will be added. + :param root_path: The path that static, template, and resource files + are relative to. Typically not set, it is discovered based on + the ``import_name``. + + .. versionadded:: 2.0 + """ + + cli: Group + name: str + _static_folder: str | None = None + _static_url_path: str | None = None + + def __init__( + self, + import_name: str, + static_folder: str | os.PathLike[str] | None = None, + static_url_path: str | None = None, + template_folder: str | os.PathLike[str] | None = None, + root_path: str | None = None, + ): + #: The name of the package or module that this object belongs + #: to. Do not change this once it is set by the constructor. + self.import_name = import_name + + self.static_folder = static_folder + self.static_url_path = static_url_path + + #: The path to the templates folder, relative to + #: :attr:`root_path`, to add to the template loader. ``None`` if + #: templates should not be added. + self.template_folder = template_folder + + if root_path is None: + root_path = get_root_path(self.import_name) + + #: Absolute path to the package on the filesystem. Used to look + #: up resources contained in the package. + self.root_path = root_path + + #: A dictionary mapping endpoint names to view functions. + #: + #: To register a view function, use the :meth:`route` decorator. + #: + #: This data structure is internal. It should not be modified + #: directly and its format may change at any time. + self.view_functions: dict[str, ft.RouteCallable] = {} + + #: A data structure of registered error handlers, in the format + #: ``{scope: {code: {class: handler}}}``. The ``scope`` key is + #: the name of a blueprint the handlers are active for, or + #: ``None`` for all requests. The ``code`` key is the HTTP + #: status code for ``HTTPException``, or ``None`` for + #: other exceptions. The innermost dictionary maps exception + #: classes to handler functions. + #: + #: To register an error handler, use the :meth:`errorhandler` + #: decorator. + #: + #: This data structure is internal. It should not be modified + #: directly and its format may change at any time. + self.error_handler_spec: dict[ + ft.AppOrBlueprintKey, + dict[int | None, dict[type[Exception], ft.ErrorHandlerCallable]], + ] = defaultdict(lambda: defaultdict(dict)) + + #: A data structure of functions to call at the beginning of + #: each request, in the format ``{scope: [functions]}``. The + #: ``scope`` key is the name of a blueprint the functions are + #: active for, or ``None`` for all requests. + #: + #: To register a function, use the :meth:`before_request` + #: decorator. + #: + #: This data structure is internal. It should not be modified + #: directly and its format may change at any time. + self.before_request_funcs: dict[ + ft.AppOrBlueprintKey, list[ft.BeforeRequestCallable] + ] = defaultdict(list) + + #: A data structure of functions to call at the end of each + #: request, in the format ``{scope: [functions]}``. The + #: ``scope`` key is the name of a blueprint the functions are + #: active for, or ``None`` for all requests. + #: + #: To register a function, use the :meth:`after_request` + #: decorator. + #: + #: This data structure is internal. It should not be modified + #: directly and its format may change at any time. + self.after_request_funcs: dict[ + ft.AppOrBlueprintKey, list[ft.AfterRequestCallable[t.Any]] + ] = defaultdict(list) + + #: A data structure of functions to call at the end of each + #: request even if an exception is raised, in the format + #: ``{scope: [functions]}``. The ``scope`` key is the name of a + #: blueprint the functions are active for, or ``None`` for all + #: requests. + #: + #: To register a function, use the :meth:`teardown_request` + #: decorator. + #: + #: This data structure is internal. It should not be modified + #: directly and its format may change at any time. + self.teardown_request_funcs: dict[ + ft.AppOrBlueprintKey, list[ft.TeardownCallable] + ] = defaultdict(list) + + #: A data structure of functions to call to pass extra context + #: values when rendering templates, in the format + #: ``{scope: [functions]}``. The ``scope`` key is the name of a + #: blueprint the functions are active for, or ``None`` for all + #: requests. + #: + #: To register a function, use the :meth:`context_processor` + #: decorator. + #: + #: This data structure is internal. It should not be modified + #: directly and its format may change at any time. + self.template_context_processors: dict[ + ft.AppOrBlueprintKey, list[ft.TemplateContextProcessorCallable] + ] = defaultdict(list, {None: [_default_template_ctx_processor]}) + + #: A data structure of functions to call to modify the keyword + #: arguments passed to the view function, in the format + #: ``{scope: [functions]}``. The ``scope`` key is the name of a + #: blueprint the functions are active for, or ``None`` for all + #: requests. + #: + #: To register a function, use the + #: :meth:`url_value_preprocessor` decorator. + #: + #: This data structure is internal. It should not be modified + #: directly and its format may change at any time. + self.url_value_preprocessors: dict[ + ft.AppOrBlueprintKey, + list[ft.URLValuePreprocessorCallable], + ] = defaultdict(list) + + #: A data structure of functions to call to modify the keyword + #: arguments when generating URLs, in the format + #: ``{scope: [functions]}``. The ``scope`` key is the name of a + #: blueprint the functions are active for, or ``None`` for all + #: requests. + #: + #: To register a function, use the :meth:`url_defaults` + #: decorator. + #: + #: This data structure is internal. It should not be modified + #: directly and its format may change at any time. + self.url_default_functions: dict[ + ft.AppOrBlueprintKey, list[ft.URLDefaultCallable] + ] = defaultdict(list) + + def __repr__(self) -> str: + return f"<{type(self).__name__} {self.name!r}>" + + def _check_setup_finished(self, f_name: str) -> None: + raise NotImplementedError + + @property + def static_folder(self) -> str | None: + """The absolute path to the configured static folder. ``None`` + if no static folder is set. + """ + if self._static_folder is not None: + return os.path.join(self.root_path, self._static_folder) + else: + return None + + @static_folder.setter + def static_folder(self, value: str | os.PathLike[str] | None) -> None: + if value is not None: + value = os.fspath(value).rstrip(r"\/") + + self._static_folder = value + + @property + def has_static_folder(self) -> bool: + """``True`` if :attr:`static_folder` is set. + + .. versionadded:: 0.5 + """ + return self.static_folder is not None + + @property + def static_url_path(self) -> str | None: + """The URL prefix that the static route will be accessible from. + + If it was not configured during init, it is derived from + :attr:`static_folder`. + """ + if self._static_url_path is not None: + return self._static_url_path + + if self.static_folder is not None: + basename = os.path.basename(self.static_folder) + return f"/{basename}".rstrip("/") + + return None + + @static_url_path.setter + def static_url_path(self, value: str | None) -> None: + if value is not None: + value = value.rstrip("/") + + self._static_url_path = value + + @cached_property + def jinja_loader(self) -> BaseLoader | None: + """The Jinja loader for this object's templates. By default this + is a class :class:`jinja2.loaders.FileSystemLoader` to + :attr:`template_folder` if it is set. + + .. versionadded:: 0.5 + """ + if self.template_folder is not None: + return FileSystemLoader(os.path.join(self.root_path, self.template_folder)) + else: + return None + + def _method_route( + self, + method: str, + rule: str, + options: dict[str, t.Any], + ) -> t.Callable[[T_route], T_route]: + if "methods" in options: + raise TypeError("Use the 'route' decorator to use the 'methods' argument.") + + return self.route(rule, methods=[method], **options) + + @setupmethod + def get(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]: + """Shortcut for :meth:`route` with ``methods=["GET"]``. + + .. versionadded:: 2.0 + """ + return self._method_route("GET", rule, options) + + @setupmethod + def post(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]: + """Shortcut for :meth:`route` with ``methods=["POST"]``. + + .. versionadded:: 2.0 + """ + return self._method_route("POST", rule, options) + + @setupmethod + def put(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]: + """Shortcut for :meth:`route` with ``methods=["PUT"]``. + + .. versionadded:: 2.0 + """ + return self._method_route("PUT", rule, options) + + @setupmethod + def delete(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]: + """Shortcut for :meth:`route` with ``methods=["DELETE"]``. + + .. versionadded:: 2.0 + """ + return self._method_route("DELETE", rule, options) + + @setupmethod + def patch(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]: + """Shortcut for :meth:`route` with ``methods=["PATCH"]``. + + .. versionadded:: 2.0 + """ + return self._method_route("PATCH", rule, options) + + @setupmethod + def route(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]: + """Decorate a view function to register it with the given URL + rule and options. Calls :meth:`add_url_rule`, which has more + details about the implementation. + + .. code-block:: python + + @app.route("/") + def index(): + return "Hello, World!" + + See :ref:`url-route-registrations`. + + The endpoint name for the route defaults to the name of the view + function if the ``endpoint`` parameter isn't passed. + + The ``methods`` parameter defaults to ``["GET"]``. ``HEAD`` and + ``OPTIONS`` are added automatically. + + :param rule: The URL rule string. + :param options: Extra options passed to the + :class:`~werkzeug.routing.Rule` object. + """ + + def decorator(f: T_route) -> T_route: + endpoint = options.pop("endpoint", None) + self.add_url_rule(rule, endpoint, f, **options) + return f + + return decorator + + @setupmethod + def add_url_rule( + self, + rule: str, + endpoint: str | None = None, + view_func: ft.RouteCallable | None = None, + provide_automatic_options: bool | None = None, + **options: t.Any, + ) -> None: + """Register a rule for routing incoming requests and building + URLs. The :meth:`route` decorator is a shortcut to call this + with the ``view_func`` argument. These are equivalent: + + .. code-block:: python + + @app.route("/") + def index(): + ... + + .. code-block:: python + + def index(): + ... + + app.add_url_rule("/", view_func=index) + + See :ref:`url-route-registrations`. + + The endpoint name for the route defaults to the name of the view + function if the ``endpoint`` parameter isn't passed. An error + will be raised if a function has already been registered for the + endpoint. + + The ``methods`` parameter defaults to ``["GET"]``. ``HEAD`` is + always added automatically, and ``OPTIONS`` is added + automatically by default. + + ``view_func`` does not necessarily need to be passed, but if the + rule should participate in routing an endpoint name must be + associated with a view function at some point with the + :meth:`endpoint` decorator. + + .. code-block:: python + + app.add_url_rule("/", endpoint="index") + + @app.endpoint("index") + def index(): + ... + + If ``view_func`` has a ``required_methods`` attribute, those + methods are added to the passed and automatic methods. If it + has a ``provide_automatic_methods`` attribute, it is used as the + default if the parameter is not passed. + + :param rule: The URL rule string. + :param endpoint: The endpoint name to associate with the rule + and view function. Used when routing and building URLs. + Defaults to ``view_func.__name__``. + :param view_func: The view function to associate with the + endpoint name. + :param provide_automatic_options: Add the ``OPTIONS`` method and + respond to ``OPTIONS`` requests automatically. + :param options: Extra options passed to the + :class:`~werkzeug.routing.Rule` object. + """ + raise NotImplementedError + + @setupmethod + def endpoint(self, endpoint: str) -> t.Callable[[F], F]: + """Decorate a view function to register it for the given + endpoint. Used if a rule is added without a ``view_func`` with + :meth:`add_url_rule`. + + .. code-block:: python + + app.add_url_rule("/ex", endpoint="example") + + @app.endpoint("example") + def example(): + ... + + :param endpoint: The endpoint name to associate with the view + function. + """ + + def decorator(f: F) -> F: + self.view_functions[endpoint] = f + return f + + return decorator + + @setupmethod + def before_request(self, f: T_before_request) -> T_before_request: + """Register a function to run before each request. + + For example, this can be used to open a database connection, or + to load the logged in user from the session. + + .. code-block:: python + + @app.before_request + def load_user(): + if "user_id" in session: + g.user = db.session.get(session["user_id"]) + + The function will be called without any arguments. If it returns + a non-``None`` value, the value is handled as if it was the + return value from the view, and further request handling is + stopped. + + This is available on both app and blueprint objects. When used on an app, this + executes before every request. When used on a blueprint, this executes before + every request that the blueprint handles. To register with a blueprint and + execute before every request, use :meth:`.Blueprint.before_app_request`. + """ + self.before_request_funcs.setdefault(None, []).append(f) + return f + + @setupmethod + def after_request(self, f: T_after_request) -> T_after_request: + """Register a function to run after each request to this object. + + The function is called with the response object, and must return + a response object. This allows the functions to modify or + replace the response before it is sent. + + If a function raises an exception, any remaining + ``after_request`` functions will not be called. Therefore, this + should not be used for actions that must execute, such as to + close resources. Use :meth:`teardown_request` for that. + + This is available on both app and blueprint objects. When used on an app, this + executes after every request. When used on a blueprint, this executes after + every request that the blueprint handles. To register with a blueprint and + execute after every request, use :meth:`.Blueprint.after_app_request`. + """ + self.after_request_funcs.setdefault(None, []).append(f) + return f + + @setupmethod + def teardown_request(self, f: T_teardown) -> T_teardown: + """Register a function to be called when the request context is + popped. Typically this happens at the end of each request, but + contexts may be pushed manually as well during testing. + + .. code-block:: python + + with app.test_request_context(): + ... + + When the ``with`` block exits (or ``ctx.pop()`` is called), the + teardown functions are called just before the request context is + made inactive. + + When a teardown function was called because of an unhandled + exception it will be passed an error object. If an + :meth:`errorhandler` is registered, it will handle the exception + and the teardown will not receive it. + + Teardown functions must avoid raising exceptions. If they + execute code that might fail they must surround that code with a + ``try``/``except`` block and log any errors. + + The return values of teardown functions are ignored. + + This is available on both app and blueprint objects. When used on an app, this + executes after every request. When used on a blueprint, this executes after + every request that the blueprint handles. To register with a blueprint and + execute after every request, use :meth:`.Blueprint.teardown_app_request`. + """ + self.teardown_request_funcs.setdefault(None, []).append(f) + return f + + @setupmethod + def context_processor( + self, + f: T_template_context_processor, + ) -> T_template_context_processor: + """Registers a template context processor function. These functions run before + rendering a template. The keys of the returned dict are added as variables + available in the template. + + This is available on both app and blueprint objects. When used on an app, this + is called for every rendered template. When used on a blueprint, this is called + for templates rendered from the blueprint's views. To register with a blueprint + and affect every template, use :meth:`.Blueprint.app_context_processor`. + """ + self.template_context_processors[None].append(f) + return f + + @setupmethod + def url_value_preprocessor( + self, + f: T_url_value_preprocessor, + ) -> T_url_value_preprocessor: + """Register a URL value preprocessor function for all view + functions in the application. These functions will be called before the + :meth:`before_request` functions. + + The function can modify the values captured from the matched url before + they are passed to the view. For example, this can be used to pop a + common language code value and place it in ``g`` rather than pass it to + every view. + + The function is passed the endpoint name and values dict. The return + value is ignored. + + This is available on both app and blueprint objects. When used on an app, this + is called for every request. When used on a blueprint, this is called for + requests that the blueprint handles. To register with a blueprint and affect + every request, use :meth:`.Blueprint.app_url_value_preprocessor`. + """ + self.url_value_preprocessors[None].append(f) + return f + + @setupmethod + def url_defaults(self, f: T_url_defaults) -> T_url_defaults: + """Callback function for URL defaults for all view functions of the + application. It's called with the endpoint and values and should + update the values passed in place. + + This is available on both app and blueprint objects. When used on an app, this + is called for every request. When used on a blueprint, this is called for + requests that the blueprint handles. To register with a blueprint and affect + every request, use :meth:`.Blueprint.app_url_defaults`. + """ + self.url_default_functions[None].append(f) + return f + + @setupmethod + def errorhandler( + self, code_or_exception: type[Exception] | int + ) -> t.Callable[[T_error_handler], T_error_handler]: + """Register a function to handle errors by code or exception class. + + A decorator that is used to register a function given an + error code. Example:: + + @app.errorhandler(404) + def page_not_found(error): + return 'This page does not exist', 404 + + You can also register handlers for arbitrary exceptions:: + + @app.errorhandler(DatabaseError) + def special_exception_handler(error): + return 'Database connection failed', 500 + + This is available on both app and blueprint objects. When used on an app, this + can handle errors from every request. When used on a blueprint, this can handle + errors from requests that the blueprint handles. To register with a blueprint + and affect every request, use :meth:`.Blueprint.app_errorhandler`. + + .. versionadded:: 0.7 + Use :meth:`register_error_handler` instead of modifying + :attr:`error_handler_spec` directly, for application wide error + handlers. + + .. versionadded:: 0.7 + One can now additionally also register custom exception types + that do not necessarily have to be a subclass of the + :class:`~werkzeug.exceptions.HTTPException` class. + + :param code_or_exception: the code as integer for the handler, or + an arbitrary exception + """ + + def decorator(f: T_error_handler) -> T_error_handler: + self.register_error_handler(code_or_exception, f) + return f + + return decorator + + @setupmethod + def register_error_handler( + self, + code_or_exception: type[Exception] | int, + f: ft.ErrorHandlerCallable, + ) -> None: + """Alternative error attach function to the :meth:`errorhandler` + decorator that is more straightforward to use for non decorator + usage. + + .. versionadded:: 0.7 + """ + exc_class, code = self._get_exc_class_and_code(code_or_exception) + self.error_handler_spec[None][code][exc_class] = f + + @staticmethod + def _get_exc_class_and_code( + exc_class_or_code: type[Exception] | int, + ) -> tuple[type[Exception], int | None]: + """Get the exception class being handled. For HTTP status codes + or ``HTTPException`` subclasses, return both the exception and + status code. + + :param exc_class_or_code: Any exception class, or an HTTP status + code as an integer. + """ + exc_class: type[Exception] + + if isinstance(exc_class_or_code, int): + try: + exc_class = default_exceptions[exc_class_or_code] + except KeyError: + raise ValueError( + f"'{exc_class_or_code}' is not a recognized HTTP" + " error code. Use a subclass of HTTPException with" + " that code instead." + ) from None + else: + exc_class = exc_class_or_code + + if isinstance(exc_class, Exception): + raise TypeError( + f"{exc_class!r} is an instance, not a class. Handlers" + " can only be registered for Exception classes or HTTP" + " error codes." + ) + + if not issubclass(exc_class, Exception): + raise ValueError( + f"'{exc_class.__name__}' is not a subclass of Exception." + " Handlers can only be registered for Exception classes" + " or HTTP error codes." + ) + + if issubclass(exc_class, HTTPException): + return exc_class, exc_class.code + else: + return exc_class, None + + +def _endpoint_from_view_func(view_func: ft.RouteCallable) -> str: + """Internal helper that returns the default endpoint for a given + function. This always is the function name. + """ + assert view_func is not None, "expected view func if endpoint is not provided." + return view_func.__name__ + + +def _find_package_path(import_name: str) -> str: + """Find the path that contains the package or module.""" + root_mod_name, _, _ = import_name.partition(".") + + try: + root_spec = importlib.util.find_spec(root_mod_name) + + if root_spec is None: + raise ValueError("not found") + except (ImportError, ValueError): + # ImportError: the machinery told us it does not exist + # ValueError: + # - the module name was invalid + # - the module name is __main__ + # - we raised `ValueError` due to `root_spec` being `None` + return os.getcwd() + + if root_spec.submodule_search_locations: + if root_spec.origin is None or root_spec.origin == "namespace": + # namespace package + package_spec = importlib.util.find_spec(import_name) + + if package_spec is not None and package_spec.submodule_search_locations: + # Pick the path in the namespace that contains the submodule. + package_path = pathlib.Path( + os.path.commonpath(package_spec.submodule_search_locations) + ) + search_location = next( + location + for location in root_spec.submodule_search_locations + if package_path.is_relative_to(location) + ) + else: + # Pick the first path. + search_location = root_spec.submodule_search_locations[0] + + return os.path.dirname(search_location) + else: + # package with __init__.py + return os.path.dirname(os.path.dirname(root_spec.origin)) + else: + # module + return os.path.dirname(root_spec.origin) # type: ignore[type-var, return-value] + + +def find_package(import_name: str) -> tuple[str | None, str]: + """Find the prefix that a package is installed under, and the path + that it would be imported from. + + The prefix is the directory containing the standard directory + hierarchy (lib, bin, etc.). If the package is not installed to the + system (:attr:`sys.prefix`) or a virtualenv (``site-packages``), + ``None`` is returned. + + The path is the entry in :attr:`sys.path` that contains the package + for import. If the package is not installed, it's assumed that the + package was imported from the current working directory. + """ + package_path = _find_package_path(import_name) + py_prefix = os.path.abspath(sys.prefix) + + # installed to the system + if pathlib.PurePath(package_path).is_relative_to(py_prefix): + return py_prefix, package_path + + site_parent, site_folder = os.path.split(package_path) + + # installed to a virtualenv + if site_folder.lower() == "site-packages": + parent, folder = os.path.split(site_parent) + + # Windows (prefix/lib/site-packages) + if folder.lower() == "lib": + return parent, package_path + + # Unix (prefix/lib/pythonX.Y/site-packages) + if os.path.basename(parent).lower() == "lib": + return os.path.dirname(parent), package_path + + # something else (prefix/site-packages) + return site_parent, package_path + + # not installed + return None, package_path diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask/sessions.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask/sessions.py new file mode 100644 index 000000000..ad357706f --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask/sessions.py @@ -0,0 +1,385 @@ +from __future__ import annotations + +import collections.abc as c +import hashlib +import typing as t +from collections.abc import MutableMapping +from datetime import datetime +from datetime import timezone + +from itsdangerous import BadSignature +from itsdangerous import URLSafeTimedSerializer +from werkzeug.datastructures import CallbackDict + +from .json.tag import TaggedJSONSerializer + +if t.TYPE_CHECKING: # pragma: no cover + import typing_extensions as te + + from .app import Flask + from .wrappers import Request + from .wrappers import Response + + +class SessionMixin(MutableMapping[str, t.Any]): + """Expands a basic dictionary with session attributes.""" + + @property + def permanent(self) -> bool: + """This reflects the ``'_permanent'`` key in the dict.""" + return self.get("_permanent", False) # type: ignore[no-any-return] + + @permanent.setter + def permanent(self, value: bool) -> None: + self["_permanent"] = bool(value) + + #: Some implementations can detect whether a session is newly + #: created, but that is not guaranteed. Use with caution. The mixin + # default is hard-coded ``False``. + new = False + + #: Some implementations can detect changes to the session and set + #: this when that happens. The mixin default is hard coded to + #: ``True``. + modified = True + + accessed = False + """Indicates if the session was accessed, even if it was not modified. This + is set when the session object is accessed through the request context, + including the global :data:`.session` proxy. A ``Vary: cookie`` header will + be added if this is ``True``. + + .. versionchanged:: 3.1.3 + This is tracked by the request context. + """ + + +class SecureCookieSession(CallbackDict[str, t.Any], SessionMixin): + """Base class for sessions based on signed cookies. + + This session backend will set the :attr:`modified` and + :attr:`accessed` attributes. It cannot reliably track whether a + session is new (vs. empty), so :attr:`new` remains hard coded to + ``False``. + """ + + #: When data is changed, this is set to ``True``. Only the session + #: dictionary itself is tracked; if the session contains mutable + #: data (for example a nested dict) then this must be set to + #: ``True`` manually when modifying that data. The session cookie + #: will only be written to the response if this is ``True``. + modified = False + + def __init__( + self, + initial: c.Mapping[str, t.Any] | None = None, + ) -> None: + def on_update(self: te.Self) -> None: + self.modified = True + + super().__init__(initial, on_update) + + +class NullSession(SecureCookieSession): + """Class used to generate nicer error messages if sessions are not + available. Will still allow read-only access to the empty session + but fail on setting. + """ + + def _fail(self, *args: t.Any, **kwargs: t.Any) -> t.NoReturn: + raise RuntimeError( + "The session is unavailable because no secret " + "key was set. Set the secret_key on the " + "application to something unique and secret." + ) + + __setitem__ = __delitem__ = clear = pop = popitem = update = setdefault = _fail + del _fail + + +class SessionInterface: + """The basic interface you have to implement in order to replace the + default session interface which uses werkzeug's securecookie + implementation. The only methods you have to implement are + :meth:`open_session` and :meth:`save_session`, the others have + useful defaults which you don't need to change. + + The session object returned by the :meth:`open_session` method has to + provide a dictionary like interface plus the properties and methods + from the :class:`SessionMixin`. We recommend just subclassing a dict + and adding that mixin:: + + class Session(dict, SessionMixin): + pass + + If :meth:`open_session` returns ``None`` Flask will call into + :meth:`make_null_session` to create a session that acts as replacement + if the session support cannot work because some requirement is not + fulfilled. The default :class:`NullSession` class that is created + will complain that the secret key was not set. + + To replace the session interface on an application all you have to do + is to assign :attr:`flask.Flask.session_interface`:: + + app = Flask(__name__) + app.session_interface = MySessionInterface() + + Multiple requests with the same session may be sent and handled + concurrently. When implementing a new session interface, consider + whether reads or writes to the backing store must be synchronized. + There is no guarantee on the order in which the session for each + request is opened or saved, it will occur in the order that requests + begin and end processing. + + .. versionadded:: 0.8 + """ + + #: :meth:`make_null_session` will look here for the class that should + #: be created when a null session is requested. Likewise the + #: :meth:`is_null_session` method will perform a typecheck against + #: this type. + null_session_class = NullSession + + #: A flag that indicates if the session interface is pickle based. + #: This can be used by Flask extensions to make a decision in regards + #: to how to deal with the session object. + #: + #: .. versionadded:: 0.10 + pickle_based = False + + def make_null_session(self, app: Flask) -> NullSession: + """Creates a null session which acts as a replacement object if the + real session support could not be loaded due to a configuration + error. This mainly aids the user experience because the job of the + null session is to still support lookup without complaining but + modifications are answered with a helpful error message of what + failed. + + This creates an instance of :attr:`null_session_class` by default. + """ + return self.null_session_class() + + def is_null_session(self, obj: object) -> bool: + """Checks if a given object is a null session. Null sessions are + not asked to be saved. + + This checks if the object is an instance of :attr:`null_session_class` + by default. + """ + return isinstance(obj, self.null_session_class) + + def get_cookie_name(self, app: Flask) -> str: + """The name of the session cookie. Uses``app.config["SESSION_COOKIE_NAME"]``.""" + return app.config["SESSION_COOKIE_NAME"] # type: ignore[no-any-return] + + def get_cookie_domain(self, app: Flask) -> str | None: + """The value of the ``Domain`` parameter on the session cookie. If not set, + browsers will only send the cookie to the exact domain it was set from. + Otherwise, they will send it to any subdomain of the given value as well. + + Uses the :data:`SESSION_COOKIE_DOMAIN` config. + + .. versionchanged:: 2.3 + Not set by default, does not fall back to ``SERVER_NAME``. + """ + return app.config["SESSION_COOKIE_DOMAIN"] # type: ignore[no-any-return] + + def get_cookie_path(self, app: Flask) -> str: + """Returns the path for which the cookie should be valid. The + default implementation uses the value from the ``SESSION_COOKIE_PATH`` + config var if it's set, and falls back to ``APPLICATION_ROOT`` or + uses ``/`` if it's ``None``. + """ + return app.config["SESSION_COOKIE_PATH"] or app.config["APPLICATION_ROOT"] # type: ignore[no-any-return] + + def get_cookie_httponly(self, app: Flask) -> bool: + """Returns True if the session cookie should be httponly. This + currently just returns the value of the ``SESSION_COOKIE_HTTPONLY`` + config var. + """ + return app.config["SESSION_COOKIE_HTTPONLY"] # type: ignore[no-any-return] + + def get_cookie_secure(self, app: Flask) -> bool: + """Returns True if the cookie should be secure. This currently + just returns the value of the ``SESSION_COOKIE_SECURE`` setting. + """ + return app.config["SESSION_COOKIE_SECURE"] # type: ignore[no-any-return] + + def get_cookie_samesite(self, app: Flask) -> str | None: + """Return ``'Strict'`` or ``'Lax'`` if the cookie should use the + ``SameSite`` attribute. This currently just returns the value of + the :data:`SESSION_COOKIE_SAMESITE` setting. + """ + return app.config["SESSION_COOKIE_SAMESITE"] # type: ignore[no-any-return] + + def get_cookie_partitioned(self, app: Flask) -> bool: + """Returns True if the cookie should be partitioned. By default, uses + the value of :data:`SESSION_COOKIE_PARTITIONED`. + + .. versionadded:: 3.1 + """ + return app.config["SESSION_COOKIE_PARTITIONED"] # type: ignore[no-any-return] + + def get_expiration_time(self, app: Flask, session: SessionMixin) -> datetime | None: + """A helper method that returns an expiration date for the session + or ``None`` if the session is linked to the browser session. The + default implementation returns now + the permanent session + lifetime configured on the application. + """ + if session.permanent: + return datetime.now(timezone.utc) + app.permanent_session_lifetime + return None + + def should_set_cookie(self, app: Flask, session: SessionMixin) -> bool: + """Used by session backends to determine if a ``Set-Cookie`` header + should be set for this session cookie for this response. If the session + has been modified, the cookie is set. If the session is permanent and + the ``SESSION_REFRESH_EACH_REQUEST`` config is true, the cookie is + always set. + + This check is usually skipped if the session was deleted. + + .. versionadded:: 0.11 + """ + + return session.modified or ( + session.permanent and app.config["SESSION_REFRESH_EACH_REQUEST"] + ) + + def open_session(self, app: Flask, request: Request) -> SessionMixin | None: + """This is called at the beginning of each request, after + pushing the request context, before matching the URL. + + This must return an object which implements a dictionary-like + interface as well as the :class:`SessionMixin` interface. + + This will return ``None`` to indicate that loading failed in + some way that is not immediately an error. The request + context will fall back to using :meth:`make_null_session` + in this case. + """ + raise NotImplementedError() + + def save_session( + self, app: Flask, session: SessionMixin, response: Response + ) -> None: + """This is called at the end of each request, after generating + a response, before removing the request context. It is skipped + if :meth:`is_null_session` returns ``True``. + """ + raise NotImplementedError() + + +session_json_serializer = TaggedJSONSerializer() + + +def _lazy_sha1(string: bytes = b"") -> t.Any: + """Don't access ``hashlib.sha1`` until runtime. FIPS builds may not include + SHA-1, in which case the import and use as a default would fail before the + developer can configure something else. + """ + return hashlib.sha1(string) + + +class SecureCookieSessionInterface(SessionInterface): + """The default session interface that stores sessions in signed cookies + through the :mod:`itsdangerous` module. + """ + + #: the salt that should be applied on top of the secret key for the + #: signing of cookie based sessions. + salt = "cookie-session" + #: the hash function to use for the signature. The default is sha1 + digest_method = staticmethod(_lazy_sha1) + #: the name of the itsdangerous supported key derivation. The default + #: is hmac. + key_derivation = "hmac" + #: A python serializer for the payload. The default is a compact + #: JSON derived serializer with support for some extra Python types + #: such as datetime objects or tuples. + serializer = session_json_serializer + session_class = SecureCookieSession + + def get_signing_serializer(self, app: Flask) -> URLSafeTimedSerializer | None: + if not app.secret_key: + return None + + keys: list[str | bytes] = [] + + if fallbacks := app.config["SECRET_KEY_FALLBACKS"]: + keys.extend(fallbacks) + + keys.append(app.secret_key) # itsdangerous expects current key at top + return URLSafeTimedSerializer( + keys, # type: ignore[arg-type] + salt=self.salt, + serializer=self.serializer, + signer_kwargs={ + "key_derivation": self.key_derivation, + "digest_method": self.digest_method, + }, + ) + + def open_session(self, app: Flask, request: Request) -> SecureCookieSession | None: + s = self.get_signing_serializer(app) + if s is None: + return None + val = request.cookies.get(self.get_cookie_name(app)) + if not val: + return self.session_class() + max_age = int(app.permanent_session_lifetime.total_seconds()) + try: + data = s.loads(val, max_age=max_age) + return self.session_class(data) + except BadSignature: + return self.session_class() + + def save_session( + self, app: Flask, session: SessionMixin, response: Response + ) -> None: + name = self.get_cookie_name(app) + domain = self.get_cookie_domain(app) + path = self.get_cookie_path(app) + secure = self.get_cookie_secure(app) + partitioned = self.get_cookie_partitioned(app) + samesite = self.get_cookie_samesite(app) + httponly = self.get_cookie_httponly(app) + + # Add a "Vary: Cookie" header if the session was accessed at all. + if session.accessed: + response.vary.add("Cookie") + + # If the session is modified to be empty, remove the cookie. + # If the session is empty, return without setting the cookie. + if not session: + if session.modified: + response.delete_cookie( + name, + domain=domain, + path=path, + secure=secure, + partitioned=partitioned, + samesite=samesite, + httponly=httponly, + ) + response.vary.add("Cookie") + + return + + if not self.should_set_cookie(app, session): + return + + expires = self.get_expiration_time(app, session) + val = self.get_signing_serializer(app).dumps(dict(session)) # type: ignore[union-attr] + response.set_cookie( + name, + val, + expires=expires, + httponly=httponly, + domain=domain, + path=path, + secure=secure, + partitioned=partitioned, + samesite=samesite, + ) + response.vary.add("Cookie") diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask/signals.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask/signals.py new file mode 100644 index 000000000..444fda998 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask/signals.py @@ -0,0 +1,17 @@ +from __future__ import annotations + +from blinker import Namespace + +# This namespace is only for signals provided by Flask itself. +_signals = Namespace() + +template_rendered = _signals.signal("template-rendered") +before_render_template = _signals.signal("before-render-template") +request_started = _signals.signal("request-started") +request_finished = _signals.signal("request-finished") +request_tearing_down = _signals.signal("request-tearing-down") +got_request_exception = _signals.signal("got-request-exception") +appcontext_tearing_down = _signals.signal("appcontext-tearing-down") +appcontext_pushed = _signals.signal("appcontext-pushed") +appcontext_popped = _signals.signal("appcontext-popped") +message_flashed = _signals.signal("message-flashed") diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask/templating.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask/templating.py new file mode 100644 index 000000000..c5fb5b990 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask/templating.py @@ -0,0 +1,220 @@ +from __future__ import annotations + +import typing as t + +from jinja2 import BaseLoader +from jinja2 import Environment as BaseEnvironment +from jinja2 import Template +from jinja2 import TemplateNotFound + +from .globals import _cv_app +from .globals import _cv_request +from .globals import current_app +from .globals import request +from .helpers import stream_with_context +from .signals import before_render_template +from .signals import template_rendered + +if t.TYPE_CHECKING: # pragma: no cover + from .app import Flask + from .sansio.app import App + from .sansio.scaffold import Scaffold + + +def _default_template_ctx_processor() -> dict[str, t.Any]: + """Default template context processor. Replaces the ``request`` and ``g`` + proxies with their concrete objects for faster access. + """ + appctx = _cv_app.get(None) + reqctx = _cv_request.get(None) + rv: dict[str, t.Any] = {} + if appctx is not None: + rv["g"] = appctx.g + if reqctx is not None: + rv["request"] = reqctx.request + # The session proxy cannot be replaced, accessing it gets + # RequestContext.session, which sets session.accessed. + return rv + + +class Environment(BaseEnvironment): + """Works like a regular Jinja environment but has some additional + knowledge of how Flask's blueprint works so that it can prepend the + name of the blueprint to referenced templates if necessary. + """ + + def __init__(self, app: App, **options: t.Any) -> None: + if "loader" not in options: + options["loader"] = app.create_global_jinja_loader() + BaseEnvironment.__init__(self, **options) + self.app = app + + +class DispatchingJinjaLoader(BaseLoader): + """A loader that looks for templates in the application and all + the blueprint folders. + """ + + def __init__(self, app: App) -> None: + self.app = app + + def get_source( + self, environment: BaseEnvironment, template: str + ) -> tuple[str, str | None, t.Callable[[], bool] | None]: + if self.app.config["EXPLAIN_TEMPLATE_LOADING"]: + return self._get_source_explained(environment, template) + return self._get_source_fast(environment, template) + + def _get_source_explained( + self, environment: BaseEnvironment, template: str + ) -> tuple[str, str | None, t.Callable[[], bool] | None]: + attempts = [] + rv: tuple[str, str | None, t.Callable[[], bool] | None] | None + trv: None | (tuple[str, str | None, t.Callable[[], bool] | None]) = None + + for srcobj, loader in self._iter_loaders(template): + try: + rv = loader.get_source(environment, template) + if trv is None: + trv = rv + except TemplateNotFound: + rv = None + attempts.append((loader, srcobj, rv)) + + from .debughelpers import explain_template_loading_attempts + + explain_template_loading_attempts(self.app, template, attempts) + + if trv is not None: + return trv + raise TemplateNotFound(template) + + def _get_source_fast( + self, environment: BaseEnvironment, template: str + ) -> tuple[str, str | None, t.Callable[[], bool] | None]: + for _srcobj, loader in self._iter_loaders(template): + try: + return loader.get_source(environment, template) + except TemplateNotFound: + continue + raise TemplateNotFound(template) + + def _iter_loaders(self, template: str) -> t.Iterator[tuple[Scaffold, BaseLoader]]: + loader = self.app.jinja_loader + if loader is not None: + yield self.app, loader + + for blueprint in self.app.iter_blueprints(): + loader = blueprint.jinja_loader + if loader is not None: + yield blueprint, loader + + def list_templates(self) -> list[str]: + result = set() + loader = self.app.jinja_loader + if loader is not None: + result.update(loader.list_templates()) + + for blueprint in self.app.iter_blueprints(): + loader = blueprint.jinja_loader + if loader is not None: + for template in loader.list_templates(): + result.add(template) + + return list(result) + + +def _render(app: Flask, template: Template, context: dict[str, t.Any]) -> str: + app.update_template_context(context) + before_render_template.send( + app, _async_wrapper=app.ensure_sync, template=template, context=context + ) + rv = template.render(context) + template_rendered.send( + app, _async_wrapper=app.ensure_sync, template=template, context=context + ) + return rv + + +def render_template( + template_name_or_list: str | Template | list[str | Template], + **context: t.Any, +) -> str: + """Render a template by name with the given context. + + :param template_name_or_list: The name of the template to render. If + a list is given, the first name to exist will be rendered. + :param context: The variables to make available in the template. + """ + app = current_app._get_current_object() # type: ignore[attr-defined] + template = app.jinja_env.get_or_select_template(template_name_or_list) + return _render(app, template, context) + + +def render_template_string(source: str, **context: t.Any) -> str: + """Render a template from the given source string with the given + context. + + :param source: The source code of the template to render. + :param context: The variables to make available in the template. + """ + app = current_app._get_current_object() # type: ignore[attr-defined] + template = app.jinja_env.from_string(source) + return _render(app, template, context) + + +def _stream( + app: Flask, template: Template, context: dict[str, t.Any] +) -> t.Iterator[str]: + app.update_template_context(context) + before_render_template.send( + app, _async_wrapper=app.ensure_sync, template=template, context=context + ) + + def generate() -> t.Iterator[str]: + yield from template.generate(context) + template_rendered.send( + app, _async_wrapper=app.ensure_sync, template=template, context=context + ) + + rv = generate() + + # If a request context is active, keep it while generating. + if request: + rv = stream_with_context(rv) + + return rv + + +def stream_template( + template_name_or_list: str | Template | list[str | Template], + **context: t.Any, +) -> t.Iterator[str]: + """Render a template by name with the given context as a stream. + This returns an iterator of strings, which can be used as a + streaming response from a view. + + :param template_name_or_list: The name of the template to render. If + a list is given, the first name to exist will be rendered. + :param context: The variables to make available in the template. + + .. versionadded:: 2.2 + """ + app = current_app._get_current_object() # type: ignore[attr-defined] + template = app.jinja_env.get_or_select_template(template_name_or_list) + return _stream(app, template, context) + + +def stream_template_string(source: str, **context: t.Any) -> t.Iterator[str]: + """Render a template from the given source string with the given + context as a stream. This returns an iterator of strings, which can + be used as a streaming response from a view. + + :param source: The source code of the template to render. + :param context: The variables to make available in the template. + + .. versionadded:: 2.2 + """ + app = current_app._get_current_object() # type: ignore[attr-defined] + template = app.jinja_env.from_string(source) + return _stream(app, template, context) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask/testing.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask/testing.py new file mode 100644 index 000000000..55eb12fe7 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask/testing.py @@ -0,0 +1,298 @@ +from __future__ import annotations + +import importlib.metadata +import typing as t +from contextlib import contextmanager +from contextlib import ExitStack +from copy import copy +from types import TracebackType +from urllib.parse import urlsplit + +import werkzeug.test +from click.testing import CliRunner +from click.testing import Result +from werkzeug.test import Client +from werkzeug.wrappers import Request as BaseRequest + +from .cli import ScriptInfo +from .sessions import SessionMixin + +if t.TYPE_CHECKING: # pragma: no cover + from _typeshed.wsgi import WSGIEnvironment + from werkzeug.test import TestResponse + + from .app import Flask + + +class EnvironBuilder(werkzeug.test.EnvironBuilder): + """An :class:`~werkzeug.test.EnvironBuilder`, that takes defaults from the + application. + + :param app: The Flask application to configure the environment from. + :param path: URL path being requested. + :param base_url: Base URL where the app is being served, which + ``path`` is relative to. If not given, built from + :data:`PREFERRED_URL_SCHEME`, ``subdomain``, + :data:`SERVER_NAME`, and :data:`APPLICATION_ROOT`. + :param subdomain: Subdomain name to append to :data:`SERVER_NAME`. + :param url_scheme: Scheme to use instead of + :data:`PREFERRED_URL_SCHEME`. + :param json: If given, this is serialized as JSON and passed as + ``data``. Also defaults ``content_type`` to + ``application/json``. + :param args: other positional arguments passed to + :class:`~werkzeug.test.EnvironBuilder`. + :param kwargs: other keyword arguments passed to + :class:`~werkzeug.test.EnvironBuilder`. + """ + + def __init__( + self, + app: Flask, + path: str = "/", + base_url: str | None = None, + subdomain: str | None = None, + url_scheme: str | None = None, + *args: t.Any, + **kwargs: t.Any, + ) -> None: + assert not (base_url or subdomain or url_scheme) or ( + base_url is not None + ) != bool(subdomain or url_scheme), ( + 'Cannot pass "subdomain" or "url_scheme" with "base_url".' + ) + + if base_url is None: + http_host = app.config.get("SERVER_NAME") or "localhost" + app_root = app.config["APPLICATION_ROOT"] + + if subdomain: + http_host = f"{subdomain}.{http_host}" + + if url_scheme is None: + url_scheme = app.config["PREFERRED_URL_SCHEME"] + + url = urlsplit(path) + base_url = ( + f"{url.scheme or url_scheme}://{url.netloc or http_host}" + f"/{app_root.lstrip('/')}" + ) + path = url.path + + if url.query: + path = f"{path}?{url.query}" + + self.app = app + super().__init__(path, base_url, *args, **kwargs) + + def json_dumps(self, obj: t.Any, **kwargs: t.Any) -> str: + """Serialize ``obj`` to a JSON-formatted string. + + The serialization will be configured according to the config associated + with this EnvironBuilder's ``app``. + """ + return self.app.json.dumps(obj, **kwargs) + + +_werkzeug_version = "" + + +def _get_werkzeug_version() -> str: + global _werkzeug_version + + if not _werkzeug_version: + _werkzeug_version = importlib.metadata.version("werkzeug") + + return _werkzeug_version + + +class FlaskClient(Client): + """Works like a regular Werkzeug test client but has knowledge about + Flask's contexts to defer the cleanup of the request context until + the end of a ``with`` block. For general information about how to + use this class refer to :class:`werkzeug.test.Client`. + + .. versionchanged:: 0.12 + `app.test_client()` includes preset default environment, which can be + set after instantiation of the `app.test_client()` object in + `client.environ_base`. + + Basic usage is outlined in the :doc:`/testing` chapter. + """ + + application: Flask + + def __init__(self, *args: t.Any, **kwargs: t.Any) -> None: + super().__init__(*args, **kwargs) + self.preserve_context = False + self._new_contexts: list[t.ContextManager[t.Any]] = [] + self._context_stack = ExitStack() + self.environ_base = { + "REMOTE_ADDR": "127.0.0.1", + "HTTP_USER_AGENT": f"Werkzeug/{_get_werkzeug_version()}", + } + + @contextmanager + def session_transaction( + self, *args: t.Any, **kwargs: t.Any + ) -> t.Iterator[SessionMixin]: + """When used in combination with a ``with`` statement this opens a + session transaction. This can be used to modify the session that + the test client uses. Once the ``with`` block is left the session is + stored back. + + :: + + with client.session_transaction() as session: + session['value'] = 42 + + Internally this is implemented by going through a temporary test + request context and since session handling could depend on + request variables this function accepts the same arguments as + :meth:`~flask.Flask.test_request_context` which are directly + passed through. + """ + if self._cookies is None: + raise TypeError( + "Cookies are disabled. Create a client with 'use_cookies=True'." + ) + + app = self.application + ctx = app.test_request_context(*args, **kwargs) + self._add_cookies_to_wsgi(ctx.request.environ) + + with ctx: + sess = app.session_interface.open_session(app, ctx.request) + + if sess is None: + raise RuntimeError("Session backend did not open a session.") + + yield sess + resp = app.response_class() + + if app.session_interface.is_null_session(sess): + return + + with ctx: + app.session_interface.save_session(app, sess, resp) + + self._update_cookies_from_response( + ctx.request.host.partition(":")[0], + ctx.request.path, + resp.headers.getlist("Set-Cookie"), + ) + + def _copy_environ(self, other: WSGIEnvironment) -> WSGIEnvironment: + out = {**self.environ_base, **other} + + if self.preserve_context: + out["werkzeug.debug.preserve_context"] = self._new_contexts.append + + return out + + def _request_from_builder_args( + self, args: tuple[t.Any, ...], kwargs: dict[str, t.Any] + ) -> BaseRequest: + kwargs["environ_base"] = self._copy_environ(kwargs.get("environ_base", {})) + builder = EnvironBuilder(self.application, *args, **kwargs) + + try: + return builder.get_request() + finally: + builder.close() + + def open( + self, + *args: t.Any, + buffered: bool = False, + follow_redirects: bool = False, + **kwargs: t.Any, + ) -> TestResponse: + if args and isinstance( + args[0], (werkzeug.test.EnvironBuilder, dict, BaseRequest) + ): + if isinstance(args[0], werkzeug.test.EnvironBuilder): + builder = copy(args[0]) + builder.environ_base = self._copy_environ(builder.environ_base or {}) # type: ignore[arg-type] + request = builder.get_request() + elif isinstance(args[0], dict): + request = EnvironBuilder.from_environ( + args[0], app=self.application, environ_base=self._copy_environ({}) + ).get_request() + else: + # isinstance(args[0], BaseRequest) + request = copy(args[0]) + request.environ = self._copy_environ(request.environ) + else: + # request is None + request = self._request_from_builder_args(args, kwargs) + + # Pop any previously preserved contexts. This prevents contexts + # from being preserved across redirects or multiple requests + # within a single block. + self._context_stack.close() + + response = super().open( + request, + buffered=buffered, + follow_redirects=follow_redirects, + ) + response.json_module = self.application.json # type: ignore[assignment] + + # Re-push contexts that were preserved during the request. + for cm in self._new_contexts: + self._context_stack.enter_context(cm) + + self._new_contexts.clear() + return response + + def __enter__(self) -> FlaskClient: + if self.preserve_context: + raise RuntimeError("Cannot nest client invocations") + self.preserve_context = True + return self + + def __exit__( + self, + exc_type: type | None, + exc_value: BaseException | None, + tb: TracebackType | None, + ) -> None: + self.preserve_context = False + self._context_stack.close() + + +class FlaskCliRunner(CliRunner): + """A :class:`~click.testing.CliRunner` for testing a Flask app's + CLI commands. Typically created using + :meth:`~flask.Flask.test_cli_runner`. See :ref:`testing-cli`. + """ + + def __init__(self, app: Flask, **kwargs: t.Any) -> None: + self.app = app + super().__init__(**kwargs) + + def invoke( # type: ignore + self, cli: t.Any = None, args: t.Any = None, **kwargs: t.Any + ) -> Result: + """Invokes a CLI command in an isolated environment. See + :meth:`CliRunner.invoke ` for + full method documentation. See :ref:`testing-cli` for examples. + + If the ``obj`` argument is not given, passes an instance of + :class:`~flask.cli.ScriptInfo` that knows how to load the Flask + app being tested. + + :param cli: Command object to invoke. Default is the app's + :attr:`~flask.app.Flask.cli` group. + :param args: List of strings to invoke the command with. + + :return: a :class:`~click.testing.Result` object. + """ + if cli is None: + cli = self.app.cli + + if "obj" not in kwargs: + kwargs["obj"] = ScriptInfo(create_app=lambda: self.app) + + return super().invoke(cli, args, **kwargs) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask/typing.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask/typing.py new file mode 100644 index 000000000..6b70c4097 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask/typing.py @@ -0,0 +1,93 @@ +from __future__ import annotations + +import collections.abc as cabc +import typing as t + +if t.TYPE_CHECKING: # pragma: no cover + from _typeshed.wsgi import WSGIApplication # noqa: F401 + from werkzeug.datastructures import Headers # noqa: F401 + from werkzeug.sansio.response import Response # noqa: F401 + +# The possible types that are directly convertible or are a Response object. +ResponseValue = t.Union[ + "Response", + str, + bytes, + list[t.Any], + # Only dict is actually accepted, but Mapping allows for TypedDict. + t.Mapping[str, t.Any], + t.Iterator[str], + t.Iterator[bytes], + cabc.AsyncIterable[str], # for Quart, until App is generic. + cabc.AsyncIterable[bytes], +] + +# the possible types for an individual HTTP header +# This should be a Union, but mypy doesn't pass unless it's a TypeVar. +HeaderValue = t.Union[str, list[str], tuple[str, ...]] + +# the possible types for HTTP headers +HeadersValue = t.Union[ + "Headers", + t.Mapping[str, HeaderValue], + t.Sequence[tuple[str, HeaderValue]], +] + +# The possible types returned by a route function. +ResponseReturnValue = t.Union[ + ResponseValue, + tuple[ResponseValue, HeadersValue], + tuple[ResponseValue, int], + tuple[ResponseValue, int, HeadersValue], + "WSGIApplication", +] + +# Allow any subclass of werkzeug.Response, such as the one from Flask, +# as a callback argument. Using werkzeug.Response directly makes a +# callback annotated with flask.Response fail type checking. +ResponseClass = t.TypeVar("ResponseClass", bound="Response") + +AppOrBlueprintKey = t.Optional[str] # The App key is None, whereas blueprints are named +AfterRequestCallable = t.Union[ + t.Callable[[ResponseClass], ResponseClass], + t.Callable[[ResponseClass], t.Awaitable[ResponseClass]], +] +BeforeFirstRequestCallable = t.Union[ + t.Callable[[], None], t.Callable[[], t.Awaitable[None]] +] +BeforeRequestCallable = t.Union[ + t.Callable[[], t.Optional[ResponseReturnValue]], + t.Callable[[], t.Awaitable[t.Optional[ResponseReturnValue]]], +] +ShellContextProcessorCallable = t.Callable[[], dict[str, t.Any]] +TeardownCallable = t.Union[ + t.Callable[[t.Optional[BaseException]], None], + t.Callable[[t.Optional[BaseException]], t.Awaitable[None]], +] +TemplateContextProcessorCallable = t.Union[ + t.Callable[[], dict[str, t.Any]], + t.Callable[[], t.Awaitable[dict[str, t.Any]]], +] +TemplateFilterCallable = t.Callable[..., t.Any] +TemplateGlobalCallable = t.Callable[..., t.Any] +TemplateTestCallable = t.Callable[..., bool] +URLDefaultCallable = t.Callable[[str, dict[str, t.Any]], None] +URLValuePreprocessorCallable = t.Callable[ + [t.Optional[str], t.Optional[dict[str, t.Any]]], None +] + +# This should take Exception, but that either breaks typing the argument +# with a specific exception, or decorating multiple times with different +# exceptions (and using a union type on the argument). +# https://github.com/pallets/flask/issues/4095 +# https://github.com/pallets/flask/issues/4295 +# https://github.com/pallets/flask/issues/4297 +ErrorHandlerCallable = t.Union[ + t.Callable[[t.Any], ResponseReturnValue], + t.Callable[[t.Any], t.Awaitable[ResponseReturnValue]], +] + +RouteCallable = t.Union[ + t.Callable[..., ResponseReturnValue], + t.Callable[..., t.Awaitable[ResponseReturnValue]], +] diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask/views.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask/views.py new file mode 100644 index 000000000..53fe976dc --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask/views.py @@ -0,0 +1,191 @@ +from __future__ import annotations + +import typing as t + +from . import typing as ft +from .globals import current_app +from .globals import request + +F = t.TypeVar("F", bound=t.Callable[..., t.Any]) + +http_method_funcs = frozenset( + ["get", "post", "head", "options", "delete", "put", "trace", "patch"] +) + + +class View: + """Subclass this class and override :meth:`dispatch_request` to + create a generic class-based view. Call :meth:`as_view` to create a + view function that creates an instance of the class with the given + arguments and calls its ``dispatch_request`` method with any URL + variables. + + See :doc:`views` for a detailed guide. + + .. code-block:: python + + class Hello(View): + init_every_request = False + + def dispatch_request(self, name): + return f"Hello, {name}!" + + app.add_url_rule( + "/hello/", view_func=Hello.as_view("hello") + ) + + Set :attr:`methods` on the class to change what methods the view + accepts. + + Set :attr:`decorators` on the class to apply a list of decorators to + the generated view function. Decorators applied to the class itself + will not be applied to the generated view function! + + Set :attr:`init_every_request` to ``False`` for efficiency, unless + you need to store request-global data on ``self``. + """ + + #: The methods this view is registered for. Uses the same default + #: (``["GET", "HEAD", "OPTIONS"]``) as ``route`` and + #: ``add_url_rule`` by default. + methods: t.ClassVar[t.Collection[str] | None] = None + + #: Control whether the ``OPTIONS`` method is handled automatically. + #: Uses the same default (``True``) as ``route`` and + #: ``add_url_rule`` by default. + provide_automatic_options: t.ClassVar[bool | None] = None + + #: A list of decorators to apply, in order, to the generated view + #: function. Remember that ``@decorator`` syntax is applied bottom + #: to top, so the first decorator in the list would be the bottom + #: decorator. + #: + #: .. versionadded:: 0.8 + decorators: t.ClassVar[list[t.Callable[..., t.Any]]] = [] + + #: Create a new instance of this view class for every request by + #: default. If a view subclass sets this to ``False``, the same + #: instance is used for every request. + #: + #: A single instance is more efficient, especially if complex setup + #: is done during init. However, storing data on ``self`` is no + #: longer safe across requests, and :data:`~flask.g` should be used + #: instead. + #: + #: .. versionadded:: 2.2 + init_every_request: t.ClassVar[bool] = True + + def dispatch_request(self) -> ft.ResponseReturnValue: + """The actual view function behavior. Subclasses must override + this and return a valid response. Any variables from the URL + rule are passed as keyword arguments. + """ + raise NotImplementedError() + + @classmethod + def as_view( + cls, name: str, *class_args: t.Any, **class_kwargs: t.Any + ) -> ft.RouteCallable: + """Convert the class into a view function that can be registered + for a route. + + By default, the generated view will create a new instance of the + view class for every request and call its + :meth:`dispatch_request` method. If the view class sets + :attr:`init_every_request` to ``False``, the same instance will + be used for every request. + + Except for ``name``, all other arguments passed to this method + are forwarded to the view class ``__init__`` method. + + .. versionchanged:: 2.2 + Added the ``init_every_request`` class attribute. + """ + if cls.init_every_request: + + def view(**kwargs: t.Any) -> ft.ResponseReturnValue: + self = view.view_class( # type: ignore[attr-defined] + *class_args, **class_kwargs + ) + return current_app.ensure_sync(self.dispatch_request)(**kwargs) # type: ignore[no-any-return] + + else: + self = cls(*class_args, **class_kwargs) # pyright: ignore + + def view(**kwargs: t.Any) -> ft.ResponseReturnValue: + return current_app.ensure_sync(self.dispatch_request)(**kwargs) # type: ignore[no-any-return] + + if cls.decorators: + view.__name__ = name + view.__module__ = cls.__module__ + for decorator in cls.decorators: + view = decorator(view) + + # We attach the view class to the view function for two reasons: + # first of all it allows us to easily figure out what class-based + # view this thing came from, secondly it's also used for instantiating + # the view class so you can actually replace it with something else + # for testing purposes and debugging. + view.view_class = cls # type: ignore + view.__name__ = name + view.__doc__ = cls.__doc__ + view.__module__ = cls.__module__ + view.methods = cls.methods # type: ignore + view.provide_automatic_options = cls.provide_automatic_options # type: ignore + return view + + +class MethodView(View): + """Dispatches request methods to the corresponding instance methods. + For example, if you implement a ``get`` method, it will be used to + handle ``GET`` requests. + + This can be useful for defining a REST API. + + :attr:`methods` is automatically set based on the methods defined on + the class. + + See :doc:`views` for a detailed guide. + + .. code-block:: python + + class CounterAPI(MethodView): + def get(self): + return str(session.get("counter", 0)) + + def post(self): + session["counter"] = session.get("counter", 0) + 1 + return redirect(url_for("counter")) + + app.add_url_rule( + "/counter", view_func=CounterAPI.as_view("counter") + ) + """ + + def __init_subclass__(cls, **kwargs: t.Any) -> None: + super().__init_subclass__(**kwargs) + + if "methods" not in cls.__dict__: + methods = set() + + for base in cls.__bases__: + if getattr(base, "methods", None): + methods.update(base.methods) # type: ignore[attr-defined] + + for key in http_method_funcs: + if hasattr(cls, key): + methods.add(key.upper()) + + if methods: + cls.methods = methods + + def dispatch_request(self, **kwargs: t.Any) -> ft.ResponseReturnValue: + meth = getattr(self, request.method.lower(), None) + + # If the request method is HEAD and we don't have a handler for it + # retry with GET. + if meth is None and request.method == "HEAD": + meth = getattr(self, "get", None) + + assert meth is not None, f"Unimplemented method {request.method!r}" + return current_app.ensure_sync(meth)(**kwargs) # type: ignore[no-any-return] diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask/wrappers.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask/wrappers.py new file mode 100644 index 000000000..bab610291 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask/wrappers.py @@ -0,0 +1,257 @@ +from __future__ import annotations + +import typing as t + +from werkzeug.exceptions import BadRequest +from werkzeug.exceptions import HTTPException +from werkzeug.wrappers import Request as RequestBase +from werkzeug.wrappers import Response as ResponseBase + +from . import json +from .globals import current_app +from .helpers import _split_blueprint_path + +if t.TYPE_CHECKING: # pragma: no cover + from werkzeug.routing import Rule + + +class Request(RequestBase): + """The request object used by default in Flask. Remembers the + matched endpoint and view arguments. + + It is what ends up as :class:`~flask.request`. If you want to replace + the request object used you can subclass this and set + :attr:`~flask.Flask.request_class` to your subclass. + + The request object is a :class:`~werkzeug.wrappers.Request` subclass and + provides all of the attributes Werkzeug defines plus a few Flask + specific ones. + """ + + json_module: t.Any = json + + #: The internal URL rule that matched the request. This can be + #: useful to inspect which methods are allowed for the URL from + #: a before/after handler (``request.url_rule.methods``) etc. + #: Though if the request's method was invalid for the URL rule, + #: the valid list is available in ``routing_exception.valid_methods`` + #: instead (an attribute of the Werkzeug exception + #: :exc:`~werkzeug.exceptions.MethodNotAllowed`) + #: because the request was never internally bound. + #: + #: .. versionadded:: 0.6 + url_rule: Rule | None = None + + #: A dict of view arguments that matched the request. If an exception + #: happened when matching, this will be ``None``. + view_args: dict[str, t.Any] | None = None + + #: If matching the URL failed, this is the exception that will be + #: raised / was raised as part of the request handling. This is + #: usually a :exc:`~werkzeug.exceptions.NotFound` exception or + #: something similar. + routing_exception: HTTPException | None = None + + _max_content_length: int | None = None + _max_form_memory_size: int | None = None + _max_form_parts: int | None = None + + @property + def max_content_length(self) -> int | None: + """The maximum number of bytes that will be read during this request. If + this limit is exceeded, a 413 :exc:`~werkzeug.exceptions.RequestEntityTooLarge` + error is raised. If it is set to ``None``, no limit is enforced at the + Flask application level. However, if it is ``None`` and the request has + no ``Content-Length`` header and the WSGI server does not indicate that + it terminates the stream, then no data is read to avoid an infinite + stream. + + Each request defaults to the :data:`MAX_CONTENT_LENGTH` config, which + defaults to ``None``. It can be set on a specific ``request`` to apply + the limit to that specific view. This should be set appropriately based + on an application's or view's specific needs. + + .. versionchanged:: 3.1 + This can be set per-request. + + .. versionchanged:: 0.6 + This is configurable through Flask config. + """ + if self._max_content_length is not None: + return self._max_content_length + + if not current_app: + return super().max_content_length + + return current_app.config["MAX_CONTENT_LENGTH"] # type: ignore[no-any-return] + + @max_content_length.setter + def max_content_length(self, value: int | None) -> None: + self._max_content_length = value + + @property + def max_form_memory_size(self) -> int | None: + """The maximum size in bytes any non-file form field may be in a + ``multipart/form-data`` body. If this limit is exceeded, a 413 + :exc:`~werkzeug.exceptions.RequestEntityTooLarge` error is raised. If it + is set to ``None``, no limit is enforced at the Flask application level. + + Each request defaults to the :data:`MAX_FORM_MEMORY_SIZE` config, which + defaults to ``500_000``. It can be set on a specific ``request`` to + apply the limit to that specific view. This should be set appropriately + based on an application's or view's specific needs. + + .. versionchanged:: 3.1 + This is configurable through Flask config. + """ + if self._max_form_memory_size is not None: + return self._max_form_memory_size + + if not current_app: + return super().max_form_memory_size + + return current_app.config["MAX_FORM_MEMORY_SIZE"] # type: ignore[no-any-return] + + @max_form_memory_size.setter + def max_form_memory_size(self, value: int | None) -> None: + self._max_form_memory_size = value + + @property # type: ignore[override] + def max_form_parts(self) -> int | None: + """The maximum number of fields that may be present in a + ``multipart/form-data`` body. If this limit is exceeded, a 413 + :exc:`~werkzeug.exceptions.RequestEntityTooLarge` error is raised. If it + is set to ``None``, no limit is enforced at the Flask application level. + + Each request defaults to the :data:`MAX_FORM_PARTS` config, which + defaults to ``1_000``. It can be set on a specific ``request`` to apply + the limit to that specific view. This should be set appropriately based + on an application's or view's specific needs. + + .. versionchanged:: 3.1 + This is configurable through Flask config. + """ + if self._max_form_parts is not None: + return self._max_form_parts + + if not current_app: + return super().max_form_parts + + return current_app.config["MAX_FORM_PARTS"] # type: ignore[no-any-return] + + @max_form_parts.setter + def max_form_parts(self, value: int | None) -> None: + self._max_form_parts = value + + @property + def endpoint(self) -> str | None: + """The endpoint that matched the request URL. + + This will be ``None`` if matching failed or has not been + performed yet. + + This in combination with :attr:`view_args` can be used to + reconstruct the same URL or a modified URL. + """ + if self.url_rule is not None: + return self.url_rule.endpoint # type: ignore[no-any-return] + + return None + + @property + def blueprint(self) -> str | None: + """The registered name of the current blueprint. + + This will be ``None`` if the endpoint is not part of a + blueprint, or if URL matching failed or has not been performed + yet. + + This does not necessarily match the name the blueprint was + created with. It may have been nested, or registered with a + different name. + """ + endpoint = self.endpoint + + if endpoint is not None and "." in endpoint: + return endpoint.rpartition(".")[0] + + return None + + @property + def blueprints(self) -> list[str]: + """The registered names of the current blueprint upwards through + parent blueprints. + + This will be an empty list if there is no current blueprint, or + if URL matching failed. + + .. versionadded:: 2.0.1 + """ + name = self.blueprint + + if name is None: + return [] + + return _split_blueprint_path(name) + + def _load_form_data(self) -> None: + super()._load_form_data() + + # In debug mode we're replacing the files multidict with an ad-hoc + # subclass that raises a different error for key errors. + if ( + current_app + and current_app.debug + and self.mimetype != "multipart/form-data" + and not self.files + ): + from .debughelpers import attach_enctype_error_multidict + + attach_enctype_error_multidict(self) + + def on_json_loading_failed(self, e: ValueError | None) -> t.Any: + try: + return super().on_json_loading_failed(e) + except BadRequest as ebr: + if current_app and current_app.debug: + raise + + raise BadRequest() from ebr + + +class Response(ResponseBase): + """The response object that is used by default in Flask. Works like the + response object from Werkzeug but is set to have an HTML mimetype by + default. Quite often you don't have to create this object yourself because + :meth:`~flask.Flask.make_response` will take care of that for you. + + If you want to replace the response object used you can subclass this and + set :attr:`~flask.Flask.response_class` to your subclass. + + .. versionchanged:: 1.0 + JSON support is added to the response, like the request. This is useful + when testing to get the test client response data as JSON. + + .. versionchanged:: 1.0 + + Added :attr:`max_cookie_size`. + """ + + default_mimetype: str | None = "text/html" + + json_module = json + + autocorrect_location_header = False + + @property + def max_cookie_size(self) -> int: # type: ignore + """Read-only view of the :data:`MAX_COOKIE_SIZE` config key. + + See :attr:`~werkzeug.wrappers.Response.max_cookie_size` in + Werkzeug's docs. + """ + if current_app: + return current_app.config["MAX_COOKIE_SIZE"] # type: ignore[no-any-return] + + # return Werkzeug's default when not in an app context + return super().max_cookie_size diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_bcrypt.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_bcrypt.py new file mode 100644 index 000000000..994985a18 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_bcrypt.py @@ -0,0 +1,225 @@ +''' + flaskext.bcrypt + --------------- + + A Flask extension providing bcrypt hashing and comparison facilities. + + :copyright: (c) 2011 by Max Countryman. + :license: BSD, see LICENSE for more details. +''' + +from __future__ import absolute_import +from __future__ import print_function + +__version_info__ = ('1', '0', '1') +__version__ = '.'.join(__version_info__) +__author__ = 'Max Countryman' +__license__ = 'BSD' +__copyright__ = '(c) 2011 by Max Countryman' +__all__ = ['Bcrypt', 'check_password_hash', 'generate_password_hash'] + +import hmac + +try: + import bcrypt +except ImportError as e: + print('bcrypt is required to use Flask-Bcrypt') + raise e + +import hashlib + + +def generate_password_hash(password, rounds=None): + '''This helper function wraps the eponymous method of :class:`Bcrypt`. It + is intended to be used as a helper function at the expense of the + configuration variable provided when passing back the app object. In other + words this shortcut does not make use of the app object at all. + + To use this function, simply import it from the module and use it in a + similar fashion as the original method would be used. Here is a quick + example:: + + from flask_bcrypt import generate_password_hash + pw_hash = generate_password_hash('hunter2', 10) + + :param password: The password to be hashed. + :param rounds: The optional number of rounds. + ''' + return Bcrypt().generate_password_hash(password, rounds) + + +def check_password_hash(pw_hash, password): + '''This helper function wraps the eponymous method of :class:`Bcrypt.` It + is intended to be used as a helper function at the expense of the + configuration variable provided when passing back the app object. In other + words this shortcut does not make use of the app object at all. + + To use this function, simply import it from the module and use it in a + similar fashion as the original method would be used. Here is a quick + example:: + + from flask_bcrypt import check_password_hash + check_password_hash(pw_hash, 'hunter2') # returns True + + :param pw_hash: The hash to be compared against. + :param password: The password to compare. + ''' + return Bcrypt().check_password_hash(pw_hash, password) + + +class Bcrypt(object): + '''Bcrypt class container for password hashing and checking logic using + bcrypt, of course. This class may be used to intialize your Flask app + object. The purpose is to provide a simple interface for overriding + Werkzeug's built-in password hashing utilities. + + Although such methods are not actually overriden, the API is intentionally + made similar so that existing applications which make use of the previous + hashing functions might be easily adapted to the stronger facility of + bcrypt. + + To get started you will wrap your application's app object something like + this:: + + app = Flask(__name__) + bcrypt = Bcrypt(app) + + Now the two primary utility methods are exposed via this object, `bcrypt`. + So in the context of the application, important data, such as passwords, + could be hashed using this syntax:: + + password = 'hunter2' + pw_hash = bcrypt.generate_password_hash(password) + + Once hashed, the value is irreversible. However in the case of validating + logins a simple hashing of candidate password and subsequent comparison. + Importantly a comparison should be done in constant time. This helps + prevent timing attacks. A simple utility method is provided for this:: + + candidate = 'secret' + bcrypt.check_password_hash(pw_hash, candidate) + + If both the candidate and the existing password hash are a match + `check_password_hash` returns True. Otherwise, it returns False. + + .. admonition:: Namespacing Issues + + It's worth noting that if you use the format, `bcrypt = Bcrypt(app)` + you are effectively overriding the bcrypt module. Though it's unlikely + you would need to access the module outside of the scope of the + extension be aware that it's overriden. + + Alternatively consider using a different name, such as `flask_bcrypt + = Bcrypt(app)` to prevent naming collisions. + + Additionally a configuration value for `BCRYPT_LOG_ROUNDS` may be set in + the configuration of the Flask app. If none is provided this will + internally be assigned to 12. (This value is used in determining the + complexity of the encryption, see bcrypt for more details.) + + You may also set the hash version using the `BCRYPT_HASH_PREFIX` field in + the configuration of the Flask app. If not set, this will default to `2b`. + (See bcrypt for more details) + + By default, the bcrypt algorithm has a maximum password length of 72 bytes + and ignores any bytes beyond that. A common workaround is to hash the + given password using a cryptographic hash (such as `sha256`), take its + hexdigest to prevent NULL byte problems, and hash the result with bcrypt. + If the `BCRYPT_HANDLE_LONG_PASSWORDS` configuration value is set to `True`, + the workaround described above will be enabled. + **Warning: do not enable this option on a project that is already using + Flask-Bcrypt, or you will break password checking.** + **Warning: if this option is enabled on an existing project, disabling it + will break password checking.** + + :param app: The Flask application object. Defaults to None. + ''' + + _log_rounds = 12 + _prefix = '2b' + _handle_long_passwords = False + + def __init__(self, app=None): + if app is not None: + self.init_app(app) + + def init_app(self, app): + '''Initalizes the application with the extension. + + :param app: The Flask application object. + ''' + self._log_rounds = app.config.get('BCRYPT_LOG_ROUNDS', 12) + self._prefix = app.config.get('BCRYPT_HASH_PREFIX', '2b') + self._handle_long_passwords = app.config.get( + 'BCRYPT_HANDLE_LONG_PASSWORDS', False) + + def _unicode_to_bytes(self, unicode_string): + '''Converts a unicode string to a bytes object. + + :param unicode_string: The unicode string to convert.''' + if isinstance(unicode_string, str): + bytes_object = bytes(unicode_string, 'utf-8') + else: + bytes_object = unicode_string + return bytes_object + + def generate_password_hash(self, password, rounds=None, prefix=None): + '''Generates a password hash using bcrypt. Specifying `rounds` + sets the log_rounds parameter of `bcrypt.gensalt()` which determines + the complexity of the salt. 12 is the default value. Specifying `prefix` + sets the `prefix` parameter of `bcrypt.gensalt()` which determines the + version of the algorithm used to create the hash. + + Example usage of :class:`generate_password_hash` might look something + like this:: + + pw_hash = bcrypt.generate_password_hash('secret', 10) + + :param password: The password to be hashed. + :param rounds: The optional number of rounds. + :param prefix: The algorithm version to use. + ''' + + if not password: + raise ValueError('Password must be non-empty.') + + if rounds is None: + rounds = self._log_rounds + if prefix is None: + prefix = self._prefix + + # Python 3 unicode strings must be encoded as bytes before hashing. + password = self._unicode_to_bytes(password) + prefix = self._unicode_to_bytes(prefix) + + if self._handle_long_passwords: + password = hashlib.sha256(password).hexdigest() + password = self._unicode_to_bytes(password) + + salt = bcrypt.gensalt(rounds=rounds, prefix=prefix) + return bcrypt.hashpw(password, salt) + + def check_password_hash(self, pw_hash, password): + '''Tests a password hash against a candidate password. The candidate + password is first hashed and then subsequently compared in constant + time to the existing hash. This will either return `True` or `False`. + + Example usage of :class:`check_password_hash` would look something + like this:: + + pw_hash = bcrypt.generate_password_hash('secret', 10) + bcrypt.check_password_hash(pw_hash, 'secret') # returns True + + :param pw_hash: The hash to be compared against. + :param password: The password to compare. + ''' + + # Python 3 unicode strings must be encoded as bytes before hashing. + pw_hash = self._unicode_to_bytes(pw_hash) + password = self._unicode_to_bytes(password) + + if self._handle_long_passwords: + password = hashlib.sha256(password).hexdigest() + password = self._unicode_to_bytes(password) + + return hmac.compare_digest(bcrypt.hashpw(password, pw_hash), pw_hash) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_login/__about__.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_login/__about__.py new file mode 100644 index 000000000..1918d54f7 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_login/__about__.py @@ -0,0 +1,10 @@ +__title__ = "Flask-Login" +__description__ = "User session management for Flask" +__url__ = "https://github.com/maxcountryman/flask-login" +__version_info__ = ("0", "6", "3") +__version__ = ".".join(__version_info__) +__author__ = "Matthew Frazier" +__author_email__ = "leafstormrush@gmail.com" +__maintainer__ = "Max Countryman" +__license__ = "MIT" +__copyright__ = "(c) 2011 by Matthew Frazier" diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_login/__init__.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_login/__init__.py new file mode 100644 index 000000000..fbe9c3e77 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_login/__init__.py @@ -0,0 +1,94 @@ +from .__about__ import __version__ +from .config import AUTH_HEADER_NAME +from .config import COOKIE_DURATION +from .config import COOKIE_HTTPONLY +from .config import COOKIE_NAME +from .config import COOKIE_SECURE +from .config import ID_ATTRIBUTE +from .config import LOGIN_MESSAGE +from .config import LOGIN_MESSAGE_CATEGORY +from .config import REFRESH_MESSAGE +from .config import REFRESH_MESSAGE_CATEGORY +from .login_manager import LoginManager +from .mixins import AnonymousUserMixin +from .mixins import UserMixin +from .signals import session_protected +from .signals import user_accessed +from .signals import user_loaded_from_cookie +from .signals import user_loaded_from_request +from .signals import user_logged_in +from .signals import user_logged_out +from .signals import user_login_confirmed +from .signals import user_needs_refresh +from .signals import user_unauthorized +from .test_client import FlaskLoginClient +from .utils import confirm_login +from .utils import current_user +from .utils import decode_cookie +from .utils import encode_cookie +from .utils import fresh_login_required +from .utils import login_fresh +from .utils import login_remembered +from .utils import login_required +from .utils import login_url +from .utils import login_user +from .utils import logout_user +from .utils import make_next_param +from .utils import set_login_view + +__all__ = [ + "__version__", + "AUTH_HEADER_NAME", + "COOKIE_DURATION", + "COOKIE_HTTPONLY", + "COOKIE_NAME", + "COOKIE_SECURE", + "ID_ATTRIBUTE", + "LOGIN_MESSAGE", + "LOGIN_MESSAGE_CATEGORY", + "REFRESH_MESSAGE", + "REFRESH_MESSAGE_CATEGORY", + "LoginManager", + "AnonymousUserMixin", + "UserMixin", + "session_protected", + "user_accessed", + "user_loaded_from_cookie", + "user_loaded_from_request", + "user_logged_in", + "user_logged_out", + "user_login_confirmed", + "user_needs_refresh", + "user_unauthorized", + "FlaskLoginClient", + "confirm_login", + "current_user", + "decode_cookie", + "encode_cookie", + "fresh_login_required", + "login_fresh", + "login_remembered", + "login_required", + "login_url", + "login_user", + "logout_user", + "make_next_param", + "set_login_view", +] + + +def __getattr__(name): + if name == "user_loaded_from_header": + import warnings + from .signals import _user_loaded_from_header + + warnings.warn( + "'user_loaded_from_header' is deprecated and will be" + " removed in Flask-Login 0.7. Use" + " 'user_loaded_from_request' instead.", + DeprecationWarning, + stacklevel=2, + ) + return _user_loaded_from_header + + raise AttributeError(name) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_login/config.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_login/config.py new file mode 100644 index 000000000..fe2db2c5c --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_login/config.py @@ -0,0 +1,55 @@ +from datetime import timedelta + +#: The default name of the "remember me" cookie (``remember_token``) +COOKIE_NAME = "remember_token" + +#: The default time before the "remember me" cookie expires (365 days). +COOKIE_DURATION = timedelta(days=365) + +#: Whether the "remember me" cookie requires Secure; defaults to ``False`` +COOKIE_SECURE = False + +#: Whether the "remember me" cookie uses HttpOnly or not; defaults to ``True`` +COOKIE_HTTPONLY = True + +#: Whether the "remember me" cookie requires same origin; defaults to ``None`` +COOKIE_SAMESITE = None + +#: The default flash message to display when users need to log in. +LOGIN_MESSAGE = "Please log in to access this page." + +#: The default flash message category to display when users need to log in. +LOGIN_MESSAGE_CATEGORY = "message" + +#: The default flash message to display when users need to reauthenticate. +REFRESH_MESSAGE = "Please reauthenticate to access this page." + +#: The default flash message category to display when users need to +#: reauthenticate. +REFRESH_MESSAGE_CATEGORY = "message" + +#: The default attribute to retreive the str id of the user +ID_ATTRIBUTE = "get_id" + +#: Default name of the auth header (``Authorization``) +AUTH_HEADER_NAME = "Authorization" + +#: A set of session keys that are populated by Flask-Login. Use this set to +#: purge keys safely and accurately. +SESSION_KEYS = { + "_user_id", + "_remember", + "_remember_seconds", + "_id", + "_fresh", + "next", +} + +#: A set of HTTP methods which are exempt from `login_required` and +#: `fresh_login_required`. By default, this is just ``OPTIONS``. +EXEMPT_METHODS = {"OPTIONS"} + +#: If true, the page the user is attempting to access is stored in the session +#: rather than a url parameter when redirecting to the login view; defaults to +#: ``False``. +USE_SESSION_FOR_NEXT = False diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_login/login_manager.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_login/login_manager.py new file mode 100644 index 000000000..49d0844fa --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_login/login_manager.py @@ -0,0 +1,543 @@ +from datetime import datetime +from datetime import timedelta + +from flask import abort +from flask import current_app +from flask import flash +from flask import g +from flask import has_app_context +from flask import redirect +from flask import request +from flask import session + +from .config import AUTH_HEADER_NAME +from .config import COOKIE_DURATION +from .config import COOKIE_HTTPONLY +from .config import COOKIE_NAME +from .config import COOKIE_SAMESITE +from .config import COOKIE_SECURE +from .config import ID_ATTRIBUTE +from .config import LOGIN_MESSAGE +from .config import LOGIN_MESSAGE_CATEGORY +from .config import REFRESH_MESSAGE +from .config import REFRESH_MESSAGE_CATEGORY +from .config import SESSION_KEYS +from .config import USE_SESSION_FOR_NEXT +from .mixins import AnonymousUserMixin +from .signals import session_protected +from .signals import user_accessed +from .signals import user_loaded_from_cookie +from .signals import user_loaded_from_request +from .signals import user_needs_refresh +from .signals import user_unauthorized +from .utils import _create_identifier +from .utils import _user_context_processor +from .utils import decode_cookie +from .utils import encode_cookie +from .utils import expand_login_view +from .utils import login_url as make_login_url +from .utils import make_next_param + + +class LoginManager: + """This object is used to hold the settings used for logging in. Instances + of :class:`LoginManager` are *not* bound to specific apps, so you can + create one in the main body of your code and then bind it to your + app in a factory function. + """ + + def __init__(self, app=None, add_context_processor=True): + #: A class or factory function that produces an anonymous user, which + #: is used when no one is logged in. + self.anonymous_user = AnonymousUserMixin + + #: The name of the view to redirect to when the user needs to log in. + #: (This can be an absolute URL as well, if your authentication + #: machinery is external to your application.) + self.login_view = None + + #: Names of views to redirect to when the user needs to log in, + #: per blueprint. If the key value is set to None the value of + #: :attr:`login_view` will be used instead. + self.blueprint_login_views = {} + + #: The message to flash when a user is redirected to the login page. + self.login_message = LOGIN_MESSAGE + + #: The message category to flash when a user is redirected to the login + #: page. + self.login_message_category = LOGIN_MESSAGE_CATEGORY + + #: The name of the view to redirect to when the user needs to + #: reauthenticate. + self.refresh_view = None + + #: The message to flash when a user is redirected to the 'needs + #: refresh' page. + self.needs_refresh_message = REFRESH_MESSAGE + + #: The message category to flash when a user is redirected to the + #: 'needs refresh' page. + self.needs_refresh_message_category = REFRESH_MESSAGE_CATEGORY + + #: The mode to use session protection in. This can be either + #: ``'basic'`` (the default) or ``'strong'``, or ``None`` to disable + #: it. + self.session_protection = "basic" + + #: If present, used to translate flash messages ``self.login_message`` + #: and ``self.needs_refresh_message`` + self.localize_callback = None + + self.unauthorized_callback = None + + self.needs_refresh_callback = None + + self.id_attribute = ID_ATTRIBUTE + + self._user_callback = None + + self._header_callback = None + + self._request_callback = None + + self._session_identifier_generator = _create_identifier + + if app is not None: + self.init_app(app, add_context_processor) + + def setup_app(self, app, add_context_processor=True): # pragma: no cover + """ + This method has been deprecated. Please use + :meth:`LoginManager.init_app` instead. + """ + import warnings + + warnings.warn( + "'setup_app' is deprecated and will be removed in" + " Flask-Login 0.7. Use 'init_app' instead.", + DeprecationWarning, + stacklevel=2, + ) + self.init_app(app, add_context_processor) + + def init_app(self, app, add_context_processor=True): + """ + Configures an application. This registers an `after_request` call, and + attaches this `LoginManager` to it as `app.login_manager`. + + :param app: The :class:`flask.Flask` object to configure. + :type app: :class:`flask.Flask` + :param add_context_processor: Whether to add a context processor to + the app that adds a `current_user` variable to the template. + Defaults to ``True``. + :type add_context_processor: bool + """ + app.login_manager = self + app.after_request(self._update_remember_cookie) + + if add_context_processor: + app.context_processor(_user_context_processor) + + def unauthorized(self): + """ + This is called when the user is required to log in. If you register a + callback with :meth:`LoginManager.unauthorized_handler`, then it will + be called. Otherwise, it will take the following actions: + + - Flash :attr:`LoginManager.login_message` to the user. + + - If the app is using blueprints find the login view for + the current blueprint using `blueprint_login_views`. If the app + is not using blueprints or the login view for the current + blueprint is not specified use the value of `login_view`. + + - Redirect the user to the login view. (The page they were + attempting to access will be passed in the ``next`` query + string variable, so you can redirect there if present instead + of the homepage. Alternatively, it will be added to the session + as ``next`` if USE_SESSION_FOR_NEXT is set.) + + If :attr:`LoginManager.login_view` is not defined, then it will simply + raise a HTTP 401 (Unauthorized) error instead. + + This should be returned from a view or before/after_request function, + otherwise the redirect will have no effect. + """ + user_unauthorized.send(current_app._get_current_object()) + + if self.unauthorized_callback: + return self.unauthorized_callback() + + if request.blueprint in self.blueprint_login_views: + login_view = self.blueprint_login_views[request.blueprint] + else: + login_view = self.login_view + + if not login_view: + abort(401) + + if self.login_message: + if self.localize_callback is not None: + flash( + self.localize_callback(self.login_message), + category=self.login_message_category, + ) + else: + flash(self.login_message, category=self.login_message_category) + + config = current_app.config + if config.get("USE_SESSION_FOR_NEXT", USE_SESSION_FOR_NEXT): + login_url = expand_login_view(login_view) + session["_id"] = self._session_identifier_generator() + session["next"] = make_next_param(login_url, request.url) + redirect_url = make_login_url(login_view) + else: + redirect_url = make_login_url(login_view, next_url=request.url) + + return redirect(redirect_url) + + def user_loader(self, callback): + """ + This sets the callback for reloading a user from the session. The + function you set should take a user ID (a ``str``) and return a + user object, or ``None`` if the user does not exist. + + :param callback: The callback for retrieving a user object. + :type callback: callable + """ + self._user_callback = callback + return self.user_callback + + @property + def user_callback(self): + """Gets the user_loader callback set by user_loader decorator.""" + return self._user_callback + + def request_loader(self, callback): + """ + This sets the callback for loading a user from a Flask request. + The function you set should take Flask request object and + return a user object, or `None` if the user does not exist. + + :param callback: The callback for retrieving a user object. + :type callback: callable + """ + self._request_callback = callback + return self.request_callback + + @property + def request_callback(self): + """Gets the request_loader callback set by request_loader decorator.""" + return self._request_callback + + def unauthorized_handler(self, callback): + """ + This will set the callback for the `unauthorized` method, which among + other things is used by `login_required`. It takes no arguments, and + should return a response to be sent to the user instead of their + normal view. + + :param callback: The callback for unauthorized users. + :type callback: callable + """ + self.unauthorized_callback = callback + return callback + + def needs_refresh_handler(self, callback): + """ + This will set the callback for the `needs_refresh` method, which among + other things is used by `fresh_login_required`. It takes no arguments, + and should return a response to be sent to the user instead of their + normal view. + + :param callback: The callback for unauthorized users. + :type callback: callable + """ + self.needs_refresh_callback = callback + return callback + + def needs_refresh(self): + """ + This is called when the user is logged in, but they need to be + reauthenticated because their session is stale. If you register a + callback with `needs_refresh_handler`, then it will be called. + Otherwise, it will take the following actions: + + - Flash :attr:`LoginManager.needs_refresh_message` to the user. + + - Redirect the user to :attr:`LoginManager.refresh_view`. (The page + they were attempting to access will be passed in the ``next`` + query string variable, so you can redirect there if present + instead of the homepage.) + + If :attr:`LoginManager.refresh_view` is not defined, then it will + simply raise a HTTP 401 (Unauthorized) error instead. + + This should be returned from a view or before/after_request function, + otherwise the redirect will have no effect. + """ + user_needs_refresh.send(current_app._get_current_object()) + + if self.needs_refresh_callback: + return self.needs_refresh_callback() + + if not self.refresh_view: + abort(401) + + if self.needs_refresh_message: + if self.localize_callback is not None: + flash( + self.localize_callback(self.needs_refresh_message), + category=self.needs_refresh_message_category, + ) + else: + flash( + self.needs_refresh_message, + category=self.needs_refresh_message_category, + ) + + config = current_app.config + if config.get("USE_SESSION_FOR_NEXT", USE_SESSION_FOR_NEXT): + login_url = expand_login_view(self.refresh_view) + session["_id"] = self._session_identifier_generator() + session["next"] = make_next_param(login_url, request.url) + redirect_url = make_login_url(self.refresh_view) + else: + login_url = self.refresh_view + redirect_url = make_login_url(login_url, next_url=request.url) + + return redirect(redirect_url) + + def header_loader(self, callback): + """ + This function has been deprecated. Please use + :meth:`LoginManager.request_loader` instead. + + This sets the callback for loading a user from a header value. + The function you set should take an authentication token and + return a user object, or `None` if the user does not exist. + + :param callback: The callback for retrieving a user object. + :type callback: callable + """ + import warnings + + warnings.warn( + "'header_loader' is deprecated and will be removed in" + " Flask-Login 0.7. Use 'request_loader' instead.", + DeprecationWarning, + stacklevel=2, + ) + self._header_callback = callback + return callback + + def _update_request_context_with_user(self, user=None): + """Store the given user as ctx.user.""" + + if user is None: + user = self.anonymous_user() + + g._login_user = user + + def _load_user(self): + """Loads user from session or remember_me cookie as applicable""" + + if self._user_callback is None and self._request_callback is None: + raise Exception( + "Missing user_loader or request_loader. Refer to " + "http://flask-login.readthedocs.io/#how-it-works " + "for more info." + ) + + user_accessed.send(current_app._get_current_object()) + + # Check SESSION_PROTECTION + if self._session_protection_failed(): + return self._update_request_context_with_user() + + user = None + + # Load user from Flask Session + user_id = session.get("_user_id") + if user_id is not None and self._user_callback is not None: + user = self._user_callback(user_id) + + # Load user from Remember Me Cookie or Request Loader + if user is None: + config = current_app.config + cookie_name = config.get("REMEMBER_COOKIE_NAME", COOKIE_NAME) + header_name = config.get("AUTH_HEADER_NAME", AUTH_HEADER_NAME) + has_cookie = ( + cookie_name in request.cookies and session.get("_remember") != "clear" + ) + if has_cookie: + cookie = request.cookies[cookie_name] + user = self._load_user_from_remember_cookie(cookie) + elif self._request_callback: + user = self._load_user_from_request(request) + elif header_name in request.headers: + header = request.headers[header_name] + user = self._load_user_from_header(header) + + return self._update_request_context_with_user(user) + + def _session_protection_failed(self): + sess = session._get_current_object() + ident = self._session_identifier_generator() + + app = current_app._get_current_object() + mode = app.config.get("SESSION_PROTECTION", self.session_protection) + + if not mode or mode not in ["basic", "strong"]: + return False + + # if the sess is empty, it's an anonymous user or just logged out + # so we can skip this + if sess and ident != sess.get("_id", None): + if mode == "basic" or sess.permanent: + if sess.get("_fresh") is not False: + sess["_fresh"] = False + session_protected.send(app) + return False + elif mode == "strong": + for k in SESSION_KEYS: + sess.pop(k, None) + + sess["_remember"] = "clear" + session_protected.send(app) + return True + + return False + + def _load_user_from_remember_cookie(self, cookie): + user_id = decode_cookie(cookie) + if user_id is not None: + session["_user_id"] = user_id + session["_fresh"] = False + user = None + if self._user_callback: + user = self._user_callback(user_id) + if user is not None: + app = current_app._get_current_object() + user_loaded_from_cookie.send(app, user=user) + return user + return None + + def _load_user_from_header(self, header): + if self._header_callback: + user = self._header_callback(header) + if user is not None: + app = current_app._get_current_object() + + from .signals import _user_loaded_from_header + + _user_loaded_from_header.send(app, user=user) + return user + return None + + def _load_user_from_request(self, request): + if self._request_callback: + user = self._request_callback(request) + if user is not None: + app = current_app._get_current_object() + user_loaded_from_request.send(app, user=user) + return user + return None + + def _update_remember_cookie(self, response): + # Don't modify the session unless there's something to do. + if "_remember" not in session and current_app.config.get( + "REMEMBER_COOKIE_REFRESH_EACH_REQUEST" + ): + session["_remember"] = "set" + + if "_remember" in session: + operation = session.pop("_remember", None) + + if operation == "set" and "_user_id" in session: + self._set_cookie(response) + elif operation == "clear": + self._clear_cookie(response) + + return response + + def _set_cookie(self, response): + # cookie settings + config = current_app.config + cookie_name = config.get("REMEMBER_COOKIE_NAME", COOKIE_NAME) + domain = config.get("REMEMBER_COOKIE_DOMAIN") + path = config.get("REMEMBER_COOKIE_PATH", "/") + + secure = config.get("REMEMBER_COOKIE_SECURE", COOKIE_SECURE) + httponly = config.get("REMEMBER_COOKIE_HTTPONLY", COOKIE_HTTPONLY) + samesite = config.get("REMEMBER_COOKIE_SAMESITE", COOKIE_SAMESITE) + + if "_remember_seconds" in session: + duration = timedelta(seconds=session["_remember_seconds"]) + else: + duration = config.get("REMEMBER_COOKIE_DURATION", COOKIE_DURATION) + + # prepare data + data = encode_cookie(str(session["_user_id"])) + + if isinstance(duration, int): + duration = timedelta(seconds=duration) + + try: + expires = datetime.utcnow() + duration + except TypeError as e: + raise Exception( + "REMEMBER_COOKIE_DURATION must be a datetime.timedelta," + f" instead got: {duration}" + ) from e + + # actually set it + response.set_cookie( + cookie_name, + value=data, + expires=expires, + domain=domain, + path=path, + secure=secure, + httponly=httponly, + samesite=samesite, + ) + + def _clear_cookie(self, response): + config = current_app.config + cookie_name = config.get("REMEMBER_COOKIE_NAME", COOKIE_NAME) + domain = config.get("REMEMBER_COOKIE_DOMAIN") + path = config.get("REMEMBER_COOKIE_PATH", "/") + response.delete_cookie(cookie_name, domain=domain, path=path) + + @property + def _login_disabled(self): + """Legacy property, use app.config['LOGIN_DISABLED'] instead.""" + import warnings + + warnings.warn( + "'_login_disabled' is deprecated and will be removed in" + " Flask-Login 0.7. Use 'LOGIN_DISABLED' in 'app.config'" + " instead.", + DeprecationWarning, + stacklevel=2, + ) + + if has_app_context(): + return current_app.config.get("LOGIN_DISABLED", False) + return False + + @_login_disabled.setter + def _login_disabled(self, newvalue): + """Legacy property setter, use app.config['LOGIN_DISABLED'] instead.""" + import warnings + + warnings.warn( + "'_login_disabled' is deprecated and will be removed in" + " Flask-Login 0.7. Use 'LOGIN_DISABLED' in 'app.config'" + " instead.", + DeprecationWarning, + stacklevel=2, + ) + current_app.config["LOGIN_DISABLED"] = newvalue diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_login/mixins.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_login/mixins.py new file mode 100644 index 000000000..0b3a71bbe --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_login/mixins.py @@ -0,0 +1,65 @@ +class UserMixin: + """ + This provides default implementations for the methods that Flask-Login + expects user objects to have. + """ + + # Python 3 implicitly set __hash__ to None if we override __eq__ + # We set it back to its default implementation + __hash__ = object.__hash__ + + @property + def is_active(self): + return True + + @property + def is_authenticated(self): + return self.is_active + + @property + def is_anonymous(self): + return False + + def get_id(self): + try: + return str(self.id) + except AttributeError: + raise NotImplementedError("No `id` attribute - override `get_id`") from None + + def __eq__(self, other): + """ + Checks the equality of two `UserMixin` objects using `get_id`. + """ + if isinstance(other, UserMixin): + return self.get_id() == other.get_id() + return NotImplemented + + def __ne__(self, other): + """ + Checks the inequality of two `UserMixin` objects using `get_id`. + """ + equal = self.__eq__(other) + if equal is NotImplemented: + return NotImplemented + return not equal + + +class AnonymousUserMixin: + """ + This is the default object for representing an anonymous user. + """ + + @property + def is_authenticated(self): + return False + + @property + def is_active(self): + return False + + @property + def is_anonymous(self): + return True + + def get_id(self): + return diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_login/signals.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_login/signals.py new file mode 100644 index 000000000..cf9157f8b --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_login/signals.py @@ -0,0 +1,61 @@ +from flask.signals import Namespace + +_signals = Namespace() + +#: Sent when a user is logged in. In addition to the app (which is the +#: sender), it is passed `user`, which is the user being logged in. +user_logged_in = _signals.signal("logged-in") + +#: Sent when a user is logged out. In addition to the app (which is the +#: sender), it is passed `user`, which is the user being logged out. +user_logged_out = _signals.signal("logged-out") + +#: Sent when the user is loaded from the cookie. In addition to the app (which +#: is the sender), it is passed `user`, which is the user being reloaded. +user_loaded_from_cookie = _signals.signal("loaded-from-cookie") + +#: Sent when the user is loaded from the header. In addition to the app (which +#: is the #: sender), it is passed `user`, which is the user being reloaded. +_user_loaded_from_header = _signals.signal("loaded-from-header") + +#: Sent when the user is loaded from the request. In addition to the app (which +#: is the #: sender), it is passed `user`, which is the user being reloaded. +user_loaded_from_request = _signals.signal("loaded-from-request") + +#: Sent when a user's login is confirmed, marking it as fresh. (It is not +#: called for a normal login.) +#: It receives no additional arguments besides the app. +user_login_confirmed = _signals.signal("login-confirmed") + +#: Sent when the `unauthorized` method is called on a `LoginManager`. It +#: receives no additional arguments besides the app. +user_unauthorized = _signals.signal("unauthorized") + +#: Sent when the `needs_refresh` method is called on a `LoginManager`. It +#: receives no additional arguments besides the app. +user_needs_refresh = _signals.signal("needs-refresh") + +#: Sent whenever the user is accessed/loaded +#: receives no additional arguments besides the app. +user_accessed = _signals.signal("accessed") + +#: Sent whenever session protection takes effect, and a session is either +#: marked non-fresh or deleted. It receives no additional arguments besides +#: the app. +session_protected = _signals.signal("session-protected") + + +def __getattr__(name): + if name == "user_loaded_from_header": + import warnings + + warnings.warn( + "'user_loaded_from_header' is deprecated and will be" + " removed in Flask-Login 0.7. Use" + " 'user_loaded_from_request' instead.", + DeprecationWarning, + stacklevel=2, + ) + return _user_loaded_from_header + + raise AttributeError(name) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_login/test_client.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_login/test_client.py new file mode 100644 index 000000000..be2a8bf6a --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_login/test_client.py @@ -0,0 +1,19 @@ +from flask.testing import FlaskClient + + +class FlaskLoginClient(FlaskClient): + """ + A Flask test client that knows how to log in users + using the Flask-Login extension. + """ + + def __init__(self, *args, **kwargs): + user = kwargs.pop("user", None) + fresh = kwargs.pop("fresh_login", True) + + super().__init__(*args, **kwargs) + + if user: + with self.session_transaction() as sess: + sess["_user_id"] = user.get_id() + sess["_fresh"] = fresh diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_login/utils.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_login/utils.py new file mode 100644 index 000000000..37b20564f --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_login/utils.py @@ -0,0 +1,415 @@ +import hmac +from functools import wraps +from hashlib import sha512 +from urllib.parse import parse_qs +from urllib.parse import urlencode +from urllib.parse import urlsplit +from urllib.parse import urlunsplit + +from flask import current_app +from flask import g +from flask import has_request_context +from flask import request +from flask import session +from flask import url_for +from werkzeug.local import LocalProxy + +from .config import COOKIE_NAME +from .config import EXEMPT_METHODS +from .signals import user_logged_in +from .signals import user_logged_out +from .signals import user_login_confirmed + +#: A proxy for the current user. If no user is logged in, this will be an +#: anonymous user +current_user = LocalProxy(lambda: _get_user()) + + +def encode_cookie(payload, key=None): + """ + This will encode a ``str`` value into a cookie, and sign that cookie + with the app's secret key. + + :param payload: The value to encode, as `str`. + :type payload: str + + :param key: The key to use when creating the cookie digest. If not + specified, the SECRET_KEY value from app config will be used. + :type key: str + """ + return f"{payload}|{_cookie_digest(payload, key=key)}" + + +def decode_cookie(cookie, key=None): + """ + This decodes a cookie given by `encode_cookie`. If verification of the + cookie fails, ``None`` will be implicitly returned. + + :param cookie: An encoded cookie. + :type cookie: str + + :param key: The key to use when creating the cookie digest. If not + specified, the SECRET_KEY value from app config will be used. + :type key: str + """ + try: + payload, digest = cookie.rsplit("|", 1) + if hasattr(digest, "decode"): + digest = digest.decode("ascii") # pragma: no cover + except ValueError: + return + + if hmac.compare_digest(_cookie_digest(payload, key=key), digest): + return payload + + +def make_next_param(login_url, current_url): + """ + Reduces the scheme and host from a given URL so it can be passed to + the given `login` URL more efficiently. + + :param login_url: The login URL being redirected to. + :type login_url: str + :param current_url: The URL to reduce. + :type current_url: str + """ + l_url = urlsplit(login_url) + c_url = urlsplit(current_url) + + if (not l_url.scheme or l_url.scheme == c_url.scheme) and ( + not l_url.netloc or l_url.netloc == c_url.netloc + ): + return urlunsplit(("", "", c_url.path, c_url.query, "")) + return current_url + + +def expand_login_view(login_view): + """ + Returns the url for the login view, expanding the view name to a url if + needed. + + :param login_view: The name of the login view or a URL for the login view. + :type login_view: str + """ + if login_view.startswith(("https://", "http://", "/")): + return login_view + + return url_for(login_view) + + +def login_url(login_view, next_url=None, next_field="next"): + """ + Creates a URL for redirecting to a login page. If only `login_view` is + provided, this will just return the URL for it. If `next_url` is provided, + however, this will append a ``next=URL`` parameter to the query string + so that the login view can redirect back to that URL. Flask-Login's default + unauthorized handler uses this function when redirecting to your login url. + To force the host name used, set `FORCE_HOST_FOR_REDIRECTS` to a host. This + prevents from redirecting to external sites if request headers Host or + X-Forwarded-For are present. + + :param login_view: The name of the login view. (Alternately, the actual + URL to the login view.) + :type login_view: str + :param next_url: The URL to give the login view for redirection. + :type next_url: str + :param next_field: What field to store the next URL in. (It defaults to + ``next``.) + :type next_field: str + """ + base = expand_login_view(login_view) + + if next_url is None: + return base + + parsed_result = urlsplit(base) + md = parse_qs(parsed_result.query, keep_blank_values=True) + md[next_field] = make_next_param(base, next_url) + netloc = current_app.config.get("FORCE_HOST_FOR_REDIRECTS") or parsed_result.netloc + parsed_result = parsed_result._replace( + netloc=netloc, query=urlencode(md, doseq=True) + ) + return urlunsplit(parsed_result) + + +def login_fresh(): + """ + This returns ``True`` if the current login is fresh. + """ + return session.get("_fresh", False) + + +def login_remembered(): + """ + This returns ``True`` if the current login is remembered across sessions. + """ + config = current_app.config + cookie_name = config.get("REMEMBER_COOKIE_NAME", COOKIE_NAME) + has_cookie = cookie_name in request.cookies and session.get("_remember") != "clear" + if has_cookie: + cookie = request.cookies[cookie_name] + user_id = decode_cookie(cookie) + return user_id is not None + return False + + +def login_user(user, remember=False, duration=None, force=False, fresh=True): + """ + Logs a user in. You should pass the actual user object to this. If the + user's `is_active` property is ``False``, they will not be logged in + unless `force` is ``True``. + + This will return ``True`` if the log in attempt succeeds, and ``False`` if + it fails (i.e. because the user is inactive). + + :param user: The user object to log in. + :type user: object + :param remember: Whether to remember the user after their session expires. + Defaults to ``False``. + :type remember: bool + :param duration: The amount of time before the remember cookie expires. If + ``None`` the value set in the settings is used. Defaults to ``None``. + :type duration: :class:`datetime.timedelta` + :param force: If the user is inactive, setting this to ``True`` will log + them in regardless. Defaults to ``False``. + :type force: bool + :param fresh: setting this to ``False`` will log in the user with a session + marked as not "fresh". Defaults to ``True``. + :type fresh: bool + """ + if not force and not user.is_active: + return False + + user_id = getattr(user, current_app.login_manager.id_attribute)() + session["_user_id"] = user_id + session["_fresh"] = fresh + session["_id"] = current_app.login_manager._session_identifier_generator() + + if remember: + session["_remember"] = "set" + if duration is not None: + try: + # equal to timedelta.total_seconds() but works with Python 2.6 + session["_remember_seconds"] = ( + duration.microseconds + + (duration.seconds + duration.days * 24 * 3600) * 10**6 + ) / 10.0**6 + except AttributeError as e: + raise Exception( + f"duration must be a datetime.timedelta, instead got: {duration}" + ) from e + + current_app.login_manager._update_request_context_with_user(user) + user_logged_in.send(current_app._get_current_object(), user=_get_user()) + return True + + +def logout_user(): + """ + Logs a user out. (You do not need to pass the actual user.) This will + also clean up the remember me cookie if it exists. + """ + + user = _get_user() + + if "_user_id" in session: + session.pop("_user_id") + + if "_fresh" in session: + session.pop("_fresh") + + if "_id" in session: + session.pop("_id") + + cookie_name = current_app.config.get("REMEMBER_COOKIE_NAME", COOKIE_NAME) + if cookie_name in request.cookies: + session["_remember"] = "clear" + if "_remember_seconds" in session: + session.pop("_remember_seconds") + + user_logged_out.send(current_app._get_current_object(), user=user) + + current_app.login_manager._update_request_context_with_user() + return True + + +def confirm_login(): + """ + This sets the current session as fresh. Sessions become stale when they + are reloaded from a cookie. + """ + session["_fresh"] = True + session["_id"] = current_app.login_manager._session_identifier_generator() + user_login_confirmed.send(current_app._get_current_object()) + + +def login_required(func): + """ + If you decorate a view with this, it will ensure that the current user is + logged in and authenticated before calling the actual view. (If they are + not, it calls the :attr:`LoginManager.unauthorized` callback.) For + example:: + + @app.route('/post') + @login_required + def post(): + pass + + If there are only certain times you need to require that your user is + logged in, you can do so with:: + + if not current_user.is_authenticated: + return current_app.login_manager.unauthorized() + + ...which is essentially the code that this function adds to your views. + + It can be convenient to globally turn off authentication when unit testing. + To enable this, if the application configuration variable `LOGIN_DISABLED` + is set to `True`, this decorator will be ignored. + + .. Note :: + + Per `W3 guidelines for CORS preflight requests + `_, + HTTP ``OPTIONS`` requests are exempt from login checks. + + :param func: The view function to decorate. + :type func: function + """ + + @wraps(func) + def decorated_view(*args, **kwargs): + if request.method in EXEMPT_METHODS or current_app.config.get("LOGIN_DISABLED"): + pass + elif not current_user.is_authenticated: + return current_app.login_manager.unauthorized() + + # flask 1.x compatibility + # current_app.ensure_sync is only available in Flask >= 2.0 + if callable(getattr(current_app, "ensure_sync", None)): + return current_app.ensure_sync(func)(*args, **kwargs) + return func(*args, **kwargs) + + return decorated_view + + +def fresh_login_required(func): + """ + If you decorate a view with this, it will ensure that the current user's + login is fresh - i.e. their session was not restored from a 'remember me' + cookie. Sensitive operations, like changing a password or e-mail, should + be protected with this, to impede the efforts of cookie thieves. + + If the user is not authenticated, :meth:`LoginManager.unauthorized` is + called as normal. If they are authenticated, but their session is not + fresh, it will call :meth:`LoginManager.needs_refresh` instead. (In that + case, you will need to provide a :attr:`LoginManager.refresh_view`.) + + Behaves identically to the :func:`login_required` decorator with respect + to configuration variables. + + .. Note :: + + Per `W3 guidelines for CORS preflight requests + `_, + HTTP ``OPTIONS`` requests are exempt from login checks. + + :param func: The view function to decorate. + :type func: function + """ + + @wraps(func) + def decorated_view(*args, **kwargs): + if request.method in EXEMPT_METHODS or current_app.config.get("LOGIN_DISABLED"): + pass + elif not current_user.is_authenticated: + return current_app.login_manager.unauthorized() + elif not login_fresh(): + return current_app.login_manager.needs_refresh() + try: + # current_app.ensure_sync available in Flask >= 2.0 + return current_app.ensure_sync(func)(*args, **kwargs) + except AttributeError: # pragma: no cover + return func(*args, **kwargs) + + return decorated_view + + +def set_login_view(login_view, blueprint=None): + """ + Sets the login view for the app or blueprint. If a blueprint is passed, + the login view is set for this blueprint on ``blueprint_login_views``. + + :param login_view: The user object to log in. + :type login_view: str + :param blueprint: The blueprint which this login view should be set on. + Defaults to ``None``. + :type blueprint: object + """ + + num_login_views = len(current_app.login_manager.blueprint_login_views) + if blueprint is not None or num_login_views != 0: + (current_app.login_manager.blueprint_login_views[blueprint.name]) = login_view + + if ( + current_app.login_manager.login_view is not None + and None not in current_app.login_manager.blueprint_login_views + ): + ( + current_app.login_manager.blueprint_login_views[None] + ) = current_app.login_manager.login_view + + current_app.login_manager.login_view = None + else: + current_app.login_manager.login_view = login_view + + +def _get_user(): + if has_request_context(): + if "_login_user" not in g: + current_app.login_manager._load_user() + + return g._login_user + + return None + + +def _cookie_digest(payload, key=None): + key = _secret_key(key) + + return hmac.new(key, payload.encode("utf-8"), sha512).hexdigest() + + +def _get_remote_addr(): + address = request.headers.get("X-Forwarded-For", request.remote_addr) + if address is not None: + # An 'X-Forwarded-For' header includes a comma separated list of the + # addresses, the first address being the actual remote address. + address = address.encode("utf-8").split(b",")[0].strip() + return address + + +def _create_identifier(): + user_agent = request.headers.get("User-Agent") + if user_agent is not None: + user_agent = user_agent.encode("utf-8") + base = f"{_get_remote_addr()}|{user_agent}" + if str is bytes: + base = str(base, "utf-8", errors="replace") # pragma: no cover + h = sha512() + h.update(base.encode("utf8")) + return h.hexdigest() + + +def _user_context_processor(): + return dict(current_user=_get_user()) + + +def _secret_key(key=None): + if key is None: + key = current_app.config["SECRET_KEY"] + + if isinstance(key, str): # pragma: no cover + key = key.encode("latin1") # ensure bytes + + return key diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_mail-0.10.0.dist-info/INSTALLER b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_mail-0.10.0.dist-info/INSTALLER new file mode 100644 index 000000000..a1b589e38 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_mail-0.10.0.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_mail-0.10.0.dist-info/LICENSE.txt b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_mail-0.10.0.dist-info/LICENSE.txt new file mode 100644 index 000000000..a5f1b46a9 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_mail-0.10.0.dist-info/LICENSE.txt @@ -0,0 +1,28 @@ +BSD 3-Clause License + +Copyright (c) 2010 Pallets + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_mail-0.10.0.dist-info/METADATA b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_mail-0.10.0.dist-info/METADATA new file mode 100644 index 000000000..a453f182d --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_mail-0.10.0.dist-info/METADATA @@ -0,0 +1,68 @@ +Metadata-Version: 2.1 +Name: Flask-Mail +Version: 0.10.0 +Summary: Flask extension for sending email +Author: Dan Jacob +Maintainer-email: Pallets Ecosystem +Requires-Python: >=3.8 +Description-Content-Type: text/markdown +Classifier: Development Status :: 4 - Beta +Classifier: Framework :: Flask +Classifier: License :: OSI Approved :: BSD License +Classifier: Programming Language :: Python +Classifier: Typing :: Typed +Requires-Dist: flask +Requires-Dist: blinker +Project-URL: Changes, https://flask-mail.readthedocs.io/en/latest/changes/ +Project-URL: Chat, https://discord.gg/pallets +Project-URL: Documentation, https://flask-mail.readthedocs.io +Project-URL: Source, https://github.com/pallets-eco/flask-mail/ + +# Flask-Mail + +Flask-Mail is an extension for [Flask] that makes it easy to send emails from +your application. It simplifies the process of integrating email functionality, +allowing you to focus on building great features for your application. + +[flask]: https://flask.palletsprojects.com + + +## Pallets Community Ecosystem + +> [!IMPORTANT]\ +> This project is part of the Pallets Community Ecosystem. Pallets is the open +> source organization that maintains Flask; Pallets-Eco enables community +> maintenance of related projects. If you are interested in helping maintain +> this project, please reach out on [the Pallets Discord server][discord]. + +[discord]: https://discord.gg/pallets + + +## A Simple Example + +```python +from flask import Flask +from flask_mail import Mail, Message + +app = Flask(__name__) +app.config['MAIL_SERVER'] = 'your_mail_server' +app.config['MAIL_PORT'] = 587 +app.config['MAIL_USE_TLS'] = True +app.config['MAIL_USE_SSL'] = False +app.config['MAIL_USERNAME'] = 'your_username' +app.config['MAIL_PASSWORD'] = 'your_password' +app.config['MAIL_DEFAULT_SENDER'] = 'your_email@example.com' + +mail = Mail(app) + +@app.route('/') +def send_email(): + msg = Message( + 'Hello', + recipients=['recipient@example.com'], + body='This is a test email sent from Flask-Mail!' + ) + mail.send(msg) + return 'Email sent succesfully!' +``` + diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_mail-0.10.0.dist-info/RECORD b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_mail-0.10.0.dist-info/RECORD new file mode 100644 index 000000000..022923814 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_mail-0.10.0.dist-info/RECORD @@ -0,0 +1,9 @@ +flask_mail-0.10.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +flask_mail-0.10.0.dist-info/LICENSE.txt,sha256=NjGx7g1yxwNiJgUwLiQ9Fbx4Mtmlg13y-FTw0pk5y8M,1493 +flask_mail-0.10.0.dist-info/METADATA,sha256=NeD-q9ct7BhNLCuIpeQbrlh53eUhfhGTgv7hUbFOvAg,2070 +flask_mail-0.10.0.dist-info/RECORD,, +flask_mail-0.10.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +flask_mail-0.10.0.dist-info/WHEEL,sha256=EZbGkh7Ie4PoZfRQ8I0ZuP9VklN_TvcZ6DSE5Uar4z4,81 +flask_mail/__init__.py,sha256=9kmcIKZe6ZnajZLUmexrX13kSuRv6pWwofztlU__ZlA,20841 +flask_mail/__pycache__/__init__.cpython-312.pyc,, +flask_mail/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_mail-0.10.0.dist-info/REQUESTED b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_mail-0.10.0.dist-info/REQUESTED new file mode 100644 index 000000000..e69de29bb diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_mail-0.10.0.dist-info/WHEEL b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_mail-0.10.0.dist-info/WHEEL new file mode 100644 index 000000000..3b5e64b5e --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_mail-0.10.0.dist-info/WHEEL @@ -0,0 +1,4 @@ +Wheel-Version: 1.0 +Generator: flit 3.9.0 +Root-Is-Purelib: true +Tag: py3-none-any diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_mail/__init__.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_mail/__init__.py new file mode 100644 index 000000000..697ce0f32 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_mail/__init__.py @@ -0,0 +1,660 @@ +from __future__ import annotations + +import collections.abc as c +import re +import smtplib +import time +import typing as t +import unicodedata +import warnings +from contextlib import contextmanager +from email import charset +from email import policy +from email.encoders import encode_base64 +from email.header import Header +from email.mime.base import MIMEBase +from email.mime.multipart import MIMEMultipart +from email.mime.text import MIMEText +from email.utils import formataddr +from email.utils import formatdate +from email.utils import make_msgid +from email.utils import parseaddr +from mimetypes import guess_type +from types import TracebackType + +import blinker +from flask import current_app +from flask import Flask + +if t.TYPE_CHECKING: + import typing_extensions as te + +charset.add_charset("utf-8", charset.SHORTEST, None, "utf-8") + + +class FlaskMailUnicodeDecodeError(UnicodeDecodeError): + def __init__(self, obj: t.Any, *args: t.Any) -> None: + self.obj = obj + super().__init__(*args) + + def __str__(self) -> str: + original = super().__str__() + return f"{original}. You passed in {self.obj!r} ({type(self.obj)})" + + +def force_text(s: t.Any, encoding: str = "utf-8", errors: str = "strict") -> str: + """ + Similar to smart_text, except that lazy instances are resolved to + strings, rather than kept as lazy objects. + """ + if isinstance(s, str): + return s + + try: + if isinstance(s, bytes): + out = str(s, encoding, errors) + else: + out = str(s) + except UnicodeDecodeError as e: + if not isinstance(s, Exception): + raise FlaskMailUnicodeDecodeError(s, *e.args) from e + + out = " ".join([force_text(arg, encoding, errors) for arg in s.args]) + + return out + + +def sanitize_subject(subject: str, encoding: str = "utf-8") -> str: + try: + subject.encode("ascii") + except UnicodeEncodeError: + try: + subject = Header(subject, encoding).encode() + except UnicodeEncodeError: + subject = Header(subject, "utf-8").encode() + + return subject + + +def sanitize_address(addr: str | tuple[str, str], encoding: str = "utf-8") -> str: + if isinstance(addr, str): + addr = parseaddr(force_text(addr)) + + nm, addr = addr + + try: + nm = Header(nm, encoding).encode() + except UnicodeEncodeError: + nm = Header(nm, "utf-8").encode() + + try: + addr.encode("ascii") + except UnicodeEncodeError: # IDN + if "@" in addr: + localpart, domain = addr.split("@", 1) + localpart = str(Header(localpart, encoding)) + domain = domain.encode("idna").decode("ascii") + addr = "@".join([localpart, domain]) + else: + addr = Header(addr, encoding).encode() + + return formataddr((nm, addr)) + + +def sanitize_addresses( + addresses: c.Iterable[str | tuple[str, str]], encoding: str = "utf-8" +) -> list[str]: + return [sanitize_address(e, encoding) for e in addresses] + + +def _has_newline(line: str) -> bool: + """Used by has_bad_header to check for \\r or \\n""" + return "\n" in line or "\r" in line + + +class Connection: + """Handles connection to host.""" + + def __init__(self, mail: Mail) -> None: + self.mail = mail + self.host: smtplib.SMTP | smtplib.SMTP_SSL | None = None + self.num_emails: int = 0 + + def __enter__(self) -> te.Self: + if self.mail.suppress: + self.host = None + else: + self.host = self.configure_host() + + self.num_emails = 0 + return self + + def __exit__( + self, exc_type: type[BaseException], exc_value: BaseException, tb: TracebackType + ) -> None: + if self.host is not None: + self.host.quit() + + def configure_host(self) -> smtplib.SMTP | smtplib.SMTP_SSL: + host: smtplib.SMTP | smtplib.SMTP_SSL + + if self.mail.use_ssl: + host = smtplib.SMTP_SSL(self.mail.server, self.mail.port) + else: + host = smtplib.SMTP(self.mail.server, self.mail.port) + + host.set_debuglevel(int(self.mail.debug)) + + if self.mail.use_tls: + host.starttls() + + if self.mail.username and self.mail.password: + host.login(self.mail.username, self.mail.password) + + return host + + def send( + self, message: Message, envelope_from: str | tuple[str, str] | None = None + ) -> None: + """Verifies and sends message. + + :param message: Message instance. + :param envelope_from: Email address to be used in MAIL FROM command. + """ + assert message.send_to, "No recipients have been added" + assert message.sender, ( + "The message does not specify a sender and a default sender " + "has not been configured" + ) + + if message.has_bad_headers(): + raise BadHeaderError + + if message.date is None: + message.date = time.time() + + if self.host is not None: + self.host.sendmail( + sanitize_address(envelope_from or message.sender), + list(sanitize_addresses(message.send_to)), + message.as_bytes(), + message.mail_options, + message.rcpt_options, + ) + + app = current_app._get_current_object() # type: ignore[attr-defined] + email_dispatched.send(app, message=message) + self.num_emails += 1 + + if self.num_emails == self.mail.max_emails: + self.num_emails = 0 + + if self.host: + self.host.quit() + self.host = self.configure_host() + + def send_message(self, *args: t.Any, **kwargs: t.Any) -> None: + """Shortcut for send(msg). + + Takes same arguments as Message constructor. + + :versionadded: 0.3.5 + """ + self.send(Message(*args, **kwargs)) + + +class BadHeaderError(Exception): + pass + + +class Attachment: + """Encapsulates file attachment information. + + :param filename: filename of attachment + :param content_type: file mimetype + :param data: the raw file data + :param disposition: content-disposition (if any) + + .. versionchanged:: 0.10.0 + The `data` argument is required. + + .. versionadded: 0.3.5 + """ + + def __init__( + self, + filename: str | None = None, + content_type: str | None = None, + data: str | bytes | None = None, + disposition: str | None = None, + headers: dict[str, str] | None = None, + ): + if data is None: + raise ValueError("The 'data' argument is required.") + + self.data: str | bytes = data + + if content_type is None and filename is not None: + content_type = guess_type(filename)[0] + + if content_type is None: + if isinstance(data, str): + content_type = "text/plain" + else: + content_type = "application/octet-stream" + + self.filename: str | None = filename + self.content_type: str = content_type + self.disposition: str = disposition or "attachment" + + if headers is None: + headers = {} + + self.headers: dict[str, str] = headers + + +class Message: + """Encapsulates an email message. + + :param subject: email subject header + :param recipients: list of email addresses + :param body: plain text message + :param html: HTML message + :param alts: A dict or an iterable to go through dict() that contains multipart + alternatives + :param sender: email sender address, or **MAIL_DEFAULT_SENDER** by default + :param cc: CC list + :param bcc: BCC list + :param attachments: list of Attachment instances + :param reply_to: reply-to address + :param date: send date + :param charset: message character set + :param extra_headers: A dictionary of additional headers for the message + :param mail_options: A list of ESMTP options to be used in MAIL FROM command + :param rcpt_options: A list of ESMTP options to be used in RCPT commands + """ + + def __init__( + self, + subject: str = "", + recipients: list[str | tuple[str, str]] | None = None, + body: str | None = None, + html: str | None = None, + alts: dict[str, str] | c.Iterable[tuple[str, str]] | None = None, + sender: str | tuple[str, str] | None = None, + cc: list[str | tuple[str, str]] | None = None, + bcc: list[str | tuple[str, str]] | None = None, + attachments: list[Attachment] | None = None, + reply_to: str | tuple[str, str] | None = None, + date: float | None = None, + charset: str | None = None, + extra_headers: dict[str, str] | None = None, + mail_options: list[str] | None = None, + rcpt_options: list[str] | None = None, + ): + sender = sender or current_app.extensions["mail"].default_sender + + if isinstance(sender, tuple): + sender = f"{sender[0]} <{sender[1]}>" + + self.recipients: list[str | tuple[str, str]] = recipients or [] + self.subject: str = subject + self.sender: str | tuple[str, str] = sender # pyright: ignore + self.reply_to: str | tuple[str, str] | None = reply_to + self.cc: list[str | tuple[str, str]] = cc or [] + self.bcc: list[str | tuple[str, str]] = bcc or [] + self.body: str | None = body + self.alts: dict[str, str] = dict(alts or {}) + self.html: str | None = html + self.date: float | None = date + self.msgId: str = make_msgid() + self.charset: str | None = charset + self.extra_headers: dict[str, str] | None = extra_headers + self.mail_options: list[str] = mail_options or [] + self.rcpt_options: list[str] = rcpt_options or [] + self.attachments: list[Attachment] = attachments or [] + + @property + def send_to(self) -> set[str | tuple[str, str]]: + out = set(self.recipients) + + if self.bcc: + out.update(self.bcc) + + if self.cc: + out.update(self.cc) + + return out + + @property + def html(self) -> str | None: # pyright: ignore + return self.alts.get("html") + + @html.setter + def html(self, value: str | None) -> None: # pyright: ignore + if value is None: + self.alts.pop("html", None) + else: + self.alts["html"] = value + + def _mimetext(self, text: str | None, subtype: str = "plain") -> MIMEText: + """Creates a MIMEText object with the given subtype (default: 'plain') + If the text is unicode, the utf-8 charset is used. + """ + charset = self.charset or "utf-8" + return MIMEText(text, _subtype=subtype, _charset=charset) # type: ignore[arg-type] + + def _message(self) -> MIMEBase: + """Creates the email""" + ascii_attachments = current_app.extensions["mail"].ascii_attachments + encoding = self.charset or "utf-8" + attachments = self.attachments or [] + msg: MIMEBase + + if len(attachments) == 0 and not self.alts: + # No html content and zero attachments means plain text + msg = self._mimetext(self.body) + elif len(attachments) > 0 and not self.alts: + # No html and at least one attachment means multipart + msg = MIMEMultipart() + msg.attach(self._mimetext(self.body)) + else: + # Anything else + msg = MIMEMultipart() + alternative = MIMEMultipart("alternative") + alternative.attach(self._mimetext(self.body, "plain")) + + for mimetype, content in self.alts.items(): + alternative.attach(self._mimetext(content, mimetype)) + + msg.attach(alternative) + + if self.subject: + msg["Subject"] = sanitize_subject(force_text(self.subject), encoding) + + msg["From"] = sanitize_address(self.sender, encoding) + msg["To"] = ", ".join(list(set(sanitize_addresses(self.recipients, encoding)))) + msg["Date"] = formatdate(self.date, localtime=True) + # see RFC 5322 section 3.6.4. + msg["Message-ID"] = self.msgId + + if self.cc: + msg["Cc"] = ", ".join(list(set(sanitize_addresses(self.cc, encoding)))) + + if self.reply_to: + msg["Reply-To"] = sanitize_address(self.reply_to, encoding) + + if self.extra_headers: + for k, v in self.extra_headers.items(): + msg[k] = v + + SPACES = re.compile(r"[\s]+", re.UNICODE) + + for attachment in attachments: + f = MIMEBase(*attachment.content_type.split("/")) + f.set_payload(attachment.data) + encode_base64(f) + + if attachment.filename is not None: + filename = attachment.filename + + if ascii_attachments: + # force filename to ascii + filename = unicodedata.normalize("NFKD", attachment.filename) + filename = filename.encode("ascii", "ignore").decode("ascii") + filename = SPACES.sub(" ", filename).strip() + + try: + filename.encode("ascii") + except UnicodeEncodeError: + f.add_header( + "Content-Disposition", + attachment.disposition, + filename=("UTF8", "", filename), + ) + else: + f.add_header( + "Content-Disposition", attachment.disposition, filename=filename + ) + + for key, value in attachment.headers.items(): + f.add_header(key, value) + + msg.attach(f) + + msg.policy = policy.SMTP + return msg + + def as_string(self) -> str: + return self._message().as_string() + + def as_bytes(self) -> bytes: + return self._message().as_bytes() + + def __str__(self) -> str: + return self.as_string() + + def __bytes__(self) -> bytes: + return self.as_bytes() + + def has_bad_headers(self) -> bool: + """Checks for bad headers i.e. newlines in subject, sender or recipients. + RFC5322: Allows multiline CRLF with trailing whitespace (FWS) in headers + """ + headers = [self.sender, *self.recipients] + + if self.reply_to: + headers.append(self.reply_to) + + for header in headers: + if isinstance(header, tuple): + header = f"{header[0]} <{header[1]}>" + + if _has_newline(header): + return True + + if self.subject: + if _has_newline(self.subject): + for linenum, line in enumerate(self.subject.split("\r\n")): + if not line: + return True + if linenum > 0 and line[0] not in "\t ": + return True + if _has_newline(line): + return True + if len(line.strip()) == 0: + return True + + return False + + def is_bad_headers(self) -> bool: + warnings.warn( + "'is_bad_headers' is renamed to 'has_bad_headers'. The old name is" + " deprecated and will be removed in Flask-Mail 1.0.", + DeprecationWarning, + stacklevel=2, + ) + return self.has_bad_headers() + + def send(self, connection: Connection) -> None: + """Verifies and sends the message.""" + + connection.send(self) + + def add_recipient(self, recipient: str | tuple[str, str]) -> None: + """Adds another recipient to the message. + + :param recipient: email address of recipient. + """ + + self.recipients.append(recipient) + + def attach( + self, + filename: str | None = None, + content_type: str | None = None, + data: str | bytes | None = None, + disposition: str | None = None, + headers: dict[str, str] | None = None, + ) -> None: + """Adds an attachment to the message. + + :param filename: filename of attachment + :param content_type: file mimetype + :param data: the raw file data + :param disposition: content-disposition (if any) + """ + self.attachments.append( + Attachment(filename, content_type, data, disposition, headers) + ) + + +class _MailMixin: + @contextmanager + def record_messages(self) -> c.Iterator[list[Message]]: + """Records all messages. Use in unit tests for example:: + + with mail.record_messages() as outbox: + response = app.test_client.get("/email-sending-view/") + assert len(outbox) == 1 + assert outbox[0].subject == "testing" + + :versionadded: 0.4 + """ + outbox = [] + + def record(app: Flask, message: Message) -> None: + outbox.append(message) + + with email_dispatched.connected_to(record): + yield outbox + + def send(self, message: Message) -> None: + """Sends a single message instance. If TESTING is True the message will + not actually be sent. + + :param message: a Message instance. + """ + + with self.connect() as connection: + message.send(connection) + + def send_message(self, *args: t.Any, **kwargs: t.Any) -> None: + """Shortcut for send(msg). + + Takes same arguments as Message constructor. + + :versionadded: 0.3.5 + """ + + self.send(Message(*args, **kwargs)) + + def connect(self) -> Connection: + """Opens a connection to the mail host.""" + app = getattr(self, "app", None) or current_app + + try: + return Connection(app.extensions["mail"]) + except KeyError as err: + raise RuntimeError( + "The current application was not configured with Flask-Mail" + ) from err + + +class _Mail(_MailMixin): + def __init__( + self, + server: str, + username: str | None, + password: str | None, + port: int | None, + use_tls: bool, + use_ssl: bool, + default_sender: str | None, + debug: int, + max_emails: int | None, + suppress: bool, + ascii_attachments: bool, + ): + self.server = server + self.username = username + self.password = password + self.port = port + self.use_tls = use_tls + self.use_ssl = use_ssl + self.default_sender = default_sender + self.debug = debug + self.max_emails = max_emails + self.suppress = suppress + self.ascii_attachments = ascii_attachments + + +class Mail(_MailMixin): + """Manages email messaging.""" + + def __init__(self, app: Flask | None = None) -> None: + self.app = app + + if app is not None: + self.state: _Mail | None = self.init_app(app) + else: + self.state = None + + def init_mail( + self, config: dict[str, t.Any], debug: bool | int = False, testing: bool = False + ) -> _Mail: + return _Mail( + config.get("MAIL_SERVER", "127.0.0.1"), + config.get("MAIL_USERNAME"), + config.get("MAIL_PASSWORD"), + config.get("MAIL_PORT", 25), + config.get("MAIL_USE_TLS", False), + config.get("MAIL_USE_SSL", False), + config.get("MAIL_DEFAULT_SENDER"), + int(config.get("MAIL_DEBUG", debug)), + config.get("MAIL_MAX_EMAILS"), + config.get("MAIL_SUPPRESS_SEND", testing), + config.get("MAIL_ASCII_ATTACHMENTS", False), + ) + + def init_app(self, app: Flask) -> _Mail: + """Initializes your mail settings from the application settings. + + You can use this if you want to set up your Mail instance + at configuration time. + """ + state = self.init_mail(app.config, app.debug, app.testing) + + # register extension with app + app.extensions = getattr(app, "extensions", {}) + app.extensions["mail"] = state + return state + + def __getattr__(self, name: str) -> t.Any: + return getattr(self.state, name, None) + + +signals: blinker.Namespace = blinker.Namespace() +email_dispatched: blinker.NamedSignal = signals.signal( + "email-dispatched", + doc=""" +Signal sent when an email is dispatched. This signal will also be sent +in testing mode, even though the email will not actually be sent. +""", +) + + +def __getattr__(name: str) -> t.Any: + if name == "__version__": + import importlib.metadata + + warnings.warn( + "The '__version__' attribute is deprecated and will be removed in" + " Flask-Mail 1.0. Use feature detection or" + " 'importlib.metadata.version(\"flask-mail\")' instead.", + DeprecationWarning, + stacklevel=2, + ) + return importlib.metadata.version("flask-mail") + + raise AttributeError(name) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_mail/py.typed b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_mail/py.typed new file mode 100644 index 000000000..e69de29bb diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_sqlalchemy-3.1.1.dist-info/INSTALLER b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_sqlalchemy-3.1.1.dist-info/INSTALLER new file mode 100644 index 000000000..a1b589e38 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_sqlalchemy-3.1.1.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_sqlalchemy-3.1.1.dist-info/LICENSE.rst b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_sqlalchemy-3.1.1.dist-info/LICENSE.rst new file mode 100644 index 000000000..9d227a0cc --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_sqlalchemy-3.1.1.dist-info/LICENSE.rst @@ -0,0 +1,28 @@ +Copyright 2010 Pallets + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A +PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED +TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_sqlalchemy-3.1.1.dist-info/METADATA b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_sqlalchemy-3.1.1.dist-info/METADATA new file mode 100644 index 000000000..92f239cd9 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_sqlalchemy-3.1.1.dist-info/METADATA @@ -0,0 +1,109 @@ +Metadata-Version: 2.1 +Name: Flask-SQLAlchemy +Version: 3.1.1 +Summary: Add SQLAlchemy support to your Flask application. +Maintainer-email: Pallets +Requires-Python: >=3.8 +Description-Content-Type: text/x-rst +Classifier: Development Status :: 5 - Production/Stable +Classifier: Environment :: Web Environment +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: BSD License +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: Python +Classifier: Topic :: Internet :: WWW/HTTP :: Dynamic Content +Requires-Dist: flask>=2.2.5 +Requires-Dist: sqlalchemy>=2.0.16 +Project-URL: Changes, https://flask-sqlalchemy.palletsprojects.com/changes/ +Project-URL: Chat, https://discord.gg/pallets +Project-URL: Documentation, https://flask-sqlalchemy.palletsprojects.com +Project-URL: Donate, https://palletsprojects.com/donate +Project-URL: Issue Tracker, https://github.com/pallets-eco/flask-sqlalchemy/issues/ +Project-URL: Source Code, https://github.com/pallets-eco/flask-sqlalchemy/ + +Flask-SQLAlchemy +================ + +Flask-SQLAlchemy is an extension for `Flask`_ that adds support for +`SQLAlchemy`_ to your application. It aims to simplify using SQLAlchemy +with Flask by providing useful defaults and extra helpers that make it +easier to accomplish common tasks. + +.. _Flask: https://palletsprojects.com/p/flask/ +.. _SQLAlchemy: https://www.sqlalchemy.org + + +Installing +---------- + +Install and update using `pip`_: + +.. code-block:: text + + $ pip install -U Flask-SQLAlchemy + +.. _pip: https://pip.pypa.io/en/stable/getting-started/ + + +A Simple Example +---------------- + +.. code-block:: python + + from flask import Flask + from flask_sqlalchemy import SQLAlchemy + from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column + + app = Flask(__name__) + app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///example.sqlite" + + class Base(DeclarativeBase): + pass + + db = SQLAlchemy(app, model_class=Base) + + class User(db.Model): + id: Mapped[int] = mapped_column(db.Integer, primary_key=True) + username: Mapped[str] = mapped_column(db.String, unique=True, nullable=False) + + with app.app_context(): + db.create_all() + + db.session.add(User(username="example")) + db.session.commit() + + users = db.session.execute(db.select(User)).scalars() + + +Contributing +------------ + +For guidance on setting up a development environment and how to make a +contribution to Flask-SQLAlchemy, see the `contributing guidelines`_. + +.. _contributing guidelines: https://github.com/pallets-eco/flask-sqlalchemy/blob/main/CONTRIBUTING.rst + + +Donate +------ + +The Pallets organization develops and supports Flask-SQLAlchemy and +other popular packages. In order to grow the community of contributors +and users, and allow the maintainers to devote more time to the +projects, `please donate today`_. + +.. _please donate today: https://palletsprojects.com/donate + + +Links +----- + +- Documentation: https://flask-sqlalchemy.palletsprojects.com/ +- Changes: https://flask-sqlalchemy.palletsprojects.com/changes/ +- PyPI Releases: https://pypi.org/project/Flask-SQLAlchemy/ +- Source Code: https://github.com/pallets-eco/flask-sqlalchemy/ +- Issue Tracker: https://github.com/pallets-eco/flask-sqlalchemy/issues/ +- Website: https://palletsprojects.com/ +- Twitter: https://twitter.com/PalletsTeam +- Chat: https://discord.gg/pallets + diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_sqlalchemy-3.1.1.dist-info/RECORD b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_sqlalchemy-3.1.1.dist-info/RECORD new file mode 100644 index 000000000..46e3d0553 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_sqlalchemy-3.1.1.dist-info/RECORD @@ -0,0 +1,27 @@ +flask_sqlalchemy-3.1.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +flask_sqlalchemy-3.1.1.dist-info/LICENSE.rst,sha256=SJqOEQhQntmKN7uYPhHg9-HTHwvY-Zp5yESOf_N9B-o,1475 +flask_sqlalchemy-3.1.1.dist-info/METADATA,sha256=lBxR1akBt7n9XBjIVTL2OV52OhCfFrb-Mqtoe0DCbR8,3432 +flask_sqlalchemy-3.1.1.dist-info/RECORD,, +flask_sqlalchemy-3.1.1.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +flask_sqlalchemy-3.1.1.dist-info/WHEEL,sha256=EZbGkh7Ie4PoZfRQ8I0ZuP9VklN_TvcZ6DSE5Uar4z4,81 +flask_sqlalchemy/__init__.py,sha256=he_w4qQQVS2Z1ms5GCTptDTXNOXBXw0n8zSuWCp8n6Y,653 +flask_sqlalchemy/__pycache__/__init__.cpython-312.pyc,, +flask_sqlalchemy/__pycache__/cli.cpython-312.pyc,, +flask_sqlalchemy/__pycache__/extension.cpython-312.pyc,, +flask_sqlalchemy/__pycache__/model.cpython-312.pyc,, +flask_sqlalchemy/__pycache__/pagination.cpython-312.pyc,, +flask_sqlalchemy/__pycache__/query.cpython-312.pyc,, +flask_sqlalchemy/__pycache__/record_queries.cpython-312.pyc,, +flask_sqlalchemy/__pycache__/session.cpython-312.pyc,, +flask_sqlalchemy/__pycache__/table.cpython-312.pyc,, +flask_sqlalchemy/__pycache__/track_modifications.cpython-312.pyc,, +flask_sqlalchemy/cli.py,sha256=pg3QDxP36GW2qnwe_CpPtkRhPchyVSGM6zlBNWuNCFE,484 +flask_sqlalchemy/extension.py,sha256=71tP_kNtb5VgZdafy_OH1sWdZOA6PaT7cJqX7tKgZ-k,38261 +flask_sqlalchemy/model.py,sha256=_mSisC2Eni0TgTyFWeN_O4LIexTeP_sVTdxh03yMK50,11461 +flask_sqlalchemy/pagination.py,sha256=JFpllrqkRkwacb8DAmQWaz9wsvQa0dypfSkhUDSC2ws,11119 +flask_sqlalchemy/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +flask_sqlalchemy/query.py,sha256=Uls9qbmnpb9Vba43EDfsRP17eHJ0X4VG7SE22tH5R3g,3748 +flask_sqlalchemy/record_queries.py,sha256=ouS1ayj16h76LJprx13iYdoFZbm6m8OncrOgAVbG1Sk,3520 +flask_sqlalchemy/session.py,sha256=pBbtN8iDc8yuGVt0k18BvZHh2uEI7QPzZXO7eXrRi1g,3426 +flask_sqlalchemy/table.py,sha256=wAPOy8qwyAxpMwOIUJY4iMOultzz2W0D6xvBkQ7U2CE,859 +flask_sqlalchemy/track_modifications.py,sha256=yieyozj7IiVzwnAGZ-ZrgqrzjrUfG0kPrXBfW_hStSU,2755 diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_sqlalchemy-3.1.1.dist-info/REQUESTED b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_sqlalchemy-3.1.1.dist-info/REQUESTED new file mode 100644 index 000000000..e69de29bb diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_sqlalchemy-3.1.1.dist-info/WHEEL b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_sqlalchemy-3.1.1.dist-info/WHEEL new file mode 100644 index 000000000..3b5e64b5e --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_sqlalchemy-3.1.1.dist-info/WHEEL @@ -0,0 +1,4 @@ +Wheel-Version: 1.0 +Generator: flit 3.9.0 +Root-Is-Purelib: true +Tag: py3-none-any diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_sqlalchemy/__init__.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_sqlalchemy/__init__.py new file mode 100644 index 000000000..c2fa0591c --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_sqlalchemy/__init__.py @@ -0,0 +1,26 @@ +from __future__ import annotations + +import typing as t + +from .extension import SQLAlchemy + +__all__ = [ + "SQLAlchemy", +] + + +def __getattr__(name: str) -> t.Any: + if name == "__version__": + import importlib.metadata + import warnings + + warnings.warn( + "The '__version__' attribute is deprecated and will be removed in" + " Flask-SQLAlchemy 3.2. Use feature detection or" + " 'importlib.metadata.version(\"flask-sqlalchemy\")' instead.", + DeprecationWarning, + stacklevel=2, + ) + return importlib.metadata.version("flask-sqlalchemy") + + raise AttributeError(name) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_sqlalchemy/cli.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_sqlalchemy/cli.py new file mode 100644 index 000000000..d7d7e4bef --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_sqlalchemy/cli.py @@ -0,0 +1,16 @@ +from __future__ import annotations + +import typing as t + +from flask import current_app + + +def add_models_to_shell() -> dict[str, t.Any]: + """Registered with :meth:`~flask.Flask.shell_context_processor` if + ``add_models_to_shell`` is enabled. Adds the ``db`` instance and all model classes + to ``flask shell``. + """ + db = current_app.extensions["sqlalchemy"] + out = {m.class_.__name__: m.class_ for m in db.Model._sa_registry.mappers} + out["db"] = db + return out diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_sqlalchemy/extension.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_sqlalchemy/extension.py new file mode 100644 index 000000000..43e1b9a44 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_sqlalchemy/extension.py @@ -0,0 +1,1008 @@ +from __future__ import annotations + +import os +import types +import typing as t +import warnings +from weakref import WeakKeyDictionary + +import sqlalchemy as sa +import sqlalchemy.event as sa_event +import sqlalchemy.exc as sa_exc +import sqlalchemy.orm as sa_orm +from flask import abort +from flask import current_app +from flask import Flask +from flask import has_app_context + +from .model import _QueryProperty +from .model import BindMixin +from .model import DefaultMeta +from .model import DefaultMetaNoName +from .model import Model +from .model import NameMixin +from .pagination import Pagination +from .pagination import SelectPagination +from .query import Query +from .session import _app_ctx_id +from .session import Session +from .table import _Table + +_O = t.TypeVar("_O", bound=object) # Based on sqlalchemy.orm._typing.py + + +# Type accepted for model_class argument +_FSA_MCT = t.TypeVar( + "_FSA_MCT", + bound=t.Union[ + t.Type[Model], + sa_orm.DeclarativeMeta, + t.Type[sa_orm.DeclarativeBase], + t.Type[sa_orm.DeclarativeBaseNoMeta], + ], +) + + +# Type returned by make_declarative_base +class _FSAModel(Model): + metadata: sa.MetaData + + +def _get_2x_declarative_bases( + model_class: _FSA_MCT, +) -> list[t.Type[t.Union[sa_orm.DeclarativeBase, sa_orm.DeclarativeBaseNoMeta]]]: + return [ + b + for b in model_class.__bases__ + if issubclass(b, (sa_orm.DeclarativeBase, sa_orm.DeclarativeBaseNoMeta)) + ] + + +class SQLAlchemy: + """Integrates SQLAlchemy with Flask. This handles setting up one or more engines, + associating tables and models with specific engines, and cleaning up connections and + sessions after each request. + + Only the engine configuration is specific to each application, other things like + the model, table, metadata, and session are shared for all applications using that + extension instance. Call :meth:`init_app` to configure the extension on an + application. + + After creating the extension, create model classes by subclassing :attr:`Model`, and + table classes with :attr:`Table`. These can be accessed before :meth:`init_app` is + called, making it possible to define the models separately from the application. + + Accessing :attr:`session` and :attr:`engine` requires an active Flask application + context. This includes methods like :meth:`create_all` which use the engine. + + This class also provides access to names in SQLAlchemy's ``sqlalchemy`` and + ``sqlalchemy.orm`` modules. For example, you can use ``db.Column`` and + ``db.relationship`` instead of importing ``sqlalchemy.Column`` and + ``sqlalchemy.orm.relationship``. This can be convenient when defining models. + + :param app: Call :meth:`init_app` on this Flask application now. + :param metadata: Use this as the default :class:`sqlalchemy.schema.MetaData`. Useful + for setting a naming convention. + :param session_options: Arguments used by :attr:`session` to create each session + instance. A ``scopefunc`` key will be passed to the scoped session, not the + session instance. See :class:`sqlalchemy.orm.sessionmaker` for a list of + arguments. + :param query_class: Use this as the default query class for models and dynamic + relationships. The query interface is considered legacy in SQLAlchemy. + :param model_class: Use this as the model base class when creating the declarative + model class :attr:`Model`. Can also be a fully created declarative model class + for further customization. + :param engine_options: Default arguments used when creating every engine. These are + lower precedence than application config. See :func:`sqlalchemy.create_engine` + for a list of arguments. + :param add_models_to_shell: Add the ``db`` instance and all model classes to + ``flask shell``. + + .. versionchanged:: 3.1.0 + The ``metadata`` parameter can still be used with SQLAlchemy 1.x classes, + but is ignored when using SQLAlchemy 2.x style of declarative classes. + Instead, specify metadata on your Base class. + + .. versionchanged:: 3.1.0 + Added the ``disable_autonaming`` parameter. + + .. versionchanged:: 3.1.0 + Changed ``model_class`` parameter to accepta SQLAlchemy 2.x + declarative base subclass. + + .. versionchanged:: 3.0 + An active Flask application context is always required to access ``session`` and + ``engine``. + + .. versionchanged:: 3.0 + Separate ``metadata`` are used for each bind key. + + .. versionchanged:: 3.0 + The ``engine_options`` parameter is applied as defaults before per-engine + configuration. + + .. versionchanged:: 3.0 + The session class can be customized in ``session_options``. + + .. versionchanged:: 3.0 + Added the ``add_models_to_shell`` parameter. + + .. versionchanged:: 3.0 + Engines are created when calling ``init_app`` rather than the first time they + are accessed. + + .. versionchanged:: 3.0 + All parameters except ``app`` are keyword-only. + + .. versionchanged:: 3.0 + The extension instance is stored directly as ``app.extensions["sqlalchemy"]``. + + .. versionchanged:: 3.0 + Setup methods are renamed with a leading underscore. They are considered + internal interfaces which may change at any time. + + .. versionchanged:: 3.0 + Removed the ``use_native_unicode`` parameter and config. + + .. versionchanged:: 2.4 + Added the ``engine_options`` parameter. + + .. versionchanged:: 2.1 + Added the ``metadata``, ``query_class``, and ``model_class`` parameters. + + .. versionchanged:: 2.1 + Use the same query class across ``session``, ``Model.query`` and + ``Query``. + + .. versionchanged:: 0.16 + ``scopefunc`` is accepted in ``session_options``. + + .. versionchanged:: 0.10 + Added the ``session_options`` parameter. + """ + + def __init__( + self, + app: Flask | None = None, + *, + metadata: sa.MetaData | None = None, + session_options: dict[str, t.Any] | None = None, + query_class: type[Query] = Query, + model_class: _FSA_MCT = Model, # type: ignore[assignment] + engine_options: dict[str, t.Any] | None = None, + add_models_to_shell: bool = True, + disable_autonaming: bool = False, + ): + if session_options is None: + session_options = {} + + self.Query = query_class + """The default query class used by ``Model.query`` and ``lazy="dynamic"`` + relationships. + + .. warning:: + The query interface is considered legacy in SQLAlchemy. + + Customize this by passing the ``query_class`` parameter to the extension. + """ + + self.session = self._make_scoped_session(session_options) + """A :class:`sqlalchemy.orm.scoping.scoped_session` that creates instances of + :class:`.Session` scoped to the current Flask application context. The session + will be removed, returning the engine connection to the pool, when the + application context exits. + + Customize this by passing ``session_options`` to the extension. + + This requires that a Flask application context is active. + + .. versionchanged:: 3.0 + The session is scoped to the current app context. + """ + + self.metadatas: dict[str | None, sa.MetaData] = {} + """Map of bind keys to :class:`sqlalchemy.schema.MetaData` instances. The + ``None`` key refers to the default metadata, and is available as + :attr:`metadata`. + + Customize the default metadata by passing the ``metadata`` parameter to the + extension. This can be used to set a naming convention. When metadata for + another bind key is created, it copies the default's naming convention. + + .. versionadded:: 3.0 + """ + + if metadata is not None: + if len(_get_2x_declarative_bases(model_class)) > 0: + warnings.warn( + "When using SQLAlchemy 2.x style of declarative classes," + " the `metadata` should be an attribute of the base class." + "The metadata passed into SQLAlchemy() is ignored.", + DeprecationWarning, + stacklevel=2, + ) + else: + metadata.info["bind_key"] = None + self.metadatas[None] = metadata + + self.Table = self._make_table_class() + """A :class:`sqlalchemy.schema.Table` class that chooses a metadata + automatically. + + Unlike the base ``Table``, the ``metadata`` argument is not required. If it is + not given, it is selected based on the ``bind_key`` argument. + + :param bind_key: Used to select a different metadata. + :param args: Arguments passed to the base class. These are typically the table's + name, columns, and constraints. + :param kwargs: Arguments passed to the base class. + + .. versionchanged:: 3.0 + This is a subclass of SQLAlchemy's ``Table`` rather than a function. + """ + + self.Model = self._make_declarative_base( + model_class, disable_autonaming=disable_autonaming + ) + """A SQLAlchemy declarative model class. Subclass this to define database + models. + + If a model does not set ``__tablename__``, it will be generated by converting + the class name from ``CamelCase`` to ``snake_case``. It will not be generated + if the model looks like it uses single-table inheritance. + + If a model or parent class sets ``__bind_key__``, it will use that metadata and + database engine. Otherwise, it will use the default :attr:`metadata` and + :attr:`engine`. This is ignored if the model sets ``metadata`` or ``__table__``. + + For code using the SQLAlchemy 1.x API, customize this model by subclassing + :class:`.Model` and passing the ``model_class`` parameter to the extension. + A fully created declarative model class can be + passed as well, to use a custom metaclass. + + For code using the SQLAlchemy 2.x API, customize this model by subclassing + :class:`sqlalchemy.orm.DeclarativeBase` or + :class:`sqlalchemy.orm.DeclarativeBaseNoMeta` + and passing the ``model_class`` parameter to the extension. + """ + + if engine_options is None: + engine_options = {} + + self._engine_options = engine_options + self._app_engines: WeakKeyDictionary[Flask, dict[str | None, sa.engine.Engine]] + self._app_engines = WeakKeyDictionary() + self._add_models_to_shell = add_models_to_shell + + if app is not None: + self.init_app(app) + + def __repr__(self) -> str: + if not has_app_context(): + return f"<{type(self).__name__}>" + + message = f"{type(self).__name__} {self.engine.url}" + + if len(self.engines) > 1: + message = f"{message} +{len(self.engines) - 1}" + + return f"<{message}>" + + def init_app(self, app: Flask) -> None: + """Initialize a Flask application for use with this extension instance. This + must be called before accessing the database engine or session with the app. + + This sets default configuration values, then configures the extension on the + application and creates the engines for each bind key. Therefore, this must be + called after the application has been configured. Changes to application config + after this call will not be reflected. + + The following keys from ``app.config`` are used: + + - :data:`.SQLALCHEMY_DATABASE_URI` + - :data:`.SQLALCHEMY_ENGINE_OPTIONS` + - :data:`.SQLALCHEMY_ECHO` + - :data:`.SQLALCHEMY_BINDS` + - :data:`.SQLALCHEMY_RECORD_QUERIES` + - :data:`.SQLALCHEMY_TRACK_MODIFICATIONS` + + :param app: The Flask application to initialize. + """ + if "sqlalchemy" in app.extensions: + raise RuntimeError( + "A 'SQLAlchemy' instance has already been registered on this Flask app." + " Import and use that instance instead." + ) + + app.extensions["sqlalchemy"] = self + app.teardown_appcontext(self._teardown_session) + + if self._add_models_to_shell: + from .cli import add_models_to_shell + + app.shell_context_processor(add_models_to_shell) + + basic_uri: str | sa.engine.URL | None = app.config.setdefault( + "SQLALCHEMY_DATABASE_URI", None + ) + basic_engine_options = self._engine_options.copy() + basic_engine_options.update( + app.config.setdefault("SQLALCHEMY_ENGINE_OPTIONS", {}) + ) + echo: bool = app.config.setdefault("SQLALCHEMY_ECHO", False) + config_binds: dict[ + str | None, str | sa.engine.URL | dict[str, t.Any] + ] = app.config.setdefault("SQLALCHEMY_BINDS", {}) + engine_options: dict[str | None, dict[str, t.Any]] = {} + + # Build the engine config for each bind key. + for key, value in config_binds.items(): + engine_options[key] = self._engine_options.copy() + + if isinstance(value, (str, sa.engine.URL)): + engine_options[key]["url"] = value + else: + engine_options[key].update(value) + + # Build the engine config for the default bind key. + if basic_uri is not None: + basic_engine_options["url"] = basic_uri + + if "url" in basic_engine_options: + engine_options.setdefault(None, {}).update(basic_engine_options) + + if not engine_options: + raise RuntimeError( + "Either 'SQLALCHEMY_DATABASE_URI' or 'SQLALCHEMY_BINDS' must be set." + ) + + engines = self._app_engines.setdefault(app, {}) + + # Dispose existing engines in case init_app is called again. + if engines: + for engine in engines.values(): + engine.dispose() + + engines.clear() + + # Create the metadata and engine for each bind key. + for key, options in engine_options.items(): + self._make_metadata(key) + options.setdefault("echo", echo) + options.setdefault("echo_pool", echo) + self._apply_driver_defaults(options, app) + engines[key] = self._make_engine(key, options, app) + + if app.config.setdefault("SQLALCHEMY_RECORD_QUERIES", False): + from . import record_queries + + for engine in engines.values(): + record_queries._listen(engine) + + if app.config.setdefault("SQLALCHEMY_TRACK_MODIFICATIONS", False): + from . import track_modifications + + track_modifications._listen(self.session) + + def _make_scoped_session( + self, options: dict[str, t.Any] + ) -> sa_orm.scoped_session[Session]: + """Create a :class:`sqlalchemy.orm.scoping.scoped_session` around the factory + from :meth:`_make_session_factory`. The result is available as :attr:`session`. + + The scope function can be customized using the ``scopefunc`` key in the + ``session_options`` parameter to the extension. By default it uses the current + thread or greenlet id. + + This method is used for internal setup. Its signature may change at any time. + + :meta private: + + :param options: The ``session_options`` parameter from ``__init__``. Keyword + arguments passed to the session factory. A ``scopefunc`` key is popped. + + .. versionchanged:: 3.0 + The session is scoped to the current app context. + + .. versionchanged:: 3.0 + Renamed from ``create_scoped_session``, this method is internal. + """ + scope = options.pop("scopefunc", _app_ctx_id) + factory = self._make_session_factory(options) + return sa_orm.scoped_session(factory, scope) + + def _make_session_factory( + self, options: dict[str, t.Any] + ) -> sa_orm.sessionmaker[Session]: + """Create the SQLAlchemy :class:`sqlalchemy.orm.sessionmaker` used by + :meth:`_make_scoped_session`. + + To customize, pass the ``session_options`` parameter to :class:`SQLAlchemy`. To + customize the session class, subclass :class:`.Session` and pass it as the + ``class_`` key. + + This method is used for internal setup. Its signature may change at any time. + + :meta private: + + :param options: The ``session_options`` parameter from ``__init__``. Keyword + arguments passed to the session factory. + + .. versionchanged:: 3.0 + The session class can be customized. + + .. versionchanged:: 3.0 + Renamed from ``create_session``, this method is internal. + """ + options.setdefault("class_", Session) + options.setdefault("query_cls", self.Query) + return sa_orm.sessionmaker(db=self, **options) + + def _teardown_session(self, exc: BaseException | None) -> None: + """Remove the current session at the end of the request. + + :meta private: + + .. versionadded:: 3.0 + """ + self.session.remove() + + def _make_metadata(self, bind_key: str | None) -> sa.MetaData: + """Get or create a :class:`sqlalchemy.schema.MetaData` for the given bind key. + + This method is used for internal setup. Its signature may change at any time. + + :meta private: + + :param bind_key: The name of the metadata being created. + + .. versionadded:: 3.0 + """ + if bind_key in self.metadatas: + return self.metadatas[bind_key] + + if bind_key is not None: + # Copy the naming convention from the default metadata. + naming_convention = self._make_metadata(None).naming_convention + else: + naming_convention = None + + # Set the bind key in info to be used by session.get_bind. + metadata = sa.MetaData( + naming_convention=naming_convention, info={"bind_key": bind_key} + ) + self.metadatas[bind_key] = metadata + return metadata + + def _make_table_class(self) -> type[_Table]: + """Create a SQLAlchemy :class:`sqlalchemy.schema.Table` class that chooses a + metadata automatically based on the ``bind_key``. The result is available as + :attr:`Table`. + + This method is used for internal setup. Its signature may change at any time. + + :meta private: + + .. versionadded:: 3.0 + """ + + class Table(_Table): + def __new__( + cls, *args: t.Any, bind_key: str | None = None, **kwargs: t.Any + ) -> Table: + # If a metadata arg is passed, go directly to the base Table. Also do + # this for no args so the correct error is shown. + if not args or (len(args) >= 2 and isinstance(args[1], sa.MetaData)): + return super().__new__(cls, *args, **kwargs) + + metadata = self._make_metadata(bind_key) + return super().__new__(cls, *[args[0], metadata, *args[1:]], **kwargs) + + return Table + + def _make_declarative_base( + self, + model_class: _FSA_MCT, + disable_autonaming: bool = False, + ) -> t.Type[_FSAModel]: + """Create a SQLAlchemy declarative model class. The result is available as + :attr:`Model`. + + To customize, subclass :class:`.Model` and pass it as ``model_class`` to + :class:`SQLAlchemy`. To customize at the metaclass level, pass an already + created declarative model class as ``model_class``. + + This method is used for internal setup. Its signature may change at any time. + + :meta private: + + :param model_class: A model base class, or an already created declarative model + class. + + :param disable_autonaming: Turns off automatic tablename generation in models. + + .. versionchanged:: 3.1.0 + Added support for passing SQLAlchemy 2.x base class as model class. + Added optional ``disable_autonaming`` parameter. + + .. versionchanged:: 3.0 + Renamed with a leading underscore, this method is internal. + + .. versionchanged:: 2.3 + ``model`` can be an already created declarative model class. + """ + model: t.Type[_FSAModel] + declarative_bases = _get_2x_declarative_bases(model_class) + if len(declarative_bases) > 1: + # raise error if more than one declarative base is found + raise ValueError( + "Only one declarative base can be passed to SQLAlchemy." + " Got: {}".format(model_class.__bases__) + ) + elif len(declarative_bases) == 1: + body = dict(model_class.__dict__) + body["__fsa__"] = self + mixin_classes = [BindMixin, NameMixin, Model] + if disable_autonaming: + mixin_classes.remove(NameMixin) + model = types.new_class( + "FlaskSQLAlchemyBase", + (*mixin_classes, *model_class.__bases__), + {"metaclass": type(declarative_bases[0])}, + lambda ns: ns.update(body), + ) + elif not isinstance(model_class, sa_orm.DeclarativeMeta): + metadata = self._make_metadata(None) + metaclass = DefaultMetaNoName if disable_autonaming else DefaultMeta + model = sa_orm.declarative_base( + metadata=metadata, cls=model_class, name="Model", metaclass=metaclass + ) + else: + model = model_class # type: ignore[assignment] + + if None not in self.metadatas: + # Use the model's metadata as the default metadata. + model.metadata.info["bind_key"] = None + self.metadatas[None] = model.metadata + else: + # Use the passed in default metadata as the model's metadata. + model.metadata = self.metadatas[None] + + model.query_class = self.Query + model.query = _QueryProperty() # type: ignore[assignment] + model.__fsa__ = self + return model + + def _apply_driver_defaults(self, options: dict[str, t.Any], app: Flask) -> None: + """Apply driver-specific configuration to an engine. + + SQLite in-memory databases use ``StaticPool`` and disable ``check_same_thread``. + File paths are relative to the app's :attr:`~flask.Flask.instance_path`, + which is created if it doesn't exist. + + MySQL sets ``charset="utf8mb4"``, and ``pool_timeout`` defaults to 2 hours. + + This method is used for internal setup. Its signature may change at any time. + + :meta private: + + :param options: Arguments passed to the engine. + :param app: The application that the engine configuration belongs to. + + .. versionchanged:: 3.0 + SQLite paths are relative to ``app.instance_path``. It does not use + ``NullPool`` if ``pool_size`` is 0. Driver-level URIs are supported. + + .. versionchanged:: 3.0 + MySQL sets ``charset="utf8mb4". It does not set ``pool_size`` to 10. It + does not set ``pool_recycle`` if not using a queue pool. + + .. versionchanged:: 3.0 + Renamed from ``apply_driver_hacks``, this method is internal. It does not + return anything. + + .. versionchanged:: 2.5 + Returns ``(sa_url, options)``. + """ + url = sa.engine.make_url(options["url"]) + + if url.drivername in {"sqlite", "sqlite+pysqlite"}: + if url.database is None or url.database in {"", ":memory:"}: + options["poolclass"] = sa.pool.StaticPool + + if "connect_args" not in options: + options["connect_args"] = {} + + options["connect_args"]["check_same_thread"] = False + else: + # the url might look like sqlite:///file:path?uri=true + is_uri = url.query.get("uri", False) + + if is_uri: + db_str = url.database[5:] + else: + db_str = url.database + + if not os.path.isabs(db_str): + os.makedirs(app.instance_path, exist_ok=True) + db_str = os.path.join(app.instance_path, db_str) + + if is_uri: + db_str = f"file:{db_str}" + + options["url"] = url.set(database=db_str) + elif url.drivername.startswith("mysql"): + # set queue defaults only when using queue pool + if ( + "pool_class" not in options + or options["pool_class"] is sa.pool.QueuePool + ): + options.setdefault("pool_recycle", 7200) + + if "charset" not in url.query: + options["url"] = url.update_query_dict({"charset": "utf8mb4"}) + + def _make_engine( + self, bind_key: str | None, options: dict[str, t.Any], app: Flask + ) -> sa.engine.Engine: + """Create the :class:`sqlalchemy.engine.Engine` for the given bind key and app. + + To customize, use :data:`.SQLALCHEMY_ENGINE_OPTIONS` or + :data:`.SQLALCHEMY_BINDS` config. Pass ``engine_options`` to :class:`SQLAlchemy` + to set defaults for all engines. + + This method is used for internal setup. Its signature may change at any time. + + :meta private: + + :param bind_key: The name of the engine being created. + :param options: Arguments passed to the engine. + :param app: The application that the engine configuration belongs to. + + .. versionchanged:: 3.0 + Renamed from ``create_engine``, this method is internal. + """ + return sa.engine_from_config(options, prefix="") + + @property + def metadata(self) -> sa.MetaData: + """The default metadata used by :attr:`Model` and :attr:`Table` if no bind key + is set. + """ + return self.metadatas[None] + + @property + def engines(self) -> t.Mapping[str | None, sa.engine.Engine]: + """Map of bind keys to :class:`sqlalchemy.engine.Engine` instances for current + application. The ``None`` key refers to the default engine, and is available as + :attr:`engine`. + + To customize, set the :data:`.SQLALCHEMY_BINDS` config, and set defaults by + passing the ``engine_options`` parameter to the extension. + + This requires that a Flask application context is active. + + .. versionadded:: 3.0 + """ + app = current_app._get_current_object() # type: ignore[attr-defined] + + if app not in self._app_engines: + raise RuntimeError( + "The current Flask app is not registered with this 'SQLAlchemy'" + " instance. Did you forget to call 'init_app', or did you create" + " multiple 'SQLAlchemy' instances?" + ) + + return self._app_engines[app] + + @property + def engine(self) -> sa.engine.Engine: + """The default :class:`~sqlalchemy.engine.Engine` for the current application, + used by :attr:`session` if the :attr:`Model` or :attr:`Table` being queried does + not set a bind key. + + To customize, set the :data:`.SQLALCHEMY_ENGINE_OPTIONS` config, and set + defaults by passing the ``engine_options`` parameter to the extension. + + This requires that a Flask application context is active. + """ + return self.engines[None] + + def get_engine( + self, bind_key: str | None = None, **kwargs: t.Any + ) -> sa.engine.Engine: + """Get the engine for the given bind key for the current application. + This requires that a Flask application context is active. + + :param bind_key: The name of the engine. + + .. deprecated:: 3.0 + Will be removed in Flask-SQLAlchemy 3.2. Use ``engines[key]`` instead. + + .. versionchanged:: 3.0 + Renamed the ``bind`` parameter to ``bind_key``. Removed the ``app`` + parameter. + """ + warnings.warn( + "'get_engine' is deprecated and will be removed in Flask-SQLAlchemy" + " 3.2. Use 'engine' or 'engines[key]' instead. If you're using" + " Flask-Migrate or Alembic, you'll need to update your 'env.py' file.", + DeprecationWarning, + stacklevel=2, + ) + + if "bind" in kwargs: + bind_key = kwargs.pop("bind") + + return self.engines[bind_key] + + def get_or_404( + self, + entity: type[_O], + ident: t.Any, + *, + description: str | None = None, + **kwargs: t.Any, + ) -> _O: + """Like :meth:`session.get() ` but aborts with a + ``404 Not Found`` error instead of returning ``None``. + + :param entity: The model class to query. + :param ident: The primary key to query. + :param description: A custom message to show on the error page. + :param kwargs: Extra arguments passed to ``session.get()``. + + .. versionchanged:: 3.1 + Pass extra keyword arguments to ``session.get()``. + + .. versionadded:: 3.0 + """ + value = self.session.get(entity, ident, **kwargs) + + if value is None: + abort(404, description=description) + + return value + + def first_or_404( + self, statement: sa.sql.Select[t.Any], *, description: str | None = None + ) -> t.Any: + """Like :meth:`Result.scalar() `, but aborts + with a ``404 Not Found`` error instead of returning ``None``. + + :param statement: The ``select`` statement to execute. + :param description: A custom message to show on the error page. + + .. versionadded:: 3.0 + """ + value = self.session.execute(statement).scalar() + + if value is None: + abort(404, description=description) + + return value + + def one_or_404( + self, statement: sa.sql.Select[t.Any], *, description: str | None = None + ) -> t.Any: + """Like :meth:`Result.scalar_one() `, + but aborts with a ``404 Not Found`` error instead of raising ``NoResultFound`` + or ``MultipleResultsFound``. + + :param statement: The ``select`` statement to execute. + :param description: A custom message to show on the error page. + + .. versionadded:: 3.0 + """ + try: + return self.session.execute(statement).scalar_one() + except (sa_exc.NoResultFound, sa_exc.MultipleResultsFound): + abort(404, description=description) + + def paginate( + self, + select: sa.sql.Select[t.Any], + *, + page: int | None = None, + per_page: int | None = None, + max_per_page: int | None = None, + error_out: bool = True, + count: bool = True, + ) -> Pagination: + """Apply an offset and limit to a select statment based on the current page and + number of items per page, returning a :class:`.Pagination` object. + + The statement should select a model class, like ``select(User)``. This applies + ``unique()`` and ``scalars()`` modifiers to the result, so compound selects will + not return the expected results. + + :param select: The ``select`` statement to paginate. + :param page: The current page, used to calculate the offset. Defaults to the + ``page`` query arg during a request, or 1 otherwise. + :param per_page: The maximum number of items on a page, used to calculate the + offset and limit. Defaults to the ``per_page`` query arg during a request, + or 20 otherwise. + :param max_per_page: The maximum allowed value for ``per_page``, to limit a + user-provided value. Use ``None`` for no limit. Defaults to 100. + :param error_out: Abort with a ``404 Not Found`` error if no items are returned + and ``page`` is not 1, or if ``page`` or ``per_page`` is less than 1, or if + either are not ints. + :param count: Calculate the total number of values by issuing an extra count + query. For very complex queries this may be inaccurate or slow, so it can be + disabled and set manually if necessary. + + .. versionchanged:: 3.0 + The ``count`` query is more efficient. + + .. versionadded:: 3.0 + """ + return SelectPagination( + select=select, + session=self.session(), + page=page, + per_page=per_page, + max_per_page=max_per_page, + error_out=error_out, + count=count, + ) + + def _call_for_binds( + self, bind_key: str | None | list[str | None], op_name: str + ) -> None: + """Call a method on each metadata. + + :meta private: + + :param bind_key: A bind key or list of keys. Defaults to all binds. + :param op_name: The name of the method to call. + + .. versionchanged:: 3.0 + Renamed from ``_execute_for_all_tables``. + """ + if bind_key == "__all__": + keys: list[str | None] = list(self.metadatas) + elif bind_key is None or isinstance(bind_key, str): + keys = [bind_key] + else: + keys = bind_key + + for key in keys: + try: + engine = self.engines[key] + except KeyError: + message = f"Bind key '{key}' is not in 'SQLALCHEMY_BINDS' config." + + if key is None: + message = f"'SQLALCHEMY_DATABASE_URI' config is not set. {message}" + + raise sa_exc.UnboundExecutionError(message) from None + + metadata = self.metadatas[key] + getattr(metadata, op_name)(bind=engine) + + def create_all(self, bind_key: str | None | list[str | None] = "__all__") -> None: + """Create tables that do not exist in the database by calling + ``metadata.create_all()`` for all or some bind keys. This does not + update existing tables, use a migration library for that. + + This requires that a Flask application context is active. + + :param bind_key: A bind key or list of keys to create the tables for. Defaults + to all binds. + + .. versionchanged:: 3.0 + Renamed the ``bind`` parameter to ``bind_key``. Removed the ``app`` + parameter. + + .. versionchanged:: 0.12 + Added the ``bind`` and ``app`` parameters. + """ + self._call_for_binds(bind_key, "create_all") + + def drop_all(self, bind_key: str | None | list[str | None] = "__all__") -> None: + """Drop tables by calling ``metadata.drop_all()`` for all or some bind keys. + + This requires that a Flask application context is active. + + :param bind_key: A bind key or list of keys to drop the tables from. Defaults to + all binds. + + .. versionchanged:: 3.0 + Renamed the ``bind`` parameter to ``bind_key``. Removed the ``app`` + parameter. + + .. versionchanged:: 0.12 + Added the ``bind`` and ``app`` parameters. + """ + self._call_for_binds(bind_key, "drop_all") + + def reflect(self, bind_key: str | None | list[str | None] = "__all__") -> None: + """Load table definitions from the database by calling ``metadata.reflect()`` + for all or some bind keys. + + This requires that a Flask application context is active. + + :param bind_key: A bind key or list of keys to reflect the tables from. Defaults + to all binds. + + .. versionchanged:: 3.0 + Renamed the ``bind`` parameter to ``bind_key``. Removed the ``app`` + parameter. + + .. versionchanged:: 0.12 + Added the ``bind`` and ``app`` parameters. + """ + self._call_for_binds(bind_key, "reflect") + + def _set_rel_query(self, kwargs: dict[str, t.Any]) -> None: + """Apply the extension's :attr:`Query` class as the default for relationships + and backrefs. + + :meta private: + """ + kwargs.setdefault("query_class", self.Query) + + if "backref" in kwargs: + backref = kwargs["backref"] + + if isinstance(backref, str): + backref = (backref, {}) + + backref[1].setdefault("query_class", self.Query) + + def relationship( + self, *args: t.Any, **kwargs: t.Any + ) -> sa_orm.RelationshipProperty[t.Any]: + """A :func:`sqlalchemy.orm.relationship` that applies this extension's + :attr:`Query` class for dynamic relationships and backrefs. + + .. versionchanged:: 3.0 + The :attr:`Query` class is set on ``backref``. + """ + self._set_rel_query(kwargs) + return sa_orm.relationship(*args, **kwargs) + + def dynamic_loader( + self, argument: t.Any, **kwargs: t.Any + ) -> sa_orm.RelationshipProperty[t.Any]: + """A :func:`sqlalchemy.orm.dynamic_loader` that applies this extension's + :attr:`Query` class for relationships and backrefs. + + .. versionchanged:: 3.0 + The :attr:`Query` class is set on ``backref``. + """ + self._set_rel_query(kwargs) + return sa_orm.dynamic_loader(argument, **kwargs) + + def _relation( + self, *args: t.Any, **kwargs: t.Any + ) -> sa_orm.RelationshipProperty[t.Any]: + """A :func:`sqlalchemy.orm.relationship` that applies this extension's + :attr:`Query` class for dynamic relationships and backrefs. + + SQLAlchemy 2.0 removes this name, use ``relationship`` instead. + + :meta private: + + .. versionchanged:: 3.0 + The :attr:`Query` class is set on ``backref``. + """ + self._set_rel_query(kwargs) + f = sa_orm.relationship + return f(*args, **kwargs) + + def __getattr__(self, name: str) -> t.Any: + if name == "relation": + return self._relation + + if name == "event": + return sa_event + + if name.startswith("_"): + raise AttributeError(name) + + for mod in (sa, sa_orm): + if hasattr(mod, name): + return getattr(mod, name) + + raise AttributeError(name) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_sqlalchemy/model.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_sqlalchemy/model.py new file mode 100644 index 000000000..c6f9e5a92 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_sqlalchemy/model.py @@ -0,0 +1,330 @@ +from __future__ import annotations + +import re +import typing as t + +import sqlalchemy as sa +import sqlalchemy.orm as sa_orm + +from .query import Query + +if t.TYPE_CHECKING: + from .extension import SQLAlchemy + + +class _QueryProperty: + """A class property that creates a query object for a model. + + :meta private: + """ + + def __get__(self, obj: Model | None, cls: type[Model]) -> Query: + return cls.query_class( + cls, session=cls.__fsa__.session() # type: ignore[arg-type] + ) + + +class Model: + """The base class of the :attr:`.SQLAlchemy.Model` declarative model class. + + To define models, subclass :attr:`db.Model <.SQLAlchemy.Model>`, not this. To + customize ``db.Model``, subclass this and pass it as ``model_class`` to + :class:`.SQLAlchemy`. To customize ``db.Model`` at the metaclass level, pass an + already created declarative model class as ``model_class``. + """ + + __fsa__: t.ClassVar[SQLAlchemy] + """Internal reference to the extension object. + + :meta private: + """ + + query_class: t.ClassVar[type[Query]] = Query + """Query class used by :attr:`query`. Defaults to :attr:`.SQLAlchemy.Query`, which + defaults to :class:`.Query`. + """ + + query: t.ClassVar[Query] = _QueryProperty() # type: ignore[assignment] + """A SQLAlchemy query for a model. Equivalent to ``db.session.query(Model)``. Can be + customized per-model by overriding :attr:`query_class`. + + .. warning:: + The query interface is considered legacy in SQLAlchemy. Prefer using + ``session.execute(select())`` instead. + """ + + def __repr__(self) -> str: + state = sa.inspect(self) + assert state is not None + + if state.transient: + pk = f"(transient {id(self)})" + elif state.pending: + pk = f"(pending {id(self)})" + else: + pk = ", ".join(map(str, state.identity)) + + return f"<{type(self).__name__} {pk}>" + + +class BindMetaMixin(type): + """Metaclass mixin that sets a model's ``metadata`` based on its ``__bind_key__``. + + If the model sets ``metadata`` or ``__table__`` directly, ``__bind_key__`` is + ignored. If the ``metadata`` is the same as the parent model, it will not be set + directly on the child model. + """ + + __fsa__: SQLAlchemy + metadata: sa.MetaData + + def __init__( + cls, name: str, bases: tuple[type, ...], d: dict[str, t.Any], **kwargs: t.Any + ) -> None: + if not ("metadata" in cls.__dict__ or "__table__" in cls.__dict__): + bind_key = getattr(cls, "__bind_key__", None) + parent_metadata = getattr(cls, "metadata", None) + metadata = cls.__fsa__._make_metadata(bind_key) + + if metadata is not parent_metadata: + cls.metadata = metadata + + super().__init__(name, bases, d, **kwargs) + + +class BindMixin: + """DeclarativeBase mixin to set a model's ``metadata`` based on ``__bind_key__``. + + If no ``__bind_key__`` is specified, the model will use the default metadata + provided by ``DeclarativeBase`` or ``DeclarativeBaseNoMeta``. + If the model doesn't set ``metadata`` or ``__table__`` directly + and does set ``__bind_key__``, the model will use the metadata + for the specified bind key. + If the ``metadata`` is the same as the parent model, it will not be set + directly on the child model. + + .. versionchanged:: 3.1.0 + """ + + __fsa__: SQLAlchemy + metadata: sa.MetaData + + @classmethod + def __init_subclass__(cls: t.Type[BindMixin], **kwargs: t.Dict[str, t.Any]) -> None: + if not ("metadata" in cls.__dict__ or "__table__" in cls.__dict__) and hasattr( + cls, "__bind_key__" + ): + bind_key = getattr(cls, "__bind_key__", None) + parent_metadata = getattr(cls, "metadata", None) + metadata = cls.__fsa__._make_metadata(bind_key) + + if metadata is not parent_metadata: + cls.metadata = metadata + + super().__init_subclass__(**kwargs) + + +class NameMetaMixin(type): + """Metaclass mixin that sets a model's ``__tablename__`` by converting the + ``CamelCase`` class name to ``snake_case``. A name is set for non-abstract models + that do not otherwise define ``__tablename__``. If a model does not define a primary + key, it will not generate a name or ``__table__``, for single-table inheritance. + """ + + metadata: sa.MetaData + __tablename__: str + __table__: sa.Table + + def __init__( + cls, name: str, bases: tuple[type, ...], d: dict[str, t.Any], **kwargs: t.Any + ) -> None: + if should_set_tablename(cls): + cls.__tablename__ = camel_to_snake_case(cls.__name__) + + super().__init__(name, bases, d, **kwargs) + + # __table_cls__ has run. If no table was created, use the parent table. + if ( + "__tablename__" not in cls.__dict__ + and "__table__" in cls.__dict__ + and cls.__dict__["__table__"] is None + ): + del cls.__table__ + + def __table_cls__(cls, *args: t.Any, **kwargs: t.Any) -> sa.Table | None: + """This is called by SQLAlchemy during mapper setup. It determines the final + table object that the model will use. + + If no primary key is found, that indicates single-table inheritance, so no table + will be created and ``__tablename__`` will be unset. + """ + schema = kwargs.get("schema") + + if schema is None: + key = args[0] + else: + key = f"{schema}.{args[0]}" + + # Check if a table with this name already exists. Allows reflected tables to be + # applied to models by name. + if key in cls.metadata.tables: + return sa.Table(*args, **kwargs) + + # If a primary key is found, create a table for joined-table inheritance. + for arg in args: + if (isinstance(arg, sa.Column) and arg.primary_key) or isinstance( + arg, sa.PrimaryKeyConstraint + ): + return sa.Table(*args, **kwargs) + + # If no base classes define a table, return one that's missing a primary key + # so SQLAlchemy shows the correct error. + for base in cls.__mro__[1:-1]: + if "__table__" in base.__dict__: + break + else: + return sa.Table(*args, **kwargs) + + # Single-table inheritance, use the parent table name. __init__ will unset + # __table__ based on this. + if "__tablename__" in cls.__dict__: + del cls.__tablename__ + + return None + + +class NameMixin: + """DeclarativeBase mixin that sets a model's ``__tablename__`` by converting the + ``CamelCase`` class name to ``snake_case``. A name is set for non-abstract models + that do not otherwise define ``__tablename__``. If a model does not define a primary + key, it will not generate a name or ``__table__``, for single-table inheritance. + + .. versionchanged:: 3.1.0 + """ + + metadata: sa.MetaData + __tablename__: str + __table__: sa.Table + + @classmethod + def __init_subclass__(cls: t.Type[NameMixin], **kwargs: t.Dict[str, t.Any]) -> None: + if should_set_tablename(cls): + cls.__tablename__ = camel_to_snake_case(cls.__name__) + + super().__init_subclass__(**kwargs) + + # __table_cls__ has run. If no table was created, use the parent table. + if ( + "__tablename__" not in cls.__dict__ + and "__table__" in cls.__dict__ + and cls.__dict__["__table__"] is None + ): + del cls.__table__ + + @classmethod + def __table_cls__(cls, *args: t.Any, **kwargs: t.Any) -> sa.Table | None: + """This is called by SQLAlchemy during mapper setup. It determines the final + table object that the model will use. + + If no primary key is found, that indicates single-table inheritance, so no table + will be created and ``__tablename__`` will be unset. + """ + schema = kwargs.get("schema") + + if schema is None: + key = args[0] + else: + key = f"{schema}.{args[0]}" + + # Check if a table with this name already exists. Allows reflected tables to be + # applied to models by name. + if key in cls.metadata.tables: + return sa.Table(*args, **kwargs) + + # If a primary key is found, create a table for joined-table inheritance. + for arg in args: + if (isinstance(arg, sa.Column) and arg.primary_key) or isinstance( + arg, sa.PrimaryKeyConstraint + ): + return sa.Table(*args, **kwargs) + + # If no base classes define a table, return one that's missing a primary key + # so SQLAlchemy shows the correct error. + for base in cls.__mro__[1:-1]: + if "__table__" in base.__dict__: + break + else: + return sa.Table(*args, **kwargs) + + # Single-table inheritance, use the parent table name. __init__ will unset + # __table__ based on this. + if "__tablename__" in cls.__dict__: + del cls.__tablename__ + + return None + + +def should_set_tablename(cls: type) -> bool: + """Determine whether ``__tablename__`` should be generated for a model. + + - If no class in the MRO sets a name, one should be generated. + - If a declared attr is found, it should be used instead. + - If a name is found, it should be used if the class is a mixin, otherwise one + should be generated. + - Abstract models should not have one generated. + + Later, ``__table_cls__`` will determine if the model looks like single or + joined-table inheritance. If no primary key is found, the name will be unset. + """ + if ( + cls.__dict__.get("__abstract__", False) + or ( + not issubclass(cls, (sa_orm.DeclarativeBase, sa_orm.DeclarativeBaseNoMeta)) + and not any(isinstance(b, sa_orm.DeclarativeMeta) for b in cls.__mro__[1:]) + ) + or any( + (b is sa_orm.DeclarativeBase or b is sa_orm.DeclarativeBaseNoMeta) + for b in cls.__bases__ + ) + ): + return False + + for base in cls.__mro__: + if "__tablename__" not in base.__dict__: + continue + + if isinstance(base.__dict__["__tablename__"], sa_orm.declared_attr): + return False + + return not ( + base is cls + or base.__dict__.get("__abstract__", False) + or not ( + # SQLAlchemy 1.x + isinstance(base, sa_orm.DeclarativeMeta) + # 2.x: DeclarativeBas uses this as metaclass + or isinstance(base, sa_orm.decl_api.DeclarativeAttributeIntercept) + # 2.x: DeclarativeBaseNoMeta doesn't use a metaclass + or issubclass(base, sa_orm.DeclarativeBaseNoMeta) + ) + ) + + return True + + +def camel_to_snake_case(name: str) -> str: + """Convert a ``CamelCase`` name to ``snake_case``.""" + name = re.sub(r"((?<=[a-z0-9])[A-Z]|(?!^)[A-Z](?=[a-z]))", r"_\1", name) + return name.lower().lstrip("_") + + +class DefaultMeta(BindMetaMixin, NameMetaMixin, sa_orm.DeclarativeMeta): + """SQLAlchemy declarative metaclass that provides ``__bind_key__`` and + ``__tablename__`` support. + """ + + +class DefaultMetaNoName(BindMetaMixin, sa_orm.DeclarativeMeta): + """SQLAlchemy declarative metaclass that provides ``__bind_key__`` and + ``__tablename__`` support. + """ diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_sqlalchemy/pagination.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_sqlalchemy/pagination.py new file mode 100644 index 000000000..3d49d6e04 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_sqlalchemy/pagination.py @@ -0,0 +1,364 @@ +from __future__ import annotations + +import typing as t +from math import ceil + +import sqlalchemy as sa +import sqlalchemy.orm as sa_orm +from flask import abort +from flask import request + + +class Pagination: + """Apply an offset and limit to the query based on the current page and number of + items per page. + + Don't create pagination objects manually. They are created by + :meth:`.SQLAlchemy.paginate` and :meth:`.Query.paginate`. + + This is a base class, a subclass must implement :meth:`_query_items` and + :meth:`_query_count`. Those methods will use arguments passed as ``kwargs`` to + perform the queries. + + :param page: The current page, used to calculate the offset. Defaults to the + ``page`` query arg during a request, or 1 otherwise. + :param per_page: The maximum number of items on a page, used to calculate the + offset and limit. Defaults to the ``per_page`` query arg during a request, + or 20 otherwise. + :param max_per_page: The maximum allowed value for ``per_page``, to limit a + user-provided value. Use ``None`` for no limit. Defaults to 100. + :param error_out: Abort with a ``404 Not Found`` error if no items are returned + and ``page`` is not 1, or if ``page`` or ``per_page`` is less than 1, or if + either are not ints. + :param count: Calculate the total number of values by issuing an extra count + query. For very complex queries this may be inaccurate or slow, so it can be + disabled and set manually if necessary. + :param kwargs: Information about the query to paginate. Different subclasses will + require different arguments. + + .. versionchanged:: 3.0 + Iterating over a pagination object iterates over its items. + + .. versionchanged:: 3.0 + Creating instances manually is not a public API. + """ + + def __init__( + self, + page: int | None = None, + per_page: int | None = None, + max_per_page: int | None = 100, + error_out: bool = True, + count: bool = True, + **kwargs: t.Any, + ) -> None: + self._query_args = kwargs + page, per_page = self._prepare_page_args( + page=page, + per_page=per_page, + max_per_page=max_per_page, + error_out=error_out, + ) + + self.page: int = page + """The current page.""" + + self.per_page: int = per_page + """The maximum number of items on a page.""" + + self.max_per_page: int | None = max_per_page + """The maximum allowed value for ``per_page``.""" + + items = self._query_items() + + if not items and page != 1 and error_out: + abort(404) + + self.items: list[t.Any] = items + """The items on the current page. Iterating over the pagination object is + equivalent to iterating over the items. + """ + + if count: + total = self._query_count() + else: + total = None + + self.total: int | None = total + """The total number of items across all pages.""" + + @staticmethod + def _prepare_page_args( + *, + page: int | None = None, + per_page: int | None = None, + max_per_page: int | None = None, + error_out: bool = True, + ) -> tuple[int, int]: + if request: + if page is None: + try: + page = int(request.args.get("page", 1)) + except (TypeError, ValueError): + if error_out: + abort(404) + + page = 1 + + if per_page is None: + try: + per_page = int(request.args.get("per_page", 20)) + except (TypeError, ValueError): + if error_out: + abort(404) + + per_page = 20 + else: + if page is None: + page = 1 + + if per_page is None: + per_page = 20 + + if max_per_page is not None: + per_page = min(per_page, max_per_page) + + if page < 1: + if error_out: + abort(404) + else: + page = 1 + + if per_page < 1: + if error_out: + abort(404) + else: + per_page = 20 + + return page, per_page + + @property + def _query_offset(self) -> int: + """The index of the first item to query, passed to ``offset()``. + + :meta private: + + .. versionadded:: 3.0 + """ + return (self.page - 1) * self.per_page + + def _query_items(self) -> list[t.Any]: + """Execute the query to get the items on the current page. + + Uses init arguments stored in :attr:`_query_args`. + + :meta private: + + .. versionadded:: 3.0 + """ + raise NotImplementedError + + def _query_count(self) -> int: + """Execute the query to get the total number of items. + + Uses init arguments stored in :attr:`_query_args`. + + :meta private: + + .. versionadded:: 3.0 + """ + raise NotImplementedError + + @property + def first(self) -> int: + """The number of the first item on the page, starting from 1, or 0 if there are + no items. + + .. versionadded:: 3.0 + """ + if len(self.items) == 0: + return 0 + + return (self.page - 1) * self.per_page + 1 + + @property + def last(self) -> int: + """The number of the last item on the page, starting from 1, inclusive, or 0 if + there are no items. + + .. versionadded:: 3.0 + """ + first = self.first + return max(first, first + len(self.items) - 1) + + @property + def pages(self) -> int: + """The total number of pages.""" + if self.total == 0 or self.total is None: + return 0 + + return ceil(self.total / self.per_page) + + @property + def has_prev(self) -> bool: + """``True`` if this is not the first page.""" + return self.page > 1 + + @property + def prev_num(self) -> int | None: + """The previous page number, or ``None`` if this is the first page.""" + if not self.has_prev: + return None + + return self.page - 1 + + def prev(self, *, error_out: bool = False) -> Pagination: + """Query the :class:`Pagination` object for the previous page. + + :param error_out: Abort with a ``404 Not Found`` error if no items are returned + and ``page`` is not 1, or if ``page`` or ``per_page`` is less than 1, or if + either are not ints. + """ + p = type(self)( + page=self.page - 1, + per_page=self.per_page, + error_out=error_out, + count=False, + **self._query_args, + ) + p.total = self.total + return p + + @property + def has_next(self) -> bool: + """``True`` if this is not the last page.""" + return self.page < self.pages + + @property + def next_num(self) -> int | None: + """The next page number, or ``None`` if this is the last page.""" + if not self.has_next: + return None + + return self.page + 1 + + def next(self, *, error_out: bool = False) -> Pagination: + """Query the :class:`Pagination` object for the next page. + + :param error_out: Abort with a ``404 Not Found`` error if no items are returned + and ``page`` is not 1, or if ``page`` or ``per_page`` is less than 1, or if + either are not ints. + """ + p = type(self)( + page=self.page + 1, + per_page=self.per_page, + max_per_page=self.max_per_page, + error_out=error_out, + count=False, + **self._query_args, + ) + p.total = self.total + return p + + def iter_pages( + self, + *, + left_edge: int = 2, + left_current: int = 2, + right_current: int = 4, + right_edge: int = 2, + ) -> t.Iterator[int | None]: + """Yield page numbers for a pagination widget. Skipped pages between the edges + and middle are represented by a ``None``. + + For example, if there are 20 pages and the current page is 7, the following + values are yielded. + + .. code-block:: python + + 1, 2, None, 5, 6, 7, 8, 9, 10, 11, None, 19, 20 + + :param left_edge: How many pages to show from the first page. + :param left_current: How many pages to show left of the current page. + :param right_current: How many pages to show right of the current page. + :param right_edge: How many pages to show from the last page. + + .. versionchanged:: 3.0 + Improved efficiency of calculating what to yield. + + .. versionchanged:: 3.0 + ``right_current`` boundary is inclusive. + + .. versionchanged:: 3.0 + All parameters are keyword-only. + """ + pages_end = self.pages + 1 + + if pages_end == 1: + return + + left_end = min(1 + left_edge, pages_end) + yield from range(1, left_end) + + if left_end == pages_end: + return + + mid_start = max(left_end, self.page - left_current) + mid_end = min(self.page + right_current + 1, pages_end) + + if mid_start - left_end > 0: + yield None + + yield from range(mid_start, mid_end) + + if mid_end == pages_end: + return + + right_start = max(mid_end, pages_end - right_edge) + + if right_start - mid_end > 0: + yield None + + yield from range(right_start, pages_end) + + def __iter__(self) -> t.Iterator[t.Any]: + yield from self.items + + +class SelectPagination(Pagination): + """Returned by :meth:`.SQLAlchemy.paginate`. Takes ``select`` and ``session`` + arguments in addition to the :class:`Pagination` arguments. + + .. versionadded:: 3.0 + """ + + def _query_items(self) -> list[t.Any]: + select = self._query_args["select"] + select = select.limit(self.per_page).offset(self._query_offset) + session = self._query_args["session"] + return list(session.execute(select).unique().scalars()) + + def _query_count(self) -> int: + select = self._query_args["select"] + sub = select.options(sa_orm.lazyload("*")).order_by(None).subquery() + session = self._query_args["session"] + out = session.execute(sa.select(sa.func.count()).select_from(sub)).scalar() + return out # type: ignore[no-any-return] + + +class QueryPagination(Pagination): + """Returned by :meth:`.Query.paginate`. Takes a ``query`` argument in addition to + the :class:`Pagination` arguments. + + .. versionadded:: 3.0 + """ + + def _query_items(self) -> list[t.Any]: + query = self._query_args["query"] + out = query.limit(self.per_page).offset(self._query_offset).all() + return out # type: ignore[no-any-return] + + def _query_count(self) -> int: + # Query.count automatically disables eager loads + out = self._query_args["query"].order_by(None).count() + return out # type: ignore[no-any-return] diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_sqlalchemy/py.typed b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_sqlalchemy/py.typed new file mode 100644 index 000000000..e69de29bb diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_sqlalchemy/query.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_sqlalchemy/query.py new file mode 100644 index 000000000..35f927d28 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_sqlalchemy/query.py @@ -0,0 +1,105 @@ +from __future__ import annotations + +import typing as t + +import sqlalchemy.exc as sa_exc +import sqlalchemy.orm as sa_orm +from flask import abort + +from .pagination import Pagination +from .pagination import QueryPagination + + +class Query(sa_orm.Query): # type: ignore[type-arg] + """SQLAlchemy :class:`~sqlalchemy.orm.query.Query` subclass with some extra methods + useful for querying in a web application. + + This is the default query class for :attr:`.Model.query`. + + .. versionchanged:: 3.0 + Renamed to ``Query`` from ``BaseQuery``. + """ + + def get_or_404(self, ident: t.Any, description: str | None = None) -> t.Any: + """Like :meth:`~sqlalchemy.orm.Query.get` but aborts with a ``404 Not Found`` + error instead of returning ``None``. + + :param ident: The primary key to query. + :param description: A custom message to show on the error page. + """ + rv = self.get(ident) + + if rv is None: + abort(404, description=description) + + return rv + + def first_or_404(self, description: str | None = None) -> t.Any: + """Like :meth:`~sqlalchemy.orm.Query.first` but aborts with a ``404 Not Found`` + error instead of returning ``None``. + + :param description: A custom message to show on the error page. + """ + rv = self.first() + + if rv is None: + abort(404, description=description) + + return rv + + def one_or_404(self, description: str | None = None) -> t.Any: + """Like :meth:`~sqlalchemy.orm.Query.one` but aborts with a ``404 Not Found`` + error instead of raising ``NoResultFound`` or ``MultipleResultsFound``. + + :param description: A custom message to show on the error page. + + .. versionadded:: 3.0 + """ + try: + return self.one() + except (sa_exc.NoResultFound, sa_exc.MultipleResultsFound): + abort(404, description=description) + + def paginate( + self, + *, + page: int | None = None, + per_page: int | None = None, + max_per_page: int | None = None, + error_out: bool = True, + count: bool = True, + ) -> Pagination: + """Apply an offset and limit to the query based on the current page and number + of items per page, returning a :class:`.Pagination` object. + + :param page: The current page, used to calculate the offset. Defaults to the + ``page`` query arg during a request, or 1 otherwise. + :param per_page: The maximum number of items on a page, used to calculate the + offset and limit. Defaults to the ``per_page`` query arg during a request, + or 20 otherwise. + :param max_per_page: The maximum allowed value for ``per_page``, to limit a + user-provided value. Use ``None`` for no limit. Defaults to 100. + :param error_out: Abort with a ``404 Not Found`` error if no items are returned + and ``page`` is not 1, or if ``page`` or ``per_page`` is less than 1, or if + either are not ints. + :param count: Calculate the total number of values by issuing an extra count + query. For very complex queries this may be inaccurate or slow, so it can be + disabled and set manually if necessary. + + .. versionchanged:: 3.0 + All parameters are keyword-only. + + .. versionchanged:: 3.0 + The ``count`` query is more efficient. + + .. versionchanged:: 3.0 + ``max_per_page`` defaults to 100. + """ + return QueryPagination( + query=self, + page=page, + per_page=per_page, + max_per_page=max_per_page, + error_out=error_out, + count=count, + ) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_sqlalchemy/record_queries.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_sqlalchemy/record_queries.py new file mode 100644 index 000000000..e8273be95 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_sqlalchemy/record_queries.py @@ -0,0 +1,117 @@ +from __future__ import annotations + +import dataclasses +import inspect +import typing as t +from time import perf_counter + +import sqlalchemy as sa +import sqlalchemy.event as sa_event +from flask import current_app +from flask import g +from flask import has_app_context + + +def get_recorded_queries() -> list[_QueryInfo]: + """Get the list of recorded query information for the current session. Queries are + recorded if the config :data:`.SQLALCHEMY_RECORD_QUERIES` is enabled. + + Each query info object has the following attributes: + + ``statement`` + The string of SQL generated by SQLAlchemy with parameter placeholders. + ``parameters`` + The parameters sent with the SQL statement. + ``start_time`` / ``end_time`` + Timing info about when the query started execution and when the results where + returned. Accuracy and value depends on the operating system. + ``duration`` + The time the query took in seconds. + ``location`` + A string description of where in your application code the query was executed. + This may not be possible to calculate, and the format is not stable. + + .. versionchanged:: 3.0 + Renamed from ``get_debug_queries``. + + .. versionchanged:: 3.0 + The info object is a dataclass instead of a tuple. + + .. versionchanged:: 3.0 + The info object attribute ``context`` is renamed to ``location``. + + .. versionchanged:: 3.0 + Not enabled automatically in debug or testing mode. + """ + return g.get("_sqlalchemy_queries", []) # type: ignore[no-any-return] + + +@dataclasses.dataclass +class _QueryInfo: + """Information about an executed query. Returned by :func:`get_recorded_queries`. + + .. versionchanged:: 3.0 + Renamed from ``_DebugQueryTuple``. + + .. versionchanged:: 3.0 + Changed to a dataclass instead of a tuple. + + .. versionchanged:: 3.0 + ``context`` is renamed to ``location``. + """ + + statement: str | None + parameters: t.Any + start_time: float + end_time: float + location: str + + @property + def duration(self) -> float: + return self.end_time - self.start_time + + +def _listen(engine: sa.engine.Engine) -> None: + sa_event.listen(engine, "before_cursor_execute", _record_start, named=True) + sa_event.listen(engine, "after_cursor_execute", _record_end, named=True) + + +def _record_start(context: sa.engine.ExecutionContext, **kwargs: t.Any) -> None: + if not has_app_context(): + return + + context._fsa_start_time = perf_counter() # type: ignore[attr-defined] + + +def _record_end(context: sa.engine.ExecutionContext, **kwargs: t.Any) -> None: + if not has_app_context(): + return + + if "_sqlalchemy_queries" not in g: + g._sqlalchemy_queries = [] + + import_top = current_app.import_name.partition(".")[0] + import_dot = f"{import_top}." + frame = inspect.currentframe() + + while frame: + name = frame.f_globals.get("__name__") + + if name and (name == import_top or name.startswith(import_dot)): + code = frame.f_code + location = f"{code.co_filename}:{frame.f_lineno} ({code.co_name})" + break + + frame = frame.f_back + else: + location = "" + + g._sqlalchemy_queries.append( + _QueryInfo( + statement=context.statement, + parameters=context.parameters, + start_time=context._fsa_start_time, # type: ignore[attr-defined] + end_time=perf_counter(), + location=location, + ) + ) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_sqlalchemy/session.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_sqlalchemy/session.py new file mode 100644 index 000000000..631fffa82 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_sqlalchemy/session.py @@ -0,0 +1,111 @@ +from __future__ import annotations + +import typing as t + +import sqlalchemy as sa +import sqlalchemy.exc as sa_exc +import sqlalchemy.orm as sa_orm +from flask.globals import app_ctx + +if t.TYPE_CHECKING: + from .extension import SQLAlchemy + + +class Session(sa_orm.Session): + """A SQLAlchemy :class:`~sqlalchemy.orm.Session` class that chooses what engine to + use based on the bind key associated with the metadata associated with the thing + being queried. + + To customize ``db.session``, subclass this and pass it as the ``class_`` key in the + ``session_options`` to :class:`.SQLAlchemy`. + + .. versionchanged:: 3.0 + Renamed from ``SignallingSession``. + """ + + def __init__(self, db: SQLAlchemy, **kwargs: t.Any) -> None: + super().__init__(**kwargs) + self._db = db + self._model_changes: dict[object, tuple[t.Any, str]] = {} + + def get_bind( + self, + mapper: t.Any | None = None, + clause: t.Any | None = None, + bind: sa.engine.Engine | sa.engine.Connection | None = None, + **kwargs: t.Any, + ) -> sa.engine.Engine | sa.engine.Connection: + """Select an engine based on the ``bind_key`` of the metadata associated with + the model or table being queried. If no bind key is set, uses the default bind. + + .. versionchanged:: 3.0.3 + Fix finding the bind for a joined inheritance model. + + .. versionchanged:: 3.0 + The implementation more closely matches the base SQLAlchemy implementation. + + .. versionchanged:: 2.1 + Support joining an external transaction. + """ + if bind is not None: + return bind + + engines = self._db.engines + + if mapper is not None: + try: + mapper = sa.inspect(mapper) + except sa_exc.NoInspectionAvailable as e: + if isinstance(mapper, type): + raise sa_orm.exc.UnmappedClassError(mapper) from e + + raise + + engine = _clause_to_engine(mapper.local_table, engines) + + if engine is not None: + return engine + + if clause is not None: + engine = _clause_to_engine(clause, engines) + + if engine is not None: + return engine + + if None in engines: + return engines[None] + + return super().get_bind(mapper=mapper, clause=clause, bind=bind, **kwargs) + + +def _clause_to_engine( + clause: sa.ClauseElement | None, + engines: t.Mapping[str | None, sa.engine.Engine], +) -> sa.engine.Engine | None: + """If the clause is a table, return the engine associated with the table's + metadata's bind key. + """ + table = None + + if clause is not None: + if isinstance(clause, sa.Table): + table = clause + elif isinstance(clause, sa.UpdateBase) and isinstance(clause.table, sa.Table): + table = clause.table + + if table is not None and "bind_key" in table.metadata.info: + key = table.metadata.info["bind_key"] + + if key not in engines: + raise sa_exc.UnboundExecutionError( + f"Bind key '{key}' is not in 'SQLALCHEMY_BINDS' config." + ) + + return engines[key] + + return None + + +def _app_ctx_id() -> int: + """Get the id of the current Flask application context for the session scope.""" + return id(app_ctx._get_current_object()) # type: ignore[attr-defined] diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_sqlalchemy/table.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_sqlalchemy/table.py new file mode 100644 index 000000000..ab08a692a --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_sqlalchemy/table.py @@ -0,0 +1,39 @@ +from __future__ import annotations + +import typing as t + +import sqlalchemy as sa +import sqlalchemy.sql.schema as sa_sql_schema + + +class _Table(sa.Table): + @t.overload + def __init__( + self, + name: str, + *args: sa_sql_schema.SchemaItem, + bind_key: str | None = None, + **kwargs: t.Any, + ) -> None: + ... + + @t.overload + def __init__( + self, + name: str, + metadata: sa.MetaData, + *args: sa_sql_schema.SchemaItem, + **kwargs: t.Any, + ) -> None: + ... + + @t.overload + def __init__( + self, name: str, *args: sa_sql_schema.SchemaItem, **kwargs: t.Any + ) -> None: + ... + + def __init__( + self, name: str, *args: sa_sql_schema.SchemaItem, **kwargs: t.Any + ) -> None: + super().__init__(name, *args, **kwargs) # type: ignore[arg-type] diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_sqlalchemy/track_modifications.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_sqlalchemy/track_modifications.py new file mode 100644 index 000000000..7028b6538 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_sqlalchemy/track_modifications.py @@ -0,0 +1,88 @@ +from __future__ import annotations + +import typing as t + +import sqlalchemy as sa +import sqlalchemy.event as sa_event +import sqlalchemy.orm as sa_orm +from flask import current_app +from flask import has_app_context +from flask.signals import Namespace # type: ignore[attr-defined] + +if t.TYPE_CHECKING: + from .session import Session + +_signals = Namespace() + +models_committed = _signals.signal("models-committed") +"""This Blinker signal is sent after the session is committed if there were changed +models in the session. + +The sender is the application that emitted the changes. The receiver is passed the +``changes`` argument with a list of tuples in the form ``(instance, operation)``. +The operations are ``"insert"``, ``"update"``, and ``"delete"``. +""" + +before_models_committed = _signals.signal("before-models-committed") +"""This signal works exactly like :data:`models_committed` but is emitted before the +commit takes place. +""" + + +def _listen(session: sa_orm.scoped_session[Session]) -> None: + sa_event.listen(session, "before_flush", _record_ops, named=True) + sa_event.listen(session, "before_commit", _record_ops, named=True) + sa_event.listen(session, "before_commit", _before_commit) + sa_event.listen(session, "after_commit", _after_commit) + sa_event.listen(session, "after_rollback", _after_rollback) + + +def _record_ops(session: Session, **kwargs: t.Any) -> None: + if not has_app_context(): + return + + if not current_app.config["SQLALCHEMY_TRACK_MODIFICATIONS"]: + return + + for targets, operation in ( + (session.new, "insert"), + (session.dirty, "update"), + (session.deleted, "delete"), + ): + for target in targets: + state = sa.inspect(target) + key = state.identity_key if state.has_identity else id(target) + session._model_changes[key] = (target, operation) + + +def _before_commit(session: Session) -> None: + if not has_app_context(): + return + + app = current_app._get_current_object() # type: ignore[attr-defined] + + if not app.config["SQLALCHEMY_TRACK_MODIFICATIONS"]: + return + + if session._model_changes: + changes = list(session._model_changes.values()) + before_models_committed.send(app, changes=changes) + + +def _after_commit(session: Session) -> None: + if not has_app_context(): + return + + app = current_app._get_current_object() # type: ignore[attr-defined] + + if not app.config["SQLALCHEMY_TRACK_MODIFICATIONS"]: + return + + if session._model_changes: + changes = list(session._model_changes.values()) + models_committed.send(app, changes=changes) + session._model_changes.clear() + + +def _after_rollback(session: Session) -> None: + session._model_changes.clear() diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_wtf-1.2.2.dist-info/INSTALLER b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_wtf-1.2.2.dist-info/INSTALLER new file mode 100644 index 000000000..a1b589e38 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_wtf-1.2.2.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_wtf-1.2.2.dist-info/METADATA b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_wtf-1.2.2.dist-info/METADATA new file mode 100644 index 000000000..0658f87e9 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_wtf-1.2.2.dist-info/METADATA @@ -0,0 +1,72 @@ +Metadata-Version: 2.3 +Name: Flask-WTF +Version: 1.2.2 +Summary: Form rendering, validation, and CSRF protection for Flask with WTForms. +Project-URL: Documentation, https://flask-wtf.readthedocs.io/ +Project-URL: Changes, https://flask-wtf.readthedocs.io/changes/ +Project-URL: Source Code, https://github.com/pallets-eco/flask-wtf/ +Project-URL: Issue Tracker, https://github.com/pallets-eco/flask-wtf/issues/ +Project-URL: Chat, https://discord.gg/pallets +Maintainer: WTForms +License: Copyright 2010 WTForms + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are + met: + + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + 3. Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A + PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED + TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +License-File: LICENSE.rst +Classifier: Development Status :: 5 - Production/Stable +Classifier: Environment :: Web Environment +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: BSD License +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: Python +Classifier: Topic :: Internet :: WWW/HTTP :: Dynamic Content +Classifier: Topic :: Internet :: WWW/HTTP :: WSGI +Classifier: Topic :: Internet :: WWW/HTTP :: WSGI :: Application +Classifier: Topic :: Software Development :: Libraries :: Application Frameworks +Requires-Python: >=3.9 +Requires-Dist: flask +Requires-Dist: itsdangerous +Requires-Dist: wtforms +Provides-Extra: email +Requires-Dist: email-validator; extra == 'email' +Description-Content-Type: text/x-rst + +Flask-WTF +========= + +Simple integration of Flask and WTForms, including CSRF, file upload, +and reCAPTCHA. + +Links +----- + +- Documentation: https://flask-wtf.readthedocs.io/ +- Changes: https://flask-wtf.readthedocs.io/changes/ +- PyPI Releases: https://pypi.org/project/Flask-WTF/ +- Source Code: https://github.com/pallets-eco/flask-wtf/ +- Issue Tracker: https://github.com/pallets-eco/flask-wtf/issues/ +- Chat: https://discord.gg/pallets diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_wtf-1.2.2.dist-info/RECORD b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_wtf-1.2.2.dist-info/RECORD new file mode 100644 index 000000000..3fbe1db40 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_wtf-1.2.2.dist-info/RECORD @@ -0,0 +1,26 @@ +flask_wtf-1.2.2.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +flask_wtf-1.2.2.dist-info/METADATA,sha256=Z0LaCPBB6RVW1BohxeYvGOkbiAXAtkDhPpNxsXZZkLM,3389 +flask_wtf-1.2.2.dist-info/RECORD,, +flask_wtf-1.2.2.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +flask_wtf-1.2.2.dist-info/WHEEL,sha256=1yFddiXMmvYK7QYTqtRNtX66WJ0Mz8PYEiEUoOUUxRY,87 +flask_wtf-1.2.2.dist-info/licenses/LICENSE.rst,sha256=1fGQNkUVeMs27u8EyZ6_fXyi5w3PBDY2UZvEIOFafGI,1475 +flask_wtf/__init__.py,sha256=1v73MaP8sjOe-mJ5DtKaMn_ZvQwAoV5TIxpjE1i3n9A,338 +flask_wtf/__pycache__/__init__.cpython-312.pyc,, +flask_wtf/__pycache__/_compat.cpython-312.pyc,, +flask_wtf/__pycache__/csrf.cpython-312.pyc,, +flask_wtf/__pycache__/file.cpython-312.pyc,, +flask_wtf/__pycache__/form.cpython-312.pyc,, +flask_wtf/__pycache__/i18n.cpython-312.pyc,, +flask_wtf/_compat.py,sha256=N3sqC9yzFWY-3MZ7QazX1sidvkO3d5yy4NR6lkp0s94,248 +flask_wtf/csrf.py,sha256=O-fjnWygxxi_FsIU2koua97ZpIhiOJVDHA57dXLpvTA,10171 +flask_wtf/file.py,sha256=E-PvtzlOGqbtsLVkbooDSo_klCf7oWQvTZWk1hkNBoY,4636 +flask_wtf/form.py,sha256=TmR7xCrxin2LHp6thn7fq1OeU8aLB7xsZzvv52nH7Ss,4049 +flask_wtf/i18n.py,sha256=TyO8gqt9DocHMSaNhj0KKgxoUrPYs-G1nVW-jns0SOw,1166 +flask_wtf/recaptcha/__init__.py,sha256=odaCRkvoG999MnGiaSfA1sEt6OnAOqumg78jO53GL-4,168 +flask_wtf/recaptcha/__pycache__/__init__.cpython-312.pyc,, +flask_wtf/recaptcha/__pycache__/fields.cpython-312.pyc,, +flask_wtf/recaptcha/__pycache__/validators.cpython-312.pyc,, +flask_wtf/recaptcha/__pycache__/widgets.cpython-312.pyc,, +flask_wtf/recaptcha/fields.py,sha256=M1-RFuUKOsJAzsLm3xaaxuhX2bB9oRqS-HVSN-NpkmI,433 +flask_wtf/recaptcha/validators.py,sha256=3sd1mUQT3Y3D_WJeKwecxUGstnhh_QD-A_dEBJfkf6s,2434 +flask_wtf/recaptcha/widgets.py,sha256=J_XyxAZt3uB15diIMnkXXGII2dmsWCsVsKV3KQYn4Ns,1512 diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_wtf-1.2.2.dist-info/REQUESTED b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_wtf-1.2.2.dist-info/REQUESTED new file mode 100644 index 000000000..e69de29bb diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_wtf-1.2.2.dist-info/WHEEL b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_wtf-1.2.2.dist-info/WHEEL new file mode 100644 index 000000000..cdd68a497 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_wtf-1.2.2.dist-info/WHEEL @@ -0,0 +1,4 @@ +Wheel-Version: 1.0 +Generator: hatchling 1.25.0 +Root-Is-Purelib: true +Tag: py3-none-any diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_wtf-1.2.2.dist-info/licenses/LICENSE.rst b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_wtf-1.2.2.dist-info/licenses/LICENSE.rst new file mode 100644 index 000000000..63c3617a2 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_wtf-1.2.2.dist-info/licenses/LICENSE.rst @@ -0,0 +1,28 @@ +Copyright 2010 WTForms + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A +PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED +TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_wtf/__init__.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_wtf/__init__.py new file mode 100644 index 000000000..c152a7695 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_wtf/__init__.py @@ -0,0 +1,16 @@ +from .csrf import CSRFProtect +from .form import FlaskForm +from .form import Form +from .recaptcha import Recaptcha +from .recaptcha import RecaptchaField +from .recaptcha import RecaptchaWidget + +__version__ = "1.2.2" +__all__ = [ + "CSRFProtect", + "FlaskForm", + "Form", + "Recaptcha", + "RecaptchaField", + "RecaptchaWidget", +] diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_wtf/_compat.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_wtf/_compat.py new file mode 100644 index 000000000..50973e063 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_wtf/_compat.py @@ -0,0 +1,11 @@ +import warnings + + +class FlaskWTFDeprecationWarning(DeprecationWarning): + pass + + +warnings.simplefilter("always", FlaskWTFDeprecationWarning) +warnings.filterwarnings( + "ignore", category=FlaskWTFDeprecationWarning, module="wtforms|flask_wtf" +) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_wtf/csrf.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_wtf/csrf.py new file mode 100644 index 000000000..06afa0cd4 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_wtf/csrf.py @@ -0,0 +1,329 @@ +import hashlib +import hmac +import logging +import os +from urllib.parse import urlparse + +from flask import Blueprint +from flask import current_app +from flask import g +from flask import request +from flask import session +from itsdangerous import BadData +from itsdangerous import SignatureExpired +from itsdangerous import URLSafeTimedSerializer +from werkzeug.exceptions import BadRequest +from wtforms import ValidationError +from wtforms.csrf.core import CSRF + +__all__ = ("generate_csrf", "validate_csrf", "CSRFProtect") +logger = logging.getLogger(__name__) + + +def generate_csrf(secret_key=None, token_key=None): + """Generate a CSRF token. The token is cached for a request, so multiple + calls to this function will generate the same token. + + During testing, it might be useful to access the signed token in + ``g.csrf_token`` and the raw token in ``session['csrf_token']``. + + :param secret_key: Used to securely sign the token. Default is + ``WTF_CSRF_SECRET_KEY`` or ``SECRET_KEY``. + :param token_key: Key where token is stored in session for comparison. + Default is ``WTF_CSRF_FIELD_NAME`` or ``'csrf_token'``. + """ + + secret_key = _get_config( + secret_key, + "WTF_CSRF_SECRET_KEY", + current_app.secret_key, + message="A secret key is required to use CSRF.", + ) + field_name = _get_config( + token_key, + "WTF_CSRF_FIELD_NAME", + "csrf_token", + message="A field name is required to use CSRF.", + ) + + if field_name not in g: + s = URLSafeTimedSerializer(secret_key, salt="wtf-csrf-token") + + if field_name not in session: + session[field_name] = hashlib.sha1(os.urandom(64)).hexdigest() + + try: + token = s.dumps(session[field_name]) + except TypeError: + session[field_name] = hashlib.sha1(os.urandom(64)).hexdigest() + token = s.dumps(session[field_name]) + + setattr(g, field_name, token) + + return g.get(field_name) + + +def validate_csrf(data, secret_key=None, time_limit=None, token_key=None): + """Check if the given data is a valid CSRF token. This compares the given + signed token to the one stored in the session. + + :param data: The signed CSRF token to be checked. + :param secret_key: Used to securely sign the token. Default is + ``WTF_CSRF_SECRET_KEY`` or ``SECRET_KEY``. + :param time_limit: Number of seconds that the token is valid. Default is + ``WTF_CSRF_TIME_LIMIT`` or 3600 seconds (60 minutes). + :param token_key: Key where token is stored in session for comparison. + Default is ``WTF_CSRF_FIELD_NAME`` or ``'csrf_token'``. + + :raises ValidationError: Contains the reason that validation failed. + + .. versionchanged:: 0.14 + Raises ``ValidationError`` with a specific error message rather than + returning ``True`` or ``False``. + """ + + secret_key = _get_config( + secret_key, + "WTF_CSRF_SECRET_KEY", + current_app.secret_key, + message="A secret key is required to use CSRF.", + ) + field_name = _get_config( + token_key, + "WTF_CSRF_FIELD_NAME", + "csrf_token", + message="A field name is required to use CSRF.", + ) + time_limit = _get_config(time_limit, "WTF_CSRF_TIME_LIMIT", 3600, required=False) + + if not data: + raise ValidationError("The CSRF token is missing.") + + if field_name not in session: + raise ValidationError("The CSRF session token is missing.") + + s = URLSafeTimedSerializer(secret_key, salt="wtf-csrf-token") + + try: + token = s.loads(data, max_age=time_limit) + except SignatureExpired as e: + raise ValidationError("The CSRF token has expired.") from e + except BadData as e: + raise ValidationError("The CSRF token is invalid.") from e + + if not hmac.compare_digest(session[field_name], token): + raise ValidationError("The CSRF tokens do not match.") + + +def _get_config( + value, config_name, default=None, required=True, message="CSRF is not configured." +): + """Find config value based on provided value, Flask config, and default + value. + + :param value: already provided config value + :param config_name: Flask ``config`` key + :param default: default value if not provided or configured + :param required: whether the value must not be ``None`` + :param message: error message if required config is not found + :raises KeyError: if required config is not found + """ + + if value is None: + value = current_app.config.get(config_name, default) + + if required and value is None: + raise RuntimeError(message) + + return value + + +class _FlaskFormCSRF(CSRF): + def setup_form(self, form): + self.meta = form.meta + return super().setup_form(form) + + def generate_csrf_token(self, csrf_token_field): + return generate_csrf( + secret_key=self.meta.csrf_secret, token_key=self.meta.csrf_field_name + ) + + def validate_csrf_token(self, form, field): + if g.get("csrf_valid", False): + # already validated by CSRFProtect + return + + try: + validate_csrf( + field.data, + self.meta.csrf_secret, + self.meta.csrf_time_limit, + self.meta.csrf_field_name, + ) + except ValidationError as e: + logger.info(e.args[0]) + raise + + +class CSRFProtect: + """Enable CSRF protection globally for a Flask app. + + :: + + app = Flask(__name__) + csrf = CSRFProtect(app) + + Checks the ``csrf_token`` field sent with forms, or the ``X-CSRFToken`` + header sent with JavaScript requests. Render the token in templates using + ``{{ csrf_token() }}``. + + See the :ref:`csrf` documentation. + """ + + def __init__(self, app=None): + self._exempt_views = set() + self._exempt_blueprints = set() + + if app: + self.init_app(app) + + def init_app(self, app): + app.extensions["csrf"] = self + + app.config.setdefault("WTF_CSRF_ENABLED", True) + app.config.setdefault("WTF_CSRF_CHECK_DEFAULT", True) + app.config["WTF_CSRF_METHODS"] = set( + app.config.get("WTF_CSRF_METHODS", ["POST", "PUT", "PATCH", "DELETE"]) + ) + app.config.setdefault("WTF_CSRF_FIELD_NAME", "csrf_token") + app.config.setdefault("WTF_CSRF_HEADERS", ["X-CSRFToken", "X-CSRF-Token"]) + app.config.setdefault("WTF_CSRF_TIME_LIMIT", 3600) + app.config.setdefault("WTF_CSRF_SSL_STRICT", True) + + app.jinja_env.globals["csrf_token"] = generate_csrf + app.context_processor(lambda: {"csrf_token": generate_csrf}) + + @app.before_request + def csrf_protect(): + if not app.config["WTF_CSRF_ENABLED"]: + return + + if not app.config["WTF_CSRF_CHECK_DEFAULT"]: + return + + if request.method not in app.config["WTF_CSRF_METHODS"]: + return + + if not request.endpoint: + return + + if app.blueprints.get(request.blueprint) in self._exempt_blueprints: + return + + view = app.view_functions.get(request.endpoint) + dest = f"{view.__module__}.{view.__name__}" + + if dest in self._exempt_views: + return + + self.protect() + + def _get_csrf_token(self): + # find the token in the form data + field_name = current_app.config["WTF_CSRF_FIELD_NAME"] + base_token = request.form.get(field_name) + + if base_token: + return base_token + + # if the form has a prefix, the name will be {prefix}-csrf_token + for key in request.form: + if key.endswith(field_name): + csrf_token = request.form[key] + + if csrf_token: + return csrf_token + + # find the token in the headers + for header_name in current_app.config["WTF_CSRF_HEADERS"]: + csrf_token = request.headers.get(header_name) + + if csrf_token: + return csrf_token + + return None + + def protect(self): + if request.method not in current_app.config["WTF_CSRF_METHODS"]: + return + + try: + validate_csrf(self._get_csrf_token()) + except ValidationError as e: + logger.info(e.args[0]) + self._error_response(e.args[0]) + + if request.is_secure and current_app.config["WTF_CSRF_SSL_STRICT"]: + if not request.referrer: + self._error_response("The referrer header is missing.") + + good_referrer = f"https://{request.host}/" + + if not same_origin(request.referrer, good_referrer): + self._error_response("The referrer does not match the host.") + + g.csrf_valid = True # mark this request as CSRF valid + + def exempt(self, view): + """Mark a view or blueprint to be excluded from CSRF protection. + + :: + + @app.route('/some-view', methods=['POST']) + @csrf.exempt + def some_view(): + ... + + :: + + bp = Blueprint(...) + csrf.exempt(bp) + + """ + + if isinstance(view, Blueprint): + self._exempt_blueprints.add(view) + return view + + if isinstance(view, str): + view_location = view + else: + view_location = ".".join((view.__module__, view.__name__)) + + self._exempt_views.add(view_location) + return view + + def _error_response(self, reason): + raise CSRFError(reason) + + +class CSRFError(BadRequest): + """Raise if the client sends invalid CSRF data with the request. + + Generates a 400 Bad Request response with the failure reason by default. + Customize the response by registering a handler with + :meth:`flask.Flask.errorhandler`. + """ + + description = "CSRF validation failed." + + +def same_origin(current_uri, compare_uri): + current = urlparse(current_uri) + compare = urlparse(compare_uri) + + return ( + current.scheme == compare.scheme + and current.hostname == compare.hostname + and current.port == compare.port + ) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_wtf/file.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_wtf/file.py new file mode 100644 index 000000000..98c45770d --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_wtf/file.py @@ -0,0 +1,146 @@ +from collections import abc + +from werkzeug.datastructures import FileStorage +from wtforms import FileField as _FileField +from wtforms import MultipleFileField as _MultipleFileField +from wtforms.validators import DataRequired +from wtforms.validators import StopValidation +from wtforms.validators import ValidationError + + +class FileField(_FileField): + """Werkzeug-aware subclass of :class:`wtforms.fields.FileField`.""" + + def process_formdata(self, valuelist): + valuelist = (x for x in valuelist if isinstance(x, FileStorage) and x) + data = next(valuelist, None) + + if data is not None: + self.data = data + else: + self.raw_data = () + + +class MultipleFileField(_MultipleFileField): + """Werkzeug-aware subclass of :class:`wtforms.fields.MultipleFileField`. + + .. versionadded:: 1.2.0 + """ + + def process_formdata(self, valuelist): + valuelist = (x for x in valuelist if isinstance(x, FileStorage) and x) + data = list(valuelist) or None + + if data is not None: + self.data = data + else: + self.raw_data = () + + +class FileRequired(DataRequired): + """Validates that the uploaded files(s) is a Werkzeug + :class:`~werkzeug.datastructures.FileStorage` object. + + :param message: error message + + You can also use the synonym ``file_required``. + """ + + def __call__(self, form, field): + field_data = [field.data] if not isinstance(field.data, list) else field.data + if not ( + all(isinstance(x, FileStorage) and x for x in field_data) and field_data + ): + raise StopValidation( + self.message or field.gettext("This field is required.") + ) + + +file_required = FileRequired + + +class FileAllowed: + """Validates that the uploaded file(s) is allowed by a given list of + extensions or a Flask-Uploads :class:`~flaskext.uploads.UploadSet`. + + :param upload_set: A list of extensions or an + :class:`~flaskext.uploads.UploadSet` + :param message: error message + + You can also use the synonym ``file_allowed``. + """ + + def __init__(self, upload_set, message=None): + self.upload_set = upload_set + self.message = message + + def __call__(self, form, field): + field_data = [field.data] if not isinstance(field.data, list) else field.data + if not ( + all(isinstance(x, FileStorage) and x for x in field_data) and field_data + ): + return + + filenames = [f.filename.lower() for f in field_data] + + for filename in filenames: + if isinstance(self.upload_set, abc.Iterable): + if any(filename.endswith("." + x) for x in self.upload_set): + continue + + raise StopValidation( + self.message + or field.gettext( + "File does not have an approved extension: {extensions}" + ).format(extensions=", ".join(self.upload_set)) + ) + + if not self.upload_set.file_allowed(field_data, filename): + raise StopValidation( + self.message + or field.gettext("File does not have an approved extension.") + ) + + +file_allowed = FileAllowed + + +class FileSize: + """Validates that the uploaded file(s) is within a minimum and maximum + file size (set in bytes). + + :param min_size: minimum allowed file size (in bytes). Defaults to 0 bytes. + :param max_size: maximum allowed file size (in bytes). + :param message: error message + + You can also use the synonym ``file_size``. + """ + + def __init__(self, max_size, min_size=0, message=None): + self.min_size = min_size + self.max_size = max_size + self.message = message + + def __call__(self, form, field): + field_data = [field.data] if not isinstance(field.data, list) else field.data + if not ( + all(isinstance(x, FileStorage) and x for x in field_data) and field_data + ): + return + + for f in field_data: + file_size = len(f.read()) + f.seek(0) # reset cursor position to beginning of file + + if (file_size < self.min_size) or (file_size > self.max_size): + # the file is too small or too big => validation failure + raise ValidationError( + self.message + or field.gettext( + f"File must be between {self.min_size}" + f" and {self.max_size} bytes." + ) + ) + + +file_size = FileSize diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_wtf/form.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_wtf/form.py new file mode 100644 index 000000000..c7f52e022 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_wtf/form.py @@ -0,0 +1,127 @@ +from flask import current_app +from flask import request +from flask import session +from markupsafe import Markup +from werkzeug.datastructures import CombinedMultiDict +from werkzeug.datastructures import ImmutableMultiDict +from werkzeug.utils import cached_property +from wtforms import Form +from wtforms.meta import DefaultMeta +from wtforms.widgets import HiddenInput + +from .csrf import _FlaskFormCSRF + +try: + from .i18n import translations +except ImportError: + translations = None # babel not installed + + +SUBMIT_METHODS = {"POST", "PUT", "PATCH", "DELETE"} +_Auto = object() + + +class FlaskForm(Form): + """Flask-specific subclass of WTForms :class:`~wtforms.form.Form`. + + If ``formdata`` is not specified, this will use :attr:`flask.request.form` + and :attr:`flask.request.files`. Explicitly pass ``formdata=None`` to + prevent this. + """ + + class Meta(DefaultMeta): + csrf_class = _FlaskFormCSRF + csrf_context = session # not used, provided for custom csrf_class + + @cached_property + def csrf(self): + return current_app.config.get("WTF_CSRF_ENABLED", True) + + @cached_property + def csrf_secret(self): + return current_app.config.get("WTF_CSRF_SECRET_KEY", current_app.secret_key) + + @cached_property + def csrf_field_name(self): + return current_app.config.get("WTF_CSRF_FIELD_NAME", "csrf_token") + + @cached_property + def csrf_time_limit(self): + return current_app.config.get("WTF_CSRF_TIME_LIMIT", 3600) + + def wrap_formdata(self, form, formdata): + if formdata is _Auto: + if _is_submitted(): + if request.files: + return CombinedMultiDict((request.files, request.form)) + elif request.form: + return request.form + elif request.is_json: + return ImmutableMultiDict(request.get_json()) + + return None + + return formdata + + def get_translations(self, form): + if not current_app.config.get("WTF_I18N_ENABLED", True): + return super().get_translations(form) + + return translations + + def __init__(self, formdata=_Auto, **kwargs): + super().__init__(formdata=formdata, **kwargs) + + def is_submitted(self): + """Consider the form submitted if there is an active request and + the method is ``POST``, ``PUT``, ``PATCH``, or ``DELETE``. + """ + + return _is_submitted() + + def validate_on_submit(self, extra_validators=None): + """Call :meth:`validate` only if the form is submitted. + This is a shortcut for ``form.is_submitted() and form.validate()``. + """ + return self.is_submitted() and self.validate(extra_validators=extra_validators) + + def hidden_tag(self, *fields): + """Render the form's hidden fields in one call. + + A field is considered hidden if it uses the + :class:`~wtforms.widgets.HiddenInput` widget. + + If ``fields`` are given, only render the given fields that + are hidden. If a string is passed, render the field with that + name if it exists. + + .. versionchanged:: 0.13 + + No longer wraps inputs in hidden div. + This is valid HTML 5. + + .. versionchanged:: 0.13 + + Skip passed fields that aren't hidden. + Skip passed names that don't exist. + """ + + def hidden_fields(fields): + for f in fields: + if isinstance(f, str): + f = getattr(self, f, None) + + if f is None or not isinstance(f.widget, HiddenInput): + continue + + yield f + + return Markup("\n".join(str(f) for f in hidden_fields(fields or self))) + + +def _is_submitted(): + """Consider the form submitted if there is an active request and + the method is ``POST``, ``PUT``, ``PATCH``, or ``DELETE``. + """ + + return bool(request) and request.method in SUBMIT_METHODS diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_wtf/i18n.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_wtf/i18n.py new file mode 100644 index 000000000..1cc0e9c5a --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_wtf/i18n.py @@ -0,0 +1,47 @@ +from babel import support +from flask import current_app +from flask import request +from flask_babel import get_locale +from wtforms.i18n import messages_path + +__all__ = ("Translations", "translations") + + +def _get_translations(): + """Returns the correct gettext translations. + Copy from flask-babel with some modifications. + """ + + if not request: + return None + + # babel should be in extensions for get_locale + if "babel" not in current_app.extensions: + return None + + translations = getattr(request, "wtforms_translations", None) + + if translations is None: + translations = support.Translations.load( + messages_path(), [get_locale()], domain="wtforms" + ) + request.wtforms_translations = translations + + return translations + + +class Translations: + def gettext(self, string): + t = _get_translations() + return string if t is None else t.ugettext(string) + + def ngettext(self, singular, plural, n): + t = _get_translations() + + if t is None: + return singular if n == 1 else plural + + return t.ungettext(singular, plural, n) + + +translations = Translations() diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_wtf/recaptcha/__init__.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_wtf/recaptcha/__init__.py new file mode 100644 index 000000000..c414a9fbb --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_wtf/recaptcha/__init__.py @@ -0,0 +1,5 @@ +from .fields import RecaptchaField +from .validators import Recaptcha +from .widgets import RecaptchaWidget + +__all__ = ["RecaptchaField", "RecaptchaWidget", "Recaptcha"] diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_wtf/recaptcha/fields.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_wtf/recaptcha/fields.py new file mode 100644 index 000000000..e91fd092f --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_wtf/recaptcha/fields.py @@ -0,0 +1,17 @@ +from wtforms.fields import Field + +from . import widgets +from .validators import Recaptcha + +__all__ = ["RecaptchaField"] + + +class RecaptchaField(Field): + widget = widgets.RecaptchaWidget() + + # error message if recaptcha validation fails + recaptcha_error = None + + def __init__(self, label="", validators=None, **kwargs): + validators = validators or [Recaptcha()] + super().__init__(label, validators, **kwargs) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_wtf/recaptcha/validators.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_wtf/recaptcha/validators.py new file mode 100644 index 000000000..c5cafb347 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_wtf/recaptcha/validators.py @@ -0,0 +1,75 @@ +import json +from urllib import request as http +from urllib.parse import urlencode + +from flask import current_app +from flask import request +from wtforms import ValidationError + +RECAPTCHA_VERIFY_SERVER_DEFAULT = "https://www.google.com/recaptcha/api/siteverify" +RECAPTCHA_ERROR_CODES = { + "missing-input-secret": "The secret parameter is missing.", + "invalid-input-secret": "The secret parameter is invalid or malformed.", + "missing-input-response": "The response parameter is missing.", + "invalid-input-response": "The response parameter is invalid or malformed.", +} + + +__all__ = ["Recaptcha"] + + +class Recaptcha: + """Validates a ReCaptcha.""" + + def __init__(self, message=None): + if message is None: + message = RECAPTCHA_ERROR_CODES["missing-input-response"] + self.message = message + + def __call__(self, form, field): + if current_app.testing: + return True + + if request.is_json: + response = request.json.get("g-recaptcha-response", "") + else: + response = request.form.get("g-recaptcha-response", "") + remote_ip = request.remote_addr + + if not response: + raise ValidationError(field.gettext(self.message)) + + if not self._validate_recaptcha(response, remote_ip): + field.recaptcha_error = "incorrect-captcha-sol" + raise ValidationError(field.gettext(self.message)) + + def _validate_recaptcha(self, response, remote_addr): + """Performs the actual validation.""" + try: + private_key = current_app.config["RECAPTCHA_PRIVATE_KEY"] + except KeyError: + raise RuntimeError("No RECAPTCHA_PRIVATE_KEY config set") from None + + verify_server = current_app.config.get("RECAPTCHA_VERIFY_SERVER") + if not verify_server: + verify_server = RECAPTCHA_VERIFY_SERVER_DEFAULT + + data = urlencode( + {"secret": private_key, "remoteip": remote_addr, "response": response} + ) + + http_response = http.urlopen(verify_server, data.encode("utf-8")) + + if http_response.code != 200: + return False + + json_resp = json.loads(http_response.read()) + + if json_resp["success"]: + return True + + for error in json_resp.get("error-codes", []): + if error in RECAPTCHA_ERROR_CODES: + raise ValidationError(RECAPTCHA_ERROR_CODES[error]) + + return False diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_wtf/recaptcha/widgets.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_wtf/recaptcha/widgets.py new file mode 100644 index 000000000..bfae830bb --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/flask_wtf/recaptcha/widgets.py @@ -0,0 +1,43 @@ +from urllib.parse import urlencode + +from flask import current_app +from markupsafe import Markup + +RECAPTCHA_SCRIPT_DEFAULT = "https://www.google.com/recaptcha/api.js" +RECAPTCHA_DIV_CLASS_DEFAULT = "g-recaptcha" +RECAPTCHA_TEMPLATE = """ + +
+""" + +__all__ = ["RecaptchaWidget"] + + +class RecaptchaWidget: + def recaptcha_html(self, public_key): + html = current_app.config.get("RECAPTCHA_HTML") + if html: + return Markup(html) + params = current_app.config.get("RECAPTCHA_PARAMETERS") + script = current_app.config.get("RECAPTCHA_SCRIPT") + if not script: + script = RECAPTCHA_SCRIPT_DEFAULT + if params: + script += "?" + urlencode(params) + attrs = current_app.config.get("RECAPTCHA_DATA_ATTRS", {}) + attrs["sitekey"] = public_key + snippet = " ".join(f'data-{k}="{attrs[k]}"' for k in attrs) # noqa: B028, B907 + div_class = current_app.config.get("RECAPTCHA_DIV_CLASS") + if not div_class: + div_class = RECAPTCHA_DIV_CLASS_DEFAULT + return Markup(RECAPTCHA_TEMPLATE % (script, div_class, snippet)) + + def __call__(self, field, error=None, **kwargs): + """Returns the recaptcha input HTML.""" + + try: + public_key = current_app.config["RECAPTCHA_PUBLIC_KEY"] + except KeyError: + raise RuntimeError("RECAPTCHA_PUBLIC_KEY config not set") from None + + return self.recaptcha_html(public_key) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet-3.4.0.dist-info/INSTALLER b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet-3.4.0.dist-info/INSTALLER new file mode 100644 index 000000000..a1b589e38 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet-3.4.0.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet-3.4.0.dist-info/METADATA b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet-3.4.0.dist-info/METADATA new file mode 100644 index 000000000..dc123ec7f --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet-3.4.0.dist-info/METADATA @@ -0,0 +1,98 @@ +Metadata-Version: 2.4 +Name: greenlet +Version: 3.4.0 +Summary: Lightweight in-process concurrent programming +Author-email: Alexey Borzenkov +Maintainer-email: Jason Madden +License-Expression: MIT AND PSF-2.0 +Project-URL: Homepage, https://greenlet.readthedocs.io +Project-URL: Documentation, https://greenlet.readthedocs.io +Project-URL: Repository, https://github.com/python-greenlet/greenlet +Project-URL: Issues, https://github.com/python-greenlet/greenlet/issues +Project-URL: Changelog, https://greenlet.readthedocs.io/en/latest/changes.html +Keywords: greenlet,coroutine,concurrency,threads,cooperative +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: Natural Language :: English +Classifier: Programming Language :: C +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Programming Language :: Python :: 3.14 +Classifier: Operating System :: OS Independent +Classifier: Topic :: Software Development :: Libraries :: Python Modules +Requires-Python: >=3.10 +Description-Content-Type: text/x-rst +License-File: LICENSE +License-File: LICENSE.PSF +Provides-Extra: docs +Requires-Dist: Sphinx; extra == "docs" +Requires-Dist: furo; extra == "docs" +Provides-Extra: test +Requires-Dist: objgraph; extra == "test" +Requires-Dist: psutil; extra == "test" +Requires-Dist: setuptools; extra == "test" +Dynamic: license-file + +.. This file is included into docs/history.rst + + +Greenlets are lightweight coroutines for in-process concurrent +programming. + +The "greenlet" package is a spin-off of `Stackless`_, a version of +CPython that supports micro-threads called "tasklets". Tasklets run +pseudo-concurrently (typically in a single or a few OS-level threads) +and are synchronized with data exchanges on "channels". + +A "greenlet", on the other hand, is a still more primitive notion of +micro-thread with no implicit scheduling; coroutines, in other words. +This is useful when you want to control exactly when your code runs. +You can build custom scheduled micro-threads on top of greenlet; +however, it seems that greenlets are useful on their own as a way to +make advanced control flow structures. For example, we can recreate +generators; the difference with Python's own generators is that our +generators can call nested functions and the nested functions can +yield values too. (Additionally, you don't need a "yield" keyword. See +the example in `test_generator.py +`_). + +Greenlets are provided as a C extension module for the regular unmodified +interpreter. + +.. _`Stackless`: http://www.stackless.com + + +Who is using Greenlet? +====================== + +There are several libraries that use Greenlet as a more flexible +alternative to Python's built in coroutine support: + + - `Concurrence`_ + - `Eventlet`_ + - `Gevent`_ + +.. _Concurrence: http://opensource.hyves.org/concurrence/ +.. _Eventlet: http://eventlet.net/ +.. _Gevent: http://www.gevent.org/ + +Getting Greenlet +================ + +The easiest way to get Greenlet is to install it with pip:: + + pip install greenlet + + +Source code archives and binary distributions are available on the +python package index at https://pypi.org/project/greenlet + +The source code repository is hosted on github: +https://github.com/python-greenlet/greenlet + +Documentation is available on readthedocs.org: +https://greenlet.readthedocs.io diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet-3.4.0.dist-info/RECORD b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet-3.4.0.dist-info/RECORD new file mode 100644 index 000000000..3af3cb39f --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet-3.4.0.dist-info/RECORD @@ -0,0 +1,123 @@ +../../../include/site/python3.12/greenlet/greenlet.h,sha256=sz5pYRSQqedgOt2AMgxLZdTjO-qcr_JMvgiEJR9IAJ8,4755 +greenlet-3.4.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +greenlet-3.4.0.dist-info/METADATA,sha256=-zIXBbzIyLO2Novm22C_WqFPK7m9UAla82dLVW8cNCA,3731 +greenlet-3.4.0.dist-info/RECORD,, +greenlet-3.4.0.dist-info/WHEEL,sha256=CBghnJIUYaoRKC7n2UtUahcLsAwN9MrFKB4Pz3esY5k,152 +greenlet-3.4.0.dist-info/licenses/LICENSE,sha256=dpgx1uXfrywggC-sz_H6-0wgJd2PYlPfpH_K1Z1NCXk,1434 +greenlet-3.4.0.dist-info/licenses/LICENSE.PSF,sha256=5f88I8EQ5JTNfXNsEP2W1GJFe6_soxCEDbZScpjH1Gs,2424 +greenlet-3.4.0.dist-info/top_level.txt,sha256=YSnRsCRoO61JGlP57o8iKL6rdLWDWuiyKD8ekpWUsDc,9 +greenlet/CObjects.cpp,sha256=d3VEawuIDUwXGo31lapKVrSuxCbMw5lM4iIMH-kxlMY,3576 +greenlet/PyGreenlet.cpp,sha256=Hxw2rfecEE93vx_4Te8LRW7vqlI7-BImno1rO9Ja2ws,28184 +greenlet/PyGreenlet.hpp,sha256=2ZQlOxYNoy7QwD7mppFoOXe_At56NIsJ0eNsE_hoSsw,1463 +greenlet/PyGreenletUnswitchable.cpp,sha256=XxpqPaQLOXaEcWTTfKMS8R7Osa3yzp7B_QYbFzxc0ck,4156 +greenlet/PyModule.cpp,sha256=vGk4BVdxo4Tc_sH3ozQVDszT-WoopEkkwrgikOavzPk,9004 +greenlet/TBrokenGreenlet.cpp,sha256=smN26uC7ahAbNYiS10rtWPjCeTG4jevM8siA2sjJiXg,1021 +greenlet/TExceptionState.cpp,sha256=U7Ctw9fBdNraS0d174MoQW7bN-ae209Ta0JuiKpcpVI,1359 +greenlet/TGreenlet.cpp,sha256=cZHRBkMd91Zpz74aNsfq-hpQ_AO37q7B2aczBUFlQec,26239 +greenlet/TGreenlet.hpp,sha256=2X-bj7eDHgbIfK2clNvUExAwC-NH3I3U_ATPeY9tNJ4,29262 +greenlet/TGreenletGlobals.cpp,sha256=Amj0iOP_JUqfDfYeqtw_K4KlNcKR2cqDGuU6A6W8nJs,3930 +greenlet/TMainGreenlet.cpp,sha256=ghEHPdjAnc1eMcEo8ag00fZPR_JeM8aJby8l_IQewtc,3593 +greenlet/TPythonState.cpp,sha256=SMRBgdWNiJNYYy4tquU1u64gWKmflrlucvBEQAvp53Q,19610 +greenlet/TStackState.cpp,sha256=V444I8Jj9DhQz-9leVW_9dtiSRjaE1NMlgDG02Xxq-Y,7381 +greenlet/TThreadState.hpp,sha256=tGZwsV8DWv7cZ0dB8cUuBRMXYrdHFJniao8gdfoMYTI,23902 +greenlet/TThreadStateCreator.hpp,sha256=WIOSdT0Ey6KFqnM9qj3D95s9q7kUFsTSBgEQG3bbfJI,2767 +greenlet/TThreadStateDestroy.cpp,sha256=sUWjvJ4hT9nbJd6k9JLwjDqFcv2TdFaO_X9d41RbgoE,8178 +greenlet/TUserGreenlet.cpp,sha256=lR4nUD_lY7u1P2Y-I0gminmdH7j1aOB54i6912az6UE,24333 +greenlet/__init__.py,sha256=fEcPHPYCYtWuL6BpqgyIk1ugnoOIp0yBqf9LJlD6VaU,1442 +greenlet/__pycache__/__init__.cpython-312.pyc,, +greenlet/_greenlet.cpython-312-x86_64-linux-gnu.so,sha256=fWWJrs7dDXAutXFVZiHP7hqQcZG3A76Yr08PKlmQzd0,1400064 +greenlet/greenlet.cpp,sha256=-Wb-4wm4D64pUW_cawaJqZi0-EqcbHD1hea_AY42Ioc,12121 +greenlet/greenlet.h,sha256=sz5pYRSQqedgOt2AMgxLZdTjO-qcr_JMvgiEJR9IAJ8,4755 +greenlet/greenlet_allocator.hpp,sha256=n28rwj76RVSn7B5QDA00nL8OBjfFeiOM1QGrVrHhfsk,1835 +greenlet/greenlet_compiler_compat.hpp,sha256=nRxpLN9iNbnLVyFDeVmOwyeeNm6scQrOed1l7JQYMCM,4346 +greenlet/greenlet_cpython_compat.hpp,sha256=Mo2YqcvZsC7ZaWQTXOL7oyfpSjo-7nExMhus0KXx2TU,3325 +greenlet/greenlet_exceptions.hpp,sha256=06Bx81DtVaJTa6RtiMcV141b-XHv4ppEgVItkblcLWY,4503 +greenlet/greenlet_internal.hpp,sha256=YCqnF6tbiWDlInNiZ5AU9RG8iC3dQlGFr8lk_JMtY2Q,2768 +greenlet/greenlet_msvc_compat.hpp,sha256=Lg5xtV5zrRMIGcoieMKmXPhEzXu55aqfM1L8OygnmAY,3195 +greenlet/greenlet_refs.hpp,sha256=tpLilLSty3QMnlZbURQRwYDUGIsi2-WplQzLyFxQwQo,36351 +greenlet/greenlet_slp_switch.hpp,sha256=T1Y-w01yBBljePiHgUaWCs3XZSdtHSrtLvvkMXFDUN4,3298 +greenlet/greenlet_thread_support.hpp,sha256=XUJ6ljWjf9OYyuOILiz8e_yHvT3fbaUiHdhiPNQUV4s,867 +greenlet/platform/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +greenlet/platform/__pycache__/__init__.cpython-312.pyc,, +greenlet/platform/setup_switch_x64_masm.cmd,sha256=ZpClUJeU0ujEPSTWNSepP0W2f9XiYQKA8QKSoVou8EU,143 +greenlet/platform/switch_aarch64_gcc.h,sha256=GKC0yWNXnbK2X--X6aguRCMj2Tg7hDU1Zkl3RljDvC8,4307 +greenlet/platform/switch_alpha_unix.h,sha256=Z-SvF8JQV3oxWT8JRbL9RFu4gRFxPdJ7cviM8YayMmw,671 +greenlet/platform/switch_amd64_unix.h,sha256=EcSFCBlodEBhqhKjcJqY_5Dn_jn7pKpkJlOvp7gFXLI,2748 +greenlet/platform/switch_arm32_gcc.h,sha256=Z3KkHszdgq6uU4YN3BxvKMG2AdDnovwCCNrqGWZ1Lyo,2479 +greenlet/platform/switch_arm32_ios.h,sha256=mm5_R9aXB92hyxzFRwB71M60H6AlvHjrpTrc72Pz3l8,1892 +greenlet/platform/switch_arm64_masm.asm,sha256=4kpTtfy7rfcr8j1CpJLAK21EtZpGDAJXWRU68HEy5A8,1245 +greenlet/platform/switch_arm64_masm.obj,sha256=DmLnIB_icoEHAz1naue_pJPTZgR9ElM7-Nmztr-o9_U,746 +greenlet/platform/switch_arm64_msvc.h,sha256=RqK5MHLmXI3Q-FQ7tm32KWnbDNZKnkJdq8CR89cz640,398 +greenlet/platform/switch_csky_gcc.h,sha256=kDikyiPpewP71KoBZQO_MukDTXTXBiC7x-hF0_2DL0w,1331 +greenlet/platform/switch_loongarch64_linux.h,sha256=7M-Dhc4Q8tRbJCJhalDLwU6S9Mx8MjmN1RbTDgIvQTM,779 +greenlet/platform/switch_m68k_gcc.h,sha256=VSa6NpZhvyyvF-Q58CTIWSpEDo4FKygOyTz00whctlw,928 +greenlet/platform/switch_mips_unix.h,sha256=DsbNLh3Nde3WhnK5dwNaVu9r60iAWoCyEemxwBBOHBI,1462 +greenlet/platform/switch_ppc64_aix.h,sha256=_BL0iyRr3ZA5iPlr3uk9SJ5sNRWGYLrXcZ5z-CE9anE,3860 +greenlet/platform/switch_ppc64_linux.h,sha256=0rriT5XyxPb0GqsSSn_bP9iQsnjsPbBmu0yqo5goSyQ,3815 +greenlet/platform/switch_ppc_aix.h,sha256=pHA4slEjUFP3J3SYm1TAlNPhgb2G_PAtax5cO8BEe1A,2941 +greenlet/platform/switch_ppc_linux.h,sha256=YwrlKUzxlXuiKMQqr6MFAV1bPzWnmvk6X1AqJZEpOWU,2759 +greenlet/platform/switch_ppc_macosx.h,sha256=Z6KN_ud0n6nC3ltJrNz2qtvER6vnRAVRNH9mdIDpMxY,2624 +greenlet/platform/switch_ppc_unix.h,sha256=-ZG7MSSPEA5N4qO9PQChtyEJ-Fm6qInhyZm_ZBHTtMg,2652 +greenlet/platform/switch_riscv_unix.h,sha256=606V6ACDf79Fz_WGItnkgbjIJ0pGg_sHmPyDxQYKK58,949 +greenlet/platform/switch_s390_unix.h,sha256=RRlGu957ybmq95qNNY4Qw1mcaoT3eBnW5KbVwu48KX8,2763 +greenlet/platform/switch_sh_gcc.h,sha256=mcRJBTu-2UBf4kZtX601qofwuDuy-Y-hnxJtrcaB7do,901 +greenlet/platform/switch_sparc_sun_gcc.h,sha256=xZish9GsMHBienUbUMsX1-ZZ-as7hs36sVhYIE3ew8Y,2797 +greenlet/platform/switch_x32_unix.h,sha256=nM98PKtzTWc1lcM7TRMUZJzskVdR1C69U1UqZRWX0GE,1509 +greenlet/platform/switch_x64_masm.asm,sha256=nu6n2sWyXuXfpPx40d9YmLfHXUc1sHgeTvX1kUzuvEM,1841 +greenlet/platform/switch_x64_masm.obj,sha256=GNtTNxYdo7idFUYsQv-mrXWgyT5EJ93-9q90lN6svtQ,1078 +greenlet/platform/switch_x64_msvc.h,sha256=LIeasyKo_vHzspdMzMHbosRhrBfKI4BkQOh4qcTHyJw,1805 +greenlet/platform/switch_x86_msvc.h,sha256=TtGOwinbFfnn6clxMNkCz8i6OmgB6kVRrShoF5iT9to,12838 +greenlet/platform/switch_x86_unix.h,sha256=VplW9H0FF0cZHw1DhJdIUs5q6YLS4cwb2nYwjF83R1s,3059 +greenlet/slp_platformselect.h,sha256=hTb3GFdcPUYJTuu1MY93js7MZEax1_e5E-gflpi0RzI,3959 +greenlet/tests/__init__.py,sha256=EtTtQfpRDde0MhsdAM5Cm7LYIfS_HKUIFwquiH4Q7ac,9736 +greenlet/tests/__pycache__/__init__.cpython-312.pyc,, +greenlet/tests/__pycache__/fail_clearing_run_switches.cpython-312.pyc,, +greenlet/tests/__pycache__/fail_cpp_exception.cpython-312.pyc,, +greenlet/tests/__pycache__/fail_initialstub_already_started.cpython-312.pyc,, +greenlet/tests/__pycache__/fail_slp_switch.cpython-312.pyc,, +greenlet/tests/__pycache__/fail_switch_three_greenlets.cpython-312.pyc,, +greenlet/tests/__pycache__/fail_switch_three_greenlets2.cpython-312.pyc,, +greenlet/tests/__pycache__/fail_switch_two_greenlets.cpython-312.pyc,, +greenlet/tests/__pycache__/leakcheck.cpython-312.pyc,, +greenlet/tests/__pycache__/test_contextvars.cpython-312.pyc,, +greenlet/tests/__pycache__/test_cpp.cpython-312.pyc,, +greenlet/tests/__pycache__/test_extension_interface.cpython-312.pyc,, +greenlet/tests/__pycache__/test_gc.cpython-312.pyc,, +greenlet/tests/__pycache__/test_generator.cpython-312.pyc,, +greenlet/tests/__pycache__/test_generator_nested.cpython-312.pyc,, +greenlet/tests/__pycache__/test_greenlet.cpython-312.pyc,, +greenlet/tests/__pycache__/test_greenlet_trash.cpython-312.pyc,, +greenlet/tests/__pycache__/test_interpreter_shutdown.cpython-312.pyc,, +greenlet/tests/__pycache__/test_leaks.cpython-312.pyc,, +greenlet/tests/__pycache__/test_stack_saved.cpython-312.pyc,, +greenlet/tests/__pycache__/test_throw.cpython-312.pyc,, +greenlet/tests/__pycache__/test_tracing.cpython-312.pyc,, +greenlet/tests/__pycache__/test_version.cpython-312.pyc,, +greenlet/tests/__pycache__/test_weakref.cpython-312.pyc,, +greenlet/tests/_test_extension.c,sha256=OjbrUaa2Xf9xUsbfzF5uZLR0tHJQJ60wrRr6G7Im92w,6987 +greenlet/tests/_test_extension.cpython-312-x86_64-linux-gnu.so,sha256=1i3wYKDt2Q2ZK-XEfW0YuoK3avbHkQQEUhui3rmt8kI,17256 +greenlet/tests/_test_extension_cpp.cpp,sha256=P2qtldzeOLTVdf7KS6il33KsO9mg2kUO0nmYbXvVFaE,6713 +greenlet/tests/_test_extension_cpp.cpython-312-x86_64-linux-gnu.so,sha256=VXR5JSi_kJCAgUA9UV3rbMaoTfKSzGdKr7Z3RYcFThg,58728 +greenlet/tests/fail_clearing_run_switches.py,sha256=o433oA_nUCtOPaMEGc8VEhZIKa71imVHXFw7TsXaP8M,1263 +greenlet/tests/fail_cpp_exception.py,sha256=o_ZbipWikok8Bjc-vjiQvcb5FHh2nVW-McGKMLcMzh0,985 +greenlet/tests/fail_initialstub_already_started.py,sha256=txENn5IyzGx2p-XR1XB7qXmC8JX_4mKDEA8kYBXUQKc,1961 +greenlet/tests/fail_slp_switch.py,sha256=rJBZcZfTWR3e2ERQtPAud6YKShiDsP84PmwOJbp4ey0,524 +greenlet/tests/fail_switch_three_greenlets.py,sha256=zSitV7rkNnaoHYVzAGGLnxz-yPtohXJJzaE8ehFDQ0M,956 +greenlet/tests/fail_switch_three_greenlets2.py,sha256=FPJensn2EJxoropl03JSTVP3kgP33k04h6aDWWozrOk,1285 +greenlet/tests/fail_switch_two_greenlets.py,sha256=1CaI8s3504VbbF1vj1uBYuy-zxBHVzHPIAd1LIc8ONg,817 +greenlet/tests/leakcheck.py,sha256=MYXge7xJUxNFYXnS6yOpHyFMF41RSkOf4-oWErcXy70,12613 +greenlet/tests/test_contextvars.py,sha256=bMWvdF26uxawPM2hSvuPscdvRAPwQE3gAM6qzqEtZgY,9564 +greenlet/tests/test_cpp.py,sha256=Q4sIw4Zrennpq0QMaFqV8i5bVUjh68Q67wjJGv5pT5A,3164 +greenlet/tests/test_extension_interface.py,sha256=U-6pKuoQrcJEIb4xtBP0uLh-RixwCnh-XryrwAXfAoU,4820 +greenlet/tests/test_gc.py,sha256=xrIreQr85eO8WlpHs6IWCa5C4ecIA6t2_IrkS76Fdjg,2922 +greenlet/tests/test_generator.py,sha256=tONXiTf98VGm347o1b-810daPiwdla5cbpFg6QI1R1g,1240 +greenlet/tests/test_generator_nested.py,sha256=7v4HOYrf1XZP39dk5IUMubdZ8yc3ynwZcqj9GUJyMSA,3718 +greenlet/tests/test_greenlet.py,sha256=wqZIrPhsheDkBAqLZ-qI_jlqAkDfvZOm0MoiN9dPkJw,50495 +greenlet/tests/test_greenlet_trash.py,sha256=M94zmemBACFQ1G9lfuqr2dCZMZ1YAQCagVuIn3O_TuI,8369 +greenlet/tests/test_interpreter_shutdown.py,sha256=E3ogc9h9lWsF__k-bJVESCfnmZMM7dHYkvPq7nVkJ9M,33309 +greenlet/tests/test_leaks.py,sha256=uoimfenpeFILMlkUaD5v0Vkrr1M7J6t-e4bzyl9WlW0,19242 +greenlet/tests/test_stack_saved.py,sha256=eyzqNY2VCGuGlxhT_In6TvZ6Okb0AXFZVyBEnK1jDwA,446 +greenlet/tests/test_throw.py,sha256=u2TQ_WvvCd6N6JdXWIxVEcXkKu5fepDlz9dktYdmtng,3712 +greenlet/tests/test_tracing.py,sha256=NwU4Z4z7Yt2ekv7GB8-dVM3aJ3ZMx1utqbpv_-KU5B8,8553 +greenlet/tests/test_version.py,sha256=8lk49x1wav1RWGpQk5MA8i_ZP-M0OhpHXUftuqVN72c,1528 +greenlet/tests/test_weakref.py,sha256=F8M23btEF87bIbpptLNBORosbQqNZGiYeKMqYjWrsak,883 diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet-3.4.0.dist-info/WHEEL b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet-3.4.0.dist-info/WHEEL new file mode 100644 index 000000000..c68a95b27 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet-3.4.0.dist-info/WHEEL @@ -0,0 +1,6 @@ +Wheel-Version: 1.0 +Generator: setuptools (82.0.1) +Root-Is-Purelib: false +Tag: cp312-cp312-manylinux_2_24_x86_64 +Tag: cp312-cp312-manylinux_2_28_x86_64 + diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet-3.4.0.dist-info/licenses/LICENSE b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet-3.4.0.dist-info/licenses/LICENSE new file mode 100644 index 000000000..b73a4a10c --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet-3.4.0.dist-info/licenses/LICENSE @@ -0,0 +1,30 @@ +The following files are derived from Stackless Python and are subject to the +same license as Stackless Python: + + src/greenlet/slp_platformselect.h + files in src/greenlet/platform/ directory + +See LICENSE.PSF and http://www.stackless.com/ for details. + +Unless otherwise noted, the files in greenlet have been released under the +following MIT license: + +Copyright (c) Armin Rigo, Christian Tismer and contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet-3.4.0.dist-info/licenses/LICENSE.PSF b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet-3.4.0.dist-info/licenses/LICENSE.PSF new file mode 100644 index 000000000..d3b509a2b --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet-3.4.0.dist-info/licenses/LICENSE.PSF @@ -0,0 +1,47 @@ +PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2 +-------------------------------------------- + +1. This LICENSE AGREEMENT is between the Python Software Foundation +("PSF"), and the Individual or Organization ("Licensee") accessing and +otherwise using this software ("Python") in source or binary form and +its associated documentation. + +2. Subject to the terms and conditions of this License Agreement, PSF hereby +grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce, +analyze, test, perform and/or display publicly, prepare derivative works, +distribute, and otherwise use Python alone or in any derivative version, +provided, however, that PSF's License Agreement and PSF's notice of copyright, +i.e., "Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, +2011 Python Software Foundation; All Rights Reserved" are retained in Python +alone or in any derivative version prepared by Licensee. + +3. In the event Licensee prepares a derivative work that is based on +or incorporates Python or any part thereof, and wants to make +the derivative work available to others as provided herein, then +Licensee hereby agrees to include in any such work a brief summary of +the changes made to Python. + +4. PSF is making Python available to Licensee on an "AS IS" +basis. PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR +IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND +DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS +FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON WILL NOT +INFRINGE ANY THIRD PARTY RIGHTS. + +5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON +FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS +A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON, +OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. + +6. This License Agreement will automatically terminate upon a material +breach of its terms and conditions. + +7. Nothing in this License Agreement shall be deemed to create any +relationship of agency, partnership, or joint venture between PSF and +Licensee. This License Agreement does not grant permission to use PSF +trademarks or trade name in a trademark sense to endorse or promote +products or services of Licensee, or any third party. + +8. By copying, installing or otherwise using Python, Licensee +agrees to be bound by the terms and conditions of this License +Agreement. diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet-3.4.0.dist-info/top_level.txt b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet-3.4.0.dist-info/top_level.txt new file mode 100644 index 000000000..46725be4f --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet-3.4.0.dist-info/top_level.txt @@ -0,0 +1 @@ +greenlet diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/CObjects.cpp b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/CObjects.cpp new file mode 100644 index 000000000..a5a9921bc --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/CObjects.cpp @@ -0,0 +1,160 @@ +#ifndef COBJECTS_CPP +#define COBJECTS_CPP +/***************************************************************************** + * C interface + * + * These are exported using the CObject API + */ +#ifdef __clang__ +# pragma clang diagnostic push +# pragma clang diagnostic ignored "-Wunused-function" +#endif + +#include "greenlet_exceptions.hpp" + +#include "greenlet_internal.hpp" +#include "greenlet_refs.hpp" + + +#include "TThreadStateDestroy.cpp" + +#include "PyGreenlet.hpp" + +using greenlet::PyErrOccurred; +using greenlet::Require; + + + +extern "C" { +static PyGreenlet* +PyGreenlet_GetCurrent(void) +{ + if (greenlet::IsShuttingDown()) { + return nullptr; + } + return GET_THREAD_STATE().state().get_current().relinquish_ownership(); +} + +static int +PyGreenlet_SetParent(PyGreenlet* g, PyGreenlet* nparent) +{ + return green_setparent((PyGreenlet*)g, (PyObject*)nparent, NULL); +} + +static PyGreenlet* +PyGreenlet_New(PyObject* run, PyGreenlet* parent) +{ + using greenlet::refs::NewDictReference; + // In the past, we didn't use green_new and green_init, but that + // was a maintenance issue because we duplicated code. This way is + // much safer, but slightly slower. If that's a problem, we could + // refactor green_init to separate argument parsing from initialization. + OwnedGreenlet g = OwnedGreenlet::consuming(green_new(&PyGreenlet_Type, nullptr, nullptr)); + if (!g) { + return NULL; + } + + try { + NewDictReference kwargs; + if (run) { + kwargs.SetItem(mod_globs->str_run, run); + } + if (parent) { + kwargs.SetItem("parent", (PyObject*)parent); + } + + Require(green_init(g.borrow(), mod_globs->empty_tuple, kwargs.borrow())); + } + catch (const PyErrOccurred&) { + return nullptr; + } + + return g.relinquish_ownership(); +} + +static PyObject* +PyGreenlet_Switch(PyGreenlet* self, PyObject* args, PyObject* kwargs) +{ + if (!PyGreenlet_Check(self)) { + PyErr_BadArgument(); + return NULL; + } + + if (args == NULL) { + args = mod_globs->empty_tuple; + } + + if (kwargs == NULL || !PyDict_Check(kwargs)) { + kwargs = NULL; + } + + return green_switch(self, args, kwargs); +} + +static PyObject* +PyGreenlet_Throw(PyGreenlet* self, PyObject* typ, PyObject* val, PyObject* tb) +{ + if (!PyGreenlet_Check(self)) { + PyErr_BadArgument(); + return nullptr; + } + try { + PyErrPieces err_pieces(typ, val, tb); + return internal_green_throw(self, err_pieces).relinquish_ownership(); + } + catch (const PyErrOccurred&) { + return nullptr; + } +} + + + +static int +Extern_PyGreenlet_MAIN(PyGreenlet* self) +{ + if (!PyGreenlet_Check(self)) { + PyErr_BadArgument(); + return -1; + } + return self->pimpl->main(); +} + +static int +Extern_PyGreenlet_ACTIVE(PyGreenlet* self) +{ + if (!PyGreenlet_Check(self)) { + PyErr_BadArgument(); + return -1; + } + return self->pimpl->active(); +} + +static int +Extern_PyGreenlet_STARTED(PyGreenlet* self) +{ + if (!PyGreenlet_Check(self)) { + PyErr_BadArgument(); + return -1; + } + return self->pimpl->started(); +} + +static PyGreenlet* +Extern_PyGreenlet_GET_PARENT(PyGreenlet* self) +{ + if (!PyGreenlet_Check(self)) { + PyErr_BadArgument(); + return NULL; + } + // This can return NULL even if there is no exception + return self->pimpl->parent().acquire(); +} +} // extern C. + +/** End C API ****************************************************************/ +#ifdef __clang__ +# pragma clang diagnostic pop +#endif + + +#endif diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/PyGreenlet.cpp b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/PyGreenlet.cpp new file mode 100644 index 000000000..b022d5c0a --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/PyGreenlet.cpp @@ -0,0 +1,841 @@ +/* -*- indent-tabs-mode: nil; tab-width: 4; -*- */ +#ifndef PYGREENLET_CPP +#define PYGREENLET_CPP +/***************** +The Python slot functions for TGreenlet. + */ + + +#define PY_SSIZE_T_CLEAN +#include +#include "structmember.h" // PyMemberDef + +#include "greenlet_internal.hpp" +#include "TThreadStateDestroy.cpp" +#include "TGreenlet.hpp" +// #include "TUserGreenlet.cpp" +// #include "TMainGreenlet.cpp" +// #include "TBrokenGreenlet.cpp" + + +#include "greenlet_refs.hpp" +#include "greenlet_slp_switch.hpp" + +#include "greenlet_thread_support.hpp" +#include "TGreenlet.hpp" + +#include "TGreenletGlobals.cpp" +#include "TThreadStateDestroy.cpp" +#include "PyGreenlet.hpp" +// #include "TGreenlet.cpp" + +// #include "TExceptionState.cpp" +// #include "TPythonState.cpp" +// #include "TStackState.cpp" + +using greenlet::LockGuard; +using greenlet::LockInitError; +using greenlet::PyErrOccurred; +using greenlet::Require; + +using greenlet::g_handle_exit; +using greenlet::single_result; + +using greenlet::Greenlet; +using greenlet::UserGreenlet; +using greenlet::MainGreenlet; +using greenlet::BrokenGreenlet; +using greenlet::ThreadState; +using greenlet::PythonState; +using greenlet::refs::PyCriticalObjectSection; + + +static PyGreenlet* +green_new(PyTypeObject* type, PyObject* UNUSED(args), PyObject* UNUSED(kwds)) +{ + PyGreenlet* o = + (PyGreenlet*)PyBaseObject_Type.tp_new(type, mod_globs->empty_tuple, mod_globs->empty_dict); + if (o) { + // Recall: borrowing or getting the current greenlet + // causes the "deleteme list" to get cleared. So constructing a greenlet + // can do things like cause other greenlets to get finalized. + UserGreenlet* c = new UserGreenlet(o, GET_THREAD_STATE().state().borrow_current()); + assert(Py_REFCNT(o) == 1); + // Also: This looks like a memory leak, but isn't. + // Constructing the C++ object assigns it to the pimpl pointer + // of the Python object (o); we'll need that later. + assert(c == o->pimpl); + } + return o; +} + + +// green_init is used in the tp_init slot. So it's important that +// it can be called directly from CPython. Thus, we don't use +// BorrowedGreenlet and BorrowedObject --- although in theory +// these should be binary layout compatible, that may not be +// guaranteed to be the case (32-bit linux ppc possibly). +static int +green_init(PyGreenlet* self, PyObject* args, PyObject* kwargs) +{ + PyArgParseParam run; + PyArgParseParam nparent; + static const char* kwlist[] = { + "run", + "parent", + NULL + }; + + // recall: The O specifier does NOT increase the reference count. + if (!PyArg_ParseTupleAndKeywords( + args, kwargs, "|OO:green", (char**)kwlist, &run, &nparent)) { + return -1; + } + + if (run) { + if (green_setrun(self, run, NULL)) { + return -1; + } + } + if (nparent && !nparent.is_None()) { + return green_setparent(self, nparent, NULL); + } + return 0; +} + + + +static int +green_traverse(PyGreenlet* self, visitproc visit, void* arg) +{ + // We must only visit referenced objects, i.e. only objects + // Py_INCREF'ed by this greenlet (directly or indirectly): + // + // - stack_prev is not visited: holds previous stack pointer, but it's not + // referenced + // - frames are not visited as we don't strongly reference them; + // alive greenlets are not garbage collected + // anyway. This can be a problem, however, if this greenlet is + // never allowed to finish, and is referenced from the frame: we + // have an uncollectible cycle in that case. Note that the + // frame object itself is also frequently not even tracked by the GC + // starting with Python 3.7 (frames are allocated by the + // interpreter untracked, and only become tracked when their + // evaluation is finished if they have a refcount > 1). All of + // this is to say that we should probably strongly reference + // the frame object. Doing so, while always allowing GC on a + // greenlet, solves several leaks for us. + + Py_VISIT(self->dict); + if (!self->pimpl) { + // Hmm. I have seen this at interpreter shutdown time, + // I think. That's very odd because this doesn't go away until + // we're ``green_dealloc()``, at which point we shouldn't be + // traversed anymore. + return 0; + } + + return self->pimpl->tp_traverse(visit, arg); +} + +static int +green_is_gc(PyObject* _self) +{ + BorrowedGreenlet self(_self); + int result = 0; + /* Main greenlet can be garbage collected since it can only + become unreachable if the underlying thread exited. + Active greenlets --- including those that are suspended --- + cannot be garbage collected, however. + */ + if (self->main() || !self->active()) { + result = 1; + } + // The main greenlet pointer will eventually go away after the thread dies. + if (self->was_running_in_dead_thread()) { + // Our thread is dead! We can never run again. Might as well + // GC us. Note that if a tuple containing only us and other + // immutable objects had been scanned before this, when we + // would have returned 0, the tuple will take itself out of GC + // tracking and never be investigated again. So that could + // result in both us and the tuple leaking due to an + // unreachable/uncollectible reference. The same goes for + // dictionaries. + // + // It's not a great idea to be changing our GC state on the + // fly. + result = 1; + } + return result; +} + + +static int +green_clear(PyGreenlet* self) +{ + /* Greenlet is only cleared if it is about to be collected. + Since active greenlets are not garbage collectable, we can + be sure that, even if they are deallocated during clear, + nothing they reference is in unreachable or finalizers, + so even if it switches we are relatively safe. */ + // XXX: Are we responsible for clearing weakrefs here? + Py_CLEAR(self->dict); + return self->pimpl->tp_clear(); +} + +/** + * Returns 0 on failure (the object was resurrected) or 1 on success. + **/ +static int +_green_dealloc_kill_started_non_main_greenlet(BorrowedGreenlet self) +{ + // During interpreter finalization, we cannot safely throw GreenletExit + // into the greenlet. Doing so calls g_switch(), which performs a stack + // switch and runs Python code via _PyEval_EvalFrameDefault. On Python + // < 3.11, executing Python code in a partially-torn-down interpreter + // leads to SIGSEGV (greenlet 3.x) or SIGABRT (greenlet 2.x). + // + // Python 3.11+ restructured interpreter finalization internals (frame + // representation, data stack management, recursion tracking) so that + // g_switch() during finalization is safe. On older Pythons, we simply + // mark the greenlet dead without throwing, which avoids the crash at + // the cost of not running any cleanup code inside the greenlet. + // + // See: https://github.com/python-greenlet/greenlet/issues/411 + // https://github.com/python-greenlet/greenlet/issues/351 + if (greenlet::IsShuttingDown()) { + self->murder_in_place(); + return 1; + } + + /* Hacks hacks hacks copied from instance_dealloc() */ + /* Temporarily resurrect the greenlet. */ + assert(self.REFCNT() == 0); + Py_SET_REFCNT(self.borrow(), 1); + /* Save the current exception, if any. */ + PyErrPieces saved_err; + try { + // BY THE TIME WE GET HERE, the state may actually be going + // away + // if we're shutting down the interpreter and freeing thread + // entries, + // this could result in freeing greenlets that were leaked. So + // we can't try to read the state. + self->deallocing_greenlet_in_thread( + self->thread_state() + ? static_cast(GET_THREAD_STATE()) + : nullptr); + } + catch (const PyErrOccurred&) { + PyErr_WriteUnraisable(self.borrow_o()); + /* XXX what else should we do? */ + } + /* Check for no resurrection must be done while we keep + * our internal reference, otherwise PyFile_WriteObject + * causes recursion if using Py_INCREF/Py_DECREF + */ + if (self.REFCNT() == 1 && self->active()) { + /* Not resurrected, but still not dead! + XXX what else should we do? we complain. */ + PyObject* f = PySys_GetObject("stderr"); + Py_INCREF(self.borrow_o()); /* leak! */ + if (f != NULL) { + // PySys_GetObject returns a borrowed ref which could go + // away when we run arbitrary code, as we do for any of + // the ``PyFile_Write`` APIs. + Py_INCREF(f); + // Note that we're not handling errors here. They either + // work or they don't, and any exception they raised will + // be replaced by PyErrRestore. + PyFile_WriteString("GreenletExit did not kill ", f); + PyFile_WriteObject(self.borrow_o(), f, 0); + PyFile_WriteString("\n", f); + Py_DECREF(f); + } + } + /* Restore the saved exception. */ + saved_err.PyErrRestore(); + /* Undo the temporary resurrection; can't use DECREF here, + * it would cause a recursive call. + */ + assert(self.REFCNT() > 0); + + Py_ssize_t refcnt = self.REFCNT() - 1; + Py_SET_REFCNT(self.borrow_o(), refcnt); + if (refcnt != 0) { + /* Resurrected! */ + _Py_NewReference(self.borrow_o()); + Py_SET_REFCNT(self.borrow_o(), refcnt); + /* Better to use tp_finalizer slot (PEP 442) + * and call ``PyObject_CallFinalizerFromDealloc``, + * but that's only supported in Python 3.4+; see + * Modules/_io/iobase.c for an example. + * TODO: We no longer run on anything that old, switch to finalizers. + * + * The following approach is copied from iobase.c in CPython 2.7. + * (along with much of this function in general). Here's their + * comment: + * + * When called from a heap type's dealloc, the type will be + * decref'ed on return (see e.g. subtype_dealloc in typeobject.c). + * + * On free-threaded builds of CPython, the type is meant to be immortal + * so we probably shouldn't mess with this? See + * test_issue_245_reference_counting_subclass_no_threads + */ + if (PyType_HasFeature(self.TYPE(), Py_TPFLAGS_HEAPTYPE)) { + Py_INCREF(self.TYPE()); + } + + PyObject_GC_Track((PyObject*)self); + + GREENLET_Py_DEC_REFTOTAL; +#ifdef COUNT_ALLOCS + --Py_TYPE(self)->tp_frees; + --Py_TYPE(self)->tp_allocs; +#endif /* COUNT_ALLOCS */ + return 0; + } + return 1; +} + + +static void +green_dealloc(PyGreenlet* self) +{ + PyObject_GC_UnTrack(self); + BorrowedGreenlet me(self); + if (me->active() + && me->started() + && !me->main()) { + if (!_green_dealloc_kill_started_non_main_greenlet(me)) { + return; + } + } + + if (self->weakreflist != NULL) { + PyObject_ClearWeakRefs((PyObject*)self); + } + Py_CLEAR(self->dict); + + if (self->pimpl) { + // In case deleting this, which frees some memory, + // somehow winds up calling back into us. That's usually a + //bug in our code. + Greenlet* p = self->pimpl; + self->pimpl = nullptr; + delete p; + } + // and finally we're done. self is now invalid. + Py_TYPE(self)->tp_free((PyObject*)self); +} + + + +static OwnedObject +internal_green_throw(BorrowedGreenlet self, PyErrPieces& err_pieces) +{ + PyObject* result = nullptr; + err_pieces.PyErrRestore(); + assert(PyErr_Occurred()); + if (self->started() && !self->active()) { + /* dead greenlet: turn GreenletExit into a regular return */ + result = g_handle_exit(OwnedObject()).relinquish_ownership(); + } + self->args() <<= result; + + return single_result(self->g_switch()); +} + + + +PyDoc_STRVAR( + green_switch_doc, + "switch(*args, **kwargs)\n" + "\n" + "Switch execution to this greenlet.\n" + "\n" + "If this greenlet has never been run, then this greenlet\n" + "will be switched to using the body of ``self.run(*args, **kwargs)``.\n" + "\n" + "If the greenlet is active (has been run, but was switch()'ed\n" + "out before leaving its run function), then this greenlet will\n" + "be resumed and the return value to its switch call will be\n" + "None if no arguments are given, the given argument if one\n" + "argument is given, or the args tuple and keyword args dict if\n" + "multiple arguments are given.\n" + "\n" + "If the greenlet is dead, or is the current greenlet then this\n" + "function will simply return the arguments using the same rules as\n" + "above.\n"); + +static PyObject* +green_switch(PyGreenlet* self, PyObject* args, PyObject* kwargs) +{ + // Our use of Greenlet::args() makes this method non-reentrant. + // Therefore, check to be sure the switch will be allowed --- + // we're calling from the same thread that ``self`` belongs to --- + // BEFORE doing anything with args(). If we don't do this, we can + // find args() getting clobbered by switches that will never + // succeed. + // + // TODO: We're only doing this for free-threaded builds because + // those are the only ones that have demonstrated an issue, + // trusting our later checks in g_switch to perform the same + // function and the GIL to keep us from being reentered in regular + // builds. BUT should we always do this as an extra measure of + // safety in case we run code at unexpected times (e.g., a GC?) +#ifdef Py_GIL_DISABLED + try { + self->pimpl->check_switch_allowed(); + } + catch (const PyErrOccurred&) { + return nullptr; + } +#endif + + + using greenlet::SwitchingArgs; + SwitchingArgs switch_args(OwnedObject::owning(args), OwnedObject::owning(kwargs)); + self->pimpl->may_switch_away(); + self->pimpl->args() <<= switch_args; + + // If we're switching out of a greenlet, and that switch is the + // last thing the greenlet does, the greenlet ought to be able to + // go ahead and die at that point. Currently, someone else must + // manually switch back to the greenlet so that we "fall off the + // end" and can perform cleanup. You'd think we'd be able to + // figure out that this is happening using the frame's ``f_lasti`` + // member, which is supposed to be an index into + // ``frame->f_code->co_code``, the bytecode string. However, in + // recent interpreters, ``f_lasti`` tends not to be updated thanks + // to things like the PREDICT() macros in ceval.c. So it doesn't + // really work to do that in many cases. For example, the Python + // code: + // def run(): + // greenlet.getcurrent().parent.switch() + // produces bytecode of len 16, with the actual call to switch() + // being at index 10 (in Python 3.10). However, the reported + // ``f_lasti`` we actually see is...5! (Which happens to be the + // second byte of the CALL_METHOD op for ``getcurrent()``). + + try { + OwnedObject result(single_result(self->pimpl->g_switch())); +#ifndef NDEBUG + // Note that the current greenlet isn't necessarily self. If self + // finished, we went to one of its parents. + assert(!self->pimpl->args()); + + const BorrowedGreenlet& current = GET_THREAD_STATE().state().borrow_current(); + // It's possible it's never been switched to. + assert(!current->args()); +#endif + PyObject* p = result.relinquish_ownership(); + + if (!p && !PyErr_Occurred()) { + // This shouldn't be happening anymore, so the asserts + // are there for debug builds. Non-debug builds + // crash "gracefully" in this case, although there is an + // argument to be made for killing the process in all + // cases --- for this to be the case, our switches + // probably nested in an incorrect way, so the state is + // suspicious. Nothing should be corrupt though, just + // confused at the Python level. Letting this propagate is + // probably good enough. + assert(p || PyErr_Occurred()); + throw PyErrOccurred( + mod_globs->PyExc_GreenletError, + "Greenlet.switch() returned NULL without an exception set." + ); + } + return p; + } + catch(const PyErrOccurred&) { + return nullptr; + } +} + +PyDoc_STRVAR( + green_throw_doc, + "Switches execution to this greenlet, but immediately raises the\n" + "given exception in this greenlet. If no argument is provided, the " + "exception\n" + "defaults to `greenlet.GreenletExit`. The normal exception\n" + "propagation rules apply, as described for `switch`. Note that calling " + "this\n" + "method is almost equivalent to the following::\n" + "\n" + " def raiser():\n" + " raise typ, val, tb\n" + " g_raiser = greenlet(raiser, parent=g)\n" + " g_raiser.switch()\n" + "\n" + "except that this trick does not work for the\n" + "`greenlet.GreenletExit` exception, which would not propagate\n" + "from ``g_raiser`` to ``g``.\n"); + +static PyObject* +green_throw(PyGreenlet* self, PyObject* args) +{ + // See green_switch for why we call this early. +#ifdef Py_GIL_DISABLED + try { + self->pimpl->check_switch_allowed(); + } + catch (const PyErrOccurred&) { + return nullptr; + } +#endif + + PyArgParseParam typ(mod_globs->PyExc_GreenletExit); + PyArgParseParam val; + PyArgParseParam tb; + + if (!PyArg_ParseTuple(args, "|OOO:throw", &typ, &val, &tb)) { + return nullptr; + } + + assert(typ.borrow() || val.borrow()); + + self->pimpl->may_switch_away(); + try { + // Both normalizing the error and the actual throw_greenlet + // could throw PyErrOccurred. + PyErrPieces err_pieces(typ.borrow(), val.borrow(), tb.borrow()); + + return internal_green_throw(self, err_pieces).relinquish_ownership(); + } + catch (const PyErrOccurred&) { + return nullptr; + } +} + +static int +green_bool(PyGreenlet* self) +{ + return self->pimpl->active(); +} + +/** + * CAUTION: Allocates memory, may run GC and arbitrary Python code. + */ +static PyObject* +green_getdict(PyGreenlet* self, void* UNUSED(context)) +{ + PyCriticalObjectSection cs(self); + if (self->dict == NULL) { + self->dict = PyDict_New(); + if (self->dict == NULL) { + return NULL; + } + } + Py_INCREF(self->dict); + return self->dict; +} + +static int +green_setdict(PyGreenlet* self, PyObject* val, void* UNUSED(context)) +{ + if (val == NULL) { + PyErr_SetString(PyExc_TypeError, "__dict__ may not be deleted"); + return -1; + } + if (!PyDict_Check(val)) { + PyErr_SetString(PyExc_TypeError, "__dict__ must be a dictionary"); + return -1; + } + PyCriticalObjectSection cs(self); + PyObject* tmp = self->dict; + Py_INCREF(val); + self->dict = val; + Py_XDECREF(tmp); + return 0; +} + +static bool +_green_not_dead(BorrowedGreenlet self) +{ + // XXX: Where else should we do this? + // Probably on entry to most Python-facing functions? + if (self->was_running_in_dead_thread()) { + self->deactivate_and_free(); + return false; + } + return self->active() || !self->started(); +} + + +static PyObject* +green_getdead(PyGreenlet* self, void* UNUSED(context)) +{ + PyCriticalObjectSection cs(self); + if (_green_not_dead(self)) { + Py_RETURN_FALSE; + } + else { + Py_RETURN_TRUE; + } +} + +static PyObject* +green_get_stack_saved(PyGreenlet* self, void* UNUSED(context)) +{ + return PyLong_FromSsize_t(self->pimpl->stack_saved()); +} + + +static PyObject* +green_getrun(PyGreenlet* self, void* UNUSED(context)) +{ + PyCriticalObjectSection cs(self); + try { + OwnedObject result(BorrowedGreenlet(self)->run()); + return result.relinquish_ownership(); + } + catch(const PyErrOccurred&) { + return nullptr; + } +} + + +static int +green_setrun(PyGreenlet* self, PyObject* nrun, void* UNUSED(context)) +{ + PyCriticalObjectSection cs(self); + try { + BorrowedGreenlet(self)->run(nrun); + return 0; + } + catch(const PyErrOccurred&) { + return -1; + } +} + +static PyObject* +green_getparent(PyGreenlet* self, void* UNUSED(context)) +{ + PyCriticalObjectSection cs(self); + return BorrowedGreenlet(self)->parent().acquire_or_None(); +} + + +static int +green_setparent(PyGreenlet* self, PyObject* nparent, void* UNUSED(context)) +{ + PyCriticalObjectSection cs(self); + try { + BorrowedGreenlet(self)->parent(nparent); + } + catch(const PyErrOccurred&) { + return -1; + } + return 0; +} + + +static PyObject* +green_getcontext(const PyGreenlet* self, void* UNUSED(context)) +{ + PyCriticalObjectSection cs(self); + const Greenlet *const g = self->pimpl; + try { + OwnedObject result(g->context()); + return result.relinquish_ownership(); + } + catch(const PyErrOccurred&) { + return nullptr; + } +} + +static int +green_setcontext(PyGreenlet* self, PyObject* nctx, void* UNUSED(context)) +{ + PyCriticalObjectSection cs(self); + try { + BorrowedGreenlet(self)->context(nctx); + return 0; + } + catch(const PyErrOccurred&) { + return -1; + } +} + + +static PyObject* +green_getframe(PyGreenlet* self, void* UNUSED(context)) +{ + PyCriticalObjectSection cs(self); + const PythonState::OwnedFrame& top_frame = BorrowedGreenlet(self)->top_frame(); + return top_frame.acquire_or_None(); +} + + +static PyObject* +green_getstate(PyGreenlet* self) +{ + PyErr_Format(PyExc_TypeError, + "cannot serialize '%s' object", + Py_TYPE(self)->tp_name); + return nullptr; +} + +static PyObject* +green_repr(PyGreenlet* _self) +{ + BorrowedGreenlet self(_self); + /* + Return a string like + + + The handling of greenlets across threads is not super good. + We mostly use the internal definitions of these terms, but they + generally should make sense to users as well. + */ + PyObject* result; + int never_started = !self->started() && !self->active(); + + const char* const tp_name = Py_TYPE(self)->tp_name; + + if (_green_not_dead(self)) { + /* XXX: The otid= is almost useless because you can't correlate it to + any thread identifier exposed to Python. We could use + PyThreadState_GET()->thread_id, but we'd need to save that in the + greenlet, or save the whole PyThreadState object itself. + + As it stands, its only useful for identifying greenlets from the same thread. + */ + const char* state_in_thread; + if (self->was_running_in_dead_thread()) { + // The thread it was running in is dead! + // This can happen, especially at interpreter shut down. + // It complicates debugging output because it may be + // impossible to access the current thread state at that + // time. Thus, don't access the current thread state. + state_in_thread = " (thread exited)"; + } + else { + state_in_thread = GET_THREAD_STATE().state().is_current(self) + ? " current" + : (self->started() ? " suspended" : ""); + } + result = PyUnicode_FromFormat( + "<%s object at %p (otid=%p)%s%s%s%s>", + tp_name, + self.borrow_o(), + self->thread_state(), + state_in_thread, + self->active() ? " active" : "", + never_started ? " pending" : " started", + self->main() ? " main" : "" + ); + } + else { + result = PyUnicode_FromFormat( + "<%s object at %p (otid=%p) %sdead>", + tp_name, + self.borrow_o(), + self->thread_state(), + self->was_running_in_dead_thread() + ? "(thread exited) " + : "" + ); + } + + return result; +} + + +static PyMethodDef green_methods[] = { + { + .ml_name="switch", + .ml_meth=reinterpret_cast(green_switch), + .ml_flags=METH_VARARGS | METH_KEYWORDS, + .ml_doc=green_switch_doc + }, + {.ml_name="throw", .ml_meth=(PyCFunction)green_throw, .ml_flags=METH_VARARGS, .ml_doc=green_throw_doc}, + {.ml_name="__getstate__", .ml_meth=(PyCFunction)green_getstate, .ml_flags=METH_NOARGS, .ml_doc=NULL}, + {.ml_name=NULL, .ml_meth=NULL} /* sentinel */ +}; + +static PyGetSetDef green_getsets[] = { + /* name, getter, setter, doc, context pointer */ + {.name="__dict__", .get=(getter)green_getdict, .set=(setter)green_setdict}, + {.name="run", .get=(getter)green_getrun, .set=(setter)green_setrun}, + {.name="parent", .get=(getter)green_getparent, .set=(setter)green_setparent}, + {.name="gr_frame", .get=(getter)green_getframe }, + { + .name="gr_context", + .get=(getter)green_getcontext, + .set=(setter)green_setcontext + }, + {.name="dead", .get=(getter)green_getdead}, + {.name="_stack_saved", .get=(getter)green_get_stack_saved}, + {.name=NULL} +}; + +static PyMemberDef green_members[] = { + {.name=NULL} +}; + +static PyNumberMethods green_as_number = { + .nb_bool=(inquiry)green_bool, +}; + + +PyTypeObject PyGreenlet_Type = { + .ob_base=PyVarObject_HEAD_INIT(NULL, 0) + .tp_name="greenlet.greenlet", /* tp_name */ + .tp_basicsize=sizeof(PyGreenlet), /* tp_basicsize */ + /* methods */ + .tp_dealloc=(destructor)green_dealloc, /* tp_dealloc */ + .tp_repr=(reprfunc)green_repr, /* tp_repr */ + .tp_as_number=&green_as_number, /* tp_as _number*/ + .tp_flags=G_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ + .tp_doc="greenlet(run=None, parent=None) -> greenlet\n\n" + "Creates a new greenlet object (without running it).\n\n" + " - *run* -- The callable to invoke.\n" + " - *parent* -- The parent greenlet. The default is the current " + "greenlet.", /* tp_doc */ + .tp_traverse=(traverseproc)green_traverse, /* tp_traverse */ + .tp_clear=(inquiry)green_clear, /* tp_clear */ + .tp_weaklistoffset=offsetof(PyGreenlet, weakreflist), /* tp_weaklistoffset */ + + .tp_methods=green_methods, /* tp_methods */ + .tp_members=green_members, /* tp_members */ + .tp_getset=green_getsets, /* tp_getset */ + .tp_dictoffset=offsetof(PyGreenlet, dict), /* tp_dictoffset */ + .tp_init=(initproc)green_init, /* tp_init */ + .tp_alloc=PyType_GenericAlloc, /* tp_alloc */ + .tp_new=(newfunc)green_new, /* tp_new */ + .tp_free=PyObject_GC_Del, /* tp_free */ +#ifndef Py_GIL_DISABLED +/* + We may have been handling this wrong all along. + + It shows as a problem with the GIL disabled. In builds of 3.14 with + assertions enabled, we break the garbage collector if we *ever* + return false from this function. The docs say this is to distinguish + some objects that are collectable vs some that are not, specifically + giving the example of PyTypeObject as the only place this is done, + where it distinguishes between static types like this one (allocated + by the C runtime at load time) and dynamic heap types (created at + runtime as objects). With the GIL disabled, all allocations that are + potentially collectable go in the mimalloc heap, and the collector + asserts that tp_is_gc() is true for them as it walks through the + heap object by object. Since we set the Py_TPFLAGS_HAS_GC bit, we + are always allocated in that mimalloc heap, so we must always be + collectable. + + XXX: TODO: Could this be responsible for some apparent leaks, even + on GIL builds, at least in 3.14? See if we can catch an assertion + failure in the GC on regular 3.14 as well. + */ + .tp_is_gc=(inquiry)green_is_gc, /* tp_is_gc */ +#endif +}; + +#endif + +// Local Variables: +// flycheck-clang-include-path: ("/opt/local/Library/Frameworks/Python.framework/Versions/3.8/include/python3.8") +// End: diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/PyGreenlet.hpp b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/PyGreenlet.hpp new file mode 100644 index 000000000..df6cd805b --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/PyGreenlet.hpp @@ -0,0 +1,35 @@ +#ifndef PYGREENLET_HPP +#define PYGREENLET_HPP + + +#include "greenlet.h" +#include "greenlet_compiler_compat.hpp" +#include "greenlet_refs.hpp" + + +using greenlet::refs::OwnedGreenlet; +using greenlet::refs::BorrowedGreenlet; +using greenlet::refs::BorrowedObject;; +using greenlet::refs::OwnedObject; +using greenlet::refs::PyErrPieces; + + +// XXX: These doesn't really belong here, it's not a Python slot. +static OwnedObject internal_green_throw(BorrowedGreenlet self, PyErrPieces& err_pieces); + +static PyGreenlet* green_new(PyTypeObject* type, PyObject* UNUSED(args), PyObject* UNUSED(kwds)); +static int green_clear(PyGreenlet* self); +static int green_init(PyGreenlet* self, PyObject* args, PyObject* kwargs); +static int green_setparent(PyGreenlet* self, PyObject* nparent, void* UNUSED(context)); +static int green_setrun(PyGreenlet* self, PyObject* nrun, void* UNUSED(context)); +static int green_traverse(PyGreenlet* self, visitproc visit, void* arg); +static void green_dealloc(PyGreenlet* self); +static PyObject* green_getparent(PyGreenlet* self, void* UNUSED(context)); + +static int green_is_gc(PyObject* self); +static PyObject* green_getdead(PyGreenlet* self, void* UNUSED(context)); +static PyObject* green_getrun(PyGreenlet* self, void* UNUSED(context)); +static int green_setcontext(PyGreenlet* self, PyObject* nctx, void* UNUSED(context)); +static PyObject* green_getframe(PyGreenlet* self, void* UNUSED(context)); +static PyObject* green_repr(PyGreenlet* self); +#endif diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/PyGreenletUnswitchable.cpp b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/PyGreenletUnswitchable.cpp new file mode 100644 index 000000000..729cb7386 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/PyGreenletUnswitchable.cpp @@ -0,0 +1,150 @@ +/* -*- indent-tabs-mode: nil; tab-width: 4; -*- */ +/** + Implementation of the Python slots for PyGreenletUnswitchable_Type +*/ +#ifndef PY_GREENLET_UNSWITCHABLE_CPP +#define PY_GREENLET_UNSWITCHABLE_CPP + + + +#define PY_SSIZE_T_CLEAN +#include +#include "structmember.h" // PyMemberDef + +#include "greenlet_internal.hpp" +// Code after this point can assume access to things declared in stdint.h, +// including the fixed-width types. This goes for the platform-specific switch functions +// as well. +#include "greenlet_refs.hpp" +#include "greenlet_slp_switch.hpp" + +#include "greenlet_thread_support.hpp" +#include "TGreenlet.hpp" + +#include "TGreenlet.cpp" +#include "TGreenletGlobals.cpp" +#include "TThreadStateDestroy.cpp" + + +using greenlet::LockGuard; +using greenlet::LockInitError; +using greenlet::PyErrOccurred; +using greenlet::Require; + +using greenlet::g_handle_exit; +using greenlet::single_result; + +using greenlet::Greenlet; +using greenlet::UserGreenlet; +using greenlet::MainGreenlet; +using greenlet::BrokenGreenlet; +using greenlet::ThreadState; +using greenlet::PythonState; + + +#include "PyGreenlet.hpp" + +static PyGreenlet* +green_unswitchable_new(PyTypeObject* type, PyObject* UNUSED(args), PyObject* UNUSED(kwds)) +{ + PyGreenlet* o = + (PyGreenlet*)PyBaseObject_Type.tp_new(type, mod_globs->empty_tuple, mod_globs->empty_dict); + if (o) { + new BrokenGreenlet(o, GET_THREAD_STATE().state().borrow_current()); + assert(Py_REFCNT(o) == 1); + } + return o; +} + +static PyObject* +green_unswitchable_getforce(PyGreenlet* self, void* UNUSED(context)) +{ + BrokenGreenlet* broken = dynamic_cast(self->pimpl); + return PyBool_FromLong(broken->_force_switch_error); +} + +static int +green_unswitchable_setforce(PyGreenlet* self, PyObject* nforce, void* UNUSED(context)) +{ + if (!nforce) { + PyErr_SetString( + PyExc_AttributeError, + "Cannot delete force_switch_error" + ); + return -1; + } + BrokenGreenlet* broken = dynamic_cast(self->pimpl); + int is_true = PyObject_IsTrue(nforce); + if (is_true == -1) { + return -1; + } + broken->_force_switch_error = is_true; + return 0; +} + +static PyObject* +green_unswitchable_getforceslp(PyGreenlet* self, void* UNUSED(context)) +{ + BrokenGreenlet* broken = dynamic_cast(self->pimpl); + return PyBool_FromLong(broken->_force_slp_switch_error); +} + +static int +green_unswitchable_setforceslp(PyGreenlet* self, PyObject* nforce, void* UNUSED(context)) +{ + if (!nforce) { + PyErr_SetString( + PyExc_AttributeError, + "Cannot delete force_slp_switch_error" + ); + return -1; + } + BrokenGreenlet* broken = dynamic_cast(self->pimpl); + int is_true = PyObject_IsTrue(nforce); + if (is_true == -1) { + return -1; + } + broken->_force_slp_switch_error = is_true; + return 0; +} + +static PyGetSetDef green_unswitchable_getsets[] = { + /* name, getter, setter, doc, closure (context pointer) */ + { + .name="force_switch_error", + .get=(getter)green_unswitchable_getforce, + .set=(setter)green_unswitchable_setforce, + .doc=nullptr + }, + { + .name="force_slp_switch_error", + .get=(getter)green_unswitchable_getforceslp, + .set=(setter)green_unswitchable_setforceslp, + .doc=nullptr + }, + {.name=nullptr} +}; + +PyTypeObject PyGreenletUnswitchable_Type = { + .ob_base = PyVarObject_HEAD_INIT(NULL, 0) + .tp_name = "greenlet._greenlet.UnswitchableGreenlet", + .tp_dealloc = (destructor)green_dealloc, + .tp_flags = G_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, + .tp_doc = "Undocumented internal class for testing error conditions", + .tp_traverse = (traverseproc)green_traverse, + .tp_clear = (inquiry)green_clear, + + .tp_getset = green_unswitchable_getsets, + .tp_base = &PyGreenlet_Type, + .tp_init = (initproc)green_init, + .tp_alloc = PyType_GenericAlloc, + .tp_new = (newfunc)green_unswitchable_new, + .tp_free = PyObject_GC_Del, +#ifndef Py_GIL_DISABLED + // See comments in the base type + .tp_is_gc = (inquiry)green_is_gc, +#endif +}; + + +#endif diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/PyModule.cpp b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/PyModule.cpp new file mode 100644 index 000000000..c127d7c1c --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/PyModule.cpp @@ -0,0 +1,309 @@ +#ifndef PY_MODULE_CPP +#define PY_MODULE_CPP + +#include "greenlet_internal.hpp" + + +#include "TGreenletGlobals.cpp" +#include "TMainGreenlet.cpp" +#include "TThreadStateDestroy.cpp" + +using greenlet::LockGuard; +using greenlet::ThreadState; + +#ifdef __clang__ +# pragma clang diagnostic push +# pragma clang diagnostic ignored "-Wunused-function" +# pragma clang diagnostic ignored "-Wunused-variable" +#endif + + +static PyObject* +_greenlet_atexit_callback(PyObject* UNUSED(self), PyObject* UNUSED(args)) +{ + greenlet::g_greenlet_shutting_down = 1; + Py_RETURN_NONE; +} + +static PyMethodDef _greenlet_atexit_method = { + "_greenlet_cleanup", _greenlet_atexit_callback, + METH_NOARGS, NULL +}; + + +PyDoc_STRVAR(mod_getcurrent_doc, + "getcurrent() -> greenlet\n" + "\n" + "Returns the current greenlet (i.e. the one which called this " + "function).\n"); + +static PyObject* +mod_getcurrent(PyObject* UNUSED(module)) +{ + if (greenlet::IsShuttingDown()) { + Py_RETURN_NONE; + } + return GET_THREAD_STATE().state().get_current().relinquish_ownership_o(); +} + +PyDoc_STRVAR(mod_settrace_doc, + "settrace(callback) -> object\n" + "\n" + "Sets a new tracing function and returns the previous one.\n"); +static PyObject* +mod_settrace(PyObject* UNUSED(module), PyObject* args) +{ + PyArgParseParam tracefunc; + if (!PyArg_ParseTuple(args, "O", &tracefunc)) { + return NULL; + } + ThreadState& state = GET_THREAD_STATE(); + OwnedObject previous = state.get_tracefunc(); + if (!previous) { + previous = Py_None; + } + + state.set_tracefunc(tracefunc); + + return previous.relinquish_ownership(); +} + +PyDoc_STRVAR(mod_gettrace_doc, + "gettrace() -> object\n" + "\n" + "Returns the currently set tracing function, or None.\n"); + +static PyObject* +mod_gettrace(PyObject* UNUSED(module)) +{ + OwnedObject tracefunc = GET_THREAD_STATE().state().get_tracefunc(); + if (!tracefunc) { + tracefunc = Py_None; + } + return tracefunc.relinquish_ownership(); +} + + + +PyDoc_STRVAR(mod_set_thread_local_doc, + "set_thread_local(key, value) -> None\n" + "\n" + "Set a value in the current thread-local dictionary. Debugging only.\n"); + +static PyObject* +mod_set_thread_local(PyObject* UNUSED(module), PyObject* args) +{ + PyArgParseParam key; + PyArgParseParam value; + PyObject* result = NULL; + + if (PyArg_UnpackTuple(args, "set_thread_local", 2, 2, &key, &value)) { + if(PyDict_SetItem( + PyThreadState_GetDict(), // borrow + key, + value) == 0 ) { + // success + Py_INCREF(Py_None); + result = Py_None; + } + } + return result; +} + +PyDoc_STRVAR(mod_get_pending_cleanup_count_doc, + "get_pending_cleanup_count() -> Integer\n" + "\n" + "Get the number of greenlet cleanup operations pending. Testing only.\n"); + + +static PyObject* +mod_get_pending_cleanup_count(PyObject* UNUSED(module)) +{ + LockGuard cleanup_lock(*mod_globs->thread_states_to_destroy_lock); + return PyLong_FromSize_t(mod_globs->thread_states_to_destroy.size()); +} + +PyDoc_STRVAR(mod_get_total_main_greenlets_doc, + "get_total_main_greenlets() -> Integer\n" + "\n" + "Quickly return the number of main greenlets that exist. Testing only.\n"); + +static PyObject* +mod_get_total_main_greenlets(PyObject* UNUSED(module)) +{ + return PyLong_FromSize_t(G_TOTAL_MAIN_GREENLETS); +} + + + +PyDoc_STRVAR(mod_get_clocks_used_doing_optional_cleanup_doc, + "get_clocks_used_doing_optional_cleanup() -> Integer\n" + "\n" + "Get the number of clock ticks the program has used doing optional " + "greenlet cleanup.\n" + "Beginning in greenlet 2.0, greenlet tries to find and dispose of greenlets\n" + "that leaked after a thread exited. This requires invoking Python's garbage collector,\n" + "which may have a performance cost proportional to the number of live objects.\n" + "This function returns the amount of processor time\n" + "greenlet has used to do this. In programs that run with very large amounts of live\n" + "objects, this metric can be used to decide whether the cost of doing this cleanup\n" + "is worth the memory leak being corrected. If not, you can disable the cleanup\n" + "using ``enable_optional_cleanup(False)``.\n" + "The units are arbitrary and can only be compared to themselves (similarly to ``time.clock()``);\n" + "for example, to see how it scales with your heap. You can attempt to convert them into seconds\n" + "by dividing by the value of CLOCKS_PER_SEC." + "If cleanup has been disabled, returns None." + "\n" + "This is an implementation specific, provisional API. It may be changed or removed\n" + "in the future.\n" + ".. versionadded:: 2.0" + ); +static PyObject* +mod_get_clocks_used_doing_optional_cleanup(PyObject* UNUSED(module)) +{ + std::clock_t clocks = ThreadState::clocks_used_doing_gc(); + + if (clocks == std::clock_t(-1)) { + Py_RETURN_NONE; + } + // This might not actually work on some implementations; clock_t + // is an opaque type. + return PyLong_FromSsize_t(clocks); +} + +PyDoc_STRVAR(mod_enable_optional_cleanup_doc, + "mod_enable_optional_cleanup(bool) -> None\n" + "\n" + "Enable or disable optional cleanup operations.\n" + "See ``get_clocks_used_doing_optional_cleanup()`` for details.\n" + ); +static PyObject* +mod_enable_optional_cleanup(PyObject* UNUSED(module), PyObject* flag) +{ + int is_true = PyObject_IsTrue(flag); + if (is_true == -1) { + return nullptr; + } + + if (is_true) { + std::clock_t clocks = ThreadState::clocks_used_doing_gc(); + // If we already have a value, we don't want to lose it. + if (clocks == std::clock_t(-1)) { + ThreadState::set_clocks_used_doing_gc(0); + } + } + else { + ThreadState::set_clocks_used_doing_gc(std::clock_t(-1)); + } + Py_RETURN_NONE; +} + + + + +#if !GREENLET_PY313 +PyDoc_STRVAR(mod_get_tstate_trash_delete_nesting_doc, + "get_tstate_trash_delete_nesting() -> Integer\n" + "\n" + "Return the 'trash can' nesting level. Testing only.\n"); +static PyObject* +mod_get_tstate_trash_delete_nesting(PyObject* UNUSED(module)) +{ + PyThreadState* tstate = PyThreadState_GET(); + +#if GREENLET_PY312 + return PyLong_FromLong(tstate->trash.delete_nesting); +#else + return PyLong_FromLong(tstate->trash_delete_nesting); +#endif +} +#endif + + + + +static PyMethodDef GreenMethods[] = { + { + .ml_name="getcurrent", + .ml_meth=(PyCFunction)mod_getcurrent, + .ml_flags=METH_NOARGS, + .ml_doc=mod_getcurrent_doc + }, + { + .ml_name="settrace", + .ml_meth=(PyCFunction)mod_settrace, + .ml_flags=METH_VARARGS, + .ml_doc=mod_settrace_doc + }, + { + .ml_name="gettrace", + .ml_meth=(PyCFunction)mod_gettrace, + .ml_flags=METH_NOARGS, + .ml_doc=mod_gettrace_doc + }, + { + .ml_name="set_thread_local", + .ml_meth=(PyCFunction)mod_set_thread_local, + .ml_flags=METH_VARARGS, + .ml_doc=mod_set_thread_local_doc + }, + { + .ml_name="get_pending_cleanup_count", + .ml_meth=(PyCFunction)mod_get_pending_cleanup_count, + .ml_flags=METH_NOARGS, + .ml_doc=mod_get_pending_cleanup_count_doc + }, + { + .ml_name="get_total_main_greenlets", + .ml_meth=(PyCFunction)mod_get_total_main_greenlets, + .ml_flags=METH_NOARGS, + .ml_doc=mod_get_total_main_greenlets_doc + }, + { + .ml_name="get_clocks_used_doing_optional_cleanup", + .ml_meth=(PyCFunction)mod_get_clocks_used_doing_optional_cleanup, + .ml_flags=METH_NOARGS, + .ml_doc=mod_get_clocks_used_doing_optional_cleanup_doc + }, + { + .ml_name="enable_optional_cleanup", + .ml_meth=(PyCFunction)mod_enable_optional_cleanup, + .ml_flags=METH_O, + .ml_doc=mod_enable_optional_cleanup_doc + }, +#if !GREENLET_PY313 + { + .ml_name="get_tstate_trash_delete_nesting", + .ml_meth=(PyCFunction)mod_get_tstate_trash_delete_nesting, + .ml_flags=METH_NOARGS, + .ml_doc=mod_get_tstate_trash_delete_nesting_doc + }, +#endif + {.ml_name=NULL, .ml_meth=NULL} /* Sentinel */ +}; + +static const char* const copy_on_greentype[] = { + "getcurrent", + "error", + "GreenletExit", + "settrace", + "gettrace", + NULL +}; + +static struct PyModuleDef greenlet_module_def = { + .m_base=PyModuleDef_HEAD_INIT, + .m_name="greenlet._greenlet", + .m_doc=NULL, + .m_size=-1, + .m_methods=GreenMethods, +}; + + +#endif + +#ifdef __clang__ +# pragma clang diagnostic pop +#elif defined(__GNUC__) +# pragma GCC diagnostic pop +#endif diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/TBrokenGreenlet.cpp b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/TBrokenGreenlet.cpp new file mode 100644 index 000000000..7e9ab5be9 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/TBrokenGreenlet.cpp @@ -0,0 +1,45 @@ +/* -*- indent-tabs-mode: nil; tab-width: 4; -*- */ +/** + * Implementation of greenlet::UserGreenlet. + * + * Format with: + * clang-format -i --style=file src/greenlet/greenlet.c + * + * + * Fix missing braces with: + * clang-tidy src/greenlet/greenlet.c -fix -checks="readability-braces-around-statements" +*/ + +#include "TGreenlet.hpp" + +namespace greenlet { + +void* BrokenGreenlet::operator new(size_t UNUSED(count)) +{ + return allocator.allocate(1); +} + + +void BrokenGreenlet::operator delete(void* ptr) +{ + return allocator.deallocate(static_cast(ptr), + 1); +} + +greenlet::PythonAllocator greenlet::BrokenGreenlet::allocator; + +bool +BrokenGreenlet::force_slp_switch_error() const noexcept +{ + return this->_force_slp_switch_error; +} + +UserGreenlet::switchstack_result_t BrokenGreenlet::g_switchstack(void) +{ + if (this->_force_switch_error) { + return switchstack_result_t(-1); + } + return UserGreenlet::g_switchstack(); +} + +}; //namespace greenlet diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/TExceptionState.cpp b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/TExceptionState.cpp new file mode 100644 index 000000000..08a94ae83 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/TExceptionState.cpp @@ -0,0 +1,62 @@ +#ifndef GREENLET_EXCEPTION_STATE_CPP +#define GREENLET_EXCEPTION_STATE_CPP + +#include +#include "TGreenlet.hpp" + +namespace greenlet { + + +ExceptionState::ExceptionState() +{ + this->clear(); +} + +void ExceptionState::operator<<(const PyThreadState *const tstate) noexcept +{ + this->exc_info = tstate->exc_info; + this->exc_state = tstate->exc_state; +} + +void ExceptionState::operator>>(PyThreadState *const tstate) noexcept +{ + tstate->exc_state = this->exc_state; + tstate->exc_info = + this->exc_info ? this->exc_info : &tstate->exc_state; + this->clear(); +} + +void ExceptionState::clear() noexcept +{ + this->exc_info = nullptr; + this->exc_state.exc_value = nullptr; +#if !GREENLET_PY311 + this->exc_state.exc_type = nullptr; + this->exc_state.exc_traceback = nullptr; +#endif + this->exc_state.previous_item = nullptr; +} + +int ExceptionState::tp_traverse(visitproc visit, void* arg) noexcept +{ + Py_VISIT(this->exc_state.exc_value); +#if !GREENLET_PY311 + Py_VISIT(this->exc_state.exc_type); + Py_VISIT(this->exc_state.exc_traceback); +#endif + return 0; +} + +void ExceptionState::tp_clear() noexcept +{ + Py_CLEAR(this->exc_state.exc_value); +#if !GREENLET_PY311 + Py_CLEAR(this->exc_state.exc_type); + Py_CLEAR(this->exc_state.exc_traceback); +#endif +} + + +}; // namespace greenlet + +#endif // GREENLET_EXCEPTION_STATE_CPP diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/TGreenlet.cpp b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/TGreenlet.cpp new file mode 100644 index 000000000..7ec86f98a --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/TGreenlet.cpp @@ -0,0 +1,729 @@ +/* -*- indent-tabs-mode: nil; tab-width: 4; -*- */ +/** + * Implementation of greenlet::Greenlet. + * + * Format with: + * clang-format -i --style=file src/greenlet/greenlet.c + * + * + * Fix missing braces with: + * clang-tidy src/greenlet/greenlet.c -fix -checks="readability-braces-around-statements" +*/ +#ifndef TGREENLET_CPP +#define TGREENLET_CPP +#include "greenlet_internal.hpp" +#include "TGreenlet.hpp" + + +#include "TGreenletGlobals.cpp" +#include "TThreadStateDestroy.cpp" + +namespace greenlet { + +Greenlet::Greenlet(PyGreenlet* p) + : Greenlet(p, StackState()) +{ +} + +Greenlet::Greenlet(PyGreenlet* p, const StackState& initial_stack) + : _self(p), stack_state(initial_stack) +{ + assert(p->pimpl == nullptr); + p->pimpl = this; +} + +Greenlet::~Greenlet() +{ + // XXX: Can't do this. tp_clear is a virtual function, and by the + // time we're here, we've sliced off our child classes. + //this->tp_clear(); + this->_self->pimpl = nullptr; +} + +bool +Greenlet::force_slp_switch_error() const noexcept +{ + return false; +} + +void +Greenlet::release_args() +{ + this->switch_args.CLEAR(); +} + +/** + * CAUTION: This will allocate memory and may trigger garbage + * collection and arbitrary Python code. + */ +OwnedObject +Greenlet::throw_GreenletExit_during_dealloc(const ThreadState& UNUSED(current_thread_state)) +{ + // If we're killed because we lost all references in the + // middle of a switch, that's ok. Don't reset the args/kwargs, + // we still want to pass them to the parent. + PyErr_SetString(mod_globs->PyExc_GreenletExit, + "Killing the greenlet because all references have vanished."); + // To get here it had to have run before + return this->g_switch(); +} + +inline void +Greenlet::slp_restore_state() noexcept +{ +#ifdef SLP_BEFORE_RESTORE_STATE + SLP_BEFORE_RESTORE_STATE(); +#endif + this->stack_state.copy_heap_to_stack( + this->thread_state()->borrow_current()->stack_state); +} + + +inline int +Greenlet::slp_save_state(char *const stackref) noexcept +{ + // XXX: This used to happen in the middle, before saving, but + // after finding the next owner. Does that matter? This is + // only defined for Sparc/GCC where it flushes register + // windows to the stack (I think) +#ifdef SLP_BEFORE_SAVE_STATE + SLP_BEFORE_SAVE_STATE(); +#endif + return this->stack_state.copy_stack_to_heap(stackref, + this->thread_state()->borrow_current()->stack_state); +} + +/** + * CAUTION: This will allocate memory and may trigger garbage + * collection and arbitrary Python code. + */ +OwnedObject +Greenlet::on_switchstack_or_initialstub_failure( + Greenlet* target, + const Greenlet::switchstack_result_t& err, + const bool target_was_me, + const bool was_initial_stub) +{ + // If we get here, either g_initialstub() + // failed, or g_switchstack() failed. Either one of those + // cases SHOULD leave us in the original greenlet with a valid stack. + if (!PyErr_Occurred()) { + PyErr_SetString( + PyExc_SystemError, + was_initial_stub + ? "Failed to switch stacks into a greenlet for the first time." + : "Failed to switch stacks into a running greenlet."); + } + this->release_args(); + + if (target && !target_was_me) { + target->murder_in_place(); + } + + assert(!err.the_new_current_greenlet); + assert(!err.origin_greenlet); + return OwnedObject(); + +} + +OwnedGreenlet +Greenlet::g_switchstack_success() noexcept +{ + PyThreadState* tstate = PyThreadState_GET(); + // restore the saved state + this->python_state >> tstate; + this->exception_state >> tstate; + + // The thread state hasn't been changed yet. + ThreadState* thread_state = this->thread_state(); + OwnedGreenlet result(thread_state->get_current()); + thread_state->set_current(this->self()); + //assert(thread_state->borrow_current().borrow() == this->_self); + return result; +} + +Greenlet::switchstack_result_t +Greenlet::g_switchstack(void) +{ + // if any of these assertions fail, it's likely because we + // switched away and tried to switch back to us. Early stages of + // switching are not reentrant because we re-use ``this->args()``. + // Switching away would happen if we trigger a garbage collection + // (by just using some Python APIs that happen to allocate Python + // objects) and some garbage had weakref callbacks or __del__ that + // switches (people don't write code like that by hand, but with + // gevent it's possible without realizing it) + assert(this->args() || PyErr_Occurred()); + { /* save state */ + if (this->thread_state()->is_current(this->self())) { + // Hmm, nothing to do. + // TODO: Does this bypass trace events that are + // important? + return switchstack_result_t(0, + this, this->thread_state()->borrow_current()); + } + BorrowedGreenlet current = this->thread_state()->borrow_current(); + PyThreadState* tstate = PyThreadState_GET(); + + current->python_state << tstate; + current->exception_state << tstate; + this->python_state.will_switch_from(tstate); + switching_thread_state = this; + current->expose_frames(); + } + assert(this->args() || PyErr_Occurred()); + // If this is the first switch into a greenlet, this will + // return twice, once with 1 in the new greenlet, once with 0 + // in the origin. + int err; + if (this->force_slp_switch_error()) { + err = -1; + } + else { + err = slp_switch(); + } + + if (err < 0) { /* error */ + // Tested by + // test_greenlet.TestBrokenGreenlets.test_failed_to_slp_switch_into_running + // + // It's not clear if it's worth trying to clean up and + // continue here. Failing to switch stacks is a big deal which + // may not be recoverable (who knows what state the stack is in). + // Also, we've stolen references in preparation for calling + // ``g_switchstack_success()`` and we don't have a clean + // mechanism for backing that all out. + Py_FatalError("greenlet: Failed low-level slp_switch(). The stack is probably corrupt."); + } + + // No stack-based variables are valid anymore. + + // But the global is thread_local volatile so we can reload it without the + // compiler caching it from earlier. + Greenlet* greenlet_that_switched_in = switching_thread_state; // aka this + switching_thread_state = nullptr; + // except that no stack variables are valid, we would: + // assert(this == greenlet_that_switched_in); + + // switchstack success is where we restore the exception state, + // etc. It returns the origin greenlet because its convenient. + + OwnedGreenlet origin = greenlet_that_switched_in->g_switchstack_success(); + assert(greenlet_that_switched_in->args() || PyErr_Occurred()); + return switchstack_result_t(err, greenlet_that_switched_in, origin); +} + + +inline void +Greenlet::check_switch_allowed() const +{ + // TODO: Make this take a parameter of the current greenlet, + // or current main greenlet, to make the check for + // cross-thread switching cheaper. Surely somewhere up the + // call stack we've already accessed the thread local variable. + + // We expect to always have a main greenlet now; accessing the thread state + // created it. However, if we get here and cleanup has already + // begun because we're a greenlet that was running in a + // (now dead) thread, these invariants will not hold true. In + // fact, accessing `this->thread_state` may not even be possible. + + // If the thread this greenlet was running in is dead, + // we'll still have a reference to a main greenlet, but the + // thread state pointer we have is bogus (should be nullptr) + // TODO: Give the objects an API to determine if they belong + // to a dead thread. + + const BorrowedMainGreenlet my_main_greenlet = this->find_main_greenlet_in_lineage(); + + if (!my_main_greenlet) { + throw PyErrOccurred(mod_globs->PyExc_GreenletError, + "cannot switch to a garbage collected greenlet"); + } + + if (!my_main_greenlet->thread_state()) { + throw PyErrOccurred(mod_globs->PyExc_GreenletError, + "cannot switch to a different thread (which happens to have exited)"); + } + + // The main greenlet we found was from the .parent lineage. + // That may or may not have any relationship to the main + // greenlet of the running thread. We can't actually access + // our this->thread_state members to try to check that, + // because it could be in the process of getting destroyed, + // but setting the main_greenlet->thread_state member to NULL + // may not be visible yet. So we need to check against the + // current thread state (once the cheaper checks are out of + // the way) + const BorrowedMainGreenlet main_greenlet_cur_thread = GET_THREAD_STATE().state().borrow_main_greenlet(); + if ( + // lineage main greenlet is not this thread's greenlet + main_greenlet_cur_thread != my_main_greenlet + || ( + // atteched to some thread + this->main_greenlet() + // XXX: Same condition as above. Was this supposed to be + // this->main_greenlet()? + && main_greenlet_cur_thread != my_main_greenlet) + // switching into a known dead thread (XXX: which, if we get here, + // is bad, because we just accessed the thread state, which is + // gone!) + || (!main_greenlet_cur_thread->thread_state())) { + // CAUTION: This may trigger memory allocations, gc, and + // arbitrary Python code. + throw PyErrOccurred( + mod_globs->PyExc_GreenletError, + "Cannot switch to a different thread\n\tCurrent: %R\n\tExpected: %R", + main_greenlet_cur_thread, my_main_greenlet); + } +} + +const OwnedObject +Greenlet::context() const +{ + using greenlet::PythonStateContext; + OwnedObject result; + + if (this->is_currently_running_in_some_thread()) { + /* Currently running greenlet: context is stored in the thread state, + not the greenlet object. */ + if (GET_THREAD_STATE().state().is_current(this->self())) { + result = PythonStateContext::context(PyThreadState_GET()); + } + else { + throw ValueError( + "cannot get context of a " + "greenlet that is running in a different thread"); + } + } + else { + /* Greenlet is not running: just return context. */ + result = this->python_state.context(); + } + if (!result) { + result = OwnedObject::None(); + } + return result; +} + + +void +Greenlet::context(BorrowedObject given) +{ + using greenlet::PythonStateContext; + if (!given) { + throw AttributeError("can't delete context attribute"); + } + if (given.is_None()) { + /* "Empty context" is stored as NULL, not None. */ + given = nullptr; + } + + //checks type, incrs refcnt + greenlet::refs::OwnedContext context(given); + PyThreadState* tstate = PyThreadState_GET(); + + if (this->is_currently_running_in_some_thread()) { + if (!GET_THREAD_STATE().state().is_current(this->self())) { + throw ValueError("cannot set context of a greenlet" + " that is running in a different thread"); + } + + /* Currently running greenlet: context is stored in the thread state, + not the greenlet object. */ + OwnedObject octx = OwnedObject::consuming(PythonStateContext::context(tstate)); + PythonStateContext::context(tstate, context.relinquish_ownership()); + } + else { + /* Greenlet is not running: just set context. Note that the + greenlet may be dead.*/ + this->python_state.context() = context; + } +} + +/** + * CAUTION: May invoke arbitrary Python code. + * + * Figure out what the result of ``greenlet.switch(arg, kwargs)`` + * should be and transfers ownership of it to the left-hand-side. + * + * If switch() was just passed an arg tuple, then we'll just return that. + * If only keyword arguments were passed, then we'll pass the keyword + * argument dict. Otherwise, we'll create a tuple of (args, kwargs) and + * return both. + * + * CAUTION: This may allocate a new tuple object, which may + * cause the Python garbage collector to run, which in turn may + * run arbitrary Python code that switches. + */ +OwnedObject& operator<<=(OwnedObject& lhs, greenlet::SwitchingArgs& rhs) noexcept +{ + // Because this may invoke arbitrary Python code, which could + // result in switching back to us, we need to get the + // arguments locally on the stack. + assert(rhs); + OwnedObject args = rhs.args(); + OwnedObject kwargs = rhs.kwargs(); + rhs.CLEAR(); + // We shouldn't be called twice for the same switch. + assert(args || kwargs); + assert(!rhs); + + if (!kwargs) { + lhs = args; + } + else if (!PyDict_Size(kwargs.borrow())) { + lhs = args; + } + else if (!PySequence_Length(args.borrow())) { + lhs = kwargs; + } + else { + // PyTuple_Pack allocates memory, may GC, may run arbitrary + // Python code. + lhs = OwnedObject::consuming(PyTuple_Pack(2, args.borrow(), kwargs.borrow())); + } + return lhs; +} + +static OwnedObject +g_handle_exit(const OwnedObject& greenlet_result) +{ + if (!greenlet_result && mod_globs->PyExc_GreenletExit.PyExceptionMatches()) { + /* catch and ignore GreenletExit */ + PyErrFetchParam val; + // TODO: When we run on 3.12+ only (GREENLET_312), switch to the + // ``PyErr_GetRaisedException`` family of functions. The + // ``PyErr_Fetch`` family is deprecated on 3.12+, but is part + // of the stable ABI so it's not going anywhere. + PyErr_Fetch(PyErrFetchParam(), val, PyErrFetchParam()); + if (!val) { + return OwnedObject::None(); + } + return OwnedObject(val); + } + + if (greenlet_result) { + // package the result into a 1-tuple + // PyTuple_Pack increments the reference of its arguments, + // so we always need to decref the greenlet result; + // the owner will do that. + return OwnedObject::consuming(PyTuple_Pack(1, greenlet_result.borrow())); + } + + return OwnedObject(); +} + + + +/** + * May run arbitrary Python code. + */ +OwnedObject +Greenlet::g_switch_finish(const switchstack_result_t& err) +{ + assert(err.the_new_current_greenlet == this); + + ThreadState& state = *this->thread_state(); + // Because calling the trace function could do arbitrary things, + // including switching away from this greenlet and then maybe + // switching back, we need to capture the arguments now so that + // they don't change. + OwnedObject result; + if (this->args()) { + result <<= this->args(); + } + else { + assert(PyErr_Occurred()); + } + assert(!this->args()); + try { + // Our only caller handles the bad error case + assert(err.status >= 0); + assert(state.borrow_current() == this->self()); + if (OwnedObject tracefunc = state.get_tracefunc()) { + assert(result || PyErr_Occurred()); + g_calltrace(tracefunc, + result ? mod_globs->event_switch : mod_globs->event_throw, + err.origin_greenlet, + this->self()); + } + // The above could have invoked arbitrary Python code, but + // it couldn't switch back to this object and *also* + // throw an exception, so the args won't have changed. + + if (PyErr_Occurred()) { + // We get here if we fell of the end of the run() function + // raising an exception. The switch itself was + // successful, but the function raised. + // valgrind reports that memory allocated here can still + // be reached after a test run. + throw PyErrOccurred::from_current(); + } + return result; + } + catch (const PyErrOccurred&) { + /* Turn switch errors into switch throws */ + /* Turn trace errors into switch throws */ + this->release_args(); + throw; + } +} + +void +Greenlet::g_calltrace(const OwnedObject& tracefunc, + const greenlet::refs::ImmortalEventName& event, + const BorrowedGreenlet& origin, + const BorrowedGreenlet& target) +{ + PyErrPieces saved_exc; + try { + TracingGuard tracing_guard; + // TODO: We have saved the active exception (if any) that's + // about to be raised. In the 'throw' case, we could provide + // the exception to the tracefunction, which seems very helpful. + tracing_guard.CallTraceFunction(tracefunc, event, origin, target); + } + catch (const PyErrOccurred&) { + // In case of exceptions trace function is removed, + // and any existing exception is replaced with the tracing + // exception. + GET_THREAD_STATE().state().set_tracefunc(Py_None); + throw; + } + + saved_exc.PyErrRestore(); + assert( + (event == mod_globs->event_throw && PyErr_Occurred()) + || (event == mod_globs->event_switch && !PyErr_Occurred()) + ); +} + +void +Greenlet::murder_in_place() +{ + if (this->active()) { + assert(!this->is_currently_running_in_some_thread()); + this->deactivate_and_free(); + } +} + +inline void +Greenlet::deactivate_and_free() +{ + if (!this->active()) { + return; + } + // Throw away any saved stack. + this->stack_state = StackState(); + assert(!this->stack_state.active()); + // Throw away any Python references. + // We're holding a borrowed reference to the last + // frame we executed. Since we borrowed it, the + // normal traversal, clear, and dealloc functions + // ignore it, meaning it leaks. (The thread state + // object can't find it to clear it when that's + // deallocated either, because by definition if we + // got an object on this list, it wasn't + // running and the thread state doesn't have + // this frame.) + // So here, we *do* clear it. + this->python_state.tp_clear(true); +} + +bool +Greenlet::belongs_to_thread(const ThreadState* thread_state) const +{ + if (!this->thread_state() // not running anywhere, or thread + // exited + || !thread_state) { // same, or there is no thread state. + return false; + } + return true; +} + + +void +Greenlet::deallocing_greenlet_in_thread(const ThreadState* current_thread_state) +{ + /* Cannot raise an exception to kill the greenlet if + it is not running in the same thread! */ + if (this->belongs_to_thread(current_thread_state)) { + assert(current_thread_state); + // To get here it had to have run before + /* Send the greenlet a GreenletExit exception. */ + + // We don't care about the return value, only whether an + // exception happened. + this->throw_GreenletExit_during_dealloc(*current_thread_state); + return; + } + + // Not the same thread! Temporarily save the greenlet + // into its thread's deleteme list, *if* it exists. + // If that thread has already exited, and processed its pending + // cleanup, we'll never be able to clean everything up: we won't + // be able to raise an exception. + // That's mostly OK! Since we can't add it to a list, our refcount + // won't increase, and we'll go ahead with the DECREFs later. + + ThreadState *const thread_state = this->thread_state(); + if (thread_state) { + thread_state->delete_when_thread_running(this->self()); + } + else { + // The thread is dead, we can't raise an exception. + // We need to make it look non-active, though, so that dealloc + // finishes killing it. + this->deactivate_and_free(); + } + return; +} + + +int +Greenlet::tp_traverse(visitproc visit, void* arg) +{ + + int result; + if ((result = this->exception_state.tp_traverse(visit, arg)) != 0) { + return result; + } + //XXX: This is ugly. But so is handling everything having to do + //with the top frame. + bool visit_top_frame = this->was_running_in_dead_thread(); + // When true, the thread is dead. Our implicit weak reference to the + // frame is now all that's left; we consider ourselves to + // strongly own it now. + if ((result = this->python_state.tp_traverse(visit, arg, visit_top_frame)) != 0) { + return result; + } + return 0; +} + +int +Greenlet::tp_clear() +{ + bool own_top_frame = this->was_running_in_dead_thread(); + this->exception_state.tp_clear(); + this->python_state.tp_clear(own_top_frame); + return 0; +} + +bool Greenlet::is_currently_running_in_some_thread() const +{ + return this->stack_state.active() && !this->python_state.top_frame(); +} + +#if GREENLET_PY312 +void GREENLET_NOINLINE(Greenlet::expose_frames)() +{ + if (!this->python_state.top_frame()) { + return; + } + + _PyInterpreterFrame* last_complete_iframe = nullptr; + _PyInterpreterFrame* iframe = this->python_state.top_frame()->f_frame; + while (iframe) { + // We must make a copy before looking at the iframe contents, + // since iframe might point to a portion of the greenlet's C stack + // that was spilled when switching greenlets. + _PyInterpreterFrame iframe_copy; + this->stack_state.copy_from_stack(&iframe_copy, iframe, sizeof(*iframe)); + if (!_PyFrame_IsIncomplete(&iframe_copy)) { + // If the iframe were OWNED_BY_CSTACK then it would always be + // incomplete. Since it's not incomplete, it's not on the C stack + // and we can access it through the original `iframe` pointer + // directly. This is important since GetFrameObject might + // lazily _create_ the frame object and we don't want the + // interpreter to lose track of it. + // + #if !GREENLET_PY315 + // This enum value was removed in + // https://github.com/python/cpython/pull/141108 + + assert(iframe_copy.owner != FRAME_OWNED_BY_CSTACK); + #endif + + // We really want to just write: + // PyFrameObject* frame = _PyFrame_GetFrameObject(iframe); + // but _PyFrame_GetFrameObject calls _PyFrame_MakeAndSetFrameObject + // which is not a visible symbol in libpython. The easiest + // way to get a public function to call it is using + // PyFrame_GetBack, which is defined as follows: + // assert(frame != NULL); + // assert(!_PyFrame_IsIncomplete(frame->f_frame)); + // PyFrameObject *back = frame->f_back; + // if (back == NULL) { + // _PyInterpreterFrame *prev = frame->f_frame->previous; + // prev = _PyFrame_GetFirstComplete(prev); + // if (prev) { + // back = _PyFrame_GetFrameObject(prev); + // } + // } + // return (PyFrameObject*)Py_XNewRef(back); + if (!iframe->frame_obj) { + PyFrameObject dummy_frame; + _PyInterpreterFrame dummy_iframe; + dummy_frame.f_back = nullptr; + dummy_frame.f_frame = &dummy_iframe; + // force the iframe to be considered complete without + // needing to check its code object: + dummy_iframe.owner = FRAME_OWNED_BY_GENERATOR; + dummy_iframe.previous = iframe; + assert(!_PyFrame_IsIncomplete(&dummy_iframe)); + // Drop the returned reference immediately; the iframe + // continues to hold a strong reference + Py_XDECREF(PyFrame_GetBack(&dummy_frame)); + assert(iframe->frame_obj); + } + + // This is a complete frame, so make the last one of those we saw + // point at it, bypassing any incomplete frames (which may have + // been on the C stack) in between the two. We're overwriting + // last_complete_iframe->previous and need that to be reversible, + // so we store the original previous ptr in the frame object + // (which we must have created on a previous iteration through + // this loop). The frame object has a bunch of storage that is + // only used when its iframe is OWNED_BY_FRAME_OBJECT, which only + // occurs when the frame object outlives the frame's execution, + // which can't have happened yet because the frame is currently + // executing as far as the interpreter is concerned. So, we can + // reuse it for our own purposes. + assert(iframe->owner == FRAME_OWNED_BY_THREAD + || iframe->owner == FRAME_OWNED_BY_GENERATOR); + if (last_complete_iframe) { + assert(last_complete_iframe->frame_obj); + memcpy(&last_complete_iframe->frame_obj->_f_frame_data[0], + &last_complete_iframe->previous, sizeof(void *)); + last_complete_iframe->previous = iframe; + } + last_complete_iframe = iframe; + } + // Frames that are OWNED_BY_FRAME_OBJECT are linked via the + // frame's f_back while all others are linked via the iframe's + // previous ptr. Since all the frames we traverse are running + // as far as the interpreter is concerned, we don't have to + // worry about the OWNED_BY_FRAME_OBJECT case. + iframe = iframe_copy.previous; + } + + // Give the outermost complete iframe a null previous pointer to + // account for any potential incomplete/C-stack iframes between it + // and the actual top-of-stack + if (last_complete_iframe) { + assert(last_complete_iframe->frame_obj); + memcpy(&last_complete_iframe->frame_obj->_f_frame_data[0], + &last_complete_iframe->previous, sizeof(void *)); + last_complete_iframe->previous = nullptr; + } +} +#else +void Greenlet::expose_frames() +{ + +} +#endif + +}; // namespace greenlet +#endif diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/TGreenlet.hpp b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/TGreenlet.hpp new file mode 100644 index 000000000..0d4e0d9c8 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/TGreenlet.hpp @@ -0,0 +1,849 @@ +#ifndef GREENLET_GREENLET_HPP +#define GREENLET_GREENLET_HPP +/* + * Declarations of the core data structures. +*/ + +#define PY_SSIZE_T_CLEAN +#include + +#include + +#include "greenlet_compiler_compat.hpp" +#include "greenlet_refs.hpp" +#include "greenlet_cpython_compat.hpp" +#include "greenlet_allocator.hpp" + +using greenlet::refs::OwnedObject; +using greenlet::refs::OwnedGreenlet; +using greenlet::refs::OwnedMainGreenlet; +using greenlet::refs::BorrowedGreenlet; + +#if PY_VERSION_HEX < 0x30B00A6 + // prior to 3.11.0a6 +# define _PyCFrame CFrame +# define _PyInterpreterFrame _interpreter_frame +#endif + +#if GREENLET_PY312 +# define Py_BUILD_CORE +# include "internal/pycore_frame.h" +#endif + +#if GREENLET_PY314 +# include "internal/pycore_interpframe_structs.h" +#if defined(_MSC_VER) || defined(__MINGW64__) +# include "greenlet_msvc_compat.hpp" +#else +# include "internal/pycore_interpframe.h" +#endif +#ifdef Py_GIL_DISABLED +# include "internal/pycore_tstate.h" +#endif +#endif + +// XXX: TODO: Work to remove all virtual functions +// for speed of calling and size of objects (no vtable). +// One pattern is the Curiously Recurring Template +namespace greenlet +{ + class ExceptionState + { + private: + G_NO_COPIES_OF_CLS(ExceptionState); + + // Even though these are borrowed objects, we actually own + // them, when they're not null. + // XXX: Express that in the API. + private: + _PyErr_StackItem* exc_info; + _PyErr_StackItem exc_state; + public: + ExceptionState(); + void operator<<(const PyThreadState *const tstate) noexcept; + void operator>>(PyThreadState* tstate) noexcept; + void clear() noexcept; + + int tp_traverse(visitproc visit, void* arg) noexcept; + void tp_clear() noexcept; + }; + + template + void operator<<(const PyThreadState *const tstate, T& exc); + + class PythonStateContext + { + protected: + greenlet::refs::OwnedContext _context; + public: + inline const greenlet::refs::OwnedContext& context() const + { + return this->_context; + } + inline greenlet::refs::OwnedContext& context() + { + return this->_context; + } + + inline void tp_clear() + { + this->_context.CLEAR(); + } + + template + inline static PyObject* context(T* tstate) + { + return tstate->context; + } + + template + inline static void context(T* tstate, PyObject* new_context) + { + tstate->context = new_context; + tstate->context_ver++; + } + }; + class SwitchingArgs; + class PythonState : public PythonStateContext + { + public: + typedef greenlet::refs::OwnedReference OwnedFrame; + private: + G_NO_COPIES_OF_CLS(PythonState); + // We own this if we're suspended (although currently we don't + // tp_traverse into it; that's a TODO). If we're running, it's + // empty. If we get deallocated and *still* have a frame, it + // won't be reachable from the place that normally decref's + // it, so we need to do it (hence owning it). + OwnedFrame _top_frame; +#if GREENLET_USE_CFRAME + _PyCFrame* cframe; + int use_tracing; +#endif +#if GREENLET_PY314 + int py_recursion_depth; + // I think this is only used by the JIT. At least, + // we only got errors not switching it when the JIT was enabled. + // Python/generated_cases.c.h:12469: _PyEval_EvalFrameDefault: + // Assertion `tstate->current_executor == NULL' failed. + // see https://github.com/python-greenlet/greenlet/issues/460 + PyObject* current_executor; + _PyStackRef* stackpointer; + #ifdef Py_GIL_DISABLED + _PyCStackRef* c_stack_refs; + #endif +#elif GREENLET_PY312 + int py_recursion_depth; + int c_recursion_depth; +#else + int recursion_depth; +#endif +#if GREENLET_PY313 + PyObject *delete_later; +#else + int trash_delete_nesting; +#endif +#if GREENLET_PY311 + _PyInterpreterFrame* current_frame; + _PyStackChunk* datastack_chunk; + PyObject** datastack_top; + PyObject** datastack_limit; +#endif + // The PyInterpreterFrame list on 3.12+ contains some entries that are + // on the C stack, which can't be directly accessed while a greenlet is + // suspended. In order to keep greenlet gr_frame introspection working, + // we adjust stack switching to rewrite the interpreter frame list + // to skip these C-stack frames; we call this "exposing" the greenlet's + // frames because it makes them valid to work with in Python. Then when + // the greenlet is resumed we need to remember to reverse the operation + // we did. The C-stack frames are "entry frames" which are a low-level + // interpreter detail; they're not needed for introspection, but do + // need to be present for the eval loop to work. + void unexpose_frames(); + + public: + + PythonState(); + // You can use this for testing whether we have a frame + // or not. It returns const so they can't modify it. + const OwnedFrame& top_frame() const noexcept; + + inline void operator<<(const PyThreadState *const tstate) noexcept; + inline void operator>>(PyThreadState* tstate) noexcept; + void clear() noexcept; + + int tp_traverse(visitproc visit, void* arg, bool visit_top_frame) noexcept; + void tp_clear(bool own_top_frame) noexcept; + void set_initial_state(const PyThreadState* const tstate) noexcept; +#if GREENLET_USE_CFRAME + void set_new_cframe(_PyCFrame& frame) noexcept; +#endif + + void may_switch_away() noexcept; + inline void will_switch_from(PyThreadState *const origin_tstate) noexcept; + void did_finish(PyThreadState* tstate) noexcept; + }; + + class StackState + { + // By having only plain C (POD) members, no virtual functions + // or bases, we get a trivial assignment operator generated + // for us. However, that's not safe since we do manage memory. + // So we declare an assignment operator that only works if we + // don't have any memory allocated. (We don't use + // std::shared_ptr for reference counting just to keep this + // object small) + private: + char* _stack_start; + char* stack_stop; + char* stack_copy; + intptr_t _stack_saved; + StackState* stack_prev; + inline int copy_stack_to_heap_up_to(const char* const stop) noexcept; + inline void free_stack_copy() noexcept; + + public: + /** + * Creates a started, but inactive, state, using *current* + * as the previous. + */ + StackState(void* mark, StackState& current); + /** + * Creates an inactive, unstarted, state. + */ + StackState(); + ~StackState(); + StackState(const StackState& other); + StackState& operator=(const StackState& other); + inline void copy_heap_to_stack(const StackState& current) noexcept; + inline int copy_stack_to_heap(char* const stackref, const StackState& current) noexcept; + inline bool started() const noexcept; + inline bool main() const noexcept; + inline bool active() const noexcept; + inline void set_active() noexcept; + inline void set_inactive() noexcept; + inline intptr_t stack_saved() const noexcept; + inline char* stack_start() const noexcept; + static inline StackState make_main() noexcept; +#ifdef GREENLET_USE_STDIO + friend std::ostream& operator<<(std::ostream& os, const StackState& s); +#endif + + // Fill in [dest, dest + n) with the values that would be at + // [src, src + n) while this greenlet is running. This is like memcpy + // except that if the greenlet is suspended it accounts for the portion + // of the greenlet's stack that was spilled to the heap. `src` may + // be on this greenlet's stack, or on the heap, but not on a different + // greenlet's stack. + void copy_from_stack(void* dest, const void* src, size_t n) const; + }; +#ifdef GREENLET_USE_STDIO + std::ostream& operator<<(std::ostream& os, const StackState& s); +#endif + + class SwitchingArgs + { + private: + G_NO_ASSIGNMENT_OF_CLS(SwitchingArgs); + // If args and kwargs are both false (NULL), this is a *throw*, not a + // switch. PyErr_... must have been called already. + OwnedObject _args; + OwnedObject _kwargs; + public: + + SwitchingArgs() + {} + + SwitchingArgs(const OwnedObject& args, const OwnedObject& kwargs) + : _args(args), + _kwargs(kwargs) + {} + + SwitchingArgs(const SwitchingArgs& other) + : _args(other._args), + _kwargs(other._kwargs) + {} + + const OwnedObject& args() + { + return this->_args; + } + + const OwnedObject& kwargs() + { + return this->_kwargs; + } + + /** + * Moves ownership from the argument to this object. + */ + SwitchingArgs& operator<<=(SwitchingArgs& other) + { + if (this != &other) { + this->_args = other._args; + this->_kwargs = other._kwargs; + other.CLEAR(); + } + return *this; + } + + /** + * Acquires ownership of the argument (consumes the reference). + */ + SwitchingArgs& operator<<=(PyObject* args) + { + this->_args = OwnedObject::consuming(args); + this->_kwargs.CLEAR(); + return *this; + } + + /** + * Acquires ownership of the argument. + * + * Sets the args to be the given value; clears the kwargs. + */ + SwitchingArgs& operator<<=(OwnedObject& args) + { + assert(&args != &this->_args); + this->_args = args; + this->_kwargs.CLEAR(); + args.CLEAR(); + + return *this; + } + + explicit operator bool() const noexcept + { + return this->_args || this->_kwargs; + } + + inline void CLEAR() + { + this->_args.CLEAR(); + this->_kwargs.CLEAR(); + } + + const std::string as_str() const noexcept + { + return PyUnicode_AsUTF8( + OwnedObject::consuming( + PyUnicode_FromFormat( + "SwitchingArgs(args=%R, kwargs=%R)", + this->_args.borrow(), + this->_kwargs.borrow() + ) + ).borrow() + ); + } + }; + + class ThreadState; + + class UserGreenlet; + class MainGreenlet; + + class Greenlet + { + private: + G_NO_COPIES_OF_CLS(Greenlet); + PyGreenlet* const _self; + private: + // XXX: Work to remove these. + friend class ThreadState; + friend class UserGreenlet; + friend class MainGreenlet; + protected: + ExceptionState exception_state; + SwitchingArgs switch_args; + StackState stack_state; + PythonState python_state; + Greenlet(PyGreenlet* p, const StackState& initial_state); + public: + // This constructor takes ownership of the PyGreenlet, by + // setting ``p->pimpl = this;``. + Greenlet(PyGreenlet* p); + virtual ~Greenlet(); + + const OwnedObject context() const; + + // You MUST call this _very_ early in the switching process to + // prepare anything that may need prepared. This might perform + // garbage collections or otherwise run arbitrary Python code. + // + // One specific use of it is for Python 3.11+, preventing + // running arbitrary code at unsafe times. See + // PythonState::may_switch_away(). + inline void may_switch_away() + { + this->python_state.may_switch_away(); + } + + inline void context(refs::BorrowedObject new_context); + + inline SwitchingArgs& args() + { + return this->switch_args; + } + + virtual const refs::BorrowedMainGreenlet main_greenlet() const = 0; + + inline intptr_t stack_saved() const noexcept + { + return this->stack_state.stack_saved(); + } + + // This is used by the macro SLP_SAVE_STATE to compute the + // difference in stack sizes. It might be nice to handle the + // computation ourself, but the type of the result + // varies by platform, so doing it in the macro is the + // simplest way. + inline const char* stack_start() const noexcept + { + return this->stack_state.stack_start(); + } + + virtual OwnedObject throw_GreenletExit_during_dealloc(const ThreadState& current_thread_state); + + /** + * Depends on the state of this->args() or the current Python + * error indicator. Thus, it is not threadsafe or reentrant. + * You (you being ``green_switch``, the Python-level + * ``greenlet.switch`` method) should call + * ``check_switch_allowed`` in free-threaded builds before + * calling this method and catch ``PyErrOccurred`` if it isn't + * a valid switch. This method should also call that method + * because there are places where we can switch internally + * without going through the Python method. + */ + virtual OwnedObject g_switch() = 0; + /** + * Force the greenlet to appear dead. Used when it's not + * possible to throw an exception into a greenlet anymore. + * + * This losses access to the thread state and the main greenlet. + */ + virtual void murder_in_place(); + + /** + * Called when somebody notices we were running in a dead + * thread to allow cleaning up resources (because we can't + * raise GreenletExit into it anymore). + * This is very similar to ``murder_in_place()``, except that + * it DOES NOT lose the main greenlet or thread state. + */ + inline void deactivate_and_free(); + + + // Called when some thread wants to deallocate a greenlet + // object. + // The thread may or may not be the same thread the greenlet + // was running in. + // The thread state will be null if the thread the greenlet + // was running in was known to have exited. + void deallocing_greenlet_in_thread(const ThreadState* current_state); + + // Must be called on 3.12+ before exposing a suspended greenlet's + // frames to user code. This rewrites the linked list of interpreter + // frames to skip the ones that are being stored on the C stack (which + // can't be safely accessed while the greenlet is suspended because + // that stack space might be hosting a different greenlet), and + // sets PythonState::frames_were_exposed so we remember to restore + // the original list before resuming the greenlet. The C-stack frames + // are a low-level interpreter implementation detail; while they're + // important to the bytecode eval loop, they're superfluous for + // introspection purposes. + void expose_frames(); + + + // TODO: Figure out how to make these non-public. + inline void slp_restore_state() noexcept; + inline int slp_save_state(char *const stackref) noexcept; + + inline bool is_currently_running_in_some_thread() const; + virtual bool belongs_to_thread(const ThreadState* state) const; + + inline bool started() const + { + return this->stack_state.started(); + } + inline bool active() const + { + return this->stack_state.active(); + } + inline bool main() const + { + return this->stack_state.main(); + } + virtual refs::BorrowedMainGreenlet find_main_greenlet_in_lineage() const = 0; + + virtual const OwnedGreenlet parent() const = 0; + virtual void parent(const refs::BorrowedObject new_parent) = 0; + + inline const PythonState::OwnedFrame& top_frame() + { + return this->python_state.top_frame(); + } + + virtual const OwnedObject& run() const = 0; + virtual void run(const refs::BorrowedObject nrun) = 0; + + + virtual int tp_traverse(visitproc visit, void* arg); + virtual int tp_clear(); + + + // Return the thread state that the greenlet is running in, or + // null if the greenlet is not running or the thread is known + // to have exited. + virtual ThreadState* thread_state() const noexcept = 0; + + // Return true if the greenlet is known to have been running + // (active) in a thread that has now exited. + virtual bool was_running_in_dead_thread() const noexcept = 0; + + // Return a borrowed greenlet that is the Python object + // this object represents. + inline BorrowedGreenlet self() const noexcept + { + return BorrowedGreenlet(this->_self); + } + + // For testing. If this returns true, we should pretend that + // slp_switch() failed. + virtual bool force_slp_switch_error() const noexcept; + + // Check the preconditions for switching to this greenlet; if they + // aren't met, throws PyErrOccurred. Most callers will want to + // catch this and clear the arguments if they've been set. + inline void check_switch_allowed() const; + + protected: + inline void release_args(); + + // The functions that must not be inlined are declared virtual. + // We also mark them as protected, not private, so that the + // compiler is forced to call them through a function pointer. + // (A sufficiently smart compiler could directly call a private + // virtual function since it can never be overridden in a + // subclass). + + // Also TODO: Switch away from integer error codes and to enums, + // or throw exceptions when possible. + struct switchstack_result_t + { + int status; + Greenlet* the_new_current_greenlet; + OwnedGreenlet origin_greenlet; + + switchstack_result_t() + : status(0), + the_new_current_greenlet(nullptr) + {} + + switchstack_result_t(int err) + : status(err), + the_new_current_greenlet(nullptr) + {} + + switchstack_result_t(int err, Greenlet* state, OwnedGreenlet& origin) + : status(err), + the_new_current_greenlet(state), + origin_greenlet(origin) + { + } + + switchstack_result_t(int err, Greenlet* state, const BorrowedGreenlet& origin) + : status(err), + the_new_current_greenlet(state), + origin_greenlet(origin) + { + } + + switchstack_result_t(const switchstack_result_t& other) + : status(other.status), + the_new_current_greenlet(other.the_new_current_greenlet), + origin_greenlet(other.origin_greenlet) + {} + + switchstack_result_t& operator=(const switchstack_result_t& other) + { + this->status = other.status; + this->the_new_current_greenlet = other.the_new_current_greenlet; + this->origin_greenlet = other.origin_greenlet; + return *this; + } + }; + + OwnedObject on_switchstack_or_initialstub_failure( + Greenlet* target, + const switchstack_result_t& err, + const bool target_was_me=false, + const bool was_initial_stub=false); + + // Returns the previous greenlet we just switched away from. + virtual OwnedGreenlet g_switchstack_success() noexcept; + + class GreenletStartedWhileInPython : public std::runtime_error + { + public: + GreenletStartedWhileInPython() : std::runtime_error("") + {} + }; + + protected: + + + /** + Perform a stack switch into this greenlet. + + This temporarily sets the global variable + ``switching_thread_state`` to this greenlet; as soon as the + call to ``slp_switch`` completes, this is reset to NULL. + Consequently, this depends on the GIL. + + TODO: Adopt the stackman model and pass ``slp_switch`` a + callback function and context pointer; this eliminates the + need for global variables altogether. + + Because the stack switch happens in this function, this + function can't use its own stack (local) variables, set + before the switch, and then accessed after the switch. + + Further, you con't even access ``g_thread_state_global`` + before and after the switch from the global variable. + Because it is thread local some compilers cache it in a + register/on the stack, notably new versions of MSVC; this + breaks with strange crashes sometime later, because writing + to anything in ``g_thread_state_global`` after the switch + is actually writing to random memory. For this reason, we + call a non-inlined function to finish the operation. (XXX: + The ``/GT`` MSVC compiler argument probably fixes that.) + + It is very important that stack switch is 'atomic', i.e. no + calls into other Python code allowed (except very few that + are safe), because global variables are very fragile. (This + should no longer be the case with thread-local variables.) + + */ + // Made virtual to facilitate subclassing UserGreenlet for testing. + virtual switchstack_result_t g_switchstack(void); + +class TracingGuard +{ +private: + PyThreadState* tstate; +public: + TracingGuard() + : tstate(PyThreadState_GET()) + { + PyThreadState_EnterTracing(this->tstate); + } + + ~TracingGuard() + { + PyThreadState_LeaveTracing(this->tstate); + this->tstate = nullptr; + } + + inline void CallTraceFunction(const OwnedObject& tracefunc, + const greenlet::refs::ImmortalEventName& event, + const BorrowedGreenlet& origin, + const BorrowedGreenlet& target) + { + // TODO: This calls tracefunc(event, (origin, target)). Add a shortcut + // function for that that's specialized to avoid the Py_BuildValue + // string parsing, or start with just using "ON" format with PyTuple_Pack(2, + // origin, target). That seems like what the N format is meant + // for. + // XXX: Why does event not automatically cast back to a PyObject? + // It tries to call the "deleted constructor ImmortalEventName + // const" instead. + assert(tracefunc); + assert(event); + assert(origin); + assert(target); + greenlet::refs::NewReference retval( + PyObject_CallFunction( + tracefunc.borrow(), + "O(OO)", + event.borrow(), + origin.borrow(), + target.borrow() + )); + if (!retval) { + throw PyErrOccurred::from_current(); + } + } +}; + + static void + g_calltrace(const OwnedObject& tracefunc, + const greenlet::refs::ImmortalEventName& event, + const greenlet::refs::BorrowedGreenlet& origin, + const BorrowedGreenlet& target); + private: + OwnedObject g_switch_finish(const switchstack_result_t& err); + + }; + + class UserGreenlet : public Greenlet + { + private: + static greenlet::PythonAllocator allocator; + OwnedMainGreenlet _main_greenlet; + OwnedObject _run_callable; + OwnedGreenlet _parent; + public: + static void* operator new(size_t UNUSED(count)); + static void operator delete(void* ptr); + + UserGreenlet(PyGreenlet* p, BorrowedGreenlet the_parent); + virtual ~UserGreenlet(); + + virtual refs::BorrowedMainGreenlet find_main_greenlet_in_lineage() const; + virtual bool was_running_in_dead_thread() const noexcept; + virtual ThreadState* thread_state() const noexcept; + virtual OwnedObject g_switch(); + virtual const OwnedObject& run() const + { + if (this->started() || !this->_run_callable) { + throw AttributeError("run"); + } + return this->_run_callable; + } + virtual void run(const refs::BorrowedObject nrun); + + virtual const OwnedGreenlet parent() const; + virtual void parent(const refs::BorrowedObject new_parent); + + virtual const refs::BorrowedMainGreenlet main_greenlet() const; + + virtual void murder_in_place(); + virtual bool belongs_to_thread(const ThreadState* state) const; + virtual int tp_traverse(visitproc visit, void* arg); + virtual int tp_clear(); + class ParentIsCurrentGuard + { + private: + OwnedGreenlet oldparent; + UserGreenlet* greenlet; + G_NO_COPIES_OF_CLS(ParentIsCurrentGuard); + public: + ParentIsCurrentGuard(UserGreenlet* p, const ThreadState& thread_state); + ~ParentIsCurrentGuard(); + }; + virtual OwnedObject throw_GreenletExit_during_dealloc(const ThreadState& current_thread_state); + protected: + virtual switchstack_result_t g_initialstub(void* mark); + private: + // This function isn't meant to return. + // This accepts raw pointers and the ownership of them at the + // same time. The caller should use ``inner_bootstrap(origin.relinquish_ownership())``. + void inner_bootstrap(PyGreenlet* origin_greenlet, PyObject* run); + }; + + class BrokenGreenlet : public UserGreenlet + { + private: + static greenlet::PythonAllocator allocator; + public: + bool _force_switch_error = false; + bool _force_slp_switch_error = false; + + static void* operator new(size_t UNUSED(count)); + static void operator delete(void* ptr); + BrokenGreenlet(PyGreenlet* p, BorrowedGreenlet the_parent) + : UserGreenlet(p, the_parent) + {} + virtual ~BrokenGreenlet() + {} + + virtual switchstack_result_t g_switchstack(void); + virtual bool force_slp_switch_error() const noexcept; + + }; + + class MainGreenlet : public Greenlet + { + private: + static greenlet::PythonAllocator allocator; + refs::BorrowedMainGreenlet _self; + std::atomic _thread_state; + G_NO_COPIES_OF_CLS(MainGreenlet); + public: + static void* operator new(size_t UNUSED(count)); + static void operator delete(void* ptr); + + MainGreenlet(refs::BorrowedMainGreenlet::PyType*, ThreadState*); + virtual ~MainGreenlet(); + + + virtual const OwnedObject& run() const; + virtual void run(const refs::BorrowedObject nrun); + + virtual const OwnedGreenlet parent() const; + virtual void parent(const refs::BorrowedObject new_parent); + + virtual const refs::BorrowedMainGreenlet main_greenlet() const; + + virtual refs::BorrowedMainGreenlet find_main_greenlet_in_lineage() const; + virtual bool was_running_in_dead_thread() const noexcept; + virtual ThreadState* thread_state() const noexcept; + void thread_state(ThreadState*) noexcept; + virtual OwnedObject g_switch(); + virtual int tp_traverse(visitproc visit, void* arg); + }; + + // Instantiate one on the stack to save the GC state, + // and then disable GC. When it goes out of scope, GC will be + // restored to its original state. + class GCDisabledGuard + { + private: + int was_enabled = 0; + public: + GCDisabledGuard() + : was_enabled(PyGC_IsEnabled()) + { + PyGC_Disable(); + } + + ~GCDisabledGuard() + { + if (this->was_enabled) { + PyGC_Enable(); + } + } + }; + + OwnedObject& operator<<=(OwnedObject& lhs, greenlet::SwitchingArgs& rhs) noexcept; + + //TODO: Greenlet::g_switch() should call this automatically on its + //return value. As it is, the module code is calling it. + static inline OwnedObject + single_result(const OwnedObject& results) + { + if (results + && PyTuple_Check(results.borrow()) + && PyTuple_GET_SIZE(results.borrow()) == 1) { + PyObject* result = PyTuple_GET_ITEM(results.borrow(), 0); + assert(result); + return OwnedObject::owning(result); + } + return results; + } + + + static OwnedObject + g_handle_exit(const OwnedObject& greenlet_result); + + + template + void operator<<(const PyThreadState *const lhs, T& rhs) + { + rhs.operator<<(lhs); + } + +} // namespace greenlet ; + +#endif diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/TGreenletGlobals.cpp b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/TGreenletGlobals.cpp new file mode 100644 index 000000000..a67797ad3 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/TGreenletGlobals.cpp @@ -0,0 +1,113 @@ +/* -*- indent-tabs-mode: nil; tab-width: 4; -*- */ +/** + * Implementation of GreenletGlobals. + * + * Format with: + * clang-format -i --style=file src/greenlet/greenlet.c + * + * + * Fix missing braces with: + * clang-tidy src/greenlet/greenlet.c -fix -checks="readability-braces-around-statements" +*/ +#ifndef T_GREENLET_GLOBALS +#define T_GREENLET_GLOBALS + +#include + +#include "greenlet_refs.hpp" +#include "greenlet_exceptions.hpp" +#include "greenlet_thread_support.hpp" +#include "greenlet_internal.hpp" + +namespace greenlet { + +// This encapsulates what were previously module global "constants" +// established at init time. +// This is a step towards Python3 style module state that allows +// reloading. +// +// In an earlier iteration of this code, we used placement new to be +// able to allocate this object statically still, so that references +// to its members don't incur an extra pointer indirection. +// But under some scenarios, that could result in crashes at +// shutdown because apparently the destructor was getting run twice? +class GreenletGlobals +{ + +public: + const greenlet::refs::ImmortalEventName event_switch; + const greenlet::refs::ImmortalEventName event_throw; + const greenlet::refs::ImmortalException PyExc_GreenletError; + const greenlet::refs::ImmortalException PyExc_GreenletExit; + const greenlet::refs::ImmortalObject empty_tuple; + const greenlet::refs::ImmortalObject empty_dict; + const greenlet::refs::ImmortalString str_run; + Mutex* const thread_states_to_destroy_lock; + greenlet::cleanup_queue_t thread_states_to_destroy; + + GreenletGlobals() : + event_switch("switch"), + event_throw("throw"), + PyExc_GreenletError("greenlet.error"), + PyExc_GreenletExit("greenlet.GreenletExit", PyExc_BaseException), + empty_tuple(Require(PyTuple_New(0))), + empty_dict(Require(PyDict_New())), + str_run("run"), + thread_states_to_destroy_lock(new Mutex()) + {} + + ~GreenletGlobals() + { + // This object is (currently) effectively immortal, and not + // just because of those placement new tricks; if we try to + // deallocate the static object we allocated, and overwrote, + // we would be doing so at C++ teardown time, which is after + // the final Python GIL is released, and we can't use the API + // then. + // (The members will still be destructed, but they also don't + // do any deallocation.) + } + + /** + * Must be holding the ``thread_states_to_destroy`` lock. + */ + void queue_to_destroy(ThreadState* ts) const + { + // we're currently accessed through a static const object, + // implicitly marking our members as const, so code can't just + // call push_back (or pop_back) without casting away the + // const. + // + // Do that for callers. + greenlet::cleanup_queue_t& q = const_cast( + this->thread_states_to_destroy); + // make sure we don't ever try to clean up a state more than + // once. Because they're thread-local, and we ultimately call this + // method from the destructor of the thread local variable, + // we should never find the item already present. This check + // is nominally O(n) in the size of the vector. + assert(std::find(q.begin(), q.end(), ts) == q.end()); + q.push_back(ts); + } + + /** + * Must be holding the ``thread_states_to_destroy`` lock. + */ + ThreadState* take_next_to_destroy() const + { + greenlet::cleanup_queue_t& q = const_cast( + this->thread_states_to_destroy); + if (q.empty()) { + return nullptr; + } + ThreadState* result = q.back(); + q.pop_back(); + return result; + } +}; + +}; // namespace greenlet + +static const greenlet::GreenletGlobals* mod_globs; + +#endif // T_GREENLET_GLOBALS diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/TMainGreenlet.cpp b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/TMainGreenlet.cpp new file mode 100644 index 000000000..e0db0a4f3 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/TMainGreenlet.cpp @@ -0,0 +1,163 @@ +/* -*- indent-tabs-mode: nil; tab-width: 4; -*- */ +/** + * Implementation of greenlet::MainGreenlet. + * + * Format with: + * clang-format -i --style=file src/greenlet/greenlet.c + * + * + * Fix missing braces with: + * clang-tidy src/greenlet/greenlet.c -fix -checks="readability-braces-around-statements" +*/ +#ifndef T_MAIN_GREENLET_CPP +#define T_MAIN_GREENLET_CPP + +#include "TGreenlet.hpp" + +#ifdef Py_GIL_DISABLED +#include +#endif + +// Incremented when we create a main greenlet, in a new thread, decremented +// when it is destroyed. +#ifdef Py_GIL_DISABLED +static std::atomic G_TOTAL_MAIN_GREENLETS(0); +#else +// Protected by the GIL. +static Py_ssize_t G_TOTAL_MAIN_GREENLETS; +#endif + +namespace greenlet { +greenlet::PythonAllocator MainGreenlet::allocator; + +void* MainGreenlet::operator new(size_t UNUSED(count)) +{ + return allocator.allocate(1); +} + + +void MainGreenlet::operator delete(void* ptr) +{ + return allocator.deallocate(static_cast(ptr), + 1); +} + + +MainGreenlet::MainGreenlet(PyGreenlet* p, ThreadState* state) + : Greenlet(p, StackState::make_main()), + _self(p), + _thread_state(state) +{ + G_TOTAL_MAIN_GREENLETS++; +} + +MainGreenlet::~MainGreenlet() +{ + G_TOTAL_MAIN_GREENLETS--; + this->tp_clear(); +} + +ThreadState* +MainGreenlet::thread_state() const noexcept +{ + return this->_thread_state; +} + +void +MainGreenlet::thread_state(ThreadState* t) noexcept +{ + // this method is only used during thread tear down, when it is + // called with nullptr, signalling the thread is dead. + assert(!t); + this->_thread_state = t; +} + + +const BorrowedMainGreenlet +MainGreenlet::main_greenlet() const +{ + return this->_self; +} + +BorrowedMainGreenlet +MainGreenlet::find_main_greenlet_in_lineage() const +{ + return BorrowedMainGreenlet(this->_self); +} + +bool +MainGreenlet::was_running_in_dead_thread() const noexcept +{ + return !this->_thread_state; +} + +OwnedObject +MainGreenlet::g_switch() +{ + try { + this->check_switch_allowed(); + } + catch (const PyErrOccurred&) { + this->release_args(); + throw; + } + + switchstack_result_t err = this->g_switchstack(); + if (err.status < 0) { + // XXX: This code path is untested, but it is shared + // with the UserGreenlet path that is tested. + return this->on_switchstack_or_initialstub_failure( + this, + err, + true, // target was me + false // was initial stub + ); + } + + return err.the_new_current_greenlet->g_switch_finish(err); +} + +int +MainGreenlet::tp_traverse(visitproc visit, void* arg) +{ + ThreadState* thread_state = this->_thread_state.load(); + if (thread_state) { + // we've already traversed main, (self), don't do it again. + int result = thread_state->tp_traverse(visit, arg, false); + if (result) { + return result; + } + } + return Greenlet::tp_traverse(visit, arg); +} + +const OwnedObject& +MainGreenlet::run() const +{ + throw AttributeError("Main greenlets do not have a run attribute."); +} + +void +MainGreenlet::run(const BorrowedObject UNUSED(nrun)) +{ + throw AttributeError("Main greenlets do not have a run attribute."); +} + +void +MainGreenlet::parent(const BorrowedObject raw_new_parent) +{ + if (!raw_new_parent) { + throw AttributeError("can't delete attribute"); + } + throw AttributeError("cannot set the parent of a main greenlet"); +} + +const OwnedGreenlet +MainGreenlet::parent() const +{ + return OwnedGreenlet(); // null becomes None +} + +}; // namespace greenlet + +#endif diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/TPythonState.cpp b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/TPythonState.cpp new file mode 100644 index 000000000..7c493b8e4 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/TPythonState.cpp @@ -0,0 +1,490 @@ +#ifndef GREENLET_PYTHON_STATE_CPP +#define GREENLET_PYTHON_STATE_CPP + +#include +#include "TGreenlet.hpp" + +namespace greenlet { + +PythonState::PythonState() + : _top_frame() +#if GREENLET_USE_CFRAME + ,cframe(nullptr) + ,use_tracing(0) +#endif +#if GREENLET_PY314 + ,py_recursion_depth(0) + ,current_executor(nullptr) + ,stackpointer(nullptr) + #ifdef Py_GIL_DISABLED + ,c_stack_refs(nullptr) + #endif +#elif GREENLET_PY312 + ,py_recursion_depth(0) + ,c_recursion_depth(0) +#else + ,recursion_depth(0) +#endif +#if GREENLET_PY313 + ,delete_later(nullptr) +#else + ,trash_delete_nesting(0) +#endif +#if GREENLET_PY311 + ,current_frame(nullptr) + ,datastack_chunk(nullptr) + ,datastack_top(nullptr) + ,datastack_limit(nullptr) +#endif +{ +#if GREENLET_USE_CFRAME + /* + The PyThreadState->cframe pointer usually points to memory on + the stack, alloceted in a call into PyEval_EvalFrameDefault. + + Initially, before any evaluation begins, it points to the + initial PyThreadState object's ``root_cframe`` object, which is + statically allocated for the lifetime of the thread. + + A greenlet can last for longer than a call to + PyEval_EvalFrameDefault, so we can't set its ``cframe`` pointer + to be the current ``PyThreadState->cframe``; nor could we use + one from the greenlet parent for the same reason. Yet a further + no: we can't allocate one scoped to the greenlet and then + destroy it when the greenlet is deallocated, because inside the + interpreter the _PyCFrame objects form a linked list, and that too + can result in accessing memory beyond its dynamic lifetime (if + the greenlet doesn't actually finish before it dies, its entry + could still be in the list). + + Using the ``root_cframe`` is problematic, though, because its + members are never modified by the interpreter and are set to 0, + meaning that its ``use_tracing`` flag is never updated. We don't + want to modify that value in the ``root_cframe`` ourself: it + *shouldn't* matter much because we should probably never get + back to the point where that's the only cframe on the stack; + even if it did matter, the major consequence of an incorrect + value for ``use_tracing`` is that if its true the interpreter + does some extra work --- however, it's just good code hygiene. + + Our solution: before a greenlet runs, after its initial + creation, it uses the ``root_cframe`` just to have something to + put there. However, once the greenlet is actually switched to + for the first time, ``g_initialstub`` (which doesn't actually + "return" while the greenlet is running) stores a new _PyCFrame on + its local stack, and copies the appropriate values from the + currently running _PyCFrame; this is then made the _PyCFrame for the + newly-minted greenlet. ``g_initialstub`` then proceeds to call + ``glet.run()``, which results in ``PyEval_...`` adding the + _PyCFrame to the list. Switches continue as normal. Finally, when + the greenlet finishes, the call to ``glet.run()`` returns and + the _PyCFrame is taken out of the linked list and the stack value + is now unused and free to expire. + + XXX: I think we can do better. If we're deallocing in the same + thread, can't we traverse the list and unlink our frame? + Can we just keep a reference to the thread state in case we + dealloc in another thread? (Is that even possible if we're still + running and haven't returned from g_initialstub?) + */ + this->cframe = &PyThreadState_GET()->root_cframe; +#endif +} + + +inline void PythonState::may_switch_away() noexcept +{ +#if GREENLET_PY311 + // PyThreadState_GetFrame is probably going to have to allocate a + // new frame object. That may trigger garbage collection. Because + // we call this during the early phases of a switch (it doesn't + // matter to which greenlet, as this has a global effect), if a GC + // triggers a switch away, two things can happen, both bad: + // - We might not get switched back to, halting forward progress. + // this is pathological, but possible. + // - We might get switched back to with a different set of + // arguments or a throw instead of a switch. That would corrupt + // our state (specifically, PyErr_Occurred() and this->args() + // would no longer agree). + // + // Thus, when we call this API, we need to have GC disabled. + // This method serves as a bottleneck we call when maybe beginning + // a switch. In this way, it is always safe -- no risk of GC -- to + // use ``_GetFrame()`` whenever we need to, just as it was in + // <=3.10 (because subsequent calls will be cached and not + // allocate memory). + + GCDisabledGuard no_gc; + Py_XDECREF(PyThreadState_GetFrame(PyThreadState_GET())); +#endif +} + +void PythonState::operator<<(const PyThreadState *const tstate) noexcept +{ + this->_context.steal(tstate->context); +#if GREENLET_USE_CFRAME + /* + IMPORTANT: ``cframe`` is a pointer into the STACK. Thus, because + the call to ``slp_switch()`` changes the contents of the stack, + you cannot read from ``ts_current->cframe`` after that call and + necessarily get the same values you get from reading it here. + Anything you need to restore from now to then must be saved in a + global/threadlocal variable (because we can't use stack + variables here either). For things that need to persist across + the switch, use `will_switch_from`. + */ + this->cframe = tstate->cframe; + #if !GREENLET_PY312 + this->use_tracing = tstate->cframe->use_tracing; + #endif +#endif // GREENLET_USE_CFRAME +#if GREENLET_PY311 + #if GREENLET_PY314 + this->py_recursion_depth = tstate->py_recursion_limit - tstate->py_recursion_remaining; + this->current_executor = tstate->current_executor; + #ifdef Py_GIL_DISABLED + this->c_stack_refs = ((_PyThreadStateImpl*)tstate)->c_stack_refs; + #endif + #elif GREENLET_PY312 + this->py_recursion_depth = tstate->py_recursion_limit - tstate->py_recursion_remaining; + this->c_recursion_depth = Py_C_RECURSION_LIMIT - tstate->c_recursion_remaining; + #else // not 312 + this->recursion_depth = tstate->recursion_limit - tstate->recursion_remaining; + #endif // GREENLET_PY312 + #if GREENLET_PY313 + this->current_frame = tstate->current_frame; + #elif GREENLET_USE_CFRAME + this->current_frame = tstate->cframe->current_frame; + #endif + this->datastack_chunk = tstate->datastack_chunk; + this->datastack_top = tstate->datastack_top; + this->datastack_limit = tstate->datastack_limit; + + PyFrameObject *frame = PyThreadState_GetFrame((PyThreadState *)tstate); + Py_XDECREF(frame); // PyThreadState_GetFrame gives us a new + // reference. + this->_top_frame.steal(frame); + #if GREENLET_PY314 + if (this->top_frame()) { + this->stackpointer = this->_top_frame->f_frame->stackpointer; + } + else { + this->stackpointer = nullptr; + } + #endif + #if GREENLET_PY313 + // By contract of _PyTrash_thread_deposit_object, + // the ``delete_later`` object has a refcount of 0. + // We take a strong reference to it. + // + // Now, ``delete_later`` is managed as a + // linked list whose objects are unconditionally deallocated + // WITHOUT calling DECREF on them, so it's not clear what that is + // actually accomplishing. That is, if another object is pushed on + // the list and then the list is deallocated, this object will + // still be deallocated. This strong reference serves as a form of + // resurrection, meaning that when operator>> DECREFs it, we might + // enter its ``tp_dealloc`` function again. + // + // In practice, it's quite difficult to arrange for this to be + // a non-null value during a greenlet switch. + // ``greenlet.tests.test_greenlet_trash`` tries, but under 3.14, + // at least, fails to do so. + this->delete_later = Py_XNewRef(tstate->delete_later); + #elif GREENLET_PY312 + this->trash_delete_nesting = tstate->trash.delete_nesting; + #else // not 312 or 3.13+ + this->trash_delete_nesting = tstate->trash_delete_nesting; + #endif // GREENLET_PY312 +#else // Not 311 + this->recursion_depth = tstate->recursion_depth; + this->_top_frame.steal(tstate->frame); + this->trash_delete_nesting = tstate->trash_delete_nesting; +#endif // GREENLET_PY311 +} + +#if GREENLET_PY312 +void GREENLET_NOINLINE(PythonState::unexpose_frames)() +{ + if (!this->top_frame()) { + return; + } + + // See GreenletState::expose_frames() and the comment on frames_were_exposed + // for more information about this logic. + _PyInterpreterFrame *iframe = this->_top_frame->f_frame; + while (iframe != nullptr) { + _PyInterpreterFrame *prev_exposed = iframe->previous; + assert(iframe->frame_obj); + memcpy(&iframe->previous, &iframe->frame_obj->_f_frame_data[0], + sizeof(void *)); + iframe = prev_exposed; + } +} +#else +void PythonState::unexpose_frames() +{} +#endif + +void PythonState::operator>>(PyThreadState *const tstate) noexcept +{ + tstate->context = this->_context.relinquish_ownership(); + /* Incrementing this value invalidates the contextvars cache, + which would otherwise remain valid across switches */ + tstate->context_ver++; +#if GREENLET_USE_CFRAME + tstate->cframe = this->cframe; + /* + If we were tracing, we need to keep tracing. + There should never be the possibility of hitting the + root_cframe here. See note above about why we can't + just copy this from ``origin->cframe->use_tracing``. + */ + #if !GREENLET_PY312 + tstate->cframe->use_tracing = this->use_tracing; + #endif +#endif // GREENLET_USE_CFRAME +#if GREENLET_PY311 + #if GREENLET_PY314 + tstate->py_recursion_remaining = tstate->py_recursion_limit - this->py_recursion_depth; + tstate->current_executor = this->current_executor; + #ifdef Py_GIL_DISABLED + ((_PyThreadStateImpl*)tstate)->c_stack_refs = this->c_stack_refs; + #endif + this->unexpose_frames(); + #elif GREENLET_PY312 + tstate->py_recursion_remaining = tstate->py_recursion_limit - this->py_recursion_depth; + tstate->c_recursion_remaining = Py_C_RECURSION_LIMIT - this->c_recursion_depth; + this->unexpose_frames(); + #else // \/ 3.11 + tstate->recursion_remaining = tstate->recursion_limit - this->recursion_depth; + #endif // GREENLET_PY312 + #if GREENLET_PY313 + tstate->current_frame = this->current_frame; + #elif GREENLET_USE_CFRAME + tstate->cframe->current_frame = this->current_frame; + #endif + tstate->datastack_chunk = this->datastack_chunk; + tstate->datastack_top = this->datastack_top; + tstate->datastack_limit = this->datastack_limit; +#if GREENLET_PY314 && defined(Py_GIL_DISABLED) + if (this->top_frame()) { + this->_top_frame->f_frame->stackpointer = this->stackpointer; + } +#endif + this->_top_frame.relinquish_ownership(); + #if GREENLET_PY313 + // See comments in operator<<. We own a strong reference to + // this->delete_later, which may or may not be the same object as + // tstate->delete_later (depending if something pushed an object + // onto the trashcan). Again, because ``delete_later`` is managed + // as a linked list, it's not clear that saving and restoring the + // value, especially without ever setting it to NULL, accomplishes + // much...but the code was added by a core dev, so assume correct. + // + // Recall that tstate->delete_later is supposed to have a refcount + // of 0, because objects are added there from their ``tp_dealloc`` + // method. So we should only need to DECREF it if we're the ones + // that INCREF'd it in operator<<. (This is different than the + // core dev's original code which always did this.) + if (this->delete_later == tstate->delete_later) { + Py_XDECREF(tstate->delete_later); + tstate->delete_later = this->delete_later; + this->delete_later = nullptr; + } + else { + // it got switched behind our back. So the reference we own + // needs to be explicitly cleared. + tstate->delete_later = this->delete_later; + Py_CLEAR(this->delete_later); + } + + + #elif GREENLET_PY312 + tstate->trash.delete_nesting = this->trash_delete_nesting; + #else // not 3.12 + tstate->trash_delete_nesting = this->trash_delete_nesting; + #endif // GREENLET_PY312 +#else // not 3.11 + tstate->frame = this->_top_frame.relinquish_ownership(); + tstate->recursion_depth = this->recursion_depth; + tstate->trash_delete_nesting = this->trash_delete_nesting; +#endif // GREENLET_PY311 +} + +inline void PythonState::will_switch_from(PyThreadState *const origin_tstate) noexcept +{ +#if GREENLET_USE_CFRAME && !GREENLET_PY312 + // The weird thing is, we don't actually save this for an + // effect on the current greenlet, it's saved for an + // effect on the target greenlet. That is, we want + // continuity of this setting across the greenlet switch. + this->use_tracing = origin_tstate->cframe->use_tracing; +#endif +} + +void PythonState::set_initial_state(const PyThreadState* const tstate) noexcept +{ + this->_top_frame = nullptr; +#if GREENLET_PY314 + this->py_recursion_depth = tstate->py_recursion_limit - tstate->py_recursion_remaining; + this->current_executor = tstate->current_executor; + #ifdef Py_GIL_DISABLED + this->c_stack_refs = ((_PyThreadStateImpl*)tstate)->c_stack_refs; + #endif + // this->stackpointer is left null because this->_top_frame is + // null so there is no value to copy. +#elif GREENLET_PY312 + this->py_recursion_depth = tstate->py_recursion_limit - tstate->py_recursion_remaining; +#if GREENLET_314 + this->c_recursion_depth = 0; // unused on 3.14 +#else + this->c_recursion_depth = Py_C_RECURSION_LIMIT - tstate->c_recursion_remaining; +#endif +#elif GREENLET_PY311 + this->recursion_depth = tstate->recursion_limit - tstate->recursion_remaining; +#else + this->recursion_depth = tstate->recursion_depth; +#endif +} +// TODO: Better state management about when we own the top frame. +int PythonState::tp_traverse(visitproc visit, void* arg, bool own_top_frame) noexcept +{ + Py_VISIT(this->_context.borrow()); + if (own_top_frame) { + Py_VISIT(this->_top_frame.borrow()); + } +#if GREENLET_PY314 + // TODO: Should we be visiting the c_stack_refs objects? + // CPython uses a specific macro to do that which takes into + // account boxing and null values and then calls + // ``_PyGC_VisitStackRef``, but we don't have access to that, and + // we can't duplicate it ourself (because it compares + // ``visitproc`` to another function we can't access). + // The naive way of looping over c_stack_refs->ref and visiting + // those crashes the process (at least with GIL disabled). +#endif + // Note that we DO NOT visit ``delete_later``. Even if it's + // non-null and we technically own a reference to it, its + // reference count already went to 0 once and it was in the + // process of being deallocated. The trash can mechanism linked it + // into a list that will be cleaned at some later time, and it has + // become untracked by the GC. + return 0; +} + +void PythonState::tp_clear(bool own_top_frame) noexcept +{ + PythonStateContext::tp_clear(); + // If we get here owning a frame, + // we got dealloc'd without being finished. We may or may not be + // in the same thread. + if (own_top_frame) { + this->_top_frame.CLEAR(); + } +} + +#if GREENLET_USE_CFRAME +void PythonState::set_new_cframe(_PyCFrame& frame) noexcept +{ + frame = *PyThreadState_GET()->cframe; + /* Make the target greenlet refer to the stack value. */ + this->cframe = &frame; + /* + And restore the link to the previous frame so this one gets + unliked appropriately. + */ + this->cframe->previous = &PyThreadState_GET()->root_cframe; +} +#endif + +const PythonState::OwnedFrame& PythonState::top_frame() const noexcept +{ + return this->_top_frame; +} + +void PythonState::did_finish(PyThreadState* tstate) noexcept +{ +#if GREENLET_PY311 + // See https://github.com/gevent/gevent/issues/1924 and + // https://github.com/python-greenlet/greenlet/issues/328. In + // short, Python 3.11 allocates memory for frames as a sort of + // linked list that's kept as part of PyThreadState in the + // ``datastack_chunk`` member and friends. These are saved and + // restored as part of switching greenlets. + // + // When we initially switch to a greenlet, we set those to NULL. + // That causes the frame management code to treat this like a + // brand new thread and start a fresh list of chunks, beginning + // with a new "root" chunk. As we make calls in this greenlet, + // those chunks get added, and as calls return, they get popped. + // But the frame code (pystate.c) is careful to make sure that the + // root chunk never gets popped. + // + // Thus, when a greenlet exits for the last time, there will be at + // least a single root chunk that we must be responsible for + // deallocating. + // + // The complex part is that these chunks are allocated and freed + // using ``_PyObject_VirtualAlloc``/``Free``. Those aren't public + // functions, and they aren't exported for linking. It so happens + // that we know they are just thin wrappers around the Arena + // allocator, so we can use that directly to deallocate in a + // compatible way. + // + // CAUTION: Check this implementation detail on every major version. + // + // It might be nice to be able to do this in our destructor, but + // can we be sure that no one else is using that memory? Plus, as + // described below, our pointers may not even be valid anymore. As + // a special case, there is one time that we know we can do this, + // and that's from the destructor of the associated UserGreenlet + // (NOT main greenlet) + PyObjectArenaAllocator alloc; + _PyStackChunk* chunk = nullptr; + if (tstate) { + // We really did finish, we can never be switched to again. + chunk = tstate->datastack_chunk; + // Unfortunately, we can't do much sanity checking. Our + // this->datastack_chunk pointer is out of date (evaluation may + // have popped down through it already) so we can't verify that + // we deallocate it. I don't think we can even check datastack_top + // for the same reason. + + PyObject_GetArenaAllocator(&alloc); + tstate->datastack_chunk = nullptr; + tstate->datastack_limit = nullptr; + tstate->datastack_top = nullptr; + + } + else if (this->datastack_chunk) { + // The UserGreenlet (NOT the main greenlet!) is being deallocated. If we're + // still holding a stack chunk, it's garbage because we know + // we can never switch back to let cPython clean it up. + // Because the last time we got switched away from, and we + // haven't run since then, we know our chain is valid and can + // be dealloced. + chunk = this->datastack_chunk; + PyObject_GetArenaAllocator(&alloc); + } + + if (alloc.free && chunk) { + // In case the arena mechanism has been torn down already. + while (chunk) { + _PyStackChunk *prev = chunk->previous; + chunk->previous = nullptr; + alloc.free(alloc.ctx, chunk, chunk->size); + chunk = prev; + } + } + + this->datastack_chunk = nullptr; + this->datastack_limit = nullptr; + this->datastack_top = nullptr; +#endif +} + + +}; // namespace greenlet + +#endif // GREENLET_PYTHON_STATE_CPP diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/TStackState.cpp b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/TStackState.cpp new file mode 100644 index 000000000..9743ab51b --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/TStackState.cpp @@ -0,0 +1,265 @@ +#ifndef GREENLET_STACK_STATE_CPP +#define GREENLET_STACK_STATE_CPP + +#include "TGreenlet.hpp" + +namespace greenlet { + +#ifdef GREENLET_USE_STDIO +#include +using std::cerr; +using std::endl; + +std::ostream& operator<<(std::ostream& os, const StackState& s) +{ + os << "StackState(stack_start=" << (void*)s._stack_start + << ", stack_stop=" << (void*)s.stack_stop + << ", stack_copy=" << (void*)s.stack_copy + << ", stack_saved=" << s._stack_saved + << ", stack_prev=" << s.stack_prev + << ", addr=" << &s + << ")"; + return os; +} +#endif + +StackState::StackState(void* mark, StackState& current) + : _stack_start(nullptr), + stack_stop((char*)mark), + stack_copy(nullptr), + _stack_saved(0), + /* Skip a dying greenlet */ + stack_prev(current._stack_start + ? ¤t + : current.stack_prev) +{ +} + +StackState::StackState() + : _stack_start(nullptr), + stack_stop(nullptr), + stack_copy(nullptr), + _stack_saved(0), + stack_prev(nullptr) +{ +} + +StackState::StackState(const StackState& other) +// can't use a delegating constructor because of +// MSVC for Python 2.7 + : _stack_start(nullptr), + stack_stop(nullptr), + stack_copy(nullptr), + _stack_saved(0), + stack_prev(nullptr) +{ + this->operator=(other); +} + +StackState& StackState::operator=(const StackState& other) +{ + if (&other == this) { + return *this; + } + if (other._stack_saved) { + throw std::runtime_error("Refusing to steal memory."); + } + + //If we have memory allocated, dispose of it + this->free_stack_copy(); + + this->_stack_start = other._stack_start; + this->stack_stop = other.stack_stop; + this->stack_copy = other.stack_copy; + this->_stack_saved = other._stack_saved; + this->stack_prev = other.stack_prev; + return *this; +} + +inline void StackState::free_stack_copy() noexcept +{ + PyMem_Free(this->stack_copy); + this->stack_copy = nullptr; + this->_stack_saved = 0; +} + +inline void StackState::copy_heap_to_stack(const StackState& current) noexcept +{ + + /* Restore the heap copy back into the C stack */ + if (this->_stack_saved != 0) { + memcpy(this->_stack_start, this->stack_copy, this->_stack_saved); + this->free_stack_copy(); + } + StackState* owner = const_cast(¤t); + if (!owner->_stack_start) { + owner = owner->stack_prev; /* greenlet is dying, skip it */ + } + while (owner && owner->stack_stop <= this->stack_stop) { + // cerr << "\tOwner: " << owner << endl; + owner = owner->stack_prev; /* find greenlet with more stack */ + } + this->stack_prev = owner; + // cerr << "\tFinished with: " << *this << endl; +} + +inline int StackState::copy_stack_to_heap_up_to(const char* const stop) noexcept +{ + /* Save more of g's stack into the heap -- at least up to 'stop' + g->stack_stop |________| + | | + | __ stop . . . . . + | | ==> . . + |________| _______ + | | | | + | | | | + g->stack_start | | |_______| g->stack_copy + */ + intptr_t sz1 = this->_stack_saved; + intptr_t sz2 = stop - this->_stack_start; + assert(this->_stack_start); + if (sz2 > sz1) { + char* c = (char*)PyMem_Realloc(this->stack_copy, sz2); + if (!c) { + PyErr_NoMemory(); + return -1; + } + memcpy(c + sz1, this->_stack_start + sz1, sz2 - sz1); + this->stack_copy = c; + this->_stack_saved = sz2; + } + return 0; +} + +inline int StackState::copy_stack_to_heap(char* const stackref, + const StackState& current) noexcept +{ + /* must free all the C stack up to target_stop */ + const char* const target_stop = this->stack_stop; + + StackState* owner = const_cast(¤t); + assert(owner->_stack_saved == 0); // everything is present on the stack + if (!owner->_stack_start) { + owner = owner->stack_prev; /* not saved if dying */ + } + else { + owner->_stack_start = stackref; + } + + while (owner->stack_stop < target_stop) { + /* ts_current is entierely within the area to free */ + if (owner->copy_stack_to_heap_up_to(owner->stack_stop)) { + return -1; /* XXX */ + } + owner = owner->stack_prev; + } + if (owner != this) { + if (owner->copy_stack_to_heap_up_to(target_stop)) { + return -1; /* XXX */ + } + } + return 0; +} + +inline bool StackState::started() const noexcept +{ + return this->stack_stop != nullptr; +} + +inline bool StackState::main() const noexcept +{ + return this->stack_stop == (char*)-1; +} + +inline bool StackState::active() const noexcept +{ + return this->_stack_start != nullptr; +} + +inline void StackState::set_active() noexcept +{ + assert(this->_stack_start == nullptr); + this->_stack_start = (char*)1; +} + +inline void StackState::set_inactive() noexcept +{ + this->_stack_start = nullptr; + // XXX: What if we still have memory out there? + // That case is actually triggered by + // test_issue251_issue252_explicit_reference_not_collectable (greenlet.tests.test_leaks.TestLeaks) + // and + // test_issue251_issue252_need_to_collect_in_background + // (greenlet.tests.test_leaks.TestLeaks) + // + // Those objects never get deallocated, so the destructor never + // runs. + // It *seems* safe to clean up the memory here? + if (this->_stack_saved) { + this->free_stack_copy(); + } +} + +inline intptr_t StackState::stack_saved() const noexcept +{ + return this->_stack_saved; +} + +inline char* StackState::stack_start() const noexcept +{ + return this->_stack_start; +} + + +inline StackState StackState::make_main() noexcept +{ + StackState s; + s._stack_start = (char*)1; + s.stack_stop = (char*)-1; + return s; +} + +StackState::~StackState() +{ + if (this->_stack_saved != 0) { + this->free_stack_copy(); + } +} + +void StackState::copy_from_stack(void* vdest, const void* vsrc, size_t n) const +{ + char* dest = static_cast(vdest); + const char* src = static_cast(vsrc); + if (src + n <= this->_stack_start + || src >= this->_stack_start + this->_stack_saved + || this->_stack_saved == 0) { + // Nothing we're copying was spilled from the stack + memcpy(dest, src, n); + return; + } + + if (src < this->_stack_start) { + // Copy the part before the saved stack. + // We know src + n > _stack_start due to the test above. + const size_t nbefore = this->_stack_start - src; + memcpy(dest, src, nbefore); + dest += nbefore; + src += nbefore; + n -= nbefore; + } + // We know src >= _stack_start after the before-copy, and + // src < _stack_start + _stack_saved due to the first if condition + size_t nspilled = std::min(n, this->_stack_start + this->_stack_saved - src); + memcpy(dest, this->stack_copy + (src - this->_stack_start), nspilled); + dest += nspilled; + src += nspilled; + n -= nspilled; + if (n > 0) { + // Copy the part after the saved stack + memcpy(dest, src, n); + } +} + +}; // namespace greenlet + +#endif // GREENLET_STACK_STATE_CPP diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/TThreadState.hpp b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/TThreadState.hpp new file mode 100644 index 000000000..fe74ce365 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/TThreadState.hpp @@ -0,0 +1,627 @@ +#ifndef GREENLET_THREAD_STATE_HPP +#define GREENLET_THREAD_STATE_HPP + +#include +#include +#include +#include + +#include "greenlet_internal.hpp" +#include "greenlet_refs.hpp" +#include "greenlet_thread_support.hpp" + +using greenlet::LockGuard; +using greenlet::refs::BorrowedObject; +using greenlet::refs::BorrowedGreenlet; +using greenlet::refs::BorrowedMainGreenlet; +using greenlet::refs::OwnedMainGreenlet; +using greenlet::refs::OwnedObject; +using greenlet::refs::OwnedGreenlet; +using greenlet::refs::OwnedList; +using greenlet::refs::PyErrFetchParam; +using greenlet::refs::PyArgParseParam; +using greenlet::refs::ImmortalString; +using greenlet::refs::CreatedModule; +using greenlet::refs::PyErrPieces; +using greenlet::refs::NewReference; + + +namespace greenlet { +/** + * Thread-local state of greenlets. + * + * Each native thread will get exactly one of these objects, + * automatically accessed through the best available thread-local + * mechanism the compiler supports (``thread_local`` for C++11 + * compilers or ``__thread``/``declspec(thread)`` for older GCC/clang + * or MSVC, respectively.) + * + * Previously, we kept thread-local state mostly in a bunch of + * ``static volatile`` variables in the main greenlet file.. This had + * the problem of requiring extra checks, loops, and great care + * accessing these variables if we potentially invoked any Python code + * that could release the GIL, because the state could change out from + * under us. Making the variables thread-local solves this problem. + * + * When we detected that a greenlet API accessing the current greenlet + * was invoked from a different thread than the greenlet belonged to, + * we stored a reference to the greenlet in the Python thread + * dictionary for the thread the greenlet belonged to. This could lead + * to memory leaks if the thread then exited (because of a reference + * cycle, as greenlets referred to the thread dictionary, and deleting + * non-current greenlets leaked their frame plus perhaps arguments on + * the C stack). If a thread exited while still having running + * greenlet objects (perhaps that had just switched back to the main + * greenlet), and did not invoke one of the greenlet APIs *in that + * thread, immediately before it exited, without some other thread + * then being invoked*, such a leak was guaranteed. + * + * This can be partly solved by using compiler thread-local variables + * instead of the Python thread dictionary, thus avoiding a cycle. + * + * To fully solve this problem, we need a reliable way to know that a + * thread is done and we should clean up the main greenlet. On POSIX, + * we can use the destructor function of ``pthread_key_create``, but + * there's nothing similar on Windows; a C++11 thread local object + * reliably invokes its destructor when the thread it belongs to exits + * (non-C++11 compilers offer ``__thread`` or ``declspec(thread)`` to + * create thread-local variables, but they can't hold C++ objects that + * invoke destructors; the C++11 version is the most portable solution + * I found). When the thread exits, we can drop references and + * otherwise manipulate greenlets and frames that we know can no + * longer be switched to. + * + * There are two small wrinkles. The first is that when the thread + * exits, it is too late to actually invoke Python APIs: the Python + * thread state is gone, and the GIL is released. To solve *this* + * problem, our destructor uses ``Py_AddPendingCall`` to transfer the + * destruction work to the main thread. + * + * The second is that once the thread exits, the thread local object + * is invalid and we can't even access a pointer to it, so we can't + * pass it to ``Py_AddPendingCall``. This is handled by actually using + * a second object that's thread local (ThreadStateCreator) and having + * it dynamically allocate this object so it can live until the + * pending call runs. + */ + + + +class ThreadState { +private: + // As of commit 08ad1dd7012b101db953f492e0021fb08634afad + // this class needed 56 bytes in o Py_DEBUG build + // on 64-bit macOS 11. + // Adding the vector takes us up to 80 bytes () + + /* Strong reference to the main greenlet */ + OwnedMainGreenlet main_greenlet; + + /* Strong reference to the current greenlet. */ + OwnedGreenlet current_greenlet; + + /* Strong reference to the trace function, if any. */ + OwnedObject tracefunc; + + // Use std::allocator (malloc/free) instead of PythonAllocator + // (PyMem_Malloc) for the deleteme list. During Py_FinalizeEx on + // Python < 3.11, the PyObject_Malloc pool that holds ThreadState + // can be disrupted, corrupting any PythonAllocator-backed + // containers. Using std::allocator makes this vector independent + // of Python's allocator lifecycle. + typedef std::vector deleteme_t; + /* A vector of raw PyGreenlet pointers representing things that need + deleted when this thread is running. The vector owns the + references, but you need to manually INCREF/DECREF as you use + them. We don't use a vector because we + make copy of this vector, and that would become O(n) as all the + refcounts are incremented in the copy. + */ + deleteme_t deleteme; +#ifdef Py_GIL_DISABLED + // On free-threaded builds, we need to protect shared access to + // the deleteme list by a mutex. It can be written from one thread + // while being read in another + Mutex deleteme_lock; +#endif + +#ifdef GREENLET_NEEDS_EXCEPTION_STATE_SAVED + void* exception_state; +#endif + +#ifdef Py_GIL_DISABLED + static std::atomic _clocks_used_doing_gc; +#else + static std::clock_t _clocks_used_doing_gc; +#endif + static ImmortalString get_referrers_name; + + G_NO_COPIES_OF_CLS(ThreadState); + + + // Allocates a main greenlet for the thread state. If this fails, + // exits the process. Called only during constructing a ThreadState. + MainGreenlet* alloc_main() + { + PyGreenlet* gmain; + + /* create the main greenlet for this thread */ + gmain = reinterpret_cast(PyType_GenericAlloc(&PyGreenlet_Type, 0)); + if (gmain == NULL) { + throw PyFatalError("alloc_main failed to alloc"); //exits the process + } + + MainGreenlet* const main = new MainGreenlet(gmain, this); + + assert(Py_REFCNT(gmain) == 1); + assert(gmain->pimpl == main); + return main; + } + + +public: + // Allocate ThreadState with malloc/free rather than Python's + // object allocator. ThreadState outlives many Python objects and + // must remain valid throughout Py_FinalizeEx. On Python < 3.11, + // PyObject_Malloc pools can be disrupted during early + // finalization, corrupting any C++ objects stored in them. + static void* operator new(size_t count) + { + void* p = std::malloc(count); + if (!p) { + throw std::bad_alloc(); + } + return p; + } + + static void operator delete(void* ptr) + { + std::free(ptr); + } + + static void init() + { + ThreadState::get_referrers_name = "get_referrers"; + ThreadState::set_clocks_used_doing_gc(0); + } + + ThreadState() + { + +#ifdef GREENLET_NEEDS_EXCEPTION_STATE_SAVED + this->exception_state = slp_get_exception_state(); +#endif + + // XXX: Potentially dangerous, exposing a not fully + // constructed object. + MainGreenlet* const main = this->alloc_main(); + this->main_greenlet = OwnedMainGreenlet::consuming( + main->self() + ); + assert(this->main_greenlet); + this->current_greenlet = main->self(); + // The main greenlet starts with 1 refs: The returned one. We + // then copied it to the current greenlet. + assert(this->main_greenlet.REFCNT() == 2); + } + + inline void restore_exception_state() + { +#ifdef GREENLET_NEEDS_EXCEPTION_STATE_SAVED + // It's probably important this be inlined and only call C + // functions to avoid adding an SEH frame. + slp_set_exception_state(this->exception_state); +#endif + } + + inline bool has_main_greenlet() const noexcept + { + return bool(this->main_greenlet); + } + + // Called from the ThreadStateCreator when we're in non-standard + // threading mode. In that case, there is an object in the Python + // thread state dictionary that points to us. The main greenlet + // also traverses into us, in which case it's crucial not to + // traverse back into the main greenlet. + int tp_traverse(visitproc visit, void* arg, bool traverse_main=true) + { + if (traverse_main) { + Py_VISIT(main_greenlet.borrow_o()); + } + if (traverse_main || current_greenlet != main_greenlet) { + Py_VISIT(current_greenlet.borrow_o()); + } + Py_VISIT(tracefunc.borrow()); + return 0; + } + + inline BorrowedMainGreenlet borrow_main_greenlet() const noexcept + { + assert(this->main_greenlet); + assert(this->main_greenlet.REFCNT() >= 2); + return this->main_greenlet; + }; + + inline OwnedMainGreenlet get_main_greenlet() const noexcept + { + return this->main_greenlet; + } + + /** + * If we have a main greenlet, mark it as dead by setting its + * thread_state to null (this part is atomic with respect to other + * threads looking at the main greenlet's thread_state). + */ + inline bool mark_main_greenlet_dead() noexcept + { + PyGreenlet* main_greenlet = this->main_greenlet.borrow(); + if (!main_greenlet) { + return false; + } + assert(main_greenlet->pimpl->thread_state() == this + || main_greenlet->pimpl->thread_state() == nullptr); + dynamic_cast(main_greenlet->pimpl)->thread_state(nullptr); + return true; + } + + /** + * In addition to returning a new reference to the currunt + * greenlet, this performs any maintenance needed. + */ + inline OwnedGreenlet get_current() + { + /* green_dealloc() cannot delete greenlets from other threads, so + it stores them in the thread dict; delete them now. */ + this->clear_deleteme_list(); + //assert(this->current_greenlet->main_greenlet == this->main_greenlet); + //assert(this->main_greenlet->main_greenlet == this->main_greenlet); + return this->current_greenlet; + } + + /** + * As for non-const get_current(); + */ + inline BorrowedGreenlet borrow_current() + { + this->clear_deleteme_list(); + return this->current_greenlet; + } + + /** + * Does no maintenance. + */ + inline OwnedGreenlet get_current() const + { + return this->current_greenlet; + } + + template + inline bool is_current(const refs::PyObjectPointer& obj) const + { + return this->current_greenlet.borrow_o() == obj.borrow_o(); + } + + inline void set_current(const OwnedGreenlet& target) + { + this->current_greenlet = target; + } + +private: + /** + * Deref and remove the greenlets from the deleteme list. Must be + * holding the GIL. + * + * If *murder* is true, then we must be called from a different + * thread than the one that these greenlets were running in. + * In that case, if the greenlet was actually running, we destroy + * the frame reference and otherwise make it appear dead before + * proceeding; otherwise, we would try (and fail) to raise an + * exception in it and wind up right back in this list. + */ + inline void clear_deleteme_list(const bool murder=false) + { +#ifdef Py_GIL_DISABLED + LockGuard deleteme_guard(this->deleteme_lock); +#endif + if (this->deleteme.empty()) { + return; + } + // Move the list contents out with swap — a constant-time + // pointer exchange that never allocates. The previous + // code used a copy (deleteme_t copy = this->deleteme) + // which allocated through PythonAllocator / PyMem_Malloc; + // that could SIGSEGV during early Py_FinalizeEx on Python + // < 3.11 when the allocator is partially torn down. + deleteme_t copy; + std::swap(copy, this->deleteme); + + // During Py_FinalizeEx cleanup, the GC or atexit handlers + // may have already collected objects in this list, + // leaving dangling pointers. Attempting Py_DECREF on + // freed memory causes a SIGSEGV. g_greenlet_shutting_down + // covers the early atexit phase; Py_IsFinalizing() covers + // later phases. Thus, we deliberately leak. + if (greenlet::IsShuttingDown()) { + return; + } + + // Preserve any pending exception so that cleanup-triggered + // errors don't accidentally swallow an unrelated exception + // (e.g. one set by throw() before a switch). + PyErrPieces incoming_err; + + for(deleteme_t::iterator it = copy.begin(), end = copy.end(); + it != end; + ++it ) { + PyGreenlet* to_del = *it; + if (murder) { + // Force each greenlet to appear dead; we can't raise an + // exception into it anymore anyway. + to_del->pimpl->murder_in_place(); + } + + // The only reference to these greenlets should be in + // this list, decreffing them should let them be + // deleted again, triggering calls to green_dealloc() + // in the correct thread (if we're not murdering). + // This may run arbitrary Python code and switch + // threads or greenlets! + Py_DECREF(to_del); + if (PyErr_Occurred()) { + PyErr_WriteUnraisable(nullptr); + PyErr_Clear(); + } + } + // Not worried about C++ exception safety here in terms of + // making sure we restore the error. Either we'll catch it + // above and establish the error from that exception + // (which, yes, might overwrite something from before we + // entered, but we're in an undefined situation at that + // point) or we won't catch it at all and will crash the + // process. + // + // As for Python exception safety, there's no chance we're + // overwriting an exception (from the loop) with no + // exception (captured NULLs before we entered the loop), + // because there CAN'T BE any exception from the loop --- + // we clear them. So we're either restoring a pre-existing + // exception, or leaving the exception unset (by restoring + // NULL). + incoming_err.PyErrRestore(); + } + +public: + + /** + * Returns a new reference, or a false object. + */ + inline OwnedObject get_tracefunc() const + { + return tracefunc; + }; + + + inline void set_tracefunc(BorrowedObject tracefunc) + { + assert(tracefunc); + if (tracefunc == BorrowedObject(Py_None)) { + this->tracefunc.CLEAR(); + } + else { + this->tracefunc = tracefunc; + } + } + + /** + * Given a reference to a greenlet that some other thread + * attempted to delete (has a refcount of 0) store it for later + * deletion when the thread this state belongs to is current. + */ + inline void delete_when_thread_running(PyGreenlet* to_del) + { + Py_INCREF(to_del); +#ifdef Py_GIL_DISABLED + LockGuard deleteme_guard(this->deleteme_lock); +#endif + this->deleteme.push_back(to_del); + } + + /** + * Set to std::clock_t(-1) to disable. + */ + inline static std::clock_t clocks_used_doing_gc() + { +#ifdef Py_GIL_DISABLED + return ThreadState::_clocks_used_doing_gc.load(std::memory_order_relaxed); +#else + return ThreadState::_clocks_used_doing_gc; +#endif + } + + inline static void set_clocks_used_doing_gc(std::clock_t value) + { +#ifdef Py_GIL_DISABLED + ThreadState::_clocks_used_doing_gc.store(value, std::memory_order_relaxed); +#else + ThreadState::_clocks_used_doing_gc = value; +#endif + } + + inline static void add_clocks_used_doing_gc(std::clock_t value) + { +#ifdef Py_GIL_DISABLED + ThreadState::_clocks_used_doing_gc.fetch_add(value, std::memory_order_relaxed); +#else + ThreadState::_clocks_used_doing_gc += value; +#endif + } + + // Runs in some arbitrary thread that Python is using to invoke + // pending callbacks. This may not be the thread that was + // running the greenlets. + ~ThreadState() + { + if (!PyInterpreterState_Head()) { + // We shouldn't get here (our callers protect us) + // but if we do, all we can do is bail early. + return; + } + + // During interpreter finalization, Python APIs like + // PyImport_ImportModule are unsafe (the import machinery may + // be partially torn down). On Python < 3.11, perform only the + // minimal cleanup that is safe: clear our strong references + // so we don't leak, but skip the GC-based leak detection. + // + // Python 3.11+ restructured interpreter finalization so that + // these APIs remain safe during shutdown. + if (greenlet::IsShuttingDown()) { + this->tracefunc.CLEAR(); + if (this->current_greenlet) { + this->current_greenlet->murder_in_place(); + this->current_greenlet.CLEAR(); + } + this->main_greenlet.CLEAR(); + return; + } + + // We should not have an "origin" greenlet; that only exists + // for the temporary time during a switch, which should not + // be in progress as the thread dies. + //assert(!this->switching_state.origin); + + this->tracefunc.CLEAR(); + + // Forcibly GC as much as we can. + this->clear_deleteme_list(true); + + // The pending call did this. + assert(this->main_greenlet->thread_state() == nullptr); + + // If the main greenlet is the current greenlet, + // then we "fell off the end" and the thread died. + // It's possible that there is some other greenlet that + // switched to us, leaving a reference to the main greenlet + // on the stack, somewhere uncollectible. Try to detect that. + if (this->current_greenlet == this->main_greenlet && this->current_greenlet) { + assert( + this->current_greenlet->is_currently_running_in_some_thread() + || this->current_greenlet->was_running_in_dead_thread() + ); + // Drop one reference we hold. + this->current_greenlet.CLEAR(); + assert(!this->current_greenlet); + // Only our reference to the main greenlet should be left, + // But hold onto the pointer in case we need to do extra cleanup. + PyGreenlet* old_main_greenlet = this->main_greenlet.borrow(); + Py_ssize_t cnt = this->main_greenlet.REFCNT(); + this->main_greenlet.CLEAR(); + if (ThreadState::clocks_used_doing_gc() != std::clock_t(-1) + && cnt == 2 && Py_REFCNT(old_main_greenlet) == 1) { + // Highly likely that the reference is somewhere on + // the stack, not reachable by GC. Verify. + // XXX: This is O(n) in the total number of objects. + // TODO: Add a way to disable this at runtime, and + // another way to report on it. + std::clock_t begin = std::clock(); + NewReference gc(PyImport_ImportModule("gc")); + if (gc) { + OwnedObject get_referrers = gc.PyRequireAttr(ThreadState::get_referrers_name); + OwnedList refs(get_referrers.PyCall(old_main_greenlet)); + if (refs && refs.empty()) { + assert(refs.REFCNT() == 1); + // We found nothing! So we left a dangling + // reference: Probably the last thing some + // other greenlet did was call + // 'getcurrent().parent.switch()' to switch + // back to us. Clean it up. This will be the + // case on CPython 3.7 and newer, as they use + // an internal calling conversion that avoids + // creating method objects and storing them on + // the stack. + Py_DECREF(old_main_greenlet); + } + else if (refs + && refs.size() == 1 + && PyCFunction_Check(refs.at(0)) + && Py_REFCNT(refs.at(0)) == 2) { + assert(refs.REFCNT() == 1); + // Ok, we found a C method that refers to the + // main greenlet, and its only referenced + // twice, once in the list we just created, + // once from...somewhere else. If we can't + // find where else, then this is a leak. + // This happens in older versions of CPython + // that create a bound method object somewhere + // on the stack that we'll never get back to. + if (PyCFunction_GetFunction(refs.at(0).borrow()) == (PyCFunction)green_switch) { + BorrowedObject function_w = refs.at(0); + refs.clear(); // destroy the reference + // from the list. + // back to one reference. Can *it* be + // found? + assert(function_w.REFCNT() == 1); + refs = get_referrers.PyCall(function_w); + if (refs && refs.empty()) { + // Nope, it can't be found so it won't + // ever be GC'd. Drop it. + Py_CLEAR(function_w); + } + } + } + std::clock_t end = std::clock(); + ThreadState::add_clocks_used_doing_gc(end - begin); + } + } + } + + // We need to make sure this greenlet appears to be dead, + // because otherwise deallocing it would fail to raise an + // exception in it (the thread is dead) and put it back in our + // deleteme list. + if (this->current_greenlet) { + this->current_greenlet->murder_in_place(); + this->current_greenlet.CLEAR(); + } + + if (this->main_greenlet) { + // Couldn't have been the main greenlet that was running + // when the thread exited (because we already cleared this + // pointer if it was). This shouldn't be possible? + + // If the main greenlet was current when the thread died (it + // should be, right?) then we cleared its self pointer above + // when we cleared the current greenlet's main greenlet pointer. + // assert(this->main_greenlet->main_greenlet == this->main_greenlet + // || !this->main_greenlet->main_greenlet); + // // self reference, probably gone + // this->main_greenlet->main_greenlet.CLEAR(); + + // This will actually go away when the ivar is destructed. + this->main_greenlet.CLEAR(); + } + + if (PyErr_Occurred()) { + PyErr_WriteUnraisable(NULL); + PyErr_Clear(); + } + + } + +}; + +ImmortalString ThreadState::get_referrers_name(nullptr); +#ifdef Py_GIL_DISABLED +std::atomic ThreadState::_clocks_used_doing_gc(0); +#else +std::clock_t ThreadState::_clocks_used_doing_gc(0); +#endif + + + + + +}; // namespace greenlet + +#endif diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/TThreadStateCreator.hpp b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/TThreadStateCreator.hpp new file mode 100644 index 000000000..b6d7d5977 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/TThreadStateCreator.hpp @@ -0,0 +1,105 @@ +#ifndef GREENLET_THREAD_STATE_CREATOR_HPP +#define GREENLET_THREAD_STATE_CREATOR_HPP + +#include +#include + +#include "greenlet_internal.hpp" +#include "greenlet_refs.hpp" +#include "greenlet_thread_support.hpp" + +#include "TThreadState.hpp" + +namespace greenlet { + + +typedef void (*ThreadStateDestructor)(ThreadState* const); + +// Only one of these, auto created per thread as a thread_local. +// This means we don't have to worry about atomic access to the +// internals, because by definition all access is happening on a +// single thread. +// Constructing the state constructs the MainGreenlet. +template +class ThreadStateCreator +{ +private: + // Initialized to 1, and, if still 1, created on access. + // Set to 0 on destruction. + ThreadState* _state; + G_NO_COPIES_OF_CLS(ThreadStateCreator); + + inline bool has_initialized_state() const noexcept + { + return this->_state != (ThreadState*)1; + } + + inline bool has_state() const noexcept + { + return this->has_initialized_state() && this->_state != nullptr; + } + +public: + + ThreadStateCreator() : + _state((ThreadState*)1) + { + } + + ~ThreadStateCreator() + { + if (this->has_state()) { + Destructor(this->_state); + } + + this->_state = nullptr; + } + + inline ThreadState& state() + { + // The main greenlet will own this pointer when it is created, + // which will be right after this. The plan is to give every + // greenlet a pointer to the main greenlet for the thread it + // runs in; if we are doing something cross-thread, we need to + // access the pointer from the main greenlet. Deleting the + // thread, and hence the thread-local storage, will delete the + // state pointer in the main greenlet. + if (!this->has_initialized_state()) { + // XXX: Assuming allocation never fails + this->_state = new ThreadState; + // For non-standard threading, we need to store an object + // in the Python thread state dictionary so that it can be + // DECREF'd when the thread ends (ideally; the dict could + // last longer) and clean this object up. + } + if (!this->_state) { + throw std::runtime_error("Accessing state after destruction."); + } + return *this->_state; + } + + operator ThreadState&() + { + return this->state(); + } + + operator ThreadState*() + { + return &this->state(); + } + + inline int tp_traverse(visitproc visit, void* arg) + { + if (this->has_state()) { + return this->_state->tp_traverse(visit, arg); + } + return 0; + } + +}; + + + +}; // namespace greenlet + +#endif diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/TThreadStateDestroy.cpp b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/TThreadStateDestroy.cpp new file mode 100644 index 000000000..5562a736f --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/TThreadStateDestroy.cpp @@ -0,0 +1,217 @@ +/* -*- indent-tabs-mode: nil; tab-width: 4; -*- */ +/** + * Implementation of the ThreadState destructors. + * + * Format with: + * clang-format -i --style=file src/greenlet/greenlet.c + * + * + * Fix missing braces with: + * clang-tidy src/greenlet/greenlet.c -fix -checks="readability-braces-around-statements" +*/ +#ifndef T_THREADSTATE_DESTROY +#define T_THREADSTATE_DESTROY + +#include "TGreenlet.hpp" + +#include "greenlet_thread_support.hpp" +#include "greenlet_compiler_compat.hpp" +#include "TGreenletGlobals.cpp" +#include "TThreadState.hpp" +#include "TThreadStateCreator.hpp" + +namespace greenlet { + +extern "C" { + +struct ThreadState_DestroyNoGIL +{ + /** + This function uses the same lock that the PendingCallback does + */ + static void + MarkGreenletDeadAndQueueCleanup(ThreadState* const state) + { +#if GREENLET_BROKEN_THREAD_LOCAL_CLEANUP_JUST_LEAK + // One rare platform. + return; +#endif + // We are *NOT* holding the GIL. Our thread is in the middle + // of its death throes and the Python thread state is already + // gone so we can't use most Python APIs. One that is safe is + // ``Py_AddPendingCall``, unless the interpreter itself has + // been torn down. There is a limited number of calls that can + // be queued: 32 (NPENDINGCALLS) in CPython 3.10, so we + // coalesce these calls using our own queue. + + if (!MarkGreenletDeadIfNeeded(state)) { + // No state, or no greenlet + return; + } + + // XXX: Because we don't have the GIL, this is a race condition. + if (!PyInterpreterState_Head()) { + // We have to leak the thread state, if the + // interpreter has shut down when we're getting + // deallocated, we can't run the cleanup code that + // deleting it would imply. + return; + } + + AddToCleanupQueue(state); + + } + +private: + + // If the state has an allocated main greenlet: + // - mark the greenlet as dead by disassociating it from the state; + // - return 1 + // Otherwise, return 0. + static bool + MarkGreenletDeadIfNeeded(ThreadState* const state) + { + if (!state) { + return false; + } + LockGuard cleanup_lock(*mod_globs->thread_states_to_destroy_lock); + // mark the thread as dead ASAP. + // TODO: While the state variable tracking the death is + // atomic, and used with the strictest memory ordering, could + // this still be hiding race conditions? Specifically, is + // there a scenario where a thread is dying and thread local + // variables are being deconstructed, and some other thread + // tries to switch/throw to a greenlet owned by this thread, + // such that we think the switch will work but it won't? + return state->mark_main_greenlet_dead(); + } + + static void + AddToCleanupQueue(ThreadState* const state) + { + assert(state && state->has_main_greenlet()); + + // NOTE: Because we're not holding the GIL here, some other + // Python thread could run and call ``os.fork()``, which would + // be bad if that happened while we are holding the cleanup + // lock (it wouldn't function in the child process). + // Make a best effort to try to keep the duration we hold the + // lock short. + // TODO: On platforms that support it, use ``pthread_atfork`` to + // drop this lock. + LockGuard cleanup_lock(*mod_globs->thread_states_to_destroy_lock); + + mod_globs->queue_to_destroy(state); + if (mod_globs->thread_states_to_destroy.size() == 1) { + // We added the first item to the queue. We need to schedule + // the cleanup. + + // A size greater than 1 means that we have already added the pending call, + // and in fact, it may be executing now. + // If it is executing, our lock makes sure that it will see the item we just added + // to the queue on its next iteration (after we release the lock) + // + // A size of 1 means there is no pending call, OR the pending call is + // currently executing, has dropped the lock, and is deleting the last item + // from the queue; its next iteration will go ahead and delete the item we just added. + // And the pending call we schedule here will have no work to do. + int result = AddPendingCall( + PendingCallback_DestroyQueue, + nullptr); + if (result < 0) { + // Hmm, what can we do here? + fprintf(stderr, + "greenlet: WARNING: failed in call to Py_AddPendingCall; " + "expect a memory leak.\n"); + } + } + } + + static int + PendingCallback_DestroyQueue(void* UNUSED(arg)) + { + // We're may or may not be holding the GIL here (depending on + // Py_GIL_DISABLED), so calls to ``os.fork()`` may or may not + // be possible. + while (1) { + ThreadState* to_destroy; + { + LockGuard cleanup_lock(*mod_globs->thread_states_to_destroy_lock); + if (mod_globs->thread_states_to_destroy.empty()) { + break; + } + to_destroy = mod_globs->take_next_to_destroy(); + } + assert(to_destroy); + assert(to_destroy->has_main_greenlet()); + // Drop the lock while we do the actual deletion. + // This allows other calls to MarkGreenletDeadAndQueueCleanup + // to enter and add to our queue. + DestroyOne(to_destroy); + } + return 0; + } + + static void + DestroyOne(const ThreadState* const state) + { + // May or may not be holding the GIL (depending on Py_GIL_DISABLED). + // Passed a non-shared pointer to the actual thread state. + // state -> main greenlet + // + // The thread_state in the main greenlet has already been + // cleared by the time this function runs from our pending + // callback, but the greenlet itself is still there. +#ifndef NDEBUG + PyGreenlet* main(state->borrow_main_greenlet()); + assert(main); + assert(main->pimpl->thread_state() == nullptr); +#endif + delete state; // Deleting this runs the destructor, DECREFs the main greenlet. + } + + + static int AddPendingCall(int (*func)(void*), void* arg) + { + // If the interpreter is in the middle of finalizing, we can't + // add a pending call. Trying to do so will end up in a + // SIGSEGV, as Py_AddPendingCall will not be able to get the + // interpreter and will try to dereference a NULL pointer. + // It's possible this can still segfault if we happen to get + // context switched, and maybe we should just always implement + // our own AddPendingCall, but I'd like to see if this works + // first + if (greenlet::IsShuttingDown()) { +#ifdef GREENLET_DEBUG + // No need to log in the general case. Yes, we'll leak, + // but we're shutting down so it should be ok. + fprintf(stderr, + "greenlet: WARNING: Interpreter is finalizing. Ignoring " + "call to Py_AddPendingCall; \n"); +#endif + return 0; + } + return Py_AddPendingCall(func, arg); + } + + + + + +}; +}; + +}; // namespace greenlet + +// The intent when GET_THREAD_STATE() is needed multiple times in a +// function is to take a reference to its return value in a local +// variable, to avoid the thread-local indirection. On some platforms +// (macOS), accessing a thread-local involves a function call (plus an +// initial function call in each function that uses a thread local); +// in contrast, static volatile variables are at some pre-computed +// offset. +typedef greenlet::ThreadStateCreator ThreadStateCreator; +static thread_local ThreadStateCreator g_thread_state_global; +#define GET_THREAD_STATE() g_thread_state_global + +#endif //T_THREADSTATE_DESTROY diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/TUserGreenlet.cpp b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/TUserGreenlet.cpp new file mode 100644 index 000000000..a8eeabb3a --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/TUserGreenlet.cpp @@ -0,0 +1,674 @@ +/* -*- indent-tabs-mode: nil; tab-width: 4; -*- */ +/** + * Implementation of greenlet::UserGreenlet. + * + * Format with: + * clang-format -i --style=file src/greenlet/greenlet.c + * + * + * Fix missing braces with: + * clang-tidy src/greenlet/greenlet.c -fix -checks="readability-braces-around-statements" +*/ +#ifndef T_USER_GREENLET_CPP +#define T_USER_GREENLET_CPP + +#include "greenlet_internal.hpp" +#include "TGreenlet.hpp" + +#include "TThreadStateDestroy.cpp" + + +namespace greenlet { +using greenlet::refs::BorrowedMainGreenlet; +greenlet::PythonAllocator UserGreenlet::allocator; + +void* UserGreenlet::operator new(size_t UNUSED(count)) +{ + return allocator.allocate(1); +} + + +void UserGreenlet::operator delete(void* ptr) +{ + return allocator.deallocate(static_cast(ptr), + 1); +} + + +UserGreenlet::UserGreenlet(PyGreenlet* p, BorrowedGreenlet the_parent) + : Greenlet(p), _parent(the_parent) +{ +} + +UserGreenlet::~UserGreenlet() +{ + // Python 3.11: If we don't clear out the raw frame datastack + // when deleting an unfinished greenlet, + // TestLeaks.test_untracked_memory_doesnt_increase_unfinished_thread_dealloc_in_main fails. + this->python_state.did_finish(nullptr); + this->tp_clear(); +} + + +const BorrowedMainGreenlet +UserGreenlet::main_greenlet() const +{ + return this->_main_greenlet; +} + + +BorrowedMainGreenlet +UserGreenlet::find_main_greenlet_in_lineage() const +{ + if (this->started()) { + assert(this->_main_greenlet); + return BorrowedMainGreenlet(this->_main_greenlet); + } + + if (!this->_parent) { + /* garbage collected greenlet in chain */ + // XXX: WHAT? + return BorrowedMainGreenlet(nullptr); + } + + return this->_parent->find_main_greenlet_in_lineage(); +} + + +/** + * CAUTION: This will allocate memory and may trigger garbage + * collection and arbitrary Python code. + */ +OwnedObject +UserGreenlet::throw_GreenletExit_during_dealloc(const ThreadState& current_thread_state) +{ + /* The dying greenlet cannot be a parent of ts_current + because the 'parent' field chain would hold a + reference */ + UserGreenlet::ParentIsCurrentGuard with_current_parent(this, current_thread_state); + + // We don't care about the return value, only whether an + // exception happened. Whether or not an exception happens, + // we need to restore the parent in case the greenlet gets + // resurrected. + return Greenlet::throw_GreenletExit_during_dealloc(current_thread_state); +} + +ThreadState* +UserGreenlet::thread_state() const noexcept +{ + // TODO: maybe make this throw, if the thread state isn't there? + // if (!this->main_greenlet) { + // throw std::runtime_error("No thread state"); // TODO: Better exception + // } + if (!this->_main_greenlet) { + return nullptr; + } + return this->_main_greenlet->thread_state(); +} + + +bool +UserGreenlet::was_running_in_dead_thread() const noexcept +{ + return this->_main_greenlet && !this->thread_state(); +} + +OwnedObject +UserGreenlet::g_switch() +{ + try { + if (!this->args() && !PyErr_Occurred()) { + // we have nothing to send as the result of switching, + // most likely because we've somehow allowed concurrent + // uses of switch from multiple threads (which may or may + // not be allowed by check_switch_allowed) + // ``green_switch`` defends against this by calling + // ``check_switch_allowed`` before messing with + // ``args()``, but we have at least one internal caller + // (``throw_GreenletExit_during_dealloc``) so we keep both + // this explicit check and our call to + // ``check_switch_allowed`` + throw PyErrOccurred(mod_globs->PyExc_GreenletError, + "cannot switch with no pending arguments or exception"); + } + this->check_switch_allowed(); + } + catch (const PyErrOccurred&) { + this->release_args(); + throw; + } + + // Switching greenlets used to attempt to clean out ones that need + // deleted *if* we detected a thread switch. Should it still do + // that? + // An issue is that if we delete a greenlet from another thread, + // it gets queued to this thread, and ``kill_greenlet()`` switches + // back into the greenlet + + /* find the real target by ignoring dead greenlets, + and if necessary starting a greenlet. */ + switchstack_result_t err; + Greenlet* target = this; + // TODO: probably cleaner to handle the case where we do + // switch to ourself separately from the other cases. + // This can probably even further be simplified if we keep + // track of the switching_state we're going for and just call + // into g_switch() if it's not ourself. The main problem with that + // is that we would be using more stack space. + bool target_was_me = true; + bool was_initial_stub = false; + while (target) { + if (target->active()) { + if (!target_was_me) { + target->args() <<= this->args(); + assert(!this->args()); + } + err = target->g_switchstack(); + break; + } + if (!target->started()) { + // We never encounter a main greenlet that's not started. + assert(!target->main()); + UserGreenlet* real_target = static_cast(target); + assert(real_target); + void* dummymarker; + was_initial_stub = true; + if (!target_was_me) { + target->args() <<= this->args(); + assert(!this->args()); + } + try { + // This can only throw back to us while we're + // still in this greenlet. Once the new greenlet + // is bootstrapped, it has its own exception state. + err = real_target->g_initialstub(&dummymarker); + } + catch (const PyErrOccurred&) { + this->release_args(); + throw; + } + catch (const GreenletStartedWhileInPython&) { + // The greenlet was started sometime before this + // greenlet actually switched to it, i.e., + // "concurrent" calls to switch() or throw(). + // We need to retry the switch. + // Note that the current greenlet has been reset + // to this one (or we wouldn't be running!) + continue; + } + break; + } + + target = target->parent(); + target_was_me = false; + } + // The ``this`` pointer and all other stack or register based + // variables are invalid now, at least where things succeed + // above. + // But this one, probably not so much? It's not clear if it's + // safe to throw an exception at this point. + + if (err.status < 0) { + // If we get here, either g_initialstub() + // failed, or g_switchstack() failed. Either one of those + // cases SHOULD leave us in the original greenlet with a valid + // stack. + return this->on_switchstack_or_initialstub_failure(target, err, target_was_me, was_initial_stub); + } + + // err.the_new_current_greenlet would be the same as ``target``, + // if target wasn't probably corrupt. + return err.the_new_current_greenlet->g_switch_finish(err); +} + + + +Greenlet::switchstack_result_t +UserGreenlet::g_initialstub(void* mark) +{ + OwnedObject run; + + // We need to grab a reference to the current switch arguments + // in case we're entered concurrently during the call to + // GetAttr() and have to try again. + // We'll restore them when we return in that case. + // Scope them tightly to avoid ref leaks. + { + SwitchingArgs args(this->args()); + + /* save exception in case getattr clears it */ + PyErrPieces saved; + + /* + self.run is the object to call in the new greenlet. + This could run arbitrary python code and switch greenlets! + */ + run = this->self().PyRequireAttr(mod_globs->str_run); + /* restore saved exception */ + saved.PyErrRestore(); + + + /* recheck that it's safe to switch in case greenlet reparented anywhere above */ + this->check_switch_allowed(); + + /* by the time we got here another start could happen elsewhere, + * that means it should now be a regular switch. + * This can happen if the Python code is a subclass that implements + * __getattribute__ or __getattr__, or makes ``run`` a descriptor; + * all of those can run arbitrary code that switches back into + * this greenlet. + */ + if (this->stack_state.started()) { + // the successful switch cleared these out, we need to + // restore our version. They will be copied on up to the + // next target. + assert(!this->args()); + this->args() <<= args; + throw GreenletStartedWhileInPython(); + } + } + + // Sweet, if we got here, we have the go-ahead and will switch + // greenlets. + // Nothing we do from here on out should allow for a thread or + // greenlet switch: No arbitrary calls to Python, including + // decref'ing + +#if GREENLET_USE_CFRAME + /* OK, we need it, we're about to switch greenlets, save the state. */ + /* + See green_new(). This is a stack-allocated variable used + while *self* is in PyObject_Call(). + We want to defer copying the state info until we're sure + we need it and are in a stable place to do so. + */ + _PyCFrame trace_info; + + this->python_state.set_new_cframe(trace_info); +#endif + /* start the greenlet */ + ThreadState& thread_state = GET_THREAD_STATE().state(); + this->stack_state = StackState(mark, + thread_state.borrow_current()->stack_state); + this->python_state.set_initial_state(PyThreadState_GET()); + this->exception_state.clear(); + this->_main_greenlet = thread_state.get_main_greenlet(); + + /* perform the initial switch */ + switchstack_result_t err = this->g_switchstack(); + /* returns twice! + The 1st time with ``err == 1``: we are in the new greenlet. + This one owns a greenlet that used to be current. + The 2nd time with ``err <= 0``: back in the caller's + greenlet; this happens if the child finishes or switches + explicitly to us. Either way, the ``err`` variable is + created twice at the same memory location, but possibly + having different ``origin`` values. Note that it's not + constructed for the second time until the switch actually happens. + */ + if (err.status == 1) { + // In the new greenlet. + + // This never returns! Calling inner_bootstrap steals + // the contents of our run object within this stack frame, so + // it is not valid to do anything with it. + try { + this->inner_bootstrap(err.origin_greenlet.relinquish_ownership(), + run.relinquish_ownership()); + } + // Getting a C++ exception here isn't good. It's probably a + // bug in the underlying greenlet, meaning it's probably a + // C++ extension. We're going to abort anyway, but try to + // display some nice information *if* possible. Some obscure + // platforms don't properly support this (old 32-bit Arm, see see + // https://github.com/python-greenlet/greenlet/issues/385); that's not + // great, but should usually be OK because, as mentioned above, we're + // terminating anyway. + // + // The catching is tested by + // ``test_cpp.CPPTests.test_unhandled_exception_in_greenlet_aborts``. + // + // PyErrOccurred can theoretically be thrown by + // inner_bootstrap() -> g_switch_finish(), but that should + // never make it back to here. It is a std::exception and + // would be caught if it is. + catch (const std::exception& e) { + std::string base = "greenlet: Unhandled C++ exception: "; + base += e.what(); + Py_FatalError(base.c_str()); + } + catch (...) { + // Some compilers/runtimes use exceptions internally. + // It appears that GCC on Linux with libstdc++ throws an + // exception internally at process shutdown time to unwind + // stacks and clean up resources. Depending on exactly + // where we are when the process exits, that could result + // in an unknown exception getting here. If we + // Py_FatalError() or abort() here, we interfere with + // orderly process shutdown. Throwing the exception on up + // is the right thing to do. + // + // gevent's ``examples/dns_mass_resolve.py`` demonstrates this. +#ifndef NDEBUG + fprintf(stderr, + "greenlet: inner_bootstrap threw unknown exception; " + "is the process terminating?\n"); +#endif + throw; + } + Py_FatalError("greenlet: inner_bootstrap returned with no exception.\n"); + } + + + // In contrast, notice that we're keeping the origin greenlet + // around as an owned reference; we need it to call the trace + // function for the switch back into the parent. It was only + // captured at the time the switch actually happened, though, + // so we haven't been keeping an extra reference around this + // whole time. + + /* back in the parent */ + if (err.status < 0) { + /* start failed badly, restore greenlet state */ + this->stack_state = StackState(); + this->_main_greenlet.CLEAR(); + // CAUTION: This may run arbitrary Python code. + run.CLEAR(); // inner_bootstrap didn't run, we own the reference. + } + + // In the success case, the spawned code (inner_bootstrap) will + // take care of decrefing this, so we relinquish ownership so as + // to not double-decref. + + run.relinquish_ownership(); + + return err; +} + + +void +UserGreenlet::inner_bootstrap(PyGreenlet* origin_greenlet, PyObject* run) +{ + // The arguments here would be another great place for move. + // As it is, we take them as a reference so that when we clear + // them we clear what's on the stack above us. Do that NOW, and + // without using a C++ RAII object, + // so there's no way that exiting the parent frame can clear it, + // or we clear it unexpectedly. This arises in the context of the + // interpreter shutting down. See https://github.com/python-greenlet/greenlet/issues/325 + //PyObject* run = _run.relinquish_ownership(); + + /* in the new greenlet */ + assert(this->thread_state()->borrow_current() == BorrowedGreenlet(this->_self)); + // C++ exceptions cannot propagate to the parent greenlet from + // here. (TODO: Do we need a catch(...) clause, perhaps on the + // function itself? ALl we could do is terminate the program.) + // NOTE: On 32-bit Windows, the call chain is extremely + // important here in ways that are subtle, having to do with + // the depth of the SEH list. The call to restore it MUST NOT + // add a new SEH handler to the list, or we'll restore it to + // the wrong thing. + this->thread_state()->restore_exception_state(); + /* stack variables from above are no good and also will not unwind! */ + // EXCEPT: That can't be true, we access run, among others, here. + + this->stack_state.set_active(); /* running */ + + // We're about to possibly run Python code again, which + // could switch back/away to/from us, so we need to grab the + // arguments locally. + SwitchingArgs args; + args <<= this->args(); + assert(!this->args()); + + // XXX: We could clear this much earlier, right? + // Or would that introduce the possibility of running Python + // code when we don't want to? + // CAUTION: This may run arbitrary Python code. + this->_run_callable.CLEAR(); + + + // The first switch we need to manually call the trace + // function here instead of in g_switch_finish, because we + // never return there. + if (OwnedObject tracefunc = this->thread_state()->get_tracefunc()) { + OwnedGreenlet trace_origin; + trace_origin = origin_greenlet; + try { + g_calltrace(tracefunc, + args ? mod_globs->event_switch : mod_globs->event_throw, + trace_origin, + this->_self); + } + catch (const PyErrOccurred&) { + /* Turn trace errors into switch throws */ + args.CLEAR(); + } + } + + // We no longer need the origin, it was only here for + // tracing. + // We may never actually exit this stack frame so we need + // to explicitly clear it. + // This could run Python code and switch. + Py_CLEAR(origin_greenlet); + + OwnedObject result; + if (!args) { + /* pending exception */ + result = NULL; + } + else { + /* call g.run(*args, **kwargs) */ + // This could result in further switches + try { + //result = run.PyCall(args.args(), args.kwargs()); + // CAUTION: Just invoking this, before the function even + // runs, may cause memory allocations, which may trigger + // GC, which may run arbitrary Python code. + result = OwnedObject::consuming(PyObject_Call(run, args.args().borrow(), args.kwargs().borrow())); + } + catch (...) { + // Unhandled C++ exception! + + // If we declare ourselves as noexcept, if we don't catch + // this here, most platforms will just abort() the + // process. But on 64-bit Windows with older versions of + // the C runtime, this can actually corrupt memory and + // just return. We see this when compiling with the + // Windows 7.0 SDK targeting Windows Server 2008, but not + // when using the Appveyor Visual Studio 2019 image. So + // this currently only affects Python 2.7 on Windows 64. + // That is, the tests pass and the runtime aborts + // everywhere else. + // + // However, if we catch it and try to continue with a + // Python error, then all Windows 64 bit platforms corrupt + // memory. So all we can do is manually abort, hopefully + // with a good error message. (Note that the above was + // tested WITHOUT the `/EHr` switch being used at compile + // time, so MSVC may have "optimized" out important + // checking. Using that switch, we may be in a better + // place in terms of memory corruption.) But sometimes it + // can't be caught here at all, which is confusing but not + // terribly surprising; so again, the G_NOEXCEPT_WIN32 + // plus "/EHr". + // + // Hopefully the basic C stdlib is still functional enough + // for us to at least print an error. + // + // It gets more complicated than that, though, on some + // platforms, specifically at least Linux/gcc/libstdc++. They use + // an exception to unwind the stack when a background + // thread exits. (See comments about noexcept.) So this + // may not actually represent anything untoward. On those + // platforms we allow throws of this to propagate, or + // attempt to anyway. +# if defined(WIN32) || defined(_WIN32) + Py_FatalError( + "greenlet: Unhandled C++ exception from a greenlet run function. " + "Because memory is likely corrupted, terminating process."); + std::abort(); +#else + throw; +#endif + } + } + // These lines may run arbitrary code + args.CLEAR(); + Py_CLEAR(run); + + if (!result + && mod_globs->PyExc_GreenletExit.PyExceptionMatches() + && (this->args())) { + // This can happen, for example, if our only reference + // goes away after we switch back to the parent. + // See test_dealloc_switch_args_not_lost + PyErrPieces clear_error; + result <<= this->args(); + result = single_result(result); + } + this->release_args(); + this->python_state.did_finish(PyThreadState_GET()); + + result = g_handle_exit(result); + assert(this->thread_state()->borrow_current() == this->_self); + + /* jump back to parent */ + this->stack_state.set_inactive(); /* dead */ + + + // TODO: Can we decref some things here? Release our main greenlet + // and maybe parent? + for (Greenlet* parent = this->_parent; + parent; + parent = parent->parent()) { + // We need to somewhere consume a reference to + // the result; in most cases we'll never have control + // back in this stack frame again. Calling + // green_switch actually adds another reference! + // This would probably be clearer with a specific API + // to hand results to the parent. + parent->args() <<= result; + assert(!result); + // The parent greenlet now owns the result; in the + // typical case we'll never get back here to assign to + // result and thus release the reference. + try { + result = parent->g_switch(); + } + catch (const PyErrOccurred&) { + // Ignore, keep passing the error on up. + } + + /* Return here means switch to parent failed, + * in which case we throw *current* exception + * to the next parent in chain. + */ + assert(!result); + } + /* We ran out of parents, cannot continue */ + PyErr_WriteUnraisable(this->self().borrow_o()); + Py_FatalError("greenlet: ran out of parent greenlets while propagating exception; " + "cannot continue"); + std::abort(); +} + +void +UserGreenlet::run(const BorrowedObject nrun) +{ + if (this->started()) { + throw AttributeError( + "run cannot be set " + "after the start of the greenlet"); + } + this->_run_callable = nrun; +} + +const OwnedGreenlet +UserGreenlet::parent() const +{ + return this->_parent; +} + +void +UserGreenlet::parent(const BorrowedObject raw_new_parent) +{ + if (!raw_new_parent) { + throw AttributeError("can't delete attribute"); + } + + BorrowedMainGreenlet main_greenlet_of_new_parent; + BorrowedGreenlet new_parent(raw_new_parent.borrow()); // could + // throw + // TypeError! + for (BorrowedGreenlet p = new_parent; p; p = p->parent()) { + if (p == this->self()) { + throw ValueError("cyclic parent chain"); + } + main_greenlet_of_new_parent = p->main_greenlet(); + } + + if (!main_greenlet_of_new_parent) { + throw ValueError("parent must not be garbage collected"); + } + + if (this->started() + && this->_main_greenlet != main_greenlet_of_new_parent) { + throw ValueError("parent cannot be on a different thread"); + } + + this->_parent = new_parent; +} + +void +UserGreenlet::murder_in_place() +{ + this->_main_greenlet.CLEAR(); + Greenlet::murder_in_place(); +} + +bool +UserGreenlet::belongs_to_thread(const ThreadState* thread_state) const +{ + return Greenlet::belongs_to_thread(thread_state) && this->_main_greenlet == thread_state->borrow_main_greenlet(); +} + + +int +UserGreenlet::tp_traverse(visitproc visit, void* arg) +{ + Py_VISIT(this->_parent.borrow_o()); + Py_VISIT(this->_main_greenlet.borrow_o()); + Py_VISIT(this->_run_callable.borrow_o()); + + return Greenlet::tp_traverse(visit, arg); +} + +int +UserGreenlet::tp_clear() +{ + Greenlet::tp_clear(); + this->_parent.CLEAR(); + this->_main_greenlet.CLEAR(); + this->_run_callable.CLEAR(); + return 0; +} + +UserGreenlet::ParentIsCurrentGuard::ParentIsCurrentGuard(UserGreenlet* p, + const ThreadState& thread_state) + : oldparent(p->_parent), + greenlet(p) +{ + p->_parent = thread_state.get_current(); +} + +UserGreenlet::ParentIsCurrentGuard::~ParentIsCurrentGuard() +{ + this->greenlet->_parent = oldparent; + oldparent.CLEAR(); +} + +}; //namespace greenlet +#endif diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/__init__.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/__init__.py new file mode 100644 index 000000000..e80849e37 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/__init__.py @@ -0,0 +1,62 @@ +# -*- coding: utf-8 -*- +""" +The root of the greenlet package. +""" + +__all__ = [ + '__version__', + '_C_API', + + 'GreenletExit', + 'error', + + 'getcurrent', + 'greenlet', + + 'gettrace', + 'settrace', +] + +# pylint:disable=no-name-in-module + +### +# Metadata +### +__version__ = '3.4.0' +from ._greenlet import _C_API # pylint:disable=no-name-in-module + +### +# Exceptions +### +from ._greenlet import GreenletExit +from ._greenlet import error + +### +# greenlets +### +from ._greenlet import getcurrent +from ._greenlet import greenlet + +### +# tracing +### +from ._greenlet import gettrace +from ._greenlet import settrace + +### +# Constants +# These constants aren't documented and aren't recommended. +# In 1.0, USE_GC and USE_TRACING are always true, and USE_CONTEXT_VARS +# is the same as ``sys.version_info[:2] >= 3.7`` +### +from ._greenlet import GREENLET_USE_CONTEXT_VARS # pylint:disable=unused-import +from ._greenlet import GREENLET_USE_GC # pylint:disable=unused-import +from ._greenlet import GREENLET_USE_TRACING # pylint:disable=unused-import + +# Controlling the use of the gc module. Provisional API for this greenlet +# implementation in 2.0. +from ._greenlet import CLOCKS_PER_SEC # pylint:disable=unused-import +from ._greenlet import enable_optional_cleanup # pylint:disable=unused-import +from ._greenlet import get_clocks_used_doing_optional_cleanup # pylint:disable=unused-import + +# Other APIS in the _greenlet module are for test support. diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/_greenlet.cpython-312-x86_64-linux-gnu.so b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/_greenlet.cpython-312-x86_64-linux-gnu.so new file mode 100755 index 000000000..d897bb205 Binary files /dev/null and b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/_greenlet.cpython-312-x86_64-linux-gnu.so differ diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/greenlet.cpp b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/greenlet.cpp new file mode 100644 index 000000000..b9d9236e8 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/greenlet.cpp @@ -0,0 +1,343 @@ +/* -*- indent-tabs-mode: nil; tab-width: 4; -*- */ +/* Format with: + * clang-format -i --style=file src/greenlet/greenlet.c + * + * + * Fix missing braces with: + * clang-tidy src/greenlet/greenlet.c -fix -checks="readability-braces-around-statements" +*/ +#include +#include +#include +#include + + +#define PY_SSIZE_T_CLEAN +#include +#include "structmember.h" // PyMemberDef + +#include "greenlet_internal.hpp" +// Code after this point can assume access to things declared in stdint.h, +// including the fixed-width types. This goes for the platform-specific switch functions +// as well. +#include "greenlet_refs.hpp" +#include "greenlet_slp_switch.hpp" + +#include "greenlet_thread_support.hpp" +#include "TGreenlet.hpp" + +#include "TGreenletGlobals.cpp" + +#include "TGreenlet.cpp" +#include "TMainGreenlet.cpp" +#include "TUserGreenlet.cpp" +#include "TBrokenGreenlet.cpp" +#include "TExceptionState.cpp" +#include "TPythonState.cpp" +#include "TStackState.cpp" + +#include "TThreadState.hpp" +#include "TThreadStateCreator.hpp" +#include "TThreadStateDestroy.cpp" + +#include "PyGreenlet.cpp" +#include "PyGreenletUnswitchable.cpp" +#include "CObjects.cpp" + +using greenlet::LockGuard; +using greenlet::LockInitError; +using greenlet::PyErrOccurred; +using greenlet::Require; + +using greenlet::g_handle_exit; +using greenlet::single_result; + +using greenlet::Greenlet; +using greenlet::UserGreenlet; +using greenlet::MainGreenlet; +using greenlet::BrokenGreenlet; +using greenlet::ThreadState; +using greenlet::PythonState; + + + +// ******* Implementation of things from included files +template +greenlet::refs::_BorrowedGreenlet& greenlet::refs::_BorrowedGreenlet::operator=(const greenlet::refs::BorrowedObject& other) +{ + this->_set_raw_pointer(static_cast(other)); + return *this; +} + +template +inline greenlet::refs::_BorrowedGreenlet::operator Greenlet*() const noexcept +{ + if (!this->p) { + return nullptr; + } + return reinterpret_cast(this->p)->pimpl; +} + +template +greenlet::refs::_BorrowedGreenlet::_BorrowedGreenlet(const BorrowedObject& p) + : BorrowedReference(nullptr) +{ + + this->_set_raw_pointer(p.borrow()); +} + +template +inline greenlet::refs::_OwnedGreenlet::operator Greenlet*() const noexcept +{ + if (!this->p) { + return nullptr; + } + return reinterpret_cast(this->p)->pimpl; +} + + + +#ifdef __clang__ +# pragma clang diagnostic push +# pragma clang diagnostic ignored "-Wmissing-field-initializers" +# pragma clang diagnostic ignored "-Wwritable-strings" +#elif defined(__GNUC__) +# pragma GCC diagnostic push +// warning: ISO C++ forbids converting a string constant to ‘char*’ +// (The python APIs aren't const correct and accept writable char*) +# pragma GCC diagnostic ignored "-Wwrite-strings" +#endif + + +/*********************************************************** + +A PyGreenlet is a range of C stack addresses that must be +saved and restored in such a way that the full range of the +stack contains valid data when we switch to it. + +Stack layout for a greenlet: + + | ^^^ | + | older data | + | | + stack_stop . |_______________| + . | | + . | greenlet data | + . | in stack | + . * |_______________| . . _____________ stack_copy + stack_saved + . | | | | + . | data | |greenlet data| + . | unrelated | | saved | + . | to | | in heap | + stack_start . | this | . . |_____________| stack_copy + | greenlet | + | | + | newer data | + | vvv | + + +Note that a greenlet's stack data is typically partly at its correct +place in the stack, and partly saved away in the heap, but always in +the above configuration: two blocks, the more recent one in the heap +and the older one still in the stack (either block may be empty). + +Greenlets are chained: each points to the previous greenlet, which is +the one that owns the data currently in the C stack above my +stack_stop. The currently running greenlet is the first element of +this chain. The main (initial) greenlet is the last one. Greenlets +whose stack is entirely in the heap can be skipped from the chain. + +The chain is not related to execution order, but only to the order +in which bits of C stack happen to belong to greenlets at a particular +point in time. + +The main greenlet doesn't have a stack_stop: it is responsible for the +complete rest of the C stack, and we don't know where it begins. We +use (char*) -1, the largest possible address. + +States: + stack_stop == NULL && stack_start == NULL: did not start yet + stack_stop != NULL && stack_start == NULL: already finished + stack_stop != NULL && stack_start != NULL: active + +The running greenlet's stack_start is undefined but not NULL. + + ***********************************************************/ + + + + +/***********************************************************/ + +/* Some functions must not be inlined: + * slp_restore_state, when inlined into slp_switch might cause + it to restore stack over its own local variables + * slp_save_state, when inlined would add its own local + variables to the saved stack, wasting space + * slp_switch, cannot be inlined for obvious reasons + * g_initialstub, when inlined would receive a pointer into its + own stack frame, leading to incomplete stack save/restore + +g_initialstub is a member function and declared virtual so that the +compiler always calls it through a vtable. + +slp_save_state and slp_restore_state are also member functions. They +are called from trampoline functions that themselves are declared as +not eligible for inlining. +*/ + +extern "C" { +static int GREENLET_NOINLINE(slp_save_state_trampoline)(char* stackref) +{ + return switching_thread_state->slp_save_state(stackref); +} +static void GREENLET_NOINLINE(slp_restore_state_trampoline)() +{ + switching_thread_state->slp_restore_state(); +} +} + + +/***********************************************************/ + + +#include "PyModule.cpp" + + + +static PyObject* +greenlet_internal_mod_init() noexcept +{ + static void* _PyGreenlet_API[PyGreenlet_API_pointers]; + + try { + CreatedModule m(greenlet_module_def); + + Require(PyType_Ready(&PyGreenlet_Type)); + Require(PyType_Ready(&PyGreenletUnswitchable_Type)); + + mod_globs = new greenlet::GreenletGlobals; + ThreadState::init(); + + m.PyAddObject("greenlet", PyGreenlet_Type); + m.PyAddObject("UnswitchableGreenlet", PyGreenletUnswitchable_Type); + m.PyAddObject("error", mod_globs->PyExc_GreenletError); + m.PyAddObject("GreenletExit", mod_globs->PyExc_GreenletExit); + + m.PyAddObject("GREENLET_USE_GC", 1); + m.PyAddObject("GREENLET_USE_TRACING", 1); + m.PyAddObject("GREENLET_USE_CONTEXT_VARS", 1L); + m.PyAddObject("GREENLET_USE_STANDARD_THREADING", 1L); + + NewReference clocks_per_sec(Require(PyLong_FromSsize_t(CLOCKS_PER_SEC))); + m.PyAddObject("CLOCKS_PER_SEC", clocks_per_sec); + + /* also publish module-level data as attributes of the greentype. */ + // XXX: This is weird, and enables a strange pattern of + // confusing the class greenlet with the module greenlet; with + // the exception of (possibly) ``getcurrent()``, this + // shouldn't be encouraged so don't add new items here. + for (const char* const* p = copy_on_greentype; *p; p++) { + OwnedObject o = m.PyRequireAttr(*p); + Require(PyDict_SetItemString(PyGreenlet_Type.tp_dict, *p, o.borrow())); + } + + /* + * Expose C API + */ + + /* types */ + _PyGreenlet_API[PyGreenlet_Type_NUM] = (void*)&PyGreenlet_Type; + + /* exceptions */ + _PyGreenlet_API[PyExc_GreenletError_NUM] = (void*)mod_globs->PyExc_GreenletError; + _PyGreenlet_API[PyExc_GreenletExit_NUM] = (void*)mod_globs->PyExc_GreenletExit; + + /* methods */ + _PyGreenlet_API[PyGreenlet_New_NUM] = (void*)PyGreenlet_New; + _PyGreenlet_API[PyGreenlet_GetCurrent_NUM] = (void*)PyGreenlet_GetCurrent; + _PyGreenlet_API[PyGreenlet_Throw_NUM] = (void*)PyGreenlet_Throw; + _PyGreenlet_API[PyGreenlet_Switch_NUM] = (void*)PyGreenlet_Switch; + _PyGreenlet_API[PyGreenlet_SetParent_NUM] = (void*)PyGreenlet_SetParent; + + /* Previously macros, but now need to be functions externally. */ + _PyGreenlet_API[PyGreenlet_MAIN_NUM] = (void*)Extern_PyGreenlet_MAIN; + _PyGreenlet_API[PyGreenlet_STARTED_NUM] = (void*)Extern_PyGreenlet_STARTED; + _PyGreenlet_API[PyGreenlet_ACTIVE_NUM] = (void*)Extern_PyGreenlet_ACTIVE; + _PyGreenlet_API[PyGreenlet_GET_PARENT_NUM] = (void*)Extern_PyGreenlet_GET_PARENT; + + /* XXX: Note that our module name is ``greenlet._greenlet``, but for + backwards compatibility with existing C code, we need the _C_API to + be directly in greenlet. + */ + const NewReference c_api_object(Require( + PyCapsule_New( + (void*)_PyGreenlet_API, + "greenlet._C_API", + NULL))); + m.PyAddObject("_C_API", c_api_object); + assert(c_api_object.REFCNT() == 2); + + // cerr << "Sizes:" + // << "\n\tGreenlet : " << sizeof(Greenlet) + // << "\n\tUserGreenlet : " << sizeof(UserGreenlet) + // << "\n\tMainGreenlet : " << sizeof(MainGreenlet) + // << "\n\tExceptionState : " << sizeof(greenlet::ExceptionState) + // << "\n\tPythonState : " << sizeof(greenlet::PythonState) + // << "\n\tStackState : " << sizeof(greenlet::StackState) + // << "\n\tSwitchingArgs : " << sizeof(greenlet::SwitchingArgs) + // << "\n\tOwnedObject : " << sizeof(greenlet::refs::OwnedObject) + // << "\n\tBorrowedObject : " << sizeof(greenlet::refs::BorrowedObject) + // << "\n\tPyGreenlet : " << sizeof(PyGreenlet) + // << endl; + +#ifdef Py_GIL_DISABLED + PyUnstable_Module_SetGIL(m.borrow(), Py_MOD_GIL_NOT_USED); +#endif + + // Register an atexit handler that sets + // g_greenlet_shutting_down. Python's atexit is LIFO: + // registered last = called first. By registering here (at + // import time, after most other libraries), our handler runs + // before their cleanup code, which may try to call + // greenlet.getcurrent() on objects whose type has been + // invalidated. _Py_IsFinalizing() alone is insufficient on + // ALL Python versions because it is only set AFTER atexit + // handlers complete inside Py_FinalizeEx. + { + NewReference atexit_mod(Require(PyImport_ImportModule("atexit"))); + OwnedObject register_fn = atexit_mod.PyRequireAttr("register"); + NewReference callback(Require( + PyCFunction_New(&_greenlet_atexit_method, NULL))); + NewReference args(Require(PyTuple_Pack(1, callback.borrow()))); + NewReference result(Require( + PyObject_Call(register_fn.borrow(), args.borrow(), NULL))); + } + + return m.borrow(); // But really it's the main reference. + } + catch (const LockInitError& e) { + PyErr_SetString(PyExc_MemoryError, e.what()); + return NULL; + } + catch (const PyErrOccurred&) { + return NULL; + } + +} + +extern "C" { + +PyMODINIT_FUNC +PyInit__greenlet(void) +{ + return greenlet_internal_mod_init(); +} + +}; // extern C + +#ifdef __clang__ +# pragma clang diagnostic pop +#elif defined(__GNUC__) +# pragma GCC diagnostic pop +#endif diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/greenlet.h b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/greenlet.h new file mode 100644 index 000000000..d02a16e43 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/greenlet.h @@ -0,0 +1,164 @@ +/* -*- indent-tabs-mode: nil; tab-width: 4; -*- */ + +/* Greenlet object interface */ + +#ifndef Py_GREENLETOBJECT_H +#define Py_GREENLETOBJECT_H + + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/* This is deprecated and undocumented. It does not change. */ +#define GREENLET_VERSION "1.0.0" + +#ifndef GREENLET_MODULE +#define implementation_ptr_t void* +#endif + +typedef struct _greenlet { + PyObject_HEAD + PyObject* weakreflist; + PyObject* dict; + implementation_ptr_t pimpl; +} PyGreenlet; + +#define PyGreenlet_Check(op) (op && PyObject_TypeCheck(op, &PyGreenlet_Type)) + + +/* C API functions */ + +/* Total number of symbols that are exported */ +#define PyGreenlet_API_pointers 12 + +#define PyGreenlet_Type_NUM 0 +#define PyExc_GreenletError_NUM 1 +#define PyExc_GreenletExit_NUM 2 + +#define PyGreenlet_New_NUM 3 +#define PyGreenlet_GetCurrent_NUM 4 +#define PyGreenlet_Throw_NUM 5 +#define PyGreenlet_Switch_NUM 6 +#define PyGreenlet_SetParent_NUM 7 + +#define PyGreenlet_MAIN_NUM 8 +#define PyGreenlet_STARTED_NUM 9 +#define PyGreenlet_ACTIVE_NUM 10 +#define PyGreenlet_GET_PARENT_NUM 11 + +#ifndef GREENLET_MODULE +/* This section is used by modules that uses the greenlet C API */ +static void** _PyGreenlet_API = NULL; + +# define PyGreenlet_Type \ + (*(PyTypeObject*)_PyGreenlet_API[PyGreenlet_Type_NUM]) + +# define PyExc_GreenletError \ + ((PyObject*)_PyGreenlet_API[PyExc_GreenletError_NUM]) + +# define PyExc_GreenletExit \ + ((PyObject*)_PyGreenlet_API[PyExc_GreenletExit_NUM]) + +/* + * PyGreenlet_New(PyObject *args) + * + * greenlet.greenlet(run, parent=None) + */ +# define PyGreenlet_New \ + (*(PyGreenlet * (*)(PyObject * run, PyGreenlet * parent)) \ + _PyGreenlet_API[PyGreenlet_New_NUM]) + +/* + * PyGreenlet_GetCurrent(void) + * + * greenlet.getcurrent() + */ +# define PyGreenlet_GetCurrent \ + (*(PyGreenlet * (*)(void)) _PyGreenlet_API[PyGreenlet_GetCurrent_NUM]) + +/* + * PyGreenlet_Throw( + * PyGreenlet *greenlet, + * PyObject *typ, + * PyObject *val, + * PyObject *tb) + * + * g.throw(...) + */ +# define PyGreenlet_Throw \ + (*(PyObject * (*)(PyGreenlet * self, \ + PyObject * typ, \ + PyObject * val, \ + PyObject * tb)) \ + _PyGreenlet_API[PyGreenlet_Throw_NUM]) + +/* + * PyGreenlet_Switch(PyGreenlet *greenlet, PyObject *args) + * + * g.switch(*args, **kwargs) + */ +# define PyGreenlet_Switch \ + (*(PyObject * \ + (*)(PyGreenlet * greenlet, PyObject * args, PyObject * kwargs)) \ + _PyGreenlet_API[PyGreenlet_Switch_NUM]) + +/* + * PyGreenlet_SetParent(PyObject *greenlet, PyObject *new_parent) + * + * g.parent = new_parent + */ +# define PyGreenlet_SetParent \ + (*(int (*)(PyGreenlet * greenlet, PyGreenlet * nparent)) \ + _PyGreenlet_API[PyGreenlet_SetParent_NUM]) + +/* + * PyGreenlet_GetParent(PyObject* greenlet) + * + * return greenlet.parent; + * + * This could return NULL even if there is no exception active. + * If it does not return NULL, you are responsible for decrementing the + * reference count. + */ +# define PyGreenlet_GetParent \ + (*(PyGreenlet* (*)(PyGreenlet*)) \ + _PyGreenlet_API[PyGreenlet_GET_PARENT_NUM]) + +/* + * deprecated, undocumented alias. + */ +# define PyGreenlet_GET_PARENT PyGreenlet_GetParent + +# define PyGreenlet_MAIN \ + (*(int (*)(PyGreenlet*)) \ + _PyGreenlet_API[PyGreenlet_MAIN_NUM]) + +# define PyGreenlet_STARTED \ + (*(int (*)(PyGreenlet*)) \ + _PyGreenlet_API[PyGreenlet_STARTED_NUM]) + +# define PyGreenlet_ACTIVE \ + (*(int (*)(PyGreenlet*)) \ + _PyGreenlet_API[PyGreenlet_ACTIVE_NUM]) + + + + +/* Macro that imports greenlet and initializes C API */ +/* NOTE: This has actually moved to ``greenlet._greenlet._C_API``, but we + keep the older definition to be sure older code that might have a copy of + the header still works. */ +# define PyGreenlet_Import() \ + { \ + _PyGreenlet_API = (void**)PyCapsule_Import("greenlet._C_API", 0); \ + } + +#endif /* GREENLET_MODULE */ + +#ifdef __cplusplus +} +#endif +#endif /* !Py_GREENLETOBJECT_H */ diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/greenlet_allocator.hpp b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/greenlet_allocator.hpp new file mode 100644 index 000000000..1cd9223ad --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/greenlet_allocator.hpp @@ -0,0 +1,76 @@ +#ifndef GREENLET_ALLOCATOR_HPP +#define GREENLET_ALLOCATOR_HPP + +#define PY_SSIZE_T_CLEAN +#include +#include +#include "greenlet_compiler_compat.hpp" +#include "greenlet_cpython_compat.hpp" + + +namespace greenlet +{ + // This allocator is stateless; all instances are identical. + // It can *ONLY* be used when we're sure we're holding the GIL + // (Python's allocators require the GIL). + template + struct PythonAllocator : public std::allocator { + + PythonAllocator(const PythonAllocator& UNUSED(other)) + : std::allocator() + { + } + + PythonAllocator(const std::allocator other) + : std::allocator(other) + {} + + template + PythonAllocator(const std::allocator& other) + : std::allocator(other) + { + } + + PythonAllocator() : std::allocator() {} + + T* allocate(size_t number_objects, const void* UNUSED(hint)=0) + { + void* p; + if (number_objects == 1) { +#ifdef Py_GIL_DISABLED + p = PyMem_Malloc(sizeof(T) * number_objects); +#else + p = PyObject_Malloc(sizeof(T)); +#endif + } + else { + p = PyMem_Malloc(sizeof(T) * number_objects); + } + return static_cast(p); + } + + void deallocate(T* t, size_t n) + { + void* p = t; + if (n == 1) { +#ifdef Py_GIL_DISABLED + PyMem_Free(p); +#else + PyObject_Free(p); +#endif + } + else { + PyMem_Free(p); + } + } + // This member is deprecated in C++17 and removed in C++20 + template< class U > + struct rebind { + typedef PythonAllocator other; + }; + + }; + +} + +#endif diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/greenlet_compiler_compat.hpp b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/greenlet_compiler_compat.hpp new file mode 100644 index 000000000..af24bd83e --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/greenlet_compiler_compat.hpp @@ -0,0 +1,98 @@ +/* -*- indent-tabs-mode: nil; tab-width: 4; -*- */ +#ifndef GREENLET_COMPILER_COMPAT_HPP +#define GREENLET_COMPILER_COMPAT_HPP + +/** + * Definitions to aid with compatibility with different compilers. + * + * .. caution:: Use extreme care with noexcept. + * Some compilers and runtimes, specifically gcc/libgcc/libstdc++ on + * Linux, implement stack unwinding by throwing an uncatchable + * exception, one that specifically does not appear to be an active + * exception to the rest of the runtime. If this happens while we're in a noexcept function, + * we have violated our dynamic exception contract, and so the runtime + * will call std::terminate(), which kills the process with the + * unhelpful message "terminate called without an active exception". + * + * This has happened in this scenario: A background thread is running + * a greenlet that has made a native call and released the GIL. + * Meanwhile, the main thread finishes and starts shutting down the + * interpreter. When the background thread is scheduled again and + * attempts to obtain the GIL, it notices that the interpreter is + * exiting and calls ``pthread_exit()``. This in turn starts to unwind + * the stack by throwing that exception. But we had the ``PyCall`` + * functions annotated as noexcept, so the runtime terminated us. + * + * #2 0x00007fab26fec2b7 in std::terminate() () from /lib/x86_64-linux-gnu/libstdc++.so.6 + * #3 0x00007fab26febb3c in __gxx_personality_v0 () from /lib/x86_64-linux-gnu/libstdc++.so.6 + * #4 0x00007fab26f34de6 in ?? () from /lib/x86_64-linux-gnu/libgcc_s.so.1 + * #6 0x00007fab276a34c6 in __GI___pthread_unwind at ./nptl/unwind.c:130 + * #7 0x00007fab2769bd3a in __do_cancel () at ../sysdeps/nptl/pthreadP.h:280 + * #8 __GI___pthread_exit (value=value@entry=0x0) at ./nptl/pthread_exit.c:36 + * #9 0x000000000052e567 in PyThread_exit_thread () at ../Python/thread_pthread.h:370 + * #10 0x00000000004d60b5 in take_gil at ../Python/ceval_gil.h:224 + * #11 0x00000000004d65f9 in PyEval_RestoreThread at ../Python/ceval.c:467 + * #12 0x000000000060cce3 in setipaddr at ../Modules/socketmodule.c:1203 + * #13 0x00000000006101cd in socket_gethostbyname + */ + +#include + +# define G_NO_COPIES_OF_CLS(Cls) private: \ + Cls(const Cls& other) = delete; \ + Cls& operator=(const Cls& other) = delete + +# define G_NO_ASSIGNMENT_OF_CLS(Cls) private: \ + Cls& operator=(const Cls& other) = delete + +# define G_NO_COPY_CONSTRUCTOR_OF_CLS(Cls) private: \ + Cls(const Cls& other) = delete; + + +// CAUTION: MSVC is stupidly picky: +// +// "The compiler ignores, without warning, any __declspec keywords +// placed after * or & and in front of the variable identifier in a +// declaration." +// (https://docs.microsoft.com/en-us/cpp/cpp/declspec?view=msvc-160) +// +// So pointer return types must be handled differently (because of the +// trailing *), or you get inscrutable compiler warnings like "error +// C2059: syntax error: ''" +// +// In C++ 11, there is a standard syntax for attributes, and +// GCC defines an attribute to use with this: [[gnu:noinline]]. +// In the future, this is expected to become standard. + +#if defined(__GNUC__) || defined(__clang__) +/* We used to check for GCC 4+ or 3.4+, but those compilers are + laughably out of date. Just assume they support it. */ +# define GREENLET_NOINLINE(name) __attribute__((noinline)) name +# define GREENLET_NOINLINE_P(rtype, name) rtype __attribute__((noinline)) name +# define UNUSED(x) UNUSED_ ## x __attribute__((__unused__)) +#elif defined(_MSC_VER) +/* We used to check for && (_MSC_VER >= 1300) but that's also out of date. */ +# define GREENLET_NOINLINE(name) __declspec(noinline) name +# define GREENLET_NOINLINE_P(rtype, name) __declspec(noinline) rtype name +# define UNUSED(x) UNUSED_ ## x +#endif + +#if defined(_MSC_VER) +# define G_NOEXCEPT_WIN32 noexcept +#else +# define G_NOEXCEPT_WIN32 +#endif + +#if defined(__GNUC__) && defined(__POWERPC__) && defined(__APPLE__) +// 32-bit PPC/MacOSX. Only known to be tested on unreleased versions +// of macOS 10.6 using a macports build gcc 14. It appears that +// running C++ destructors of thread-local variables is broken. + +// See https://github.com/python-greenlet/greenlet/pull/419 +# define GREENLET_BROKEN_THREAD_LOCAL_CLEANUP_JUST_LEAK 1 +#else +# define GREENLET_BROKEN_THREAD_LOCAL_CLEANUP_JUST_LEAK 0 +#endif + + +#endif diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/greenlet_cpython_compat.hpp b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/greenlet_cpython_compat.hpp new file mode 100644 index 000000000..e76f3420c --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/greenlet_cpython_compat.hpp @@ -0,0 +1,117 @@ +/* -*- indent-tabs-mode: nil; tab-width: 4; -*- */ +#ifndef GREENLET_CPYTHON_COMPAT_H +#define GREENLET_CPYTHON_COMPAT_H + +/** + * Helpers for compatibility with multiple versions of CPython. + */ + +#define PY_SSIZE_T_CLEAN +#include "Python.h" + +/* +Python 3.10 beta 1 changed tstate->use_tracing to a nested cframe member. +See https://github.com/python/cpython/pull/25276 +We have to save and restore this as well. + +Python 3.13 removed PyThreadState.cframe (GH-108035). +*/ +#if PY_VERSION_HEX < 0x30D0000 +# define GREENLET_USE_CFRAME 1 +#else +# define GREENLET_USE_CFRAME 0 +#endif + + +#if PY_VERSION_HEX >= 0x30B00A4 +/* +Greenlet won't compile on anything older than Python 3.11 alpha 4 (see +https://bugs.python.org/issue46090). Summary of breaking internal changes: +- Python 3.11 alpha 1 changed how frame objects are represented internally. + - https://github.com/python/cpython/pull/30122 +- Python 3.11 alpha 3 changed how recursion limits are stored. + - https://github.com/python/cpython/pull/29524 +- Python 3.11 alpha 4 changed how exception state is stored. It also includes a + change to help greenlet save and restore the interpreter frame "data stack". + - https://github.com/python/cpython/pull/30122 + - https://github.com/python/cpython/pull/30234 +*/ +# define GREENLET_PY311 1 +#else +# define GREENLET_PY311 0 +#endif + + +#if PY_VERSION_HEX >= 0x30C0000 +# define GREENLET_PY312 1 +#else +# define GREENLET_PY312 0 +#endif + +#if PY_VERSION_HEX >= 0x30D0000 +# define GREENLET_PY313 1 +#else +# define GREENLET_PY313 0 +#endif + +#if PY_VERSION_HEX >= 0x30E0000 +# define GREENLET_PY314 1 +#else +# define GREENLET_PY314 0 +#endif + +#if PY_VERSION_HEX >= 0x30F0000 +# define GREENLET_PY315 1 +#else +# define GREENLET_PY315 0 +#endif + + +/* _Py_DEC_REFTOTAL macro has been removed from Python 3.9 by: + https://github.com/python/cpython/commit/49932fec62c616ec88da52642339d83ae719e924 + + The symbol we use to replace it was removed by at least 3.12. +*/ +#if defined(Py_REF_DEBUG) && !GREENLET_PY312 +# define GREENLET_Py_DEC_REFTOTAL _Py_RefTotal-- +#else +# define GREENLET_Py_DEC_REFTOTAL +#endif + + +#define G_TPFLAGS_DEFAULT Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_VERSION_TAG | Py_TPFLAGS_HAVE_GC + + +// bpo-43760 added PyThreadState_EnterTracing() to Python 3.11.0a2 +#if PY_VERSION_HEX < 0x030B00A2 && !defined(PYPY_VERSION) +static inline void PyThreadState_EnterTracing(PyThreadState *tstate) +{ + tstate->tracing++; + tstate->cframe->use_tracing = 0; +} +#endif + +// bpo-43760 added PyThreadState_LeaveTracing() to Python 3.11.0a2 +#if PY_VERSION_HEX < 0x030B00A2 && !defined(PYPY_VERSION) +static inline void PyThreadState_LeaveTracing(PyThreadState *tstate) +{ + tstate->tracing--; + int use_tracing = (tstate->c_tracefunc != NULL + || tstate->c_profilefunc != NULL); + tstate->cframe->use_tracing = use_tracing; +} +#endif + +#if !defined(Py_C_RECURSION_LIMIT) && defined(C_RECURSION_LIMIT) +# define Py_C_RECURSION_LIMIT C_RECURSION_LIMIT +#endif + +// Py_IsFinalizing() became a public API in Python 3.13. Map it to the +// private _Py_IsFinalizing() on older versions so all call sites can +// use the standard name. Remove this once greenlet drops support for +// Python < 3.13. +#if !GREENLET_PY313 +# define Py_IsFinalizing() _Py_IsFinalizing() +#endif + +#endif /* GREENLET_CPYTHON_COMPAT_H */ diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/greenlet_exceptions.hpp b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/greenlet_exceptions.hpp new file mode 100644 index 000000000..617f07c2f --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/greenlet_exceptions.hpp @@ -0,0 +1,171 @@ +#ifndef GREENLET_EXCEPTIONS_HPP +#define GREENLET_EXCEPTIONS_HPP + +#define PY_SSIZE_T_CLEAN +#include +#include +#include + +#ifdef __clang__ +# pragma clang diagnostic push +# pragma clang diagnostic ignored "-Wunused-function" +#endif + +namespace greenlet { + + class PyErrOccurred : public std::runtime_error + { + public: + + // CAUTION: In debug builds, may run arbitrary Python code. + static const PyErrOccurred + from_current() + { + assert(PyErr_Occurred()); +#ifndef NDEBUG + // This is not exception safe, and + // not necessarily safe in general (what if it switches?) + // But we only do this in debug mode, where we are in + // tight control of what exceptions are getting raised and + // can prevent those issues. + + // You can't call PyObject_Str with a pending exception. + PyObject* typ; + PyObject* val; + PyObject* tb; + + PyErr_Fetch(&typ, &val, &tb); + PyObject* typs = PyObject_Str(typ); + PyObject* vals = PyObject_Str(val ? val : typ); + const char* typ_msg = PyUnicode_AsUTF8(typs); + const char* val_msg = PyUnicode_AsUTF8(vals); + PyErr_Restore(typ, val, tb); + + std::string msg(typ_msg); + msg += ": "; + msg += val_msg; + PyErrOccurred ex(msg); + Py_XDECREF(typs); + Py_XDECREF(vals); + + return ex; +#else + return PyErrOccurred(); +#endif + } + + PyErrOccurred() : std::runtime_error("") + { + assert(PyErr_Occurred()); + } + + PyErrOccurred(const std::string& msg) : std::runtime_error(msg) + { + assert(PyErr_Occurred()); + } + + PyErrOccurred(PyObject* exc_kind, const char* const msg) + : std::runtime_error(msg) + { + PyErr_SetString(exc_kind, msg); + } + + PyErrOccurred(PyObject* exc_kind, const std::string msg) + : std::runtime_error(msg) + { + // This copies the c_str, so we don't have any lifetime + // issues to worry about. + PyErr_SetString(exc_kind, msg.c_str()); + } + + PyErrOccurred(PyObject* exc_kind, + const std::string msg, //This is the format + //string; that's not + //usually safe! + + PyObject* borrowed_obj_one, PyObject* borrowed_obj_two) + : std::runtime_error(msg) + { + + //This is designed specifically for the + //``check_switch_allowed`` function. + + // PyObject_Str and PyObject_Repr are safe to call with + // NULL pointers; they return the string "" in that + // case. + // This function always returns null. + PyErr_Format(exc_kind, + msg.c_str(), + borrowed_obj_one, borrowed_obj_two); + } + }; + + class TypeError : public PyErrOccurred + { + public: + TypeError(const char* const what) + : PyErrOccurred(PyExc_TypeError, what) + { + } + TypeError(const std::string what) + : PyErrOccurred(PyExc_TypeError, what) + { + } + }; + + class ValueError : public PyErrOccurred + { + public: + ValueError(const char* const what) + : PyErrOccurred(PyExc_ValueError, what) + { + } + }; + + class AttributeError : public PyErrOccurred + { + public: + AttributeError(const char* const what) + : PyErrOccurred(PyExc_AttributeError, what) + { + } + }; + + /** + * Calls `Py_FatalError` when constructed, so you can't actually + * throw this. It just makes static analysis easier. + */ + class PyFatalError : public std::runtime_error + { + public: + PyFatalError(const char* const msg) + : std::runtime_error(msg) + { + Py_FatalError(msg); + } + }; + + static inline PyObject* + Require(PyObject* p, const std::string& msg="") + { + if (!p) { + throw PyErrOccurred(msg); + } + return p; + }; + + static inline void + Require(const int retval) + { + if (retval < 0) { + throw PyErrOccurred(); + } + }; + + +}; +#ifdef __clang__ +# pragma clang diagnostic pop +#endif + +#endif diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/greenlet_internal.hpp b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/greenlet_internal.hpp new file mode 100644 index 000000000..4aca792c5 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/greenlet_internal.hpp @@ -0,0 +1,109 @@ +/* -*- indent-tabs-mode: nil; tab-width: 4; -*- */ +#ifndef GREENLET_INTERNAL_H +#define GREENLET_INTERNAL_H +#ifdef __clang__ +# pragma clang diagnostic push +# pragma clang diagnostic ignored "-Wunused-function" +#endif + +/** + * Implementation helpers. + * + * C++ templates and inline functions should go here. + */ +#define PY_SSIZE_T_CLEAN +#include "greenlet_compiler_compat.hpp" +#include "greenlet_cpython_compat.hpp" +#include "greenlet_exceptions.hpp" +#include "TGreenlet.hpp" +#include "greenlet_allocator.hpp" + +#include +#include + +#define GREENLET_MODULE +struct _greenlet; +typedef struct _greenlet PyGreenlet; +namespace greenlet { + + class ThreadState; + // We can't use the PythonAllocator for this, because we push to it + // from the thread state destructor, which doesn't have the GIL, + // and Python's allocators can only be called with the GIL. + typedef std::vector cleanup_queue_t; +}; + + +#define implementation_ptr_t greenlet::Greenlet* + + +#include "greenlet.h" + +void +greenlet::refs::MainGreenletExactChecker(void *p) +{ + if (!p) { + return; + } + if (greenlet::IsShuttingDown()) { + return; + } + // We control the class of the main greenlet exactly. + if (Py_TYPE(p) != &PyGreenlet_Type) { + std::string err("MainGreenlet: Expected exactly a greenlet, not a "); + err += Py_TYPE(p)->tp_name; + throw greenlet::TypeError(err); + } + + // Greenlets from dead threads no longer respond to main() with a + // true value; so in that case we need to perform an additional + // check. + Greenlet* g = static_cast(p)->pimpl; + if (g->main()) { + return; + } + if (!dynamic_cast(g)) { + std::string err("MainGreenlet: Expected exactly a main greenlet, not a "); + err += Py_TYPE(p)->tp_name; + throw greenlet::TypeError(err); + } +} + + + +template +inline greenlet::Greenlet* greenlet::refs::_OwnedGreenlet::operator->() const noexcept +{ + return reinterpret_cast(this->p)->pimpl; +} + +template +inline greenlet::Greenlet* greenlet::refs::_BorrowedGreenlet::operator->() const noexcept +{ + return reinterpret_cast(this->p)->pimpl; +} + +#include +#include + + +extern PyTypeObject PyGreenlet_Type; + + + +/** + * Forward declarations needed in multiple files. + */ +static PyObject* green_switch(PyGreenlet* self, PyObject* args, PyObject* kwargs); + + +#ifdef __clang__ +# pragma clang diagnostic pop +#endif + + +#endif + +// Local Variables: +// flycheck-clang-include-path: ("../../include" "/opt/local/Library/Frameworks/Python.framework/Versions/3.10/include/python3.10") +// End: diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/greenlet_msvc_compat.hpp b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/greenlet_msvc_compat.hpp new file mode 100644 index 000000000..9635a1b96 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/greenlet_msvc_compat.hpp @@ -0,0 +1,100 @@ +#ifndef GREENLET_MSVC_COMPAT_HPP +#define GREENLET_MSVC_COMPAT_HPP +/* + * Support for MSVC on Windows. + * + * Beginning with Python 3.14, some of the internal + * include files we need are not compatible with MSVC + * in C++ mode: + * + * internal\pycore_stackref.h(253): error C4576: a parenthesized type + * followed by an initializer list is a non-standard explicit type conversion syntax + * + * This file is included from ``internal/pycore_interpframe.h``, which + * we need for the ``_PyFrame_IsIncomplete`` API. + * + * Unfortunately, that API is a ``static inline`` function, as are a + * bunch of the functions it calls. The only solution seems to be to + * copy those definitions and the supporting inline functions here. + * + * Now, this makes us VERY fragile to changes in those functions. Because + * they're internal and static, the CPython devs might feel free to change + * them in even minor versions, meaning that we could runtime link and load, + * but still crash. We have that problem on all platforms though. It's just worse + * here because we have to keep copying the updated definitions. + */ +#include +#include "greenlet_cpython_compat.hpp" + +// This file is only included on 3.14+ + +extern "C" { + +// pycore_code.h ---------------- +#define _PyCode_CODE(CO) _Py_RVALUE((_Py_CODEUNIT *)(CO)->co_code_adaptive) + +#ifdef Py_GIL_DISABLED +static inline _PyCodeArray * +_PyCode_GetTLBCArray(PyCodeObject *co) +{ + return _Py_STATIC_CAST(_PyCodeArray *, + _Py_atomic_load_ptr_acquire(&co->co_tlbc)); +} +#endif +// End pycore_code.h ---------- + +// pycore_interpframe.h ---------- +#if !defined(Py_GIL_DISABLED) && defined(Py_STACKREF_DEBUG) + +#define Py_TAG_BITS 0 +#else +#define Py_TAG_BITS ((uintptr_t)1) +#define Py_TAG_DEFERRED (1) +#endif + + +static const _PyStackRef PyStackRef_NULL = { .bits = Py_TAG_DEFERRED}; +#define PyStackRef_IsNull(stackref) ((stackref).bits == PyStackRef_NULL.bits) + +static inline PyObject * +PyStackRef_AsPyObjectBorrow(_PyStackRef stackref) +{ + PyObject *cleared = ((PyObject *)((stackref).bits & (~Py_TAG_BITS))); + return cleared; +} + +static inline PyCodeObject *_PyFrame_GetCode(_PyInterpreterFrame *f) { + assert(!PyStackRef_IsNull(f->f_executable)); + PyObject *executable = PyStackRef_AsPyObjectBorrow(f->f_executable); + assert(PyCode_Check(executable)); + return (PyCodeObject *)executable; +} + + +static inline _Py_CODEUNIT * +_PyFrame_GetBytecode(_PyInterpreterFrame *f) +{ +#ifdef Py_GIL_DISABLED + PyCodeObject *co = _PyFrame_GetCode(f); + _PyCodeArray *tlbc = _PyCode_GetTLBCArray(co); + assert(f->tlbc_index >= 0 && f->tlbc_index < tlbc->size); + return (_Py_CODEUNIT *)tlbc->entries[f->tlbc_index]; +#else + return _PyCode_CODE(_PyFrame_GetCode(f)); +#endif +} + +static inline bool //_Py_NO_SANITIZE_THREAD +_PyFrame_IsIncomplete(_PyInterpreterFrame *frame) +{ + if (frame->owner >= FRAME_OWNED_BY_INTERPRETER) { + return true; + } + return frame->owner != FRAME_OWNED_BY_GENERATOR && + frame->instr_ptr < _PyFrame_GetBytecode(frame) + + _PyFrame_GetCode(frame)->_co_firsttraceable; +} +// pycore_interpframe.h ---------- + +} +#endif // GREENLET_MSVC_COMPAT_HPP diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/greenlet_refs.hpp b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/greenlet_refs.hpp new file mode 100644 index 000000000..7a87863f0 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/greenlet_refs.hpp @@ -0,0 +1,1172 @@ +#ifndef GREENLET_REFS_HPP +#define GREENLET_REFS_HPP + +#define PY_SSIZE_T_CLEAN +#include + +#include + +//#include "greenlet_internal.hpp" +#include "greenlet_compiler_compat.hpp" +#include "greenlet_cpython_compat.hpp" +#include "greenlet_exceptions.hpp" + +struct _greenlet; +struct _PyMainGreenlet; + +typedef struct _greenlet PyGreenlet; +extern PyTypeObject PyGreenlet_Type; + + +#ifdef GREENLET_USE_STDIO +#include +using std::cerr; +using std::endl; +#endif + +namespace greenlet +{ + class Greenlet; + // _Py_IsFinalizing() is only set AFTER atexit handlers complete + // inside Py_FinalizeEx on ALL Python versions (including 3.11+). + // Code running in atexit handlers (e.g. uWSGI plugin cleanup + // calling Py_FinalizeEx, New Relic agent shutdown) can still call + // greenlet.getcurrent(), but by that time type objects or + // internal state may have been invalidated. This flag is set by + // an atexit handler registered at module init (LIFO = runs + // first). + // + // Because this is only set from an atexit handler, by which point + // we're single threaded, there should be no need to make it + // std::atomic. + // TODO: Move this to the GreenletGlobals object? + static int g_greenlet_shutting_down; + + static inline bool + IsShuttingDown() + { + return greenlet::g_greenlet_shutting_down || Py_IsFinalizing(); + } + + namespace refs + { + // Type checkers throw a TypeError if the argument is not + // null, and isn't of the required Python type. + // (We can't use most of the defined type checkers + // like PyList_Check, etc, directly, because they are + // implemented as macros.) + typedef void (*TypeChecker)(void*); + + void + NoOpChecker(void*) + { + return; + } + + void + GreenletChecker(void *p) + { + if (!p) { + return; + } + if (IsShuttingDown()) { + return; + } + + PyTypeObject* typ = Py_TYPE(p); + // fast, common path. (PyObject_TypeCheck is a macro or + // static inline function, and it also does a + // direct comparison of the type pointers, but its fast + // path only handles one type) + if (typ == &PyGreenlet_Type) { + return; + } + + if (!PyObject_TypeCheck(p, &PyGreenlet_Type)) { + std::string err("GreenletChecker: Expected any type of greenlet, not "); + err += Py_TYPE(p)->tp_name; + throw TypeError(err); + } + } + + void + MainGreenletExactChecker(void *p); + + template + class PyObjectPointer; + + template + class OwnedReference; + + + template + class BorrowedReference; + + typedef BorrowedReference BorrowedObject; + typedef OwnedReference OwnedObject; + + class ImmortalObject; + class ImmortalString; + + template + class _OwnedGreenlet; + + typedef _OwnedGreenlet OwnedGreenlet; + typedef _OwnedGreenlet OwnedMainGreenlet; + + template + class _BorrowedGreenlet; + + typedef _BorrowedGreenlet BorrowedGreenlet; + + void + ContextExactChecker(void *p) + { + if (!p) { + return; + } + if (IsShuttingDown()) { + return; + } + if (!PyContext_CheckExact(p)) { + throw TypeError( + "greenlet context must be a contextvars.Context or None" + ); + } + } + + typedef OwnedReference OwnedContext; + } +} + +namespace greenlet { + + + namespace refs { + // A set of classes to make reference counting rules in python + // code explicit. + // + // Rules of use: + // (1) Functions returning a new reference that the caller of the + // function is expected to dispose of should return a + // ``OwnedObject`` object. This object automatically releases its + // reference when it goes out of scope. It works like a ``std::shared_ptr`` + // and can be copied or used as a function parameter (but don't do + // that). Note that constructing a ``OwnedObject`` from a + // PyObject* steals the reference. + // (2) Parameters to functions should be either a + // ``OwnedObject&``, or, more generally, a ``PyObjectPointer&``. + // If the function needs to create its own new reference, it can + // do so by copying to a local ``OwnedObject``. + // (3) Functions returning an existing pointer that is NOT + // incref'd, and which the caller MUST NOT decref, + // should return a ``BorrowedObject``. + + // XXX: The following two paragraphs do not hold for all platforms. + // Notably, 32-bit PPC Linux passes structs by reference, not by + // value, so this actually doesn't work. (Although that's the only + // platform that doesn't work on.) DO NOT ATTEMPT IT. The + // unfortunate consequence of that is that the slots which we + // *know* are already type safe will wind up calling the type + // checker function (when we had the slots accepting + // BorrowedGreenlet, this was bypassed), so this slows us down. + // TODO: Optimize this again. + + // For a class with a single pointer member, whose constructor + // does nothing but copy a pointer parameter into the member, and + // which can then be converted back to the pointer type, compilers + // generate code that's the same as just passing the pointer. + // That is, func(BorrowedObject x) called like ``PyObject* p = + // ...; f(p)`` has 0 overhead. Similarly, they "unpack" to the + // pointer type with 0 overhead. + // + // If there are no virtual functions, no complex inheritance (maybe?) and + // no destructor, these can be directly used as parameters in + // Python callbacks like tp_init: the layout is the same as a + // single pointer. Only subclasses with trivial constructors that + // do nothing but set the single pointer member are safe to use + // that way. + + + // This is the base class for things that can be done with a + // PyObject pointer. It assumes nothing about memory management. + // NOTE: Nothing is virtual, so subclasses shouldn't add new + // storage fields or try to override these methods. + template + class PyObjectPointer + { + public: + typedef T PyType; + protected: + T* p; + public: + PyObjectPointer(T* it=nullptr) : p(it) + { + TC(p); + } + + // We don't allow automatic casting to PyObject* at this + // level, because then we could be passed to Py_DECREF/INCREF, + // but we want nothing to do with memory management. If you + // know better, then you can use the get() method, like on a + // std::shared_ptr. Except we name it borrow() to clarify that + // if this is a reference-tracked object, the pointer you get + // back will go away when the object does. + // TODO: This should probably not exist here, but be moved + // down to relevant sub-types. + + T* borrow() const noexcept + { + return this->p; + } + + PyObject* borrow_o() const noexcept + { + return reinterpret_cast(this->p); + } + + T* operator->() const noexcept + { + return this->p; + } + + bool is_None() const noexcept + { + return this->p == Py_None; + } + + PyObject* acquire_or_None() const noexcept + { + PyObject* result = this->p ? reinterpret_cast(this->p) : Py_None; + Py_INCREF(result); + return result; + } + + explicit operator bool() const noexcept + { + return this->p != nullptr; + } + + bool operator!() const noexcept + { + return this->p == nullptr; + } + + Py_ssize_t REFCNT() const noexcept + { + return p ? Py_REFCNT(p) : -42; + } + + PyTypeObject* TYPE() const noexcept + { + return p ? Py_TYPE(p) : nullptr; + } + + inline OwnedObject PyStr() const noexcept; + inline const std::string as_str() const noexcept; + inline OwnedObject PyGetAttr(const ImmortalObject& name) const noexcept; + inline OwnedObject PyRequireAttr(const char* const name) const; + inline OwnedObject PyRequireAttr(const ImmortalString& name) const; + inline OwnedObject PyCall(const BorrowedObject& arg) const; + inline OwnedObject PyCall(PyGreenlet* arg) const ; + inline OwnedObject PyCall(PyObject* arg) const ; + // PyObject_Call(this, args, kwargs); + inline OwnedObject PyCall(const BorrowedObject args, + const BorrowedObject kwargs) const; + inline OwnedObject PyCall(const OwnedObject& args, + const OwnedObject& kwargs) const; + + protected: + void _set_raw_pointer(void* t) + { + TC(t); + p = reinterpret_cast(t); + } + void* _get_raw_pointer() const + { + return p; + } + }; + +#ifdef GREENLET_USE_STDIO + template + std::ostream& operator<<(std::ostream& os, const PyObjectPointer& s) + { + const std::type_info& t = typeid(s); + os << t.name() + << "(addr=" << s.borrow() + << ", refcnt=" << s.REFCNT() + << ", value=" << s.as_str() + << ")"; + + return os; + } +#endif + + template + inline bool operator==(const PyObjectPointer& lhs, const PyObject* const rhs) noexcept + { + return static_cast(lhs.borrow_o()) == static_cast(rhs); + } + + template + inline bool operator==(const PyObjectPointer& lhs, const PyObjectPointer& rhs) noexcept + { + return lhs.borrow_o() == rhs.borrow_o(); + } + + template + inline bool operator!=(const PyObjectPointer& lhs, + const PyObjectPointer& rhs) noexcept + { + return lhs.borrow_o() != rhs.borrow_o(); + } + + template + class OwnedReference : public PyObjectPointer + { + private: + friend class OwnedList; + + protected: + explicit OwnedReference(T* it) : PyObjectPointer(it) + { + } + + public: + + // Constructors + + static OwnedReference consuming(PyObject* p) + { + return OwnedReference(reinterpret_cast(p)); + } + + static OwnedReference owning(T* p) + { + OwnedReference result(p); + Py_XINCREF(result.p); + return result; + } + + OwnedReference() : PyObjectPointer(nullptr) + {} + + explicit OwnedReference(const PyObjectPointer<>& other) + : PyObjectPointer(nullptr) + { + T* op = other.borrow(); + TC(op); + this->p = other.borrow(); + Py_XINCREF(this->p); + } + + // It would be good to make use of the C++11 distinction + // between move and copy operations, e.g., constructing from a + // pointer should be a move operation. + // In the common case of ``OwnedObject x = Py_SomeFunction()``, + // the call to the copy constructor will be elided completely. + OwnedReference(const OwnedReference& other) + : PyObjectPointer(other.p) + { + Py_XINCREF(this->p); + } + + static OwnedReference None() + { + Py_INCREF(Py_None); + return OwnedReference(Py_None); + } + + // We can assign from exactly our type without any extra checking + OwnedReference& operator=(const OwnedReference& other) + { + Py_XINCREF(other.p); + const T* tmp = this->p; + this->p = other.p; + Py_XDECREF(tmp); + return *this; + } + + OwnedReference& operator=(const BorrowedReference other) + { + return this->operator=(other.borrow()); + } + + OwnedReference& operator=(T* const other) + { + TC(other); + Py_XINCREF(other); + T* tmp = this->p; + this->p = other; + Py_XDECREF(tmp); + return *this; + } + + // We can assign from an arbitrary reference type + // if it passes our check. + template + OwnedReference& operator=(const OwnedReference& other) + { + X* op = other.borrow(); + TC(op); + return this->operator=(reinterpret_cast(op)); + } + + inline void steal(T* other) + { + assert(this->p == nullptr); + TC(other); + this->p = other; + } + + T* relinquish_ownership() + { + T* result = this->p; + this->p = nullptr; + return result; + } + + T* acquire() const + { + // Return a new reference. + // TODO: This may go away when we have reference objects + // throughout the code. + Py_XINCREF(this->p); + return this->p; + } + + // Nothing else declares a destructor, we're the leaf, so we + // should be able to get away without virtual. + ~OwnedReference() + { + Py_CLEAR(this->p); + } + + void CLEAR() + { + Py_CLEAR(this->p); + assert(this->p == nullptr); + } + }; + + static inline + void operator<<=(PyObject*& target, OwnedObject& o) + { + target = o.relinquish_ownership(); + } + + + class NewReference : public OwnedObject + { + private: + G_NO_COPIES_OF_CLS(NewReference); + public: + // Consumes the reference. Only use this + // for API return values. + NewReference(PyObject* it) : OwnedObject(it) + { + } + }; + + class NewDictReference : public NewReference + { + private: + G_NO_COPIES_OF_CLS(NewDictReference); + public: + NewDictReference() : NewReference(PyDict_New()) + { + if (!this->p) { + throw PyErrOccurred(); + } + } + + void SetItem(const char* const key, PyObject* value) + { + Require(PyDict_SetItemString(this->p, key, value)); + } + + void SetItem(const PyObjectPointer<>& key, PyObject* value) + { + Require(PyDict_SetItem(this->p, key.borrow_o(), value)); + } + }; + + template + class _OwnedGreenlet: public OwnedReference + { + private: + protected: + _OwnedGreenlet(T* it) : OwnedReference(it) + {} + + public: + _OwnedGreenlet() : OwnedReference() + {} + + _OwnedGreenlet(const _OwnedGreenlet& other) : OwnedReference(other) + { + } + _OwnedGreenlet(OwnedMainGreenlet& other) : + OwnedReference(reinterpret_cast(other.acquire())) + { + } + _OwnedGreenlet(const BorrowedGreenlet& other); + // Steals a reference. + static _OwnedGreenlet consuming(PyGreenlet* it) + { + return _OwnedGreenlet(reinterpret_cast(it)); + } + + inline _OwnedGreenlet& operator=(const OwnedGreenlet& other) + { + return this->operator=(other.borrow()); + } + + inline _OwnedGreenlet& operator=(const BorrowedGreenlet& other); + + _OwnedGreenlet& operator=(const OwnedMainGreenlet& other) + { + PyGreenlet* owned = other.acquire(); + Py_XDECREF(this->p); + this->p = reinterpret_cast(owned); + return *this; + } + + _OwnedGreenlet& operator=(T* const other) + { + OwnedReference::operator=(other); + return *this; + } + + T* relinquish_ownership() + { + T* result = this->p; + this->p = nullptr; + return result; + } + + PyObject* relinquish_ownership_o() + { + return reinterpret_cast(relinquish_ownership()); + } + + inline Greenlet* operator->() const noexcept; + inline operator Greenlet*() const noexcept; + }; + + template + class BorrowedReference : public PyObjectPointer + { + public: + // Allow implicit creation from PyObject* pointers as we + // transition to using these classes. Also allow automatic + // conversion to PyObject* for passing to C API calls and even + // for Py_INCREF/DECREF, because we ourselves do no memory management. + BorrowedReference(T* it) : PyObjectPointer(it) + {} + + BorrowedReference(const PyObjectPointer& ref) : PyObjectPointer(ref.borrow()) + {} + + BorrowedReference() : PyObjectPointer(nullptr) + {} + + operator T*() const + { + return this->p; + } + }; + + typedef BorrowedReference BorrowedObject; + //typedef BorrowedReference BorrowedGreenlet; + + template + class _BorrowedGreenlet : public BorrowedReference + { + public: + _BorrowedGreenlet() : + BorrowedReference(nullptr) + {} + + _BorrowedGreenlet(T* it) : + BorrowedReference(it) + {} + + _BorrowedGreenlet(const BorrowedObject& it); + + _BorrowedGreenlet(const OwnedGreenlet& it) : + BorrowedReference(it.borrow()) + {} + + _BorrowedGreenlet& operator=(const BorrowedObject& other); + + // We get one of these for PyGreenlet, but one for PyObject + // is handy as well + operator PyObject*() const + { + return reinterpret_cast(this->p); + } + Greenlet* operator->() const noexcept; + operator Greenlet*() const noexcept; + }; + + typedef _BorrowedGreenlet BorrowedGreenlet; + + template + _OwnedGreenlet::_OwnedGreenlet(const BorrowedGreenlet& other) + : OwnedReference(reinterpret_cast(other.borrow())) + { + Py_XINCREF(this->p); + } + + + class BorrowedMainGreenlet + : public _BorrowedGreenlet + { + public: + BorrowedMainGreenlet(const OwnedMainGreenlet& it) : + _BorrowedGreenlet(it.borrow()) + {} + BorrowedMainGreenlet(PyGreenlet* it=nullptr) + : _BorrowedGreenlet(it) + {} + }; + + template + _OwnedGreenlet& _OwnedGreenlet::operator=(const BorrowedGreenlet& other) + { + return this->operator=(other.borrow()); + } + + + class ImmortalObject : public PyObjectPointer<> + { + private: + G_NO_ASSIGNMENT_OF_CLS(ImmortalObject); + public: + explicit ImmortalObject(PyObject* it) : PyObjectPointer<>(it) + { + } + + ImmortalObject(const ImmortalObject& other) + : PyObjectPointer<>(other.p) + { + + } + + /** + * Become the new owner of the object. Does not change the + * reference count. + */ + ImmortalObject& operator=(PyObject* it) + { + assert(this->p == nullptr); + this->p = it; + return *this; + } + + static ImmortalObject consuming(PyObject* it) + { + return ImmortalObject(it); + } + + inline operator PyObject*() const + { + return this->p; + } + }; + + class ImmortalString : public ImmortalObject + { + private: + G_NO_COPIES_OF_CLS(ImmortalString); + const char* str; + public: + ImmortalString(const char* const str) : + ImmortalObject(str ? Require(PyUnicode_InternFromString(str)) : nullptr) + { + this->str = str; + } + + inline ImmortalString& operator=(const char* const str) + { + if (!this->p) { + this->p = Require(PyUnicode_InternFromString(str)); + this->str = str; + } + else { + assert(this->str == str); + } + return *this; + } + + inline operator std::string() const + { + return this->str; + } + + }; + + class ImmortalEventName : public ImmortalString + { + private: + G_NO_COPIES_OF_CLS(ImmortalEventName); + public: + ImmortalEventName(const char* const str) : ImmortalString(str) + {} + }; + + class ImmortalException : public ImmortalObject + { + private: + G_NO_COPIES_OF_CLS(ImmortalException); + public: + ImmortalException(const char* const name, PyObject* base=nullptr) : + ImmortalObject(name + // Python 2.7 isn't const correct + ? Require(PyErr_NewException((char*)name, base, nullptr)) + : nullptr) + {} + + inline bool PyExceptionMatches() const + { + return PyErr_ExceptionMatches(this->p) > 0; + } + + }; + + template + inline OwnedObject PyObjectPointer::PyStr() const noexcept + { + if (!this->p) { + return OwnedObject(); + } + return OwnedObject::consuming(PyObject_Str(reinterpret_cast(this->p))); + } + + template + inline const std::string PyObjectPointer::as_str() const noexcept + { + // NOTE: This is not Python exception safe. + if (this->p) { + // The Python APIs return a cached char* value that's only valid + // as long as the original object stays around, and we're + // about to (probably) toss it. Hence the copy to std::string. + OwnedObject py_str = this->PyStr(); + if (!py_str) { + return "(nil)"; + } + return PyUnicode_AsUTF8(py_str.borrow()); + } + return "(nil)"; + } + + template + inline OwnedObject PyObjectPointer::PyGetAttr(const ImmortalObject& name) const noexcept + { + assert(this->p); + return OwnedObject::consuming(PyObject_GetAttr(reinterpret_cast(this->p), name)); + } + + template + inline OwnedObject PyObjectPointer::PyRequireAttr(const char* const name) const + { + assert(this->p); + return OwnedObject::consuming(Require(PyObject_GetAttrString(this->p, name), name)); + } + + template + inline OwnedObject PyObjectPointer::PyRequireAttr(const ImmortalString& name) const + { + assert(this->p); + return OwnedObject::consuming(Require( + PyObject_GetAttr( + reinterpret_cast(this->p), + name + ), + name + )); + } + + template + inline OwnedObject PyObjectPointer::PyCall(const BorrowedObject& arg) const + { + return this->PyCall(arg.borrow()); + } + + template + inline OwnedObject PyObjectPointer::PyCall(PyGreenlet* arg) const + { + return this->PyCall(reinterpret_cast(arg)); + } + + template + inline OwnedObject PyObjectPointer::PyCall(PyObject* arg) const + { + assert(this->p); + return OwnedObject::consuming(PyObject_CallFunctionObjArgs(this->p, arg, NULL)); + } + + template + inline OwnedObject PyObjectPointer::PyCall(const BorrowedObject args, + const BorrowedObject kwargs) const + { + assert(this->p); + return OwnedObject::consuming(PyObject_Call(this->p, args, kwargs)); + } + + template + inline OwnedObject PyObjectPointer::PyCall(const OwnedObject& args, + const OwnedObject& kwargs) const + { + assert(this->p); + return OwnedObject::consuming(PyObject_Call(this->p, args.borrow(), kwargs.borrow())); + } + + inline void + ListChecker(void * p) + { + if (!p) { + return; + } + if (!PyList_Check(p)) { + throw TypeError("Expected a list"); + } + } + + class OwnedList : public OwnedReference + { + private: + G_NO_ASSIGNMENT_OF_CLS(OwnedList); + public: + // TODO: Would like to use move. + explicit OwnedList(const OwnedObject& other) + : OwnedReference(other) + { + } + + OwnedList& operator=(const OwnedObject& other) + { + if (other && PyList_Check(other.p)) { + // Valid list. Own a new reference to it, discard the + // reference to what we did own. + PyObject* new_ptr = other.p; + Py_INCREF(new_ptr); + Py_XDECREF(this->p); + this->p = new_ptr; + } + else { + // Either the other object was NULL (an error) or it + // wasn't a list. Either way, we're now invalidated. + Py_XDECREF(this->p); + this->p = nullptr; + } + return *this; + } + + inline bool empty() const + { + return PyList_GET_SIZE(p) == 0; + } + + inline Py_ssize_t size() const + { + return PyList_GET_SIZE(p); + } + + inline BorrowedObject at(const Py_ssize_t index) const + { + return PyList_GET_ITEM(p, index); + } + + inline void clear() + { + PyList_SetSlice(p, 0, PyList_GET_SIZE(p), NULL); + } + }; + + // Use this to represent the module object used at module init + // time. + // This could either be a borrowed (Py2) or new (Py3) reference; + // either way, we don't want to do any memory management + // on it here, Python itself will handle that. + // XXX: Actually, that's not quite right. On Python 3, if an + // exception occurs before we return to the interpreter, this will + // leak; but all previous versions also had that problem. + class CreatedModule : public PyObjectPointer<> + { + private: + G_NO_COPIES_OF_CLS(CreatedModule); + public: + CreatedModule(PyModuleDef& mod_def) : PyObjectPointer<>( + Require(PyModule_Create(&mod_def))) + { + } + + // PyAddObject(): Add a new reference to the object to the module. + void PyAddObject(const char* name, const long new_bool) + { + Require(PyModule_AddIntConstant(this->p, name, new_bool)); + } + + // It is safe to pass a null value to this API because we use + // PyModule_AddObjectRef under the covers which allows null. + void PyAddObject(const char* name, const OwnedObject& new_object) + { + // The caller already owns a reference they will decref + // when their variable goes out of scope, we still need to + // incref/decref. + this->PyAddObject(name, new_object.borrow()); + } + + void PyAddObject(const char* name, const ImmortalObject& new_object) + { + this->PyAddObject(name, new_object.borrow()); + } + + void PyAddObject(const char* name, PyTypeObject& type) + { + this->PyAddObject(name, reinterpret_cast(&type)); + } + + private: + + void PyAddObject(const char* name, PyObject* new_object) + { + Require(PyModule_AddObjectRef(this->p, name, new_object)); + } + }; + + class PyErrFetchParam : public PyObjectPointer<> + { + // Not an owned object, because we can't be initialized with + // one, and we only sometimes acquire ownership. + private: + G_NO_COPIES_OF_CLS(PyErrFetchParam); + public: + // To allow declaring these and passing them to + // PyErr_Fetch we implement the empty constructor, + // and the address operator. + PyErrFetchParam() : PyObjectPointer<>(nullptr) + { + } + + PyObject** operator&() + { + return &this->p; + } + + // This allows us to pass one directly without the &, + // BUT it has higher precedence than the bool operator + // if it's not explicit. + operator PyObject**() + { + return &this->p; + } + + // We don't want to be able to pass these to Py_DECREF and + // such so we don't have the implicit PyObject* conversion. + + inline PyObject* relinquish_ownership() + { + PyObject* result = this->p; + this->p = nullptr; + return result; + } + + ~PyErrFetchParam() + { + Py_XDECREF(p); + } + }; + + class OwnedErrPiece : public OwnedObject + { + private: + + public: + // Unlike OwnedObject, this increments the refcount. + OwnedErrPiece(PyObject* p=nullptr) : OwnedObject(p) + { + this->acquire(); + } + + PyObject** operator&() + { + return &this->p; + } + + inline operator PyObject*() const + { + return this->p; + } + + operator PyTypeObject*() const + { + return reinterpret_cast(this->p); + } + }; + + // TODO: When we run on 3.12+ only (GREENLET_312), switch to the + // ``PyErr_GetRaisedException`` family of functions. The + // ``PyErr_Fetch`` family is deprecated on 3.12+, but is part + // of the stable ABI so it's not going anywhere. + class PyErrPieces + { + private: + OwnedErrPiece type; + OwnedErrPiece instance; + OwnedErrPiece traceback; + bool restored; + public: + // Takes new references; if we're destroyed before + // restoring the error, we drop the references. + PyErrPieces(PyObject* t, PyObject* v, PyObject* tb) : + type(t), + instance(v), + traceback(tb), + restored(0) + { + this->normalize(); + } + + PyErrPieces() : + restored(0) + { + // PyErr_Fetch transfers ownership to us, so + // we don't actually need to INCREF; but we *do* + // need to DECREF if we're not restored. + PyErrFetchParam t, v, tb; + PyErr_Fetch(&t, &v, &tb); + type.steal(t.relinquish_ownership()); + instance.steal(v.relinquish_ownership()); + traceback.steal(tb.relinquish_ownership()); + } + + void PyErrRestore() + { + // can only do this once + assert(!this->restored); + this->restored = true; + PyErr_Restore( + this->type.relinquish_ownership(), + this->instance.relinquish_ownership(), + this->traceback.relinquish_ownership()); + assert(!this->type && !this->instance && !this->traceback); + } + + private: + void normalize() + { + // First, check the traceback argument, replacing None, + // with NULL + if (traceback.is_None()) { + traceback = nullptr; + } + + if (traceback && !PyTraceBack_Check(traceback.borrow())) { + throw PyErrOccurred(PyExc_TypeError, + "throw() third argument must be a traceback object"); + } + + if (PyExceptionClass_Check(type)) { + // If we just had a type, we'll now have a type and + // instance. + // The type's refcount will have gone up by one + // because of the instance and the instance will have + // a refcount of one. Either way, we owned, and still + // do own, exactly one reference. + PyErr_NormalizeException(&type, &instance, &traceback); + + } + else if (PyExceptionInstance_Check(type)) { + /* Raising an instance --- usually that means an + object that is a subclass of BaseException, but on + Python 2, that can also mean an arbitrary old-style + object. The value should be a dummy. */ + if (instance && !instance.is_None()) { + throw PyErrOccurred( + PyExc_TypeError, + "instance exception may not have a separate value"); + } + /* Normalize to raise , */ + this->instance = this->type; + this->type = PyExceptionInstance_Class(instance.borrow()); + + /* + It would be tempting to do this: + + Py_ssize_t type_count = Py_REFCNT(Py_TYPE(instance.borrow())); + this->type = PyExceptionInstance_Class(instance.borrow()); + assert(this->type.REFCNT() == type_count + 1); + + But that doesn't work on Python 2 in the case of + old-style instances: The result of Py_TYPE is going to + be the global shared that all + old-style classes have, while the return of Instance_Class() + will be the Python-level class object. The two are unrelated. + */ + } + else { + /* Not something you can raise. throw() fails. */ + PyErr_Format(PyExc_TypeError, + "exceptions must be classes, or instances, not %s", + Py_TYPE(type.borrow())->tp_name); + throw PyErrOccurred(); + } + } + }; + + // PyArg_Parse's O argument returns a borrowed reference. + class PyArgParseParam : public BorrowedObject + { + private: + G_NO_COPIES_OF_CLS(PyArgParseParam); + public: + explicit PyArgParseParam(PyObject* p=nullptr) : BorrowedObject(p) + { + } + + inline PyObject** operator&() + { + return &this->p; + } + }; + +#ifdef Py_GIL_DISABLED + // building on 3.13 or newer, free-threaded + class PyCriticalObjectSection { + private: + G_NO_COPIES_OF_CLS(PyCriticalObjectSection); + PyCriticalSection _py_cs; + public: + explicit PyCriticalObjectSection(PyObject* p) + { + PyCriticalSection_Begin(&this->_py_cs, p); + } + explicit PyCriticalObjectSection(const PyGreenlet* p) + : PyCriticalObjectSection( + reinterpret_cast( + const_cast(p))) + {} + ~PyCriticalObjectSection() + { + PyCriticalSection_End(&this->_py_cs); + } + }; +#else + class PyCriticalObjectSection { + public: + explicit PyCriticalObjectSection(PyObject* UNUSED(p)) + {} + explicit PyCriticalObjectSection(const PyGreenlet* UNUSED(p)) + {} + }; + +#endif + + +};}; + +#endif diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/greenlet_slp_switch.hpp b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/greenlet_slp_switch.hpp new file mode 100644 index 000000000..bdffccaed --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/greenlet_slp_switch.hpp @@ -0,0 +1,103 @@ +#ifndef GREENLET_SLP_SWITCH_HPP +#define GREENLET_SLP_SWITCH_HPP + +#include "greenlet_compiler_compat.hpp" +#include "greenlet_refs.hpp" + +/* + * the following macros are spliced into the OS/compiler + * specific code, in order to simplify maintenance. + */ +// We can save about 10% of the time it takes to switch greenlets if +// we thread the thread state through the slp_save_state() and the +// following slp_restore_state() calls from +// slp_switch()->g_switchstack() (which already needs to access it). +// +// However: +// +// that requires changing the prototypes and implementations of the +// switching functions. If we just change the prototype of +// slp_switch() to accept the argument and update the macros, without +// changing the implementation of slp_switch(), we get crashes on +// 64-bit Linux and 32-bit x86 (for reasons that aren't 100% clear); +// on the other hand, 64-bit macOS seems to be fine. Also, 64-bit +// windows is an issue because slp_switch is written fully in assembly +// and currently ignores its argument so some code would have to be +// adjusted there to pass the argument on to the +// ``slp_save_state_asm()`` function (but interestingly, because of +// the calling convention, the extra argument is just ignored and +// things function fine, albeit slower, if we just modify +// ``slp_save_state_asm`()` to fetch the pointer to pass to the +// macro.) +// +// Our compromise is to use a *glabal*, untracked, weak, pointer +// to the necessary thread state during the process of switching only. +// This is safe because we're protected by the GIL, and if we're +// running this code, the thread isn't exiting. This also nets us a +// 10-12% speed improvement. + +#if Py_GIL_DISABLED +thread_local greenlet::Greenlet* switching_thread_state = nullptr; +#else +static greenlet::Greenlet* volatile switching_thread_state = nullptr; +#endif + + +extern "C" { +static int GREENLET_NOINLINE(slp_save_state_trampoline)(char* stackref); +static void GREENLET_NOINLINE(slp_restore_state_trampoline)(); +} + + +#define SLP_SAVE_STATE(stackref, stsizediff) \ +do { \ + assert(switching_thread_state); \ + stackref += STACK_MAGIC; \ + if (slp_save_state_trampoline((char*)stackref)) \ + return -1; \ + if (!switching_thread_state->active()) \ + return 1; \ + stsizediff = switching_thread_state->stack_start() - (char*)stackref; \ +} while (0) + +#define SLP_RESTORE_STATE() slp_restore_state_trampoline() + +#define SLP_EVAL +extern "C" { +#define slp_switch GREENLET_NOINLINE(slp_switch) +#include "slp_platformselect.h" +} +#undef slp_switch + +#ifndef STACK_MAGIC +# error \ + "greenlet needs to be ported to this platform, or taught how to detect your compiler properly." +#endif /* !STACK_MAGIC */ + + + +#ifdef EXTERNAL_ASM +/* CCP addition: Make these functions, to be called from assembler. + * The token include file for the given platform should enable the + * EXTERNAL_ASM define so that this is included. + */ +extern "C" { +intptr_t +slp_save_state_asm(intptr_t* ref) +{ + intptr_t diff; + SLP_SAVE_STATE(ref, diff); + return diff; +} + +void +slp_restore_state_asm(void) +{ + SLP_RESTORE_STATE(); +} + +extern int slp_switch(void); +}; +#endif + +#endif diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/greenlet_thread_support.hpp b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/greenlet_thread_support.hpp new file mode 100644 index 000000000..3ded7d2b7 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/greenlet_thread_support.hpp @@ -0,0 +1,31 @@ +#ifndef GREENLET_THREAD_SUPPORT_HPP +#define GREENLET_THREAD_SUPPORT_HPP + +/** + * Defines various utility functions to help greenlet integrate well + * with threads. This used to be needed when we supported Python + * 2.7 on Windows, which used a very old compiler. We wrote an + * alternative implementation using Python APIs and POSIX or Windows + * APIs, but that's no longer needed. So this file is a shadow of its + * former self --- but may be needed in the future. + */ + +#include +#include +#include + +#include "greenlet_compiler_compat.hpp" + +namespace greenlet { + typedef std::mutex Mutex; + typedef std::lock_guard LockGuard; + class LockInitError : public std::runtime_error + { + public: + LockInitError(const char* what) : std::runtime_error(what) + {}; + }; +}; + + +#endif /* GREENLET_THREAD_SUPPORT_HPP */ diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/platform/__init__.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/platform/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/platform/setup_switch_x64_masm.cmd b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/platform/setup_switch_x64_masm.cmd new file mode 100644 index 000000000..092859555 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/platform/setup_switch_x64_masm.cmd @@ -0,0 +1,2 @@ +call "C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\vcvarsall.bat" amd64 +ml64 /nologo /c /Fo switch_x64_masm.obj switch_x64_masm.asm diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/platform/switch_aarch64_gcc.h b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/platform/switch_aarch64_gcc.h new file mode 100644 index 000000000..058617c40 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/platform/switch_aarch64_gcc.h @@ -0,0 +1,124 @@ +/* + * this is the internal transfer function. + * + * HISTORY + * 07-Sep-16 Add clang support using x register naming. Fredrik Fornwall + * 13-Apr-13 Add support for strange GCC caller-save decisions + * 08-Apr-13 File creation. Michael Matz + * + * NOTES + * + * Simply save all callee saved registers + * + */ + +#define STACK_REFPLUS 1 + +#ifdef SLP_EVAL +#define STACK_MAGIC 0 +#define REGS_TO_SAVE "x19", "x20", "x21", "x22", "x23", "x24", "x25", "x26", \ + "x27", "x28", "x30" /* aka lr */, \ + "v8", "v9", "v10", "v11", \ + "v12", "v13", "v14", "v15" + +/* + * Recall: + asm asm-qualifiers ( AssemblerTemplate + : OutputOperands + [ : InputOperands + [ : Clobbers ] ]) + + or (if asm-qualifiers contains 'goto') + + asm asm-qualifiers ( AssemblerTemplate + : OutputOperands + : InputOperands + : Clobbers + : GotoLabels) + + and OutputOperands are + + [ [asmSymbolicName] ] constraint (cvariablename) + + When a name is given, refer to it as ``%[the name]``. + When not given, ``%i`` where ``i`` is the zero-based index. + + constraints starting with ``=`` means only writing; ``+`` means + reading and writing. + + This is followed by ``r`` (must be register) or ``m`` (must be memory) + and these can be combined. + + The ``cvariablename`` is actually an lvalue expression. + + In AArch65, 31 general purpose registers. If named X0... they are + 64-bit. If named W0... they are the bottom 32 bits of the + corresponding 64 bit register. + + XZR and WZR are hardcoded to 0, and ignore writes. + + Arguments are in X0..X7. C++ uses X0 for ``this``. X0 holds simple return + values (?) + + Whenever a W register is written, the top half of the X register is zeroed. + */ + +static int +slp_switch(void) +{ + int err; + void *fp; + /* Windowz uses a 32-bit long on a 64-bit platform, unlike the rest of + the world, and in theory we can be compiled with GCC/llvm on 64-bit + windows. So we need a fixed-width type. + */ + int64_t *stackref, stsizediff; + __asm__ volatile ("" : : : REGS_TO_SAVE); + __asm__ volatile ("str x29, %0" : "=m"(fp) : : ); + __asm__ ("mov %0, sp" : "=r" (stackref)); + { + SLP_SAVE_STATE(stackref, stsizediff); + __asm__ volatile ( + "add sp,sp,%0\n" + "add x29,x29,%0\n" + : + : "r" (stsizediff) + ); + SLP_RESTORE_STATE(); + /* SLP_SAVE_STATE macro contains some return statements + (of -1 and 1). It falls through only when + the return value of slp_save_state() is zero, which + is placed in x0. + In that case we (slp_switch) also want to return zero + (also in x0 of course). + Now, some GCC versions (seen with 4.8) think it's a + good idea to save/restore x0 around the call to + slp_restore_state(), instead of simply zeroing it + at the return below. But slp_restore_state + writes random values to the stack slot used for this + save/restore (from when it once was saved above in + SLP_SAVE_STATE, when it was still uninitialized), so + "restoring" that precious zero actually makes us + return random values. There are some ways to make + GCC not use that zero value in the normal return path + (e.g. making err volatile, but that costs a little + stack space), and the simplest is to call a function + that returns an unknown value (which happens to be zero), + so the saved/restored value is unused. + + Thus, this line stores a 0 into the ``err`` variable + (which must be held in a register for this instruction, + of course). The ``w`` qualifier causes the instruction + to use W0 instead of X0, otherwise we get a warning + about a value size mismatch (because err is an int, + and aarch64 platforms are LP64: 32-bit int, 64 bit long + and pointer). + */ + __asm__ volatile ("mov %w0, #0" : "=r" (err)); + } + __asm__ volatile ("ldr x29, %0" : : "m" (fp) :); + __asm__ volatile ("" : : : REGS_TO_SAVE); + return err; +} + +#endif diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/platform/switch_alpha_unix.h b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/platform/switch_alpha_unix.h new file mode 100644 index 000000000..7e07abfc2 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/platform/switch_alpha_unix.h @@ -0,0 +1,30 @@ +#define STACK_REFPLUS 1 + +#ifdef SLP_EVAL +#define STACK_MAGIC 0 + +#define REGS_TO_SAVE "$9", "$10", "$11", "$12", "$13", "$14", "$15", \ + "$f2", "$f3", "$f4", "$f5", "$f6", "$f7", "$f8", "$f9" + +static int +slp_switch(void) +{ + int ret; + long *stackref, stsizediff; + __asm__ volatile ("" : : : REGS_TO_SAVE); + __asm__ volatile ("mov $30, %0" : "=r" (stackref) : ); + { + SLP_SAVE_STATE(stackref, stsizediff); + __asm__ volatile ( + "addq $30, %0, $30\n\t" + : /* no outputs */ + : "r" (stsizediff) + ); + SLP_RESTORE_STATE(); + } + __asm__ volatile ("" : : : REGS_TO_SAVE); + __asm__ volatile ("mov $31, %0" : "=r" (ret) : ); + return ret; +} + +#endif diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/platform/switch_amd64_unix.h b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/platform/switch_amd64_unix.h new file mode 100644 index 000000000..d4701105f --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/platform/switch_amd64_unix.h @@ -0,0 +1,87 @@ +/* + * this is the internal transfer function. + * + * HISTORY + * 3-May-13 Ralf Schmitt + * Add support for strange GCC caller-save decisions + * (ported from switch_aarch64_gcc.h) + * 18-Aug-11 Alexey Borzenkov + * Correctly save rbp, csr and cw + * 01-Apr-04 Hye-Shik Chang + * Ported from i386 to amd64. + * 24-Nov-02 Christian Tismer + * needed to add another magic constant to insure + * that f in slp_eval_frame(PyFrameObject *f) + * STACK_REFPLUS will probably be 1 in most cases. + * gets included into the saved stack area. + * 17-Sep-02 Christian Tismer + * after virtualizing stack save/restore, the + * stack size shrunk a bit. Needed to introduce + * an adjustment STACK_MAGIC per platform. + * 15-Sep-02 Gerd Woetzel + * slightly changed framework for spark + * 31-Avr-02 Armin Rigo + * Added ebx, esi and edi register-saves. + * 01-Mar-02 Samual M. Rushing + * Ported from i386. + */ + +#define STACK_REFPLUS 1 + +#ifdef SLP_EVAL + +/* #define STACK_MAGIC 3 */ +/* the above works fine with gcc 2.96, but 2.95.3 wants this */ +#define STACK_MAGIC 0 + +#define REGS_TO_SAVE "r12", "r13", "r14", "r15" + +static int +slp_switch(void) +{ + int err; + void* rbp; + void* rbx; + unsigned int csr; + unsigned short cw; + /* This used to be declared 'register', but that does nothing in + modern compilers and is explicitly forbidden in some new + standards. */ + long *stackref, stsizediff; + __asm__ volatile ("" : : : REGS_TO_SAVE); + __asm__ volatile ("fstcw %0" : "=m" (cw)); + __asm__ volatile ("stmxcsr %0" : "=m" (csr)); + __asm__ volatile ("movq %%rbp, %0" : "=m" (rbp)); + __asm__ volatile ("movq %%rbx, %0" : "=m" (rbx)); + __asm__ ("movq %%rsp, %0" : "=g" (stackref)); + { + SLP_SAVE_STATE(stackref, stsizediff); + __asm__ volatile ( + "addq %0, %%rsp\n" + "addq %0, %%rbp\n" + : + : "r" (stsizediff) + ); + SLP_RESTORE_STATE(); + __asm__ volatile ("xorq %%rax, %%rax" : "=a" (err)); + } + __asm__ volatile ("movq %0, %%rbx" : : "m" (rbx)); + __asm__ volatile ("movq %0, %%rbp" : : "m" (rbp)); + __asm__ volatile ("ldmxcsr %0" : : "m" (csr)); + __asm__ volatile ("fldcw %0" : : "m" (cw)); + __asm__ volatile ("" : : : REGS_TO_SAVE); + return err; +} + +#endif + +/* + * further self-processing support + */ + +/* + * if you want to add self-inspection tools, place them + * here. See the x86_msvc for the necessary defines. + * These features are highly experimental und not + * essential yet. + */ diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/platform/switch_arm32_gcc.h b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/platform/switch_arm32_gcc.h new file mode 100644 index 000000000..655003aa1 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/platform/switch_arm32_gcc.h @@ -0,0 +1,79 @@ +/* + * this is the internal transfer function. + * + * HISTORY + * 14-Aug-06 File creation. Ported from Arm Thumb. Sylvain Baro + * 3-Sep-06 Commented out saving of r1-r3 (r4 already commented out) as I + * read that these do not need to be saved. Also added notes and + * errors related to the frame pointer. Richard Tew. + * + * NOTES + * + * It is not possible to detect if fp is used or not, so the supplied + * switch function needs to support it, so that you can remove it if + * it does not apply to you. + * + * POSSIBLE ERRORS + * + * "fp cannot be used in asm here" + * + * - Try commenting out "fp" in REGS_TO_SAVE. + * + */ + +#define STACK_REFPLUS 1 + +#ifdef SLP_EVAL +#define STACK_MAGIC 0 +#define REG_SP "sp" +#define REG_SPSP "sp,sp" +#ifdef __thumb__ +#define REG_FP "r7" +#define REG_FPFP "r7,r7" +#define REGS_TO_SAVE_GENERAL "r4", "r5", "r6", "r8", "r9", "r10", "r11", "lr" +#else +#define REG_FP "fp" +#define REG_FPFP "fp,fp" +#define REGS_TO_SAVE_GENERAL "r4", "r5", "r6", "r7", "r8", "r9", "r10", "lr" +#endif +#if defined(__SOFTFP__) +#define REGS_TO_SAVE REGS_TO_SAVE_GENERAL +#elif defined(__VFP_FP__) +#define REGS_TO_SAVE REGS_TO_SAVE_GENERAL, "d8", "d9", "d10", "d11", \ + "d12", "d13", "d14", "d15" +#elif defined(__MAVERICK__) +#define REGS_TO_SAVE REGS_TO_SAVE_GENERAL, "mvf4", "mvf5", "mvf6", "mvf7", \ + "mvf8", "mvf9", "mvf10", "mvf11", \ + "mvf12", "mvf13", "mvf14", "mvf15" +#else +#define REGS_TO_SAVE REGS_TO_SAVE_GENERAL, "f4", "f5", "f6", "f7" +#endif + +static int +#ifdef __GNUC__ +__attribute__((optimize("no-omit-frame-pointer"))) +#endif +slp_switch(void) +{ + void *fp; + int *stackref, stsizediff; + int result; + __asm__ volatile ("" : : : REGS_TO_SAVE); + __asm__ volatile ("mov r0," REG_FP "\n\tstr r0,%0" : "=m" (fp) : : "r0"); + __asm__ ("mov %0," REG_SP : "=r" (stackref)); + { + SLP_SAVE_STATE(stackref, stsizediff); + __asm__ volatile ( + "add " REG_SPSP ",%0\n" + "add " REG_FPFP ",%0\n" + : + : "r" (stsizediff) + ); + SLP_RESTORE_STATE(); + } + __asm__ volatile ("ldr r0,%1\n\tmov " REG_FP ",r0\n\tmov %0, #0" : "=r" (result) : "m" (fp) : "r0"); + __asm__ volatile ("" : : : REGS_TO_SAVE); + return result; +} + +#endif diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/platform/switch_arm32_ios.h b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/platform/switch_arm32_ios.h new file mode 100644 index 000000000..9e640e15f --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/platform/switch_arm32_ios.h @@ -0,0 +1,67 @@ +/* + * this is the internal transfer function. + * + * HISTORY + * 31-May-15 iOS support. Ported from arm32. Proton + * + * NOTES + * + * It is not possible to detect if fp is used or not, so the supplied + * switch function needs to support it, so that you can remove it if + * it does not apply to you. + * + * POSSIBLE ERRORS + * + * "fp cannot be used in asm here" + * + * - Try commenting out "fp" in REGS_TO_SAVE. + * + */ + +#define STACK_REFPLUS 1 + +#ifdef SLP_EVAL + +#define STACK_MAGIC 0 +#define REG_SP "sp" +#define REG_SPSP "sp,sp" +#define REG_FP "r7" +#define REG_FPFP "r7,r7" +#define REGS_TO_SAVE_GENERAL "r4", "r5", "r6", "r8", "r10", "r11", "lr" +#define REGS_TO_SAVE REGS_TO_SAVE_GENERAL, "d8", "d9", "d10", "d11", \ + "d12", "d13", "d14", "d15" + +static int +#ifdef __GNUC__ +__attribute__((optimize("no-omit-frame-pointer"))) +#endif +slp_switch(void) +{ + void *fp; + int *stackref, stsizediff, result; + __asm__ volatile ("" : : : REGS_TO_SAVE); + __asm__ volatile ("str " REG_FP ",%0" : "=m" (fp)); + __asm__ ("mov %0," REG_SP : "=r" (stackref)); + { + SLP_SAVE_STATE(stackref, stsizediff); + __asm__ volatile ( + "add " REG_SPSP ",%0\n" + "add " REG_FPFP ",%0\n" + : + : "r" (stsizediff) + : REGS_TO_SAVE /* Clobber registers, force compiler to + * recalculate address of void *fp from REG_SP or REG_FP */ + ); + SLP_RESTORE_STATE(); + } + __asm__ volatile ( + "ldr " REG_FP ", %1\n\t" + "mov %0, #0" + : "=r" (result) + : "m" (fp) + : REGS_TO_SAVE /* Force compiler to restore saved registers after this */ + ); + return result; +} + +#endif diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/platform/switch_arm64_masm.asm b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/platform/switch_arm64_masm.asm new file mode 100644 index 000000000..29f9c225e --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/platform/switch_arm64_masm.asm @@ -0,0 +1,53 @@ + AREA switch_arm64_masm, CODE, READONLY; + GLOBAL slp_switch [FUNC] + EXTERN slp_save_state_asm + EXTERN slp_restore_state_asm + +slp_switch + ; push callee saved registers to stack + stp x19, x20, [sp, #-16]! + stp x21, x22, [sp, #-16]! + stp x23, x24, [sp, #-16]! + stp x25, x26, [sp, #-16]! + stp x27, x28, [sp, #-16]! + stp x29, x30, [sp, #-16]! + stp d8, d9, [sp, #-16]! + stp d10, d11, [sp, #-16]! + stp d12, d13, [sp, #-16]! + stp d14, d15, [sp, #-16]! + + ; call slp_save_state_asm with stack pointer + mov x0, sp + bl slp_save_state_asm + + ; early return for return value of 1 and -1 + cmp x0, #-1 + b.eq RETURN + cmp x0, #1 + b.eq RETURN + + ; increment stack and frame pointer + add sp, sp, x0 + add x29, x29, x0 + + bl slp_restore_state_asm + + ; store return value for successful completion of routine + mov x0, #0 + +RETURN + ; pop registers from stack + ldp d14, d15, [sp], #16 + ldp d12, d13, [sp], #16 + ldp d10, d11, [sp], #16 + ldp d8, d9, [sp], #16 + ldp x29, x30, [sp], #16 + ldp x27, x28, [sp], #16 + ldp x25, x26, [sp], #16 + ldp x23, x24, [sp], #16 + ldp x21, x22, [sp], #16 + ldp x19, x20, [sp], #16 + + ret + + END diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/platform/switch_arm64_masm.obj b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/platform/switch_arm64_masm.obj new file mode 100644 index 000000000..f6f220e43 Binary files /dev/null and b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/platform/switch_arm64_masm.obj differ diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/platform/switch_arm64_msvc.h b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/platform/switch_arm64_msvc.h new file mode 100644 index 000000000..7ab7f45be --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/platform/switch_arm64_msvc.h @@ -0,0 +1,17 @@ +/* + * this is the internal transfer function. + * + * HISTORY + * 21-Oct-21 Niyas Sait + * First version to enable win/arm64 support. + */ + +#define STACK_REFPLUS 1 +#define STACK_MAGIC 0 + +/* Use the generic support for an external assembly language slp_switch function. */ +#define EXTERNAL_ASM + +#ifdef SLP_EVAL +/* This always uses the external masm assembly file. */ +#endif \ No newline at end of file diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/platform/switch_csky_gcc.h b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/platform/switch_csky_gcc.h new file mode 100644 index 000000000..ac469d3a0 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/platform/switch_csky_gcc.h @@ -0,0 +1,48 @@ +#ifdef SLP_EVAL +#define STACK_MAGIC 0 +#define REG_FP "r8" +#ifdef __CSKYABIV2__ +#define REGS_TO_SAVE_GENERAL "r4", "r5", "r6", "r7", "r9", "r10", "r11", "r15",\ + "r16", "r17", "r18", "r19", "r20", "r21", "r22",\ + "r23", "r24", "r25" + +#if defined (__CSKY_HARD_FLOAT__) || (__CSKY_VDSP__) +#define REGS_TO_SAVE REGS_TO_SAVE_GENERAL, "vr8", "vr9", "vr10", "vr11", "vr12",\ + "vr13", "vr14", "vr15" +#else +#define REGS_TO_SAVE REGS_TO_SAVE_GENERAL +#endif +#else +#define REGS_TO_SAVE "r9", "r10", "r11", "r12", "r13", "r15" +#endif + + +static int +#ifdef __GNUC__ +__attribute__((optimize("no-omit-frame-pointer"))) +#endif +slp_switch(void) +{ + int *stackref, stsizediff; + int result; + + __asm__ volatile ("" : : : REGS_TO_SAVE); + __asm__ ("mov %0, sp" : "=r" (stackref)); + { + SLP_SAVE_STATE(stackref, stsizediff); + __asm__ volatile ( + "addu sp,%0\n" + "addu "REG_FP",%0\n" + : + : "r" (stsizediff) + ); + + SLP_RESTORE_STATE(); + } + __asm__ volatile ("movi %0, 0" : "=r" (result)); + __asm__ volatile ("" : : : REGS_TO_SAVE); + + return result; +} + +#endif diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/platform/switch_loongarch64_linux.h b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/platform/switch_loongarch64_linux.h new file mode 100644 index 000000000..9eaf34ef4 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/platform/switch_loongarch64_linux.h @@ -0,0 +1,31 @@ +#define STACK_REFPLUS 1 + +#ifdef SLP_EVAL +#define STACK_MAGIC 0 + +#define REGS_TO_SAVE "s0", "s1", "s2", "s3", "s4", "s5", \ + "s6", "s7", "s8", "fp", \ + "f24", "f25", "f26", "f27", "f28", "f29", "f30", "f31" + +static int +slp_switch(void) +{ + int ret; + long *stackref, stsizediff; + __asm__ volatile ("" : : : REGS_TO_SAVE); + __asm__ volatile ("move %0, $sp" : "=r" (stackref) : ); + { + SLP_SAVE_STATE(stackref, stsizediff); + __asm__ volatile ( + "add.d $sp, $sp, %0\n\t" + : /* no outputs */ + : "r" (stsizediff) + ); + SLP_RESTORE_STATE(); + } + __asm__ volatile ("" : : : REGS_TO_SAVE); + __asm__ volatile ("move %0, $zero" : "=r" (ret) : ); + return ret; +} + +#endif diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/platform/switch_m68k_gcc.h b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/platform/switch_m68k_gcc.h new file mode 100644 index 000000000..da761c2da --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/platform/switch_m68k_gcc.h @@ -0,0 +1,38 @@ +/* + * this is the internal transfer function. + * + * HISTORY + * 2014-01-06 Andreas Schwab + * File created. + */ + +#ifdef SLP_EVAL + +#define STACK_MAGIC 0 + +#define REGS_TO_SAVE "%d2", "%d3", "%d4", "%d5", "%d6", "%d7", \ + "%a2", "%a3", "%a4" + +static int +slp_switch(void) +{ + int err; + int *stackref, stsizediff; + void *fp, *a5; + __asm__ volatile ("" : : : REGS_TO_SAVE); + __asm__ volatile ("move.l %%fp, %0" : "=m"(fp)); + __asm__ volatile ("move.l %%a5, %0" : "=m"(a5)); + __asm__ ("move.l %%sp, %0" : "=r"(stackref)); + { + SLP_SAVE_STATE(stackref, stsizediff); + __asm__ volatile ("add.l %0, %%sp; add.l %0, %%fp" : : "r"(stsizediff)); + SLP_RESTORE_STATE(); + __asm__ volatile ("clr.l %0" : "=g" (err)); + } + __asm__ volatile ("move.l %0, %%a5" : : "m"(a5)); + __asm__ volatile ("move.l %0, %%fp" : : "m"(fp)); + __asm__ volatile ("" : : : REGS_TO_SAVE); + return err; +} + +#endif diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/platform/switch_mips_unix.h b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/platform/switch_mips_unix.h new file mode 100644 index 000000000..50e70c45b --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/platform/switch_mips_unix.h @@ -0,0 +1,65 @@ +/* + * this is the internal transfer function. + * + * HISTORY + * 20-Sep-14 Matt Madison + * Re-code the saving of the gp register for MIPS64. + * 05-Jan-08 Thiemo Seufer + * Ported from ppc. + */ + +#define STACK_REFPLUS 1 + +#ifdef SLP_EVAL + +#define STACK_MAGIC 0 + +#define REGS_TO_SAVE "$16", "$17", "$18", "$19", "$20", "$21", "$22", \ + "$23", "$30" +__attribute__((nomips16)) +static int +slp_switch(void) +{ + int err; + int *stackref, stsizediff; +#ifdef __mips64 + uint64_t gpsave; +#endif + __asm__ __volatile__ ("" : : : REGS_TO_SAVE); +#ifdef __mips64 + __asm__ __volatile__ ("sd $28,%0" : "=m" (gpsave) : : ); +#endif + __asm__ ("move %0, $29" : "=r" (stackref) : ); + { + SLP_SAVE_STATE(stackref, stsizediff); + __asm__ __volatile__ ( +#ifdef __mips64 + "daddu $29, $29, %0\n" +#else + "addu $29, $29, %0\n" +#endif + : /* no outputs */ + : "r" (stsizediff) + ); + SLP_RESTORE_STATE(); + } +#ifdef __mips64 + __asm__ __volatile__ ("ld $28,%0" : : "m" (gpsave) : ); +#endif + __asm__ __volatile__ ("" : : : REGS_TO_SAVE); + __asm__ __volatile__ ("move %0, $0" : "=r" (err)); + return err; +} + +#endif + +/* + * further self-processing support + */ + +/* + * if you want to add self-inspection tools, place them + * here. See the x86_msvc for the necessary defines. + * These features are highly experimental und not + * essential yet. + */ diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/platform/switch_ppc64_aix.h b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/platform/switch_ppc64_aix.h new file mode 100644 index 000000000..e7e0b8776 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/platform/switch_ppc64_aix.h @@ -0,0 +1,103 @@ +/* + * this is the internal transfer function. + * + * HISTORY + * 16-Oct-20 Jesse Gorzinski + * Copied from Linux PPC64 implementation + * 04-Sep-18 Alexey Borzenkov + * Workaround a gcc bug using manual save/restore of r30 + * 21-Mar-18 Tulio Magno Quites Machado Filho + * Added r30 to the list of saved registers in order to fully comply with + * both ppc64 ELFv1 ABI and the ppc64le ELFv2 ABI, that classify this + * register as a nonvolatile register used for local variables. + * 21-Mar-18 Laszlo Boszormenyi + * Save r2 (TOC pointer) manually. + * 10-Dec-13 Ulrich Weigand + * Support ELFv2 ABI. Save float/vector registers. + * 09-Mar-12 Michael Ellerman + * 64-bit implementation, copied from 32-bit. + * 07-Sep-05 (py-dev mailing list discussion) + * removed 'r31' from the register-saved. !!!! WARNING !!!! + * It means that this file can no longer be compiled statically! + * It is now only suitable as part of a dynamic library! + * 14-Jan-04 Bob Ippolito + * added cr2-cr4 to the registers to be saved. + * Open questions: Should we save FP registers? + * What about vector registers? + * Differences between darwin and unix? + * 24-Nov-02 Christian Tismer + * needed to add another magic constant to insure + * that f in slp_eval_frame(PyFrameObject *f) + * STACK_REFPLUS will probably be 1 in most cases. + * gets included into the saved stack area. + * 04-Oct-02 Gustavo Niemeyer + * Ported from MacOS version. + * 17-Sep-02 Christian Tismer + * after virtualizing stack save/restore, the + * stack size shrunk a bit. Needed to introduce + * an adjustment STACK_MAGIC per platform. + * 15-Sep-02 Gerd Woetzel + * slightly changed framework for sparc + * 29-Jun-02 Christian Tismer + * Added register 13-29, 31 saves. The same way as + * Armin Rigo did for the x86_unix version. + * This seems to be now fully functional! + * 04-Mar-02 Hye-Shik Chang + * Ported from i386. + * 31-Jul-12 Trevor Bowen + * Changed memory constraints to register only. + */ + +#define STACK_REFPLUS 1 + +#ifdef SLP_EVAL + +#define STACK_MAGIC 6 + +#if defined(__ALTIVEC__) +#define ALTIVEC_REGS \ + "v20", "v21", "v22", "v23", "v24", "v25", "v26", "v27", \ + "v28", "v29", "v30", "v31", +#else +#define ALTIVEC_REGS +#endif + +#define REGS_TO_SAVE "r14", "r15", "r16", "r17", "r18", "r19", "r20", \ + "r21", "r22", "r23", "r24", "r25", "r26", "r27", "r28", "r29", \ + "r31", \ + "fr14", "fr15", "fr16", "fr17", "fr18", "fr19", "fr20", "fr21", \ + "fr22", "fr23", "fr24", "fr25", "fr26", "fr27", "fr28", "fr29", \ + "fr30", "fr31", \ + ALTIVEC_REGS \ + "cr2", "cr3", "cr4" + +static int +slp_switch(void) +{ + int err; + long *stackref, stsizediff; + void * toc; + void * r30; + __asm__ volatile ("" : : : REGS_TO_SAVE); + __asm__ volatile ("std 2, %0" : "=m" (toc)); + __asm__ volatile ("std 30, %0" : "=m" (r30)); + __asm__ ("mr %0, 1" : "=r" (stackref) : ); + { + SLP_SAVE_STATE(stackref, stsizediff); + __asm__ volatile ( + "mr 11, %0\n" + "add 1, 1, 11\n" + : /* no outputs */ + : "r" (stsizediff) + : "11" + ); + SLP_RESTORE_STATE(); + } + __asm__ volatile ("ld 30, %0" : : "m" (r30)); + __asm__ volatile ("ld 2, %0" : : "m" (toc)); + __asm__ volatile ("" : : : REGS_TO_SAVE); + __asm__ volatile ("li %0, 0" : "=r" (err)); + return err; +} + +#endif diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/platform/switch_ppc64_linux.h b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/platform/switch_ppc64_linux.h new file mode 100644 index 000000000..3c324d00c --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/platform/switch_ppc64_linux.h @@ -0,0 +1,105 @@ +/* + * this is the internal transfer function. + * + * HISTORY + * 04-Sep-18 Alexey Borzenkov + * Workaround a gcc bug using manual save/restore of r30 + * 21-Mar-18 Tulio Magno Quites Machado Filho + * Added r30 to the list of saved registers in order to fully comply with + * both ppc64 ELFv1 ABI and the ppc64le ELFv2 ABI, that classify this + * register as a nonvolatile register used for local variables. + * 21-Mar-18 Laszlo Boszormenyi + * Save r2 (TOC pointer) manually. + * 10-Dec-13 Ulrich Weigand + * Support ELFv2 ABI. Save float/vector registers. + * 09-Mar-12 Michael Ellerman + * 64-bit implementation, copied from 32-bit. + * 07-Sep-05 (py-dev mailing list discussion) + * removed 'r31' from the register-saved. !!!! WARNING !!!! + * It means that this file can no longer be compiled statically! + * It is now only suitable as part of a dynamic library! + * 14-Jan-04 Bob Ippolito + * added cr2-cr4 to the registers to be saved. + * Open questions: Should we save FP registers? + * What about vector registers? + * Differences between darwin and unix? + * 24-Nov-02 Christian Tismer + * needed to add another magic constant to insure + * that f in slp_eval_frame(PyFrameObject *f) + * STACK_REFPLUS will probably be 1 in most cases. + * gets included into the saved stack area. + * 04-Oct-02 Gustavo Niemeyer + * Ported from MacOS version. + * 17-Sep-02 Christian Tismer + * after virtualizing stack save/restore, the + * stack size shrunk a bit. Needed to introduce + * an adjustment STACK_MAGIC per platform. + * 15-Sep-02 Gerd Woetzel + * slightly changed framework for sparc + * 29-Jun-02 Christian Tismer + * Added register 13-29, 31 saves. The same way as + * Armin Rigo did for the x86_unix version. + * This seems to be now fully functional! + * 04-Mar-02 Hye-Shik Chang + * Ported from i386. + * 31-Jul-12 Trevor Bowen + * Changed memory constraints to register only. + */ + +#define STACK_REFPLUS 1 + +#ifdef SLP_EVAL + +#if _CALL_ELF == 2 +#define STACK_MAGIC 4 +#else +#define STACK_MAGIC 6 +#endif + +#if defined(__ALTIVEC__) +#define ALTIVEC_REGS \ + "v20", "v21", "v22", "v23", "v24", "v25", "v26", "v27", \ + "v28", "v29", "v30", "v31", +#else +#define ALTIVEC_REGS +#endif + +#define REGS_TO_SAVE "r14", "r15", "r16", "r17", "r18", "r19", "r20", \ + "r21", "r22", "r23", "r24", "r25", "r26", "r27", "r28", "r29", \ + "r31", \ + "fr14", "fr15", "fr16", "fr17", "fr18", "fr19", "fr20", "fr21", \ + "fr22", "fr23", "fr24", "fr25", "fr26", "fr27", "fr28", "fr29", \ + "fr30", "fr31", \ + ALTIVEC_REGS \ + "cr2", "cr3", "cr4" + +static int +slp_switch(void) +{ + int err; + long *stackref, stsizediff; + void * toc; + void * r30; + __asm__ volatile ("" : : : REGS_TO_SAVE); + __asm__ volatile ("std 2, %0" : "=m" (toc)); + __asm__ volatile ("std 30, %0" : "=m" (r30)); + __asm__ ("mr %0, 1" : "=r" (stackref) : ); + { + SLP_SAVE_STATE(stackref, stsizediff); + __asm__ volatile ( + "mr 11, %0\n" + "add 1, 1, 11\n" + : /* no outputs */ + : "r" (stsizediff) + : "11" + ); + SLP_RESTORE_STATE(); + } + __asm__ volatile ("ld 30, %0" : : "m" (r30)); + __asm__ volatile ("ld 2, %0" : : "m" (toc)); + __asm__ volatile ("" : : : REGS_TO_SAVE); + __asm__ volatile ("li %0, 0" : "=r" (err)); + return err; +} + +#endif diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/platform/switch_ppc_aix.h b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/platform/switch_ppc_aix.h new file mode 100644 index 000000000..6d93c1326 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/platform/switch_ppc_aix.h @@ -0,0 +1,87 @@ +/* + * this is the internal transfer function. + * + * HISTORY + * 07-Mar-11 Floris Bruynooghe + * Do not add stsizediff to general purpose + * register (GPR) 30 as this is a non-volatile and + * unused by the PowerOpen Environment, therefore + * this was modifying a user register instead of the + * frame pointer (which does not seem to exist). + * 07-Sep-05 (py-dev mailing list discussion) + * removed 'r31' from the register-saved. !!!! WARNING !!!! + * It means that this file can no longer be compiled statically! + * It is now only suitable as part of a dynamic library! + * 14-Jan-04 Bob Ippolito + * added cr2-cr4 to the registers to be saved. + * Open questions: Should we save FP registers? + * What about vector registers? + * Differences between darwin and unix? + * 24-Nov-02 Christian Tismer + * needed to add another magic constant to insure + * that f in slp_eval_frame(PyFrameObject *f) + * STACK_REFPLUS will probably be 1 in most cases. + * gets included into the saved stack area. + * 04-Oct-02 Gustavo Niemeyer + * Ported from MacOS version. + * 17-Sep-02 Christian Tismer + * after virtualizing stack save/restore, the + * stack size shrunk a bit. Needed to introduce + * an adjustment STACK_MAGIC per platform. + * 15-Sep-02 Gerd Woetzel + * slightly changed framework for sparc + * 29-Jun-02 Christian Tismer + * Added register 13-29, 31 saves. The same way as + * Armin Rigo did for the x86_unix version. + * This seems to be now fully functional! + * 04-Mar-02 Hye-Shik Chang + * Ported from i386. + */ + +#define STACK_REFPLUS 1 + +#ifdef SLP_EVAL + +#define STACK_MAGIC 3 + +/* !!!!WARNING!!!! need to add "r31" in the next line if this header file + * is meant to be compiled non-dynamically! + */ +#define REGS_TO_SAVE "r13", "r14", "r15", "r16", "r17", "r18", "r19", "r20", \ + "r21", "r22", "r23", "r24", "r25", "r26", "r27", "r28", "r29", \ + "cr2", "cr3", "cr4" +static int +slp_switch(void) +{ + int err; + int *stackref, stsizediff; + __asm__ volatile ("" : : : REGS_TO_SAVE); + __asm__ ("mr %0, 1" : "=r" (stackref) : ); + { + SLP_SAVE_STATE(stackref, stsizediff); + __asm__ volatile ( + "mr 11, %0\n" + "add 1, 1, 11\n" + : /* no outputs */ + : "r" (stsizediff) + : "11" + ); + SLP_RESTORE_STATE(); + } + __asm__ volatile ("" : : : REGS_TO_SAVE); + __asm__ volatile ("li %0, 0" : "=r" (err)); + return err; +} + +#endif + +/* + * further self-processing support + */ + +/* + * if you want to add self-inspection tools, place them + * here. See the x86_msvc for the necessary defines. + * These features are highly experimental und not + * essential yet. + */ diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/platform/switch_ppc_linux.h b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/platform/switch_ppc_linux.h new file mode 100644 index 000000000..e83ad70a5 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/platform/switch_ppc_linux.h @@ -0,0 +1,84 @@ +/* + * this is the internal transfer function. + * + * HISTORY + * 07-Sep-05 (py-dev mailing list discussion) + * removed 'r31' from the register-saved. !!!! WARNING !!!! + * It means that this file can no longer be compiled statically! + * It is now only suitable as part of a dynamic library! + * 14-Jan-04 Bob Ippolito + * added cr2-cr4 to the registers to be saved. + * Open questions: Should we save FP registers? + * What about vector registers? + * Differences between darwin and unix? + * 24-Nov-02 Christian Tismer + * needed to add another magic constant to insure + * that f in slp_eval_frame(PyFrameObject *f) + * STACK_REFPLUS will probably be 1 in most cases. + * gets included into the saved stack area. + * 04-Oct-02 Gustavo Niemeyer + * Ported from MacOS version. + * 17-Sep-02 Christian Tismer + * after virtualizing stack save/restore, the + * stack size shrunk a bit. Needed to introduce + * an adjustment STACK_MAGIC per platform. + * 15-Sep-02 Gerd Woetzel + * slightly changed framework for sparc + * 29-Jun-02 Christian Tismer + * Added register 13-29, 31 saves. The same way as + * Armin Rigo did for the x86_unix version. + * This seems to be now fully functional! + * 04-Mar-02 Hye-Shik Chang + * Ported from i386. + * 31-Jul-12 Trevor Bowen + * Changed memory constraints to register only. + */ + +#define STACK_REFPLUS 1 + +#ifdef SLP_EVAL + +#define STACK_MAGIC 3 + +/* !!!!WARNING!!!! need to add "r31" in the next line if this header file + * is meant to be compiled non-dynamically! + */ +#define REGS_TO_SAVE "r13", "r14", "r15", "r16", "r17", "r18", "r19", "r20", \ + "r21", "r22", "r23", "r24", "r25", "r26", "r27", "r28", "r29", \ + "cr2", "cr3", "cr4" +static int +slp_switch(void) +{ + int err; + int *stackref, stsizediff; + __asm__ volatile ("" : : : REGS_TO_SAVE); + __asm__ ("mr %0, 1" : "=r" (stackref) : ); + { + SLP_SAVE_STATE(stackref, stsizediff); + __asm__ volatile ( + "mr 11, %0\n" + "add 1, 1, 11\n" + "add 30, 30, 11\n" + : /* no outputs */ + : "r" (stsizediff) + : "11" + ); + SLP_RESTORE_STATE(); + } + __asm__ volatile ("" : : : REGS_TO_SAVE); + __asm__ volatile ("li %0, 0" : "=r" (err)); + return err; +} + +#endif + +/* + * further self-processing support + */ + +/* + * if you want to add self-inspection tools, place them + * here. See the x86_msvc for the necessary defines. + * These features are highly experimental und not + * essential yet. + */ diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/platform/switch_ppc_macosx.h b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/platform/switch_ppc_macosx.h new file mode 100644 index 000000000..bd414c68e --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/platform/switch_ppc_macosx.h @@ -0,0 +1,82 @@ +/* + * this is the internal transfer function. + * + * HISTORY + * 07-Sep-05 (py-dev mailing list discussion) + * removed 'r31' from the register-saved. !!!! WARNING !!!! + * It means that this file can no longer be compiled statically! + * It is now only suitable as part of a dynamic library! + * 14-Jan-04 Bob Ippolito + * added cr2-cr4 to the registers to be saved. + * Open questions: Should we save FP registers? + * What about vector registers? + * Differences between darwin and unix? + * 24-Nov-02 Christian Tismer + * needed to add another magic constant to insure + * that f in slp_eval_frame(PyFrameObject *f) + * STACK_REFPLUS will probably be 1 in most cases. + * gets included into the saved stack area. + * 17-Sep-02 Christian Tismer + * after virtualizing stack save/restore, the + * stack size shrunk a bit. Needed to introduce + * an adjustment STACK_MAGIC per platform. + * 15-Sep-02 Gerd Woetzel + * slightly changed framework for sparc + * 29-Jun-02 Christian Tismer + * Added register 13-29, 31 saves. The same way as + * Armin Rigo did for the x86_unix version. + * This seems to be now fully functional! + * 04-Mar-02 Hye-Shik Chang + * Ported from i386. + */ + +#define STACK_REFPLUS 1 + +#ifdef SLP_EVAL + +#define STACK_MAGIC 3 + +/* !!!!WARNING!!!! need to add "r31" in the next line if this header file + * is meant to be compiled non-dynamically! + */ +#define REGS_TO_SAVE "r13", "r14", "r15", "r16", "r17", "r18", "r19", "r20", \ + "r21", "r22", "r23", "r24", "r25", "r26", "r27", "r28", "r29", \ + "cr2", "cr3", "cr4" + +static int +slp_switch(void) +{ + int err; + int *stackref, stsizediff; + __asm__ volatile ("" : : : REGS_TO_SAVE); + __asm__ ("; asm block 2\n\tmr %0, r1" : "=r" (stackref) : ); + { + SLP_SAVE_STATE(stackref, stsizediff); + __asm__ volatile ( + "; asm block 3\n" + "\tmr r11, %0\n" + "\tadd r1, r1, r11\n" + "\tadd r30, r30, r11\n" + : /* no outputs */ + : "r" (stsizediff) + : "r11" + ); + SLP_RESTORE_STATE(); + } + __asm__ volatile ("" : : : REGS_TO_SAVE); + __asm__ volatile ("li %0, 0" : "=r" (err)); + return err; +} + +#endif + +/* + * further self-processing support + */ + +/* + * if you want to add self-inspection tools, place them + * here. See the x86_msvc for the necessary defines. + * These features are highly experimental und not + * essential yet. + */ diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/platform/switch_ppc_unix.h b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/platform/switch_ppc_unix.h new file mode 100644 index 000000000..bb188080a --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/platform/switch_ppc_unix.h @@ -0,0 +1,82 @@ +/* + * this is the internal transfer function. + * + * HISTORY + * 07-Sep-05 (py-dev mailing list discussion) + * removed 'r31' from the register-saved. !!!! WARNING !!!! + * It means that this file can no longer be compiled statically! + * It is now only suitable as part of a dynamic library! + * 14-Jan-04 Bob Ippolito + * added cr2-cr4 to the registers to be saved. + * Open questions: Should we save FP registers? + * What about vector registers? + * Differences between darwin and unix? + * 24-Nov-02 Christian Tismer + * needed to add another magic constant to insure + * that f in slp_eval_frame(PyFrameObject *f) + * STACK_REFPLUS will probably be 1 in most cases. + * gets included into the saved stack area. + * 04-Oct-02 Gustavo Niemeyer + * Ported from MacOS version. + * 17-Sep-02 Christian Tismer + * after virtualizing stack save/restore, the + * stack size shrunk a bit. Needed to introduce + * an adjustment STACK_MAGIC per platform. + * 15-Sep-02 Gerd Woetzel + * slightly changed framework for sparc + * 29-Jun-02 Christian Tismer + * Added register 13-29, 31 saves. The same way as + * Armin Rigo did for the x86_unix version. + * This seems to be now fully functional! + * 04-Mar-02 Hye-Shik Chang + * Ported from i386. + */ + +#define STACK_REFPLUS 1 + +#ifdef SLP_EVAL + +#define STACK_MAGIC 3 + +/* !!!!WARNING!!!! need to add "r31" in the next line if this header file + * is meant to be compiled non-dynamically! + */ +#define REGS_TO_SAVE "r13", "r14", "r15", "r16", "r17", "r18", "r19", "r20", \ + "r21", "r22", "r23", "r24", "r25", "r26", "r27", "r28", "r29", \ + "cr2", "cr3", "cr4" +static int +slp_switch(void) +{ + int err; + int *stackref, stsizediff; + __asm__ volatile ("" : : : REGS_TO_SAVE); + __asm__ ("mr %0, 1" : "=r" (stackref) : ); + { + SLP_SAVE_STATE(stackref, stsizediff); + __asm__ volatile ( + "mr 11, %0\n" + "add 1, 1, 11\n" + "add 30, 30, 11\n" + : /* no outputs */ + : "r" (stsizediff) + : "11" + ); + SLP_RESTORE_STATE(); + } + __asm__ volatile ("" : : : REGS_TO_SAVE); + __asm__ volatile ("li %0, 0" : "=r" (err)); + return err; +} + +#endif + +/* + * further self-processing support + */ + +/* + * if you want to add self-inspection tools, place them + * here. See the x86_msvc for the necessary defines. + * These features are highly experimental und not + * essential yet. + */ diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/platform/switch_riscv_unix.h b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/platform/switch_riscv_unix.h new file mode 100644 index 000000000..876112223 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/platform/switch_riscv_unix.h @@ -0,0 +1,41 @@ +#define STACK_REFPLUS 1 + +#ifdef SLP_EVAL +#define STACK_MAGIC 0 + +#define REGS_TO_SAVE "s1", "s2", "s3", "s4", "s5", \ + "s6", "s7", "s8", "s9", "s10", "s11", "fs0", "fs1", \ + "fs2", "fs3", "fs4", "fs5", "fs6", "fs7", "fs8", "fs9", \ + "fs10", "fs11" + +static int +slp_switch(void) +{ + int ret; + long fp; + long *stackref, stsizediff; + + __asm__ volatile ("" : : : REGS_TO_SAVE); + __asm__ volatile ("mv %0, fp" : "=r" (fp) : ); + __asm__ volatile ("mv %0, sp" : "=r" (stackref) : ); + { + SLP_SAVE_STATE(stackref, stsizediff); + __asm__ volatile ( + "add sp, sp, %0\n\t" + "add fp, fp, %0\n\t" + : /* no outputs */ + : "r" (stsizediff) + ); + SLP_RESTORE_STATE(); + } + __asm__ volatile ("" : : : REGS_TO_SAVE); +#if __riscv_xlen == 32 + __asm__ volatile ("lw fp, %0" : : "m" (fp)); +#else + __asm__ volatile ("ld fp, %0" : : "m" (fp)); +#endif + __asm__ volatile ("mv %0, zero" : "=r" (ret) : ); + return ret; +} + +#endif diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/platform/switch_s390_unix.h b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/platform/switch_s390_unix.h new file mode 100644 index 000000000..9199367f8 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/platform/switch_s390_unix.h @@ -0,0 +1,87 @@ +/* + * this is the internal transfer function. + * + * HISTORY + * 25-Jan-12 Alexey Borzenkov + * Fixed Linux/S390 port to work correctly with + * different optimization options both on 31-bit + * and 64-bit. Thanks to Stefan Raabe for lots + * of testing. + * 24-Nov-02 Christian Tismer + * needed to add another magic constant to insure + * that f in slp_eval_frame(PyFrameObject *f) + * STACK_REFPLUS will probably be 1 in most cases. + * gets included into the saved stack area. + * 06-Oct-02 Gustavo Niemeyer + * Ported to Linux/S390. + */ + +#define STACK_REFPLUS 1 + +#ifdef SLP_EVAL + +#ifdef __s390x__ +#define STACK_MAGIC 20 /* 20 * 8 = 160 bytes of function call area */ +#else +#define STACK_MAGIC 24 /* 24 * 4 = 96 bytes of function call area */ +#endif + +/* Technically, r11-r13 also need saving, but function prolog starts + with stm(g) and since there are so many saved registers already + it won't be optimized, resulting in all r6-r15 being saved */ +#define REGS_TO_SAVE "r6", "r7", "r8", "r9", "r10", "r14", \ + "f0", "f1", "f2", "f3", "f4", "f5", "f6", "f7", \ + "f8", "f9", "f10", "f11", "f12", "f13", "f14", "f15" + +static int +slp_switch(void) +{ + int ret; + long *stackref, stsizediff; + __asm__ volatile ("" : : : REGS_TO_SAVE); +#ifdef __s390x__ + __asm__ volatile ("lgr %0, 15" : "=r" (stackref) : ); +#else + __asm__ volatile ("lr %0, 15" : "=r" (stackref) : ); +#endif + { + SLP_SAVE_STATE(stackref, stsizediff); +/* N.B. + r11 may be used as the frame pointer, and in that case it cannot be + clobbered and needs offsetting just like the stack pointer (but in cases + where frame pointer isn't used we might clobber it accidentally). What's + scary is that r11 is 2nd (and even 1st when GOT is used) callee saved + register that gcc would chose for surviving function calls. However, + since r6-r10 are clobbered above, their cost for reuse is reduced, so + gcc IRA will chose them over r11 (not seeing r11 is implicitly saved), + making it relatively safe to offset in all cases. :) */ + __asm__ volatile ( +#ifdef __s390x__ + "agr 15, %0\n\t" + "agr 11, %0" +#else + "ar 15, %0\n\t" + "ar 11, %0" +#endif + : /* no outputs */ + : "r" (stsizediff) + ); + SLP_RESTORE_STATE(); + } + __asm__ volatile ("" : : : REGS_TO_SAVE); + __asm__ volatile ("lhi %0, 0" : "=r" (ret) : ); + return ret; +} + +#endif + +/* + * further self-processing support + */ + +/* + * if you want to add self-inspection tools, place them + * here. See the x86_msvc for the necessary defines. + * These features are highly experimental und not + * essential yet. + */ diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/platform/switch_sh_gcc.h b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/platform/switch_sh_gcc.h new file mode 100644 index 000000000..5ecc3b394 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/platform/switch_sh_gcc.h @@ -0,0 +1,36 @@ +#define STACK_REFPLUS 1 + +#ifdef SLP_EVAL +#define STACK_MAGIC 0 +#define REGS_TO_SAVE "r8", "r9", "r10", "r11", "r13", \ + "fr12", "fr13", "fr14", "fr15" + +// r12 Global context pointer, GP +// r14 Frame pointer, FP +// r15 Stack pointer, SP + +static int +slp_switch(void) +{ + int err; + void* fp; + int *stackref, stsizediff; + __asm__ volatile("" : : : REGS_TO_SAVE); + __asm__ volatile("mov.l r14, %0" : "=m"(fp) : :); + __asm__("mov r15, %0" : "=r"(stackref)); + { + SLP_SAVE_STATE(stackref, stsizediff); + __asm__ volatile( + "add %0, r15\n" + "add %0, r14\n" + : /* no outputs */ + : "r"(stsizediff)); + SLP_RESTORE_STATE(); + __asm__ volatile("mov r0, %0" : "=r"(err) : :); + } + __asm__ volatile("mov.l %0, r14" : : "m"(fp) :); + __asm__ volatile("" : : : REGS_TO_SAVE); + return err; +} + +#endif diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/platform/switch_sparc_sun_gcc.h b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/platform/switch_sparc_sun_gcc.h new file mode 100644 index 000000000..96990c391 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/platform/switch_sparc_sun_gcc.h @@ -0,0 +1,92 @@ +/* + * this is the internal transfer function. + * + * HISTORY + * 16-May-15 Alexey Borzenkov + * Move stack spilling code inside save/restore functions + * 30-Aug-13 Floris Bruynooghe + Clean the register windows again before returning. + This does not clobber the PIC register as it leaves + the current window intact and is required for multi- + threaded code to work correctly. + * 08-Mar-11 Floris Bruynooghe + * No need to set return value register explicitly + * before the stack and framepointer are adjusted + * as none of the other registers are influenced by + * this. Also don't needlessly clean the windows + * ('ta %0" :: "i" (ST_CLEAN_WINDOWS)') as that + * clobbers the gcc PIC register (%l7). + * 24-Nov-02 Christian Tismer + * needed to add another magic constant to insure + * that f in slp_eval_frame(PyFrameObject *f) + * STACK_REFPLUS will probably be 1 in most cases. + * gets included into the saved stack area. + * 17-Sep-02 Christian Tismer + * after virtualizing stack save/restore, the + * stack size shrunk a bit. Needed to introduce + * an adjustment STACK_MAGIC per platform. + * 15-Sep-02 Gerd Woetzel + * added support for SunOS sparc with gcc + */ + +#define STACK_REFPLUS 1 + +#ifdef SLP_EVAL + + +#define STACK_MAGIC 0 + + +#if defined(__sparcv9) +#define SLP_FLUSHW __asm__ volatile ("flushw") +#else +#define SLP_FLUSHW __asm__ volatile ("ta 3") /* ST_FLUSH_WINDOWS */ +#endif + +/* On sparc we need to spill register windows inside save/restore functions */ +#define SLP_BEFORE_SAVE_STATE() SLP_FLUSHW +#define SLP_BEFORE_RESTORE_STATE() SLP_FLUSHW + + +static int +slp_switch(void) +{ + int err; + int *stackref, stsizediff; + + /* Put current stack pointer into stackref. + * Register spilling is done in save/restore. + */ + __asm__ volatile ("mov %%sp, %0" : "=r" (stackref)); + + { + /* Thou shalt put SLP_SAVE_STATE into a local block */ + /* Copy the current stack onto the heap */ + SLP_SAVE_STATE(stackref, stsizediff); + + /* Increment stack and frame pointer by stsizediff */ + __asm__ volatile ( + "add %0, %%sp, %%sp\n\t" + "add %0, %%fp, %%fp" + : : "r" (stsizediff)); + + /* Copy new stack from it's save store on the heap */ + SLP_RESTORE_STATE(); + + __asm__ volatile ("mov %1, %0" : "=r" (err) : "i" (0)); + return err; + } +} + +#endif + +/* + * further self-processing support + */ + +/* + * if you want to add self-inspection tools, place them + * here. See the x86_msvc for the necessary defines. + * These features are highly experimental und not + * essential yet. + */ diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/platform/switch_x32_unix.h b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/platform/switch_x32_unix.h new file mode 100644 index 000000000..893369c7a --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/platform/switch_x32_unix.h @@ -0,0 +1,63 @@ +/* + * this is the internal transfer function. + * + * HISTORY + * 17-Aug-12 Fantix King + * Ported from amd64. + */ + +#define STACK_REFPLUS 1 + +#ifdef SLP_EVAL + +#define STACK_MAGIC 0 + +#define REGS_TO_SAVE "r12", "r13", "r14", "r15" + + +static int +slp_switch(void) +{ + void* ebp; + void* ebx; + unsigned int csr; + unsigned short cw; + int err; + int *stackref, stsizediff; + __asm__ volatile ("" : : : REGS_TO_SAVE); + __asm__ volatile ("fstcw %0" : "=m" (cw)); + __asm__ volatile ("stmxcsr %0" : "=m" (csr)); + __asm__ volatile ("movl %%ebp, %0" : "=m" (ebp)); + __asm__ volatile ("movl %%ebx, %0" : "=m" (ebx)); + __asm__ ("movl %%esp, %0" : "=g" (stackref)); + { + SLP_SAVE_STATE(stackref, stsizediff); + __asm__ volatile ( + "addl %0, %%esp\n" + "addl %0, %%ebp\n" + : + : "r" (stsizediff) + ); + SLP_RESTORE_STATE(); + } + __asm__ volatile ("movl %0, %%ebx" : : "m" (ebx)); + __asm__ volatile ("movl %0, %%ebp" : : "m" (ebp)); + __asm__ volatile ("ldmxcsr %0" : : "m" (csr)); + __asm__ volatile ("fldcw %0" : : "m" (cw)); + __asm__ volatile ("" : : : REGS_TO_SAVE); + __asm__ volatile ("xorl %%eax, %%eax" : "=a" (err)); + return err; +} + +#endif + +/* + * further self-processing support + */ + +/* + * if you want to add self-inspection tools, place them + * here. See the x86_msvc for the necessary defines. + * These features are highly experimental und not + * essential yet. + */ diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/platform/switch_x64_masm.asm b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/platform/switch_x64_masm.asm new file mode 100644 index 000000000..f5c72a27d --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/platform/switch_x64_masm.asm @@ -0,0 +1,111 @@ +; +; stack switching code for MASM on x641 +; Kristjan Valur Jonsson, sept 2005 +; + + +;prototypes for our calls +slp_save_state_asm PROTO +slp_restore_state_asm PROTO + + +pushxmm MACRO reg + sub rsp, 16 + .allocstack 16 + movaps [rsp], reg ; faster than movups, but we must be aligned + ; .savexmm128 reg, offset (don't know what offset is, no documentation) +ENDM +popxmm MACRO reg + movaps reg, [rsp] ; faster than movups, but we must be aligned + add rsp, 16 +ENDM + +pushreg MACRO reg + push reg + .pushreg reg +ENDM +popreg MACRO reg + pop reg +ENDM + + +.code +slp_switch PROC FRAME + ;realign stack to 16 bytes after return address push, makes the following faster + sub rsp,8 + .allocstack 8 + + pushxmm xmm15 + pushxmm xmm14 + pushxmm xmm13 + pushxmm xmm12 + pushxmm xmm11 + pushxmm xmm10 + pushxmm xmm9 + pushxmm xmm8 + pushxmm xmm7 + pushxmm xmm6 + + pushreg r15 + pushreg r14 + pushreg r13 + pushreg r12 + + pushreg rbp + pushreg rbx + pushreg rdi + pushreg rsi + + sub rsp, 10h ;allocate the singlefunction argument (must be multiple of 16) + .allocstack 10h +.endprolog + + lea rcx, [rsp+10h] ;load stack base that we are saving + call slp_save_state_asm ;pass stackpointer, return offset in eax + cmp rax, 1 + je EXIT1 + cmp rax, -1 + je EXIT2 + ;actual stack switch: + add rsp, rax + call slp_restore_state_asm + xor rax, rax ;return 0 + +EXIT: + + add rsp, 10h + popreg rsi + popreg rdi + popreg rbx + popreg rbp + + popreg r12 + popreg r13 + popreg r14 + popreg r15 + + popxmm xmm6 + popxmm xmm7 + popxmm xmm8 + popxmm xmm9 + popxmm xmm10 + popxmm xmm11 + popxmm xmm12 + popxmm xmm13 + popxmm xmm14 + popxmm xmm15 + + add rsp, 8 + ret + +EXIT1: + mov rax, 1 + jmp EXIT + +EXIT2: + sar rax, 1 + jmp EXIT + +slp_switch ENDP + +END \ No newline at end of file diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/platform/switch_x64_masm.obj b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/platform/switch_x64_masm.obj new file mode 100644 index 000000000..64e3e6b89 Binary files /dev/null and b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/platform/switch_x64_masm.obj differ diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/platform/switch_x64_msvc.h b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/platform/switch_x64_msvc.h new file mode 100644 index 000000000..601ea5605 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/platform/switch_x64_msvc.h @@ -0,0 +1,60 @@ +/* + * this is the internal transfer function. + * + * HISTORY + * 24-Nov-02 Christian Tismer + * needed to add another magic constant to insure + * that f in slp_eval_frame(PyFrameObject *f) + * STACK_REFPLUS will probably be 1 in most cases. + * gets included into the saved stack area. + * 26-Sep-02 Christian Tismer + * again as a result of virtualized stack access, + * the compiler used less registers. Needed to + * explicit mention registers in order to get them saved. + * Thanks to Jeff Senn for pointing this out and help. + * 17-Sep-02 Christian Tismer + * after virtualizing stack save/restore, the + * stack size shrunk a bit. Needed to introduce + * an adjustment STACK_MAGIC per platform. + * 15-Sep-02 Gerd Woetzel + * slightly changed framework for sparc + * 01-Mar-02 Christian Tismer + * Initial final version after lots of iterations for i386. + */ + +/* Avoid alloca redefined warning on mingw64 */ +#ifndef alloca +#define alloca _alloca +#endif + +#define STACK_REFPLUS 1 +#define STACK_MAGIC 0 + +/* Use the generic support for an external assembly language slp_switch function. */ +#define EXTERNAL_ASM + +#ifdef SLP_EVAL +/* This always uses the external masm assembly file. */ +#endif + +/* + * further self-processing support + */ + +/* we have IsBadReadPtr available, so we can peek at objects */ +/* +#define STACKLESS_SPY + +#ifdef IMPLEMENT_STACKLESSMODULE +#include "Windows.h" +#define CANNOT_READ_MEM(p, bytes) IsBadReadPtr(p, bytes) + +static int IS_ON_STACK(void*p) +{ + int stackref; + intptr_t stackbase = ((intptr_t)&stackref) & 0xfffff000; + return (intptr_t)p >= stackbase && (intptr_t)p < stackbase + 0x00100000; +} + +#endif +*/ \ No newline at end of file diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/platform/switch_x86_msvc.h b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/platform/switch_x86_msvc.h new file mode 100644 index 000000000..0f3a59f52 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/platform/switch_x86_msvc.h @@ -0,0 +1,326 @@ +/* + * this is the internal transfer function. + * + * HISTORY + * 24-Nov-02 Christian Tismer + * needed to add another magic constant to insure + * that f in slp_eval_frame(PyFrameObject *f) + * STACK_REFPLUS will probably be 1 in most cases. + * gets included into the saved stack area. + * 26-Sep-02 Christian Tismer + * again as a result of virtualized stack access, + * the compiler used less registers. Needed to + * explicit mention registers in order to get them saved. + * Thanks to Jeff Senn for pointing this out and help. + * 17-Sep-02 Christian Tismer + * after virtualizing stack save/restore, the + * stack size shrunk a bit. Needed to introduce + * an adjustment STACK_MAGIC per platform. + * 15-Sep-02 Gerd Woetzel + * slightly changed framework for sparc + * 01-Mar-02 Christian Tismer + * Initial final version after lots of iterations for i386. + */ + +#define alloca _alloca + +#define STACK_REFPLUS 1 + +#ifdef SLP_EVAL + +#define STACK_MAGIC 0 + +/* Some magic to quell warnings and keep slp_switch() from crashing when built + with VC90. Disable global optimizations, and the warning: frame pointer + register 'ebp' modified by inline assembly code. + + We used to just disable global optimizations ("g") but upstream stackless + Python, as well as stackman, turn off all optimizations. + +References: +https://github.com/stackless-dev/stackman/blob/dbc72fe5207a2055e658c819fdeab9731dee78b9/stackman/platforms/switch_x86_msvc.h +https://github.com/stackless-dev/stackless/blob/main-slp/Stackless/platf/switch_x86_msvc.h +*/ +#define WIN32_LEAN_AND_MEAN +#include + +#pragma optimize("", off) /* so that autos are stored on the stack */ +#pragma warning(disable:4731) +#pragma warning(disable:4733) /* disable warning about modifying FS[0] */ + +/** + * Most modern compilers and environments handle C++ exceptions without any + * special help from us. MSVC on 32-bit windows is an exception. There, C++ + * exceptions are dealt with using Windows' Structured Exception Handling + * (SEH). + * + * SEH is implemented as a singly linked list of nodes. The + * head of this list is stored in the Thread Information Block, which itself + * is pointed to from the FS register. It's the first field in the structure, + * or offset 0, so we can access it using assembly FS:[0], or the compiler + * intrinsics and field offset information from the headers (as we do below). + * Somewhat unusually, the tail of the list doesn't have prev == NULL, it has + * prev == 0xFFFFFFFF. + * + * SEH was designed for C, and traditionally uses the MSVC compiler + * intrinsincs __try{}/__except{}. It is also utilized for C++ exceptions by + * MSVC; there, every throw of a C++ exception raises a SEH error with the + * ExceptionCode 0xE06D7363; the SEH handler list is then traversed to + * deal with the exception. + * + * If the SEH list is corrupt, then when a C++ exception is thrown the program + * will abruptly exit with exit code 1. This does not use std::terminate(), so + * std::set_terminate() is useless to debug this. + * + * The SEH list is closely tied to the call stack; entering a function that + * uses __try{} or most C++ functions will push a new handler onto the front + * of the list. Returning from the function will remove the handler. Saving + * and restoring the head node of the SEH list (FS:[0]) per-greenlet is NOT + * ENOUGH to make SEH or exceptions work. + * + * Stack switching breaks SEH because the call stack no longer necessarily + * matches the SEH list. For example, given greenlet A that switches to + * greenlet B, at the moment of entering greenlet B, we will have any SEH + * handlers from greenlet A on the SEH list; greenlet B can then add its own + * handlers to the SEH list. When greenlet B switches back to greenlet A, + * greenlet B's handlers would still be on the SEH stack, but when switch() + * returns control to greenlet A, we have replaced the contents of the stack + * in memory, so all the address that greenlet B added to the SEH list are now + * invalid: part of the call stack has been unwound, but the SEH list was out + * of sync with the call stack. The net effect is that exception handling + * stops working. + * + * Thus, when switching greenlets, we need to be sure that the SEH list + * matches the effective call stack, "cutting out" any handlers that were + * pushed by the greenlet that switched out and which are no longer valid. + * + * The easiest way to do this is to capture the SEH list at the time the main + * greenlet for a thread is created, and, when initially starting a greenlet, + * start a new SEH list for it, which contains nothing but the handler + * established for the new greenlet itself, with the tail being the handlers + * for the main greenlet. If we then save and restore the SEH per-greenlet, + * they won't interfere with each others SEH lists. (No greenlet can unwind + * the call stack past the handlers established by the main greenlet). + * + * By observation, a new thread starts with three SEH handlers on the list. By + * the time we get around to creating the main greenlet, though, there can be + * many more, established by transient calls that lead to the creation of the + * main greenlet. Therefore, 3 is a magic constant telling us when to perform + * the initial slice. + * + * All of this can be debugged using a vectored exception handler, which + * operates independently of the SEH handler list, and is called first. + * Walking the SEH list at key points can also be helpful. + * + * References: + * https://en.wikipedia.org/wiki/Win32_Thread_Information_Block + * https://devblogs.microsoft.com/oldnewthing/20100730-00/?p=13273 + * https://docs.microsoft.com/en-us/cpp/cpp/try-except-statement?view=msvc-160 + * https://docs.microsoft.com/en-us/cpp/cpp/structured-exception-handling-c-cpp?view=msvc-160 + * https://docs.microsoft.com/en-us/windows/win32/debug/structured-exception-handling + * https://docs.microsoft.com/en-us/windows/win32/debug/using-a-vectored-exception-handler + * https://bytepointer.com/resources/pietrek_crash_course_depths_of_win32_seh.htm + */ +#define GREENLET_NEEDS_EXCEPTION_STATE_SAVED + + +typedef struct _GExceptionRegistration { + struct _GExceptionRegistration* prev; + void* handler_f; +} GExceptionRegistration; + +static void +slp_set_exception_state(const void *const seh_state) +{ + // Because the stack from from which we do this is ALSO a handler, and + // that one we want to keep, we need to relink the current SEH handler + // frame to point to this one, cutting out the middle men, as it were. + // + // Entering a try block doesn't change the SEH frame, but entering a + // function containing a try block does. + GExceptionRegistration* current_seh_state = (GExceptionRegistration*)__readfsdword(FIELD_OFFSET(NT_TIB, ExceptionList)); + current_seh_state->prev = (GExceptionRegistration*)seh_state; +} + + +static GExceptionRegistration* +x86_slp_get_third_oldest_handler() +{ + GExceptionRegistration* a = NULL; /* Closest to the top */ + GExceptionRegistration* b = NULL; /* second */ + GExceptionRegistration* c = NULL; + GExceptionRegistration* seh_state = (GExceptionRegistration*)__readfsdword(FIELD_OFFSET(NT_TIB, ExceptionList)); + a = b = c = seh_state; + + while (seh_state && seh_state != (GExceptionRegistration*)0xFFFFFFFF) { + if ((void*)seh_state->prev < (void*)100) { + fprintf(stderr, "\tERROR: Broken SEH chain.\n"); + return NULL; + } + a = b; + b = c; + c = seh_state; + + seh_state = seh_state->prev; + } + return a ? a : (b ? b : c); +} + + +static void* +slp_get_exception_state() +{ + // XXX: There appear to be three SEH handlers on the stack already at the + // start of the thread. Is that a guarantee? Almost certainly not. Yet in + // all observed cases it has been three. This is consistent with + // faulthandler off or on, and optimizations off or on. It may not be + // consistent with other operating system versions, though: we only have + // CI on one or two versions (don't ask what there are). + // In theory we could capture the number of handlers on the chain when + // PyInit__greenlet is called: there are probably only the default + // handlers at that point (unless we're embedded and people have used + // __try/__except or a C++ handler)? + return x86_slp_get_third_oldest_handler(); +} + +static int +slp_switch(void) +{ + /* MASM syntax is typically reversed from other assemblers. + It is usually + */ + int *stackref, stsizediff; + /* store the structured exception state for this stack */ + DWORD seh_state = __readfsdword(FIELD_OFFSET(NT_TIB, ExceptionList)); + __asm mov stackref, esp; + /* modify EBX, ESI and EDI in order to get them preserved */ + __asm mov ebx, ebx; + __asm xchg esi, edi; + { + SLP_SAVE_STATE(stackref, stsizediff); + __asm { + mov eax, stsizediff + add esp, eax + add ebp, eax + } + SLP_RESTORE_STATE(); + } + __writefsdword(FIELD_OFFSET(NT_TIB, ExceptionList), seh_state); + return 0; +} + +/* re-enable ebp warning and global optimizations. */ +#pragma optimize("", on) +#pragma warning(default:4731) +#pragma warning(default:4733) /* disable warning about modifying FS[0] */ + + +#endif + +/* + * further self-processing support + */ + +/* we have IsBadReadPtr available, so we can peek at objects */ +#define STACKLESS_SPY + +#ifdef GREENLET_DEBUG + +#define CANNOT_READ_MEM(p, bytes) IsBadReadPtr(p, bytes) + +static int IS_ON_STACK(void*p) +{ + int stackref; + int stackbase = ((int)&stackref) & 0xfffff000; + return (int)p >= stackbase && (int)p < stackbase + 0x00100000; +} + +static void +x86_slp_show_seh_chain() +{ + GExceptionRegistration* seh_state = (GExceptionRegistration*)__readfsdword(FIELD_OFFSET(NT_TIB, ExceptionList)); + fprintf(stderr, "====== SEH Chain ======\n"); + while (seh_state && seh_state != (GExceptionRegistration*)0xFFFFFFFF) { + fprintf(stderr, "\tSEH_chain addr: %p handler: %p prev: %p\n", + seh_state, + seh_state->handler_f, seh_state->prev); + if ((void*)seh_state->prev < (void*)100) { + fprintf(stderr, "\tERROR: Broken chain.\n"); + break; + } + seh_state = seh_state->prev; + } + fprintf(stderr, "====== End SEH Chain ======\n"); + fflush(NULL); + return; +} + +//addVectoredExceptionHandler constants: +//CALL_FIRST means call this exception handler first; +//CALL_LAST means call this exception handler last +#define CALL_FIRST 1 +#define CALL_LAST 0 + +LONG WINAPI +GreenletVectorHandler(PEXCEPTION_POINTERS ExceptionInfo) +{ + // We get one of these for every C++ exception, with code + // E06D7363 + // This is a special value that means "C++ exception from MSVC" + // https://devblogs.microsoft.com/oldnewthing/20100730-00/?p=13273 + // + // Install in the module init function with: + // AddVectoredExceptionHandler(CALL_FIRST, GreenletVectorHandler); + PEXCEPTION_RECORD ExceptionRecord = ExceptionInfo->ExceptionRecord; + + fprintf(stderr, + "GOT VECTORED EXCEPTION:\n" + "\tExceptionCode : %p\n" + "\tExceptionFlags : %p\n" + "\tExceptionAddr : %p\n" + "\tNumberparams : %ld\n", + ExceptionRecord->ExceptionCode, + ExceptionRecord->ExceptionFlags, + ExceptionRecord->ExceptionAddress, + ExceptionRecord->NumberParameters + ); + if (ExceptionRecord->ExceptionFlags & 1) { + fprintf(stderr, "\t\tEH_NONCONTINUABLE\n" ); + } + if (ExceptionRecord->ExceptionFlags & 2) { + fprintf(stderr, "\t\tEH_UNWINDING\n" ); + } + if (ExceptionRecord->ExceptionFlags & 4) { + fprintf(stderr, "\t\tEH_EXIT_UNWIND\n" ); + } + if (ExceptionRecord->ExceptionFlags & 8) { + fprintf(stderr, "\t\tEH_STACK_INVALID\n" ); + } + if (ExceptionRecord->ExceptionFlags & 0x10) { + fprintf(stderr, "\t\tEH_NESTED_CALL\n" ); + } + if (ExceptionRecord->ExceptionFlags & 0x20) { + fprintf(stderr, "\t\tEH_TARGET_UNWIND\n" ); + } + if (ExceptionRecord->ExceptionFlags & 0x40) { + fprintf(stderr, "\t\tEH_COLLIDED_UNWIND\n" ); + } + fprintf(stderr, "\n"); + fflush(NULL); + for(DWORD i = 0; i < ExceptionRecord->NumberParameters; i++) { + fprintf(stderr, "\t\t\tParam %ld: %lX\n", i, ExceptionRecord->ExceptionInformation[i]); + } + + if (ExceptionRecord->NumberParameters == 3) { + fprintf(stderr, "\tAbout to traverse SEH chain\n"); + // C++ Exception records have 3 params. + x86_slp_show_seh_chain(); + } + + return EXCEPTION_CONTINUE_SEARCH; +} + + + + +#endif diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/platform/switch_x86_unix.h b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/platform/switch_x86_unix.h new file mode 100644 index 000000000..493fa6baa --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/platform/switch_x86_unix.h @@ -0,0 +1,105 @@ +/* + * this is the internal transfer function. + * + * HISTORY + * 3-May-13 Ralf Schmitt + * Add support for strange GCC caller-save decisions + * (ported from switch_aarch64_gcc.h) + * 19-Aug-11 Alexey Borzenkov + * Correctly save ebp, ebx and cw + * 07-Sep-05 (py-dev mailing list discussion) + * removed 'ebx' from the register-saved. !!!! WARNING !!!! + * It means that this file can no longer be compiled statically! + * It is now only suitable as part of a dynamic library! + * 24-Nov-02 Christian Tismer + * needed to add another magic constant to insure + * that f in slp_eval_frame(PyFrameObject *f) + * STACK_REFPLUS will probably be 1 in most cases. + * gets included into the saved stack area. + * 17-Sep-02 Christian Tismer + * after virtualizing stack save/restore, the + * stack size shrunk a bit. Needed to introduce + * an adjustment STACK_MAGIC per platform. + * 15-Sep-02 Gerd Woetzel + * slightly changed framework for spark + * 31-Avr-02 Armin Rigo + * Added ebx, esi and edi register-saves. + * 01-Mar-02 Samual M. Rushing + * Ported from i386. + */ + +#define STACK_REFPLUS 1 + +#ifdef SLP_EVAL + +/* #define STACK_MAGIC 3 */ +/* the above works fine with gcc 2.96, but 2.95.3 wants this */ +#define STACK_MAGIC 0 + +#if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 5) +# define ATTR_NOCLONE __attribute__((noclone)) +#else +# define ATTR_NOCLONE +#endif + +static int +slp_switch(void) +{ + int err; +#ifdef _WIN32 + void *seh; +#endif + void *ebp, *ebx; + unsigned short cw; + int *stackref, stsizediff; + __asm__ volatile ("" : : : "esi", "edi"); + __asm__ volatile ("fstcw %0" : "=m" (cw)); + __asm__ volatile ("movl %%ebp, %0" : "=m" (ebp)); + __asm__ volatile ("movl %%ebx, %0" : "=m" (ebx)); +#ifdef _WIN32 + __asm__ volatile ( + "movl %%fs:0x0, %%eax\n" + "movl %%eax, %0\n" + : "=m" (seh) + : + : "eax"); +#endif + __asm__ ("movl %%esp, %0" : "=g" (stackref)); + { + SLP_SAVE_STATE(stackref, stsizediff); + __asm__ volatile ( + "addl %0, %%esp\n" + "addl %0, %%ebp\n" + : + : "r" (stsizediff) + ); + SLP_RESTORE_STATE(); + __asm__ volatile ("xorl %%eax, %%eax" : "=a" (err)); + } +#ifdef _WIN32 + __asm__ volatile ( + "movl %0, %%eax\n" + "movl %%eax, %%fs:0x0\n" + : + : "m" (seh) + : "eax"); +#endif + __asm__ volatile ("movl %0, %%ebx" : : "m" (ebx)); + __asm__ volatile ("movl %0, %%ebp" : : "m" (ebp)); + __asm__ volatile ("fldcw %0" : : "m" (cw)); + __asm__ volatile ("" : : : "esi", "edi"); + return err; +} + +#endif + +/* + * further self-processing support + */ + +/* + * if you want to add self-inspection tools, place them + * here. See the x86_msvc for the necessary defines. + * These features are highly experimental und not + * essential yet. + */ diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/slp_platformselect.h b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/slp_platformselect.h new file mode 100644 index 000000000..d9b7d0a71 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/slp_platformselect.h @@ -0,0 +1,77 @@ +/* + * Platform Selection for Stackless Python + */ +#ifdef __cplusplus +extern "C" { +#endif + +#if defined(MS_WIN32) && !defined(MS_WIN64) && defined(_M_IX86) && defined(_MSC_VER) +# include "platform/switch_x86_msvc.h" /* MS Visual Studio on X86 */ +#elif defined(MS_WIN64) && defined(_M_X64) && defined(_MSC_VER) || defined(__MINGW64__) +# include "platform/switch_x64_msvc.h" /* MS Visual Studio on X64 */ +#elif defined(MS_WIN64) && defined(_M_ARM64) +# include "platform/switch_arm64_msvc.h" /* MS Visual Studio on ARM64 */ +#elif defined(__GNUC__) && defined(__amd64__) && defined(__ILP32__) +# include "platform/switch_x32_unix.h" /* gcc on amd64 with x32 ABI */ +#elif defined(__GNUC__) && defined(__amd64__) +# include "platform/switch_amd64_unix.h" /* gcc on amd64 */ +#elif defined(__GNUC__) && defined(__i386__) +# include "platform/switch_x86_unix.h" /* gcc on X86 */ +#elif defined(__GNUC__) && defined(__powerpc64__) && (defined(__linux__) || defined(__FreeBSD__)) +# include "platform/switch_ppc64_linux.h" /* gcc on PowerPC 64-bit */ +#elif defined(__GNUC__) && defined(__PPC__) && (defined(__linux__) || defined(__FreeBSD__)) +# include "platform/switch_ppc_linux.h" /* gcc on PowerPC */ +#elif defined(__GNUC__) && defined(__POWERPC__) && defined(__APPLE__) +# include "platform/switch_ppc_macosx.h" /* Apple MacOS X on 32-bit PowerPC */ +#elif defined(__GNUC__) && defined(__powerpc64__) && defined(_AIX) +# include "platform/switch_ppc64_aix.h" /* gcc on AIX/PowerPC 64-bit */ +#elif defined(__GNUC__) && defined(_ARCH_PPC) && defined(_AIX) +# include "platform/switch_ppc_aix.h" /* gcc on AIX/PowerPC */ +#elif defined(__GNUC__) && defined(__powerpc__) && defined(__NetBSD__) +#include "platform/switch_ppc_unix.h" /* gcc on NetBSD/powerpc */ +#elif defined(__GNUC__) && defined(sparc) +# include "platform/switch_sparc_sun_gcc.h" /* SunOS sparc with gcc */ +#elif defined(__GNUC__) && defined(__sparc__) +# include "platform/switch_sparc_sun_gcc.h" /* NetBSD sparc with gcc */ +#elif defined(__SUNPRO_C) && defined(sparc) && defined(sun) +# include "platform/switch_sparc_sun_gcc.h" /* SunStudio on amd64 */ +#elif defined(__SUNPRO_C) && defined(__amd64__) && defined(sun) +# include "platform/switch_amd64_unix.h" /* SunStudio on amd64 */ +#elif defined(__SUNPRO_C) && defined(__i386__) && defined(sun) +# include "platform/switch_x86_unix.h" /* SunStudio on x86 */ +#elif defined(__GNUC__) && defined(__s390__) && defined(__linux__) +# include "platform/switch_s390_unix.h" /* Linux/S390 */ +#elif defined(__GNUC__) && defined(__s390x__) && defined(__linux__) +# include "platform/switch_s390_unix.h" /* Linux/S390 zSeries (64-bit) */ +#elif defined(__GNUC__) && defined(__arm__) +# ifdef __APPLE__ +# include +# endif +# if TARGET_OS_IPHONE +# include "platform/switch_arm32_ios.h" /* iPhone OS on arm32 */ +# else +# include "platform/switch_arm32_gcc.h" /* gcc using arm32 */ +# endif +#elif defined(__GNUC__) && defined(__mips__) && defined(__linux__) +# include "platform/switch_mips_unix.h" /* Linux/MIPS */ +#elif defined(__GNUC__) && defined(__aarch64__) +# include "platform/switch_aarch64_gcc.h" /* Aarch64 ABI */ +#elif defined(__GNUC__) && defined(__mc68000__) +# include "platform/switch_m68k_gcc.h" /* gcc on m68k */ +#elif defined(__GNUC__) && defined(__csky__) +#include "platform/switch_csky_gcc.h" /* gcc on csky */ +# elif defined(__GNUC__) && defined(__riscv) +# include "platform/switch_riscv_unix.h" /* gcc on RISC-V */ +#elif defined(__GNUC__) && defined(__alpha__) +# include "platform/switch_alpha_unix.h" /* gcc on DEC Alpha */ +#elif defined(MS_WIN32) && defined(__llvm__) && defined(__aarch64__) +# include "platform/switch_aarch64_gcc.h" /* LLVM Aarch64 ABI for Windows */ +#elif defined(__GNUC__) && defined(__loongarch64) && defined(__linux__) +# include "platform/switch_loongarch64_linux.h" /* LoongArch64 */ +#elif defined(__GNUC__) && defined(__sh__) +# include "platform/switch_sh_gcc.h" /* SuperH */ +#endif + +#ifdef __cplusplus +}; +#endif diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/tests/__init__.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/tests/__init__.py new file mode 100644 index 000000000..1861360bd --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/tests/__init__.py @@ -0,0 +1,248 @@ +# -*- coding: utf-8 -*- +""" +Tests for greenlet. + +""" +import os +import sys +import sysconfig +import unittest + +from gc import collect +from gc import get_objects +from threading import active_count as active_thread_count +from time import sleep +from time import time + +import psutil + +from greenlet import greenlet as RawGreenlet +from greenlet import getcurrent + +from greenlet._greenlet import get_pending_cleanup_count +from greenlet._greenlet import get_total_main_greenlets + +from . import leakcheck + +PY312 = sys.version_info[:2] >= (3, 12) +PY313 = sys.version_info[:2] >= (3, 13) +# XXX: First tested on 3.14a7. Revisit all uses of this on later versions to ensure they +# are still valid. +PY314 = sys.version_info[:2] >= (3, 14) + +WIN = sys.platform.startswith("win") +RUNNING_ON_GITHUB_ACTIONS = os.environ.get('GITHUB_ACTIONS') +RUNNING_ON_TRAVIS = os.environ.get('TRAVIS') or RUNNING_ON_GITHUB_ACTIONS +RUNNING_ON_APPVEYOR = os.environ.get('APPVEYOR') +RUNNING_ON_CI = RUNNING_ON_TRAVIS or RUNNING_ON_APPVEYOR +RUNNING_ON_MANYLINUX = os.environ.get('GREENLET_MANYLINUX') + +# Is the current interpreter free-threaded?) Note that this +# isn't the same as whether the GIL is enabled, this is the build-time +# value. Certain CPython details, like the garbage collector, +# work very differently on potentially-free-threaded builds than +# standard builds. +RUNNING_ON_FREETHREAD_BUILD = bool(sysconfig.get_config_var("Py_GIL_DISABLED")) + +class TestCaseMetaClass(type): + # wrap each test method with + # a) leak checks + def __new__(cls, classname, bases, classDict): + # pylint and pep8 fight over what this should be called (mcs or cls). + # pylint gets it right, but we can't scope disable pep8, so we go with + # its convention. + # pylint: disable=bad-mcs-classmethod-argument + check_totalrefcount = True + + # Python 3: must copy, we mutate the classDict. Interestingly enough, + # it doesn't actually error out, but under 3.6 we wind up wrapping + # and re-wrapping the same items over and over and over. + for key, value in list(classDict.items()): + if key.startswith('test') and callable(value): + classDict.pop(key) + if check_totalrefcount: + value = leakcheck.wrap_refcount(value) + classDict[key] = value + return type.__new__(cls, classname, bases, classDict) + + +class TestCase(unittest.TestCase, metaclass=TestCaseMetaClass): + + cleanup_attempt_sleep_duration = 0.001 + cleanup_max_sleep_seconds = 1 + + def wait_for_pending_cleanups(self, + initial_active_threads=None, + initial_main_greenlets=None): + initial_active_threads = initial_active_threads or self.threads_before_test + initial_main_greenlets = initial_main_greenlets or self.main_greenlets_before_test + sleep_time = self.cleanup_attempt_sleep_duration + # NOTE: This is racy! A Python-level thread object may be dead + # and gone, but the C thread may not yet have fired its + # destructors and added to the queue. There's no particular + # way to know that's about to happen. We try to watch the + # Python threads to make sure they, at least, have gone away. + # Counting the main greenlets, which we can easily do deterministically, + # also helps. + + # Always sleep at least once to let other threads run + sleep(sleep_time) + quit_after = time() + self.cleanup_max_sleep_seconds + # TODO: We could add an API that calls us back when a particular main greenlet is deleted? + # It would have to drop the GIL + while ( + get_pending_cleanup_count() + or active_thread_count() > initial_active_threads + or (not self.expect_greenlet_leak + and get_total_main_greenlets() > initial_main_greenlets)): + sleep(sleep_time) + if time() > quit_after: + print("Time limit exceeded.") + print("Threads: Waiting for only", initial_active_threads, + "-->", active_thread_count()) + print("MGlets : Waiting for only", initial_main_greenlets, + "-->", get_total_main_greenlets()) + break + collect() + + def count_objects(self, kind=list, exact_kind=True): + # pylint:disable=unidiomatic-typecheck + # Collect the garbage. + for _ in range(3): + collect() + if exact_kind: + return sum( + 1 + for x in get_objects() + if type(x) is kind + ) + # instances + return sum( + 1 + for x in get_objects() + if isinstance(x, kind) + ) + + greenlets_before_test = 0 + threads_before_test = 0 + main_greenlets_before_test = 0 + expect_greenlet_leak = False + + def count_greenlets(self): + """ + Find all the greenlets and subclasses tracked by the GC. + """ + return self.count_objects(RawGreenlet, False) + + def setUp(self): + # Ensure the main greenlet exists, otherwise the first test + # gets a false positive leak + super().setUp() + getcurrent() + self.threads_before_test = active_thread_count() + self.main_greenlets_before_test = get_total_main_greenlets() + self.wait_for_pending_cleanups(self.threads_before_test, self.main_greenlets_before_test) + self.greenlets_before_test = self.count_greenlets() + + def tearDown(self): + if getattr(self, 'skipTearDown', False): + return + + self.wait_for_pending_cleanups(self.threads_before_test, self.main_greenlets_before_test) + super().tearDown() + + def get_expected_returncodes_for_aborted_process(self): + import signal + # The child should be aborted in an unusual way. On POSIX + # platforms, this is done with abort() and signal.SIGABRT, + # which is reflected in a negative return value; however, on + # Windows, even though we observe the child print "Fatal + # Python error: Aborted" and in older versions of the C + # runtime "This application has requested the Runtime to + # terminate it in an unusual way," it always has an exit code + # of 3. This is interesting because 3 is the error code for + # ERROR_PATH_NOT_FOUND; BUT: the C runtime abort() function + # also uses this code. + # + # If we link to the static C library on Windows, the error + # code changes to '0xc0000409' (hex(3221226505)), which + # apparently is STATUS_STACK_BUFFER_OVERRUN; but "What this + # means is that nowadays when you get a + # STATUS_STACK_BUFFER_OVERRUN, it doesn’t actually mean that + # there is a stack buffer overrun. It just means that the + # application decided to terminate itself with great haste." + # + # + # On windows, we've also seen '0xc0000005' (hex(3221225477)). + # That's "Access Violation" + # + # See + # https://devblogs.microsoft.com/oldnewthing/20110519-00/?p=10623 + # and + # https://docs.microsoft.com/en-us/previous-versions/k089yyh0(v=vs.140)?redirectedfrom=MSDN + # and + # https://devblogs.microsoft.com/oldnewthing/20190108-00/?p=100655 + expected_exit = ( + -signal.SIGABRT, + # But beginning on Python 3.11, the faulthandler + # that prints the C backtraces sometimes segfaults after + # reporting the exception but before printing the stack. + # This has only been seen on linux/gcc. + -signal.SIGSEGV, + ) if not WIN else ( + 3, + 0xc0000409, + 0xc0000005, + ) + return expected_exit + + def get_process_uss(self): + """ + Return the current process's USS in bytes. + + uss is available on Linux, macOS, Windows. Also known as + "Unique Set Size", this is the memory which is unique to a + process and which would be freed if the process was terminated + right now. + + If this is not supported by ``psutil``, this raises the + :exc:`unittest.SkipTest` exception. + """ + try: + return psutil.Process().memory_full_info().uss + except AttributeError as e: + raise unittest.SkipTest("uss not supported") from e + + def run_script(self, script_name, show_output=True): + import subprocess + script = os.path.join( + os.path.dirname(__file__), + script_name, + ) + + try: + return subprocess.check_output([sys.executable, script], + encoding='utf-8', + stderr=subprocess.STDOUT) + except subprocess.CalledProcessError as ex: + if show_output: + print('-----') + print('Failed to run script', script) + print('~~~~~') + print(ex.output) + print('------') + raise + + + def assertScriptRaises(self, script_name, exitcodes=None): + import subprocess + with self.assertRaises(subprocess.CalledProcessError) as exc: + output = self.run_script(script_name, show_output=False) + __traceback_info__ = output + # We're going to fail the assertion if we get here, at least + # preserve the output in the traceback. + + if exitcodes is None: + exitcodes = self.get_expected_returncodes_for_aborted_process() + self.assertIn(exc.exception.returncode, exitcodes) + return exc.exception diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/tests/_test_extension.c b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/tests/_test_extension.c new file mode 100644 index 000000000..91b9fa674 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/tests/_test_extension.c @@ -0,0 +1,261 @@ +/* This is a set of functions used by test_extension_interface.py to test the + * Greenlet C API. + */ + +#include "../greenlet.h" + +#ifndef Py_RETURN_NONE +# define Py_RETURN_NONE return Py_INCREF(Py_None), Py_None +#endif + +#define TEST_MODULE_NAME "_test_extension" + +// CAUTION: MSVC is stupidly picky: +// +// "The compiler ignores, without warning, any __declspec keywords +// placed after * or & and in front of the variable identifier in a +// declaration." +// (https://docs.microsoft.com/en-us/cpp/cpp/declspec?view=msvc-160) +// +// So pointer return types must be handled differently (because of the +// trailing *), or you get inscrutable compiler warnings like "error +// C2059: syntax error: ''" +// +// In C23, there is a standard syntax for attributes, and +// GCC defines an attribute to use with this: [[gnu:noinline]]. +// In the future, this is expected to become standard. + +#if defined(__GNUC__) || defined(__clang__) +/* We used to check for GCC 4+ or 3.4+, but those compilers are + laughably out of date. Just assume they support it. */ +# define UNUSED(x) UNUSED_ ## x __attribute__((__unused__)) +#elif defined(_MSC_VER) +/* We used to check for && (_MSC_VER >= 1300) but that's also out of date. */ +# define UNUSED(x) UNUSED_ ## x +#endif + +static PyObject* +test_switch(PyObject* UNUSED(self), PyObject* greenlet) +{ + PyObject* result = NULL; + + if (greenlet == NULL || !PyGreenlet_Check(greenlet)) { + PyErr_BadArgument(); + return NULL; + } + + result = PyGreenlet_Switch((PyGreenlet*)greenlet, NULL, NULL); + if (result == NULL) { + if (!PyErr_Occurred()) { + PyErr_SetString(PyExc_AssertionError, + "greenlet.switch() failed for some reason."); + } + return NULL; + } + return result; +} + +static PyObject* +test_switch_kwargs(PyObject* UNUSED(self), PyObject* args, PyObject* kwargs) +{ + PyGreenlet* g = NULL; + PyObject* result = NULL; + + if (!PyArg_ParseTuple(args, "O!", &PyGreenlet_Type, &g)) { + return NULL; + } + + if (g == NULL || !PyGreenlet_Check(g)) { + PyErr_BadArgument(); + return NULL; + } + + result = PyGreenlet_Switch(g, NULL, kwargs); + if (result == NULL) { + if (!PyErr_Occurred()) { + PyErr_SetString(PyExc_AssertionError, + "greenlet.switch() failed for some reason."); + } + return NULL; + } + return result; +} + +static PyObject* +test_getcurrent(PyObject* UNUSED(self)) +{ + PyGreenlet* g = PyGreenlet_GetCurrent(); + if (g == NULL || !PyGreenlet_Check(g) || !PyGreenlet_ACTIVE(g)) { + PyErr_SetString(PyExc_AssertionError, + "getcurrent() returned an invalid greenlet"); + Py_XDECREF(g); + return NULL; + } + Py_DECREF(g); + Py_RETURN_NONE; +} + +static PyObject* +test_setparent(PyObject* UNUSED(self), PyObject* arg) +{ + PyGreenlet* current; + PyGreenlet* greenlet = NULL; + PyObject* switch_result = NULL; + + if (arg == NULL || !PyGreenlet_Check(arg)) { + PyErr_BadArgument(); + return NULL; + } + if ((current = PyGreenlet_GetCurrent()) == NULL) { + return NULL; + } + greenlet = (PyGreenlet*)arg; + if (PyGreenlet_SetParent(greenlet, current)) { + Py_DECREF(current); + return NULL; + } + Py_DECREF(current); + + switch_result = PyGreenlet_Switch(greenlet, NULL, NULL); + if (switch_result == NULL) { + return NULL; + } + Py_DECREF(switch_result); + Py_RETURN_NONE; +} + +static PyObject* +test_new_greenlet(PyObject* UNUSED(self), PyObject* callable) +{ + PyObject* result = NULL; + PyGreenlet* greenlet = PyGreenlet_New(callable, NULL); + + if (!greenlet) { + return NULL; + } + + result = PyGreenlet_Switch(greenlet, NULL, NULL); + Py_CLEAR(greenlet); + if (result == NULL) { + return NULL; + } + + return result; +} + +static PyObject* +test_raise_dead_greenlet(PyObject* UNUSED(self)) +{ + PyErr_SetString(PyExc_GreenletExit, "test GreenletExit exception."); + return NULL; +} + +static PyObject* +test_raise_greenlet_error(PyObject* UNUSED(self)) +{ + PyErr_SetString(PyExc_GreenletError, "test greenlet.error exception"); + return NULL; +} + +static PyObject* +test_throw(PyObject* UNUSED(self), PyGreenlet* g) +{ + const char msg[] = "take that sucka!"; + PyObject* msg_obj = Py_BuildValue("s", msg); + PyGreenlet_Throw(g, PyExc_ValueError, msg_obj, NULL); + Py_DECREF(msg_obj); + if (PyErr_Occurred()) { + return NULL; + } + Py_RETURN_NONE; +} + +static PyObject* +test_throw_exact(PyObject* UNUSED(self), PyObject* args) +{ + PyGreenlet* g = NULL; + PyObject* typ = NULL; + PyObject* val = NULL; + PyObject* tb = NULL; + + if (!PyArg_ParseTuple(args, "OOOO:throw", &g, &typ, &val, &tb)) { + return NULL; + } + + PyGreenlet_Throw(g, typ, val, tb); + if (PyErr_Occurred()) { + return NULL; + } + Py_RETURN_NONE; +} + +static PyMethodDef test_methods[] = { + {"test_switch", + (PyCFunction)test_switch, + METH_O, + "Switch to the provided greenlet sending provided arguments, and \n" + "return the results."}, + {"test_switch_kwargs", + (PyCFunction)test_switch_kwargs, + METH_VARARGS | METH_KEYWORDS, + "Switch to the provided greenlet sending the provided keyword args."}, + {"test_getcurrent", + (PyCFunction)test_getcurrent, + METH_NOARGS, + "Test PyGreenlet_GetCurrent()"}, + {"test_setparent", + (PyCFunction)test_setparent, + METH_O, + "Se the parent of the provided greenlet and switch to it."}, + {"test_new_greenlet", + (PyCFunction)test_new_greenlet, + METH_O, + "Test PyGreenlet_New()"}, + {"test_raise_dead_greenlet", + (PyCFunction)test_raise_dead_greenlet, + METH_NOARGS, + "Just raise greenlet.GreenletExit"}, + {"test_raise_greenlet_error", + (PyCFunction)test_raise_greenlet_error, + METH_NOARGS, + "Just raise greenlet.error"}, + {"test_throw", + (PyCFunction)test_throw, + METH_O, + "Throw a ValueError at the provided greenlet"}, + {"test_throw_exact", + (PyCFunction)test_throw_exact, + METH_VARARGS, + "Throw exactly the arguments given at the provided greenlet"}, + {NULL, NULL, 0, NULL} +}; + + +#define INITERROR return NULL + +static struct PyModuleDef moduledef = {PyModuleDef_HEAD_INIT, + TEST_MODULE_NAME, + NULL, + 0, + test_methods, + NULL, + NULL, + NULL, + NULL}; + +PyMODINIT_FUNC +PyInit__test_extension(void) +{ + PyObject* module = NULL; + module = PyModule_Create(&moduledef); + + if (module == NULL) { + return NULL; + } + + PyGreenlet_Import(); +#ifdef Py_GIL_DISABLED + PyUnstable_Module_SetGIL(module, Py_MOD_GIL_NOT_USED); +#endif + return module; +} diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/tests/_test_extension.cpython-312-x86_64-linux-gnu.so b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/tests/_test_extension.cpython-312-x86_64-linux-gnu.so new file mode 100755 index 000000000..78059824a Binary files /dev/null and b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/tests/_test_extension.cpython-312-x86_64-linux-gnu.so differ diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/tests/_test_extension_cpp.cpp b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/tests/_test_extension_cpp.cpp new file mode 100644 index 000000000..fc7902f65 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/tests/_test_extension_cpp.cpp @@ -0,0 +1,230 @@ +/* This is a set of functions used to test C++ exceptions are not + * broken during greenlet switches + */ + +#include "../greenlet.h" +#include "../greenlet_compiler_compat.hpp" +#include +#include + +struct exception_t { + int depth; + exception_t(int depth) : depth(depth) {} +}; + +/* Functions are called via pointers to prevent inlining */ +static void (*p_test_exception_throw_nonstd)(int depth); +static void (*p_test_exception_throw_std)(); +static PyObject* (*p_test_exception_switch_recurse)(int depth, int left); + +static void +test_exception_throw_nonstd(int depth) +{ + throw exception_t(depth); +} + +static void +test_exception_throw_std() +{ + throw std::runtime_error("Thrown from an extension."); +} + +static PyObject* +test_exception_switch_recurse(int depth, int left) +{ + if (left > 0) { + return p_test_exception_switch_recurse(depth, left - 1); + } + + PyObject* result = NULL; + PyGreenlet* self = PyGreenlet_GetCurrent(); + if (self == NULL) + return NULL; + + try { + if (PyGreenlet_Switch(PyGreenlet_GET_PARENT(self), NULL, NULL) == NULL) { + Py_DECREF(self); + return NULL; + } + p_test_exception_throw_nonstd(depth); + PyErr_SetString(PyExc_RuntimeError, + "throwing C++ exception didn't work"); + } + catch (const exception_t& e) { + if (e.depth != depth) + PyErr_SetString(PyExc_AssertionError, "depth mismatch"); + else + result = PyLong_FromLong(depth); + } + catch (...) { + PyErr_SetString(PyExc_RuntimeError, "unexpected C++ exception"); + } + + Py_DECREF(self); + return result; +} + +/* test_exception_switch(int depth) + * - recurses depth times + * - switches to parent inside try/catch block + * - throws an exception that (expected to be caught in the same function) + * - verifies depth matches (exceptions shouldn't be caught in other greenlets) + */ +static PyObject* +test_exception_switch(PyObject* UNUSED(self), PyObject* args) +{ + int depth; + if (!PyArg_ParseTuple(args, "i", &depth)) + return NULL; + return p_test_exception_switch_recurse(depth, depth); +} + + +static PyObject* +py_test_exception_throw_nonstd(PyObject* UNUSED(self), PyObject* args) +{ + if (!PyArg_ParseTuple(args, "")) + return NULL; + p_test_exception_throw_nonstd(0); + PyErr_SetString(PyExc_AssertionError, "unreachable code running after throw"); + return NULL; +} + +static PyObject* +py_test_exception_throw_std(PyObject* UNUSED(self), PyObject* args) +{ + if (!PyArg_ParseTuple(args, "")) + return NULL; + p_test_exception_throw_std(); + PyErr_SetString(PyExc_AssertionError, "unreachable code running after throw"); + return NULL; +} + +static PyObject* +py_test_call(PyObject* UNUSED(self), PyObject* arg) +{ + PyObject* noargs = PyTuple_New(0); + PyObject* ret = PyObject_Call(arg, noargs, nullptr); + Py_DECREF(noargs); + return ret; +} + + + +/* test_exception_switch_and_do_in_g2(g2func) + * - creates new greenlet g2 to run g2func + * - switches to g2 inside try/catch block + * - verifies that no exception has been caught + * + * it is used together with test_exception_throw to verify that unhandled + * exceptions thrown in one greenlet do not propagate to other greenlet nor + * segfault the process. + */ +static PyObject* +test_exception_switch_and_do_in_g2(PyObject* UNUSED(self), PyObject* args) +{ + PyObject* g2func = NULL; + PyObject* result = NULL; + + if (!PyArg_ParseTuple(args, "O", &g2func)) + return NULL; + PyGreenlet* g2 = PyGreenlet_New(g2func, NULL); + if (!g2) { + return NULL; + } + + try { + result = PyGreenlet_Switch(g2, NULL, NULL); + if (!result) { + Py_DECREF(g2); + return NULL; + } + } + catch (const exception_t& e) { + /* if we are here the memory can be already corrupted and the program + * might crash before below py-level exception might become printed. + * -> print something to stderr to make it clear that we had entered + * this catch block. + * See comments in inner_bootstrap() + */ +#if defined(WIN32) || defined(_WIN32) + fprintf(stderr, "C++ exception unexpectedly caught in g1\n"); + PyErr_SetString(PyExc_AssertionError, "C++ exception unexpectedly caught in g1"); + Py_XDECREF(result); + return NULL; +#else + throw; +#endif + } + + Py_XDECREF(result); + Py_RETURN_NONE; +} + +static PyMethodDef test_methods[] = { + {"test_exception_switch", + (PyCFunction)&test_exception_switch, + METH_VARARGS, + "Switches to parent twice, to test exception handling and greenlet " + "switching."}, + {"test_exception_switch_and_do_in_g2", + (PyCFunction)&test_exception_switch_and_do_in_g2, + METH_VARARGS, + "Creates new greenlet g2 to run g2func and switches to it inside try/catch " + "block. Used together with test_exception_throw to verify that unhandled " + "C++ exceptions thrown in a greenlet doe not corrupt memory."}, + {"test_exception_throw_nonstd", + (PyCFunction)&py_test_exception_throw_nonstd, + METH_VARARGS, + "Throws non-standard C++ exception. Calling this function directly should abort the process." + }, + {"test_exception_throw_std", + (PyCFunction)&py_test_exception_throw_std, + METH_VARARGS, + "Throws standard C++ exception. Calling this function directly should abort the process." + }, + {"test_call", + (PyCFunction)&py_test_call, + METH_O, + "Call the given callable. Unlike calling it directly, this creates a " + "new C-level stack frame, which may be helpful in testing." + }, + {NULL, NULL, 0, NULL} +}; + + +static struct PyModuleDef moduledef = {PyModuleDef_HEAD_INIT, + "greenlet.tests._test_extension_cpp", + NULL, + 0, + test_methods, + NULL, + NULL, + NULL, + NULL}; + +PyMODINIT_FUNC +PyInit__test_extension_cpp(void) +{ + PyObject* module = NULL; + + module = PyModule_Create(&moduledef); + + if (module == NULL) { + return NULL; + } + + PyGreenlet_Import(); + if (_PyGreenlet_API == NULL) { + return NULL; + } + + p_test_exception_throw_nonstd = test_exception_throw_nonstd; + p_test_exception_throw_std = test_exception_throw_std; + p_test_exception_switch_recurse = test_exception_switch_recurse; +#ifdef Py_GIL_DISABLED + PyUnstable_Module_SetGIL(module, Py_MOD_GIL_NOT_USED); +#endif + + return module; +} diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/tests/_test_extension_cpp.cpython-312-x86_64-linux-gnu.so b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/tests/_test_extension_cpp.cpython-312-x86_64-linux-gnu.so new file mode 100755 index 000000000..3aca65067 Binary files /dev/null and b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/tests/_test_extension_cpp.cpython-312-x86_64-linux-gnu.so differ diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/tests/fail_clearing_run_switches.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/tests/fail_clearing_run_switches.py new file mode 100644 index 000000000..6dd1492ff --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/tests/fail_clearing_run_switches.py @@ -0,0 +1,47 @@ +# -*- coding: utf-8 -*- +""" +If we have a run callable passed to the constructor or set as an +attribute, but we don't actually use that (because ``__getattribute__`` +or the like interferes), then when we clear callable before beginning +to run, there's an opportunity for Python code to run. + +""" +import greenlet + +g = None +main = greenlet.getcurrent() + +results = [] + +class RunCallable: + + def __del__(self): + results.append(('RunCallable', '__del__')) + main.switch('from RunCallable') + + +class G(greenlet.greenlet): + + def __getattribute__(self, name): + if name == 'run': + results.append(('G.__getattribute__', 'run')) + return run_func + return object.__getattribute__(self, name) + + +def run_func(): + results.append(('run_func', 'enter')) + + +g = G(RunCallable()) +# Try to start G. It will get to the point where it deletes +# its run callable C++ variable in inner_bootstrap. That triggers +# the __del__ method, which switches back to main before g +# actually even starts running. +x = g.switch() +results.append(('main: g.switch()', x)) +# In the C++ code, this results in g->g_switch() appearing to return, even though +# it has yet to run. +print('In main with', x, flush=True) +g.switch() +print('RESULTS', results) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/tests/fail_cpp_exception.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/tests/fail_cpp_exception.py new file mode 100644 index 000000000..fa4dc2eb3 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/tests/fail_cpp_exception.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +""" +Helper for testing a C++ exception throw aborts the process. + +Takes one argument, the name of the function in :mod:`_test_extension_cpp` to call. +""" +import sys +import greenlet +from greenlet.tests import _test_extension_cpp +print('fail_cpp_exception is running') + +def run_unhandled_exception_in_greenlet_aborts(): + def _(): + _test_extension_cpp.test_exception_switch_and_do_in_g2( + _test_extension_cpp.test_exception_throw_nonstd + ) + g1 = greenlet.greenlet(_) + g1.switch() + + +func_name = sys.argv[1] +try: + func = getattr(_test_extension_cpp, func_name) +except AttributeError: + if func_name == run_unhandled_exception_in_greenlet_aborts.__name__: + func = run_unhandled_exception_in_greenlet_aborts + elif func_name == 'run_as_greenlet_target': + g = greenlet.greenlet(_test_extension_cpp.test_exception_throw_std) + func = g.switch + else: + raise +print('raising', func, flush=True) +func() diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/tests/fail_initialstub_already_started.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/tests/fail_initialstub_already_started.py new file mode 100644 index 000000000..c1a44efd2 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/tests/fail_initialstub_already_started.py @@ -0,0 +1,78 @@ +""" +Testing initialstub throwing an already started exception. +""" + +import greenlet + +a = None +b = None +c = None +main = greenlet.getcurrent() + +# If we switch into a dead greenlet, +# we go looking for its parents. +# if a parent is not yet started, we start it. + +results = [] + +def a_run(*args): + #results.append('A') + results.append(('Begin A', args)) + + +def c_run(): + results.append('Begin C') + b.switch('From C') + results.append('C done') + +class A(greenlet.greenlet): pass + +class B(greenlet.greenlet): + doing_it = False + def __getattribute__(self, name): + if name == 'run' and not self.doing_it: + assert greenlet.getcurrent() is c + self.doing_it = True + results.append('Switch to b from B.__getattribute__ in ' + + type(greenlet.getcurrent()).__name__) + b.switch() + results.append('B.__getattribute__ back from main in ' + + type(greenlet.getcurrent()).__name__) + if name == 'run': + name = '_B_run' + return object.__getattribute__(self, name) + + def _B_run(self, *arg): + results.append(('Begin B', arg)) + results.append('_B_run switching to main') + main.switch('From B') + +class C(greenlet.greenlet): + pass +a = A(a_run) +b = B(parent=a) +c = C(c_run, b) + +# Start a child; while running, it will start B, +# but starting B will ALSO start B. +result = c.switch() +results.append(('main from c', result)) + +# Switch back to C, which was in the middle of switching +# already. This will throw the ``GreenletStartedWhileInPython`` +# exception, which results in parent A getting started (B is finished) +c.switch() + +results.append(('A dead?', a.dead, 'B dead?', b.dead, 'C dead?', c.dead)) + +# A and B should both be dead now. +assert a.dead +assert b.dead +assert not c.dead + +result = c.switch() +results.append(('main from c.2', result)) +# Now C is dead +assert c.dead + +print("RESULTS:", results) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/tests/fail_slp_switch.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/tests/fail_slp_switch.py new file mode 100644 index 000000000..09905269f --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/tests/fail_slp_switch.py @@ -0,0 +1,29 @@ +# -*- coding: utf-8 -*- +""" +A test helper for seeing what happens when slp_switch() +fails. +""" +# pragma: no cover + +import greenlet + + +print('fail_slp_switch is running', flush=True) + +runs = [] +def func(): + runs.append(1) + greenlet.getcurrent().parent.switch() + runs.append(2) + greenlet.getcurrent().parent.switch() + runs.append(3) + +g = greenlet._greenlet.UnswitchableGreenlet(func) +g.switch() +assert runs == [1] +g.switch() +assert runs == [1, 2] +g.force_slp_switch_error = True + +# This should crash. +g.switch() diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/tests/fail_switch_three_greenlets.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/tests/fail_switch_three_greenlets.py new file mode 100644 index 000000000..e151b19a6 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/tests/fail_switch_three_greenlets.py @@ -0,0 +1,44 @@ +""" +Uses a trace function to switch greenlets at unexpected times. + +In the trace function, we switch from the current greenlet to another +greenlet, which switches +""" +import greenlet + +g1 = None +g2 = None + +switch_to_g2 = False + +def tracefunc(*args): + print('TRACE', *args) + global switch_to_g2 + if switch_to_g2: + switch_to_g2 = False + g2.switch() + print('\tLEAVE TRACE', *args) + +def g1_run(): + print('In g1_run') + global switch_to_g2 + switch_to_g2 = True + from_parent = greenlet.getcurrent().parent.switch() + print('Return to g1_run') + print('From parent', from_parent) + +def g2_run(): + #g1.switch() + greenlet.getcurrent().parent.switch() + +greenlet.settrace(tracefunc) + +g1 = greenlet.greenlet(g1_run) +g2 = greenlet.greenlet(g2_run) + +# This switch didn't actually finish! +# And if it did, it would raise TypeError +# because g1_run() doesn't take any arguments. +g1.switch(1) +print('Back in main') +g1.switch(2) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/tests/fail_switch_three_greenlets2.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/tests/fail_switch_three_greenlets2.py new file mode 100644 index 000000000..1f6b66bc6 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/tests/fail_switch_three_greenlets2.py @@ -0,0 +1,55 @@ +""" +Like fail_switch_three_greenlets, but the call into g1_run would actually be +valid. +""" +import greenlet + +g1 = None +g2 = None + +switch_to_g2 = True + +results = [] + +def tracefunc(*args): + results.append(('trace', args[0])) + print('TRACE', *args) + global switch_to_g2 + if switch_to_g2: + switch_to_g2 = False + g2.switch('g2 from tracefunc') + print('\tLEAVE TRACE', *args) + +def g1_run(arg): + results.append(('g1 arg', arg)) + print('In g1_run') + from_parent = greenlet.getcurrent().parent.switch('from g1_run') + results.append(('g1 from parent', from_parent)) + return 'g1 done' + +def g2_run(arg): + #g1.switch() + results.append(('g2 arg', arg)) + parent = greenlet.getcurrent().parent.switch('from g2_run') + global switch_to_g2 + switch_to_g2 = False + results.append(('g2 from parent', parent)) + return 'g2 done' + + +greenlet.settrace(tracefunc) + +g1 = greenlet.greenlet(g1_run) +g2 = greenlet.greenlet(g2_run) + +x = g1.switch('g1 from main') +results.append(('main g1', x)) +print('Back in main', x) +x = g1.switch('g2 from main') +results.append(('main g2', x)) +print('back in amain again', x) +x = g1.switch('g1 from main 2') +results.append(('main g1.2', x)) +x = g2.switch() +results.append(('main g2.2', x)) +print("RESULTS:", results) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/tests/fail_switch_two_greenlets.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/tests/fail_switch_two_greenlets.py new file mode 100644 index 000000000..3e52345a6 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/tests/fail_switch_two_greenlets.py @@ -0,0 +1,41 @@ +""" +Uses a trace function to switch greenlets at unexpected times. + +In the trace function, we switch from the current greenlet to another +greenlet, which switches +""" +import greenlet + +g1 = None +g2 = None + +switch_to_g2 = False + +def tracefunc(*args): + print('TRACE', *args) + global switch_to_g2 + if switch_to_g2: + switch_to_g2 = False + g2.switch() + print('\tLEAVE TRACE', *args) + +def g1_run(): + print('In g1_run') + global switch_to_g2 + switch_to_g2 = True + greenlet.getcurrent().parent.switch() + print('Return to g1_run') + print('Falling off end of g1_run') + +def g2_run(): + g1.switch() + print('Falling off end of g2') + +greenlet.settrace(tracefunc) + +g1 = greenlet.greenlet(g1_run) +g2 = greenlet.greenlet(g2_run) + +g1.switch() +print('Falling off end of main') +g2.switch() diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/tests/leakcheck.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/tests/leakcheck.py new file mode 100644 index 000000000..993e3fa8b --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/tests/leakcheck.py @@ -0,0 +1,334 @@ +# Copyright (c) 2018 gevent community +# Copyright (c) 2021 greenlet community +# +# This was originally part of gevent's test suite. The main author +# (Jason Madden) vendored a copy of it into greenlet. +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +# THE SOFTWARE. +import os +import sys +import gc + +from functools import wraps +import unittest + + +import objgraph + +# graphviz 0.18 (Nov 7 2021), available only on Python 3.6 and newer, +# has added type hints (sigh). It wants to use ``typing.Literal`` for +# some stuff, but that's only available on Python 3.9+. If that's not +# found, it creates a ``unittest.mock.MagicMock`` object and annotates +# with that. These are GC'able objects, and doing almost *anything* +# with them results in an explosion of objects. For example, trying to +# compare them for equality creates new objects. This causes our +# leakchecks to fail, with reports like: +# +# greenlet.tests.leakcheck.LeakCheckError: refcount increased by [337, 1333, 343, 430, 530, 643, 769] +# _Call 1820 +546 +# dict 4094 +76 +# MagicProxy 585 +73 +# tuple 2693 +66 +# _CallList 24 +3 +# weakref 1441 +1 +# function 5996 +1 +# type 736 +1 +# cell 592 +1 +# MagicMock 8 +1 +# +# To avoid this, we *could* filter this type of object out early. In +# principle it could leak, but we don't use mocks in greenlet, so it +# doesn't leak from us. However, a further issue is that ``MagicMock`` +# objects have subobjects that are also GC'able, like ``_Call``, and +# those create new mocks of their own too. So we'd have to filter them +# as well, and they're not public. That's OK, we can workaround the +# problem by being very careful to never compare by equality or other +# user-defined operators, only using object identity or other builtin +# functions. + +RUNNING_ON_GITHUB_ACTIONS = os.environ.get('GITHUB_ACTIONS') +RUNNING_ON_TRAVIS = os.environ.get('TRAVIS') or RUNNING_ON_GITHUB_ACTIONS +RUNNING_ON_APPVEYOR = os.environ.get('APPVEYOR') +RUNNING_ON_CI = RUNNING_ON_TRAVIS or RUNNING_ON_APPVEYOR +RUNNING_ON_MANYLINUX = os.environ.get('GREENLET_MANYLINUX') +SKIP_LEAKCHECKS = RUNNING_ON_MANYLINUX or os.environ.get('GREENLET_SKIP_LEAKCHECKS') +SKIP_FAILING_LEAKCHECKS = os.environ.get('GREENLET_SKIP_FAILING_LEAKCHECKS') +ONLY_FAILING_LEAKCHECKS = os.environ.get('GREENLET_ONLY_FAILING_LEAKCHECKS') + +def ignores_leakcheck(func): + """ + Ignore the given object during leakchecks. + + Can be applied to a method, in which case the method will run, but + will not be subject to leak checks. + + If applied to a class, the entire class will be skipped during leakchecks. This + is intended to be used for classes that are very slow and cause problems such as + test timeouts; typically it will be used for classes that are subclasses of a base + class and specify variants of behaviour (such as pool sizes). + """ + func.ignore_leakcheck = True + return func + +def fails_leakcheck(func): + """ + Mark that the function is known to leak. + """ + func.fails_leakcheck = True + if SKIP_FAILING_LEAKCHECKS: + func = unittest.skip("Skipping known failures")(func) + return func + +class LeakCheckError(AssertionError): + pass + +if hasattr(sys, 'getobjects'): + # In a Python build with ``--with-trace-refs``, make objgraph + # trace *all* the objects, not just those that are tracked by the + # GC + class _MockGC(object): + def get_objects(self): + return sys.getobjects(0) # pylint:disable=no-member + def __getattr__(self, name): + return getattr(gc, name) + objgraph.gc = _MockGC() + fails_strict_leakcheck = fails_leakcheck +else: + def fails_strict_leakcheck(func): + """ + Decorator for a function that is known to fail when running + strict (``sys.getobjects()``) leakchecks. + + This type of leakcheck finds all objects, even those, such as + strings, which are not tracked by the garbage collector. + """ + return func + +class ignores_types_in_strict_leakcheck(object): + def __init__(self, types): + self.types = types + def __call__(self, func): + func.leakcheck_ignore_types = self.types + return func + +class _RefCountChecker(object): + + # Some builtin things that we ignore + # XXX: Those things were ignored by gevent, but they're important here, + # presumably. + IGNORED_TYPES = () #(tuple, dict, types.FrameType, types.TracebackType) + + # Names of types that should be ignored. Use this when we cannot + # or don't want to import the class directly. + IGNORED_TYPE_NAMES = ( + # This appears in Python3.14 with the JIT enabled. It + # doesn't seem to be directly exposed to Python; the only way to get + # one is to cause code to get jitted and then look for all objects + # and find one with this name. But they multiply as code + # executes and gets jitted, in ways we don't want to rely on. + # So just ignore it. + 'uop_executor', + ) + + def __init__(self, testcase, function): + self.testcase = testcase + self.function = function + self.deltas = [] + self.peak_stats = {} + self.ignored_types = () + + # The very first time we are called, we have already been + # self.setUp() by the test runner, so we don't need to do it again. + self.needs_setUp = False + + def _include_object_p(self, obj): + # pylint:disable=too-many-return-statements + # + # See the comment block at the top. We must be careful to + # avoid invoking user-defined operations. + if obj is self: + return False + kind = type(obj) + # ``self._include_object_p == obj`` returns NotImplemented + # for non-function objects, which causes the interpreter + # to try to reverse the order of arguments...which leads + # to the explosion of mock objects. We don't want that, so we implement + # the check manually. + if kind == type(self._include_object_p): # pylint: disable=unidiomatic-typecheck + try: + # pylint:disable=not-callable + exact_method_equals = self._include_object_p.__eq__(obj) + except AttributeError: + # Python 2.7 methods may only have __cmp__, and that raises a + # TypeError for non-method arguments + # pylint:disable=no-member + exact_method_equals = self._include_object_p.__cmp__(obj) == 0 + + if exact_method_equals is not NotImplemented and exact_method_equals: + return False + + # Similarly, we need to check identity in our __dict__ to avoid mock explosions. + for x in self.__dict__.values(): + if obj is x: + return False + + + if ( + kind in self.ignored_types + or kind in self.IGNORED_TYPES + or kind.__name__ in self.IGNORED_TYPE_NAMES + ): + return False + + + return True + + def _growth(self): + return objgraph.growth(limit=None, peak_stats=self.peak_stats, + filter=self._include_object_p) + + def _report_diff(self, growth): + if not growth: + return "" + + lines = [] + width = max(len(name) for name, _, _ in growth) + for name, count, delta in growth: + lines.append('%-*s%9d %+9d' % (width, name, count, delta)) + + diff = '\n'.join(lines) + return diff + + + def _run_test(self, args, kwargs): + gc_enabled = gc.isenabled() + gc.disable() + + if self.needs_setUp: + self.testcase.setUp() + self.testcase.skipTearDown = False + try: + self.function(self.testcase, *args, **kwargs) + finally: + self.testcase.tearDown() + self.testcase.doCleanups() + self.testcase.skipTearDown = True + self.needs_setUp = True + if gc_enabled: + gc.enable() + + def _growth_after(self): + # Grab post snapshot + # pylint:disable=no-member + if 'urlparse' in sys.modules: + sys.modules['urlparse'].clear_cache() + if 'urllib.parse' in sys.modules: + sys.modules['urllib.parse'].clear_cache() + + return self._growth() + + def _check_deltas(self, growth): + # Return false when we have decided there is no leak, + # true if we should keep looping, raises an assertion + # if we have decided there is a leak. + + deltas = self.deltas + if not deltas: + # We haven't run yet, no data, keep looping + return True + + if gc.garbage: + raise LeakCheckError("Generated uncollectable garbage %r" % (gc.garbage,)) + + + # the following configurations are classified as "no leak" + # [0, 0] + # [x, 0, 0] + # [... a, b, c, d] where a+b+c+d = 0 + # + # the following configurations are classified as "leak" + # [... z, z, z] where z > 0 + + if deltas[-2:] == [0, 0] and len(deltas) in (2, 3): + return False + + if deltas[-3:] == [0, 0, 0]: + return False + + if len(deltas) >= 4 and sum(deltas[-4:]) == 0: + return False + + if len(deltas) >= 3 and deltas[-1] > 0 and deltas[-1] == deltas[-2] and deltas[-2] == deltas[-3]: + diff = self._report_diff(growth) + raise LeakCheckError('refcount increased by %r\n%s' % (deltas, diff)) + + # OK, we don't know for sure yet. Let's search for more + if sum(deltas[-3:]) <= 0 or sum(deltas[-4:]) <= 0 or deltas[-4:].count(0) >= 2: + # this is suspicious, so give a few more runs + limit = 11 + else: + limit = 7 + if len(deltas) >= limit: + raise LeakCheckError('refcount increased by %r\n%s' + % (deltas, + self._report_diff(growth))) + + # We couldn't decide yet, keep going + return True + + def __call__(self, args, kwargs): + for _ in range(3): + gc.collect() + + expect_failure = getattr(self.function, 'fails_leakcheck', False) + if expect_failure: + self.testcase.expect_greenlet_leak = True + self.ignored_types = getattr(self.function, "leakcheck_ignore_types", ()) + + # Capture state before; the incremental will be + # updated by each call to _growth_after + growth = self._growth() + + try: + while self._check_deltas(growth): + self._run_test(args, kwargs) + + growth = self._growth_after() + + self.deltas.append(sum((stat[2] for stat in growth))) + except LeakCheckError: + if not expect_failure: + raise + else: + if expect_failure: + raise LeakCheckError("Expected %s to leak but it did not." % (self.function,)) + +def wrap_refcount(method): + if getattr(method, 'ignore_leakcheck', False) or SKIP_LEAKCHECKS: + return method + + @wraps(method) + def wrapper(self, *args, **kwargs): # pylint:disable=too-many-branches + if getattr(self, 'ignore_leakcheck', False): + raise unittest.SkipTest("This class ignored during leakchecks") + if ONLY_FAILING_LEAKCHECKS and not getattr(method, 'fails_leakcheck', False): + raise unittest.SkipTest("Only running tests that fail leakchecks.") + return _RefCountChecker(self, method)(args, kwargs) + + return wrapper diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/tests/test_contextvars.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/tests/test_contextvars.py new file mode 100644 index 000000000..f7dea75f3 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/tests/test_contextvars.py @@ -0,0 +1,282 @@ +import gc +import sys +import unittest +from contextvars import Context +from contextvars import ContextVar +from contextvars import copy_context +from functools import partial + +from greenlet import getcurrent +from greenlet import greenlet + +from . import PY314 +from . import TestCase + +# From the documentation: +# +# Important: Context Variables should be created at the top module +# level and never in closures. Context objects hold strong +# references to context variables which prevents context variables +# from being properly garbage collected. +ID_VAR = ContextVar("id", default=None) +VAR_VAR = ContextVar("var", default=None) +ContextVar = None + + +class ContextVarsTests(TestCase): + def _new_ctx_run(self, *args, **kwargs): + return copy_context().run(*args, **kwargs) + + def _increment(self, greenlet_id, callback, counts, expect): + ctx_var = ID_VAR + if expect is None: + self.assertIsNone(ctx_var.get()) + else: + self.assertEqual(ctx_var.get(), expect) + ctx_var.set(greenlet_id) + for _ in range(2): + counts[ctx_var.get()] += 1 + callback() + + def _test_context(self, propagate_by): + # pylint:disable=too-many-branches + ID_VAR.set(0) + + callback = getcurrent().switch + counts = dict((i, 0) for i in range(5)) + + lets = [ + greenlet(partial( + partial( + copy_context().run, + self._increment + ) if propagate_by == "run" else self._increment, + greenlet_id=i, + callback=callback, + counts=counts, + expect=( + i - 1 if propagate_by == "share" else + 0 if propagate_by in ("set", "run") else None + ) + )) + for i in range(1, 5) + ] + + for let in lets: + if propagate_by == "set": + let.gr_context = copy_context() + elif propagate_by == "share": + let.gr_context = getcurrent().gr_context + + for i in range(2): + counts[ID_VAR.get()] += 1 + for let in lets: + let.switch() + + if propagate_by == "run": + # Must leave each context.run() in reverse order of entry + for let in reversed(lets): + let.switch() + else: + # No context.run(), so fine to exit in any order. + for let in lets: + let.switch() + + for let in lets: + self.assertTrue(let.dead) + # When using run(), we leave the run() as the greenlet dies, + # and there's no context "underneath". When not using run(), + # gr_context still reflects the context the greenlet was + # running in. + if propagate_by == 'run': + self.assertIsNone(let.gr_context) + else: + self.assertIsNotNone(let.gr_context) + + + if propagate_by == "share": + self.assertEqual(counts, {0: 1, 1: 1, 2: 1, 3: 1, 4: 6}) + else: + self.assertEqual(set(counts.values()), set([2])) + + def test_context_propagated_by_context_run(self): + self._new_ctx_run(self._test_context, "run") + + def test_context_propagated_by_setting_attribute(self): + self._new_ctx_run(self._test_context, "set") + + def test_context_not_propagated(self): + self._new_ctx_run(self._test_context, None) + + def test_context_shared(self): + self._new_ctx_run(self._test_context, "share") + + def test_break_ctxvars(self): + let1 = greenlet(copy_context().run) + let2 = greenlet(copy_context().run) + let1.switch(getcurrent().switch) + let2.switch(getcurrent().switch) + # Since let2 entered the current context and let1 exits its own, the + # interpreter emits: + # RuntimeError: cannot exit context: thread state references a different context object + let1.switch() + + def test_not_broken_if_using_attribute_instead_of_context_run(self): + let1 = greenlet(getcurrent().switch) + let2 = greenlet(getcurrent().switch) + let1.gr_context = copy_context() + let2.gr_context = copy_context() + let1.switch() + let2.switch() + let1.switch() + let2.switch() + + def test_context_assignment_while_running(self): + # pylint:disable=too-many-statements + ID_VAR.set(None) + + def target(): + self.assertIsNone(ID_VAR.get()) + self.assertIsNone(gr.gr_context) + + # Context is created on first use + ID_VAR.set(1) + self.assertIsInstance(gr.gr_context, Context) + self.assertEqual(ID_VAR.get(), 1) + self.assertEqual(gr.gr_context[ID_VAR], 1) + + # Clearing the context makes it get re-created as another + # empty context when next used + old_context = gr.gr_context + gr.gr_context = None # assign None while running + self.assertIsNone(ID_VAR.get()) + self.assertIsNone(gr.gr_context) + ID_VAR.set(2) + self.assertIsInstance(gr.gr_context, Context) + self.assertEqual(ID_VAR.get(), 2) + self.assertEqual(gr.gr_context[ID_VAR], 2) + + new_context = gr.gr_context + getcurrent().parent.switch((old_context, new_context)) + # parent switches us back to old_context + + self.assertEqual(ID_VAR.get(), 1) + gr.gr_context = new_context # assign non-None while running + self.assertEqual(ID_VAR.get(), 2) + + getcurrent().parent.switch() + # parent switches us back to no context + self.assertIsNone(ID_VAR.get()) + self.assertIsNone(gr.gr_context) + gr.gr_context = old_context + self.assertEqual(ID_VAR.get(), 1) + + getcurrent().parent.switch() + # parent switches us back to no context + self.assertIsNone(ID_VAR.get()) + self.assertIsNone(gr.gr_context) + + gr = greenlet(target) + + with self.assertRaisesRegex(AttributeError, "can't delete context attribute"): + del gr.gr_context + + self.assertIsNone(gr.gr_context) + old_context, new_context = gr.switch() + self.assertIs(new_context, gr.gr_context) + self.assertEqual(old_context[ID_VAR], 1) + self.assertEqual(new_context[ID_VAR], 2) + self.assertEqual(new_context.run(ID_VAR.get), 2) + gr.gr_context = old_context # assign non-None while suspended + gr.switch() + self.assertIs(gr.gr_context, new_context) + gr.gr_context = None # assign None while suspended + gr.switch() + self.assertIs(gr.gr_context, old_context) + gr.gr_context = None + gr.switch() + self.assertIsNone(gr.gr_context) + + # Make sure there are no reference leaks + gr = None + gc.collect() + # Python 3.14 elides reference counting operations + # in some cases. See https://github.com/python/cpython/pull/130708 + self.assertEqual(sys.getrefcount(old_context), 2 if not PY314 else 1) + self.assertEqual(sys.getrefcount(new_context), 2 if not PY314 else 1) + + def test_context_assignment_different_thread(self): + import threading + VAR_VAR.set(None) + ctx = Context() + + is_running = threading.Event() + should_suspend = threading.Event() + did_suspend = threading.Event() + should_exit = threading.Event() + holder = [] + + def greenlet_in_thread_fn(): + VAR_VAR.set(1) + is_running.set() + should_suspend.wait(10) + VAR_VAR.set(2) + getcurrent().parent.switch() + holder.append(VAR_VAR.get()) + + def thread_fn(): + gr = greenlet(greenlet_in_thread_fn) + gr.gr_context = ctx + holder.append(gr) + gr.switch() + did_suspend.set() + should_exit.wait(10) + gr.switch() + del gr + greenlet() # trigger cleanup + + thread = threading.Thread(target=thread_fn, daemon=True) + thread.start() + is_running.wait(10) + gr = holder[0] + + # Can't access or modify context if the greenlet is running + # in a different thread + with self.assertRaisesRegex(ValueError, "running in a different"): + getattr(gr, 'gr_context') + with self.assertRaisesRegex(ValueError, "running in a different"): + gr.gr_context = None + + should_suspend.set() + did_suspend.wait(10) + + # OK to access and modify context if greenlet is suspended + self.assertIs(gr.gr_context, ctx) + self.assertEqual(gr.gr_context[VAR_VAR], 2) + gr.gr_context = None + + should_exit.set() + thread.join(10) + + self.assertEqual(holder, [gr, None]) + + # Context can still be accessed/modified when greenlet is dead: + self.assertIsNone(gr.gr_context) + gr.gr_context = ctx + self.assertIs(gr.gr_context, ctx) + + # Otherwise we leak greenlets on some platforms. + # XXX: Should be able to do this automatically + del holder[:] + gr = None + thread = None + + def test_context_assignment_wrong_type(self): + g = greenlet() + with self.assertRaisesRegex(TypeError, + "greenlet context must be a contextvars.Context or None"): + g.gr_context = self + + +if __name__ == '__main__': + unittest.main() diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/tests/test_cpp.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/tests/test_cpp.py new file mode 100644 index 000000000..6ad5bcc0f --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/tests/test_cpp.py @@ -0,0 +1,91 @@ +import gc +import subprocess +import unittest + +import greenlet +import objgraph + +from . import WIN +from . import TestCase +from . import _test_extension_cpp + + +class CPPTests(TestCase): + def test_exception_switch(self): + greenlets = [] + for i in range(4): + g = greenlet.greenlet(_test_extension_cpp.test_exception_switch) + g.switch(i) + greenlets.append(g) + for i, g in enumerate(greenlets): + self.assertEqual(g.switch(), i) + + def _do_test_unhandled_exception(self, target): + import os + import sys + script = os.path.join( + os.path.dirname(__file__), + 'fail_cpp_exception.py', + ) + args = [sys.executable, script, target.__name__ if not isinstance(target, str) else target] + __traceback_info__ = args + with self.assertRaises(subprocess.CalledProcessError) as exc: + subprocess.check_output( + args, + encoding='utf-8', + stderr=subprocess.STDOUT + ) + + ex = exc.exception + expected_exit = self.get_expected_returncodes_for_aborted_process() + self.assertIn(ex.returncode, expected_exit) + self.assertIn('fail_cpp_exception is running', ex.output) + return ex.output + + + def test_unhandled_nonstd_exception_aborts(self): + # verify that plain unhandled throw aborts + self._do_test_unhandled_exception(_test_extension_cpp.test_exception_throw_nonstd) + + def test_unhandled_std_exception_aborts(self): + # verify that plain unhandled throw aborts + self._do_test_unhandled_exception(_test_extension_cpp.test_exception_throw_std) + + @unittest.skipIf(WIN, "XXX: This does not crash on Windows") + # Meaning the exception is getting lost somewhere... + def test_unhandled_std_exception_as_greenlet_function_aborts(self): + # verify that plain unhandled throw aborts + output = self._do_test_unhandled_exception('run_as_greenlet_target') + self.assertIn( + # We really expect this to be prefixed with "greenlet: Unhandled C++ exception:" + # as added by our handler for std::exception (see TUserGreenlet.cpp), but + # that's not correct everywhere --- our handler never runs before std::terminate + # gets called (for example, on arm32). + 'Thrown from an extension.', + output + ) + + def test_unhandled_exception_in_greenlet_aborts(self): + # verify that unhandled throw called in greenlet aborts too + self._do_test_unhandled_exception('run_unhandled_exception_in_greenlet_aborts') + + + def test_leak_test_exception_switch_and_do_in_g2(self): + def raiser(): + raise ValueError("boom") + + gc.collect() + before = objgraph.count("greenlet") + + for _ in range(1000): + with self.assertRaises(ValueError): + _test_extension_cpp.test_exception_switch_and_do_in_g2(raiser) + + gc.collect() + after = objgraph.count("greenlet") + leaked = after - before + self.assertEqual(0, leaked) + + +if __name__ == '__main__': + unittest.main() diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/tests/test_extension_interface.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/tests/test_extension_interface.py new file mode 100644 index 000000000..4261897cb --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/tests/test_extension_interface.py @@ -0,0 +1,141 @@ +import sys + +import greenlet +from . import _test_extension +from . import TestCase +from .leakcheck import ignores_leakcheck + +# pylint:disable=c-extension-no-member + +class CAPITests(TestCase): + def test_switch(self): + self.assertEqual( + 50, _test_extension.test_switch(greenlet.greenlet(lambda: 50))) + + def test_switch_kwargs(self): + def adder(x, y): + return x * y + g = greenlet.greenlet(adder) + self.assertEqual(6, _test_extension.test_switch_kwargs(g, x=3, y=2)) + + with self.assertRaisesRegex(TypeError, "argument 1 must be greenlet"): + _test_extension.test_switch_kwargs("not a greenlet") + + def test_setparent(self): + # pylint:disable=disallowed-name + def foo(): + def bar(): + greenlet.getcurrent().parent.switch() + + # This final switch should go back to the main greenlet, since + # the test_setparent() function in the C extension should have + # reparented this greenlet. + greenlet.getcurrent().parent.switch() + raise AssertionError("Should never have reached this code") + child = greenlet.greenlet(bar) + child.switch() + greenlet.getcurrent().parent.switch(child) + greenlet.getcurrent().parent.throw( + AssertionError("Should never reach this code")) + foo_child = greenlet.greenlet(foo).switch() + self.assertEqual(None, _test_extension.test_setparent(foo_child)) + + def test_getcurrent(self): + _test_extension.test_getcurrent() + + def test_new_greenlet(self): + self.assertEqual(-15, _test_extension.test_new_greenlet(lambda: -15)) + + def test_raise_greenlet_dead(self): + self.assertRaises( + greenlet.GreenletExit, _test_extension.test_raise_dead_greenlet) + + def test_raise_greenlet_error(self): + self.assertRaises( + greenlet.error, _test_extension.test_raise_greenlet_error) + + def test_throw(self): + seen = [] + + def foo(): # pylint:disable=disallowed-name + try: + greenlet.getcurrent().parent.switch() + except ValueError: + seen.append(sys.exc_info()[1]) + except greenlet.GreenletExit: + raise AssertionError + g = greenlet.greenlet(foo) + g.switch() + _test_extension.test_throw(g) + self.assertEqual(len(seen), 1) + self.assertTrue( + isinstance(seen[0], ValueError), + "ValueError was not raised in foo()") + self.assertEqual( + str(seen[0]), + 'take that sucka!', + "message doesn't match") + + def test_non_traceback_param(self): + with self.assertRaises(TypeError) as exc: + _test_extension.test_throw_exact( + greenlet.getcurrent(), + Exception, + Exception(), + self + ) + self.assertEqual(str(exc.exception), + "throw() third argument must be a traceback object") + + def test_instance_of_wrong_type(self): + with self.assertRaises(TypeError) as exc: + _test_extension.test_throw_exact( + greenlet.getcurrent(), + Exception(), + BaseException(), + None, + ) + + self.assertEqual(str(exc.exception), + "instance exception may not have a separate value") + + def test_not_throwable(self): + with self.assertRaises(TypeError) as exc: + _test_extension.test_throw_exact( + greenlet.getcurrent(), + "abc", + None, + None, + ) + self.assertEqual(str(exc.exception), + "exceptions must be classes, or instances, not str") + + @ignores_leakcheck + def test_leaks(self): + from . import PY314 + iters = 100 + if PY314: + expected_refs = [1] * iters + else: + expected_refs = [2] * iters + for name, caller in ( + ("test_switch", + lambda: _test_extension.test_switch(greenlet.greenlet(object))), + ("test_switch_kwargs", + lambda: _test_extension.test_switch_kwargs(greenlet.greenlet(object))), + ("test_new_greenlet", + lambda: _test_extension.test_new_greenlet(object)), + ): + with self.subTest(name): + results = [caller() for _ in range(iters)] + refs = [ + sys.getrefcount(i) - 1 # ignore ref in ``i`` + for i + in results + ] + self.assertEqual(refs, expected_refs) + + +if __name__ == '__main__': + import unittest + unittest.main() diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/tests/test_gc.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/tests/test_gc.py new file mode 100644 index 000000000..898452f1d --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/tests/test_gc.py @@ -0,0 +1,86 @@ +import gc + +import weakref + +import greenlet + + +from . import TestCase +from .leakcheck import fails_leakcheck +# These only work with greenlet gc support +# which is no longer optional. +assert greenlet.GREENLET_USE_GC + +class TestGC(TestCase): + def test_dead_circular_ref(self): + o = weakref.ref(greenlet.greenlet(greenlet.getcurrent).switch()) + gc.collect() + if o() is not None: + import sys + print("O IS NOT NONE.", sys.getrefcount(o())) + self.assertIsNone(o()) + self.assertFalse(gc.garbage, gc.garbage) + + def test_circular_greenlet(self): + class circular_greenlet(greenlet.greenlet): + self = None + o = circular_greenlet() + o.self = o + o = weakref.ref(o) + gc.collect() + self.assertIsNone(o()) + self.assertFalse(gc.garbage, gc.garbage) + + def test_inactive_ref(self): + class inactive_greenlet(greenlet.greenlet): + def __init__(self): + greenlet.greenlet.__init__(self, run=self.run) + + def run(self): + pass + o = inactive_greenlet() + o = weakref.ref(o) + gc.collect() + self.assertIsNone(o()) + self.assertFalse(gc.garbage, gc.garbage) + + @fails_leakcheck + def test_finalizer_crash(self): + # This test is designed to crash when active greenlets + # are made garbage collectable, until the underlying + # problem is resolved. How does it work: + # - order of object creation is important + # - array is created first, so it is moved to unreachable first + # - we create a cycle between a greenlet and this array + # - we create an object that participates in gc, is only + # referenced by a greenlet, and would corrupt gc lists + # on destruction, the easiest is to use an object with + # a finalizer + # - because array is the first object in unreachable it is + # cleared first, which causes all references to greenlet + # to disappear and causes greenlet to be destroyed, but since + # it is still live it causes a switch during gc, which causes + # an object with finalizer to be destroyed, which causes stack + # corruption and then a crash + + class object_with_finalizer(object): + def __del__(self): + pass + array = [] + parent = greenlet.getcurrent() + def greenlet_body(): + greenlet.getcurrent().object = object_with_finalizer() + try: + parent.switch() + except greenlet.GreenletExit: + print("Got greenlet exit!") + finally: + del greenlet.getcurrent().object + g = greenlet.greenlet(greenlet_body) + g.array = array + array.append(g) + g.switch() + del array + del g + greenlet.getcurrent() + gc.collect() diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/tests/test_generator.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/tests/test_generator.py new file mode 100644 index 000000000..ca4a644b6 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/tests/test_generator.py @@ -0,0 +1,59 @@ + +from greenlet import greenlet + +from . import TestCase + +class genlet(greenlet): + parent = None + def __init__(self, *args, **kwds): + self.args = args + self.kwds = kwds + + def run(self): + fn, = self.fn + fn(*self.args, **self.kwds) + + def __iter__(self): + return self + + def __next__(self): + self.parent = greenlet.getcurrent() + result = self.switch() + if self: + return result + + raise StopIteration + + next = __next__ + + +def Yield(value): + g = greenlet.getcurrent() + while not isinstance(g, genlet): + if g is None: + raise RuntimeError('yield outside a genlet') + g = g.parent + g.parent.switch(value) + + +def generator(func): + class Generator(genlet): + fn = (func,) + return Generator + +# ____________________________________________________________ + + +class GeneratorTests(TestCase): + def test_generator(self): + seen = [] + + def g(n): + for i in range(n): + seen.append(i) + Yield(i) + g = generator(g) + for _ in range(3): + for j in g(5): + seen.append(j) + self.assertEqual(seen, 3 * [0, 0, 1, 1, 2, 2, 3, 3, 4, 4]) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/tests/test_generator_nested.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/tests/test_generator_nested.py new file mode 100644 index 000000000..8d752a63d --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/tests/test_generator_nested.py @@ -0,0 +1,168 @@ + +from greenlet import greenlet +from . import TestCase +from .leakcheck import fails_leakcheck + +class genlet(greenlet): + parent = None + def __init__(self, *args, **kwds): + self.args = args + self.kwds = kwds + self.child = None + + def run(self): + # Note the function is packed in a tuple + # to avoid creating a bound method for it. + fn, = self.fn + fn(*self.args, **self.kwds) + + def __iter__(self): + return self + + def set_child(self, child): + self.child = child + + def __next__(self): + if self.child: + child = self.child + while child.child: + tmp = child + child = child.child + tmp.child = None + + result = child.switch() + else: + self.parent = greenlet.getcurrent() + result = self.switch() + + if self: + return result + + raise StopIteration + + next = __next__ + +def Yield(value, level=1): + g = greenlet.getcurrent() + + while level != 0: + if not isinstance(g, genlet): + raise RuntimeError('yield outside a genlet') + if level > 1: + g.parent.set_child(g) + g = g.parent + level -= 1 + + g.switch(value) + + +def Genlet(func): + class TheGenlet(genlet): + fn = (func,) + return TheGenlet + +# ____________________________________________________________ + + +def g1(n, seen): + for i in range(n): + seen.append(i + 1) + yield i + + +def g2(n, seen): + for i in range(n): + seen.append(i + 1) + Yield(i) + +g2 = Genlet(g2) + + +def nested(i): + Yield(i) + + +def g3(n, seen): + for i in range(n): + seen.append(i + 1) + nested(i) +g3 = Genlet(g3) + + +def a(n): + if n == 0: + return + for ii in ax(n - 1): + Yield(ii) + Yield(n) +ax = Genlet(a) + + +def perms(l): + if len(l) > 1: + for e in l: + # No syntactical sugar for generator expressions + x = [Yield([e] + p) for p in perms([x for x in l if x != e])] + assert x + else: + Yield(l) +perms = Genlet(perms) + + +def gr1(n): + for ii in range(1, n): + Yield(ii) + Yield(ii * ii, 2) + +gr1 = Genlet(gr1) + + +def gr2(n, seen): + for ii in gr1(n): + seen.append(ii) + +gr2 = Genlet(gr2) + + +class NestedGeneratorTests(TestCase): + def test_layered_genlets(self): + seen = [] + for ii in gr2(5, seen): + seen.append(ii) + self.assertEqual(seen, [1, 1, 2, 4, 3, 9, 4, 16]) + + @fails_leakcheck + def test_permutations(self): + gen_perms = perms(list(range(4))) + permutations = list(gen_perms) + self.assertEqual(len(permutations), 4 * 3 * 2 * 1) + self.assertIn([0, 1, 2, 3], permutations) + self.assertIn([3, 2, 1, 0], permutations) + res = [] + for ii in zip(perms(list(range(4))), perms(list(range(3)))): + res.append(ii) + self.assertEqual( + res, + [([0, 1, 2, 3], [0, 1, 2]), ([0, 1, 3, 2], [0, 2, 1]), + ([0, 2, 1, 3], [1, 0, 2]), ([0, 2, 3, 1], [1, 2, 0]), + ([0, 3, 1, 2], [2, 0, 1]), ([0, 3, 2, 1], [2, 1, 0])]) + # XXX Test to make sure we are working as a generator expression + + def test_genlet_simple(self): + for g in g1, g2, g3: + seen = [] + for _ in range(3): + for j in g(5, seen): + seen.append(j) + self.assertEqual(seen, 3 * [1, 0, 2, 1, 3, 2, 4, 3, 5, 4]) + + def test_genlet_bad(self): + try: + Yield(10) + except RuntimeError: + pass + + def test_nested_genlets(self): + seen = [] + for ii in ax(5): + seen.append(ii) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/tests/test_greenlet.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/tests/test_greenlet.py new file mode 100644 index 000000000..5e184518d --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/tests/test_greenlet.py @@ -0,0 +1,1426 @@ +import gc +import sys +import time +import threading +import unittest + +from abc import ABCMeta +from abc import abstractmethod + +import greenlet +from greenlet import greenlet as RawGreenlet +from . import TestCase +from . import RUNNING_ON_MANYLINUX +from . import PY313 +from . import PY314 +from . import RUNNING_ON_FREETHREAD_BUILD +from .leakcheck import fails_leakcheck +from .leakcheck import ignores_leakcheck + + +# We manually manage locks in many tests +# pylint:disable=consider-using-with +# pylint:disable=too-many-public-methods +# This module is quite large. +# TODO: Refactor into separate test files. For example, +# put all the regression tests that used to produce +# crashes in test_greenlet_no_crash; put tests that DO deliberately crash +# the interpreter into test_greenlet_crash. +# pylint:disable=too-many-lines + +class SomeError(Exception): + pass + + +def fmain(seen): + try: + greenlet.getcurrent().parent.switch() + except: + seen.append(sys.exc_info()[0]) + raise + raise SomeError + + +def send_exception(g, exc): + # note: send_exception(g, exc) can be now done with g.throw(exc). + # the purpose of this test is to explicitly check the propagation rules. + def crasher(exc): + raise exc + g1 = RawGreenlet(crasher, parent=g) + g1.switch(exc) + + +class TestGreenlet(TestCase): + + def _do_simple_test(self): + lst = [] + + def f(): + lst.append(1) + greenlet.getcurrent().parent.switch() + lst.append(3) + g = RawGreenlet(f) + lst.append(0) + g.switch() + lst.append(2) + g.switch() + lst.append(4) + self.assertEqual(lst, list(range(5))) + + def test_simple(self): + self._do_simple_test() + + def test_switch_no_run_raises_AttributeError(self): + g = RawGreenlet() + with self.assertRaises(AttributeError) as exc: + g.switch() + + self.assertIn("run", str(exc.exception)) + + def test_throw_no_run_raises_AttributeError(self): + g = RawGreenlet() + with self.assertRaises(AttributeError) as exc: + g.throw(SomeError) + + self.assertIn("run", str(exc.exception)) + + def test_parent_equals_None(self): + g = RawGreenlet(parent=None) + self.assertIsNotNone(g) + self.assertIs(g.parent, greenlet.getcurrent()) + + def test_run_equals_None(self): + g = RawGreenlet(run=None) + self.assertIsNotNone(g) + self.assertIsNone(g.run) + + def test_two_children(self): + lst = [] + + def f(): + lst.append(1) + greenlet.getcurrent().parent.switch() + lst.extend([1, 1]) + g = RawGreenlet(f) + h = RawGreenlet(f) + g.switch() + self.assertEqual(len(lst), 1) + h.switch() + self.assertEqual(len(lst), 2) + h.switch() + self.assertEqual(len(lst), 4) + self.assertEqual(h.dead, True) + g.switch() + self.assertEqual(len(lst), 6) + self.assertEqual(g.dead, True) + + def test_two_recursive_children(self): + lst = [] + + def f(): + lst.append('b') + greenlet.getcurrent().parent.switch() + + def g(): + lst.append('a') + g = RawGreenlet(f) + g.switch() + lst.append('c') + self.assertEqual(sys.getrefcount(g), 2 if not PY314 else 1) + g = RawGreenlet(g) + # Python 3.14 elides reference counting operations + # in some cases. See https://github.com/python/cpython/pull/130708 + self.assertEqual(sys.getrefcount(g), 2 if not PY314 else 1) + g.switch() + self.assertEqual(lst, ['a', 'b', 'c']) + # Just the one in this frame, plus the one on the stack we pass to the function + self.assertEqual(sys.getrefcount(g), 2 if not PY314 else 1) + + def test_threads(self): + success = [] + + def f(): + self._do_simple_test() + success.append(True) + ths = [threading.Thread(target=f) for i in range(10)] + for th in ths: + th.start() + for th in ths: + th.join(10) + self.assertEqual(len(success), len(ths)) + + @ignores_leakcheck + def test_switching_many_threads(self): + # This can expose issues on the free-threaded build. + def creates_greenlet(greenlets, wait_to_die_until): + def body(): + while True: + greenlet.getcurrent().parent.switch() + g = greenlet.greenlet(body) + g.switch() + greenlets.append(g) + wait_to_die_until.wait() + + def switches_from_other_thread(greenlets, wait_to_check_until, quit_after): + wait_to_check_until.wait() + while not quit_after.is_set(): + for g in list(greenlets): + try: + if not g.dead: + g.switch() + except greenlet.error: + # Every attempt where the greenlet isn't dead should + # raise this + pass + + def run_it(thread_count=16): + greenlets = [] + greenlets_all_created = threading.Event() + all_threads_dead = threading.Event() + + creators = [ + threading.Thread(target=creates_greenlet, args=(greenlets, + greenlets_all_created)) + for _ + in range(thread_count) + ] + + switchers = [ + threading.Thread(target=switches_from_other_thread, + args=(greenlets, greenlets_all_created, + all_threads_dead)) + for _ + in range(thread_count) + ] + + for t in (creators + switchers): + t.start() + + # Simple polling loop + while len(greenlets) < thread_count: + time.sleep(0.0001) + greenlets_all_created.set() + + for t in creators: + t.join(1.0) + all_threads_dead.set() + for t in switchers: + t.join(1.0) + + # enough reps to have a chance of repeating, not so many it + # takes forever + for _ in range(20): + run_it() + gc.collect() + + def test_exception(self): + seen = [] + g1 = RawGreenlet(fmain) + g2 = RawGreenlet(fmain) + g1.switch(seen) + g2.switch(seen) + g2.parent = g1 + + self.assertEqual(seen, []) + #with self.assertRaises(SomeError): + # p("***Switching back") + # g2.switch() + # Creating this as a bound method can reveal bugs that + # are hidden on newer versions of Python that avoid creating + # bound methods for direct expressions; IOW, don't use the `with` + # form! + self.assertRaises(SomeError, g2.switch) + self.assertEqual(seen, [SomeError]) + + value = g2.switch() + self.assertEqual(value, ()) + self.assertEqual(seen, [SomeError]) + + value = g2.switch(25) + self.assertEqual(value, 25) + self.assertEqual(seen, [SomeError]) + + + def test_send_exception(self): + seen = [] + g1 = RawGreenlet(fmain) + g1.switch(seen) + self.assertRaises(KeyError, send_exception, g1, KeyError) + self.assertEqual(seen, [KeyError]) + + def test_dealloc(self): + seen = [] + g1 = RawGreenlet(fmain) + g2 = RawGreenlet(fmain) + g1.switch(seen) + g2.switch(seen) + self.assertEqual(seen, []) + del g1 + gc.collect() + self.assertEqual(seen, [greenlet.GreenletExit]) + del g2 + gc.collect() + self.assertEqual(seen, [greenlet.GreenletExit, greenlet.GreenletExit]) + + def test_dealloc_catches_GreenletExit_throws_other(self): + def run(): + try: + greenlet.getcurrent().parent.switch() + except greenlet.GreenletExit: + raise SomeError from None + + g = RawGreenlet(run) + g.switch() + + unraisable_events = [] + old_hook = sys.unraisablehook + def _capture(unraisable): + unraisable_events.append(unraisable) + sys.unraisablehook = _capture + try: + del g + finally: + sys.unraisablehook = old_hook + + self.assertEqual(len(unraisable_events), 1) + self.assertIsInstance(unraisable_events[0].exc_value, SomeError) + + + @unittest.skipIf( + PY313 and RUNNING_ON_MANYLINUX, + "Sometimes flaky (getting one GreenletExit in the second list)" + # Probably due to funky timing interactions? + # TODO: FIXME Make that work. + ) + + def test_dealloc_other_thread(self): + seen = [] + someref = [] + + bg_glet_created_running_and_no_longer_ref_in_bg = threading.Event() + fg_ref_released = threading.Event() + bg_should_be_clear = threading.Event() + ok_to_exit_bg_thread = threading.Event() + + def f(): + g1 = RawGreenlet(fmain) + g1.switch(seen) + someref.append(g1) + del g1 + gc.collect() + bg_glet_created_running_and_no_longer_ref_in_bg.set() + fg_ref_released.wait(3) + + RawGreenlet() # trigger release + bg_should_be_clear.set() + ok_to_exit_bg_thread.wait(3) + RawGreenlet() # One more time + + t = threading.Thread(target=f) + t.start() + bg_glet_created_running_and_no_longer_ref_in_bg.wait(10) + + self.assertEqual(seen, []) + self.assertEqual(len(someref), 1) + del someref[:] + if not RUNNING_ON_FREETHREAD_BUILD: + # The free-threaded GC is very different. In 3.14rc1, + # the free-threaded GC traverses ``g1``, realizes it is + # not referenced from anywhere else IT cares about, + # calls ``tp_clear`` and then ``green_dealloc``. This causes + # the greenlet to lose its reference to the main greenlet and thread + # in which it was running, which means we can no longer throw an + # exception into it, preventing the rest of this test from working. + # Standard 3.14 traverses the object but doesn't ``tp_clear`` or + # ``green_dealloc`` it. + gc.collect() + # g1 is not released immediately because it's from another thread; + # switching back to that thread will allocate a greenlet and thus + # trigger deletion actions. + self.assertEqual(seen, []) + fg_ref_released.set() + bg_should_be_clear.wait(3) + try: + self.assertEqual(seen, [greenlet.GreenletExit]) + finally: + ok_to_exit_bg_thread.set() + t.join(10) + del seen[:] + del someref[:] + + def test_frame(self): + def f1(): + f = sys._getframe(0) # pylint:disable=protected-access + self.assertEqual(f.f_back, None) + greenlet.getcurrent().parent.switch(f) + return "meaning of life" + g = RawGreenlet(f1) + frame = g.switch() + self.assertTrue(frame is g.gr_frame) + self.assertTrue(g) + + from_g = g.switch() + self.assertFalse(g) + self.assertEqual(from_g, 'meaning of life') + self.assertEqual(g.gr_frame, None) + + def test_thread_bug(self): + def runner(x): + g = RawGreenlet(lambda: time.sleep(x)) + g.switch() + t1 = threading.Thread(target=runner, args=(0.2,)) + t2 = threading.Thread(target=runner, args=(0.3,)) + t1.start() + t2.start() + t1.join(10) + t2.join(10) + + def test_switch_kwargs(self): + def run(a, b): + self.assertEqual(a, 4) + self.assertEqual(b, 2) + return 42 + x = RawGreenlet(run).switch(a=4, b=2) + self.assertEqual(x, 42) + + def test_switch_kwargs_to_parent(self): + def run(x): + greenlet.getcurrent().parent.switch(x=x) + greenlet.getcurrent().parent.switch(2, x=3) + return x, x ** 2 + g = RawGreenlet(run) + self.assertEqual({'x': 3}, g.switch(3)) + self.assertEqual(((2,), {'x': 3}), g.switch()) + self.assertEqual((3, 9), g.switch()) + + def test_switch_to_another_thread(self): + data = {} + created_event = threading.Event() + done_event = threading.Event() + + def run(): + data['g'] = RawGreenlet(lambda: None) + created_event.set() + done_event.wait(10) + thread = threading.Thread(target=run) + thread.start() + created_event.wait(10) + with self.assertRaises(greenlet.error): + data['g'].switch() + done_event.set() + thread.join(10) + # XXX: Should handle this automatically + data.clear() + + def test_exc_state(self): + def f(): + try: + raise ValueError('fun') + except: # pylint:disable=bare-except + exc_info = sys.exc_info() + RawGreenlet(h).switch() + self.assertEqual(exc_info, sys.exc_info()) + + def h(): + self.assertEqual(sys.exc_info(), (None, None, None)) + + RawGreenlet(f).switch() + + def test_instance_dict(self): + def f(): + greenlet.getcurrent().test = 42 + def deldict(g): + del g.__dict__ + def setdict(g, value): + g.__dict__ = value + g = RawGreenlet(f) + self.assertEqual(g.__dict__, {}) + g.switch() + self.assertEqual(g.test, 42) + self.assertEqual(g.__dict__, {'test': 42}) + g.__dict__ = g.__dict__ + self.assertEqual(g.__dict__, {'test': 42}) + self.assertRaises(TypeError, deldict, g) + self.assertRaises(TypeError, setdict, g, 42) + + def test_running_greenlet_has_no_run(self): + has_run = [] + def func(): + has_run.append( + hasattr(greenlet.getcurrent(), 'run') + ) + + g = RawGreenlet(func) + g.switch() + self.assertEqual(has_run, [False]) + + def test_deepcopy(self): + import copy + self.assertRaises(TypeError, copy.copy, RawGreenlet()) + self.assertRaises(TypeError, copy.deepcopy, RawGreenlet()) + + def test_parent_restored_on_kill(self): + hub = RawGreenlet(lambda: None) + main = greenlet.getcurrent() + result = [] + def worker(): + try: + # Wait to be killed by going back to the test. + main.switch() + except greenlet.GreenletExit: + # Resurrect and switch to parent + result.append(greenlet.getcurrent().parent) + result.append(greenlet.getcurrent()) + hub.switch() + g = RawGreenlet(worker, parent=hub) + g.switch() + # delete the only reference, thereby raising GreenletExit + del g + self.assertTrue(result) + self.assertIs(result[0], main) + self.assertIs(result[1].parent, hub) + # Delete them, thereby breaking the cycle between the greenlet + # and the frame, which otherwise would never be collectable + # XXX: We should be able to automatically fix this. + del result[:] + hub = None + main = None + + def test_parent_return_failure(self): + # No run causes AttributeError on switch + g1 = RawGreenlet() + # Greenlet that implicitly switches to parent + g2 = RawGreenlet(lambda: None, parent=g1) + # AttributeError should propagate to us, no fatal errors + with self.assertRaises(AttributeError): + g2.switch() + + def test_throw_exception_not_lost(self): + class mygreenlet(RawGreenlet): + def __getattribute__(self, name): + try: + raise Exception # pylint:disable=broad-exception-raised + except: # pylint:disable=bare-except + pass + return RawGreenlet.__getattribute__(self, name) + g = mygreenlet(lambda: None) + self.assertRaises(SomeError, g.throw, SomeError()) + + @fails_leakcheck + def _do_test_throw_to_dead_thread_doesnt_crash(self, wait_for_cleanup=False): + result = [] + def worker(): + greenlet.getcurrent().parent.switch() + + def creator(): + g = RawGreenlet(worker) + g.switch() + result.append(g) + if wait_for_cleanup: + # Let this greenlet eventually be cleaned up. + g.switch() + greenlet.getcurrent() + t = threading.Thread(target=creator) + t.start() + t.join(10) + del t + # But, depending on the operating system, the thread + # deallocator may not actually have run yet! So we can't be + # sure about the error message unless we wait. + if wait_for_cleanup: + self.wait_for_pending_cleanups() + with self.assertRaises(greenlet.error) as exc: + result[0].throw(SomeError) + + if not wait_for_cleanup: + s = str(exc.exception) + self.assertTrue( + s == "cannot switch to a different thread (which happens to have exited)" + or 'Cannot switch' in s + ) + else: + self.assertEqual( + str(exc.exception), + "cannot switch to a different thread (which happens to have exited)", + ) + + if hasattr(result[0].gr_frame, 'clear'): + # The frame is actually executing (it thinks), we can't clear it. + with self.assertRaises(RuntimeError): + result[0].gr_frame.clear() + # Unfortunately, this doesn't actually clear the references, they're in the + # fast local array. + if not wait_for_cleanup: + # f_locals has no clear method in Python 3.13 + if hasattr(result[0].gr_frame.f_locals, 'clear'): + result[0].gr_frame.f_locals.clear() + else: + self.assertIsNone(result[0].gr_frame) + + del creator + worker = None + del result[:] + # XXX: we ought to be able to automatically fix this. + # See issue 252 + self.expect_greenlet_leak = True # direct us not to wait for it to go away + + @fails_leakcheck + def test_throw_to_dead_thread_doesnt_crash(self): + self._do_test_throw_to_dead_thread_doesnt_crash() + + def test_throw_to_dead_thread_doesnt_crash_wait(self): + self._do_test_throw_to_dead_thread_doesnt_crash(True) + + @fails_leakcheck + def test_recursive_startup(self): + class convoluted(RawGreenlet): + def __init__(self): + RawGreenlet.__init__(self) + self.count = 0 + def __getattribute__(self, name): + if name == 'run' and self.count == 0: + self.count = 1 + self.switch(43) + return RawGreenlet.__getattribute__(self, name) + def run(self, value): + while True: + self.parent.switch(value) + g = convoluted() + self.assertEqual(g.switch(42), 43) + # Exits the running greenlet, otherwise it leaks + # XXX: We should be able to automatically fix this + #g.throw(greenlet.GreenletExit) + #del g + self.expect_greenlet_leak = True + + def test_threaded_updatecurrent(self): + # released when main thread should execute + lock1 = threading.Lock() + lock1.acquire() + # released when another thread should execute + lock2 = threading.Lock() + lock2.acquire() + class finalized(object): + def __del__(self): + # happens while in green_updatecurrent() in main greenlet + # should be very careful not to accidentally call it again + # at the same time we must make sure another thread executes + lock2.release() + lock1.acquire() + # now ts_current belongs to another thread + def deallocator(): + greenlet.getcurrent().parent.switch() + def fthread(): + lock2.acquire() + greenlet.getcurrent() + del g[0] + lock1.release() + lock2.acquire() + greenlet.getcurrent() + lock1.release() + main = greenlet.getcurrent() + g = [RawGreenlet(deallocator)] + g[0].bomb = finalized() + g[0].switch() + t = threading.Thread(target=fthread) + t.start() + # let another thread grab ts_current and deallocate g[0] + lock2.release() + lock1.acquire() + # this is the corner stone + # getcurrent() will notice that ts_current belongs to another thread + # and start the update process, which would notice that g[0] should + # be deallocated, and that will execute an object's finalizer. Now, + # that object will let another thread run so it can grab ts_current + # again, which would likely crash the interpreter if there's no + # check for this case at the end of green_updatecurrent(). This test + # passes if getcurrent() returns correct result, but it's likely + # to randomly crash if it's not anyway. + self.assertEqual(greenlet.getcurrent(), main) + # wait for another thread to complete, just in case + t.join(10) + + def test_dealloc_switch_args_not_lost(self): + seen = [] + def worker(): + # wait for the value + value = greenlet.getcurrent().parent.switch() + # delete all references to ourself + del worker[0] + initiator.parent = greenlet.getcurrent().parent + # switch to main with the value, but because + # ts_current is the last reference to us we + # return here immediately, where we resurrect ourself. + try: + greenlet.getcurrent().parent.switch(value) + finally: + seen.append(greenlet.getcurrent()) + def initiator(): + return 42 # implicitly falls thru to parent + + worker = [RawGreenlet(worker)] + + worker[0].switch() # prime worker + initiator = RawGreenlet(initiator, worker[0]) + value = initiator.switch() + self.assertTrue(seen) + self.assertEqual(value, 42) + + def test_tuple_subclass(self): + # The point of this test is to see what happens when a custom + # tuple subclass is used as an object passed directly to the C + # function ``green_switch``; part of ``green_switch`` checks + # the ``len()`` of the ``args`` tuple, and that can call back + # into Python. Here, when it calls back into Python, we + # recursively enter ``green_switch`` again. + + # This test is really only relevant on Python 2. The builtin + # `apply` function directly passes the given args tuple object + # to the underlying function, whereas the Python 3 version + # unpacks and repacks into an actual tuple. This could still + # happen using the C API on Python 3 though. We should write a + # builtin version of apply() ourself. + def _apply(func, a, k): + func(*a, **k) + + class mytuple(tuple): + def __len__(self): + greenlet.getcurrent().switch() + return tuple.__len__(self) + args = mytuple() + kwargs = dict(a=42) + def switchapply(): + _apply(greenlet.getcurrent().parent.switch, args, kwargs) + g = RawGreenlet(switchapply) + self.assertEqual(g.switch(), kwargs) + + def test_abstract_subclasses(self): + AbstractSubclass = ABCMeta( + 'AbstractSubclass', + (RawGreenlet,), + {'run': abstractmethod(lambda self: None)}) + + class BadSubclass(AbstractSubclass): + pass + + class GoodSubclass(AbstractSubclass): + def run(self): + pass + + GoodSubclass() # should not raise + self.assertRaises(TypeError, BadSubclass) + + def test_implicit_parent_with_threads(self): + if not gc.isenabled(): + return # cannot test with disabled gc + N = gc.get_threshold()[0] + if N < 50: + return # cannot test with such a small N + def attempt(): + lock1 = threading.Lock() + lock1.acquire() + lock2 = threading.Lock() + lock2.acquire() + recycled = [False] + def another_thread(): + lock1.acquire() # wait for gc + greenlet.getcurrent() # update ts_current + lock2.release() # release gc + t = threading.Thread(target=another_thread) + t.start() + class gc_callback(object): + def __del__(self): + lock1.release() + lock2.acquire() + recycled[0] = True + class garbage(object): + def __init__(self): + self.cycle = self + self.callback = gc_callback() + l = [] + x = range(N*2) + current = greenlet.getcurrent() + g = garbage() + for _ in x: + g = None # lose reference to garbage + if recycled[0]: + # gc callback called prematurely + t.join(10) + return False + last = RawGreenlet() + if recycled[0]: + break # yes! gc called in green_new + l.append(last) # increase allocation counter + else: + # gc callback not called when expected + gc.collect() + if recycled[0]: + t.join(10) + return False + self.assertEqual(last.parent, current) + for g in l: + self.assertEqual(g.parent, current) + return True + for _ in range(5): + if attempt(): + break + + def test_issue_245_reference_counting_subclass_no_threads(self): + # https://github.com/python-greenlet/greenlet/issues/245 + # Before the fix, this crashed pretty reliably on + # Python 3.10, at least on macOS; but much less reliably on other + # interpreters (memory layout must have changed). + # The threaded test crashed more reliably on more interpreters. + from greenlet import getcurrent + from greenlet import GreenletExit + + class Greenlet(RawGreenlet): + pass + + initial_refs = sys.getrefcount(Greenlet) + # This has to be an instance variable because + # Python 2 raises a SyntaxError if we delete a local + # variable referenced in an inner scope. + self.glets = [] # pylint:disable=attribute-defined-outside-init + + def greenlet_main(): + try: + getcurrent().parent.switch() + except GreenletExit: + self.glets.append(getcurrent()) + + # Before the + for _ in range(10): + Greenlet(greenlet_main).switch() + + del self.glets + if RUNNING_ON_FREETHREAD_BUILD: + # Free-threaded builds make types immortal, which gives us + # weird numbers here, and we actually do APPEAR to end + # up with one more reference than we started with, at least on 3.14. + # If we change the code in green_dealloc to avoid increffing the type + # (which fixed this initial bug), then our leakchecks find other objects + # that have leaked, including a tuple, a dict, and a type. So that's not the + # right solution. Instead we change the test: + # XXX: FIXME: Is there a better way? + self.assertGreaterEqual(sys.getrefcount(Greenlet), initial_refs) + else: + self.assertEqual(sys.getrefcount(Greenlet), initial_refs) + + @unittest.skipIf( + PY313 and RUNNING_ON_MANYLINUX, + "The manylinux images appear to hang on this test on 3.13rc2" + # Or perhaps I just got tired of waiting for the 450s timeout. + # Still, it shouldn't take anywhere near that long. Does not reproduce in + # Ubuntu images, on macOS or Windows. + ) + def test_issue_245_reference_counting_subclass_threads(self): + # https://github.com/python-greenlet/greenlet/issues/245 + from threading import Thread + from threading import Event + + from greenlet import getcurrent + + class MyGreenlet(RawGreenlet): + pass + + glets = [] + ref_cleared = Event() + + def greenlet_main(): + getcurrent().parent.switch() + + def thread_main(greenlet_running_event): + mine = MyGreenlet(greenlet_main) + glets.append(mine) + # The greenlets being deleted must be active + mine.switch() + # Don't keep any reference to it in this thread + del mine + # Let main know we published our greenlet. + greenlet_running_event.set() + # Wait for main to let us know the references are + # gone and the greenlet objects no longer reachable + ref_cleared.wait(10) + # The creating thread must call getcurrent() (or a few other + # greenlet APIs) because that's when the thread-local list of dead + # greenlets gets cleared. + getcurrent() + + # We start with 3 references to the subclass: + # - This module + # - Its __mro__ + # - The __subclassess__ attribute of greenlet + # - (If we call gc.get_referents(), we find four entries, including + # some other tuple ``(greenlet)`` that I'm not sure about but must be part + # of the machinery.) + # + # On Python 3.10 it's often enough to just run 3 threads; on Python 2.7, + # more threads are needed, and the results are still + # non-deterministic. Presumably the memory layouts are different + initial_refs = sys.getrefcount(MyGreenlet) + thread_ready_events = [] + thread_count = initial_refs + 45 + if RUNNING_ON_FREETHREAD_BUILD: + # types are immortal, so this is a HUGE number most likely, + # and we can't create that many threads. + thread_count = 50 + for _ in range(thread_count): + event = Event() + thread = Thread(target=thread_main, args=(event,)) + thread_ready_events.append(event) + thread.start() + + + for done_event in thread_ready_events: + done_event.wait(10) + + + del glets[:] + ref_cleared.set() + # Let any other thread run; it will crash the interpreter + # if not fixed (or silently corrupt memory and we possibly crash + # later). + self.wait_for_pending_cleanups() + self.assertEqual(sys.getrefcount(MyGreenlet), initial_refs) + + def test_falling_off_end_switches_to_unstarted_parent_raises_error(self): + def no_args(): + return 13 + + parent_never_started = RawGreenlet(no_args) + + def leaf(): + return 42 + + child = RawGreenlet(leaf, parent_never_started) + + # Because the run function takes to arguments + with self.assertRaises(TypeError): + child.switch() + + def test_falling_off_end_switches_to_unstarted_parent_works(self): + def one_arg(x): + return (x, 24) + + parent_never_started = RawGreenlet(one_arg) + + def leaf(): + return 42 + + child = RawGreenlet(leaf, parent_never_started) + + result = child.switch() + self.assertEqual(result, (42, 24)) + + def test_switch_to_dead_greenlet_with_unstarted_perverse_parent(self): + class Parent(RawGreenlet): + def __getattribute__(self, name): + if name == 'run': + raise SomeError + + + parent_never_started = Parent() + seen = [] + child = RawGreenlet(lambda: seen.append(42), parent_never_started) + # Because we automatically start the parent when the child is + # finished + with self.assertRaises(SomeError): + child.switch() + + self.assertEqual(seen, [42]) + + with self.assertRaises(SomeError): + child.switch() + self.assertEqual(seen, [42]) + + def test_switch_to_dead_greenlet_reparent(self): + seen = [] + parent_never_started = RawGreenlet(lambda: seen.append(24)) + child = RawGreenlet(lambda: seen.append(42)) + + child.switch() + self.assertEqual(seen, [42]) + + child.parent = parent_never_started + # This actually is the same as switching to the parent. + result = child.switch() + self.assertIsNone(result) + self.assertEqual(seen, [42, 24]) + + def test_can_access_f_back_of_suspended_greenlet(self): + # This tests our frame rewriting to work around Python 3.12+ having + # some interpreter frames on the C stack. It will crash in the absence + # of that logic. + main = greenlet.getcurrent() + + def outer(): + inner() + + def inner(): + main.switch(sys._getframe(0)) + + hub = RawGreenlet(outer) + # start it + hub.switch() + + # start another greenlet to make sure we aren't relying on + # anything in `hub` still being on the C stack + unrelated = RawGreenlet(lambda: None) + unrelated.switch() + + # now it is suspended + self.assertIsNotNone(hub.gr_frame) + self.assertEqual(hub.gr_frame.f_code.co_name, "inner") + self.assertIsNotNone(hub.gr_frame.f_back) + self.assertEqual(hub.gr_frame.f_back.f_code.co_name, "outer") + # The next line is what would crash + self.assertIsNone(hub.gr_frame.f_back.f_back) + + def test_get_stack_with_nested_c_calls(self): + from functools import partial + from . import _test_extension_cpp + + def recurse(v): + if v > 0: + return v * _test_extension_cpp.test_call(partial(recurse, v - 1)) + return greenlet.getcurrent().parent.switch() + + gr = RawGreenlet(recurse) + gr.switch(5) + frame = gr.gr_frame + for i in range(5): + self.assertEqual(frame.f_locals["v"], i) + frame = frame.f_back + self.assertEqual(frame.f_locals["v"], 5) + self.assertIsNone(frame.f_back) + self.assertEqual(gr.switch(10), 1200) # 1200 = 5! * 10 + + def test_frames_always_exposed(self): + # On Python 3.12 this will crash if we don't set the + # gr_frames_always_exposed attribute. More background: + # https://github.com/python-greenlet/greenlet/issues/388 + main = greenlet.getcurrent() + + def outer(): + inner(sys._getframe(0)) + + def inner(frame): + main.switch(frame) + + gr = RawGreenlet(outer) + frame = gr.switch() + + # Do something else to clobber the part of the C stack used by `gr`, + # so we can't skate by on "it just happened to still be there" + unrelated = RawGreenlet(lambda: None) + unrelated.switch() + + self.assertEqual(frame.f_code.co_name, "outer") + # The next line crashes on 3.12 if we haven't exposed the frames. + self.assertIsNone(frame.f_back) + + +class TestGreenletSetParentErrors(TestCase): + def test_threaded_reparent(self): + data = {} + created_event = threading.Event() + done_event = threading.Event() + + def run(): + data['g'] = RawGreenlet(lambda: None) + created_event.set() + done_event.wait(10) + + def blank(): + greenlet.getcurrent().parent.switch() + + thread = threading.Thread(target=run) + thread.start() + created_event.wait(10) + g = RawGreenlet(blank) + g.switch() + with self.assertRaises(ValueError) as exc: + g.parent = data['g'] + done_event.set() + thread.join(10) + + self.assertEqual(str(exc.exception), "parent cannot be on a different thread") + + def test_unexpected_reparenting(self): + another = [] + def worker(): + g = RawGreenlet(lambda: None) + another.append(g) + g.switch() + t = threading.Thread(target=worker) + t.start() + t.join(10) + # The first time we switch (running g_initialstub(), which is + # when we look up the run attribute) we attempt to change the + # parent to one from another thread (which also happens to be + # dead). ``g_initialstub()`` should detect this and raise a + # greenlet error. + # + # EXCEPT: With the fix for #252, this is actually detected + # sooner, when setting the parent itself. Prior to that fix, + # the main greenlet from the background thread kept a valid + # value for ``run_info``, and appeared to be a valid parent + # until we actually started the greenlet. But now that it's + # cleared, this test is catching whether ``green_setparent`` + # can detect the dead thread. + # + # Further refactoring once again changes this back to a greenlet.error + # + # We need to wait for the cleanup to happen, but we're + # deliberately leaking a main greenlet here. + self.wait_for_pending_cleanups(initial_main_greenlets=self.main_greenlets_before_test + 1) + + class convoluted(RawGreenlet): + def __getattribute__(self, name): + if name == 'run': + self.parent = another[0] # pylint:disable=attribute-defined-outside-init + return RawGreenlet.__getattribute__(self, name) + g = convoluted(lambda: None) + with self.assertRaises(greenlet.error) as exc: + g.switch() + self.assertEqual(str(exc.exception), + "cannot switch to a different thread (which happens to have exited)") + del another[:] + + def test_unexpected_reparenting_thread_running(self): + # Like ``test_unexpected_reparenting``, except the background thread is + # actually still alive. + another = [] + switched_to_greenlet = threading.Event() + keep_main_alive = threading.Event() + def worker(): + g = RawGreenlet(lambda: None) + another.append(g) + g.switch() + switched_to_greenlet.set() + keep_main_alive.wait(10) + class convoluted(RawGreenlet): + def __getattribute__(self, name): + if name == 'run': + self.parent = another[0] # pylint:disable=attribute-defined-outside-init + return RawGreenlet.__getattribute__(self, name) + + t = threading.Thread(target=worker) + t.start() + + switched_to_greenlet.wait(10) + try: + g = convoluted(lambda: None) + + with self.assertRaises(greenlet.error) as exc: + g.switch() + self.assertIn("Cannot switch to a different thread", str(exc.exception)) + self.assertIn("Expected", str(exc.exception)) + self.assertIn("Current", str(exc.exception)) + finally: + keep_main_alive.set() + t.join(10) + # XXX: Should handle this automatically. + del another[:] + + def test_cannot_delete_parent(self): + worker = RawGreenlet(lambda: None) + self.assertIs(worker.parent, greenlet.getcurrent()) + + with self.assertRaises(AttributeError) as exc: + del worker.parent + self.assertEqual(str(exc.exception), "can't delete attribute") + + def test_cannot_delete_parent_of_main(self): + with self.assertRaises(AttributeError) as exc: + del greenlet.getcurrent().parent + self.assertEqual(str(exc.exception), "can't delete attribute") + + + def test_main_greenlet_parent_is_none(self): + # assuming we're in a main greenlet here. + self.assertIsNone(greenlet.getcurrent().parent) + + def test_set_parent_wrong_types(self): + def bg(): + # Go back to main. + greenlet.getcurrent().parent.switch() + + def check(glet): + for p in None, 1, self, "42": + with self.assertRaises(TypeError) as exc: + glet.parent = p + + self.assertEqual( + str(exc.exception), + "GreenletChecker: Expected any type of greenlet, not " + type(p).__name__) + + # First, not running + g = RawGreenlet(bg) + self.assertFalse(g) + check(g) + + # Then when running. + g.switch() + self.assertTrue(g) + check(g) + + # Let it finish + g.switch() + + + def test_trivial_cycle(self): + glet = RawGreenlet(lambda: None) + with self.assertRaises(ValueError) as exc: + glet.parent = glet + self.assertEqual(str(exc.exception), "cyclic parent chain") + + def test_trivial_cycle_main(self): + # This used to produce a ValueError, but we catch it earlier than that now. + with self.assertRaises(AttributeError) as exc: + greenlet.getcurrent().parent = greenlet.getcurrent() + self.assertEqual(str(exc.exception), "cannot set the parent of a main greenlet") + + def test_deeper_cycle(self): + g1 = RawGreenlet(lambda: None) + g2 = RawGreenlet(lambda: None) + g3 = RawGreenlet(lambda: None) + + g1.parent = g2 + g2.parent = g3 + with self.assertRaises(ValueError) as exc: + g3.parent = g1 + self.assertEqual(str(exc.exception), "cyclic parent chain") + + +class TestRepr(TestCase): + + if not hasattr(TestCase, 'assertEndsWith'): # Added in 3.14 + def assertEndsWith(self, s, suffix, msg=None): + self.assertTrue(s.endswith(suffix), (s, suffix, msg)) + + def test_main_while_running(self): + r = repr(greenlet.getcurrent()) + self.assertEndsWith(r, " current active started main>") + + def test_main_in_background(self): + main = greenlet.getcurrent() + def run(): + return repr(main) + + g = RawGreenlet(run) + r = g.switch() + self.assertEndsWith(r, ' suspended active started main>') + + def test_initial(self): + r = repr(RawGreenlet()) + self.assertEndsWith(r, ' pending>') + + def test_main_from_other_thread(self): + main = greenlet.getcurrent() + + class T(threading.Thread): + original_main = thread_main = None + main_glet = None + def run(self): + self.original_main = repr(main) + self.main_glet = greenlet.getcurrent() + self.thread_main = repr(self.main_glet) + + t = T() + t.start() + t.join(10) + + self.assertEndsWith(t.original_main, ' suspended active started main>') + self.assertEndsWith(t.thread_main, ' current active started main>') + # give the machinery time to notice the death of the thread, + # and clean it up. Note that we don't use + # ``expect_greenlet_leak`` or wait_for_pending_cleanups, + # because at this point we know we have an extra greenlet + # still reachable. + for _ in range(3): + time.sleep(0.001) + + # In the past, main greenlets, even from dead threads, never + # really appear dead. We have fixed that, and we also report + # that the thread is dead in the repr. (Do this multiple times + # to make sure that we don't self-modify and forget our state + # in the C++ code). + for _ in range(3): + self.assertTrue(t.main_glet.dead) + r = repr(t.main_glet) + self.assertEndsWith(r, ' (thread exited) dead>') + + def test_dead(self): + g = RawGreenlet(lambda: None) + g.switch() + self.assertEndsWith(repr(g), ' dead>') + self.assertNotIn('suspended', repr(g)) + self.assertNotIn('started', repr(g)) + self.assertNotIn('active', repr(g)) + + def test_formatting_produces_native_str(self): + # https://github.com/python-greenlet/greenlet/issues/218 + # %s formatting on Python 2 was producing unicode, not str. + + g_dead = RawGreenlet(lambda: None) + g_not_started = RawGreenlet(lambda: None) + g_cur = greenlet.getcurrent() + + for g in g_dead, g_not_started, g_cur: + + self.assertIsInstance( + '%s' % (g,), + str + ) + self.assertIsInstance( + '%r' % (g,), + str, + ) + + +class TestMainGreenlet(TestCase): + # Tests some implementation details, and relies on some + # implementation details. + + def _check_current_is_main(self): + # implementation detail + assert 'main' in repr(greenlet.getcurrent()) + + t = type(greenlet.getcurrent()) + assert 'main' not in repr(t) + return t + + def test_main_greenlet_type_can_be_subclassed(self): + main_type = self._check_current_is_main() + subclass = type('subclass', (main_type,), {}) + self.assertIsNotNone(subclass) + + def test_main_greenlet_is_greenlet(self): + self._check_current_is_main() + self.assertIsInstance(greenlet.getcurrent(), RawGreenlet) + + + +class TestBrokenGreenlets(TestCase): + # Tests for things that used to, or still do, terminate the interpreter. + # This often means doing unsavory things. + + def test_failed_to_initialstub(self): + def func(): + raise AssertionError("Never get here") + + + g = greenlet._greenlet.UnswitchableGreenlet(func) + g.force_switch_error = True + + with self.assertRaisesRegex(SystemError, + "Failed to switch stacks into a greenlet for the first time."): + g.switch() + + def test_failed_to_switch_into_running(self): + runs = [] + def func(): + runs.append(1) + greenlet.getcurrent().parent.switch() + runs.append(2) + greenlet.getcurrent().parent.switch() + runs.append(3) # pragma: no cover + + g = greenlet._greenlet.UnswitchableGreenlet(func) + g.switch() + self.assertEqual(runs, [1]) + g.switch() + self.assertEqual(runs, [1, 2]) + g.force_switch_error = True + + with self.assertRaisesRegex(SystemError, + "Failed to switch stacks into a running greenlet."): + g.switch() + + # If we stopped here, we would fail the leakcheck, because we've left + # the ``inner_bootstrap()`` C frame and its descendents hanging around, + # which have a bunch of Python references. They'll never get cleaned up + # if we don't let the greenlet finish. + g.force_switch_error = False + g.switch() + self.assertEqual(runs, [1, 2, 3]) + + def test_failed_to_slp_switch_into_running(self): + ex = self.assertScriptRaises('fail_slp_switch.py') + + self.assertIn('fail_slp_switch is running', ex.output) + self.assertIn(ex.returncode, self.get_expected_returncodes_for_aborted_process()) + + def test_reentrant_switch_two_greenlets(self): + # Before we started capturing the arguments in g_switch_finish, this could crash. + output = self.run_script('fail_switch_two_greenlets.py') + self.assertIn('In g1_run', output) + self.assertIn('TRACE', output) + self.assertIn('LEAVE TRACE', output) + self.assertIn('Falling off end of main', output) + self.assertIn('Falling off end of g1_run', output) + self.assertIn('Falling off end of g2', output) + + def test_reentrant_switch_three_greenlets(self): + # On debug builds of greenlet, this used to crash with an assertion error; + # on non-debug versions, it ran fine (which it should not do!). + # Now it always crashes correctly with a TypeError + ex = self.assertScriptRaises('fail_switch_three_greenlets.py', exitcodes=(1,)) + + self.assertIn('TypeError', ex.output) + self.assertIn('positional arguments', ex.output) + + def test_reentrant_switch_three_greenlets2(self): + # This actually passed on debug and non-debug builds. It + # should probably have been triggering some debug assertions + # but it didn't. + # + # I think the fixes for the above test also kicked in here. + output = self.run_script('fail_switch_three_greenlets2.py') + self.assertIn( + "RESULTS: [('trace', 'switch'), " + "('trace', 'switch'), ('g2 arg', 'g2 from tracefunc'), " + "('trace', 'switch'), ('main g1', 'from g2_run'), ('trace', 'switch'), " + "('g1 arg', 'g1 from main'), ('trace', 'switch'), ('main g2', 'from g1_run'), " + "('trace', 'switch'), ('g1 from parent', 'g1 from main 2'), ('trace', 'switch'), " + "('main g1.2', 'g1 done'), ('trace', 'switch'), ('g2 from parent', ()), " + "('trace', 'switch'), ('main g2.2', 'g2 done')]", + output + ) + + def test_reentrant_switch_GreenletAlreadyStartedInPython(self): + output = self.run_script('fail_initialstub_already_started.py') + + self.assertIn( + "RESULTS: ['Begin C', 'Switch to b from B.__getattribute__ in C', " + "('Begin B', ()), '_B_run switching to main', ('main from c', 'From B'), " + "'B.__getattribute__ back from main in C', ('Begin A', (None,)), " + "('A dead?', True, 'B dead?', True, 'C dead?', False), " + "'C done', ('main from c.2', None)]", + output + ) + + def test_reentrant_switch_run_callable_has_del(self): + output = self.run_script('fail_clearing_run_switches.py') + self.assertIn( + "RESULTS [" + "('G.__getattribute__', 'run'), ('RunCallable', '__del__'), " + "('main: g.switch()', 'from RunCallable'), ('run_func', 'enter')" + "]", + output + ) + +class TestModule(TestCase): + + @unittest.skipUnless(hasattr(sys, '_is_gil_enabled'), + "Needs 3.13 and above for sys._is_gil_enabled") + def test_no_gil_on_free_threaded(self): + if RUNNING_ON_FREETHREAD_BUILD: + self.assertFalse(sys._is_gil_enabled()) + else: + self.assertTrue(sys._is_gil_enabled()) + +if __name__ == '__main__': + unittest.main() diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/tests/test_greenlet_trash.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/tests/test_greenlet_trash.py new file mode 100644 index 000000000..66a7ec658 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/tests/test_greenlet_trash.py @@ -0,0 +1,195 @@ +# -*- coding: utf-8 -*- +""" +Tests for greenlets interacting with the CPython trash can API. + +The CPython trash can API is not designed to be re-entered from a +single thread. But this can happen using greenlets, if something +during the object deallocation process switches greenlets, and this second +greenlet then causes the trash can to get entered again. Here, we do this +very explicitly, but in other cases (like gevent) it could be arbitrarily more +complicated: for example, a weakref callback might try to acquire a lock that's +already held by another greenlet; that would allow a greenlet switch to occur. + +See https://github.com/gevent/gevent/issues/1909 + +This test is fragile and relies on details of the CPython +implementation (like most of the rest of this package): + + - We enter the trashcan and deferred deallocation after + ``_PyTrash_UNWIND_LEVEL`` calls. This constant, defined in + CPython's object.c, is generally 50. That's basically how many objects are required to + get us into the deferred deallocation situation. + + - The test fails by hitting an ``assert()`` in object.c; if the + build didn't enable assert, then we don't catch this. + + - If the test fails in that way, the interpreter crashes. +""" + +import unittest + + +class TestTrashCanReEnter(unittest.TestCase): + + def test_it(self): + try: + # pylint:disable-next=no-name-in-module + from greenlet._greenlet import get_tstate_trash_delete_nesting + except ImportError: + import sys + # Python 3.13 has no "trash delete nesting" anymore (but + # "delete later") Our test as written won't be able to check + # the nesting depth anymore, but on debug builds it should + # still be able to trigger a crash if we get things wrong. + # However, at least on 3.14, the greenlet switch in the test + # below never finds an active value for + # ``tstate->delete_later``, meaning this test isn't testing + # what we want it to. + assert sys.version_info[:2] >= (3, 13) + def get_tstate_trash_delete_nesting(): + return 0 + + # Try several times to trigger it, because it isn't 100% + # reliable. + for i in range(30): + with self.subTest(i=i): + self.check_it(get_tstate_trash_delete_nesting) + + def check_it(self, get_tstate_trash_delete_nesting): # pylint:disable=too-many-statements + import greenlet + main = greenlet.getcurrent() + + assert get_tstate_trash_delete_nesting() == 0 + + # We expect to be in deferred deallocation after this many + # deallocations have occurred. TODO: I wish we had a better way to do + # this --- that was before get_tstate_trash_delete_nesting; perhaps + # we can use that API to do better? (Probably not, it is non-functional in + # 3.13+) + TRASH_UNWIND_LEVEL = 500 # 50 is the nominal default on 3.12 + # How many objects to put in a container; it's the container that + # queues objects for deferred deallocation. + OBJECTS_PER_CONTAINER = 1000 + + class Dealloc: # define the class here because we alter class variables each time we run. + """ + An object with a ``__del__`` method. When it starts getting deallocated + from a deferred trash can run, it switches greenlets, allocates more objects + which then also go in the trash can. If we don't save state appropriately, + nesting gets out of order and we can crash the interpreter. + """ + + #: Has our deallocation actually run and switched greenlets? + #: When it does, this will be set to the current greenlet. This should + #: be happening in the main greenlet, so we check that down below. + SPAWNED = False + + #: Has the background greenlet run? + BG_RAN = False + + BG_GLET = None + + #: How many of these things have ever been allocated. + CREATED = 0 + + #: How many of these things have ever been deallocated. + DESTROYED = 0 + + #: How many were destroyed not in the main greenlet. There should always + #: be some. + #: If the test is broken or things change in the trashcan implementation, + #: this may not be correct. + DESTROYED_BG = 0 + + def __init__(self, sequence_number): + """ + :param sequence_number: The ordinal of this object during + one particular creation run. This is used to detect (guess, really) + when we have entered the trash can's deferred deallocation. + """ + self.i = sequence_number + Dealloc.CREATED += 1 + + def __del__(self): + if self.i == TRASH_UNWIND_LEVEL and not self.SPAWNED: + Dealloc.SPAWNED = greenlet.getcurrent() + other = Dealloc.BG_GLET = greenlet.greenlet(background_greenlet) + x = other.switch() + assert x == 42 + # It's important that we don't switch back to the greenlet, + # we leave it hanging there in an incomplete state. But we don't let it + # get collected, either. If we complete it now, while we're still + # in the scope of the initial trash can, things work out and we + # don't see the problem. We need this greenlet to complete + # at some point in the future, after we've exited this trash can invocation. + del other + elif self.i == 40 and greenlet.getcurrent() is not main: + Dealloc.BG_RAN = True + try: + main.switch(42) + except greenlet.GreenletExit as ex: + # We expect this; all references to us go away + # while we're still running, and we need to finish deleting + # ourself. + Dealloc.BG_RAN = type(ex) + del ex + + # Record the fact that we're dead last of all. This ensures that + # we actually get returned too. + Dealloc.DESTROYED += 1 + if greenlet.getcurrent() is not main: + Dealloc.DESTROYED_BG += 1 + + + def background_greenlet(): + # We direct through a second function, instead of + # directly calling ``make_some()``, so that we have complete + # control over when these objects are destroyed: we need them + # to be destroyed in the context of the background greenlet + t = make_some() + del t # Triggere deletion. + + def make_some(): + t = () + i = OBJECTS_PER_CONTAINER + while i: + # Nest the tuples; it's the recursion that gets us + # into trash. + t = (Dealloc(i), t) + i -= 1 + return t + + + some = make_some() + self.assertEqual(Dealloc.CREATED, OBJECTS_PER_CONTAINER) + self.assertEqual(Dealloc.DESTROYED, 0) + + # If we're going to crash, it should be on the following line. + # We only crash if ``assert()`` is enabled, of course. + del some + + # For non-debug builds of CPython, we won't crash. The best we can do is check + # the nesting level explicitly. + self.assertEqual(0, get_tstate_trash_delete_nesting()) + + # Discard this, raising GreenletExit into where it is waiting. + Dealloc.BG_GLET = None + # The same nesting level maintains. + self.assertEqual(0, get_tstate_trash_delete_nesting()) + + # We definitely cleaned some up in the background + self.assertGreater(Dealloc.DESTROYED_BG, 0) + + # Make sure all the cleanups happened. + self.assertIs(Dealloc.SPAWNED, main) + self.assertTrue(Dealloc.BG_RAN) + self.assertEqual(Dealloc.BG_RAN, greenlet.GreenletExit) + self.assertEqual(Dealloc.CREATED, Dealloc.DESTROYED ) + self.assertEqual(Dealloc.CREATED, OBJECTS_PER_CONTAINER * 2) + + import gc + gc.collect() + + +if __name__ == '__main__': + unittest.main() diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/tests/test_interpreter_shutdown.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/tests/test_interpreter_shutdown.py new file mode 100644 index 000000000..7032d5b26 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/tests/test_interpreter_shutdown.py @@ -0,0 +1,822 @@ +# -*- coding: utf-8 -*- +""" +Tests for greenlet behavior during interpreter shutdown (Py_FinalizeEx). + +During interpreter shutdown, several greenlet code paths can access +partially-destroyed Python state, leading to SIGSEGV. Two independent +guards protect against this on ALL Python versions: + + 1. g_greenlet_shutting_down — set by an atexit handler registered at + greenlet import time (LIFO = runs before other cleanup). Covers + the atexit phase of Py_FinalizeEx, where _Py_IsFinalizing() is + still False on all Python versions. + + 2. Py_IsFinalizing() — covers the GC collection and later phases of + Py_FinalizeEx, where __del__ methods and destructor code run. + +These tests are organized into four groups: + + A. Core safety (smoke): no crashes with active greenlets at shutdown. + B. Cleanup semantics: GreenletExit / finally still works during + normal thread exit (the standard production path). + C. Atexit "still works" tests: getcurrent() / greenlet construction + during atexit handlers registered AFTER greenlet import (i.e. + BEFORE greenlet's cleanup handler in LIFO order) must return + valid objects — verifies the guards don't over-block. + D. TDD-certified regression tests: getcurrent() must return None + when called AFTER greenlet's cleanup (GC finalization phase + or late atexit phase). These tests fail on greenlet 3.3.2 + and pass with the fix across Python 3.10-3.14. +""" +import sys +import subprocess +import unittest +import textwrap + +from greenlet.tests import TestCase + + +class TestInterpreterShutdown(TestCase): # pylint:disable=too-many-public-methods + + def _run_shutdown_script(self, script_body): + """ + Run a Python script in a subprocess that exercises greenlet + during interpreter shutdown. Returns (returncode, stdout, stderr). + """ + full_script = textwrap.dedent(script_body) + result = subprocess.run( + [sys.executable, '-c', full_script], + capture_output=True, + text=True, + timeout=30, + check=False, + ) + return result.returncode, result.stdout, result.stderr + + # ----------------------------------------------------------------- + # Group A: Core safety — no crashes with active greenlets at exit + # ----------------------------------------------------------------- + + def test_active_greenlet_at_shutdown_no_crash(self): + """ + An active (suspended) greenlet that is deallocated during + interpreter shutdown should not crash the process. + + Before the fix, this would SIGSEGV on Python < 3.11 because + _green_dealloc_kill_started_non_main_greenlet tried to call + g_switch() during Py_FinalizeEx. + """ + rc, stdout, stderr = self._run_shutdown_script("""\ + import greenlet + + def worker(): + greenlet.getcurrent().parent.switch("from worker") + return "done" + + g = greenlet.greenlet(worker) + result = g.switch() + assert result == "from worker", result + print("OK: exiting with active greenlet") + """) + self.assertEqual(rc, 0, f"Process crashed (rc={rc}):\n{stdout}{stderr}") + self.assertIn("OK: exiting with active greenlet", stdout) + + def test_multiple_active_greenlets_at_shutdown(self): + """ + Multiple suspended greenlets at shutdown should all be cleaned + up without crashing. + """ + rc, stdout, stderr = self._run_shutdown_script("""\ + import greenlet + + def worker(name): + greenlet.getcurrent().parent.switch(f"hello from {name}") + return "done" + + greenlets = [] + for i in range(10): + g = greenlet.greenlet(worker) + result = g.switch(f"g{i}") + greenlets.append(g) + + print(f"OK: {len(greenlets)} active greenlets at shutdown") + """) + self.assertEqual(rc, 0, f"Process crashed (rc={rc}):\n{stdout}{stderr}") + self.assertIn("OK: 10 active greenlets at shutdown", stdout) + + def test_nested_greenlets_at_shutdown(self): + """ + Nested (chained parent) greenlets at shutdown should not crash. + """ + rc, stdout, stderr = self._run_shutdown_script("""\ + import greenlet + + def inner(): + greenlet.getcurrent().parent.switch("inner done") + + def outer(): + g_inner = greenlet.greenlet(inner) + g_inner.switch() + greenlet.getcurrent().parent.switch("outer done") + + g = greenlet.greenlet(outer) + result = g.switch() + assert result == "outer done", result + print("OK: nested greenlets at shutdown") + """) + self.assertEqual(rc, 0, f"Process crashed (rc={rc}):\n{stdout}{stderr}") + self.assertIn("OK: nested greenlets at shutdown", stdout) + + def test_threaded_greenlets_at_shutdown(self): + """ + Greenlets in worker threads that are still referenced at + shutdown should not crash. + """ + rc, stdout, stderr = self._run_shutdown_script("""\ + import greenlet + import threading + + results = [] + + def thread_worker(): + def greenlet_func(): + greenlet.getcurrent().parent.switch("from thread greenlet") + return "done" + + g = greenlet.greenlet(greenlet_func) + val = g.switch() + results.append((g, val)) + + threads = [] + for _ in range(3): + t = threading.Thread(target=thread_worker) + t.start() + threads.append(t) + + for t in threads: + t.join() + + print(f"OK: {len(results)} threaded greenlets at shutdown") + """) + self.assertEqual(rc, 0, f"Process crashed (rc={rc}):\n{stdout}{stderr}") + self.assertIn("OK: 3 threaded greenlets at shutdown", stdout) + + # ----------------------------------------------------------------- + # Group B: Cleanup semantics — thread exit + # ----------------------------------------------------------------- + # + # These tests verify that GreenletExit / try-finally still work + # correctly during normal thread exit (the standard production + # path, e.g. uWSGI worker threads finishing a request). This is + # NOT interpreter shutdown; the guards do not fire here. + + def test_greenlet_cleanup_during_thread_exit(self): + """ + When a thread exits normally while holding active greenlets, + GreenletExit IS thrown and cleanup code runs. This is the + standard cleanup path used in production (e.g. uWSGI worker + threads finishing a request). + """ + rc, stdout, stderr = self._run_shutdown_script("""\ + import os + import threading + import greenlet + + _write = os.write + + def thread_func(): + def worker(_w=_write, + _GreenletExit=greenlet.GreenletExit): + try: + greenlet.getcurrent().parent.switch("suspended") + except _GreenletExit: + _w(1, b"CLEANUP: GreenletExit caught\\n") + raise + + g = greenlet.greenlet(worker) + g.switch() + # Thread exits with active greenlet -> thread-state + # cleanup triggers GreenletExit + + t = threading.Thread(target=thread_func) + t.start() + t.join() + print("OK: thread cleanup done") + """) + self.assertEqual(rc, 0, f"Process crashed (rc={rc}):\n{stdout}{stderr}") + self.assertIn("OK: thread cleanup done", stdout) + self.assertIn("CLEANUP: GreenletExit caught", stdout) + + def test_finally_block_during_thread_exit(self): + """ + try/finally blocks in active greenlets run correctly when the + owning thread exits. + """ + rc, stdout, stderr = self._run_shutdown_script("""\ + import os + import threading + import greenlet + + _write = os.write + + def thread_func(): + def worker(_w=_write): + try: + greenlet.getcurrent().parent.switch("suspended") + finally: + _w(1, b"FINALLY: cleanup executed\\n") + + g = greenlet.greenlet(worker) + g.switch() + + t = threading.Thread(target=thread_func) + t.start() + t.join() + print("OK: thread cleanup done") + """) + self.assertEqual(rc, 0, f"Process crashed (rc={rc}):\n{stdout}{stderr}") + self.assertIn("OK: thread cleanup done", stdout) + self.assertIn("FINALLY: cleanup executed", stdout) + + def test_many_greenlets_with_cleanup_at_shutdown(self): + """ + Stress test: many active greenlets with cleanup code at shutdown. + Ensures no crashes regardless of deallocation order. + """ + rc, stdout, stderr = self._run_shutdown_script("""\ + import sys + import greenlet + + cleanup_count = 0 + + def worker(idx): + global cleanup_count + try: + greenlet.getcurrent().parent.switch(f"ready-{idx}") + except greenlet.GreenletExit: + cleanup_count += 1 + raise + + greenlets = [] + for i in range(50): + g = greenlet.greenlet(worker) + result = g.switch(i) + greenlets.append(g) + + print(f"OK: {len(greenlets)} greenlets about to shut down") + # Note: we can't easily print cleanup_count during shutdown + # since it happens after the main module's code runs. + """) + self.assertEqual(rc, 0, f"Process crashed (rc={rc}):\n{stdout}{stderr}") + self.assertIn("OK: 50 greenlets about to shut down", stdout) + + def test_deeply_nested_greenlets_at_shutdown(self): + """ + Deeply nested greenlet parent chains at shutdown. + Tests that the deallocation order doesn't cause issues. + """ + rc, stdout, stderr = self._run_shutdown_script("""\ + import greenlet + + def level(depth, max_depth): + if depth < max_depth: + g = greenlet.greenlet(level) + g.switch(depth + 1, max_depth) + greenlet.getcurrent().parent.switch(f"depth-{depth}") + + g = greenlet.greenlet(level) + result = g.switch(0, 10) + print(f"OK: nested to depth 10, got {result}") + """) + self.assertEqual(rc, 0, f"Process crashed (rc={rc}):\n{stdout}{stderr}") + self.assertIn("OK: nested to depth 10", stdout) + + def test_greenlet_with_traceback_at_shutdown(self): + """ + A greenlet that has an active exception context when it's + suspended should not crash during shutdown cleanup. + """ + rc, stdout, stderr = self._run_shutdown_script("""\ + import greenlet + + def worker(): + try: + raise ValueError("test error") + except ValueError: + # Suspend while an exception is active on the stack + greenlet.getcurrent().parent.switch("suspended with exc") + return "done" + + g = greenlet.greenlet(worker) + result = g.switch() + assert result == "suspended with exc" + print("OK: greenlet with active exception at shutdown") + """) + self.assertEqual(rc, 0, f"Process crashed (rc={rc}):\n{stdout}{stderr}") + self.assertIn("OK: greenlet with active exception at shutdown", stdout) + + # ----------------------------------------------------------------- + # Group C: getcurrent() / construction / gettrace() / settrace() + # during atexit — registered AFTER greenlet import + # + # These atexit handlers are registered AFTER ``import greenlet``, + # so they run BEFORE greenlet's own cleanup handler (LIFO). At + # this point g_greenlet_shutting_down is still 0 and + # _Py_IsFinalizing() is False, so getcurrent() must still return + # a valid greenlet object. These tests guard against the fix + # being too aggressive (over-blocking getcurrent early). + # ----------------------------------------------------------------- + + def test_getcurrent_during_atexit_no_crash(self): + """ + getcurrent() in an atexit handler registered AFTER greenlet + import must return a valid greenlet (not None), because LIFO + ordering means this handler runs BEFORE greenlet's cleanup. + """ + rc, stdout, stderr = self._run_shutdown_script("""\ + import atexit + import greenlet + + def call_getcurrent_at_exit(): + try: + g = greenlet.getcurrent() + if g is not None and type(g).__name__ == 'greenlet': + print(f"OK: getcurrent returned valid greenlet") + elif g is None: + print("FAIL: getcurrent returned None (over-blocked)") + else: + print(f"FAIL: unexpected {g!r}") + except Exception as e: + print(f"OK: getcurrent raised {type(e).__name__}: {e}") + + atexit.register(call_getcurrent_at_exit) + print("OK: atexit registered") + """) + self.assertEqual(rc, 0, f"Process crashed (rc={rc}):\n{stdout}{stderr}") + self.assertIn("OK: atexit registered", stdout) + self.assertIn("OK: getcurrent returned valid greenlet", stdout, + "getcurrent() should return a valid greenlet when called " + "before greenlet's cleanup handler (LIFO ordering)") + + def test_gettrace_during_atexit_no_crash(self): + """ + Calling greenlet.gettrace() during atexit must not crash. + """ + rc, stdout, stderr = self._run_shutdown_script("""\ + import atexit + import greenlet + + def check_at_exit(): + try: + result = greenlet.gettrace() + print(f"OK: gettrace returned {result!r}") + except Exception as e: + print(f"OK: gettrace raised {type(e).__name__}: {e}") + + atexit.register(check_at_exit) + print("OK: registered") + """) + self.assertEqual(rc, 0, f"Process crashed (rc={rc}):\n{stdout}{stderr}") + self.assertIn("OK: registered", stdout) + + def test_settrace_during_atexit_no_crash(self): + """ + Calling greenlet.settrace() during atexit must not crash. + """ + rc, stdout, stderr = self._run_shutdown_script("""\ + import atexit + import greenlet + + def check_at_exit(): + try: + greenlet.settrace(lambda *args: None) + print("OK: settrace succeeded") + except Exception as e: + print(f"OK: settrace raised {type(e).__name__}: {e}") + + atexit.register(check_at_exit) + print("OK: registered") + """) + self.assertEqual(rc, 0, f"Process crashed (rc={rc}):\n{stdout}{stderr}") + self.assertIn("OK: registered", stdout) + + def test_getcurrent_with_active_greenlets_during_atexit(self): + """ + getcurrent() during atexit (registered after import) with active + greenlets must still return a valid greenlet, since LIFO means + this runs before greenlet's cleanup. + """ + rc, stdout, stderr = self._run_shutdown_script("""\ + import atexit + import greenlet + + def worker(): + greenlet.getcurrent().parent.switch("ready") + + greenlets = [] + for i in range(5): + g = greenlet.greenlet(worker) + result = g.switch() + greenlets.append(g) + + def check_at_exit(): + try: + g = greenlet.getcurrent() + if g is not None and type(g).__name__ == 'greenlet': + print(f"OK: getcurrent returned valid greenlet") + elif g is None: + print("FAIL: getcurrent returned None (over-blocked)") + else: + print(f"FAIL: unexpected {g!r}") + except Exception as e: + print(f"OK: getcurrent raised {type(e).__name__}: {e}") + + atexit.register(check_at_exit) + print(f"OK: {len(greenlets)} active greenlets, atexit registered") + """) + self.assertEqual(rc, 0, f"Process crashed (rc={rc}):\n{stdout}{stderr}") + self.assertIn("OK: 5 active greenlets, atexit registered", stdout) + self.assertIn("OK: getcurrent returned valid greenlet", stdout, + "getcurrent() should return a valid greenlet when called " + "before greenlet's cleanup handler (LIFO ordering)") + + def test_greenlet_construction_during_atexit_no_crash(self): + """ + Constructing a new greenlet during atexit (registered after + import) must succeed, since this runs before greenlet's cleanup. + """ + rc, stdout, stderr = self._run_shutdown_script("""\ + import atexit + import greenlet + + def create_greenlets_at_exit(): + try: + def noop(): + pass + g = greenlet.greenlet(noop) + if g is not None: + print(f"OK: created greenlet successfully") + else: + print("FAIL: greenlet() returned None") + except Exception as e: + print(f"OK: construction raised {type(e).__name__}: {e}") + + atexit.register(create_greenlets_at_exit) + print("OK: atexit registered") + """) + self.assertEqual(rc, 0, f"Process crashed (rc={rc}):\n{stdout}{stderr}") + self.assertIn("OK: atexit registered", stdout) + self.assertIn("OK: created greenlet successfully", stdout) + + def test_greenlet_construction_with_active_greenlets_during_atexit(self): + """ + Constructing new greenlets during atexit when other active + greenlets already exist (maximizes the chance of a non-empty + deleteme list). + """ + rc, stdout, stderr = self._run_shutdown_script("""\ + import atexit + import greenlet + + def worker(): + greenlet.getcurrent().parent.switch("ready") + + greenlets = [] + for i in range(10): + g = greenlet.greenlet(worker) + g.switch() + greenlets.append(g) + + def create_at_exit(): + try: + new_greenlets = [] + for i in range(5): + g = greenlet.greenlet(lambda: None) + new_greenlets.append(g) + print(f"OK: created {len(new_greenlets)} greenlets at exit") + except Exception as e: + print(f"OK: raised {type(e).__name__}: {e}") + + atexit.register(create_at_exit) + print(f"OK: {len(greenlets)} active greenlets, atexit registered") + """) + self.assertEqual(rc, 0, f"Process crashed (rc={rc}):\n{stdout}{stderr}") + self.assertIn("OK: 10 active greenlets, atexit registered", stdout) + + def test_greenlet_construction_with_cross_thread_deleteme_during_atexit(self): + """ + Create greenlets in a worker thread, transfer them to the main + thread, then drop them — populating the deleteme list. Then + construct a new greenlet during atexit. On Python < 3.11 + clear_deleteme_list() could previously crash if the + PythonAllocator vector copy failed during early Py_FinalizeEx; + using std::swap eliminates that allocation. + """ + rc, stdout, stderr = self._run_shutdown_script("""\ + import atexit + import greenlet + import threading + + cross_thread_refs = [] + + def thread_worker(): + # Create greenlets in this thread + def gl_body(): + greenlet.getcurrent().parent.switch("ready") + for _ in range(20): + g = greenlet.greenlet(gl_body) + g.switch() + cross_thread_refs.append(g) + + t = threading.Thread(target=thread_worker) + t.start() + t.join() + + # Dropping these references in the main thread + # causes them to be added to the main thread's + # deleteme list (deferred cross-thread dealloc). + cross_thread_refs.clear() + + def create_at_exit(): + try: + g = greenlet.greenlet(lambda: None) + print(f"OK: created greenlet at exit {g!r}") + except Exception as e: + print(f"OK: raised {type(e).__name__}: {e}") + + atexit.register(create_at_exit) + print("OK: cross-thread setup done, atexit registered") + """) + self.assertEqual(rc, 0, f"Process crashed (rc={rc}):\n{stdout}{stderr}") + self.assertIn("OK: cross-thread setup done, atexit registered", stdout) + + + # ----------------------------------------------------------------- + # Group D.1: TDD-certified — getcurrent() during GC finalization + # + # These tests use gc.disable() + reference cycles to force __del__ + # to run during Py_FinalizeEx's GC pass, where Py_IsFinalizing() + # is True. Without the fix, getcurrent() returns a live greenlet + # (unguarded); with the fix, it returns None. + # + # TDD verification (greenlet 3.3.2 = RED, patched = GREEN): + # Python 3.10: RED (UNGUARDED) → GREEN (GUARDED) + # Python 3.11: RED (UNGUARDED) → GREEN (GUARDED) + # Python 3.12: RED (UNGUARDED) → GREEN (GUARDED) + # Python 3.13: RED (UNGUARDED) → GREEN (GUARDED) + # Python 3.14: RED (UNGUARDED) → GREEN (GUARDED) + # ----------------------------------------------------------------- + + def test_getcurrent_returns_none_during_gc_finalization(self): + """ + greenlet.getcurrent() must return None when called from a + __del__ method during Py_FinalizeEx's GC collection pass. + + On Python >= 3.11, _Py_IsFinalizing() is True during this + phase. Without the Py_IsFinalizing() guard in mod_getcurrent, + this would return a greenlet — the same unguarded code path + that leads to SIGSEGV in production (uWSGI worker recycling). + """ + rc, stdout, stderr = self._run_shutdown_script("""\ + import gc + import os + import greenlet + + gc.disable() + + class CleanupChecker: + def __del__(self): + try: + cur = greenlet.getcurrent() + if cur is None: + os.write(1, b"GUARDED: getcurrent=None\\n") + else: + os.write(1, b"UNGUARDED: getcurrent=" + + type(cur).__name__.encode() + b"\\n") + except Exception as e: + os.write(1, b"EXCEPTION: " + str(e).encode() + b"\\n") + + # Reference cycle: only collected during Py_FinalizeEx GC pass + a = CleanupChecker() + b = {"ref": a} + a._cycle = b + del a, b + + print("OK: deferred cycle created") + """) + self.assertEqual(rc, 0, f"Process crashed (rc={rc}):\n{stdout}{stderr}") + self.assertIn("OK: deferred cycle created", stdout) + self.assertIn("GUARDED: getcurrent=None", stdout, + "getcurrent() must return None during GC finalization; " + "returned a live object instead (missing Py_IsFinalizing guard)") + + def test_getcurrent_returns_none_during_gc_finalization_with_active_greenlets(self): + """ + Same as above but with active greenlets at shutdown, which + increases the amount of C++ destructor work during finalization. + """ + rc, stdout, stderr = self._run_shutdown_script("""\ + import gc + import os + import greenlet + + gc.disable() + + class CleanupChecker: + def __del__(self): + try: + cur = greenlet.getcurrent() + if cur is None: + os.write(1, b"GUARDED: getcurrent=None\\n") + else: + os.write(1, b"UNGUARDED: getcurrent=" + + type(cur).__name__.encode() + b"\\n") + except Exception as e: + os.write(1, b"EXCEPTION: " + str(e).encode() + b"\\n") + + # Create active greenlets + greenlets = [] + for _ in range(10): + def worker(): + greenlet.getcurrent().parent.switch("suspended") + g = greenlet.greenlet(worker) + g.switch() + greenlets.append(g) + + # Reference cycle deferred to Py_FinalizeEx + a = CleanupChecker() + b = {"ref": a} + a._cycle = b + del a, b + + print(f"OK: {len(greenlets)} active greenlets, cycle deferred") + """) + self.assertEqual(rc, 0, f"Process crashed (rc={rc}):\n{stdout}{stderr}") + self.assertIn("OK: 10 active greenlets, cycle deferred", stdout) + self.assertIn("GUARDED: getcurrent=None", stdout, + "getcurrent() must return None during GC finalization; " + "returned a live object instead (missing Py_IsFinalizing guard)") + + def test_getcurrent_returns_none_during_gc_finalization_cross_thread(self): + """ + Combines cross-thread greenlet deallocation (deleteme list) + with the GC finalization check. This simulates the production + scenario where uWSGI worker threads create greenlets that are + transferred to the main thread, then cleaned up during + Py_FinalizeEx. + """ + rc, stdout, stderr = self._run_shutdown_script("""\ + import gc + import os + import threading + import greenlet + + gc.disable() + + class CleanupChecker: + def __del__(self): + try: + cur = greenlet.getcurrent() + if cur is None: + os.write(1, b"GUARDED: getcurrent=None\\n") + else: + os.write(1, b"UNGUARDED: getcurrent=" + + type(cur).__name__.encode() + b"\\n") + except Exception as e: + os.write(1, b"EXCEPTION: " + str(e).encode() + b"\\n") + + # Create cross-thread greenlet references + cross_refs = [] + def thread_fn(): + for _ in range(20): + def body(): + greenlet.getcurrent().parent.switch("x") + g = greenlet.greenlet(body) + g.switch() + cross_refs.append(g) + t = threading.Thread(target=thread_fn) + t.start() + t.join() + cross_refs.clear() + + # Reference cycle deferred to Py_FinalizeEx + a = CleanupChecker() + b = {"ref": a} + a._cycle = b + del a, b + + print("OK: cross-thread cleanup + cycle deferred") + """) + self.assertEqual(rc, 0, f"Process crashed (rc={rc}):\n{stdout}{stderr}") + self.assertIn("OK: cross-thread cleanup + cycle deferred", stdout) + self.assertIn("GUARDED: getcurrent=None", stdout, + "getcurrent() must return None during GC finalization; " + "returned a live object instead (missing Py_IsFinalizing guard)") + + + # ----------------------------------------------------------------- + # Group D.2: TDD-certified — getcurrent() during atexit phase + # + # These tests register the checker BEFORE importing greenlet. + # Python's atexit is LIFO, so greenlet's handler (registered at + # import) runs FIRST and sets g_greenlet_shutting_down=1; then + # the checker runs SECOND and observes getcurrent() → None. + # + # This covers the atexit phase where _Py_IsFinalizing() is still + # False on ALL Python versions — the exact window that causes + # SIGSEGV in production (uWSGI worker recycling → Py_FinalizeEx). + # + # TDD verification (greenlet 3.3.2 = RED, patched = GREEN): + # Python 3.10: RED (UNGUARDED) → GREEN (GUARDED) + # Python 3.11: RED (UNGUARDED) → GREEN (GUARDED) + # Python 3.12: RED (UNGUARDED) → GREEN (GUARDED) + # Python 3.13: RED (UNGUARDED) → GREEN (GUARDED) + # Python 3.14: RED (UNGUARDED) → GREEN (GUARDED) + # ----------------------------------------------------------------- + + def test_getcurrent_returns_none_during_atexit_phase(self): + """ + greenlet.getcurrent() must return None when called from an + atexit handler that runs AFTER greenlet's own atexit handler. + + This tests the g_greenlet_shutting_down flag, which is needed + because _Py_IsFinalizing() is still False during the atexit + phase on ALL Python versions. Without g_greenlet_shutting_down, + getcurrent() proceeds unguarded into partially-torn-down state. + """ + rc, stdout, stderr = self._run_shutdown_script("""\ + import atexit + import os + + def late_checker(): + try: + import greenlet + cur = greenlet.getcurrent() + if cur is None: + os.write(1, b"GUARDED: getcurrent=None\\n") + else: + os.write(1, b"UNGUARDED: getcurrent=" + + type(cur).__name__.encode() + b"\\n") + except Exception as e: + os.write(1, b"EXCEPTION: " + str(e).encode() + b"\\n") + + # Register BEFORE importing greenlet. LIFO order: + # greenlet's handler (registered at import) runs FIRST, + # late_checker runs SECOND — seeing the flag already set. + atexit.register(late_checker) + + import greenlet + print("OK: atexit registered before greenlet import") + """) + self.assertEqual(rc, 0, f"Process crashed (rc={rc}):\n{stdout}{stderr}") + self.assertIn("OK: atexit registered before greenlet import", stdout) + self.assertIn("GUARDED: getcurrent=None", stdout, + "getcurrent() must return None during atexit phase; " + "returned a live object instead (missing " + "g_greenlet_shutting_down atexit handler)") + + def test_getcurrent_returns_none_during_atexit_phase_with_active_greenlets(self): + """ + Same as above but with active greenlets, ensuring the atexit + guard works even when there is greenlet state to clean up. + """ + rc, stdout, stderr = self._run_shutdown_script("""\ + import atexit + import os + + def late_checker(): + try: + import greenlet + cur = greenlet.getcurrent() + if cur is None: + os.write(1, b"GUARDED: getcurrent=None\\n") + else: + os.write(1, b"UNGUARDED: getcurrent=" + + type(cur).__name__.encode() + b"\\n") + except Exception as e: + os.write(1, b"EXCEPTION: " + str(e).encode() + b"\\n") + + atexit.register(late_checker) + + import greenlet + + greenlets = [] + for _ in range(10): + def worker(): + greenlet.getcurrent().parent.switch("parked") + g = greenlet.greenlet(worker) + g.switch() + greenlets.append(g) + + print(f"OK: {len(greenlets)} active greenlets, atexit registered") + """) + self.assertEqual(rc, 0, f"Process crashed (rc={rc}):\n{stdout}{stderr}") + self.assertIn("OK: 10 active greenlets, atexit registered", stdout) + self.assertIn("GUARDED: getcurrent=None", stdout, + "getcurrent() must return None during atexit phase; " + "returned a live object instead (missing " + "g_greenlet_shutting_down atexit handler)") + + +if __name__ == '__main__': + unittest.main() diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/tests/test_leaks.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/tests/test_leaks.py new file mode 100644 index 000000000..1d3eb07bf --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/tests/test_leaks.py @@ -0,0 +1,478 @@ +# -*- coding: utf-8 -*- +""" +Testing scenarios that may have leaked. +""" +import sys +import gc + +import time +import weakref +import threading + + +import greenlet +from . import TestCase +from . import PY314 +from . import RUNNING_ON_FREETHREAD_BUILD +from . import WIN +from .leakcheck import fails_leakcheck +from .leakcheck import ignores_leakcheck +from .leakcheck import RUNNING_ON_MANYLINUX + + +# pylint:disable=protected-access + +assert greenlet.GREENLET_USE_GC # Option to disable this was removed in 1.0 + +class HasFinalizerTracksInstances(object): + EXTANT_INSTANCES = set() + def __init__(self, msg): + self.msg = sys.intern(msg) + self.EXTANT_INSTANCES.add(id(self)) + def __del__(self): + self.EXTANT_INSTANCES.remove(id(self)) + def __repr__(self): + return "" % ( + id(self), self.msg + ) + @classmethod + def reset(cls): + cls.EXTANT_INSTANCES.clear() + + +def fails_leakcheck_except_on_free_thraded(func): + if RUNNING_ON_FREETHREAD_BUILD: + # These all seem to pass on free threading because + # of the changes to the garbage collector + return func + return fails_leakcheck(func) + + +class TestLeaks(TestCase): + + def test_arg_refs(self): + args = ('a', 'b', 'c') + refcount_before = sys.getrefcount(args) + # pylint:disable=unnecessary-lambda + g = greenlet.greenlet( + lambda *args: greenlet.getcurrent().parent.switch(*args)) + for _ in range(100): + g.switch(*args) + self.assertEqual(sys.getrefcount(args), refcount_before) + + def test_kwarg_refs(self): + kwargs = {} + self.assertEqual(sys.getrefcount(kwargs), 2 if not PY314 else 1) + # pylint:disable=unnecessary-lambda + g = greenlet.greenlet( + lambda **gkwargs: greenlet.getcurrent().parent.switch(**gkwargs)) + for _ in range(100): + g.switch(**kwargs) + # Python 3.14 elides reference counting operations + # in some cases. See https://github.com/python/cpython/pull/130708 + self.assertEqual(sys.getrefcount(kwargs), 2 if not PY314 else 1) + + + @staticmethod + def __recycle_threads(): + # By introducing a thread that does sleep we allow other threads, + # that have triggered their __block condition, but did not have a + # chance to deallocate their thread state yet, to finally do so. + # The way it works is by requiring a GIL switch (different thread), + # which does a GIL release (sleep), which might do a GIL switch + # to finished threads and allow them to clean up. + def worker(): + time.sleep(0.001) + t = threading.Thread(target=worker) + t.start() + time.sleep(0.001) + t.join(10) + + def test_threaded_leak(self): + gg = [] + def worker(): + # only main greenlet present + gg.append(weakref.ref(greenlet.getcurrent())) + for _ in range(2): + t = threading.Thread(target=worker) + t.start() + t.join(10) + del t + greenlet.getcurrent() # update ts_current + self.__recycle_threads() + greenlet.getcurrent() # update ts_current + gc.collect() + greenlet.getcurrent() # update ts_current + for g in gg: + self.assertIsNone(g()) + + def test_threaded_adv_leak(self): + gg = [] + def worker(): + # main and additional *finished* greenlets + ll = greenlet.getcurrent().ll = [] + def additional(): + ll.append(greenlet.getcurrent()) + for _ in range(2): + greenlet.greenlet(additional).switch() + gg.append(weakref.ref(greenlet.getcurrent())) + for _ in range(2): + t = threading.Thread(target=worker) + t.start() + t.join(10) + del t + greenlet.getcurrent() # update ts_current + self.__recycle_threads() + greenlet.getcurrent() # update ts_current + gc.collect() + greenlet.getcurrent() # update ts_current + for g in gg: + self.assertIsNone(g()) + + def assertClocksUsed(self): + used = greenlet._greenlet.get_clocks_used_doing_optional_cleanup() + self.assertGreaterEqual(used, 0) + # we don't lose the value + greenlet._greenlet.enable_optional_cleanup(True) + used2 = greenlet._greenlet.get_clocks_used_doing_optional_cleanup() + self.assertEqual(used, used2) + self.assertGreater(greenlet._greenlet.CLOCKS_PER_SEC, 1) + + def _check_issue251(self, + manually_collect_background=True, + explicit_reference_to_switch=False): + # See https://github.com/python-greenlet/greenlet/issues/251 + # Killing a greenlet (probably not the main one) + # in one thread from another thread would + # result in leaking a list (the ts_delkey list). + # We no longer use lists to hold that stuff, though. + + # For the test to be valid, even empty lists have to be tracked by the + # GC + + assert gc.is_tracked([]) + HasFinalizerTracksInstances.reset() + greenlet.getcurrent() + greenlets_before = self.count_objects(greenlet.greenlet, exact_kind=False) + + background_glet_running = threading.Event() + background_glet_killed = threading.Event() + background_greenlets = [] + + # XXX: Switching this to a greenlet subclass that overrides + # run results in all callers failing the leaktest; that + # greenlet instance is leaked. There's a bound method for + # run() living on the stack of the greenlet in g_initialstub, + # and since we don't manually switch back to the background + # greenlet to let it "fall off the end" and exit the + # g_initialstub function, it never gets cleaned up. Making the + # garbage collector aware of this bound method (making it an + # attribute of the greenlet structure and traversing into it) + # doesn't help, for some reason. + def background_greenlet(): + # Throw control back to the main greenlet. + jd = HasFinalizerTracksInstances("DELETING STACK OBJECT") + greenlet._greenlet.set_thread_local( + 'test_leaks_key', + HasFinalizerTracksInstances("DELETING THREAD STATE")) + # Explicitly keeping 'switch' in a local variable + # breaks this test in all versions + if explicit_reference_to_switch: + s = greenlet.getcurrent().parent.switch + s([jd]) + else: + greenlet.getcurrent().parent.switch([jd]) + + bg_main_wrefs = [] + + def background_thread(): + glet = greenlet.greenlet(background_greenlet) + bg_main_wrefs.append(weakref.ref(glet.parent)) + + background_greenlets.append(glet) + glet.switch() # Be sure it's active. + # Control is ours again. + del glet # Delete one reference from the thread it runs in. + background_glet_running.set() + background_glet_killed.wait(10) + + # To trigger the background collection of the dead + # greenlet, thus clearing out the contents of the list, we + # need to run some APIs. See issue 252. + if manually_collect_background: + greenlet.getcurrent() + + + t = threading.Thread(target=background_thread) + t.start() + background_glet_running.wait(10) + greenlet.getcurrent() + lists_before = self.count_objects(list, exact_kind=True) + + assert len(background_greenlets) == 1 + self.assertFalse(background_greenlets[0].dead) + # Delete the last reference to the background greenlet + # from a different thread. This puts it in the background thread's + # ts_delkey list. + del background_greenlets[:] + background_glet_killed.set() + + # Now wait for the background thread to die. + t.join(10) + del t + # As part of the fix for 252, we need to cycle the ceval.c + # interpreter loop to be sure it has had a chance to process + # the pending call. + self.wait_for_pending_cleanups() + + lists_after = self.count_objects(list, exact_kind=True) + greenlets_after = self.count_objects(greenlet.greenlet, exact_kind=False) + + # On 2.7, we observe that lists_after is smaller than + # lists_before. No idea what lists got cleaned up. All the + # Python 3 versions match exactly. + self.assertLessEqual(lists_after, lists_before) + # On versions after 3.6, we've successfully cleaned up the + # greenlet references thanks to the internal "vectorcall" + # protocol; prior to that, there is a reference path through + # the ``greenlet.switch`` method still on the stack that we + # can't reach to clean up. The C code goes through terrific + # lengths to clean that up. + if not explicit_reference_to_switch \ + and greenlet._greenlet.get_clocks_used_doing_optional_cleanup() is not None: + # If cleanup was disabled, though, we may not find it. + self.assertEqual(greenlets_after, greenlets_before) + if manually_collect_background: + # TODO: Figure out how to make this work! + # The one on the stack is still leaking somehow + # in the non-manually-collect state. + self.assertEqual(HasFinalizerTracksInstances.EXTANT_INSTANCES, set()) + else: + # The explicit reference prevents us from collecting it + # and it isn't always found by the GC either for some + # reason. The entire frame is leaked somehow, on some + # platforms (e.g., MacPorts builds of Python (all + # versions!)), but not on other platforms (the linux and + # windows builds on GitHub actions and Appveyor). So we'd + # like to write a test that proves that the main greenlet + # sticks around, and we can on my machine (macOS 11.6, + # MacPorts builds of everything) but we can't write that + # same test on other platforms. However, hopefully iteration + # done by leakcheck will find it. + pass + + if greenlet._greenlet.get_clocks_used_doing_optional_cleanup() is not None: + self.assertClocksUsed() + + def test_issue251_killing_cross_thread_leaks_list(self): + self._check_issue251() + + def test_issue251_with_cleanup_disabled(self): + greenlet._greenlet.enable_optional_cleanup(False) + try: + self._check_issue251() + finally: + greenlet._greenlet.enable_optional_cleanup(True) + + @fails_leakcheck_except_on_free_thraded + def test_issue251_issue252_need_to_collect_in_background(self): + # Between greenlet 1.1.2 and the next version, this was still + # failing because the leak of the list still exists when we + # don't call a greenlet API before exiting the thread. The + # proximate cause is that neither of the two greenlets from + # the background thread are actually being destroyed, even + # though the GC is in fact visiting both objects. It's not + # clear where that leak is? For some reason the thread-local + # dict holding it isn't being cleaned up. + # + # The leak, I think, is in the CPYthon internal function that + # calls into green_switch(). The argument tuple is still on + # the C stack somewhere and can't be reached? That doesn't + # make sense, because the tuple should be collectable when + # this object goes away. + # + # Note that this test sometimes spuriously passes on Linux, + # for some reason, but I've never seen it pass on macOS. + self._check_issue251(manually_collect_background=False) + + @fails_leakcheck_except_on_free_thraded + def test_issue251_issue252_need_to_collect_in_background_cleanup_disabled(self): + self.expect_greenlet_leak = True + greenlet._greenlet.enable_optional_cleanup(False) + try: + self._check_issue251(manually_collect_background=False) + finally: + greenlet._greenlet.enable_optional_cleanup(True) + + @fails_leakcheck_except_on_free_thraded + def test_issue251_issue252_explicit_reference_not_collectable(self): + self._check_issue251( + manually_collect_background=False, + explicit_reference_to_switch=True) + + UNTRACK_ATTEMPTS = 100 + + def _only_test_some_versions(self): + # We're only looking for this problem specifically on 3.11, + # and this set of tests is relatively fragile, depending on + # OS and memory management details. So we want to run it on 3.11+ + # (obviously) but not every older 3.x version in order to reduce + # false negatives. At the moment, those false results seem to have + # resolved, so we are actually running this on 3.8+ + assert sys.version_info[0] >= 3 + if RUNNING_ON_MANYLINUX: + self.skipTest("Slow and not worth repeating here") + + @ignores_leakcheck + # Because we're just trying to track raw memory, not objects, and running + # the leakcheck makes an already slow test slower. + def test_untracked_memory_doesnt_increase(self): + # See https://github.com/gevent/gevent/issues/1924 + # and https://github.com/python-greenlet/greenlet/issues/328 + self._only_test_some_versions() + def f(): + return 1 + + ITER = 10000 + def run_it(): + for _ in range(ITER): + greenlet.greenlet(f).switch() + + # Establish baseline + for _ in range(3): + run_it() + + # uss: (Linux, macOS, Windows): aka "Unique Set Size", this is + # the memory which is unique to a process and which would be + # freed if the process was terminated right now. + uss_before = self.get_process_uss() + + for count in range(self.UNTRACK_ATTEMPTS): + uss_before = max(uss_before, self.get_process_uss()) + run_it() + + uss_after = self.get_process_uss() + if uss_after <= uss_before and count > 1: + break + + self.assertLessEqual(uss_after, uss_before) + + def _check_untracked_memory_thread(self, deallocate_in_thread=True): + self._only_test_some_versions() + # Like the above test, but what if there are a bunch of + # unfinished greenlets in a thread that dies? + # Does it matter if we deallocate in the thread or not? + + # First, make sure we can get useful measurements. This will + # be skipped if not. + self.get_process_uss() + + EXIT_COUNT = [0] + + def f(): + try: + greenlet.getcurrent().parent.switch() + except greenlet.GreenletExit: + EXIT_COUNT[0] += 1 + raise + return 1 + + ITER = 10000 + def run_it(): + glets = [] + for _ in range(ITER): + # Greenlet starts, switches back to us. + # We keep a strong reference to the greenlet though so it doesn't + # get a GreenletExit exception. + g = greenlet.greenlet(f) + glets.append(g) + g.switch() + + return glets + + test = self + + class ThreadFunc: + uss_before = uss_after = 0 + glets = () + ITER = 2 + def __call__(self): + self.uss_before = test.get_process_uss() + + for _ in range(self.ITER): + self.glets += tuple(run_it()) + + for g in self.glets: + test.assertIn('suspended active', str(g)) + # Drop them. + if deallocate_in_thread: + self.glets = () + self.uss_after = test.get_process_uss() + + # Establish baseline + uss_before = uss_after = None + for count in range(self.UNTRACK_ATTEMPTS): + EXIT_COUNT[0] = 0 + thread_func = ThreadFunc() + t = threading.Thread(target=thread_func) + t.start() + t.join(30) + self.assertFalse(t.is_alive()) + + if uss_before is None: + uss_before = thread_func.uss_before + + uss_before = max(uss_before, thread_func.uss_before) + if deallocate_in_thread: + self.assertEqual(thread_func.glets, ()) + self.assertEqual(EXIT_COUNT[0], ITER * thread_func.ITER) + + del thread_func # Deallocate the greenlets; but this won't raise into them + del t + if not deallocate_in_thread: + self.assertEqual(EXIT_COUNT[0], 0) + if deallocate_in_thread: + self.wait_for_pending_cleanups() + + uss_after = self.get_process_uss() + # See if we achieve a non-growth state at some point. Break when we do. + if uss_after <= uss_before and count > 1: + break + + self.wait_for_pending_cleanups() + uss_after = self.get_process_uss() + # On Windows, USS can fluctuate by tens of KB between measurements + # due to working set trimming, page table updates, etc. Allow a + # small tolerance so OS-level noise doesn't cause false failures. + # Real leaks produce MBs of growth (each iteration creates 20k + # greenlets), so 512 KB is well below the detection threshold for + # genuine issues. + tolerance = 512 * 1024 if WIN else 0 + self.assertLessEqual(uss_after, uss_before + tolerance, + "after attempts %d" % (count,)) + + @ignores_leakcheck + # Because we're just trying to track raw memory, not objects, and running + # the leakcheck makes an already slow test slower. + def test_untracked_memory_doesnt_increase_unfinished_thread_dealloc_in_thread(self): + self._check_untracked_memory_thread(deallocate_in_thread=True) + + @ignores_leakcheck + # Because the main greenlets from the background threads do not exit in a timely fashion, + # we fail the object-based leakchecks. + def test_untracked_memory_doesnt_increase_unfinished_thread_dealloc_in_main(self): + # Between Feb 10 and Feb 20 2026, this test started failing on + # Github Actions, windows 3.14t. With no relevant code changes on + # our part. Both versions were 3.14.3 (same build). The only change + # is the Github actions "Runner Image". The working one was version + # 20260202.17.1, while the updated failing version was + # 20260217.31.1. Both report the same version of the operating system + # (Microsoft Windows Server 2025 10.0.26100). + # + # Reevaluate on future runner image releases. + if WIN and RUNNING_ON_FREETHREAD_BUILD and PY314: + self.skipTest("Windows 3.14t appears to leak. No other platform does.") + self._check_untracked_memory_thread(deallocate_in_thread=False) + +if __name__ == '__main__': + __import__('unittest').main() diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/tests/test_stack_saved.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/tests/test_stack_saved.py new file mode 100644 index 000000000..b362bf95a --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/tests/test_stack_saved.py @@ -0,0 +1,19 @@ +import greenlet +from . import TestCase + + +class Test(TestCase): + + def test_stack_saved(self): + main = greenlet.getcurrent() + self.assertEqual(main._stack_saved, 0) + + def func(): + main.switch(main._stack_saved) + + g = greenlet.greenlet(func) + x = g.switch() + self.assertGreater(x, 0) + self.assertGreater(g._stack_saved, 0) + g.switch() + self.assertEqual(g._stack_saved, 0) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/tests/test_throw.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/tests/test_throw.py new file mode 100644 index 000000000..f4f9a1402 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/tests/test_throw.py @@ -0,0 +1,128 @@ +import sys + + +from greenlet import greenlet +from . import TestCase + +def switch(*args): + return greenlet.getcurrent().parent.switch(*args) + + +class ThrowTests(TestCase): + def test_class(self): + def f(): + try: + switch("ok") + except RuntimeError: + switch("ok") + return + switch("fail") + g = greenlet(f) + res = g.switch() + self.assertEqual(res, "ok") + res = g.throw(RuntimeError) + self.assertEqual(res, "ok") + + def test_val(self): + def f(): + try: + switch("ok") + except RuntimeError: + val = sys.exc_info()[1] + if str(val) == "ciao": + switch("ok") + return + switch("fail") + + g = greenlet(f) + res = g.switch() + self.assertEqual(res, "ok") + res = g.throw(RuntimeError("ciao")) + self.assertEqual(res, "ok") + + g = greenlet(f) + res = g.switch() + self.assertEqual(res, "ok") + res = g.throw(RuntimeError, "ciao") + self.assertEqual(res, "ok") + + def test_kill(self): + def f(): + switch("ok") + switch("fail") + g = greenlet(f) + res = g.switch() + self.assertEqual(res, "ok") + res = g.throw() + self.assertTrue(isinstance(res, greenlet.GreenletExit)) + self.assertTrue(g.dead) + res = g.throw() # immediately eaten by the already-dead greenlet + self.assertTrue(isinstance(res, greenlet.GreenletExit)) + + def test_throw_goes_to_original_parent(self): + main = greenlet.getcurrent() + + def f1(): + try: + main.switch("f1 ready to catch") + except IndexError: + return "caught" + return "normal exit" + + def f2(): + main.switch("from f2") + + g1 = greenlet(f1) + g2 = greenlet(f2, parent=g1) + with self.assertRaises(IndexError): + g2.throw(IndexError) + self.assertTrue(g2.dead) + self.assertTrue(g1.dead) + + g1 = greenlet(f1) + g2 = greenlet(f2, parent=g1) + res = g1.switch() + self.assertEqual(res, "f1 ready to catch") + res = g2.throw(IndexError) + self.assertEqual(res, "caught") + self.assertTrue(g2.dead) + self.assertTrue(g1.dead) + + g1 = greenlet(f1) + g2 = greenlet(f2, parent=g1) + res = g1.switch() + self.assertEqual(res, "f1 ready to catch") + res = g2.switch() + self.assertEqual(res, "from f2") + res = g2.throw(IndexError) + self.assertEqual(res, "caught") + self.assertTrue(g2.dead) + self.assertTrue(g1.dead) + + def test_non_traceback_param(self): + with self.assertRaises(TypeError) as exc: + greenlet.getcurrent().throw( + Exception, + Exception(), + self + ) + self.assertEqual(str(exc.exception), + "throw() third argument must be a traceback object") + + def test_instance_of_wrong_type(self): + with self.assertRaises(TypeError) as exc: + greenlet.getcurrent().throw( + Exception(), + BaseException() + ) + + self.assertEqual(str(exc.exception), + "instance exception may not have a separate value") + + def test_not_throwable(self): + with self.assertRaises(TypeError) as exc: + greenlet.getcurrent().throw( + "abc" + ) + self.assertEqual(str(exc.exception), + "exceptions must be classes, or instances, not str") diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/tests/test_tracing.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/tests/test_tracing.py new file mode 100644 index 000000000..c54a910a1 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/tests/test_tracing.py @@ -0,0 +1,298 @@ +import sys +import sysconfig +import greenlet +import unittest + +from . import TestCase +from . import PY312 + +# https://discuss.python.org/t/cpython-3-12-greenlet-and-tracing-profiling-how-to-not-crash-and-get-correct-results/33144/2 +# When build variables are available, OPT is the best way of detecting +# the build with assertions enabled. Otherwise, fallback to detecting PyDEBUG +# build. +ASSERTION_BUILD_PY312 = ( + PY312 and ( + "-DNDEBUG" not in sysconfig.get_config_var("OPT").split() + if sysconfig.get_config_var("OPT") is not None + else hasattr(sys, 'gettotalrefcount') + ), + "Broken on assertion-enabled builds of Python 3.12" +) + +class SomeError(Exception): + pass + +class GreenletTracer(object): + oldtrace = None + + def __init__(self, error_on_trace=False): + self.actions = [] + self.error_on_trace = error_on_trace + + def __call__(self, *args): + self.actions.append(args) + if self.error_on_trace: + raise SomeError + + def __enter__(self): + self.oldtrace = greenlet.settrace(self) + return self.actions + + def __exit__(self, *args): + greenlet.settrace(self.oldtrace) + + +class TestGreenletTracing(TestCase): + """ + Tests of ``greenlet.settrace()`` + """ + + def test_a_greenlet_tracing(self): + main = greenlet.getcurrent() + def dummy(): + pass + def dummyexc(): + raise SomeError() + + with GreenletTracer() as actions: + g1 = greenlet.greenlet(dummy) + g1.switch() + g2 = greenlet.greenlet(dummyexc) + self.assertRaises(SomeError, g2.switch) + + self.assertEqual(actions, [ + ('switch', (main, g1)), + ('switch', (g1, main)), + ('switch', (main, g2)), + ('throw', (g2, main)), + ]) + + def test_b_exception_disables_tracing(self): + main = greenlet.getcurrent() + def dummy(): + main.switch() + g = greenlet.greenlet(dummy) + g.switch() + with GreenletTracer(error_on_trace=True) as actions: + self.assertRaises(SomeError, g.switch) + self.assertEqual(greenlet.gettrace(), None) + + self.assertEqual(actions, [ + ('switch', (main, g)), + ]) + + def test_set_same_tracer_twice(self): + # https://github.com/python-greenlet/greenlet/issues/332 + # Our logic in asserting that the tracefunction should + # gain a reference was incorrect if the same tracefunction was set + # twice. + tracer = GreenletTracer() + with tracer: + greenlet.settrace(tracer) + + +class PythonTracer(object): + oldtrace = None + + def __init__(self): + self.actions = [] + + def __call__(self, frame, event, arg): + # Record the co_name so we have an idea what function we're in. + self.actions.append((event, frame.f_code.co_name)) + + def __enter__(self): + self.oldtrace = sys.setprofile(self) + return self.actions + + def __exit__(self, *args): + sys.setprofile(self.oldtrace) + +def tpt_callback(): + return 42 + +class TestPythonTracing(TestCase): + """ + Tests of the interaction of ``sys.settrace()`` + with greenlet facilities. + + NOTE: Most of this is probably CPython specific. + """ + + maxDiff = None + + def test_trace_events_trivial(self): + with PythonTracer() as actions: + tpt_callback() + # If we use the sys.settrace instead of setprofile, we get + # this: + + # self.assertEqual(actions, [ + # ('call', 'tpt_callback'), + # ('call', '__exit__'), + # ]) + + self.assertEqual(actions, [ + ('return', '__enter__'), + ('call', 'tpt_callback'), + ('return', 'tpt_callback'), + ('call', '__exit__'), + ('c_call', '__exit__'), + ]) + + def _trace_switch(self, glet): + with PythonTracer() as actions: + glet.switch() + return actions + + def _check_trace_events_func_already_set(self, glet): + actions = self._trace_switch(glet) + self.assertEqual(actions, [ + ('return', '__enter__'), + ('c_call', '_trace_switch'), + ('call', 'run'), + ('call', 'tpt_callback'), + ('return', 'tpt_callback'), + ('return', 'run'), + ('c_return', '_trace_switch'), + ('call', '__exit__'), + ('c_call', '__exit__'), + ]) + + def test_trace_events_into_greenlet_func_already_set(self): + def run(): + return tpt_callback() + + self._check_trace_events_func_already_set(greenlet.greenlet(run)) + + def test_trace_events_into_greenlet_subclass_already_set(self): + class X(greenlet.greenlet): + def run(self): + return tpt_callback() + self._check_trace_events_func_already_set(X()) + + def _check_trace_events_from_greenlet_sets_profiler(self, g, tracer): + g.switch() + tpt_callback() + tracer.__exit__() + self.assertEqual(tracer.actions, [ + ('return', '__enter__'), + ('call', 'tpt_callback'), + ('return', 'tpt_callback'), + ('return', 'run'), + ('call', 'tpt_callback'), + ('return', 'tpt_callback'), + ('call', '__exit__'), + ('c_call', '__exit__'), + ]) + + + def test_trace_events_from_greenlet_func_sets_profiler(self): + tracer = PythonTracer() + def run(): + tracer.__enter__() + return tpt_callback() + + self._check_trace_events_from_greenlet_sets_profiler(greenlet.greenlet(run), + tracer) + + def test_trace_events_from_greenlet_subclass_sets_profiler(self): + tracer = PythonTracer() + class X(greenlet.greenlet): + def run(self): + tracer.__enter__() + return tpt_callback() + + self._check_trace_events_from_greenlet_sets_profiler(X(), tracer) + + @unittest.skipIf(*ASSERTION_BUILD_PY312) + def test_trace_events_multiple_greenlets_switching(self): + tracer = PythonTracer() + + g1 = None + g2 = None + + def g1_run(): + tracer.__enter__() + tpt_callback() + g2.switch() + tpt_callback() + return 42 + + def g2_run(): + tpt_callback() + tracer.__exit__() + tpt_callback() + g1.switch() + + g1 = greenlet.greenlet(g1_run) + g2 = greenlet.greenlet(g2_run) + + x = g1.switch() + self.assertEqual(x, 42) + tpt_callback() # ensure not in the trace + self.assertEqual(tracer.actions, [ + ('return', '__enter__'), + ('call', 'tpt_callback'), + ('return', 'tpt_callback'), + ('c_call', 'g1_run'), + ('call', 'g2_run'), + ('call', 'tpt_callback'), + ('return', 'tpt_callback'), + ('call', '__exit__'), + ('c_call', '__exit__'), + ]) + + @unittest.skipIf(*ASSERTION_BUILD_PY312) + def test_trace_events_multiple_greenlets_switching_siblings(self): + # Like the first version, but get both greenlets running first + # as "siblings" and then establish the tracing. + tracer = PythonTracer() + + g1 = None + g2 = None + + def g1_run(): + greenlet.getcurrent().parent.switch() + tracer.__enter__() + tpt_callback() + g2.switch() + tpt_callback() + return 42 + + def g2_run(): + greenlet.getcurrent().parent.switch() + + tpt_callback() + tracer.__exit__() + tpt_callback() + g1.switch() + + g1 = greenlet.greenlet(g1_run) + g2 = greenlet.greenlet(g2_run) + + # Start g1 + g1.switch() + # And it immediately returns control to us. + # Start g2 + g2.switch() + # Which also returns. Now kick of the real part of the + # test. + x = g1.switch() + self.assertEqual(x, 42) + + tpt_callback() # ensure not in the trace + self.assertEqual(tracer.actions, [ + ('return', '__enter__'), + ('call', 'tpt_callback'), + ('return', 'tpt_callback'), + ('c_call', 'g1_run'), + ('call', 'tpt_callback'), + ('return', 'tpt_callback'), + ('call', '__exit__'), + ('c_call', '__exit__'), + ]) + + +if __name__ == '__main__': + unittest.main() diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/tests/test_version.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/tests/test_version.py new file mode 100644 index 000000000..12b55c27a --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/tests/test_version.py @@ -0,0 +1,46 @@ +#! /usr/bin/env python + +import sys +import os +from unittest import TestCase as NonLeakingTestCase + +import greenlet + +# No reason to run this multiple times under leakchecks, +# it doesn't do anything. +class VersionTests(NonLeakingTestCase): + def test_version(self): + def find_dominating_file(name): + if os.path.exists(name): + return name + + tried = [] + here = os.path.abspath(os.path.dirname(__file__)) + for i in range(10): + up = ['..'] * i + path = [here] + up + [name] + fname = os.path.join(*path) + fname = os.path.abspath(fname) + tried.append(fname) + if os.path.exists(fname): + return fname + raise AssertionError("Could not find file " + name + "; checked " + str(tried)) + + try: + setup_py = find_dominating_file('setup.py') + except AssertionError as e: + self.skipTest("Unable to find setup.py; must be out of tree. " + str(e)) + + + invoke_setup = "%s %s --version" % (sys.executable, setup_py) + with os.popen(invoke_setup) as f: + sversion = f.read().strip() + + if not sversion or not sversion[0].isdigit(): + self.skipTest( + "setup.py --version did not return a version string " + "(likely a setuptools compatibility issue): " + + repr(sversion[:80]) + ) + + self.assertEqual(sversion, greenlet.__version__) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/tests/test_weakref.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/tests/test_weakref.py new file mode 100644 index 000000000..05a38a7f1 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/greenlet/tests/test_weakref.py @@ -0,0 +1,35 @@ +import gc +import weakref + + +import greenlet +from . import TestCase + +class WeakRefTests(TestCase): + def test_dead_weakref(self): + def _dead_greenlet(): + g = greenlet.greenlet(lambda: None) + g.switch() + return g + o = weakref.ref(_dead_greenlet()) + gc.collect() + self.assertEqual(o(), None) + + def test_inactive_weakref(self): + o = weakref.ref(greenlet.greenlet()) + gc.collect() + self.assertEqual(o(), None) + + def test_dealloc_weakref(self): + seen = [] + def worker(): + try: + greenlet.getcurrent().parent.switch() + finally: + seen.append(g()) + g = greenlet.greenlet(worker) + g.switch() + g2 = greenlet.greenlet(lambda: None, g) + g = weakref.ref(g2) + g2 = None + self.assertEqual(seen, [None]) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/idna-3.11.dist-info/INSTALLER b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/idna-3.11.dist-info/INSTALLER new file mode 100644 index 000000000..a1b589e38 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/idna-3.11.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/idna-3.11.dist-info/METADATA b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/idna-3.11.dist-info/METADATA new file mode 100644 index 000000000..7a4a4b7a7 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/idna-3.11.dist-info/METADATA @@ -0,0 +1,209 @@ +Metadata-Version: 2.4 +Name: idna +Version: 3.11 +Summary: Internationalized Domain Names in Applications (IDNA) +Author-email: Kim Davies +Requires-Python: >=3.8 +Description-Content-Type: text/x-rst +License-Expression: BSD-3-Clause +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: Intended Audience :: System Administrators +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3 :: Only +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Programming Language :: Python :: 3.14 +Classifier: Programming Language :: Python :: Implementation :: CPython +Classifier: Programming Language :: Python :: Implementation :: PyPy +Classifier: Topic :: Internet :: Name Service (DNS) +Classifier: Topic :: Software Development :: Libraries :: Python Modules +Classifier: Topic :: Utilities +License-File: LICENSE.md +Requires-Dist: ruff >= 0.6.2 ; extra == "all" +Requires-Dist: mypy >= 1.11.2 ; extra == "all" +Requires-Dist: pytest >= 8.3.2 ; extra == "all" +Requires-Dist: flake8 >= 7.1.1 ; extra == "all" +Project-URL: Changelog, https://github.com/kjd/idna/blob/master/HISTORY.rst +Project-URL: Issue tracker, https://github.com/kjd/idna/issues +Project-URL: Source, https://github.com/kjd/idna +Provides-Extra: all + +Internationalized Domain Names in Applications (IDNA) +===================================================== + +Support for `Internationalized Domain Names in +Applications (IDNA) `_ +and `Unicode IDNA Compatibility Processing +`_. + +The latest versions of these standards supplied here provide +more comprehensive language coverage and reduce the potential of +allowing domains with known security vulnerabilities. This library +is a suitable replacement for the “encodings.idna” +module that comes with the Python standard library, but which +only supports an older superseded IDNA specification from 2003. + +Basic functions are simply executed: + +.. code-block:: pycon + + >>> import idna + >>> idna.encode('ドメイン.テスト') + b'xn--eckwd4c7c.xn--zckzah' + >>> print(idna.decode('xn--eckwd4c7c.xn--zckzah')) + ドメイン.テスト + + +Installation +------------ + +This package is available for installation from PyPI via the +typical mechanisms, such as: + +.. code-block:: bash + + $ python3 -m pip install idna + + +Usage +----- + +For typical usage, the ``encode`` and ``decode`` functions will take a +domain name argument and perform a conversion to ASCII compatible encoding +(known as A-labels), or to Unicode strings (known as U-labels) +respectively. + +.. code-block:: pycon + + >>> import idna + >>> idna.encode('ドメイン.テスト') + b'xn--eckwd4c7c.xn--zckzah' + >>> print(idna.decode('xn--eckwd4c7c.xn--zckzah')) + ドメイン.テスト + +Conversions can be applied at a per-label basis using the ``ulabel`` or +``alabel`` functions if necessary: + +.. code-block:: pycon + + >>> idna.alabel('测试') + b'xn--0zwm56d' + + +Compatibility Mapping (UTS #46) ++++++++++++++++++++++++++++++++ + +This library provides support for `Unicode IDNA Compatibility +Processing `_ which normalizes input from +different potential ways a user may input a domain prior to performing the IDNA +conversion operations. This functionality, known as a +`mapping `_, is considered by the +specification to be a local user-interface issue distinct from IDNA +conversion functionality. + +For example, “Königsgäßchen” is not a permissible label as *LATIN +CAPITAL LETTER K* is not allowed (nor are capital letters in general). +UTS 46 will convert this into lower case prior to applying the IDNA +conversion. + +.. code-block:: pycon + + >>> import idna + >>> idna.encode('Königsgäßchen') + ... + idna.core.InvalidCodepoint: Codepoint U+004B at position 1 of 'Königsgäßchen' not allowed + >>> idna.encode('Königsgäßchen', uts46=True) + b'xn--knigsgchen-b4a3dun' + >>> print(idna.decode('xn--knigsgchen-b4a3dun')) + königsgäßchen + + +Exceptions +---------- + +All errors raised during the conversion following the specification +should raise an exception derived from the ``idna.IDNAError`` base +class. + +More specific exceptions that may be generated as ``idna.IDNABidiError`` +when the error reflects an illegal combination of left-to-right and +right-to-left characters in a label; ``idna.InvalidCodepoint`` when +a specific codepoint is an illegal character in an IDN label (i.e. +INVALID); and ``idna.InvalidCodepointContext`` when the codepoint is +illegal based on its position in the string (i.e. it is CONTEXTO or CONTEXTJ +but the contextual requirements are not satisfied.) + +Building and Diagnostics +------------------------ + +The IDNA and UTS 46 functionality relies upon pre-calculated lookup +tables for performance. These tables are derived from computing against +eligibility criteria in the respective standards using the command-line +script ``tools/idna-data``. + +This tool will fetch relevant codepoint data from the Unicode repository +and perform the required calculations to identify eligibility. There are +three main modes: + +* ``idna-data make-libdata``. Generates ``idnadata.py`` and + ``uts46data.py``, the pre-calculated lookup tables used for IDNA and + UTS 46 conversions. Implementers who wish to track this library against + a different Unicode version may use this tool to manually generate a + different version of the ``idnadata.py`` and ``uts46data.py`` files. + +* ``idna-data make-table``. Generate a table of the IDNA disposition + (e.g. PVALID, CONTEXTJ, CONTEXTO) in the format found in Appendix + B.1 of RFC 5892 and the pre-computed tables published by `IANA + `_. + +* ``idna-data U+0061``. Prints debugging output on the various + properties associated with an individual Unicode codepoint (in this + case, U+0061), that are used to assess the IDNA and UTS 46 status of a + codepoint. This is helpful in debugging or analysis. + +The tool accepts a number of arguments, described using ``idna-data +-h``. Most notably, the ``--version`` argument allows the specification +of the version of Unicode to be used in computing the table data. For +example, ``idna-data --version 9.0.0 make-libdata`` will generate +library data against Unicode 9.0.0. + + +Additional Notes +---------------- + +* **Packages**. The latest tagged release version is published in the + `Python Package Index `_. + +* **Version support**. This library supports Python 3.8 and higher. + As this library serves as a low-level toolkit for a variety of + applications, many of which strive for broad compatibility with older + Python versions, there is no rush to remove older interpreter support. + Support for older versions are likely to be removed from new releases + as automated tests can no longer easily be run, i.e. once the Python + version is officially end-of-life. + +* **Testing**. The library has a test suite based on each rule of the + IDNA specification, as well as tests that are provided as part of the + Unicode Technical Standard 46, `Unicode IDNA Compatibility Processing + `_. + +* **Emoji**. It is an occasional request to support emoji domains in + this library. Encoding of symbols like emoji is expressly prohibited by + the technical standard IDNA 2008 and emoji domains are broadly phased + out across the domain industry due to associated security risks. For + now, applications that need to support these non-compliant labels + may wish to consider trying the encode/decode operation in this library + first, and then falling back to using `encodings.idna`. See `the Github + project `_ for more discussion. + +* **Transitional processing**. Unicode 16.0.0 removed transitional + processing so the `transitional` argument for the encode() method + no longer has any effect and will be removed at a later date. + diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/idna-3.11.dist-info/RECORD b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/idna-3.11.dist-info/RECORD new file mode 100644 index 000000000..8525b6daf --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/idna-3.11.dist-info/RECORD @@ -0,0 +1,22 @@ +idna-3.11.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +idna-3.11.dist-info/METADATA,sha256=fCwSww9SuiN8TIHllFSASUQCW55hAs8dzKnr9RaEEbA,8378 +idna-3.11.dist-info/RECORD,, +idna-3.11.dist-info/WHEEL,sha256=G2gURzTEtmeR8nrdXUJfNiB3VYVxigPQ-bEQujpNiNs,82 +idna-3.11.dist-info/licenses/LICENSE.md,sha256=t6M2q_OwThgOwGXN0W5wXQeeHMehT5EKpukYfza5zYc,1541 +idna/__init__.py,sha256=MPqNDLZbXqGaNdXxAFhiqFPKEQXju2jNQhCey6-5eJM,868 +idna/__pycache__/__init__.cpython-312.pyc,, +idna/__pycache__/codec.cpython-312.pyc,, +idna/__pycache__/compat.cpython-312.pyc,, +idna/__pycache__/core.cpython-312.pyc,, +idna/__pycache__/idnadata.cpython-312.pyc,, +idna/__pycache__/intranges.cpython-312.pyc,, +idna/__pycache__/package_data.cpython-312.pyc,, +idna/__pycache__/uts46data.cpython-312.pyc,, +idna/codec.py,sha256=M2SGWN7cs_6B32QmKTyTN6xQGZeYQgQ2wiX3_DR6loE,3438 +idna/compat.py,sha256=RzLy6QQCdl9784aFhb2EX9EKGCJjg0P3PilGdeXXcx8,316 +idna/core.py,sha256=P26_XVycuMTZ1R2mNK1ZREVzM5mvTzdabBXfyZVU1Lc,13246 +idna/idnadata.py,sha256=SG8jhaGE53iiD6B49pt2pwTv_UvClciWE-N54oR2p4U,79623 +idna/intranges.py,sha256=amUtkdhYcQG8Zr-CoMM_kVRacxkivC1WgxN1b63KKdU,1898 +idna/package_data.py,sha256=_CUavOxobnbyNG2FLyHoN8QHP3QM9W1tKuw7eq9QwBk,21 +idna/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +idna/uts46data.py,sha256=H9J35VkD0F9L9mKOqjeNGd2A-Va6FlPoz6Jz4K7h-ps,243725 diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/idna-3.11.dist-info/WHEEL b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/idna-3.11.dist-info/WHEEL new file mode 100644 index 000000000..d8b9936da --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/idna-3.11.dist-info/WHEEL @@ -0,0 +1,4 @@ +Wheel-Version: 1.0 +Generator: flit 3.12.0 +Root-Is-Purelib: true +Tag: py3-none-any diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/idna-3.11.dist-info/licenses/LICENSE.md b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/idna-3.11.dist-info/licenses/LICENSE.md new file mode 100644 index 000000000..256ba90cd --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/idna-3.11.dist-info/licenses/LICENSE.md @@ -0,0 +1,31 @@ +BSD 3-Clause License + +Copyright (c) 2013-2025, Kim Davies and contributors. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED +TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/idna/__init__.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/idna/__init__.py new file mode 100644 index 000000000..cfdc030a7 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/idna/__init__.py @@ -0,0 +1,45 @@ +from .core import ( + IDNABidiError, + IDNAError, + InvalidCodepoint, + InvalidCodepointContext, + alabel, + check_bidi, + check_hyphen_ok, + check_initial_combiner, + check_label, + check_nfc, + decode, + encode, + ulabel, + uts46_remap, + valid_contextj, + valid_contexto, + valid_label_length, + valid_string_length, +) +from .intranges import intranges_contain +from .package_data import __version__ + +__all__ = [ + "__version__", + "IDNABidiError", + "IDNAError", + "InvalidCodepoint", + "InvalidCodepointContext", + "alabel", + "check_bidi", + "check_hyphen_ok", + "check_initial_combiner", + "check_label", + "check_nfc", + "decode", + "encode", + "intranges_contain", + "ulabel", + "uts46_remap", + "valid_contextj", + "valid_contexto", + "valid_label_length", + "valid_string_length", +] diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/idna/codec.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/idna/codec.py new file mode 100644 index 000000000..cbc2e4ff4 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/idna/codec.py @@ -0,0 +1,122 @@ +import codecs +import re +from typing import Any, Optional, Tuple + +from .core import IDNAError, alabel, decode, encode, ulabel + +_unicode_dots_re = re.compile("[\u002e\u3002\uff0e\uff61]") + + +class Codec(codecs.Codec): + def encode(self, data: str, errors: str = "strict") -> Tuple[bytes, int]: + if errors != "strict": + raise IDNAError('Unsupported error handling "{}"'.format(errors)) + + if not data: + return b"", 0 + + return encode(data), len(data) + + def decode(self, data: bytes, errors: str = "strict") -> Tuple[str, int]: + if errors != "strict": + raise IDNAError('Unsupported error handling "{}"'.format(errors)) + + if not data: + return "", 0 + + return decode(data), len(data) + + +class IncrementalEncoder(codecs.BufferedIncrementalEncoder): + def _buffer_encode(self, data: str, errors: str, final: bool) -> Tuple[bytes, int]: + if errors != "strict": + raise IDNAError('Unsupported error handling "{}"'.format(errors)) + + if not data: + return b"", 0 + + labels = _unicode_dots_re.split(data) + trailing_dot = b"" + if labels: + if not labels[-1]: + trailing_dot = b"." + del labels[-1] + elif not final: + # Keep potentially unfinished label until the next call + del labels[-1] + if labels: + trailing_dot = b"." + + result = [] + size = 0 + for label in labels: + result.append(alabel(label)) + if size: + size += 1 + size += len(label) + + # Join with U+002E + result_bytes = b".".join(result) + trailing_dot + size += len(trailing_dot) + return result_bytes, size + + +class IncrementalDecoder(codecs.BufferedIncrementalDecoder): + def _buffer_decode(self, data: Any, errors: str, final: bool) -> Tuple[str, int]: + if errors != "strict": + raise IDNAError('Unsupported error handling "{}"'.format(errors)) + + if not data: + return ("", 0) + + if not isinstance(data, str): + data = str(data, "ascii") + + labels = _unicode_dots_re.split(data) + trailing_dot = "" + if labels: + if not labels[-1]: + trailing_dot = "." + del labels[-1] + elif not final: + # Keep potentially unfinished label until the next call + del labels[-1] + if labels: + trailing_dot = "." + + result = [] + size = 0 + for label in labels: + result.append(ulabel(label)) + if size: + size += 1 + size += len(label) + + result_str = ".".join(result) + trailing_dot + size += len(trailing_dot) + return (result_str, size) + + +class StreamWriter(Codec, codecs.StreamWriter): + pass + + +class StreamReader(Codec, codecs.StreamReader): + pass + + +def search_function(name: str) -> Optional[codecs.CodecInfo]: + if name != "idna2008": + return None + return codecs.CodecInfo( + name=name, + encode=Codec().encode, + decode=Codec().decode, # type: ignore + incrementalencoder=IncrementalEncoder, + incrementaldecoder=IncrementalDecoder, + streamwriter=StreamWriter, + streamreader=StreamReader, + ) + + +codecs.register(search_function) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/idna/compat.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/idna/compat.py new file mode 100644 index 000000000..1df9f2a70 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/idna/compat.py @@ -0,0 +1,15 @@ +from typing import Any, Union + +from .core import decode, encode + + +def ToASCII(label: str) -> bytes: + return encode(label) + + +def ToUnicode(label: Union[bytes, bytearray]) -> str: + return decode(label) + + +def nameprep(s: Any) -> None: + raise NotImplementedError("IDNA 2008 does not utilise nameprep protocol") diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/idna/core.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/idna/core.py new file mode 100644 index 000000000..8177bf7a3 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/idna/core.py @@ -0,0 +1,437 @@ +import bisect +import re +import unicodedata +from typing import Optional, Union + +from . import idnadata +from .intranges import intranges_contain + +_virama_combining_class = 9 +_alabel_prefix = b"xn--" +_unicode_dots_re = re.compile("[\u002e\u3002\uff0e\uff61]") + + +class IDNAError(UnicodeError): + """Base exception for all IDNA-encoding related problems""" + + pass + + +class IDNABidiError(IDNAError): + """Exception when bidirectional requirements are not satisfied""" + + pass + + +class InvalidCodepoint(IDNAError): + """Exception when a disallowed or unallocated codepoint is used""" + + pass + + +class InvalidCodepointContext(IDNAError): + """Exception when the codepoint is not valid in the context it is used""" + + pass + + +def _combining_class(cp: int) -> int: + v = unicodedata.combining(chr(cp)) + if v == 0: + if not unicodedata.name(chr(cp)): + raise ValueError("Unknown character in unicodedata") + return v + + +def _is_script(cp: str, script: str) -> bool: + return intranges_contain(ord(cp), idnadata.scripts[script]) + + +def _punycode(s: str) -> bytes: + return s.encode("punycode") + + +def _unot(s: int) -> str: + return "U+{:04X}".format(s) + + +def valid_label_length(label: Union[bytes, str]) -> bool: + if len(label) > 63: + return False + return True + + +def valid_string_length(label: Union[bytes, str], trailing_dot: bool) -> bool: + if len(label) > (254 if trailing_dot else 253): + return False + return True + + +def check_bidi(label: str, check_ltr: bool = False) -> bool: + # Bidi rules should only be applied if string contains RTL characters + bidi_label = False + for idx, cp in enumerate(label, 1): + direction = unicodedata.bidirectional(cp) + if direction == "": + # String likely comes from a newer version of Unicode + raise IDNABidiError("Unknown directionality in label {} at position {}".format(repr(label), idx)) + if direction in ["R", "AL", "AN"]: + bidi_label = True + if not bidi_label and not check_ltr: + return True + + # Bidi rule 1 + direction = unicodedata.bidirectional(label[0]) + if direction in ["R", "AL"]: + rtl = True + elif direction == "L": + rtl = False + else: + raise IDNABidiError("First codepoint in label {} must be directionality L, R or AL".format(repr(label))) + + valid_ending = False + number_type: Optional[str] = None + for idx, cp in enumerate(label, 1): + direction = unicodedata.bidirectional(cp) + + if rtl: + # Bidi rule 2 + if direction not in [ + "R", + "AL", + "AN", + "EN", + "ES", + "CS", + "ET", + "ON", + "BN", + "NSM", + ]: + raise IDNABidiError("Invalid direction for codepoint at position {} in a right-to-left label".format(idx)) + # Bidi rule 3 + if direction in ["R", "AL", "EN", "AN"]: + valid_ending = True + elif direction != "NSM": + valid_ending = False + # Bidi rule 4 + if direction in ["AN", "EN"]: + if not number_type: + number_type = direction + else: + if number_type != direction: + raise IDNABidiError("Can not mix numeral types in a right-to-left label") + else: + # Bidi rule 5 + if direction not in ["L", "EN", "ES", "CS", "ET", "ON", "BN", "NSM"]: + raise IDNABidiError("Invalid direction for codepoint at position {} in a left-to-right label".format(idx)) + # Bidi rule 6 + if direction in ["L", "EN"]: + valid_ending = True + elif direction != "NSM": + valid_ending = False + + if not valid_ending: + raise IDNABidiError("Label ends with illegal codepoint directionality") + + return True + + +def check_initial_combiner(label: str) -> bool: + if unicodedata.category(label[0])[0] == "M": + raise IDNAError("Label begins with an illegal combining character") + return True + + +def check_hyphen_ok(label: str) -> bool: + if label[2:4] == "--": + raise IDNAError("Label has disallowed hyphens in 3rd and 4th position") + if label[0] == "-" or label[-1] == "-": + raise IDNAError("Label must not start or end with a hyphen") + return True + + +def check_nfc(label: str) -> None: + if unicodedata.normalize("NFC", label) != label: + raise IDNAError("Label must be in Normalization Form C") + + +def valid_contextj(label: str, pos: int) -> bool: + cp_value = ord(label[pos]) + + if cp_value == 0x200C: + if pos > 0: + if _combining_class(ord(label[pos - 1])) == _virama_combining_class: + return True + + ok = False + for i in range(pos - 1, -1, -1): + joining_type = idnadata.joining_types.get(ord(label[i])) + if joining_type == ord("T"): + continue + elif joining_type in [ord("L"), ord("D")]: + ok = True + break + else: + break + + if not ok: + return False + + ok = False + for i in range(pos + 1, len(label)): + joining_type = idnadata.joining_types.get(ord(label[i])) + if joining_type == ord("T"): + continue + elif joining_type in [ord("R"), ord("D")]: + ok = True + break + else: + break + return ok + + if cp_value == 0x200D: + if pos > 0: + if _combining_class(ord(label[pos - 1])) == _virama_combining_class: + return True + return False + + else: + return False + + +def valid_contexto(label: str, pos: int, exception: bool = False) -> bool: + cp_value = ord(label[pos]) + + if cp_value == 0x00B7: + if 0 < pos < len(label) - 1: + if ord(label[pos - 1]) == 0x006C and ord(label[pos + 1]) == 0x006C: + return True + return False + + elif cp_value == 0x0375: + if pos < len(label) - 1 and len(label) > 1: + return _is_script(label[pos + 1], "Greek") + return False + + elif cp_value == 0x05F3 or cp_value == 0x05F4: + if pos > 0: + return _is_script(label[pos - 1], "Hebrew") + return False + + elif cp_value == 0x30FB: + for cp in label: + if cp == "\u30fb": + continue + if _is_script(cp, "Hiragana") or _is_script(cp, "Katakana") or _is_script(cp, "Han"): + return True + return False + + elif 0x660 <= cp_value <= 0x669: + for cp in label: + if 0x6F0 <= ord(cp) <= 0x06F9: + return False + return True + + elif 0x6F0 <= cp_value <= 0x6F9: + for cp in label: + if 0x660 <= ord(cp) <= 0x0669: + return False + return True + + return False + + +def check_label(label: Union[str, bytes, bytearray]) -> None: + if isinstance(label, (bytes, bytearray)): + label = label.decode("utf-8") + if len(label) == 0: + raise IDNAError("Empty Label") + + check_nfc(label) + check_hyphen_ok(label) + check_initial_combiner(label) + + for pos, cp in enumerate(label): + cp_value = ord(cp) + if intranges_contain(cp_value, idnadata.codepoint_classes["PVALID"]): + continue + elif intranges_contain(cp_value, idnadata.codepoint_classes["CONTEXTJ"]): + try: + if not valid_contextj(label, pos): + raise InvalidCodepointContext( + "Joiner {} not allowed at position {} in {}".format(_unot(cp_value), pos + 1, repr(label)) + ) + except ValueError: + raise IDNAError( + "Unknown codepoint adjacent to joiner {} at position {} in {}".format( + _unot(cp_value), pos + 1, repr(label) + ) + ) + elif intranges_contain(cp_value, idnadata.codepoint_classes["CONTEXTO"]): + if not valid_contexto(label, pos): + raise InvalidCodepointContext( + "Codepoint {} not allowed at position {} in {}".format(_unot(cp_value), pos + 1, repr(label)) + ) + else: + raise InvalidCodepoint( + "Codepoint {} at position {} of {} not allowed".format(_unot(cp_value), pos + 1, repr(label)) + ) + + check_bidi(label) + + +def alabel(label: str) -> bytes: + try: + label_bytes = label.encode("ascii") + ulabel(label_bytes) + if not valid_label_length(label_bytes): + raise IDNAError("Label too long") + return label_bytes + except UnicodeEncodeError: + pass + + check_label(label) + label_bytes = _alabel_prefix + _punycode(label) + + if not valid_label_length(label_bytes): + raise IDNAError("Label too long") + + return label_bytes + + +def ulabel(label: Union[str, bytes, bytearray]) -> str: + if not isinstance(label, (bytes, bytearray)): + try: + label_bytes = label.encode("ascii") + except UnicodeEncodeError: + check_label(label) + return label + else: + label_bytes = bytes(label) + + label_bytes = label_bytes.lower() + if label_bytes.startswith(_alabel_prefix): + label_bytes = label_bytes[len(_alabel_prefix) :] + if not label_bytes: + raise IDNAError("Malformed A-label, no Punycode eligible content found") + if label_bytes.decode("ascii")[-1] == "-": + raise IDNAError("A-label must not end with a hyphen") + else: + check_label(label_bytes) + return label_bytes.decode("ascii") + + try: + label = label_bytes.decode("punycode") + except UnicodeError: + raise IDNAError("Invalid A-label") + check_label(label) + return label + + +def uts46_remap(domain: str, std3_rules: bool = True, transitional: bool = False) -> str: + """Re-map the characters in the string according to UTS46 processing.""" + from .uts46data import uts46data + + output = "" + + for pos, char in enumerate(domain): + code_point = ord(char) + try: + uts46row = uts46data[code_point if code_point < 256 else bisect.bisect_left(uts46data, (code_point, "Z")) - 1] + status = uts46row[1] + replacement: Optional[str] = None + if len(uts46row) == 3: + replacement = uts46row[2] + if ( + status == "V" + or (status == "D" and not transitional) + or (status == "3" and not std3_rules and replacement is None) + ): + output += char + elif replacement is not None and ( + status == "M" or (status == "3" and not std3_rules) or (status == "D" and transitional) + ): + output += replacement + elif status != "I": + raise IndexError() + except IndexError: + raise InvalidCodepoint( + "Codepoint {} not allowed at position {} in {}".format(_unot(code_point), pos + 1, repr(domain)) + ) + + return unicodedata.normalize("NFC", output) + + +def encode( + s: Union[str, bytes, bytearray], + strict: bool = False, + uts46: bool = False, + std3_rules: bool = False, + transitional: bool = False, +) -> bytes: + if not isinstance(s, str): + try: + s = str(s, "ascii") + except UnicodeDecodeError: + raise IDNAError("should pass a unicode string to the function rather than a byte string.") + if uts46: + s = uts46_remap(s, std3_rules, transitional) + trailing_dot = False + result = [] + if strict: + labels = s.split(".") + else: + labels = _unicode_dots_re.split(s) + if not labels or labels == [""]: + raise IDNAError("Empty domain") + if labels[-1] == "": + del labels[-1] + trailing_dot = True + for label in labels: + s = alabel(label) + if s: + result.append(s) + else: + raise IDNAError("Empty label") + if trailing_dot: + result.append(b"") + s = b".".join(result) + if not valid_string_length(s, trailing_dot): + raise IDNAError("Domain too long") + return s + + +def decode( + s: Union[str, bytes, bytearray], + strict: bool = False, + uts46: bool = False, + std3_rules: bool = False, +) -> str: + try: + if not isinstance(s, str): + s = str(s, "ascii") + except UnicodeDecodeError: + raise IDNAError("Invalid ASCII in A-label") + if uts46: + s = uts46_remap(s, std3_rules, False) + trailing_dot = False + result = [] + if not strict: + labels = _unicode_dots_re.split(s) + else: + labels = s.split(".") + if not labels or labels == [""]: + raise IDNAError("Empty domain") + if not labels[-1]: + del labels[-1] + trailing_dot = True + for label in labels: + s = ulabel(label) + if s: + result.append(s) + else: + raise IDNAError("Empty label") + if trailing_dot: + result.append("") + return ".".join(result) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/idna/idnadata.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/idna/idnadata.py new file mode 100644 index 000000000..ded47cae0 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/idna/idnadata.py @@ -0,0 +1,4309 @@ +# This file is automatically generated by tools/idna-data + +__version__ = "16.0.0" + +scripts = { + "Greek": ( + 0x37000000374, + 0x37500000378, + 0x37A0000037E, + 0x37F00000380, + 0x38400000385, + 0x38600000387, + 0x3880000038B, + 0x38C0000038D, + 0x38E000003A2, + 0x3A3000003E2, + 0x3F000000400, + 0x1D2600001D2B, + 0x1D5D00001D62, + 0x1D6600001D6B, + 0x1DBF00001DC0, + 0x1F0000001F16, + 0x1F1800001F1E, + 0x1F2000001F46, + 0x1F4800001F4E, + 0x1F5000001F58, + 0x1F5900001F5A, + 0x1F5B00001F5C, + 0x1F5D00001F5E, + 0x1F5F00001F7E, + 0x1F8000001FB5, + 0x1FB600001FC5, + 0x1FC600001FD4, + 0x1FD600001FDC, + 0x1FDD00001FF0, + 0x1FF200001FF5, + 0x1FF600001FFF, + 0x212600002127, + 0xAB650000AB66, + 0x101400001018F, + 0x101A0000101A1, + 0x1D2000001D246, + ), + "Han": ( + 0x2E8000002E9A, + 0x2E9B00002EF4, + 0x2F0000002FD6, + 0x300500003006, + 0x300700003008, + 0x30210000302A, + 0x30380000303C, + 0x340000004DC0, + 0x4E000000A000, + 0xF9000000FA6E, + 0xFA700000FADA, + 0x16FE200016FE4, + 0x16FF000016FF2, + 0x200000002A6E0, + 0x2A7000002B73A, + 0x2B7400002B81E, + 0x2B8200002CEA2, + 0x2CEB00002EBE1, + 0x2EBF00002EE5E, + 0x2F8000002FA1E, + 0x300000003134B, + 0x31350000323B0, + ), + "Hebrew": ( + 0x591000005C8, + 0x5D0000005EB, + 0x5EF000005F5, + 0xFB1D0000FB37, + 0xFB380000FB3D, + 0xFB3E0000FB3F, + 0xFB400000FB42, + 0xFB430000FB45, + 0xFB460000FB50, + ), + "Hiragana": ( + 0x304100003097, + 0x309D000030A0, + 0x1B0010001B120, + 0x1B1320001B133, + 0x1B1500001B153, + 0x1F2000001F201, + ), + "Katakana": ( + 0x30A1000030FB, + 0x30FD00003100, + 0x31F000003200, + 0x32D0000032FF, + 0x330000003358, + 0xFF660000FF70, + 0xFF710000FF9E, + 0x1AFF00001AFF4, + 0x1AFF50001AFFC, + 0x1AFFD0001AFFF, + 0x1B0000001B001, + 0x1B1200001B123, + 0x1B1550001B156, + 0x1B1640001B168, + ), +} +joining_types = { + 0xAD: 84, + 0x300: 84, + 0x301: 84, + 0x302: 84, + 0x303: 84, + 0x304: 84, + 0x305: 84, + 0x306: 84, + 0x307: 84, + 0x308: 84, + 0x309: 84, + 0x30A: 84, + 0x30B: 84, + 0x30C: 84, + 0x30D: 84, + 0x30E: 84, + 0x30F: 84, + 0x310: 84, + 0x311: 84, + 0x312: 84, + 0x313: 84, + 0x314: 84, + 0x315: 84, + 0x316: 84, + 0x317: 84, + 0x318: 84, + 0x319: 84, + 0x31A: 84, + 0x31B: 84, + 0x31C: 84, + 0x31D: 84, + 0x31E: 84, + 0x31F: 84, + 0x320: 84, + 0x321: 84, + 0x322: 84, + 0x323: 84, + 0x324: 84, + 0x325: 84, + 0x326: 84, + 0x327: 84, + 0x328: 84, + 0x329: 84, + 0x32A: 84, + 0x32B: 84, + 0x32C: 84, + 0x32D: 84, + 0x32E: 84, + 0x32F: 84, + 0x330: 84, + 0x331: 84, + 0x332: 84, + 0x333: 84, + 0x334: 84, + 0x335: 84, + 0x336: 84, + 0x337: 84, + 0x338: 84, + 0x339: 84, + 0x33A: 84, + 0x33B: 84, + 0x33C: 84, + 0x33D: 84, + 0x33E: 84, + 0x33F: 84, + 0x340: 84, + 0x341: 84, + 0x342: 84, + 0x343: 84, + 0x344: 84, + 0x345: 84, + 0x346: 84, + 0x347: 84, + 0x348: 84, + 0x349: 84, + 0x34A: 84, + 0x34B: 84, + 0x34C: 84, + 0x34D: 84, + 0x34E: 84, + 0x34F: 84, + 0x350: 84, + 0x351: 84, + 0x352: 84, + 0x353: 84, + 0x354: 84, + 0x355: 84, + 0x356: 84, + 0x357: 84, + 0x358: 84, + 0x359: 84, + 0x35A: 84, + 0x35B: 84, + 0x35C: 84, + 0x35D: 84, + 0x35E: 84, + 0x35F: 84, + 0x360: 84, + 0x361: 84, + 0x362: 84, + 0x363: 84, + 0x364: 84, + 0x365: 84, + 0x366: 84, + 0x367: 84, + 0x368: 84, + 0x369: 84, + 0x36A: 84, + 0x36B: 84, + 0x36C: 84, + 0x36D: 84, + 0x36E: 84, + 0x36F: 84, + 0x483: 84, + 0x484: 84, + 0x485: 84, + 0x486: 84, + 0x487: 84, + 0x488: 84, + 0x489: 84, + 0x591: 84, + 0x592: 84, + 0x593: 84, + 0x594: 84, + 0x595: 84, + 0x596: 84, + 0x597: 84, + 0x598: 84, + 0x599: 84, + 0x59A: 84, + 0x59B: 84, + 0x59C: 84, + 0x59D: 84, + 0x59E: 84, + 0x59F: 84, + 0x5A0: 84, + 0x5A1: 84, + 0x5A2: 84, + 0x5A3: 84, + 0x5A4: 84, + 0x5A5: 84, + 0x5A6: 84, + 0x5A7: 84, + 0x5A8: 84, + 0x5A9: 84, + 0x5AA: 84, + 0x5AB: 84, + 0x5AC: 84, + 0x5AD: 84, + 0x5AE: 84, + 0x5AF: 84, + 0x5B0: 84, + 0x5B1: 84, + 0x5B2: 84, + 0x5B3: 84, + 0x5B4: 84, + 0x5B5: 84, + 0x5B6: 84, + 0x5B7: 84, + 0x5B8: 84, + 0x5B9: 84, + 0x5BA: 84, + 0x5BB: 84, + 0x5BC: 84, + 0x5BD: 84, + 0x5BF: 84, + 0x5C1: 84, + 0x5C2: 84, + 0x5C4: 84, + 0x5C5: 84, + 0x5C7: 84, + 0x610: 84, + 0x611: 84, + 0x612: 84, + 0x613: 84, + 0x614: 84, + 0x615: 84, + 0x616: 84, + 0x617: 84, + 0x618: 84, + 0x619: 84, + 0x61A: 84, + 0x61C: 84, + 0x620: 68, + 0x622: 82, + 0x623: 82, + 0x624: 82, + 0x625: 82, + 0x626: 68, + 0x627: 82, + 0x628: 68, + 0x629: 82, + 0x62A: 68, + 0x62B: 68, + 0x62C: 68, + 0x62D: 68, + 0x62E: 68, + 0x62F: 82, + 0x630: 82, + 0x631: 82, + 0x632: 82, + 0x633: 68, + 0x634: 68, + 0x635: 68, + 0x636: 68, + 0x637: 68, + 0x638: 68, + 0x639: 68, + 0x63A: 68, + 0x63B: 68, + 0x63C: 68, + 0x63D: 68, + 0x63E: 68, + 0x63F: 68, + 0x640: 67, + 0x641: 68, + 0x642: 68, + 0x643: 68, + 0x644: 68, + 0x645: 68, + 0x646: 68, + 0x647: 68, + 0x648: 82, + 0x649: 68, + 0x64A: 68, + 0x64B: 84, + 0x64C: 84, + 0x64D: 84, + 0x64E: 84, + 0x64F: 84, + 0x650: 84, + 0x651: 84, + 0x652: 84, + 0x653: 84, + 0x654: 84, + 0x655: 84, + 0x656: 84, + 0x657: 84, + 0x658: 84, + 0x659: 84, + 0x65A: 84, + 0x65B: 84, + 0x65C: 84, + 0x65D: 84, + 0x65E: 84, + 0x65F: 84, + 0x66E: 68, + 0x66F: 68, + 0x670: 84, + 0x671: 82, + 0x672: 82, + 0x673: 82, + 0x675: 82, + 0x676: 82, + 0x677: 82, + 0x678: 68, + 0x679: 68, + 0x67A: 68, + 0x67B: 68, + 0x67C: 68, + 0x67D: 68, + 0x67E: 68, + 0x67F: 68, + 0x680: 68, + 0x681: 68, + 0x682: 68, + 0x683: 68, + 0x684: 68, + 0x685: 68, + 0x686: 68, + 0x687: 68, + 0x688: 82, + 0x689: 82, + 0x68A: 82, + 0x68B: 82, + 0x68C: 82, + 0x68D: 82, + 0x68E: 82, + 0x68F: 82, + 0x690: 82, + 0x691: 82, + 0x692: 82, + 0x693: 82, + 0x694: 82, + 0x695: 82, + 0x696: 82, + 0x697: 82, + 0x698: 82, + 0x699: 82, + 0x69A: 68, + 0x69B: 68, + 0x69C: 68, + 0x69D: 68, + 0x69E: 68, + 0x69F: 68, + 0x6A0: 68, + 0x6A1: 68, + 0x6A2: 68, + 0x6A3: 68, + 0x6A4: 68, + 0x6A5: 68, + 0x6A6: 68, + 0x6A7: 68, + 0x6A8: 68, + 0x6A9: 68, + 0x6AA: 68, + 0x6AB: 68, + 0x6AC: 68, + 0x6AD: 68, + 0x6AE: 68, + 0x6AF: 68, + 0x6B0: 68, + 0x6B1: 68, + 0x6B2: 68, + 0x6B3: 68, + 0x6B4: 68, + 0x6B5: 68, + 0x6B6: 68, + 0x6B7: 68, + 0x6B8: 68, + 0x6B9: 68, + 0x6BA: 68, + 0x6BB: 68, + 0x6BC: 68, + 0x6BD: 68, + 0x6BE: 68, + 0x6BF: 68, + 0x6C0: 82, + 0x6C1: 68, + 0x6C2: 68, + 0x6C3: 82, + 0x6C4: 82, + 0x6C5: 82, + 0x6C6: 82, + 0x6C7: 82, + 0x6C8: 82, + 0x6C9: 82, + 0x6CA: 82, + 0x6CB: 82, + 0x6CC: 68, + 0x6CD: 82, + 0x6CE: 68, + 0x6CF: 82, + 0x6D0: 68, + 0x6D1: 68, + 0x6D2: 82, + 0x6D3: 82, + 0x6D5: 82, + 0x6D6: 84, + 0x6D7: 84, + 0x6D8: 84, + 0x6D9: 84, + 0x6DA: 84, + 0x6DB: 84, + 0x6DC: 84, + 0x6DF: 84, + 0x6E0: 84, + 0x6E1: 84, + 0x6E2: 84, + 0x6E3: 84, + 0x6E4: 84, + 0x6E7: 84, + 0x6E8: 84, + 0x6EA: 84, + 0x6EB: 84, + 0x6EC: 84, + 0x6ED: 84, + 0x6EE: 82, + 0x6EF: 82, + 0x6FA: 68, + 0x6FB: 68, + 0x6FC: 68, + 0x6FF: 68, + 0x70F: 84, + 0x710: 82, + 0x711: 84, + 0x712: 68, + 0x713: 68, + 0x714: 68, + 0x715: 82, + 0x716: 82, + 0x717: 82, + 0x718: 82, + 0x719: 82, + 0x71A: 68, + 0x71B: 68, + 0x71C: 68, + 0x71D: 68, + 0x71E: 82, + 0x71F: 68, + 0x720: 68, + 0x721: 68, + 0x722: 68, + 0x723: 68, + 0x724: 68, + 0x725: 68, + 0x726: 68, + 0x727: 68, + 0x728: 82, + 0x729: 68, + 0x72A: 82, + 0x72B: 68, + 0x72C: 82, + 0x72D: 68, + 0x72E: 68, + 0x72F: 82, + 0x730: 84, + 0x731: 84, + 0x732: 84, + 0x733: 84, + 0x734: 84, + 0x735: 84, + 0x736: 84, + 0x737: 84, + 0x738: 84, + 0x739: 84, + 0x73A: 84, + 0x73B: 84, + 0x73C: 84, + 0x73D: 84, + 0x73E: 84, + 0x73F: 84, + 0x740: 84, + 0x741: 84, + 0x742: 84, + 0x743: 84, + 0x744: 84, + 0x745: 84, + 0x746: 84, + 0x747: 84, + 0x748: 84, + 0x749: 84, + 0x74A: 84, + 0x74D: 82, + 0x74E: 68, + 0x74F: 68, + 0x750: 68, + 0x751: 68, + 0x752: 68, + 0x753: 68, + 0x754: 68, + 0x755: 68, + 0x756: 68, + 0x757: 68, + 0x758: 68, + 0x759: 82, + 0x75A: 82, + 0x75B: 82, + 0x75C: 68, + 0x75D: 68, + 0x75E: 68, + 0x75F: 68, + 0x760: 68, + 0x761: 68, + 0x762: 68, + 0x763: 68, + 0x764: 68, + 0x765: 68, + 0x766: 68, + 0x767: 68, + 0x768: 68, + 0x769: 68, + 0x76A: 68, + 0x76B: 82, + 0x76C: 82, + 0x76D: 68, + 0x76E: 68, + 0x76F: 68, + 0x770: 68, + 0x771: 82, + 0x772: 68, + 0x773: 82, + 0x774: 82, + 0x775: 68, + 0x776: 68, + 0x777: 68, + 0x778: 82, + 0x779: 82, + 0x77A: 68, + 0x77B: 68, + 0x77C: 68, + 0x77D: 68, + 0x77E: 68, + 0x77F: 68, + 0x7A6: 84, + 0x7A7: 84, + 0x7A8: 84, + 0x7A9: 84, + 0x7AA: 84, + 0x7AB: 84, + 0x7AC: 84, + 0x7AD: 84, + 0x7AE: 84, + 0x7AF: 84, + 0x7B0: 84, + 0x7CA: 68, + 0x7CB: 68, + 0x7CC: 68, + 0x7CD: 68, + 0x7CE: 68, + 0x7CF: 68, + 0x7D0: 68, + 0x7D1: 68, + 0x7D2: 68, + 0x7D3: 68, + 0x7D4: 68, + 0x7D5: 68, + 0x7D6: 68, + 0x7D7: 68, + 0x7D8: 68, + 0x7D9: 68, + 0x7DA: 68, + 0x7DB: 68, + 0x7DC: 68, + 0x7DD: 68, + 0x7DE: 68, + 0x7DF: 68, + 0x7E0: 68, + 0x7E1: 68, + 0x7E2: 68, + 0x7E3: 68, + 0x7E4: 68, + 0x7E5: 68, + 0x7E6: 68, + 0x7E7: 68, + 0x7E8: 68, + 0x7E9: 68, + 0x7EA: 68, + 0x7EB: 84, + 0x7EC: 84, + 0x7ED: 84, + 0x7EE: 84, + 0x7EF: 84, + 0x7F0: 84, + 0x7F1: 84, + 0x7F2: 84, + 0x7F3: 84, + 0x7FA: 67, + 0x7FD: 84, + 0x816: 84, + 0x817: 84, + 0x818: 84, + 0x819: 84, + 0x81B: 84, + 0x81C: 84, + 0x81D: 84, + 0x81E: 84, + 0x81F: 84, + 0x820: 84, + 0x821: 84, + 0x822: 84, + 0x823: 84, + 0x825: 84, + 0x826: 84, + 0x827: 84, + 0x829: 84, + 0x82A: 84, + 0x82B: 84, + 0x82C: 84, + 0x82D: 84, + 0x840: 82, + 0x841: 68, + 0x842: 68, + 0x843: 68, + 0x844: 68, + 0x845: 68, + 0x846: 82, + 0x847: 82, + 0x848: 68, + 0x849: 82, + 0x84A: 68, + 0x84B: 68, + 0x84C: 68, + 0x84D: 68, + 0x84E: 68, + 0x84F: 68, + 0x850: 68, + 0x851: 68, + 0x852: 68, + 0x853: 68, + 0x854: 82, + 0x855: 68, + 0x856: 82, + 0x857: 82, + 0x858: 82, + 0x859: 84, + 0x85A: 84, + 0x85B: 84, + 0x860: 68, + 0x862: 68, + 0x863: 68, + 0x864: 68, + 0x865: 68, + 0x867: 82, + 0x868: 68, + 0x869: 82, + 0x86A: 82, + 0x870: 82, + 0x871: 82, + 0x872: 82, + 0x873: 82, + 0x874: 82, + 0x875: 82, + 0x876: 82, + 0x877: 82, + 0x878: 82, + 0x879: 82, + 0x87A: 82, + 0x87B: 82, + 0x87C: 82, + 0x87D: 82, + 0x87E: 82, + 0x87F: 82, + 0x880: 82, + 0x881: 82, + 0x882: 82, + 0x883: 67, + 0x884: 67, + 0x885: 67, + 0x886: 68, + 0x889: 68, + 0x88A: 68, + 0x88B: 68, + 0x88C: 68, + 0x88D: 68, + 0x88E: 82, + 0x897: 84, + 0x898: 84, + 0x899: 84, + 0x89A: 84, + 0x89B: 84, + 0x89C: 84, + 0x89D: 84, + 0x89E: 84, + 0x89F: 84, + 0x8A0: 68, + 0x8A1: 68, + 0x8A2: 68, + 0x8A3: 68, + 0x8A4: 68, + 0x8A5: 68, + 0x8A6: 68, + 0x8A7: 68, + 0x8A8: 68, + 0x8A9: 68, + 0x8AA: 82, + 0x8AB: 82, + 0x8AC: 82, + 0x8AE: 82, + 0x8AF: 68, + 0x8B0: 68, + 0x8B1: 82, + 0x8B2: 82, + 0x8B3: 68, + 0x8B4: 68, + 0x8B5: 68, + 0x8B6: 68, + 0x8B7: 68, + 0x8B8: 68, + 0x8B9: 82, + 0x8BA: 68, + 0x8BB: 68, + 0x8BC: 68, + 0x8BD: 68, + 0x8BE: 68, + 0x8BF: 68, + 0x8C0: 68, + 0x8C1: 68, + 0x8C2: 68, + 0x8C3: 68, + 0x8C4: 68, + 0x8C5: 68, + 0x8C6: 68, + 0x8C7: 68, + 0x8C8: 68, + 0x8CA: 84, + 0x8CB: 84, + 0x8CC: 84, + 0x8CD: 84, + 0x8CE: 84, + 0x8CF: 84, + 0x8D0: 84, + 0x8D1: 84, + 0x8D2: 84, + 0x8D3: 84, + 0x8D4: 84, + 0x8D5: 84, + 0x8D6: 84, + 0x8D7: 84, + 0x8D8: 84, + 0x8D9: 84, + 0x8DA: 84, + 0x8DB: 84, + 0x8DC: 84, + 0x8DD: 84, + 0x8DE: 84, + 0x8DF: 84, + 0x8E0: 84, + 0x8E1: 84, + 0x8E3: 84, + 0x8E4: 84, + 0x8E5: 84, + 0x8E6: 84, + 0x8E7: 84, + 0x8E8: 84, + 0x8E9: 84, + 0x8EA: 84, + 0x8EB: 84, + 0x8EC: 84, + 0x8ED: 84, + 0x8EE: 84, + 0x8EF: 84, + 0x8F0: 84, + 0x8F1: 84, + 0x8F2: 84, + 0x8F3: 84, + 0x8F4: 84, + 0x8F5: 84, + 0x8F6: 84, + 0x8F7: 84, + 0x8F8: 84, + 0x8F9: 84, + 0x8FA: 84, + 0x8FB: 84, + 0x8FC: 84, + 0x8FD: 84, + 0x8FE: 84, + 0x8FF: 84, + 0x900: 84, + 0x901: 84, + 0x902: 84, + 0x93A: 84, + 0x93C: 84, + 0x941: 84, + 0x942: 84, + 0x943: 84, + 0x944: 84, + 0x945: 84, + 0x946: 84, + 0x947: 84, + 0x948: 84, + 0x94D: 84, + 0x951: 84, + 0x952: 84, + 0x953: 84, + 0x954: 84, + 0x955: 84, + 0x956: 84, + 0x957: 84, + 0x962: 84, + 0x963: 84, + 0x981: 84, + 0x9BC: 84, + 0x9C1: 84, + 0x9C2: 84, + 0x9C3: 84, + 0x9C4: 84, + 0x9CD: 84, + 0x9E2: 84, + 0x9E3: 84, + 0x9FE: 84, + 0xA01: 84, + 0xA02: 84, + 0xA3C: 84, + 0xA41: 84, + 0xA42: 84, + 0xA47: 84, + 0xA48: 84, + 0xA4B: 84, + 0xA4C: 84, + 0xA4D: 84, + 0xA51: 84, + 0xA70: 84, + 0xA71: 84, + 0xA75: 84, + 0xA81: 84, + 0xA82: 84, + 0xABC: 84, + 0xAC1: 84, + 0xAC2: 84, + 0xAC3: 84, + 0xAC4: 84, + 0xAC5: 84, + 0xAC7: 84, + 0xAC8: 84, + 0xACD: 84, + 0xAE2: 84, + 0xAE3: 84, + 0xAFA: 84, + 0xAFB: 84, + 0xAFC: 84, + 0xAFD: 84, + 0xAFE: 84, + 0xAFF: 84, + 0xB01: 84, + 0xB3C: 84, + 0xB3F: 84, + 0xB41: 84, + 0xB42: 84, + 0xB43: 84, + 0xB44: 84, + 0xB4D: 84, + 0xB55: 84, + 0xB56: 84, + 0xB62: 84, + 0xB63: 84, + 0xB82: 84, + 0xBC0: 84, + 0xBCD: 84, + 0xC00: 84, + 0xC04: 84, + 0xC3C: 84, + 0xC3E: 84, + 0xC3F: 84, + 0xC40: 84, + 0xC46: 84, + 0xC47: 84, + 0xC48: 84, + 0xC4A: 84, + 0xC4B: 84, + 0xC4C: 84, + 0xC4D: 84, + 0xC55: 84, + 0xC56: 84, + 0xC62: 84, + 0xC63: 84, + 0xC81: 84, + 0xCBC: 84, + 0xCBF: 84, + 0xCC6: 84, + 0xCCC: 84, + 0xCCD: 84, + 0xCE2: 84, + 0xCE3: 84, + 0xD00: 84, + 0xD01: 84, + 0xD3B: 84, + 0xD3C: 84, + 0xD41: 84, + 0xD42: 84, + 0xD43: 84, + 0xD44: 84, + 0xD4D: 84, + 0xD62: 84, + 0xD63: 84, + 0xD81: 84, + 0xDCA: 84, + 0xDD2: 84, + 0xDD3: 84, + 0xDD4: 84, + 0xDD6: 84, + 0xE31: 84, + 0xE34: 84, + 0xE35: 84, + 0xE36: 84, + 0xE37: 84, + 0xE38: 84, + 0xE39: 84, + 0xE3A: 84, + 0xE47: 84, + 0xE48: 84, + 0xE49: 84, + 0xE4A: 84, + 0xE4B: 84, + 0xE4C: 84, + 0xE4D: 84, + 0xE4E: 84, + 0xEB1: 84, + 0xEB4: 84, + 0xEB5: 84, + 0xEB6: 84, + 0xEB7: 84, + 0xEB8: 84, + 0xEB9: 84, + 0xEBA: 84, + 0xEBB: 84, + 0xEBC: 84, + 0xEC8: 84, + 0xEC9: 84, + 0xECA: 84, + 0xECB: 84, + 0xECC: 84, + 0xECD: 84, + 0xECE: 84, + 0xF18: 84, + 0xF19: 84, + 0xF35: 84, + 0xF37: 84, + 0xF39: 84, + 0xF71: 84, + 0xF72: 84, + 0xF73: 84, + 0xF74: 84, + 0xF75: 84, + 0xF76: 84, + 0xF77: 84, + 0xF78: 84, + 0xF79: 84, + 0xF7A: 84, + 0xF7B: 84, + 0xF7C: 84, + 0xF7D: 84, + 0xF7E: 84, + 0xF80: 84, + 0xF81: 84, + 0xF82: 84, + 0xF83: 84, + 0xF84: 84, + 0xF86: 84, + 0xF87: 84, + 0xF8D: 84, + 0xF8E: 84, + 0xF8F: 84, + 0xF90: 84, + 0xF91: 84, + 0xF92: 84, + 0xF93: 84, + 0xF94: 84, + 0xF95: 84, + 0xF96: 84, + 0xF97: 84, + 0xF99: 84, + 0xF9A: 84, + 0xF9B: 84, + 0xF9C: 84, + 0xF9D: 84, + 0xF9E: 84, + 0xF9F: 84, + 0xFA0: 84, + 0xFA1: 84, + 0xFA2: 84, + 0xFA3: 84, + 0xFA4: 84, + 0xFA5: 84, + 0xFA6: 84, + 0xFA7: 84, + 0xFA8: 84, + 0xFA9: 84, + 0xFAA: 84, + 0xFAB: 84, + 0xFAC: 84, + 0xFAD: 84, + 0xFAE: 84, + 0xFAF: 84, + 0xFB0: 84, + 0xFB1: 84, + 0xFB2: 84, + 0xFB3: 84, + 0xFB4: 84, + 0xFB5: 84, + 0xFB6: 84, + 0xFB7: 84, + 0xFB8: 84, + 0xFB9: 84, + 0xFBA: 84, + 0xFBB: 84, + 0xFBC: 84, + 0xFC6: 84, + 0x102D: 84, + 0x102E: 84, + 0x102F: 84, + 0x1030: 84, + 0x1032: 84, + 0x1033: 84, + 0x1034: 84, + 0x1035: 84, + 0x1036: 84, + 0x1037: 84, + 0x1039: 84, + 0x103A: 84, + 0x103D: 84, + 0x103E: 84, + 0x1058: 84, + 0x1059: 84, + 0x105E: 84, + 0x105F: 84, + 0x1060: 84, + 0x1071: 84, + 0x1072: 84, + 0x1073: 84, + 0x1074: 84, + 0x1082: 84, + 0x1085: 84, + 0x1086: 84, + 0x108D: 84, + 0x109D: 84, + 0x135D: 84, + 0x135E: 84, + 0x135F: 84, + 0x1712: 84, + 0x1713: 84, + 0x1714: 84, + 0x1732: 84, + 0x1733: 84, + 0x1752: 84, + 0x1753: 84, + 0x1772: 84, + 0x1773: 84, + 0x17B4: 84, + 0x17B5: 84, + 0x17B7: 84, + 0x17B8: 84, + 0x17B9: 84, + 0x17BA: 84, + 0x17BB: 84, + 0x17BC: 84, + 0x17BD: 84, + 0x17C6: 84, + 0x17C9: 84, + 0x17CA: 84, + 0x17CB: 84, + 0x17CC: 84, + 0x17CD: 84, + 0x17CE: 84, + 0x17CF: 84, + 0x17D0: 84, + 0x17D1: 84, + 0x17D2: 84, + 0x17D3: 84, + 0x17DD: 84, + 0x1807: 68, + 0x180A: 67, + 0x180B: 84, + 0x180C: 84, + 0x180D: 84, + 0x180F: 84, + 0x1820: 68, + 0x1821: 68, + 0x1822: 68, + 0x1823: 68, + 0x1824: 68, + 0x1825: 68, + 0x1826: 68, + 0x1827: 68, + 0x1828: 68, + 0x1829: 68, + 0x182A: 68, + 0x182B: 68, + 0x182C: 68, + 0x182D: 68, + 0x182E: 68, + 0x182F: 68, + 0x1830: 68, + 0x1831: 68, + 0x1832: 68, + 0x1833: 68, + 0x1834: 68, + 0x1835: 68, + 0x1836: 68, + 0x1837: 68, + 0x1838: 68, + 0x1839: 68, + 0x183A: 68, + 0x183B: 68, + 0x183C: 68, + 0x183D: 68, + 0x183E: 68, + 0x183F: 68, + 0x1840: 68, + 0x1841: 68, + 0x1842: 68, + 0x1843: 68, + 0x1844: 68, + 0x1845: 68, + 0x1846: 68, + 0x1847: 68, + 0x1848: 68, + 0x1849: 68, + 0x184A: 68, + 0x184B: 68, + 0x184C: 68, + 0x184D: 68, + 0x184E: 68, + 0x184F: 68, + 0x1850: 68, + 0x1851: 68, + 0x1852: 68, + 0x1853: 68, + 0x1854: 68, + 0x1855: 68, + 0x1856: 68, + 0x1857: 68, + 0x1858: 68, + 0x1859: 68, + 0x185A: 68, + 0x185B: 68, + 0x185C: 68, + 0x185D: 68, + 0x185E: 68, + 0x185F: 68, + 0x1860: 68, + 0x1861: 68, + 0x1862: 68, + 0x1863: 68, + 0x1864: 68, + 0x1865: 68, + 0x1866: 68, + 0x1867: 68, + 0x1868: 68, + 0x1869: 68, + 0x186A: 68, + 0x186B: 68, + 0x186C: 68, + 0x186D: 68, + 0x186E: 68, + 0x186F: 68, + 0x1870: 68, + 0x1871: 68, + 0x1872: 68, + 0x1873: 68, + 0x1874: 68, + 0x1875: 68, + 0x1876: 68, + 0x1877: 68, + 0x1878: 68, + 0x1885: 84, + 0x1886: 84, + 0x1887: 68, + 0x1888: 68, + 0x1889: 68, + 0x188A: 68, + 0x188B: 68, + 0x188C: 68, + 0x188D: 68, + 0x188E: 68, + 0x188F: 68, + 0x1890: 68, + 0x1891: 68, + 0x1892: 68, + 0x1893: 68, + 0x1894: 68, + 0x1895: 68, + 0x1896: 68, + 0x1897: 68, + 0x1898: 68, + 0x1899: 68, + 0x189A: 68, + 0x189B: 68, + 0x189C: 68, + 0x189D: 68, + 0x189E: 68, + 0x189F: 68, + 0x18A0: 68, + 0x18A1: 68, + 0x18A2: 68, + 0x18A3: 68, + 0x18A4: 68, + 0x18A5: 68, + 0x18A6: 68, + 0x18A7: 68, + 0x18A8: 68, + 0x18A9: 84, + 0x18AA: 68, + 0x1920: 84, + 0x1921: 84, + 0x1922: 84, + 0x1927: 84, + 0x1928: 84, + 0x1932: 84, + 0x1939: 84, + 0x193A: 84, + 0x193B: 84, + 0x1A17: 84, + 0x1A18: 84, + 0x1A1B: 84, + 0x1A56: 84, + 0x1A58: 84, + 0x1A59: 84, + 0x1A5A: 84, + 0x1A5B: 84, + 0x1A5C: 84, + 0x1A5D: 84, + 0x1A5E: 84, + 0x1A60: 84, + 0x1A62: 84, + 0x1A65: 84, + 0x1A66: 84, + 0x1A67: 84, + 0x1A68: 84, + 0x1A69: 84, + 0x1A6A: 84, + 0x1A6B: 84, + 0x1A6C: 84, + 0x1A73: 84, + 0x1A74: 84, + 0x1A75: 84, + 0x1A76: 84, + 0x1A77: 84, + 0x1A78: 84, + 0x1A79: 84, + 0x1A7A: 84, + 0x1A7B: 84, + 0x1A7C: 84, + 0x1A7F: 84, + 0x1AB0: 84, + 0x1AB1: 84, + 0x1AB2: 84, + 0x1AB3: 84, + 0x1AB4: 84, + 0x1AB5: 84, + 0x1AB6: 84, + 0x1AB7: 84, + 0x1AB8: 84, + 0x1AB9: 84, + 0x1ABA: 84, + 0x1ABB: 84, + 0x1ABC: 84, + 0x1ABD: 84, + 0x1ABE: 84, + 0x1ABF: 84, + 0x1AC0: 84, + 0x1AC1: 84, + 0x1AC2: 84, + 0x1AC3: 84, + 0x1AC4: 84, + 0x1AC5: 84, + 0x1AC6: 84, + 0x1AC7: 84, + 0x1AC8: 84, + 0x1AC9: 84, + 0x1ACA: 84, + 0x1ACB: 84, + 0x1ACC: 84, + 0x1ACD: 84, + 0x1ACE: 84, + 0x1B00: 84, + 0x1B01: 84, + 0x1B02: 84, + 0x1B03: 84, + 0x1B34: 84, + 0x1B36: 84, + 0x1B37: 84, + 0x1B38: 84, + 0x1B39: 84, + 0x1B3A: 84, + 0x1B3C: 84, + 0x1B42: 84, + 0x1B6B: 84, + 0x1B6C: 84, + 0x1B6D: 84, + 0x1B6E: 84, + 0x1B6F: 84, + 0x1B70: 84, + 0x1B71: 84, + 0x1B72: 84, + 0x1B73: 84, + 0x1B80: 84, + 0x1B81: 84, + 0x1BA2: 84, + 0x1BA3: 84, + 0x1BA4: 84, + 0x1BA5: 84, + 0x1BA8: 84, + 0x1BA9: 84, + 0x1BAB: 84, + 0x1BAC: 84, + 0x1BAD: 84, + 0x1BE6: 84, + 0x1BE8: 84, + 0x1BE9: 84, + 0x1BED: 84, + 0x1BEF: 84, + 0x1BF0: 84, + 0x1BF1: 84, + 0x1C2C: 84, + 0x1C2D: 84, + 0x1C2E: 84, + 0x1C2F: 84, + 0x1C30: 84, + 0x1C31: 84, + 0x1C32: 84, + 0x1C33: 84, + 0x1C36: 84, + 0x1C37: 84, + 0x1CD0: 84, + 0x1CD1: 84, + 0x1CD2: 84, + 0x1CD4: 84, + 0x1CD5: 84, + 0x1CD6: 84, + 0x1CD7: 84, + 0x1CD8: 84, + 0x1CD9: 84, + 0x1CDA: 84, + 0x1CDB: 84, + 0x1CDC: 84, + 0x1CDD: 84, + 0x1CDE: 84, + 0x1CDF: 84, + 0x1CE0: 84, + 0x1CE2: 84, + 0x1CE3: 84, + 0x1CE4: 84, + 0x1CE5: 84, + 0x1CE6: 84, + 0x1CE7: 84, + 0x1CE8: 84, + 0x1CED: 84, + 0x1CF4: 84, + 0x1CF8: 84, + 0x1CF9: 84, + 0x1DC0: 84, + 0x1DC1: 84, + 0x1DC2: 84, + 0x1DC3: 84, + 0x1DC4: 84, + 0x1DC5: 84, + 0x1DC6: 84, + 0x1DC7: 84, + 0x1DC8: 84, + 0x1DC9: 84, + 0x1DCA: 84, + 0x1DCB: 84, + 0x1DCC: 84, + 0x1DCD: 84, + 0x1DCE: 84, + 0x1DCF: 84, + 0x1DD0: 84, + 0x1DD1: 84, + 0x1DD2: 84, + 0x1DD3: 84, + 0x1DD4: 84, + 0x1DD5: 84, + 0x1DD6: 84, + 0x1DD7: 84, + 0x1DD8: 84, + 0x1DD9: 84, + 0x1DDA: 84, + 0x1DDB: 84, + 0x1DDC: 84, + 0x1DDD: 84, + 0x1DDE: 84, + 0x1DDF: 84, + 0x1DE0: 84, + 0x1DE1: 84, + 0x1DE2: 84, + 0x1DE3: 84, + 0x1DE4: 84, + 0x1DE5: 84, + 0x1DE6: 84, + 0x1DE7: 84, + 0x1DE8: 84, + 0x1DE9: 84, + 0x1DEA: 84, + 0x1DEB: 84, + 0x1DEC: 84, + 0x1DED: 84, + 0x1DEE: 84, + 0x1DEF: 84, + 0x1DF0: 84, + 0x1DF1: 84, + 0x1DF2: 84, + 0x1DF3: 84, + 0x1DF4: 84, + 0x1DF5: 84, + 0x1DF6: 84, + 0x1DF7: 84, + 0x1DF8: 84, + 0x1DF9: 84, + 0x1DFA: 84, + 0x1DFB: 84, + 0x1DFC: 84, + 0x1DFD: 84, + 0x1DFE: 84, + 0x1DFF: 84, + 0x200B: 84, + 0x200D: 67, + 0x200E: 84, + 0x200F: 84, + 0x202A: 84, + 0x202B: 84, + 0x202C: 84, + 0x202D: 84, + 0x202E: 84, + 0x2060: 84, + 0x2061: 84, + 0x2062: 84, + 0x2063: 84, + 0x2064: 84, + 0x206A: 84, + 0x206B: 84, + 0x206C: 84, + 0x206D: 84, + 0x206E: 84, + 0x206F: 84, + 0x20D0: 84, + 0x20D1: 84, + 0x20D2: 84, + 0x20D3: 84, + 0x20D4: 84, + 0x20D5: 84, + 0x20D6: 84, + 0x20D7: 84, + 0x20D8: 84, + 0x20D9: 84, + 0x20DA: 84, + 0x20DB: 84, + 0x20DC: 84, + 0x20DD: 84, + 0x20DE: 84, + 0x20DF: 84, + 0x20E0: 84, + 0x20E1: 84, + 0x20E2: 84, + 0x20E3: 84, + 0x20E4: 84, + 0x20E5: 84, + 0x20E6: 84, + 0x20E7: 84, + 0x20E8: 84, + 0x20E9: 84, + 0x20EA: 84, + 0x20EB: 84, + 0x20EC: 84, + 0x20ED: 84, + 0x20EE: 84, + 0x20EF: 84, + 0x20F0: 84, + 0x2CEF: 84, + 0x2CF0: 84, + 0x2CF1: 84, + 0x2D7F: 84, + 0x2DE0: 84, + 0x2DE1: 84, + 0x2DE2: 84, + 0x2DE3: 84, + 0x2DE4: 84, + 0x2DE5: 84, + 0x2DE6: 84, + 0x2DE7: 84, + 0x2DE8: 84, + 0x2DE9: 84, + 0x2DEA: 84, + 0x2DEB: 84, + 0x2DEC: 84, + 0x2DED: 84, + 0x2DEE: 84, + 0x2DEF: 84, + 0x2DF0: 84, + 0x2DF1: 84, + 0x2DF2: 84, + 0x2DF3: 84, + 0x2DF4: 84, + 0x2DF5: 84, + 0x2DF6: 84, + 0x2DF7: 84, + 0x2DF8: 84, + 0x2DF9: 84, + 0x2DFA: 84, + 0x2DFB: 84, + 0x2DFC: 84, + 0x2DFD: 84, + 0x2DFE: 84, + 0x2DFF: 84, + 0x302A: 84, + 0x302B: 84, + 0x302C: 84, + 0x302D: 84, + 0x3099: 84, + 0x309A: 84, + 0xA66F: 84, + 0xA670: 84, + 0xA671: 84, + 0xA672: 84, + 0xA674: 84, + 0xA675: 84, + 0xA676: 84, + 0xA677: 84, + 0xA678: 84, + 0xA679: 84, + 0xA67A: 84, + 0xA67B: 84, + 0xA67C: 84, + 0xA67D: 84, + 0xA69E: 84, + 0xA69F: 84, + 0xA6F0: 84, + 0xA6F1: 84, + 0xA802: 84, + 0xA806: 84, + 0xA80B: 84, + 0xA825: 84, + 0xA826: 84, + 0xA82C: 84, + 0xA840: 68, + 0xA841: 68, + 0xA842: 68, + 0xA843: 68, + 0xA844: 68, + 0xA845: 68, + 0xA846: 68, + 0xA847: 68, + 0xA848: 68, + 0xA849: 68, + 0xA84A: 68, + 0xA84B: 68, + 0xA84C: 68, + 0xA84D: 68, + 0xA84E: 68, + 0xA84F: 68, + 0xA850: 68, + 0xA851: 68, + 0xA852: 68, + 0xA853: 68, + 0xA854: 68, + 0xA855: 68, + 0xA856: 68, + 0xA857: 68, + 0xA858: 68, + 0xA859: 68, + 0xA85A: 68, + 0xA85B: 68, + 0xA85C: 68, + 0xA85D: 68, + 0xA85E: 68, + 0xA85F: 68, + 0xA860: 68, + 0xA861: 68, + 0xA862: 68, + 0xA863: 68, + 0xA864: 68, + 0xA865: 68, + 0xA866: 68, + 0xA867: 68, + 0xA868: 68, + 0xA869: 68, + 0xA86A: 68, + 0xA86B: 68, + 0xA86C: 68, + 0xA86D: 68, + 0xA86E: 68, + 0xA86F: 68, + 0xA870: 68, + 0xA871: 68, + 0xA872: 76, + 0xA8C4: 84, + 0xA8C5: 84, + 0xA8E0: 84, + 0xA8E1: 84, + 0xA8E2: 84, + 0xA8E3: 84, + 0xA8E4: 84, + 0xA8E5: 84, + 0xA8E6: 84, + 0xA8E7: 84, + 0xA8E8: 84, + 0xA8E9: 84, + 0xA8EA: 84, + 0xA8EB: 84, + 0xA8EC: 84, + 0xA8ED: 84, + 0xA8EE: 84, + 0xA8EF: 84, + 0xA8F0: 84, + 0xA8F1: 84, + 0xA8FF: 84, + 0xA926: 84, + 0xA927: 84, + 0xA928: 84, + 0xA929: 84, + 0xA92A: 84, + 0xA92B: 84, + 0xA92C: 84, + 0xA92D: 84, + 0xA947: 84, + 0xA948: 84, + 0xA949: 84, + 0xA94A: 84, + 0xA94B: 84, + 0xA94C: 84, + 0xA94D: 84, + 0xA94E: 84, + 0xA94F: 84, + 0xA950: 84, + 0xA951: 84, + 0xA980: 84, + 0xA981: 84, + 0xA982: 84, + 0xA9B3: 84, + 0xA9B6: 84, + 0xA9B7: 84, + 0xA9B8: 84, + 0xA9B9: 84, + 0xA9BC: 84, + 0xA9BD: 84, + 0xA9E5: 84, + 0xAA29: 84, + 0xAA2A: 84, + 0xAA2B: 84, + 0xAA2C: 84, + 0xAA2D: 84, + 0xAA2E: 84, + 0xAA31: 84, + 0xAA32: 84, + 0xAA35: 84, + 0xAA36: 84, + 0xAA43: 84, + 0xAA4C: 84, + 0xAA7C: 84, + 0xAAB0: 84, + 0xAAB2: 84, + 0xAAB3: 84, + 0xAAB4: 84, + 0xAAB7: 84, + 0xAAB8: 84, + 0xAABE: 84, + 0xAABF: 84, + 0xAAC1: 84, + 0xAAEC: 84, + 0xAAED: 84, + 0xAAF6: 84, + 0xABE5: 84, + 0xABE8: 84, + 0xABED: 84, + 0xFB1E: 84, + 0xFE00: 84, + 0xFE01: 84, + 0xFE02: 84, + 0xFE03: 84, + 0xFE04: 84, + 0xFE05: 84, + 0xFE06: 84, + 0xFE07: 84, + 0xFE08: 84, + 0xFE09: 84, + 0xFE0A: 84, + 0xFE0B: 84, + 0xFE0C: 84, + 0xFE0D: 84, + 0xFE0E: 84, + 0xFE0F: 84, + 0xFE20: 84, + 0xFE21: 84, + 0xFE22: 84, + 0xFE23: 84, + 0xFE24: 84, + 0xFE25: 84, + 0xFE26: 84, + 0xFE27: 84, + 0xFE28: 84, + 0xFE29: 84, + 0xFE2A: 84, + 0xFE2B: 84, + 0xFE2C: 84, + 0xFE2D: 84, + 0xFE2E: 84, + 0xFE2F: 84, + 0xFEFF: 84, + 0xFFF9: 84, + 0xFFFA: 84, + 0xFFFB: 84, + 0x101FD: 84, + 0x102E0: 84, + 0x10376: 84, + 0x10377: 84, + 0x10378: 84, + 0x10379: 84, + 0x1037A: 84, + 0x10A01: 84, + 0x10A02: 84, + 0x10A03: 84, + 0x10A05: 84, + 0x10A06: 84, + 0x10A0C: 84, + 0x10A0D: 84, + 0x10A0E: 84, + 0x10A0F: 84, + 0x10A38: 84, + 0x10A39: 84, + 0x10A3A: 84, + 0x10A3F: 84, + 0x10AC0: 68, + 0x10AC1: 68, + 0x10AC2: 68, + 0x10AC3: 68, + 0x10AC4: 68, + 0x10AC5: 82, + 0x10AC7: 82, + 0x10AC9: 82, + 0x10ACA: 82, + 0x10ACD: 76, + 0x10ACE: 82, + 0x10ACF: 82, + 0x10AD0: 82, + 0x10AD1: 82, + 0x10AD2: 82, + 0x10AD3: 68, + 0x10AD4: 68, + 0x10AD5: 68, + 0x10AD6: 68, + 0x10AD7: 76, + 0x10AD8: 68, + 0x10AD9: 68, + 0x10ADA: 68, + 0x10ADB: 68, + 0x10ADC: 68, + 0x10ADD: 82, + 0x10ADE: 68, + 0x10ADF: 68, + 0x10AE0: 68, + 0x10AE1: 82, + 0x10AE4: 82, + 0x10AE5: 84, + 0x10AE6: 84, + 0x10AEB: 68, + 0x10AEC: 68, + 0x10AED: 68, + 0x10AEE: 68, + 0x10AEF: 82, + 0x10B80: 68, + 0x10B81: 82, + 0x10B82: 68, + 0x10B83: 82, + 0x10B84: 82, + 0x10B85: 82, + 0x10B86: 68, + 0x10B87: 68, + 0x10B88: 68, + 0x10B89: 82, + 0x10B8A: 68, + 0x10B8B: 68, + 0x10B8C: 82, + 0x10B8D: 68, + 0x10B8E: 82, + 0x10B8F: 82, + 0x10B90: 68, + 0x10B91: 82, + 0x10BA9: 82, + 0x10BAA: 82, + 0x10BAB: 82, + 0x10BAC: 82, + 0x10BAD: 68, + 0x10BAE: 68, + 0x10D00: 76, + 0x10D01: 68, + 0x10D02: 68, + 0x10D03: 68, + 0x10D04: 68, + 0x10D05: 68, + 0x10D06: 68, + 0x10D07: 68, + 0x10D08: 68, + 0x10D09: 68, + 0x10D0A: 68, + 0x10D0B: 68, + 0x10D0C: 68, + 0x10D0D: 68, + 0x10D0E: 68, + 0x10D0F: 68, + 0x10D10: 68, + 0x10D11: 68, + 0x10D12: 68, + 0x10D13: 68, + 0x10D14: 68, + 0x10D15: 68, + 0x10D16: 68, + 0x10D17: 68, + 0x10D18: 68, + 0x10D19: 68, + 0x10D1A: 68, + 0x10D1B: 68, + 0x10D1C: 68, + 0x10D1D: 68, + 0x10D1E: 68, + 0x10D1F: 68, + 0x10D20: 68, + 0x10D21: 68, + 0x10D22: 82, + 0x10D23: 68, + 0x10D24: 84, + 0x10D25: 84, + 0x10D26: 84, + 0x10D27: 84, + 0x10D69: 84, + 0x10D6A: 84, + 0x10D6B: 84, + 0x10D6C: 84, + 0x10D6D: 84, + 0x10EAB: 84, + 0x10EAC: 84, + 0x10EC2: 82, + 0x10EC3: 68, + 0x10EC4: 68, + 0x10EFC: 84, + 0x10EFD: 84, + 0x10EFE: 84, + 0x10EFF: 84, + 0x10F30: 68, + 0x10F31: 68, + 0x10F32: 68, + 0x10F33: 82, + 0x10F34: 68, + 0x10F35: 68, + 0x10F36: 68, + 0x10F37: 68, + 0x10F38: 68, + 0x10F39: 68, + 0x10F3A: 68, + 0x10F3B: 68, + 0x10F3C: 68, + 0x10F3D: 68, + 0x10F3E: 68, + 0x10F3F: 68, + 0x10F40: 68, + 0x10F41: 68, + 0x10F42: 68, + 0x10F43: 68, + 0x10F44: 68, + 0x10F46: 84, + 0x10F47: 84, + 0x10F48: 84, + 0x10F49: 84, + 0x10F4A: 84, + 0x10F4B: 84, + 0x10F4C: 84, + 0x10F4D: 84, + 0x10F4E: 84, + 0x10F4F: 84, + 0x10F50: 84, + 0x10F51: 68, + 0x10F52: 68, + 0x10F53: 68, + 0x10F54: 82, + 0x10F70: 68, + 0x10F71: 68, + 0x10F72: 68, + 0x10F73: 68, + 0x10F74: 82, + 0x10F75: 82, + 0x10F76: 68, + 0x10F77: 68, + 0x10F78: 68, + 0x10F79: 68, + 0x10F7A: 68, + 0x10F7B: 68, + 0x10F7C: 68, + 0x10F7D: 68, + 0x10F7E: 68, + 0x10F7F: 68, + 0x10F80: 68, + 0x10F81: 68, + 0x10F82: 84, + 0x10F83: 84, + 0x10F84: 84, + 0x10F85: 84, + 0x10FB0: 68, + 0x10FB2: 68, + 0x10FB3: 68, + 0x10FB4: 82, + 0x10FB5: 82, + 0x10FB6: 82, + 0x10FB8: 68, + 0x10FB9: 82, + 0x10FBA: 82, + 0x10FBB: 68, + 0x10FBC: 68, + 0x10FBD: 82, + 0x10FBE: 68, + 0x10FBF: 68, + 0x10FC1: 68, + 0x10FC2: 82, + 0x10FC3: 82, + 0x10FC4: 68, + 0x10FC9: 82, + 0x10FCA: 68, + 0x10FCB: 76, + 0x11001: 84, + 0x11038: 84, + 0x11039: 84, + 0x1103A: 84, + 0x1103B: 84, + 0x1103C: 84, + 0x1103D: 84, + 0x1103E: 84, + 0x1103F: 84, + 0x11040: 84, + 0x11041: 84, + 0x11042: 84, + 0x11043: 84, + 0x11044: 84, + 0x11045: 84, + 0x11046: 84, + 0x11070: 84, + 0x11073: 84, + 0x11074: 84, + 0x1107F: 84, + 0x11080: 84, + 0x11081: 84, + 0x110B3: 84, + 0x110B4: 84, + 0x110B5: 84, + 0x110B6: 84, + 0x110B9: 84, + 0x110BA: 84, + 0x110C2: 84, + 0x11100: 84, + 0x11101: 84, + 0x11102: 84, + 0x11127: 84, + 0x11128: 84, + 0x11129: 84, + 0x1112A: 84, + 0x1112B: 84, + 0x1112D: 84, + 0x1112E: 84, + 0x1112F: 84, + 0x11130: 84, + 0x11131: 84, + 0x11132: 84, + 0x11133: 84, + 0x11134: 84, + 0x11173: 84, + 0x11180: 84, + 0x11181: 84, + 0x111B6: 84, + 0x111B7: 84, + 0x111B8: 84, + 0x111B9: 84, + 0x111BA: 84, + 0x111BB: 84, + 0x111BC: 84, + 0x111BD: 84, + 0x111BE: 84, + 0x111C9: 84, + 0x111CA: 84, + 0x111CB: 84, + 0x111CC: 84, + 0x111CF: 84, + 0x1122F: 84, + 0x11230: 84, + 0x11231: 84, + 0x11234: 84, + 0x11236: 84, + 0x11237: 84, + 0x1123E: 84, + 0x11241: 84, + 0x112DF: 84, + 0x112E3: 84, + 0x112E4: 84, + 0x112E5: 84, + 0x112E6: 84, + 0x112E7: 84, + 0x112E8: 84, + 0x112E9: 84, + 0x112EA: 84, + 0x11300: 84, + 0x11301: 84, + 0x1133B: 84, + 0x1133C: 84, + 0x11340: 84, + 0x11366: 84, + 0x11367: 84, + 0x11368: 84, + 0x11369: 84, + 0x1136A: 84, + 0x1136B: 84, + 0x1136C: 84, + 0x11370: 84, + 0x11371: 84, + 0x11372: 84, + 0x11373: 84, + 0x11374: 84, + 0x113BB: 84, + 0x113BC: 84, + 0x113BD: 84, + 0x113BE: 84, + 0x113BF: 84, + 0x113C0: 84, + 0x113CE: 84, + 0x113D0: 84, + 0x113D2: 84, + 0x113E1: 84, + 0x113E2: 84, + 0x11438: 84, + 0x11439: 84, + 0x1143A: 84, + 0x1143B: 84, + 0x1143C: 84, + 0x1143D: 84, + 0x1143E: 84, + 0x1143F: 84, + 0x11442: 84, + 0x11443: 84, + 0x11444: 84, + 0x11446: 84, + 0x1145E: 84, + 0x114B3: 84, + 0x114B4: 84, + 0x114B5: 84, + 0x114B6: 84, + 0x114B7: 84, + 0x114B8: 84, + 0x114BA: 84, + 0x114BF: 84, + 0x114C0: 84, + 0x114C2: 84, + 0x114C3: 84, + 0x115B2: 84, + 0x115B3: 84, + 0x115B4: 84, + 0x115B5: 84, + 0x115BC: 84, + 0x115BD: 84, + 0x115BF: 84, + 0x115C0: 84, + 0x115DC: 84, + 0x115DD: 84, + 0x11633: 84, + 0x11634: 84, + 0x11635: 84, + 0x11636: 84, + 0x11637: 84, + 0x11638: 84, + 0x11639: 84, + 0x1163A: 84, + 0x1163D: 84, + 0x1163F: 84, + 0x11640: 84, + 0x116AB: 84, + 0x116AD: 84, + 0x116B0: 84, + 0x116B1: 84, + 0x116B2: 84, + 0x116B3: 84, + 0x116B4: 84, + 0x116B5: 84, + 0x116B7: 84, + 0x1171D: 84, + 0x1171F: 84, + 0x11722: 84, + 0x11723: 84, + 0x11724: 84, + 0x11725: 84, + 0x11727: 84, + 0x11728: 84, + 0x11729: 84, + 0x1172A: 84, + 0x1172B: 84, + 0x1182F: 84, + 0x11830: 84, + 0x11831: 84, + 0x11832: 84, + 0x11833: 84, + 0x11834: 84, + 0x11835: 84, + 0x11836: 84, + 0x11837: 84, + 0x11839: 84, + 0x1183A: 84, + 0x1193B: 84, + 0x1193C: 84, + 0x1193E: 84, + 0x11943: 84, + 0x119D4: 84, + 0x119D5: 84, + 0x119D6: 84, + 0x119D7: 84, + 0x119DA: 84, + 0x119DB: 84, + 0x119E0: 84, + 0x11A01: 84, + 0x11A02: 84, + 0x11A03: 84, + 0x11A04: 84, + 0x11A05: 84, + 0x11A06: 84, + 0x11A07: 84, + 0x11A08: 84, + 0x11A09: 84, + 0x11A0A: 84, + 0x11A33: 84, + 0x11A34: 84, + 0x11A35: 84, + 0x11A36: 84, + 0x11A37: 84, + 0x11A38: 84, + 0x11A3B: 84, + 0x11A3C: 84, + 0x11A3D: 84, + 0x11A3E: 84, + 0x11A47: 84, + 0x11A51: 84, + 0x11A52: 84, + 0x11A53: 84, + 0x11A54: 84, + 0x11A55: 84, + 0x11A56: 84, + 0x11A59: 84, + 0x11A5A: 84, + 0x11A5B: 84, + 0x11A8A: 84, + 0x11A8B: 84, + 0x11A8C: 84, + 0x11A8D: 84, + 0x11A8E: 84, + 0x11A8F: 84, + 0x11A90: 84, + 0x11A91: 84, + 0x11A92: 84, + 0x11A93: 84, + 0x11A94: 84, + 0x11A95: 84, + 0x11A96: 84, + 0x11A98: 84, + 0x11A99: 84, + 0x11C30: 84, + 0x11C31: 84, + 0x11C32: 84, + 0x11C33: 84, + 0x11C34: 84, + 0x11C35: 84, + 0x11C36: 84, + 0x11C38: 84, + 0x11C39: 84, + 0x11C3A: 84, + 0x11C3B: 84, + 0x11C3C: 84, + 0x11C3D: 84, + 0x11C3F: 84, + 0x11C92: 84, + 0x11C93: 84, + 0x11C94: 84, + 0x11C95: 84, + 0x11C96: 84, + 0x11C97: 84, + 0x11C98: 84, + 0x11C99: 84, + 0x11C9A: 84, + 0x11C9B: 84, + 0x11C9C: 84, + 0x11C9D: 84, + 0x11C9E: 84, + 0x11C9F: 84, + 0x11CA0: 84, + 0x11CA1: 84, + 0x11CA2: 84, + 0x11CA3: 84, + 0x11CA4: 84, + 0x11CA5: 84, + 0x11CA6: 84, + 0x11CA7: 84, + 0x11CAA: 84, + 0x11CAB: 84, + 0x11CAC: 84, + 0x11CAD: 84, + 0x11CAE: 84, + 0x11CAF: 84, + 0x11CB0: 84, + 0x11CB2: 84, + 0x11CB3: 84, + 0x11CB5: 84, + 0x11CB6: 84, + 0x11D31: 84, + 0x11D32: 84, + 0x11D33: 84, + 0x11D34: 84, + 0x11D35: 84, + 0x11D36: 84, + 0x11D3A: 84, + 0x11D3C: 84, + 0x11D3D: 84, + 0x11D3F: 84, + 0x11D40: 84, + 0x11D41: 84, + 0x11D42: 84, + 0x11D43: 84, + 0x11D44: 84, + 0x11D45: 84, + 0x11D47: 84, + 0x11D90: 84, + 0x11D91: 84, + 0x11D95: 84, + 0x11D97: 84, + 0x11EF3: 84, + 0x11EF4: 84, + 0x11F00: 84, + 0x11F01: 84, + 0x11F36: 84, + 0x11F37: 84, + 0x11F38: 84, + 0x11F39: 84, + 0x11F3A: 84, + 0x11F40: 84, + 0x11F42: 84, + 0x11F5A: 84, + 0x13430: 84, + 0x13431: 84, + 0x13432: 84, + 0x13433: 84, + 0x13434: 84, + 0x13435: 84, + 0x13436: 84, + 0x13437: 84, + 0x13438: 84, + 0x13439: 84, + 0x1343A: 84, + 0x1343B: 84, + 0x1343C: 84, + 0x1343D: 84, + 0x1343E: 84, + 0x1343F: 84, + 0x13440: 84, + 0x13447: 84, + 0x13448: 84, + 0x13449: 84, + 0x1344A: 84, + 0x1344B: 84, + 0x1344C: 84, + 0x1344D: 84, + 0x1344E: 84, + 0x1344F: 84, + 0x13450: 84, + 0x13451: 84, + 0x13452: 84, + 0x13453: 84, + 0x13454: 84, + 0x13455: 84, + 0x1611E: 84, + 0x1611F: 84, + 0x16120: 84, + 0x16121: 84, + 0x16122: 84, + 0x16123: 84, + 0x16124: 84, + 0x16125: 84, + 0x16126: 84, + 0x16127: 84, + 0x16128: 84, + 0x16129: 84, + 0x1612D: 84, + 0x1612E: 84, + 0x1612F: 84, + 0x16AF0: 84, + 0x16AF1: 84, + 0x16AF2: 84, + 0x16AF3: 84, + 0x16AF4: 84, + 0x16B30: 84, + 0x16B31: 84, + 0x16B32: 84, + 0x16B33: 84, + 0x16B34: 84, + 0x16B35: 84, + 0x16B36: 84, + 0x16F4F: 84, + 0x16F8F: 84, + 0x16F90: 84, + 0x16F91: 84, + 0x16F92: 84, + 0x16FE4: 84, + 0x1BC9D: 84, + 0x1BC9E: 84, + 0x1BCA0: 84, + 0x1BCA1: 84, + 0x1BCA2: 84, + 0x1BCA3: 84, + 0x1CF00: 84, + 0x1CF01: 84, + 0x1CF02: 84, + 0x1CF03: 84, + 0x1CF04: 84, + 0x1CF05: 84, + 0x1CF06: 84, + 0x1CF07: 84, + 0x1CF08: 84, + 0x1CF09: 84, + 0x1CF0A: 84, + 0x1CF0B: 84, + 0x1CF0C: 84, + 0x1CF0D: 84, + 0x1CF0E: 84, + 0x1CF0F: 84, + 0x1CF10: 84, + 0x1CF11: 84, + 0x1CF12: 84, + 0x1CF13: 84, + 0x1CF14: 84, + 0x1CF15: 84, + 0x1CF16: 84, + 0x1CF17: 84, + 0x1CF18: 84, + 0x1CF19: 84, + 0x1CF1A: 84, + 0x1CF1B: 84, + 0x1CF1C: 84, + 0x1CF1D: 84, + 0x1CF1E: 84, + 0x1CF1F: 84, + 0x1CF20: 84, + 0x1CF21: 84, + 0x1CF22: 84, + 0x1CF23: 84, + 0x1CF24: 84, + 0x1CF25: 84, + 0x1CF26: 84, + 0x1CF27: 84, + 0x1CF28: 84, + 0x1CF29: 84, + 0x1CF2A: 84, + 0x1CF2B: 84, + 0x1CF2C: 84, + 0x1CF2D: 84, + 0x1CF30: 84, + 0x1CF31: 84, + 0x1CF32: 84, + 0x1CF33: 84, + 0x1CF34: 84, + 0x1CF35: 84, + 0x1CF36: 84, + 0x1CF37: 84, + 0x1CF38: 84, + 0x1CF39: 84, + 0x1CF3A: 84, + 0x1CF3B: 84, + 0x1CF3C: 84, + 0x1CF3D: 84, + 0x1CF3E: 84, + 0x1CF3F: 84, + 0x1CF40: 84, + 0x1CF41: 84, + 0x1CF42: 84, + 0x1CF43: 84, + 0x1CF44: 84, + 0x1CF45: 84, + 0x1CF46: 84, + 0x1D167: 84, + 0x1D168: 84, + 0x1D169: 84, + 0x1D173: 84, + 0x1D174: 84, + 0x1D175: 84, + 0x1D176: 84, + 0x1D177: 84, + 0x1D178: 84, + 0x1D179: 84, + 0x1D17A: 84, + 0x1D17B: 84, + 0x1D17C: 84, + 0x1D17D: 84, + 0x1D17E: 84, + 0x1D17F: 84, + 0x1D180: 84, + 0x1D181: 84, + 0x1D182: 84, + 0x1D185: 84, + 0x1D186: 84, + 0x1D187: 84, + 0x1D188: 84, + 0x1D189: 84, + 0x1D18A: 84, + 0x1D18B: 84, + 0x1D1AA: 84, + 0x1D1AB: 84, + 0x1D1AC: 84, + 0x1D1AD: 84, + 0x1D242: 84, + 0x1D243: 84, + 0x1D244: 84, + 0x1DA00: 84, + 0x1DA01: 84, + 0x1DA02: 84, + 0x1DA03: 84, + 0x1DA04: 84, + 0x1DA05: 84, + 0x1DA06: 84, + 0x1DA07: 84, + 0x1DA08: 84, + 0x1DA09: 84, + 0x1DA0A: 84, + 0x1DA0B: 84, + 0x1DA0C: 84, + 0x1DA0D: 84, + 0x1DA0E: 84, + 0x1DA0F: 84, + 0x1DA10: 84, + 0x1DA11: 84, + 0x1DA12: 84, + 0x1DA13: 84, + 0x1DA14: 84, + 0x1DA15: 84, + 0x1DA16: 84, + 0x1DA17: 84, + 0x1DA18: 84, + 0x1DA19: 84, + 0x1DA1A: 84, + 0x1DA1B: 84, + 0x1DA1C: 84, + 0x1DA1D: 84, + 0x1DA1E: 84, + 0x1DA1F: 84, + 0x1DA20: 84, + 0x1DA21: 84, + 0x1DA22: 84, + 0x1DA23: 84, + 0x1DA24: 84, + 0x1DA25: 84, + 0x1DA26: 84, + 0x1DA27: 84, + 0x1DA28: 84, + 0x1DA29: 84, + 0x1DA2A: 84, + 0x1DA2B: 84, + 0x1DA2C: 84, + 0x1DA2D: 84, + 0x1DA2E: 84, + 0x1DA2F: 84, + 0x1DA30: 84, + 0x1DA31: 84, + 0x1DA32: 84, + 0x1DA33: 84, + 0x1DA34: 84, + 0x1DA35: 84, + 0x1DA36: 84, + 0x1DA3B: 84, + 0x1DA3C: 84, + 0x1DA3D: 84, + 0x1DA3E: 84, + 0x1DA3F: 84, + 0x1DA40: 84, + 0x1DA41: 84, + 0x1DA42: 84, + 0x1DA43: 84, + 0x1DA44: 84, + 0x1DA45: 84, + 0x1DA46: 84, + 0x1DA47: 84, + 0x1DA48: 84, + 0x1DA49: 84, + 0x1DA4A: 84, + 0x1DA4B: 84, + 0x1DA4C: 84, + 0x1DA4D: 84, + 0x1DA4E: 84, + 0x1DA4F: 84, + 0x1DA50: 84, + 0x1DA51: 84, + 0x1DA52: 84, + 0x1DA53: 84, + 0x1DA54: 84, + 0x1DA55: 84, + 0x1DA56: 84, + 0x1DA57: 84, + 0x1DA58: 84, + 0x1DA59: 84, + 0x1DA5A: 84, + 0x1DA5B: 84, + 0x1DA5C: 84, + 0x1DA5D: 84, + 0x1DA5E: 84, + 0x1DA5F: 84, + 0x1DA60: 84, + 0x1DA61: 84, + 0x1DA62: 84, + 0x1DA63: 84, + 0x1DA64: 84, + 0x1DA65: 84, + 0x1DA66: 84, + 0x1DA67: 84, + 0x1DA68: 84, + 0x1DA69: 84, + 0x1DA6A: 84, + 0x1DA6B: 84, + 0x1DA6C: 84, + 0x1DA75: 84, + 0x1DA84: 84, + 0x1DA9B: 84, + 0x1DA9C: 84, + 0x1DA9D: 84, + 0x1DA9E: 84, + 0x1DA9F: 84, + 0x1DAA1: 84, + 0x1DAA2: 84, + 0x1DAA3: 84, + 0x1DAA4: 84, + 0x1DAA5: 84, + 0x1DAA6: 84, + 0x1DAA7: 84, + 0x1DAA8: 84, + 0x1DAA9: 84, + 0x1DAAA: 84, + 0x1DAAB: 84, + 0x1DAAC: 84, + 0x1DAAD: 84, + 0x1DAAE: 84, + 0x1DAAF: 84, + 0x1E000: 84, + 0x1E001: 84, + 0x1E002: 84, + 0x1E003: 84, + 0x1E004: 84, + 0x1E005: 84, + 0x1E006: 84, + 0x1E008: 84, + 0x1E009: 84, + 0x1E00A: 84, + 0x1E00B: 84, + 0x1E00C: 84, + 0x1E00D: 84, + 0x1E00E: 84, + 0x1E00F: 84, + 0x1E010: 84, + 0x1E011: 84, + 0x1E012: 84, + 0x1E013: 84, + 0x1E014: 84, + 0x1E015: 84, + 0x1E016: 84, + 0x1E017: 84, + 0x1E018: 84, + 0x1E01B: 84, + 0x1E01C: 84, + 0x1E01D: 84, + 0x1E01E: 84, + 0x1E01F: 84, + 0x1E020: 84, + 0x1E021: 84, + 0x1E023: 84, + 0x1E024: 84, + 0x1E026: 84, + 0x1E027: 84, + 0x1E028: 84, + 0x1E029: 84, + 0x1E02A: 84, + 0x1E08F: 84, + 0x1E130: 84, + 0x1E131: 84, + 0x1E132: 84, + 0x1E133: 84, + 0x1E134: 84, + 0x1E135: 84, + 0x1E136: 84, + 0x1E2AE: 84, + 0x1E2EC: 84, + 0x1E2ED: 84, + 0x1E2EE: 84, + 0x1E2EF: 84, + 0x1E4EC: 84, + 0x1E4ED: 84, + 0x1E4EE: 84, + 0x1E4EF: 84, + 0x1E5EE: 84, + 0x1E5EF: 84, + 0x1E8D0: 84, + 0x1E8D1: 84, + 0x1E8D2: 84, + 0x1E8D3: 84, + 0x1E8D4: 84, + 0x1E8D5: 84, + 0x1E8D6: 84, + 0x1E900: 68, + 0x1E901: 68, + 0x1E902: 68, + 0x1E903: 68, + 0x1E904: 68, + 0x1E905: 68, + 0x1E906: 68, + 0x1E907: 68, + 0x1E908: 68, + 0x1E909: 68, + 0x1E90A: 68, + 0x1E90B: 68, + 0x1E90C: 68, + 0x1E90D: 68, + 0x1E90E: 68, + 0x1E90F: 68, + 0x1E910: 68, + 0x1E911: 68, + 0x1E912: 68, + 0x1E913: 68, + 0x1E914: 68, + 0x1E915: 68, + 0x1E916: 68, + 0x1E917: 68, + 0x1E918: 68, + 0x1E919: 68, + 0x1E91A: 68, + 0x1E91B: 68, + 0x1E91C: 68, + 0x1E91D: 68, + 0x1E91E: 68, + 0x1E91F: 68, + 0x1E920: 68, + 0x1E921: 68, + 0x1E922: 68, + 0x1E923: 68, + 0x1E924: 68, + 0x1E925: 68, + 0x1E926: 68, + 0x1E927: 68, + 0x1E928: 68, + 0x1E929: 68, + 0x1E92A: 68, + 0x1E92B: 68, + 0x1E92C: 68, + 0x1E92D: 68, + 0x1E92E: 68, + 0x1E92F: 68, + 0x1E930: 68, + 0x1E931: 68, + 0x1E932: 68, + 0x1E933: 68, + 0x1E934: 68, + 0x1E935: 68, + 0x1E936: 68, + 0x1E937: 68, + 0x1E938: 68, + 0x1E939: 68, + 0x1E93A: 68, + 0x1E93B: 68, + 0x1E93C: 68, + 0x1E93D: 68, + 0x1E93E: 68, + 0x1E93F: 68, + 0x1E940: 68, + 0x1E941: 68, + 0x1E942: 68, + 0x1E943: 68, + 0x1E944: 84, + 0x1E945: 84, + 0x1E946: 84, + 0x1E947: 84, + 0x1E948: 84, + 0x1E949: 84, + 0x1E94A: 84, + 0x1E94B: 84, + 0xE0001: 84, + 0xE0020: 84, + 0xE0021: 84, + 0xE0022: 84, + 0xE0023: 84, + 0xE0024: 84, + 0xE0025: 84, + 0xE0026: 84, + 0xE0027: 84, + 0xE0028: 84, + 0xE0029: 84, + 0xE002A: 84, + 0xE002B: 84, + 0xE002C: 84, + 0xE002D: 84, + 0xE002E: 84, + 0xE002F: 84, + 0xE0030: 84, + 0xE0031: 84, + 0xE0032: 84, + 0xE0033: 84, + 0xE0034: 84, + 0xE0035: 84, + 0xE0036: 84, + 0xE0037: 84, + 0xE0038: 84, + 0xE0039: 84, + 0xE003A: 84, + 0xE003B: 84, + 0xE003C: 84, + 0xE003D: 84, + 0xE003E: 84, + 0xE003F: 84, + 0xE0040: 84, + 0xE0041: 84, + 0xE0042: 84, + 0xE0043: 84, + 0xE0044: 84, + 0xE0045: 84, + 0xE0046: 84, + 0xE0047: 84, + 0xE0048: 84, + 0xE0049: 84, + 0xE004A: 84, + 0xE004B: 84, + 0xE004C: 84, + 0xE004D: 84, + 0xE004E: 84, + 0xE004F: 84, + 0xE0050: 84, + 0xE0051: 84, + 0xE0052: 84, + 0xE0053: 84, + 0xE0054: 84, + 0xE0055: 84, + 0xE0056: 84, + 0xE0057: 84, + 0xE0058: 84, + 0xE0059: 84, + 0xE005A: 84, + 0xE005B: 84, + 0xE005C: 84, + 0xE005D: 84, + 0xE005E: 84, + 0xE005F: 84, + 0xE0060: 84, + 0xE0061: 84, + 0xE0062: 84, + 0xE0063: 84, + 0xE0064: 84, + 0xE0065: 84, + 0xE0066: 84, + 0xE0067: 84, + 0xE0068: 84, + 0xE0069: 84, + 0xE006A: 84, + 0xE006B: 84, + 0xE006C: 84, + 0xE006D: 84, + 0xE006E: 84, + 0xE006F: 84, + 0xE0070: 84, + 0xE0071: 84, + 0xE0072: 84, + 0xE0073: 84, + 0xE0074: 84, + 0xE0075: 84, + 0xE0076: 84, + 0xE0077: 84, + 0xE0078: 84, + 0xE0079: 84, + 0xE007A: 84, + 0xE007B: 84, + 0xE007C: 84, + 0xE007D: 84, + 0xE007E: 84, + 0xE007F: 84, + 0xE0100: 84, + 0xE0101: 84, + 0xE0102: 84, + 0xE0103: 84, + 0xE0104: 84, + 0xE0105: 84, + 0xE0106: 84, + 0xE0107: 84, + 0xE0108: 84, + 0xE0109: 84, + 0xE010A: 84, + 0xE010B: 84, + 0xE010C: 84, + 0xE010D: 84, + 0xE010E: 84, + 0xE010F: 84, + 0xE0110: 84, + 0xE0111: 84, + 0xE0112: 84, + 0xE0113: 84, + 0xE0114: 84, + 0xE0115: 84, + 0xE0116: 84, + 0xE0117: 84, + 0xE0118: 84, + 0xE0119: 84, + 0xE011A: 84, + 0xE011B: 84, + 0xE011C: 84, + 0xE011D: 84, + 0xE011E: 84, + 0xE011F: 84, + 0xE0120: 84, + 0xE0121: 84, + 0xE0122: 84, + 0xE0123: 84, + 0xE0124: 84, + 0xE0125: 84, + 0xE0126: 84, + 0xE0127: 84, + 0xE0128: 84, + 0xE0129: 84, + 0xE012A: 84, + 0xE012B: 84, + 0xE012C: 84, + 0xE012D: 84, + 0xE012E: 84, + 0xE012F: 84, + 0xE0130: 84, + 0xE0131: 84, + 0xE0132: 84, + 0xE0133: 84, + 0xE0134: 84, + 0xE0135: 84, + 0xE0136: 84, + 0xE0137: 84, + 0xE0138: 84, + 0xE0139: 84, + 0xE013A: 84, + 0xE013B: 84, + 0xE013C: 84, + 0xE013D: 84, + 0xE013E: 84, + 0xE013F: 84, + 0xE0140: 84, + 0xE0141: 84, + 0xE0142: 84, + 0xE0143: 84, + 0xE0144: 84, + 0xE0145: 84, + 0xE0146: 84, + 0xE0147: 84, + 0xE0148: 84, + 0xE0149: 84, + 0xE014A: 84, + 0xE014B: 84, + 0xE014C: 84, + 0xE014D: 84, + 0xE014E: 84, + 0xE014F: 84, + 0xE0150: 84, + 0xE0151: 84, + 0xE0152: 84, + 0xE0153: 84, + 0xE0154: 84, + 0xE0155: 84, + 0xE0156: 84, + 0xE0157: 84, + 0xE0158: 84, + 0xE0159: 84, + 0xE015A: 84, + 0xE015B: 84, + 0xE015C: 84, + 0xE015D: 84, + 0xE015E: 84, + 0xE015F: 84, + 0xE0160: 84, + 0xE0161: 84, + 0xE0162: 84, + 0xE0163: 84, + 0xE0164: 84, + 0xE0165: 84, + 0xE0166: 84, + 0xE0167: 84, + 0xE0168: 84, + 0xE0169: 84, + 0xE016A: 84, + 0xE016B: 84, + 0xE016C: 84, + 0xE016D: 84, + 0xE016E: 84, + 0xE016F: 84, + 0xE0170: 84, + 0xE0171: 84, + 0xE0172: 84, + 0xE0173: 84, + 0xE0174: 84, + 0xE0175: 84, + 0xE0176: 84, + 0xE0177: 84, + 0xE0178: 84, + 0xE0179: 84, + 0xE017A: 84, + 0xE017B: 84, + 0xE017C: 84, + 0xE017D: 84, + 0xE017E: 84, + 0xE017F: 84, + 0xE0180: 84, + 0xE0181: 84, + 0xE0182: 84, + 0xE0183: 84, + 0xE0184: 84, + 0xE0185: 84, + 0xE0186: 84, + 0xE0187: 84, + 0xE0188: 84, + 0xE0189: 84, + 0xE018A: 84, + 0xE018B: 84, + 0xE018C: 84, + 0xE018D: 84, + 0xE018E: 84, + 0xE018F: 84, + 0xE0190: 84, + 0xE0191: 84, + 0xE0192: 84, + 0xE0193: 84, + 0xE0194: 84, + 0xE0195: 84, + 0xE0196: 84, + 0xE0197: 84, + 0xE0198: 84, + 0xE0199: 84, + 0xE019A: 84, + 0xE019B: 84, + 0xE019C: 84, + 0xE019D: 84, + 0xE019E: 84, + 0xE019F: 84, + 0xE01A0: 84, + 0xE01A1: 84, + 0xE01A2: 84, + 0xE01A3: 84, + 0xE01A4: 84, + 0xE01A5: 84, + 0xE01A6: 84, + 0xE01A7: 84, + 0xE01A8: 84, + 0xE01A9: 84, + 0xE01AA: 84, + 0xE01AB: 84, + 0xE01AC: 84, + 0xE01AD: 84, + 0xE01AE: 84, + 0xE01AF: 84, + 0xE01B0: 84, + 0xE01B1: 84, + 0xE01B2: 84, + 0xE01B3: 84, + 0xE01B4: 84, + 0xE01B5: 84, + 0xE01B6: 84, + 0xE01B7: 84, + 0xE01B8: 84, + 0xE01B9: 84, + 0xE01BA: 84, + 0xE01BB: 84, + 0xE01BC: 84, + 0xE01BD: 84, + 0xE01BE: 84, + 0xE01BF: 84, + 0xE01C0: 84, + 0xE01C1: 84, + 0xE01C2: 84, + 0xE01C3: 84, + 0xE01C4: 84, + 0xE01C5: 84, + 0xE01C6: 84, + 0xE01C7: 84, + 0xE01C8: 84, + 0xE01C9: 84, + 0xE01CA: 84, + 0xE01CB: 84, + 0xE01CC: 84, + 0xE01CD: 84, + 0xE01CE: 84, + 0xE01CF: 84, + 0xE01D0: 84, + 0xE01D1: 84, + 0xE01D2: 84, + 0xE01D3: 84, + 0xE01D4: 84, + 0xE01D5: 84, + 0xE01D6: 84, + 0xE01D7: 84, + 0xE01D8: 84, + 0xE01D9: 84, + 0xE01DA: 84, + 0xE01DB: 84, + 0xE01DC: 84, + 0xE01DD: 84, + 0xE01DE: 84, + 0xE01DF: 84, + 0xE01E0: 84, + 0xE01E1: 84, + 0xE01E2: 84, + 0xE01E3: 84, + 0xE01E4: 84, + 0xE01E5: 84, + 0xE01E6: 84, + 0xE01E7: 84, + 0xE01E8: 84, + 0xE01E9: 84, + 0xE01EA: 84, + 0xE01EB: 84, + 0xE01EC: 84, + 0xE01ED: 84, + 0xE01EE: 84, + 0xE01EF: 84, +} +codepoint_classes = { + "PVALID": ( + 0x2D0000002E, + 0x300000003A, + 0x610000007B, + 0xDF000000F7, + 0xF800000100, + 0x10100000102, + 0x10300000104, + 0x10500000106, + 0x10700000108, + 0x1090000010A, + 0x10B0000010C, + 0x10D0000010E, + 0x10F00000110, + 0x11100000112, + 0x11300000114, + 0x11500000116, + 0x11700000118, + 0x1190000011A, + 0x11B0000011C, + 0x11D0000011E, + 0x11F00000120, + 0x12100000122, + 0x12300000124, + 0x12500000126, + 0x12700000128, + 0x1290000012A, + 0x12B0000012C, + 0x12D0000012E, + 0x12F00000130, + 0x13100000132, + 0x13500000136, + 0x13700000139, + 0x13A0000013B, + 0x13C0000013D, + 0x13E0000013F, + 0x14200000143, + 0x14400000145, + 0x14600000147, + 0x14800000149, + 0x14B0000014C, + 0x14D0000014E, + 0x14F00000150, + 0x15100000152, + 0x15300000154, + 0x15500000156, + 0x15700000158, + 0x1590000015A, + 0x15B0000015C, + 0x15D0000015E, + 0x15F00000160, + 0x16100000162, + 0x16300000164, + 0x16500000166, + 0x16700000168, + 0x1690000016A, + 0x16B0000016C, + 0x16D0000016E, + 0x16F00000170, + 0x17100000172, + 0x17300000174, + 0x17500000176, + 0x17700000178, + 0x17A0000017B, + 0x17C0000017D, + 0x17E0000017F, + 0x18000000181, + 0x18300000184, + 0x18500000186, + 0x18800000189, + 0x18C0000018E, + 0x19200000193, + 0x19500000196, + 0x1990000019C, + 0x19E0000019F, + 0x1A1000001A2, + 0x1A3000001A4, + 0x1A5000001A6, + 0x1A8000001A9, + 0x1AA000001AC, + 0x1AD000001AE, + 0x1B0000001B1, + 0x1B4000001B5, + 0x1B6000001B7, + 0x1B9000001BC, + 0x1BD000001C4, + 0x1CE000001CF, + 0x1D0000001D1, + 0x1D2000001D3, + 0x1D4000001D5, + 0x1D6000001D7, + 0x1D8000001D9, + 0x1DA000001DB, + 0x1DC000001DE, + 0x1DF000001E0, + 0x1E1000001E2, + 0x1E3000001E4, + 0x1E5000001E6, + 0x1E7000001E8, + 0x1E9000001EA, + 0x1EB000001EC, + 0x1ED000001EE, + 0x1EF000001F1, + 0x1F5000001F6, + 0x1F9000001FA, + 0x1FB000001FC, + 0x1FD000001FE, + 0x1FF00000200, + 0x20100000202, + 0x20300000204, + 0x20500000206, + 0x20700000208, + 0x2090000020A, + 0x20B0000020C, + 0x20D0000020E, + 0x20F00000210, + 0x21100000212, + 0x21300000214, + 0x21500000216, + 0x21700000218, + 0x2190000021A, + 0x21B0000021C, + 0x21D0000021E, + 0x21F00000220, + 0x22100000222, + 0x22300000224, + 0x22500000226, + 0x22700000228, + 0x2290000022A, + 0x22B0000022C, + 0x22D0000022E, + 0x22F00000230, + 0x23100000232, + 0x2330000023A, + 0x23C0000023D, + 0x23F00000241, + 0x24200000243, + 0x24700000248, + 0x2490000024A, + 0x24B0000024C, + 0x24D0000024E, + 0x24F000002B0, + 0x2B9000002C2, + 0x2C6000002D2, + 0x2EC000002ED, + 0x2EE000002EF, + 0x30000000340, + 0x34200000343, + 0x3460000034F, + 0x35000000370, + 0x37100000372, + 0x37300000374, + 0x37700000378, + 0x37B0000037E, + 0x39000000391, + 0x3AC000003CF, + 0x3D7000003D8, + 0x3D9000003DA, + 0x3DB000003DC, + 0x3DD000003DE, + 0x3DF000003E0, + 0x3E1000003E2, + 0x3E3000003E4, + 0x3E5000003E6, + 0x3E7000003E8, + 0x3E9000003EA, + 0x3EB000003EC, + 0x3ED000003EE, + 0x3EF000003F0, + 0x3F3000003F4, + 0x3F8000003F9, + 0x3FB000003FD, + 0x43000000460, + 0x46100000462, + 0x46300000464, + 0x46500000466, + 0x46700000468, + 0x4690000046A, + 0x46B0000046C, + 0x46D0000046E, + 0x46F00000470, + 0x47100000472, + 0x47300000474, + 0x47500000476, + 0x47700000478, + 0x4790000047A, + 0x47B0000047C, + 0x47D0000047E, + 0x47F00000480, + 0x48100000482, + 0x48300000488, + 0x48B0000048C, + 0x48D0000048E, + 0x48F00000490, + 0x49100000492, + 0x49300000494, + 0x49500000496, + 0x49700000498, + 0x4990000049A, + 0x49B0000049C, + 0x49D0000049E, + 0x49F000004A0, + 0x4A1000004A2, + 0x4A3000004A4, + 0x4A5000004A6, + 0x4A7000004A8, + 0x4A9000004AA, + 0x4AB000004AC, + 0x4AD000004AE, + 0x4AF000004B0, + 0x4B1000004B2, + 0x4B3000004B4, + 0x4B5000004B6, + 0x4B7000004B8, + 0x4B9000004BA, + 0x4BB000004BC, + 0x4BD000004BE, + 0x4BF000004C0, + 0x4C2000004C3, + 0x4C4000004C5, + 0x4C6000004C7, + 0x4C8000004C9, + 0x4CA000004CB, + 0x4CC000004CD, + 0x4CE000004D0, + 0x4D1000004D2, + 0x4D3000004D4, + 0x4D5000004D6, + 0x4D7000004D8, + 0x4D9000004DA, + 0x4DB000004DC, + 0x4DD000004DE, + 0x4DF000004E0, + 0x4E1000004E2, + 0x4E3000004E4, + 0x4E5000004E6, + 0x4E7000004E8, + 0x4E9000004EA, + 0x4EB000004EC, + 0x4ED000004EE, + 0x4EF000004F0, + 0x4F1000004F2, + 0x4F3000004F4, + 0x4F5000004F6, + 0x4F7000004F8, + 0x4F9000004FA, + 0x4FB000004FC, + 0x4FD000004FE, + 0x4FF00000500, + 0x50100000502, + 0x50300000504, + 0x50500000506, + 0x50700000508, + 0x5090000050A, + 0x50B0000050C, + 0x50D0000050E, + 0x50F00000510, + 0x51100000512, + 0x51300000514, + 0x51500000516, + 0x51700000518, + 0x5190000051A, + 0x51B0000051C, + 0x51D0000051E, + 0x51F00000520, + 0x52100000522, + 0x52300000524, + 0x52500000526, + 0x52700000528, + 0x5290000052A, + 0x52B0000052C, + 0x52D0000052E, + 0x52F00000530, + 0x5590000055A, + 0x56000000587, + 0x58800000589, + 0x591000005BE, + 0x5BF000005C0, + 0x5C1000005C3, + 0x5C4000005C6, + 0x5C7000005C8, + 0x5D0000005EB, + 0x5EF000005F3, + 0x6100000061B, + 0x62000000640, + 0x64100000660, + 0x66E00000675, + 0x679000006D4, + 0x6D5000006DD, + 0x6DF000006E9, + 0x6EA000006F0, + 0x6FA00000700, + 0x7100000074B, + 0x74D000007B2, + 0x7C0000007F6, + 0x7FD000007FE, + 0x8000000082E, + 0x8400000085C, + 0x8600000086B, + 0x87000000888, + 0x8890000088F, + 0x897000008E2, + 0x8E300000958, + 0x96000000964, + 0x96600000970, + 0x97100000984, + 0x9850000098D, + 0x98F00000991, + 0x993000009A9, + 0x9AA000009B1, + 0x9B2000009B3, + 0x9B6000009BA, + 0x9BC000009C5, + 0x9C7000009C9, + 0x9CB000009CF, + 0x9D7000009D8, + 0x9E0000009E4, + 0x9E6000009F2, + 0x9FC000009FD, + 0x9FE000009FF, + 0xA0100000A04, + 0xA0500000A0B, + 0xA0F00000A11, + 0xA1300000A29, + 0xA2A00000A31, + 0xA3200000A33, + 0xA3500000A36, + 0xA3800000A3A, + 0xA3C00000A3D, + 0xA3E00000A43, + 0xA4700000A49, + 0xA4B00000A4E, + 0xA5100000A52, + 0xA5C00000A5D, + 0xA6600000A76, + 0xA8100000A84, + 0xA8500000A8E, + 0xA8F00000A92, + 0xA9300000AA9, + 0xAAA00000AB1, + 0xAB200000AB4, + 0xAB500000ABA, + 0xABC00000AC6, + 0xAC700000ACA, + 0xACB00000ACE, + 0xAD000000AD1, + 0xAE000000AE4, + 0xAE600000AF0, + 0xAF900000B00, + 0xB0100000B04, + 0xB0500000B0D, + 0xB0F00000B11, + 0xB1300000B29, + 0xB2A00000B31, + 0xB3200000B34, + 0xB3500000B3A, + 0xB3C00000B45, + 0xB4700000B49, + 0xB4B00000B4E, + 0xB5500000B58, + 0xB5F00000B64, + 0xB6600000B70, + 0xB7100000B72, + 0xB8200000B84, + 0xB8500000B8B, + 0xB8E00000B91, + 0xB9200000B96, + 0xB9900000B9B, + 0xB9C00000B9D, + 0xB9E00000BA0, + 0xBA300000BA5, + 0xBA800000BAB, + 0xBAE00000BBA, + 0xBBE00000BC3, + 0xBC600000BC9, + 0xBCA00000BCE, + 0xBD000000BD1, + 0xBD700000BD8, + 0xBE600000BF0, + 0xC0000000C0D, + 0xC0E00000C11, + 0xC1200000C29, + 0xC2A00000C3A, + 0xC3C00000C45, + 0xC4600000C49, + 0xC4A00000C4E, + 0xC5500000C57, + 0xC5800000C5B, + 0xC5D00000C5E, + 0xC6000000C64, + 0xC6600000C70, + 0xC8000000C84, + 0xC8500000C8D, + 0xC8E00000C91, + 0xC9200000CA9, + 0xCAA00000CB4, + 0xCB500000CBA, + 0xCBC00000CC5, + 0xCC600000CC9, + 0xCCA00000CCE, + 0xCD500000CD7, + 0xCDD00000CDF, + 0xCE000000CE4, + 0xCE600000CF0, + 0xCF100000CF4, + 0xD0000000D0D, + 0xD0E00000D11, + 0xD1200000D45, + 0xD4600000D49, + 0xD4A00000D4F, + 0xD5400000D58, + 0xD5F00000D64, + 0xD6600000D70, + 0xD7A00000D80, + 0xD8100000D84, + 0xD8500000D97, + 0xD9A00000DB2, + 0xDB300000DBC, + 0xDBD00000DBE, + 0xDC000000DC7, + 0xDCA00000DCB, + 0xDCF00000DD5, + 0xDD600000DD7, + 0xDD800000DE0, + 0xDE600000DF0, + 0xDF200000DF4, + 0xE0100000E33, + 0xE3400000E3B, + 0xE4000000E4F, + 0xE5000000E5A, + 0xE8100000E83, + 0xE8400000E85, + 0xE8600000E8B, + 0xE8C00000EA4, + 0xEA500000EA6, + 0xEA700000EB3, + 0xEB400000EBE, + 0xEC000000EC5, + 0xEC600000EC7, + 0xEC800000ECF, + 0xED000000EDA, + 0xEDE00000EE0, + 0xF0000000F01, + 0xF0B00000F0C, + 0xF1800000F1A, + 0xF2000000F2A, + 0xF3500000F36, + 0xF3700000F38, + 0xF3900000F3A, + 0xF3E00000F43, + 0xF4400000F48, + 0xF4900000F4D, + 0xF4E00000F52, + 0xF5300000F57, + 0xF5800000F5C, + 0xF5D00000F69, + 0xF6A00000F6D, + 0xF7100000F73, + 0xF7400000F75, + 0xF7A00000F81, + 0xF8200000F85, + 0xF8600000F93, + 0xF9400000F98, + 0xF9900000F9D, + 0xF9E00000FA2, + 0xFA300000FA7, + 0xFA800000FAC, + 0xFAD00000FB9, + 0xFBA00000FBD, + 0xFC600000FC7, + 0x10000000104A, + 0x10500000109E, + 0x10D0000010FB, + 0x10FD00001100, + 0x120000001249, + 0x124A0000124E, + 0x125000001257, + 0x125800001259, + 0x125A0000125E, + 0x126000001289, + 0x128A0000128E, + 0x1290000012B1, + 0x12B2000012B6, + 0x12B8000012BF, + 0x12C0000012C1, + 0x12C2000012C6, + 0x12C8000012D7, + 0x12D800001311, + 0x131200001316, + 0x13180000135B, + 0x135D00001360, + 0x138000001390, + 0x13A0000013F6, + 0x14010000166D, + 0x166F00001680, + 0x16810000169B, + 0x16A0000016EB, + 0x16F1000016F9, + 0x170000001716, + 0x171F00001735, + 0x174000001754, + 0x17600000176D, + 0x176E00001771, + 0x177200001774, + 0x1780000017B4, + 0x17B6000017D4, + 0x17D7000017D8, + 0x17DC000017DE, + 0x17E0000017EA, + 0x18100000181A, + 0x182000001879, + 0x1880000018AB, + 0x18B0000018F6, + 0x19000000191F, + 0x19200000192C, + 0x19300000193C, + 0x19460000196E, + 0x197000001975, + 0x1980000019AC, + 0x19B0000019CA, + 0x19D0000019DA, + 0x1A0000001A1C, + 0x1A2000001A5F, + 0x1A6000001A7D, + 0x1A7F00001A8A, + 0x1A9000001A9A, + 0x1AA700001AA8, + 0x1AB000001ABE, + 0x1ABF00001ACF, + 0x1B0000001B4D, + 0x1B5000001B5A, + 0x1B6B00001B74, + 0x1B8000001BF4, + 0x1C0000001C38, + 0x1C4000001C4A, + 0x1C4D00001C7E, + 0x1C8A00001C8B, + 0x1CD000001CD3, + 0x1CD400001CFB, + 0x1D0000001D2C, + 0x1D2F00001D30, + 0x1D3B00001D3C, + 0x1D4E00001D4F, + 0x1D6B00001D78, + 0x1D7900001D9B, + 0x1DC000001E00, + 0x1E0100001E02, + 0x1E0300001E04, + 0x1E0500001E06, + 0x1E0700001E08, + 0x1E0900001E0A, + 0x1E0B00001E0C, + 0x1E0D00001E0E, + 0x1E0F00001E10, + 0x1E1100001E12, + 0x1E1300001E14, + 0x1E1500001E16, + 0x1E1700001E18, + 0x1E1900001E1A, + 0x1E1B00001E1C, + 0x1E1D00001E1E, + 0x1E1F00001E20, + 0x1E2100001E22, + 0x1E2300001E24, + 0x1E2500001E26, + 0x1E2700001E28, + 0x1E2900001E2A, + 0x1E2B00001E2C, + 0x1E2D00001E2E, + 0x1E2F00001E30, + 0x1E3100001E32, + 0x1E3300001E34, + 0x1E3500001E36, + 0x1E3700001E38, + 0x1E3900001E3A, + 0x1E3B00001E3C, + 0x1E3D00001E3E, + 0x1E3F00001E40, + 0x1E4100001E42, + 0x1E4300001E44, + 0x1E4500001E46, + 0x1E4700001E48, + 0x1E4900001E4A, + 0x1E4B00001E4C, + 0x1E4D00001E4E, + 0x1E4F00001E50, + 0x1E5100001E52, + 0x1E5300001E54, + 0x1E5500001E56, + 0x1E5700001E58, + 0x1E5900001E5A, + 0x1E5B00001E5C, + 0x1E5D00001E5E, + 0x1E5F00001E60, + 0x1E6100001E62, + 0x1E6300001E64, + 0x1E6500001E66, + 0x1E6700001E68, + 0x1E6900001E6A, + 0x1E6B00001E6C, + 0x1E6D00001E6E, + 0x1E6F00001E70, + 0x1E7100001E72, + 0x1E7300001E74, + 0x1E7500001E76, + 0x1E7700001E78, + 0x1E7900001E7A, + 0x1E7B00001E7C, + 0x1E7D00001E7E, + 0x1E7F00001E80, + 0x1E8100001E82, + 0x1E8300001E84, + 0x1E8500001E86, + 0x1E8700001E88, + 0x1E8900001E8A, + 0x1E8B00001E8C, + 0x1E8D00001E8E, + 0x1E8F00001E90, + 0x1E9100001E92, + 0x1E9300001E94, + 0x1E9500001E9A, + 0x1E9C00001E9E, + 0x1E9F00001EA0, + 0x1EA100001EA2, + 0x1EA300001EA4, + 0x1EA500001EA6, + 0x1EA700001EA8, + 0x1EA900001EAA, + 0x1EAB00001EAC, + 0x1EAD00001EAE, + 0x1EAF00001EB0, + 0x1EB100001EB2, + 0x1EB300001EB4, + 0x1EB500001EB6, + 0x1EB700001EB8, + 0x1EB900001EBA, + 0x1EBB00001EBC, + 0x1EBD00001EBE, + 0x1EBF00001EC0, + 0x1EC100001EC2, + 0x1EC300001EC4, + 0x1EC500001EC6, + 0x1EC700001EC8, + 0x1EC900001ECA, + 0x1ECB00001ECC, + 0x1ECD00001ECE, + 0x1ECF00001ED0, + 0x1ED100001ED2, + 0x1ED300001ED4, + 0x1ED500001ED6, + 0x1ED700001ED8, + 0x1ED900001EDA, + 0x1EDB00001EDC, + 0x1EDD00001EDE, + 0x1EDF00001EE0, + 0x1EE100001EE2, + 0x1EE300001EE4, + 0x1EE500001EE6, + 0x1EE700001EE8, + 0x1EE900001EEA, + 0x1EEB00001EEC, + 0x1EED00001EEE, + 0x1EEF00001EF0, + 0x1EF100001EF2, + 0x1EF300001EF4, + 0x1EF500001EF6, + 0x1EF700001EF8, + 0x1EF900001EFA, + 0x1EFB00001EFC, + 0x1EFD00001EFE, + 0x1EFF00001F08, + 0x1F1000001F16, + 0x1F2000001F28, + 0x1F3000001F38, + 0x1F4000001F46, + 0x1F5000001F58, + 0x1F6000001F68, + 0x1F7000001F71, + 0x1F7200001F73, + 0x1F7400001F75, + 0x1F7600001F77, + 0x1F7800001F79, + 0x1F7A00001F7B, + 0x1F7C00001F7D, + 0x1FB000001FB2, + 0x1FB600001FB7, + 0x1FC600001FC7, + 0x1FD000001FD3, + 0x1FD600001FD8, + 0x1FE000001FE3, + 0x1FE400001FE8, + 0x1FF600001FF7, + 0x214E0000214F, + 0x218400002185, + 0x2C3000002C60, + 0x2C6100002C62, + 0x2C6500002C67, + 0x2C6800002C69, + 0x2C6A00002C6B, + 0x2C6C00002C6D, + 0x2C7100002C72, + 0x2C7300002C75, + 0x2C7600002C7C, + 0x2C8100002C82, + 0x2C8300002C84, + 0x2C8500002C86, + 0x2C8700002C88, + 0x2C8900002C8A, + 0x2C8B00002C8C, + 0x2C8D00002C8E, + 0x2C8F00002C90, + 0x2C9100002C92, + 0x2C9300002C94, + 0x2C9500002C96, + 0x2C9700002C98, + 0x2C9900002C9A, + 0x2C9B00002C9C, + 0x2C9D00002C9E, + 0x2C9F00002CA0, + 0x2CA100002CA2, + 0x2CA300002CA4, + 0x2CA500002CA6, + 0x2CA700002CA8, + 0x2CA900002CAA, + 0x2CAB00002CAC, + 0x2CAD00002CAE, + 0x2CAF00002CB0, + 0x2CB100002CB2, + 0x2CB300002CB4, + 0x2CB500002CB6, + 0x2CB700002CB8, + 0x2CB900002CBA, + 0x2CBB00002CBC, + 0x2CBD00002CBE, + 0x2CBF00002CC0, + 0x2CC100002CC2, + 0x2CC300002CC4, + 0x2CC500002CC6, + 0x2CC700002CC8, + 0x2CC900002CCA, + 0x2CCB00002CCC, + 0x2CCD00002CCE, + 0x2CCF00002CD0, + 0x2CD100002CD2, + 0x2CD300002CD4, + 0x2CD500002CD6, + 0x2CD700002CD8, + 0x2CD900002CDA, + 0x2CDB00002CDC, + 0x2CDD00002CDE, + 0x2CDF00002CE0, + 0x2CE100002CE2, + 0x2CE300002CE5, + 0x2CEC00002CED, + 0x2CEE00002CF2, + 0x2CF300002CF4, + 0x2D0000002D26, + 0x2D2700002D28, + 0x2D2D00002D2E, + 0x2D3000002D68, + 0x2D7F00002D97, + 0x2DA000002DA7, + 0x2DA800002DAF, + 0x2DB000002DB7, + 0x2DB800002DBF, + 0x2DC000002DC7, + 0x2DC800002DCF, + 0x2DD000002DD7, + 0x2DD800002DDF, + 0x2DE000002E00, + 0x2E2F00002E30, + 0x300500003008, + 0x302A0000302E, + 0x303C0000303D, + 0x304100003097, + 0x30990000309B, + 0x309D0000309F, + 0x30A1000030FB, + 0x30FC000030FF, + 0x310500003130, + 0x31A0000031C0, + 0x31F000003200, + 0x340000004DC0, + 0x4E000000A48D, + 0xA4D00000A4FE, + 0xA5000000A60D, + 0xA6100000A62C, + 0xA6410000A642, + 0xA6430000A644, + 0xA6450000A646, + 0xA6470000A648, + 0xA6490000A64A, + 0xA64B0000A64C, + 0xA64D0000A64E, + 0xA64F0000A650, + 0xA6510000A652, + 0xA6530000A654, + 0xA6550000A656, + 0xA6570000A658, + 0xA6590000A65A, + 0xA65B0000A65C, + 0xA65D0000A65E, + 0xA65F0000A660, + 0xA6610000A662, + 0xA6630000A664, + 0xA6650000A666, + 0xA6670000A668, + 0xA6690000A66A, + 0xA66B0000A66C, + 0xA66D0000A670, + 0xA6740000A67E, + 0xA67F0000A680, + 0xA6810000A682, + 0xA6830000A684, + 0xA6850000A686, + 0xA6870000A688, + 0xA6890000A68A, + 0xA68B0000A68C, + 0xA68D0000A68E, + 0xA68F0000A690, + 0xA6910000A692, + 0xA6930000A694, + 0xA6950000A696, + 0xA6970000A698, + 0xA6990000A69A, + 0xA69B0000A69C, + 0xA69E0000A6E6, + 0xA6F00000A6F2, + 0xA7170000A720, + 0xA7230000A724, + 0xA7250000A726, + 0xA7270000A728, + 0xA7290000A72A, + 0xA72B0000A72C, + 0xA72D0000A72E, + 0xA72F0000A732, + 0xA7330000A734, + 0xA7350000A736, + 0xA7370000A738, + 0xA7390000A73A, + 0xA73B0000A73C, + 0xA73D0000A73E, + 0xA73F0000A740, + 0xA7410000A742, + 0xA7430000A744, + 0xA7450000A746, + 0xA7470000A748, + 0xA7490000A74A, + 0xA74B0000A74C, + 0xA74D0000A74E, + 0xA74F0000A750, + 0xA7510000A752, + 0xA7530000A754, + 0xA7550000A756, + 0xA7570000A758, + 0xA7590000A75A, + 0xA75B0000A75C, + 0xA75D0000A75E, + 0xA75F0000A760, + 0xA7610000A762, + 0xA7630000A764, + 0xA7650000A766, + 0xA7670000A768, + 0xA7690000A76A, + 0xA76B0000A76C, + 0xA76D0000A76E, + 0xA76F0000A770, + 0xA7710000A779, + 0xA77A0000A77B, + 0xA77C0000A77D, + 0xA77F0000A780, + 0xA7810000A782, + 0xA7830000A784, + 0xA7850000A786, + 0xA7870000A789, + 0xA78C0000A78D, + 0xA78E0000A790, + 0xA7910000A792, + 0xA7930000A796, + 0xA7970000A798, + 0xA7990000A79A, + 0xA79B0000A79C, + 0xA79D0000A79E, + 0xA79F0000A7A0, + 0xA7A10000A7A2, + 0xA7A30000A7A4, + 0xA7A50000A7A6, + 0xA7A70000A7A8, + 0xA7A90000A7AA, + 0xA7AF0000A7B0, + 0xA7B50000A7B6, + 0xA7B70000A7B8, + 0xA7B90000A7BA, + 0xA7BB0000A7BC, + 0xA7BD0000A7BE, + 0xA7BF0000A7C0, + 0xA7C10000A7C2, + 0xA7C30000A7C4, + 0xA7C80000A7C9, + 0xA7CA0000A7CB, + 0xA7CD0000A7CE, + 0xA7D10000A7D2, + 0xA7D30000A7D4, + 0xA7D50000A7D6, + 0xA7D70000A7D8, + 0xA7D90000A7DA, + 0xA7DB0000A7DC, + 0xA7F60000A7F8, + 0xA7FA0000A828, + 0xA82C0000A82D, + 0xA8400000A874, + 0xA8800000A8C6, + 0xA8D00000A8DA, + 0xA8E00000A8F8, + 0xA8FB0000A8FC, + 0xA8FD0000A92E, + 0xA9300000A954, + 0xA9800000A9C1, + 0xA9CF0000A9DA, + 0xA9E00000A9FF, + 0xAA000000AA37, + 0xAA400000AA4E, + 0xAA500000AA5A, + 0xAA600000AA77, + 0xAA7A0000AAC3, + 0xAADB0000AADE, + 0xAAE00000AAF0, + 0xAAF20000AAF7, + 0xAB010000AB07, + 0xAB090000AB0F, + 0xAB110000AB17, + 0xAB200000AB27, + 0xAB280000AB2F, + 0xAB300000AB5B, + 0xAB600000AB69, + 0xABC00000ABEB, + 0xABEC0000ABEE, + 0xABF00000ABFA, + 0xAC000000D7A4, + 0xFA0E0000FA10, + 0xFA110000FA12, + 0xFA130000FA15, + 0xFA1F0000FA20, + 0xFA210000FA22, + 0xFA230000FA25, + 0xFA270000FA2A, + 0xFB1E0000FB1F, + 0xFE200000FE30, + 0xFE730000FE74, + 0x100000001000C, + 0x1000D00010027, + 0x100280001003B, + 0x1003C0001003E, + 0x1003F0001004E, + 0x100500001005E, + 0x10080000100FB, + 0x101FD000101FE, + 0x102800001029D, + 0x102A0000102D1, + 0x102E0000102E1, + 0x1030000010320, + 0x1032D00010341, + 0x103420001034A, + 0x103500001037B, + 0x103800001039E, + 0x103A0000103C4, + 0x103C8000103D0, + 0x104280001049E, + 0x104A0000104AA, + 0x104D8000104FC, + 0x1050000010528, + 0x1053000010564, + 0x10597000105A2, + 0x105A3000105B2, + 0x105B3000105BA, + 0x105BB000105BD, + 0x105C0000105F4, + 0x1060000010737, + 0x1074000010756, + 0x1076000010768, + 0x1078000010781, + 0x1080000010806, + 0x1080800010809, + 0x1080A00010836, + 0x1083700010839, + 0x1083C0001083D, + 0x1083F00010856, + 0x1086000010877, + 0x108800001089F, + 0x108E0000108F3, + 0x108F4000108F6, + 0x1090000010916, + 0x109200001093A, + 0x10980000109B8, + 0x109BE000109C0, + 0x10A0000010A04, + 0x10A0500010A07, + 0x10A0C00010A14, + 0x10A1500010A18, + 0x10A1900010A36, + 0x10A3800010A3B, + 0x10A3F00010A40, + 0x10A6000010A7D, + 0x10A8000010A9D, + 0x10AC000010AC8, + 0x10AC900010AE7, + 0x10B0000010B36, + 0x10B4000010B56, + 0x10B6000010B73, + 0x10B8000010B92, + 0x10C0000010C49, + 0x10CC000010CF3, + 0x10D0000010D28, + 0x10D3000010D3A, + 0x10D4000010D50, + 0x10D6900010D6E, + 0x10D6F00010D86, + 0x10E8000010EAA, + 0x10EAB00010EAD, + 0x10EB000010EB2, + 0x10EC200010EC5, + 0x10EFC00010F1D, + 0x10F2700010F28, + 0x10F3000010F51, + 0x10F7000010F86, + 0x10FB000010FC5, + 0x10FE000010FF7, + 0x1100000011047, + 0x1106600011076, + 0x1107F000110BB, + 0x110C2000110C3, + 0x110D0000110E9, + 0x110F0000110FA, + 0x1110000011135, + 0x1113600011140, + 0x1114400011148, + 0x1115000011174, + 0x1117600011177, + 0x11180000111C5, + 0x111C9000111CD, + 0x111CE000111DB, + 0x111DC000111DD, + 0x1120000011212, + 0x1121300011238, + 0x1123E00011242, + 0x1128000011287, + 0x1128800011289, + 0x1128A0001128E, + 0x1128F0001129E, + 0x1129F000112A9, + 0x112B0000112EB, + 0x112F0000112FA, + 0x1130000011304, + 0x113050001130D, + 0x1130F00011311, + 0x1131300011329, + 0x1132A00011331, + 0x1133200011334, + 0x113350001133A, + 0x1133B00011345, + 0x1134700011349, + 0x1134B0001134E, + 0x1135000011351, + 0x1135700011358, + 0x1135D00011364, + 0x113660001136D, + 0x1137000011375, + 0x113800001138A, + 0x1138B0001138C, + 0x1138E0001138F, + 0x11390000113B6, + 0x113B7000113C1, + 0x113C2000113C3, + 0x113C5000113C6, + 0x113C7000113CB, + 0x113CC000113D4, + 0x113E1000113E3, + 0x114000001144B, + 0x114500001145A, + 0x1145E00011462, + 0x11480000114C6, + 0x114C7000114C8, + 0x114D0000114DA, + 0x11580000115B6, + 0x115B8000115C1, + 0x115D8000115DE, + 0x1160000011641, + 0x1164400011645, + 0x116500001165A, + 0x11680000116B9, + 0x116C0000116CA, + 0x116D0000116E4, + 0x117000001171B, + 0x1171D0001172C, + 0x117300001173A, + 0x1174000011747, + 0x118000001183B, + 0x118C0000118EA, + 0x118FF00011907, + 0x119090001190A, + 0x1190C00011914, + 0x1191500011917, + 0x1191800011936, + 0x1193700011939, + 0x1193B00011944, + 0x119500001195A, + 0x119A0000119A8, + 0x119AA000119D8, + 0x119DA000119E2, + 0x119E3000119E5, + 0x11A0000011A3F, + 0x11A4700011A48, + 0x11A5000011A9A, + 0x11A9D00011A9E, + 0x11AB000011AF9, + 0x11BC000011BE1, + 0x11BF000011BFA, + 0x11C0000011C09, + 0x11C0A00011C37, + 0x11C3800011C41, + 0x11C5000011C5A, + 0x11C7200011C90, + 0x11C9200011CA8, + 0x11CA900011CB7, + 0x11D0000011D07, + 0x11D0800011D0A, + 0x11D0B00011D37, + 0x11D3A00011D3B, + 0x11D3C00011D3E, + 0x11D3F00011D48, + 0x11D5000011D5A, + 0x11D6000011D66, + 0x11D6700011D69, + 0x11D6A00011D8F, + 0x11D9000011D92, + 0x11D9300011D99, + 0x11DA000011DAA, + 0x11EE000011EF7, + 0x11F0000011F11, + 0x11F1200011F3B, + 0x11F3E00011F43, + 0x11F5000011F5B, + 0x11FB000011FB1, + 0x120000001239A, + 0x1248000012544, + 0x12F9000012FF1, + 0x1300000013430, + 0x1344000013456, + 0x13460000143FB, + 0x1440000014647, + 0x161000001613A, + 0x1680000016A39, + 0x16A4000016A5F, + 0x16A6000016A6A, + 0x16A7000016ABF, + 0x16AC000016ACA, + 0x16AD000016AEE, + 0x16AF000016AF5, + 0x16B0000016B37, + 0x16B4000016B44, + 0x16B5000016B5A, + 0x16B6300016B78, + 0x16B7D00016B90, + 0x16D4000016D6D, + 0x16D7000016D7A, + 0x16E6000016E80, + 0x16F0000016F4B, + 0x16F4F00016F88, + 0x16F8F00016FA0, + 0x16FE000016FE2, + 0x16FE300016FE5, + 0x16FF000016FF2, + 0x17000000187F8, + 0x1880000018CD6, + 0x18CFF00018D09, + 0x1AFF00001AFF4, + 0x1AFF50001AFFC, + 0x1AFFD0001AFFF, + 0x1B0000001B123, + 0x1B1320001B133, + 0x1B1500001B153, + 0x1B1550001B156, + 0x1B1640001B168, + 0x1B1700001B2FC, + 0x1BC000001BC6B, + 0x1BC700001BC7D, + 0x1BC800001BC89, + 0x1BC900001BC9A, + 0x1BC9D0001BC9F, + 0x1CCF00001CCFA, + 0x1CF000001CF2E, + 0x1CF300001CF47, + 0x1DA000001DA37, + 0x1DA3B0001DA6D, + 0x1DA750001DA76, + 0x1DA840001DA85, + 0x1DA9B0001DAA0, + 0x1DAA10001DAB0, + 0x1DF000001DF1F, + 0x1DF250001DF2B, + 0x1E0000001E007, + 0x1E0080001E019, + 0x1E01B0001E022, + 0x1E0230001E025, + 0x1E0260001E02B, + 0x1E08F0001E090, + 0x1E1000001E12D, + 0x1E1300001E13E, + 0x1E1400001E14A, + 0x1E14E0001E14F, + 0x1E2900001E2AF, + 0x1E2C00001E2FA, + 0x1E4D00001E4FA, + 0x1E5D00001E5FB, + 0x1E7E00001E7E7, + 0x1E7E80001E7EC, + 0x1E7ED0001E7EF, + 0x1E7F00001E7FF, + 0x1E8000001E8C5, + 0x1E8D00001E8D7, + 0x1E9220001E94C, + 0x1E9500001E95A, + 0x200000002A6E0, + 0x2A7000002B73A, + 0x2B7400002B81E, + 0x2B8200002CEA2, + 0x2CEB00002EBE1, + 0x2EBF00002EE5E, + 0x300000003134B, + 0x31350000323B0, + ), + "CONTEXTJ": (0x200C0000200E,), + "CONTEXTO": ( + 0xB7000000B8, + 0x37500000376, + 0x5F3000005F5, + 0x6600000066A, + 0x6F0000006FA, + 0x30FB000030FC, + ), +} diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/idna/intranges.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/idna/intranges.py new file mode 100644 index 000000000..7bfaa8d80 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/idna/intranges.py @@ -0,0 +1,57 @@ +""" +Given a list of integers, made up of (hopefully) a small number of long runs +of consecutive integers, compute a representation of the form +((start1, end1), (start2, end2) ...). Then answer the question "was x present +in the original list?" in time O(log(# runs)). +""" + +import bisect +from typing import List, Tuple + + +def intranges_from_list(list_: List[int]) -> Tuple[int, ...]: + """Represent a list of integers as a sequence of ranges: + ((start_0, end_0), (start_1, end_1), ...), such that the original + integers are exactly those x such that start_i <= x < end_i for some i. + + Ranges are encoded as single integers (start << 32 | end), not as tuples. + """ + + sorted_list = sorted(list_) + ranges = [] + last_write = -1 + for i in range(len(sorted_list)): + if i + 1 < len(sorted_list): + if sorted_list[i] == sorted_list[i + 1] - 1: + continue + current_range = sorted_list[last_write + 1 : i + 1] + ranges.append(_encode_range(current_range[0], current_range[-1] + 1)) + last_write = i + + return tuple(ranges) + + +def _encode_range(start: int, end: int) -> int: + return (start << 32) | end + + +def _decode_range(r: int) -> Tuple[int, int]: + return (r >> 32), (r & ((1 << 32) - 1)) + + +def intranges_contain(int_: int, ranges: Tuple[int, ...]) -> bool: + """Determine if `int_` falls into one of the ranges in `ranges`.""" + tuple_ = _encode_range(int_, 0) + pos = bisect.bisect_left(ranges, tuple_) + # we could be immediately ahead of a tuple (start, end) + # with start < int_ <= end + if pos > 0: + left, right = _decode_range(ranges[pos - 1]) + if left <= int_ < right: + return True + # or we could be immediately behind a tuple (int_, end) + if pos < len(ranges): + left, _ = _decode_range(ranges[pos]) + if left == int_: + return True + return False diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/idna/package_data.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/idna/package_data.py new file mode 100644 index 000000000..7272c8d92 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/idna/package_data.py @@ -0,0 +1 @@ +__version__ = "3.11" diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/idna/py.typed b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/idna/py.typed new file mode 100644 index 000000000..e69de29bb diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/idna/uts46data.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/idna/uts46data.py new file mode 100644 index 000000000..4610b71da --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/idna/uts46data.py @@ -0,0 +1,8841 @@ +# This file is automatically generated by tools/idna-data +# vim: set fileencoding=utf-8 : + +from typing import List, Tuple, Union + +"""IDNA Mapping Table from UTS46.""" + + +__version__ = "16.0.0" + + +def _seg_0() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0x0, "V"), + (0x1, "V"), + (0x2, "V"), + (0x3, "V"), + (0x4, "V"), + (0x5, "V"), + (0x6, "V"), + (0x7, "V"), + (0x8, "V"), + (0x9, "V"), + (0xA, "V"), + (0xB, "V"), + (0xC, "V"), + (0xD, "V"), + (0xE, "V"), + (0xF, "V"), + (0x10, "V"), + (0x11, "V"), + (0x12, "V"), + (0x13, "V"), + (0x14, "V"), + (0x15, "V"), + (0x16, "V"), + (0x17, "V"), + (0x18, "V"), + (0x19, "V"), + (0x1A, "V"), + (0x1B, "V"), + (0x1C, "V"), + (0x1D, "V"), + (0x1E, "V"), + (0x1F, "V"), + (0x20, "V"), + (0x21, "V"), + (0x22, "V"), + (0x23, "V"), + (0x24, "V"), + (0x25, "V"), + (0x26, "V"), + (0x27, "V"), + (0x28, "V"), + (0x29, "V"), + (0x2A, "V"), + (0x2B, "V"), + (0x2C, "V"), + (0x2D, "V"), + (0x2E, "V"), + (0x2F, "V"), + (0x30, "V"), + (0x31, "V"), + (0x32, "V"), + (0x33, "V"), + (0x34, "V"), + (0x35, "V"), + (0x36, "V"), + (0x37, "V"), + (0x38, "V"), + (0x39, "V"), + (0x3A, "V"), + (0x3B, "V"), + (0x3C, "V"), + (0x3D, "V"), + (0x3E, "V"), + (0x3F, "V"), + (0x40, "V"), + (0x41, "M", "a"), + (0x42, "M", "b"), + (0x43, "M", "c"), + (0x44, "M", "d"), + (0x45, "M", "e"), + (0x46, "M", "f"), + (0x47, "M", "g"), + (0x48, "M", "h"), + (0x49, "M", "i"), + (0x4A, "M", "j"), + (0x4B, "M", "k"), + (0x4C, "M", "l"), + (0x4D, "M", "m"), + (0x4E, "M", "n"), + (0x4F, "M", "o"), + (0x50, "M", "p"), + (0x51, "M", "q"), + (0x52, "M", "r"), + (0x53, "M", "s"), + (0x54, "M", "t"), + (0x55, "M", "u"), + (0x56, "M", "v"), + (0x57, "M", "w"), + (0x58, "M", "x"), + (0x59, "M", "y"), + (0x5A, "M", "z"), + (0x5B, "V"), + (0x5C, "V"), + (0x5D, "V"), + (0x5E, "V"), + (0x5F, "V"), + (0x60, "V"), + (0x61, "V"), + (0x62, "V"), + (0x63, "V"), + ] + + +def _seg_1() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0x64, "V"), + (0x65, "V"), + (0x66, "V"), + (0x67, "V"), + (0x68, "V"), + (0x69, "V"), + (0x6A, "V"), + (0x6B, "V"), + (0x6C, "V"), + (0x6D, "V"), + (0x6E, "V"), + (0x6F, "V"), + (0x70, "V"), + (0x71, "V"), + (0x72, "V"), + (0x73, "V"), + (0x74, "V"), + (0x75, "V"), + (0x76, "V"), + (0x77, "V"), + (0x78, "V"), + (0x79, "V"), + (0x7A, "V"), + (0x7B, "V"), + (0x7C, "V"), + (0x7D, "V"), + (0x7E, "V"), + (0x7F, "V"), + (0x80, "X"), + (0x81, "X"), + (0x82, "X"), + (0x83, "X"), + (0x84, "X"), + (0x85, "X"), + (0x86, "X"), + (0x87, "X"), + (0x88, "X"), + (0x89, "X"), + (0x8A, "X"), + (0x8B, "X"), + (0x8C, "X"), + (0x8D, "X"), + (0x8E, "X"), + (0x8F, "X"), + (0x90, "X"), + (0x91, "X"), + (0x92, "X"), + (0x93, "X"), + (0x94, "X"), + (0x95, "X"), + (0x96, "X"), + (0x97, "X"), + (0x98, "X"), + (0x99, "X"), + (0x9A, "X"), + (0x9B, "X"), + (0x9C, "X"), + (0x9D, "X"), + (0x9E, "X"), + (0x9F, "X"), + (0xA0, "M", " "), + (0xA1, "V"), + (0xA2, "V"), + (0xA3, "V"), + (0xA4, "V"), + (0xA5, "V"), + (0xA6, "V"), + (0xA7, "V"), + (0xA8, "M", " ̈"), + (0xA9, "V"), + (0xAA, "M", "a"), + (0xAB, "V"), + (0xAC, "V"), + (0xAD, "I"), + (0xAE, "V"), + (0xAF, "M", " ̄"), + (0xB0, "V"), + (0xB1, "V"), + (0xB2, "M", "2"), + (0xB3, "M", "3"), + (0xB4, "M", " ́"), + (0xB5, "M", "μ"), + (0xB6, "V"), + (0xB7, "V"), + (0xB8, "M", " ̧"), + (0xB9, "M", "1"), + (0xBA, "M", "o"), + (0xBB, "V"), + (0xBC, "M", "1⁄4"), + (0xBD, "M", "1⁄2"), + (0xBE, "M", "3⁄4"), + (0xBF, "V"), + (0xC0, "M", "à"), + (0xC1, "M", "á"), + (0xC2, "M", "â"), + (0xC3, "M", "ã"), + (0xC4, "M", "ä"), + (0xC5, "M", "å"), + (0xC6, "M", "æ"), + (0xC7, "M", "ç"), + ] + + +def _seg_2() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0xC8, "M", "è"), + (0xC9, "M", "é"), + (0xCA, "M", "ê"), + (0xCB, "M", "ë"), + (0xCC, "M", "ì"), + (0xCD, "M", "í"), + (0xCE, "M", "î"), + (0xCF, "M", "ï"), + (0xD0, "M", "ð"), + (0xD1, "M", "ñ"), + (0xD2, "M", "ò"), + (0xD3, "M", "ó"), + (0xD4, "M", "ô"), + (0xD5, "M", "õ"), + (0xD6, "M", "ö"), + (0xD7, "V"), + (0xD8, "M", "ø"), + (0xD9, "M", "ù"), + (0xDA, "M", "ú"), + (0xDB, "M", "û"), + (0xDC, "M", "ü"), + (0xDD, "M", "ý"), + (0xDE, "M", "þ"), + (0xDF, "D", "ss"), + (0xE0, "V"), + (0xE1, "V"), + (0xE2, "V"), + (0xE3, "V"), + (0xE4, "V"), + (0xE5, "V"), + (0xE6, "V"), + (0xE7, "V"), + (0xE8, "V"), + (0xE9, "V"), + (0xEA, "V"), + (0xEB, "V"), + (0xEC, "V"), + (0xED, "V"), + (0xEE, "V"), + (0xEF, "V"), + (0xF0, "V"), + (0xF1, "V"), + (0xF2, "V"), + (0xF3, "V"), + (0xF4, "V"), + (0xF5, "V"), + (0xF6, "V"), + (0xF7, "V"), + (0xF8, "V"), + (0xF9, "V"), + (0xFA, "V"), + (0xFB, "V"), + (0xFC, "V"), + (0xFD, "V"), + (0xFE, "V"), + (0xFF, "V"), + (0x100, "M", "ā"), + (0x101, "V"), + (0x102, "M", "ă"), + (0x103, "V"), + (0x104, "M", "ą"), + (0x105, "V"), + (0x106, "M", "ć"), + (0x107, "V"), + (0x108, "M", "ĉ"), + (0x109, "V"), + (0x10A, "M", "ċ"), + (0x10B, "V"), + (0x10C, "M", "č"), + (0x10D, "V"), + (0x10E, "M", "ď"), + (0x10F, "V"), + (0x110, "M", "đ"), + (0x111, "V"), + (0x112, "M", "ē"), + (0x113, "V"), + (0x114, "M", "ĕ"), + (0x115, "V"), + (0x116, "M", "ė"), + (0x117, "V"), + (0x118, "M", "ę"), + (0x119, "V"), + (0x11A, "M", "ě"), + (0x11B, "V"), + (0x11C, "M", "ĝ"), + (0x11D, "V"), + (0x11E, "M", "ğ"), + (0x11F, "V"), + (0x120, "M", "ġ"), + (0x121, "V"), + (0x122, "M", "ģ"), + (0x123, "V"), + (0x124, "M", "ĥ"), + (0x125, "V"), + (0x126, "M", "ħ"), + (0x127, "V"), + (0x128, "M", "ĩ"), + (0x129, "V"), + (0x12A, "M", "ī"), + (0x12B, "V"), + ] + + +def _seg_3() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0x12C, "M", "ĭ"), + (0x12D, "V"), + (0x12E, "M", "į"), + (0x12F, "V"), + (0x130, "M", "i̇"), + (0x131, "V"), + (0x132, "M", "ij"), + (0x134, "M", "ĵ"), + (0x135, "V"), + (0x136, "M", "ķ"), + (0x137, "V"), + (0x139, "M", "ĺ"), + (0x13A, "V"), + (0x13B, "M", "ļ"), + (0x13C, "V"), + (0x13D, "M", "ľ"), + (0x13E, "V"), + (0x13F, "M", "l·"), + (0x141, "M", "ł"), + (0x142, "V"), + (0x143, "M", "ń"), + (0x144, "V"), + (0x145, "M", "ņ"), + (0x146, "V"), + (0x147, "M", "ň"), + (0x148, "V"), + (0x149, "M", "ʼn"), + (0x14A, "M", "ŋ"), + (0x14B, "V"), + (0x14C, "M", "ō"), + (0x14D, "V"), + (0x14E, "M", "ŏ"), + (0x14F, "V"), + (0x150, "M", "ő"), + (0x151, "V"), + (0x152, "M", "œ"), + (0x153, "V"), + (0x154, "M", "ŕ"), + (0x155, "V"), + (0x156, "M", "ŗ"), + (0x157, "V"), + (0x158, "M", "ř"), + (0x159, "V"), + (0x15A, "M", "ś"), + (0x15B, "V"), + (0x15C, "M", "ŝ"), + (0x15D, "V"), + (0x15E, "M", "ş"), + (0x15F, "V"), + (0x160, "M", "š"), + (0x161, "V"), + (0x162, "M", "ţ"), + (0x163, "V"), + (0x164, "M", "ť"), + (0x165, "V"), + (0x166, "M", "ŧ"), + (0x167, "V"), + (0x168, "M", "ũ"), + (0x169, "V"), + (0x16A, "M", "ū"), + (0x16B, "V"), + (0x16C, "M", "ŭ"), + (0x16D, "V"), + (0x16E, "M", "ů"), + (0x16F, "V"), + (0x170, "M", "ű"), + (0x171, "V"), + (0x172, "M", "ų"), + (0x173, "V"), + (0x174, "M", "ŵ"), + (0x175, "V"), + (0x176, "M", "ŷ"), + (0x177, "V"), + (0x178, "M", "ÿ"), + (0x179, "M", "ź"), + (0x17A, "V"), + (0x17B, "M", "ż"), + (0x17C, "V"), + (0x17D, "M", "ž"), + (0x17E, "V"), + (0x17F, "M", "s"), + (0x180, "V"), + (0x181, "M", "ɓ"), + (0x182, "M", "ƃ"), + (0x183, "V"), + (0x184, "M", "ƅ"), + (0x185, "V"), + (0x186, "M", "ɔ"), + (0x187, "M", "ƈ"), + (0x188, "V"), + (0x189, "M", "ɖ"), + (0x18A, "M", "ɗ"), + (0x18B, "M", "ƌ"), + (0x18C, "V"), + (0x18E, "M", "ǝ"), + (0x18F, "M", "ə"), + (0x190, "M", "ɛ"), + (0x191, "M", "ƒ"), + (0x192, "V"), + (0x193, "M", "ɠ"), + ] + + +def _seg_4() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0x194, "M", "ɣ"), + (0x195, "V"), + (0x196, "M", "ɩ"), + (0x197, "M", "ɨ"), + (0x198, "M", "ƙ"), + (0x199, "V"), + (0x19C, "M", "ɯ"), + (0x19D, "M", "ɲ"), + (0x19E, "V"), + (0x19F, "M", "ɵ"), + (0x1A0, "M", "ơ"), + (0x1A1, "V"), + (0x1A2, "M", "ƣ"), + (0x1A3, "V"), + (0x1A4, "M", "ƥ"), + (0x1A5, "V"), + (0x1A6, "M", "ʀ"), + (0x1A7, "M", "ƨ"), + (0x1A8, "V"), + (0x1A9, "M", "ʃ"), + (0x1AA, "V"), + (0x1AC, "M", "ƭ"), + (0x1AD, "V"), + (0x1AE, "M", "ʈ"), + (0x1AF, "M", "ư"), + (0x1B0, "V"), + (0x1B1, "M", "ʊ"), + (0x1B2, "M", "ʋ"), + (0x1B3, "M", "ƴ"), + (0x1B4, "V"), + (0x1B5, "M", "ƶ"), + (0x1B6, "V"), + (0x1B7, "M", "ʒ"), + (0x1B8, "M", "ƹ"), + (0x1B9, "V"), + (0x1BC, "M", "ƽ"), + (0x1BD, "V"), + (0x1C4, "M", "dž"), + (0x1C7, "M", "lj"), + (0x1CA, "M", "nj"), + (0x1CD, "M", "ǎ"), + (0x1CE, "V"), + (0x1CF, "M", "ǐ"), + (0x1D0, "V"), + (0x1D1, "M", "ǒ"), + (0x1D2, "V"), + (0x1D3, "M", "ǔ"), + (0x1D4, "V"), + (0x1D5, "M", "ǖ"), + (0x1D6, "V"), + (0x1D7, "M", "ǘ"), + (0x1D8, "V"), + (0x1D9, "M", "ǚ"), + (0x1DA, "V"), + (0x1DB, "M", "ǜ"), + (0x1DC, "V"), + (0x1DE, "M", "ǟ"), + (0x1DF, "V"), + (0x1E0, "M", "ǡ"), + (0x1E1, "V"), + (0x1E2, "M", "ǣ"), + (0x1E3, "V"), + (0x1E4, "M", "ǥ"), + (0x1E5, "V"), + (0x1E6, "M", "ǧ"), + (0x1E7, "V"), + (0x1E8, "M", "ǩ"), + (0x1E9, "V"), + (0x1EA, "M", "ǫ"), + (0x1EB, "V"), + (0x1EC, "M", "ǭ"), + (0x1ED, "V"), + (0x1EE, "M", "ǯ"), + (0x1EF, "V"), + (0x1F1, "M", "dz"), + (0x1F4, "M", "ǵ"), + (0x1F5, "V"), + (0x1F6, "M", "ƕ"), + (0x1F7, "M", "ƿ"), + (0x1F8, "M", "ǹ"), + (0x1F9, "V"), + (0x1FA, "M", "ǻ"), + (0x1FB, "V"), + (0x1FC, "M", "ǽ"), + (0x1FD, "V"), + (0x1FE, "M", "ǿ"), + (0x1FF, "V"), + (0x200, "M", "ȁ"), + (0x201, "V"), + (0x202, "M", "ȃ"), + (0x203, "V"), + (0x204, "M", "ȅ"), + (0x205, "V"), + (0x206, "M", "ȇ"), + (0x207, "V"), + (0x208, "M", "ȉ"), + (0x209, "V"), + (0x20A, "M", "ȋ"), + (0x20B, "V"), + (0x20C, "M", "ȍ"), + ] + + +def _seg_5() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0x20D, "V"), + (0x20E, "M", "ȏ"), + (0x20F, "V"), + (0x210, "M", "ȑ"), + (0x211, "V"), + (0x212, "M", "ȓ"), + (0x213, "V"), + (0x214, "M", "ȕ"), + (0x215, "V"), + (0x216, "M", "ȗ"), + (0x217, "V"), + (0x218, "M", "ș"), + (0x219, "V"), + (0x21A, "M", "ț"), + (0x21B, "V"), + (0x21C, "M", "ȝ"), + (0x21D, "V"), + (0x21E, "M", "ȟ"), + (0x21F, "V"), + (0x220, "M", "ƞ"), + (0x221, "V"), + (0x222, "M", "ȣ"), + (0x223, "V"), + (0x224, "M", "ȥ"), + (0x225, "V"), + (0x226, "M", "ȧ"), + (0x227, "V"), + (0x228, "M", "ȩ"), + (0x229, "V"), + (0x22A, "M", "ȫ"), + (0x22B, "V"), + (0x22C, "M", "ȭ"), + (0x22D, "V"), + (0x22E, "M", "ȯ"), + (0x22F, "V"), + (0x230, "M", "ȱ"), + (0x231, "V"), + (0x232, "M", "ȳ"), + (0x233, "V"), + (0x23A, "M", "ⱥ"), + (0x23B, "M", "ȼ"), + (0x23C, "V"), + (0x23D, "M", "ƚ"), + (0x23E, "M", "ⱦ"), + (0x23F, "V"), + (0x241, "M", "ɂ"), + (0x242, "V"), + (0x243, "M", "ƀ"), + (0x244, "M", "ʉ"), + (0x245, "M", "ʌ"), + (0x246, "M", "ɇ"), + (0x247, "V"), + (0x248, "M", "ɉ"), + (0x249, "V"), + (0x24A, "M", "ɋ"), + (0x24B, "V"), + (0x24C, "M", "ɍ"), + (0x24D, "V"), + (0x24E, "M", "ɏ"), + (0x24F, "V"), + (0x2B0, "M", "h"), + (0x2B1, "M", "ɦ"), + (0x2B2, "M", "j"), + (0x2B3, "M", "r"), + (0x2B4, "M", "ɹ"), + (0x2B5, "M", "ɻ"), + (0x2B6, "M", "ʁ"), + (0x2B7, "M", "w"), + (0x2B8, "M", "y"), + (0x2B9, "V"), + (0x2D8, "M", " ̆"), + (0x2D9, "M", " ̇"), + (0x2DA, "M", " ̊"), + (0x2DB, "M", " ̨"), + (0x2DC, "M", " ̃"), + (0x2DD, "M", " ̋"), + (0x2DE, "V"), + (0x2E0, "M", "ɣ"), + (0x2E1, "M", "l"), + (0x2E2, "M", "s"), + (0x2E3, "M", "x"), + (0x2E4, "M", "ʕ"), + (0x2E5, "V"), + (0x340, "M", "̀"), + (0x341, "M", "́"), + (0x342, "V"), + (0x343, "M", "̓"), + (0x344, "M", "̈́"), + (0x345, "M", "ι"), + (0x346, "V"), + (0x34F, "I"), + (0x350, "V"), + (0x370, "M", "ͱ"), + (0x371, "V"), + (0x372, "M", "ͳ"), + (0x373, "V"), + (0x374, "M", "ʹ"), + (0x375, "V"), + (0x376, "M", "ͷ"), + (0x377, "V"), + ] + + +def _seg_6() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0x378, "X"), + (0x37A, "M", " ι"), + (0x37B, "V"), + (0x37E, "M", ";"), + (0x37F, "M", "ϳ"), + (0x380, "X"), + (0x384, "M", " ́"), + (0x385, "M", " ̈́"), + (0x386, "M", "ά"), + (0x387, "M", "·"), + (0x388, "M", "έ"), + (0x389, "M", "ή"), + (0x38A, "M", "ί"), + (0x38B, "X"), + (0x38C, "M", "ό"), + (0x38D, "X"), + (0x38E, "M", "ύ"), + (0x38F, "M", "ώ"), + (0x390, "V"), + (0x391, "M", "α"), + (0x392, "M", "β"), + (0x393, "M", "γ"), + (0x394, "M", "δ"), + (0x395, "M", "ε"), + (0x396, "M", "ζ"), + (0x397, "M", "η"), + (0x398, "M", "θ"), + (0x399, "M", "ι"), + (0x39A, "M", "κ"), + (0x39B, "M", "λ"), + (0x39C, "M", "μ"), + (0x39D, "M", "ν"), + (0x39E, "M", "ξ"), + (0x39F, "M", "ο"), + (0x3A0, "M", "π"), + (0x3A1, "M", "ρ"), + (0x3A2, "X"), + (0x3A3, "M", "σ"), + (0x3A4, "M", "τ"), + (0x3A5, "M", "υ"), + (0x3A6, "M", "φ"), + (0x3A7, "M", "χ"), + (0x3A8, "M", "ψ"), + (0x3A9, "M", "ω"), + (0x3AA, "M", "ϊ"), + (0x3AB, "M", "ϋ"), + (0x3AC, "V"), + (0x3C2, "D", "σ"), + (0x3C3, "V"), + (0x3CF, "M", "ϗ"), + (0x3D0, "M", "β"), + (0x3D1, "M", "θ"), + (0x3D2, "M", "υ"), + (0x3D3, "M", "ύ"), + (0x3D4, "M", "ϋ"), + (0x3D5, "M", "φ"), + (0x3D6, "M", "π"), + (0x3D7, "V"), + (0x3D8, "M", "ϙ"), + (0x3D9, "V"), + (0x3DA, "M", "ϛ"), + (0x3DB, "V"), + (0x3DC, "M", "ϝ"), + (0x3DD, "V"), + (0x3DE, "M", "ϟ"), + (0x3DF, "V"), + (0x3E0, "M", "ϡ"), + (0x3E1, "V"), + (0x3E2, "M", "ϣ"), + (0x3E3, "V"), + (0x3E4, "M", "ϥ"), + (0x3E5, "V"), + (0x3E6, "M", "ϧ"), + (0x3E7, "V"), + (0x3E8, "M", "ϩ"), + (0x3E9, "V"), + (0x3EA, "M", "ϫ"), + (0x3EB, "V"), + (0x3EC, "M", "ϭ"), + (0x3ED, "V"), + (0x3EE, "M", "ϯ"), + (0x3EF, "V"), + (0x3F0, "M", "κ"), + (0x3F1, "M", "ρ"), + (0x3F2, "M", "σ"), + (0x3F3, "V"), + (0x3F4, "M", "θ"), + (0x3F5, "M", "ε"), + (0x3F6, "V"), + (0x3F7, "M", "ϸ"), + (0x3F8, "V"), + (0x3F9, "M", "σ"), + (0x3FA, "M", "ϻ"), + (0x3FB, "V"), + (0x3FD, "M", "ͻ"), + (0x3FE, "M", "ͼ"), + (0x3FF, "M", "ͽ"), + (0x400, "M", "ѐ"), + (0x401, "M", "ё"), + (0x402, "M", "ђ"), + ] + + +def _seg_7() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0x403, "M", "ѓ"), + (0x404, "M", "є"), + (0x405, "M", "ѕ"), + (0x406, "M", "і"), + (0x407, "M", "ї"), + (0x408, "M", "ј"), + (0x409, "M", "љ"), + (0x40A, "M", "њ"), + (0x40B, "M", "ћ"), + (0x40C, "M", "ќ"), + (0x40D, "M", "ѝ"), + (0x40E, "M", "ў"), + (0x40F, "M", "џ"), + (0x410, "M", "а"), + (0x411, "M", "б"), + (0x412, "M", "в"), + (0x413, "M", "г"), + (0x414, "M", "д"), + (0x415, "M", "е"), + (0x416, "M", "ж"), + (0x417, "M", "з"), + (0x418, "M", "и"), + (0x419, "M", "й"), + (0x41A, "M", "к"), + (0x41B, "M", "л"), + (0x41C, "M", "м"), + (0x41D, "M", "н"), + (0x41E, "M", "о"), + (0x41F, "M", "п"), + (0x420, "M", "р"), + (0x421, "M", "с"), + (0x422, "M", "т"), + (0x423, "M", "у"), + (0x424, "M", "ф"), + (0x425, "M", "х"), + (0x426, "M", "ц"), + (0x427, "M", "ч"), + (0x428, "M", "ш"), + (0x429, "M", "щ"), + (0x42A, "M", "ъ"), + (0x42B, "M", "ы"), + (0x42C, "M", "ь"), + (0x42D, "M", "э"), + (0x42E, "M", "ю"), + (0x42F, "M", "я"), + (0x430, "V"), + (0x460, "M", "ѡ"), + (0x461, "V"), + (0x462, "M", "ѣ"), + (0x463, "V"), + (0x464, "M", "ѥ"), + (0x465, "V"), + (0x466, "M", "ѧ"), + (0x467, "V"), + (0x468, "M", "ѩ"), + (0x469, "V"), + (0x46A, "M", "ѫ"), + (0x46B, "V"), + (0x46C, "M", "ѭ"), + (0x46D, "V"), + (0x46E, "M", "ѯ"), + (0x46F, "V"), + (0x470, "M", "ѱ"), + (0x471, "V"), + (0x472, "M", "ѳ"), + (0x473, "V"), + (0x474, "M", "ѵ"), + (0x475, "V"), + (0x476, "M", "ѷ"), + (0x477, "V"), + (0x478, "M", "ѹ"), + (0x479, "V"), + (0x47A, "M", "ѻ"), + (0x47B, "V"), + (0x47C, "M", "ѽ"), + (0x47D, "V"), + (0x47E, "M", "ѿ"), + (0x47F, "V"), + (0x480, "M", "ҁ"), + (0x481, "V"), + (0x48A, "M", "ҋ"), + (0x48B, "V"), + (0x48C, "M", "ҍ"), + (0x48D, "V"), + (0x48E, "M", "ҏ"), + (0x48F, "V"), + (0x490, "M", "ґ"), + (0x491, "V"), + (0x492, "M", "ғ"), + (0x493, "V"), + (0x494, "M", "ҕ"), + (0x495, "V"), + (0x496, "M", "җ"), + (0x497, "V"), + (0x498, "M", "ҙ"), + (0x499, "V"), + (0x49A, "M", "қ"), + (0x49B, "V"), + (0x49C, "M", "ҝ"), + (0x49D, "V"), + ] + + +def _seg_8() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0x49E, "M", "ҟ"), + (0x49F, "V"), + (0x4A0, "M", "ҡ"), + (0x4A1, "V"), + (0x4A2, "M", "ң"), + (0x4A3, "V"), + (0x4A4, "M", "ҥ"), + (0x4A5, "V"), + (0x4A6, "M", "ҧ"), + (0x4A7, "V"), + (0x4A8, "M", "ҩ"), + (0x4A9, "V"), + (0x4AA, "M", "ҫ"), + (0x4AB, "V"), + (0x4AC, "M", "ҭ"), + (0x4AD, "V"), + (0x4AE, "M", "ү"), + (0x4AF, "V"), + (0x4B0, "M", "ұ"), + (0x4B1, "V"), + (0x4B2, "M", "ҳ"), + (0x4B3, "V"), + (0x4B4, "M", "ҵ"), + (0x4B5, "V"), + (0x4B6, "M", "ҷ"), + (0x4B7, "V"), + (0x4B8, "M", "ҹ"), + (0x4B9, "V"), + (0x4BA, "M", "һ"), + (0x4BB, "V"), + (0x4BC, "M", "ҽ"), + (0x4BD, "V"), + (0x4BE, "M", "ҿ"), + (0x4BF, "V"), + (0x4C0, "M", "ӏ"), + (0x4C1, "M", "ӂ"), + (0x4C2, "V"), + (0x4C3, "M", "ӄ"), + (0x4C4, "V"), + (0x4C5, "M", "ӆ"), + (0x4C6, "V"), + (0x4C7, "M", "ӈ"), + (0x4C8, "V"), + (0x4C9, "M", "ӊ"), + (0x4CA, "V"), + (0x4CB, "M", "ӌ"), + (0x4CC, "V"), + (0x4CD, "M", "ӎ"), + (0x4CE, "V"), + (0x4D0, "M", "ӑ"), + (0x4D1, "V"), + (0x4D2, "M", "ӓ"), + (0x4D3, "V"), + (0x4D4, "M", "ӕ"), + (0x4D5, "V"), + (0x4D6, "M", "ӗ"), + (0x4D7, "V"), + (0x4D8, "M", "ә"), + (0x4D9, "V"), + (0x4DA, "M", "ӛ"), + (0x4DB, "V"), + (0x4DC, "M", "ӝ"), + (0x4DD, "V"), + (0x4DE, "M", "ӟ"), + (0x4DF, "V"), + (0x4E0, "M", "ӡ"), + (0x4E1, "V"), + (0x4E2, "M", "ӣ"), + (0x4E3, "V"), + (0x4E4, "M", "ӥ"), + (0x4E5, "V"), + (0x4E6, "M", "ӧ"), + (0x4E7, "V"), + (0x4E8, "M", "ө"), + (0x4E9, "V"), + (0x4EA, "M", "ӫ"), + (0x4EB, "V"), + (0x4EC, "M", "ӭ"), + (0x4ED, "V"), + (0x4EE, "M", "ӯ"), + (0x4EF, "V"), + (0x4F0, "M", "ӱ"), + (0x4F1, "V"), + (0x4F2, "M", "ӳ"), + (0x4F3, "V"), + (0x4F4, "M", "ӵ"), + (0x4F5, "V"), + (0x4F6, "M", "ӷ"), + (0x4F7, "V"), + (0x4F8, "M", "ӹ"), + (0x4F9, "V"), + (0x4FA, "M", "ӻ"), + (0x4FB, "V"), + (0x4FC, "M", "ӽ"), + (0x4FD, "V"), + (0x4FE, "M", "ӿ"), + (0x4FF, "V"), + (0x500, "M", "ԁ"), + (0x501, "V"), + (0x502, "M", "ԃ"), + ] + + +def _seg_9() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0x503, "V"), + (0x504, "M", "ԅ"), + (0x505, "V"), + (0x506, "M", "ԇ"), + (0x507, "V"), + (0x508, "M", "ԉ"), + (0x509, "V"), + (0x50A, "M", "ԋ"), + (0x50B, "V"), + (0x50C, "M", "ԍ"), + (0x50D, "V"), + (0x50E, "M", "ԏ"), + (0x50F, "V"), + (0x510, "M", "ԑ"), + (0x511, "V"), + (0x512, "M", "ԓ"), + (0x513, "V"), + (0x514, "M", "ԕ"), + (0x515, "V"), + (0x516, "M", "ԗ"), + (0x517, "V"), + (0x518, "M", "ԙ"), + (0x519, "V"), + (0x51A, "M", "ԛ"), + (0x51B, "V"), + (0x51C, "M", "ԝ"), + (0x51D, "V"), + (0x51E, "M", "ԟ"), + (0x51F, "V"), + (0x520, "M", "ԡ"), + (0x521, "V"), + (0x522, "M", "ԣ"), + (0x523, "V"), + (0x524, "M", "ԥ"), + (0x525, "V"), + (0x526, "M", "ԧ"), + (0x527, "V"), + (0x528, "M", "ԩ"), + (0x529, "V"), + (0x52A, "M", "ԫ"), + (0x52B, "V"), + (0x52C, "M", "ԭ"), + (0x52D, "V"), + (0x52E, "M", "ԯ"), + (0x52F, "V"), + (0x530, "X"), + (0x531, "M", "ա"), + (0x532, "M", "բ"), + (0x533, "M", "գ"), + (0x534, "M", "դ"), + (0x535, "M", "ե"), + (0x536, "M", "զ"), + (0x537, "M", "է"), + (0x538, "M", "ը"), + (0x539, "M", "թ"), + (0x53A, "M", "ժ"), + (0x53B, "M", "ի"), + (0x53C, "M", "լ"), + (0x53D, "M", "խ"), + (0x53E, "M", "ծ"), + (0x53F, "M", "կ"), + (0x540, "M", "հ"), + (0x541, "M", "ձ"), + (0x542, "M", "ղ"), + (0x543, "M", "ճ"), + (0x544, "M", "մ"), + (0x545, "M", "յ"), + (0x546, "M", "ն"), + (0x547, "M", "շ"), + (0x548, "M", "ո"), + (0x549, "M", "չ"), + (0x54A, "M", "պ"), + (0x54B, "M", "ջ"), + (0x54C, "M", "ռ"), + (0x54D, "M", "ս"), + (0x54E, "M", "վ"), + (0x54F, "M", "տ"), + (0x550, "M", "ր"), + (0x551, "M", "ց"), + (0x552, "M", "ւ"), + (0x553, "M", "փ"), + (0x554, "M", "ք"), + (0x555, "M", "օ"), + (0x556, "M", "ֆ"), + (0x557, "X"), + (0x559, "V"), + (0x587, "M", "եւ"), + (0x588, "V"), + (0x58B, "X"), + (0x58D, "V"), + (0x590, "X"), + (0x591, "V"), + (0x5C8, "X"), + (0x5D0, "V"), + (0x5EB, "X"), + (0x5EF, "V"), + (0x5F5, "X"), + (0x606, "V"), + (0x61C, "X"), + (0x61D, "V"), + ] + + +def _seg_10() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0x675, "M", "اٴ"), + (0x676, "M", "وٴ"), + (0x677, "M", "ۇٴ"), + (0x678, "M", "يٴ"), + (0x679, "V"), + (0x6DD, "X"), + (0x6DE, "V"), + (0x70E, "X"), + (0x710, "V"), + (0x74B, "X"), + (0x74D, "V"), + (0x7B2, "X"), + (0x7C0, "V"), + (0x7FB, "X"), + (0x7FD, "V"), + (0x82E, "X"), + (0x830, "V"), + (0x83F, "X"), + (0x840, "V"), + (0x85C, "X"), + (0x85E, "V"), + (0x85F, "X"), + (0x860, "V"), + (0x86B, "X"), + (0x870, "V"), + (0x88F, "X"), + (0x897, "V"), + (0x8E2, "X"), + (0x8E3, "V"), + (0x958, "M", "क़"), + (0x959, "M", "ख़"), + (0x95A, "M", "ग़"), + (0x95B, "M", "ज़"), + (0x95C, "M", "ड़"), + (0x95D, "M", "ढ़"), + (0x95E, "M", "फ़"), + (0x95F, "M", "य़"), + (0x960, "V"), + (0x984, "X"), + (0x985, "V"), + (0x98D, "X"), + (0x98F, "V"), + (0x991, "X"), + (0x993, "V"), + (0x9A9, "X"), + (0x9AA, "V"), + (0x9B1, "X"), + (0x9B2, "V"), + (0x9B3, "X"), + (0x9B6, "V"), + (0x9BA, "X"), + (0x9BC, "V"), + (0x9C5, "X"), + (0x9C7, "V"), + (0x9C9, "X"), + (0x9CB, "V"), + (0x9CF, "X"), + (0x9D7, "V"), + (0x9D8, "X"), + (0x9DC, "M", "ড়"), + (0x9DD, "M", "ঢ়"), + (0x9DE, "X"), + (0x9DF, "M", "য়"), + (0x9E0, "V"), + (0x9E4, "X"), + (0x9E6, "V"), + (0x9FF, "X"), + (0xA01, "V"), + (0xA04, "X"), + (0xA05, "V"), + (0xA0B, "X"), + (0xA0F, "V"), + (0xA11, "X"), + (0xA13, "V"), + (0xA29, "X"), + (0xA2A, "V"), + (0xA31, "X"), + (0xA32, "V"), + (0xA33, "M", "ਲ਼"), + (0xA34, "X"), + (0xA35, "V"), + (0xA36, "M", "ਸ਼"), + (0xA37, "X"), + (0xA38, "V"), + (0xA3A, "X"), + (0xA3C, "V"), + (0xA3D, "X"), + (0xA3E, "V"), + (0xA43, "X"), + (0xA47, "V"), + (0xA49, "X"), + (0xA4B, "V"), + (0xA4E, "X"), + (0xA51, "V"), + (0xA52, "X"), + (0xA59, "M", "ਖ਼"), + (0xA5A, "M", "ਗ਼"), + (0xA5B, "M", "ਜ਼"), + (0xA5C, "V"), + (0xA5D, "X"), + ] + + +def _seg_11() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0xA5E, "M", "ਫ਼"), + (0xA5F, "X"), + (0xA66, "V"), + (0xA77, "X"), + (0xA81, "V"), + (0xA84, "X"), + (0xA85, "V"), + (0xA8E, "X"), + (0xA8F, "V"), + (0xA92, "X"), + (0xA93, "V"), + (0xAA9, "X"), + (0xAAA, "V"), + (0xAB1, "X"), + (0xAB2, "V"), + (0xAB4, "X"), + (0xAB5, "V"), + (0xABA, "X"), + (0xABC, "V"), + (0xAC6, "X"), + (0xAC7, "V"), + (0xACA, "X"), + (0xACB, "V"), + (0xACE, "X"), + (0xAD0, "V"), + (0xAD1, "X"), + (0xAE0, "V"), + (0xAE4, "X"), + (0xAE6, "V"), + (0xAF2, "X"), + (0xAF9, "V"), + (0xB00, "X"), + (0xB01, "V"), + (0xB04, "X"), + (0xB05, "V"), + (0xB0D, "X"), + (0xB0F, "V"), + (0xB11, "X"), + (0xB13, "V"), + (0xB29, "X"), + (0xB2A, "V"), + (0xB31, "X"), + (0xB32, "V"), + (0xB34, "X"), + (0xB35, "V"), + (0xB3A, "X"), + (0xB3C, "V"), + (0xB45, "X"), + (0xB47, "V"), + (0xB49, "X"), + (0xB4B, "V"), + (0xB4E, "X"), + (0xB55, "V"), + (0xB58, "X"), + (0xB5C, "M", "ଡ଼"), + (0xB5D, "M", "ଢ଼"), + (0xB5E, "X"), + (0xB5F, "V"), + (0xB64, "X"), + (0xB66, "V"), + (0xB78, "X"), + (0xB82, "V"), + (0xB84, "X"), + (0xB85, "V"), + (0xB8B, "X"), + (0xB8E, "V"), + (0xB91, "X"), + (0xB92, "V"), + (0xB96, "X"), + (0xB99, "V"), + (0xB9B, "X"), + (0xB9C, "V"), + (0xB9D, "X"), + (0xB9E, "V"), + (0xBA0, "X"), + (0xBA3, "V"), + (0xBA5, "X"), + (0xBA8, "V"), + (0xBAB, "X"), + (0xBAE, "V"), + (0xBBA, "X"), + (0xBBE, "V"), + (0xBC3, "X"), + (0xBC6, "V"), + (0xBC9, "X"), + (0xBCA, "V"), + (0xBCE, "X"), + (0xBD0, "V"), + (0xBD1, "X"), + (0xBD7, "V"), + (0xBD8, "X"), + (0xBE6, "V"), + (0xBFB, "X"), + (0xC00, "V"), + (0xC0D, "X"), + (0xC0E, "V"), + (0xC11, "X"), + (0xC12, "V"), + (0xC29, "X"), + (0xC2A, "V"), + ] + + +def _seg_12() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0xC3A, "X"), + (0xC3C, "V"), + (0xC45, "X"), + (0xC46, "V"), + (0xC49, "X"), + (0xC4A, "V"), + (0xC4E, "X"), + (0xC55, "V"), + (0xC57, "X"), + (0xC58, "V"), + (0xC5B, "X"), + (0xC5D, "V"), + (0xC5E, "X"), + (0xC60, "V"), + (0xC64, "X"), + (0xC66, "V"), + (0xC70, "X"), + (0xC77, "V"), + (0xC8D, "X"), + (0xC8E, "V"), + (0xC91, "X"), + (0xC92, "V"), + (0xCA9, "X"), + (0xCAA, "V"), + (0xCB4, "X"), + (0xCB5, "V"), + (0xCBA, "X"), + (0xCBC, "V"), + (0xCC5, "X"), + (0xCC6, "V"), + (0xCC9, "X"), + (0xCCA, "V"), + (0xCCE, "X"), + (0xCD5, "V"), + (0xCD7, "X"), + (0xCDD, "V"), + (0xCDF, "X"), + (0xCE0, "V"), + (0xCE4, "X"), + (0xCE6, "V"), + (0xCF0, "X"), + (0xCF1, "V"), + (0xCF4, "X"), + (0xD00, "V"), + (0xD0D, "X"), + (0xD0E, "V"), + (0xD11, "X"), + (0xD12, "V"), + (0xD45, "X"), + (0xD46, "V"), + (0xD49, "X"), + (0xD4A, "V"), + (0xD50, "X"), + (0xD54, "V"), + (0xD64, "X"), + (0xD66, "V"), + (0xD80, "X"), + (0xD81, "V"), + (0xD84, "X"), + (0xD85, "V"), + (0xD97, "X"), + (0xD9A, "V"), + (0xDB2, "X"), + (0xDB3, "V"), + (0xDBC, "X"), + (0xDBD, "V"), + (0xDBE, "X"), + (0xDC0, "V"), + (0xDC7, "X"), + (0xDCA, "V"), + (0xDCB, "X"), + (0xDCF, "V"), + (0xDD5, "X"), + (0xDD6, "V"), + (0xDD7, "X"), + (0xDD8, "V"), + (0xDE0, "X"), + (0xDE6, "V"), + (0xDF0, "X"), + (0xDF2, "V"), + (0xDF5, "X"), + (0xE01, "V"), + (0xE33, "M", "ํา"), + (0xE34, "V"), + (0xE3B, "X"), + (0xE3F, "V"), + (0xE5C, "X"), + (0xE81, "V"), + (0xE83, "X"), + (0xE84, "V"), + (0xE85, "X"), + (0xE86, "V"), + (0xE8B, "X"), + (0xE8C, "V"), + (0xEA4, "X"), + (0xEA5, "V"), + (0xEA6, "X"), + (0xEA7, "V"), + (0xEB3, "M", "ໍາ"), + (0xEB4, "V"), + ] + + +def _seg_13() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0xEBE, "X"), + (0xEC0, "V"), + (0xEC5, "X"), + (0xEC6, "V"), + (0xEC7, "X"), + (0xEC8, "V"), + (0xECF, "X"), + (0xED0, "V"), + (0xEDA, "X"), + (0xEDC, "M", "ຫນ"), + (0xEDD, "M", "ຫມ"), + (0xEDE, "V"), + (0xEE0, "X"), + (0xF00, "V"), + (0xF0C, "M", "་"), + (0xF0D, "V"), + (0xF43, "M", "གྷ"), + (0xF44, "V"), + (0xF48, "X"), + (0xF49, "V"), + (0xF4D, "M", "ཌྷ"), + (0xF4E, "V"), + (0xF52, "M", "དྷ"), + (0xF53, "V"), + (0xF57, "M", "བྷ"), + (0xF58, "V"), + (0xF5C, "M", "ཛྷ"), + (0xF5D, "V"), + (0xF69, "M", "ཀྵ"), + (0xF6A, "V"), + (0xF6D, "X"), + (0xF71, "V"), + (0xF73, "M", "ཱི"), + (0xF74, "V"), + (0xF75, "M", "ཱུ"), + (0xF76, "M", "ྲྀ"), + (0xF77, "M", "ྲཱྀ"), + (0xF78, "M", "ླྀ"), + (0xF79, "M", "ླཱྀ"), + (0xF7A, "V"), + (0xF81, "M", "ཱྀ"), + (0xF82, "V"), + (0xF93, "M", "ྒྷ"), + (0xF94, "V"), + (0xF98, "X"), + (0xF99, "V"), + (0xF9D, "M", "ྜྷ"), + (0xF9E, "V"), + (0xFA2, "M", "ྡྷ"), + (0xFA3, "V"), + (0xFA7, "M", "ྦྷ"), + (0xFA8, "V"), + (0xFAC, "M", "ྫྷ"), + (0xFAD, "V"), + (0xFB9, "M", "ྐྵ"), + (0xFBA, "V"), + (0xFBD, "X"), + (0xFBE, "V"), + (0xFCD, "X"), + (0xFCE, "V"), + (0xFDB, "X"), + (0x1000, "V"), + (0x10A0, "M", "ⴀ"), + (0x10A1, "M", "ⴁ"), + (0x10A2, "M", "ⴂ"), + (0x10A3, "M", "ⴃ"), + (0x10A4, "M", "ⴄ"), + (0x10A5, "M", "ⴅ"), + (0x10A6, "M", "ⴆ"), + (0x10A7, "M", "ⴇ"), + (0x10A8, "M", "ⴈ"), + (0x10A9, "M", "ⴉ"), + (0x10AA, "M", "ⴊ"), + (0x10AB, "M", "ⴋ"), + (0x10AC, "M", "ⴌ"), + (0x10AD, "M", "ⴍ"), + (0x10AE, "M", "ⴎ"), + (0x10AF, "M", "ⴏ"), + (0x10B0, "M", "ⴐ"), + (0x10B1, "M", "ⴑ"), + (0x10B2, "M", "ⴒ"), + (0x10B3, "M", "ⴓ"), + (0x10B4, "M", "ⴔ"), + (0x10B5, "M", "ⴕ"), + (0x10B6, "M", "ⴖ"), + (0x10B7, "M", "ⴗ"), + (0x10B8, "M", "ⴘ"), + (0x10B9, "M", "ⴙ"), + (0x10BA, "M", "ⴚ"), + (0x10BB, "M", "ⴛ"), + (0x10BC, "M", "ⴜ"), + (0x10BD, "M", "ⴝ"), + (0x10BE, "M", "ⴞ"), + (0x10BF, "M", "ⴟ"), + (0x10C0, "M", "ⴠ"), + (0x10C1, "M", "ⴡ"), + (0x10C2, "M", "ⴢ"), + (0x10C3, "M", "ⴣ"), + (0x10C4, "M", "ⴤ"), + (0x10C5, "M", "ⴥ"), + ] + + +def _seg_14() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0x10C6, "X"), + (0x10C7, "M", "ⴧ"), + (0x10C8, "X"), + (0x10CD, "M", "ⴭ"), + (0x10CE, "X"), + (0x10D0, "V"), + (0x10FC, "M", "ნ"), + (0x10FD, "V"), + (0x115F, "I"), + (0x1161, "V"), + (0x1249, "X"), + (0x124A, "V"), + (0x124E, "X"), + (0x1250, "V"), + (0x1257, "X"), + (0x1258, "V"), + (0x1259, "X"), + (0x125A, "V"), + (0x125E, "X"), + (0x1260, "V"), + (0x1289, "X"), + (0x128A, "V"), + (0x128E, "X"), + (0x1290, "V"), + (0x12B1, "X"), + (0x12B2, "V"), + (0x12B6, "X"), + (0x12B8, "V"), + (0x12BF, "X"), + (0x12C0, "V"), + (0x12C1, "X"), + (0x12C2, "V"), + (0x12C6, "X"), + (0x12C8, "V"), + (0x12D7, "X"), + (0x12D8, "V"), + (0x1311, "X"), + (0x1312, "V"), + (0x1316, "X"), + (0x1318, "V"), + (0x135B, "X"), + (0x135D, "V"), + (0x137D, "X"), + (0x1380, "V"), + (0x139A, "X"), + (0x13A0, "V"), + (0x13F6, "X"), + (0x13F8, "M", "Ᏸ"), + (0x13F9, "M", "Ᏹ"), + (0x13FA, "M", "Ᏺ"), + (0x13FB, "M", "Ᏻ"), + (0x13FC, "M", "Ᏼ"), + (0x13FD, "M", "Ᏽ"), + (0x13FE, "X"), + (0x1400, "V"), + (0x1680, "X"), + (0x1681, "V"), + (0x169D, "X"), + (0x16A0, "V"), + (0x16F9, "X"), + (0x1700, "V"), + (0x1716, "X"), + (0x171F, "V"), + (0x1737, "X"), + (0x1740, "V"), + (0x1754, "X"), + (0x1760, "V"), + (0x176D, "X"), + (0x176E, "V"), + (0x1771, "X"), + (0x1772, "V"), + (0x1774, "X"), + (0x1780, "V"), + (0x17B4, "I"), + (0x17B6, "V"), + (0x17DE, "X"), + (0x17E0, "V"), + (0x17EA, "X"), + (0x17F0, "V"), + (0x17FA, "X"), + (0x1800, "V"), + (0x180B, "I"), + (0x1810, "V"), + (0x181A, "X"), + (0x1820, "V"), + (0x1879, "X"), + (0x1880, "V"), + (0x18AB, "X"), + (0x18B0, "V"), + (0x18F6, "X"), + (0x1900, "V"), + (0x191F, "X"), + (0x1920, "V"), + (0x192C, "X"), + (0x1930, "V"), + (0x193C, "X"), + (0x1940, "V"), + (0x1941, "X"), + (0x1944, "V"), + (0x196E, "X"), + ] + + +def _seg_15() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0x1970, "V"), + (0x1975, "X"), + (0x1980, "V"), + (0x19AC, "X"), + (0x19B0, "V"), + (0x19CA, "X"), + (0x19D0, "V"), + (0x19DB, "X"), + (0x19DE, "V"), + (0x1A1C, "X"), + (0x1A1E, "V"), + (0x1A5F, "X"), + (0x1A60, "V"), + (0x1A7D, "X"), + (0x1A7F, "V"), + (0x1A8A, "X"), + (0x1A90, "V"), + (0x1A9A, "X"), + (0x1AA0, "V"), + (0x1AAE, "X"), + (0x1AB0, "V"), + (0x1ACF, "X"), + (0x1B00, "V"), + (0x1B4D, "X"), + (0x1B4E, "V"), + (0x1BF4, "X"), + (0x1BFC, "V"), + (0x1C38, "X"), + (0x1C3B, "V"), + (0x1C4A, "X"), + (0x1C4D, "V"), + (0x1C80, "M", "в"), + (0x1C81, "M", "д"), + (0x1C82, "M", "о"), + (0x1C83, "M", "с"), + (0x1C84, "M", "т"), + (0x1C86, "M", "ъ"), + (0x1C87, "M", "ѣ"), + (0x1C88, "M", "ꙋ"), + (0x1C89, "M", "ᲊ"), + (0x1C8A, "V"), + (0x1C8B, "X"), + (0x1C90, "M", "ა"), + (0x1C91, "M", "ბ"), + (0x1C92, "M", "გ"), + (0x1C93, "M", "დ"), + (0x1C94, "M", "ე"), + (0x1C95, "M", "ვ"), + (0x1C96, "M", "ზ"), + (0x1C97, "M", "თ"), + (0x1C98, "M", "ი"), + (0x1C99, "M", "კ"), + (0x1C9A, "M", "ლ"), + (0x1C9B, "M", "მ"), + (0x1C9C, "M", "ნ"), + (0x1C9D, "M", "ო"), + (0x1C9E, "M", "პ"), + (0x1C9F, "M", "ჟ"), + (0x1CA0, "M", "რ"), + (0x1CA1, "M", "ს"), + (0x1CA2, "M", "ტ"), + (0x1CA3, "M", "უ"), + (0x1CA4, "M", "ფ"), + (0x1CA5, "M", "ქ"), + (0x1CA6, "M", "ღ"), + (0x1CA7, "M", "ყ"), + (0x1CA8, "M", "შ"), + (0x1CA9, "M", "ჩ"), + (0x1CAA, "M", "ც"), + (0x1CAB, "M", "ძ"), + (0x1CAC, "M", "წ"), + (0x1CAD, "M", "ჭ"), + (0x1CAE, "M", "ხ"), + (0x1CAF, "M", "ჯ"), + (0x1CB0, "M", "ჰ"), + (0x1CB1, "M", "ჱ"), + (0x1CB2, "M", "ჲ"), + (0x1CB3, "M", "ჳ"), + (0x1CB4, "M", "ჴ"), + (0x1CB5, "M", "ჵ"), + (0x1CB6, "M", "ჶ"), + (0x1CB7, "M", "ჷ"), + (0x1CB8, "M", "ჸ"), + (0x1CB9, "M", "ჹ"), + (0x1CBA, "M", "ჺ"), + (0x1CBB, "X"), + (0x1CBD, "M", "ჽ"), + (0x1CBE, "M", "ჾ"), + (0x1CBF, "M", "ჿ"), + (0x1CC0, "V"), + (0x1CC8, "X"), + (0x1CD0, "V"), + (0x1CFB, "X"), + (0x1D00, "V"), + (0x1D2C, "M", "a"), + (0x1D2D, "M", "æ"), + (0x1D2E, "M", "b"), + (0x1D2F, "V"), + (0x1D30, "M", "d"), + (0x1D31, "M", "e"), + ] + + +def _seg_16() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0x1D32, "M", "ǝ"), + (0x1D33, "M", "g"), + (0x1D34, "M", "h"), + (0x1D35, "M", "i"), + (0x1D36, "M", "j"), + (0x1D37, "M", "k"), + (0x1D38, "M", "l"), + (0x1D39, "M", "m"), + (0x1D3A, "M", "n"), + (0x1D3B, "V"), + (0x1D3C, "M", "o"), + (0x1D3D, "M", "ȣ"), + (0x1D3E, "M", "p"), + (0x1D3F, "M", "r"), + (0x1D40, "M", "t"), + (0x1D41, "M", "u"), + (0x1D42, "M", "w"), + (0x1D43, "M", "a"), + (0x1D44, "M", "ɐ"), + (0x1D45, "M", "ɑ"), + (0x1D46, "M", "ᴂ"), + (0x1D47, "M", "b"), + (0x1D48, "M", "d"), + (0x1D49, "M", "e"), + (0x1D4A, "M", "ə"), + (0x1D4B, "M", "ɛ"), + (0x1D4C, "M", "ɜ"), + (0x1D4D, "M", "g"), + (0x1D4E, "V"), + (0x1D4F, "M", "k"), + (0x1D50, "M", "m"), + (0x1D51, "M", "ŋ"), + (0x1D52, "M", "o"), + (0x1D53, "M", "ɔ"), + (0x1D54, "M", "ᴖ"), + (0x1D55, "M", "ᴗ"), + (0x1D56, "M", "p"), + (0x1D57, "M", "t"), + (0x1D58, "M", "u"), + (0x1D59, "M", "ᴝ"), + (0x1D5A, "M", "ɯ"), + (0x1D5B, "M", "v"), + (0x1D5C, "M", "ᴥ"), + (0x1D5D, "M", "β"), + (0x1D5E, "M", "γ"), + (0x1D5F, "M", "δ"), + (0x1D60, "M", "φ"), + (0x1D61, "M", "χ"), + (0x1D62, "M", "i"), + (0x1D63, "M", "r"), + (0x1D64, "M", "u"), + (0x1D65, "M", "v"), + (0x1D66, "M", "β"), + (0x1D67, "M", "γ"), + (0x1D68, "M", "ρ"), + (0x1D69, "M", "φ"), + (0x1D6A, "M", "χ"), + (0x1D6B, "V"), + (0x1D78, "M", "н"), + (0x1D79, "V"), + (0x1D9B, "M", "ɒ"), + (0x1D9C, "M", "c"), + (0x1D9D, "M", "ɕ"), + (0x1D9E, "M", "ð"), + (0x1D9F, "M", "ɜ"), + (0x1DA0, "M", "f"), + (0x1DA1, "M", "ɟ"), + (0x1DA2, "M", "ɡ"), + (0x1DA3, "M", "ɥ"), + (0x1DA4, "M", "ɨ"), + (0x1DA5, "M", "ɩ"), + (0x1DA6, "M", "ɪ"), + (0x1DA7, "M", "ᵻ"), + (0x1DA8, "M", "ʝ"), + (0x1DA9, "M", "ɭ"), + (0x1DAA, "M", "ᶅ"), + (0x1DAB, "M", "ʟ"), + (0x1DAC, "M", "ɱ"), + (0x1DAD, "M", "ɰ"), + (0x1DAE, "M", "ɲ"), + (0x1DAF, "M", "ɳ"), + (0x1DB0, "M", "ɴ"), + (0x1DB1, "M", "ɵ"), + (0x1DB2, "M", "ɸ"), + (0x1DB3, "M", "ʂ"), + (0x1DB4, "M", "ʃ"), + (0x1DB5, "M", "ƫ"), + (0x1DB6, "M", "ʉ"), + (0x1DB7, "M", "ʊ"), + (0x1DB8, "M", "ᴜ"), + (0x1DB9, "M", "ʋ"), + (0x1DBA, "M", "ʌ"), + (0x1DBB, "M", "z"), + (0x1DBC, "M", "ʐ"), + (0x1DBD, "M", "ʑ"), + (0x1DBE, "M", "ʒ"), + (0x1DBF, "M", "θ"), + (0x1DC0, "V"), + (0x1E00, "M", "ḁ"), + (0x1E01, "V"), + ] + + +def _seg_17() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0x1E02, "M", "ḃ"), + (0x1E03, "V"), + (0x1E04, "M", "ḅ"), + (0x1E05, "V"), + (0x1E06, "M", "ḇ"), + (0x1E07, "V"), + (0x1E08, "M", "ḉ"), + (0x1E09, "V"), + (0x1E0A, "M", "ḋ"), + (0x1E0B, "V"), + (0x1E0C, "M", "ḍ"), + (0x1E0D, "V"), + (0x1E0E, "M", "ḏ"), + (0x1E0F, "V"), + (0x1E10, "M", "ḑ"), + (0x1E11, "V"), + (0x1E12, "M", "ḓ"), + (0x1E13, "V"), + (0x1E14, "M", "ḕ"), + (0x1E15, "V"), + (0x1E16, "M", "ḗ"), + (0x1E17, "V"), + (0x1E18, "M", "ḙ"), + (0x1E19, "V"), + (0x1E1A, "M", "ḛ"), + (0x1E1B, "V"), + (0x1E1C, "M", "ḝ"), + (0x1E1D, "V"), + (0x1E1E, "M", "ḟ"), + (0x1E1F, "V"), + (0x1E20, "M", "ḡ"), + (0x1E21, "V"), + (0x1E22, "M", "ḣ"), + (0x1E23, "V"), + (0x1E24, "M", "ḥ"), + (0x1E25, "V"), + (0x1E26, "M", "ḧ"), + (0x1E27, "V"), + (0x1E28, "M", "ḩ"), + (0x1E29, "V"), + (0x1E2A, "M", "ḫ"), + (0x1E2B, "V"), + (0x1E2C, "M", "ḭ"), + (0x1E2D, "V"), + (0x1E2E, "M", "ḯ"), + (0x1E2F, "V"), + (0x1E30, "M", "ḱ"), + (0x1E31, "V"), + (0x1E32, "M", "ḳ"), + (0x1E33, "V"), + (0x1E34, "M", "ḵ"), + (0x1E35, "V"), + (0x1E36, "M", "ḷ"), + (0x1E37, "V"), + (0x1E38, "M", "ḹ"), + (0x1E39, "V"), + (0x1E3A, "M", "ḻ"), + (0x1E3B, "V"), + (0x1E3C, "M", "ḽ"), + (0x1E3D, "V"), + (0x1E3E, "M", "ḿ"), + (0x1E3F, "V"), + (0x1E40, "M", "ṁ"), + (0x1E41, "V"), + (0x1E42, "M", "ṃ"), + (0x1E43, "V"), + (0x1E44, "M", "ṅ"), + (0x1E45, "V"), + (0x1E46, "M", "ṇ"), + (0x1E47, "V"), + (0x1E48, "M", "ṉ"), + (0x1E49, "V"), + (0x1E4A, "M", "ṋ"), + (0x1E4B, "V"), + (0x1E4C, "M", "ṍ"), + (0x1E4D, "V"), + (0x1E4E, "M", "ṏ"), + (0x1E4F, "V"), + (0x1E50, "M", "ṑ"), + (0x1E51, "V"), + (0x1E52, "M", "ṓ"), + (0x1E53, "V"), + (0x1E54, "M", "ṕ"), + (0x1E55, "V"), + (0x1E56, "M", "ṗ"), + (0x1E57, "V"), + (0x1E58, "M", "ṙ"), + (0x1E59, "V"), + (0x1E5A, "M", "ṛ"), + (0x1E5B, "V"), + (0x1E5C, "M", "ṝ"), + (0x1E5D, "V"), + (0x1E5E, "M", "ṟ"), + (0x1E5F, "V"), + (0x1E60, "M", "ṡ"), + (0x1E61, "V"), + (0x1E62, "M", "ṣ"), + (0x1E63, "V"), + (0x1E64, "M", "ṥ"), + (0x1E65, "V"), + ] + + +def _seg_18() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0x1E66, "M", "ṧ"), + (0x1E67, "V"), + (0x1E68, "M", "ṩ"), + (0x1E69, "V"), + (0x1E6A, "M", "ṫ"), + (0x1E6B, "V"), + (0x1E6C, "M", "ṭ"), + (0x1E6D, "V"), + (0x1E6E, "M", "ṯ"), + (0x1E6F, "V"), + (0x1E70, "M", "ṱ"), + (0x1E71, "V"), + (0x1E72, "M", "ṳ"), + (0x1E73, "V"), + (0x1E74, "M", "ṵ"), + (0x1E75, "V"), + (0x1E76, "M", "ṷ"), + (0x1E77, "V"), + (0x1E78, "M", "ṹ"), + (0x1E79, "V"), + (0x1E7A, "M", "ṻ"), + (0x1E7B, "V"), + (0x1E7C, "M", "ṽ"), + (0x1E7D, "V"), + (0x1E7E, "M", "ṿ"), + (0x1E7F, "V"), + (0x1E80, "M", "ẁ"), + (0x1E81, "V"), + (0x1E82, "M", "ẃ"), + (0x1E83, "V"), + (0x1E84, "M", "ẅ"), + (0x1E85, "V"), + (0x1E86, "M", "ẇ"), + (0x1E87, "V"), + (0x1E88, "M", "ẉ"), + (0x1E89, "V"), + (0x1E8A, "M", "ẋ"), + (0x1E8B, "V"), + (0x1E8C, "M", "ẍ"), + (0x1E8D, "V"), + (0x1E8E, "M", "ẏ"), + (0x1E8F, "V"), + (0x1E90, "M", "ẑ"), + (0x1E91, "V"), + (0x1E92, "M", "ẓ"), + (0x1E93, "V"), + (0x1E94, "M", "ẕ"), + (0x1E95, "V"), + (0x1E9A, "M", "aʾ"), + (0x1E9B, "M", "ṡ"), + (0x1E9C, "V"), + (0x1E9E, "M", "ß"), + (0x1E9F, "V"), + (0x1EA0, "M", "ạ"), + (0x1EA1, "V"), + (0x1EA2, "M", "ả"), + (0x1EA3, "V"), + (0x1EA4, "M", "ấ"), + (0x1EA5, "V"), + (0x1EA6, "M", "ầ"), + (0x1EA7, "V"), + (0x1EA8, "M", "ẩ"), + (0x1EA9, "V"), + (0x1EAA, "M", "ẫ"), + (0x1EAB, "V"), + (0x1EAC, "M", "ậ"), + (0x1EAD, "V"), + (0x1EAE, "M", "ắ"), + (0x1EAF, "V"), + (0x1EB0, "M", "ằ"), + (0x1EB1, "V"), + (0x1EB2, "M", "ẳ"), + (0x1EB3, "V"), + (0x1EB4, "M", "ẵ"), + (0x1EB5, "V"), + (0x1EB6, "M", "ặ"), + (0x1EB7, "V"), + (0x1EB8, "M", "ẹ"), + (0x1EB9, "V"), + (0x1EBA, "M", "ẻ"), + (0x1EBB, "V"), + (0x1EBC, "M", "ẽ"), + (0x1EBD, "V"), + (0x1EBE, "M", "ế"), + (0x1EBF, "V"), + (0x1EC0, "M", "ề"), + (0x1EC1, "V"), + (0x1EC2, "M", "ể"), + (0x1EC3, "V"), + (0x1EC4, "M", "ễ"), + (0x1EC5, "V"), + (0x1EC6, "M", "ệ"), + (0x1EC7, "V"), + (0x1EC8, "M", "ỉ"), + (0x1EC9, "V"), + (0x1ECA, "M", "ị"), + (0x1ECB, "V"), + (0x1ECC, "M", "ọ"), + (0x1ECD, "V"), + (0x1ECE, "M", "ỏ"), + ] + + +def _seg_19() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0x1ECF, "V"), + (0x1ED0, "M", "ố"), + (0x1ED1, "V"), + (0x1ED2, "M", "ồ"), + (0x1ED3, "V"), + (0x1ED4, "M", "ổ"), + (0x1ED5, "V"), + (0x1ED6, "M", "ỗ"), + (0x1ED7, "V"), + (0x1ED8, "M", "ộ"), + (0x1ED9, "V"), + (0x1EDA, "M", "ớ"), + (0x1EDB, "V"), + (0x1EDC, "M", "ờ"), + (0x1EDD, "V"), + (0x1EDE, "M", "ở"), + (0x1EDF, "V"), + (0x1EE0, "M", "ỡ"), + (0x1EE1, "V"), + (0x1EE2, "M", "ợ"), + (0x1EE3, "V"), + (0x1EE4, "M", "ụ"), + (0x1EE5, "V"), + (0x1EE6, "M", "ủ"), + (0x1EE7, "V"), + (0x1EE8, "M", "ứ"), + (0x1EE9, "V"), + (0x1EEA, "M", "ừ"), + (0x1EEB, "V"), + (0x1EEC, "M", "ử"), + (0x1EED, "V"), + (0x1EEE, "M", "ữ"), + (0x1EEF, "V"), + (0x1EF0, "M", "ự"), + (0x1EF1, "V"), + (0x1EF2, "M", "ỳ"), + (0x1EF3, "V"), + (0x1EF4, "M", "ỵ"), + (0x1EF5, "V"), + (0x1EF6, "M", "ỷ"), + (0x1EF7, "V"), + (0x1EF8, "M", "ỹ"), + (0x1EF9, "V"), + (0x1EFA, "M", "ỻ"), + (0x1EFB, "V"), + (0x1EFC, "M", "ỽ"), + (0x1EFD, "V"), + (0x1EFE, "M", "ỿ"), + (0x1EFF, "V"), + (0x1F08, "M", "ἀ"), + (0x1F09, "M", "ἁ"), + (0x1F0A, "M", "ἂ"), + (0x1F0B, "M", "ἃ"), + (0x1F0C, "M", "ἄ"), + (0x1F0D, "M", "ἅ"), + (0x1F0E, "M", "ἆ"), + (0x1F0F, "M", "ἇ"), + (0x1F10, "V"), + (0x1F16, "X"), + (0x1F18, "M", "ἐ"), + (0x1F19, "M", "ἑ"), + (0x1F1A, "M", "ἒ"), + (0x1F1B, "M", "ἓ"), + (0x1F1C, "M", "ἔ"), + (0x1F1D, "M", "ἕ"), + (0x1F1E, "X"), + (0x1F20, "V"), + (0x1F28, "M", "ἠ"), + (0x1F29, "M", "ἡ"), + (0x1F2A, "M", "ἢ"), + (0x1F2B, "M", "ἣ"), + (0x1F2C, "M", "ἤ"), + (0x1F2D, "M", "ἥ"), + (0x1F2E, "M", "ἦ"), + (0x1F2F, "M", "ἧ"), + (0x1F30, "V"), + (0x1F38, "M", "ἰ"), + (0x1F39, "M", "ἱ"), + (0x1F3A, "M", "ἲ"), + (0x1F3B, "M", "ἳ"), + (0x1F3C, "M", "ἴ"), + (0x1F3D, "M", "ἵ"), + (0x1F3E, "M", "ἶ"), + (0x1F3F, "M", "ἷ"), + (0x1F40, "V"), + (0x1F46, "X"), + (0x1F48, "M", "ὀ"), + (0x1F49, "M", "ὁ"), + (0x1F4A, "M", "ὂ"), + (0x1F4B, "M", "ὃ"), + (0x1F4C, "M", "ὄ"), + (0x1F4D, "M", "ὅ"), + (0x1F4E, "X"), + (0x1F50, "V"), + (0x1F58, "X"), + (0x1F59, "M", "ὑ"), + (0x1F5A, "X"), + (0x1F5B, "M", "ὓ"), + (0x1F5C, "X"), + (0x1F5D, "M", "ὕ"), + ] + + +def _seg_20() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0x1F5E, "X"), + (0x1F5F, "M", "ὗ"), + (0x1F60, "V"), + (0x1F68, "M", "ὠ"), + (0x1F69, "M", "ὡ"), + (0x1F6A, "M", "ὢ"), + (0x1F6B, "M", "ὣ"), + (0x1F6C, "M", "ὤ"), + (0x1F6D, "M", "ὥ"), + (0x1F6E, "M", "ὦ"), + (0x1F6F, "M", "ὧ"), + (0x1F70, "V"), + (0x1F71, "M", "ά"), + (0x1F72, "V"), + (0x1F73, "M", "έ"), + (0x1F74, "V"), + (0x1F75, "M", "ή"), + (0x1F76, "V"), + (0x1F77, "M", "ί"), + (0x1F78, "V"), + (0x1F79, "M", "ό"), + (0x1F7A, "V"), + (0x1F7B, "M", "ύ"), + (0x1F7C, "V"), + (0x1F7D, "M", "ώ"), + (0x1F7E, "X"), + (0x1F80, "M", "ἀι"), + (0x1F81, "M", "ἁι"), + (0x1F82, "M", "ἂι"), + (0x1F83, "M", "ἃι"), + (0x1F84, "M", "ἄι"), + (0x1F85, "M", "ἅι"), + (0x1F86, "M", "ἆι"), + (0x1F87, "M", "ἇι"), + (0x1F88, "M", "ἀι"), + (0x1F89, "M", "ἁι"), + (0x1F8A, "M", "ἂι"), + (0x1F8B, "M", "ἃι"), + (0x1F8C, "M", "ἄι"), + (0x1F8D, "M", "ἅι"), + (0x1F8E, "M", "ἆι"), + (0x1F8F, "M", "ἇι"), + (0x1F90, "M", "ἠι"), + (0x1F91, "M", "ἡι"), + (0x1F92, "M", "ἢι"), + (0x1F93, "M", "ἣι"), + (0x1F94, "M", "ἤι"), + (0x1F95, "M", "ἥι"), + (0x1F96, "M", "ἦι"), + (0x1F97, "M", "ἧι"), + (0x1F98, "M", "ἠι"), + (0x1F99, "M", "ἡι"), + (0x1F9A, "M", "ἢι"), + (0x1F9B, "M", "ἣι"), + (0x1F9C, "M", "ἤι"), + (0x1F9D, "M", "ἥι"), + (0x1F9E, "M", "ἦι"), + (0x1F9F, "M", "ἧι"), + (0x1FA0, "M", "ὠι"), + (0x1FA1, "M", "ὡι"), + (0x1FA2, "M", "ὢι"), + (0x1FA3, "M", "ὣι"), + (0x1FA4, "M", "ὤι"), + (0x1FA5, "M", "ὥι"), + (0x1FA6, "M", "ὦι"), + (0x1FA7, "M", "ὧι"), + (0x1FA8, "M", "ὠι"), + (0x1FA9, "M", "ὡι"), + (0x1FAA, "M", "ὢι"), + (0x1FAB, "M", "ὣι"), + (0x1FAC, "M", "ὤι"), + (0x1FAD, "M", "ὥι"), + (0x1FAE, "M", "ὦι"), + (0x1FAF, "M", "ὧι"), + (0x1FB0, "V"), + (0x1FB2, "M", "ὰι"), + (0x1FB3, "M", "αι"), + (0x1FB4, "M", "άι"), + (0x1FB5, "X"), + (0x1FB6, "V"), + (0x1FB7, "M", "ᾶι"), + (0x1FB8, "M", "ᾰ"), + (0x1FB9, "M", "ᾱ"), + (0x1FBA, "M", "ὰ"), + (0x1FBB, "M", "ά"), + (0x1FBC, "M", "αι"), + (0x1FBD, "M", " ̓"), + (0x1FBE, "M", "ι"), + (0x1FBF, "M", " ̓"), + (0x1FC0, "M", " ͂"), + (0x1FC1, "M", " ̈͂"), + (0x1FC2, "M", "ὴι"), + (0x1FC3, "M", "ηι"), + (0x1FC4, "M", "ήι"), + (0x1FC5, "X"), + (0x1FC6, "V"), + (0x1FC7, "M", "ῆι"), + (0x1FC8, "M", "ὲ"), + (0x1FC9, "M", "έ"), + (0x1FCA, "M", "ὴ"), + ] + + +def _seg_21() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0x1FCB, "M", "ή"), + (0x1FCC, "M", "ηι"), + (0x1FCD, "M", " ̓̀"), + (0x1FCE, "M", " ̓́"), + (0x1FCF, "M", " ̓͂"), + (0x1FD0, "V"), + (0x1FD3, "M", "ΐ"), + (0x1FD4, "X"), + (0x1FD6, "V"), + (0x1FD8, "M", "ῐ"), + (0x1FD9, "M", "ῑ"), + (0x1FDA, "M", "ὶ"), + (0x1FDB, "M", "ί"), + (0x1FDC, "X"), + (0x1FDD, "M", " ̔̀"), + (0x1FDE, "M", " ̔́"), + (0x1FDF, "M", " ̔͂"), + (0x1FE0, "V"), + (0x1FE3, "M", "ΰ"), + (0x1FE4, "V"), + (0x1FE8, "M", "ῠ"), + (0x1FE9, "M", "ῡ"), + (0x1FEA, "M", "ὺ"), + (0x1FEB, "M", "ύ"), + (0x1FEC, "M", "ῥ"), + (0x1FED, "M", " ̈̀"), + (0x1FEE, "M", " ̈́"), + (0x1FEF, "M", "`"), + (0x1FF0, "X"), + (0x1FF2, "M", "ὼι"), + (0x1FF3, "M", "ωι"), + (0x1FF4, "M", "ώι"), + (0x1FF5, "X"), + (0x1FF6, "V"), + (0x1FF7, "M", "ῶι"), + (0x1FF8, "M", "ὸ"), + (0x1FF9, "M", "ό"), + (0x1FFA, "M", "ὼ"), + (0x1FFB, "M", "ώ"), + (0x1FFC, "M", "ωι"), + (0x1FFD, "M", " ́"), + (0x1FFE, "M", " ̔"), + (0x1FFF, "X"), + (0x2000, "M", " "), + (0x200B, "I"), + (0x200C, "D", ""), + (0x200E, "X"), + (0x2010, "V"), + (0x2011, "M", "‐"), + (0x2012, "V"), + (0x2017, "M", " ̳"), + (0x2018, "V"), + (0x2024, "X"), + (0x2027, "V"), + (0x2028, "X"), + (0x202F, "M", " "), + (0x2030, "V"), + (0x2033, "M", "′′"), + (0x2034, "M", "′′′"), + (0x2035, "V"), + (0x2036, "M", "‵‵"), + (0x2037, "M", "‵‵‵"), + (0x2038, "V"), + (0x203C, "M", "!!"), + (0x203D, "V"), + (0x203E, "M", " ̅"), + (0x203F, "V"), + (0x2047, "M", "??"), + (0x2048, "M", "?!"), + (0x2049, "M", "!?"), + (0x204A, "V"), + (0x2057, "M", "′′′′"), + (0x2058, "V"), + (0x205F, "M", " "), + (0x2060, "I"), + (0x2065, "X"), + (0x206A, "I"), + (0x2070, "M", "0"), + (0x2071, "M", "i"), + (0x2072, "X"), + (0x2074, "M", "4"), + (0x2075, "M", "5"), + (0x2076, "M", "6"), + (0x2077, "M", "7"), + (0x2078, "M", "8"), + (0x2079, "M", "9"), + (0x207A, "M", "+"), + (0x207B, "M", "−"), + (0x207C, "M", "="), + (0x207D, "M", "("), + (0x207E, "M", ")"), + (0x207F, "M", "n"), + (0x2080, "M", "0"), + (0x2081, "M", "1"), + (0x2082, "M", "2"), + (0x2083, "M", "3"), + (0x2084, "M", "4"), + (0x2085, "M", "5"), + (0x2086, "M", "6"), + (0x2087, "M", "7"), + ] + + +def _seg_22() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0x2088, "M", "8"), + (0x2089, "M", "9"), + (0x208A, "M", "+"), + (0x208B, "M", "−"), + (0x208C, "M", "="), + (0x208D, "M", "("), + (0x208E, "M", ")"), + (0x208F, "X"), + (0x2090, "M", "a"), + (0x2091, "M", "e"), + (0x2092, "M", "o"), + (0x2093, "M", "x"), + (0x2094, "M", "ə"), + (0x2095, "M", "h"), + (0x2096, "M", "k"), + (0x2097, "M", "l"), + (0x2098, "M", "m"), + (0x2099, "M", "n"), + (0x209A, "M", "p"), + (0x209B, "M", "s"), + (0x209C, "M", "t"), + (0x209D, "X"), + (0x20A0, "V"), + (0x20A8, "M", "rs"), + (0x20A9, "V"), + (0x20C1, "X"), + (0x20D0, "V"), + (0x20F1, "X"), + (0x2100, "M", "a/c"), + (0x2101, "M", "a/s"), + (0x2102, "M", "c"), + (0x2103, "M", "°c"), + (0x2104, "V"), + (0x2105, "M", "c/o"), + (0x2106, "M", "c/u"), + (0x2107, "M", "ɛ"), + (0x2108, "V"), + (0x2109, "M", "°f"), + (0x210A, "M", "g"), + (0x210B, "M", "h"), + (0x210F, "M", "ħ"), + (0x2110, "M", "i"), + (0x2112, "M", "l"), + (0x2114, "V"), + (0x2115, "M", "n"), + (0x2116, "M", "no"), + (0x2117, "V"), + (0x2119, "M", "p"), + (0x211A, "M", "q"), + (0x211B, "M", "r"), + (0x211E, "V"), + (0x2120, "M", "sm"), + (0x2121, "M", "tel"), + (0x2122, "M", "tm"), + (0x2123, "V"), + (0x2124, "M", "z"), + (0x2125, "V"), + (0x2126, "M", "ω"), + (0x2127, "V"), + (0x2128, "M", "z"), + (0x2129, "V"), + (0x212A, "M", "k"), + (0x212B, "M", "å"), + (0x212C, "M", "b"), + (0x212D, "M", "c"), + (0x212E, "V"), + (0x212F, "M", "e"), + (0x2131, "M", "f"), + (0x2132, "M", "ⅎ"), + (0x2133, "M", "m"), + (0x2134, "M", "o"), + (0x2135, "M", "א"), + (0x2136, "M", "ב"), + (0x2137, "M", "ג"), + (0x2138, "M", "ד"), + (0x2139, "M", "i"), + (0x213A, "V"), + (0x213B, "M", "fax"), + (0x213C, "M", "π"), + (0x213D, "M", "γ"), + (0x213F, "M", "π"), + (0x2140, "M", "∑"), + (0x2141, "V"), + (0x2145, "M", "d"), + (0x2147, "M", "e"), + (0x2148, "M", "i"), + (0x2149, "M", "j"), + (0x214A, "V"), + (0x2150, "M", "1⁄7"), + (0x2151, "M", "1⁄9"), + (0x2152, "M", "1⁄10"), + (0x2153, "M", "1⁄3"), + (0x2154, "M", "2⁄3"), + (0x2155, "M", "1⁄5"), + (0x2156, "M", "2⁄5"), + (0x2157, "M", "3⁄5"), + (0x2158, "M", "4⁄5"), + (0x2159, "M", "1⁄6"), + (0x215A, "M", "5⁄6"), + (0x215B, "M", "1⁄8"), + ] + + +def _seg_23() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0x215C, "M", "3⁄8"), + (0x215D, "M", "5⁄8"), + (0x215E, "M", "7⁄8"), + (0x215F, "M", "1⁄"), + (0x2160, "M", "i"), + (0x2161, "M", "ii"), + (0x2162, "M", "iii"), + (0x2163, "M", "iv"), + (0x2164, "M", "v"), + (0x2165, "M", "vi"), + (0x2166, "M", "vii"), + (0x2167, "M", "viii"), + (0x2168, "M", "ix"), + (0x2169, "M", "x"), + (0x216A, "M", "xi"), + (0x216B, "M", "xii"), + (0x216C, "M", "l"), + (0x216D, "M", "c"), + (0x216E, "M", "d"), + (0x216F, "M", "m"), + (0x2170, "M", "i"), + (0x2171, "M", "ii"), + (0x2172, "M", "iii"), + (0x2173, "M", "iv"), + (0x2174, "M", "v"), + (0x2175, "M", "vi"), + (0x2176, "M", "vii"), + (0x2177, "M", "viii"), + (0x2178, "M", "ix"), + (0x2179, "M", "x"), + (0x217A, "M", "xi"), + (0x217B, "M", "xii"), + (0x217C, "M", "l"), + (0x217D, "M", "c"), + (0x217E, "M", "d"), + (0x217F, "M", "m"), + (0x2180, "V"), + (0x2183, "M", "ↄ"), + (0x2184, "V"), + (0x2189, "M", "0⁄3"), + (0x218A, "V"), + (0x218C, "X"), + (0x2190, "V"), + (0x222C, "M", "∫∫"), + (0x222D, "M", "∫∫∫"), + (0x222E, "V"), + (0x222F, "M", "∮∮"), + (0x2230, "M", "∮∮∮"), + (0x2231, "V"), + (0x2329, "M", "〈"), + (0x232A, "M", "〉"), + (0x232B, "V"), + (0x242A, "X"), + (0x2440, "V"), + (0x244B, "X"), + (0x2460, "M", "1"), + (0x2461, "M", "2"), + (0x2462, "M", "3"), + (0x2463, "M", "4"), + (0x2464, "M", "5"), + (0x2465, "M", "6"), + (0x2466, "M", "7"), + (0x2467, "M", "8"), + (0x2468, "M", "9"), + (0x2469, "M", "10"), + (0x246A, "M", "11"), + (0x246B, "M", "12"), + (0x246C, "M", "13"), + (0x246D, "M", "14"), + (0x246E, "M", "15"), + (0x246F, "M", "16"), + (0x2470, "M", "17"), + (0x2471, "M", "18"), + (0x2472, "M", "19"), + (0x2473, "M", "20"), + (0x2474, "M", "(1)"), + (0x2475, "M", "(2)"), + (0x2476, "M", "(3)"), + (0x2477, "M", "(4)"), + (0x2478, "M", "(5)"), + (0x2479, "M", "(6)"), + (0x247A, "M", "(7)"), + (0x247B, "M", "(8)"), + (0x247C, "M", "(9)"), + (0x247D, "M", "(10)"), + (0x247E, "M", "(11)"), + (0x247F, "M", "(12)"), + (0x2480, "M", "(13)"), + (0x2481, "M", "(14)"), + (0x2482, "M", "(15)"), + (0x2483, "M", "(16)"), + (0x2484, "M", "(17)"), + (0x2485, "M", "(18)"), + (0x2486, "M", "(19)"), + (0x2487, "M", "(20)"), + (0x2488, "X"), + (0x249C, "M", "(a)"), + (0x249D, "M", "(b)"), + (0x249E, "M", "(c)"), + (0x249F, "M", "(d)"), + ] + + +def _seg_24() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0x24A0, "M", "(e)"), + (0x24A1, "M", "(f)"), + (0x24A2, "M", "(g)"), + (0x24A3, "M", "(h)"), + (0x24A4, "M", "(i)"), + (0x24A5, "M", "(j)"), + (0x24A6, "M", "(k)"), + (0x24A7, "M", "(l)"), + (0x24A8, "M", "(m)"), + (0x24A9, "M", "(n)"), + (0x24AA, "M", "(o)"), + (0x24AB, "M", "(p)"), + (0x24AC, "M", "(q)"), + (0x24AD, "M", "(r)"), + (0x24AE, "M", "(s)"), + (0x24AF, "M", "(t)"), + (0x24B0, "M", "(u)"), + (0x24B1, "M", "(v)"), + (0x24B2, "M", "(w)"), + (0x24B3, "M", "(x)"), + (0x24B4, "M", "(y)"), + (0x24B5, "M", "(z)"), + (0x24B6, "M", "a"), + (0x24B7, "M", "b"), + (0x24B8, "M", "c"), + (0x24B9, "M", "d"), + (0x24BA, "M", "e"), + (0x24BB, "M", "f"), + (0x24BC, "M", "g"), + (0x24BD, "M", "h"), + (0x24BE, "M", "i"), + (0x24BF, "M", "j"), + (0x24C0, "M", "k"), + (0x24C1, "M", "l"), + (0x24C2, "M", "m"), + (0x24C3, "M", "n"), + (0x24C4, "M", "o"), + (0x24C5, "M", "p"), + (0x24C6, "M", "q"), + (0x24C7, "M", "r"), + (0x24C8, "M", "s"), + (0x24C9, "M", "t"), + (0x24CA, "M", "u"), + (0x24CB, "M", "v"), + (0x24CC, "M", "w"), + (0x24CD, "M", "x"), + (0x24CE, "M", "y"), + (0x24CF, "M", "z"), + (0x24D0, "M", "a"), + (0x24D1, "M", "b"), + (0x24D2, "M", "c"), + (0x24D3, "M", "d"), + (0x24D4, "M", "e"), + (0x24D5, "M", "f"), + (0x24D6, "M", "g"), + (0x24D7, "M", "h"), + (0x24D8, "M", "i"), + (0x24D9, "M", "j"), + (0x24DA, "M", "k"), + (0x24DB, "M", "l"), + (0x24DC, "M", "m"), + (0x24DD, "M", "n"), + (0x24DE, "M", "o"), + (0x24DF, "M", "p"), + (0x24E0, "M", "q"), + (0x24E1, "M", "r"), + (0x24E2, "M", "s"), + (0x24E3, "M", "t"), + (0x24E4, "M", "u"), + (0x24E5, "M", "v"), + (0x24E6, "M", "w"), + (0x24E7, "M", "x"), + (0x24E8, "M", "y"), + (0x24E9, "M", "z"), + (0x24EA, "M", "0"), + (0x24EB, "V"), + (0x2A0C, "M", "∫∫∫∫"), + (0x2A0D, "V"), + (0x2A74, "M", "::="), + (0x2A75, "M", "=="), + (0x2A76, "M", "==="), + (0x2A77, "V"), + (0x2ADC, "M", "⫝̸"), + (0x2ADD, "V"), + (0x2B74, "X"), + (0x2B76, "V"), + (0x2B96, "X"), + (0x2B97, "V"), + (0x2C00, "M", "ⰰ"), + (0x2C01, "M", "ⰱ"), + (0x2C02, "M", "ⰲ"), + (0x2C03, "M", "ⰳ"), + (0x2C04, "M", "ⰴ"), + (0x2C05, "M", "ⰵ"), + (0x2C06, "M", "ⰶ"), + (0x2C07, "M", "ⰷ"), + (0x2C08, "M", "ⰸ"), + (0x2C09, "M", "ⰹ"), + (0x2C0A, "M", "ⰺ"), + (0x2C0B, "M", "ⰻ"), + ] + + +def _seg_25() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0x2C0C, "M", "ⰼ"), + (0x2C0D, "M", "ⰽ"), + (0x2C0E, "M", "ⰾ"), + (0x2C0F, "M", "ⰿ"), + (0x2C10, "M", "ⱀ"), + (0x2C11, "M", "ⱁ"), + (0x2C12, "M", "ⱂ"), + (0x2C13, "M", "ⱃ"), + (0x2C14, "M", "ⱄ"), + (0x2C15, "M", "ⱅ"), + (0x2C16, "M", "ⱆ"), + (0x2C17, "M", "ⱇ"), + (0x2C18, "M", "ⱈ"), + (0x2C19, "M", "ⱉ"), + (0x2C1A, "M", "ⱊ"), + (0x2C1B, "M", "ⱋ"), + (0x2C1C, "M", "ⱌ"), + (0x2C1D, "M", "ⱍ"), + (0x2C1E, "M", "ⱎ"), + (0x2C1F, "M", "ⱏ"), + (0x2C20, "M", "ⱐ"), + (0x2C21, "M", "ⱑ"), + (0x2C22, "M", "ⱒ"), + (0x2C23, "M", "ⱓ"), + (0x2C24, "M", "ⱔ"), + (0x2C25, "M", "ⱕ"), + (0x2C26, "M", "ⱖ"), + (0x2C27, "M", "ⱗ"), + (0x2C28, "M", "ⱘ"), + (0x2C29, "M", "ⱙ"), + (0x2C2A, "M", "ⱚ"), + (0x2C2B, "M", "ⱛ"), + (0x2C2C, "M", "ⱜ"), + (0x2C2D, "M", "ⱝ"), + (0x2C2E, "M", "ⱞ"), + (0x2C2F, "M", "ⱟ"), + (0x2C30, "V"), + (0x2C60, "M", "ⱡ"), + (0x2C61, "V"), + (0x2C62, "M", "ɫ"), + (0x2C63, "M", "ᵽ"), + (0x2C64, "M", "ɽ"), + (0x2C65, "V"), + (0x2C67, "M", "ⱨ"), + (0x2C68, "V"), + (0x2C69, "M", "ⱪ"), + (0x2C6A, "V"), + (0x2C6B, "M", "ⱬ"), + (0x2C6C, "V"), + (0x2C6D, "M", "ɑ"), + (0x2C6E, "M", "ɱ"), + (0x2C6F, "M", "ɐ"), + (0x2C70, "M", "ɒ"), + (0x2C71, "V"), + (0x2C72, "M", "ⱳ"), + (0x2C73, "V"), + (0x2C75, "M", "ⱶ"), + (0x2C76, "V"), + (0x2C7C, "M", "j"), + (0x2C7D, "M", "v"), + (0x2C7E, "M", "ȿ"), + (0x2C7F, "M", "ɀ"), + (0x2C80, "M", "ⲁ"), + (0x2C81, "V"), + (0x2C82, "M", "ⲃ"), + (0x2C83, "V"), + (0x2C84, "M", "ⲅ"), + (0x2C85, "V"), + (0x2C86, "M", "ⲇ"), + (0x2C87, "V"), + (0x2C88, "M", "ⲉ"), + (0x2C89, "V"), + (0x2C8A, "M", "ⲋ"), + (0x2C8B, "V"), + (0x2C8C, "M", "ⲍ"), + (0x2C8D, "V"), + (0x2C8E, "M", "ⲏ"), + (0x2C8F, "V"), + (0x2C90, "M", "ⲑ"), + (0x2C91, "V"), + (0x2C92, "M", "ⲓ"), + (0x2C93, "V"), + (0x2C94, "M", "ⲕ"), + (0x2C95, "V"), + (0x2C96, "M", "ⲗ"), + (0x2C97, "V"), + (0x2C98, "M", "ⲙ"), + (0x2C99, "V"), + (0x2C9A, "M", "ⲛ"), + (0x2C9B, "V"), + (0x2C9C, "M", "ⲝ"), + (0x2C9D, "V"), + (0x2C9E, "M", "ⲟ"), + (0x2C9F, "V"), + (0x2CA0, "M", "ⲡ"), + (0x2CA1, "V"), + (0x2CA2, "M", "ⲣ"), + (0x2CA3, "V"), + (0x2CA4, "M", "ⲥ"), + (0x2CA5, "V"), + ] + + +def _seg_26() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0x2CA6, "M", "ⲧ"), + (0x2CA7, "V"), + (0x2CA8, "M", "ⲩ"), + (0x2CA9, "V"), + (0x2CAA, "M", "ⲫ"), + (0x2CAB, "V"), + (0x2CAC, "M", "ⲭ"), + (0x2CAD, "V"), + (0x2CAE, "M", "ⲯ"), + (0x2CAF, "V"), + (0x2CB0, "M", "ⲱ"), + (0x2CB1, "V"), + (0x2CB2, "M", "ⲳ"), + (0x2CB3, "V"), + (0x2CB4, "M", "ⲵ"), + (0x2CB5, "V"), + (0x2CB6, "M", "ⲷ"), + (0x2CB7, "V"), + (0x2CB8, "M", "ⲹ"), + (0x2CB9, "V"), + (0x2CBA, "M", "ⲻ"), + (0x2CBB, "V"), + (0x2CBC, "M", "ⲽ"), + (0x2CBD, "V"), + (0x2CBE, "M", "ⲿ"), + (0x2CBF, "V"), + (0x2CC0, "M", "ⳁ"), + (0x2CC1, "V"), + (0x2CC2, "M", "ⳃ"), + (0x2CC3, "V"), + (0x2CC4, "M", "ⳅ"), + (0x2CC5, "V"), + (0x2CC6, "M", "ⳇ"), + (0x2CC7, "V"), + (0x2CC8, "M", "ⳉ"), + (0x2CC9, "V"), + (0x2CCA, "M", "ⳋ"), + (0x2CCB, "V"), + (0x2CCC, "M", "ⳍ"), + (0x2CCD, "V"), + (0x2CCE, "M", "ⳏ"), + (0x2CCF, "V"), + (0x2CD0, "M", "ⳑ"), + (0x2CD1, "V"), + (0x2CD2, "M", "ⳓ"), + (0x2CD3, "V"), + (0x2CD4, "M", "ⳕ"), + (0x2CD5, "V"), + (0x2CD6, "M", "ⳗ"), + (0x2CD7, "V"), + (0x2CD8, "M", "ⳙ"), + (0x2CD9, "V"), + (0x2CDA, "M", "ⳛ"), + (0x2CDB, "V"), + (0x2CDC, "M", "ⳝ"), + (0x2CDD, "V"), + (0x2CDE, "M", "ⳟ"), + (0x2CDF, "V"), + (0x2CE0, "M", "ⳡ"), + (0x2CE1, "V"), + (0x2CE2, "M", "ⳣ"), + (0x2CE3, "V"), + (0x2CEB, "M", "ⳬ"), + (0x2CEC, "V"), + (0x2CED, "M", "ⳮ"), + (0x2CEE, "V"), + (0x2CF2, "M", "ⳳ"), + (0x2CF3, "V"), + (0x2CF4, "X"), + (0x2CF9, "V"), + (0x2D26, "X"), + (0x2D27, "V"), + (0x2D28, "X"), + (0x2D2D, "V"), + (0x2D2E, "X"), + (0x2D30, "V"), + (0x2D68, "X"), + (0x2D6F, "M", "ⵡ"), + (0x2D70, "V"), + (0x2D71, "X"), + (0x2D7F, "V"), + (0x2D97, "X"), + (0x2DA0, "V"), + (0x2DA7, "X"), + (0x2DA8, "V"), + (0x2DAF, "X"), + (0x2DB0, "V"), + (0x2DB7, "X"), + (0x2DB8, "V"), + (0x2DBF, "X"), + (0x2DC0, "V"), + (0x2DC7, "X"), + (0x2DC8, "V"), + (0x2DCF, "X"), + (0x2DD0, "V"), + (0x2DD7, "X"), + (0x2DD8, "V"), + (0x2DDF, "X"), + (0x2DE0, "V"), + (0x2E5E, "X"), + ] + + +def _seg_27() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0x2E80, "V"), + (0x2E9A, "X"), + (0x2E9B, "V"), + (0x2E9F, "M", "母"), + (0x2EA0, "V"), + (0x2EF3, "M", "龟"), + (0x2EF4, "X"), + (0x2F00, "M", "一"), + (0x2F01, "M", "丨"), + (0x2F02, "M", "丶"), + (0x2F03, "M", "丿"), + (0x2F04, "M", "乙"), + (0x2F05, "M", "亅"), + (0x2F06, "M", "二"), + (0x2F07, "M", "亠"), + (0x2F08, "M", "人"), + (0x2F09, "M", "儿"), + (0x2F0A, "M", "入"), + (0x2F0B, "M", "八"), + (0x2F0C, "M", "冂"), + (0x2F0D, "M", "冖"), + (0x2F0E, "M", "冫"), + (0x2F0F, "M", "几"), + (0x2F10, "M", "凵"), + (0x2F11, "M", "刀"), + (0x2F12, "M", "力"), + (0x2F13, "M", "勹"), + (0x2F14, "M", "匕"), + (0x2F15, "M", "匚"), + (0x2F16, "M", "匸"), + (0x2F17, "M", "十"), + (0x2F18, "M", "卜"), + (0x2F19, "M", "卩"), + (0x2F1A, "M", "厂"), + (0x2F1B, "M", "厶"), + (0x2F1C, "M", "又"), + (0x2F1D, "M", "口"), + (0x2F1E, "M", "囗"), + (0x2F1F, "M", "土"), + (0x2F20, "M", "士"), + (0x2F21, "M", "夂"), + (0x2F22, "M", "夊"), + (0x2F23, "M", "夕"), + (0x2F24, "M", "大"), + (0x2F25, "M", "女"), + (0x2F26, "M", "子"), + (0x2F27, "M", "宀"), + (0x2F28, "M", "寸"), + (0x2F29, "M", "小"), + (0x2F2A, "M", "尢"), + (0x2F2B, "M", "尸"), + (0x2F2C, "M", "屮"), + (0x2F2D, "M", "山"), + (0x2F2E, "M", "巛"), + (0x2F2F, "M", "工"), + (0x2F30, "M", "己"), + (0x2F31, "M", "巾"), + (0x2F32, "M", "干"), + (0x2F33, "M", "幺"), + (0x2F34, "M", "广"), + (0x2F35, "M", "廴"), + (0x2F36, "M", "廾"), + (0x2F37, "M", "弋"), + (0x2F38, "M", "弓"), + (0x2F39, "M", "彐"), + (0x2F3A, "M", "彡"), + (0x2F3B, "M", "彳"), + (0x2F3C, "M", "心"), + (0x2F3D, "M", "戈"), + (0x2F3E, "M", "戶"), + (0x2F3F, "M", "手"), + (0x2F40, "M", "支"), + (0x2F41, "M", "攴"), + (0x2F42, "M", "文"), + (0x2F43, "M", "斗"), + (0x2F44, "M", "斤"), + (0x2F45, "M", "方"), + (0x2F46, "M", "无"), + (0x2F47, "M", "日"), + (0x2F48, "M", "曰"), + (0x2F49, "M", "月"), + (0x2F4A, "M", "木"), + (0x2F4B, "M", "欠"), + (0x2F4C, "M", "止"), + (0x2F4D, "M", "歹"), + (0x2F4E, "M", "殳"), + (0x2F4F, "M", "毋"), + (0x2F50, "M", "比"), + (0x2F51, "M", "毛"), + (0x2F52, "M", "氏"), + (0x2F53, "M", "气"), + (0x2F54, "M", "水"), + (0x2F55, "M", "火"), + (0x2F56, "M", "爪"), + (0x2F57, "M", "父"), + (0x2F58, "M", "爻"), + (0x2F59, "M", "爿"), + (0x2F5A, "M", "片"), + (0x2F5B, "M", "牙"), + (0x2F5C, "M", "牛"), + ] + + +def _seg_28() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0x2F5D, "M", "犬"), + (0x2F5E, "M", "玄"), + (0x2F5F, "M", "玉"), + (0x2F60, "M", "瓜"), + (0x2F61, "M", "瓦"), + (0x2F62, "M", "甘"), + (0x2F63, "M", "生"), + (0x2F64, "M", "用"), + (0x2F65, "M", "田"), + (0x2F66, "M", "疋"), + (0x2F67, "M", "疒"), + (0x2F68, "M", "癶"), + (0x2F69, "M", "白"), + (0x2F6A, "M", "皮"), + (0x2F6B, "M", "皿"), + (0x2F6C, "M", "目"), + (0x2F6D, "M", "矛"), + (0x2F6E, "M", "矢"), + (0x2F6F, "M", "石"), + (0x2F70, "M", "示"), + (0x2F71, "M", "禸"), + (0x2F72, "M", "禾"), + (0x2F73, "M", "穴"), + (0x2F74, "M", "立"), + (0x2F75, "M", "竹"), + (0x2F76, "M", "米"), + (0x2F77, "M", "糸"), + (0x2F78, "M", "缶"), + (0x2F79, "M", "网"), + (0x2F7A, "M", "羊"), + (0x2F7B, "M", "羽"), + (0x2F7C, "M", "老"), + (0x2F7D, "M", "而"), + (0x2F7E, "M", "耒"), + (0x2F7F, "M", "耳"), + (0x2F80, "M", "聿"), + (0x2F81, "M", "肉"), + (0x2F82, "M", "臣"), + (0x2F83, "M", "自"), + (0x2F84, "M", "至"), + (0x2F85, "M", "臼"), + (0x2F86, "M", "舌"), + (0x2F87, "M", "舛"), + (0x2F88, "M", "舟"), + (0x2F89, "M", "艮"), + (0x2F8A, "M", "色"), + (0x2F8B, "M", "艸"), + (0x2F8C, "M", "虍"), + (0x2F8D, "M", "虫"), + (0x2F8E, "M", "血"), + (0x2F8F, "M", "行"), + (0x2F90, "M", "衣"), + (0x2F91, "M", "襾"), + (0x2F92, "M", "見"), + (0x2F93, "M", "角"), + (0x2F94, "M", "言"), + (0x2F95, "M", "谷"), + (0x2F96, "M", "豆"), + (0x2F97, "M", "豕"), + (0x2F98, "M", "豸"), + (0x2F99, "M", "貝"), + (0x2F9A, "M", "赤"), + (0x2F9B, "M", "走"), + (0x2F9C, "M", "足"), + (0x2F9D, "M", "身"), + (0x2F9E, "M", "車"), + (0x2F9F, "M", "辛"), + (0x2FA0, "M", "辰"), + (0x2FA1, "M", "辵"), + (0x2FA2, "M", "邑"), + (0x2FA3, "M", "酉"), + (0x2FA4, "M", "釆"), + (0x2FA5, "M", "里"), + (0x2FA6, "M", "金"), + (0x2FA7, "M", "長"), + (0x2FA8, "M", "門"), + (0x2FA9, "M", "阜"), + (0x2FAA, "M", "隶"), + (0x2FAB, "M", "隹"), + (0x2FAC, "M", "雨"), + (0x2FAD, "M", "靑"), + (0x2FAE, "M", "非"), + (0x2FAF, "M", "面"), + (0x2FB0, "M", "革"), + (0x2FB1, "M", "韋"), + (0x2FB2, "M", "韭"), + (0x2FB3, "M", "音"), + (0x2FB4, "M", "頁"), + (0x2FB5, "M", "風"), + (0x2FB6, "M", "飛"), + (0x2FB7, "M", "食"), + (0x2FB8, "M", "首"), + (0x2FB9, "M", "香"), + (0x2FBA, "M", "馬"), + (0x2FBB, "M", "骨"), + (0x2FBC, "M", "高"), + (0x2FBD, "M", "髟"), + (0x2FBE, "M", "鬥"), + (0x2FBF, "M", "鬯"), + (0x2FC0, "M", "鬲"), + ] + + +def _seg_29() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0x2FC1, "M", "鬼"), + (0x2FC2, "M", "魚"), + (0x2FC3, "M", "鳥"), + (0x2FC4, "M", "鹵"), + (0x2FC5, "M", "鹿"), + (0x2FC6, "M", "麥"), + (0x2FC7, "M", "麻"), + (0x2FC8, "M", "黃"), + (0x2FC9, "M", "黍"), + (0x2FCA, "M", "黑"), + (0x2FCB, "M", "黹"), + (0x2FCC, "M", "黽"), + (0x2FCD, "M", "鼎"), + (0x2FCE, "M", "鼓"), + (0x2FCF, "M", "鼠"), + (0x2FD0, "M", "鼻"), + (0x2FD1, "M", "齊"), + (0x2FD2, "M", "齒"), + (0x2FD3, "M", "龍"), + (0x2FD4, "M", "龜"), + (0x2FD5, "M", "龠"), + (0x2FD6, "X"), + (0x3000, "M", " "), + (0x3001, "V"), + (0x3002, "M", "."), + (0x3003, "V"), + (0x3036, "M", "〒"), + (0x3037, "V"), + (0x3038, "M", "十"), + (0x3039, "M", "卄"), + (0x303A, "M", "卅"), + (0x303B, "V"), + (0x3040, "X"), + (0x3041, "V"), + (0x3097, "X"), + (0x3099, "V"), + (0x309B, "M", " ゙"), + (0x309C, "M", " ゚"), + (0x309D, "V"), + (0x309F, "M", "より"), + (0x30A0, "V"), + (0x30FF, "M", "コト"), + (0x3100, "X"), + (0x3105, "V"), + (0x3130, "X"), + (0x3131, "M", "ᄀ"), + (0x3132, "M", "ᄁ"), + (0x3133, "M", "ᆪ"), + (0x3134, "M", "ᄂ"), + (0x3135, "M", "ᆬ"), + (0x3136, "M", "ᆭ"), + (0x3137, "M", "ᄃ"), + (0x3138, "M", "ᄄ"), + (0x3139, "M", "ᄅ"), + (0x313A, "M", "ᆰ"), + (0x313B, "M", "ᆱ"), + (0x313C, "M", "ᆲ"), + (0x313D, "M", "ᆳ"), + (0x313E, "M", "ᆴ"), + (0x313F, "M", "ᆵ"), + (0x3140, "M", "ᄚ"), + (0x3141, "M", "ᄆ"), + (0x3142, "M", "ᄇ"), + (0x3143, "M", "ᄈ"), + (0x3144, "M", "ᄡ"), + (0x3145, "M", "ᄉ"), + (0x3146, "M", "ᄊ"), + (0x3147, "M", "ᄋ"), + (0x3148, "M", "ᄌ"), + (0x3149, "M", "ᄍ"), + (0x314A, "M", "ᄎ"), + (0x314B, "M", "ᄏ"), + (0x314C, "M", "ᄐ"), + (0x314D, "M", "ᄑ"), + (0x314E, "M", "ᄒ"), + (0x314F, "M", "ᅡ"), + (0x3150, "M", "ᅢ"), + (0x3151, "M", "ᅣ"), + (0x3152, "M", "ᅤ"), + (0x3153, "M", "ᅥ"), + (0x3154, "M", "ᅦ"), + (0x3155, "M", "ᅧ"), + (0x3156, "M", "ᅨ"), + (0x3157, "M", "ᅩ"), + (0x3158, "M", "ᅪ"), + (0x3159, "M", "ᅫ"), + (0x315A, "M", "ᅬ"), + (0x315B, "M", "ᅭ"), + (0x315C, "M", "ᅮ"), + (0x315D, "M", "ᅯ"), + (0x315E, "M", "ᅰ"), + (0x315F, "M", "ᅱ"), + (0x3160, "M", "ᅲ"), + (0x3161, "M", "ᅳ"), + (0x3162, "M", "ᅴ"), + (0x3163, "M", "ᅵ"), + (0x3164, "I"), + (0x3165, "M", "ᄔ"), + (0x3166, "M", "ᄕ"), + (0x3167, "M", "ᇇ"), + ] + + +def _seg_30() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0x3168, "M", "ᇈ"), + (0x3169, "M", "ᇌ"), + (0x316A, "M", "ᇎ"), + (0x316B, "M", "ᇓ"), + (0x316C, "M", "ᇗ"), + (0x316D, "M", "ᇙ"), + (0x316E, "M", "ᄜ"), + (0x316F, "M", "ᇝ"), + (0x3170, "M", "ᇟ"), + (0x3171, "M", "ᄝ"), + (0x3172, "M", "ᄞ"), + (0x3173, "M", "ᄠ"), + (0x3174, "M", "ᄢ"), + (0x3175, "M", "ᄣ"), + (0x3176, "M", "ᄧ"), + (0x3177, "M", "ᄩ"), + (0x3178, "M", "ᄫ"), + (0x3179, "M", "ᄬ"), + (0x317A, "M", "ᄭ"), + (0x317B, "M", "ᄮ"), + (0x317C, "M", "ᄯ"), + (0x317D, "M", "ᄲ"), + (0x317E, "M", "ᄶ"), + (0x317F, "M", "ᅀ"), + (0x3180, "M", "ᅇ"), + (0x3181, "M", "ᅌ"), + (0x3182, "M", "ᇱ"), + (0x3183, "M", "ᇲ"), + (0x3184, "M", "ᅗ"), + (0x3185, "M", "ᅘ"), + (0x3186, "M", "ᅙ"), + (0x3187, "M", "ᆄ"), + (0x3188, "M", "ᆅ"), + (0x3189, "M", "ᆈ"), + (0x318A, "M", "ᆑ"), + (0x318B, "M", "ᆒ"), + (0x318C, "M", "ᆔ"), + (0x318D, "M", "ᆞ"), + (0x318E, "M", "ᆡ"), + (0x318F, "X"), + (0x3190, "V"), + (0x3192, "M", "一"), + (0x3193, "M", "二"), + (0x3194, "M", "三"), + (0x3195, "M", "四"), + (0x3196, "M", "上"), + (0x3197, "M", "中"), + (0x3198, "M", "下"), + (0x3199, "M", "甲"), + (0x319A, "M", "乙"), + (0x319B, "M", "丙"), + (0x319C, "M", "丁"), + (0x319D, "M", "天"), + (0x319E, "M", "地"), + (0x319F, "M", "人"), + (0x31A0, "V"), + (0x31E6, "X"), + (0x31F0, "V"), + (0x3200, "M", "(ᄀ)"), + (0x3201, "M", "(ᄂ)"), + (0x3202, "M", "(ᄃ)"), + (0x3203, "M", "(ᄅ)"), + (0x3204, "M", "(ᄆ)"), + (0x3205, "M", "(ᄇ)"), + (0x3206, "M", "(ᄉ)"), + (0x3207, "M", "(ᄋ)"), + (0x3208, "M", "(ᄌ)"), + (0x3209, "M", "(ᄎ)"), + (0x320A, "M", "(ᄏ)"), + (0x320B, "M", "(ᄐ)"), + (0x320C, "M", "(ᄑ)"), + (0x320D, "M", "(ᄒ)"), + (0x320E, "M", "(가)"), + (0x320F, "M", "(나)"), + (0x3210, "M", "(다)"), + (0x3211, "M", "(라)"), + (0x3212, "M", "(마)"), + (0x3213, "M", "(바)"), + (0x3214, "M", "(사)"), + (0x3215, "M", "(아)"), + (0x3216, "M", "(자)"), + (0x3217, "M", "(차)"), + (0x3218, "M", "(카)"), + (0x3219, "M", "(타)"), + (0x321A, "M", "(파)"), + (0x321B, "M", "(하)"), + (0x321C, "M", "(주)"), + (0x321D, "M", "(오전)"), + (0x321E, "M", "(오후)"), + (0x321F, "X"), + (0x3220, "M", "(一)"), + (0x3221, "M", "(二)"), + (0x3222, "M", "(三)"), + (0x3223, "M", "(四)"), + (0x3224, "M", "(五)"), + (0x3225, "M", "(六)"), + (0x3226, "M", "(七)"), + (0x3227, "M", "(八)"), + (0x3228, "M", "(九)"), + (0x3229, "M", "(十)"), + ] + + +def _seg_31() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0x322A, "M", "(月)"), + (0x322B, "M", "(火)"), + (0x322C, "M", "(水)"), + (0x322D, "M", "(木)"), + (0x322E, "M", "(金)"), + (0x322F, "M", "(土)"), + (0x3230, "M", "(日)"), + (0x3231, "M", "(株)"), + (0x3232, "M", "(有)"), + (0x3233, "M", "(社)"), + (0x3234, "M", "(名)"), + (0x3235, "M", "(特)"), + (0x3236, "M", "(財)"), + (0x3237, "M", "(祝)"), + (0x3238, "M", "(労)"), + (0x3239, "M", "(代)"), + (0x323A, "M", "(呼)"), + (0x323B, "M", "(学)"), + (0x323C, "M", "(監)"), + (0x323D, "M", "(企)"), + (0x323E, "M", "(資)"), + (0x323F, "M", "(協)"), + (0x3240, "M", "(祭)"), + (0x3241, "M", "(休)"), + (0x3242, "M", "(自)"), + (0x3243, "M", "(至)"), + (0x3244, "M", "問"), + (0x3245, "M", "幼"), + (0x3246, "M", "文"), + (0x3247, "M", "箏"), + (0x3248, "V"), + (0x3250, "M", "pte"), + (0x3251, "M", "21"), + (0x3252, "M", "22"), + (0x3253, "M", "23"), + (0x3254, "M", "24"), + (0x3255, "M", "25"), + (0x3256, "M", "26"), + (0x3257, "M", "27"), + (0x3258, "M", "28"), + (0x3259, "M", "29"), + (0x325A, "M", "30"), + (0x325B, "M", "31"), + (0x325C, "M", "32"), + (0x325D, "M", "33"), + (0x325E, "M", "34"), + (0x325F, "M", "35"), + (0x3260, "M", "ᄀ"), + (0x3261, "M", "ᄂ"), + (0x3262, "M", "ᄃ"), + (0x3263, "M", "ᄅ"), + (0x3264, "M", "ᄆ"), + (0x3265, "M", "ᄇ"), + (0x3266, "M", "ᄉ"), + (0x3267, "M", "ᄋ"), + (0x3268, "M", "ᄌ"), + (0x3269, "M", "ᄎ"), + (0x326A, "M", "ᄏ"), + (0x326B, "M", "ᄐ"), + (0x326C, "M", "ᄑ"), + (0x326D, "M", "ᄒ"), + (0x326E, "M", "가"), + (0x326F, "M", "나"), + (0x3270, "M", "다"), + (0x3271, "M", "라"), + (0x3272, "M", "마"), + (0x3273, "M", "바"), + (0x3274, "M", "사"), + (0x3275, "M", "아"), + (0x3276, "M", "자"), + (0x3277, "M", "차"), + (0x3278, "M", "카"), + (0x3279, "M", "타"), + (0x327A, "M", "파"), + (0x327B, "M", "하"), + (0x327C, "M", "참고"), + (0x327D, "M", "주의"), + (0x327E, "M", "우"), + (0x327F, "V"), + (0x3280, "M", "一"), + (0x3281, "M", "二"), + (0x3282, "M", "三"), + (0x3283, "M", "四"), + (0x3284, "M", "五"), + (0x3285, "M", "六"), + (0x3286, "M", "七"), + (0x3287, "M", "八"), + (0x3288, "M", "九"), + (0x3289, "M", "十"), + (0x328A, "M", "月"), + (0x328B, "M", "火"), + (0x328C, "M", "水"), + (0x328D, "M", "木"), + (0x328E, "M", "金"), + (0x328F, "M", "土"), + (0x3290, "M", "日"), + (0x3291, "M", "株"), + (0x3292, "M", "有"), + (0x3293, "M", "社"), + (0x3294, "M", "名"), + ] + + +def _seg_32() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0x3295, "M", "特"), + (0x3296, "M", "財"), + (0x3297, "M", "祝"), + (0x3298, "M", "労"), + (0x3299, "M", "秘"), + (0x329A, "M", "男"), + (0x329B, "M", "女"), + (0x329C, "M", "適"), + (0x329D, "M", "優"), + (0x329E, "M", "印"), + (0x329F, "M", "注"), + (0x32A0, "M", "項"), + (0x32A1, "M", "休"), + (0x32A2, "M", "写"), + (0x32A3, "M", "正"), + (0x32A4, "M", "上"), + (0x32A5, "M", "中"), + (0x32A6, "M", "下"), + (0x32A7, "M", "左"), + (0x32A8, "M", "右"), + (0x32A9, "M", "医"), + (0x32AA, "M", "宗"), + (0x32AB, "M", "学"), + (0x32AC, "M", "監"), + (0x32AD, "M", "企"), + (0x32AE, "M", "資"), + (0x32AF, "M", "協"), + (0x32B0, "M", "夜"), + (0x32B1, "M", "36"), + (0x32B2, "M", "37"), + (0x32B3, "M", "38"), + (0x32B4, "M", "39"), + (0x32B5, "M", "40"), + (0x32B6, "M", "41"), + (0x32B7, "M", "42"), + (0x32B8, "M", "43"), + (0x32B9, "M", "44"), + (0x32BA, "M", "45"), + (0x32BB, "M", "46"), + (0x32BC, "M", "47"), + (0x32BD, "M", "48"), + (0x32BE, "M", "49"), + (0x32BF, "M", "50"), + (0x32C0, "M", "1月"), + (0x32C1, "M", "2月"), + (0x32C2, "M", "3月"), + (0x32C3, "M", "4月"), + (0x32C4, "M", "5月"), + (0x32C5, "M", "6月"), + (0x32C6, "M", "7月"), + (0x32C7, "M", "8月"), + (0x32C8, "M", "9月"), + (0x32C9, "M", "10月"), + (0x32CA, "M", "11月"), + (0x32CB, "M", "12月"), + (0x32CC, "M", "hg"), + (0x32CD, "M", "erg"), + (0x32CE, "M", "ev"), + (0x32CF, "M", "ltd"), + (0x32D0, "M", "ア"), + (0x32D1, "M", "イ"), + (0x32D2, "M", "ウ"), + (0x32D3, "M", "エ"), + (0x32D4, "M", "オ"), + (0x32D5, "M", "カ"), + (0x32D6, "M", "キ"), + (0x32D7, "M", "ク"), + (0x32D8, "M", "ケ"), + (0x32D9, "M", "コ"), + (0x32DA, "M", "サ"), + (0x32DB, "M", "シ"), + (0x32DC, "M", "ス"), + (0x32DD, "M", "セ"), + (0x32DE, "M", "ソ"), + (0x32DF, "M", "タ"), + (0x32E0, "M", "チ"), + (0x32E1, "M", "ツ"), + (0x32E2, "M", "テ"), + (0x32E3, "M", "ト"), + (0x32E4, "M", "ナ"), + (0x32E5, "M", "ニ"), + (0x32E6, "M", "ヌ"), + (0x32E7, "M", "ネ"), + (0x32E8, "M", "ノ"), + (0x32E9, "M", "ハ"), + (0x32EA, "M", "ヒ"), + (0x32EB, "M", "フ"), + (0x32EC, "M", "ヘ"), + (0x32ED, "M", "ホ"), + (0x32EE, "M", "マ"), + (0x32EF, "M", "ミ"), + (0x32F0, "M", "ム"), + (0x32F1, "M", "メ"), + (0x32F2, "M", "モ"), + (0x32F3, "M", "ヤ"), + (0x32F4, "M", "ユ"), + (0x32F5, "M", "ヨ"), + (0x32F6, "M", "ラ"), + (0x32F7, "M", "リ"), + (0x32F8, "M", "ル"), + ] + + +def _seg_33() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0x32F9, "M", "レ"), + (0x32FA, "M", "ロ"), + (0x32FB, "M", "ワ"), + (0x32FC, "M", "ヰ"), + (0x32FD, "M", "ヱ"), + (0x32FE, "M", "ヲ"), + (0x32FF, "M", "令和"), + (0x3300, "M", "アパート"), + (0x3301, "M", "アルファ"), + (0x3302, "M", "アンペア"), + (0x3303, "M", "アール"), + (0x3304, "M", "イニング"), + (0x3305, "M", "インチ"), + (0x3306, "M", "ウォン"), + (0x3307, "M", "エスクード"), + (0x3308, "M", "エーカー"), + (0x3309, "M", "オンス"), + (0x330A, "M", "オーム"), + (0x330B, "M", "カイリ"), + (0x330C, "M", "カラット"), + (0x330D, "M", "カロリー"), + (0x330E, "M", "ガロン"), + (0x330F, "M", "ガンマ"), + (0x3310, "M", "ギガ"), + (0x3311, "M", "ギニー"), + (0x3312, "M", "キュリー"), + (0x3313, "M", "ギルダー"), + (0x3314, "M", "キロ"), + (0x3315, "M", "キログラム"), + (0x3316, "M", "キロメートル"), + (0x3317, "M", "キロワット"), + (0x3318, "M", "グラム"), + (0x3319, "M", "グラムトン"), + (0x331A, "M", "クルゼイロ"), + (0x331B, "M", "クローネ"), + (0x331C, "M", "ケース"), + (0x331D, "M", "コルナ"), + (0x331E, "M", "コーポ"), + (0x331F, "M", "サイクル"), + (0x3320, "M", "サンチーム"), + (0x3321, "M", "シリング"), + (0x3322, "M", "センチ"), + (0x3323, "M", "セント"), + (0x3324, "M", "ダース"), + (0x3325, "M", "デシ"), + (0x3326, "M", "ドル"), + (0x3327, "M", "トン"), + (0x3328, "M", "ナノ"), + (0x3329, "M", "ノット"), + (0x332A, "M", "ハイツ"), + (0x332B, "M", "パーセント"), + (0x332C, "M", "パーツ"), + (0x332D, "M", "バーレル"), + (0x332E, "M", "ピアストル"), + (0x332F, "M", "ピクル"), + (0x3330, "M", "ピコ"), + (0x3331, "M", "ビル"), + (0x3332, "M", "ファラッド"), + (0x3333, "M", "フィート"), + (0x3334, "M", "ブッシェル"), + (0x3335, "M", "フラン"), + (0x3336, "M", "ヘクタール"), + (0x3337, "M", "ペソ"), + (0x3338, "M", "ペニヒ"), + (0x3339, "M", "ヘルツ"), + (0x333A, "M", "ペンス"), + (0x333B, "M", "ページ"), + (0x333C, "M", "ベータ"), + (0x333D, "M", "ポイント"), + (0x333E, "M", "ボルト"), + (0x333F, "M", "ホン"), + (0x3340, "M", "ポンド"), + (0x3341, "M", "ホール"), + (0x3342, "M", "ホーン"), + (0x3343, "M", "マイクロ"), + (0x3344, "M", "マイル"), + (0x3345, "M", "マッハ"), + (0x3346, "M", "マルク"), + (0x3347, "M", "マンション"), + (0x3348, "M", "ミクロン"), + (0x3349, "M", "ミリ"), + (0x334A, "M", "ミリバール"), + (0x334B, "M", "メガ"), + (0x334C, "M", "メガトン"), + (0x334D, "M", "メートル"), + (0x334E, "M", "ヤード"), + (0x334F, "M", "ヤール"), + (0x3350, "M", "ユアン"), + (0x3351, "M", "リットル"), + (0x3352, "M", "リラ"), + (0x3353, "M", "ルピー"), + (0x3354, "M", "ルーブル"), + (0x3355, "M", "レム"), + (0x3356, "M", "レントゲン"), + (0x3357, "M", "ワット"), + (0x3358, "M", "0点"), + (0x3359, "M", "1点"), + (0x335A, "M", "2点"), + (0x335B, "M", "3点"), + (0x335C, "M", "4点"), + ] + + +def _seg_34() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0x335D, "M", "5点"), + (0x335E, "M", "6点"), + (0x335F, "M", "7点"), + (0x3360, "M", "8点"), + (0x3361, "M", "9点"), + (0x3362, "M", "10点"), + (0x3363, "M", "11点"), + (0x3364, "M", "12点"), + (0x3365, "M", "13点"), + (0x3366, "M", "14点"), + (0x3367, "M", "15点"), + (0x3368, "M", "16点"), + (0x3369, "M", "17点"), + (0x336A, "M", "18点"), + (0x336B, "M", "19点"), + (0x336C, "M", "20点"), + (0x336D, "M", "21点"), + (0x336E, "M", "22点"), + (0x336F, "M", "23点"), + (0x3370, "M", "24点"), + (0x3371, "M", "hpa"), + (0x3372, "M", "da"), + (0x3373, "M", "au"), + (0x3374, "M", "bar"), + (0x3375, "M", "ov"), + (0x3376, "M", "pc"), + (0x3377, "M", "dm"), + (0x3378, "M", "dm2"), + (0x3379, "M", "dm3"), + (0x337A, "M", "iu"), + (0x337B, "M", "平成"), + (0x337C, "M", "昭和"), + (0x337D, "M", "大正"), + (0x337E, "M", "明治"), + (0x337F, "M", "株式会社"), + (0x3380, "M", "pa"), + (0x3381, "M", "na"), + (0x3382, "M", "μa"), + (0x3383, "M", "ma"), + (0x3384, "M", "ka"), + (0x3385, "M", "kb"), + (0x3386, "M", "mb"), + (0x3387, "M", "gb"), + (0x3388, "M", "cal"), + (0x3389, "M", "kcal"), + (0x338A, "M", "pf"), + (0x338B, "M", "nf"), + (0x338C, "M", "μf"), + (0x338D, "M", "μg"), + (0x338E, "M", "mg"), + (0x338F, "M", "kg"), + (0x3390, "M", "hz"), + (0x3391, "M", "khz"), + (0x3392, "M", "mhz"), + (0x3393, "M", "ghz"), + (0x3394, "M", "thz"), + (0x3395, "M", "μl"), + (0x3396, "M", "ml"), + (0x3397, "M", "dl"), + (0x3398, "M", "kl"), + (0x3399, "M", "fm"), + (0x339A, "M", "nm"), + (0x339B, "M", "μm"), + (0x339C, "M", "mm"), + (0x339D, "M", "cm"), + (0x339E, "M", "km"), + (0x339F, "M", "mm2"), + (0x33A0, "M", "cm2"), + (0x33A1, "M", "m2"), + (0x33A2, "M", "km2"), + (0x33A3, "M", "mm3"), + (0x33A4, "M", "cm3"), + (0x33A5, "M", "m3"), + (0x33A6, "M", "km3"), + (0x33A7, "M", "m∕s"), + (0x33A8, "M", "m∕s2"), + (0x33A9, "M", "pa"), + (0x33AA, "M", "kpa"), + (0x33AB, "M", "mpa"), + (0x33AC, "M", "gpa"), + (0x33AD, "M", "rad"), + (0x33AE, "M", "rad∕s"), + (0x33AF, "M", "rad∕s2"), + (0x33B0, "M", "ps"), + (0x33B1, "M", "ns"), + (0x33B2, "M", "μs"), + (0x33B3, "M", "ms"), + (0x33B4, "M", "pv"), + (0x33B5, "M", "nv"), + (0x33B6, "M", "μv"), + (0x33B7, "M", "mv"), + (0x33B8, "M", "kv"), + (0x33B9, "M", "mv"), + (0x33BA, "M", "pw"), + (0x33BB, "M", "nw"), + (0x33BC, "M", "μw"), + (0x33BD, "M", "mw"), + (0x33BE, "M", "kw"), + (0x33BF, "M", "mw"), + (0x33C0, "M", "kω"), + ] + + +def _seg_35() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0x33C1, "M", "mω"), + (0x33C2, "X"), + (0x33C3, "M", "bq"), + (0x33C4, "M", "cc"), + (0x33C5, "M", "cd"), + (0x33C6, "M", "c∕kg"), + (0x33C7, "X"), + (0x33C8, "M", "db"), + (0x33C9, "M", "gy"), + (0x33CA, "M", "ha"), + (0x33CB, "M", "hp"), + (0x33CC, "M", "in"), + (0x33CD, "M", "kk"), + (0x33CE, "M", "km"), + (0x33CF, "M", "kt"), + (0x33D0, "M", "lm"), + (0x33D1, "M", "ln"), + (0x33D2, "M", "log"), + (0x33D3, "M", "lx"), + (0x33D4, "M", "mb"), + (0x33D5, "M", "mil"), + (0x33D6, "M", "mol"), + (0x33D7, "M", "ph"), + (0x33D8, "X"), + (0x33D9, "M", "ppm"), + (0x33DA, "M", "pr"), + (0x33DB, "M", "sr"), + (0x33DC, "M", "sv"), + (0x33DD, "M", "wb"), + (0x33DE, "M", "v∕m"), + (0x33DF, "M", "a∕m"), + (0x33E0, "M", "1日"), + (0x33E1, "M", "2日"), + (0x33E2, "M", "3日"), + (0x33E3, "M", "4日"), + (0x33E4, "M", "5日"), + (0x33E5, "M", "6日"), + (0x33E6, "M", "7日"), + (0x33E7, "M", "8日"), + (0x33E8, "M", "9日"), + (0x33E9, "M", "10日"), + (0x33EA, "M", "11日"), + (0x33EB, "M", "12日"), + (0x33EC, "M", "13日"), + (0x33ED, "M", "14日"), + (0x33EE, "M", "15日"), + (0x33EF, "M", "16日"), + (0x33F0, "M", "17日"), + (0x33F1, "M", "18日"), + (0x33F2, "M", "19日"), + (0x33F3, "M", "20日"), + (0x33F4, "M", "21日"), + (0x33F5, "M", "22日"), + (0x33F6, "M", "23日"), + (0x33F7, "M", "24日"), + (0x33F8, "M", "25日"), + (0x33F9, "M", "26日"), + (0x33FA, "M", "27日"), + (0x33FB, "M", "28日"), + (0x33FC, "M", "29日"), + (0x33FD, "M", "30日"), + (0x33FE, "M", "31日"), + (0x33FF, "M", "gal"), + (0x3400, "V"), + (0xA48D, "X"), + (0xA490, "V"), + (0xA4C7, "X"), + (0xA4D0, "V"), + (0xA62C, "X"), + (0xA640, "M", "ꙁ"), + (0xA641, "V"), + (0xA642, "M", "ꙃ"), + (0xA643, "V"), + (0xA644, "M", "ꙅ"), + (0xA645, "V"), + (0xA646, "M", "ꙇ"), + (0xA647, "V"), + (0xA648, "M", "ꙉ"), + (0xA649, "V"), + (0xA64A, "M", "ꙋ"), + (0xA64B, "V"), + (0xA64C, "M", "ꙍ"), + (0xA64D, "V"), + (0xA64E, "M", "ꙏ"), + (0xA64F, "V"), + (0xA650, "M", "ꙑ"), + (0xA651, "V"), + (0xA652, "M", "ꙓ"), + (0xA653, "V"), + (0xA654, "M", "ꙕ"), + (0xA655, "V"), + (0xA656, "M", "ꙗ"), + (0xA657, "V"), + (0xA658, "M", "ꙙ"), + (0xA659, "V"), + (0xA65A, "M", "ꙛ"), + (0xA65B, "V"), + (0xA65C, "M", "ꙝ"), + (0xA65D, "V"), + (0xA65E, "M", "ꙟ"), + ] + + +def _seg_36() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0xA65F, "V"), + (0xA660, "M", "ꙡ"), + (0xA661, "V"), + (0xA662, "M", "ꙣ"), + (0xA663, "V"), + (0xA664, "M", "ꙥ"), + (0xA665, "V"), + (0xA666, "M", "ꙧ"), + (0xA667, "V"), + (0xA668, "M", "ꙩ"), + (0xA669, "V"), + (0xA66A, "M", "ꙫ"), + (0xA66B, "V"), + (0xA66C, "M", "ꙭ"), + (0xA66D, "V"), + (0xA680, "M", "ꚁ"), + (0xA681, "V"), + (0xA682, "M", "ꚃ"), + (0xA683, "V"), + (0xA684, "M", "ꚅ"), + (0xA685, "V"), + (0xA686, "M", "ꚇ"), + (0xA687, "V"), + (0xA688, "M", "ꚉ"), + (0xA689, "V"), + (0xA68A, "M", "ꚋ"), + (0xA68B, "V"), + (0xA68C, "M", "ꚍ"), + (0xA68D, "V"), + (0xA68E, "M", "ꚏ"), + (0xA68F, "V"), + (0xA690, "M", "ꚑ"), + (0xA691, "V"), + (0xA692, "M", "ꚓ"), + (0xA693, "V"), + (0xA694, "M", "ꚕ"), + (0xA695, "V"), + (0xA696, "M", "ꚗ"), + (0xA697, "V"), + (0xA698, "M", "ꚙ"), + (0xA699, "V"), + (0xA69A, "M", "ꚛ"), + (0xA69B, "V"), + (0xA69C, "M", "ъ"), + (0xA69D, "M", "ь"), + (0xA69E, "V"), + (0xA6F8, "X"), + (0xA700, "V"), + (0xA722, "M", "ꜣ"), + (0xA723, "V"), + (0xA724, "M", "ꜥ"), + (0xA725, "V"), + (0xA726, "M", "ꜧ"), + (0xA727, "V"), + (0xA728, "M", "ꜩ"), + (0xA729, "V"), + (0xA72A, "M", "ꜫ"), + (0xA72B, "V"), + (0xA72C, "M", "ꜭ"), + (0xA72D, "V"), + (0xA72E, "M", "ꜯ"), + (0xA72F, "V"), + (0xA732, "M", "ꜳ"), + (0xA733, "V"), + (0xA734, "M", "ꜵ"), + (0xA735, "V"), + (0xA736, "M", "ꜷ"), + (0xA737, "V"), + (0xA738, "M", "ꜹ"), + (0xA739, "V"), + (0xA73A, "M", "ꜻ"), + (0xA73B, "V"), + (0xA73C, "M", "ꜽ"), + (0xA73D, "V"), + (0xA73E, "M", "ꜿ"), + (0xA73F, "V"), + (0xA740, "M", "ꝁ"), + (0xA741, "V"), + (0xA742, "M", "ꝃ"), + (0xA743, "V"), + (0xA744, "M", "ꝅ"), + (0xA745, "V"), + (0xA746, "M", "ꝇ"), + (0xA747, "V"), + (0xA748, "M", "ꝉ"), + (0xA749, "V"), + (0xA74A, "M", "ꝋ"), + (0xA74B, "V"), + (0xA74C, "M", "ꝍ"), + (0xA74D, "V"), + (0xA74E, "M", "ꝏ"), + (0xA74F, "V"), + (0xA750, "M", "ꝑ"), + (0xA751, "V"), + (0xA752, "M", "ꝓ"), + (0xA753, "V"), + (0xA754, "M", "ꝕ"), + (0xA755, "V"), + (0xA756, "M", "ꝗ"), + (0xA757, "V"), + ] + + +def _seg_37() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0xA758, "M", "ꝙ"), + (0xA759, "V"), + (0xA75A, "M", "ꝛ"), + (0xA75B, "V"), + (0xA75C, "M", "ꝝ"), + (0xA75D, "V"), + (0xA75E, "M", "ꝟ"), + (0xA75F, "V"), + (0xA760, "M", "ꝡ"), + (0xA761, "V"), + (0xA762, "M", "ꝣ"), + (0xA763, "V"), + (0xA764, "M", "ꝥ"), + (0xA765, "V"), + (0xA766, "M", "ꝧ"), + (0xA767, "V"), + (0xA768, "M", "ꝩ"), + (0xA769, "V"), + (0xA76A, "M", "ꝫ"), + (0xA76B, "V"), + (0xA76C, "M", "ꝭ"), + (0xA76D, "V"), + (0xA76E, "M", "ꝯ"), + (0xA76F, "V"), + (0xA770, "M", "ꝯ"), + (0xA771, "V"), + (0xA779, "M", "ꝺ"), + (0xA77A, "V"), + (0xA77B, "M", "ꝼ"), + (0xA77C, "V"), + (0xA77D, "M", "ᵹ"), + (0xA77E, "M", "ꝿ"), + (0xA77F, "V"), + (0xA780, "M", "ꞁ"), + (0xA781, "V"), + (0xA782, "M", "ꞃ"), + (0xA783, "V"), + (0xA784, "M", "ꞅ"), + (0xA785, "V"), + (0xA786, "M", "ꞇ"), + (0xA787, "V"), + (0xA78B, "M", "ꞌ"), + (0xA78C, "V"), + (0xA78D, "M", "ɥ"), + (0xA78E, "V"), + (0xA790, "M", "ꞑ"), + (0xA791, "V"), + (0xA792, "M", "ꞓ"), + (0xA793, "V"), + (0xA796, "M", "ꞗ"), + (0xA797, "V"), + (0xA798, "M", "ꞙ"), + (0xA799, "V"), + (0xA79A, "M", "ꞛ"), + (0xA79B, "V"), + (0xA79C, "M", "ꞝ"), + (0xA79D, "V"), + (0xA79E, "M", "ꞟ"), + (0xA79F, "V"), + (0xA7A0, "M", "ꞡ"), + (0xA7A1, "V"), + (0xA7A2, "M", "ꞣ"), + (0xA7A3, "V"), + (0xA7A4, "M", "ꞥ"), + (0xA7A5, "V"), + (0xA7A6, "M", "ꞧ"), + (0xA7A7, "V"), + (0xA7A8, "M", "ꞩ"), + (0xA7A9, "V"), + (0xA7AA, "M", "ɦ"), + (0xA7AB, "M", "ɜ"), + (0xA7AC, "M", "ɡ"), + (0xA7AD, "M", "ɬ"), + (0xA7AE, "M", "ɪ"), + (0xA7AF, "V"), + (0xA7B0, "M", "ʞ"), + (0xA7B1, "M", "ʇ"), + (0xA7B2, "M", "ʝ"), + (0xA7B3, "M", "ꭓ"), + (0xA7B4, "M", "ꞵ"), + (0xA7B5, "V"), + (0xA7B6, "M", "ꞷ"), + (0xA7B7, "V"), + (0xA7B8, "M", "ꞹ"), + (0xA7B9, "V"), + (0xA7BA, "M", "ꞻ"), + (0xA7BB, "V"), + (0xA7BC, "M", "ꞽ"), + (0xA7BD, "V"), + (0xA7BE, "M", "ꞿ"), + (0xA7BF, "V"), + (0xA7C0, "M", "ꟁ"), + (0xA7C1, "V"), + (0xA7C2, "M", "ꟃ"), + (0xA7C3, "V"), + (0xA7C4, "M", "ꞔ"), + (0xA7C5, "M", "ʂ"), + (0xA7C6, "M", "ᶎ"), + (0xA7C7, "M", "ꟈ"), + (0xA7C8, "V"), + ] + + +def _seg_38() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0xA7C9, "M", "ꟊ"), + (0xA7CA, "V"), + (0xA7CB, "M", "ɤ"), + (0xA7CC, "M", "ꟍ"), + (0xA7CD, "V"), + (0xA7CE, "X"), + (0xA7D0, "M", "ꟑ"), + (0xA7D1, "V"), + (0xA7D2, "X"), + (0xA7D3, "V"), + (0xA7D4, "X"), + (0xA7D5, "V"), + (0xA7D6, "M", "ꟗ"), + (0xA7D7, "V"), + (0xA7D8, "M", "ꟙ"), + (0xA7D9, "V"), + (0xA7DA, "M", "ꟛ"), + (0xA7DB, "V"), + (0xA7DC, "M", "ƛ"), + (0xA7DD, "X"), + (0xA7F2, "M", "c"), + (0xA7F3, "M", "f"), + (0xA7F4, "M", "q"), + (0xA7F5, "M", "ꟶ"), + (0xA7F6, "V"), + (0xA7F8, "M", "ħ"), + (0xA7F9, "M", "œ"), + (0xA7FA, "V"), + (0xA82D, "X"), + (0xA830, "V"), + (0xA83A, "X"), + (0xA840, "V"), + (0xA878, "X"), + (0xA880, "V"), + (0xA8C6, "X"), + (0xA8CE, "V"), + (0xA8DA, "X"), + (0xA8E0, "V"), + (0xA954, "X"), + (0xA95F, "V"), + (0xA97D, "X"), + (0xA980, "V"), + (0xA9CE, "X"), + (0xA9CF, "V"), + (0xA9DA, "X"), + (0xA9DE, "V"), + (0xA9FF, "X"), + (0xAA00, "V"), + (0xAA37, "X"), + (0xAA40, "V"), + (0xAA4E, "X"), + (0xAA50, "V"), + (0xAA5A, "X"), + (0xAA5C, "V"), + (0xAAC3, "X"), + (0xAADB, "V"), + (0xAAF7, "X"), + (0xAB01, "V"), + (0xAB07, "X"), + (0xAB09, "V"), + (0xAB0F, "X"), + (0xAB11, "V"), + (0xAB17, "X"), + (0xAB20, "V"), + (0xAB27, "X"), + (0xAB28, "V"), + (0xAB2F, "X"), + (0xAB30, "V"), + (0xAB5C, "M", "ꜧ"), + (0xAB5D, "M", "ꬷ"), + (0xAB5E, "M", "ɫ"), + (0xAB5F, "M", "ꭒ"), + (0xAB60, "V"), + (0xAB69, "M", "ʍ"), + (0xAB6A, "V"), + (0xAB6C, "X"), + (0xAB70, "M", "Ꭰ"), + (0xAB71, "M", "Ꭱ"), + (0xAB72, "M", "Ꭲ"), + (0xAB73, "M", "Ꭳ"), + (0xAB74, "M", "Ꭴ"), + (0xAB75, "M", "Ꭵ"), + (0xAB76, "M", "Ꭶ"), + (0xAB77, "M", "Ꭷ"), + (0xAB78, "M", "Ꭸ"), + (0xAB79, "M", "Ꭹ"), + (0xAB7A, "M", "Ꭺ"), + (0xAB7B, "M", "Ꭻ"), + (0xAB7C, "M", "Ꭼ"), + (0xAB7D, "M", "Ꭽ"), + (0xAB7E, "M", "Ꭾ"), + (0xAB7F, "M", "Ꭿ"), + (0xAB80, "M", "Ꮀ"), + (0xAB81, "M", "Ꮁ"), + (0xAB82, "M", "Ꮂ"), + (0xAB83, "M", "Ꮃ"), + (0xAB84, "M", "Ꮄ"), + (0xAB85, "M", "Ꮅ"), + (0xAB86, "M", "Ꮆ"), + (0xAB87, "M", "Ꮇ"), + ] + + +def _seg_39() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0xAB88, "M", "Ꮈ"), + (0xAB89, "M", "Ꮉ"), + (0xAB8A, "M", "Ꮊ"), + (0xAB8B, "M", "Ꮋ"), + (0xAB8C, "M", "Ꮌ"), + (0xAB8D, "M", "Ꮍ"), + (0xAB8E, "M", "Ꮎ"), + (0xAB8F, "M", "Ꮏ"), + (0xAB90, "M", "Ꮐ"), + (0xAB91, "M", "Ꮑ"), + (0xAB92, "M", "Ꮒ"), + (0xAB93, "M", "Ꮓ"), + (0xAB94, "M", "Ꮔ"), + (0xAB95, "M", "Ꮕ"), + (0xAB96, "M", "Ꮖ"), + (0xAB97, "M", "Ꮗ"), + (0xAB98, "M", "Ꮘ"), + (0xAB99, "M", "Ꮙ"), + (0xAB9A, "M", "Ꮚ"), + (0xAB9B, "M", "Ꮛ"), + (0xAB9C, "M", "Ꮜ"), + (0xAB9D, "M", "Ꮝ"), + (0xAB9E, "M", "Ꮞ"), + (0xAB9F, "M", "Ꮟ"), + (0xABA0, "M", "Ꮠ"), + (0xABA1, "M", "Ꮡ"), + (0xABA2, "M", "Ꮢ"), + (0xABA3, "M", "Ꮣ"), + (0xABA4, "M", "Ꮤ"), + (0xABA5, "M", "Ꮥ"), + (0xABA6, "M", "Ꮦ"), + (0xABA7, "M", "Ꮧ"), + (0xABA8, "M", "Ꮨ"), + (0xABA9, "M", "Ꮩ"), + (0xABAA, "M", "Ꮪ"), + (0xABAB, "M", "Ꮫ"), + (0xABAC, "M", "Ꮬ"), + (0xABAD, "M", "Ꮭ"), + (0xABAE, "M", "Ꮮ"), + (0xABAF, "M", "Ꮯ"), + (0xABB0, "M", "Ꮰ"), + (0xABB1, "M", "Ꮱ"), + (0xABB2, "M", "Ꮲ"), + (0xABB3, "M", "Ꮳ"), + (0xABB4, "M", "Ꮴ"), + (0xABB5, "M", "Ꮵ"), + (0xABB6, "M", "Ꮶ"), + (0xABB7, "M", "Ꮷ"), + (0xABB8, "M", "Ꮸ"), + (0xABB9, "M", "Ꮹ"), + (0xABBA, "M", "Ꮺ"), + (0xABBB, "M", "Ꮻ"), + (0xABBC, "M", "Ꮼ"), + (0xABBD, "M", "Ꮽ"), + (0xABBE, "M", "Ꮾ"), + (0xABBF, "M", "Ꮿ"), + (0xABC0, "V"), + (0xABEE, "X"), + (0xABF0, "V"), + (0xABFA, "X"), + (0xAC00, "V"), + (0xD7A4, "X"), + (0xD7B0, "V"), + (0xD7C7, "X"), + (0xD7CB, "V"), + (0xD7FC, "X"), + (0xF900, "M", "豈"), + (0xF901, "M", "更"), + (0xF902, "M", "車"), + (0xF903, "M", "賈"), + (0xF904, "M", "滑"), + (0xF905, "M", "串"), + (0xF906, "M", "句"), + (0xF907, "M", "龜"), + (0xF909, "M", "契"), + (0xF90A, "M", "金"), + (0xF90B, "M", "喇"), + (0xF90C, "M", "奈"), + (0xF90D, "M", "懶"), + (0xF90E, "M", "癩"), + (0xF90F, "M", "羅"), + (0xF910, "M", "蘿"), + (0xF911, "M", "螺"), + (0xF912, "M", "裸"), + (0xF913, "M", "邏"), + (0xF914, "M", "樂"), + (0xF915, "M", "洛"), + (0xF916, "M", "烙"), + (0xF917, "M", "珞"), + (0xF918, "M", "落"), + (0xF919, "M", "酪"), + (0xF91A, "M", "駱"), + (0xF91B, "M", "亂"), + (0xF91C, "M", "卵"), + (0xF91D, "M", "欄"), + (0xF91E, "M", "爛"), + (0xF91F, "M", "蘭"), + (0xF920, "M", "鸞"), + (0xF921, "M", "嵐"), + (0xF922, "M", "濫"), + ] + + +def _seg_40() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0xF923, "M", "藍"), + (0xF924, "M", "襤"), + (0xF925, "M", "拉"), + (0xF926, "M", "臘"), + (0xF927, "M", "蠟"), + (0xF928, "M", "廊"), + (0xF929, "M", "朗"), + (0xF92A, "M", "浪"), + (0xF92B, "M", "狼"), + (0xF92C, "M", "郎"), + (0xF92D, "M", "來"), + (0xF92E, "M", "冷"), + (0xF92F, "M", "勞"), + (0xF930, "M", "擄"), + (0xF931, "M", "櫓"), + (0xF932, "M", "爐"), + (0xF933, "M", "盧"), + (0xF934, "M", "老"), + (0xF935, "M", "蘆"), + (0xF936, "M", "虜"), + (0xF937, "M", "路"), + (0xF938, "M", "露"), + (0xF939, "M", "魯"), + (0xF93A, "M", "鷺"), + (0xF93B, "M", "碌"), + (0xF93C, "M", "祿"), + (0xF93D, "M", "綠"), + (0xF93E, "M", "菉"), + (0xF93F, "M", "錄"), + (0xF940, "M", "鹿"), + (0xF941, "M", "論"), + (0xF942, "M", "壟"), + (0xF943, "M", "弄"), + (0xF944, "M", "籠"), + (0xF945, "M", "聾"), + (0xF946, "M", "牢"), + (0xF947, "M", "磊"), + (0xF948, "M", "賂"), + (0xF949, "M", "雷"), + (0xF94A, "M", "壘"), + (0xF94B, "M", "屢"), + (0xF94C, "M", "樓"), + (0xF94D, "M", "淚"), + (0xF94E, "M", "漏"), + (0xF94F, "M", "累"), + (0xF950, "M", "縷"), + (0xF951, "M", "陋"), + (0xF952, "M", "勒"), + (0xF953, "M", "肋"), + (0xF954, "M", "凜"), + (0xF955, "M", "凌"), + (0xF956, "M", "稜"), + (0xF957, "M", "綾"), + (0xF958, "M", "菱"), + (0xF959, "M", "陵"), + (0xF95A, "M", "讀"), + (0xF95B, "M", "拏"), + (0xF95C, "M", "樂"), + (0xF95D, "M", "諾"), + (0xF95E, "M", "丹"), + (0xF95F, "M", "寧"), + (0xF960, "M", "怒"), + (0xF961, "M", "率"), + (0xF962, "M", "異"), + (0xF963, "M", "北"), + (0xF964, "M", "磻"), + (0xF965, "M", "便"), + (0xF966, "M", "復"), + (0xF967, "M", "不"), + (0xF968, "M", "泌"), + (0xF969, "M", "數"), + (0xF96A, "M", "索"), + (0xF96B, "M", "參"), + (0xF96C, "M", "塞"), + (0xF96D, "M", "省"), + (0xF96E, "M", "葉"), + (0xF96F, "M", "說"), + (0xF970, "M", "殺"), + (0xF971, "M", "辰"), + (0xF972, "M", "沈"), + (0xF973, "M", "拾"), + (0xF974, "M", "若"), + (0xF975, "M", "掠"), + (0xF976, "M", "略"), + (0xF977, "M", "亮"), + (0xF978, "M", "兩"), + (0xF979, "M", "凉"), + (0xF97A, "M", "梁"), + (0xF97B, "M", "糧"), + (0xF97C, "M", "良"), + (0xF97D, "M", "諒"), + (0xF97E, "M", "量"), + (0xF97F, "M", "勵"), + (0xF980, "M", "呂"), + (0xF981, "M", "女"), + (0xF982, "M", "廬"), + (0xF983, "M", "旅"), + (0xF984, "M", "濾"), + (0xF985, "M", "礪"), + (0xF986, "M", "閭"), + ] + + +def _seg_41() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0xF987, "M", "驪"), + (0xF988, "M", "麗"), + (0xF989, "M", "黎"), + (0xF98A, "M", "力"), + (0xF98B, "M", "曆"), + (0xF98C, "M", "歷"), + (0xF98D, "M", "轢"), + (0xF98E, "M", "年"), + (0xF98F, "M", "憐"), + (0xF990, "M", "戀"), + (0xF991, "M", "撚"), + (0xF992, "M", "漣"), + (0xF993, "M", "煉"), + (0xF994, "M", "璉"), + (0xF995, "M", "秊"), + (0xF996, "M", "練"), + (0xF997, "M", "聯"), + (0xF998, "M", "輦"), + (0xF999, "M", "蓮"), + (0xF99A, "M", "連"), + (0xF99B, "M", "鍊"), + (0xF99C, "M", "列"), + (0xF99D, "M", "劣"), + (0xF99E, "M", "咽"), + (0xF99F, "M", "烈"), + (0xF9A0, "M", "裂"), + (0xF9A1, "M", "說"), + (0xF9A2, "M", "廉"), + (0xF9A3, "M", "念"), + (0xF9A4, "M", "捻"), + (0xF9A5, "M", "殮"), + (0xF9A6, "M", "簾"), + (0xF9A7, "M", "獵"), + (0xF9A8, "M", "令"), + (0xF9A9, "M", "囹"), + (0xF9AA, "M", "寧"), + (0xF9AB, "M", "嶺"), + (0xF9AC, "M", "怜"), + (0xF9AD, "M", "玲"), + (0xF9AE, "M", "瑩"), + (0xF9AF, "M", "羚"), + (0xF9B0, "M", "聆"), + (0xF9B1, "M", "鈴"), + (0xF9B2, "M", "零"), + (0xF9B3, "M", "靈"), + (0xF9B4, "M", "領"), + (0xF9B5, "M", "例"), + (0xF9B6, "M", "禮"), + (0xF9B7, "M", "醴"), + (0xF9B8, "M", "隸"), + (0xF9B9, "M", "惡"), + (0xF9BA, "M", "了"), + (0xF9BB, "M", "僚"), + (0xF9BC, "M", "寮"), + (0xF9BD, "M", "尿"), + (0xF9BE, "M", "料"), + (0xF9BF, "M", "樂"), + (0xF9C0, "M", "燎"), + (0xF9C1, "M", "療"), + (0xF9C2, "M", "蓼"), + (0xF9C3, "M", "遼"), + (0xF9C4, "M", "龍"), + (0xF9C5, "M", "暈"), + (0xF9C6, "M", "阮"), + (0xF9C7, "M", "劉"), + (0xF9C8, "M", "杻"), + (0xF9C9, "M", "柳"), + (0xF9CA, "M", "流"), + (0xF9CB, "M", "溜"), + (0xF9CC, "M", "琉"), + (0xF9CD, "M", "留"), + (0xF9CE, "M", "硫"), + (0xF9CF, "M", "紐"), + (0xF9D0, "M", "類"), + (0xF9D1, "M", "六"), + (0xF9D2, "M", "戮"), + (0xF9D3, "M", "陸"), + (0xF9D4, "M", "倫"), + (0xF9D5, "M", "崙"), + (0xF9D6, "M", "淪"), + (0xF9D7, "M", "輪"), + (0xF9D8, "M", "律"), + (0xF9D9, "M", "慄"), + (0xF9DA, "M", "栗"), + (0xF9DB, "M", "率"), + (0xF9DC, "M", "隆"), + (0xF9DD, "M", "利"), + (0xF9DE, "M", "吏"), + (0xF9DF, "M", "履"), + (0xF9E0, "M", "易"), + (0xF9E1, "M", "李"), + (0xF9E2, "M", "梨"), + (0xF9E3, "M", "泥"), + (0xF9E4, "M", "理"), + (0xF9E5, "M", "痢"), + (0xF9E6, "M", "罹"), + (0xF9E7, "M", "裏"), + (0xF9E8, "M", "裡"), + (0xF9E9, "M", "里"), + (0xF9EA, "M", "離"), + ] + + +def _seg_42() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0xF9EB, "M", "匿"), + (0xF9EC, "M", "溺"), + (0xF9ED, "M", "吝"), + (0xF9EE, "M", "燐"), + (0xF9EF, "M", "璘"), + (0xF9F0, "M", "藺"), + (0xF9F1, "M", "隣"), + (0xF9F2, "M", "鱗"), + (0xF9F3, "M", "麟"), + (0xF9F4, "M", "林"), + (0xF9F5, "M", "淋"), + (0xF9F6, "M", "臨"), + (0xF9F7, "M", "立"), + (0xF9F8, "M", "笠"), + (0xF9F9, "M", "粒"), + (0xF9FA, "M", "狀"), + (0xF9FB, "M", "炙"), + (0xF9FC, "M", "識"), + (0xF9FD, "M", "什"), + (0xF9FE, "M", "茶"), + (0xF9FF, "M", "刺"), + (0xFA00, "M", "切"), + (0xFA01, "M", "度"), + (0xFA02, "M", "拓"), + (0xFA03, "M", "糖"), + (0xFA04, "M", "宅"), + (0xFA05, "M", "洞"), + (0xFA06, "M", "暴"), + (0xFA07, "M", "輻"), + (0xFA08, "M", "行"), + (0xFA09, "M", "降"), + (0xFA0A, "M", "見"), + (0xFA0B, "M", "廓"), + (0xFA0C, "M", "兀"), + (0xFA0D, "M", "嗀"), + (0xFA0E, "V"), + (0xFA10, "M", "塚"), + (0xFA11, "V"), + (0xFA12, "M", "晴"), + (0xFA13, "V"), + (0xFA15, "M", "凞"), + (0xFA16, "M", "猪"), + (0xFA17, "M", "益"), + (0xFA18, "M", "礼"), + (0xFA19, "M", "神"), + (0xFA1A, "M", "祥"), + (0xFA1B, "M", "福"), + (0xFA1C, "M", "靖"), + (0xFA1D, "M", "精"), + (0xFA1E, "M", "羽"), + (0xFA1F, "V"), + (0xFA20, "M", "蘒"), + (0xFA21, "V"), + (0xFA22, "M", "諸"), + (0xFA23, "V"), + (0xFA25, "M", "逸"), + (0xFA26, "M", "都"), + (0xFA27, "V"), + (0xFA2A, "M", "飯"), + (0xFA2B, "M", "飼"), + (0xFA2C, "M", "館"), + (0xFA2D, "M", "鶴"), + (0xFA2E, "M", "郞"), + (0xFA2F, "M", "隷"), + (0xFA30, "M", "侮"), + (0xFA31, "M", "僧"), + (0xFA32, "M", "免"), + (0xFA33, "M", "勉"), + (0xFA34, "M", "勤"), + (0xFA35, "M", "卑"), + (0xFA36, "M", "喝"), + (0xFA37, "M", "嘆"), + (0xFA38, "M", "器"), + (0xFA39, "M", "塀"), + (0xFA3A, "M", "墨"), + (0xFA3B, "M", "層"), + (0xFA3C, "M", "屮"), + (0xFA3D, "M", "悔"), + (0xFA3E, "M", "慨"), + (0xFA3F, "M", "憎"), + (0xFA40, "M", "懲"), + (0xFA41, "M", "敏"), + (0xFA42, "M", "既"), + (0xFA43, "M", "暑"), + (0xFA44, "M", "梅"), + (0xFA45, "M", "海"), + (0xFA46, "M", "渚"), + (0xFA47, "M", "漢"), + (0xFA48, "M", "煮"), + (0xFA49, "M", "爫"), + (0xFA4A, "M", "琢"), + (0xFA4B, "M", "碑"), + (0xFA4C, "M", "社"), + (0xFA4D, "M", "祉"), + (0xFA4E, "M", "祈"), + (0xFA4F, "M", "祐"), + (0xFA50, "M", "祖"), + (0xFA51, "M", "祝"), + (0xFA52, "M", "禍"), + (0xFA53, "M", "禎"), + ] + + +def _seg_43() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0xFA54, "M", "穀"), + (0xFA55, "M", "突"), + (0xFA56, "M", "節"), + (0xFA57, "M", "練"), + (0xFA58, "M", "縉"), + (0xFA59, "M", "繁"), + (0xFA5A, "M", "署"), + (0xFA5B, "M", "者"), + (0xFA5C, "M", "臭"), + (0xFA5D, "M", "艹"), + (0xFA5F, "M", "著"), + (0xFA60, "M", "褐"), + (0xFA61, "M", "視"), + (0xFA62, "M", "謁"), + (0xFA63, "M", "謹"), + (0xFA64, "M", "賓"), + (0xFA65, "M", "贈"), + (0xFA66, "M", "辶"), + (0xFA67, "M", "逸"), + (0xFA68, "M", "難"), + (0xFA69, "M", "響"), + (0xFA6A, "M", "頻"), + (0xFA6B, "M", "恵"), + (0xFA6C, "M", "𤋮"), + (0xFA6D, "M", "舘"), + (0xFA6E, "X"), + (0xFA70, "M", "並"), + (0xFA71, "M", "况"), + (0xFA72, "M", "全"), + (0xFA73, "M", "侀"), + (0xFA74, "M", "充"), + (0xFA75, "M", "冀"), + (0xFA76, "M", "勇"), + (0xFA77, "M", "勺"), + (0xFA78, "M", "喝"), + (0xFA79, "M", "啕"), + (0xFA7A, "M", "喙"), + (0xFA7B, "M", "嗢"), + (0xFA7C, "M", "塚"), + (0xFA7D, "M", "墳"), + (0xFA7E, "M", "奄"), + (0xFA7F, "M", "奔"), + (0xFA80, "M", "婢"), + (0xFA81, "M", "嬨"), + (0xFA82, "M", "廒"), + (0xFA83, "M", "廙"), + (0xFA84, "M", "彩"), + (0xFA85, "M", "徭"), + (0xFA86, "M", "惘"), + (0xFA87, "M", "慎"), + (0xFA88, "M", "愈"), + (0xFA89, "M", "憎"), + (0xFA8A, "M", "慠"), + (0xFA8B, "M", "懲"), + (0xFA8C, "M", "戴"), + (0xFA8D, "M", "揄"), + (0xFA8E, "M", "搜"), + (0xFA8F, "M", "摒"), + (0xFA90, "M", "敖"), + (0xFA91, "M", "晴"), + (0xFA92, "M", "朗"), + (0xFA93, "M", "望"), + (0xFA94, "M", "杖"), + (0xFA95, "M", "歹"), + (0xFA96, "M", "殺"), + (0xFA97, "M", "流"), + (0xFA98, "M", "滛"), + (0xFA99, "M", "滋"), + (0xFA9A, "M", "漢"), + (0xFA9B, "M", "瀞"), + (0xFA9C, "M", "煮"), + (0xFA9D, "M", "瞧"), + (0xFA9E, "M", "爵"), + (0xFA9F, "M", "犯"), + (0xFAA0, "M", "猪"), + (0xFAA1, "M", "瑱"), + (0xFAA2, "M", "甆"), + (0xFAA3, "M", "画"), + (0xFAA4, "M", "瘝"), + (0xFAA5, "M", "瘟"), + (0xFAA6, "M", "益"), + (0xFAA7, "M", "盛"), + (0xFAA8, "M", "直"), + (0xFAA9, "M", "睊"), + (0xFAAA, "M", "着"), + (0xFAAB, "M", "磌"), + (0xFAAC, "M", "窱"), + (0xFAAD, "M", "節"), + (0xFAAE, "M", "类"), + (0xFAAF, "M", "絛"), + (0xFAB0, "M", "練"), + (0xFAB1, "M", "缾"), + (0xFAB2, "M", "者"), + (0xFAB3, "M", "荒"), + (0xFAB4, "M", "華"), + (0xFAB5, "M", "蝹"), + (0xFAB6, "M", "襁"), + (0xFAB7, "M", "覆"), + (0xFAB8, "M", "視"), + (0xFAB9, "M", "調"), + ] + + +def _seg_44() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0xFABA, "M", "諸"), + (0xFABB, "M", "請"), + (0xFABC, "M", "謁"), + (0xFABD, "M", "諾"), + (0xFABE, "M", "諭"), + (0xFABF, "M", "謹"), + (0xFAC0, "M", "變"), + (0xFAC1, "M", "贈"), + (0xFAC2, "M", "輸"), + (0xFAC3, "M", "遲"), + (0xFAC4, "M", "醙"), + (0xFAC5, "M", "鉶"), + (0xFAC6, "M", "陼"), + (0xFAC7, "M", "難"), + (0xFAC8, "M", "靖"), + (0xFAC9, "M", "韛"), + (0xFACA, "M", "響"), + (0xFACB, "M", "頋"), + (0xFACC, "M", "頻"), + (0xFACD, "M", "鬒"), + (0xFACE, "M", "龜"), + (0xFACF, "M", "𢡊"), + (0xFAD0, "M", "𢡄"), + (0xFAD1, "M", "𣏕"), + (0xFAD2, "M", "㮝"), + (0xFAD3, "M", "䀘"), + (0xFAD4, "M", "䀹"), + (0xFAD5, "M", "𥉉"), + (0xFAD6, "M", "𥳐"), + (0xFAD7, "M", "𧻓"), + (0xFAD8, "M", "齃"), + (0xFAD9, "M", "龎"), + (0xFADA, "X"), + (0xFB00, "M", "ff"), + (0xFB01, "M", "fi"), + (0xFB02, "M", "fl"), + (0xFB03, "M", "ffi"), + (0xFB04, "M", "ffl"), + (0xFB05, "M", "st"), + (0xFB07, "X"), + (0xFB13, "M", "մն"), + (0xFB14, "M", "մե"), + (0xFB15, "M", "մի"), + (0xFB16, "M", "վն"), + (0xFB17, "M", "մխ"), + (0xFB18, "X"), + (0xFB1D, "M", "יִ"), + (0xFB1E, "V"), + (0xFB1F, "M", "ײַ"), + (0xFB20, "M", "ע"), + (0xFB21, "M", "א"), + (0xFB22, "M", "ד"), + (0xFB23, "M", "ה"), + (0xFB24, "M", "כ"), + (0xFB25, "M", "ל"), + (0xFB26, "M", "ם"), + (0xFB27, "M", "ר"), + (0xFB28, "M", "ת"), + (0xFB29, "M", "+"), + (0xFB2A, "M", "שׁ"), + (0xFB2B, "M", "שׂ"), + (0xFB2C, "M", "שּׁ"), + (0xFB2D, "M", "שּׂ"), + (0xFB2E, "M", "אַ"), + (0xFB2F, "M", "אָ"), + (0xFB30, "M", "אּ"), + (0xFB31, "M", "בּ"), + (0xFB32, "M", "גּ"), + (0xFB33, "M", "דּ"), + (0xFB34, "M", "הּ"), + (0xFB35, "M", "וּ"), + (0xFB36, "M", "זּ"), + (0xFB37, "X"), + (0xFB38, "M", "טּ"), + (0xFB39, "M", "יּ"), + (0xFB3A, "M", "ךּ"), + (0xFB3B, "M", "כּ"), + (0xFB3C, "M", "לּ"), + (0xFB3D, "X"), + (0xFB3E, "M", "מּ"), + (0xFB3F, "X"), + (0xFB40, "M", "נּ"), + (0xFB41, "M", "סּ"), + (0xFB42, "X"), + (0xFB43, "M", "ףּ"), + (0xFB44, "M", "פּ"), + (0xFB45, "X"), + (0xFB46, "M", "צּ"), + (0xFB47, "M", "קּ"), + (0xFB48, "M", "רּ"), + (0xFB49, "M", "שּ"), + (0xFB4A, "M", "תּ"), + (0xFB4B, "M", "וֹ"), + (0xFB4C, "M", "בֿ"), + (0xFB4D, "M", "כֿ"), + (0xFB4E, "M", "פֿ"), + (0xFB4F, "M", "אל"), + (0xFB50, "M", "ٱ"), + (0xFB52, "M", "ٻ"), + (0xFB56, "M", "پ"), + ] + + +def _seg_45() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0xFB5A, "M", "ڀ"), + (0xFB5E, "M", "ٺ"), + (0xFB62, "M", "ٿ"), + (0xFB66, "M", "ٹ"), + (0xFB6A, "M", "ڤ"), + (0xFB6E, "M", "ڦ"), + (0xFB72, "M", "ڄ"), + (0xFB76, "M", "ڃ"), + (0xFB7A, "M", "چ"), + (0xFB7E, "M", "ڇ"), + (0xFB82, "M", "ڍ"), + (0xFB84, "M", "ڌ"), + (0xFB86, "M", "ڎ"), + (0xFB88, "M", "ڈ"), + (0xFB8A, "M", "ژ"), + (0xFB8C, "M", "ڑ"), + (0xFB8E, "M", "ک"), + (0xFB92, "M", "گ"), + (0xFB96, "M", "ڳ"), + (0xFB9A, "M", "ڱ"), + (0xFB9E, "M", "ں"), + (0xFBA0, "M", "ڻ"), + (0xFBA4, "M", "ۀ"), + (0xFBA6, "M", "ہ"), + (0xFBAA, "M", "ھ"), + (0xFBAE, "M", "ے"), + (0xFBB0, "M", "ۓ"), + (0xFBB2, "V"), + (0xFBC3, "X"), + (0xFBD3, "M", "ڭ"), + (0xFBD7, "M", "ۇ"), + (0xFBD9, "M", "ۆ"), + (0xFBDB, "M", "ۈ"), + (0xFBDD, "M", "ۇٴ"), + (0xFBDE, "M", "ۋ"), + (0xFBE0, "M", "ۅ"), + (0xFBE2, "M", "ۉ"), + (0xFBE4, "M", "ې"), + (0xFBE8, "M", "ى"), + (0xFBEA, "M", "ئا"), + (0xFBEC, "M", "ئە"), + (0xFBEE, "M", "ئو"), + (0xFBF0, "M", "ئۇ"), + (0xFBF2, "M", "ئۆ"), + (0xFBF4, "M", "ئۈ"), + (0xFBF6, "M", "ئې"), + (0xFBF9, "M", "ئى"), + (0xFBFC, "M", "ی"), + (0xFC00, "M", "ئج"), + (0xFC01, "M", "ئح"), + (0xFC02, "M", "ئم"), + (0xFC03, "M", "ئى"), + (0xFC04, "M", "ئي"), + (0xFC05, "M", "بج"), + (0xFC06, "M", "بح"), + (0xFC07, "M", "بخ"), + (0xFC08, "M", "بم"), + (0xFC09, "M", "بى"), + (0xFC0A, "M", "بي"), + (0xFC0B, "M", "تج"), + (0xFC0C, "M", "تح"), + (0xFC0D, "M", "تخ"), + (0xFC0E, "M", "تم"), + (0xFC0F, "M", "تى"), + (0xFC10, "M", "تي"), + (0xFC11, "M", "ثج"), + (0xFC12, "M", "ثم"), + (0xFC13, "M", "ثى"), + (0xFC14, "M", "ثي"), + (0xFC15, "M", "جح"), + (0xFC16, "M", "جم"), + (0xFC17, "M", "حج"), + (0xFC18, "M", "حم"), + (0xFC19, "M", "خج"), + (0xFC1A, "M", "خح"), + (0xFC1B, "M", "خم"), + (0xFC1C, "M", "سج"), + (0xFC1D, "M", "سح"), + (0xFC1E, "M", "سخ"), + (0xFC1F, "M", "سم"), + (0xFC20, "M", "صح"), + (0xFC21, "M", "صم"), + (0xFC22, "M", "ضج"), + (0xFC23, "M", "ضح"), + (0xFC24, "M", "ضخ"), + (0xFC25, "M", "ضم"), + (0xFC26, "M", "طح"), + (0xFC27, "M", "طم"), + (0xFC28, "M", "ظم"), + (0xFC29, "M", "عج"), + (0xFC2A, "M", "عم"), + (0xFC2B, "M", "غج"), + (0xFC2C, "M", "غم"), + (0xFC2D, "M", "فج"), + (0xFC2E, "M", "فح"), + (0xFC2F, "M", "فخ"), + (0xFC30, "M", "فم"), + (0xFC31, "M", "فى"), + (0xFC32, "M", "في"), + (0xFC33, "M", "قح"), + ] + + +def _seg_46() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0xFC34, "M", "قم"), + (0xFC35, "M", "قى"), + (0xFC36, "M", "قي"), + (0xFC37, "M", "كا"), + (0xFC38, "M", "كج"), + (0xFC39, "M", "كح"), + (0xFC3A, "M", "كخ"), + (0xFC3B, "M", "كل"), + (0xFC3C, "M", "كم"), + (0xFC3D, "M", "كى"), + (0xFC3E, "M", "كي"), + (0xFC3F, "M", "لج"), + (0xFC40, "M", "لح"), + (0xFC41, "M", "لخ"), + (0xFC42, "M", "لم"), + (0xFC43, "M", "لى"), + (0xFC44, "M", "لي"), + (0xFC45, "M", "مج"), + (0xFC46, "M", "مح"), + (0xFC47, "M", "مخ"), + (0xFC48, "M", "مم"), + (0xFC49, "M", "مى"), + (0xFC4A, "M", "مي"), + (0xFC4B, "M", "نج"), + (0xFC4C, "M", "نح"), + (0xFC4D, "M", "نخ"), + (0xFC4E, "M", "نم"), + (0xFC4F, "M", "نى"), + (0xFC50, "M", "ني"), + (0xFC51, "M", "هج"), + (0xFC52, "M", "هم"), + (0xFC53, "M", "هى"), + (0xFC54, "M", "هي"), + (0xFC55, "M", "يج"), + (0xFC56, "M", "يح"), + (0xFC57, "M", "يخ"), + (0xFC58, "M", "يم"), + (0xFC59, "M", "يى"), + (0xFC5A, "M", "يي"), + (0xFC5B, "M", "ذٰ"), + (0xFC5C, "M", "رٰ"), + (0xFC5D, "M", "ىٰ"), + (0xFC5E, "M", " ٌّ"), + (0xFC5F, "M", " ٍّ"), + (0xFC60, "M", " َّ"), + (0xFC61, "M", " ُّ"), + (0xFC62, "M", " ِّ"), + (0xFC63, "M", " ّٰ"), + (0xFC64, "M", "ئر"), + (0xFC65, "M", "ئز"), + (0xFC66, "M", "ئم"), + (0xFC67, "M", "ئن"), + (0xFC68, "M", "ئى"), + (0xFC69, "M", "ئي"), + (0xFC6A, "M", "بر"), + (0xFC6B, "M", "بز"), + (0xFC6C, "M", "بم"), + (0xFC6D, "M", "بن"), + (0xFC6E, "M", "بى"), + (0xFC6F, "M", "بي"), + (0xFC70, "M", "تر"), + (0xFC71, "M", "تز"), + (0xFC72, "M", "تم"), + (0xFC73, "M", "تن"), + (0xFC74, "M", "تى"), + (0xFC75, "M", "تي"), + (0xFC76, "M", "ثر"), + (0xFC77, "M", "ثز"), + (0xFC78, "M", "ثم"), + (0xFC79, "M", "ثن"), + (0xFC7A, "M", "ثى"), + (0xFC7B, "M", "ثي"), + (0xFC7C, "M", "فى"), + (0xFC7D, "M", "في"), + (0xFC7E, "M", "قى"), + (0xFC7F, "M", "قي"), + (0xFC80, "M", "كا"), + (0xFC81, "M", "كل"), + (0xFC82, "M", "كم"), + (0xFC83, "M", "كى"), + (0xFC84, "M", "كي"), + (0xFC85, "M", "لم"), + (0xFC86, "M", "لى"), + (0xFC87, "M", "لي"), + (0xFC88, "M", "ما"), + (0xFC89, "M", "مم"), + (0xFC8A, "M", "نر"), + (0xFC8B, "M", "نز"), + (0xFC8C, "M", "نم"), + (0xFC8D, "M", "نن"), + (0xFC8E, "M", "نى"), + (0xFC8F, "M", "ني"), + (0xFC90, "M", "ىٰ"), + (0xFC91, "M", "ير"), + (0xFC92, "M", "يز"), + (0xFC93, "M", "يم"), + (0xFC94, "M", "ين"), + (0xFC95, "M", "يى"), + (0xFC96, "M", "يي"), + (0xFC97, "M", "ئج"), + ] + + +def _seg_47() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0xFC98, "M", "ئح"), + (0xFC99, "M", "ئخ"), + (0xFC9A, "M", "ئم"), + (0xFC9B, "M", "ئه"), + (0xFC9C, "M", "بج"), + (0xFC9D, "M", "بح"), + (0xFC9E, "M", "بخ"), + (0xFC9F, "M", "بم"), + (0xFCA0, "M", "به"), + (0xFCA1, "M", "تج"), + (0xFCA2, "M", "تح"), + (0xFCA3, "M", "تخ"), + (0xFCA4, "M", "تم"), + (0xFCA5, "M", "ته"), + (0xFCA6, "M", "ثم"), + (0xFCA7, "M", "جح"), + (0xFCA8, "M", "جم"), + (0xFCA9, "M", "حج"), + (0xFCAA, "M", "حم"), + (0xFCAB, "M", "خج"), + (0xFCAC, "M", "خم"), + (0xFCAD, "M", "سج"), + (0xFCAE, "M", "سح"), + (0xFCAF, "M", "سخ"), + (0xFCB0, "M", "سم"), + (0xFCB1, "M", "صح"), + (0xFCB2, "M", "صخ"), + (0xFCB3, "M", "صم"), + (0xFCB4, "M", "ضج"), + (0xFCB5, "M", "ضح"), + (0xFCB6, "M", "ضخ"), + (0xFCB7, "M", "ضم"), + (0xFCB8, "M", "طح"), + (0xFCB9, "M", "ظم"), + (0xFCBA, "M", "عج"), + (0xFCBB, "M", "عم"), + (0xFCBC, "M", "غج"), + (0xFCBD, "M", "غم"), + (0xFCBE, "M", "فج"), + (0xFCBF, "M", "فح"), + (0xFCC0, "M", "فخ"), + (0xFCC1, "M", "فم"), + (0xFCC2, "M", "قح"), + (0xFCC3, "M", "قم"), + (0xFCC4, "M", "كج"), + (0xFCC5, "M", "كح"), + (0xFCC6, "M", "كخ"), + (0xFCC7, "M", "كل"), + (0xFCC8, "M", "كم"), + (0xFCC9, "M", "لج"), + (0xFCCA, "M", "لح"), + (0xFCCB, "M", "لخ"), + (0xFCCC, "M", "لم"), + (0xFCCD, "M", "له"), + (0xFCCE, "M", "مج"), + (0xFCCF, "M", "مح"), + (0xFCD0, "M", "مخ"), + (0xFCD1, "M", "مم"), + (0xFCD2, "M", "نج"), + (0xFCD3, "M", "نح"), + (0xFCD4, "M", "نخ"), + (0xFCD5, "M", "نم"), + (0xFCD6, "M", "نه"), + (0xFCD7, "M", "هج"), + (0xFCD8, "M", "هم"), + (0xFCD9, "M", "هٰ"), + (0xFCDA, "M", "يج"), + (0xFCDB, "M", "يح"), + (0xFCDC, "M", "يخ"), + (0xFCDD, "M", "يم"), + (0xFCDE, "M", "يه"), + (0xFCDF, "M", "ئم"), + (0xFCE0, "M", "ئه"), + (0xFCE1, "M", "بم"), + (0xFCE2, "M", "به"), + (0xFCE3, "M", "تم"), + (0xFCE4, "M", "ته"), + (0xFCE5, "M", "ثم"), + (0xFCE6, "M", "ثه"), + (0xFCE7, "M", "سم"), + (0xFCE8, "M", "سه"), + (0xFCE9, "M", "شم"), + (0xFCEA, "M", "شه"), + (0xFCEB, "M", "كل"), + (0xFCEC, "M", "كم"), + (0xFCED, "M", "لم"), + (0xFCEE, "M", "نم"), + (0xFCEF, "M", "نه"), + (0xFCF0, "M", "يم"), + (0xFCF1, "M", "يه"), + (0xFCF2, "M", "ـَّ"), + (0xFCF3, "M", "ـُّ"), + (0xFCF4, "M", "ـِّ"), + (0xFCF5, "M", "طى"), + (0xFCF6, "M", "طي"), + (0xFCF7, "M", "عى"), + (0xFCF8, "M", "عي"), + (0xFCF9, "M", "غى"), + (0xFCFA, "M", "غي"), + (0xFCFB, "M", "سى"), + ] + + +def _seg_48() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0xFCFC, "M", "سي"), + (0xFCFD, "M", "شى"), + (0xFCFE, "M", "شي"), + (0xFCFF, "M", "حى"), + (0xFD00, "M", "حي"), + (0xFD01, "M", "جى"), + (0xFD02, "M", "جي"), + (0xFD03, "M", "خى"), + (0xFD04, "M", "خي"), + (0xFD05, "M", "صى"), + (0xFD06, "M", "صي"), + (0xFD07, "M", "ضى"), + (0xFD08, "M", "ضي"), + (0xFD09, "M", "شج"), + (0xFD0A, "M", "شح"), + (0xFD0B, "M", "شخ"), + (0xFD0C, "M", "شم"), + (0xFD0D, "M", "شر"), + (0xFD0E, "M", "سر"), + (0xFD0F, "M", "صر"), + (0xFD10, "M", "ضر"), + (0xFD11, "M", "طى"), + (0xFD12, "M", "طي"), + (0xFD13, "M", "عى"), + (0xFD14, "M", "عي"), + (0xFD15, "M", "غى"), + (0xFD16, "M", "غي"), + (0xFD17, "M", "سى"), + (0xFD18, "M", "سي"), + (0xFD19, "M", "شى"), + (0xFD1A, "M", "شي"), + (0xFD1B, "M", "حى"), + (0xFD1C, "M", "حي"), + (0xFD1D, "M", "جى"), + (0xFD1E, "M", "جي"), + (0xFD1F, "M", "خى"), + (0xFD20, "M", "خي"), + (0xFD21, "M", "صى"), + (0xFD22, "M", "صي"), + (0xFD23, "M", "ضى"), + (0xFD24, "M", "ضي"), + (0xFD25, "M", "شج"), + (0xFD26, "M", "شح"), + (0xFD27, "M", "شخ"), + (0xFD28, "M", "شم"), + (0xFD29, "M", "شر"), + (0xFD2A, "M", "سر"), + (0xFD2B, "M", "صر"), + (0xFD2C, "M", "ضر"), + (0xFD2D, "M", "شج"), + (0xFD2E, "M", "شح"), + (0xFD2F, "M", "شخ"), + (0xFD30, "M", "شم"), + (0xFD31, "M", "سه"), + (0xFD32, "M", "شه"), + (0xFD33, "M", "طم"), + (0xFD34, "M", "سج"), + (0xFD35, "M", "سح"), + (0xFD36, "M", "سخ"), + (0xFD37, "M", "شج"), + (0xFD38, "M", "شح"), + (0xFD39, "M", "شخ"), + (0xFD3A, "M", "طم"), + (0xFD3B, "M", "ظم"), + (0xFD3C, "M", "اً"), + (0xFD3E, "V"), + (0xFD50, "M", "تجم"), + (0xFD51, "M", "تحج"), + (0xFD53, "M", "تحم"), + (0xFD54, "M", "تخم"), + (0xFD55, "M", "تمج"), + (0xFD56, "M", "تمح"), + (0xFD57, "M", "تمخ"), + (0xFD58, "M", "جمح"), + (0xFD5A, "M", "حمي"), + (0xFD5B, "M", "حمى"), + (0xFD5C, "M", "سحج"), + (0xFD5D, "M", "سجح"), + (0xFD5E, "M", "سجى"), + (0xFD5F, "M", "سمح"), + (0xFD61, "M", "سمج"), + (0xFD62, "M", "سمم"), + (0xFD64, "M", "صحح"), + (0xFD66, "M", "صمم"), + (0xFD67, "M", "شحم"), + (0xFD69, "M", "شجي"), + (0xFD6A, "M", "شمخ"), + (0xFD6C, "M", "شمم"), + (0xFD6E, "M", "ضحى"), + (0xFD6F, "M", "ضخم"), + (0xFD71, "M", "طمح"), + (0xFD73, "M", "طمم"), + (0xFD74, "M", "طمي"), + (0xFD75, "M", "عجم"), + (0xFD76, "M", "عمم"), + (0xFD78, "M", "عمى"), + (0xFD79, "M", "غمم"), + (0xFD7A, "M", "غمي"), + (0xFD7B, "M", "غمى"), + (0xFD7C, "M", "فخم"), + ] + + +def _seg_49() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0xFD7E, "M", "قمح"), + (0xFD7F, "M", "قمم"), + (0xFD80, "M", "لحم"), + (0xFD81, "M", "لحي"), + (0xFD82, "M", "لحى"), + (0xFD83, "M", "لجج"), + (0xFD85, "M", "لخم"), + (0xFD87, "M", "لمح"), + (0xFD89, "M", "محج"), + (0xFD8A, "M", "محم"), + (0xFD8B, "M", "محي"), + (0xFD8C, "M", "مجح"), + (0xFD8D, "M", "مجم"), + (0xFD8E, "M", "مخج"), + (0xFD8F, "M", "مخم"), + (0xFD90, "X"), + (0xFD92, "M", "مجخ"), + (0xFD93, "M", "همج"), + (0xFD94, "M", "همم"), + (0xFD95, "M", "نحم"), + (0xFD96, "M", "نحى"), + (0xFD97, "M", "نجم"), + (0xFD99, "M", "نجى"), + (0xFD9A, "M", "نمي"), + (0xFD9B, "M", "نمى"), + (0xFD9C, "M", "يمم"), + (0xFD9E, "M", "بخي"), + (0xFD9F, "M", "تجي"), + (0xFDA0, "M", "تجى"), + (0xFDA1, "M", "تخي"), + (0xFDA2, "M", "تخى"), + (0xFDA3, "M", "تمي"), + (0xFDA4, "M", "تمى"), + (0xFDA5, "M", "جمي"), + (0xFDA6, "M", "جحى"), + (0xFDA7, "M", "جمى"), + (0xFDA8, "M", "سخى"), + (0xFDA9, "M", "صحي"), + (0xFDAA, "M", "شحي"), + (0xFDAB, "M", "ضحي"), + (0xFDAC, "M", "لجي"), + (0xFDAD, "M", "لمي"), + (0xFDAE, "M", "يحي"), + (0xFDAF, "M", "يجي"), + (0xFDB0, "M", "يمي"), + (0xFDB1, "M", "ممي"), + (0xFDB2, "M", "قمي"), + (0xFDB3, "M", "نحي"), + (0xFDB4, "M", "قمح"), + (0xFDB5, "M", "لحم"), + (0xFDB6, "M", "عمي"), + (0xFDB7, "M", "كمي"), + (0xFDB8, "M", "نجح"), + (0xFDB9, "M", "مخي"), + (0xFDBA, "M", "لجم"), + (0xFDBB, "M", "كمم"), + (0xFDBC, "M", "لجم"), + (0xFDBD, "M", "نجح"), + (0xFDBE, "M", "جحي"), + (0xFDBF, "M", "حجي"), + (0xFDC0, "M", "مجي"), + (0xFDC1, "M", "فمي"), + (0xFDC2, "M", "بحي"), + (0xFDC3, "M", "كمم"), + (0xFDC4, "M", "عجم"), + (0xFDC5, "M", "صمم"), + (0xFDC6, "M", "سخي"), + (0xFDC7, "M", "نجي"), + (0xFDC8, "X"), + (0xFDCF, "V"), + (0xFDD0, "X"), + (0xFDF0, "M", "صلے"), + (0xFDF1, "M", "قلے"), + (0xFDF2, "M", "الله"), + (0xFDF3, "M", "اكبر"), + (0xFDF4, "M", "محمد"), + (0xFDF5, "M", "صلعم"), + (0xFDF6, "M", "رسول"), + (0xFDF7, "M", "عليه"), + (0xFDF8, "M", "وسلم"), + (0xFDF9, "M", "صلى"), + (0xFDFA, "M", "صلى الله عليه وسلم"), + (0xFDFB, "M", "جل جلاله"), + (0xFDFC, "M", "ریال"), + (0xFDFD, "V"), + (0xFE00, "I"), + (0xFE10, "M", ","), + (0xFE11, "M", "、"), + (0xFE12, "X"), + (0xFE13, "M", ":"), + (0xFE14, "M", ";"), + (0xFE15, "M", "!"), + (0xFE16, "M", "?"), + (0xFE17, "M", "〖"), + (0xFE18, "M", "〗"), + (0xFE19, "X"), + (0xFE20, "V"), + (0xFE30, "X"), + (0xFE31, "M", "—"), + (0xFE32, "M", "–"), + ] + + +def _seg_50() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0xFE33, "M", "_"), + (0xFE35, "M", "("), + (0xFE36, "M", ")"), + (0xFE37, "M", "{"), + (0xFE38, "M", "}"), + (0xFE39, "M", "〔"), + (0xFE3A, "M", "〕"), + (0xFE3B, "M", "【"), + (0xFE3C, "M", "】"), + (0xFE3D, "M", "《"), + (0xFE3E, "M", "》"), + (0xFE3F, "M", "〈"), + (0xFE40, "M", "〉"), + (0xFE41, "M", "「"), + (0xFE42, "M", "」"), + (0xFE43, "M", "『"), + (0xFE44, "M", "』"), + (0xFE45, "V"), + (0xFE47, "M", "["), + (0xFE48, "M", "]"), + (0xFE49, "M", " ̅"), + (0xFE4D, "M", "_"), + (0xFE50, "M", ","), + (0xFE51, "M", "、"), + (0xFE52, "X"), + (0xFE54, "M", ";"), + (0xFE55, "M", ":"), + (0xFE56, "M", "?"), + (0xFE57, "M", "!"), + (0xFE58, "M", "—"), + (0xFE59, "M", "("), + (0xFE5A, "M", ")"), + (0xFE5B, "M", "{"), + (0xFE5C, "M", "}"), + (0xFE5D, "M", "〔"), + (0xFE5E, "M", "〕"), + (0xFE5F, "M", "#"), + (0xFE60, "M", "&"), + (0xFE61, "M", "*"), + (0xFE62, "M", "+"), + (0xFE63, "M", "-"), + (0xFE64, "M", "<"), + (0xFE65, "M", ">"), + (0xFE66, "M", "="), + (0xFE67, "X"), + (0xFE68, "M", "\\"), + (0xFE69, "M", "$"), + (0xFE6A, "M", "%"), + (0xFE6B, "M", "@"), + (0xFE6C, "X"), + (0xFE70, "M", " ً"), + (0xFE71, "M", "ـً"), + (0xFE72, "M", " ٌ"), + (0xFE73, "V"), + (0xFE74, "M", " ٍ"), + (0xFE75, "X"), + (0xFE76, "M", " َ"), + (0xFE77, "M", "ـَ"), + (0xFE78, "M", " ُ"), + (0xFE79, "M", "ـُ"), + (0xFE7A, "M", " ِ"), + (0xFE7B, "M", "ـِ"), + (0xFE7C, "M", " ّ"), + (0xFE7D, "M", "ـّ"), + (0xFE7E, "M", " ْ"), + (0xFE7F, "M", "ـْ"), + (0xFE80, "M", "ء"), + (0xFE81, "M", "آ"), + (0xFE83, "M", "أ"), + (0xFE85, "M", "ؤ"), + (0xFE87, "M", "إ"), + (0xFE89, "M", "ئ"), + (0xFE8D, "M", "ا"), + (0xFE8F, "M", "ب"), + (0xFE93, "M", "ة"), + (0xFE95, "M", "ت"), + (0xFE99, "M", "ث"), + (0xFE9D, "M", "ج"), + (0xFEA1, "M", "ح"), + (0xFEA5, "M", "خ"), + (0xFEA9, "M", "د"), + (0xFEAB, "M", "ذ"), + (0xFEAD, "M", "ر"), + (0xFEAF, "M", "ز"), + (0xFEB1, "M", "س"), + (0xFEB5, "M", "ش"), + (0xFEB9, "M", "ص"), + (0xFEBD, "M", "ض"), + (0xFEC1, "M", "ط"), + (0xFEC5, "M", "ظ"), + (0xFEC9, "M", "ع"), + (0xFECD, "M", "غ"), + (0xFED1, "M", "ف"), + (0xFED5, "M", "ق"), + (0xFED9, "M", "ك"), + (0xFEDD, "M", "ل"), + (0xFEE1, "M", "م"), + (0xFEE5, "M", "ن"), + (0xFEE9, "M", "ه"), + (0xFEED, "M", "و"), + ] + + +def _seg_51() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0xFEEF, "M", "ى"), + (0xFEF1, "M", "ي"), + (0xFEF5, "M", "لآ"), + (0xFEF7, "M", "لأ"), + (0xFEF9, "M", "لإ"), + (0xFEFB, "M", "لا"), + (0xFEFD, "X"), + (0xFEFF, "I"), + (0xFF00, "X"), + (0xFF01, "M", "!"), + (0xFF02, "M", '"'), + (0xFF03, "M", "#"), + (0xFF04, "M", "$"), + (0xFF05, "M", "%"), + (0xFF06, "M", "&"), + (0xFF07, "M", "'"), + (0xFF08, "M", "("), + (0xFF09, "M", ")"), + (0xFF0A, "M", "*"), + (0xFF0B, "M", "+"), + (0xFF0C, "M", ","), + (0xFF0D, "M", "-"), + (0xFF0E, "M", "."), + (0xFF0F, "M", "/"), + (0xFF10, "M", "0"), + (0xFF11, "M", "1"), + (0xFF12, "M", "2"), + (0xFF13, "M", "3"), + (0xFF14, "M", "4"), + (0xFF15, "M", "5"), + (0xFF16, "M", "6"), + (0xFF17, "M", "7"), + (0xFF18, "M", "8"), + (0xFF19, "M", "9"), + (0xFF1A, "M", ":"), + (0xFF1B, "M", ";"), + (0xFF1C, "M", "<"), + (0xFF1D, "M", "="), + (0xFF1E, "M", ">"), + (0xFF1F, "M", "?"), + (0xFF20, "M", "@"), + (0xFF21, "M", "a"), + (0xFF22, "M", "b"), + (0xFF23, "M", "c"), + (0xFF24, "M", "d"), + (0xFF25, "M", "e"), + (0xFF26, "M", "f"), + (0xFF27, "M", "g"), + (0xFF28, "M", "h"), + (0xFF29, "M", "i"), + (0xFF2A, "M", "j"), + (0xFF2B, "M", "k"), + (0xFF2C, "M", "l"), + (0xFF2D, "M", "m"), + (0xFF2E, "M", "n"), + (0xFF2F, "M", "o"), + (0xFF30, "M", "p"), + (0xFF31, "M", "q"), + (0xFF32, "M", "r"), + (0xFF33, "M", "s"), + (0xFF34, "M", "t"), + (0xFF35, "M", "u"), + (0xFF36, "M", "v"), + (0xFF37, "M", "w"), + (0xFF38, "M", "x"), + (0xFF39, "M", "y"), + (0xFF3A, "M", "z"), + (0xFF3B, "M", "["), + (0xFF3C, "M", "\\"), + (0xFF3D, "M", "]"), + (0xFF3E, "M", "^"), + (0xFF3F, "M", "_"), + (0xFF40, "M", "`"), + (0xFF41, "M", "a"), + (0xFF42, "M", "b"), + (0xFF43, "M", "c"), + (0xFF44, "M", "d"), + (0xFF45, "M", "e"), + (0xFF46, "M", "f"), + (0xFF47, "M", "g"), + (0xFF48, "M", "h"), + (0xFF49, "M", "i"), + (0xFF4A, "M", "j"), + (0xFF4B, "M", "k"), + (0xFF4C, "M", "l"), + (0xFF4D, "M", "m"), + (0xFF4E, "M", "n"), + (0xFF4F, "M", "o"), + (0xFF50, "M", "p"), + (0xFF51, "M", "q"), + (0xFF52, "M", "r"), + (0xFF53, "M", "s"), + (0xFF54, "M", "t"), + (0xFF55, "M", "u"), + (0xFF56, "M", "v"), + (0xFF57, "M", "w"), + (0xFF58, "M", "x"), + (0xFF59, "M", "y"), + (0xFF5A, "M", "z"), + (0xFF5B, "M", "{"), + ] + + +def _seg_52() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0xFF5C, "M", "|"), + (0xFF5D, "M", "}"), + (0xFF5E, "M", "~"), + (0xFF5F, "M", "⦅"), + (0xFF60, "M", "⦆"), + (0xFF61, "M", "."), + (0xFF62, "M", "「"), + (0xFF63, "M", "」"), + (0xFF64, "M", "、"), + (0xFF65, "M", "・"), + (0xFF66, "M", "ヲ"), + (0xFF67, "M", "ァ"), + (0xFF68, "M", "ィ"), + (0xFF69, "M", "ゥ"), + (0xFF6A, "M", "ェ"), + (0xFF6B, "M", "ォ"), + (0xFF6C, "M", "ャ"), + (0xFF6D, "M", "ュ"), + (0xFF6E, "M", "ョ"), + (0xFF6F, "M", "ッ"), + (0xFF70, "M", "ー"), + (0xFF71, "M", "ア"), + (0xFF72, "M", "イ"), + (0xFF73, "M", "ウ"), + (0xFF74, "M", "エ"), + (0xFF75, "M", "オ"), + (0xFF76, "M", "カ"), + (0xFF77, "M", "キ"), + (0xFF78, "M", "ク"), + (0xFF79, "M", "ケ"), + (0xFF7A, "M", "コ"), + (0xFF7B, "M", "サ"), + (0xFF7C, "M", "シ"), + (0xFF7D, "M", "ス"), + (0xFF7E, "M", "セ"), + (0xFF7F, "M", "ソ"), + (0xFF80, "M", "タ"), + (0xFF81, "M", "チ"), + (0xFF82, "M", "ツ"), + (0xFF83, "M", "テ"), + (0xFF84, "M", "ト"), + (0xFF85, "M", "ナ"), + (0xFF86, "M", "ニ"), + (0xFF87, "M", "ヌ"), + (0xFF88, "M", "ネ"), + (0xFF89, "M", "ノ"), + (0xFF8A, "M", "ハ"), + (0xFF8B, "M", "ヒ"), + (0xFF8C, "M", "フ"), + (0xFF8D, "M", "ヘ"), + (0xFF8E, "M", "ホ"), + (0xFF8F, "M", "マ"), + (0xFF90, "M", "ミ"), + (0xFF91, "M", "ム"), + (0xFF92, "M", "メ"), + (0xFF93, "M", "モ"), + (0xFF94, "M", "ヤ"), + (0xFF95, "M", "ユ"), + (0xFF96, "M", "ヨ"), + (0xFF97, "M", "ラ"), + (0xFF98, "M", "リ"), + (0xFF99, "M", "ル"), + (0xFF9A, "M", "レ"), + (0xFF9B, "M", "ロ"), + (0xFF9C, "M", "ワ"), + (0xFF9D, "M", "ン"), + (0xFF9E, "M", "゙"), + (0xFF9F, "M", "゚"), + (0xFFA0, "I"), + (0xFFA1, "M", "ᄀ"), + (0xFFA2, "M", "ᄁ"), + (0xFFA3, "M", "ᆪ"), + (0xFFA4, "M", "ᄂ"), + (0xFFA5, "M", "ᆬ"), + (0xFFA6, "M", "ᆭ"), + (0xFFA7, "M", "ᄃ"), + (0xFFA8, "M", "ᄄ"), + (0xFFA9, "M", "ᄅ"), + (0xFFAA, "M", "ᆰ"), + (0xFFAB, "M", "ᆱ"), + (0xFFAC, "M", "ᆲ"), + (0xFFAD, "M", "ᆳ"), + (0xFFAE, "M", "ᆴ"), + (0xFFAF, "M", "ᆵ"), + (0xFFB0, "M", "ᄚ"), + (0xFFB1, "M", "ᄆ"), + (0xFFB2, "M", "ᄇ"), + (0xFFB3, "M", "ᄈ"), + (0xFFB4, "M", "ᄡ"), + (0xFFB5, "M", "ᄉ"), + (0xFFB6, "M", "ᄊ"), + (0xFFB7, "M", "ᄋ"), + (0xFFB8, "M", "ᄌ"), + (0xFFB9, "M", "ᄍ"), + (0xFFBA, "M", "ᄎ"), + (0xFFBB, "M", "ᄏ"), + (0xFFBC, "M", "ᄐ"), + (0xFFBD, "M", "ᄑ"), + (0xFFBE, "M", "ᄒ"), + (0xFFBF, "X"), + ] + + +def _seg_53() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0xFFC2, "M", "ᅡ"), + (0xFFC3, "M", "ᅢ"), + (0xFFC4, "M", "ᅣ"), + (0xFFC5, "M", "ᅤ"), + (0xFFC6, "M", "ᅥ"), + (0xFFC7, "M", "ᅦ"), + (0xFFC8, "X"), + (0xFFCA, "M", "ᅧ"), + (0xFFCB, "M", "ᅨ"), + (0xFFCC, "M", "ᅩ"), + (0xFFCD, "M", "ᅪ"), + (0xFFCE, "M", "ᅫ"), + (0xFFCF, "M", "ᅬ"), + (0xFFD0, "X"), + (0xFFD2, "M", "ᅭ"), + (0xFFD3, "M", "ᅮ"), + (0xFFD4, "M", "ᅯ"), + (0xFFD5, "M", "ᅰ"), + (0xFFD6, "M", "ᅱ"), + (0xFFD7, "M", "ᅲ"), + (0xFFD8, "X"), + (0xFFDA, "M", "ᅳ"), + (0xFFDB, "M", "ᅴ"), + (0xFFDC, "M", "ᅵ"), + (0xFFDD, "X"), + (0xFFE0, "M", "¢"), + (0xFFE1, "M", "£"), + (0xFFE2, "M", "¬"), + (0xFFE3, "M", " ̄"), + (0xFFE4, "M", "¦"), + (0xFFE5, "M", "¥"), + (0xFFE6, "M", "₩"), + (0xFFE7, "X"), + (0xFFE8, "M", "│"), + (0xFFE9, "M", "←"), + (0xFFEA, "M", "↑"), + (0xFFEB, "M", "→"), + (0xFFEC, "M", "↓"), + (0xFFED, "M", "■"), + (0xFFEE, "M", "○"), + (0xFFEF, "X"), + (0x10000, "V"), + (0x1000C, "X"), + (0x1000D, "V"), + (0x10027, "X"), + (0x10028, "V"), + (0x1003B, "X"), + (0x1003C, "V"), + (0x1003E, "X"), + (0x1003F, "V"), + (0x1004E, "X"), + (0x10050, "V"), + (0x1005E, "X"), + (0x10080, "V"), + (0x100FB, "X"), + (0x10100, "V"), + (0x10103, "X"), + (0x10107, "V"), + (0x10134, "X"), + (0x10137, "V"), + (0x1018F, "X"), + (0x10190, "V"), + (0x1019D, "X"), + (0x101A0, "V"), + (0x101A1, "X"), + (0x101D0, "V"), + (0x101FE, "X"), + (0x10280, "V"), + (0x1029D, "X"), + (0x102A0, "V"), + (0x102D1, "X"), + (0x102E0, "V"), + (0x102FC, "X"), + (0x10300, "V"), + (0x10324, "X"), + (0x1032D, "V"), + (0x1034B, "X"), + (0x10350, "V"), + (0x1037B, "X"), + (0x10380, "V"), + (0x1039E, "X"), + (0x1039F, "V"), + (0x103C4, "X"), + (0x103C8, "V"), + (0x103D6, "X"), + (0x10400, "M", "𐐨"), + (0x10401, "M", "𐐩"), + (0x10402, "M", "𐐪"), + (0x10403, "M", "𐐫"), + (0x10404, "M", "𐐬"), + (0x10405, "M", "𐐭"), + (0x10406, "M", "𐐮"), + (0x10407, "M", "𐐯"), + (0x10408, "M", "𐐰"), + (0x10409, "M", "𐐱"), + (0x1040A, "M", "𐐲"), + (0x1040B, "M", "𐐳"), + (0x1040C, "M", "𐐴"), + (0x1040D, "M", "𐐵"), + (0x1040E, "M", "𐐶"), + ] + + +def _seg_54() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0x1040F, "M", "𐐷"), + (0x10410, "M", "𐐸"), + (0x10411, "M", "𐐹"), + (0x10412, "M", "𐐺"), + (0x10413, "M", "𐐻"), + (0x10414, "M", "𐐼"), + (0x10415, "M", "𐐽"), + (0x10416, "M", "𐐾"), + (0x10417, "M", "𐐿"), + (0x10418, "M", "𐑀"), + (0x10419, "M", "𐑁"), + (0x1041A, "M", "𐑂"), + (0x1041B, "M", "𐑃"), + (0x1041C, "M", "𐑄"), + (0x1041D, "M", "𐑅"), + (0x1041E, "M", "𐑆"), + (0x1041F, "M", "𐑇"), + (0x10420, "M", "𐑈"), + (0x10421, "M", "𐑉"), + (0x10422, "M", "𐑊"), + (0x10423, "M", "𐑋"), + (0x10424, "M", "𐑌"), + (0x10425, "M", "𐑍"), + (0x10426, "M", "𐑎"), + (0x10427, "M", "𐑏"), + (0x10428, "V"), + (0x1049E, "X"), + (0x104A0, "V"), + (0x104AA, "X"), + (0x104B0, "M", "𐓘"), + (0x104B1, "M", "𐓙"), + (0x104B2, "M", "𐓚"), + (0x104B3, "M", "𐓛"), + (0x104B4, "M", "𐓜"), + (0x104B5, "M", "𐓝"), + (0x104B6, "M", "𐓞"), + (0x104B7, "M", "𐓟"), + (0x104B8, "M", "𐓠"), + (0x104B9, "M", "𐓡"), + (0x104BA, "M", "𐓢"), + (0x104BB, "M", "𐓣"), + (0x104BC, "M", "𐓤"), + (0x104BD, "M", "𐓥"), + (0x104BE, "M", "𐓦"), + (0x104BF, "M", "𐓧"), + (0x104C0, "M", "𐓨"), + (0x104C1, "M", "𐓩"), + (0x104C2, "M", "𐓪"), + (0x104C3, "M", "𐓫"), + (0x104C4, "M", "𐓬"), + (0x104C5, "M", "𐓭"), + (0x104C6, "M", "𐓮"), + (0x104C7, "M", "𐓯"), + (0x104C8, "M", "𐓰"), + (0x104C9, "M", "𐓱"), + (0x104CA, "M", "𐓲"), + (0x104CB, "M", "𐓳"), + (0x104CC, "M", "𐓴"), + (0x104CD, "M", "𐓵"), + (0x104CE, "M", "𐓶"), + (0x104CF, "M", "𐓷"), + (0x104D0, "M", "𐓸"), + (0x104D1, "M", "𐓹"), + (0x104D2, "M", "𐓺"), + (0x104D3, "M", "𐓻"), + (0x104D4, "X"), + (0x104D8, "V"), + (0x104FC, "X"), + (0x10500, "V"), + (0x10528, "X"), + (0x10530, "V"), + (0x10564, "X"), + (0x1056F, "V"), + (0x10570, "M", "𐖗"), + (0x10571, "M", "𐖘"), + (0x10572, "M", "𐖙"), + (0x10573, "M", "𐖚"), + (0x10574, "M", "𐖛"), + (0x10575, "M", "𐖜"), + (0x10576, "M", "𐖝"), + (0x10577, "M", "𐖞"), + (0x10578, "M", "𐖟"), + (0x10579, "M", "𐖠"), + (0x1057A, "M", "𐖡"), + (0x1057B, "X"), + (0x1057C, "M", "𐖣"), + (0x1057D, "M", "𐖤"), + (0x1057E, "M", "𐖥"), + (0x1057F, "M", "𐖦"), + (0x10580, "M", "𐖧"), + (0x10581, "M", "𐖨"), + (0x10582, "M", "𐖩"), + (0x10583, "M", "𐖪"), + (0x10584, "M", "𐖫"), + (0x10585, "M", "𐖬"), + (0x10586, "M", "𐖭"), + (0x10587, "M", "𐖮"), + (0x10588, "M", "𐖯"), + (0x10589, "M", "𐖰"), + (0x1058A, "M", "𐖱"), + ] + + +def _seg_55() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0x1058B, "X"), + (0x1058C, "M", "𐖳"), + (0x1058D, "M", "𐖴"), + (0x1058E, "M", "𐖵"), + (0x1058F, "M", "𐖶"), + (0x10590, "M", "𐖷"), + (0x10591, "M", "𐖸"), + (0x10592, "M", "𐖹"), + (0x10593, "X"), + (0x10594, "M", "𐖻"), + (0x10595, "M", "𐖼"), + (0x10596, "X"), + (0x10597, "V"), + (0x105A2, "X"), + (0x105A3, "V"), + (0x105B2, "X"), + (0x105B3, "V"), + (0x105BA, "X"), + (0x105BB, "V"), + (0x105BD, "X"), + (0x105C0, "V"), + (0x105F4, "X"), + (0x10600, "V"), + (0x10737, "X"), + (0x10740, "V"), + (0x10756, "X"), + (0x10760, "V"), + (0x10768, "X"), + (0x10780, "V"), + (0x10781, "M", "ː"), + (0x10782, "M", "ˑ"), + (0x10783, "M", "æ"), + (0x10784, "M", "ʙ"), + (0x10785, "M", "ɓ"), + (0x10786, "X"), + (0x10787, "M", "ʣ"), + (0x10788, "M", "ꭦ"), + (0x10789, "M", "ʥ"), + (0x1078A, "M", "ʤ"), + (0x1078B, "M", "ɖ"), + (0x1078C, "M", "ɗ"), + (0x1078D, "M", "ᶑ"), + (0x1078E, "M", "ɘ"), + (0x1078F, "M", "ɞ"), + (0x10790, "M", "ʩ"), + (0x10791, "M", "ɤ"), + (0x10792, "M", "ɢ"), + (0x10793, "M", "ɠ"), + (0x10794, "M", "ʛ"), + (0x10795, "M", "ħ"), + (0x10796, "M", "ʜ"), + (0x10797, "M", "ɧ"), + (0x10798, "M", "ʄ"), + (0x10799, "M", "ʪ"), + (0x1079A, "M", "ʫ"), + (0x1079B, "M", "ɬ"), + (0x1079C, "M", "𝼄"), + (0x1079D, "M", "ꞎ"), + (0x1079E, "M", "ɮ"), + (0x1079F, "M", "𝼅"), + (0x107A0, "M", "ʎ"), + (0x107A1, "M", "𝼆"), + (0x107A2, "M", "ø"), + (0x107A3, "M", "ɶ"), + (0x107A4, "M", "ɷ"), + (0x107A5, "M", "q"), + (0x107A6, "M", "ɺ"), + (0x107A7, "M", "𝼈"), + (0x107A8, "M", "ɽ"), + (0x107A9, "M", "ɾ"), + (0x107AA, "M", "ʀ"), + (0x107AB, "M", "ʨ"), + (0x107AC, "M", "ʦ"), + (0x107AD, "M", "ꭧ"), + (0x107AE, "M", "ʧ"), + (0x107AF, "M", "ʈ"), + (0x107B0, "M", "ⱱ"), + (0x107B1, "X"), + (0x107B2, "M", "ʏ"), + (0x107B3, "M", "ʡ"), + (0x107B4, "M", "ʢ"), + (0x107B5, "M", "ʘ"), + (0x107B6, "M", "ǀ"), + (0x107B7, "M", "ǁ"), + (0x107B8, "M", "ǂ"), + (0x107B9, "M", "𝼊"), + (0x107BA, "M", "𝼞"), + (0x107BB, "X"), + (0x10800, "V"), + (0x10806, "X"), + (0x10808, "V"), + (0x10809, "X"), + (0x1080A, "V"), + (0x10836, "X"), + (0x10837, "V"), + (0x10839, "X"), + (0x1083C, "V"), + (0x1083D, "X"), + (0x1083F, "V"), + (0x10856, "X"), + ] + + +def _seg_56() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0x10857, "V"), + (0x1089F, "X"), + (0x108A7, "V"), + (0x108B0, "X"), + (0x108E0, "V"), + (0x108F3, "X"), + (0x108F4, "V"), + (0x108F6, "X"), + (0x108FB, "V"), + (0x1091C, "X"), + (0x1091F, "V"), + (0x1093A, "X"), + (0x1093F, "V"), + (0x10940, "X"), + (0x10980, "V"), + (0x109B8, "X"), + (0x109BC, "V"), + (0x109D0, "X"), + (0x109D2, "V"), + (0x10A04, "X"), + (0x10A05, "V"), + (0x10A07, "X"), + (0x10A0C, "V"), + (0x10A14, "X"), + (0x10A15, "V"), + (0x10A18, "X"), + (0x10A19, "V"), + (0x10A36, "X"), + (0x10A38, "V"), + (0x10A3B, "X"), + (0x10A3F, "V"), + (0x10A49, "X"), + (0x10A50, "V"), + (0x10A59, "X"), + (0x10A60, "V"), + (0x10AA0, "X"), + (0x10AC0, "V"), + (0x10AE7, "X"), + (0x10AEB, "V"), + (0x10AF7, "X"), + (0x10B00, "V"), + (0x10B36, "X"), + (0x10B39, "V"), + (0x10B56, "X"), + (0x10B58, "V"), + (0x10B73, "X"), + (0x10B78, "V"), + (0x10B92, "X"), + (0x10B99, "V"), + (0x10B9D, "X"), + (0x10BA9, "V"), + (0x10BB0, "X"), + (0x10C00, "V"), + (0x10C49, "X"), + (0x10C80, "M", "𐳀"), + (0x10C81, "M", "𐳁"), + (0x10C82, "M", "𐳂"), + (0x10C83, "M", "𐳃"), + (0x10C84, "M", "𐳄"), + (0x10C85, "M", "𐳅"), + (0x10C86, "M", "𐳆"), + (0x10C87, "M", "𐳇"), + (0x10C88, "M", "𐳈"), + (0x10C89, "M", "𐳉"), + (0x10C8A, "M", "𐳊"), + (0x10C8B, "M", "𐳋"), + (0x10C8C, "M", "𐳌"), + (0x10C8D, "M", "𐳍"), + (0x10C8E, "M", "𐳎"), + (0x10C8F, "M", "𐳏"), + (0x10C90, "M", "𐳐"), + (0x10C91, "M", "𐳑"), + (0x10C92, "M", "𐳒"), + (0x10C93, "M", "𐳓"), + (0x10C94, "M", "𐳔"), + (0x10C95, "M", "𐳕"), + (0x10C96, "M", "𐳖"), + (0x10C97, "M", "𐳗"), + (0x10C98, "M", "𐳘"), + (0x10C99, "M", "𐳙"), + (0x10C9A, "M", "𐳚"), + (0x10C9B, "M", "𐳛"), + (0x10C9C, "M", "𐳜"), + (0x10C9D, "M", "𐳝"), + (0x10C9E, "M", "𐳞"), + (0x10C9F, "M", "𐳟"), + (0x10CA0, "M", "𐳠"), + (0x10CA1, "M", "𐳡"), + (0x10CA2, "M", "𐳢"), + (0x10CA3, "M", "𐳣"), + (0x10CA4, "M", "𐳤"), + (0x10CA5, "M", "𐳥"), + (0x10CA6, "M", "𐳦"), + (0x10CA7, "M", "𐳧"), + (0x10CA8, "M", "𐳨"), + (0x10CA9, "M", "𐳩"), + (0x10CAA, "M", "𐳪"), + (0x10CAB, "M", "𐳫"), + (0x10CAC, "M", "𐳬"), + (0x10CAD, "M", "𐳭"), + ] + + +def _seg_57() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0x10CAE, "M", "𐳮"), + (0x10CAF, "M", "𐳯"), + (0x10CB0, "M", "𐳰"), + (0x10CB1, "M", "𐳱"), + (0x10CB2, "M", "𐳲"), + (0x10CB3, "X"), + (0x10CC0, "V"), + (0x10CF3, "X"), + (0x10CFA, "V"), + (0x10D28, "X"), + (0x10D30, "V"), + (0x10D3A, "X"), + (0x10D40, "V"), + (0x10D50, "M", "𐵰"), + (0x10D51, "M", "𐵱"), + (0x10D52, "M", "𐵲"), + (0x10D53, "M", "𐵳"), + (0x10D54, "M", "𐵴"), + (0x10D55, "M", "𐵵"), + (0x10D56, "M", "𐵶"), + (0x10D57, "M", "𐵷"), + (0x10D58, "M", "𐵸"), + (0x10D59, "M", "𐵹"), + (0x10D5A, "M", "𐵺"), + (0x10D5B, "M", "𐵻"), + (0x10D5C, "M", "𐵼"), + (0x10D5D, "M", "𐵽"), + (0x10D5E, "M", "𐵾"), + (0x10D5F, "M", "𐵿"), + (0x10D60, "M", "𐶀"), + (0x10D61, "M", "𐶁"), + (0x10D62, "M", "𐶂"), + (0x10D63, "M", "𐶃"), + (0x10D64, "M", "𐶄"), + (0x10D65, "M", "𐶅"), + (0x10D66, "X"), + (0x10D69, "V"), + (0x10D86, "X"), + (0x10D8E, "V"), + (0x10D90, "X"), + (0x10E60, "V"), + (0x10E7F, "X"), + (0x10E80, "V"), + (0x10EAA, "X"), + (0x10EAB, "V"), + (0x10EAE, "X"), + (0x10EB0, "V"), + (0x10EB2, "X"), + (0x10EC2, "V"), + (0x10EC5, "X"), + (0x10EFC, "V"), + (0x10F28, "X"), + (0x10F30, "V"), + (0x10F5A, "X"), + (0x10F70, "V"), + (0x10F8A, "X"), + (0x10FB0, "V"), + (0x10FCC, "X"), + (0x10FE0, "V"), + (0x10FF7, "X"), + (0x11000, "V"), + (0x1104E, "X"), + (0x11052, "V"), + (0x11076, "X"), + (0x1107F, "V"), + (0x110BD, "X"), + (0x110BE, "V"), + (0x110C3, "X"), + (0x110D0, "V"), + (0x110E9, "X"), + (0x110F0, "V"), + (0x110FA, "X"), + (0x11100, "V"), + (0x11135, "X"), + (0x11136, "V"), + (0x11148, "X"), + (0x11150, "V"), + (0x11177, "X"), + (0x11180, "V"), + (0x111E0, "X"), + (0x111E1, "V"), + (0x111F5, "X"), + (0x11200, "V"), + (0x11212, "X"), + (0x11213, "V"), + (0x11242, "X"), + (0x11280, "V"), + (0x11287, "X"), + (0x11288, "V"), + (0x11289, "X"), + (0x1128A, "V"), + (0x1128E, "X"), + (0x1128F, "V"), + (0x1129E, "X"), + (0x1129F, "V"), + (0x112AA, "X"), + (0x112B0, "V"), + (0x112EB, "X"), + (0x112F0, "V"), + (0x112FA, "X"), + ] + + +def _seg_58() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0x11300, "V"), + (0x11304, "X"), + (0x11305, "V"), + (0x1130D, "X"), + (0x1130F, "V"), + (0x11311, "X"), + (0x11313, "V"), + (0x11329, "X"), + (0x1132A, "V"), + (0x11331, "X"), + (0x11332, "V"), + (0x11334, "X"), + (0x11335, "V"), + (0x1133A, "X"), + (0x1133B, "V"), + (0x11345, "X"), + (0x11347, "V"), + (0x11349, "X"), + (0x1134B, "V"), + (0x1134E, "X"), + (0x11350, "V"), + (0x11351, "X"), + (0x11357, "V"), + (0x11358, "X"), + (0x1135D, "V"), + (0x11364, "X"), + (0x11366, "V"), + (0x1136D, "X"), + (0x11370, "V"), + (0x11375, "X"), + (0x11380, "V"), + (0x1138A, "X"), + (0x1138B, "V"), + (0x1138C, "X"), + (0x1138E, "V"), + (0x1138F, "X"), + (0x11390, "V"), + (0x113B6, "X"), + (0x113B7, "V"), + (0x113C1, "X"), + (0x113C2, "V"), + (0x113C3, "X"), + (0x113C5, "V"), + (0x113C6, "X"), + (0x113C7, "V"), + (0x113CB, "X"), + (0x113CC, "V"), + (0x113D6, "X"), + (0x113D7, "V"), + (0x113D9, "X"), + (0x113E1, "V"), + (0x113E3, "X"), + (0x11400, "V"), + (0x1145C, "X"), + (0x1145D, "V"), + (0x11462, "X"), + (0x11480, "V"), + (0x114C8, "X"), + (0x114D0, "V"), + (0x114DA, "X"), + (0x11580, "V"), + (0x115B6, "X"), + (0x115B8, "V"), + (0x115DE, "X"), + (0x11600, "V"), + (0x11645, "X"), + (0x11650, "V"), + (0x1165A, "X"), + (0x11660, "V"), + (0x1166D, "X"), + (0x11680, "V"), + (0x116BA, "X"), + (0x116C0, "V"), + (0x116CA, "X"), + (0x116D0, "V"), + (0x116E4, "X"), + (0x11700, "V"), + (0x1171B, "X"), + (0x1171D, "V"), + (0x1172C, "X"), + (0x11730, "V"), + (0x11747, "X"), + (0x11800, "V"), + (0x1183C, "X"), + (0x118A0, "M", "𑣀"), + (0x118A1, "M", "𑣁"), + (0x118A2, "M", "𑣂"), + (0x118A3, "M", "𑣃"), + (0x118A4, "M", "𑣄"), + (0x118A5, "M", "𑣅"), + (0x118A6, "M", "𑣆"), + (0x118A7, "M", "𑣇"), + (0x118A8, "M", "𑣈"), + (0x118A9, "M", "𑣉"), + (0x118AA, "M", "𑣊"), + (0x118AB, "M", "𑣋"), + (0x118AC, "M", "𑣌"), + (0x118AD, "M", "𑣍"), + (0x118AE, "M", "𑣎"), + (0x118AF, "M", "𑣏"), + ] + + +def _seg_59() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0x118B0, "M", "𑣐"), + (0x118B1, "M", "𑣑"), + (0x118B2, "M", "𑣒"), + (0x118B3, "M", "𑣓"), + (0x118B4, "M", "𑣔"), + (0x118B5, "M", "𑣕"), + (0x118B6, "M", "𑣖"), + (0x118B7, "M", "𑣗"), + (0x118B8, "M", "𑣘"), + (0x118B9, "M", "𑣙"), + (0x118BA, "M", "𑣚"), + (0x118BB, "M", "𑣛"), + (0x118BC, "M", "𑣜"), + (0x118BD, "M", "𑣝"), + (0x118BE, "M", "𑣞"), + (0x118BF, "M", "𑣟"), + (0x118C0, "V"), + (0x118F3, "X"), + (0x118FF, "V"), + (0x11907, "X"), + (0x11909, "V"), + (0x1190A, "X"), + (0x1190C, "V"), + (0x11914, "X"), + (0x11915, "V"), + (0x11917, "X"), + (0x11918, "V"), + (0x11936, "X"), + (0x11937, "V"), + (0x11939, "X"), + (0x1193B, "V"), + (0x11947, "X"), + (0x11950, "V"), + (0x1195A, "X"), + (0x119A0, "V"), + (0x119A8, "X"), + (0x119AA, "V"), + (0x119D8, "X"), + (0x119DA, "V"), + (0x119E5, "X"), + (0x11A00, "V"), + (0x11A48, "X"), + (0x11A50, "V"), + (0x11AA3, "X"), + (0x11AB0, "V"), + (0x11AF9, "X"), + (0x11B00, "V"), + (0x11B0A, "X"), + (0x11BC0, "V"), + (0x11BE2, "X"), + (0x11BF0, "V"), + (0x11BFA, "X"), + (0x11C00, "V"), + (0x11C09, "X"), + (0x11C0A, "V"), + (0x11C37, "X"), + (0x11C38, "V"), + (0x11C46, "X"), + (0x11C50, "V"), + (0x11C6D, "X"), + (0x11C70, "V"), + (0x11C90, "X"), + (0x11C92, "V"), + (0x11CA8, "X"), + (0x11CA9, "V"), + (0x11CB7, "X"), + (0x11D00, "V"), + (0x11D07, "X"), + (0x11D08, "V"), + (0x11D0A, "X"), + (0x11D0B, "V"), + (0x11D37, "X"), + (0x11D3A, "V"), + (0x11D3B, "X"), + (0x11D3C, "V"), + (0x11D3E, "X"), + (0x11D3F, "V"), + (0x11D48, "X"), + (0x11D50, "V"), + (0x11D5A, "X"), + (0x11D60, "V"), + (0x11D66, "X"), + (0x11D67, "V"), + (0x11D69, "X"), + (0x11D6A, "V"), + (0x11D8F, "X"), + (0x11D90, "V"), + (0x11D92, "X"), + (0x11D93, "V"), + (0x11D99, "X"), + (0x11DA0, "V"), + (0x11DAA, "X"), + (0x11EE0, "V"), + (0x11EF9, "X"), + (0x11F00, "V"), + (0x11F11, "X"), + (0x11F12, "V"), + (0x11F3B, "X"), + (0x11F3E, "V"), + (0x11F5B, "X"), + ] + + +def _seg_60() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0x11FB0, "V"), + (0x11FB1, "X"), + (0x11FC0, "V"), + (0x11FF2, "X"), + (0x11FFF, "V"), + (0x1239A, "X"), + (0x12400, "V"), + (0x1246F, "X"), + (0x12470, "V"), + (0x12475, "X"), + (0x12480, "V"), + (0x12544, "X"), + (0x12F90, "V"), + (0x12FF3, "X"), + (0x13000, "V"), + (0x13430, "X"), + (0x13440, "V"), + (0x13456, "X"), + (0x13460, "V"), + (0x143FB, "X"), + (0x14400, "V"), + (0x14647, "X"), + (0x16100, "V"), + (0x1613A, "X"), + (0x16800, "V"), + (0x16A39, "X"), + (0x16A40, "V"), + (0x16A5F, "X"), + (0x16A60, "V"), + (0x16A6A, "X"), + (0x16A6E, "V"), + (0x16ABF, "X"), + (0x16AC0, "V"), + (0x16ACA, "X"), + (0x16AD0, "V"), + (0x16AEE, "X"), + (0x16AF0, "V"), + (0x16AF6, "X"), + (0x16B00, "V"), + (0x16B46, "X"), + (0x16B50, "V"), + (0x16B5A, "X"), + (0x16B5B, "V"), + (0x16B62, "X"), + (0x16B63, "V"), + (0x16B78, "X"), + (0x16B7D, "V"), + (0x16B90, "X"), + (0x16D40, "V"), + (0x16D7A, "X"), + (0x16E40, "M", "𖹠"), + (0x16E41, "M", "𖹡"), + (0x16E42, "M", "𖹢"), + (0x16E43, "M", "𖹣"), + (0x16E44, "M", "𖹤"), + (0x16E45, "M", "𖹥"), + (0x16E46, "M", "𖹦"), + (0x16E47, "M", "𖹧"), + (0x16E48, "M", "𖹨"), + (0x16E49, "M", "𖹩"), + (0x16E4A, "M", "𖹪"), + (0x16E4B, "M", "𖹫"), + (0x16E4C, "M", "𖹬"), + (0x16E4D, "M", "𖹭"), + (0x16E4E, "M", "𖹮"), + (0x16E4F, "M", "𖹯"), + (0x16E50, "M", "𖹰"), + (0x16E51, "M", "𖹱"), + (0x16E52, "M", "𖹲"), + (0x16E53, "M", "𖹳"), + (0x16E54, "M", "𖹴"), + (0x16E55, "M", "𖹵"), + (0x16E56, "M", "𖹶"), + (0x16E57, "M", "𖹷"), + (0x16E58, "M", "𖹸"), + (0x16E59, "M", "𖹹"), + (0x16E5A, "M", "𖹺"), + (0x16E5B, "M", "𖹻"), + (0x16E5C, "M", "𖹼"), + (0x16E5D, "M", "𖹽"), + (0x16E5E, "M", "𖹾"), + (0x16E5F, "M", "𖹿"), + (0x16E60, "V"), + (0x16E9B, "X"), + (0x16F00, "V"), + (0x16F4B, "X"), + (0x16F4F, "V"), + (0x16F88, "X"), + (0x16F8F, "V"), + (0x16FA0, "X"), + (0x16FE0, "V"), + (0x16FE5, "X"), + (0x16FF0, "V"), + (0x16FF2, "X"), + (0x17000, "V"), + (0x187F8, "X"), + (0x18800, "V"), + (0x18CD6, "X"), + (0x18CFF, "V"), + (0x18D09, "X"), + ] + + +def _seg_61() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0x1AFF0, "V"), + (0x1AFF4, "X"), + (0x1AFF5, "V"), + (0x1AFFC, "X"), + (0x1AFFD, "V"), + (0x1AFFF, "X"), + (0x1B000, "V"), + (0x1B123, "X"), + (0x1B132, "V"), + (0x1B133, "X"), + (0x1B150, "V"), + (0x1B153, "X"), + (0x1B155, "V"), + (0x1B156, "X"), + (0x1B164, "V"), + (0x1B168, "X"), + (0x1B170, "V"), + (0x1B2FC, "X"), + (0x1BC00, "V"), + (0x1BC6B, "X"), + (0x1BC70, "V"), + (0x1BC7D, "X"), + (0x1BC80, "V"), + (0x1BC89, "X"), + (0x1BC90, "V"), + (0x1BC9A, "X"), + (0x1BC9C, "V"), + (0x1BCA0, "I"), + (0x1BCA4, "X"), + (0x1CC00, "V"), + (0x1CCD6, "M", "a"), + (0x1CCD7, "M", "b"), + (0x1CCD8, "M", "c"), + (0x1CCD9, "M", "d"), + (0x1CCDA, "M", "e"), + (0x1CCDB, "M", "f"), + (0x1CCDC, "M", "g"), + (0x1CCDD, "M", "h"), + (0x1CCDE, "M", "i"), + (0x1CCDF, "M", "j"), + (0x1CCE0, "M", "k"), + (0x1CCE1, "M", "l"), + (0x1CCE2, "M", "m"), + (0x1CCE3, "M", "n"), + (0x1CCE4, "M", "o"), + (0x1CCE5, "M", "p"), + (0x1CCE6, "M", "q"), + (0x1CCE7, "M", "r"), + (0x1CCE8, "M", "s"), + (0x1CCE9, "M", "t"), + (0x1CCEA, "M", "u"), + (0x1CCEB, "M", "v"), + (0x1CCEC, "M", "w"), + (0x1CCED, "M", "x"), + (0x1CCEE, "M", "y"), + (0x1CCEF, "M", "z"), + (0x1CCF0, "M", "0"), + (0x1CCF1, "M", "1"), + (0x1CCF2, "M", "2"), + (0x1CCF3, "M", "3"), + (0x1CCF4, "M", "4"), + (0x1CCF5, "M", "5"), + (0x1CCF6, "M", "6"), + (0x1CCF7, "M", "7"), + (0x1CCF8, "M", "8"), + (0x1CCF9, "M", "9"), + (0x1CCFA, "X"), + (0x1CD00, "V"), + (0x1CEB4, "X"), + (0x1CF00, "V"), + (0x1CF2E, "X"), + (0x1CF30, "V"), + (0x1CF47, "X"), + (0x1CF50, "V"), + (0x1CFC4, "X"), + (0x1D000, "V"), + (0x1D0F6, "X"), + (0x1D100, "V"), + (0x1D127, "X"), + (0x1D129, "V"), + (0x1D15E, "M", "𝅗𝅥"), + (0x1D15F, "M", "𝅘𝅥"), + (0x1D160, "M", "𝅘𝅥𝅮"), + (0x1D161, "M", "𝅘𝅥𝅯"), + (0x1D162, "M", "𝅘𝅥𝅰"), + (0x1D163, "M", "𝅘𝅥𝅱"), + (0x1D164, "M", "𝅘𝅥𝅲"), + (0x1D165, "V"), + (0x1D173, "I"), + (0x1D17B, "V"), + (0x1D1BB, "M", "𝆹𝅥"), + (0x1D1BC, "M", "𝆺𝅥"), + (0x1D1BD, "M", "𝆹𝅥𝅮"), + (0x1D1BE, "M", "𝆺𝅥𝅮"), + (0x1D1BF, "M", "𝆹𝅥𝅯"), + (0x1D1C0, "M", "𝆺𝅥𝅯"), + (0x1D1C1, "V"), + (0x1D1EB, "X"), + (0x1D200, "V"), + (0x1D246, "X"), + ] + + +def _seg_62() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0x1D2C0, "V"), + (0x1D2D4, "X"), + (0x1D2E0, "V"), + (0x1D2F4, "X"), + (0x1D300, "V"), + (0x1D357, "X"), + (0x1D360, "V"), + (0x1D379, "X"), + (0x1D400, "M", "a"), + (0x1D401, "M", "b"), + (0x1D402, "M", "c"), + (0x1D403, "M", "d"), + (0x1D404, "M", "e"), + (0x1D405, "M", "f"), + (0x1D406, "M", "g"), + (0x1D407, "M", "h"), + (0x1D408, "M", "i"), + (0x1D409, "M", "j"), + (0x1D40A, "M", "k"), + (0x1D40B, "M", "l"), + (0x1D40C, "M", "m"), + (0x1D40D, "M", "n"), + (0x1D40E, "M", "o"), + (0x1D40F, "M", "p"), + (0x1D410, "M", "q"), + (0x1D411, "M", "r"), + (0x1D412, "M", "s"), + (0x1D413, "M", "t"), + (0x1D414, "M", "u"), + (0x1D415, "M", "v"), + (0x1D416, "M", "w"), + (0x1D417, "M", "x"), + (0x1D418, "M", "y"), + (0x1D419, "M", "z"), + (0x1D41A, "M", "a"), + (0x1D41B, "M", "b"), + (0x1D41C, "M", "c"), + (0x1D41D, "M", "d"), + (0x1D41E, "M", "e"), + (0x1D41F, "M", "f"), + (0x1D420, "M", "g"), + (0x1D421, "M", "h"), + (0x1D422, "M", "i"), + (0x1D423, "M", "j"), + (0x1D424, "M", "k"), + (0x1D425, "M", "l"), + (0x1D426, "M", "m"), + (0x1D427, "M", "n"), + (0x1D428, "M", "o"), + (0x1D429, "M", "p"), + (0x1D42A, "M", "q"), + (0x1D42B, "M", "r"), + (0x1D42C, "M", "s"), + (0x1D42D, "M", "t"), + (0x1D42E, "M", "u"), + (0x1D42F, "M", "v"), + (0x1D430, "M", "w"), + (0x1D431, "M", "x"), + (0x1D432, "M", "y"), + (0x1D433, "M", "z"), + (0x1D434, "M", "a"), + (0x1D435, "M", "b"), + (0x1D436, "M", "c"), + (0x1D437, "M", "d"), + (0x1D438, "M", "e"), + (0x1D439, "M", "f"), + (0x1D43A, "M", "g"), + (0x1D43B, "M", "h"), + (0x1D43C, "M", "i"), + (0x1D43D, "M", "j"), + (0x1D43E, "M", "k"), + (0x1D43F, "M", "l"), + (0x1D440, "M", "m"), + (0x1D441, "M", "n"), + (0x1D442, "M", "o"), + (0x1D443, "M", "p"), + (0x1D444, "M", "q"), + (0x1D445, "M", "r"), + (0x1D446, "M", "s"), + (0x1D447, "M", "t"), + (0x1D448, "M", "u"), + (0x1D449, "M", "v"), + (0x1D44A, "M", "w"), + (0x1D44B, "M", "x"), + (0x1D44C, "M", "y"), + (0x1D44D, "M", "z"), + (0x1D44E, "M", "a"), + (0x1D44F, "M", "b"), + (0x1D450, "M", "c"), + (0x1D451, "M", "d"), + (0x1D452, "M", "e"), + (0x1D453, "M", "f"), + (0x1D454, "M", "g"), + (0x1D455, "X"), + (0x1D456, "M", "i"), + (0x1D457, "M", "j"), + (0x1D458, "M", "k"), + (0x1D459, "M", "l"), + (0x1D45A, "M", "m"), + (0x1D45B, "M", "n"), + ] + + +def _seg_63() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0x1D45C, "M", "o"), + (0x1D45D, "M", "p"), + (0x1D45E, "M", "q"), + (0x1D45F, "M", "r"), + (0x1D460, "M", "s"), + (0x1D461, "M", "t"), + (0x1D462, "M", "u"), + (0x1D463, "M", "v"), + (0x1D464, "M", "w"), + (0x1D465, "M", "x"), + (0x1D466, "M", "y"), + (0x1D467, "M", "z"), + (0x1D468, "M", "a"), + (0x1D469, "M", "b"), + (0x1D46A, "M", "c"), + (0x1D46B, "M", "d"), + (0x1D46C, "M", "e"), + (0x1D46D, "M", "f"), + (0x1D46E, "M", "g"), + (0x1D46F, "M", "h"), + (0x1D470, "M", "i"), + (0x1D471, "M", "j"), + (0x1D472, "M", "k"), + (0x1D473, "M", "l"), + (0x1D474, "M", "m"), + (0x1D475, "M", "n"), + (0x1D476, "M", "o"), + (0x1D477, "M", "p"), + (0x1D478, "M", "q"), + (0x1D479, "M", "r"), + (0x1D47A, "M", "s"), + (0x1D47B, "M", "t"), + (0x1D47C, "M", "u"), + (0x1D47D, "M", "v"), + (0x1D47E, "M", "w"), + (0x1D47F, "M", "x"), + (0x1D480, "M", "y"), + (0x1D481, "M", "z"), + (0x1D482, "M", "a"), + (0x1D483, "M", "b"), + (0x1D484, "M", "c"), + (0x1D485, "M", "d"), + (0x1D486, "M", "e"), + (0x1D487, "M", "f"), + (0x1D488, "M", "g"), + (0x1D489, "M", "h"), + (0x1D48A, "M", "i"), + (0x1D48B, "M", "j"), + (0x1D48C, "M", "k"), + (0x1D48D, "M", "l"), + (0x1D48E, "M", "m"), + (0x1D48F, "M", "n"), + (0x1D490, "M", "o"), + (0x1D491, "M", "p"), + (0x1D492, "M", "q"), + (0x1D493, "M", "r"), + (0x1D494, "M", "s"), + (0x1D495, "M", "t"), + (0x1D496, "M", "u"), + (0x1D497, "M", "v"), + (0x1D498, "M", "w"), + (0x1D499, "M", "x"), + (0x1D49A, "M", "y"), + (0x1D49B, "M", "z"), + (0x1D49C, "M", "a"), + (0x1D49D, "X"), + (0x1D49E, "M", "c"), + (0x1D49F, "M", "d"), + (0x1D4A0, "X"), + (0x1D4A2, "M", "g"), + (0x1D4A3, "X"), + (0x1D4A5, "M", "j"), + (0x1D4A6, "M", "k"), + (0x1D4A7, "X"), + (0x1D4A9, "M", "n"), + (0x1D4AA, "M", "o"), + (0x1D4AB, "M", "p"), + (0x1D4AC, "M", "q"), + (0x1D4AD, "X"), + (0x1D4AE, "M", "s"), + (0x1D4AF, "M", "t"), + (0x1D4B0, "M", "u"), + (0x1D4B1, "M", "v"), + (0x1D4B2, "M", "w"), + (0x1D4B3, "M", "x"), + (0x1D4B4, "M", "y"), + (0x1D4B5, "M", "z"), + (0x1D4B6, "M", "a"), + (0x1D4B7, "M", "b"), + (0x1D4B8, "M", "c"), + (0x1D4B9, "M", "d"), + (0x1D4BA, "X"), + (0x1D4BB, "M", "f"), + (0x1D4BC, "X"), + (0x1D4BD, "M", "h"), + (0x1D4BE, "M", "i"), + (0x1D4BF, "M", "j"), + (0x1D4C0, "M", "k"), + (0x1D4C1, "M", "l"), + (0x1D4C2, "M", "m"), + ] + + +def _seg_64() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0x1D4C3, "M", "n"), + (0x1D4C4, "X"), + (0x1D4C5, "M", "p"), + (0x1D4C6, "M", "q"), + (0x1D4C7, "M", "r"), + (0x1D4C8, "M", "s"), + (0x1D4C9, "M", "t"), + (0x1D4CA, "M", "u"), + (0x1D4CB, "M", "v"), + (0x1D4CC, "M", "w"), + (0x1D4CD, "M", "x"), + (0x1D4CE, "M", "y"), + (0x1D4CF, "M", "z"), + (0x1D4D0, "M", "a"), + (0x1D4D1, "M", "b"), + (0x1D4D2, "M", "c"), + (0x1D4D3, "M", "d"), + (0x1D4D4, "M", "e"), + (0x1D4D5, "M", "f"), + (0x1D4D6, "M", "g"), + (0x1D4D7, "M", "h"), + (0x1D4D8, "M", "i"), + (0x1D4D9, "M", "j"), + (0x1D4DA, "M", "k"), + (0x1D4DB, "M", "l"), + (0x1D4DC, "M", "m"), + (0x1D4DD, "M", "n"), + (0x1D4DE, "M", "o"), + (0x1D4DF, "M", "p"), + (0x1D4E0, "M", "q"), + (0x1D4E1, "M", "r"), + (0x1D4E2, "M", "s"), + (0x1D4E3, "M", "t"), + (0x1D4E4, "M", "u"), + (0x1D4E5, "M", "v"), + (0x1D4E6, "M", "w"), + (0x1D4E7, "M", "x"), + (0x1D4E8, "M", "y"), + (0x1D4E9, "M", "z"), + (0x1D4EA, "M", "a"), + (0x1D4EB, "M", "b"), + (0x1D4EC, "M", "c"), + (0x1D4ED, "M", "d"), + (0x1D4EE, "M", "e"), + (0x1D4EF, "M", "f"), + (0x1D4F0, "M", "g"), + (0x1D4F1, "M", "h"), + (0x1D4F2, "M", "i"), + (0x1D4F3, "M", "j"), + (0x1D4F4, "M", "k"), + (0x1D4F5, "M", "l"), + (0x1D4F6, "M", "m"), + (0x1D4F7, "M", "n"), + (0x1D4F8, "M", "o"), + (0x1D4F9, "M", "p"), + (0x1D4FA, "M", "q"), + (0x1D4FB, "M", "r"), + (0x1D4FC, "M", "s"), + (0x1D4FD, "M", "t"), + (0x1D4FE, "M", "u"), + (0x1D4FF, "M", "v"), + (0x1D500, "M", "w"), + (0x1D501, "M", "x"), + (0x1D502, "M", "y"), + (0x1D503, "M", "z"), + (0x1D504, "M", "a"), + (0x1D505, "M", "b"), + (0x1D506, "X"), + (0x1D507, "M", "d"), + (0x1D508, "M", "e"), + (0x1D509, "M", "f"), + (0x1D50A, "M", "g"), + (0x1D50B, "X"), + (0x1D50D, "M", "j"), + (0x1D50E, "M", "k"), + (0x1D50F, "M", "l"), + (0x1D510, "M", "m"), + (0x1D511, "M", "n"), + (0x1D512, "M", "o"), + (0x1D513, "M", "p"), + (0x1D514, "M", "q"), + (0x1D515, "X"), + (0x1D516, "M", "s"), + (0x1D517, "M", "t"), + (0x1D518, "M", "u"), + (0x1D519, "M", "v"), + (0x1D51A, "M", "w"), + (0x1D51B, "M", "x"), + (0x1D51C, "M", "y"), + (0x1D51D, "X"), + (0x1D51E, "M", "a"), + (0x1D51F, "M", "b"), + (0x1D520, "M", "c"), + (0x1D521, "M", "d"), + (0x1D522, "M", "e"), + (0x1D523, "M", "f"), + (0x1D524, "M", "g"), + (0x1D525, "M", "h"), + (0x1D526, "M", "i"), + (0x1D527, "M", "j"), + ] + + +def _seg_65() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0x1D528, "M", "k"), + (0x1D529, "M", "l"), + (0x1D52A, "M", "m"), + (0x1D52B, "M", "n"), + (0x1D52C, "M", "o"), + (0x1D52D, "M", "p"), + (0x1D52E, "M", "q"), + (0x1D52F, "M", "r"), + (0x1D530, "M", "s"), + (0x1D531, "M", "t"), + (0x1D532, "M", "u"), + (0x1D533, "M", "v"), + (0x1D534, "M", "w"), + (0x1D535, "M", "x"), + (0x1D536, "M", "y"), + (0x1D537, "M", "z"), + (0x1D538, "M", "a"), + (0x1D539, "M", "b"), + (0x1D53A, "X"), + (0x1D53B, "M", "d"), + (0x1D53C, "M", "e"), + (0x1D53D, "M", "f"), + (0x1D53E, "M", "g"), + (0x1D53F, "X"), + (0x1D540, "M", "i"), + (0x1D541, "M", "j"), + (0x1D542, "M", "k"), + (0x1D543, "M", "l"), + (0x1D544, "M", "m"), + (0x1D545, "X"), + (0x1D546, "M", "o"), + (0x1D547, "X"), + (0x1D54A, "M", "s"), + (0x1D54B, "M", "t"), + (0x1D54C, "M", "u"), + (0x1D54D, "M", "v"), + (0x1D54E, "M", "w"), + (0x1D54F, "M", "x"), + (0x1D550, "M", "y"), + (0x1D551, "X"), + (0x1D552, "M", "a"), + (0x1D553, "M", "b"), + (0x1D554, "M", "c"), + (0x1D555, "M", "d"), + (0x1D556, "M", "e"), + (0x1D557, "M", "f"), + (0x1D558, "M", "g"), + (0x1D559, "M", "h"), + (0x1D55A, "M", "i"), + (0x1D55B, "M", "j"), + (0x1D55C, "M", "k"), + (0x1D55D, "M", "l"), + (0x1D55E, "M", "m"), + (0x1D55F, "M", "n"), + (0x1D560, "M", "o"), + (0x1D561, "M", "p"), + (0x1D562, "M", "q"), + (0x1D563, "M", "r"), + (0x1D564, "M", "s"), + (0x1D565, "M", "t"), + (0x1D566, "M", "u"), + (0x1D567, "M", "v"), + (0x1D568, "M", "w"), + (0x1D569, "M", "x"), + (0x1D56A, "M", "y"), + (0x1D56B, "M", "z"), + (0x1D56C, "M", "a"), + (0x1D56D, "M", "b"), + (0x1D56E, "M", "c"), + (0x1D56F, "M", "d"), + (0x1D570, "M", "e"), + (0x1D571, "M", "f"), + (0x1D572, "M", "g"), + (0x1D573, "M", "h"), + (0x1D574, "M", "i"), + (0x1D575, "M", "j"), + (0x1D576, "M", "k"), + (0x1D577, "M", "l"), + (0x1D578, "M", "m"), + (0x1D579, "M", "n"), + (0x1D57A, "M", "o"), + (0x1D57B, "M", "p"), + (0x1D57C, "M", "q"), + (0x1D57D, "M", "r"), + (0x1D57E, "M", "s"), + (0x1D57F, "M", "t"), + (0x1D580, "M", "u"), + (0x1D581, "M", "v"), + (0x1D582, "M", "w"), + (0x1D583, "M", "x"), + (0x1D584, "M", "y"), + (0x1D585, "M", "z"), + (0x1D586, "M", "a"), + (0x1D587, "M", "b"), + (0x1D588, "M", "c"), + (0x1D589, "M", "d"), + (0x1D58A, "M", "e"), + (0x1D58B, "M", "f"), + (0x1D58C, "M", "g"), + (0x1D58D, "M", "h"), + ] + + +def _seg_66() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0x1D58E, "M", "i"), + (0x1D58F, "M", "j"), + (0x1D590, "M", "k"), + (0x1D591, "M", "l"), + (0x1D592, "M", "m"), + (0x1D593, "M", "n"), + (0x1D594, "M", "o"), + (0x1D595, "M", "p"), + (0x1D596, "M", "q"), + (0x1D597, "M", "r"), + (0x1D598, "M", "s"), + (0x1D599, "M", "t"), + (0x1D59A, "M", "u"), + (0x1D59B, "M", "v"), + (0x1D59C, "M", "w"), + (0x1D59D, "M", "x"), + (0x1D59E, "M", "y"), + (0x1D59F, "M", "z"), + (0x1D5A0, "M", "a"), + (0x1D5A1, "M", "b"), + (0x1D5A2, "M", "c"), + (0x1D5A3, "M", "d"), + (0x1D5A4, "M", "e"), + (0x1D5A5, "M", "f"), + (0x1D5A6, "M", "g"), + (0x1D5A7, "M", "h"), + (0x1D5A8, "M", "i"), + (0x1D5A9, "M", "j"), + (0x1D5AA, "M", "k"), + (0x1D5AB, "M", "l"), + (0x1D5AC, "M", "m"), + (0x1D5AD, "M", "n"), + (0x1D5AE, "M", "o"), + (0x1D5AF, "M", "p"), + (0x1D5B0, "M", "q"), + (0x1D5B1, "M", "r"), + (0x1D5B2, "M", "s"), + (0x1D5B3, "M", "t"), + (0x1D5B4, "M", "u"), + (0x1D5B5, "M", "v"), + (0x1D5B6, "M", "w"), + (0x1D5B7, "M", "x"), + (0x1D5B8, "M", "y"), + (0x1D5B9, "M", "z"), + (0x1D5BA, "M", "a"), + (0x1D5BB, "M", "b"), + (0x1D5BC, "M", "c"), + (0x1D5BD, "M", "d"), + (0x1D5BE, "M", "e"), + (0x1D5BF, "M", "f"), + (0x1D5C0, "M", "g"), + (0x1D5C1, "M", "h"), + (0x1D5C2, "M", "i"), + (0x1D5C3, "M", "j"), + (0x1D5C4, "M", "k"), + (0x1D5C5, "M", "l"), + (0x1D5C6, "M", "m"), + (0x1D5C7, "M", "n"), + (0x1D5C8, "M", "o"), + (0x1D5C9, "M", "p"), + (0x1D5CA, "M", "q"), + (0x1D5CB, "M", "r"), + (0x1D5CC, "M", "s"), + (0x1D5CD, "M", "t"), + (0x1D5CE, "M", "u"), + (0x1D5CF, "M", "v"), + (0x1D5D0, "M", "w"), + (0x1D5D1, "M", "x"), + (0x1D5D2, "M", "y"), + (0x1D5D3, "M", "z"), + (0x1D5D4, "M", "a"), + (0x1D5D5, "M", "b"), + (0x1D5D6, "M", "c"), + (0x1D5D7, "M", "d"), + (0x1D5D8, "M", "e"), + (0x1D5D9, "M", "f"), + (0x1D5DA, "M", "g"), + (0x1D5DB, "M", "h"), + (0x1D5DC, "M", "i"), + (0x1D5DD, "M", "j"), + (0x1D5DE, "M", "k"), + (0x1D5DF, "M", "l"), + (0x1D5E0, "M", "m"), + (0x1D5E1, "M", "n"), + (0x1D5E2, "M", "o"), + (0x1D5E3, "M", "p"), + (0x1D5E4, "M", "q"), + (0x1D5E5, "M", "r"), + (0x1D5E6, "M", "s"), + (0x1D5E7, "M", "t"), + (0x1D5E8, "M", "u"), + (0x1D5E9, "M", "v"), + (0x1D5EA, "M", "w"), + (0x1D5EB, "M", "x"), + (0x1D5EC, "M", "y"), + (0x1D5ED, "M", "z"), + (0x1D5EE, "M", "a"), + (0x1D5EF, "M", "b"), + (0x1D5F0, "M", "c"), + (0x1D5F1, "M", "d"), + ] + + +def _seg_67() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0x1D5F2, "M", "e"), + (0x1D5F3, "M", "f"), + (0x1D5F4, "M", "g"), + (0x1D5F5, "M", "h"), + (0x1D5F6, "M", "i"), + (0x1D5F7, "M", "j"), + (0x1D5F8, "M", "k"), + (0x1D5F9, "M", "l"), + (0x1D5FA, "M", "m"), + (0x1D5FB, "M", "n"), + (0x1D5FC, "M", "o"), + (0x1D5FD, "M", "p"), + (0x1D5FE, "M", "q"), + (0x1D5FF, "M", "r"), + (0x1D600, "M", "s"), + (0x1D601, "M", "t"), + (0x1D602, "M", "u"), + (0x1D603, "M", "v"), + (0x1D604, "M", "w"), + (0x1D605, "M", "x"), + (0x1D606, "M", "y"), + (0x1D607, "M", "z"), + (0x1D608, "M", "a"), + (0x1D609, "M", "b"), + (0x1D60A, "M", "c"), + (0x1D60B, "M", "d"), + (0x1D60C, "M", "e"), + (0x1D60D, "M", "f"), + (0x1D60E, "M", "g"), + (0x1D60F, "M", "h"), + (0x1D610, "M", "i"), + (0x1D611, "M", "j"), + (0x1D612, "M", "k"), + (0x1D613, "M", "l"), + (0x1D614, "M", "m"), + (0x1D615, "M", "n"), + (0x1D616, "M", "o"), + (0x1D617, "M", "p"), + (0x1D618, "M", "q"), + (0x1D619, "M", "r"), + (0x1D61A, "M", "s"), + (0x1D61B, "M", "t"), + (0x1D61C, "M", "u"), + (0x1D61D, "M", "v"), + (0x1D61E, "M", "w"), + (0x1D61F, "M", "x"), + (0x1D620, "M", "y"), + (0x1D621, "M", "z"), + (0x1D622, "M", "a"), + (0x1D623, "M", "b"), + (0x1D624, "M", "c"), + (0x1D625, "M", "d"), + (0x1D626, "M", "e"), + (0x1D627, "M", "f"), + (0x1D628, "M", "g"), + (0x1D629, "M", "h"), + (0x1D62A, "M", "i"), + (0x1D62B, "M", "j"), + (0x1D62C, "M", "k"), + (0x1D62D, "M", "l"), + (0x1D62E, "M", "m"), + (0x1D62F, "M", "n"), + (0x1D630, "M", "o"), + (0x1D631, "M", "p"), + (0x1D632, "M", "q"), + (0x1D633, "M", "r"), + (0x1D634, "M", "s"), + (0x1D635, "M", "t"), + (0x1D636, "M", "u"), + (0x1D637, "M", "v"), + (0x1D638, "M", "w"), + (0x1D639, "M", "x"), + (0x1D63A, "M", "y"), + (0x1D63B, "M", "z"), + (0x1D63C, "M", "a"), + (0x1D63D, "M", "b"), + (0x1D63E, "M", "c"), + (0x1D63F, "M", "d"), + (0x1D640, "M", "e"), + (0x1D641, "M", "f"), + (0x1D642, "M", "g"), + (0x1D643, "M", "h"), + (0x1D644, "M", "i"), + (0x1D645, "M", "j"), + (0x1D646, "M", "k"), + (0x1D647, "M", "l"), + (0x1D648, "M", "m"), + (0x1D649, "M", "n"), + (0x1D64A, "M", "o"), + (0x1D64B, "M", "p"), + (0x1D64C, "M", "q"), + (0x1D64D, "M", "r"), + (0x1D64E, "M", "s"), + (0x1D64F, "M", "t"), + (0x1D650, "M", "u"), + (0x1D651, "M", "v"), + (0x1D652, "M", "w"), + (0x1D653, "M", "x"), + (0x1D654, "M", "y"), + (0x1D655, "M", "z"), + ] + + +def _seg_68() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0x1D656, "M", "a"), + (0x1D657, "M", "b"), + (0x1D658, "M", "c"), + (0x1D659, "M", "d"), + (0x1D65A, "M", "e"), + (0x1D65B, "M", "f"), + (0x1D65C, "M", "g"), + (0x1D65D, "M", "h"), + (0x1D65E, "M", "i"), + (0x1D65F, "M", "j"), + (0x1D660, "M", "k"), + (0x1D661, "M", "l"), + (0x1D662, "M", "m"), + (0x1D663, "M", "n"), + (0x1D664, "M", "o"), + (0x1D665, "M", "p"), + (0x1D666, "M", "q"), + (0x1D667, "M", "r"), + (0x1D668, "M", "s"), + (0x1D669, "M", "t"), + (0x1D66A, "M", "u"), + (0x1D66B, "M", "v"), + (0x1D66C, "M", "w"), + (0x1D66D, "M", "x"), + (0x1D66E, "M", "y"), + (0x1D66F, "M", "z"), + (0x1D670, "M", "a"), + (0x1D671, "M", "b"), + (0x1D672, "M", "c"), + (0x1D673, "M", "d"), + (0x1D674, "M", "e"), + (0x1D675, "M", "f"), + (0x1D676, "M", "g"), + (0x1D677, "M", "h"), + (0x1D678, "M", "i"), + (0x1D679, "M", "j"), + (0x1D67A, "M", "k"), + (0x1D67B, "M", "l"), + (0x1D67C, "M", "m"), + (0x1D67D, "M", "n"), + (0x1D67E, "M", "o"), + (0x1D67F, "M", "p"), + (0x1D680, "M", "q"), + (0x1D681, "M", "r"), + (0x1D682, "M", "s"), + (0x1D683, "M", "t"), + (0x1D684, "M", "u"), + (0x1D685, "M", "v"), + (0x1D686, "M", "w"), + (0x1D687, "M", "x"), + (0x1D688, "M", "y"), + (0x1D689, "M", "z"), + (0x1D68A, "M", "a"), + (0x1D68B, "M", "b"), + (0x1D68C, "M", "c"), + (0x1D68D, "M", "d"), + (0x1D68E, "M", "e"), + (0x1D68F, "M", "f"), + (0x1D690, "M", "g"), + (0x1D691, "M", "h"), + (0x1D692, "M", "i"), + (0x1D693, "M", "j"), + (0x1D694, "M", "k"), + (0x1D695, "M", "l"), + (0x1D696, "M", "m"), + (0x1D697, "M", "n"), + (0x1D698, "M", "o"), + (0x1D699, "M", "p"), + (0x1D69A, "M", "q"), + (0x1D69B, "M", "r"), + (0x1D69C, "M", "s"), + (0x1D69D, "M", "t"), + (0x1D69E, "M", "u"), + (0x1D69F, "M", "v"), + (0x1D6A0, "M", "w"), + (0x1D6A1, "M", "x"), + (0x1D6A2, "M", "y"), + (0x1D6A3, "M", "z"), + (0x1D6A4, "M", "ı"), + (0x1D6A5, "M", "ȷ"), + (0x1D6A6, "X"), + (0x1D6A8, "M", "α"), + (0x1D6A9, "M", "β"), + (0x1D6AA, "M", "γ"), + (0x1D6AB, "M", "δ"), + (0x1D6AC, "M", "ε"), + (0x1D6AD, "M", "ζ"), + (0x1D6AE, "M", "η"), + (0x1D6AF, "M", "θ"), + (0x1D6B0, "M", "ι"), + (0x1D6B1, "M", "κ"), + (0x1D6B2, "M", "λ"), + (0x1D6B3, "M", "μ"), + (0x1D6B4, "M", "ν"), + (0x1D6B5, "M", "ξ"), + (0x1D6B6, "M", "ο"), + (0x1D6B7, "M", "π"), + (0x1D6B8, "M", "ρ"), + (0x1D6B9, "M", "θ"), + (0x1D6BA, "M", "σ"), + ] + + +def _seg_69() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0x1D6BB, "M", "τ"), + (0x1D6BC, "M", "υ"), + (0x1D6BD, "M", "φ"), + (0x1D6BE, "M", "χ"), + (0x1D6BF, "M", "ψ"), + (0x1D6C0, "M", "ω"), + (0x1D6C1, "M", "∇"), + (0x1D6C2, "M", "α"), + (0x1D6C3, "M", "β"), + (0x1D6C4, "M", "γ"), + (0x1D6C5, "M", "δ"), + (0x1D6C6, "M", "ε"), + (0x1D6C7, "M", "ζ"), + (0x1D6C8, "M", "η"), + (0x1D6C9, "M", "θ"), + (0x1D6CA, "M", "ι"), + (0x1D6CB, "M", "κ"), + (0x1D6CC, "M", "λ"), + (0x1D6CD, "M", "μ"), + (0x1D6CE, "M", "ν"), + (0x1D6CF, "M", "ξ"), + (0x1D6D0, "M", "ο"), + (0x1D6D1, "M", "π"), + (0x1D6D2, "M", "ρ"), + (0x1D6D3, "M", "σ"), + (0x1D6D5, "M", "τ"), + (0x1D6D6, "M", "υ"), + (0x1D6D7, "M", "φ"), + (0x1D6D8, "M", "χ"), + (0x1D6D9, "M", "ψ"), + (0x1D6DA, "M", "ω"), + (0x1D6DB, "M", "∂"), + (0x1D6DC, "M", "ε"), + (0x1D6DD, "M", "θ"), + (0x1D6DE, "M", "κ"), + (0x1D6DF, "M", "φ"), + (0x1D6E0, "M", "ρ"), + (0x1D6E1, "M", "π"), + (0x1D6E2, "M", "α"), + (0x1D6E3, "M", "β"), + (0x1D6E4, "M", "γ"), + (0x1D6E5, "M", "δ"), + (0x1D6E6, "M", "ε"), + (0x1D6E7, "M", "ζ"), + (0x1D6E8, "M", "η"), + (0x1D6E9, "M", "θ"), + (0x1D6EA, "M", "ι"), + (0x1D6EB, "M", "κ"), + (0x1D6EC, "M", "λ"), + (0x1D6ED, "M", "μ"), + (0x1D6EE, "M", "ν"), + (0x1D6EF, "M", "ξ"), + (0x1D6F0, "M", "ο"), + (0x1D6F1, "M", "π"), + (0x1D6F2, "M", "ρ"), + (0x1D6F3, "M", "θ"), + (0x1D6F4, "M", "σ"), + (0x1D6F5, "M", "τ"), + (0x1D6F6, "M", "υ"), + (0x1D6F7, "M", "φ"), + (0x1D6F8, "M", "χ"), + (0x1D6F9, "M", "ψ"), + (0x1D6FA, "M", "ω"), + (0x1D6FB, "M", "∇"), + (0x1D6FC, "M", "α"), + (0x1D6FD, "M", "β"), + (0x1D6FE, "M", "γ"), + (0x1D6FF, "M", "δ"), + (0x1D700, "M", "ε"), + (0x1D701, "M", "ζ"), + (0x1D702, "M", "η"), + (0x1D703, "M", "θ"), + (0x1D704, "M", "ι"), + (0x1D705, "M", "κ"), + (0x1D706, "M", "λ"), + (0x1D707, "M", "μ"), + (0x1D708, "M", "ν"), + (0x1D709, "M", "ξ"), + (0x1D70A, "M", "ο"), + (0x1D70B, "M", "π"), + (0x1D70C, "M", "ρ"), + (0x1D70D, "M", "σ"), + (0x1D70F, "M", "τ"), + (0x1D710, "M", "υ"), + (0x1D711, "M", "φ"), + (0x1D712, "M", "χ"), + (0x1D713, "M", "ψ"), + (0x1D714, "M", "ω"), + (0x1D715, "M", "∂"), + (0x1D716, "M", "ε"), + (0x1D717, "M", "θ"), + (0x1D718, "M", "κ"), + (0x1D719, "M", "φ"), + (0x1D71A, "M", "ρ"), + (0x1D71B, "M", "π"), + (0x1D71C, "M", "α"), + (0x1D71D, "M", "β"), + (0x1D71E, "M", "γ"), + (0x1D71F, "M", "δ"), + (0x1D720, "M", "ε"), + ] + + +def _seg_70() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0x1D721, "M", "ζ"), + (0x1D722, "M", "η"), + (0x1D723, "M", "θ"), + (0x1D724, "M", "ι"), + (0x1D725, "M", "κ"), + (0x1D726, "M", "λ"), + (0x1D727, "M", "μ"), + (0x1D728, "M", "ν"), + (0x1D729, "M", "ξ"), + (0x1D72A, "M", "ο"), + (0x1D72B, "M", "π"), + (0x1D72C, "M", "ρ"), + (0x1D72D, "M", "θ"), + (0x1D72E, "M", "σ"), + (0x1D72F, "M", "τ"), + (0x1D730, "M", "υ"), + (0x1D731, "M", "φ"), + (0x1D732, "M", "χ"), + (0x1D733, "M", "ψ"), + (0x1D734, "M", "ω"), + (0x1D735, "M", "∇"), + (0x1D736, "M", "α"), + (0x1D737, "M", "β"), + (0x1D738, "M", "γ"), + (0x1D739, "M", "δ"), + (0x1D73A, "M", "ε"), + (0x1D73B, "M", "ζ"), + (0x1D73C, "M", "η"), + (0x1D73D, "M", "θ"), + (0x1D73E, "M", "ι"), + (0x1D73F, "M", "κ"), + (0x1D740, "M", "λ"), + (0x1D741, "M", "μ"), + (0x1D742, "M", "ν"), + (0x1D743, "M", "ξ"), + (0x1D744, "M", "ο"), + (0x1D745, "M", "π"), + (0x1D746, "M", "ρ"), + (0x1D747, "M", "σ"), + (0x1D749, "M", "τ"), + (0x1D74A, "M", "υ"), + (0x1D74B, "M", "φ"), + (0x1D74C, "M", "χ"), + (0x1D74D, "M", "ψ"), + (0x1D74E, "M", "ω"), + (0x1D74F, "M", "∂"), + (0x1D750, "M", "ε"), + (0x1D751, "M", "θ"), + (0x1D752, "M", "κ"), + (0x1D753, "M", "φ"), + (0x1D754, "M", "ρ"), + (0x1D755, "M", "π"), + (0x1D756, "M", "α"), + (0x1D757, "M", "β"), + (0x1D758, "M", "γ"), + (0x1D759, "M", "δ"), + (0x1D75A, "M", "ε"), + (0x1D75B, "M", "ζ"), + (0x1D75C, "M", "η"), + (0x1D75D, "M", "θ"), + (0x1D75E, "M", "ι"), + (0x1D75F, "M", "κ"), + (0x1D760, "M", "λ"), + (0x1D761, "M", "μ"), + (0x1D762, "M", "ν"), + (0x1D763, "M", "ξ"), + (0x1D764, "M", "ο"), + (0x1D765, "M", "π"), + (0x1D766, "M", "ρ"), + (0x1D767, "M", "θ"), + (0x1D768, "M", "σ"), + (0x1D769, "M", "τ"), + (0x1D76A, "M", "υ"), + (0x1D76B, "M", "φ"), + (0x1D76C, "M", "χ"), + (0x1D76D, "M", "ψ"), + (0x1D76E, "M", "ω"), + (0x1D76F, "M", "∇"), + (0x1D770, "M", "α"), + (0x1D771, "M", "β"), + (0x1D772, "M", "γ"), + (0x1D773, "M", "δ"), + (0x1D774, "M", "ε"), + (0x1D775, "M", "ζ"), + (0x1D776, "M", "η"), + (0x1D777, "M", "θ"), + (0x1D778, "M", "ι"), + (0x1D779, "M", "κ"), + (0x1D77A, "M", "λ"), + (0x1D77B, "M", "μ"), + (0x1D77C, "M", "ν"), + (0x1D77D, "M", "ξ"), + (0x1D77E, "M", "ο"), + (0x1D77F, "M", "π"), + (0x1D780, "M", "ρ"), + (0x1D781, "M", "σ"), + (0x1D783, "M", "τ"), + (0x1D784, "M", "υ"), + (0x1D785, "M", "φ"), + (0x1D786, "M", "χ"), + ] + + +def _seg_71() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0x1D787, "M", "ψ"), + (0x1D788, "M", "ω"), + (0x1D789, "M", "∂"), + (0x1D78A, "M", "ε"), + (0x1D78B, "M", "θ"), + (0x1D78C, "M", "κ"), + (0x1D78D, "M", "φ"), + (0x1D78E, "M", "ρ"), + (0x1D78F, "M", "π"), + (0x1D790, "M", "α"), + (0x1D791, "M", "β"), + (0x1D792, "M", "γ"), + (0x1D793, "M", "δ"), + (0x1D794, "M", "ε"), + (0x1D795, "M", "ζ"), + (0x1D796, "M", "η"), + (0x1D797, "M", "θ"), + (0x1D798, "M", "ι"), + (0x1D799, "M", "κ"), + (0x1D79A, "M", "λ"), + (0x1D79B, "M", "μ"), + (0x1D79C, "M", "ν"), + (0x1D79D, "M", "ξ"), + (0x1D79E, "M", "ο"), + (0x1D79F, "M", "π"), + (0x1D7A0, "M", "ρ"), + (0x1D7A1, "M", "θ"), + (0x1D7A2, "M", "σ"), + (0x1D7A3, "M", "τ"), + (0x1D7A4, "M", "υ"), + (0x1D7A5, "M", "φ"), + (0x1D7A6, "M", "χ"), + (0x1D7A7, "M", "ψ"), + (0x1D7A8, "M", "ω"), + (0x1D7A9, "M", "∇"), + (0x1D7AA, "M", "α"), + (0x1D7AB, "M", "β"), + (0x1D7AC, "M", "γ"), + (0x1D7AD, "M", "δ"), + (0x1D7AE, "M", "ε"), + (0x1D7AF, "M", "ζ"), + (0x1D7B0, "M", "η"), + (0x1D7B1, "M", "θ"), + (0x1D7B2, "M", "ι"), + (0x1D7B3, "M", "κ"), + (0x1D7B4, "M", "λ"), + (0x1D7B5, "M", "μ"), + (0x1D7B6, "M", "ν"), + (0x1D7B7, "M", "ξ"), + (0x1D7B8, "M", "ο"), + (0x1D7B9, "M", "π"), + (0x1D7BA, "M", "ρ"), + (0x1D7BB, "M", "σ"), + (0x1D7BD, "M", "τ"), + (0x1D7BE, "M", "υ"), + (0x1D7BF, "M", "φ"), + (0x1D7C0, "M", "χ"), + (0x1D7C1, "M", "ψ"), + (0x1D7C2, "M", "ω"), + (0x1D7C3, "M", "∂"), + (0x1D7C4, "M", "ε"), + (0x1D7C5, "M", "θ"), + (0x1D7C6, "M", "κ"), + (0x1D7C7, "M", "φ"), + (0x1D7C8, "M", "ρ"), + (0x1D7C9, "M", "π"), + (0x1D7CA, "M", "ϝ"), + (0x1D7CC, "X"), + (0x1D7CE, "M", "0"), + (0x1D7CF, "M", "1"), + (0x1D7D0, "M", "2"), + (0x1D7D1, "M", "3"), + (0x1D7D2, "M", "4"), + (0x1D7D3, "M", "5"), + (0x1D7D4, "M", "6"), + (0x1D7D5, "M", "7"), + (0x1D7D6, "M", "8"), + (0x1D7D7, "M", "9"), + (0x1D7D8, "M", "0"), + (0x1D7D9, "M", "1"), + (0x1D7DA, "M", "2"), + (0x1D7DB, "M", "3"), + (0x1D7DC, "M", "4"), + (0x1D7DD, "M", "5"), + (0x1D7DE, "M", "6"), + (0x1D7DF, "M", "7"), + (0x1D7E0, "M", "8"), + (0x1D7E1, "M", "9"), + (0x1D7E2, "M", "0"), + (0x1D7E3, "M", "1"), + (0x1D7E4, "M", "2"), + (0x1D7E5, "M", "3"), + (0x1D7E6, "M", "4"), + (0x1D7E7, "M", "5"), + (0x1D7E8, "M", "6"), + (0x1D7E9, "M", "7"), + (0x1D7EA, "M", "8"), + (0x1D7EB, "M", "9"), + (0x1D7EC, "M", "0"), + (0x1D7ED, "M", "1"), + ] + + +def _seg_72() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0x1D7EE, "M", "2"), + (0x1D7EF, "M", "3"), + (0x1D7F0, "M", "4"), + (0x1D7F1, "M", "5"), + (0x1D7F2, "M", "6"), + (0x1D7F3, "M", "7"), + (0x1D7F4, "M", "8"), + (0x1D7F5, "M", "9"), + (0x1D7F6, "M", "0"), + (0x1D7F7, "M", "1"), + (0x1D7F8, "M", "2"), + (0x1D7F9, "M", "3"), + (0x1D7FA, "M", "4"), + (0x1D7FB, "M", "5"), + (0x1D7FC, "M", "6"), + (0x1D7FD, "M", "7"), + (0x1D7FE, "M", "8"), + (0x1D7FF, "M", "9"), + (0x1D800, "V"), + (0x1DA8C, "X"), + (0x1DA9B, "V"), + (0x1DAA0, "X"), + (0x1DAA1, "V"), + (0x1DAB0, "X"), + (0x1DF00, "V"), + (0x1DF1F, "X"), + (0x1DF25, "V"), + (0x1DF2B, "X"), + (0x1E000, "V"), + (0x1E007, "X"), + (0x1E008, "V"), + (0x1E019, "X"), + (0x1E01B, "V"), + (0x1E022, "X"), + (0x1E023, "V"), + (0x1E025, "X"), + (0x1E026, "V"), + (0x1E02B, "X"), + (0x1E030, "M", "а"), + (0x1E031, "M", "б"), + (0x1E032, "M", "в"), + (0x1E033, "M", "г"), + (0x1E034, "M", "д"), + (0x1E035, "M", "е"), + (0x1E036, "M", "ж"), + (0x1E037, "M", "з"), + (0x1E038, "M", "и"), + (0x1E039, "M", "к"), + (0x1E03A, "M", "л"), + (0x1E03B, "M", "м"), + (0x1E03C, "M", "о"), + (0x1E03D, "M", "п"), + (0x1E03E, "M", "р"), + (0x1E03F, "M", "с"), + (0x1E040, "M", "т"), + (0x1E041, "M", "у"), + (0x1E042, "M", "ф"), + (0x1E043, "M", "х"), + (0x1E044, "M", "ц"), + (0x1E045, "M", "ч"), + (0x1E046, "M", "ш"), + (0x1E047, "M", "ы"), + (0x1E048, "M", "э"), + (0x1E049, "M", "ю"), + (0x1E04A, "M", "ꚉ"), + (0x1E04B, "M", "ә"), + (0x1E04C, "M", "і"), + (0x1E04D, "M", "ј"), + (0x1E04E, "M", "ө"), + (0x1E04F, "M", "ү"), + (0x1E050, "M", "ӏ"), + (0x1E051, "M", "а"), + (0x1E052, "M", "б"), + (0x1E053, "M", "в"), + (0x1E054, "M", "г"), + (0x1E055, "M", "д"), + (0x1E056, "M", "е"), + (0x1E057, "M", "ж"), + (0x1E058, "M", "з"), + (0x1E059, "M", "и"), + (0x1E05A, "M", "к"), + (0x1E05B, "M", "л"), + (0x1E05C, "M", "о"), + (0x1E05D, "M", "п"), + (0x1E05E, "M", "с"), + (0x1E05F, "M", "у"), + (0x1E060, "M", "ф"), + (0x1E061, "M", "х"), + (0x1E062, "M", "ц"), + (0x1E063, "M", "ч"), + (0x1E064, "M", "ш"), + (0x1E065, "M", "ъ"), + (0x1E066, "M", "ы"), + (0x1E067, "M", "ґ"), + (0x1E068, "M", "і"), + (0x1E069, "M", "ѕ"), + (0x1E06A, "M", "џ"), + (0x1E06B, "M", "ҫ"), + (0x1E06C, "M", "ꙑ"), + (0x1E06D, "M", "ұ"), + ] + + +def _seg_73() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0x1E06E, "X"), + (0x1E08F, "V"), + (0x1E090, "X"), + (0x1E100, "V"), + (0x1E12D, "X"), + (0x1E130, "V"), + (0x1E13E, "X"), + (0x1E140, "V"), + (0x1E14A, "X"), + (0x1E14E, "V"), + (0x1E150, "X"), + (0x1E290, "V"), + (0x1E2AF, "X"), + (0x1E2C0, "V"), + (0x1E2FA, "X"), + (0x1E2FF, "V"), + (0x1E300, "X"), + (0x1E4D0, "V"), + (0x1E4FA, "X"), + (0x1E5D0, "V"), + (0x1E5FB, "X"), + (0x1E5FF, "V"), + (0x1E600, "X"), + (0x1E7E0, "V"), + (0x1E7E7, "X"), + (0x1E7E8, "V"), + (0x1E7EC, "X"), + (0x1E7ED, "V"), + (0x1E7EF, "X"), + (0x1E7F0, "V"), + (0x1E7FF, "X"), + (0x1E800, "V"), + (0x1E8C5, "X"), + (0x1E8C7, "V"), + (0x1E8D7, "X"), + (0x1E900, "M", "𞤢"), + (0x1E901, "M", "𞤣"), + (0x1E902, "M", "𞤤"), + (0x1E903, "M", "𞤥"), + (0x1E904, "M", "𞤦"), + (0x1E905, "M", "𞤧"), + (0x1E906, "M", "𞤨"), + (0x1E907, "M", "𞤩"), + (0x1E908, "M", "𞤪"), + (0x1E909, "M", "𞤫"), + (0x1E90A, "M", "𞤬"), + (0x1E90B, "M", "𞤭"), + (0x1E90C, "M", "𞤮"), + (0x1E90D, "M", "𞤯"), + (0x1E90E, "M", "𞤰"), + (0x1E90F, "M", "𞤱"), + (0x1E910, "M", "𞤲"), + (0x1E911, "M", "𞤳"), + (0x1E912, "M", "𞤴"), + (0x1E913, "M", "𞤵"), + (0x1E914, "M", "𞤶"), + (0x1E915, "M", "𞤷"), + (0x1E916, "M", "𞤸"), + (0x1E917, "M", "𞤹"), + (0x1E918, "M", "𞤺"), + (0x1E919, "M", "𞤻"), + (0x1E91A, "M", "𞤼"), + (0x1E91B, "M", "𞤽"), + (0x1E91C, "M", "𞤾"), + (0x1E91D, "M", "𞤿"), + (0x1E91E, "M", "𞥀"), + (0x1E91F, "M", "𞥁"), + (0x1E920, "M", "𞥂"), + (0x1E921, "M", "𞥃"), + (0x1E922, "V"), + (0x1E94C, "X"), + (0x1E950, "V"), + (0x1E95A, "X"), + (0x1E95E, "V"), + (0x1E960, "X"), + (0x1EC71, "V"), + (0x1ECB5, "X"), + (0x1ED01, "V"), + (0x1ED3E, "X"), + (0x1EE00, "M", "ا"), + (0x1EE01, "M", "ب"), + (0x1EE02, "M", "ج"), + (0x1EE03, "M", "د"), + (0x1EE04, "X"), + (0x1EE05, "M", "و"), + (0x1EE06, "M", "ز"), + (0x1EE07, "M", "ح"), + (0x1EE08, "M", "ط"), + (0x1EE09, "M", "ي"), + (0x1EE0A, "M", "ك"), + (0x1EE0B, "M", "ل"), + (0x1EE0C, "M", "م"), + (0x1EE0D, "M", "ن"), + (0x1EE0E, "M", "س"), + (0x1EE0F, "M", "ع"), + (0x1EE10, "M", "ف"), + (0x1EE11, "M", "ص"), + (0x1EE12, "M", "ق"), + (0x1EE13, "M", "ر"), + (0x1EE14, "M", "ش"), + ] + + +def _seg_74() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0x1EE15, "M", "ت"), + (0x1EE16, "M", "ث"), + (0x1EE17, "M", "خ"), + (0x1EE18, "M", "ذ"), + (0x1EE19, "M", "ض"), + (0x1EE1A, "M", "ظ"), + (0x1EE1B, "M", "غ"), + (0x1EE1C, "M", "ٮ"), + (0x1EE1D, "M", "ں"), + (0x1EE1E, "M", "ڡ"), + (0x1EE1F, "M", "ٯ"), + (0x1EE20, "X"), + (0x1EE21, "M", "ب"), + (0x1EE22, "M", "ج"), + (0x1EE23, "X"), + (0x1EE24, "M", "ه"), + (0x1EE25, "X"), + (0x1EE27, "M", "ح"), + (0x1EE28, "X"), + (0x1EE29, "M", "ي"), + (0x1EE2A, "M", "ك"), + (0x1EE2B, "M", "ل"), + (0x1EE2C, "M", "م"), + (0x1EE2D, "M", "ن"), + (0x1EE2E, "M", "س"), + (0x1EE2F, "M", "ع"), + (0x1EE30, "M", "ف"), + (0x1EE31, "M", "ص"), + (0x1EE32, "M", "ق"), + (0x1EE33, "X"), + (0x1EE34, "M", "ش"), + (0x1EE35, "M", "ت"), + (0x1EE36, "M", "ث"), + (0x1EE37, "M", "خ"), + (0x1EE38, "X"), + (0x1EE39, "M", "ض"), + (0x1EE3A, "X"), + (0x1EE3B, "M", "غ"), + (0x1EE3C, "X"), + (0x1EE42, "M", "ج"), + (0x1EE43, "X"), + (0x1EE47, "M", "ح"), + (0x1EE48, "X"), + (0x1EE49, "M", "ي"), + (0x1EE4A, "X"), + (0x1EE4B, "M", "ل"), + (0x1EE4C, "X"), + (0x1EE4D, "M", "ن"), + (0x1EE4E, "M", "س"), + (0x1EE4F, "M", "ع"), + (0x1EE50, "X"), + (0x1EE51, "M", "ص"), + (0x1EE52, "M", "ق"), + (0x1EE53, "X"), + (0x1EE54, "M", "ش"), + (0x1EE55, "X"), + (0x1EE57, "M", "خ"), + (0x1EE58, "X"), + (0x1EE59, "M", "ض"), + (0x1EE5A, "X"), + (0x1EE5B, "M", "غ"), + (0x1EE5C, "X"), + (0x1EE5D, "M", "ں"), + (0x1EE5E, "X"), + (0x1EE5F, "M", "ٯ"), + (0x1EE60, "X"), + (0x1EE61, "M", "ب"), + (0x1EE62, "M", "ج"), + (0x1EE63, "X"), + (0x1EE64, "M", "ه"), + (0x1EE65, "X"), + (0x1EE67, "M", "ح"), + (0x1EE68, "M", "ط"), + (0x1EE69, "M", "ي"), + (0x1EE6A, "M", "ك"), + (0x1EE6B, "X"), + (0x1EE6C, "M", "م"), + (0x1EE6D, "M", "ن"), + (0x1EE6E, "M", "س"), + (0x1EE6F, "M", "ع"), + (0x1EE70, "M", "ف"), + (0x1EE71, "M", "ص"), + (0x1EE72, "M", "ق"), + (0x1EE73, "X"), + (0x1EE74, "M", "ش"), + (0x1EE75, "M", "ت"), + (0x1EE76, "M", "ث"), + (0x1EE77, "M", "خ"), + (0x1EE78, "X"), + (0x1EE79, "M", "ض"), + (0x1EE7A, "M", "ظ"), + (0x1EE7B, "M", "غ"), + (0x1EE7C, "M", "ٮ"), + (0x1EE7D, "X"), + (0x1EE7E, "M", "ڡ"), + (0x1EE7F, "X"), + (0x1EE80, "M", "ا"), + (0x1EE81, "M", "ب"), + (0x1EE82, "M", "ج"), + (0x1EE83, "M", "د"), + ] + + +def _seg_75() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0x1EE84, "M", "ه"), + (0x1EE85, "M", "و"), + (0x1EE86, "M", "ز"), + (0x1EE87, "M", "ح"), + (0x1EE88, "M", "ط"), + (0x1EE89, "M", "ي"), + (0x1EE8A, "X"), + (0x1EE8B, "M", "ل"), + (0x1EE8C, "M", "م"), + (0x1EE8D, "M", "ن"), + (0x1EE8E, "M", "س"), + (0x1EE8F, "M", "ع"), + (0x1EE90, "M", "ف"), + (0x1EE91, "M", "ص"), + (0x1EE92, "M", "ق"), + (0x1EE93, "M", "ر"), + (0x1EE94, "M", "ش"), + (0x1EE95, "M", "ت"), + (0x1EE96, "M", "ث"), + (0x1EE97, "M", "خ"), + (0x1EE98, "M", "ذ"), + (0x1EE99, "M", "ض"), + (0x1EE9A, "M", "ظ"), + (0x1EE9B, "M", "غ"), + (0x1EE9C, "X"), + (0x1EEA1, "M", "ب"), + (0x1EEA2, "M", "ج"), + (0x1EEA3, "M", "د"), + (0x1EEA4, "X"), + (0x1EEA5, "M", "و"), + (0x1EEA6, "M", "ز"), + (0x1EEA7, "M", "ح"), + (0x1EEA8, "M", "ط"), + (0x1EEA9, "M", "ي"), + (0x1EEAA, "X"), + (0x1EEAB, "M", "ل"), + (0x1EEAC, "M", "م"), + (0x1EEAD, "M", "ن"), + (0x1EEAE, "M", "س"), + (0x1EEAF, "M", "ع"), + (0x1EEB0, "M", "ف"), + (0x1EEB1, "M", "ص"), + (0x1EEB2, "M", "ق"), + (0x1EEB3, "M", "ر"), + (0x1EEB4, "M", "ش"), + (0x1EEB5, "M", "ت"), + (0x1EEB6, "M", "ث"), + (0x1EEB7, "M", "خ"), + (0x1EEB8, "M", "ذ"), + (0x1EEB9, "M", "ض"), + (0x1EEBA, "M", "ظ"), + (0x1EEBB, "M", "غ"), + (0x1EEBC, "X"), + (0x1EEF0, "V"), + (0x1EEF2, "X"), + (0x1F000, "V"), + (0x1F02C, "X"), + (0x1F030, "V"), + (0x1F094, "X"), + (0x1F0A0, "V"), + (0x1F0AF, "X"), + (0x1F0B1, "V"), + (0x1F0C0, "X"), + (0x1F0C1, "V"), + (0x1F0D0, "X"), + (0x1F0D1, "V"), + (0x1F0F6, "X"), + (0x1F101, "M", "0,"), + (0x1F102, "M", "1,"), + (0x1F103, "M", "2,"), + (0x1F104, "M", "3,"), + (0x1F105, "M", "4,"), + (0x1F106, "M", "5,"), + (0x1F107, "M", "6,"), + (0x1F108, "M", "7,"), + (0x1F109, "M", "8,"), + (0x1F10A, "M", "9,"), + (0x1F10B, "V"), + (0x1F110, "M", "(a)"), + (0x1F111, "M", "(b)"), + (0x1F112, "M", "(c)"), + (0x1F113, "M", "(d)"), + (0x1F114, "M", "(e)"), + (0x1F115, "M", "(f)"), + (0x1F116, "M", "(g)"), + (0x1F117, "M", "(h)"), + (0x1F118, "M", "(i)"), + (0x1F119, "M", "(j)"), + (0x1F11A, "M", "(k)"), + (0x1F11B, "M", "(l)"), + (0x1F11C, "M", "(m)"), + (0x1F11D, "M", "(n)"), + (0x1F11E, "M", "(o)"), + (0x1F11F, "M", "(p)"), + (0x1F120, "M", "(q)"), + (0x1F121, "M", "(r)"), + (0x1F122, "M", "(s)"), + (0x1F123, "M", "(t)"), + (0x1F124, "M", "(u)"), + (0x1F125, "M", "(v)"), + ] + + +def _seg_76() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0x1F126, "M", "(w)"), + (0x1F127, "M", "(x)"), + (0x1F128, "M", "(y)"), + (0x1F129, "M", "(z)"), + (0x1F12A, "M", "〔s〕"), + (0x1F12B, "M", "c"), + (0x1F12C, "M", "r"), + (0x1F12D, "M", "cd"), + (0x1F12E, "M", "wz"), + (0x1F12F, "V"), + (0x1F130, "M", "a"), + (0x1F131, "M", "b"), + (0x1F132, "M", "c"), + (0x1F133, "M", "d"), + (0x1F134, "M", "e"), + (0x1F135, "M", "f"), + (0x1F136, "M", "g"), + (0x1F137, "M", "h"), + (0x1F138, "M", "i"), + (0x1F139, "M", "j"), + (0x1F13A, "M", "k"), + (0x1F13B, "M", "l"), + (0x1F13C, "M", "m"), + (0x1F13D, "M", "n"), + (0x1F13E, "M", "o"), + (0x1F13F, "M", "p"), + (0x1F140, "M", "q"), + (0x1F141, "M", "r"), + (0x1F142, "M", "s"), + (0x1F143, "M", "t"), + (0x1F144, "M", "u"), + (0x1F145, "M", "v"), + (0x1F146, "M", "w"), + (0x1F147, "M", "x"), + (0x1F148, "M", "y"), + (0x1F149, "M", "z"), + (0x1F14A, "M", "hv"), + (0x1F14B, "M", "mv"), + (0x1F14C, "M", "sd"), + (0x1F14D, "M", "ss"), + (0x1F14E, "M", "ppv"), + (0x1F14F, "M", "wc"), + (0x1F150, "V"), + (0x1F16A, "M", "mc"), + (0x1F16B, "M", "md"), + (0x1F16C, "M", "mr"), + (0x1F16D, "V"), + (0x1F190, "M", "dj"), + (0x1F191, "V"), + (0x1F1AE, "X"), + (0x1F1E6, "V"), + (0x1F200, "M", "ほか"), + (0x1F201, "M", "ココ"), + (0x1F202, "M", "サ"), + (0x1F203, "X"), + (0x1F210, "M", "手"), + (0x1F211, "M", "字"), + (0x1F212, "M", "双"), + (0x1F213, "M", "デ"), + (0x1F214, "M", "二"), + (0x1F215, "M", "多"), + (0x1F216, "M", "解"), + (0x1F217, "M", "天"), + (0x1F218, "M", "交"), + (0x1F219, "M", "映"), + (0x1F21A, "M", "無"), + (0x1F21B, "M", "料"), + (0x1F21C, "M", "前"), + (0x1F21D, "M", "後"), + (0x1F21E, "M", "再"), + (0x1F21F, "M", "新"), + (0x1F220, "M", "初"), + (0x1F221, "M", "終"), + (0x1F222, "M", "生"), + (0x1F223, "M", "販"), + (0x1F224, "M", "声"), + (0x1F225, "M", "吹"), + (0x1F226, "M", "演"), + (0x1F227, "M", "投"), + (0x1F228, "M", "捕"), + (0x1F229, "M", "一"), + (0x1F22A, "M", "三"), + (0x1F22B, "M", "遊"), + (0x1F22C, "M", "左"), + (0x1F22D, "M", "中"), + (0x1F22E, "M", "右"), + (0x1F22F, "M", "指"), + (0x1F230, "M", "走"), + (0x1F231, "M", "打"), + (0x1F232, "M", "禁"), + (0x1F233, "M", "空"), + (0x1F234, "M", "合"), + (0x1F235, "M", "満"), + (0x1F236, "M", "有"), + (0x1F237, "M", "月"), + (0x1F238, "M", "申"), + (0x1F239, "M", "割"), + (0x1F23A, "M", "営"), + (0x1F23B, "M", "配"), + (0x1F23C, "X"), + ] + + +def _seg_77() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0x1F240, "M", "〔本〕"), + (0x1F241, "M", "〔三〕"), + (0x1F242, "M", "〔二〕"), + (0x1F243, "M", "〔安〕"), + (0x1F244, "M", "〔点〕"), + (0x1F245, "M", "〔打〕"), + (0x1F246, "M", "〔盗〕"), + (0x1F247, "M", "〔勝〕"), + (0x1F248, "M", "〔敗〕"), + (0x1F249, "X"), + (0x1F250, "M", "得"), + (0x1F251, "M", "可"), + (0x1F252, "X"), + (0x1F260, "V"), + (0x1F266, "X"), + (0x1F300, "V"), + (0x1F6D8, "X"), + (0x1F6DC, "V"), + (0x1F6ED, "X"), + (0x1F6F0, "V"), + (0x1F6FD, "X"), + (0x1F700, "V"), + (0x1F777, "X"), + (0x1F77B, "V"), + (0x1F7DA, "X"), + (0x1F7E0, "V"), + (0x1F7EC, "X"), + (0x1F7F0, "V"), + (0x1F7F1, "X"), + (0x1F800, "V"), + (0x1F80C, "X"), + (0x1F810, "V"), + (0x1F848, "X"), + (0x1F850, "V"), + (0x1F85A, "X"), + (0x1F860, "V"), + (0x1F888, "X"), + (0x1F890, "V"), + (0x1F8AE, "X"), + (0x1F8B0, "V"), + (0x1F8BC, "X"), + (0x1F8C0, "V"), + (0x1F8C2, "X"), + (0x1F900, "V"), + (0x1FA54, "X"), + (0x1FA60, "V"), + (0x1FA6E, "X"), + (0x1FA70, "V"), + (0x1FA7D, "X"), + (0x1FA80, "V"), + (0x1FA8A, "X"), + (0x1FA8F, "V"), + (0x1FAC7, "X"), + (0x1FACE, "V"), + (0x1FADD, "X"), + (0x1FADF, "V"), + (0x1FAEA, "X"), + (0x1FAF0, "V"), + (0x1FAF9, "X"), + (0x1FB00, "V"), + (0x1FB93, "X"), + (0x1FB94, "V"), + (0x1FBF0, "M", "0"), + (0x1FBF1, "M", "1"), + (0x1FBF2, "M", "2"), + (0x1FBF3, "M", "3"), + (0x1FBF4, "M", "4"), + (0x1FBF5, "M", "5"), + (0x1FBF6, "M", "6"), + (0x1FBF7, "M", "7"), + (0x1FBF8, "M", "8"), + (0x1FBF9, "M", "9"), + (0x1FBFA, "X"), + (0x20000, "V"), + (0x2A6E0, "X"), + (0x2A700, "V"), + (0x2B73A, "X"), + (0x2B740, "V"), + (0x2B81E, "X"), + (0x2B820, "V"), + (0x2CEA2, "X"), + (0x2CEB0, "V"), + (0x2EBE1, "X"), + (0x2EBF0, "V"), + (0x2EE5E, "X"), + (0x2F800, "M", "丽"), + (0x2F801, "M", "丸"), + (0x2F802, "M", "乁"), + (0x2F803, "M", "𠄢"), + (0x2F804, "M", "你"), + (0x2F805, "M", "侮"), + (0x2F806, "M", "侻"), + (0x2F807, "M", "倂"), + (0x2F808, "M", "偺"), + (0x2F809, "M", "備"), + (0x2F80A, "M", "僧"), + (0x2F80B, "M", "像"), + (0x2F80C, "M", "㒞"), + (0x2F80D, "M", "𠘺"), + (0x2F80E, "M", "免"), + ] + + +def _seg_78() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0x2F80F, "M", "兔"), + (0x2F810, "M", "兤"), + (0x2F811, "M", "具"), + (0x2F812, "M", "𠔜"), + (0x2F813, "M", "㒹"), + (0x2F814, "M", "內"), + (0x2F815, "M", "再"), + (0x2F816, "M", "𠕋"), + (0x2F817, "M", "冗"), + (0x2F818, "M", "冤"), + (0x2F819, "M", "仌"), + (0x2F81A, "M", "冬"), + (0x2F81B, "M", "况"), + (0x2F81C, "M", "𩇟"), + (0x2F81D, "M", "凵"), + (0x2F81E, "M", "刃"), + (0x2F81F, "M", "㓟"), + (0x2F820, "M", "刻"), + (0x2F821, "M", "剆"), + (0x2F822, "M", "割"), + (0x2F823, "M", "剷"), + (0x2F824, "M", "㔕"), + (0x2F825, "M", "勇"), + (0x2F826, "M", "勉"), + (0x2F827, "M", "勤"), + (0x2F828, "M", "勺"), + (0x2F829, "M", "包"), + (0x2F82A, "M", "匆"), + (0x2F82B, "M", "北"), + (0x2F82C, "M", "卉"), + (0x2F82D, "M", "卑"), + (0x2F82E, "M", "博"), + (0x2F82F, "M", "即"), + (0x2F830, "M", "卽"), + (0x2F831, "M", "卿"), + (0x2F834, "M", "𠨬"), + (0x2F835, "M", "灰"), + (0x2F836, "M", "及"), + (0x2F837, "M", "叟"), + (0x2F838, "M", "𠭣"), + (0x2F839, "M", "叫"), + (0x2F83A, "M", "叱"), + (0x2F83B, "M", "吆"), + (0x2F83C, "M", "咞"), + (0x2F83D, "M", "吸"), + (0x2F83E, "M", "呈"), + (0x2F83F, "M", "周"), + (0x2F840, "M", "咢"), + (0x2F841, "M", "哶"), + (0x2F842, "M", "唐"), + (0x2F843, "M", "啓"), + (0x2F844, "M", "啣"), + (0x2F845, "M", "善"), + (0x2F847, "M", "喙"), + (0x2F848, "M", "喫"), + (0x2F849, "M", "喳"), + (0x2F84A, "M", "嗂"), + (0x2F84B, "M", "圖"), + (0x2F84C, "M", "嘆"), + (0x2F84D, "M", "圗"), + (0x2F84E, "M", "噑"), + (0x2F84F, "M", "噴"), + (0x2F850, "M", "切"), + (0x2F851, "M", "壮"), + (0x2F852, "M", "城"), + (0x2F853, "M", "埴"), + (0x2F854, "M", "堍"), + (0x2F855, "M", "型"), + (0x2F856, "M", "堲"), + (0x2F857, "M", "報"), + (0x2F858, "M", "墬"), + (0x2F859, "M", "𡓤"), + (0x2F85A, "M", "売"), + (0x2F85B, "M", "壷"), + (0x2F85C, "M", "夆"), + (0x2F85D, "M", "多"), + (0x2F85E, "M", "夢"), + (0x2F85F, "M", "奢"), + (0x2F860, "M", "𡚨"), + (0x2F861, "M", "𡛪"), + (0x2F862, "M", "姬"), + (0x2F863, "M", "娛"), + (0x2F864, "M", "娧"), + (0x2F865, "M", "姘"), + (0x2F866, "M", "婦"), + (0x2F867, "M", "㛮"), + (0x2F868, "M", "㛼"), + (0x2F869, "M", "嬈"), + (0x2F86A, "M", "嬾"), + (0x2F86C, "M", "𡧈"), + (0x2F86D, "M", "寃"), + (0x2F86E, "M", "寘"), + (0x2F86F, "M", "寧"), + (0x2F870, "M", "寳"), + (0x2F871, "M", "𡬘"), + (0x2F872, "M", "寿"), + (0x2F873, "M", "将"), + (0x2F874, "M", "当"), + (0x2F875, "M", "尢"), + (0x2F876, "M", "㞁"), + ] + + +def _seg_79() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0x2F877, "M", "屠"), + (0x2F878, "M", "屮"), + (0x2F879, "M", "峀"), + (0x2F87A, "M", "岍"), + (0x2F87B, "M", "𡷤"), + (0x2F87C, "M", "嵃"), + (0x2F87D, "M", "𡷦"), + (0x2F87E, "M", "嵮"), + (0x2F87F, "M", "嵫"), + (0x2F880, "M", "嵼"), + (0x2F881, "M", "巡"), + (0x2F882, "M", "巢"), + (0x2F883, "M", "㠯"), + (0x2F884, "M", "巽"), + (0x2F885, "M", "帨"), + (0x2F886, "M", "帽"), + (0x2F887, "M", "幩"), + (0x2F888, "M", "㡢"), + (0x2F889, "M", "𢆃"), + (0x2F88A, "M", "㡼"), + (0x2F88B, "M", "庰"), + (0x2F88C, "M", "庳"), + (0x2F88D, "M", "庶"), + (0x2F88E, "M", "廊"), + (0x2F88F, "M", "𪎒"), + (0x2F890, "M", "廾"), + (0x2F891, "M", "𢌱"), + (0x2F893, "M", "舁"), + (0x2F894, "M", "弢"), + (0x2F896, "M", "㣇"), + (0x2F897, "M", "𣊸"), + (0x2F898, "M", "𦇚"), + (0x2F899, "M", "形"), + (0x2F89A, "M", "彫"), + (0x2F89B, "M", "㣣"), + (0x2F89C, "M", "徚"), + (0x2F89D, "M", "忍"), + (0x2F89E, "M", "志"), + (0x2F89F, "M", "忹"), + (0x2F8A0, "M", "悁"), + (0x2F8A1, "M", "㤺"), + (0x2F8A2, "M", "㤜"), + (0x2F8A3, "M", "悔"), + (0x2F8A4, "M", "𢛔"), + (0x2F8A5, "M", "惇"), + (0x2F8A6, "M", "慈"), + (0x2F8A7, "M", "慌"), + (0x2F8A8, "M", "慎"), + (0x2F8A9, "M", "慌"), + (0x2F8AA, "M", "慺"), + (0x2F8AB, "M", "憎"), + (0x2F8AC, "M", "憲"), + (0x2F8AD, "M", "憤"), + (0x2F8AE, "M", "憯"), + (0x2F8AF, "M", "懞"), + (0x2F8B0, "M", "懲"), + (0x2F8B1, "M", "懶"), + (0x2F8B2, "M", "成"), + (0x2F8B3, "M", "戛"), + (0x2F8B4, "M", "扝"), + (0x2F8B5, "M", "抱"), + (0x2F8B6, "M", "拔"), + (0x2F8B7, "M", "捐"), + (0x2F8B8, "M", "𢬌"), + (0x2F8B9, "M", "挽"), + (0x2F8BA, "M", "拼"), + (0x2F8BB, "M", "捨"), + (0x2F8BC, "M", "掃"), + (0x2F8BD, "M", "揤"), + (0x2F8BE, "M", "𢯱"), + (0x2F8BF, "M", "搢"), + (0x2F8C0, "M", "揅"), + (0x2F8C1, "M", "掩"), + (0x2F8C2, "M", "㨮"), + (0x2F8C3, "M", "摩"), + (0x2F8C4, "M", "摾"), + (0x2F8C5, "M", "撝"), + (0x2F8C6, "M", "摷"), + (0x2F8C7, "M", "㩬"), + (0x2F8C8, "M", "敏"), + (0x2F8C9, "M", "敬"), + (0x2F8CA, "M", "𣀊"), + (0x2F8CB, "M", "旣"), + (0x2F8CC, "M", "書"), + (0x2F8CD, "M", "晉"), + (0x2F8CE, "M", "㬙"), + (0x2F8CF, "M", "暑"), + (0x2F8D0, "M", "㬈"), + (0x2F8D1, "M", "㫤"), + (0x2F8D2, "M", "冒"), + (0x2F8D3, "M", "冕"), + (0x2F8D4, "M", "最"), + (0x2F8D5, "M", "暜"), + (0x2F8D6, "M", "肭"), + (0x2F8D7, "M", "䏙"), + (0x2F8D8, "M", "朗"), + (0x2F8D9, "M", "望"), + (0x2F8DA, "M", "朡"), + (0x2F8DB, "M", "杞"), + (0x2F8DC, "M", "杓"), + ] + + +def _seg_80() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0x2F8DD, "M", "𣏃"), + (0x2F8DE, "M", "㭉"), + (0x2F8DF, "M", "柺"), + (0x2F8E0, "M", "枅"), + (0x2F8E1, "M", "桒"), + (0x2F8E2, "M", "梅"), + (0x2F8E3, "M", "𣑭"), + (0x2F8E4, "M", "梎"), + (0x2F8E5, "M", "栟"), + (0x2F8E6, "M", "椔"), + (0x2F8E7, "M", "㮝"), + (0x2F8E8, "M", "楂"), + (0x2F8E9, "M", "榣"), + (0x2F8EA, "M", "槪"), + (0x2F8EB, "M", "檨"), + (0x2F8EC, "M", "𣚣"), + (0x2F8ED, "M", "櫛"), + (0x2F8EE, "M", "㰘"), + (0x2F8EF, "M", "次"), + (0x2F8F0, "M", "𣢧"), + (0x2F8F1, "M", "歔"), + (0x2F8F2, "M", "㱎"), + (0x2F8F3, "M", "歲"), + (0x2F8F4, "M", "殟"), + (0x2F8F5, "M", "殺"), + (0x2F8F6, "M", "殻"), + (0x2F8F7, "M", "𣪍"), + (0x2F8F8, "M", "𡴋"), + (0x2F8F9, "M", "𣫺"), + (0x2F8FA, "M", "汎"), + (0x2F8FB, "M", "𣲼"), + (0x2F8FC, "M", "沿"), + (0x2F8FD, "M", "泍"), + (0x2F8FE, "M", "汧"), + (0x2F8FF, "M", "洖"), + (0x2F900, "M", "派"), + (0x2F901, "M", "海"), + (0x2F902, "M", "流"), + (0x2F903, "M", "浩"), + (0x2F904, "M", "浸"), + (0x2F905, "M", "涅"), + (0x2F906, "M", "𣴞"), + (0x2F907, "M", "洴"), + (0x2F908, "M", "港"), + (0x2F909, "M", "湮"), + (0x2F90A, "M", "㴳"), + (0x2F90B, "M", "滋"), + (0x2F90C, "M", "滇"), + (0x2F90D, "M", "𣻑"), + (0x2F90E, "M", "淹"), + (0x2F90F, "M", "潮"), + (0x2F910, "M", "𣽞"), + (0x2F911, "M", "𣾎"), + (0x2F912, "M", "濆"), + (0x2F913, "M", "瀹"), + (0x2F914, "M", "瀞"), + (0x2F915, "M", "瀛"), + (0x2F916, "M", "㶖"), + (0x2F917, "M", "灊"), + (0x2F918, "M", "災"), + (0x2F919, "M", "灷"), + (0x2F91A, "M", "炭"), + (0x2F91B, "M", "𠔥"), + (0x2F91C, "M", "煅"), + (0x2F91D, "M", "𤉣"), + (0x2F91E, "M", "熜"), + (0x2F91F, "M", "𤎫"), + (0x2F920, "M", "爨"), + (0x2F921, "M", "爵"), + (0x2F922, "M", "牐"), + (0x2F923, "M", "𤘈"), + (0x2F924, "M", "犀"), + (0x2F925, "M", "犕"), + (0x2F926, "M", "𤜵"), + (0x2F927, "M", "𤠔"), + (0x2F928, "M", "獺"), + (0x2F929, "M", "王"), + (0x2F92A, "M", "㺬"), + (0x2F92B, "M", "玥"), + (0x2F92C, "M", "㺸"), + (0x2F92E, "M", "瑇"), + (0x2F92F, "M", "瑜"), + (0x2F930, "M", "瑱"), + (0x2F931, "M", "璅"), + (0x2F932, "M", "瓊"), + (0x2F933, "M", "㼛"), + (0x2F934, "M", "甤"), + (0x2F935, "M", "𤰶"), + (0x2F936, "M", "甾"), + (0x2F937, "M", "𤲒"), + (0x2F938, "M", "異"), + (0x2F939, "M", "𢆟"), + (0x2F93A, "M", "瘐"), + (0x2F93B, "M", "𤾡"), + (0x2F93C, "M", "𤾸"), + (0x2F93D, "M", "𥁄"), + (0x2F93E, "M", "㿼"), + (0x2F93F, "M", "䀈"), + (0x2F940, "M", "直"), + (0x2F941, "M", "𥃳"), + ] + + +def _seg_81() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0x2F942, "M", "𥃲"), + (0x2F943, "M", "𥄙"), + (0x2F944, "M", "𥄳"), + (0x2F945, "M", "眞"), + (0x2F946, "M", "真"), + (0x2F948, "M", "睊"), + (0x2F949, "M", "䀹"), + (0x2F94A, "M", "瞋"), + (0x2F94B, "M", "䁆"), + (0x2F94C, "M", "䂖"), + (0x2F94D, "M", "𥐝"), + (0x2F94E, "M", "硎"), + (0x2F94F, "M", "碌"), + (0x2F950, "M", "磌"), + (0x2F951, "M", "䃣"), + (0x2F952, "M", "𥘦"), + (0x2F953, "M", "祖"), + (0x2F954, "M", "𥚚"), + (0x2F955, "M", "𥛅"), + (0x2F956, "M", "福"), + (0x2F957, "M", "秫"), + (0x2F958, "M", "䄯"), + (0x2F959, "M", "穀"), + (0x2F95A, "M", "穊"), + (0x2F95B, "M", "穏"), + (0x2F95C, "M", "𥥼"), + (0x2F95D, "M", "𥪧"), + (0x2F95F, "M", "竮"), + (0x2F960, "M", "䈂"), + (0x2F961, "M", "𥮫"), + (0x2F962, "M", "篆"), + (0x2F963, "M", "築"), + (0x2F964, "M", "䈧"), + (0x2F965, "M", "𥲀"), + (0x2F966, "M", "糒"), + (0x2F967, "M", "䊠"), + (0x2F968, "M", "糨"), + (0x2F969, "M", "糣"), + (0x2F96A, "M", "紀"), + (0x2F96B, "M", "𥾆"), + (0x2F96C, "M", "絣"), + (0x2F96D, "M", "䌁"), + (0x2F96E, "M", "緇"), + (0x2F96F, "M", "縂"), + (0x2F970, "M", "繅"), + (0x2F971, "M", "䌴"), + (0x2F972, "M", "𦈨"), + (0x2F973, "M", "𦉇"), + (0x2F974, "M", "䍙"), + (0x2F975, "M", "𦋙"), + (0x2F976, "M", "罺"), + (0x2F977, "M", "𦌾"), + (0x2F978, "M", "羕"), + (0x2F979, "M", "翺"), + (0x2F97A, "M", "者"), + (0x2F97B, "M", "𦓚"), + (0x2F97C, "M", "𦔣"), + (0x2F97D, "M", "聠"), + (0x2F97E, "M", "𦖨"), + (0x2F97F, "M", "聰"), + (0x2F980, "M", "𣍟"), + (0x2F981, "M", "䏕"), + (0x2F982, "M", "育"), + (0x2F983, "M", "脃"), + (0x2F984, "M", "䐋"), + (0x2F985, "M", "脾"), + (0x2F986, "M", "媵"), + (0x2F987, "M", "𦞧"), + (0x2F988, "M", "𦞵"), + (0x2F989, "M", "𣎓"), + (0x2F98A, "M", "𣎜"), + (0x2F98B, "M", "舁"), + (0x2F98C, "M", "舄"), + (0x2F98D, "M", "辞"), + (0x2F98E, "M", "䑫"), + (0x2F98F, "M", "芑"), + (0x2F990, "M", "芋"), + (0x2F991, "M", "芝"), + (0x2F992, "M", "劳"), + (0x2F993, "M", "花"), + (0x2F994, "M", "芳"), + (0x2F995, "M", "芽"), + (0x2F996, "M", "苦"), + (0x2F997, "M", "𦬼"), + (0x2F998, "M", "若"), + (0x2F999, "M", "茝"), + (0x2F99A, "M", "荣"), + (0x2F99B, "M", "莭"), + (0x2F99C, "M", "茣"), + (0x2F99D, "M", "莽"), + (0x2F99E, "M", "菧"), + (0x2F99F, "M", "著"), + (0x2F9A0, "M", "荓"), + (0x2F9A1, "M", "菊"), + (0x2F9A2, "M", "菌"), + (0x2F9A3, "M", "菜"), + (0x2F9A4, "M", "𦰶"), + (0x2F9A5, "M", "𦵫"), + (0x2F9A6, "M", "𦳕"), + (0x2F9A7, "M", "䔫"), + ] + + +def _seg_82() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0x2F9A8, "M", "蓱"), + (0x2F9A9, "M", "蓳"), + (0x2F9AA, "M", "蔖"), + (0x2F9AB, "M", "𧏊"), + (0x2F9AC, "M", "蕤"), + (0x2F9AD, "M", "𦼬"), + (0x2F9AE, "M", "䕝"), + (0x2F9AF, "M", "䕡"), + (0x2F9B0, "M", "𦾱"), + (0x2F9B1, "M", "𧃒"), + (0x2F9B2, "M", "䕫"), + (0x2F9B3, "M", "虐"), + (0x2F9B4, "M", "虜"), + (0x2F9B5, "M", "虧"), + (0x2F9B6, "M", "虩"), + (0x2F9B7, "M", "蚩"), + (0x2F9B8, "M", "蚈"), + (0x2F9B9, "M", "蜎"), + (0x2F9BA, "M", "蛢"), + (0x2F9BB, "M", "蝹"), + (0x2F9BC, "M", "蜨"), + (0x2F9BD, "M", "蝫"), + (0x2F9BE, "M", "螆"), + (0x2F9BF, "M", "䗗"), + (0x2F9C0, "M", "蟡"), + (0x2F9C1, "M", "蠁"), + (0x2F9C2, "M", "䗹"), + (0x2F9C3, "M", "衠"), + (0x2F9C4, "M", "衣"), + (0x2F9C5, "M", "𧙧"), + (0x2F9C6, "M", "裗"), + (0x2F9C7, "M", "裞"), + (0x2F9C8, "M", "䘵"), + (0x2F9C9, "M", "裺"), + (0x2F9CA, "M", "㒻"), + (0x2F9CB, "M", "𧢮"), + (0x2F9CC, "M", "𧥦"), + (0x2F9CD, "M", "䚾"), + (0x2F9CE, "M", "䛇"), + (0x2F9CF, "M", "誠"), + (0x2F9D0, "M", "諭"), + (0x2F9D1, "M", "變"), + (0x2F9D2, "M", "豕"), + (0x2F9D3, "M", "𧲨"), + (0x2F9D4, "M", "貫"), + (0x2F9D5, "M", "賁"), + (0x2F9D6, "M", "贛"), + (0x2F9D7, "M", "起"), + (0x2F9D8, "M", "𧼯"), + (0x2F9D9, "M", "𠠄"), + (0x2F9DA, "M", "跋"), + (0x2F9DB, "M", "趼"), + (0x2F9DC, "M", "跰"), + (0x2F9DD, "M", "𠣞"), + (0x2F9DE, "M", "軔"), + (0x2F9DF, "M", "輸"), + (0x2F9E0, "M", "𨗒"), + (0x2F9E1, "M", "𨗭"), + (0x2F9E2, "M", "邔"), + (0x2F9E3, "M", "郱"), + (0x2F9E4, "M", "鄑"), + (0x2F9E5, "M", "𨜮"), + (0x2F9E6, "M", "鄛"), + (0x2F9E7, "M", "鈸"), + (0x2F9E8, "M", "鋗"), + (0x2F9E9, "M", "鋘"), + (0x2F9EA, "M", "鉼"), + (0x2F9EB, "M", "鏹"), + (0x2F9EC, "M", "鐕"), + (0x2F9ED, "M", "𨯺"), + (0x2F9EE, "M", "開"), + (0x2F9EF, "M", "䦕"), + (0x2F9F0, "M", "閷"), + (0x2F9F1, "M", "𨵷"), + (0x2F9F2, "M", "䧦"), + (0x2F9F3, "M", "雃"), + (0x2F9F4, "M", "嶲"), + (0x2F9F5, "M", "霣"), + (0x2F9F6, "M", "𩅅"), + (0x2F9F7, "M", "𩈚"), + (0x2F9F8, "M", "䩮"), + (0x2F9F9, "M", "䩶"), + (0x2F9FA, "M", "韠"), + (0x2F9FB, "M", "𩐊"), + (0x2F9FC, "M", "䪲"), + (0x2F9FD, "M", "𩒖"), + (0x2F9FE, "M", "頋"), + (0x2FA00, "M", "頩"), + (0x2FA01, "M", "𩖶"), + (0x2FA02, "M", "飢"), + (0x2FA03, "M", "䬳"), + (0x2FA04, "M", "餩"), + (0x2FA05, "M", "馧"), + (0x2FA06, "M", "駂"), + (0x2FA07, "M", "駾"), + (0x2FA08, "M", "䯎"), + (0x2FA09, "M", "𩬰"), + (0x2FA0A, "M", "鬒"), + (0x2FA0B, "M", "鱀"), + (0x2FA0C, "M", "鳽"), + ] + + +def _seg_83() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0x2FA0D, "M", "䳎"), + (0x2FA0E, "M", "䳭"), + (0x2FA0F, "M", "鵧"), + (0x2FA10, "M", "𪃎"), + (0x2FA11, "M", "䳸"), + (0x2FA12, "M", "𪄅"), + (0x2FA13, "M", "𪈎"), + (0x2FA14, "M", "𪊑"), + (0x2FA15, "M", "麻"), + (0x2FA16, "M", "䵖"), + (0x2FA17, "M", "黹"), + (0x2FA18, "M", "黾"), + (0x2FA19, "M", "鼅"), + (0x2FA1A, "M", "鼏"), + (0x2FA1B, "M", "鼖"), + (0x2FA1C, "M", "鼻"), + (0x2FA1D, "M", "𪘀"), + (0x2FA1E, "X"), + (0x30000, "V"), + (0x3134B, "X"), + (0x31350, "V"), + (0x323B0, "X"), + (0xE0100, "I"), + (0xE01F0, "X"), + ] + + +uts46data = tuple( + _seg_0() + + _seg_1() + + _seg_2() + + _seg_3() + + _seg_4() + + _seg_5() + + _seg_6() + + _seg_7() + + _seg_8() + + _seg_9() + + _seg_10() + + _seg_11() + + _seg_12() + + _seg_13() + + _seg_14() + + _seg_15() + + _seg_16() + + _seg_17() + + _seg_18() + + _seg_19() + + _seg_20() + + _seg_21() + + _seg_22() + + _seg_23() + + _seg_24() + + _seg_25() + + _seg_26() + + _seg_27() + + _seg_28() + + _seg_29() + + _seg_30() + + _seg_31() + + _seg_32() + + _seg_33() + + _seg_34() + + _seg_35() + + _seg_36() + + _seg_37() + + _seg_38() + + _seg_39() + + _seg_40() + + _seg_41() + + _seg_42() + + _seg_43() + + _seg_44() + + _seg_45() + + _seg_46() + + _seg_47() + + _seg_48() + + _seg_49() + + _seg_50() + + _seg_51() + + _seg_52() + + _seg_53() + + _seg_54() + + _seg_55() + + _seg_56() + + _seg_57() + + _seg_58() + + _seg_59() + + _seg_60() + + _seg_61() + + _seg_62() + + _seg_63() + + _seg_64() + + _seg_65() + + _seg_66() + + _seg_67() + + _seg_68() + + _seg_69() + + _seg_70() + + _seg_71() + + _seg_72() + + _seg_73() + + _seg_74() + + _seg_75() + + _seg_76() + + _seg_77() + + _seg_78() + + _seg_79() + + _seg_80() + + _seg_81() + + _seg_82() + + _seg_83() +) # type: Tuple[Union[Tuple[int, str], Tuple[int, str, str]], ...] diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/itsdangerous-2.0.1.dist-info/INSTALLER b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/itsdangerous-2.0.1.dist-info/INSTALLER new file mode 100644 index 000000000..a1b589e38 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/itsdangerous-2.0.1.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/itsdangerous-2.0.1.dist-info/LICENSE.rst b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/itsdangerous-2.0.1.dist-info/LICENSE.rst new file mode 100644 index 000000000..7b190ca67 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/itsdangerous-2.0.1.dist-info/LICENSE.rst @@ -0,0 +1,28 @@ +Copyright 2011 Pallets + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A +PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED +TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/itsdangerous-2.0.1.dist-info/METADATA b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/itsdangerous-2.0.1.dist-info/METADATA new file mode 100644 index 000000000..660e9a24d --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/itsdangerous-2.0.1.dist-info/METADATA @@ -0,0 +1,96 @@ +Metadata-Version: 2.1 +Name: itsdangerous +Version: 2.0.1 +Summary: Safely pass data to untrusted environments and back. +Home-page: https://palletsprojects.com/p/itsdangerous/ +Author: Armin Ronacher +Author-email: armin.ronacher@active-4.com +Maintainer: Pallets +Maintainer-email: contact@palletsprojects.com +License: BSD-3-Clause +Project-URL: Donate, https://palletsprojects.com/donate +Project-URL: Documentation, https://itsdangerous.palletsprojects.com/ +Project-URL: Changes, https://itsdangerous.palletsprojects.com/changes/ +Project-URL: Source Code, https://github.com/pallets/itsdangerous/ +Project-URL: Issue Tracker, https://github.com/pallets/itsdangerous/issues/ +Project-URL: Twitter, https://twitter.com/PalletsTeam +Project-URL: Chat, https://discord.gg/pallets +Platform: UNKNOWN +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: BSD License +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: Python +Requires-Python: >=3.6 +Description-Content-Type: text/x-rst + +ItsDangerous +============ + +... so better sign this + +Various helpers to pass data to untrusted environments and to get it +back safe and sound. Data is cryptographically signed to ensure that a +token has not been tampered with. + +It's possible to customize how data is serialized. Data is compressed as +needed. A timestamp can be added and verified automatically while +loading a token. + + +Installing +---------- + +Install and update using `pip`_: + +.. code-block:: text + + pip install -U itsdangerous + +.. _pip: https://pip.pypa.io/en/stable/quickstart/ + + +A Simple Example +---------------- + +Here's how you could generate a token for transmitting a user's id and +name between web requests. + +.. code-block:: python + + from itsdangerous import URLSafeSerializer + auth_s = URLSafeSerializer("secret key", "auth") + token = auth_s.dumps({"id": 5, "name": "itsdangerous"}) + + print(token) + # eyJpZCI6NSwibmFtZSI6Iml0c2Rhbmdlcm91cyJ9.6YP6T0BaO67XP--9UzTrmurXSmg + + data = auth_s.loads(token) + print(data["name"]) + # itsdangerous + + +Donate +------ + +The Pallets organization develops and supports ItsDangerous and other +popular packages. In order to grow the community of contributors and +users, and allow the maintainers to devote more time to the projects, +`please donate today`_. + +.. _please donate today: https://palletsprojects.com/donate + + +Links +----- + +- Documentation: https://itsdangerous.palletsprojects.com/ +- Changes: https://itsdangerous.palletsprojects.com/changes/ +- PyPI Releases: https://pypi.org/project/ItsDangerous/ +- Source Code: https://github.com/pallets/itsdangerous/ +- Issue Tracker: https://github.com/pallets/itsdnagerous/issues/ +- Website: https://palletsprojects.com/p/itsdangerous/ +- Twitter: https://twitter.com/PalletsTeam +- Chat: https://discord.gg/pallets + + diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/itsdangerous-2.0.1.dist-info/RECORD b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/itsdangerous-2.0.1.dist-info/RECORD new file mode 100644 index 000000000..6d5a7f2e4 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/itsdangerous-2.0.1.dist-info/RECORD @@ -0,0 +1,26 @@ +itsdangerous-2.0.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +itsdangerous-2.0.1.dist-info/LICENSE.rst,sha256=Y68JiRtr6K0aQlLtQ68PTvun_JSOIoNnvtfzxa4LCdc,1475 +itsdangerous-2.0.1.dist-info/METADATA,sha256=QefBW2TemRBgE96yYn3UP-A51t8KTukwDHi7PopLOhQ,2897 +itsdangerous-2.0.1.dist-info/RECORD,, +itsdangerous-2.0.1.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +itsdangerous-2.0.1.dist-info/WHEEL,sha256=OqRkF0eY5GHssMorFjlbTIq072vpHpF60fIQA6lS9xA,92 +itsdangerous-2.0.1.dist-info/top_level.txt,sha256=gKN1OKLk81i7fbWWildJA88EQ9NhnGMSvZqhfz9ICjk,13 +itsdangerous/__init__.py,sha256=kFOxywqkUzCZHjc7l4RNjbirFIkG7R-IED7VwytJI_U,993 +itsdangerous/__pycache__/__init__.cpython-312.pyc,, +itsdangerous/__pycache__/_json.cpython-312.pyc,, +itsdangerous/__pycache__/encoding.cpython-312.pyc,, +itsdangerous/__pycache__/exc.cpython-312.pyc,, +itsdangerous/__pycache__/jws.cpython-312.pyc,, +itsdangerous/__pycache__/serializer.cpython-312.pyc,, +itsdangerous/__pycache__/signer.cpython-312.pyc,, +itsdangerous/__pycache__/timed.cpython-312.pyc,, +itsdangerous/__pycache__/url_safe.cpython-312.pyc,, +itsdangerous/_json.py,sha256=7nGypi9qk_1whBcPl3uYe-sWl1T-vloc9-BLK5TZAwE,918 +itsdangerous/encoding.py,sha256=zXNcTsxoCXQ0J76FCtn45Gb2zg4mwjKTPmHJUt2T_eA,1407 +itsdangerous/exc.py,sha256=VFxmP2lMoSJFqxNMzWonqs35ROII4-fvCBfG0v1Tkbs,3206 +itsdangerous/jws.py,sha256=keAvHRMieLBIQRPsvMU4W8CQPcaCqDU5Uc8plify5KU,8137 +itsdangerous/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +itsdangerous/serializer.py,sha256=zS6ZztooC_7qFwdO140NnI5MVvqKJEFbWbsOcXOO__Y,11137 +itsdangerous/signer.py,sha256=QUH0iX0in-OTptMAXKU5zWMwmOCXn1fsDsubXiGdFN4,9367 +itsdangerous/timed.py,sha256=vb-BZ57WyHd1hh9gbXae4qZhKNqZICuDflLINcsp9iY,7850 +itsdangerous/url_safe.py,sha256=WLIicndsXvzS2edX7XH8bjo9nurgE-brgo915CsAR9g,2388 diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/itsdangerous-2.0.1.dist-info/REQUESTED b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/itsdangerous-2.0.1.dist-info/REQUESTED new file mode 100644 index 000000000..e69de29bb diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/itsdangerous-2.0.1.dist-info/WHEEL b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/itsdangerous-2.0.1.dist-info/WHEEL new file mode 100644 index 000000000..385faab05 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/itsdangerous-2.0.1.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: bdist_wheel (0.36.2) +Root-Is-Purelib: true +Tag: py3-none-any + diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/itsdangerous-2.0.1.dist-info/top_level.txt b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/itsdangerous-2.0.1.dist-info/top_level.txt new file mode 100644 index 000000000..e163955e8 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/itsdangerous-2.0.1.dist-info/top_level.txt @@ -0,0 +1 @@ +itsdangerous diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/itsdangerous/__init__.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/itsdangerous/__init__.py new file mode 100644 index 000000000..5010252b4 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/itsdangerous/__init__.py @@ -0,0 +1,22 @@ +from ._json import json +from .encoding import base64_decode as base64_decode +from .encoding import base64_encode as base64_encode +from .encoding import want_bytes as want_bytes +from .exc import BadData as BadData +from .exc import BadHeader as BadHeader +from .exc import BadPayload as BadPayload +from .exc import BadSignature as BadSignature +from .exc import BadTimeSignature as BadTimeSignature +from .exc import SignatureExpired as SignatureExpired +from .jws import JSONWebSignatureSerializer +from .jws import TimedJSONWebSignatureSerializer +from .serializer import Serializer as Serializer +from .signer import HMACAlgorithm as HMACAlgorithm +from .signer import NoneAlgorithm as NoneAlgorithm +from .signer import Signer as Signer +from .timed import TimedSerializer as TimedSerializer +from .timed import TimestampSigner as TimestampSigner +from .url_safe import URLSafeSerializer as URLSafeSerializer +from .url_safe import URLSafeTimedSerializer as URLSafeTimedSerializer + +__version__ = "2.0.1" diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/itsdangerous/_json.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/itsdangerous/_json.py new file mode 100644 index 000000000..9368da2ac --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/itsdangerous/_json.py @@ -0,0 +1,34 @@ +import json as _json +import typing as _t +from types import ModuleType + + +class _CompactJSON: + """Wrapper around json module that strips whitespace.""" + + @staticmethod + def loads(payload: _t.Union[str, bytes]) -> _t.Any: + return _json.loads(payload) + + @staticmethod + def dumps(obj: _t.Any, **kwargs: _t.Any) -> str: + kwargs.setdefault("ensure_ascii", False) + kwargs.setdefault("separators", (",", ":")) + return _json.dumps(obj, **kwargs) + + +class DeprecatedJSON(ModuleType): + def __getattribute__(self, item: str) -> _t.Any: + import warnings + + warnings.warn( + "Importing 'itsdangerous.json' is deprecated and will be" + " removed in ItsDangerous 2.1. Use Python's 'json' module" + " instead.", + DeprecationWarning, + stacklevel=2, + ) + return getattr(_json, item) + + +json = DeprecatedJSON("json") diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/itsdangerous/encoding.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/itsdangerous/encoding.py new file mode 100644 index 000000000..cacc1c5f2 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/itsdangerous/encoding.py @@ -0,0 +1,54 @@ +import base64 +import string +import struct +import typing as _t + +from .exc import BadData + +_t_str_bytes = _t.Union[str, bytes] + + +def want_bytes( + s: _t_str_bytes, encoding: str = "utf-8", errors: str = "strict" +) -> bytes: + if isinstance(s, str): + s = s.encode(encoding, errors) + + return s + + +def base64_encode(string: _t_str_bytes) -> bytes: + """Base64 encode a string of bytes or text. The resulting bytes are + safe to use in URLs. + """ + string = want_bytes(string) + return base64.urlsafe_b64encode(string).rstrip(b"=") + + +def base64_decode(string: _t_str_bytes) -> bytes: + """Base64 decode a URL-safe string of bytes or text. The result is + bytes. + """ + string = want_bytes(string, encoding="ascii", errors="ignore") + string += b"=" * (-len(string) % 4) + + try: + return base64.urlsafe_b64decode(string) + except (TypeError, ValueError): + raise BadData("Invalid base64-encoded data") + + +# The alphabet used by base64.urlsafe_* +_base64_alphabet = f"{string.ascii_letters}{string.digits}-_=".encode("ascii") + +_int64_struct = struct.Struct(">Q") +_int_to_bytes = _int64_struct.pack +_bytes_to_int = _t.cast("_t.Callable[[bytes], _t.Tuple[int]]", _int64_struct.unpack) + + +def int_to_bytes(num: int) -> bytes: + return _int_to_bytes(num).lstrip(b"\x00") + + +def bytes_to_int(bytestr: bytes) -> int: + return _bytes_to_int(bytestr.rjust(8, b"\x00"))[0] diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/itsdangerous/exc.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/itsdangerous/exc.py new file mode 100644 index 000000000..c38a6af52 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/itsdangerous/exc.py @@ -0,0 +1,107 @@ +import typing as _t +from datetime import datetime + +_t_opt_any = _t.Optional[_t.Any] +_t_opt_exc = _t.Optional[Exception] + + +class BadData(Exception): + """Raised if bad data of any sort was encountered. This is the base + for all exceptions that ItsDangerous defines. + + .. versionadded:: 0.15 + """ + + def __init__(self, message: str): + super().__init__(message) + self.message = message + + def __str__(self) -> str: + return self.message + + +class BadSignature(BadData): + """Raised if a signature does not match.""" + + def __init__(self, message: str, payload: _t_opt_any = None): + super().__init__(message) + + #: The payload that failed the signature test. In some + #: situations you might still want to inspect this, even if + #: you know it was tampered with. + #: + #: .. versionadded:: 0.14 + self.payload: _t_opt_any = payload + + +class BadTimeSignature(BadSignature): + """Raised if a time-based signature is invalid. This is a subclass + of :class:`BadSignature`. + """ + + def __init__( + self, + message: str, + payload: _t_opt_any = None, + date_signed: _t.Optional[datetime] = None, + ): + super().__init__(message, payload) + + #: If the signature expired this exposes the date of when the + #: signature was created. This can be helpful in order to + #: tell the user how long a link has been gone stale. + #: + #: .. versionchanged:: 2.0 + #: The datetime value is timezone-aware rather than naive. + #: + #: .. versionadded:: 0.14 + self.date_signed = date_signed + + +class SignatureExpired(BadTimeSignature): + """Raised if a signature timestamp is older than ``max_age``. This + is a subclass of :exc:`BadTimeSignature`. + """ + + +class BadHeader(BadSignature): + """Raised if a signed header is invalid in some form. This only + happens for serializers that have a header that goes with the + signature. + + .. versionadded:: 0.24 + """ + + def __init__( + self, + message: str, + payload: _t_opt_any = None, + header: _t_opt_any = None, + original_error: _t_opt_exc = None, + ): + super().__init__(message, payload) + + #: If the header is actually available but just malformed it + #: might be stored here. + self.header: _t_opt_any = header + + #: If available, the error that indicates why the payload was + #: not valid. This might be ``None``. + self.original_error: _t_opt_exc = original_error + + +class BadPayload(BadData): + """Raised if a payload is invalid. This could happen if the payload + is loaded despite an invalid signature, or if there is a mismatch + between the serializer and deserializer. The original exception + that occurred during loading is stored on as :attr:`original_error`. + + .. versionadded:: 0.15 + """ + + def __init__(self, message: str, original_error: _t_opt_exc = None): + super().__init__(message) + + #: If available, the error that indicates why the payload was + #: not valid. This might be ``None``. + self.original_error: _t_opt_exc = original_error diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/itsdangerous/jws.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/itsdangerous/jws.py new file mode 100644 index 000000000..2353a30fe --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/itsdangerous/jws.py @@ -0,0 +1,259 @@ +import hashlib +import time +import warnings +from datetime import datetime +from datetime import timezone +from decimal import Decimal +from numbers import Real + +from ._json import _CompactJSON +from .encoding import base64_decode +from .encoding import base64_encode +from .encoding import want_bytes +from .exc import BadData +from .exc import BadHeader +from .exc import BadPayload +from .exc import BadSignature +from .exc import SignatureExpired +from .serializer import Serializer +from .signer import HMACAlgorithm +from .signer import NoneAlgorithm + + +class JSONWebSignatureSerializer(Serializer): + """This serializer implements JSON Web Signature (JWS) support. Only + supports the JWS Compact Serialization. + + .. deprecated:: 2.0 + Will be removed in ItsDangerous 2.1. Use a dedicated library + such as authlib. + """ + + jws_algorithms = { + "HS256": HMACAlgorithm(hashlib.sha256), + "HS384": HMACAlgorithm(hashlib.sha384), + "HS512": HMACAlgorithm(hashlib.sha512), + "none": NoneAlgorithm(), + } + + #: The default algorithm to use for signature generation + default_algorithm = "HS512" + + default_serializer = _CompactJSON + + def __init__( + self, + secret_key, + salt=None, + serializer=None, + serializer_kwargs=None, + signer=None, + signer_kwargs=None, + algorithm_name=None, + ): + warnings.warn( + "JWS support is deprecated and will be removed in" + " ItsDangerous 2.1. Use a dedicated JWS/JWT library such as" + " authlib.", + DeprecationWarning, + stacklevel=2, + ) + super().__init__( + secret_key, + salt=salt, + serializer=serializer, + serializer_kwargs=serializer_kwargs, + signer=signer, + signer_kwargs=signer_kwargs, + ) + + if algorithm_name is None: + algorithm_name = self.default_algorithm + + self.algorithm_name = algorithm_name + self.algorithm = self.make_algorithm(algorithm_name) + + def load_payload(self, payload, serializer=None, return_header=False): + payload = want_bytes(payload) + + if b"." not in payload: + raise BadPayload('No "." found in value') + + base64d_header, base64d_payload = payload.split(b".", 1) + + try: + json_header = base64_decode(base64d_header) + except Exception as e: + raise BadHeader( + "Could not base64 decode the header because of an exception", + original_error=e, + ) + + try: + json_payload = base64_decode(base64d_payload) + except Exception as e: + raise BadPayload( + "Could not base64 decode the payload because of an exception", + original_error=e, + ) + + try: + header = super().load_payload(json_header, serializer=_CompactJSON) + except BadData as e: + raise BadHeader( + "Could not unserialize header because it was malformed", + original_error=e, + ) + + if not isinstance(header, dict): + raise BadHeader("Header payload is not a JSON object", header=header) + + payload = super().load_payload(json_payload, serializer=serializer) + + if return_header: + return payload, header + + return payload + + def dump_payload(self, header, obj): + base64d_header = base64_encode( + self.serializer.dumps(header, **self.serializer_kwargs) + ) + base64d_payload = base64_encode( + self.serializer.dumps(obj, **self.serializer_kwargs) + ) + return base64d_header + b"." + base64d_payload + + def make_algorithm(self, algorithm_name): + try: + return self.jws_algorithms[algorithm_name] + except KeyError: + raise NotImplementedError("Algorithm not supported") + + def make_signer(self, salt=None, algorithm=None): + if salt is None: + salt = self.salt + + key_derivation = "none" if salt is None else None + + if algorithm is None: + algorithm = self.algorithm + + return self.signer( + self.secret_keys, + salt=salt, + sep=".", + key_derivation=key_derivation, + algorithm=algorithm, + ) + + def make_header(self, header_fields): + header = header_fields.copy() if header_fields else {} + header["alg"] = self.algorithm_name + return header + + def dumps(self, obj, salt=None, header_fields=None): + """Like :meth:`.Serializer.dumps` but creates a JSON Web + Signature. It also allows for specifying additional fields to be + included in the JWS header. + """ + header = self.make_header(header_fields) + signer = self.make_signer(salt, self.algorithm) + return signer.sign(self.dump_payload(header, obj)) + + def loads(self, s, salt=None, return_header=False): + """Reverse of :meth:`dumps`. If requested via ``return_header`` + it will return a tuple of payload and header. + """ + payload, header = self.load_payload( + self.make_signer(salt, self.algorithm).unsign(want_bytes(s)), + return_header=True, + ) + + if header.get("alg") != self.algorithm_name: + raise BadHeader("Algorithm mismatch", header=header, payload=payload) + + if return_header: + return payload, header + + return payload + + def loads_unsafe(self, s, salt=None, return_header=False): + kwargs = {"return_header": return_header} + return self._loads_unsafe_impl(s, salt, kwargs, kwargs) + + +class TimedJSONWebSignatureSerializer(JSONWebSignatureSerializer): + """Works like the regular :class:`JSONWebSignatureSerializer` but + also records the time of the signing and can be used to expire + signatures. + + JWS currently does not specify this behavior but it mentions a + possible extension like this in the spec. Expiry date is encoded + into the header similar to what's specified in `draft-ietf-oauth + -json-web-token `_. + """ + + DEFAULT_EXPIRES_IN = 3600 + + def __init__(self, secret_key, expires_in=None, **kwargs): + super().__init__(secret_key, **kwargs) + + if expires_in is None: + expires_in = self.DEFAULT_EXPIRES_IN + + self.expires_in = expires_in + + def make_header(self, header_fields): + header = super().make_header(header_fields) + iat = self.now() + exp = iat + self.expires_in + header["iat"] = iat + header["exp"] = exp + return header + + def loads(self, s, salt=None, return_header=False): + payload, header = super().loads(s, salt, return_header=True) + + if "exp" not in header: + raise BadSignature("Missing expiry date", payload=payload) + + int_date_error = BadHeader("Expiry date is not an IntDate", payload=payload) + + try: + header["exp"] = int(header["exp"]) + except ValueError: + raise int_date_error + + if header["exp"] < 0: + raise int_date_error + + if header["exp"] < self.now(): + raise SignatureExpired( + "Signature expired", + payload=payload, + date_signed=self.get_issue_date(header), + ) + + if return_header: + return payload, header + + return payload + + def get_issue_date(self, header): + """If the header contains the ``iat`` field, return the date the + signature was issued, as a timezone-aware + :class:`datetime.datetime` in UTC. + + .. versionchanged:: 2.0 + The timestamp is returned as a timezone-aware ``datetime`` + in UTC rather than a naive ``datetime`` assumed to be UTC. + """ + rv = header.get("iat") + + if isinstance(rv, (Real, Decimal)): + return datetime.fromtimestamp(int(rv), tz=timezone.utc) + + def now(self): + return int(time.time()) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/itsdangerous/py.typed b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/itsdangerous/py.typed new file mode 100644 index 000000000..e69de29bb diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/itsdangerous/serializer.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/itsdangerous/serializer.py new file mode 100644 index 000000000..36a73fbaa --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/itsdangerous/serializer.py @@ -0,0 +1,295 @@ +import json +import typing as _t + +from .encoding import want_bytes +from .exc import BadPayload +from .exc import BadSignature +from .signer import _make_keys_list +from .signer import Signer + +_t_str_bytes = _t.Union[str, bytes] +_t_opt_str_bytes = _t.Optional[_t_str_bytes] +_t_kwargs = _t.Dict[str, _t.Any] +_t_opt_kwargs = _t.Optional[_t_kwargs] +_t_signer = _t.Type[Signer] +_t_fallbacks = _t.List[_t.Union[_t_kwargs, _t.Tuple[_t_signer, _t_kwargs], _t_signer]] +_t_load_unsafe = _t.Tuple[bool, _t.Any] +_t_secret_key = _t.Union[_t.Iterable[_t_str_bytes], _t_str_bytes] + + +def is_text_serializer(serializer: _t.Any) -> bool: + """Checks whether a serializer generates text or binary.""" + return isinstance(serializer.dumps({}), str) + + +class Serializer: + """A serializer wraps a :class:`~itsdangerous.signer.Signer` to + enable serializing and securely signing data other than bytes. It + can unsign to verify that the data hasn't been changed. + + The serializer provides :meth:`dumps` and :meth:`loads`, similar to + :mod:`json`, and by default uses :mod:`json` internally to serialize + the data to bytes. + + The secret key should be a random string of ``bytes`` and should not + be saved to code or version control. Different salts should be used + to distinguish signing in different contexts. See :doc:`/concepts` + for information about the security of the secret key and salt. + + :param secret_key: The secret key to sign and verify with. Can be a + list of keys, oldest to newest, to support key rotation. + :param salt: Extra key to combine with ``secret_key`` to distinguish + signatures in different contexts. + :param serializer: An object that provides ``dumps`` and ``loads`` + methods for serializing data to a string. Defaults to + :attr:`default_serializer`, which defaults to :mod:`json`. + :param serializer_kwargs: Keyword arguments to pass when calling + ``serializer.dumps``. + :param signer: A ``Signer`` class to instantiate when signing data. + Defaults to :attr:`default_signer`, which defaults to + :class:`~itsdangerous.signer.Signer`. + :param signer_kwargs: Keyword arguments to pass when instantiating + the ``Signer`` class. + :param fallback_signers: List of signer parameters to try when + unsigning with the default signer fails. Each item can be a dict + of ``signer_kwargs``, a ``Signer`` class, or a tuple of + ``(signer, signer_kwargs)``. Defaults to + :attr:`default_fallback_signers`. + + .. versionchanged:: 2.0 + Added support for key rotation by passing a list to + ``secret_key``. + + .. versionchanged:: 2.0 + Removed the default SHA-512 fallback signer from + ``default_fallback_signers``. + + .. versionchanged:: 1.1 + Added support for ``fallback_signers`` and configured a default + SHA-512 fallback. This fallback is for users who used the yanked + 1.0.0 release which defaulted to SHA-512. + + .. versionchanged:: 0.14 + The ``signer`` and ``signer_kwargs`` parameters were added to + the constructor. + """ + + #: The default serialization module to use to serialize data to a + #: string internally. The default is :mod:`json`, but can be changed + #: to any object that provides ``dumps`` and ``loads`` methods. + default_serializer: _t.Any = json + + #: The default ``Signer`` class to instantiate when signing data. + #: The default is :class:`itsdangerous.signer.Signer`. + default_signer: _t_signer = Signer + + #: The default fallback signers to try when unsigning fails. + default_fallback_signers: _t_fallbacks = [] + + def __init__( + self, + secret_key: _t_secret_key, + salt: _t_opt_str_bytes = b"itsdangerous", + serializer: _t.Any = None, + serializer_kwargs: _t_opt_kwargs = None, + signer: _t.Optional[_t_signer] = None, + signer_kwargs: _t_opt_kwargs = None, + fallback_signers: _t.Optional[_t_fallbacks] = None, + ): + #: The list of secret keys to try for verifying signatures, from + #: oldest to newest. The newest (last) key is used for signing. + #: + #: This allows a key rotation system to keep a list of allowed + #: keys and remove expired ones. + self.secret_keys: _t.List[bytes] = _make_keys_list(secret_key) + + if salt is not None: + salt = want_bytes(salt) + # if salt is None then the signer's default is used + + self.salt = salt + + if serializer is None: + serializer = self.default_serializer + + self.serializer: _t.Any = serializer + self.is_text_serializer: bool = is_text_serializer(serializer) + + if signer is None: + signer = self.default_signer + + self.signer: _t_signer = signer + self.signer_kwargs: _t_kwargs = signer_kwargs or {} + + if fallback_signers is None: + fallback_signers = list(self.default_fallback_signers or ()) + + self.fallback_signers: _t_fallbacks = fallback_signers + self.serializer_kwargs: _t_kwargs = serializer_kwargs or {} + + @property + def secret_key(self) -> bytes: + """The newest (last) entry in the :attr:`secret_keys` list. This + is for compatibility from before key rotation support was added. + """ + return self.secret_keys[-1] + + def load_payload( + self, payload: bytes, serializer: _t.Optional[_t.Any] = None + ) -> _t.Any: + """Loads the encoded object. This function raises + :class:`.BadPayload` if the payload is not valid. The + ``serializer`` parameter can be used to override the serializer + stored on the class. The encoded ``payload`` should always be + bytes. + """ + if serializer is None: + serializer = self.serializer + is_text = self.is_text_serializer + else: + is_text = is_text_serializer(serializer) + + try: + if is_text: + return serializer.loads(payload.decode("utf-8")) + + return serializer.loads(payload) + except Exception as e: + raise BadPayload( + "Could not load the payload because an exception" + " occurred on unserializing the data.", + original_error=e, + ) + + def dump_payload(self, obj: _t.Any) -> bytes: + """Dumps the encoded object. The return value is always bytes. + If the internal serializer returns text, the value will be + encoded as UTF-8. + """ + return want_bytes(self.serializer.dumps(obj, **self.serializer_kwargs)) + + def make_signer(self, salt: _t_opt_str_bytes = None) -> Signer: + """Creates a new instance of the signer to be used. The default + implementation uses the :class:`.Signer` base class. + """ + if salt is None: + salt = self.salt + + return self.signer(self.secret_keys, salt=salt, **self.signer_kwargs) + + def iter_unsigners(self, salt: _t_opt_str_bytes = None) -> _t.Iterator[Signer]: + """Iterates over all signers to be tried for unsigning. Starts + with the configured signer, then constructs each signer + specified in ``fallback_signers``. + """ + if salt is None: + salt = self.salt + + yield self.make_signer(salt) + + for fallback in self.fallback_signers: + if isinstance(fallback, dict): + kwargs = fallback + fallback = self.signer + elif isinstance(fallback, tuple): + fallback, kwargs = fallback + else: + kwargs = self.signer_kwargs + + for secret_key in self.secret_keys: + yield fallback(secret_key, salt=salt, **kwargs) + + def dumps(self, obj: _t.Any, salt: _t_opt_str_bytes = None) -> _t_str_bytes: + """Returns a signed string serialized with the internal + serializer. The return value can be either a byte or unicode + string depending on the format of the internal serializer. + """ + payload = want_bytes(self.dump_payload(obj)) + rv = self.make_signer(salt).sign(payload) + + if self.is_text_serializer: + return rv.decode("utf-8") + + return rv + + def dump(self, obj: _t.Any, f: _t.IO, salt: _t_opt_str_bytes = None) -> None: + """Like :meth:`dumps` but dumps into a file. The file handle has + to be compatible with what the internal serializer expects. + """ + f.write(self.dumps(obj, salt)) + + def loads( + self, s: _t_str_bytes, salt: _t_opt_str_bytes = None, **kwargs: _t.Any + ) -> _t.Any: + """Reverse of :meth:`dumps`. Raises :exc:`.BadSignature` if the + signature validation fails. + """ + s = want_bytes(s) + last_exception = None + + for signer in self.iter_unsigners(salt): + try: + return self.load_payload(signer.unsign(s)) + except BadSignature as err: + last_exception = err + + raise _t.cast(BadSignature, last_exception) + + def load(self, f: _t.IO, salt: _t_opt_str_bytes = None) -> _t.Any: + """Like :meth:`loads` but loads from a file.""" + return self.loads(f.read(), salt) + + def loads_unsafe( + self, s: _t_str_bytes, salt: _t_opt_str_bytes = None + ) -> _t_load_unsafe: + """Like :meth:`loads` but without verifying the signature. This + is potentially very dangerous to use depending on how your + serializer works. The return value is ``(signature_valid, + payload)`` instead of just the payload. The first item will be a + boolean that indicates if the signature is valid. This function + never fails. + + Use it for debugging only and if you know that your serializer + module is not exploitable (for example, do not use it with a + pickle serializer). + + .. versionadded:: 0.15 + """ + return self._loads_unsafe_impl(s, salt) + + def _loads_unsafe_impl( + self, + s: _t_str_bytes, + salt: _t_opt_str_bytes, + load_kwargs: _t_opt_kwargs = None, + load_payload_kwargs: _t_opt_kwargs = None, + ) -> _t_load_unsafe: + """Low level helper function to implement :meth:`loads_unsafe` + in serializer subclasses. + """ + if load_kwargs is None: + load_kwargs = {} + + try: + return True, self.loads(s, salt=salt, **load_kwargs) + except BadSignature as e: + if e.payload is None: + return False, None + + if load_payload_kwargs is None: + load_payload_kwargs = {} + + try: + return ( + False, + self.load_payload(e.payload, **load_payload_kwargs), + ) + except BadPayload: + return False, None + + def load_unsafe(self, f: _t.IO, salt: _t_opt_str_bytes = None) -> _t_load_unsafe: + """Like :meth:`loads_unsafe` but loads from a file. + + .. versionadded:: 0.15 + """ + return self.loads_unsafe(f.read(), salt=salt) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/itsdangerous/signer.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/itsdangerous/signer.py new file mode 100644 index 000000000..aa12005e9 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/itsdangerous/signer.py @@ -0,0 +1,257 @@ +import hashlib +import hmac +import typing as _t + +from .encoding import _base64_alphabet +from .encoding import base64_decode +from .encoding import base64_encode +from .encoding import want_bytes +from .exc import BadSignature + +_t_str_bytes = _t.Union[str, bytes] +_t_opt_str_bytes = _t.Optional[_t_str_bytes] +_t_secret_key = _t.Union[_t.Iterable[_t_str_bytes], _t_str_bytes] + + +class SigningAlgorithm: + """Subclasses must implement :meth:`get_signature` to provide + signature generation functionality. + """ + + def get_signature(self, key: bytes, value: bytes) -> bytes: + """Returns the signature for the given key and value.""" + raise NotImplementedError() + + def verify_signature(self, key: bytes, value: bytes, sig: bytes) -> bool: + """Verifies the given signature matches the expected + signature. + """ + return hmac.compare_digest(sig, self.get_signature(key, value)) + + +class NoneAlgorithm(SigningAlgorithm): + """Provides an algorithm that does not perform any signing and + returns an empty signature. + """ + + def get_signature(self, key: bytes, value: bytes) -> bytes: + return b"" + + +class HMACAlgorithm(SigningAlgorithm): + """Provides signature generation using HMACs.""" + + #: The digest method to use with the MAC algorithm. This defaults to + #: SHA1, but can be changed to any other function in the hashlib + #: module. + default_digest_method: _t.Any = staticmethod(hashlib.sha1) + + def __init__(self, digest_method: _t.Any = None): + if digest_method is None: + digest_method = self.default_digest_method + + self.digest_method: _t.Any = digest_method + + def get_signature(self, key: bytes, value: bytes) -> bytes: + mac = hmac.new(key, msg=value, digestmod=self.digest_method) + return mac.digest() + + +def _make_keys_list(secret_key: _t_secret_key) -> _t.List[bytes]: + if isinstance(secret_key, (str, bytes)): + return [want_bytes(secret_key)] + + return [want_bytes(s) for s in secret_key] + + +class Signer: + """A signer securely signs bytes, then unsigns them to verify that + the value hasn't been changed. + + The secret key should be a random string of ``bytes`` and should not + be saved to code or version control. Different salts should be used + to distinguish signing in different contexts. See :doc:`/concepts` + for information about the security of the secret key and salt. + + :param secret_key: The secret key to sign and verify with. Can be a + list of keys, oldest to newest, to support key rotation. + :param salt: Extra key to combine with ``secret_key`` to distinguish + signatures in different contexts. + :param sep: Separator between the signature and value. + :param key_derivation: How to derive the signing key from the secret + key and salt. Possible values are ``concat``, ``django-concat``, + or ``hmac``. Defaults to :attr:`default_key_derivation`, which + defaults to ``django-concat``. + :param digest_method: Hash function to use when generating the HMAC + signature. Defaults to :attr:`default_digest_method`, which + defaults to :func:`hashlib.sha1`. Note that the security of the + hash alone doesn't apply when used intermediately in HMAC. + :param algorithm: A :class:`SigningAlgorithm` instance to use + instead of building a default :class:`HMACAlgorithm` with the + ``digest_method``. + + .. versionchanged:: 2.0 + Added support for key rotation by passing a list to + ``secret_key``. + + .. versionchanged:: 0.18 + ``algorithm`` was added as an argument to the class constructor. + + .. versionchanged:: 0.14 + ``key_derivation`` and ``digest_method`` were added as arguments + to the class constructor. + """ + + #: The default digest method to use for the signer. The default is + #: :func:`hashlib.sha1`, but can be changed to any :mod:`hashlib` or + #: compatible object. Note that the security of the hash alone + #: doesn't apply when used intermediately in HMAC. + #: + #: .. versionadded:: 0.14 + default_digest_method: _t.Any = staticmethod(hashlib.sha1) + + #: The default scheme to use to derive the signing key from the + #: secret key and salt. The default is ``django-concat``. Possible + #: values are ``concat``, ``django-concat``, and ``hmac``. + #: + #: .. versionadded:: 0.14 + default_key_derivation: str = "django-concat" + + def __init__( + self, + secret_key: _t_secret_key, + salt: _t_opt_str_bytes = b"itsdangerous.Signer", + sep: _t_str_bytes = b".", + key_derivation: _t.Optional[str] = None, + digest_method: _t.Optional[_t.Any] = None, + algorithm: _t.Optional[SigningAlgorithm] = None, + ): + #: The list of secret keys to try for verifying signatures, from + #: oldest to newest. The newest (last) key is used for signing. + #: + #: This allows a key rotation system to keep a list of allowed + #: keys and remove expired ones. + self.secret_keys: _t.List[bytes] = _make_keys_list(secret_key) + self.sep: bytes = want_bytes(sep) + + if self.sep in _base64_alphabet: + raise ValueError( + "The given separator cannot be used because it may be" + " contained in the signature itself. ASCII letters," + " digits, and '-_=' must not be used." + ) + + if salt is not None: + salt = want_bytes(salt) + else: + salt = b"itsdangerous.Signer" + + self.salt = salt + + if key_derivation is None: + key_derivation = self.default_key_derivation + + self.key_derivation: str = key_derivation + + if digest_method is None: + digest_method = self.default_digest_method + + self.digest_method: _t.Any = digest_method + + if algorithm is None: + algorithm = HMACAlgorithm(self.digest_method) + + self.algorithm: SigningAlgorithm = algorithm + + @property + def secret_key(self) -> bytes: + """The newest (last) entry in the :attr:`secret_keys` list. This + is for compatibility from before key rotation support was added. + """ + return self.secret_keys[-1] + + def derive_key(self, secret_key: _t_opt_str_bytes = None) -> bytes: + """This method is called to derive the key. The default key + derivation choices can be overridden here. Key derivation is not + intended to be used as a security method to make a complex key + out of a short password. Instead you should use large random + secret keys. + + :param secret_key: A specific secret key to derive from. + Defaults to the last item in :attr:`secret_keys`. + + .. versionchanged:: 2.0 + Added the ``secret_key`` parameter. + """ + if secret_key is None: + secret_key = self.secret_keys[-1] + else: + secret_key = want_bytes(secret_key) + + if self.key_derivation == "concat": + return _t.cast(bytes, self.digest_method(self.salt + secret_key).digest()) + elif self.key_derivation == "django-concat": + return _t.cast( + bytes, self.digest_method(self.salt + b"signer" + secret_key).digest() + ) + elif self.key_derivation == "hmac": + mac = hmac.new(secret_key, digestmod=self.digest_method) + mac.update(self.salt) + return mac.digest() + elif self.key_derivation == "none": + return secret_key + else: + raise TypeError("Unknown key derivation method") + + def get_signature(self, value: _t_str_bytes) -> bytes: + """Returns the signature for the given value.""" + value = want_bytes(value) + key = self.derive_key() + sig = self.algorithm.get_signature(key, value) + return base64_encode(sig) + + def sign(self, value: _t_str_bytes) -> bytes: + """Signs the given string.""" + value = want_bytes(value) + return value + self.sep + self.get_signature(value) + + def verify_signature(self, value: _t_str_bytes, sig: _t_str_bytes) -> bool: + """Verifies the signature for the given value.""" + try: + sig = base64_decode(sig) + except Exception: + return False + + value = want_bytes(value) + + for secret_key in reversed(self.secret_keys): + key = self.derive_key(secret_key) + + if self.algorithm.verify_signature(key, value, sig): + return True + + return False + + def unsign(self, signed_value: _t_str_bytes) -> bytes: + """Unsigns the given string.""" + signed_value = want_bytes(signed_value) + + if self.sep not in signed_value: + raise BadSignature(f"No {self.sep!r} found in value") + + value, sig = signed_value.rsplit(self.sep, 1) + + if self.verify_signature(value, sig): + return value + + raise BadSignature(f"Signature {sig!r} does not match", payload=value) + + def validate(self, signed_value: _t_str_bytes) -> bool: + """Only validates the given signed value. Returns ``True`` if + the signature exists and is valid. + """ + try: + self.unsign(signed_value) + return True + except BadSignature: + return False diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/itsdangerous/timed.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/itsdangerous/timed.py new file mode 100644 index 000000000..5ea957f9d --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/itsdangerous/timed.py @@ -0,0 +1,227 @@ +import time +import typing +import typing as _t +from datetime import datetime +from datetime import timezone + +from .encoding import base64_decode +from .encoding import base64_encode +from .encoding import bytes_to_int +from .encoding import int_to_bytes +from .encoding import want_bytes +from .exc import BadSignature +from .exc import BadTimeSignature +from .exc import SignatureExpired +from .serializer import Serializer +from .signer import Signer + +_t_str_bytes = _t.Union[str, bytes] +_t_opt_str_bytes = _t.Optional[_t_str_bytes] +_t_opt_int = _t.Optional[int] + +if _t.TYPE_CHECKING: + import typing_extensions as _te + + +class TimestampSigner(Signer): + """Works like the regular :class:`.Signer` but also records the time + of the signing and can be used to expire signatures. The + :meth:`unsign` method can raise :exc:`.SignatureExpired` if the + unsigning failed because the signature is expired. + """ + + def get_timestamp(self) -> int: + """Returns the current timestamp. The function must return an + integer. + """ + return int(time.time()) + + def timestamp_to_datetime(self, ts: int) -> datetime: + """Convert the timestamp from :meth:`get_timestamp` into an + aware :class`datetime.datetime` in UTC. + + .. versionchanged:: 2.0 + The timestamp is returned as a timezone-aware ``datetime`` + in UTC rather than a naive ``datetime`` assumed to be UTC. + """ + return datetime.fromtimestamp(ts, tz=timezone.utc) + + def sign(self, value: _t_str_bytes) -> bytes: + """Signs the given string and also attaches time information.""" + value = want_bytes(value) + timestamp = base64_encode(int_to_bytes(self.get_timestamp())) + sep = want_bytes(self.sep) + value = value + sep + timestamp + return value + sep + self.get_signature(value) + + # Ignore overlapping signatures check, return_timestamp is the only + # parameter that affects the return type. + + @typing.overload + def unsign( # type: ignore + self, + signed_value: _t_str_bytes, + max_age: _t_opt_int = None, + return_timestamp: "_te.Literal[False]" = False, + ) -> bytes: + ... + + @typing.overload + def unsign( + self, + signed_value: _t_str_bytes, + max_age: _t_opt_int = None, + return_timestamp: "_te.Literal[True]" = True, + ) -> _t.Tuple[bytes, datetime]: + ... + + def unsign( + self, + signed_value: _t_str_bytes, + max_age: _t_opt_int = None, + return_timestamp: bool = False, + ) -> _t.Union[_t.Tuple[bytes, datetime], bytes]: + """Works like the regular :meth:`.Signer.unsign` but can also + validate the time. See the base docstring of the class for + the general behavior. If ``return_timestamp`` is ``True`` the + timestamp of the signature will be returned as an aware + :class:`datetime.datetime` object in UTC. + + .. versionchanged:: 2.0 + The timestamp is returned as a timezone-aware ``datetime`` + in UTC rather than a naive ``datetime`` assumed to be UTC. + """ + try: + result = super().unsign(signed_value) + sig_error = None + except BadSignature as e: + sig_error = e + result = e.payload or b"" + + sep = want_bytes(self.sep) + + # If there is no timestamp in the result there is something + # seriously wrong. In case there was a signature error, we raise + # that one directly, otherwise we have a weird situation in + # which we shouldn't have come except someone uses a time-based + # serializer on non-timestamp data, so catch that. + if sep not in result: + if sig_error: + raise sig_error + + raise BadTimeSignature("timestamp missing", payload=result) + + value, ts_bytes = result.rsplit(sep, 1) + ts_int: _t_opt_int = None + ts_dt: _t.Optional[datetime] = None + + try: + ts_int = bytes_to_int(base64_decode(ts_bytes)) + except Exception: + pass + + # Signature is *not* okay. Raise a proper error now that we have + # split the value and the timestamp. + if sig_error is not None: + if ts_int is not None: + ts_dt = self.timestamp_to_datetime(ts_int) + + raise BadTimeSignature(str(sig_error), payload=value, date_signed=ts_dt) + + # Signature was okay but the timestamp is actually not there or + # malformed. Should not happen, but we handle it anyway. + if ts_int is None: + raise BadTimeSignature("Malformed timestamp", payload=value) + + # Check timestamp is not older than max_age + if max_age is not None: + age = self.get_timestamp() - ts_int + + if age > max_age: + raise SignatureExpired( + f"Signature age {age} > {max_age} seconds", + payload=value, + date_signed=self.timestamp_to_datetime(ts_int), + ) + + if age < 0: + raise SignatureExpired( + f"Signature age {age} < 0 seconds", + payload=value, + date_signed=self.timestamp_to_datetime(ts_int), + ) + + if return_timestamp: + return value, self.timestamp_to_datetime(ts_int) + + return value + + def validate(self, signed_value: _t_str_bytes, max_age: _t_opt_int = None) -> bool: + """Only validates the given signed value. Returns ``True`` if + the signature exists and is valid.""" + try: + self.unsign(signed_value, max_age=max_age) + return True + except BadSignature: + return False + + +class TimedSerializer(Serializer): + """Uses :class:`TimestampSigner` instead of the default + :class:`.Signer`. + """ + + default_signer: _t.Type[TimestampSigner] = TimestampSigner + + def iter_unsigners( + self, salt: _t_opt_str_bytes = None + ) -> _t.Iterator[TimestampSigner]: + return _t.cast("_t.Iterator[TimestampSigner]", super().iter_unsigners(salt)) + + # TODO: Signature is incompatible because parameters were added + # before salt. + + def loads( # type: ignore + self, + s: _t_str_bytes, + max_age: _t_opt_int = None, + return_timestamp: bool = False, + salt: _t_opt_str_bytes = None, + ) -> _t.Any: + """Reverse of :meth:`dumps`, raises :exc:`.BadSignature` if the + signature validation fails. If a ``max_age`` is provided it will + ensure the signature is not older than that time in seconds. In + case the signature is outdated, :exc:`.SignatureExpired` is + raised. All arguments are forwarded to the signer's + :meth:`~TimestampSigner.unsign` method. + """ + s = want_bytes(s) + last_exception = None + + for signer in self.iter_unsigners(salt): + try: + base64d, timestamp = signer.unsign( + s, max_age=max_age, return_timestamp=True + ) + payload = self.load_payload(base64d) + + if return_timestamp: + return payload, timestamp + + return payload + except SignatureExpired: + # The signature was unsigned successfully but was + # expired. Do not try the next signer. + raise + except BadSignature as err: + last_exception = err + + raise _t.cast(BadSignature, last_exception) + + def loads_unsafe( # type: ignore + self, + s: _t_str_bytes, + max_age: _t_opt_int = None, + salt: _t_opt_str_bytes = None, + ) -> _t.Tuple[bool, _t.Any]: + return self._loads_unsafe_impl(s, salt, load_kwargs={"max_age": max_age}) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/itsdangerous/url_safe.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/itsdangerous/url_safe.py new file mode 100644 index 000000000..f76fa24f7 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/itsdangerous/url_safe.py @@ -0,0 +1,80 @@ +import typing as _t +import zlib + +from ._json import _CompactJSON +from .encoding import base64_decode +from .encoding import base64_encode +from .exc import BadPayload +from .serializer import Serializer +from .timed import TimedSerializer + + +class URLSafeSerializerMixin(Serializer): + """Mixed in with a regular serializer it will attempt to zlib + compress the string to make it shorter if necessary. It will also + base64 encode the string so that it can safely be placed in a URL. + """ + + default_serializer = _CompactJSON + + def load_payload( + self, + payload: bytes, + *args: _t.Any, + serializer: _t.Optional[_t.Any] = None, + **kwargs: _t.Any, + ) -> _t.Any: + decompress = False + + if payload.startswith(b"."): + payload = payload[1:] + decompress = True + + try: + json = base64_decode(payload) + except Exception as e: + raise BadPayload( + "Could not base64 decode the payload because of an exception", + original_error=e, + ) + + if decompress: + try: + json = zlib.decompress(json) + except Exception as e: + raise BadPayload( + "Could not zlib decompress the payload before decoding the payload", + original_error=e, + ) + + return super().load_payload(json, *args, **kwargs) + + def dump_payload(self, obj: _t.Any) -> bytes: + json = super().dump_payload(obj) + is_compressed = False + compressed = zlib.compress(json) + + if len(compressed) < (len(json) - 1): + json = compressed + is_compressed = True + + base64d = base64_encode(json) + + if is_compressed: + base64d = b"." + base64d + + return base64d + + +class URLSafeSerializer(URLSafeSerializerMixin, Serializer): + """Works like :class:`.Serializer` but dumps and loads into a URL + safe string consisting of the upper and lowercase character of the + alphabet as well as ``'_'``, ``'-'`` and ``'.'``. + """ + + +class URLSafeTimedSerializer(URLSafeSerializerMixin, TimedSerializer): + """Works like :class:`.TimedSerializer` but dumps and loads into a + URL safe string consisting of the upper and lowercase character of + the alphabet as well as ``'_'``, ``'-'`` and ``'.'``. + """ diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/jinja2-3.1.6.dist-info/INSTALLER b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/jinja2-3.1.6.dist-info/INSTALLER new file mode 100644 index 000000000..a1b589e38 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/jinja2-3.1.6.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/jinja2-3.1.6.dist-info/METADATA b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/jinja2-3.1.6.dist-info/METADATA new file mode 100644 index 000000000..ffef2ff3b --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/jinja2-3.1.6.dist-info/METADATA @@ -0,0 +1,84 @@ +Metadata-Version: 2.4 +Name: Jinja2 +Version: 3.1.6 +Summary: A very fast and expressive template engine. +Maintainer-email: Pallets +Requires-Python: >=3.7 +Description-Content-Type: text/markdown +Classifier: Development Status :: 5 - Production/Stable +Classifier: Environment :: Web Environment +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: BSD License +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: Python +Classifier: Topic :: Internet :: WWW/HTTP :: Dynamic Content +Classifier: Topic :: Text Processing :: Markup :: HTML +Classifier: Typing :: Typed +License-File: LICENSE.txt +Requires-Dist: MarkupSafe>=2.0 +Requires-Dist: Babel>=2.7 ; extra == "i18n" +Project-URL: Changes, https://jinja.palletsprojects.com/changes/ +Project-URL: Chat, https://discord.gg/pallets +Project-URL: Documentation, https://jinja.palletsprojects.com/ +Project-URL: Donate, https://palletsprojects.com/donate +Project-URL: Source, https://github.com/pallets/jinja/ +Provides-Extra: i18n + +# Jinja + +Jinja is a fast, expressive, extensible templating engine. Special +placeholders in the template allow writing code similar to Python +syntax. Then the template is passed data to render the final document. + +It includes: + +- Template inheritance and inclusion. +- Define and import macros within templates. +- HTML templates can use autoescaping to prevent XSS from untrusted + user input. +- A sandboxed environment can safely render untrusted templates. +- AsyncIO support for generating templates and calling async + functions. +- I18N support with Babel. +- Templates are compiled to optimized Python code just-in-time and + cached, or can be compiled ahead-of-time. +- Exceptions point to the correct line in templates to make debugging + easier. +- Extensible filters, tests, functions, and even syntax. + +Jinja's philosophy is that while application logic belongs in Python if +possible, it shouldn't make the template designer's job difficult by +restricting functionality too much. + + +## In A Nutshell + +```jinja +{% extends "base.html" %} +{% block title %}Members{% endblock %} +{% block content %} + +{% endblock %} +``` + +## Donate + +The Pallets organization develops and supports Jinja and other popular +packages. In order to grow the community of contributors and users, and +allow the maintainers to devote more time to the projects, [please +donate today][]. + +[please donate today]: https://palletsprojects.com/donate + +## Contributing + +See our [detailed contributing documentation][contrib] for many ways to +contribute, including reporting issues, requesting features, asking or answering +questions, and making PRs. + +[contrib]: https://palletsprojects.com/contributing/ + diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/jinja2-3.1.6.dist-info/RECORD b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/jinja2-3.1.6.dist-info/RECORD new file mode 100644 index 000000000..ffa3866a4 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/jinja2-3.1.6.dist-info/RECORD @@ -0,0 +1,57 @@ +jinja2-3.1.6.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +jinja2-3.1.6.dist-info/METADATA,sha256=aMVUj7Z8QTKhOJjZsx7FDGvqKr3ZFdkh8hQ1XDpkmcg,2871 +jinja2-3.1.6.dist-info/RECORD,, +jinja2-3.1.6.dist-info/WHEEL,sha256=_2ozNFCLWc93bK4WKHCO-eDUENDlo-dgc9cU3qokYO4,82 +jinja2-3.1.6.dist-info/entry_points.txt,sha256=OL85gYU1eD8cuPlikifFngXpeBjaxl6rIJ8KkC_3r-I,58 +jinja2-3.1.6.dist-info/licenses/LICENSE.txt,sha256=O0nc7kEF6ze6wQ-vG-JgQI_oXSUrjp3y4JefweCUQ3s,1475 +jinja2/__init__.py,sha256=xxepO9i7DHsqkQrgBEduLtfoz2QCuT6_gbL4XSN1hbU,1928 +jinja2/__pycache__/__init__.cpython-312.pyc,, +jinja2/__pycache__/_identifier.cpython-312.pyc,, +jinja2/__pycache__/async_utils.cpython-312.pyc,, +jinja2/__pycache__/bccache.cpython-312.pyc,, +jinja2/__pycache__/compiler.cpython-312.pyc,, +jinja2/__pycache__/constants.cpython-312.pyc,, +jinja2/__pycache__/debug.cpython-312.pyc,, +jinja2/__pycache__/defaults.cpython-312.pyc,, +jinja2/__pycache__/environment.cpython-312.pyc,, +jinja2/__pycache__/exceptions.cpython-312.pyc,, +jinja2/__pycache__/ext.cpython-312.pyc,, +jinja2/__pycache__/filters.cpython-312.pyc,, +jinja2/__pycache__/idtracking.cpython-312.pyc,, +jinja2/__pycache__/lexer.cpython-312.pyc,, +jinja2/__pycache__/loaders.cpython-312.pyc,, +jinja2/__pycache__/meta.cpython-312.pyc,, +jinja2/__pycache__/nativetypes.cpython-312.pyc,, +jinja2/__pycache__/nodes.cpython-312.pyc,, +jinja2/__pycache__/optimizer.cpython-312.pyc,, +jinja2/__pycache__/parser.cpython-312.pyc,, +jinja2/__pycache__/runtime.cpython-312.pyc,, +jinja2/__pycache__/sandbox.cpython-312.pyc,, +jinja2/__pycache__/tests.cpython-312.pyc,, +jinja2/__pycache__/utils.cpython-312.pyc,, +jinja2/__pycache__/visitor.cpython-312.pyc,, +jinja2/_identifier.py,sha256=_zYctNKzRqlk_murTNlzrju1FFJL7Va_Ijqqd7ii2lU,1958 +jinja2/async_utils.py,sha256=vK-PdsuorOMnWSnEkT3iUJRIkTnYgO2T6MnGxDgHI5o,2834 +jinja2/bccache.py,sha256=gh0qs9rulnXo0PhX5jTJy2UHzI8wFnQ63o_vw7nhzRg,14061 +jinja2/compiler.py,sha256=9RpCQl5X88BHllJiPsHPh295Hh0uApvwFJNQuutULeM,74131 +jinja2/constants.py,sha256=GMoFydBF_kdpaRKPoM5cl5MviquVRLVyZtfp5-16jg0,1433 +jinja2/debug.py,sha256=CnHqCDHd-BVGvti_8ZsTolnXNhA3ECsY-6n_2pwU8Hw,6297 +jinja2/defaults.py,sha256=boBcSw78h-lp20YbaXSJsqkAI2uN_mD_TtCydpeq5wU,1267 +jinja2/environment.py,sha256=9nhrP7Ch-NbGX00wvyr4yy-uhNHq2OCc60ggGrni_fk,61513 +jinja2/exceptions.py,sha256=ioHeHrWwCWNaXX1inHmHVblvc4haO7AXsjCp3GfWvx0,5071 +jinja2/ext.py,sha256=5PF5eHfh8mXAIxXHHRB2xXbXohi8pE3nHSOxa66uS7E,31875 +jinja2/filters.py,sha256=PQ_Egd9n9jSgtnGQYyF4K5j2nYwhUIulhPnyimkdr-k,55212 +jinja2/idtracking.py,sha256=-ll5lIp73pML3ErUYiIJj7tdmWxcH_IlDv3yA_hiZYo,10555 +jinja2/lexer.py,sha256=LYiYio6br-Tep9nPcupWXsPEtjluw3p1mU-lNBVRUfk,29786 +jinja2/loaders.py,sha256=wIrnxjvcbqh5VwW28NSkfotiDq8qNCxIOSFbGUiSLB4,24055 +jinja2/meta.py,sha256=OTDPkaFvU2Hgvx-6akz7154F8BIWaRmvJcBFvwopHww,4397 +jinja2/nativetypes.py,sha256=7GIGALVJgdyL80oZJdQUaUfwSt5q2lSSZbXt0dNf_M4,4210 +jinja2/nodes.py,sha256=m1Duzcr6qhZI8JQ6VyJgUNinjAf5bQzijSmDnMsvUx8,34579 +jinja2/optimizer.py,sha256=rJnCRlQ7pZsEEmMhsQDgC_pKyDHxP5TPS6zVPGsgcu8,1651 +jinja2/parser.py,sha256=lLOFy3sEmHc5IaEHRiH1sQVnId2moUQzhyeJZTtdY30,40383 +jinja2/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +jinja2/runtime.py,sha256=gDk-GvdriJXqgsGbHgrcKTP0Yp6zPXzhzrIpCFH3jAU,34249 +jinja2/sandbox.py,sha256=Mw2aitlY2I8la7FYhcX2YG9BtUYcLnD0Gh3d29cDWrY,15009 +jinja2/tests.py,sha256=VLsBhVFnWg-PxSBz1MhRnNWgP1ovXk3neO1FLQMeC9Q,5926 +jinja2/utils.py,sha256=rRp3o9e7ZKS4fyrWRbELyLcpuGVTFcnooaOa1qx_FIk,24129 +jinja2/visitor.py,sha256=EcnL1PIwf_4RVCOMxsRNuR8AXHbS1qfAdMOE2ngKJz4,3557 diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/jinja2-3.1.6.dist-info/WHEEL b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/jinja2-3.1.6.dist-info/WHEEL new file mode 100644 index 000000000..23d2d7e9a --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/jinja2-3.1.6.dist-info/WHEEL @@ -0,0 +1,4 @@ +Wheel-Version: 1.0 +Generator: flit 3.11.0 +Root-Is-Purelib: true +Tag: py3-none-any diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/jinja2-3.1.6.dist-info/entry_points.txt b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/jinja2-3.1.6.dist-info/entry_points.txt new file mode 100644 index 000000000..abc3eae3b --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/jinja2-3.1.6.dist-info/entry_points.txt @@ -0,0 +1,3 @@ +[babel.extractors] +jinja2=jinja2.ext:babel_extract[i18n] + diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/jinja2-3.1.6.dist-info/licenses/LICENSE.txt b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/jinja2-3.1.6.dist-info/licenses/LICENSE.txt new file mode 100644 index 000000000..c37cae49e --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/jinja2-3.1.6.dist-info/licenses/LICENSE.txt @@ -0,0 +1,28 @@ +Copyright 2007 Pallets + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A +PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED +TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/jinja2/__init__.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/jinja2/__init__.py new file mode 100644 index 000000000..1a423a3ea --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/jinja2/__init__.py @@ -0,0 +1,38 @@ +"""Jinja is a template engine written in pure Python. It provides a +non-XML syntax that supports inline expressions and an optional +sandboxed environment. +""" + +from .bccache import BytecodeCache as BytecodeCache +from .bccache import FileSystemBytecodeCache as FileSystemBytecodeCache +from .bccache import MemcachedBytecodeCache as MemcachedBytecodeCache +from .environment import Environment as Environment +from .environment import Template as Template +from .exceptions import TemplateAssertionError as TemplateAssertionError +from .exceptions import TemplateError as TemplateError +from .exceptions import TemplateNotFound as TemplateNotFound +from .exceptions import TemplateRuntimeError as TemplateRuntimeError +from .exceptions import TemplatesNotFound as TemplatesNotFound +from .exceptions import TemplateSyntaxError as TemplateSyntaxError +from .exceptions import UndefinedError as UndefinedError +from .loaders import BaseLoader as BaseLoader +from .loaders import ChoiceLoader as ChoiceLoader +from .loaders import DictLoader as DictLoader +from .loaders import FileSystemLoader as FileSystemLoader +from .loaders import FunctionLoader as FunctionLoader +from .loaders import ModuleLoader as ModuleLoader +from .loaders import PackageLoader as PackageLoader +from .loaders import PrefixLoader as PrefixLoader +from .runtime import ChainableUndefined as ChainableUndefined +from .runtime import DebugUndefined as DebugUndefined +from .runtime import make_logging_undefined as make_logging_undefined +from .runtime import StrictUndefined as StrictUndefined +from .runtime import Undefined as Undefined +from .utils import clear_caches as clear_caches +from .utils import is_undefined as is_undefined +from .utils import pass_context as pass_context +from .utils import pass_environment as pass_environment +from .utils import pass_eval_context as pass_eval_context +from .utils import select_autoescape as select_autoescape + +__version__ = "3.1.6" diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/jinja2/_identifier.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/jinja2/_identifier.py new file mode 100644 index 000000000..928c1503c --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/jinja2/_identifier.py @@ -0,0 +1,6 @@ +import re + +# generated by scripts/generate_identifier_pattern.py +pattern = re.compile( + r"[\w·̀-ͯ·҃-֑҇-ׇֽֿׁׂׅׄؐ-ًؚ-ٰٟۖ-ۜ۟-۪ۤۧۨ-ܑۭܰ-݊ަ-ް߫-߽߳ࠖ-࠙ࠛ-ࠣࠥ-ࠧࠩ-࡙࠭-࡛࣓-ࣣ࣡-ःऺ-़ा-ॏ॑-ॗॢॣঁ-ঃ়া-ৄেৈো-্ৗৢৣ৾ਁ-ਃ਼ਾ-ੂੇੈੋ-੍ੑੰੱੵઁ-ઃ઼ા-ૅે-ૉો-્ૢૣૺ-૿ଁ-ଃ଼ା-ୄେୈୋ-୍ୖୗୢୣஂா-ூெ-ைொ-்ௗఀ-ఄా-ౄె-ైొ-్ౕౖౢౣಁ-ಃ಼ಾ-ೄೆ-ೈೊ-್ೕೖೢೣഀ-ഃ഻഼ാ-ൄെ-ൈൊ-്ൗൢൣංඃ්ා-ුූෘ-ෟෲෳัิ-ฺ็-๎ັິ-ູົຼ່-ໍ༹༘༙༵༷༾༿ཱ-྄྆྇ྍ-ྗྙ-ྼ࿆ါ-ှၖ-ၙၞ-ၠၢ-ၤၧ-ၭၱ-ၴႂ-ႍႏႚ-ႝ፝-፟ᜒ-᜔ᜲ-᜴ᝒᝓᝲᝳ឴-៓៝᠋-᠍ᢅᢆᢩᤠ-ᤫᤰ-᤻ᨗ-ᨛᩕ-ᩞ᩠-᩿᩼᪰-᪽ᬀ-ᬄ᬴-᭄᭫-᭳ᮀ-ᮂᮡ-ᮭ᯦-᯳ᰤ-᰷᳐-᳔᳒-᳨᳭ᳲ-᳴᳷-᳹᷀-᷹᷻-᷿‿⁀⁔⃐-⃥⃜⃡-⃰℘℮⳯-⵿⳱ⷠ-〪ⷿ-゙゚〯꙯ꙴ-꙽ꚞꚟ꛰꛱ꠂ꠆ꠋꠣ-ꠧꢀꢁꢴ-ꣅ꣠-꣱ꣿꤦ-꤭ꥇ-꥓ꦀ-ꦃ꦳-꧀ꧥꨩ-ꨶꩃꩌꩍꩻ-ꩽꪰꪲ-ꪴꪷꪸꪾ꪿꫁ꫫ-ꫯꫵ꫶ꯣ-ꯪ꯬꯭ﬞ︀-️︠-︯︳︴﹍-﹏_𐇽𐋠𐍶-𐍺𐨁-𐨃𐨅𐨆𐨌-𐨏𐨸-𐨿𐨺𐫦𐫥𐴤-𐽆𐴧-𐽐𑀀-𑀂𑀸-𑁆𑁿-𑂂𑂰-𑂺𑄀-𑄂𑄧-𑄴𑅅𑅆𑅳𑆀-𑆂𑆳-𑇀𑇉-𑇌𑈬-𑈷𑈾𑋟-𑋪𑌀-𑌃𑌻𑌼𑌾-𑍄𑍇𑍈𑍋-𑍍𑍗𑍢𑍣𑍦-𑍬𑍰-𑍴𑐵-𑑆𑑞𑒰-𑓃𑖯-𑖵𑖸-𑗀𑗜𑗝𑘰-𑙀𑚫-𑚷𑜝-𑜫𑠬-𑠺𑨁-𑨊𑨳-𑨹𑨻-𑨾𑩇𑩑-𑩛𑪊-𑪙𑰯-𑰶𑰸-𑰿𑲒-𑲧𑲩-𑲶𑴱-𑴶𑴺𑴼𑴽𑴿-𑵅𑵇𑶊-𑶎𑶐𑶑𑶓-𑶗𑻳-𑻶𖫰-𖫴𖬰-𖬶𖽑-𖽾𖾏-𖾒𛲝𛲞𝅥-𝅩𝅭-𝅲𝅻-𝆂𝆅-𝆋𝆪-𝆭𝉂-𝉄𝨀-𝨶𝨻-𝩬𝩵𝪄𝪛-𝪟𝪡-𝪯𞀀-𞀆𞀈-𞀘𞀛-𞀡𞀣𞀤𞀦-𞣐𞀪-𞣖𞥄-𞥊󠄀-󠇯]+" # noqa: B950 +) diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/jinja2/async_utils.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/jinja2/async_utils.py new file mode 100644 index 000000000..f0c140205 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/jinja2/async_utils.py @@ -0,0 +1,99 @@ +import inspect +import typing as t +from functools import WRAPPER_ASSIGNMENTS +from functools import wraps + +from .utils import _PassArg +from .utils import pass_eval_context + +if t.TYPE_CHECKING: + import typing_extensions as te + +V = t.TypeVar("V") + + +def async_variant(normal_func): # type: ignore + def decorator(async_func): # type: ignore + pass_arg = _PassArg.from_obj(normal_func) + need_eval_context = pass_arg is None + + if pass_arg is _PassArg.environment: + + def is_async(args: t.Any) -> bool: + return t.cast(bool, args[0].is_async) + + else: + + def is_async(args: t.Any) -> bool: + return t.cast(bool, args[0].environment.is_async) + + # Take the doc and annotations from the sync function, but the + # name from the async function. Pallets-Sphinx-Themes + # build_function_directive expects __wrapped__ to point to the + # sync function. + async_func_attrs = ("__module__", "__name__", "__qualname__") + normal_func_attrs = tuple(set(WRAPPER_ASSIGNMENTS).difference(async_func_attrs)) + + @wraps(normal_func, assigned=normal_func_attrs) + @wraps(async_func, assigned=async_func_attrs, updated=()) + def wrapper(*args, **kwargs): # type: ignore + b = is_async(args) + + if need_eval_context: + args = args[1:] + + if b: + return async_func(*args, **kwargs) + + return normal_func(*args, **kwargs) + + if need_eval_context: + wrapper = pass_eval_context(wrapper) + + wrapper.jinja_async_variant = True # type: ignore[attr-defined] + return wrapper + + return decorator + + +_common_primitives = {int, float, bool, str, list, dict, tuple, type(None)} + + +async def auto_await(value: t.Union[t.Awaitable["V"], "V"]) -> "V": + # Avoid a costly call to isawaitable + if type(value) in _common_primitives: + return t.cast("V", value) + + if inspect.isawaitable(value): + return await t.cast("t.Awaitable[V]", value) + + return value + + +class _IteratorToAsyncIterator(t.Generic[V]): + def __init__(self, iterator: "t.Iterator[V]"): + self._iterator = iterator + + def __aiter__(self) -> "te.Self": + return self + + async def __anext__(self) -> V: + try: + return next(self._iterator) + except StopIteration as e: + raise StopAsyncIteration(e.value) from e + + +def auto_aiter( + iterable: "t.Union[t.AsyncIterable[V], t.Iterable[V]]", +) -> "t.AsyncIterator[V]": + if hasattr(iterable, "__aiter__"): + return iterable.__aiter__() + else: + return _IteratorToAsyncIterator(iter(iterable)) + + +async def auto_to_list( + value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]", +) -> t.List["V"]: + return [x async for x in auto_aiter(value)] diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/jinja2/bccache.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/jinja2/bccache.py new file mode 100644 index 000000000..ada8b099f --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/jinja2/bccache.py @@ -0,0 +1,408 @@ +"""The optional bytecode cache system. This is useful if you have very +complex template situations and the compilation of all those templates +slows down your application too much. + +Situations where this is useful are often forking web applications that +are initialized on the first request. +""" + +import errno +import fnmatch +import marshal +import os +import pickle +import stat +import sys +import tempfile +import typing as t +from hashlib import sha1 +from io import BytesIO +from types import CodeType + +if t.TYPE_CHECKING: + import typing_extensions as te + + from .environment import Environment + + class _MemcachedClient(te.Protocol): + def get(self, key: str) -> bytes: ... + + def set( + self, key: str, value: bytes, timeout: t.Optional[int] = None + ) -> None: ... + + +bc_version = 5 +# Magic bytes to identify Jinja bytecode cache files. Contains the +# Python major and minor version to avoid loading incompatible bytecode +# if a project upgrades its Python version. +bc_magic = ( + b"j2" + + pickle.dumps(bc_version, 2) + + pickle.dumps((sys.version_info[0] << 24) | sys.version_info[1], 2) +) + + +class Bucket: + """Buckets are used to store the bytecode for one template. It's created + and initialized by the bytecode cache and passed to the loading functions. + + The buckets get an internal checksum from the cache assigned and use this + to automatically reject outdated cache material. Individual bytecode + cache subclasses don't have to care about cache invalidation. + """ + + def __init__(self, environment: "Environment", key: str, checksum: str) -> None: + self.environment = environment + self.key = key + self.checksum = checksum + self.reset() + + def reset(self) -> None: + """Resets the bucket (unloads the bytecode).""" + self.code: t.Optional[CodeType] = None + + def load_bytecode(self, f: t.BinaryIO) -> None: + """Loads bytecode from a file or file like object.""" + # make sure the magic header is correct + magic = f.read(len(bc_magic)) + if magic != bc_magic: + self.reset() + return + # the source code of the file changed, we need to reload + checksum = pickle.load(f) + if self.checksum != checksum: + self.reset() + return + # if marshal_load fails then we need to reload + try: + self.code = marshal.load(f) + except (EOFError, ValueError, TypeError): + self.reset() + return + + def write_bytecode(self, f: t.IO[bytes]) -> None: + """Dump the bytecode into the file or file like object passed.""" + if self.code is None: + raise TypeError("can't write empty bucket") + f.write(bc_magic) + pickle.dump(self.checksum, f, 2) + marshal.dump(self.code, f) + + def bytecode_from_string(self, string: bytes) -> None: + """Load bytecode from bytes.""" + self.load_bytecode(BytesIO(string)) + + def bytecode_to_string(self) -> bytes: + """Return the bytecode as bytes.""" + out = BytesIO() + self.write_bytecode(out) + return out.getvalue() + + +class BytecodeCache: + """To implement your own bytecode cache you have to subclass this class + and override :meth:`load_bytecode` and :meth:`dump_bytecode`. Both of + these methods are passed a :class:`~jinja2.bccache.Bucket`. + + A very basic bytecode cache that saves the bytecode on the file system:: + + from os import path + + class MyCache(BytecodeCache): + + def __init__(self, directory): + self.directory = directory + + def load_bytecode(self, bucket): + filename = path.join(self.directory, bucket.key) + if path.exists(filename): + with open(filename, 'rb') as f: + bucket.load_bytecode(f) + + def dump_bytecode(self, bucket): + filename = path.join(self.directory, bucket.key) + with open(filename, 'wb') as f: + bucket.write_bytecode(f) + + A more advanced version of a filesystem based bytecode cache is part of + Jinja. + """ + + def load_bytecode(self, bucket: Bucket) -> None: + """Subclasses have to override this method to load bytecode into a + bucket. If they are not able to find code in the cache for the + bucket, it must not do anything. + """ + raise NotImplementedError() + + def dump_bytecode(self, bucket: Bucket) -> None: + """Subclasses have to override this method to write the bytecode + from a bucket back to the cache. If it unable to do so it must not + fail silently but raise an exception. + """ + raise NotImplementedError() + + def clear(self) -> None: + """Clears the cache. This method is not used by Jinja but should be + implemented to allow applications to clear the bytecode cache used + by a particular environment. + """ + + def get_cache_key( + self, name: str, filename: t.Optional[t.Union[str]] = None + ) -> str: + """Returns the unique hash key for this template name.""" + hash = sha1(name.encode("utf-8")) + + if filename is not None: + hash.update(f"|{filename}".encode()) + + return hash.hexdigest() + + def get_source_checksum(self, source: str) -> str: + """Returns a checksum for the source.""" + return sha1(source.encode("utf-8")).hexdigest() + + def get_bucket( + self, + environment: "Environment", + name: str, + filename: t.Optional[str], + source: str, + ) -> Bucket: + """Return a cache bucket for the given template. All arguments are + mandatory but filename may be `None`. + """ + key = self.get_cache_key(name, filename) + checksum = self.get_source_checksum(source) + bucket = Bucket(environment, key, checksum) + self.load_bytecode(bucket) + return bucket + + def set_bucket(self, bucket: Bucket) -> None: + """Put the bucket into the cache.""" + self.dump_bytecode(bucket) + + +class FileSystemBytecodeCache(BytecodeCache): + """A bytecode cache that stores bytecode on the filesystem. It accepts + two arguments: The directory where the cache items are stored and a + pattern string that is used to build the filename. + + If no directory is specified a default cache directory is selected. On + Windows the user's temp directory is used, on UNIX systems a directory + is created for the user in the system temp directory. + + The pattern can be used to have multiple separate caches operate on the + same directory. The default pattern is ``'__jinja2_%s.cache'``. ``%s`` + is replaced with the cache key. + + >>> bcc = FileSystemBytecodeCache('/tmp/jinja_cache', '%s.cache') + + This bytecode cache supports clearing of the cache using the clear method. + """ + + def __init__( + self, directory: t.Optional[str] = None, pattern: str = "__jinja2_%s.cache" + ) -> None: + if directory is None: + directory = self._get_default_cache_dir() + self.directory = directory + self.pattern = pattern + + def _get_default_cache_dir(self) -> str: + def _unsafe_dir() -> "te.NoReturn": + raise RuntimeError( + "Cannot determine safe temp directory. You " + "need to explicitly provide one." + ) + + tmpdir = tempfile.gettempdir() + + # On windows the temporary directory is used specific unless + # explicitly forced otherwise. We can just use that. + if os.name == "nt": + return tmpdir + if not hasattr(os, "getuid"): + _unsafe_dir() + + dirname = f"_jinja2-cache-{os.getuid()}" + actual_dir = os.path.join(tmpdir, dirname) + + try: + os.mkdir(actual_dir, stat.S_IRWXU) + except OSError as e: + if e.errno != errno.EEXIST: + raise + try: + os.chmod(actual_dir, stat.S_IRWXU) + actual_dir_stat = os.lstat(actual_dir) + if ( + actual_dir_stat.st_uid != os.getuid() + or not stat.S_ISDIR(actual_dir_stat.st_mode) + or stat.S_IMODE(actual_dir_stat.st_mode) != stat.S_IRWXU + ): + _unsafe_dir() + except OSError as e: + if e.errno != errno.EEXIST: + raise + + actual_dir_stat = os.lstat(actual_dir) + if ( + actual_dir_stat.st_uid != os.getuid() + or not stat.S_ISDIR(actual_dir_stat.st_mode) + or stat.S_IMODE(actual_dir_stat.st_mode) != stat.S_IRWXU + ): + _unsafe_dir() + + return actual_dir + + def _get_cache_filename(self, bucket: Bucket) -> str: + return os.path.join(self.directory, self.pattern % (bucket.key,)) + + def load_bytecode(self, bucket: Bucket) -> None: + filename = self._get_cache_filename(bucket) + + # Don't test for existence before opening the file, since the + # file could disappear after the test before the open. + try: + f = open(filename, "rb") + except (FileNotFoundError, IsADirectoryError, PermissionError): + # PermissionError can occur on Windows when an operation is + # in progress, such as calling clear(). + return + + with f: + bucket.load_bytecode(f) + + def dump_bytecode(self, bucket: Bucket) -> None: + # Write to a temporary file, then rename to the real name after + # writing. This avoids another process reading the file before + # it is fully written. + name = self._get_cache_filename(bucket) + f = tempfile.NamedTemporaryFile( + mode="wb", + dir=os.path.dirname(name), + prefix=os.path.basename(name), + suffix=".tmp", + delete=False, + ) + + def remove_silent() -> None: + try: + os.remove(f.name) + except OSError: + # Another process may have called clear(). On Windows, + # another program may be holding the file open. + pass + + try: + with f: + bucket.write_bytecode(f) + except BaseException: + remove_silent() + raise + + try: + os.replace(f.name, name) + except OSError: + # Another process may have called clear(). On Windows, + # another program may be holding the file open. + remove_silent() + except BaseException: + remove_silent() + raise + + def clear(self) -> None: + # imported lazily here because google app-engine doesn't support + # write access on the file system and the function does not exist + # normally. + from os import remove + + files = fnmatch.filter(os.listdir(self.directory), self.pattern % ("*",)) + for filename in files: + try: + remove(os.path.join(self.directory, filename)) + except OSError: + pass + + +class MemcachedBytecodeCache(BytecodeCache): + """This class implements a bytecode cache that uses a memcache cache for + storing the information. It does not enforce a specific memcache library + (tummy's memcache or cmemcache) but will accept any class that provides + the minimal interface required. + + Libraries compatible with this class: + + - `cachelib `_ + - `python-memcached `_ + + (Unfortunately the django cache interface is not compatible because it + does not support storing binary data, only text. You can however pass + the underlying cache client to the bytecode cache which is available + as `django.core.cache.cache._client`.) + + The minimal interface for the client passed to the constructor is this: + + .. class:: MinimalClientInterface + + .. method:: set(key, value[, timeout]) + + Stores the bytecode in the cache. `value` is a string and + `timeout` the timeout of the key. If timeout is not provided + a default timeout or no timeout should be assumed, if it's + provided it's an integer with the number of seconds the cache + item should exist. + + .. method:: get(key) + + Returns the value for the cache key. If the item does not + exist in the cache the return value must be `None`. + + The other arguments to the constructor are the prefix for all keys that + is added before the actual cache key and the timeout for the bytecode in + the cache system. We recommend a high (or no) timeout. + + This bytecode cache does not support clearing of used items in the cache. + The clear method is a no-operation function. + + .. versionadded:: 2.7 + Added support for ignoring memcache errors through the + `ignore_memcache_errors` parameter. + """ + + def __init__( + self, + client: "_MemcachedClient", + prefix: str = "jinja2/bytecode/", + timeout: t.Optional[int] = None, + ignore_memcache_errors: bool = True, + ): + self.client = client + self.prefix = prefix + self.timeout = timeout + self.ignore_memcache_errors = ignore_memcache_errors + + def load_bytecode(self, bucket: Bucket) -> None: + try: + code = self.client.get(self.prefix + bucket.key) + except Exception: + if not self.ignore_memcache_errors: + raise + else: + bucket.bytecode_from_string(code) + + def dump_bytecode(self, bucket: Bucket) -> None: + key = self.prefix + bucket.key + value = bucket.bytecode_to_string() + + try: + if self.timeout is not None: + self.client.set(key, value, self.timeout) + else: + self.client.set(key, value) + except Exception: + if not self.ignore_memcache_errors: + raise diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/jinja2/compiler.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/jinja2/compiler.py new file mode 100644 index 000000000..a4ff6a1b1 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/jinja2/compiler.py @@ -0,0 +1,1998 @@ +"""Compiles nodes from the parser into Python code.""" + +import typing as t +from contextlib import contextmanager +from functools import update_wrapper +from io import StringIO +from itertools import chain +from keyword import iskeyword as is_python_keyword + +from markupsafe import escape +from markupsafe import Markup + +from . import nodes +from .exceptions import TemplateAssertionError +from .idtracking import Symbols +from .idtracking import VAR_LOAD_ALIAS +from .idtracking import VAR_LOAD_PARAMETER +from .idtracking import VAR_LOAD_RESOLVE +from .idtracking import VAR_LOAD_UNDEFINED +from .nodes import EvalContext +from .optimizer import Optimizer +from .utils import _PassArg +from .utils import concat +from .visitor import NodeVisitor + +if t.TYPE_CHECKING: + import typing_extensions as te + + from .environment import Environment + +F = t.TypeVar("F", bound=t.Callable[..., t.Any]) + +operators = { + "eq": "==", + "ne": "!=", + "gt": ">", + "gteq": ">=", + "lt": "<", + "lteq": "<=", + "in": "in", + "notin": "not in", +} + + +def optimizeconst(f: F) -> F: + def new_func( + self: "CodeGenerator", node: nodes.Expr, frame: "Frame", **kwargs: t.Any + ) -> t.Any: + # Only optimize if the frame is not volatile + if self.optimizer is not None and not frame.eval_ctx.volatile: + new_node = self.optimizer.visit(node, frame.eval_ctx) + + if new_node != node: + return self.visit(new_node, frame) + + return f(self, node, frame, **kwargs) + + return update_wrapper(new_func, f) # type: ignore[return-value] + + +def _make_binop(op: str) -> t.Callable[["CodeGenerator", nodes.BinExpr, "Frame"], None]: + @optimizeconst + def visitor(self: "CodeGenerator", node: nodes.BinExpr, frame: Frame) -> None: + if ( + self.environment.sandboxed and op in self.environment.intercepted_binops # type: ignore + ): + self.write(f"environment.call_binop(context, {op!r}, ") + self.visit(node.left, frame) + self.write(", ") + self.visit(node.right, frame) + else: + self.write("(") + self.visit(node.left, frame) + self.write(f" {op} ") + self.visit(node.right, frame) + + self.write(")") + + return visitor + + +def _make_unop( + op: str, +) -> t.Callable[["CodeGenerator", nodes.UnaryExpr, "Frame"], None]: + @optimizeconst + def visitor(self: "CodeGenerator", node: nodes.UnaryExpr, frame: Frame) -> None: + if ( + self.environment.sandboxed and op in self.environment.intercepted_unops # type: ignore + ): + self.write(f"environment.call_unop(context, {op!r}, ") + self.visit(node.node, frame) + else: + self.write("(" + op) + self.visit(node.node, frame) + + self.write(")") + + return visitor + + +def generate( + node: nodes.Template, + environment: "Environment", + name: t.Optional[str], + filename: t.Optional[str], + stream: t.Optional[t.TextIO] = None, + defer_init: bool = False, + optimized: bool = True, +) -> t.Optional[str]: + """Generate the python source for a node tree.""" + if not isinstance(node, nodes.Template): + raise TypeError("Can't compile non template nodes") + + generator = environment.code_generator_class( + environment, name, filename, stream, defer_init, optimized + ) + generator.visit(node) + + if stream is None: + return generator.stream.getvalue() # type: ignore + + return None + + +def has_safe_repr(value: t.Any) -> bool: + """Does the node have a safe representation?""" + if value is None or value is NotImplemented or value is Ellipsis: + return True + + if type(value) in {bool, int, float, complex, range, str, Markup}: + return True + + if type(value) in {tuple, list, set, frozenset}: + return all(has_safe_repr(v) for v in value) + + if type(value) is dict: # noqa E721 + return all(has_safe_repr(k) and has_safe_repr(v) for k, v in value.items()) + + return False + + +def find_undeclared( + nodes: t.Iterable[nodes.Node], names: t.Iterable[str] +) -> t.Set[str]: + """Check if the names passed are accessed undeclared. The return value + is a set of all the undeclared names from the sequence of names found. + """ + visitor = UndeclaredNameVisitor(names) + try: + for node in nodes: + visitor.visit(node) + except VisitorExit: + pass + return visitor.undeclared + + +class MacroRef: + def __init__(self, node: t.Union[nodes.Macro, nodes.CallBlock]) -> None: + self.node = node + self.accesses_caller = False + self.accesses_kwargs = False + self.accesses_varargs = False + + +class Frame: + """Holds compile time information for us.""" + + def __init__( + self, + eval_ctx: EvalContext, + parent: t.Optional["Frame"] = None, + level: t.Optional[int] = None, + ) -> None: + self.eval_ctx = eval_ctx + + # the parent of this frame + self.parent = parent + + if parent is None: + self.symbols = Symbols(level=level) + + # in some dynamic inheritance situations the compiler needs to add + # write tests around output statements. + self.require_output_check = False + + # inside some tags we are using a buffer rather than yield statements. + # this for example affects {% filter %} or {% macro %}. If a frame + # is buffered this variable points to the name of the list used as + # buffer. + self.buffer: t.Optional[str] = None + + # the name of the block we're in, otherwise None. + self.block: t.Optional[str] = None + + else: + self.symbols = Symbols(parent.symbols, level=level) + self.require_output_check = parent.require_output_check + self.buffer = parent.buffer + self.block = parent.block + + # a toplevel frame is the root + soft frames such as if conditions. + self.toplevel = False + + # the root frame is basically just the outermost frame, so no if + # conditions. This information is used to optimize inheritance + # situations. + self.rootlevel = False + + # variables set inside of loops and blocks should not affect outer frames, + # but they still needs to be kept track of as part of the active context. + self.loop_frame = False + self.block_frame = False + + # track whether the frame is being used in an if-statement or conditional + # expression as it determines which errors should be raised during runtime + # or compile time. + self.soft_frame = False + + def copy(self) -> "te.Self": + """Create a copy of the current one.""" + rv = object.__new__(self.__class__) + rv.__dict__.update(self.__dict__) + rv.symbols = self.symbols.copy() + return rv + + def inner(self, isolated: bool = False) -> "Frame": + """Return an inner frame.""" + if isolated: + return Frame(self.eval_ctx, level=self.symbols.level + 1) + return Frame(self.eval_ctx, self) + + def soft(self) -> "te.Self": + """Return a soft frame. A soft frame may not be modified as + standalone thing as it shares the resources with the frame it + was created of, but it's not a rootlevel frame any longer. + + This is only used to implement if-statements and conditional + expressions. + """ + rv = self.copy() + rv.rootlevel = False + rv.soft_frame = True + return rv + + __copy__ = copy + + +class VisitorExit(RuntimeError): + """Exception used by the `UndeclaredNameVisitor` to signal a stop.""" + + +class DependencyFinderVisitor(NodeVisitor): + """A visitor that collects filter and test calls.""" + + def __init__(self) -> None: + self.filters: t.Set[str] = set() + self.tests: t.Set[str] = set() + + def visit_Filter(self, node: nodes.Filter) -> None: + self.generic_visit(node) + self.filters.add(node.name) + + def visit_Test(self, node: nodes.Test) -> None: + self.generic_visit(node) + self.tests.add(node.name) + + def visit_Block(self, node: nodes.Block) -> None: + """Stop visiting at blocks.""" + + +class UndeclaredNameVisitor(NodeVisitor): + """A visitor that checks if a name is accessed without being + declared. This is different from the frame visitor as it will + not stop at closure frames. + """ + + def __init__(self, names: t.Iterable[str]) -> None: + self.names = set(names) + self.undeclared: t.Set[str] = set() + + def visit_Name(self, node: nodes.Name) -> None: + if node.ctx == "load" and node.name in self.names: + self.undeclared.add(node.name) + if self.undeclared == self.names: + raise VisitorExit() + else: + self.names.discard(node.name) + + def visit_Block(self, node: nodes.Block) -> None: + """Stop visiting a blocks.""" + + +class CompilerExit(Exception): + """Raised if the compiler encountered a situation where it just + doesn't make sense to further process the code. Any block that + raises such an exception is not further processed. + """ + + +class CodeGenerator(NodeVisitor): + def __init__( + self, + environment: "Environment", + name: t.Optional[str], + filename: t.Optional[str], + stream: t.Optional[t.TextIO] = None, + defer_init: bool = False, + optimized: bool = True, + ) -> None: + if stream is None: + stream = StringIO() + self.environment = environment + self.name = name + self.filename = filename + self.stream = stream + self.created_block_context = False + self.defer_init = defer_init + self.optimizer: t.Optional[Optimizer] = None + + if optimized: + self.optimizer = Optimizer(environment) + + # aliases for imports + self.import_aliases: t.Dict[str, str] = {} + + # a registry for all blocks. Because blocks are moved out + # into the global python scope they are registered here + self.blocks: t.Dict[str, nodes.Block] = {} + + # the number of extends statements so far + self.extends_so_far = 0 + + # some templates have a rootlevel extends. In this case we + # can safely assume that we're a child template and do some + # more optimizations. + self.has_known_extends = False + + # the current line number + self.code_lineno = 1 + + # registry of all filters and tests (global, not block local) + self.tests: t.Dict[str, str] = {} + self.filters: t.Dict[str, str] = {} + + # the debug information + self.debug_info: t.List[t.Tuple[int, int]] = [] + self._write_debug_info: t.Optional[int] = None + + # the number of new lines before the next write() + self._new_lines = 0 + + # the line number of the last written statement + self._last_line = 0 + + # true if nothing was written so far. + self._first_write = True + + # used by the `temporary_identifier` method to get new + # unique, temporary identifier + self._last_identifier = 0 + + # the current indentation + self._indentation = 0 + + # Tracks toplevel assignments + self._assign_stack: t.List[t.Set[str]] = [] + + # Tracks parameter definition blocks + self._param_def_block: t.List[t.Set[str]] = [] + + # Tracks the current context. + self._context_reference_stack = ["context"] + + @property + def optimized(self) -> bool: + return self.optimizer is not None + + # -- Various compilation helpers + + def fail(self, msg: str, lineno: int) -> "te.NoReturn": + """Fail with a :exc:`TemplateAssertionError`.""" + raise TemplateAssertionError(msg, lineno, self.name, self.filename) + + def temporary_identifier(self) -> str: + """Get a new unique identifier.""" + self._last_identifier += 1 + return f"t_{self._last_identifier}" + + def buffer(self, frame: Frame) -> None: + """Enable buffering for the frame from that point onwards.""" + frame.buffer = self.temporary_identifier() + self.writeline(f"{frame.buffer} = []") + + def return_buffer_contents( + self, frame: Frame, force_unescaped: bool = False + ) -> None: + """Return the buffer contents of the frame.""" + if not force_unescaped: + if frame.eval_ctx.volatile: + self.writeline("if context.eval_ctx.autoescape:") + self.indent() + self.writeline(f"return Markup(concat({frame.buffer}))") + self.outdent() + self.writeline("else:") + self.indent() + self.writeline(f"return concat({frame.buffer})") + self.outdent() + return + elif frame.eval_ctx.autoescape: + self.writeline(f"return Markup(concat({frame.buffer}))") + return + self.writeline(f"return concat({frame.buffer})") + + def indent(self) -> None: + """Indent by one.""" + self._indentation += 1 + + def outdent(self, step: int = 1) -> None: + """Outdent by step.""" + self._indentation -= step + + def start_write(self, frame: Frame, node: t.Optional[nodes.Node] = None) -> None: + """Yield or write into the frame buffer.""" + if frame.buffer is None: + self.writeline("yield ", node) + else: + self.writeline(f"{frame.buffer}.append(", node) + + def end_write(self, frame: Frame) -> None: + """End the writing process started by `start_write`.""" + if frame.buffer is not None: + self.write(")") + + def simple_write( + self, s: str, frame: Frame, node: t.Optional[nodes.Node] = None + ) -> None: + """Simple shortcut for start_write + write + end_write.""" + self.start_write(frame, node) + self.write(s) + self.end_write(frame) + + def blockvisit(self, nodes: t.Iterable[nodes.Node], frame: Frame) -> None: + """Visit a list of nodes as block in a frame. If the current frame + is no buffer a dummy ``if 0: yield None`` is written automatically. + """ + try: + self.writeline("pass") + for node in nodes: + self.visit(node, frame) + except CompilerExit: + pass + + def write(self, x: str) -> None: + """Write a string into the output stream.""" + if self._new_lines: + if not self._first_write: + self.stream.write("\n" * self._new_lines) + self.code_lineno += self._new_lines + if self._write_debug_info is not None: + self.debug_info.append((self._write_debug_info, self.code_lineno)) + self._write_debug_info = None + self._first_write = False + self.stream.write(" " * self._indentation) + self._new_lines = 0 + self.stream.write(x) + + def writeline( + self, x: str, node: t.Optional[nodes.Node] = None, extra: int = 0 + ) -> None: + """Combination of newline and write.""" + self.newline(node, extra) + self.write(x) + + def newline(self, node: t.Optional[nodes.Node] = None, extra: int = 0) -> None: + """Add one or more newlines before the next write.""" + self._new_lines = max(self._new_lines, 1 + extra) + if node is not None and node.lineno != self._last_line: + self._write_debug_info = node.lineno + self._last_line = node.lineno + + def signature( + self, + node: t.Union[nodes.Call, nodes.Filter, nodes.Test], + frame: Frame, + extra_kwargs: t.Optional[t.Mapping[str, t.Any]] = None, + ) -> None: + """Writes a function call to the stream for the current node. + A leading comma is added automatically. The extra keyword + arguments may not include python keywords otherwise a syntax + error could occur. The extra keyword arguments should be given + as python dict. + """ + # if any of the given keyword arguments is a python keyword + # we have to make sure that no invalid call is created. + kwarg_workaround = any( + is_python_keyword(t.cast(str, k)) + for k in chain((x.key for x in node.kwargs), extra_kwargs or ()) + ) + + for arg in node.args: + self.write(", ") + self.visit(arg, frame) + + if not kwarg_workaround: + for kwarg in node.kwargs: + self.write(", ") + self.visit(kwarg, frame) + if extra_kwargs is not None: + for key, value in extra_kwargs.items(): + self.write(f", {key}={value}") + if node.dyn_args: + self.write(", *") + self.visit(node.dyn_args, frame) + + if kwarg_workaround: + if node.dyn_kwargs is not None: + self.write(", **dict({") + else: + self.write(", **{") + for kwarg in node.kwargs: + self.write(f"{kwarg.key!r}: ") + self.visit(kwarg.value, frame) + self.write(", ") + if extra_kwargs is not None: + for key, value in extra_kwargs.items(): + self.write(f"{key!r}: {value}, ") + if node.dyn_kwargs is not None: + self.write("}, **") + self.visit(node.dyn_kwargs, frame) + self.write(")") + else: + self.write("}") + + elif node.dyn_kwargs is not None: + self.write(", **") + self.visit(node.dyn_kwargs, frame) + + def pull_dependencies(self, nodes: t.Iterable[nodes.Node]) -> None: + """Find all filter and test names used in the template and + assign them to variables in the compiled namespace. Checking + that the names are registered with the environment is done when + compiling the Filter and Test nodes. If the node is in an If or + CondExpr node, the check is done at runtime instead. + + .. versionchanged:: 3.0 + Filters and tests in If and CondExpr nodes are checked at + runtime instead of compile time. + """ + visitor = DependencyFinderVisitor() + + for node in nodes: + visitor.visit(node) + + for id_map, names, dependency in ( + (self.filters, visitor.filters, "filters"), + ( + self.tests, + visitor.tests, + "tests", + ), + ): + for name in sorted(names): + if name not in id_map: + id_map[name] = self.temporary_identifier() + + # add check during runtime that dependencies used inside of executed + # blocks are defined, as this step may be skipped during compile time + self.writeline("try:") + self.indent() + self.writeline(f"{id_map[name]} = environment.{dependency}[{name!r}]") + self.outdent() + self.writeline("except KeyError:") + self.indent() + self.writeline("@internalcode") + self.writeline(f"def {id_map[name]}(*unused):") + self.indent() + self.writeline( + f'raise TemplateRuntimeError("No {dependency[:-1]}' + f' named {name!r} found.")' + ) + self.outdent() + self.outdent() + + def enter_frame(self, frame: Frame) -> None: + undefs = [] + for target, (action, param) in frame.symbols.loads.items(): + if action == VAR_LOAD_PARAMETER: + pass + elif action == VAR_LOAD_RESOLVE: + self.writeline(f"{target} = {self.get_resolve_func()}({param!r})") + elif action == VAR_LOAD_ALIAS: + self.writeline(f"{target} = {param}") + elif action == VAR_LOAD_UNDEFINED: + undefs.append(target) + else: + raise NotImplementedError("unknown load instruction") + if undefs: + self.writeline(f"{' = '.join(undefs)} = missing") + + def leave_frame(self, frame: Frame, with_python_scope: bool = False) -> None: + if not with_python_scope: + undefs = [] + for target in frame.symbols.loads: + undefs.append(target) + if undefs: + self.writeline(f"{' = '.join(undefs)} = missing") + + def choose_async(self, async_value: str = "async ", sync_value: str = "") -> str: + return async_value if self.environment.is_async else sync_value + + def func(self, name: str) -> str: + return f"{self.choose_async()}def {name}" + + def macro_body( + self, node: t.Union[nodes.Macro, nodes.CallBlock], frame: Frame + ) -> t.Tuple[Frame, MacroRef]: + """Dump the function def of a macro or call block.""" + frame = frame.inner() + frame.symbols.analyze_node(node) + macro_ref = MacroRef(node) + + explicit_caller = None + skip_special_params = set() + args = [] + + for idx, arg in enumerate(node.args): + if arg.name == "caller": + explicit_caller = idx + if arg.name in ("kwargs", "varargs"): + skip_special_params.add(arg.name) + args.append(frame.symbols.ref(arg.name)) + + undeclared = find_undeclared(node.body, ("caller", "kwargs", "varargs")) + + if "caller" in undeclared: + # In older Jinja versions there was a bug that allowed caller + # to retain the special behavior even if it was mentioned in + # the argument list. However thankfully this was only really + # working if it was the last argument. So we are explicitly + # checking this now and error out if it is anywhere else in + # the argument list. + if explicit_caller is not None: + try: + node.defaults[explicit_caller - len(node.args)] + except IndexError: + self.fail( + "When defining macros or call blocks the " + 'special "caller" argument must be omitted ' + "or be given a default.", + node.lineno, + ) + else: + args.append(frame.symbols.declare_parameter("caller")) + macro_ref.accesses_caller = True + if "kwargs" in undeclared and "kwargs" not in skip_special_params: + args.append(frame.symbols.declare_parameter("kwargs")) + macro_ref.accesses_kwargs = True + if "varargs" in undeclared and "varargs" not in skip_special_params: + args.append(frame.symbols.declare_parameter("varargs")) + macro_ref.accesses_varargs = True + + # macros are delayed, they never require output checks + frame.require_output_check = False + frame.symbols.analyze_node(node) + self.writeline(f"{self.func('macro')}({', '.join(args)}):", node) + self.indent() + + self.buffer(frame) + self.enter_frame(frame) + + self.push_parameter_definitions(frame) + for idx, arg in enumerate(node.args): + ref = frame.symbols.ref(arg.name) + self.writeline(f"if {ref} is missing:") + self.indent() + try: + default = node.defaults[idx - len(node.args)] + except IndexError: + self.writeline( + f'{ref} = undefined("parameter {arg.name!r} was not provided",' + f" name={arg.name!r})" + ) + else: + self.writeline(f"{ref} = ") + self.visit(default, frame) + self.mark_parameter_stored(ref) + self.outdent() + self.pop_parameter_definitions() + + self.blockvisit(node.body, frame) + self.return_buffer_contents(frame, force_unescaped=True) + self.leave_frame(frame, with_python_scope=True) + self.outdent() + + return frame, macro_ref + + def macro_def(self, macro_ref: MacroRef, frame: Frame) -> None: + """Dump the macro definition for the def created by macro_body.""" + arg_tuple = ", ".join(repr(x.name) for x in macro_ref.node.args) + name = getattr(macro_ref.node, "name", None) + if len(macro_ref.node.args) == 1: + arg_tuple += "," + self.write( + f"Macro(environment, macro, {name!r}, ({arg_tuple})," + f" {macro_ref.accesses_kwargs!r}, {macro_ref.accesses_varargs!r}," + f" {macro_ref.accesses_caller!r}, context.eval_ctx.autoescape)" + ) + + def position(self, node: nodes.Node) -> str: + """Return a human readable position for the node.""" + rv = f"line {node.lineno}" + if self.name is not None: + rv = f"{rv} in {self.name!r}" + return rv + + def dump_local_context(self, frame: Frame) -> str: + items_kv = ", ".join( + f"{name!r}: {target}" + for name, target in frame.symbols.dump_stores().items() + ) + return f"{{{items_kv}}}" + + def write_commons(self) -> None: + """Writes a common preamble that is used by root and block functions. + Primarily this sets up common local helpers and enforces a generator + through a dead branch. + """ + self.writeline("resolve = context.resolve_or_missing") + self.writeline("undefined = environment.undefined") + self.writeline("concat = environment.concat") + # always use the standard Undefined class for the implicit else of + # conditional expressions + self.writeline("cond_expr_undefined = Undefined") + self.writeline("if 0: yield None") + + def push_parameter_definitions(self, frame: Frame) -> None: + """Pushes all parameter targets from the given frame into a local + stack that permits tracking of yet to be assigned parameters. In + particular this enables the optimization from `visit_Name` to skip + undefined expressions for parameters in macros as macros can reference + otherwise unbound parameters. + """ + self._param_def_block.append(frame.symbols.dump_param_targets()) + + def pop_parameter_definitions(self) -> None: + """Pops the current parameter definitions set.""" + self._param_def_block.pop() + + def mark_parameter_stored(self, target: str) -> None: + """Marks a parameter in the current parameter definitions as stored. + This will skip the enforced undefined checks. + """ + if self._param_def_block: + self._param_def_block[-1].discard(target) + + def push_context_reference(self, target: str) -> None: + self._context_reference_stack.append(target) + + def pop_context_reference(self) -> None: + self._context_reference_stack.pop() + + def get_context_ref(self) -> str: + return self._context_reference_stack[-1] + + def get_resolve_func(self) -> str: + target = self._context_reference_stack[-1] + if target == "context": + return "resolve" + return f"{target}.resolve" + + def derive_context(self, frame: Frame) -> str: + return f"{self.get_context_ref()}.derived({self.dump_local_context(frame)})" + + def parameter_is_undeclared(self, target: str) -> bool: + """Checks if a given target is an undeclared parameter.""" + if not self._param_def_block: + return False + return target in self._param_def_block[-1] + + def push_assign_tracking(self) -> None: + """Pushes a new layer for assignment tracking.""" + self._assign_stack.append(set()) + + def pop_assign_tracking(self, frame: Frame) -> None: + """Pops the topmost level for assignment tracking and updates the + context variables if necessary. + """ + vars = self._assign_stack.pop() + if ( + not frame.block_frame + and not frame.loop_frame + and not frame.toplevel + or not vars + ): + return + public_names = [x for x in vars if x[:1] != "_"] + if len(vars) == 1: + name = next(iter(vars)) + ref = frame.symbols.ref(name) + if frame.loop_frame: + self.writeline(f"_loop_vars[{name!r}] = {ref}") + return + if frame.block_frame: + self.writeline(f"_block_vars[{name!r}] = {ref}") + return + self.writeline(f"context.vars[{name!r}] = {ref}") + else: + if frame.loop_frame: + self.writeline("_loop_vars.update({") + elif frame.block_frame: + self.writeline("_block_vars.update({") + else: + self.writeline("context.vars.update({") + for idx, name in enumerate(sorted(vars)): + if idx: + self.write(", ") + ref = frame.symbols.ref(name) + self.write(f"{name!r}: {ref}") + self.write("})") + if not frame.block_frame and not frame.loop_frame and public_names: + if len(public_names) == 1: + self.writeline(f"context.exported_vars.add({public_names[0]!r})") + else: + names_str = ", ".join(map(repr, sorted(public_names))) + self.writeline(f"context.exported_vars.update(({names_str}))") + + # -- Statement Visitors + + def visit_Template( + self, node: nodes.Template, frame: t.Optional[Frame] = None + ) -> None: + assert frame is None, "no root frame allowed" + eval_ctx = EvalContext(self.environment, self.name) + + from .runtime import async_exported + from .runtime import exported + + if self.environment.is_async: + exported_names = sorted(exported + async_exported) + else: + exported_names = sorted(exported) + + self.writeline("from jinja2.runtime import " + ", ".join(exported_names)) + + # if we want a deferred initialization we cannot move the + # environment into a local name + envenv = "" if self.defer_init else ", environment=environment" + + # do we have an extends tag at all? If not, we can save some + # overhead by just not processing any inheritance code. + have_extends = node.find(nodes.Extends) is not None + + # find all blocks + for block in node.find_all(nodes.Block): + if block.name in self.blocks: + self.fail(f"block {block.name!r} defined twice", block.lineno) + self.blocks[block.name] = block + + # find all imports and import them + for import_ in node.find_all(nodes.ImportedName): + if import_.importname not in self.import_aliases: + imp = import_.importname + self.import_aliases[imp] = alias = self.temporary_identifier() + if "." in imp: + module, obj = imp.rsplit(".", 1) + self.writeline(f"from {module} import {obj} as {alias}") + else: + self.writeline(f"import {imp} as {alias}") + + # add the load name + self.writeline(f"name = {self.name!r}") + + # generate the root render function. + self.writeline( + f"{self.func('root')}(context, missing=missing{envenv}):", extra=1 + ) + self.indent() + self.write_commons() + + # process the root + frame = Frame(eval_ctx) + if "self" in find_undeclared(node.body, ("self",)): + ref = frame.symbols.declare_parameter("self") + self.writeline(f"{ref} = TemplateReference(context)") + frame.symbols.analyze_node(node) + frame.toplevel = frame.rootlevel = True + frame.require_output_check = have_extends and not self.has_known_extends + if have_extends: + self.writeline("parent_template = None") + self.enter_frame(frame) + self.pull_dependencies(node.body) + self.blockvisit(node.body, frame) + self.leave_frame(frame, with_python_scope=True) + self.outdent() + + # make sure that the parent root is called. + if have_extends: + if not self.has_known_extends: + self.indent() + self.writeline("if parent_template is not None:") + self.indent() + if not self.environment.is_async: + self.writeline("yield from parent_template.root_render_func(context)") + else: + self.writeline("agen = parent_template.root_render_func(context)") + self.writeline("try:") + self.indent() + self.writeline("async for event in agen:") + self.indent() + self.writeline("yield event") + self.outdent() + self.outdent() + self.writeline("finally: await agen.aclose()") + self.outdent(1 + (not self.has_known_extends)) + + # at this point we now have the blocks collected and can visit them too. + for name, block in self.blocks.items(): + self.writeline( + f"{self.func('block_' + name)}(context, missing=missing{envenv}):", + block, + 1, + ) + self.indent() + self.write_commons() + # It's important that we do not make this frame a child of the + # toplevel template. This would cause a variety of + # interesting issues with identifier tracking. + block_frame = Frame(eval_ctx) + block_frame.block_frame = True + undeclared = find_undeclared(block.body, ("self", "super")) + if "self" in undeclared: + ref = block_frame.symbols.declare_parameter("self") + self.writeline(f"{ref} = TemplateReference(context)") + if "super" in undeclared: + ref = block_frame.symbols.declare_parameter("super") + self.writeline(f"{ref} = context.super({name!r}, block_{name})") + block_frame.symbols.analyze_node(block) + block_frame.block = name + self.writeline("_block_vars = {}") + self.enter_frame(block_frame) + self.pull_dependencies(block.body) + self.blockvisit(block.body, block_frame) + self.leave_frame(block_frame, with_python_scope=True) + self.outdent() + + blocks_kv_str = ", ".join(f"{x!r}: block_{x}" for x in self.blocks) + self.writeline(f"blocks = {{{blocks_kv_str}}}", extra=1) + debug_kv_str = "&".join(f"{k}={v}" for k, v in self.debug_info) + self.writeline(f"debug_info = {debug_kv_str!r}") + + def visit_Block(self, node: nodes.Block, frame: Frame) -> None: + """Call a block and register it for the template.""" + level = 0 + if frame.toplevel: + # if we know that we are a child template, there is no need to + # check if we are one + if self.has_known_extends: + return + if self.extends_so_far > 0: + self.writeline("if parent_template is None:") + self.indent() + level += 1 + + if node.scoped: + context = self.derive_context(frame) + else: + context = self.get_context_ref() + + if node.required: + self.writeline(f"if len(context.blocks[{node.name!r}]) <= 1:", node) + self.indent() + self.writeline( + f'raise TemplateRuntimeError("Required block {node.name!r} not found")', + node, + ) + self.outdent() + + if not self.environment.is_async and frame.buffer is None: + self.writeline( + f"yield from context.blocks[{node.name!r}][0]({context})", node + ) + else: + self.writeline(f"gen = context.blocks[{node.name!r}][0]({context})") + self.writeline("try:") + self.indent() + self.writeline( + f"{self.choose_async()}for event in gen:", + node, + ) + self.indent() + self.simple_write("event", frame) + self.outdent() + self.outdent() + self.writeline( + f"finally: {self.choose_async('await gen.aclose()', 'gen.close()')}" + ) + + self.outdent(level) + + def visit_Extends(self, node: nodes.Extends, frame: Frame) -> None: + """Calls the extender.""" + if not frame.toplevel: + self.fail("cannot use extend from a non top-level scope", node.lineno) + + # if the number of extends statements in general is zero so + # far, we don't have to add a check if something extended + # the template before this one. + if self.extends_so_far > 0: + # if we have a known extends we just add a template runtime + # error into the generated code. We could catch that at compile + # time too, but i welcome it not to confuse users by throwing the + # same error at different times just "because we can". + if not self.has_known_extends: + self.writeline("if parent_template is not None:") + self.indent() + self.writeline('raise TemplateRuntimeError("extended multiple times")') + + # if we have a known extends already we don't need that code here + # as we know that the template execution will end here. + if self.has_known_extends: + raise CompilerExit() + else: + self.outdent() + + self.writeline("parent_template = environment.get_template(", node) + self.visit(node.template, frame) + self.write(f", {self.name!r})") + self.writeline("for name, parent_block in parent_template.blocks.items():") + self.indent() + self.writeline("context.blocks.setdefault(name, []).append(parent_block)") + self.outdent() + + # if this extends statement was in the root level we can take + # advantage of that information and simplify the generated code + # in the top level from this point onwards + if frame.rootlevel: + self.has_known_extends = True + + # and now we have one more + self.extends_so_far += 1 + + def visit_Include(self, node: nodes.Include, frame: Frame) -> None: + """Handles includes.""" + if node.ignore_missing: + self.writeline("try:") + self.indent() + + func_name = "get_or_select_template" + if isinstance(node.template, nodes.Const): + if isinstance(node.template.value, str): + func_name = "get_template" + elif isinstance(node.template.value, (tuple, list)): + func_name = "select_template" + elif isinstance(node.template, (nodes.Tuple, nodes.List)): + func_name = "select_template" + + self.writeline(f"template = environment.{func_name}(", node) + self.visit(node.template, frame) + self.write(f", {self.name!r})") + if node.ignore_missing: + self.outdent() + self.writeline("except TemplateNotFound:") + self.indent() + self.writeline("pass") + self.outdent() + self.writeline("else:") + self.indent() + + def loop_body() -> None: + self.indent() + self.simple_write("event", frame) + self.outdent() + + if node.with_context: + self.writeline( + f"gen = template.root_render_func(" + "template.new_context(context.get_all(), True," + f" {self.dump_local_context(frame)}))" + ) + self.writeline("try:") + self.indent() + self.writeline(f"{self.choose_async()}for event in gen:") + loop_body() + self.outdent() + self.writeline( + f"finally: {self.choose_async('await gen.aclose()', 'gen.close()')}" + ) + elif self.environment.is_async: + self.writeline( + "for event in (await template._get_default_module_async())" + "._body_stream:" + ) + loop_body() + else: + self.writeline("yield from template._get_default_module()._body_stream") + + if node.ignore_missing: + self.outdent() + + def _import_common( + self, node: t.Union[nodes.Import, nodes.FromImport], frame: Frame + ) -> None: + self.write(f"{self.choose_async('await ')}environment.get_template(") + self.visit(node.template, frame) + self.write(f", {self.name!r}).") + + if node.with_context: + f_name = f"make_module{self.choose_async('_async')}" + self.write( + f"{f_name}(context.get_all(), True, {self.dump_local_context(frame)})" + ) + else: + self.write(f"_get_default_module{self.choose_async('_async')}(context)") + + def visit_Import(self, node: nodes.Import, frame: Frame) -> None: + """Visit regular imports.""" + self.writeline(f"{frame.symbols.ref(node.target)} = ", node) + if frame.toplevel: + self.write(f"context.vars[{node.target!r}] = ") + + self._import_common(node, frame) + + if frame.toplevel and not node.target.startswith("_"): + self.writeline(f"context.exported_vars.discard({node.target!r})") + + def visit_FromImport(self, node: nodes.FromImport, frame: Frame) -> None: + """Visit named imports.""" + self.newline(node) + self.write("included_template = ") + self._import_common(node, frame) + var_names = [] + discarded_names = [] + for name in node.names: + if isinstance(name, tuple): + name, alias = name + else: + alias = name + self.writeline( + f"{frame.symbols.ref(alias)} =" + f" getattr(included_template, {name!r}, missing)" + ) + self.writeline(f"if {frame.symbols.ref(alias)} is missing:") + self.indent() + # The position will contain the template name, and will be formatted + # into a string that will be compiled into an f-string. Curly braces + # in the name must be replaced with escapes so that they will not be + # executed as part of the f-string. + position = self.position(node).replace("{", "{{").replace("}", "}}") + message = ( + "the template {included_template.__name__!r}" + f" (imported on {position})" + f" does not export the requested name {name!r}" + ) + self.writeline( + f"{frame.symbols.ref(alias)} = undefined(f{message!r}, name={name!r})" + ) + self.outdent() + if frame.toplevel: + var_names.append(alias) + if not alias.startswith("_"): + discarded_names.append(alias) + + if var_names: + if len(var_names) == 1: + name = var_names[0] + self.writeline(f"context.vars[{name!r}] = {frame.symbols.ref(name)}") + else: + names_kv = ", ".join( + f"{name!r}: {frame.symbols.ref(name)}" for name in var_names + ) + self.writeline(f"context.vars.update({{{names_kv}}})") + if discarded_names: + if len(discarded_names) == 1: + self.writeline(f"context.exported_vars.discard({discarded_names[0]!r})") + else: + names_str = ", ".join(map(repr, discarded_names)) + self.writeline( + f"context.exported_vars.difference_update(({names_str}))" + ) + + def visit_For(self, node: nodes.For, frame: Frame) -> None: + loop_frame = frame.inner() + loop_frame.loop_frame = True + test_frame = frame.inner() + else_frame = frame.inner() + + # try to figure out if we have an extended loop. An extended loop + # is necessary if the loop is in recursive mode if the special loop + # variable is accessed in the body if the body is a scoped block. + extended_loop = ( + node.recursive + or "loop" + in find_undeclared(node.iter_child_nodes(only=("body",)), ("loop",)) + or any(block.scoped for block in node.find_all(nodes.Block)) + ) + + loop_ref = None + if extended_loop: + loop_ref = loop_frame.symbols.declare_parameter("loop") + + loop_frame.symbols.analyze_node(node, for_branch="body") + if node.else_: + else_frame.symbols.analyze_node(node, for_branch="else") + + if node.test: + loop_filter_func = self.temporary_identifier() + test_frame.symbols.analyze_node(node, for_branch="test") + self.writeline(f"{self.func(loop_filter_func)}(fiter):", node.test) + self.indent() + self.enter_frame(test_frame) + self.writeline(self.choose_async("async for ", "for ")) + self.visit(node.target, loop_frame) + self.write(" in ") + self.write(self.choose_async("auto_aiter(fiter)", "fiter")) + self.write(":") + self.indent() + self.writeline("if ", node.test) + self.visit(node.test, test_frame) + self.write(":") + self.indent() + self.writeline("yield ") + self.visit(node.target, loop_frame) + self.outdent(3) + self.leave_frame(test_frame, with_python_scope=True) + + # if we don't have an recursive loop we have to find the shadowed + # variables at that point. Because loops can be nested but the loop + # variable is a special one we have to enforce aliasing for it. + if node.recursive: + self.writeline( + f"{self.func('loop')}(reciter, loop_render_func, depth=0):", node + ) + self.indent() + self.buffer(loop_frame) + + # Use the same buffer for the else frame + else_frame.buffer = loop_frame.buffer + + # make sure the loop variable is a special one and raise a template + # assertion error if a loop tries to write to loop + if extended_loop: + self.writeline(f"{loop_ref} = missing") + + for name in node.find_all(nodes.Name): + if name.ctx == "store" and name.name == "loop": + self.fail( + "Can't assign to special loop variable in for-loop target", + name.lineno, + ) + + if node.else_: + iteration_indicator = self.temporary_identifier() + self.writeline(f"{iteration_indicator} = 1") + + self.writeline(self.choose_async("async for ", "for "), node) + self.visit(node.target, loop_frame) + if extended_loop: + self.write(f", {loop_ref} in {self.choose_async('Async')}LoopContext(") + else: + self.write(" in ") + + if node.test: + self.write(f"{loop_filter_func}(") + if node.recursive: + self.write("reciter") + else: + if self.environment.is_async and not extended_loop: + self.write("auto_aiter(") + self.visit(node.iter, frame) + if self.environment.is_async and not extended_loop: + self.write(")") + if node.test: + self.write(")") + + if node.recursive: + self.write(", undefined, loop_render_func, depth):") + else: + self.write(", undefined):" if extended_loop else ":") + + self.indent() + self.enter_frame(loop_frame) + + self.writeline("_loop_vars = {}") + self.blockvisit(node.body, loop_frame) + if node.else_: + self.writeline(f"{iteration_indicator} = 0") + self.outdent() + self.leave_frame( + loop_frame, with_python_scope=node.recursive and not node.else_ + ) + + if node.else_: + self.writeline(f"if {iteration_indicator}:") + self.indent() + self.enter_frame(else_frame) + self.blockvisit(node.else_, else_frame) + self.leave_frame(else_frame) + self.outdent() + + # if the node was recursive we have to return the buffer contents + # and start the iteration code + if node.recursive: + self.return_buffer_contents(loop_frame) + self.outdent() + self.start_write(frame, node) + self.write(f"{self.choose_async('await ')}loop(") + if self.environment.is_async: + self.write("auto_aiter(") + self.visit(node.iter, frame) + if self.environment.is_async: + self.write(")") + self.write(", loop)") + self.end_write(frame) + + # at the end of the iteration, clear any assignments made in the + # loop from the top level + if self._assign_stack: + self._assign_stack[-1].difference_update(loop_frame.symbols.stores) + + def visit_If(self, node: nodes.If, frame: Frame) -> None: + if_frame = frame.soft() + self.writeline("if ", node) + self.visit(node.test, if_frame) + self.write(":") + self.indent() + self.blockvisit(node.body, if_frame) + self.outdent() + for elif_ in node.elif_: + self.writeline("elif ", elif_) + self.visit(elif_.test, if_frame) + self.write(":") + self.indent() + self.blockvisit(elif_.body, if_frame) + self.outdent() + if node.else_: + self.writeline("else:") + self.indent() + self.blockvisit(node.else_, if_frame) + self.outdent() + + def visit_Macro(self, node: nodes.Macro, frame: Frame) -> None: + macro_frame, macro_ref = self.macro_body(node, frame) + self.newline() + if frame.toplevel: + if not node.name.startswith("_"): + self.write(f"context.exported_vars.add({node.name!r})") + self.writeline(f"context.vars[{node.name!r}] = ") + self.write(f"{frame.symbols.ref(node.name)} = ") + self.macro_def(macro_ref, macro_frame) + + def visit_CallBlock(self, node: nodes.CallBlock, frame: Frame) -> None: + call_frame, macro_ref = self.macro_body(node, frame) + self.writeline("caller = ") + self.macro_def(macro_ref, call_frame) + self.start_write(frame, node) + self.visit_Call(node.call, frame, forward_caller=True) + self.end_write(frame) + + def visit_FilterBlock(self, node: nodes.FilterBlock, frame: Frame) -> None: + filter_frame = frame.inner() + filter_frame.symbols.analyze_node(node) + self.enter_frame(filter_frame) + self.buffer(filter_frame) + self.blockvisit(node.body, filter_frame) + self.start_write(frame, node) + self.visit_Filter(node.filter, filter_frame) + self.end_write(frame) + self.leave_frame(filter_frame) + + def visit_With(self, node: nodes.With, frame: Frame) -> None: + with_frame = frame.inner() + with_frame.symbols.analyze_node(node) + self.enter_frame(with_frame) + for target, expr in zip(node.targets, node.values): + self.newline() + self.visit(target, with_frame) + self.write(" = ") + self.visit(expr, frame) + self.blockvisit(node.body, with_frame) + self.leave_frame(with_frame) + + def visit_ExprStmt(self, node: nodes.ExprStmt, frame: Frame) -> None: + self.newline(node) + self.visit(node.node, frame) + + class _FinalizeInfo(t.NamedTuple): + const: t.Optional[t.Callable[..., str]] + src: t.Optional[str] + + @staticmethod + def _default_finalize(value: t.Any) -> t.Any: + """The default finalize function if the environment isn't + configured with one. Or, if the environment has one, this is + called on that function's output for constants. + """ + return str(value) + + _finalize: t.Optional[_FinalizeInfo] = None + + def _make_finalize(self) -> _FinalizeInfo: + """Build the finalize function to be used on constants and at + runtime. Cached so it's only created once for all output nodes. + + Returns a ``namedtuple`` with the following attributes: + + ``const`` + A function to finalize constant data at compile time. + + ``src`` + Source code to output around nodes to be evaluated at + runtime. + """ + if self._finalize is not None: + return self._finalize + + finalize: t.Optional[t.Callable[..., t.Any]] + finalize = default = self._default_finalize + src = None + + if self.environment.finalize: + src = "environment.finalize(" + env_finalize = self.environment.finalize + pass_arg = { + _PassArg.context: "context", + _PassArg.eval_context: "context.eval_ctx", + _PassArg.environment: "environment", + }.get( + _PassArg.from_obj(env_finalize) # type: ignore + ) + finalize = None + + if pass_arg is None: + + def finalize(value: t.Any) -> t.Any: # noqa: F811 + return default(env_finalize(value)) + + else: + src = f"{src}{pass_arg}, " + + if pass_arg == "environment": + + def finalize(value: t.Any) -> t.Any: # noqa: F811 + return default(env_finalize(self.environment, value)) + + self._finalize = self._FinalizeInfo(finalize, src) + return self._finalize + + def _output_const_repr(self, group: t.Iterable[t.Any]) -> str: + """Given a group of constant values converted from ``Output`` + child nodes, produce a string to write to the template module + source. + """ + return repr(concat(group)) + + def _output_child_to_const( + self, node: nodes.Expr, frame: Frame, finalize: _FinalizeInfo + ) -> str: + """Try to optimize a child of an ``Output`` node by trying to + convert it to constant, finalized data at compile time. + + If :exc:`Impossible` is raised, the node is not constant and + will be evaluated at runtime. Any other exception will also be + evaluated at runtime for easier debugging. + """ + const = node.as_const(frame.eval_ctx) + + if frame.eval_ctx.autoescape: + const = escape(const) + + # Template data doesn't go through finalize. + if isinstance(node, nodes.TemplateData): + return str(const) + + return finalize.const(const) # type: ignore + + def _output_child_pre( + self, node: nodes.Expr, frame: Frame, finalize: _FinalizeInfo + ) -> None: + """Output extra source code before visiting a child of an + ``Output`` node. + """ + if frame.eval_ctx.volatile: + self.write("(escape if context.eval_ctx.autoescape else str)(") + elif frame.eval_ctx.autoescape: + self.write("escape(") + else: + self.write("str(") + + if finalize.src is not None: + self.write(finalize.src) + + def _output_child_post( + self, node: nodes.Expr, frame: Frame, finalize: _FinalizeInfo + ) -> None: + """Output extra source code after visiting a child of an + ``Output`` node. + """ + self.write(")") + + if finalize.src is not None: + self.write(")") + + def visit_Output(self, node: nodes.Output, frame: Frame) -> None: + # If an extends is active, don't render outside a block. + if frame.require_output_check: + # A top-level extends is known to exist at compile time. + if self.has_known_extends: + return + + self.writeline("if parent_template is None:") + self.indent() + + finalize = self._make_finalize() + body: t.List[t.Union[t.List[t.Any], nodes.Expr]] = [] + + # Evaluate constants at compile time if possible. Each item in + # body will be either a list of static data or a node to be + # evaluated at runtime. + for child in node.nodes: + try: + if not ( + # If the finalize function requires runtime context, + # constants can't be evaluated at compile time. + finalize.const + # Unless it's basic template data that won't be + # finalized anyway. + or isinstance(child, nodes.TemplateData) + ): + raise nodes.Impossible() + + const = self._output_child_to_const(child, frame, finalize) + except (nodes.Impossible, Exception): + # The node was not constant and needs to be evaluated at + # runtime. Or another error was raised, which is easier + # to debug at runtime. + body.append(child) + continue + + if body and isinstance(body[-1], list): + body[-1].append(const) + else: + body.append([const]) + + if frame.buffer is not None: + if len(body) == 1: + self.writeline(f"{frame.buffer}.append(") + else: + self.writeline(f"{frame.buffer}.extend((") + + self.indent() + + for item in body: + if isinstance(item, list): + # A group of constant data to join and output. + val = self._output_const_repr(item) + + if frame.buffer is None: + self.writeline("yield " + val) + else: + self.writeline(val + ",") + else: + if frame.buffer is None: + self.writeline("yield ", item) + else: + self.newline(item) + + # A node to be evaluated at runtime. + self._output_child_pre(item, frame, finalize) + self.visit(item, frame) + self._output_child_post(item, frame, finalize) + + if frame.buffer is not None: + self.write(",") + + if frame.buffer is not None: + self.outdent() + self.writeline(")" if len(body) == 1 else "))") + + if frame.require_output_check: + self.outdent() + + def visit_Assign(self, node: nodes.Assign, frame: Frame) -> None: + self.push_assign_tracking() + + # ``a.b`` is allowed for assignment, and is parsed as an NSRef. However, + # it is only valid if it references a Namespace object. Emit a check for + # that for each ref here, before assignment code is emitted. This can't + # be done in visit_NSRef as the ref could be in the middle of a tuple. + seen_refs: t.Set[str] = set() + + for nsref in node.find_all(nodes.NSRef): + if nsref.name in seen_refs: + # Only emit the check for each reference once, in case the same + # ref is used multiple times in a tuple, `ns.a, ns.b = c, d`. + continue + + seen_refs.add(nsref.name) + ref = frame.symbols.ref(nsref.name) + self.writeline(f"if not isinstance({ref}, Namespace):") + self.indent() + self.writeline( + "raise TemplateRuntimeError" + '("cannot assign attribute on non-namespace object")' + ) + self.outdent() + + self.newline(node) + self.visit(node.target, frame) + self.write(" = ") + self.visit(node.node, frame) + self.pop_assign_tracking(frame) + + def visit_AssignBlock(self, node: nodes.AssignBlock, frame: Frame) -> None: + self.push_assign_tracking() + block_frame = frame.inner() + # This is a special case. Since a set block always captures we + # will disable output checks. This way one can use set blocks + # toplevel even in extended templates. + block_frame.require_output_check = False + block_frame.symbols.analyze_node(node) + self.enter_frame(block_frame) + self.buffer(block_frame) + self.blockvisit(node.body, block_frame) + self.newline(node) + self.visit(node.target, frame) + self.write(" = (Markup if context.eval_ctx.autoescape else identity)(") + if node.filter is not None: + self.visit_Filter(node.filter, block_frame) + else: + self.write(f"concat({block_frame.buffer})") + self.write(")") + self.pop_assign_tracking(frame) + self.leave_frame(block_frame) + + # -- Expression Visitors + + def visit_Name(self, node: nodes.Name, frame: Frame) -> None: + if node.ctx == "store" and ( + frame.toplevel or frame.loop_frame or frame.block_frame + ): + if self._assign_stack: + self._assign_stack[-1].add(node.name) + ref = frame.symbols.ref(node.name) + + # If we are looking up a variable we might have to deal with the + # case where it's undefined. We can skip that case if the load + # instruction indicates a parameter which are always defined. + if node.ctx == "load": + load = frame.symbols.find_load(ref) + if not ( + load is not None + and load[0] == VAR_LOAD_PARAMETER + and not self.parameter_is_undeclared(ref) + ): + self.write( + f"(undefined(name={node.name!r}) if {ref} is missing else {ref})" + ) + return + + self.write(ref) + + def visit_NSRef(self, node: nodes.NSRef, frame: Frame) -> None: + # NSRef is a dotted assignment target a.b=c, but uses a[b]=c internally. + # visit_Assign emits code to validate that each ref is to a Namespace + # object only. That can't be emitted here as the ref could be in the + # middle of a tuple assignment. + ref = frame.symbols.ref(node.name) + self.writeline(f"{ref}[{node.attr!r}]") + + def visit_Const(self, node: nodes.Const, frame: Frame) -> None: + val = node.as_const(frame.eval_ctx) + if isinstance(val, float): + self.write(str(val)) + else: + self.write(repr(val)) + + def visit_TemplateData(self, node: nodes.TemplateData, frame: Frame) -> None: + try: + self.write(repr(node.as_const(frame.eval_ctx))) + except nodes.Impossible: + self.write( + f"(Markup if context.eval_ctx.autoescape else identity)({node.data!r})" + ) + + def visit_Tuple(self, node: nodes.Tuple, frame: Frame) -> None: + self.write("(") + idx = -1 + for idx, item in enumerate(node.items): + if idx: + self.write(", ") + self.visit(item, frame) + self.write(",)" if idx == 0 else ")") + + def visit_List(self, node: nodes.List, frame: Frame) -> None: + self.write("[") + for idx, item in enumerate(node.items): + if idx: + self.write(", ") + self.visit(item, frame) + self.write("]") + + def visit_Dict(self, node: nodes.Dict, frame: Frame) -> None: + self.write("{") + for idx, item in enumerate(node.items): + if idx: + self.write(", ") + self.visit(item.key, frame) + self.write(": ") + self.visit(item.value, frame) + self.write("}") + + visit_Add = _make_binop("+") + visit_Sub = _make_binop("-") + visit_Mul = _make_binop("*") + visit_Div = _make_binop("/") + visit_FloorDiv = _make_binop("//") + visit_Pow = _make_binop("**") + visit_Mod = _make_binop("%") + visit_And = _make_binop("and") + visit_Or = _make_binop("or") + visit_Pos = _make_unop("+") + visit_Neg = _make_unop("-") + visit_Not = _make_unop("not ") + + @optimizeconst + def visit_Concat(self, node: nodes.Concat, frame: Frame) -> None: + if frame.eval_ctx.volatile: + func_name = "(markup_join if context.eval_ctx.volatile else str_join)" + elif frame.eval_ctx.autoescape: + func_name = "markup_join" + else: + func_name = "str_join" + self.write(f"{func_name}((") + for arg in node.nodes: + self.visit(arg, frame) + self.write(", ") + self.write("))") + + @optimizeconst + def visit_Compare(self, node: nodes.Compare, frame: Frame) -> None: + self.write("(") + self.visit(node.expr, frame) + for op in node.ops: + self.visit(op, frame) + self.write(")") + + def visit_Operand(self, node: nodes.Operand, frame: Frame) -> None: + self.write(f" {operators[node.op]} ") + self.visit(node.expr, frame) + + @optimizeconst + def visit_Getattr(self, node: nodes.Getattr, frame: Frame) -> None: + if self.environment.is_async: + self.write("(await auto_await(") + + self.write("environment.getattr(") + self.visit(node.node, frame) + self.write(f", {node.attr!r})") + + if self.environment.is_async: + self.write("))") + + @optimizeconst + def visit_Getitem(self, node: nodes.Getitem, frame: Frame) -> None: + # slices bypass the environment getitem method. + if isinstance(node.arg, nodes.Slice): + self.visit(node.node, frame) + self.write("[") + self.visit(node.arg, frame) + self.write("]") + else: + if self.environment.is_async: + self.write("(await auto_await(") + + self.write("environment.getitem(") + self.visit(node.node, frame) + self.write(", ") + self.visit(node.arg, frame) + self.write(")") + + if self.environment.is_async: + self.write("))") + + def visit_Slice(self, node: nodes.Slice, frame: Frame) -> None: + if node.start is not None: + self.visit(node.start, frame) + self.write(":") + if node.stop is not None: + self.visit(node.stop, frame) + if node.step is not None: + self.write(":") + self.visit(node.step, frame) + + @contextmanager + def _filter_test_common( + self, node: t.Union[nodes.Filter, nodes.Test], frame: Frame, is_filter: bool + ) -> t.Iterator[None]: + if self.environment.is_async: + self.write("(await auto_await(") + + if is_filter: + self.write(f"{self.filters[node.name]}(") + func = self.environment.filters.get(node.name) + else: + self.write(f"{self.tests[node.name]}(") + func = self.environment.tests.get(node.name) + + # When inside an If or CondExpr frame, allow the filter to be + # undefined at compile time and only raise an error if it's + # actually called at runtime. See pull_dependencies. + if func is None and not frame.soft_frame: + type_name = "filter" if is_filter else "test" + self.fail(f"No {type_name} named {node.name!r}.", node.lineno) + + pass_arg = { + _PassArg.context: "context", + _PassArg.eval_context: "context.eval_ctx", + _PassArg.environment: "environment", + }.get( + _PassArg.from_obj(func) # type: ignore + ) + + if pass_arg is not None: + self.write(f"{pass_arg}, ") + + # Back to the visitor function to handle visiting the target of + # the filter or test. + yield + + self.signature(node, frame) + self.write(")") + + if self.environment.is_async: + self.write("))") + + @optimizeconst + def visit_Filter(self, node: nodes.Filter, frame: Frame) -> None: + with self._filter_test_common(node, frame, True): + # if the filter node is None we are inside a filter block + # and want to write to the current buffer + if node.node is not None: + self.visit(node.node, frame) + elif frame.eval_ctx.volatile: + self.write( + f"(Markup(concat({frame.buffer}))" + f" if context.eval_ctx.autoescape else concat({frame.buffer}))" + ) + elif frame.eval_ctx.autoescape: + self.write(f"Markup(concat({frame.buffer}))") + else: + self.write(f"concat({frame.buffer})") + + @optimizeconst + def visit_Test(self, node: nodes.Test, frame: Frame) -> None: + with self._filter_test_common(node, frame, False): + self.visit(node.node, frame) + + @optimizeconst + def visit_CondExpr(self, node: nodes.CondExpr, frame: Frame) -> None: + frame = frame.soft() + + def write_expr2() -> None: + if node.expr2 is not None: + self.visit(node.expr2, frame) + return + + self.write( + f'cond_expr_undefined("the inline if-expression on' + f" {self.position(node)} evaluated to false and no else" + f' section was defined.")' + ) + + self.write("(") + self.visit(node.expr1, frame) + self.write(" if ") + self.visit(node.test, frame) + self.write(" else ") + write_expr2() + self.write(")") + + @optimizeconst + def visit_Call( + self, node: nodes.Call, frame: Frame, forward_caller: bool = False + ) -> None: + if self.environment.is_async: + self.write("(await auto_await(") + if self.environment.sandboxed: + self.write("environment.call(context, ") + else: + self.write("context.call(") + self.visit(node.node, frame) + extra_kwargs = {"caller": "caller"} if forward_caller else None + loop_kwargs = {"_loop_vars": "_loop_vars"} if frame.loop_frame else {} + block_kwargs = {"_block_vars": "_block_vars"} if frame.block_frame else {} + if extra_kwargs: + extra_kwargs.update(loop_kwargs, **block_kwargs) + elif loop_kwargs or block_kwargs: + extra_kwargs = dict(loop_kwargs, **block_kwargs) + self.signature(node, frame, extra_kwargs) + self.write(")") + if self.environment.is_async: + self.write("))") + + def visit_Keyword(self, node: nodes.Keyword, frame: Frame) -> None: + self.write(node.key + "=") + self.visit(node.value, frame) + + # -- Unused nodes for extensions + + def visit_MarkSafe(self, node: nodes.MarkSafe, frame: Frame) -> None: + self.write("Markup(") + self.visit(node.expr, frame) + self.write(")") + + def visit_MarkSafeIfAutoescape( + self, node: nodes.MarkSafeIfAutoescape, frame: Frame + ) -> None: + self.write("(Markup if context.eval_ctx.autoescape else identity)(") + self.visit(node.expr, frame) + self.write(")") + + def visit_EnvironmentAttribute( + self, node: nodes.EnvironmentAttribute, frame: Frame + ) -> None: + self.write("environment." + node.name) + + def visit_ExtensionAttribute( + self, node: nodes.ExtensionAttribute, frame: Frame + ) -> None: + self.write(f"environment.extensions[{node.identifier!r}].{node.name}") + + def visit_ImportedName(self, node: nodes.ImportedName, frame: Frame) -> None: + self.write(self.import_aliases[node.importname]) + + def visit_InternalName(self, node: nodes.InternalName, frame: Frame) -> None: + self.write(node.name) + + def visit_ContextReference( + self, node: nodes.ContextReference, frame: Frame + ) -> None: + self.write("context") + + def visit_DerivedContextReference( + self, node: nodes.DerivedContextReference, frame: Frame + ) -> None: + self.write(self.derive_context(frame)) + + def visit_Continue(self, node: nodes.Continue, frame: Frame) -> None: + self.writeline("continue", node) + + def visit_Break(self, node: nodes.Break, frame: Frame) -> None: + self.writeline("break", node) + + def visit_Scope(self, node: nodes.Scope, frame: Frame) -> None: + scope_frame = frame.inner() + scope_frame.symbols.analyze_node(node) + self.enter_frame(scope_frame) + self.blockvisit(node.body, scope_frame) + self.leave_frame(scope_frame) + + def visit_OverlayScope(self, node: nodes.OverlayScope, frame: Frame) -> None: + ctx = self.temporary_identifier() + self.writeline(f"{ctx} = {self.derive_context(frame)}") + self.writeline(f"{ctx}.vars = ") + self.visit(node.context, frame) + self.push_context_reference(ctx) + + scope_frame = frame.inner(isolated=True) + scope_frame.symbols.analyze_node(node) + self.enter_frame(scope_frame) + self.blockvisit(node.body, scope_frame) + self.leave_frame(scope_frame) + self.pop_context_reference() + + def visit_EvalContextModifier( + self, node: nodes.EvalContextModifier, frame: Frame + ) -> None: + for keyword in node.options: + self.writeline(f"context.eval_ctx.{keyword.key} = ") + self.visit(keyword.value, frame) + try: + val = keyword.value.as_const(frame.eval_ctx) + except nodes.Impossible: + frame.eval_ctx.volatile = True + else: + setattr(frame.eval_ctx, keyword.key, val) + + def visit_ScopedEvalContextModifier( + self, node: nodes.ScopedEvalContextModifier, frame: Frame + ) -> None: + old_ctx_name = self.temporary_identifier() + saved_ctx = frame.eval_ctx.save() + self.writeline(f"{old_ctx_name} = context.eval_ctx.save()") + self.visit_EvalContextModifier(node, frame) + for child in node.body: + self.visit(child, frame) + frame.eval_ctx.revert(saved_ctx) + self.writeline(f"context.eval_ctx.revert({old_ctx_name})") diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/jinja2/constants.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/jinja2/constants.py new file mode 100644 index 000000000..41a1c23b0 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/jinja2/constants.py @@ -0,0 +1,20 @@ +#: list of lorem ipsum words used by the lipsum() helper function +LOREM_IPSUM_WORDS = """\ +a ac accumsan ad adipiscing aenean aliquam aliquet amet ante aptent arcu at +auctor augue bibendum blandit class commodo condimentum congue consectetuer +consequat conubia convallis cras cubilia cum curabitur curae cursus dapibus +diam dictum dictumst dignissim dis dolor donec dui duis egestas eget eleifend +elementum elit enim erat eros est et etiam eu euismod facilisi facilisis fames +faucibus felis fermentum feugiat fringilla fusce gravida habitant habitasse hac +hendrerit hymenaeos iaculis id imperdiet in inceptos integer interdum ipsum +justo lacinia lacus laoreet lectus leo libero ligula litora lobortis lorem +luctus maecenas magna magnis malesuada massa mattis mauris metus mi molestie +mollis montes morbi mus nam nascetur natoque nec neque netus nibh nisi nisl non +nonummy nostra nulla nullam nunc odio orci ornare parturient pede pellentesque +penatibus per pharetra phasellus placerat platea porta porttitor posuere +potenti praesent pretium primis proin pulvinar purus quam quis quisque rhoncus +ridiculus risus rutrum sagittis sapien scelerisque sed sem semper senectus sit +sociis sociosqu sodales sollicitudin suscipit suspendisse taciti tellus tempor +tempus tincidunt torquent tortor tristique turpis ullamcorper ultrices +ultricies urna ut varius vehicula vel velit venenatis vestibulum vitae vivamus +viverra volutpat vulputate""" diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/jinja2/debug.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/jinja2/debug.py new file mode 100644 index 000000000..eeeeee78b --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/jinja2/debug.py @@ -0,0 +1,191 @@ +import sys +import typing as t +from types import CodeType +from types import TracebackType + +from .exceptions import TemplateSyntaxError +from .utils import internal_code +from .utils import missing + +if t.TYPE_CHECKING: + from .runtime import Context + + +def rewrite_traceback_stack(source: t.Optional[str] = None) -> BaseException: + """Rewrite the current exception to replace any tracebacks from + within compiled template code with tracebacks that look like they + came from the template source. + + This must be called within an ``except`` block. + + :param source: For ``TemplateSyntaxError``, the original source if + known. + :return: The original exception with the rewritten traceback. + """ + _, exc_value, tb = sys.exc_info() + exc_value = t.cast(BaseException, exc_value) + tb = t.cast(TracebackType, tb) + + if isinstance(exc_value, TemplateSyntaxError) and not exc_value.translated: + exc_value.translated = True + exc_value.source = source + # Remove the old traceback, otherwise the frames from the + # compiler still show up. + exc_value.with_traceback(None) + # Outside of runtime, so the frame isn't executing template + # code, but it still needs to point at the template. + tb = fake_traceback( + exc_value, None, exc_value.filename or "", exc_value.lineno + ) + else: + # Skip the frame for the render function. + tb = tb.tb_next + + stack = [] + + # Build the stack of traceback object, replacing any in template + # code with the source file and line information. + while tb is not None: + # Skip frames decorated with @internalcode. These are internal + # calls that aren't useful in template debugging output. + if tb.tb_frame.f_code in internal_code: + tb = tb.tb_next + continue + + template = tb.tb_frame.f_globals.get("__jinja_template__") + + if template is not None: + lineno = template.get_corresponding_lineno(tb.tb_lineno) + fake_tb = fake_traceback(exc_value, tb, template.filename, lineno) + stack.append(fake_tb) + else: + stack.append(tb) + + tb = tb.tb_next + + tb_next = None + + # Assign tb_next in reverse to avoid circular references. + for tb in reversed(stack): + tb.tb_next = tb_next + tb_next = tb + + return exc_value.with_traceback(tb_next) + + +def fake_traceback( # type: ignore + exc_value: BaseException, tb: t.Optional[TracebackType], filename: str, lineno: int +) -> TracebackType: + """Produce a new traceback object that looks like it came from the + template source instead of the compiled code. The filename, line + number, and location name will point to the template, and the local + variables will be the current template context. + + :param exc_value: The original exception to be re-raised to create + the new traceback. + :param tb: The original traceback to get the local variables and + code info from. + :param filename: The template filename. + :param lineno: The line number in the template source. + """ + if tb is not None: + # Replace the real locals with the context that would be + # available at that point in the template. + locals = get_template_locals(tb.tb_frame.f_locals) + locals.pop("__jinja_exception__", None) + else: + locals = {} + + globals = { + "__name__": filename, + "__file__": filename, + "__jinja_exception__": exc_value, + } + # Raise an exception at the correct line number. + code: CodeType = compile( + "\n" * (lineno - 1) + "raise __jinja_exception__", filename, "exec" + ) + + # Build a new code object that points to the template file and + # replaces the location with a block name. + location = "template" + + if tb is not None: + function = tb.tb_frame.f_code.co_name + + if function == "root": + location = "top-level template code" + elif function.startswith("block_"): + location = f"block {function[6:]!r}" + + if sys.version_info >= (3, 8): + code = code.replace(co_name=location) + else: + code = CodeType( + code.co_argcount, + code.co_kwonlyargcount, + code.co_nlocals, + code.co_stacksize, + code.co_flags, + code.co_code, + code.co_consts, + code.co_names, + code.co_varnames, + code.co_filename, + location, + code.co_firstlineno, + code.co_lnotab, + code.co_freevars, + code.co_cellvars, + ) + + # Execute the new code, which is guaranteed to raise, and return + # the new traceback without this frame. + try: + exec(code, globals, locals) + except BaseException: + return sys.exc_info()[2].tb_next # type: ignore + + +def get_template_locals(real_locals: t.Mapping[str, t.Any]) -> t.Dict[str, t.Any]: + """Based on the runtime locals, get the context that would be + available at that point in the template. + """ + # Start with the current template context. + ctx: t.Optional[Context] = real_locals.get("context") + + if ctx is not None: + data: t.Dict[str, t.Any] = ctx.get_all().copy() + else: + data = {} + + # Might be in a derived context that only sets local variables + # rather than pushing a context. Local variables follow the scheme + # l_depth_name. Find the highest-depth local that has a value for + # each name. + local_overrides: t.Dict[str, t.Tuple[int, t.Any]] = {} + + for name, value in real_locals.items(): + if not name.startswith("l_") or value is missing: + # Not a template variable, or no longer relevant. + continue + + try: + _, depth_str, name = name.split("_", 2) + depth = int(depth_str) + except ValueError: + continue + + cur_depth = local_overrides.get(name, (-1,))[0] + + if cur_depth < depth: + local_overrides[name] = (depth, value) + + # Modify the context with any derived context. + for name, (_, value) in local_overrides.items(): + if value is missing: + data.pop(name, None) + else: + data[name] = value + + return data diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/jinja2/defaults.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/jinja2/defaults.py new file mode 100644 index 000000000..638cad3d2 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/jinja2/defaults.py @@ -0,0 +1,48 @@ +import typing as t + +from .filters import FILTERS as DEFAULT_FILTERS # noqa: F401 +from .tests import TESTS as DEFAULT_TESTS # noqa: F401 +from .utils import Cycler +from .utils import generate_lorem_ipsum +from .utils import Joiner +from .utils import Namespace + +if t.TYPE_CHECKING: + import typing_extensions as te + +# defaults for the parser / lexer +BLOCK_START_STRING = "{%" +BLOCK_END_STRING = "%}" +VARIABLE_START_STRING = "{{" +VARIABLE_END_STRING = "}}" +COMMENT_START_STRING = "{#" +COMMENT_END_STRING = "#}" +LINE_STATEMENT_PREFIX: t.Optional[str] = None +LINE_COMMENT_PREFIX: t.Optional[str] = None +TRIM_BLOCKS = False +LSTRIP_BLOCKS = False +NEWLINE_SEQUENCE: "te.Literal['\\n', '\\r\\n', '\\r']" = "\n" +KEEP_TRAILING_NEWLINE = False + +# default filters, tests and namespace + +DEFAULT_NAMESPACE = { + "range": range, + "dict": dict, + "lipsum": generate_lorem_ipsum, + "cycler": Cycler, + "joiner": Joiner, + "namespace": Namespace, +} + +# default policies +DEFAULT_POLICIES: t.Dict[str, t.Any] = { + "compiler.ascii_str": True, + "urlize.rel": "noopener", + "urlize.target": None, + "urlize.extra_schemes": None, + "truncate.leeway": 5, + "json.dumps_function": None, + "json.dumps_kwargs": {"sort_keys": True}, + "ext.i18n.trimmed": False, +} diff --git a/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/jinja2/environment.py b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/jinja2/environment.py new file mode 100644 index 000000000..0fc6e5be8 --- /dev/null +++ b/Python/Flask_Blog/11-Blueprints/venv/lib/python3.12/site-packages/jinja2/environment.py @@ -0,0 +1,1672 @@ +"""Classes for managing templates and their runtime and compile time +options. +""" + +import os +import typing +import typing as t +import weakref +from collections import ChainMap +from functools import lru_cache +from functools import partial +from functools import reduce +from types import CodeType + +from markupsafe import Markup + +from . import nodes +from .compiler import CodeGenerator +from .compiler import generate +from .defaults import BLOCK_END_STRING +from .defaults import BLOCK_START_STRING +from .defaults import COMMENT_END_STRING +from .defaults import COMMENT_START_STRING +from .defaults import DEFAULT_FILTERS # type: ignore[attr-defined] +from .defaults import DEFAULT_NAMESPACE +from .defaults import DEFAULT_POLICIES +from .defaults import DEFAULT_TESTS # type: ignore[attr-defined] +from .defaults import KEEP_TRAILING_NEWLINE +from .defaults import LINE_COMMENT_PREFIX +from .defaults import LINE_STATEMENT_PREFIX +from .defaults import LSTRIP_BLOCKS +from .defaults import NEWLINE_SEQUENCE +from .defaults import TRIM_BLOCKS +from .defaults import VARIABLE_END_STRING +from .defaults import VARIABLE_START_STRING +from .exceptions import TemplateNotFound +from .exceptions import TemplateRuntimeError +from .exceptions import TemplatesNotFound +from .exceptions import TemplateSyntaxError +from .exceptions import UndefinedError +from .lexer import get_lexer +from .lexer import Lexer +from .lexer import TokenStream +from .nodes import EvalContext +from .parser import Parser +from .runtime import Context +from .runtime import new_context +from .runtime import Undefined +from .utils import _PassArg +from .utils import concat +from .utils import consume +from .utils import import_string +from .utils import internalcode +from .utils import LRUCache +from .utils import missing + +if t.TYPE_CHECKING: + import typing_extensions as te + + from .bccache import BytecodeCache + from .ext import Extension + from .loaders import BaseLoader + +_env_bound = t.TypeVar("_env_bound", bound="Environment") + + +# for direct template usage we have up to ten living environments +@lru_cache(maxsize=10) +def get_spontaneous_environment(cls: t.Type[_env_bound], *args: t.Any) -> _env_bound: + """Return a new spontaneous environment. A spontaneous environment + is used for templates created directly rather than through an + existing environment. + + :param cls: Environment class to create. + :param args: Positional arguments passed to environment. + """ + env = cls(*args) + env.shared = True + return env + + +def create_cache( + size: int, +) -> t.Optional[t.MutableMapping[t.Tuple["weakref.ref[t.Any]", str], "Template"]]: + """Return the cache class for the given size.""" + if size == 0: + return None + + if size < 0: + return {} + + return LRUCache(size) # type: ignore + + +def copy_cache( + cache: t.Optional[t.MutableMapping[t.Any, t.Any]], +) -> t.Optional[t.MutableMapping[t.Tuple["weakref.ref[t.Any]", str], "Template"]]: + """Create an empty copy of the given cache.""" + if cache is None: + return None + + if type(cache) is dict: # noqa E721 + return {} + + return LRUCache(cache.capacity) # type: ignore + + +def load_extensions( + environment: "Environment", + extensions: t.Sequence[t.Union[str, t.Type["Extension"]]], +) -> t.Dict[str, "Extension"]: + """Load the extensions from the list and bind it to the environment. + Returns a dict of instantiated extensions. + """ + result = {} + + for extension in extensions: + if isinstance(extension, str): + extension = t.cast(t.Type["Extension"], import_string(extension)) + + result[extension.identifier] = extension(environment) + + return result + + +def _environment_config_check(environment: _env_bound) -> _env_bound: + """Perform a sanity check on the environment.""" + assert issubclass( + environment.undefined, Undefined + ), "'undefined' must be a subclass of 'jinja2.Undefined'." + assert ( + environment.block_start_string + != environment.variable_start_string + != environment.comment_start_string + ), "block, variable and comment start strings must be different." + assert environment.newline_sequence in { + "\r", + "\r\n", + "\n", + }, "'newline_sequence' must be one of '\\n', '\\r\\n', or '\\r'." + return environment + + +class Environment: + r"""The core component of Jinja is the `Environment`. It contains + important shared variables like configuration, filters, tests, + globals and others. Instances of this class may be modified if + they are not shared and if no template was loaded so far. + Modifications on environments after the first template was loaded + will lead to surprising effects and undefined behavior. + + Here are the possible initialization parameters: + + `block_start_string` + The string marking the beginning of a block. Defaults to ``'{%'``. + + `block_end_string` + The string marking the end of a block. Defaults to ``'%}'``. + + `variable_start_string` + The string marking the beginning of a print statement. + Defaults to ``'{{'``. + + `variable_end_string` + The string marking the end of a print statement. Defaults to + ``'}}'``. + + `comment_start_string` + The string marking the beginning of a comment. Defaults to ``'{#'``. + + `comment_end_string` + The string marking the end of a comment. Defaults to ``'#}'``. + + `line_statement_prefix` + If given and a string, this will be used as prefix for line based + statements. See also :ref:`line-statements`. + + `line_comment_prefix` + If given and a string, this will be used as prefix for line based + comments. See also :ref:`line-statements`. + + .. versionadded:: 2.2 + + `trim_blocks` + If this is set to ``True`` the first newline after a block is + removed (block, not variable tag!). Defaults to `False`. + + `lstrip_blocks` + If this is set to ``True`` leading spaces and tabs are stripped + from the start of a line to a block. Defaults to `False`. + + `newline_sequence` + The sequence that starts a newline. Must be one of ``'\r'``, + ``'\n'`` or ``'\r\n'``. The default is ``'\n'`` which is a + useful default for Linux and OS X systems as well as web + applications. + + `keep_trailing_newline` + Preserve the trailing newline when rendering templates. + The default is ``False``, which causes a single newline, + if present, to be stripped from the end of the template. + + .. versionadded:: 2.7 + + `extensions` + List of Jinja extensions to use. This can either be import paths + as strings or extension classes. For more information have a + look at :ref:`the extensions documentation `. + + `optimized` + should the optimizer be enabled? Default is ``True``. + + `undefined` + :class:`Undefined` or a subclass of it that is used to represent + undefined values in the template. + + `finalize` + A callable that can be used to process the result of a variable + expression before it is output. For example one can convert + ``None`` implicitly into an empty string here. + + `autoescape` + If set to ``True`` the XML/HTML autoescaping feature is enabled by + default. For more details about autoescaping see + :class:`~markupsafe.Markup`. As of Jinja 2.4 this can also + be a callable that is passed the template name and has to + return ``True`` or ``False`` depending on autoescape should be + enabled by default. + + .. versionchanged:: 2.4 + `autoescape` can now be a function + + `loader` + The template loader for this environment. + + `cache_size` + The size of the cache. Per default this is ``400`` which means + that if more than 400 templates are loaded the loader will clean + out the least recently used template. If the cache size is set to + ``0`` templates are recompiled all the time, if the cache size is + ``-1`` the cache will not be cleaned. + + .. versionchanged:: 2.8 + The cache size was increased to 400 from a low 50. + + `auto_reload` + Some loaders load templates from locations where the template + sources may change (ie: file system or database). If + ``auto_reload`` is set to ``True`` (default) every time a template is + requested the loader checks if the source changed and if yes, it + will reload the template. For higher performance it's possible to + disable that. + + `bytecode_cache` + If set to a bytecode cache object, this object will provide a + cache for the internal Jinja bytecode so that templates don't + have to be parsed if they were not changed. + + See :ref:`bytecode-cache` for more information. + + `enable_async` + If set to true this enables async template execution which + allows using async functions and generators. + """ + + #: if this environment is sandboxed. Modifying this variable won't make + #: the environment sandboxed though. For a real sandboxed environment + #: have a look at jinja2.sandbox. This flag alone controls the code + #: generation by the compiler. + sandboxed = False + + #: True if the environment is just an overlay + overlayed = False + + #: the environment this environment is linked to if it is an overlay + linked_to: t.Optional["Environment"] = None + + #: shared environments have this set to `True`. A shared environment + #: must not be modified + shared = False + + #: the class that is used for code generation. See + #: :class:`~jinja2.compiler.CodeGenerator` for more information. + code_generator_class: t.Type["CodeGenerator"] = CodeGenerator + + concat = "".join + + #: the context class that is used for templates. See + #: :class:`~jinja2.runtime.Context` for more information. + context_class: t.Type[Context] = Context + + template_class: t.Type["Template"] + + def __init__( + self, + block_start_string: str = BLOCK_START_STRING, + block_end_string: str = BLOCK_END_STRING, + variable_start_string: str = VARIABLE_START_STRING, + variable_end_string: str = VARIABLE_END_STRING, + comment_start_string: str = COMMENT_START_STRING, + comment_end_string: str = COMMENT_END_STRING, + line_statement_prefix: t.Optional[str] = LINE_STATEMENT_PREFIX, + line_comment_prefix: t.Optional[str] = LINE_COMMENT_PREFIX, + trim_blocks: bool = TRIM_BLOCKS, + lstrip_blocks: bool = LSTRIP_BLOCKS, + newline_sequence: "te.Literal['\\n', '\\r\\n', '\\r']" = NEWLINE_SEQUENCE, + keep_trailing_newline: bool = KEEP_TRAILING_NEWLINE, + extensions: t.Sequence[t.Union[str, t.Type["Extension"]]] = (), + optimized: bool = True, + undefined: t.Type[Undefined] = Undefined, + finalize: t.Optional[t.Callable[..., t.Any]] = None, + autoescape: t.Union[bool, t.Callable[[t.Optional[str]], bool]] = False, + loader: t.Optional["BaseLoader"] = None, + cache_size: int = 400, + auto_reload: bool = True, + bytecode_cache: t.Optional["BytecodeCache"] = None, + enable_async: bool = False, + ): + # !!Important notice!! + # The constructor accepts quite a few arguments that should be + # passed by keyword rather than position. However it's important to + # not change the order of arguments because it's used at least + # internally in those cases: + # - spontaneous environments (i18n extension and Template) + # - unittests + # If parameter changes are required only add parameters at the end + # and don't change the arguments (or the defaults!) of the arguments + # existing already. + + # lexer / parser information + self.block_start_string = block_start_string + self.block_end_string = block_end_string + self.variable_start_string = variable_start_string + self.variable_end_string = variable_end_string + self.comment_start_string = comment_start_string + self.comment_end_string = comment_end_string + self.line_statement_prefix = line_statement_prefix + self.line_comment_prefix = line_comment_prefix + self.trim_blocks = trim_blocks + self.lstrip_blocks = lstrip_blocks + self.newline_sequence = newline_sequence + self.keep_trailing_newline = keep_trailing_newline + + # runtime information + self.undefined: t.Type[Undefined] = undefined + self.optimized = optimized + self.finalize = finalize + self.autoescape = autoescape + + # defaults + self.filters = DEFAULT_FILTERS.copy() + self.tests = DEFAULT_TESTS.copy() + self.globals = DEFAULT_NAMESPACE.copy() + + # set the loader provided + self.loader = loader + self.cache = create_cache(cache_size) + self.bytecode_cache = bytecode_cache + self.auto_reload = auto_reload + + # configurable policies + self.policies = DEFAULT_POLICIES.copy() + + # load extensions + self.extensions = load_extensions(self, extensions) + + self.is_async = enable_async + _environment_config_check(self) + + def add_extension(self, extension: t.Union[str, t.Type["Extension"]]) -> None: + """Adds an extension after the environment was created. + + .. versionadded:: 2.5 + """ + self.extensions.update(load_extensions(self, [extension])) + + def extend(self, **attributes: t.Any) -> None: + """Add the items to the instance of the environment if they do not exist + yet. This is used by :ref:`extensions ` to register + callbacks and configuration values without breaking inheritance. + """ + for key, value in attributes.items(): + if not hasattr(self, key): + setattr(self, key, value) + + def overlay( + self, + block_start_string: str = missing, + block_end_string: str = missing, + variable_start_string: str = missing, + variable_end_string: str = missing, + comment_start_string: str = missing, + comment_end_string: str = missing, + line_statement_prefix: t.Optional[str] = missing, + line_comment_prefix: t.Optional[str] = missing, + trim_blocks: bool = missing, + lstrip_blocks: bool = missing, + newline_sequence: "te.Literal['\\n', '\\r\\n', '\\r']" = missing, + keep_trailing_newline: bool = missing, + extensions: t.Sequence[t.Union[str, t.Type["Extension"]]] = missing, + optimized: bool = missing, + undefined: t.Type[Undefined] = missing, + finalize: t.Optional[t.Callable[..., t.Any]] = missing, + autoescape: t.Union[bool, t.Callable[[t.Optional[str]], bool]] = missing, + loader: t.Optional["BaseLoader"] = missing, + cache_size: int = missing, + auto_reload: bool = missing, + bytecode_cache: t.Optional["BytecodeCache"] = missing, + enable_async: bool = missing, + ) -> "te.Self": + """Create a new overlay environment that shares all the data with the + current environment except for cache and the overridden attributes. + Extensions cannot be removed for an overlayed environment. An overlayed + environment automatically gets all the extensions of the environment it + is linked to plus optional extra extensions. + + Creating overlays should happen after the initial environment was set + up completely. Not all attributes are truly linked, some are just + copied over so modifications on the original environment may not shine + through. + + .. versionchanged:: 3.1.5 + ``enable_async`` is applied correctly. + + .. versionchanged:: 3.1.2 + Added the ``newline_sequence``, ``keep_trailing_newline``, + and ``enable_async`` parameters to match ``__init__``. + """ + args = dict(locals()) + del args["self"], args["cache_size"], args["extensions"], args["enable_async"] + + rv = object.__new__(self.__class__) + rv.__dict__.update(self.__dict__) + rv.overlayed = True + rv.linked_to = self + + for key, value in args.items(): + if value is not missing: + setattr(rv, key, value) + + if cache_size is not missing: + rv.cache = create_cache(cache_size) + else: + rv.cache = copy_cache(self.cache) + + rv.extensions = {} + for key, value in self.extensions.items(): + rv.extensions[key] = value.bind(rv) + if extensions is not missing: + rv.extensions.update(load_extensions(rv, extensions)) + + if enable_async is not missing: + rv.is_async = enable_async + + return _environment_config_check(rv) + + @property + def lexer(self) -> Lexer: + """The lexer for this environment.""" + return get_lexer(self) + + def iter_extensions(self) -> t.Iterator["Extension"]: + """Iterates over the extensions by priority.""" + return iter(sorted(self.extensions.values(), key=lambda x: x.priority)) + + def getitem( + self, obj: t.Any, argument: t.Union[str, t.Any] + ) -> t.Union[t.Any, Undefined]: + """Get an item or attribute of an object but prefer the item.""" + try: + return obj[argument] + except (AttributeError, TypeError, LookupError): + if isinstance(argument, str): + try: + attr = str(argument) + except Exception: + pass + else: + try: + return getattr(obj, attr) + except AttributeError: + pass + return self.undefined(obj=obj, name=argument) + + def getattr(self, obj: t.Any, attribute: str) -> t.Any: + """Get an item or attribute of an object but prefer the attribute. + Unlike :meth:`getitem` the attribute *must* be a string. + """ + try: + return getattr(obj, attribute) + except AttributeError: + pass + try: + return obj[attribute] + except (TypeError, LookupError, AttributeError): + return self.undefined(obj=obj, name=attribute) + + def _filter_test_common( + self, + name: t.Union[str, Undefined], + value: t.Any, + args: t.Optional[t.Sequence[t.Any]], + kwargs: t.Optional[t.Mapping[str, t.Any]], + context: t.Optional[Context], + eval_ctx: t.Optional[EvalContext], + is_filter: bool, + ) -> t.Any: + if is_filter: + env_map = self.filters + type_name = "filter" + else: + env_map = self.tests + type_name = "test" + + func = env_map.get(name) # type: ignore + + if func is None: + msg = f"No {type_name} named {name!r}." + + if isinstance(name, Undefined): + try: + name._fail_with_undefined_error() + except Exception as e: + msg = f"{msg} ({e}; did you forget to quote the callable name?)" + + raise TemplateRuntimeError(msg) + + args = [value, *(args if args is not None else ())] + kwargs = kwargs if kwargs is not None else {} + pass_arg = _PassArg.from_obj(func) + + if pass_arg is _PassArg.context: + if context is None: + raise TemplateRuntimeError( + f"Attempted to invoke a context {type_name} without context." + ) + + args.insert(0, context) + elif pass_arg is _PassArg.eval_context: + if eval_ctx is None: + if context is not None: + eval_ctx = context.eval_ctx + else: + eval_ctx = EvalContext(self) + + args.insert(0, eval_ctx) + elif pass_arg is _PassArg.environment: + args.insert(0, self) + + return func(*args, **kwargs) + + def call_filter( + self, + name: str, + value: t.Any, + args: t.Optional[t.Sequence[t.Any]] = None, + kwargs: t.Optional[t.Mapping[str, t.Any]] = None, + context: t.Optional[Context] = None, + eval_ctx: t.Optional[EvalContext] = None, + ) -> t.Any: + """Invoke a filter on a value the same way the compiler does. + + This might return a coroutine if the filter is running from an + environment in async mode and the filter supports async + execution. It's your responsibility to await this if needed. + + .. versionadded:: 2.7 + """ + return self._filter_test_common( + name, value, args, kwargs, context, eval_ctx, True + ) + + def call_test( + self, + name: str, + value: t.Any, + args: t.Optional[t.Sequence[t.Any]] = None, + kwargs: t.Optional[t.Mapping[str, t.Any]] = None, + context: t.Optional[Context] = None, + eval_ctx: t.Optional[EvalContext] = None, + ) -> t.Any: + """Invoke a test on a value the same way the compiler does. + + This might return a coroutine if the test is running from an + environment in async mode and the test supports async execution. + It's your responsibility to await this if needed. + + .. versionchanged:: 3.0 + Tests support ``@pass_context``, etc. decorators. Added + the ``context`` and ``eval_ctx`` parameters. + + .. versionadded:: 2.7 + """ + return self._filter_test_common( + name, value, args, kwargs, context, eval_ctx, False + ) + + @internalcode + def parse( + self, + source: str, + name: t.Optional[str] = None, + filename: t.Optional[str] = None, + ) -> nodes.Template: + """Parse the sourcecode and return the abstract syntax tree. This + tree of nodes is used by the compiler to convert the template into + executable source- or bytecode. This is useful for debugging or to + extract information from templates. + + If you are :ref:`developing Jinja extensions ` + this gives you a good overview of the node tree generated. + """ + try: + return self._parse(source, name, filename) + except TemplateSyntaxError: + self.handle_exception(source=source) + + def _parse( + self, source: str, name: t.Optional[str], filename: t.Optional[str] + ) -> nodes.Template: + """Internal parsing function used by `parse` and `compile`.""" + return Parser(self, source, name, filename).parse() + + def lex( + self, + source: str, + name: t.Optional[str] = None, + filename: t.Optional[str] = None, + ) -> t.Iterator[t.Tuple[int, str, str]]: + """Lex the given sourcecode and return a generator that yields + tokens as tuples in the form ``(lineno, token_type, value)``. + This can be useful for :ref:`extension development ` + and debugging templates. + + This does not perform preprocessing. If you want the preprocessing + of the extensions to be applied you have to filter source through + the :meth:`preprocess` method. + """ + source = str(source) + try: + return self.lexer.tokeniter(source, name, filename) + except TemplateSyntaxError: + self.handle_exception(source=source) + + def preprocess( + self, + source: str, + name: t.Optional[str] = None, + filename: t.Optional[str] = None, + ) -> str: + """Preprocesses the source with all extensions. This is automatically + called for all parsing and compiling methods but *not* for :meth:`lex` + because there you usually only want the actual source tokenized. + """ + return reduce( + lambda s, e: e.preprocess(s, name, filename), + self.iter_extensions(), + str(source), + ) + + def _tokenize( + self, + source: str, + name: t.Optional[str], + filename: t.Optional[str] = None, + state: t.Optional[str] = None, + ) -> TokenStream: + """Called by the parser to do the preprocessing and filtering + for all the extensions. Returns a :class:`~jinja2.lexer.TokenStream`. + """ + source = self.preprocess(source, name, filename) + stream = self.lexer.tokenize(source, name, filename, state) + + for ext in self.iter_extensions(): + stream = ext.filter_stream(stream) # type: ignore + + if not isinstance(stream, TokenStream): + stream = TokenStream(stream, name, filename) + + return stream + + def _generate( + self, + source: nodes.Template, + name: t.Optional[str], + filename: t.Optional[str], + defer_init: bool = False, + ) -> str: + """Internal hook that can be overridden to hook a different generate + method in. + + .. versionadded:: 2.5 + """ + return generate( # type: ignore + source, + self, + name, + filename, + defer_init=defer_init, + optimized=self.optimized, + ) + + def _compile(self, source: str, filename: str) -> CodeType: + """Internal hook that can be overridden to hook a different compile + method in. + + .. versionadded:: 2.5 + """ + return compile(source, filename, "exec") + + @typing.overload + def compile( + self, + source: t.Union[str, nodes.Template], + name: t.Optional[str] = None, + filename: t.Optional[str] = None, + raw: "te.Literal[False]" = False, + defer_init: bool = False, + ) -> CodeType: ... + + @typing.overload + def compile( + self, + source: t.Union[str, nodes.Template], + name: t.Optional[str] = None, + filename: t.Optional[str] = None, + raw: "te.Literal[True]" = ..., + defer_init: bool = False, + ) -> str: ... + + @internalcode + def compile( + self, + source: t.Union[str, nodes.Template], + name: t.Optional[str] = None, + filename: t.Optional[str] = None, + raw: bool = False, + defer_init: bool = False, + ) -> t.Union[str, CodeType]: + """Compile a node or template source code. The `name` parameter is + the load name of the template after it was joined using + :meth:`join_path` if necessary, not the filename on the file system. + the `filename` parameter is the estimated filename of the template on + the file system. If the template came from a database or memory this + can be omitted. + + The return value of this method is a python code object. If the `raw` + parameter is `True` the return value will be a string with python + code equivalent to the bytecode returned otherwise. This method is + mainly used internally. + + `defer_init` is use internally to aid the module code generator. This + causes the generated code to be able to import without the global + environment variable to be set. + + .. versionadded:: 2.4 + `defer_init` parameter added. + """ + source_hint = None + try: + if isinstance(source, str): + source_hint = source + source = self._parse(source, name, filename) + source = self._generate(source, name, filename, defer_init=defer_init) + if raw: + return source + if filename is None: + filename = "