bialy-dataset / coderank /units /requests.jsonl
paintedwolf-ai's picture
Release open1-b5-e4-bialy
24918f7 verified
Raw History Blame Contribute Delete
353 kB
{"repo":"requests","file":"AUTHORS.rst","line":3,"symbol":"Requests Maintainers","kind":"section","lang":"rst","code":"Requests Maintainers\n````````````````````"}
{"repo":"requests","file":"AUTHORS.rst","line":9,"symbol":"Previous Maintainers","kind":"section","lang":"rst","code":"Previous Maintainers\n````````````````````"}
{"repo":"requests","file":"AUTHORS.rst","line":16,"symbol":"Patches and Suggestions","kind":"section","lang":"rst","code":"Patches and Suggestions\n```````````````````````"}
{"repo":"requests","file":"Makefile","line":1,"symbol":".PHONY","kind":"target","lang":"make","code":".PHONY: docs"}
{"repo":"requests","file":"Makefile","line":2,"symbol":"init","kind":"target","lang":"make","code":"init:\n\tpython -m pip install -r requirements-dev.txt"}
{"repo":"requests","file":"Makefile","line":4,"symbol":"test","kind":"target","lang":"make","code":"test:\n\tpython -m pytest tests"}
{"repo":"requests","file":"Makefile","line":7,"symbol":"ci","kind":"target","lang":"make","code":"ci:\n\tpython -m pytest tests --junitxml=report.xml"}
{"repo":"requests","file":"Makefile","line":10,"symbol":"test-readme","kind":"target","lang":"make","code":"test-readme:\n\tpython setup.py check --restructuredtext --strict && ([ $$? -eq 0 ] && echo \"README.rst and HISTORY.rst ok\") || echo \"Invalid markup in README.rst or HISTORY.rst!\""}
{"repo":"requests","file":"Makefile","line":13,"symbol":"coverage","kind":"target","lang":"make","code":"coverage:\n\tpython -m pytest --cov-config .coveragerc --verbose --cov-report term --cov-report xml --cov=src/requests tests"}
{"repo":"requests","file":"Makefile","line":16,"symbol":".publishenv","kind":"target","lang":"make","code":".publishenv:\n\tpython -m venv .publishenv\n\t.publishenv/bin/pip install 'twine>=1.5.0' build"}
{"repo":"requests","file":"Makefile","line":20,"symbol":"publish","kind":"target","lang":"make","code":"publish: .publishenv\n\t.publishenv/bin/python -m build\n\t.publishenv/bin/python -m twine upload --skip-existing dist/*\n\trm -fr build dist .egg requests.egg-info"}
{"repo":"requests","file":"Makefile","line":25,"symbol":"docs","kind":"target","lang":"make","code":"docs:\n\tcd docs && make html\n\t@echo \"\\033[95m\\n\\nBuild successful! View the docs homepage at docs/_build/html/index.html.\\n\\033[0m\""}
{"repo":"requests","file":"docs/Makefile","line":5,"symbol":"SPHINXOPTS","kind":"variable","lang":"make","code":"SPHINXOPTS ="}
{"repo":"requests","file":"docs/Makefile","line":6,"symbol":"SPHINXBUILD","kind":"variable","lang":"make","code":"SPHINXBUILD = sphinx-build"}
{"repo":"requests","file":"docs/Makefile","line":7,"symbol":"PAPER","kind":"variable","lang":"make","code":"PAPER ="}
{"repo":"requests","file":"docs/Makefile","line":8,"symbol":"BUILDDIR","kind":"variable","lang":"make","code":"BUILDDIR = _build"}
{"repo":"requests","file":"docs/Makefile","line":16,"symbol":"PAPEROPT_a4","kind":"variable","lang":"make","code":"PAPEROPT_a4 = -D latex_paper_size=a4"}
{"repo":"requests","file":"docs/Makefile","line":17,"symbol":"PAPEROPT_letter","kind":"variable","lang":"make","code":"PAPEROPT_letter = -D latex_paper_size=letter"}
{"repo":"requests","file":"docs/Makefile","line":18,"symbol":"ALLSPHINXOPTS","kind":"variable","lang":"make","code":"ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) ."}
{"repo":"requests","file":"docs/Makefile","line":20,"symbol":"I18NSPHINXOPTS","kind":"variable","lang":"make","code":"I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) ."}
{"repo":"requests","file":"docs/Makefile","line":22,"symbol":".PHONY","kind":"target","lang":"make","code":".PHONY: help"}
{"repo":"requests","file":"docs/Makefile","line":23,"symbol":"help","kind":"target","lang":"make","code":"help:\n\t@echo \"Please use \\`make <target>' where <target> is one of\"\n\t@echo \" html to make standalone HTML files\"\n\t@echo \" dirhtml to make HTML files named index.html in directories\"\n\t@echo \" singlehtml to make a single large HTML file\"\n\t@echo \" pickle to make pickle files\"\n\t@echo \" json to make JSON files\"\n\t@echo \" htmlhelp to make HTML files and a HTML help project\"\n\t@echo \" qthelp to make HTML files and a qthelp project\"\n\t@echo \" applehelp to make an Apple Help Book\"\n\t@echo \" devhelp to make HTML files and a Devhelp project\"\n\t@echo \" epub to make an epub\"\n\t@echo \" latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter\"\n\t@echo \" latexpdf to make LaTeX files and run them through pdflatex\"\n\t@echo \" latexpdfja to make LaTeX files and run them through platex/dvipdfmx\"\n\t@echo \" text to make text files\"\n\t@echo \" man to make manual pages\"\n\t@echo \" texinfo to make Texinfo files\"\n\t@echo \" info to make Texinfo files and run them through makeinfo\"\n\t@echo \" gettext to make PO message catalogs\"\n\t@echo \" changes to make an overview of all changed/added/deprecated items\"\n\t@echo \" xml to make"}
{"repo":"requests","file":"docs/Makefile","line":50,"symbol":".PHONY","kind":"target","lang":"make","code":".PHONY: clean"}
{"repo":"requests","file":"docs/Makefile","line":51,"symbol":"clean","kind":"target","lang":"make","code":"clean:\n\trm -rf $(BUILDDIR)/*"}
{"repo":"requests","file":"docs/Makefile","line":54,"symbol":".PHONY","kind":"target","lang":"make","code":".PHONY: html"}
{"repo":"requests","file":"docs/Makefile","line":55,"symbol":"html","kind":"target","lang":"make","code":"html:\n\t$(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html\n\t@echo\n\t@echo \"Build finished. The HTML pages are in $(BUILDDIR)/html.\""}
{"repo":"requests","file":"docs/Makefile","line":60,"symbol":".PHONY","kind":"target","lang":"make","code":".PHONY: dirhtml"}
{"repo":"requests","file":"docs/Makefile","line":61,"symbol":"dirhtml","kind":"target","lang":"make","code":"dirhtml:\n\t$(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml\n\t@echo\n\t@echo \"Build finished. The HTML pages are in $(BUILDDIR)/dirhtml.\""}
{"repo":"requests","file":"docs/Makefile","line":66,"symbol":".PHONY","kind":"target","lang":"make","code":".PHONY: singlehtml"}
{"repo":"requests","file":"docs/Makefile","line":67,"symbol":"singlehtml","kind":"target","lang":"make","code":"singlehtml:\n\t$(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml\n\t@echo\n\t@echo \"Build finished. The HTML page is in $(BUILDDIR)/singlehtml.\""}
{"repo":"requests","file":"docs/Makefile","line":72,"symbol":".PHONY","kind":"target","lang":"make","code":".PHONY: pickle"}
{"repo":"requests","file":"docs/Makefile","line":73,"symbol":"pickle","kind":"target","lang":"make","code":"pickle:\n\t$(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle\n\t@echo\n\t@echo \"Build finished; now you can process the pickle files.\""}
{"repo":"requests","file":"docs/Makefile","line":78,"symbol":".PHONY","kind":"target","lang":"make","code":".PHONY: json"}
{"repo":"requests","file":"docs/Makefile","line":79,"symbol":"json","kind":"target","lang":"make","code":"json:\n\t$(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json\n\t@echo\n\t@echo \"Build finished; now you can process the JSON files.\""}
{"repo":"requests","file":"docs/Makefile","line":84,"symbol":".PHONY","kind":"target","lang":"make","code":".PHONY: htmlhelp"}
{"repo":"requests","file":"docs/Makefile","line":85,"symbol":"htmlhelp","kind":"target","lang":"make","code":"htmlhelp:\n\t$(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp\n\t@echo\n\t@echo \"Build finished; now you can run HTML Help Workshop with the\" \\\n\t \".hhp project file in $(BUILDDIR)/htmlhelp.\""}
{"repo":"requests","file":"docs/Makefile","line":91,"symbol":".PHONY","kind":"target","lang":"make","code":".PHONY: qthelp"}
{"repo":"requests","file":"docs/Makefile","line":92,"symbol":"qthelp","kind":"target","lang":"make","code":"qthelp:\n\t$(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp\n\t@echo\n\t@echo \"Build finished; now you can run \"qcollectiongenerator\" with the\" \\\n\t \".qhcp project file in $(BUILDDIR)/qthelp, like this:\"\n\t@echo \"# qcollectiongenerator $(BUILDDIR)/qthelp/Requests.qhcp\"\n\t@echo \"To view the help file:\"\n\t@echo \"# assistant -collectionFile $(BUILDDIR)/qthelp/Requests.qhc\""}
{"repo":"requests","file":"docs/Makefile","line":101,"symbol":".PHONY","kind":"target","lang":"make","code":".PHONY: applehelp"}
{"repo":"requests","file":"docs/Makefile","line":102,"symbol":"applehelp","kind":"target","lang":"make","code":"applehelp:\n\t$(SPHINXBUILD) -b applehelp $(ALLSPHINXOPTS) $(BUILDDIR)/applehelp\n\t@echo\n\t@echo \"Build finished. The help book is in $(BUILDDIR)/applehelp.\"\n\t@echo \"N.B. You won't be able to view it unless you put it in\" \\\n\t \"~/Library/Documentation/Help or install it in your application\" \\\n\t \"bundle.\""}
{"repo":"requests","file":"docs/Makefile","line":110,"symbol":".PHONY","kind":"target","lang":"make","code":".PHONY: devhelp"}
{"repo":"requests","file":"docs/Makefile","line":111,"symbol":"devhelp","kind":"target","lang":"make","code":"devhelp:\n\t$(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp\n\t@echo\n\t@echo \"Build finished.\"\n\t@echo \"To view the help file:\"\n\t@echo \"# mkdir -p $$HOME/.local/share/devhelp/Requests\"\n\t@echo \"# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/Requests\"\n\t@echo \"# devhelp\""}
{"repo":"requests","file":"docs/Makefile","line":120,"symbol":".PHONY","kind":"target","lang":"make","code":".PHONY: epub"}
{"repo":"requests","file":"docs/Makefile","line":121,"symbol":"epub","kind":"target","lang":"make","code":"epub:\n\t$(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub\n\t@echo\n\t@echo \"Build finished. The epub file is in $(BUILDDIR)/epub.\""}
{"repo":"requests","file":"docs/Makefile","line":126,"symbol":".PHONY","kind":"target","lang":"make","code":".PHONY: latex"}
{"repo":"requests","file":"docs/Makefile","line":127,"symbol":"latex","kind":"target","lang":"make","code":"latex:\n\t$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex\n\t@echo\n\t@echo \"Build finished; the LaTeX files are in $(BUILDDIR)/latex.\"\n\t@echo \"Run \\`make' in that directory to run these through (pdf)latex\" \\\n\t \"(use \\`make latexpdf' here to do that automatically).\""}
{"repo":"requests","file":"docs/Makefile","line":134,"symbol":".PHONY","kind":"target","lang":"make","code":".PHONY: latexpdf"}
{"repo":"requests","file":"docs/Makefile","line":135,"symbol":"latexpdf","kind":"target","lang":"make","code":"latexpdf:\n\t$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex\n\t@echo \"Running LaTeX files through pdflatex...\"\n\t$(MAKE) -C $(BUILDDIR)/latex all-pdf\n\t@echo \"pdflatex finished; the PDF files are in $(BUILDDIR)/latex.\""}
{"repo":"requests","file":"docs/Makefile","line":141,"symbol":".PHONY","kind":"target","lang":"make","code":".PHONY: latexpdfja"}
{"repo":"requests","file":"docs/Makefile","line":142,"symbol":"latexpdfja","kind":"target","lang":"make","code":"latexpdfja:\n\t$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex\n\t@echo \"Running LaTeX files through platex and dvipdfmx...\"\n\t$(MAKE) -C $(BUILDDIR)/latex all-pdf-ja\n\t@echo \"pdflatex finished; the PDF files are in $(BUILDDIR)/latex.\""}
{"repo":"requests","file":"docs/Makefile","line":148,"symbol":".PHONY","kind":"target","lang":"make","code":".PHONY: text"}
{"repo":"requests","file":"docs/Makefile","line":149,"symbol":"text","kind":"target","lang":"make","code":"text:\n\t$(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text\n\t@echo\n\t@echo \"Build finished. The text files are in $(BUILDDIR)/text.\""}
{"repo":"requests","file":"docs/Makefile","line":154,"symbol":".PHONY","kind":"target","lang":"make","code":".PHONY: man"}
{"repo":"requests","file":"docs/Makefile","line":155,"symbol":"man","kind":"target","lang":"make","code":"man:\n\t$(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man\n\t@echo\n\t@echo \"Build finished. The manual pages are in $(BUILDDIR)/man.\""}
{"repo":"requests","file":"docs/Makefile","line":160,"symbol":".PHONY","kind":"target","lang":"make","code":".PHONY: texinfo"}
{"repo":"requests","file":"docs/Makefile","line":161,"symbol":"texinfo","kind":"target","lang":"make","code":"texinfo:\n\t$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo\n\t@echo\n\t@echo \"Build finished. The Texinfo files are in $(BUILDDIR)/texinfo.\"\n\t@echo \"Run \\`make' in that directory to run these through makeinfo\" \\\n\t \"(use \\`make info' here to do that automatically).\""}
{"repo":"requests","file":"docs/Makefile","line":168,"symbol":".PHONY","kind":"target","lang":"make","code":".PHONY: info"}
{"repo":"requests","file":"docs/Makefile","line":169,"symbol":"info","kind":"target","lang":"make","code":"info:\n\t$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo\n\t@echo \"Running Texinfo files through makeinfo...\"\n\tmake -C $(BUILDDIR)/texinfo info\n\t@echo \"makeinfo finished; the Info files are in $(BUILDDIR)/texinfo.\""}
{"repo":"requests","file":"docs/Makefile","line":175,"symbol":".PHONY","kind":"target","lang":"make","code":".PHONY: gettext"}
{"repo":"requests","file":"docs/Makefile","line":176,"symbol":"gettext","kind":"target","lang":"make","code":"gettext:\n\t$(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale\n\t@echo\n\t@echo \"Build finished. The message catalogs are in $(BUILDDIR)/locale.\""}
{"repo":"requests","file":"docs/Makefile","line":181,"symbol":".PHONY","kind":"target","lang":"make","code":".PHONY: changes"}
{"repo":"requests","file":"docs/Makefile","line":182,"symbol":"changes","kind":"target","lang":"make","code":"changes:\n\t$(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes\n\t@echo\n\t@echo \"The overview file is in $(BUILDDIR)/changes.\""}
{"repo":"requests","file":"docs/Makefile","line":187,"symbol":".PHONY","kind":"target","lang":"make","code":".PHONY: linkcheck"}
{"repo":"requests","file":"docs/Makefile","line":188,"symbol":"linkcheck","kind":"target","lang":"make","code":"linkcheck:\n\t$(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck\n\t@echo\n\t@echo \"Link check complete; look for any errors in the above output \" \\\n\t \"or in $(BUILDDIR)/linkcheck/output.txt.\""}
{"repo":"requests","file":"docs/Makefile","line":194,"symbol":".PHONY","kind":"target","lang":"make","code":".PHONY: doctest"}
{"repo":"requests","file":"docs/Makefile","line":195,"symbol":"doctest","kind":"target","lang":"make","code":"doctest:\n\t$(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest\n\t@echo \"Testing of doctests in the sources finished, look at the \" \\\n\t \"results in $(BUILDDIR)/doctest/output.txt.\""}
{"repo":"requests","file":"docs/Makefile","line":200,"symbol":".PHONY","kind":"target","lang":"make","code":".PHONY: coverage"}
{"repo":"requests","file":"docs/Makefile","line":201,"symbol":"coverage","kind":"target","lang":"make","code":"coverage:\n\t$(SPHINXBUILD) -b coverage $(ALLSPHINXOPTS) $(BUILDDIR)/coverage\n\t@echo \"Testing of coverage in the sources finished, look at the \" \\\n\t \"results in $(BUILDDIR)/coverage/python.txt.\""}
{"repo":"requests","file":"docs/Makefile","line":206,"symbol":".PHONY","kind":"target","lang":"make","code":".PHONY: xml"}
{"repo":"requests","file":"docs/Makefile","line":207,"symbol":"xml","kind":"target","lang":"make","code":"xml:\n\t$(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml\n\t@echo\n\t@echo \"Build finished. The XML files are in $(BUILDDIR)/xml.\""}
{"repo":"requests","file":"docs/Makefile","line":212,"symbol":".PHONY","kind":"target","lang":"make","code":".PHONY: pseudoxml"}
{"repo":"requests","file":"docs/Makefile","line":213,"symbol":"pseudoxml","kind":"target","lang":"make","code":"pseudoxml:\n\t$(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml\n\t@echo\n\t@echo \"Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml.\""}
{"repo":"requests","file":"docs/_themes/flask_theme_support.py","line":7,"symbol":"FlaskyStyle","kind":"class","lang":"python","code":"class FlaskyStyle(Style):\n background_color = \"#f8f8f8\"\n default_style = \"\"\n\n styles = {\n # No corresponding class for the following:\n #Text: \"\", # class: ''\n Whitespace: \"underline #f8f8f8\", # class: 'w'\n Error: \"#a40000 border:#ef2929\", # class: 'err'\n Other: \"#000000\", # class 'x'\n\n Comment: \"italic #8f5902\", # class: 'c'\n Comment.Preproc: \"noitalic\", # class: 'cp'\n\n Keyword: \"bold #004461\", # class: 'k'\n Keyword.Constant: \"bold #004461\", # class: 'kc'\n Keyword.Declaration: \"bold #004461\", # class: 'kd'\n Keyword.Namespace: \"bold #004461\", # class: 'kn'\n Keyword.Pseudo: \"bold #004461\", # class: 'kp'\n Keyword.Reserved: \"bold #004461\", # class: 'kr'\n Keyword.Type: \"bold #004461\", # class: 'kt'\n\n Operator: \"#582800\", # class: 'o'\n Operator.Word: \"bold #004461\", # class: 'ow' - like keywords\n\n Punctuation: "}
{"repo":"requests","file":"docs/api.rst","line":3,"symbol":"Developer Interface","kind":"section","lang":"rst","code":"Developer Interface\n==================="}
{"repo":"requests","file":"docs/api.rst","line":13,"symbol":"Main Interface","kind":"section","lang":"rst","code":"Main Interface\n--------------"}
{"repo":"requests","file":"docs/api.rst","line":28,"symbol":"Exceptions","kind":"section","lang":"rst","code":"Exceptions\n----------"}
{"repo":"requests","file":"docs/api.rst","line":41,"symbol":"Request Sessions","kind":"section","lang":"rst","code":"Request Sessions\n----------------"}
{"repo":"requests","file":"docs/api.rst","line":50,"symbol":"Lower-Level Classes","kind":"section","lang":"rst","code":"Lower-Level Classes\n-------------------"}
{"repo":"requests","file":"docs/api.rst","line":61,"symbol":"Lower-Lower-Level Classes","kind":"section","lang":"rst","code":"Lower-Lower-Level Classes\n-------------------------"}
{"repo":"requests","file":"docs/api.rst","line":73,"symbol":"Authentication","kind":"section","lang":"rst","code":"Authentication\n--------------"}
{"repo":"requests","file":"docs/api.rst","line":83,"symbol":"Encodings","kind":"section","lang":"rst","code":"Encodings\n---------"}
{"repo":"requests","file":"docs/api.rst","line":93,"symbol":"Cookies","kind":"section","lang":"rst","code":"Cookies\n-------"}
{"repo":"requests","file":"docs/api.rst","line":108,"symbol":"Status Code Lookup","kind":"section","lang":"rst","code":"Status Code Lookup\n------------------"}
{"repo":"requests","file":"docs/api.rst","line":116,"symbol":"Migrating to 1.x","kind":"section","lang":"rst","code":"Migrating to 1.x\n----------------"}
{"repo":"requests","file":"docs/api.rst","line":123,"symbol":"API Changes","kind":"section","lang":"rst","code":"API Changes\n~~~~~~~~~~~"}
{"repo":"requests","file":"docs/api.rst","line":193,"symbol":"Licensing","kind":"section","lang":"rst","code":"Licensing\n~~~~~~~~~"}
{"repo":"requests","file":"docs/api.rst","line":205,"symbol":"Migrating to 2.x","kind":"section","lang":"rst","code":"Migrating to 2.x\n----------------"}
{"repo":"requests","file":"docs/api.rst","line":220,"symbol":"API Changes","kind":"section","lang":"rst","code":"API Changes\n~~~~~~~~~~~"}
{"repo":"requests","file":"docs/api.rst","line":250,"symbol":"Behavioural Changes","kind":"section","lang":"rst","code":"Behavioural Changes\n~~~~~~~~~~~~~~~~~~~~~~~"}
{"repo":"requests","file":"docs/community/faq.rst","line":3,"symbol":"Frequently Asked Questions","kind":"section","lang":"rst","code":"Frequently Asked Questions\n=========================="}
{"repo":"requests","file":"docs/community/faq.rst","line":8,"symbol":"Encoded Data?","kind":"section","lang":"rst","code":"Encoded Data?\n-------------"}
{"repo":"requests","file":"docs/community/faq.rst","line":21,"symbol":"Custom User-Agents?","kind":"section","lang":"rst","code":"Custom User-Agents?\n-------------------"}
{"repo":"requests","file":"docs/community/faq.rst","line":29,"symbol":"Why not Httplib2?","kind":"section","lang":"rst","code":"Why not Httplib2?\n-----------------"}
{"repo":"requests","file":"docs/community/out-there.rst","line":1,"symbol":"Integrations","kind":"section","lang":"rst","code":"Integrations\n============"}
{"repo":"requests","file":"docs/community/out-there.rst","line":4,"symbol":"Articles & Talks","kind":"section","lang":"rst","code":"Articles & Talks\n================"}
{"repo":"requests","file":"docs/community/recommended.rst","line":3,"symbol":"Recommended Packages and Extensions","kind":"section","lang":"rst","code":"Recommended Packages and Extensions\n==================================="}
{"repo":"requests","file":"docs/community/recommended.rst","line":9,"symbol":"Certifi CA Bundle","kind":"section","lang":"rst","code":"Certifi CA Bundle\n-----------------"}
{"repo":"requests","file":"docs/community/recommended.rst","line":18,"symbol":"CacheControl","kind":"section","lang":"rst","code":"CacheControl\n------------"}
{"repo":"requests","file":"docs/community/recommended.rst","line":27,"symbol":"Requests-Toolbelt","kind":"section","lang":"rst","code":"Requests-Toolbelt\n-----------------"}
{"repo":"requests","file":"docs/community/recommended.rst","line":38,"symbol":"Requests-Threads","kind":"section","lang":"rst","code":"Requests-Threads\n----------------"}
{"repo":"requests","file":"docs/community/recommended.rst","line":45,"symbol":"Requests-OAuthlib","kind":"section","lang":"rst","code":"Requests-OAuthlib\n-----------------"}
{"repo":"requests","file":"docs/community/recommended.rst","line":56,"symbol":"Betamax","kind":"section","lang":"rst","code":"Betamax\n-------"}
{"repo":"requests","file":"docs/community/release-process.rst","line":1,"symbol":"Release Process and Rules","kind":"section","lang":"rst","code":"Release Process and Rules\n========================="}
{"repo":"requests","file":"docs/community/release-process.rst","line":9,"symbol":"Major Releases","kind":"section","lang":"rst","code":"Major Releases\n--------------"}
{"repo":"requests","file":"docs/community/release-process.rst","line":26,"symbol":"Minor Releases","kind":"section","lang":"rst","code":"Minor Releases\n--------------"}
{"repo":"requests","file":"docs/community/release-process.rst","line":37,"symbol":"Hotfix Releases","kind":"section","lang":"rst","code":"Hotfix Releases\n---------------"}
{"repo":"requests","file":"docs/community/release-process.rst","line":47,"symbol":"Reasoning","kind":"section","lang":"rst","code":"Reasoning\n---------"}
{"repo":"requests","file":"docs/community/support.rst","line":3,"symbol":"Support","kind":"section","lang":"rst","code":"Support\n======="}
{"repo":"requests","file":"docs/community/updates.rst","line":4,"symbol":"Community Updates","kind":"section","lang":"rst","code":"Community Updates\n================="}
{"repo":"requests","file":"docs/community/vulnerabilities.rst","line":1,"symbol":"Vulnerability Disclosure","kind":"section","lang":"rst","code":"Vulnerability Disclosure\n========================"}
{"repo":"requests","file":"docs/dev/authors.rst","line":1,"symbol":"Authors","kind":"section","lang":"rst","code":"Authors\n======="}
{"repo":"requests","file":"docs/dev/contributing.rst","line":3,"symbol":"Contributor's Guide","kind":"section","lang":"rst","code":"Contributor's Guide\n==================="}
{"repo":"requests","file":"docs/dev/contributing.rst","line":25,"symbol":"Code of Conduct","kind":"section","lang":"rst","code":"Code of Conduct\n---------------"}
{"repo":"requests","file":"docs/dev/contributing.rst","line":39,"symbol":"Get Early Feedback","kind":"section","lang":"rst","code":"Get Early Feedback\n------------------"}
{"repo":"requests","file":"docs/dev/contributing.rst","line":49,"symbol":"Contribution Suitability","kind":"section","lang":"rst","code":"Contribution Suitability\n------------------------"}
{"repo":"requests","file":"docs/dev/contributing.rst","line":62,"symbol":"Code Contributions","kind":"section","lang":"rst","code":"Code Contributions\n------------------"}
{"repo":"requests","file":"docs/dev/contributing.rst","line":65,"symbol":"Steps for Submitting Code","kind":"section","lang":"rst","code":"Steps for Submitting Code\n~~~~~~~~~~~~~~~~~~~~~~~~~"}
{"repo":"requests","file":"docs/requirements.txt","line":3,"symbol":"Sphinx","kind":"field","lang":"requirements","code":"Sphinx==7.2.6"}
{"repo":"requests","file":"docs/user/advanced.rst","line":3,"symbol":"Advanced Usage","kind":"section","lang":"rst","code":"Advanced Usage\n=============="}
{"repo":"requests","file":"docs/user/advanced.rst","line":10,"symbol":"Session Objects","kind":"section","lang":"rst","code":"Session Objects\n---------------"}
{"repo":"requests","file":"docs/user/advanced.rst","line":87,"symbol":"Request and Response Objects","kind":"section","lang":"rst","code":"Request and Response Objects\n----------------------------"}
{"repo":"requests","file":"docs/user/advanced.rst","line":121,"symbol":"Prepared Requests","kind":"section","lang":"rst","code":"Prepared Requests\n-----------------"}
{"repo":"requests","file":"docs/user/authentication.rst","line":3,"symbol":"Authentication","kind":"section","lang":"rst","code":"Authentication\n=============="}
{"repo":"requests","file":"docs/user/authentication.rst","line":13,"symbol":"Basic Authentication","kind":"section","lang":"rst","code":"Basic Authentication\n--------------------"}
{"repo":"requests","file":"docs/user/authentication.rst","line":36,"symbol":"netrc Authentication","kind":"section","lang":"rst","code":"netrc Authentication\n~~~~~~~~~~~~~~~~~~~~"}
{"repo":"requests","file":"docs/user/authentication.rst","line":58,"symbol":"Digest Authentication","kind":"section","lang":"rst","code":"Digest Authentication\n---------------------"}
{"repo":"requests","file":"docs/user/authentication.rst","line":70,"symbol":"OAuth 1 Authentication","kind":"section","lang":"rst","code":"OAuth 1 Authentication\n----------------------"}
{"repo":"requests","file":"docs/user/authentication.rst","line":90,"symbol":"OAuth 2 and OpenID Connect Authentication","kind":"section","lang":"rst","code":"OAuth 2 and OpenID Connect Authentication\n-----------------------------------------"}
{"repo":"requests","file":"docs/user/install.rst","line":3,"symbol":"Installation of Requests","kind":"section","lang":"rst","code":"Installation of Requests\n========================"}
{"repo":"requests","file":"docs/user/install.rst","line":10,"symbol":"$ python -m pip install requests","kind":"section","lang":"rst","code":"$ python -m pip install requests\n--------------------------------"}
{"repo":"requests","file":"docs/user/install.rst","line":17,"symbol":"Get the Source Code","kind":"section","lang":"rst","code":"Get the Source Code\n-------------------"}
{"repo":"requests","file":"docs/user/quickstart.rst","line":3,"symbol":"Quickstart","kind":"section","lang":"rst","code":"Quickstart\n=========="}
{"repo":"requests","file":"requirements-dev.txt","line":2,"symbol":"pytest","kind":"field","lang":"requirements","code":"pytest>=2.8.0,<10"}
{"repo":"requests","file":"requirements-dev.txt","line":3,"symbol":"pytest-cov","kind":"field","lang":"requirements","code":"pytest-cov"}
{"repo":"requests","file":"requirements-dev.txt","line":4,"symbol":"pytest-httpbin","kind":"field","lang":"requirements","code":"pytest-httpbin==2.1.0"}
{"repo":"requests","file":"requirements-dev.txt","line":5,"symbol":"httpbin","kind":"field","lang":"requirements","code":"httpbin~=0.10.0"}
{"repo":"requests","file":"requirements-dev.txt","line":6,"symbol":"trustme","kind":"field","lang":"requirements","code":"trustme"}
{"repo":"requests","file":"requirements-dev.txt","line":7,"symbol":"wheel","kind":"field","lang":"requirements","code":"wheel"}
{"repo":"requests","file":"src/requests/__init__.py","line":60,"symbol":"check_compatibility","kind":"function","lang":"python","code":"def check_compatibility(\n urllib3_version: str,\n chardet_version: str | None,\n charset_normalizer_version: str | None,\n) -> None:\n urllib3_version_list = urllib3_version.split(\".\")[:3]\n assert urllib3_version_list != [\"dev\"] # Verify urllib3 isn't installed from git.\n\n # Sometimes, urllib3 only reports its version as 16.1.\n if len(urllib3_version_list) == 2:\n urllib3_version_list.append(\"0\")\n\n # Check urllib3 for compatibility.\n major, minor, patch = urllib3_version_list # noqa: F811\n major, minor, patch = int(major), int(minor), int(patch)\n # urllib3 >= 1.21.1\n assert major >= 1\n if major == 1:\n assert minor >= 21\n\n # Check charset_normalizer for compatibility.\n if chardet_version:\n major, minor, patch = chardet_version.split(\".\")[:3]\n major, minor, patch = int(major), int(minor), int(patch)\n # chardet_version >= 3.0.2, < 8.0.0\n assert (3, 0, 2) <= (major, minor, patch) < (8, 0, 0)\n elif charset_normalizer_version:\n major, minor, patch = charset_normalizer_version.split(\".\")[:3]\n major, minor, patch = int(major), int(minor), int(patch)\n # charset_normalizer >= 2.0.0 < 4"}
{"repo":"requests","file":"src/requests/__init__.py","line":99,"symbol":"_check_cryptography","kind":"function","lang":"python","code":"def _check_cryptography(cryptography_version: str) -> None:\n # cryptography < 1.3.4\n try:\n cryptography_version_list = list(map(int, cryptography_version.split(\".\")))\n except ValueError:\n return\n\n if cryptography_version_list < [1, 3, 4]:\n warning = f\"Old version of cryptography ({cryptography_version_list}) may cause slowdown.\"\n warnings.warn(warning, RequestsDependencyWarning)"}
{"repo":"requests","file":"src/requests/_internal_utils.py","line":26,"symbol":"to_native_string","kind":"function","lang":"python","code":"def to_native_string(string: str | bytes, encoding: str = \"ascii\") -> str:\n \"\"\"Given a string object, regardless of type, returns a representation of\n that string in the native string type, encoding and decoding where\n necessary. This assumes ASCII unless told otherwise.\n \"\"\"\n if isinstance(string, builtin_str):\n out = string\n else:\n out = string.decode(encoding)\n\n return out"}
{"repo":"requests","file":"src/requests/_internal_utils.py","line":39,"symbol":"unicode_is_ascii","kind":"function","lang":"python","code":"def unicode_is_ascii(u_string: str) -> bool:\n \"\"\"Determine if unicode string only contains ASCII characters.\n\n :param str u_string: unicode string to check. Must be unicode\n and not Python 2 `str`.\n :rtype: bool\n \"\"\"\n assert isinstance(u_string, str)\n try:\n u_string.encode(\"ascii\")\n return True\n except UnicodeEncodeError:\n return False"}
{"repo":"requests","file":"src/requests/_types.py","line":28,"symbol":"SupportsRead","kind":"class","lang":"python","code":"class SupportsRead(Protocol[_T_co]):\n def read(self, length: int = ..., /) -> _T_co: ..."}
{"repo":"requests","file":"src/requests/_types.py","line":29,"symbol":"read","kind":"function","lang":"python","code":"def read(self, length: int = ..., /) -> _T_co: ..."}
{"repo":"requests","file":"src/requests/_types.py","line":32,"symbol":"has_read","kind":"function","lang":"python","code":"def has_read(obj: Any) -> TypeIs[SupportsRead[str | bytes]]:\n \"\"\"Check if obj supports read, including __getattr__ based proxies.\"\"\"\n return isinstance(obj, SupportsRead) or hasattr(obj, \"read\")"}
{"repo":"requests","file":"src/requests/_types.py","line":38,"symbol":"SupportsItems","kind":"class","lang":"python","code":"class SupportsItems(Protocol[_KT_co, _VT_co]):\n def items(self) -> Iterable[tuple[_KT_co, _VT_co]]: ..."}
{"repo":"requests","file":"src/requests/_types.py","line":39,"symbol":"items","kind":"function","lang":"python","code":"def items(self) -> Iterable[tuple[_KT_co, _VT_co]]: ..."}
{"repo":"requests","file":"src/requests/_types.py","line":47,"symbol":"is_prepared","kind":"function","lang":"python","code":"def is_prepared(request: PreparedRequest) -> TypeIs[_ValidatedRequest]:\n \"\"\"Verify a PreparedRequest has been fully prepared.\"\"\"\n if TYPE_CHECKING:\n return request.url is not None and request.method is not None\n # noop at runtime to avoid AssertionError\n return True"}
{"repo":"requests","file":"src/requests/_types.py","line":69,"symbol":"_ValidatedRequest","kind":"class","lang":"python","code":"class _ValidatedRequest(PreparedRequest):\n \"\"\"Subtype asserting a PreparedRequest has been fully prepared before calling.\n\n The override suppression is required because mutable attribute types are\n invariant (Liskov), but we only narrow after preparation is complete. This\n is the explicit contract for Requests but Python's typing doesn't have a\n better way to represent the requirement.\n \"\"\"\n\n url: str # type: ignore[reportIncompatibleVariableOverride]\n method: str # type: ignore[reportIncompatibleVariableOverride]"}
{"repo":"requests","file":"src/requests/_types.py","line":157,"symbol":"BaseRequestKwargs","kind":"class","lang":"python","code":"class BaseRequestKwargs(TypedDict, total=False):\n headers: HeadersType\n cookies: RequestsCookieJar | CookieJar | dict[str, str] | None\n files: FilesType\n auth: AuthType\n timeout: TimeoutType\n allow_redirects: bool\n proxies: dict[str, str] | None\n hooks: HooksInputType | None\n stream: bool | None\n verify: VerifyType | None\n cert: CertType"}
{"repo":"requests","file":"src/requests/_types.py","line":170,"symbol":"RequestKwargs","kind":"class","lang":"python","code":"class RequestKwargs(BaseRequestKwargs, total=False):\n \"\"\"kwargs for request(), options(), head(), delete().\"\"\"\n\n params: ParamsType\n data: DataType\n json: JsonType"}
{"repo":"requests","file":"src/requests/_types.py","line":177,"symbol":"GetKwargs","kind":"class","lang":"python","code":"class GetKwargs(BaseRequestKwargs, total=False):\n data: DataType\n json: JsonType"}
{"repo":"requests","file":"src/requests/_types.py","line":181,"symbol":"PostKwargs","kind":"class","lang":"python","code":"class PostKwargs(BaseRequestKwargs, total=False):\n params: ParamsType"}
{"repo":"requests","file":"src/requests/_types.py","line":184,"symbol":"DataKwargs","kind":"class","lang":"python","code":"class DataKwargs(BaseRequestKwargs, total=False):\n \"\"\"kwargs for put(), patch().\"\"\"\n\n params: ParamsType\n json: JsonType"}
{"repo":"requests","file":"src/requests/adapters.py","line":66,"symbol":"SOCKSProxyManager","kind":"function","lang":"python","code":"def SOCKSProxyManager(*args: Any, **kwargs: Any) -> None:\n raise InvalidSchema(\"Missing dependencies for SOCKS support.\")"}
{"repo":"requests","file":"src/requests/adapters.py","line":85,"symbol":"_urllib3_request_context","kind":"function","lang":"python","code":"def _urllib3_request_context(\n request: PreparedRequest,\n verify: bool | str | None,\n client_cert: tuple[str, str] | str | None,\n poolmanager: PoolManager,\n) -> tuple[dict[str, Any], dict[str, Any]]:\n host_params: dict[str, Any] = {}\n pool_kwargs: dict[str, Any] = {}\n parsed_request_url = urlparse(request.url)\n scheme = parsed_request_url.scheme.lower()\n port = parsed_request_url.port\n\n cert_reqs = \"CERT_REQUIRED\"\n if verify is False:\n cert_reqs = \"CERT_NONE\"\n elif isinstance(verify, str):\n if not os.path.isdir(verify):\n pool_kwargs[\"ca_certs\"] = verify\n else:\n pool_kwargs[\"ca_cert_dir\"] = verify\n pool_kwargs[\"cert_reqs\"] = cert_reqs\n if client_cert is not None:\n if isinstance(client_cert, tuple) and len(client_cert) == 2:\n pool_kwargs[\"cert_file\"] = client_cert[0]\n pool_kwargs[\"key_file\"] = client_cert[1]\n else:\n # According to our docs, we allow users to specify just the client\n # cert path\n pool_kwargs[\"cert_file\"] = client_cert\n host_params = {\n \"scheme\": scheme,\n \"host\": parsed_request_url.hostname,\n \""}
{"repo":"requests","file":"src/requests/adapters.py","line":122,"symbol":"BaseAdapter","kind":"class","lang":"python","code":"class BaseAdapter:\n \"\"\"The Base Transport Adapter\"\"\"\n\n def __init__(self) -> None:\n super().__init__()\n\n def send(\n self,\n request: PreparedRequest,\n stream: bool = False,\n timeout: _t.TimeoutType = None,\n verify: _t.VerifyType = True,\n cert: _t.CertType = None,\n proxies: dict[str, str] | None = None,\n ) -> Response:\n \"\"\"Sends PreparedRequest object. Returns Response object.\n\n :param request: The :class:`PreparedRequest <PreparedRequest>` being sent.\n :param stream: (optional) Whether to stream the request content.\n :param timeout: (optional) How long to wait for the server to send\n data before giving up, as a float, or a :ref:`(connect timeout,\n read timeout) <timeouts>` tuple.\n :type timeout: float or tuple\n :param verify: (optional) Either a boolean, in which case it controls whether we verify\n the server's TLS certificate, or a string, in which case it must be a path\n to a CA bundle to use\n :param cert: (optional) Any user-provided SSL certificate to be trusted.\n :param proxies: (optional) The proxies dictionary "}
{"repo":"requests","file":"src/requests/adapters.py","line":125,"symbol":"__init__","kind":"function","lang":"python","code":"def __init__(self) -> None:\n super().__init__()"}
{"repo":"requests","file":"src/requests/adapters.py","line":128,"symbol":"send","kind":"function","lang":"python","code":"def send(\n self,\n request: PreparedRequest,\n stream: bool = False,\n timeout: _t.TimeoutType = None,\n verify: _t.VerifyType = True,\n cert: _t.CertType = None,\n proxies: dict[str, str] | None = None,\n ) -> Response:\n \"\"\"Sends PreparedRequest object. Returns Response object.\n\n :param request: The :class:`PreparedRequest <PreparedRequest>` being sent.\n :param stream: (optional) Whether to stream the request content.\n :param timeout: (optional) How long to wait for the server to send\n data before giving up, as a float, or a :ref:`(connect timeout,\n read timeout) <timeouts>` tuple.\n :type timeout: float or tuple\n :param verify: (optional) Either a boolean, in which case it controls whether we verify\n the server's TLS certificate, or a string, in which case it must be a path\n to a CA bundle to use\n :param cert: (optional) Any user-provided SSL certificate to be trusted.\n :param proxies: (optional) The proxies dictionary to apply to the request.\n \"\"\"\n raise NotImplementedError"}
{"repo":"requests","file":"src/requests/adapters.py","line":153,"symbol":"close","kind":"function","lang":"python","code":"def close(self) -> None:\n \"\"\"Cleans up adapter specific items.\"\"\"\n raise NotImplementedError"}
{"repo":"requests","file":"src/requests/adapters.py","line":158,"symbol":"HTTPAdapter","kind":"class","lang":"python","code":"class HTTPAdapter(BaseAdapter):\n \"\"\"The built-in HTTP Adapter for urllib3.\n\n Provides a general-case interface for Requests sessions to contact HTTP and\n HTTPS urls by implementing the Transport Adapter interface. This class will\n usually be created by the :class:`Session <Session>` class under the\n covers.\n\n :param pool_connections: The number of urllib3 connection pools to cache.\n :param pool_maxsize: The maximum number of connections to save in the pool.\n :param max_retries: The maximum number of retries each connection\n should attempt. Note, this applies only to failed DNS lookups, socket\n connections and connection timeouts, never to requests where data has\n made it to the server. By default, Requests does not retry failed\n connections. If you need granular control over the conditions under\n which we retry a request, import urllib3's ``Retry`` class and pass\n that instead.\n :param pool_block: Whether the connection pool should block for connections.\n\n Usage::\n\n >>> import requests\n >>> s = requests.Session()\n >>> a = requests.adapters.HTTPAdapter(max_retries=3)\n >>> s.mount('http://', a"}
{"repo":"requests","file":"src/requests/adapters.py","line":201,"symbol":"__init__","kind":"function","lang":"python","code":"def __init__(\n self,\n pool_connections: int = DEFAULT_POOLSIZE,\n pool_maxsize: int = DEFAULT_POOLSIZE,\n max_retries: int | Retry = DEFAULT_RETRIES,\n pool_block: bool = DEFAULT_POOLBLOCK,\n ) -> None:\n if max_retries == DEFAULT_RETRIES:\n self.max_retries = Retry(0, read=False)\n else:\n self.max_retries = Retry.from_int(max_retries)\n self.config = {}\n self.proxy_manager = {}\n\n super().__init__()\n\n self._pool_connections = pool_connections\n self._pool_maxsize = pool_maxsize\n self._pool_block = pool_block\n\n self.init_poolmanager(pool_connections, pool_maxsize, block=pool_block)"}
{"repo":"requests","file":"src/requests/adapters.py","line":223,"symbol":"__getstate__","kind":"function","lang":"python","code":"def __getstate__(self) -> dict[str, Any]:\n return {attr: getattr(self, attr, None) for attr in self.__attrs__}"}
{"repo":"requests","file":"src/requests/adapters.py","line":226,"symbol":"__setstate__","kind":"function","lang":"python","code":"def __setstate__(self, state: dict[str, Any]) -> None:\n # Can't handle by adding 'proxy_manager' to self.__attrs__ because\n # self.poolmanager uses a lambda function, which isn't pickleable.\n self.proxy_manager = {}\n self.config = {}\n\n for attr, value in state.items():\n setattr(self, attr, value)\n\n self.init_poolmanager(\n self._pool_connections, self._pool_maxsize, block=self._pool_block\n )"}
{"repo":"requests","file":"src/requests/adapters.py","line":239,"symbol":"init_poolmanager","kind":"function","lang":"python","code":"def init_poolmanager(\n self,\n connections: int,\n maxsize: int,\n block: bool = DEFAULT_POOLBLOCK,\n **pool_kwargs: Any,\n ) -> None:\n \"\"\"Initializes a urllib3 PoolManager.\n\n This method should not be called from user code, and is only\n exposed for use when subclassing the\n :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n :param connections: The number of urllib3 connection pools to cache.\n :param maxsize: The maximum number of connections to save in the pool.\n :param block: Block when no free connections are available.\n :param pool_kwargs: Extra keyword arguments used to initialize the Pool Manager.\n \"\"\"\n # save these values for pickling\n self._pool_connections = connections\n self._pool_maxsize = maxsize\n self._pool_block = block\n\n self.poolmanager = PoolManager(\n num_pools=connections,\n maxsize=maxsize,\n block=block,\n **pool_kwargs,\n )"}
{"repo":"requests","file":"src/requests/adapters.py","line":269,"symbol":"proxy_manager_for","kind":"function","lang":"python","code":"def proxy_manager_for(self, proxy: str, **proxy_kwargs: Any) -> Any:\n \"\"\"Return urllib3 ProxyManager for the given proxy.\n\n This method should not be called from user code, and is only\n exposed for use when subclassing the\n :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n :param proxy: The proxy to return a urllib3 ProxyManager for.\n :param proxy_kwargs: Extra keyword arguments used to configure the Proxy Manager.\n :returns: ProxyManager\n :rtype: urllib3.ProxyManager\n \"\"\"\n if proxy in self.proxy_manager:\n manager = self.proxy_manager[proxy]\n elif proxy.lower().startswith(\"socks\"):\n username, password = get_auth_from_url(proxy)\n manager = self.proxy_manager[proxy] = SOCKSProxyManager(\n proxy,\n username=username,\n password=password,\n num_pools=self._pool_connections,\n maxsize=self._pool_maxsize,\n block=self._pool_block,\n **proxy_kwargs,\n )\n else:\n proxy_headers = self.proxy_headers(proxy)\n manager = self.proxy_manager[proxy] ="}
{"repo":"requests","file":"src/requests/adapters.py","line":307,"symbol":"cert_verify","kind":"function","lang":"python","code":"def cert_verify(\n self, conn: Any, url: str, verify: _t.VerifyType, cert: _t.CertType\n ) -> None:\n \"\"\"Verify a SSL certificate. This method should not be called from user\n code, and is only exposed for use when subclassing the\n :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n :param conn: The urllib3 connection object associated with the cert.\n :param url: The requested URL.\n :param verify: Either a boolean, in which case it controls whether we verify\n the server's TLS certificate, or a string, in which case it must be a path\n to a CA bundle to use\n :param cert: The SSL certificate to verify.\n \"\"\"\n if url.lower().startswith(\"https\") and verify:\n cert_loc = None\n\n # Allow self-specified cert location.\n if verify is not True:\n cert_loc = verify\n\n if not cert_loc:\n cert_loc = DEFAULT_CA_BUNDLE_PATH\n\n if not cert_loc or not os.path.exists(cert_loc):\n raise OSError(\n f\"Could not find a suitable TLS CA certificate bundle, \"\n f\"invalid path: {cert_loc}\""}
{"repo":"requests","file":"src/requests/adapters.py","line":365,"symbol":"build_response","kind":"function","lang":"python","code":"def build_response(self, req: PreparedRequest, resp: Any) -> Response:\n \"\"\"Builds a :class:`Response <requests.Response>` object from a urllib3\n response. This should not be called from user code, and is only exposed\n for use when subclassing the\n :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`\n\n :param req: The :class:`PreparedRequest <PreparedRequest>` used to generate the response.\n :param resp: The urllib3 response object.\n :rtype: requests.Response\n \"\"\"\n assert _is_prepared(req)\n response = Response()\n\n # Fallback to None if there's no status_code, for whatever reason.\n response.status_code = getattr(resp, \"status\", None) # type: ignore[assignment]\n\n # Make headers case-insensitive.\n response.headers = CaseInsensitiveDict(getattr(resp, \"headers\", {}))\n\n # Set encoding.\n response.encoding = get_encoding_from_headers(response.headers)\n response.raw = resp\n response.reason = response.raw.reason\n\n if isinstance(req.url, bytes):\n response.url = req.url.decode(\"utf-8\")\n else:\n response.url = req.url\n\n # Add new"}
{"repo":"requests","file":"src/requests/adapters.py","line":403,"symbol":"build_connection_pool_key_attributes","kind":"function","lang":"python","code":"def build_connection_pool_key_attributes(\n self, request: PreparedRequest, verify: _t.VerifyType, cert: _t.CertType = None\n ) -> tuple[dict[str, Any], dict[str, Any]]:\n \"\"\"Build the PoolKey attributes used by urllib3 to return a connection.\n\n This looks at the PreparedRequest, the user-specified verify value,\n and the value of the cert parameter to determine what PoolKey values\n to use to select a connection from a given urllib3 Connection Pool.\n\n The SSL related pool key arguments are not consistently set. As of\n this writing, use the following to determine what keys may be in that\n dictionary:\n\n * If ``verify`` is ``True``, ``\"ssl_context\"`` will be set and will be the\n default Requests SSL Context\n * If ``verify`` is ``False``, ``\"ssl_context\"`` will not be set but\n ``\"cert_reqs\"`` will be set\n * If ``verify`` is a string, (i.e., it is a user-specified trust bundle)\n ``\"ca_certs\"`` will be set if the string is not a directory recognized\n by :py:func:`os.path.isdir`, otherwise ``\"ca_cert_dir\"`` will be\n set.\n * If ``\"cert\"`` is specified, ``\"cert_fil"}
{"repo":"requests","file":"src/requests/adapters.py","line":455,"symbol":"get_connection_with_tls_context","kind":"function","lang":"python","code":"def get_connection_with_tls_context(\n self,\n request: PreparedRequest,\n verify: _t.VerifyType,\n proxies: dict[str, str] | None = None,\n cert: _t.CertType = None,\n ) -> HTTPConnectionPool:\n \"\"\"Returns a urllib3 connection for the given request and TLS settings.\n This should not be called from user code, and is only exposed for use\n when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n :param request:\n The :class:`PreparedRequest <PreparedRequest>` object to be sent\n over the connection.\n :param verify:\n Either a boolean, in which case it controls whether we verify the\n server's TLS certificate, or a string, in which case it must be a\n path to a CA bundle to use.\n :param proxies:\n (optional) The proxies dictionary to apply to the request.\n :param cert:\n (optional) Any user-provided SSL certificate to be used for client\n authentication (a.k.a., mTLS).\n :rtype:\n urllib3.HTTPConnectionPool\n \"\"\"\n assert _is_prepared(request)\n\n proxy = select_proxy(request"}
{"repo":"requests","file":"src/requests/adapters.py","line":512,"symbol":"get_connection","kind":"function","lang":"python","code":"def get_connection(\n self, url: str, proxies: dict[str, str] | None = None\n ) -> HTTPConnectionPool:\n \"\"\"DEPRECATED: Users should move to `get_connection_with_tls_context`\n for all subclasses of HTTPAdapter using Requests>=2.32.2.\n\n Returns a urllib3 connection for the given URL. This should not be\n called from user code, and is only exposed for use when subclassing the\n :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n :param url: The URL to connect to.\n :param proxies: (optional) A Requests-style dictionary of proxies used on this request.\n :rtype: urllib3.HTTPConnectionPool\n \"\"\"\n warnings.warn(\n (\n \"`get_connection` has been deprecated in favor of \"\n \"`get_connection_with_tls_context`. Custom HTTPAdapter subclasses \"\n \"will need to migrate for Requests>=2.32.2. Please see \"\n \"https://github.com/psf/requests/pull/6710 for more details.\"\n ),\n DeprecationWarning,\n )\n proxy = select_proxy(url, proxies)\n\n if proxy:\n proxy = prepend_scheme_if_needed(proxy, \"http\")\n p"}
{"repo":"requests","file":"src/requests/adapters.py","line":555,"symbol":"close","kind":"function","lang":"python","code":"def close(self) -> None:\n \"\"\"Disposes of any internal state.\n\n Currently, this closes the PoolManager and any active ProxyManager,\n which closes any pooled connections.\n \"\"\"\n self.poolmanager.clear()\n for proxy in self.proxy_manager.values():\n proxy.clear()"}
{"repo":"requests","file":"src/requests/adapters.py","line":565,"symbol":"request_url","kind":"function","lang":"python","code":"def request_url(\n self, request: PreparedRequest, proxies: dict[str, str] | None\n ) -> str:\n \"\"\"Obtain the url to use when making the final request.\n\n If the message is being sent through a HTTP proxy, the full URL has to\n be used. Otherwise, we should only use the path portion of the URL.\n\n This should not be called from user code, and is only exposed for use\n when subclassing the\n :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n :param request: The :class:`PreparedRequest <PreparedRequest>` being sent.\n :param proxies: A dictionary of schemes or schemes and hosts to proxy URLs.\n :rtype: str\n \"\"\"\n assert _is_prepared(request)\n\n proxy = select_proxy(request.url, proxies)\n scheme = urlparse(request.url).scheme\n\n is_proxied_http_request = proxy and scheme != \"https\"\n using_socks_proxy = False\n if proxy:\n proxy_scheme = urlparse(proxy).scheme.lower()\n using_socks_proxy = proxy_scheme.startswith(\"socks\")\n\n url = request.path_url\n\n if is_proxied_http_request and not using_socks_proxy:\n url = urldefragauth(request."}
{"repo":"requests","file":"src/requests/adapters.py","line":599,"symbol":"add_headers","kind":"function","lang":"python","code":"def add_headers(self, request: PreparedRequest, **kwargs: Any) -> None:\n \"\"\"Add any headers needed by the connection. As of v2.0 this does\n nothing by default, but is left for overriding by users that subclass\n the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n This should not be called from user code, and is only exposed for use\n when subclassing the\n :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n :param request: The :class:`PreparedRequest <PreparedRequest>` to add headers to.\n :param kwargs: The keyword arguments from the call to send().\n \"\"\"\n pass"}
{"repo":"requests","file":"src/requests/adapters.py","line":613,"symbol":"proxy_headers","kind":"function","lang":"python","code":"def proxy_headers(self, proxy: str) -> dict[str, str]:\n \"\"\"Returns a dictionary of the headers to add to any request sent\n through a proxy. This works with urllib3 magic to ensure that they are\n correctly sent to the proxy, rather than in a tunnelled request if\n CONNECT is being used.\n\n This should not be called from user code, and is only exposed for use\n when subclassing the\n :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n :param proxy: The url of the proxy being used for this request.\n :rtype: dict\n \"\"\"\n headers: dict[str, str] = {}\n username, password = get_auth_from_url(proxy)\n\n if username:\n headers[\"Proxy-Authorization\"] = _basic_auth_str(username, password)\n\n return headers"}
{"repo":"requests","file":"src/requests/adapters.py","line":634,"symbol":"send","kind":"function","lang":"python","code":"def send(\n self,\n request: PreparedRequest,\n stream: bool = False,\n timeout: _t.TimeoutType = None,\n verify: _t.VerifyType = True,\n cert: _t.CertType = None,\n proxies: dict[str, str] | None = None,\n ) -> Response:\n \"\"\"Sends PreparedRequest object. Returns Response object.\n\n :param request: The :class:`PreparedRequest <PreparedRequest>` being sent.\n :param stream: (optional) Whether to stream the request content.\n :param timeout: (optional) How long to wait for the server to send\n data before giving up, as a float, or a :ref:`(connect timeout,\n read timeout) <timeouts>` tuple.\n :type timeout: float or tuple or urllib3 Timeout object\n :param verify: (optional) Either a boolean, in which case it controls whether\n we verify the server's TLS certificate, or a string, in which case it\n must be a path to a CA bundle to use\n :param cert: (optional) Any user-provided SSL certificate to be trusted.\n :param proxies: (optional) The proxies dictionary to apply to the request.\n :rtype: requests.Response\n \"\"\"\n\n assert _is_prep"}
{"repo":"requests","file":"src/requests/api.py","line":24,"symbol":"request","kind":"function","lang":"python","code":"def request(\n method: str, url: _t.UriType, **kwargs: Unpack[_t.RequestKwargs]\n) -> Response:\n \"\"\"Constructs and sends a :class:`Request <Request>`.\n\n :param method: method for the new :class:`Request` object: ``GET``, ``OPTIONS``, ``HEAD``, ``POST``, ``PUT``, ``PATCH``, or ``DELETE``.\n :param url: URL for the new :class:`Request` object.\n :param params: (optional) Dictionary, list of tuples or bytes to send\n in the query string for the :class:`Request`.\n :param data: (optional) Dictionary, list of tuples, bytes, or file-like\n object to send in the body of the :class:`Request`.\n :param json: (optional) A JSON serializable Python object to send in the body of the :class:`Request`.\n :param headers: (optional) Dictionary of HTTP Headers to send with the :class:`Request`.\n :param cookies: (optional) Dict or CookieJar object to send with the :class:`Request`.\n :param files: (optional) Dictionary of ``'name': file-like-objects`` (or ``{'name': file-tuple}``) for multipart encoding upload.\n ``file-tuple`` can be a 2-tuple ``('filename', fileobj)``, 3-tuple ``('filename', fileobj, 'content_type')``\n or a 4-tuple ``('filename', fileo"}
{"repo":"requests","file":"src/requests/api.py","line":74,"symbol":"get","kind":"function","lang":"python","code":"def get(\n url: _t.UriType, params: _t.ParamsType = None, **kwargs: Unpack[_t.GetKwargs]\n) -> Response:\n r\"\"\"Sends a GET request.\n\n :param url: URL for the new :class:`Request` object.\n :param params: (optional) Dictionary, list of tuples or bytes to send\n in the query string for the :class:`Request`.\n :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n :return: :class:`Response <Response>` object\n :rtype: requests.Response\n \"\"\"\n\n return request(\"get\", url, params=params, **kwargs)"}
{"repo":"requests","file":"src/requests/api.py","line":90,"symbol":"options","kind":"function","lang":"python","code":"def options(url: _t.UriType, **kwargs: Unpack[_t.RequestKwargs]) -> Response:\n r\"\"\"Sends an OPTIONS request.\n\n :param url: URL for the new :class:`Request` object.\n :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n :return: :class:`Response <Response>` object\n :rtype: requests.Response\n \"\"\"\n\n return request(\"options\", url, **kwargs)"}
{"repo":"requests","file":"src/requests/api.py","line":102,"symbol":"head","kind":"function","lang":"python","code":"def head(url: _t.UriType, **kwargs: Unpack[_t.RequestKwargs]) -> Response:\n r\"\"\"Sends a HEAD request.\n\n :param url: URL for the new :class:`Request` object.\n :param \\*\\*kwargs: Optional arguments that ``request`` takes. If\n `allow_redirects` is not provided, it will be set to `False` (as\n opposed to the default :meth:`request` behavior).\n :return: :class:`Response <Response>` object\n :rtype: requests.Response\n \"\"\"\n\n kwargs.setdefault(\"allow_redirects\", False)\n return request(\"head\", url, **kwargs)"}
{"repo":"requests","file":"src/requests/api.py","line":117,"symbol":"post","kind":"function","lang":"python","code":"def post(\n url: _t.UriType,\n data: _t.DataType = None,\n json: _t.JsonType = None,\n **kwargs: Unpack[_t.PostKwargs],\n) -> Response:\n r\"\"\"Sends a POST request.\n\n :param url: URL for the new :class:`Request` object.\n :param data: (optional) Dictionary, list of tuples, bytes, or file-like\n object to send in the body of the :class:`Request`.\n :param json: (optional) A JSON serializable Python object to send in the body of the :class:`Request`.\n :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n :return: :class:`Response <Response>` object\n :rtype: requests.Response\n \"\"\"\n\n return request(\"post\", url, data=data, json=json, **kwargs)"}
{"repo":"requests","file":"src/requests/api.py","line":137,"symbol":"put","kind":"function","lang":"python","code":"def put(\n url: _t.UriType, data: _t.DataType = None, **kwargs: Unpack[_t.DataKwargs]\n) -> Response:\n r\"\"\"Sends a PUT request.\n\n :param url: URL for the new :class:`Request` object.\n :param data: (optional) Dictionary, list of tuples, bytes, or file-like\n object to send in the body of the :class:`Request`.\n :param json: (optional) A JSON serializable Python object to send in the body of the :class:`Request`.\n :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n :return: :class:`Response <Response>` object\n :rtype: requests.Response\n \"\"\"\n\n return request(\"put\", url, data=data, **kwargs)"}
{"repo":"requests","file":"src/requests/api.py","line":154,"symbol":"patch","kind":"function","lang":"python","code":"def patch(\n url: _t.UriType, data: _t.DataType = None, **kwargs: Unpack[_t.DataKwargs]\n) -> Response:\n r\"\"\"Sends a PATCH request.\n\n :param url: URL for the new :class:`Request` object.\n :param data: (optional) Dictionary, list of tuples, bytes, or file-like\n object to send in the body of the :class:`Request`.\n :param json: (optional) A JSON serializable Python object to send in the body of the :class:`Request`.\n :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n :return: :class:`Response <Response>` object\n :rtype: requests.Response\n \"\"\"\n\n return request(\"patch\", url, data=data, **kwargs)"}
{"repo":"requests","file":"src/requests/api.py","line":171,"symbol":"delete","kind":"function","lang":"python","code":"def delete(url: _t.UriType, **kwargs: Unpack[_t.RequestKwargs]) -> Response:\n r\"\"\"Sends a DELETE request.\n\n :param url: URL for the new :class:`Request` object.\n :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n :return: :class:`Response <Response>` object\n :rtype: requests.Response\n \"\"\"\n\n return request(\"delete\", url, **kwargs)"}
{"repo":"requests","file":"src/requests/auth.py","line":34,"symbol":"_basic_auth_str","kind":"function","lang":"python","code":"def _basic_auth_str(username: bytes | str, password: bytes | str) -> str:\n \"\"\"Returns a Basic Auth string.\"\"\"\n\n # \"I want us to put a big-ol' comment on top of it that\n # says that this behaviour is dumb but we need to preserve\n # it because people are relying on it.\"\n # - Lukasa\n #\n # These are here solely to maintain backwards compatibility\n # for things like ints. This will be removed in 3.0.0.\n if not isinstance(username, basestring): # runtime guard for non-str/bytes\n warnings.warn(\n \"Non-string usernames will no longer be supported in Requests \"\n f\"3.0.0. Please convert the object you've passed in ({username!r}) to \"\n \"a string or bytes object in the near future to avoid \"\n \"problems.\",\n category=DeprecationWarning,\n )\n username = str(username)\n\n if not isinstance(password, basestring): # runtime guard for non-str/bytes\n warnings.warn(\n \"Non-string passwords will no longer be supported in Requests \"\n f\"3.0.0. Please convert the object you've passed in ({type(password)!r}) to \"\n \"a string or bytes object in the near future to av"}
{"repo":"requests","file":"src/requests/auth.py","line":78,"symbol":"AuthBase","kind":"class","lang":"python","code":"class AuthBase:\n \"\"\"Base class that all auth implementations derive from\"\"\"\n\n def __call__(self, r: PreparedRequest) -> PreparedRequest:\n raise NotImplementedError(\"Auth hooks must be callable.\")"}
{"repo":"requests","file":"src/requests/auth.py","line":81,"symbol":"__call__","kind":"function","lang":"python","code":"def __call__(self, r: PreparedRequest) -> PreparedRequest:\n raise NotImplementedError(\"Auth hooks must be callable.\")"}
{"repo":"requests","file":"src/requests/auth.py","line":85,"symbol":"HTTPBasicAuth","kind":"class","lang":"python","code":"class HTTPBasicAuth(AuthBase):\n \"\"\"Attaches HTTP Basic Authentication to the given Request object.\"\"\"\n\n username: bytes | str\n password: bytes | str\n\n @overload\n def __init__(self, username: str, password: str) -> None: ...\n @overload\n def __init__(self, username: bytes, password: bytes) -> None: ...\n\n def __init__(self, username: bytes | str, password: bytes | str) -> None:\n self.username = username\n self.password = password\n\n def __eq__(self, other: object) -> bool:\n return all(\n [\n self.username == getattr(other, \"username\", None),\n self.password == getattr(other, \"password\", None),\n ]\n )\n\n def __ne__(self, other: Any) -> bool:\n return not self == other\n\n def __call__(self, r: PreparedRequest) -> PreparedRequest:\n r.headers[\"Authorization\"] = _basic_auth_str(self.username, self.password)\n return r"}
{"repo":"requests","file":"src/requests/auth.py","line":92,"symbol":"__init__","kind":"function","lang":"python","code":"def __init__(self, username: str, password: str) -> None: ..."}
{"repo":"requests","file":"src/requests/auth.py","line":94,"symbol":"__init__","kind":"function","lang":"python","code":"def __init__(self, username: bytes, password: bytes) -> None: ..."}
{"repo":"requests","file":"src/requests/auth.py","line":96,"symbol":"__init__","kind":"function","lang":"python","code":"def __init__(self, username: bytes | str, password: bytes | str) -> None:\n self.username = username\n self.password = password"}
{"repo":"requests","file":"src/requests/auth.py","line":100,"symbol":"__eq__","kind":"function","lang":"python","code":"def __eq__(self, other: object) -> bool:\n return all(\n [\n self.username == getattr(other, \"username\", None),\n self.password == getattr(other, \"password\", None),\n ]\n )"}
{"repo":"requests","file":"src/requests/auth.py","line":108,"symbol":"__ne__","kind":"function","lang":"python","code":"def __ne__(self, other: Any) -> bool:\n return not self == other"}
{"repo":"requests","file":"src/requests/auth.py","line":111,"symbol":"__call__","kind":"function","lang":"python","code":"def __call__(self, r: PreparedRequest) -> PreparedRequest:\n r.headers[\"Authorization\"] = _basic_auth_str(self.username, self.password)\n return r"}
{"repo":"requests","file":"src/requests/auth.py","line":116,"symbol":"HTTPProxyAuth","kind":"class","lang":"python","code":"class HTTPProxyAuth(HTTPBasicAuth):\n \"\"\"Attaches HTTP Proxy Authentication to a given Request object.\"\"\"\n\n def __call__(self, r: PreparedRequest) -> PreparedRequest:\n r.headers[\"Proxy-Authorization\"] = _basic_auth_str(self.username, self.password)\n return r"}
{"repo":"requests","file":"src/requests/auth.py","line":119,"symbol":"__call__","kind":"function","lang":"python","code":"def __call__(self, r: PreparedRequest) -> PreparedRequest:\n r.headers[\"Proxy-Authorization\"] = _basic_auth_str(self.username, self.password)\n return r"}
{"repo":"requests","file":"src/requests/auth.py","line":124,"symbol":"HTTPDigestAuth","kind":"class","lang":"python","code":"class HTTPDigestAuth(AuthBase):\n \"\"\"Attaches HTTP Digest Authentication to the given Request object.\"\"\"\n\n username: bytes | str\n password: bytes | str\n _thread_local: threading.local\n last_nonce: str\n nonce_count: int\n chal: dict[str, str]\n pos: int | None\n num_401_calls: int | None\n\n @overload\n def __init__(self, username: str, password: str) -> None: ...\n @overload\n def __init__(self, username: bytes, password: bytes) -> None: ...\n\n def __init__(self, username: bytes | str, password: bytes | str) -> None:\n self.username = username\n self.password = password\n # Keep state in per-thread local storage\n self._thread_local = threading.local()\n\n def init_per_thread_state(self) -> None:\n # Ensure state is initialized just once per-thread\n if not hasattr(self._thread_local, \"init\"):\n self._thread_local.init = True\n self._thread_local.last_nonce = \"\"\n self._thread_local.nonce_count = 0\n self._thread_local.chal = {}\n self._thread_local.pos = None\n self._thread_local.num_401_calls = None\n\n def build_digest_header(self, method: str, url: s"}
{"repo":"requests","file":"src/requests/auth.py","line":137,"symbol":"__init__","kind":"function","lang":"python","code":"def __init__(self, username: str, password: str) -> None: ..."}
{"repo":"requests","file":"src/requests/auth.py","line":139,"symbol":"__init__","kind":"function","lang":"python","code":"def __init__(self, username: bytes, password: bytes) -> None: ..."}
{"repo":"requests","file":"src/requests/auth.py","line":141,"symbol":"__init__","kind":"function","lang":"python","code":"def __init__(self, username: bytes | str, password: bytes | str) -> None:\n self.username = username\n self.password = password\n # Keep state in per-thread local storage\n self._thread_local = threading.local()"}
{"repo":"requests","file":"src/requests/auth.py","line":147,"symbol":"init_per_thread_state","kind":"function","lang":"python","code":"def init_per_thread_state(self) -> None:\n # Ensure state is initialized just once per-thread\n if not hasattr(self._thread_local, \"init\"):\n self._thread_local.init = True\n self._thread_local.last_nonce = \"\"\n self._thread_local.nonce_count = 0\n self._thread_local.chal = {}\n self._thread_local.pos = None\n self._thread_local.num_401_calls = None"}
{"repo":"requests","file":"src/requests/auth.py","line":157,"symbol":"build_digest_header","kind":"function","lang":"python","code":"def build_digest_header(self, method: str, url: str) -> str | None:\n \"\"\"\n :rtype: str\n \"\"\"\n\n realm = self._thread_local.chal[\"realm\"]\n nonce = self._thread_local.chal[\"nonce\"]\n qop = self._thread_local.chal.get(\"qop\")\n algorithm = self._thread_local.chal.get(\"algorithm\")\n opaque = self._thread_local.chal.get(\"opaque\")\n hash_utf8 = None\n\n if algorithm is None:\n _algorithm = \"MD5\"\n else:\n _algorithm = algorithm.upper()\n # lambdas assume digest modules are imported at the top level\n if _algorithm == \"MD5\" or _algorithm == \"MD5-SESS\":\n\n def md5_utf8(x: str | bytes) -> str:\n if isinstance(x, str):\n x = x.encode(\"utf-8\")\n return hashlib.md5(x, usedforsecurity=False).hexdigest()\n\n hash_utf8 = md5_utf8\n elif _algorithm == \"SHA\":\n\n def sha_utf8(x: str | bytes) -> str:\n if isinstance(x, str):\n x = x.encode(\"utf-8\")\n return hashlib.sha1(x, usedforsecurity=False).hexdigest()\n\n hash_utf8 = sha_utf8\n elif _algorithm == \"SHA-256\":\n\n"}
{"repo":"requests","file":"src/requests/auth.py","line":176,"symbol":"md5_utf8","kind":"function","lang":"python","code":"def md5_utf8(x: str | bytes) -> str:\n if isinstance(x, str):\n x = x.encode(\"utf-8\")\n return hashlib.md5(x, usedforsecurity=False).hexdigest()"}
{"repo":"requests","file":"src/requests/auth.py","line":184,"symbol":"sha_utf8","kind":"function","lang":"python","code":"def sha_utf8(x: str | bytes) -> str:\n if isinstance(x, str):\n x = x.encode(\"utf-8\")\n return hashlib.sha1(x, usedforsecurity=False).hexdigest()"}
{"repo":"requests","file":"src/requests/auth.py","line":192,"symbol":"sha256_utf8","kind":"function","lang":"python","code":"def sha256_utf8(x: str | bytes) -> str:\n if isinstance(x, str):\n x = x.encode(\"utf-8\")\n return hashlib.sha256(x, usedforsecurity=False).hexdigest()"}
{"repo":"requests","file":"src/requests/auth.py","line":200,"symbol":"sha512_utf8","kind":"function","lang":"python","code":"def sha512_utf8(x: str | bytes) -> str:\n if isinstance(x, str):\n x = x.encode(\"utf-8\")\n return hashlib.sha512(x, usedforsecurity=False).hexdigest()"}
{"repo":"requests","file":"src/requests/auth.py","line":210,"symbol":"KD","kind":"function","lang":"python","code":"def KD(s: str, d: str) -> str:\n return hash_utf8(f\"{s}:{d}\")"}
{"repo":"requests","file":"src/requests/auth.py","line":268,"symbol":"handle_redirect","kind":"function","lang":"python","code":"def handle_redirect(self, r: Response, **kwargs: Any) -> None:\n \"\"\"Reset num_401_calls counter on redirects.\"\"\"\n if r.is_redirect:\n self._thread_local.num_401_calls = 1"}
{"repo":"requests","file":"src/requests/auth.py","line":273,"symbol":"handle_401","kind":"function","lang":"python","code":"def handle_401(self, r: Response, **kwargs: Any) -> Response:\n \"\"\"\n Takes the given response and tries digest-auth, if needed.\n\n :rtype: requests.Response\n \"\"\"\n\n # If response is not 4xx, do not auth\n # See https://github.com/psf/requests/issues/3772\n if not 400 <= r.status_code < 500:\n self._thread_local.num_401_calls = 1\n return r\n\n if self._thread_local.pos is not None:\n # Rewind the file position indicator of the body to where\n # it was to resend the request.\n if (seek := getattr(r.request.body, \"seek\", None)) is not None:\n seek(self._thread_local.pos)\n s_auth = r.headers.get(\"www-authenticate\", \"\")\n\n if \"digest\" in s_auth.lower() and self._thread_local.num_401_calls < 2:\n self._thread_local.num_401_calls += 1\n pat = re.compile(r\"digest \", flags=re.IGNORECASE)\n self._thread_local.chal = parse_dict_header(pat.sub(\"\", s_auth, count=1))\n\n # Consume content and release the original connection\n # to allow our new request to reuse the same one.\n r.content\n r.close()\n "}
{"repo":"requests","file":"src/requests/auth.py","line":321,"symbol":"__call__","kind":"function","lang":"python","code":"def __call__(self, r: PreparedRequest) -> PreparedRequest:\n # Initialize per-thread state, if needed\n self.init_per_thread_state()\n # If we have a saved nonce, skip the 401\n if self._thread_local.last_nonce:\n _digest_auth = self.build_digest_header(\n cast(str, r.method), cast(str, r.url)\n )\n if _digest_auth:\n r.headers[\"Authorization\"] = _digest_auth\n if (tell := getattr(r.body, \"tell\", None)) is not None:\n self._thread_local.pos = tell()\n else:\n # In the case of HTTPDigestAuth being reused and the body of\n # the previous request was a file-like object, pos has the\n # file position of the previous body. Ensure it's set to\n # None.\n self._thread_local.pos = None\n r.register_hook(\"response\", self.handle_401)\n r.register_hook(\"response\", self.handle_redirect)\n self._thread_local.num_401_calls = 1\n\n return r"}
{"repo":"requests","file":"src/requests/auth.py","line":345,"symbol":"__eq__","kind":"function","lang":"python","code":"def __eq__(self, other: object) -> bool:\n return all(\n [\n self.username == getattr(other, \"username\", None),\n self.password == getattr(other, \"password\", None),\n ]\n )"}
{"repo":"requests","file":"src/requests/auth.py","line":353,"symbol":"__ne__","kind":"function","lang":"python","code":"def __ne__(self, other: Any) -> bool:\n return not self == other"}
{"repo":"requests","file":"src/requests/compat.py","line":36,"symbol":"_resolve_char_detection","kind":"function","lang":"python","code":"def _resolve_char_detection() -> ModuleType | None:\n \"\"\"Find supported character detection libraries.\"\"\"\n chardet = None\n for lib in (\"chardet\", \"charset_normalizer\"):\n if chardet is None:\n try:\n chardet = importlib.import_module(lib)\n except ImportError:\n pass\n return chardet"}
{"repo":"requests","file":"src/requests/cookies.py","line":31,"symbol":"MockRequest","kind":"class","lang":"python","code":"class MockRequest:\n \"\"\"Wraps a `requests.PreparedRequest` to mimic a `urllib2.Request`.\n\n The code in `http.cookiejar.CookieJar` expects this interface in order to correctly\n manage cookie policies, i.e., determine whether a cookie can be set, given the\n domains of the request and the cookie.\n\n The original request object is read-only. The client is responsible for collecting\n the new headers via `get_new_headers()` and interpreting them appropriately. You\n probably want `get_cookie_header`, defined below.\n \"\"\"\n\n type: str\n\n def __init__(self, request: PreparedRequest) -> None:\n assert _is_prepared(request)\n self._r = request\n self._new_headers: dict[str, str] = {}\n self.type = urlparse(self._r.url).scheme\n\n def get_type(self) -> str:\n return self.type\n\n def get_host(self) -> str:\n return urlparse(self._r.url).netloc\n\n def get_origin_req_host(self) -> str:\n return self.get_host()\n\n def get_full_url(self) -> str:\n # Only return the response's URL if the user hadn't set the Host\n # header\n if not self._r.headers.get(\"Host\"):\n return self._r.url\n # If they "}
{"repo":"requests","file":"src/requests/cookies.py","line":45,"symbol":"__init__","kind":"function","lang":"python","code":"def __init__(self, request: PreparedRequest) -> None:\n assert _is_prepared(request)\n self._r = request\n self._new_headers: dict[str, str] = {}\n self.type = urlparse(self._r.url).scheme"}
{"repo":"requests","file":"src/requests/cookies.py","line":51,"symbol":"get_type","kind":"function","lang":"python","code":"def get_type(self) -> str:\n return self.type"}
{"repo":"requests","file":"src/requests/cookies.py","line":54,"symbol":"get_host","kind":"function","lang":"python","code":"def get_host(self) -> str:\n return urlparse(self._r.url).netloc"}
{"repo":"requests","file":"src/requests/cookies.py","line":57,"symbol":"get_origin_req_host","kind":"function","lang":"python","code":"def get_origin_req_host(self) -> str:\n return self.get_host()"}
{"repo":"requests","file":"src/requests/cookies.py","line":60,"symbol":"get_full_url","kind":"function","lang":"python","code":"def get_full_url(self) -> str:\n # Only return the response's URL if the user hadn't set the Host\n # header\n if not self._r.headers.get(\"Host\"):\n return self._r.url\n # If they did set it, retrieve it and reconstruct the expected domain\n host = to_native_string(self._r.headers[\"Host\"], encoding=\"utf-8\")\n parsed = urlparse(self._r.url)\n # Reconstruct the URL as we expect it\n return urlunparse(\n [\n parsed.scheme,\n host,\n parsed.path,\n parsed.params,\n parsed.query,\n parsed.fragment,\n ]\n )"}
{"repo":"requests","file":"src/requests/cookies.py","line":80,"symbol":"is_unverifiable","kind":"function","lang":"python","code":"def is_unverifiable(self) -> bool:\n return True"}
{"repo":"requests","file":"src/requests/cookies.py","line":83,"symbol":"has_header","kind":"function","lang":"python","code":"def has_header(self, name: str) -> bool:\n return name in self._r.headers or name in self._new_headers"}
{"repo":"requests","file":"src/requests/cookies.py","line":86,"symbol":"get_header","kind":"function","lang":"python","code":"def get_header(self, name: str, default: str | None = None) -> str | None:\n return self._r.headers.get(name, self._new_headers.get(name, default)) # type: ignore[return-value]"}
{"repo":"requests","file":"src/requests/cookies.py","line":89,"symbol":"add_header","kind":"function","lang":"python","code":"def add_header(self, key: str, val: str) -> None:\n \"\"\"cookiejar has no legitimate use for this method; add it back if you find one.\"\"\"\n raise NotImplementedError(\n \"Cookie headers should be added with add_unredirected_header()\"\n )"}
{"repo":"requests","file":"src/requests/cookies.py","line":95,"symbol":"add_unredirected_header","kind":"function","lang":"python","code":"def add_unredirected_header(self, name: str, value: str) -> None:\n self._new_headers[name] = value"}
{"repo":"requests","file":"src/requests/cookies.py","line":98,"symbol":"get_new_headers","kind":"function","lang":"python","code":"def get_new_headers(self) -> dict[str, str]:\n return self._new_headers"}
{"repo":"requests","file":"src/requests/cookies.py","line":102,"symbol":"unverifiable","kind":"function","lang":"python","code":"def unverifiable(self) -> bool:\n return self.is_unverifiable()"}
{"repo":"requests","file":"src/requests/cookies.py","line":106,"symbol":"origin_req_host","kind":"function","lang":"python","code":"def origin_req_host(self) -> str:\n return self.get_origin_req_host()"}
{"repo":"requests","file":"src/requests/cookies.py","line":110,"symbol":"host","kind":"function","lang":"python","code":"def host(self) -> str:\n return self.get_host()"}
{"repo":"requests","file":"src/requests/cookies.py","line":114,"symbol":"MockResponse","kind":"class","lang":"python","code":"class MockResponse:\n \"\"\"Wraps a `httplib.HTTPMessage` to mimic a `urllib.addinfourl`.\n\n ...what? Basically, expose the parsed HTTP headers from the server response\n the way `http.cookiejar` expects to see them.\n \"\"\"\n\n def __init__(self, headers: Any) -> None:\n \"\"\"Make a MockResponse for `cookiejar` to read.\n\n :param headers: a httplib.HTTPMessage or analogous carrying the headers\n \"\"\"\n self._headers = headers\n\n def info(self) -> Any:\n return self._headers\n\n def getheaders(self, name: str) -> Any:\n self._headers.getheaders(name)"}
{"repo":"requests","file":"src/requests/cookies.py","line":121,"symbol":"__init__","kind":"function","lang":"python","code":"def __init__(self, headers: Any) -> None:\n \"\"\"Make a MockResponse for `cookiejar` to read.\n\n :param headers: a httplib.HTTPMessage or analogous carrying the headers\n \"\"\"\n self._headers = headers"}
{"repo":"requests","file":"src/requests/cookies.py","line":128,"symbol":"info","kind":"function","lang":"python","code":"def info(self) -> Any:\n return self._headers"}
{"repo":"requests","file":"src/requests/cookies.py","line":131,"symbol":"getheaders","kind":"function","lang":"python","code":"def getheaders(self, name: str) -> Any:\n self._headers.getheaders(name)"}
{"repo":"requests","file":"src/requests/cookies.py","line":135,"symbol":"extract_cookies_to_jar","kind":"function","lang":"python","code":"def extract_cookies_to_jar(\n jar: CookieJar, request: PreparedRequest, response: Any\n) -> None:\n \"\"\"Extract the cookies from the response into a CookieJar.\n\n :param jar: http.cookiejar.CookieJar (not necessarily a RequestsCookieJar)\n :param request: our own requests.Request object\n :param response: urllib3.HTTPResponse object\n \"\"\"\n if not (hasattr(response, \"_original_response\") and response._original_response):\n return\n # the _original_response field is the wrapped httplib.HTTPResponse object,\n req = MockRequest(request)\n # pull out the HTTPMessage with the headers and put it in the mock:\n res = MockResponse(response._original_response.msg)\n jar.extract_cookies(res, req) # type: ignore[arg-type]"}
{"repo":"requests","file":"src/requests/cookies.py","line":153,"symbol":"get_cookie_header","kind":"function","lang":"python","code":"def get_cookie_header(jar: CookieJar, request: PreparedRequest) -> str | None:\n \"\"\"\n Produce an appropriate Cookie header string to be sent with `request`, or None.\n\n :rtype: str\n \"\"\"\n r = MockRequest(request)\n jar.add_cookie_header(r) # type: ignore[arg-type]\n return r.get_new_headers().get(\"Cookie\")"}
{"repo":"requests","file":"src/requests/cookies.py","line":164,"symbol":"remove_cookie_by_name","kind":"function","lang":"python","code":"def remove_cookie_by_name(\n cookiejar: CookieJar, name: str, domain: str | None = None, path: str | None = None\n) -> None:\n \"\"\"Unsets a cookie by name, by default over all domains and paths.\n\n Wraps CookieJar.clear(), is O(n).\n \"\"\"\n clearables: list[tuple[str, str, str]] = []\n for cookie in cookiejar:\n if cookie.name != name:\n continue\n if domain is not None and domain != cookie.domain:\n continue\n if path is not None and path != cookie.path:\n continue\n clearables.append((cookie.domain, cookie.path, cookie.name))\n\n for domain, path, name in clearables:\n cookiejar.clear(domain, path, name)"}
{"repo":"requests","file":"src/requests/cookies.py","line":185,"symbol":"CookieConflictError","kind":"class","lang":"python","code":"class CookieConflictError(RuntimeError):\n \"\"\"There are two cookies that meet the criteria specified in the cookie jar.\n Use .get and .set and include domain and path args in order to be more specific.\n \"\"\""}
{"repo":"requests","file":"src/requests/cookies.py","line":191,"symbol":"RequestsCookieJar","kind":"class","lang":"python","code":"class RequestsCookieJar(CookieJar, MutableMapping[str, str | None]): # type: ignore[misc]\n \"\"\"Compatibility class; is a http.cookiejar.CookieJar, but exposes a dict\n interface.\n\n This is the CookieJar we create by default for requests and sessions that\n don't specify one, since some clients may expect response.cookies and\n session.cookies to support dict operations.\n\n Requests does not use the dict interface internally; it's just for\n compatibility with external client code. All requests code should work\n out of the box with externally provided instances of ``CookieJar``, e.g.\n ``LWPCookieJar`` and ``FileCookieJar``.\n\n Unlike a regular CookieJar, this class is pickleable.\n\n .. warning:: dictionary operations that are normally O(1) may be O(n).\n \"\"\"\n\n _policy: CookiePolicy\n\n def get( # type: ignore[override]\n self,\n name: str,\n default: str | None = None,\n domain: str | None = None,\n path: str | None = None,\n ) -> str | None:\n \"\"\"Dict-like get() that also supports optional domain and path args in\n order to resolve naming collisions from using one cookie jar over\n multiple domains.\n"}
{"repo":"requests","file":"src/requests/cookies.py","line":211,"symbol":"get","kind":"function","lang":"python","code":"def get( # type: ignore[override]\n self,\n name: str,\n default: str | None = None,\n domain: str | None = None,\n path: str | None = None,\n ) -> str | None:\n \"\"\"Dict-like get() that also supports optional domain and path args in\n order to resolve naming collisions from using one cookie jar over\n multiple domains.\n\n .. warning:: operation is O(n), not O(1).\n \"\"\"\n try:\n return self._find_no_duplicates(name, domain, path)\n except KeyError:\n return default"}
{"repo":"requests","file":"src/requests/cookies.py","line":229,"symbol":"set","kind":"function","lang":"python","code":"def set(\n self, name: str, value: str | Morsel[dict[str, str]] | None, **kwargs: Any\n ) -> Cookie | None:\n \"\"\"Dict-like set() that also supports optional domain and path args in\n order to resolve naming collisions from using one cookie jar over\n multiple domains.\n \"\"\"\n # support client code that unsets cookies by assignment of a None value:\n if value is None:\n remove_cookie_by_name(\n self, name, domain=kwargs.get(\"domain\"), path=kwargs.get(\"path\")\n )\n return\n\n if isinstance(value, Morsel):\n c = morsel_to_cookie(value)\n else:\n c = create_cookie(name, value, **kwargs)\n self.set_cookie(c)\n return c"}
{"repo":"requests","file":"src/requests/cookies.py","line":250,"symbol":"iterkeys","kind":"function","lang":"python","code":"def iterkeys(self) -> Iterator[str]:\n \"\"\"Dict-like iterkeys() that returns an iterator of names of cookies\n from the jar.\n\n .. seealso:: itervalues() and iteritems().\n \"\"\"\n for cookie in iter(self):\n yield cookie.name"}
{"repo":"requests","file":"src/requests/cookies.py","line":259,"symbol":"keys","kind":"function","lang":"python","code":"def keys(self) -> list[str]: # type: ignore[override]\n \"\"\"Dict-like keys() that returns a list of names of cookies from the\n jar.\n\n .. seealso:: values() and items().\n \"\"\"\n return list(self.iterkeys())"}
{"repo":"requests","file":"src/requests/cookies.py","line":267,"symbol":"itervalues","kind":"function","lang":"python","code":"def itervalues(self) -> Iterator[str | None]:\n \"\"\"Dict-like itervalues() that returns an iterator of values of cookies\n from the jar.\n\n .. seealso:: iterkeys() and iteritems().\n \"\"\"\n for cookie in iter(self):\n yield cookie.value"}
{"repo":"requests","file":"src/requests/cookies.py","line":276,"symbol":"values","kind":"function","lang":"python","code":"def values(self) -> list[str | None]: # type: ignore[override]\n \"\"\"Dict-like values() that returns a list of values of cookies from the\n jar.\n\n .. seealso:: keys() and items().\n \"\"\"\n return list(self.itervalues())"}
{"repo":"requests","file":"src/requests/cookies.py","line":284,"symbol":"iteritems","kind":"function","lang":"python","code":"def iteritems(self) -> Iterator[tuple[str, str | None]]:\n \"\"\"Dict-like iteritems() that returns an iterator of name-value tuples\n from the jar.\n\n .. seealso:: iterkeys() and itervalues().\n \"\"\"\n for cookie in iter(self):\n yield cookie.name, cookie.value"}
{"repo":"requests","file":"src/requests/cookies.py","line":293,"symbol":"items","kind":"function","lang":"python","code":"def items(self) -> list[tuple[str, str | None]]: # type: ignore[override]\n \"\"\"Dict-like items() that returns a list of name-value tuples from the\n jar. Allows client-code to call ``dict(RequestsCookieJar)`` and get a\n vanilla python dict of key value pairs.\n\n .. seealso:: keys() and values().\n \"\"\"\n return list(self.iteritems())"}
{"repo":"requests","file":"src/requests/cookies.py","line":302,"symbol":"list_domains","kind":"function","lang":"python","code":"def list_domains(self) -> list[str]:\n \"\"\"Utility method to list all the domains in the jar.\"\"\"\n domains: list[str] = []\n for cookie in iter(self):\n if cookie.domain not in domains:\n domains.append(cookie.domain)\n return domains"}
{"repo":"requests","file":"src/requests/cookies.py","line":310,"symbol":"list_paths","kind":"function","lang":"python","code":"def list_paths(self) -> list[str]:\n \"\"\"Utility method to list all the paths in the jar.\"\"\"\n paths: list[str] = []\n for cookie in iter(self):\n if cookie.path not in paths:\n paths.append(cookie.path)\n return paths"}
{"repo":"requests","file":"src/requests/cookies.py","line":318,"symbol":"multiple_domains","kind":"function","lang":"python","code":"def multiple_domains(self) -> bool:\n \"\"\"Returns True if there are multiple domains in the jar.\n Returns False otherwise.\n\n :rtype: bool\n \"\"\"\n domains: list[str] = []\n for cookie in iter(self):\n if cookie.domain is not None and cookie.domain in domains: # type: ignore[reportUnnecessaryComparison] # defensive check\n return True\n domains.append(cookie.domain)\n return False # there is only one domain in jar"}
{"repo":"requests","file":"src/requests/cookies.py","line":331,"symbol":"get_dict","kind":"function","lang":"python","code":"def get_dict(\n self, domain: str | None = None, path: str | None = None\n ) -> dict[str, str | None]:\n \"\"\"Takes as an argument an optional domain and path and returns a plain\n old Python dict of name-value pairs of cookies that meet the\n requirements.\n\n :rtype: dict\n \"\"\"\n dictionary: dict[str, str | None] = {}\n for cookie in iter(self):\n if (domain is None or cookie.domain == domain) and (\n path is None or cookie.path == path\n ):\n dictionary[cookie.name] = cookie.value\n return dictionary"}
{"repo":"requests","file":"src/requests/cookies.py","line":348,"symbol":"__iter__","kind":"function","lang":"python","code":"def __iter__(self) -> Iterator[Cookie]: # type: ignore[override]\n \"\"\"RequestCookieJar's __iter__ comes from CookieJar not MutableMapping.\"\"\"\n return super().__iter__()"}
{"repo":"requests","file":"src/requests/cookies.py","line":352,"symbol":"__contains__","kind":"function","lang":"python","code":"def __contains__(self, name: object) -> bool:\n try:\n return super().__contains__(name)\n except CookieConflictError:\n return True"}
{"repo":"requests","file":"src/requests/cookies.py","line":358,"symbol":"__getitem__","kind":"function","lang":"python","code":"def __getitem__(self, name: str) -> str | None:\n \"\"\"Dict-like __getitem__() for compatibility with client code. Throws\n exception if there are more than one cookie with name. In that case,\n use the more explicit get() method instead.\n\n .. warning:: operation is O(n), not O(1).\n \"\"\"\n return self._find_no_duplicates(name)"}
{"repo":"requests","file":"src/requests/cookies.py","line":367,"symbol":"__setitem__","kind":"function","lang":"python","code":"def __setitem__(\n self, name: str, value: str | Morsel[dict[str, str]] | None\n ) -> None:\n \"\"\"Dict-like __setitem__ for compatibility with client code. Throws\n exception if there is already a cookie of that name in the jar. In that\n case, use the more explicit set() method instead.\n \"\"\"\n self.set(name, value)"}
{"repo":"requests","file":"src/requests/cookies.py","line":376,"symbol":"__delitem__","kind":"function","lang":"python","code":"def __delitem__(self, name: str) -> None:\n \"\"\"Deletes a cookie given a name. Wraps ``http.cookiejar.CookieJar``'s\n ``remove_cookie_by_name()``.\n \"\"\"\n remove_cookie_by_name(self, name)"}
{"repo":"requests","file":"src/requests/cookies.py","line":382,"symbol":"set_cookie","kind":"function","lang":"python","code":"def set_cookie(self, cookie: Cookie, *args: Any, **kwargs: Any) -> None:\n if (\n (value := cookie.value) is not None\n and value.startswith('\"')\n and value.endswith('\"')\n ):\n cookie.value = value.replace('\\\\\"', \"\")\n return super().set_cookie(cookie, *args, **kwargs)"}
{"repo":"requests","file":"src/requests/cookies.py","line":391,"symbol":"update","kind":"function","lang":"python","code":"def update( # type: ignore[override]\n self, other: CookieJar | SupportsKeysAndGetItem[str, str]\n ) -> None:\n \"\"\"Updates this jar with cookies from another CookieJar or dict-like\"\"\"\n if isinstance(other, cookielib.CookieJar):\n for cookie in other:\n self.set_cookie(copy.copy(cookie))\n else:\n super().update(other)"}
{"repo":"requests","file":"src/requests/cookies.py","line":401,"symbol":"_find","kind":"function","lang":"python","code":"def _find(\n self, name: str, domain: str | None = None, path: str | None = None\n ) -> str | None:\n \"\"\"Requests uses this method internally to get cookie values.\n\n If there are conflicting cookies, _find arbitrarily chooses one.\n See _find_no_duplicates if you want an exception thrown if there are\n conflicting cookies.\n\n :param name: a string containing name of cookie\n :param domain: (optional) string containing domain of cookie\n :param path: (optional) string containing path of cookie\n :return: cookie.value\n \"\"\"\n for cookie in iter(self):\n if cookie.name == name:\n if domain is None or cookie.domain == domain:\n if path is None or cookie.path == path:\n return cookie.value\n\n raise KeyError(f\"name={name!r}, domain={domain!r}, path={path!r}\")"}
{"repo":"requests","file":"src/requests/cookies.py","line":423,"symbol":"_find_no_duplicates","kind":"function","lang":"python","code":"def _find_no_duplicates(\n self, name: str, domain: str | None = None, path: str | None = None\n ) -> str:\n \"\"\"Both ``__get_item__`` and ``get`` call this function: it's never\n used elsewhere in Requests.\n\n :param name: a string containing name of cookie\n :param domain: (optional) string containing domain of cookie\n :param path: (optional) string containing path of cookie\n :raises KeyError: if cookie is not found\n :raises CookieConflictError: if there are multiple cookies\n that match name and optionally domain and path\n :return: cookie.value\n \"\"\"\n toReturn = None\n for cookie in iter(self):\n if cookie.name == name:\n if domain is None or cookie.domain == domain:\n if path is None or cookie.path == path:\n if toReturn is not None:\n # if there are multiple cookies that meet passed in criteria\n raise CookieConflictError(\n f\"There are multiple cookies with name, {name!r}\"\n )\n # we will eventually"}
{"repo":"requests","file":"src/requests/cookies.py","line":454,"symbol":"__getstate__","kind":"function","lang":"python","code":"def __getstate__(self) -> dict[str, Any]:\n \"\"\"Unlike a normal CookieJar, this class is pickleable.\"\"\"\n state = self.__dict__.copy()\n # remove the unpickleable RLock object\n state.pop(\"_cookies_lock\")\n return state"}
{"repo":"requests","file":"src/requests/cookies.py","line":461,"symbol":"__setstate__","kind":"function","lang":"python","code":"def __setstate__(self, state: dict[str, Any]) -> None:\n \"\"\"Unlike a normal CookieJar, this class is pickleable.\"\"\"\n self.__dict__.update(state)\n if \"_cookies_lock\" not in self.__dict__:\n self._cookies_lock = threading.RLock()"}
{"repo":"requests","file":"src/requests/cookies.py","line":467,"symbol":"copy","kind":"function","lang":"python","code":"def copy(self) -> RequestsCookieJar:\n \"\"\"Return a copy of this RequestsCookieJar.\"\"\"\n new_cj = RequestsCookieJar()\n new_cj.set_policy(self.get_policy())\n new_cj.update(self)\n return new_cj"}
{"repo":"requests","file":"src/requests/cookies.py","line":474,"symbol":"get_policy","kind":"function","lang":"python","code":"def get_policy(self) -> CookiePolicy:\n \"\"\"Return the CookiePolicy instance used.\"\"\"\n return self._policy"}
{"repo":"requests","file":"src/requests/cookies.py","line":479,"symbol":"_copy_cookie_jar","kind":"function","lang":"python","code":"def _copy_cookie_jar(jar: CookieJar | None) -> CookieJar | None: # type: ignore[reportUnusedFunction] # cross-module usage in models.py\n if jar is None:\n return None\n\n if copy_method := getattr(jar, \"copy\", None):\n # We're dealing with an instance of RequestsCookieJar\n return copy_method()\n # We're dealing with a generic CookieJar instance\n new_jar = copy.copy(jar)\n new_jar.clear()\n for cookie in jar:\n new_jar.set_cookie(copy.copy(cookie))\n return new_jar"}
{"repo":"requests","file":"src/requests/cookies.py","line":494,"symbol":"create_cookie","kind":"function","lang":"python","code":"def create_cookie(name: str, value: str, **kwargs: Any) -> Cookie:\n \"\"\"Make a cookie from underspecified parameters.\n\n By default, the pair of `name` and `value` will be set for the domain ''\n and sent on every request (this is sometimes called a \"supercookie\").\n \"\"\"\n result: dict[str, Any] = {\n \"version\": 0,\n \"name\": name,\n \"value\": value,\n \"port\": None,\n \"domain\": \"\",\n \"path\": \"/\",\n \"secure\": False,\n \"expires\": None,\n \"discard\": True,\n \"comment\": None,\n \"comment_url\": None,\n \"rest\": {\"HttpOnly\": None},\n \"rfc2109\": False,\n }\n\n badargs = set(kwargs) - set(result)\n if badargs:\n raise TypeError(\n f\"create_cookie() got unexpected keyword arguments: {list(badargs)}\"\n )\n\n result.update(kwargs)\n result[\"port_specified\"] = bool(result[\"port\"])\n result[\"domain_specified\"] = bool(result[\"domain\"])\n result[\"domain_initial_dot\"] = result[\"domain\"].startswith(\".\")\n result[\"path_specified\"] = bool(result[\"path\"])\n\n return cookielib.Cookie(**result)"}
{"repo":"requests","file":"src/requests/cookies.py","line":531,"symbol":"morsel_to_cookie","kind":"function","lang":"python","code":"def morsel_to_cookie(morsel: Morsel[Any]) -> Cookie:\n \"\"\"Convert a Morsel object into a Cookie containing the one k/v pair.\"\"\"\n\n expires: int | None = None\n if morsel[\"max-age\"]:\n try:\n expires = int(time.time() + int(morsel[\"max-age\"]))\n except ValueError:\n raise TypeError(f\"max-age: {morsel['max-age']} must be integer\")\n elif morsel[\"expires\"]:\n time_template = \"%a, %d-%b-%Y %H:%M:%S GMT\"\n expires = calendar.timegm(time.strptime(morsel[\"expires\"], time_template))\n return create_cookie(\n comment=morsel[\"comment\"],\n comment_url=bool(morsel[\"comment\"]),\n discard=False,\n domain=morsel[\"domain\"],\n expires=expires,\n name=morsel.key,\n path=morsel[\"path\"],\n port=None,\n rest={\"HttpOnly\": morsel[\"httponly\"]},\n rfc2109=False,\n secure=bool(morsel[\"secure\"]),\n value=morsel.value,\n version=morsel[\"version\"] or 0,\n )"}
{"repo":"requests","file":"src/requests/cookies.py","line":564,"symbol":"cookiejar_from_dict","kind":"function","lang":"python","code":"def cookiejar_from_dict(\n cookie_dict: dict[str, str] | None,\n cookiejar: None = None,\n overwrite: bool = True,\n) -> RequestsCookieJar: ..."}
{"repo":"requests","file":"src/requests/cookies.py","line":572,"symbol":"cookiejar_from_dict","kind":"function","lang":"python","code":"def cookiejar_from_dict(\n cookie_dict: dict[str, str] | None,\n cookiejar: _CookieJarT,\n overwrite: bool = True,\n) -> _CookieJarT: ..."}
{"repo":"requests","file":"src/requests/cookies.py","line":579,"symbol":"cookiejar_from_dict","kind":"function","lang":"python","code":"def cookiejar_from_dict(\n cookie_dict: dict[str, str] | None,\n cookiejar: CookieJar | None = None,\n overwrite: bool = True,\n) -> CookieJar:\n \"\"\"Returns a CookieJar from a key/value dictionary.\n\n :param cookie_dict: Dict of key/values to insert into CookieJar.\n :param cookiejar: (optional) A cookiejar to add the cookies to.\n :param overwrite: (optional) If False, will not replace cookies\n already in the jar with new ones.\n :rtype: CookieJar\n \"\"\"\n if cookiejar is None:\n cookiejar = RequestsCookieJar()\n\n if cookie_dict is not None:\n names_from_jar = [cookie.name for cookie in cookiejar]\n for name in cookie_dict:\n if overwrite or (name not in names_from_jar):\n cookiejar.set_cookie(create_cookie(name, cookie_dict[name]))\n\n return cookiejar"}
{"repo":"requests","file":"src/requests/cookies.py","line":604,"symbol":"merge_cookies","kind":"function","lang":"python","code":"def merge_cookies(\n cookiejar: CookieJar, cookies: dict[str, str] | CookieJar | None\n) -> CookieJar:\n \"\"\"Add cookies to cookiejar and returns a merged CookieJar.\n\n :param cookiejar: CookieJar object to add the cookies to.\n :param cookies: Dictionary or CookieJar object to be added.\n :rtype: CookieJar\n \"\"\"\n if not isinstance(cookiejar, cookielib.CookieJar): # runtime guard\n raise ValueError(\"You can only merge into CookieJar\")\n\n if isinstance(cookies, dict):\n cookiejar = cookiejar_from_dict(cookies, cookiejar=cookiejar, overwrite=False)\n elif isinstance(cookies, cookielib.CookieJar):\n if update_method := getattr(cookiejar, \"update\", None):\n update_method(cookies)\n else:\n for cookie_in_jar in cookies:\n cookiejar.set_cookie(cookie_in_jar)\n\n return cookiejar"}
{"repo":"requests","file":"src/requests/exceptions.py","line":20,"symbol":"RequestException","kind":"class","lang":"python","code":"class RequestException(IOError):\n \"\"\"There was an ambiguous exception that occurred while handling your\n request.\n \"\"\"\n\n response: Response | None\n request: Request | PreparedRequest | None\n\n def __init__(self, *args: Any, **kwargs: Any) -> None:\n \"\"\"Initialize RequestException with `request` and `response` objects.\"\"\"\n response: Response | None = kwargs.pop(\"response\", None)\n self.response = response\n self.request = kwargs.pop(\"request\", None)\n if response is not None and not self.request and hasattr(response, \"request\"):\n self.request = response.request\n super().__init__(*args, **kwargs)"}
{"repo":"requests","file":"src/requests/exceptions.py","line":28,"symbol":"__init__","kind":"function","lang":"python","code":"def __init__(self, *args: Any, **kwargs: Any) -> None:\n \"\"\"Initialize RequestException with `request` and `response` objects.\"\"\"\n response: Response | None = kwargs.pop(\"response\", None)\n self.response = response\n self.request = kwargs.pop(\"request\", None)\n if response is not None and not self.request and hasattr(response, \"request\"):\n self.request = response.request\n super().__init__(*args, **kwargs)"}
{"repo":"requests","file":"src/requests/exceptions.py","line":38,"symbol":"InvalidJSONError","kind":"class","lang":"python","code":"class InvalidJSONError(RequestException):\n \"\"\"A JSON error occurred.\"\"\""}
{"repo":"requests","file":"src/requests/exceptions.py","line":42,"symbol":"JSONDecodeError","kind":"class","lang":"python","code":"class JSONDecodeError(InvalidJSONError, CompatJSONDecodeError):\n \"\"\"Couldn't decode the text into json\"\"\"\n\n def __init__(self, *args: Any, **kwargs: Any) -> None:\n \"\"\"\n Construct the JSONDecodeError instance first with all\n args. Then use it's args to construct the IOError so that\n the json specific args aren't used as IOError specific args\n and the error message from JSONDecodeError is preserved.\n \"\"\"\n CompatJSONDecodeError.__init__(self, *args)\n InvalidJSONError.__init__(self, *self.args, **kwargs)\n\n def __reduce__(self) -> tuple[Any, ...] | str:\n \"\"\"\n The __reduce__ method called when pickling the object must\n be the one from the JSONDecodeError (be it json/simplejson)\n as it expects all the arguments for instantiation, not just\n one like the IOError, and the MRO would by default call the\n __reduce__ method from the IOError due to the inheritance order.\n \"\"\"\n return CompatJSONDecodeError.__reduce__(self)"}
{"repo":"requests","file":"src/requests/exceptions.py","line":45,"symbol":"__init__","kind":"function","lang":"python","code":"def __init__(self, *args: Any, **kwargs: Any) -> None:\n \"\"\"\n Construct the JSONDecodeError instance first with all\n args. Then use it's args to construct the IOError so that\n the json specific args aren't used as IOError specific args\n and the error message from JSONDecodeError is preserved.\n \"\"\"\n CompatJSONDecodeError.__init__(self, *args)\n InvalidJSONError.__init__(self, *self.args, **kwargs)"}
{"repo":"requests","file":"src/requests/exceptions.py","line":55,"symbol":"__reduce__","kind":"function","lang":"python","code":"def __reduce__(self) -> tuple[Any, ...] | str:\n \"\"\"\n The __reduce__ method called when pickling the object must\n be the one from the JSONDecodeError (be it json/simplejson)\n as it expects all the arguments for instantiation, not just\n one like the IOError, and the MRO would by default call the\n __reduce__ method from the IOError due to the inheritance order.\n \"\"\"\n return CompatJSONDecodeError.__reduce__(self)"}
{"repo":"requests","file":"src/requests/exceptions.py","line":66,"symbol":"HTTPError","kind":"class","lang":"python","code":"class HTTPError(RequestException):\n \"\"\"An HTTP error occurred.\"\"\""}
{"repo":"requests","file":"src/requests/exceptions.py","line":70,"symbol":"ConnectionError","kind":"class","lang":"python","code":"class ConnectionError(RequestException):\n \"\"\"A Connection error occurred.\"\"\""}
{"repo":"requests","file":"src/requests/exceptions.py","line":74,"symbol":"ProxyError","kind":"class","lang":"python","code":"class ProxyError(ConnectionError):\n \"\"\"A proxy error occurred.\"\"\""}
{"repo":"requests","file":"src/requests/exceptions.py","line":78,"symbol":"SSLError","kind":"class","lang":"python","code":"class SSLError(ConnectionError):\n \"\"\"An SSL error occurred.\"\"\""}
{"repo":"requests","file":"src/requests/exceptions.py","line":82,"symbol":"Timeout","kind":"class","lang":"python","code":"class Timeout(RequestException):\n \"\"\"The request timed out.\n\n Catching this error will catch both\n :exc:`~requests.exceptions.ConnectTimeout` and\n :exc:`~requests.exceptions.ReadTimeout` errors.\n \"\"\""}
{"repo":"requests","file":"src/requests/exceptions.py","line":91,"symbol":"ConnectTimeout","kind":"class","lang":"python","code":"class ConnectTimeout(ConnectionError, Timeout):\n \"\"\"The request timed out while trying to connect to the remote server.\n\n Requests that produced this error are safe to retry.\n \"\"\""}
{"repo":"requests","file":"src/requests/exceptions.py","line":98,"symbol":"ReadTimeout","kind":"class","lang":"python","code":"class ReadTimeout(Timeout):\n \"\"\"The server did not send any data in the allotted amount of time.\"\"\""}
{"repo":"requests","file":"src/requests/exceptions.py","line":102,"symbol":"URLRequired","kind":"class","lang":"python","code":"class URLRequired(RequestException):\n \"\"\"A valid URL is required to make a request.\"\"\""}
{"repo":"requests","file":"src/requests/exceptions.py","line":106,"symbol":"TooManyRedirects","kind":"class","lang":"python","code":"class TooManyRedirects(RequestException):\n \"\"\"Too many redirects.\"\"\""}
{"repo":"requests","file":"src/requests/exceptions.py","line":110,"symbol":"MissingSchema","kind":"class","lang":"python","code":"class MissingSchema(RequestException, ValueError):\n \"\"\"The URL scheme (e.g. http or https) is missing.\"\"\""}
{"repo":"requests","file":"src/requests/exceptions.py","line":114,"symbol":"InvalidSchema","kind":"class","lang":"python","code":"class InvalidSchema(RequestException, ValueError):\n \"\"\"The URL scheme provided is either invalid or unsupported.\"\"\""}
{"repo":"requests","file":"src/requests/exceptions.py","line":118,"symbol":"InvalidURL","kind":"class","lang":"python","code":"class InvalidURL(RequestException, ValueError):\n \"\"\"The URL provided was somehow invalid.\"\"\""}
{"repo":"requests","file":"src/requests/exceptions.py","line":122,"symbol":"InvalidHeader","kind":"class","lang":"python","code":"class InvalidHeader(RequestException, ValueError):\n \"\"\"The header value provided was somehow invalid.\"\"\""}
{"repo":"requests","file":"src/requests/exceptions.py","line":126,"symbol":"InvalidProxyURL","kind":"class","lang":"python","code":"class InvalidProxyURL(InvalidURL):\n \"\"\"The proxy URL provided is invalid.\"\"\""}
{"repo":"requests","file":"src/requests/exceptions.py","line":130,"symbol":"ChunkedEncodingError","kind":"class","lang":"python","code":"class ChunkedEncodingError(RequestException):\n \"\"\"The server declared chunked encoding but sent an invalid chunk.\"\"\""}
{"repo":"requests","file":"src/requests/exceptions.py","line":134,"symbol":"ContentDecodingError","kind":"class","lang":"python","code":"class ContentDecodingError(RequestException, BaseHTTPError):\n \"\"\"Failed to decode response content.\"\"\""}
{"repo":"requests","file":"src/requests/exceptions.py","line":138,"symbol":"StreamConsumedError","kind":"class","lang":"python","code":"class StreamConsumedError(RequestException, TypeError):\n \"\"\"The content for this response was already consumed.\"\"\""}
{"repo":"requests","file":"src/requests/exceptions.py","line":142,"symbol":"RetryError","kind":"class","lang":"python","code":"class RetryError(RequestException):\n \"\"\"Custom retries logic failed\"\"\""}
{"repo":"requests","file":"src/requests/exceptions.py","line":146,"symbol":"UnrewindableBodyError","kind":"class","lang":"python","code":"class UnrewindableBodyError(RequestException):\n \"\"\"Requests encountered an error when trying to rewind a body.\"\"\""}
{"repo":"requests","file":"src/requests/exceptions.py","line":153,"symbol":"RequestsWarning","kind":"class","lang":"python","code":"class RequestsWarning(Warning):\n \"\"\"Base warning for Requests.\"\"\""}
{"repo":"requests","file":"src/requests/exceptions.py","line":157,"symbol":"FileModeWarning","kind":"class","lang":"python","code":"class FileModeWarning(RequestsWarning, DeprecationWarning):\n \"\"\"A file was opened in text mode, but Requests determined its binary length.\"\"\""}
{"repo":"requests","file":"src/requests/exceptions.py","line":161,"symbol":"RequestsDependencyWarning","kind":"class","lang":"python","code":"class RequestsDependencyWarning(RequestsWarning):\n \"\"\"An imported dependency doesn't match the expected version range.\"\"\""}
{"repo":"requests","file":"src/requests/help.py","line":35,"symbol":"_implementation","kind":"function","lang":"python","code":"def _implementation():\n \"\"\"Return a dict with the Python implementation and version.\n\n Provide both the name and the version of the Python implementation\n currently running. For example, on CPython 3.10.3 it will return\n {'name': 'CPython', 'version': '3.10.3'}.\n\n This function works best on CPython and PyPy: in particular, it probably\n doesn't work for Jython or IronPython. Future investigation should be done\n to work out the correct shape of the code for those platforms.\n \"\"\"\n implementation = platform.python_implementation()\n\n if implementation == \"CPython\":\n implementation_version = platform.python_version()\n elif implementation == \"PyPy\":\n pypy = sys.pypy_version_info # type: ignore[attr-defined]\n implementation_version = f\"{pypy.major}.{pypy.minor}.{pypy.micro}\" # pyright: ignore[reportUnknownMemberType]\n if sys.pypy_version_info.releaselevel != \"final\": # type: ignore[attr-defined]\n implementation_version = \"\".join(\n [implementation_version, sys.pypy_version_info.releaselevel] # type: ignore[attr-defined]\n )\n elif implementation == \"Jython\":\n implementation_version"}
{"repo":"requests","file":"src/requests/help.py","line":67,"symbol":"info","kind":"function","lang":"python","code":"def info() -> dict[str, Any]:\n \"\"\"Generate information for a bug report.\"\"\"\n try:\n platform_info = {\n \"system\": platform.system(),\n \"release\": platform.release(),\n }\n except OSError:\n platform_info = {\n \"system\": \"Unknown\",\n \"release\": \"Unknown\",\n }\n\n implementation_info = _implementation()\n urllib3_info = {\"version\": urllib3.__version__}\n charset_normalizer_info = {\"version\": None}\n chardet_info: dict[str, str | None] = {\"version\": None}\n if charset_normalizer:\n charset_normalizer_info = {\"version\": charset_normalizer.__version__}\n if chardet:\n chardet_info = {\"version\": chardet.__version__}\n\n pyopenssl_info: dict[str, str | None] = {\n \"version\": None,\n \"openssl_version\": \"\",\n }\n if OpenSSL:\n pyopenssl_info = {\n \"version\": OpenSSL.__version__,\n \"openssl_version\": f\"{OpenSSL.SSL.OPENSSL_VERSION_NUMBER:x}\",\n }\n cryptography_info = {\n \"version\": getattr(cryptography, \"__version__\", \"\"),\n }\n idna_info = {\n \"version\": getattr(idna, \"__version__\", \"\"),\n }\n\n system_ssl = ssl.OPENSSL_VERSION"}
{"repo":"requests","file":"src/requests/help.py","line":126,"symbol":"main","kind":"function","lang":"python","code":"def main():\n \"\"\"Pretty-print the bug information as JSON.\"\"\"\n print(json.dumps(info(), sort_keys=True, indent=2))"}
{"repo":"requests","file":"src/requests/hooks.py","line":25,"symbol":"default_hooks","kind":"function","lang":"python","code":"def default_hooks() -> dict[str, list[_t.HookType]]:\n return {event: [] for event in HOOKS}"}
{"repo":"requests","file":"src/requests/hooks.py","line":32,"symbol":"dispatch_hook","kind":"function","lang":"python","code":"def dispatch_hook(\n key: str,\n hooks: _t.HooksInputType | None,\n hook_data: Response,\n **kwargs: Any,\n) -> Response:\n \"\"\"Dispatches a hook dictionary on a given piece of data.\"\"\"\n hooks_dict = hooks or {}\n hook_list: Iterable[_t.HookType] | _t.HookType | None = hooks_dict.get(key)\n if hook_list:\n if isinstance(hook_list, Callable):\n hook_list = [hook_list]\n for hook in hook_list:\n _hook_data = hook(hook_data, **kwargs)\n if _hook_data is not None:\n hook_data = _hook_data\n return hook_data"}
{"repo":"requests","file":"src/requests/models.py","line":108,"symbol":"RequestEncodingMixin","kind":"class","lang":"python","code":"class RequestEncodingMixin:\n url: str | None\n\n @property\n def path_url(self) -> str:\n \"\"\"Build the path URL to use.\"\"\"\n\n url: list[str] = []\n\n p = urlsplit(cast(str, self.url))\n\n path = p.path\n if not path:\n path = \"/\"\n\n url.append(path)\n\n query = p.query\n if query:\n url.append(\"?\")\n url.append(query)\n\n return \"\".join(url)\n\n @overload\n @staticmethod\n def _encode_params(data: str) -> str: ...\n\n @overload\n @staticmethod\n def _encode_params(data: bytes) -> bytes: ...\n\n @overload\n @staticmethod\n def _encode_params(\n data: _t.SupportsRead[str | bytes],\n ) -> _t.SupportsRead[str | bytes]: ...\n\n @overload\n @staticmethod\n def _encode_params(data: _t.KVDataType) -> str: ...\n\n @staticmethod\n def _encode_params(\n data: _t.EncodableDataType,\n ) -> str | bytes | _t.SupportsRead[str | bytes]:\n \"\"\"Encode parameters in a piece of data.\n\n Will successfully encode parameters when passed as a dict or a list of\n 2-tuples. Order is retained if data is a list of 2-tuples but arbitrary\n if parameters are supplied"}
{"repo":"requests","file":"src/requests/models.py","line":112,"symbol":"path_url","kind":"function","lang":"python","code":"def path_url(self) -> str:\n \"\"\"Build the path URL to use.\"\"\"\n\n url: list[str] = []\n\n p = urlsplit(cast(str, self.url))\n\n path = p.path\n if not path:\n path = \"/\"\n\n url.append(path)\n\n query = p.query\n if query:\n url.append(\"?\")\n url.append(query)\n\n return \"\".join(url)"}
{"repo":"requests","file":"src/requests/models.py","line":134,"symbol":"_encode_params","kind":"function","lang":"python","code":"def _encode_params(data: str) -> str: ..."}
{"repo":"requests","file":"src/requests/models.py","line":138,"symbol":"_encode_params","kind":"function","lang":"python","code":"def _encode_params(data: bytes) -> bytes: ..."}
{"repo":"requests","file":"src/requests/models.py","line":142,"symbol":"_encode_params","kind":"function","lang":"python","code":"def _encode_params(\n data: _t.SupportsRead[str | bytes],\n ) -> _t.SupportsRead[str | bytes]: ..."}
{"repo":"requests","file":"src/requests/models.py","line":148,"symbol":"_encode_params","kind":"function","lang":"python","code":"def _encode_params(data: _t.KVDataType) -> str: ..."}
{"repo":"requests","file":"src/requests/models.py","line":151,"symbol":"_encode_params","kind":"function","lang":"python","code":"def _encode_params(\n data: _t.EncodableDataType,\n ) -> str | bytes | _t.SupportsRead[str | bytes]:\n \"\"\"Encode parameters in a piece of data.\n\n Will successfully encode parameters when passed as a dict or a list of\n 2-tuples. Order is retained if data is a list of 2-tuples but arbitrary\n if parameters are supplied as a dict.\n \"\"\"\n\n if isinstance(data, (str, bytes)):\n return data\n elif _t.has_read(data):\n return data\n elif hasattr(data, \"__iter__\"):\n result: list[tuple[bytes, bytes]] = []\n for k, vs in to_key_val_list(data):\n if isinstance(vs, basestring) or not hasattr(vs, \"__iter__\"):\n vs = [vs]\n for v in vs:\n if v is not None:\n result.append(\n (\n k.encode(\"utf-8\") if isinstance(k, str) else k,\n v.encode(\"utf-8\") if isinstance(v, str) else v,\n )\n )\n return urlencode(result, doseq=True)\n else:\n return data # type: ignor"}
{"repo":"requests","file":"src/requests/models.py","line":183,"symbol":"_encode_files","kind":"function","lang":"python","code":"def _encode_files(\n files: _t.FilesType, data: _t.RawDataType | None\n ) -> tuple[bytes, str]:\n \"\"\"Build the body for a multipart/form-data request.\n\n Will successfully encode files when passed as a dict or a list of\n tuples. Order is retained if data is a list of tuples but arbitrary\n if parameters are supplied as a dict.\n The tuples may be 2-tuples (filename, fileobj), 3-tuples (filename, fileobj, contentype)\n or 4-tuples (filename, fileobj, contentype, custom_headers).\n \"\"\"\n if not files:\n raise ValueError(\"Files must be provided.\")\n elif isinstance(data, basestring):\n raise ValueError(\"Data must not be a string.\")\n\n new_fields: list[RequestField | tuple[str, bytes]] = []\n fields = to_key_val_list(data or {})\n files = to_key_val_list(files or {})\n\n for field, val in fields:\n if isinstance(val, basestring) or not hasattr(val, \"__iter__\"):\n val = [val]\n for v in val:\n if v is not None:\n # Don't call str() on bytestrings: in Py3 it all goes wrong.\n if not isinstance(v, byte"}
{"repo":"requests","file":"src/requests/models.py","line":254,"symbol":"RequestHooksMixin","kind":"class","lang":"python","code":"class RequestHooksMixin:\n hooks: dict[str, list[_t.HookType]]\n\n def register_hook(\n self, event: str, hook: Iterable[_t.HookType] | _t.HookType\n ) -> None:\n \"\"\"Properly register a hook.\"\"\"\n\n if event not in self.hooks:\n raise ValueError(f'Unsupported event specified, with event name \"{event}\"')\n\n if isinstance(hook, Callable):\n self.hooks[event].append(hook)\n elif hasattr(hook, \"__iter__\"):\n self.hooks[event].extend(\n h for h in hook if isinstance(h, Callable)\n ) # defensive runtime filter\n\n def deregister_hook(self, event: str, hook: _t.HookType) -> bool:\n \"\"\"Deregister a previously registered hook.\n Returns True if the hook existed, False if not.\n \"\"\"\n\n try:\n self.hooks[event].remove(hook)\n return True\n except ValueError:\n return False"}
{"repo":"requests","file":"src/requests/models.py","line":257,"symbol":"register_hook","kind":"function","lang":"python","code":"def register_hook(\n self, event: str, hook: Iterable[_t.HookType] | _t.HookType\n ) -> None:\n \"\"\"Properly register a hook.\"\"\"\n\n if event not in self.hooks:\n raise ValueError(f'Unsupported event specified, with event name \"{event}\"')\n\n if isinstance(hook, Callable):\n self.hooks[event].append(hook)\n elif hasattr(hook, \"__iter__\"):\n self.hooks[event].extend(\n h for h in hook if isinstance(h, Callable)\n ) # defensive runtime filter"}
{"repo":"requests","file":"src/requests/models.py","line":272,"symbol":"deregister_hook","kind":"function","lang":"python","code":"def deregister_hook(self, event: str, hook: _t.HookType) -> bool:\n \"\"\"Deregister a previously registered hook.\n Returns True if the hook existed, False if not.\n \"\"\"\n\n try:\n self.hooks[event].remove(hook)\n return True\n except ValueError:\n return False"}
{"repo":"requests","file":"src/requests/models.py","line":284,"symbol":"Request","kind":"class","lang":"python","code":"class Request(RequestHooksMixin):\n \"\"\"A user-created :class:`Request <Request>` object.\n\n Used to prepare a :class:`PreparedRequest <PreparedRequest>`, which is sent to the server.\n\n :param method: HTTP method to use.\n :param url: URL to send.\n :param headers: dictionary of headers to send.\n :param files: dictionary of {filename: fileobject} files to multipart upload.\n :param data: the body to attach to the request. If a dictionary or\n list of tuples ``[(key, value)]`` is provided, form-encoding will\n take place.\n :param json: json for the body to attach to the request (if files or data is not specified).\n :param params: URL parameters to append to the URL. If a dictionary or\n list of tuples ``[(key, value)]`` is provided, form-encoding will\n take place.\n :param auth: Auth handler or (user, pass) tuple.\n :param cookies: dictionary or CookieJar of cookies to attach to this request.\n :param hooks: dictionary of callback hooks, for internal usage.\n\n Usage::\n\n >>> import requests\n >>> req = requests.Request('GET', 'https://httpbin.org/get')\n >>> req.prepare()\n <PreparedRequest [GET]>\n \"\"\"\n\n hoo"}
{"repo":"requests","file":"src/requests/models.py","line":323,"symbol":"__init__","kind":"function","lang":"python","code":"def __init__(\n self,\n method: str | None = None,\n url: _t.UriType | None = None,\n headers: _t.HeadersType = None,\n files: _t.FilesType = None,\n data: _t.DataType = None,\n params: _t.ParamsType = None,\n auth: _t.AuthType = None,\n cookies: RequestsCookieJar | CookieJar | dict[str, str] | None = None,\n hooks: _t.HooksInputType | None = None,\n json: _t.JsonType = None,\n ) -> None:\n # Default empty dicts for dict params.\n data = [] if data is None else data\n files = [] if files is None else files\n headers = {} if headers is None else headers\n params = {} if params is None else params\n hooks = {} if hooks is None else hooks\n\n self.hooks = default_hooks()\n for k, v in list(hooks.items()):\n self.register_hook(event=k, hook=v)\n\n self.method = method\n self.url = url\n self.headers = headers\n self.files = files\n self.data = data\n self.json = json\n self.params = params\n self.auth = auth\n self.cookies = cookies"}
{"repo":"requests","file":"src/requests/models.py","line":357,"symbol":"__repr__","kind":"function","lang":"python","code":"def __repr__(self) -> str:\n return f\"<Request [{self.method}]>\""}
{"repo":"requests","file":"src/requests/models.py","line":360,"symbol":"prepare","kind":"function","lang":"python","code":"def prepare(self) -> PreparedRequest:\n \"\"\"Constructs a :class:`PreparedRequest <PreparedRequest>` for transmission and returns it.\"\"\"\n p = PreparedRequest()\n p.prepare(\n method=self.method,\n url=self.url,\n headers=self.headers,\n files=self.files,\n data=self.data,\n json=self.json,\n params=self.params,\n auth=self.auth,\n cookies=self.cookies,\n hooks=self.hooks,\n )\n return p"}
{"repo":"requests","file":"src/requests/models.py","line":378,"symbol":"PreparedRequest","kind":"class","lang":"python","code":"class PreparedRequest(RequestEncodingMixin, RequestHooksMixin):\n \"\"\"The fully mutable :class:`PreparedRequest <PreparedRequest>` object,\n containing the exact bytes that will be sent to the server.\n\n Instances are generated from a :class:`Request <Request>` object, and\n should not be instantiated manually; doing so may produce undesirable\n effects.\n\n Usage::\n\n >>> import requests\n >>> req = requests.Request('GET', 'https://httpbin.org/get')\n >>> r = req.prepare()\n >>> r\n <PreparedRequest [GET]>\n\n >>> s = requests.Session()\n >>> s.send(r)\n <Response [200]>\n \"\"\"\n\n method: str | None\n url: str | None\n headers: CaseInsensitiveDict[str | bytes]\n _cookies: RequestsCookieJar | CookieJar | None\n body: _t.BodyType\n hooks: dict[str, list[_t.HookType]]\n _body_position: int | object | None\n\n def __init__(self) -> None:\n #: HTTP verb to send to the server.\n self.method = None\n #: HTTP URL to send the request to.\n self.url = None\n #: dictionary of HTTP headers.\n self.headers = None # type: ignore[assignment]\n # The `CookieJar` used to create the Cookie header wil"}
{"repo":"requests","file":"src/requests/models.py","line":407,"symbol":"__init__","kind":"function","lang":"python","code":"def __init__(self) -> None:\n #: HTTP verb to send to the server.\n self.method = None\n #: HTTP URL to send the request to.\n self.url = None\n #: dictionary of HTTP headers.\n self.headers = None # type: ignore[assignment]\n # The `CookieJar` used to create the Cookie header will be stored here\n # after prepare_cookies is called\n self._cookies = None\n #: request body to send to the server.\n self.body = None\n #: dictionary of callback hooks, for internal usage.\n self.hooks = default_hooks()\n #: integer denoting starting position of a readable file-like body.\n self._body_position = None"}
{"repo":"requests","file":"src/requests/models.py","line":424,"symbol":"prepare","kind":"function","lang":"python","code":"def prepare(\n self,\n method: str | None = None,\n url: _t.UriType | None = None,\n headers: Mapping[str, str | bytes] | None = None,\n files: _t.FilesType = None,\n data: _t.DataType = None,\n params: _t.ParamsType = None,\n auth: _t.AuthType = None,\n cookies: RequestsCookieJar | CookieJar | dict[str, str] | None = None,\n hooks: _t.HooksInputType | None = None,\n json: _t.JsonType = None,\n ) -> None:\n \"\"\"Prepares the entire request with the given parameters.\"\"\"\n\n url = cast(\"_t.UriType\", url)\n self.prepare_method(method)\n self.prepare_url(url, params)\n self.prepare_headers(headers)\n self.prepare_cookies(cookies)\n self.prepare_body(data, files, json)\n self.prepare_auth(auth, url)\n\n # Note that prepare_auth must be last to enable authentication schemes\n # such as OAuth to work on a fully prepared request.\n\n # This MUST go after prepare_auth. Authenticators could add a hook\n self.prepare_hooks(hooks)"}
{"repo":"requests","file":"src/requests/models.py","line":453,"symbol":"__repr__","kind":"function","lang":"python","code":"def __repr__(self) -> str:\n return f\"<PreparedRequest [{self.method}]>\""}
{"repo":"requests","file":"src/requests/models.py","line":456,"symbol":"copy","kind":"function","lang":"python","code":"def copy(self) -> PreparedRequest:\n p = PreparedRequest()\n p.method = self.method\n p.url = self.url\n p.headers = self.headers.copy() if self.headers is not None else None # type: ignore[assignment]\n p._cookies = _copy_cookie_jar(self._cookies)\n p.body = self.body\n p.hooks = self.hooks\n p._body_position = self._body_position\n return p"}
{"repo":"requests","file":"src/requests/models.py","line":467,"symbol":"prepare_method","kind":"function","lang":"python","code":"def prepare_method(self, method: str | None) -> None:\n \"\"\"Prepares the given HTTP method.\"\"\"\n self.method = method\n if self.method is not None:\n self.method = to_native_string(self.method.upper())"}
{"repo":"requests","file":"src/requests/models.py","line":474,"symbol":"_get_idna_encoded_host","kind":"function","lang":"python","code":"def _get_idna_encoded_host(host: str) -> str:\n import idna\n\n try:\n host = idna.encode(host, uts46=True).decode(\"utf-8\")\n except idna.IDNAError:\n raise UnicodeError\n return host"}
{"repo":"requests","file":"src/requests/models.py","line":483,"symbol":"prepare_url","kind":"function","lang":"python","code":"def prepare_url(\n self,\n url: _t.UriType,\n params: _t.ParamsType,\n ) -> None:\n \"\"\"Prepares the given HTTP URL.\"\"\"\n #: Accept objects that have string representations.\n #: We're unable to blindly call unicode/str functions\n #: as this will include the bytestring indicator (b'')\n #: on python 3.x.\n #: https://github.com/psf/requests/pull/2238\n if isinstance(url, bytes):\n url = url.decode(\"utf8\")\n else:\n url = str(url)\n\n # Remove leading whitespaces from url\n url = url.lstrip()\n\n # Don't do any URL preparation for non-HTTP schemes like `mailto`,\n # `data` etc to work around exceptions from `url_parse`, which\n # handles RFC 3986 only.\n if \":\" in url and not url.lower().startswith(\"http\"):\n self.url = url\n return\n\n # Support for unicode domain names and paths.\n try:\n scheme, auth, host, port, path, query, fragment = parse_url(url)\n except LocationParseError as e:\n raise InvalidURL(*e.args)\n\n if not scheme:\n raise MissingSchema(\n f\"Invalid URL {url!r"}
{"repo":"requests","file":"src/requests/models.py","line":565,"symbol":"prepare_headers","kind":"function","lang":"python","code":"def prepare_headers(self, headers: Mapping[str, str | bytes] | None) -> None:\n \"\"\"Prepares the given HTTP headers.\"\"\"\n\n self.headers = CaseInsensitiveDict()\n if headers:\n for header in headers.items():\n # Raise exception on invalid header value.\n check_header_validity(header)\n name, value = header\n self.headers[to_native_string(name)] = value"}
{"repo":"requests","file":"src/requests/models.py","line":576,"symbol":"prepare_body","kind":"function","lang":"python","code":"def prepare_body(\n self, data: _t.DataType, files: _t.FilesType, json: _t.JsonType = None\n ) -> None:\n \"\"\"Prepares the given HTTP body data.\"\"\"\n\n # Check if file, fo, generator, iterator.\n # If not, run through normal process.\n\n # Nottin' on you.\n body = None\n content_type = None\n\n if not data and json is not None:\n # urllib3 requires a bytes-like body. Python 2's json.dumps\n # provides this natively, but Python 3 gives a Unicode string.\n content_type = \"application/json\"\n\n try:\n body = complexjson.dumps(json, allow_nan=False)\n except ValueError as ve:\n raise InvalidJSONError(ve, request=self)\n\n if not isinstance(body, bytes):\n body = body.encode(\"utf-8\")\n\n # data that proxies attributes to underlying objects needs hasattr\n is_iterable = isinstance(data, Iterable) or hasattr(data, \"__iter__\")\n if is_iterable and not isinstance(data, (str, bytes, list, tuple, Mapping)):\n try:\n length = super_len(data)\n except (TypeError, AttributeError, UnsupportedOperation):"}
{"repo":"requests","file":"src/requests/models.py","line":654,"symbol":"prepare_content_length","kind":"function","lang":"python","code":"def prepare_content_length(self, body: _t.BodyType) -> None:\n \"\"\"Prepare Content-Length header based on request method and body\"\"\"\n if body is not None:\n length = super_len(body)\n if length:\n # If length exists, set it. Otherwise, we fallback\n # to Transfer-Encoding: chunked.\n self.headers[\"Content-Length\"] = builtin_str(length)\n elif (\n self.method not in (\"GET\", \"HEAD\")\n and self.headers.get(\"Content-Length\") is None\n ):\n # Set Content-Length to 0 for methods that can have a body\n # but don't provide one. (i.e. not GET or HEAD)\n self.headers[\"Content-Length\"] = \"0\""}
{"repo":"requests","file":"src/requests/models.py","line":670,"symbol":"prepare_auth","kind":"function","lang":"python","code":"def prepare_auth(\n self,\n auth: _t.AuthType,\n url: _t.UriType = \"\",\n ) -> None:\n \"\"\"Prepares the given HTTP auth data.\"\"\"\n\n # If no Auth is explicitly provided, extract it from the URL first.\n if auth is None:\n url_auth = get_auth_from_url(cast(str, self.url))\n auth = url_auth if any(url_auth) else None\n\n if auth:\n if isinstance(auth, tuple) and len(auth) == 2: # type: ignore[arg-type] # pyright widens tuple from Callable in AuthType\n # special-case basic HTTP auth\n auth_handler = HTTPBasicAuth(*auth) # type: ignore[arg-type] # pyright widens tuple from Callable in AuthType\n else:\n # TODO: can be fixed by flipping the conditionals\n auth_handler = cast(\"Callable[..., PreparedRequest]\", auth)\n\n # Allow auth to make its changes.\n r = auth_handler(self)\n\n # Update self to reflect the auth changes.\n self.__dict__.update(r.__dict__)\n\n # Recompute Content-Length\n self.prepare_content_length(self.body)"}
{"repo":"requests","file":"src/requests/models.py","line":699,"symbol":"prepare_cookies","kind":"function","lang":"python","code":"def prepare_cookies(\n self, cookies: RequestsCookieJar | CookieJar | dict[str, str] | None\n ) -> None:\n \"\"\"Prepares the given HTTP cookie data.\n\n This function eventually generates a ``Cookie`` header from the\n given cookies using cookielib. Due to cookielib's design, the header\n will not be regenerated if it already exists, meaning this function\n can only be called once for the life of the\n :class:`PreparedRequest <PreparedRequest>` object. Any subsequent calls\n to ``prepare_cookies`` will have no actual effect, unless the \"Cookie\"\n header is removed beforehand.\n \"\"\"\n if isinstance(cookies, cookielib.CookieJar):\n self._cookies = cookies\n else:\n self._cookies = cookiejar_from_dict(cookies)\n\n cookies_jar = cast(\"CookieJar\", self._cookies)\n cookie_header = get_cookie_header(cookies_jar, self)\n if cookie_header is not None:\n self.headers[\"Cookie\"] = cookie_header"}
{"repo":"requests","file":"src/requests/models.py","line":722,"symbol":"prepare_hooks","kind":"function","lang":"python","code":"def prepare_hooks(self, hooks: _t.HooksInputType | None) -> None:\n \"\"\"Prepares the given hooks.\"\"\"\n # hooks can be passed as None to the prepare method and to this\n # method. To prevent iterating over None, simply use an empty list\n # if hooks is False-y\n hooks = hooks or {}\n for event in hooks:\n self.register_hook(event, hooks[event])"}
{"repo":"requests","file":"src/requests/models.py","line":732,"symbol":"Response","kind":"class","lang":"python","code":"class Response:\n \"\"\"The :class:`Response <Response>` object, which contains a\n server's response to an HTTP request.\n \"\"\"\n\n _content: bytes | Literal[False] | None\n _content_consumed: bool\n _next: PreparedRequest | None\n status_code: int\n headers: CaseInsensitiveDict[str]\n raw: Any\n url: str\n encoding: str | None\n history: list[Response]\n reason: str\n cookies: RequestsCookieJar\n elapsed: datetime.timedelta\n request: PreparedRequest\n connection: HTTPAdapter\n\n __attrs__: list[str] = [\n \"_content\",\n \"status_code\",\n \"headers\",\n \"url\",\n \"history\",\n \"encoding\",\n \"reason\",\n \"cookies\",\n \"elapsed\",\n \"request\",\n ]\n\n def __init__(self) -> None:\n self._content = False\n self._content_consumed = False\n self._next = None\n\n #: Integer Code of responded HTTP Status, e.g. 404 or 200.\n self.status_code = None # type: ignore[assignment]\n\n #: Case-insensitive Dictionary of Response Headers.\n #: For example, ``headers['content-encoding']`` will return the\n #: value of a ``'Content-Encoding'`` response header.\n se"}
{"repo":"requests","file":"src/requests/models.py","line":765,"symbol":"__init__","kind":"function","lang":"python","code":"def __init__(self) -> None:\n self._content = False\n self._content_consumed = False\n self._next = None\n\n #: Integer Code of responded HTTP Status, e.g. 404 or 200.\n self.status_code = None # type: ignore[assignment]\n\n #: Case-insensitive Dictionary of Response Headers.\n #: For example, ``headers['content-encoding']`` will return the\n #: value of a ``'Content-Encoding'`` response header.\n self.headers = CaseInsensitiveDict()\n\n #: File-like object representation of response (for advanced usage).\n #: Use of ``raw`` requires that ``stream=True`` be set on the request.\n #: This requirement does not apply for use internally to Requests.\n self.raw = None\n\n #: Final URL location of Response.\n self.url = None # type: ignore[assignment]\n\n #: Encoding to decode with when accessing r.text.\n self.encoding = None\n\n #: A list of :class:`Response <Response>` objects from\n #: the history of the Request. Any redirect responses will end\n #: up here. The list is sorted from the oldest to the most recent request.\n self.history = []\n\n #: Textual reaso"}
{"repo":"requests","file":"src/requests/models.py","line":812,"symbol":"__enter__","kind":"function","lang":"python","code":"def __enter__(self) -> Self:\n return self"}
{"repo":"requests","file":"src/requests/models.py","line":815,"symbol":"__exit__","kind":"function","lang":"python","code":"def __exit__(self, *args: Any) -> None:\n self.close()"}
{"repo":"requests","file":"src/requests/models.py","line":818,"symbol":"__getstate__","kind":"function","lang":"python","code":"def __getstate__(self) -> dict[str, Any]:\n # Consume everything; accessing the content attribute makes\n # sure the content has been fully read.\n if not self._content_consumed:\n self.content\n\n return {attr: getattr(self, attr, None) for attr in self.__attrs__}"}
{"repo":"requests","file":"src/requests/models.py","line":826,"symbol":"__setstate__","kind":"function","lang":"python","code":"def __setstate__(self, state: dict[str, Any]) -> None:\n for name, value in state.items():\n setattr(self, name, value)\n\n # pickled objects do not have .raw\n setattr(self, \"_content_consumed\", True)\n setattr(self, \"raw\", None)"}
{"repo":"requests","file":"src/requests/models.py","line":834,"symbol":"__repr__","kind":"function","lang":"python","code":"def __repr__(self) -> str:\n return f\"<Response [{self.status_code}]>\""}
{"repo":"requests","file":"src/requests/models.py","line":837,"symbol":"__bool__","kind":"function","lang":"python","code":"def __bool__(self) -> bool:\n \"\"\"Returns True if :attr:`status_code` is less than 400.\n\n This attribute checks if the status code of the response is between\n 400 and 600 to see if there was a client error or a server error. If\n the status code, is between 200 and 400, this will return True. This\n is **not** a check to see if the response code is ``200 OK``.\n \"\"\"\n return self.ok"}
{"repo":"requests","file":"src/requests/models.py","line":847,"symbol":"__nonzero__","kind":"function","lang":"python","code":"def __nonzero__(self) -> bool:\n \"\"\"Returns True if :attr:`status_code` is less than 400.\n\n This attribute checks if the status code of the response is between\n 400 and 600 to see if there was a client error or a server error. If\n the status code, is between 200 and 400, this will return True. This\n is **not** a check to see if the response code is ``200 OK``.\n \"\"\"\n return self.ok"}
{"repo":"requests","file":"src/requests/models.py","line":857,"symbol":"__iter__","kind":"function","lang":"python","code":"def __iter__(self) -> Iterator[bytes]:\n \"\"\"Allows you to use a response as an iterator.\"\"\"\n return self.iter_content(128)"}
{"repo":"requests","file":"src/requests/models.py","line":862,"symbol":"ok","kind":"function","lang":"python","code":"def ok(self) -> bool:\n \"\"\"Returns True if :attr:`status_code` is less than 400, False if not.\n\n This attribute checks if the status code of the response is between\n 400 and 600 to see if there was a client error or a server error. If\n the status code is between 200 and 400, this will return True. This\n is **not** a check to see if the response code is ``200 OK``.\n \"\"\"\n try:\n self.raise_for_status()\n except HTTPError:\n return False\n return True"}
{"repo":"requests","file":"src/requests/models.py","line":877,"symbol":"is_redirect","kind":"function","lang":"python","code":"def is_redirect(self) -> bool:\n \"\"\"True if this Response is a well-formed HTTP redirect that could have\n been processed automatically (by :meth:`Session.resolve_redirects`).\n \"\"\"\n return \"location\" in self.headers and self.status_code in REDIRECT_STATI"}
{"repo":"requests","file":"src/requests/models.py","line":884,"symbol":"is_permanent_redirect","kind":"function","lang":"python","code":"def is_permanent_redirect(self) -> bool:\n \"\"\"True if this Response one of the permanent versions of redirect.\"\"\"\n return \"location\" in self.headers and self.status_code in (\n codes.moved_permanently,\n codes.permanent_redirect,\n )"}
{"repo":"requests","file":"src/requests/models.py","line":892,"symbol":"next","kind":"function","lang":"python","code":"def next(self) -> PreparedRequest | None:\n \"\"\"Returns a PreparedRequest for the next request in a redirect chain, if there is one.\"\"\"\n return self._next"}
{"repo":"requests","file":"src/requests/models.py","line":897,"symbol":"apparent_encoding","kind":"function","lang":"python","code":"def apparent_encoding(self) -> str | None:\n \"\"\"The apparent encoding, provided by the charset_normalizer or chardet libraries.\"\"\"\n if chardet is not None:\n return chardet.detect(self.content)[\"encoding\"]\n else:\n # If no character detection library is available, we'll fall back\n # to a standard Python utf-8 str.\n return \"utf-8\""}
{"repo":"requests","file":"src/requests/models.py","line":907,"symbol":"iter_content","kind":"function","lang":"python","code":"def iter_content(\n self, chunk_size: int | None = 1, decode_unicode: Literal[False] = False\n ) -> Iterator[bytes]: ..."}
{"repo":"requests","file":"src/requests/models.py","line":911,"symbol":"iter_content","kind":"function","lang":"python","code":"def iter_content(\n self, chunk_size: int | None = 1, *, decode_unicode: Literal[True]\n ) -> Iterator[str | bytes]: ..."}
{"repo":"requests","file":"src/requests/models.py","line":914,"symbol":"iter_content","kind":"function","lang":"python","code":"def iter_content(\n self, chunk_size: int | None = 1, decode_unicode: bool = False\n ) -> Iterator[str | bytes]:\n \"\"\"Iterates over the response data. When stream=True is set on the\n request, this avoids reading the content at once into memory for\n large responses. The chunk size is the number of bytes it should\n read into memory. This is not necessarily the length of each item\n returned as decoding can take place.\n\n chunk_size must be of type int or None. A value of None will\n function differently depending on the value of `stream`.\n stream=True will read data as it arrives in whatever size the\n chunks are received. If stream=False, data is returned as\n a single chunk.\n\n If decode_unicode is True, content will be decoded using encoding\n information from the response. If no encoding information is available,\n bytes will be returned. This can be bypassed by manually setting\n `encoding` on the response.\n \"\"\"\n\n def generate() -> Generator[bytes, None, None]:\n # Special case for urllib3.\n if hasattr(self.raw, \"stream\"):\n try:\n "}
{"repo":"requests","file":"src/requests/models.py","line":935,"symbol":"generate","kind":"function","lang":"python","code":"def generate() -> Generator[bytes, None, None]:\n # Special case for urllib3.\n if hasattr(self.raw, \"stream\"):\n try:\n yield from self.raw.stream(chunk_size, decode_content=True)\n except ProtocolError as e:\n raise ChunkedEncodingError(e)\n except DecodeError as e:\n raise ContentDecodingError(e)\n except ReadTimeoutError as e:\n raise ConnectionError(e)\n except SSLError as e:\n raise RequestsSSLError(e)\n else:\n # Standard file-like object.\n while True:\n chunk = self.raw.read(chunk_size)\n if not chunk:\n break\n yield chunk\n\n self._content_consumed = True"}
{"repo":"requests","file":"src/requests/models.py","line":980,"symbol":"iter_lines","kind":"function","lang":"python","code":"def iter_lines(\n self,\n chunk_size: int = ITER_CHUNK_SIZE,\n decode_unicode: Literal[False] = False,\n delimiter: bytes | None = None,\n ) -> Iterator[bytes]: ..."}
{"repo":"requests","file":"src/requests/models.py","line":987,"symbol":"iter_lines","kind":"function","lang":"python","code":"def iter_lines(\n self,\n chunk_size: int = ITER_CHUNK_SIZE,\n *,\n decode_unicode: Literal[True],\n delimiter: str | bytes | None = None,\n ) -> Iterator[str | bytes]: ..."}
{"repo":"requests","file":"src/requests/models.py","line":994,"symbol":"iter_lines","kind":"function","lang":"python","code":"def iter_lines(\n self,\n chunk_size: int = ITER_CHUNK_SIZE,\n decode_unicode: bool = False,\n delimiter: str | bytes | None = None,\n ) -> Iterator[str | bytes]:\n \"\"\"Iterates over the response data, one line at a time. When\n stream=True is set on the request, this avoids reading the\n content at once into memory for large responses.\n\n The decode_unicode param works the same as in `iter_content`, with the\n same caveats.\n\n .. note:: This method is not reentrant safe.\n \"\"\"\n\n pending: str | bytes | None = None\n\n for chunk in self.iter_content(\n chunk_size=chunk_size, decode_unicode=decode_unicode\n ):\n if pending is not None:\n # TODO: remove cast after iter_lines rewrite\n chunk = cast(\"str | bytes\", pending + chunk)\n\n if delimiter:\n lines = chunk.split(delimiter) # type: ignore[arg-type]\n else:\n lines = chunk.splitlines()\n\n if lines and lines[-1] and chunk and lines[-1][-1] == chunk[-1]:\n pending = lines.pop()\n else:\n pending = None\n\n "}
{"repo":"requests","file":"src/requests/models.py","line":1035,"symbol":"content","kind":"function","lang":"python","code":"def content(self) -> bytes:\n \"\"\"Content of the response, in bytes.\"\"\"\n\n if self._content is False:\n # Read the contents.\n if self._content_consumed:\n raise RuntimeError(\"The content for this response was already consumed\")\n\n if self.status_code == 0 or self.raw is None:\n self._content = None\n else:\n self._content = b\"\".join(self.iter_content(CONTENT_CHUNK_SIZE)) or b\"\"\n\n self._content_consumed = True\n # don't need to release the connection; that's been handled by urllib3\n # since we exhausted the data.\n return self._content # type: ignore[return-value]"}
{"repo":"requests","file":"src/requests/models.py","line":1054,"symbol":"text","kind":"function","lang":"python","code":"def text(self) -> str:\n \"\"\"Content of the response, in unicode.\n\n If Response.encoding is None, encoding will be guessed using\n ``charset_normalizer`` or ``chardet``.\n\n The encoding of the response content is determined based solely on HTTP\n headers, following RFC 2616 to the letter. If you can take advantage of\n non-HTTP knowledge to make a better guess at the encoding, you should\n set ``r.encoding`` appropriately before accessing this property.\n \"\"\"\n\n # Try charset from content-type\n content = None\n encoding = self.encoding\n\n if not self.content:\n return \"\"\n\n # Fallback to auto-detected encoding.\n if self.encoding is None:\n encoding = self.apparent_encoding\n\n # Decode unicode from given encoding.\n try:\n content = str(self.content, encoding or \"utf-8\", errors=\"replace\")\n except (LookupError, TypeError):\n # A LookupError is raised if the encoding was not found which could\n # indicate a misspelling or similar mistake.\n #\n # A TypeError can be raised if encoding is None\n #\n "}
{"repo":"requests","file":"src/requests/models.py","line":1091,"symbol":"json","kind":"function","lang":"python","code":"def json(self, **kwargs: Any) -> Any:\n r\"\"\"Decodes the JSON response body (if any) as a Python object.\n\n This may return a dictionary, list, etc. depending on what is in the response.\n\n :param \\*\\*kwargs: Optional arguments that ``json.loads`` takes.\n :raises requests.exceptions.JSONDecodeError: If the response body does not\n contain valid json.\n \"\"\"\n\n if not self.encoding and self.content and len(self.content) > 3:\n # No encoding set. JSON RFC 4627 section 3 states we should expect\n # UTF-8, -16 or -32. Detect which one to use; If the detection or\n # decoding fails, fall back to `self.text` (using charset_normalizer to make\n # a best guess).\n encoding = guess_json_utf(self.content)\n if encoding is not None:\n try:\n return complexjson.loads(self.content.decode(encoding), **kwargs)\n except UnicodeDecodeError:\n # Wrong UTF codec detected; usually because it's not UTF-8\n # but some other 8-bit codec. This is an RFC violation,\n # and the server didn't bother to tel"}
{"repo":"requests","file":"src/requests/models.py","line":1127,"symbol":"links","kind":"function","lang":"python","code":"def links(self) -> dict[str, dict[str, str]]:\n \"\"\"Returns the parsed header links of the response, if any.\"\"\"\n\n header = self.headers.get(\"link\")\n\n resolved_links: dict[str, dict[str, str]] = {}\n\n if header:\n links = parse_header_links(header)\n\n for link in links:\n key = link.get(\"rel\") or link.get(\"url\")\n if key is not None:\n resolved_links[key] = link\n\n return resolved_links"}
{"repo":"requests","file":"src/requests/models.py","line":1144,"symbol":"raise_for_status","kind":"function","lang":"python","code":"def raise_for_status(self) -> None:\n \"\"\"Raises :class:`HTTPError`, if one occurred.\"\"\"\n\n http_error_msg = \"\"\n if isinstance(self.reason, bytes):\n # We attempt to decode utf-8 first because some servers\n # choose to localize their reason strings. If the string\n # isn't utf-8, we fall back to iso-8859-1 for all other\n # encodings. (See PR #3538)\n try:\n reason = self.reason.decode(\"utf-8\")\n except UnicodeDecodeError:\n reason = self.reason.decode(\"iso-8859-1\")\n else:\n reason = self.reason\n\n if 400 <= self.status_code < 500:\n http_error_msg = (\n f\"{self.status_code} Client Error: {reason} for url: {self.url}\"\n )\n\n elif 500 <= self.status_code < 600:\n http_error_msg = (\n f\"{self.status_code} Server Error: {reason} for url: {self.url}\"\n )\n\n if http_error_msg:\n raise HTTPError(http_error_msg, response=self)"}
{"repo":"requests","file":"src/requests/models.py","line":1173,"symbol":"close","kind":"function","lang":"python","code":"def close(self) -> None:\n \"\"\"Releases the connection back to the pool. Once this method has been\n called the underlying ``raw`` object must not be accessed again.\n\n *Note: Should not normally need to be called explicitly.*\n \"\"\"\n if not self._content_consumed:\n self.raw.close()\n\n release_conn = getattr(self.raw, \"release_conn\", None)\n if release_conn is not None:\n release_conn()"}
{"repo":"requests","file":"src/requests/sessions.py","line":76,"symbol":"merge_setting","kind":"function","lang":"python","code":"def merge_setting(\n request_setting: Any, session_setting: Any, dict_class: type = OrderedDict\n) -> Any:\n \"\"\"Determines appropriate setting for a given request, taking into account\n the explicit setting on that request, and the setting in the session. If a\n setting is a dictionary, they will be merged together using `dict_class`\n \"\"\"\n\n if session_setting is None:\n return request_setting\n\n if request_setting is None:\n return session_setting\n\n # Bypass if not a dictionary (e.g. verify)\n if not (\n isinstance(session_setting, Mapping) and isinstance(request_setting, Mapping)\n ):\n return request_setting\n\n merged_setting = dict_class(to_key_val_list(session_setting)) # type: ignore[arg-type] # isinstance narrows Any to Mapping[Unknown]\n merged_setting.update(to_key_val_list(request_setting)) # type: ignore[arg-type]\n\n # Remove keys that are set to None. Extract keys first to avoid altering\n # the dictionary during iteration.\n none_keys = [k for (k, v) in merged_setting.items() if v is None]\n for key in none_keys:\n del merged_setting[key]\n\n return merged_setting"}
{"repo":"requests","file":"src/requests/sessions.py","line":108,"symbol":"merge_hooks","kind":"function","lang":"python","code":"def merge_hooks(\n request_hooks: _t.HooksType,\n session_hooks: _t.HooksType,\n dict_class: type = OrderedDict,\n) -> _t.HooksType:\n \"\"\"Properly merges both requests and session hooks.\n\n This is necessary because when request_hooks == {'response': []}, the\n merge breaks Session hooks entirely.\n \"\"\"\n if session_hooks is None or session_hooks.get(\"response\") == []:\n return request_hooks\n\n if request_hooks is None or request_hooks.get(\"response\") == []:\n return session_hooks\n\n return merge_setting(request_hooks, session_hooks, dict_class)"}
{"repo":"requests","file":"src/requests/sessions.py","line":127,"symbol":"SessionRedirectMixin","kind":"class","lang":"python","code":"class SessionRedirectMixin:\n max_redirects: int\n trust_env: bool\n cookies: RequestsCookieJar\n\n def send(self, request: PreparedRequest, **kwargs: Any) -> Response: ...\n\n def get_redirect_target(self, resp: Response) -> str | None:\n \"\"\"Receives a Response. Returns a redirect URI or ``None``\"\"\"\n # Due to the nature of how requests processes redirects this method will\n # be called at least once upon the original response and at least twice\n # on each subsequent redirect response (if any).\n # If a custom mixin is used to handle this logic, it may be advantageous\n # to cache the redirect location onto the response object as a private\n # attribute.\n if resp.is_redirect:\n location = resp.headers[\"location\"]\n # Currently the underlying http module on py3 decode headers\n # in latin1, but empirical evidence suggests that latin1 is very\n # rarely used with non-ASCII characters in HTTP headers.\n # It is more likely to get UTF8 header rather than latin1.\n # This causes incorrect handling of UTF8 encoded location headers.\n # To solve this, we re-enco"}
{"repo":"requests","file":"src/requests/sessions.py","line":132,"symbol":"send","kind":"function","lang":"python","code":"def send(self, request: PreparedRequest, **kwargs: Any) -> Response: ..."}
{"repo":"requests","file":"src/requests/sessions.py","line":134,"symbol":"get_redirect_target","kind":"function","lang":"python","code":"def get_redirect_target(self, resp: Response) -> str | None:\n \"\"\"Receives a Response. Returns a redirect URI or ``None``\"\"\"\n # Due to the nature of how requests processes redirects this method will\n # be called at least once upon the original response and at least twice\n # on each subsequent redirect response (if any).\n # If a custom mixin is used to handle this logic, it may be advantageous\n # to cache the redirect location onto the response object as a private\n # attribute.\n if resp.is_redirect:\n location = resp.headers[\"location\"]\n # Currently the underlying http module on py3 decode headers\n # in latin1, but empirical evidence suggests that latin1 is very\n # rarely used with non-ASCII characters in HTTP headers.\n # It is more likely to get UTF8 header rather than latin1.\n # This causes incorrect handling of UTF8 encoded location headers.\n # To solve this, we re-encode the location in latin1.\n location = location.encode(\"latin1\")\n return to_native_string(location, \"utf8\")\n return None"}
{"repo":"requests","file":"src/requests/sessions.py","line":154,"symbol":"should_strip_auth","kind":"function","lang":"python","code":"def should_strip_auth(self, old_url: str, new_url: str) -> bool:\n \"\"\"Decide whether Authorization header should be removed when redirecting\"\"\"\n old_parsed = urlparse(old_url)\n new_parsed = urlparse(new_url)\n if old_parsed.hostname != new_parsed.hostname:\n return True\n # Special case: allow http -> https redirect when using the standard\n # ports. This isn't specified by RFC 7235, but is kept to avoid\n # breaking backwards compatibility with older versions of requests\n # that allowed any redirects on the same host.\n if (\n old_parsed.scheme == \"http\"\n and old_parsed.port in (80, None)\n and new_parsed.scheme == \"https\"\n and new_parsed.port in (443, None)\n ):\n return False\n\n # Handle default port usage corresponding to scheme.\n changed_port = old_parsed.port != new_parsed.port\n changed_scheme = old_parsed.scheme != new_parsed.scheme\n default_port = (DEFAULT_PORTS.get(old_parsed.scheme, None), None)\n if (\n not changed_scheme\n and old_parsed.port in default_port\n and new_parsed.port in de"}
{"repo":"requests","file":"src/requests/sessions.py","line":186,"symbol":"resolve_redirects","kind":"function","lang":"python","code":"def resolve_redirects(\n self,\n resp: Response,\n req: PreparedRequest,\n stream: bool = False,\n timeout: _t.TimeoutType = None,\n verify: _t.VerifyType = True,\n cert: _t.CertType = None,\n proxies: dict[str, str] | None = None,\n yield_requests: bool = False,\n **adapter_kwargs: Any,\n ) -> Generator[Response, None, None]:\n \"\"\"Receives a Response. Returns a generator of Responses or Requests.\"\"\"\n\n hist: list[Response] = [] # keep track of history\n\n url = self.get_redirect_target(resp)\n previous_fragment = urlparse(req.url).fragment\n while url:\n prepared_request = req.copy()\n\n # Update history and keep track of redirects.\n resp.history = hist[:]\n hist.append(resp)\n\n try:\n resp.content # Consume socket so it can be released\n except (ChunkedEncodingError, ContentDecodingError, RuntimeError):\n resp.raw.read(decode_content=False)\n\n if len(resp.history) >= self.max_redirects:\n raise TooManyRedirects(\n f\"Exceeded {self.max_redirects} redirects.\", re"}
{"repo":"requests","file":"src/requests/sessions.py","line":309,"symbol":"rebuild_auth","kind":"function","lang":"python","code":"def rebuild_auth(\n self, prepared_request: PreparedRequest, response: Response\n ) -> None:\n \"\"\"When being redirected we may want to strip authentication from the\n request to avoid leaking credentials. This method intelligently removes\n and reapplies authentication where possible to avoid credential loss.\n \"\"\"\n original_request = response.request\n assert _is_prepared(original_request)\n assert _is_prepared(prepared_request)\n\n headers = prepared_request.headers\n original_url = original_request.url\n url = prepared_request.url\n\n if \"Authorization\" in headers and self.should_strip_auth(original_url, url):\n # If we get redirected to a new host, we should strip out any\n # authentication headers.\n del headers[\"Authorization\"]\n\n # .netrc might have more auth for us on our new host.\n new_auth = get_netrc_auth(url) if self.trust_env else None\n if new_auth is not None:\n prepared_request.prepare_auth(new_auth)"}
{"repo":"requests","file":"src/requests/sessions.py","line":334,"symbol":"rebuild_proxies","kind":"function","lang":"python","code":"def rebuild_proxies(\n self,\n prepared_request: PreparedRequest,\n proxies: dict[str, str] | None,\n ) -> dict[str, str]:\n \"\"\"This method re-evaluates the proxy configuration by considering the\n environment variables. If we are redirected to a URL covered by\n NO_PROXY, we strip the proxy configuration. Otherwise, we set missing\n proxy keys for this URL (in case they were stripped by a previous\n redirect).\n\n This method also replaces the Proxy-Authorization header where\n necessary.\n\n :rtype: dict\n \"\"\"\n assert _is_prepared(prepared_request)\n headers = prepared_request.headers\n scheme = urlparse(prepared_request.url).scheme\n new_proxies = resolve_proxies(prepared_request, proxies, self.trust_env)\n\n if \"Proxy-Authorization\" in headers:\n del headers[\"Proxy-Authorization\"]\n\n try:\n username, password = get_auth_from_url(new_proxies[scheme])\n except KeyError:\n username, password = None, None\n\n # urllib3 handles proxy authorization for us in the standard adapter.\n # Avoid appending this to TLS tunneled requests wh"}
{"repo":"requests","file":"src/requests/sessions.py","line":370,"symbol":"rebuild_method","kind":"function","lang":"python","code":"def rebuild_method(\n self, prepared_request: PreparedRequest, response: Response\n ) -> None:\n \"\"\"When being redirected we may want to change the method of the request\n based on certain specs or browser behavior.\n \"\"\"\n method = prepared_request.method\n\n # https://tools.ietf.org/html/rfc7231#section-6.4.4\n if response.status_code == codes.see_other and method != \"HEAD\":\n method = \"GET\"\n\n # Do what the browsers do, despite standards...\n # First, turn 302s into GETs.\n if response.status_code == codes.found and method != \"HEAD\":\n method = \"GET\"\n\n # Second, if a POST is responded to with a 301, turn it into a GET.\n # This bizarre behaviour is explained in Issue 1704.\n if response.status_code == codes.moved and method == \"POST\":\n method = \"GET\"\n\n prepared_request.method = method"}
{"repo":"requests","file":"src/requests/sessions.py","line":395,"symbol":"Session","kind":"class","lang":"python","code":"class Session(SessionRedirectMixin):\n \"\"\"A Requests session.\n\n Provides cookie persistence, connection-pooling, and configuration.\n\n Basic Usage::\n\n >>> import requests\n >>> s = requests.Session()\n >>> s.get('https://httpbin.org/get')\n <Response [200]>\n\n Or as a context manager::\n\n >>> with requests.Session() as s:\n ... s.get('https://httpbin.org/get')\n <Response [200]>\n \"\"\"\n\n headers: CaseInsensitiveDict[str]\n auth: _t.AuthType\n proxies: dict[str, str]\n hooks: dict[str, list[_t.HookType]]\n params: MutableMapping[str, Any]\n stream: bool\n verify: _t.VerifyType\n cert: _t.CertType\n max_redirects: int\n trust_env: bool\n cookies: RequestsCookieJar\n adapters: MutableMapping[str, BaseAdapter]\n\n __attrs__: list[str] = [\n \"headers\",\n \"cookies\",\n \"auth\",\n \"proxies\",\n \"hooks\",\n \"params\",\n \"verify\",\n \"cert\",\n \"adapters\",\n \"stream\",\n \"trust_env\",\n \"max_redirects\",\n ]\n\n def __init__(self) -> None:\n #: A case-insensitive dictionary of headers to be sent on each\n #: :class:`Request <Request>` sent from th"}
{"repo":"requests","file":"src/requests/sessions.py","line":442,"symbol":"__init__","kind":"function","lang":"python","code":"def __init__(self) -> None:\n #: A case-insensitive dictionary of headers to be sent on each\n #: :class:`Request <Request>` sent from this\n #: :class:`Session <Session>`.\n self.headers = default_headers()\n\n #: Default Authentication tuple or object to attach to\n #: :class:`Request <Request>`.\n self.auth = None\n\n #: Dictionary mapping protocol or protocol and host to the URL of the proxy\n #: (e.g. {'http': 'foo.bar:3128', 'http://host.name': 'foo.bar:4012'}) to\n #: be used on each :class:`Request <Request>`.\n self.proxies = {}\n\n #: Event-handling hooks.\n self.hooks = default_hooks()\n\n #: Dictionary of querystring data to attach to each\n #: :class:`Request <Request>`. The dictionary values may be lists for\n #: representing multivalued query parameters.\n self.params = {}\n\n #: Stream response content default.\n self.stream = False\n\n #: SSL Verification default.\n #: Defaults to `True`, requiring requests to verify the TLS certificate at the\n #: remote end.\n #: If verify is set to `False`, requests will accept any TLS certificate\n "}
{"repo":"requests","file":"src/requests/sessions.py","line":505,"symbol":"__enter__","kind":"function","lang":"python","code":"def __enter__(self) -> Self:\n return self"}
{"repo":"requests","file":"src/requests/sessions.py","line":508,"symbol":"__exit__","kind":"function","lang":"python","code":"def __exit__(self, *args: Any) -> None:\n self.close()"}
{"repo":"requests","file":"src/requests/sessions.py","line":511,"symbol":"prepare_request","kind":"function","lang":"python","code":"def prepare_request(self, request: Request) -> PreparedRequest:\n \"\"\"Constructs a :class:`PreparedRequest <PreparedRequest>` for\n transmission and returns it. The :class:`PreparedRequest` has settings\n merged from the :class:`Request <Request>` instance and those of the\n :class:`Session`.\n\n :param request: :class:`Request` instance to prepare with this\n session's settings.\n :rtype: requests.PreparedRequest\n \"\"\"\n url = cast(\"_t.UriType\", request.url)\n method = cast(str, request.method)\n\n cookies = request.cookies or {}\n\n # Bootstrap CookieJar.\n if not isinstance(cookies, cookielib.CookieJar):\n cookies = cookiejar_from_dict(cookies)\n\n # Merge with session cookies\n merged_cookies = merge_cookies(\n merge_cookies(RequestsCookieJar(), self.cookies), cookies\n )\n\n # Set environment's basic authentication if not explicitly set.\n auth = request.auth\n if self.trust_env and not auth and not self.auth:\n auth = get_netrc_auth(url)\n\n p = PreparedRequest()\n p.prepare(\n method=method.upper(),\n url"}
{"repo":"requests","file":"src/requests/sessions.py","line":557,"symbol":"request","kind":"function","lang":"python","code":"def request(\n self,\n method: str,\n url: _t.UriType,\n params: _t.ParamsType = None,\n data: _t.DataType = None,\n headers: _t.HeadersType = None,\n cookies: RequestsCookieJar | CookieJar | dict[str, str] | None = None,\n files: _t.FilesType = None,\n auth: _t.AuthType = None,\n timeout: _t.TimeoutType = None,\n allow_redirects: bool = True,\n proxies: dict[str, str] | None = None,\n hooks: _t.HooksInputType | None = None,\n stream: bool | None = None,\n verify: _t.VerifyType | None = None,\n cert: _t.CertType = None,\n json: _t.JsonType = None,\n ) -> Response:\n \"\"\"Constructs a :class:`Request <Request>`, prepares it and sends it.\n Returns :class:`Response <Response>` object.\n\n :param method: method for the new :class:`Request` object.\n :param url: URL for the new :class:`Request` object.\n :param params: (optional) Dictionary or bytes to be sent in the query\n string for the :class:`Request`.\n :param data: (optional) Dictionary, list of tuples, bytes, or file-like\n object to send in the body of the :class:`Request`"}
{"repo":"requests","file":"src/requests/sessions.py","line":655,"symbol":"get","kind":"function","lang":"python","code":"def get(\n self,\n url: _t.UriType,\n params: _t.ParamsType = None,\n **kwargs: Unpack[_t.GetKwargs],\n ) -> Response:\n r\"\"\"Sends a GET request. Returns :class:`Response` object.\n\n :param url: URL for the new :class:`Request` object.\n :param params: (optional) Dictionary, list of tuples or bytes to send\n in the query string for the :class:`Request`.\n :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n :rtype: requests.Response\n \"\"\"\n\n kwargs.setdefault(\"allow_redirects\", True)\n return self.request(\"GET\", url, params=params, **kwargs)"}
{"repo":"requests","file":"src/requests/sessions.py","line":673,"symbol":"options","kind":"function","lang":"python","code":"def options(self, url: _t.UriType, **kwargs: Unpack[_t.RequestKwargs]) -> Response:\n r\"\"\"Sends a OPTIONS request. Returns :class:`Response` object.\n\n :param url: URL for the new :class:`Request` object.\n :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n :rtype: requests.Response\n \"\"\"\n\n kwargs.setdefault(\"allow_redirects\", True)\n return self.request(\"OPTIONS\", url, **kwargs)"}
{"repo":"requests","file":"src/requests/sessions.py","line":684,"symbol":"head","kind":"function","lang":"python","code":"def head(self, url: _t.UriType, **kwargs: Unpack[_t.RequestKwargs]) -> Response:\n r\"\"\"Sends a HEAD request. Returns :class:`Response` object.\n\n :param url: URL for the new :class:`Request` object.\n :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n :rtype: requests.Response\n \"\"\"\n\n kwargs.setdefault(\"allow_redirects\", False)\n return self.request(\"HEAD\", url, **kwargs)"}
{"repo":"requests","file":"src/requests/sessions.py","line":695,"symbol":"post","kind":"function","lang":"python","code":"def post(\n self,\n url: _t.UriType,\n data: _t.DataType = None,\n json: _t.JsonType = None,\n **kwargs: Unpack[_t.PostKwargs],\n ) -> Response:\n r\"\"\"Sends a POST request. Returns :class:`Response` object.\n\n :param url: URL for the new :class:`Request` object.\n :param data: (optional) Dictionary, list of tuples, bytes, or file-like\n object to send in the body of the :class:`Request`.\n :param json: (optional) json to send in the body of the :class:`Request`.\n :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n :rtype: requests.Response\n \"\"\"\n\n return self.request(\"POST\", url, data=data, json=json, **kwargs)"}
{"repo":"requests","file":"src/requests/sessions.py","line":714,"symbol":"put","kind":"function","lang":"python","code":"def put(\n self, url: _t.UriType, data: _t.DataType = None, **kwargs: Unpack[_t.DataKwargs]\n ) -> Response:\n r\"\"\"Sends a PUT request. Returns :class:`Response` object.\n\n :param url: URL for the new :class:`Request` object.\n :param data: (optional) Dictionary, list of tuples, bytes, or file-like\n object to send in the body of the :class:`Request`.\n :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n :rtype: requests.Response\n \"\"\"\n\n return self.request(\"PUT\", url, data=data, **kwargs)"}
{"repo":"requests","file":"src/requests/sessions.py","line":728,"symbol":"patch","kind":"function","lang":"python","code":"def patch(\n self, url: _t.UriType, data: _t.DataType = None, **kwargs: Unpack[_t.DataKwargs]\n ) -> Response:\n r\"\"\"Sends a PATCH request. Returns :class:`Response` object.\n\n :param url: URL for the new :class:`Request` object.\n :param data: (optional) Dictionary, list of tuples, bytes, or file-like\n object to send in the body of the :class:`Request`.\n :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n :rtype: requests.Response\n \"\"\"\n\n return self.request(\"PATCH\", url, data=data, **kwargs)"}
{"repo":"requests","file":"src/requests/sessions.py","line":742,"symbol":"delete","kind":"function","lang":"python","code":"def delete(self, url: _t.UriType, **kwargs: Unpack[_t.RequestKwargs]) -> Response:\n r\"\"\"Sends a DELETE request. Returns :class:`Response` object.\n\n :param url: URL for the new :class:`Request` object.\n :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n :rtype: requests.Response\n \"\"\"\n\n return self.request(\"DELETE\", url, **kwargs)"}
{"repo":"requests","file":"src/requests/sessions.py","line":752,"symbol":"send","kind":"function","lang":"python","code":"def send(self, request: PreparedRequest, **kwargs: Any) -> Response:\n \"\"\"Send a given PreparedRequest.\n\n :rtype: requests.Response\n \"\"\"\n # Set defaults that the hooks can utilize to ensure they always have\n # the correct parameters to reproduce the previous request.\n kwargs.setdefault(\"stream\", self.stream)\n kwargs.setdefault(\"verify\", self.verify)\n kwargs.setdefault(\"cert\", self.cert)\n if \"proxies\" not in kwargs:\n kwargs[\"proxies\"] = resolve_proxies(request, self.proxies, self.trust_env)\n\n # It's possible that users might accidentally send a Request object.\n # Guard against that specific failure case.\n if isinstance(request, Request):\n raise ValueError(\"You can only send PreparedRequests.\")\n\n assert _is_prepared(request)\n\n # Set up variables needed for resolve_redirects and dispatching of hooks\n allow_redirects = kwargs.pop(\"allow_redirects\", True)\n stream = kwargs.get(\"stream\")\n hooks = request.hooks\n\n # Get the appropriate adapter to use\n adapter = self.get_adapter(url=request.url)\n\n # Start time (approximately) of the "}
{"repo":"requests","file":"src/requests/sessions.py","line":831,"symbol":"merge_environment_settings","kind":"function","lang":"python","code":"def merge_environment_settings(\n self,\n url: str,\n proxies: dict[str, str] | None,\n stream: bool | None,\n verify: _t.VerifyType | None,\n cert: _t.CertType,\n ) -> dict[str, Any]:\n \"\"\"\n Check the environment and merge it with some settings.\n\n :rtype: dict\n \"\"\"\n # Gather clues from the surrounding environment.\n if self.trust_env:\n # Set environment's proxies.\n no_proxy = proxies.get(\"no_proxy\") if proxies is not None else None\n env_proxies = get_environ_proxies(url, no_proxy=no_proxy)\n if proxies is not None:\n for k, v in env_proxies.items():\n proxies.setdefault(k, v)\n\n # Look for requests environment configuration\n # and be compatible with cURL.\n if verify is True or verify is None:\n verify = (\n os.environ.get(\"REQUESTS_CA_BUNDLE\")\n or os.environ.get(\"CURL_CA_BUNDLE\")\n or verify\n )\n\n # Merge all the kwargs.\n proxies = merge_setting(proxies, self.proxies)\n stream = merge_setting(strea"}
{"repo":"requests","file":"src/requests/sessions.py","line":870,"symbol":"get_adapter","kind":"function","lang":"python","code":"def get_adapter(self, url: str) -> BaseAdapter:\n \"\"\"\n Returns the appropriate connection adapter for the given URL.\n\n :rtype: requests.adapters.BaseAdapter\n \"\"\"\n for prefix, adapter in self.adapters.items():\n if url.lower().startswith(prefix.lower()):\n return adapter\n\n # Nothing matches :-/\n raise InvalidSchema(f\"No connection adapters were found for {url!r}\")"}
{"repo":"requests","file":"src/requests/sessions.py","line":883,"symbol":"close","kind":"function","lang":"python","code":"def close(self) -> None:\n \"\"\"Closes all adapters and as such the session\"\"\"\n for v in self.adapters.values():\n v.close()"}
{"repo":"requests","file":"src/requests/sessions.py","line":888,"symbol":"mount","kind":"function","lang":"python","code":"def mount(self, prefix: str, adapter: BaseAdapter) -> None:\n \"\"\"Registers a connection adapter to a prefix.\n\n Adapters are sorted in descending order by prefix length.\n \"\"\"\n self.adapters[prefix] = adapter\n keys_to_move = [k for k in self.adapters if len(k) < len(prefix)]\n\n for key in keys_to_move:\n self.adapters[key] = self.adapters.pop(key)"}
{"repo":"requests","file":"src/requests/sessions.py","line":899,"symbol":"__getstate__","kind":"function","lang":"python","code":"def __getstate__(self) -> dict[str, Any]:\n state = {attr: getattr(self, attr, None) for attr in self.__attrs__}\n return state"}
{"repo":"requests","file":"src/requests/sessions.py","line":903,"symbol":"__setstate__","kind":"function","lang":"python","code":"def __setstate__(self, state: dict[str, Any]) -> None:\n for attr, value in state.items():\n setattr(self, attr, value)"}
{"repo":"requests","file":"src/requests/sessions.py","line":908,"symbol":"session","kind":"function","lang":"python","code":"def session() -> Session:\n \"\"\"\n Returns a :class:`Session` for context-management.\n\n .. deprecated:: 1.0.0\n\n This method has been deprecated since version 1.0.0 and is only kept for\n backwards compatibility. New code should use :class:`~requests.sessions.Session`\n to create a session. This may be removed at a future date.\n\n :rtype: Session\n \"\"\"\n return Session()"}
{"repo":"requests","file":"src/requests/status_codes.py","line":109,"symbol":"_init","kind":"function","lang":"python","code":"def _init():\n for code, titles in _codes.items():\n for title in titles:\n setattr(codes, title, code)\n if not title.startswith((\"\\\\\", \"/\")):\n setattr(codes, title.upper(), code)\n\n def doc(code: int) -> str:\n names = \", \".join(f\"``{n}``\" for n in _codes[code])\n return \"* %d: %s\" % (code, names)\n\n global __doc__\n __doc__ = (\n __doc__ + \"\\n\" + \"\\n\".join(doc(code) for code in sorted(_codes))\n if __doc__ is not None\n else None\n )"}
{"repo":"requests","file":"src/requests/status_codes.py","line":116,"symbol":"doc","kind":"function","lang":"python","code":"def doc(code: int) -> str:\n names = \", \".join(f\"``{n}``\" for n in _codes[code])\n return \"* %d: %s\" % (code, names)"}
{"repo":"requests","file":"src/requests/structures.py","line":20,"symbol":"CaseInsensitiveDict","kind":"class","lang":"python","code":"class CaseInsensitiveDict(MutableMapping[str, _VT], Generic[_VT]):\n \"\"\"A case-insensitive ``dict``-like object.\n\n Implements all methods and operations of\n ``MutableMapping`` as well as dict's ``copy``. Also\n provides ``lower_items``.\n\n All keys are expected to be strings. The structure remembers the\n case of the last key to be set, and ``iter(instance)``,\n ``keys()``, ``items()``, ``iterkeys()``, and ``iteritems()``\n will contain case-sensitive keys. However, querying and contains\n testing is case insensitive::\n\n cid = CaseInsensitiveDict()\n cid['Accept'] = 'application/json'\n cid['aCCEPT'] == 'application/json' # True\n list(cid) == ['Accept'] # True\n\n For example, ``headers['content-encoding']`` will return the\n value of a ``'Content-Encoding'`` response header, regardless\n of how the header name was originally stored.\n\n If the constructor, ``.update``, or equality comparison\n operations are given keys that have equal ``.lower()``s, the\n behavior is undefined.\n \"\"\"\n\n _store: OrderedDict[str, tuple[str, _VT]]\n\n def __init__(\n self,\n data: Mapping[str, _VT] | Iterable[tuple[str, _VT]] "}
{"repo":"requests","file":"src/requests/structures.py","line":49,"symbol":"__init__","kind":"function","lang":"python","code":"def __init__(\n self,\n data: Mapping[str, _VT] | Iterable[tuple[str, _VT]] | None = None,\n **kwargs: _VT,\n ) -> None:\n self._store = OrderedDict()\n if data is None:\n data = {}\n self.update(data, **kwargs)"}
{"repo":"requests","file":"src/requests/structures.py","line":59,"symbol":"__setitem__","kind":"function","lang":"python","code":"def __setitem__(self, key: str, value: _VT) -> None:\n # Use the lowercased key for lookups, but store the actual\n # key alongside the value.\n self._store[key.lower()] = (key, value)"}
{"repo":"requests","file":"src/requests/structures.py","line":64,"symbol":"__getitem__","kind":"function","lang":"python","code":"def __getitem__(self, key: str) -> _VT:\n return self._store[key.lower()][1]"}
{"repo":"requests","file":"src/requests/structures.py","line":67,"symbol":"__delitem__","kind":"function","lang":"python","code":"def __delitem__(self, key: str) -> None:\n del self._store[key.lower()]"}
{"repo":"requests","file":"src/requests/structures.py","line":70,"symbol":"__iter__","kind":"function","lang":"python","code":"def __iter__(self) -> Iterator[str]:\n return (casedkey for casedkey, _ in self._store.values())"}
{"repo":"requests","file":"src/requests/structures.py","line":73,"symbol":"__len__","kind":"function","lang":"python","code":"def __len__(self) -> int:\n return len(self._store)"}
{"repo":"requests","file":"src/requests/structures.py","line":76,"symbol":"lower_items","kind":"function","lang":"python","code":"def lower_items(self) -> Iterator[tuple[str, _VT]]:\n \"\"\"Like iteritems(), but with all lowercase keys.\"\"\"\n return ((lowerkey, keyval[1]) for (lowerkey, keyval) in self._store.items())"}
{"repo":"requests","file":"src/requests/structures.py","line":80,"symbol":"__eq__","kind":"function","lang":"python","code":"def __eq__(self, other: object) -> bool:\n if isinstance(other, Mapping):\n other_dict: CaseInsensitiveDict[Any] = CaseInsensitiveDict(other) # type: ignore[reportUnknownArgumentType]\n else:\n return NotImplemented\n # Compare insensitively\n return dict(self.lower_items()) == dict(other_dict.lower_items())"}
{"repo":"requests","file":"src/requests/structures.py","line":89,"symbol":"copy","kind":"function","lang":"python","doc":"Copy is required","code":"def copy(self) -> CaseInsensitiveDict[_VT]:\n return CaseInsensitiveDict(self._store.values())"}
{"repo":"requests","file":"src/requests/structures.py","line":92,"symbol":"__repr__","kind":"function","lang":"python","code":"def __repr__(self) -> str:\n return str(dict(self.items()))"}
{"repo":"requests","file":"src/requests/structures.py","line":96,"symbol":"LookupDict","kind":"class","lang":"python","code":"class LookupDict(dict[str, _VT]):\n \"\"\"Dictionary lookup object.\"\"\"\n\n name: Any\n\n def __init__(self, name: Any = None) -> None:\n self.name = name\n super().__init__()\n\n def __repr__(self) -> str:\n return f\"<lookup '{self.name}'>\"\n\n def __getattr__(self, key: str) -> _VT | None:\n # We need this for type checkers to infer typing\n # on attribute access with status_codes.py\n if key in self.__dict__:\n return self.__dict__[key]\n else:\n raise AttributeError(\n f\"'{type(self).__name__}' object has no attribute '{key}'\"\n )\n\n def __getitem__(self, key: str) -> _VT | None: # type: ignore[override]\n # We allow fall-through here, so values default to None\n\n return self.__dict__.get(key, None)\n\n @overload\n def get(self, key: str, default: None = None) -> _VT | None: ...\n\n @overload\n def get(self, key: str, default: _D | _VT) -> _D | _VT: ...\n\n def get(self, key: str, default: _D | None = None) -> _VT | _D | None:\n return self.__dict__.get(key, default)"}
{"repo":"requests","file":"src/requests/structures.py","line":101,"symbol":"__init__","kind":"function","lang":"python","code":"def __init__(self, name: Any = None) -> None:\n self.name = name\n super().__init__()"}
{"repo":"requests","file":"src/requests/structures.py","line":105,"symbol":"__repr__","kind":"function","lang":"python","code":"def __repr__(self) -> str:\n return f\"<lookup '{self.name}'>\""}
{"repo":"requests","file":"src/requests/structures.py","line":108,"symbol":"__getattr__","kind":"function","lang":"python","code":"def __getattr__(self, key: str) -> _VT | None:\n # We need this for type checkers to infer typing\n # on attribute access with status_codes.py\n if key in self.__dict__:\n return self.__dict__[key]\n else:\n raise AttributeError(\n f\"'{type(self).__name__}' object has no attribute '{key}'\"\n )"}
{"repo":"requests","file":"src/requests/structures.py","line":118,"symbol":"__getitem__","kind":"function","lang":"python","code":"def __getitem__(self, key: str) -> _VT | None: # type: ignore[override]\n # We allow fall-through here, so values default to None\n\n return self.__dict__.get(key, None)"}
{"repo":"requests","file":"src/requests/structures.py","line":124,"symbol":"get","kind":"function","lang":"python","code":"def get(self, key: str, default: None = None) -> _VT | None: ..."}
{"repo":"requests","file":"src/requests/structures.py","line":127,"symbol":"get","kind":"function","lang":"python","code":"def get(self, key: str, default: _D | _VT) -> _D | _VT: ..."}
{"repo":"requests","file":"src/requests/structures.py","line":129,"symbol":"get","kind":"function","lang":"python","code":"def get(self, key: str, default: _D | None = None) -> _VT | _D | None:\n return self.__dict__.get(key, default)"}
{"repo":"requests","file":"src/requests/utils.py","line":99,"symbol":"proxy_bypass_registry","kind":"function","lang":"python","code":"def proxy_bypass_registry(host: str) -> bool:\n try:\n import winreg\n except ImportError:\n return False\n\n try:\n internetSettings = winreg.OpenKey(\n winreg.HKEY_CURRENT_USER,\n r\"Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings\",\n )\n # ProxyEnable could be REG_SZ or REG_DWORD, normalizing it\n proxyEnable = int(winreg.QueryValueEx(internetSettings, \"ProxyEnable\")[0])\n # ProxyOverride is almost always a string\n proxyOverride = winreg.QueryValueEx(internetSettings, \"ProxyOverride\")[0]\n except (OSError, ValueError):\n return False\n if not proxyEnable or not proxyOverride:\n return False\n\n # make a check value list from the registry entry: replace the\n # '<local>' string by the localhost entry and the corresponding\n # canonical entry.\n proxyOverride = proxyOverride.split(\";\")\n # filter out empty strings to avoid re.match return true in the following code.\n proxyOverride = filter(None, proxyOverride)\n # now check if we match one of the registry values.\n fo"}
{"repo":"requests","file":"src/requests/utils.py","line":137,"symbol":"proxy_bypass","kind":"function","lang":"python","code":"def proxy_bypass(host: str) -> bool: # noqa\n \"\"\"Return True, if the host should be bypassed.\n\n Checks proxy settings gathered from the environment, if specified,\n or the registry.\n \"\"\"\n if getproxies_environment():\n return proxy_bypass_environment(host)\n else:\n return proxy_bypass_registry(host)"}
{"repo":"requests","file":"src/requests/utils.py","line":149,"symbol":"dict_to_sequence","kind":"function","lang":"python","code":"def dict_to_sequence(\n d: _t.SupportsItems[Any, Any] | Iterable[tuple[Any, Any]],\n) -> Iterable[tuple[Any, Any]]:\n \"\"\"Returns an internal sequence dictionary update.\"\"\"\n\n if isinstance(d, _SupportsItems):\n return d.items()\n\n return d"}
{"repo":"requests","file":"src/requests/utils.py","line":160,"symbol":"super_len","kind":"function","lang":"python","code":"def super_len(o: Any) -> int:\n total_length = None\n current_position = 0\n\n if not is_urllib3_1 and isinstance(o, str):\n # urllib3 2.x+ treats all strings as utf-8 instead\n # of latin-1 (iso-8859-1) like http.client.\n o = o.encode(\"utf-8\")\n\n if hasattr(o, \"__len__\"):\n total_length = len(o)\n\n elif hasattr(o, \"len\"):\n total_length = o.len\n\n elif hasattr(o, \"fileno\"):\n try:\n fileno = o.fileno()\n except (io.UnsupportedOperation, AttributeError):\n # AttributeError is a surprising exception, seeing as how we've just checked\n # that `hasattr(o, 'fileno')`. It happens for objects obtained via\n # `Tarfile.extractfile()`, per issue 5229.\n pass\n else:\n total_length = os.fstat(fileno).st_size\n\n # Having used fstat to determine the file length, we need to\n # confirm that this file was opened up in binary mode.\n if \"b\" not in o.mode:\n warnings.warn(\n (\n \"Requests has determined the content-length for this \"\n \"request using the binary size of the f"}
{"repo":"requests","file":"src/requests/utils.py","line":231,"symbol":"get_netrc_auth","kind":"function","lang":"python","code":"def get_netrc_auth(\n url: _t.UriType, raise_errors: bool = False\n) -> tuple[str, str] | None:\n \"\"\"Returns the Requests tuple auth for a given url from netrc.\"\"\"\n\n if isinstance(url, bytes):\n url = url.decode(\"utf-8\")\n\n netrc_file = os.environ.get(\"NETRC\")\n if netrc_file is not None:\n netrc_locations = (netrc_file,)\n else:\n netrc_locations = (f\"~/{f}\" for f in NETRC_FILES)\n\n try:\n from netrc import NetrcParseError, netrc\n\n netrc_path = None\n\n for f in netrc_locations:\n loc = os.path.expanduser(f)\n if os.path.exists(loc):\n netrc_path = loc\n break\n\n # Abort early if there isn't one.\n if netrc_path is None:\n return\n\n ri = urlparse(url)\n host = ri.hostname\n\n if host is None:\n return\n\n try:\n _netrc = netrc(netrc_path).authenticators(host)\n if _netrc and any(_netrc):\n # Return with login / password\n login_i = 0 if _netrc[0] else 1\n return (_netrc[login_i] or \"\", _netrc[2] or \"\")\n except (NetrcParseError, OSError):\n # If there was"}
{"repo":"requests","file":"src/requests/utils.py","line":283,"symbol":"guess_filename","kind":"function","lang":"python","code":"def guess_filename(obj: Any) -> str | None:\n \"\"\"Tries to guess the filename of the given object.\"\"\"\n name = getattr(obj, \"name\", None)\n if name and isinstance(name, (str, bytes)) and name[0] != \"<\" and name[-1] != \">\":\n return os.path.basename(name) # type: ignore[return-value] # urllib3 accepts bytes but types str only"}
{"repo":"requests","file":"src/requests/utils.py","line":290,"symbol":"extract_zipped_paths","kind":"function","lang":"python","code":"def extract_zipped_paths(path: str) -> str:\n \"\"\"Replace nonexistent paths that look like they refer to a member of a zip\n archive with the location of an extracted copy of the target, or else\n just return the provided path unchanged.\n \"\"\"\n if os.path.exists(path):\n # this is already a valid path, no need to do anything further\n return path\n\n # find the first valid part of the provided path and treat that as a zip archive\n # assume the rest of the path is the name of a member in the archive\n archive, member = os.path.split(path)\n while archive and not os.path.exists(archive):\n archive, prefix = os.path.split(archive)\n if not prefix:\n # If we don't check for an empty prefix after the split (in other words, archive remains unchanged after the split),\n # we _can_ end up in an infinite loop on a rare corner case affecting a small number of users\n break\n member = \"/\".join([prefix, member])\n\n if not zipfile.is_zipfile(archive):\n return path\n\n zip_file = zipfile.ZipFile(archive)\n if member not in zip_file.namelist():\n return path\n\n # we have a valid zip archive and a val"}
{"repo":"requests","file":"src/requests/utils.py","line":329,"symbol":"atomic_open","kind":"function","lang":"python","code":"def atomic_open(filename: str) -> Generator[BufferedWriter, None, None]:\n \"\"\"Write a file to the disk in an atomic fashion\"\"\"\n tmp_descriptor, tmp_name = tempfile.mkstemp(dir=os.path.dirname(filename))\n try:\n with os.fdopen(tmp_descriptor, \"wb\") as tmp_handler:\n yield tmp_handler\n os.replace(tmp_name, filename)\n except BaseException:\n os.remove(tmp_name)\n raise"}
{"repo":"requests","file":"src/requests/utils.py","line":341,"symbol":"from_key_val_list","kind":"function","lang":"python","code":"def from_key_val_list(\n value: Mapping[Any, Any] | Iterable[tuple[Any, Any]] | None,\n) -> dict[Any, Any] | None:\n \"\"\"Take an object and test to see if it can be represented as a\n dictionary. Unless it can not be represented as such, return an\n OrderedDict, e.g.,\n\n ::\n\n >>> from_key_val_list([('key', 'val')])\n OrderedDict([('key', 'val')])\n >>> from_key_val_list('string')\n Traceback (most recent call last):\n ...\n ValueError: cannot encode objects that are not 2-tuples\n >>> from_key_val_list({'key': 'val'})\n OrderedDict([('key', 'val')])\n\n :rtype: OrderedDict\n \"\"\"\n if value is None:\n return None\n\n if isinstance(value, (str, bytes, bool, int)):\n raise ValueError(\"cannot encode objects that are not 2-tuples\")\n\n return OrderedDict(value)"}
{"repo":"requests","file":"src/requests/utils.py","line":371,"symbol":"to_key_val_list","kind":"function","lang":"python","code":"def to_key_val_list(value: None) -> None: ..."}
{"repo":"requests","file":"src/requests/utils.py","line":373,"symbol":"to_key_val_list","kind":"function","lang":"python","code":"def to_key_val_list(\n value: _t.SupportsItems[_KT, _VT] | Iterable[tuple[_KT, _VT]],\n) -> list[tuple[_KT, _VT]]: ..."}
{"repo":"requests","file":"src/requests/utils.py","line":376,"symbol":"to_key_val_list","kind":"function","lang":"python","code":"def to_key_val_list(\n value: _t.SupportsItems[_KT, _VT] | Iterable[tuple[_KT, _VT]] | None,\n) -> list[tuple[_KT, _VT]] | None:\n \"\"\"Take an object and test to see if it can be represented as a\n dictionary. If it can be, return a list of tuples, e.g.,\n\n ::\n\n >>> to_key_val_list([('key', 'val')])\n [('key', 'val')]\n >>> to_key_val_list({'key': 'val'})\n [('key', 'val')]\n >>> to_key_val_list('string')\n Traceback (most recent call last):\n ...\n ValueError: cannot encode objects that are not 2-tuples\n\n :rtype: list\n \"\"\"\n if value is None:\n return None\n\n if isinstance(value, (str, bytes, bool, int)):\n raise ValueError(\"cannot encode objects that are not 2-tuples\")\n\n if isinstance(value, _SupportsItems):\n return list(value.items())\n\n return list(value)"}
{"repo":"requests","file":"src/requests/utils.py","line":408,"symbol":"parse_list_header","kind":"function","lang":"python","doc":"From mitsuhiko/werkzeug (used with permission).","code":"def parse_list_header(value: str) -> list[str]:\n \"\"\"Parse lists as described by RFC 2068 Section 2.\n\n In particular, parse comma-separated lists where the elements of\n the list may include quoted-strings. A quoted-string could\n contain a comma. A non-quoted string could have quotes in the\n middle. Quotes are removed automatically after parsing.\n\n It basically works like :func:`parse_set_header` just that items\n may appear multiple times and case sensitivity is preserved.\n\n The return value is a standard :class:`list`:\n\n >>> parse_list_header('token, \"quoted value\"')\n ['token', 'quoted value']\n\n To create a header from the :class:`list` again, use the\n :func:`dump_header` function.\n\n :param value: a string with a list header.\n :return: :class:`list`\n :rtype: list\n \"\"\"\n result: list[str] = []\n for item in _parse_list_header(value):\n if item[:1] == item[-1:] == '\"':\n item = unquote_header_value(item[1:-1])\n result.append(item)\n return result"}
{"repo":"requests","file":"src/requests/utils.py","line":440,"symbol":"parse_dict_header","kind":"function","lang":"python","doc":"From mitsuhiko/werkzeug (used with permission).","code":"def parse_dict_header(value: str) -> dict[str, str | None]:\n \"\"\"Parse lists of key, value pairs as described by RFC 2068 Section 2 and\n convert them into a python dict:\n\n >>> d = parse_dict_header('foo=\"is a fish\", bar=\"as well\"')\n >>> type(d) is dict\n True\n >>> sorted(d.items())\n [('bar', 'as well'), ('foo', 'is a fish')]\n\n If there is no value for a key it will be `None`:\n\n >>> parse_dict_header('key_without_value')\n {'key_without_value': None}\n\n To create a header from the :class:`dict` again, use the\n :func:`dump_header` function.\n\n :param value: a string with a dict header.\n :return: :class:`dict`\n :rtype: dict\n \"\"\"\n result: dict[str, str | None] = {}\n for item in _parse_list_header(value):\n if \"=\" not in item:\n result[item] = None\n continue\n name, value = item.split(\"=\", 1)\n if value[:1] == value[-1:] == '\"':\n value = unquote_header_value(value[1:-1])\n result[name] = value\n return result"}
{"repo":"requests","file":"src/requests/utils.py","line":475,"symbol":"unquote_header_value","kind":"function","lang":"python","doc":"From mitsuhiko/werkzeug (used with permission).","code":"def unquote_header_value(value: str, is_filename: bool = False) -> str:\n r\"\"\"Unquotes a header value. (Reversal of :func:`quote_header_value`).\n This does not use the real unquoting but what browsers are actually\n using for quoting.\n\n :param value: the header value to unquote.\n :rtype: str\n \"\"\"\n if value and value[0] == value[-1] == '\"':\n # this is not the real unquoting, but fixing this so that the\n # RFC is met will result in bugs with internet explorer and\n # probably some other browsers as well. IE for example is\n # uploading files with \"C:\\foo\\bar.txt\" as filename\n value = value[1:-1]\n\n # if this is a filename and the starting characters look like\n # a UNC path, then just return the value without quotes. Using the\n # replace sequence below on a UNC path has the effect of turning\n # the leading double slash into a single slash and then\n # _fix_ie_filename() doesn't work correctly. See #458.\n if not is_filename or value[:2] != \"\\\\\\\\\":\n return value.replace(\"\\\\\\\\\", \"\\\\\").replace('\\\\\"', '\"')\n return value"}
{"repo":"requests","file":"src/requests/utils.py","line":500,"symbol":"dict_from_cookiejar","kind":"function","lang":"python","code":"def dict_from_cookiejar(cj: CookieJar) -> dict[str, str | None]:\n \"\"\"Returns a key/value dictionary from a CookieJar.\n\n :param cj: CookieJar object to extract cookies from.\n :rtype: dict\n \"\"\"\n\n cookie_dict = {cookie.name: cookie.value for cookie in cj}\n return cookie_dict"}
{"repo":"requests","file":"src/requests/utils.py","line":511,"symbol":"add_dict_to_cookiejar","kind":"function","lang":"python","code":"def add_dict_to_cookiejar(cj: CookieJar, cookie_dict: dict[str, str]) -> CookieJar:\n \"\"\"Returns a CookieJar from a key/value dictionary.\n\n :param cj: CookieJar to insert cookies into.\n :param cookie_dict: Dict of key/values to insert into CookieJar.\n :rtype: CookieJar\n \"\"\"\n\n return cookiejar_from_dict(cookie_dict, cj)"}
{"repo":"requests","file":"src/requests/utils.py","line":522,"symbol":"get_encodings_from_content","kind":"function","lang":"python","code":"def get_encodings_from_content(content: str) -> list[str]:\n \"\"\"Returns encodings from given content string.\n\n :param content: bytestring to extract encodings from.\n \"\"\"\n warnings.warn(\n (\n \"In requests 3.0, get_encodings_from_content will be removed. For \"\n \"more information, please see the discussion on issue #2266. (This\"\n \" warning should only appear once.)\"\n ),\n DeprecationWarning,\n )\n\n charset_re = re.compile(r'<meta.*?charset=[\"\\']*(.+?)[\"\\'>]', flags=re.I)\n pragma_re = re.compile(r'<meta.*?content=[\"\\']*;?charset=(.+?)[\"\\'>]', flags=re.I)\n xml_re = re.compile(r'^<\\?xml.*?encoding=[\"\\']*(.+?)[\"\\'>]')\n\n return (\n charset_re.findall(content)\n + pragma_re.findall(content)\n + xml_re.findall(content)\n )"}
{"repo":"requests","file":"src/requests/utils.py","line":547,"symbol":"_parse_content_type_header","kind":"function","lang":"python","code":"def _parse_content_type_header(header: str) -> tuple[str, dict[str, Any]]:\n \"\"\"Returns content type and parameters from given header.\n\n :param header: string\n :return: tuple containing content type and dictionary of\n parameters.\n \"\"\"\n\n tokens = header.split(\";\")\n content_type, params = tokens[0].strip(), tokens[1:]\n params_dict: dict[str, str | bool] = {}\n strip_chars = \"\\\"' \"\n\n for param in params:\n param = param.strip()\n if param and (idx := param.find(\"=\")) != -1:\n key = param[:idx].strip(strip_chars)\n value = param[idx + 1 :].strip(strip_chars)\n params_dict[key.lower()] = value\n return content_type, params_dict"}
{"repo":"requests","file":"src/requests/utils.py","line":569,"symbol":"get_encoding_from_headers","kind":"function","lang":"python","code":"def get_encoding_from_headers(headers: CaseInsensitiveDict[str]) -> str | None:\n \"\"\"Returns encodings from given HTTP Header Dict.\n\n :param headers: dictionary to extract encoding from.\n :rtype: str\n \"\"\"\n\n content_type = headers.get(\"content-type\")\n\n if not content_type:\n return None\n\n content_type, params = _parse_content_type_header(content_type)\n\n if \"charset\" in params:\n return params[\"charset\"].strip(\"'\\\"\")\n\n if \"text\" in content_type:\n return \"ISO-8859-1\"\n\n if \"application/json\" in content_type:\n # Assume UTF-8 based on RFC 4627: https://www.ietf.org/rfc/rfc4627.txt since the charset was unset\n return \"utf-8\""}
{"repo":"requests","file":"src/requests/utils.py","line":594,"symbol":"stream_decode_response_unicode","kind":"function","lang":"python","code":"def stream_decode_response_unicode(\n iterator: Iterable[bytes], r: Response\n) -> Generator[str | bytes, None, None]:\n \"\"\"Stream decodes an iterator.\"\"\"\n\n if r.encoding is None:\n yield from iterator\n return\n\n decoder = codecs.getincrementaldecoder(r.encoding)(errors=\"replace\")\n for chunk in iterator:\n rv = decoder.decode(chunk)\n if rv:\n yield rv\n rv = decoder.decode(b\"\", final=True)\n if rv:\n yield rv"}
{"repo":"requests","file":"src/requests/utils.py","line":614,"symbol":"iter_slices","kind":"function","lang":"python","code":"def iter_slices(\n string: bytes, slice_length: int | None\n) -> Generator[bytes, None, None]: ..."}
{"repo":"requests","file":"src/requests/utils.py","line":618,"symbol":"iter_slices","kind":"function","lang":"python","code":"def iter_slices(\n string: str, slice_length: int | None\n) -> Generator[str, None, None]: ..."}
{"repo":"requests","file":"src/requests/utils.py","line":621,"symbol":"iter_slices","kind":"function","lang":"python","code":"def iter_slices(\n string: bytes | str, slice_length: int | None\n) -> Generator[bytes | str, None, None]:\n \"\"\"Iterate over slices of a string.\"\"\"\n pos = 0\n if slice_length is None or slice_length <= 0:\n slice_length = len(string)\n while pos < len(string):\n yield string[pos : pos + slice_length]\n pos += slice_length"}
{"repo":"requests","file":"src/requests/utils.py","line":633,"symbol":"get_unicode_from_response","kind":"function","lang":"python","code":"def get_unicode_from_response(r: Response) -> str | bytes | None:\n \"\"\"Returns the requested content back in unicode.\n\n :param r: Response object to get unicode content from.\n\n Tried:\n\n 1. charset from content-type\n 2. fall back and replace all unicode characters\n\n :rtype: str\n \"\"\"\n warnings.warn(\n (\n \"In requests 3.0, get_unicode_from_response will be removed. For \"\n \"more information, please see the discussion on issue #2266. (This\"\n \" warning should only appear once.)\"\n ),\n DeprecationWarning,\n )\n if r.content is None: # type: ignore[reportUnnecessaryComparison]\n return None\n\n tried_encodings: list[str] = []\n\n # Try charset from content-type\n encoding = get_encoding_from_headers(r.headers)\n\n if encoding:\n try:\n return str(r.content, encoding)\n except UnicodeError:\n tried_encodings.append(encoding)\n\n # Fall back:\n try:\n return str(r.content, encoding or \"utf-8\", errors=\"replace\")\n except TypeError:\n return r.content"}
{"repo":"requests","file":"src/requests/utils.py","line":680,"symbol":"unquote_unreserved","kind":"function","lang":"python","code":"def unquote_unreserved(uri: str) -> str:\n \"\"\"Un-escape any percent-escape sequences in a URI that are unreserved\n characters. This leaves all reserved, illegal and non-ASCII bytes encoded.\n\n :rtype: str\n \"\"\"\n parts = uri.split(\"%\")\n for i in range(1, len(parts)):\n h = parts[i][0:2]\n if len(h) == 2 and h.isalnum():\n try:\n c = chr(int(h, 16))\n except ValueError:\n raise InvalidURL(f\"Invalid percent-escape sequence: '{h}'\")\n\n if c in UNRESERVED_SET:\n parts[i] = c + parts[i][2:]\n else:\n parts[i] = f\"%{parts[i]}\"\n else:\n parts[i] = f\"%{parts[i]}\"\n return \"\".join(parts)"}
{"repo":"requests","file":"src/requests/utils.py","line":704,"symbol":"requote_uri","kind":"function","lang":"python","code":"def requote_uri(uri: str) -> str:\n \"\"\"Re-quote the given URI.\n\n This function passes the given URI through an unquote/quote cycle to\n ensure that it is fully and consistently quoted.\n\n :rtype: str\n \"\"\"\n safe_with_percent = \"!#$%&'()*+,/:;=?@[]~\"\n safe_without_percent = \"!#$&'()*+,/:;=?@[]~\"\n try:\n # Unquote only the unreserved characters\n # Then quote only illegal characters (do not quote reserved,\n # unreserved, or '%')\n return quote(unquote_unreserved(uri), safe=safe_with_percent)\n except InvalidURL:\n # We couldn't unquote the given URI, so let's try quoting it, but\n # there may be unquoted '%'s in the URI. We need to make sure they're\n # properly quoted so they do not cause issues elsewhere.\n return quote(uri, safe=safe_without_percent)"}
{"repo":"requests","file":"src/requests/utils.py","line":726,"symbol":"address_in_network","kind":"function","lang":"python","code":"def address_in_network(ip: str, net: str) -> bool:\n \"\"\"This function allows you to check if an IP belongs to a network subnet\n\n Example: returns True if ip = 192.168.1.1 and net = 192.168.1.0/24\n returns False if ip = 192.168.1.1 and net = 192.168.100.0/24\n\n :rtype: bool\n \"\"\"\n ipaddr = struct.unpack(\"=L\", socket.inet_aton(ip))[0]\n netaddr, bits = net.split(\"/\")\n netmask = struct.unpack(\"=L\", socket.inet_aton(dotted_netmask(int(bits))))[0]\n network = struct.unpack(\"=L\", socket.inet_aton(netaddr))[0] & netmask\n return (ipaddr & netmask) == (network & netmask)"}
{"repo":"requests","file":"src/requests/utils.py","line":741,"symbol":"dotted_netmask","kind":"function","lang":"python","code":"def dotted_netmask(mask: int) -> str:\n \"\"\"Converts mask from /xx format to xxx.xxx.xxx.xxx\n\n Example: if mask is 24 function returns 255.255.255.0\n\n :rtype: str\n \"\"\"\n bits = 0xFFFFFFFF ^ (1 << 32 - mask) - 1\n return socket.inet_ntoa(struct.pack(\">I\", bits))"}
{"repo":"requests","file":"src/requests/utils.py","line":752,"symbol":"is_ipv4_address","kind":"function","lang":"python","code":"def is_ipv4_address(string_ip: str) -> bool:\n \"\"\"\n :rtype: bool\n \"\"\"\n try:\n socket.inet_aton(string_ip)\n except OSError:\n return False\n return True"}
{"repo":"requests","file":"src/requests/utils.py","line":763,"symbol":"is_valid_cidr","kind":"function","lang":"python","code":"def is_valid_cidr(string_network: str) -> bool:\n \"\"\"\n Very simple check of the cidr format in no_proxy variable.\n\n :rtype: bool\n \"\"\"\n if string_network.count(\"/\") == 1:\n try:\n mask = int(string_network.split(\"/\")[1])\n except ValueError:\n return False\n\n if mask < 1 or mask > 32:\n return False\n\n try:\n socket.inet_aton(string_network.split(\"/\")[0])\n except OSError:\n return False\n else:\n return False\n return True"}
{"repo":"requests","file":"src/requests/utils.py","line":788,"symbol":"set_environ","kind":"function","lang":"python","code":"def set_environ(env_name: str, value: str | None) -> Generator[None, None, None]:\n \"\"\"Set the environment variable 'env_name' to 'value'\n\n Save previous value, yield, and then restore the previous value stored in\n the environment variable 'env_name'.\n\n If 'value' is None, do nothing\"\"\"\n value_changed = value is not None\n old_value: str | None = None\n if value_changed:\n old_value = os.environ.get(env_name)\n os.environ[env_name] = value\n try:\n yield\n finally:\n if value_changed:\n if old_value is None:\n del os.environ[env_name]\n else:\n os.environ[env_name] = old_value"}
{"repo":"requests","file":"src/requests/utils.py","line":810,"symbol":"should_bypass_proxies","kind":"function","lang":"python","code":"def should_bypass_proxies(url: str, no_proxy: str | None) -> bool:\n \"\"\"\n Returns whether we should bypass proxies or not.\n\n :rtype: bool\n \"\"\"\n\n # Prioritize lowercase environment variables over uppercase\n # to keep a consistent behaviour with other http projects (curl, wget).\n def get_proxy(key: str) -> str | None:\n return os.environ.get(key) or os.environ.get(key.upper())\n\n # First check whether no_proxy is defined. If it is, check that the URL\n # we're getting isn't in the no_proxy list.\n no_proxy_arg = no_proxy\n if no_proxy is None:\n no_proxy = get_proxy(\"no_proxy\")\n parsed = urlparse(url)\n hostname = parsed.hostname\n\n if hostname is None:\n # URLs don't always have hostnames, e.g. file:/// urls.\n return True\n\n if no_proxy:\n # We need to check whether we match here. We need to see if we match\n # the end of the hostname, both with and without the port.\n no_proxy_hosts = (host for host in no_proxy.replace(\" \", \"\").split(\",\") if host)\n\n if is_ipv4_address(hostname):\n for proxy_ip in no_proxy_hosts:\n if is_valid_cidr(proxy_ip):\n if address_"}
{"repo":"requests","file":"src/requests/utils.py","line":819,"symbol":"get_proxy","kind":"function","lang":"python","doc":"Prioritize lowercase environment variables over uppercase to keep a consistent behaviour with other http projects (curl, wget).","code":"def get_proxy(key: str) -> str | None:\n return os.environ.get(key) or os.environ.get(key.upper())"}
{"repo":"requests","file":"src/requests/utils.py","line":873,"symbol":"get_environ_proxies","kind":"function","lang":"python","code":"def get_environ_proxies(url: str, no_proxy: str | None = None) -> dict[str, str]:\n \"\"\"\n Return a dict of environment proxies.\n\n :rtype: dict\n \"\"\"\n if should_bypass_proxies(url, no_proxy=no_proxy):\n return {}\n else:\n return getproxies()"}
{"repo":"requests","file":"src/requests/utils.py","line":885,"symbol":"select_proxy","kind":"function","lang":"python","code":"def select_proxy(url: str, proxies: dict[str, str] | None) -> str | None:\n \"\"\"Select a proxy for the url, if applicable.\n\n :param url: The url being for the request\n :param proxies: A dictionary of schemes or schemes and hosts to proxy URLs\n \"\"\"\n proxies = proxies or {}\n urlparts = urlparse(url)\n if urlparts.hostname is None:\n return proxies.get(urlparts.scheme, proxies.get(\"all\"))\n\n proxy_keys = [\n urlparts.scheme + \"://\" + urlparts.hostname,\n urlparts.scheme,\n \"all://\" + urlparts.hostname,\n \"all\",\n ]\n proxy = None\n for proxy_key in proxy_keys:\n if proxy_key in proxies:\n proxy = proxies[proxy_key]\n break\n\n return proxy"}
{"repo":"requests","file":"src/requests/utils.py","line":911,"symbol":"resolve_proxies","kind":"function","lang":"python","code":"def resolve_proxies(\n request: Request | PreparedRequest,\n proxies: dict[str, str] | None,\n trust_env: bool = True,\n) -> dict[str, str]:\n \"\"\"This method takes proxy information from a request and configuration\n input to resolve a mapping of target proxies. This will consider settings\n such as NO_PROXY to strip proxy configurations.\n\n :param request: Request or PreparedRequest\n :param proxies: A dictionary of schemes or schemes and hosts to proxy URLs\n :param trust_env: Boolean declaring whether to trust environment configs\n\n :rtype: dict\n \"\"\"\n proxies = proxies if proxies is not None else {}\n url = cast(str, request.url)\n scheme = urlparse(url).scheme\n no_proxy = proxies.get(\"no_proxy\")\n new_proxies = proxies.copy()\n\n if trust_env and not should_bypass_proxies(url, no_proxy=no_proxy):\n environ_proxies = get_environ_proxies(url, no_proxy=no_proxy)\n\n proxy = environ_proxies.get(scheme, environ_proxies.get(\"all\"))\n\n if proxy:\n new_proxies.setdefault(scheme, proxy)\n return new_proxies"}
{"repo":"requests","file":"src/requests/utils.py","line":942,"symbol":"default_user_agent","kind":"function","lang":"python","code":"def default_user_agent(name: str = \"python-requests\") -> str:\n \"\"\"\n Return a string representing the default user agent.\n\n :rtype: str\n \"\"\"\n return f\"{name}/{__version__}\""}
{"repo":"requests","file":"src/requests/utils.py","line":951,"symbol":"default_headers","kind":"function","lang":"python","code":"def default_headers() -> CaseInsensitiveDict[str]:\n \"\"\"\n :rtype: requests.structures.CaseInsensitiveDict\n \"\"\"\n return CaseInsensitiveDict(\n {\n \"User-Agent\": default_user_agent(),\n \"Accept-Encoding\": DEFAULT_ACCEPT_ENCODING,\n \"Accept\": \"*/*\",\n \"Connection\": \"keep-alive\",\n }\n )"}
{"repo":"requests","file":"src/requests/utils.py","line":965,"symbol":"parse_header_links","kind":"function","lang":"python","code":"def parse_header_links(value: str) -> list[dict[str, str]]:\n \"\"\"Return a list of parsed link headers proxies.\n\n i.e. Link: <http:/.../front.jpeg>; rel=front; type=\"image/jpeg\",<http://.../back.jpeg>; rel=back;type=\"image/jpeg\"\n\n :rtype: list\n \"\"\"\n\n links: list[dict[str, str]] = []\n\n replace_chars = \" '\\\"\"\n\n value = value.strip(replace_chars)\n if not value:\n return links\n\n for val in re.split(\", *<\", value):\n try:\n url, params = val.split(\";\", 1)\n except ValueError:\n url, params = val, \"\"\n\n link: dict[str, str] = {\"url\": url.strip(\"<> '\\\"\")}\n\n for param in params.split(\";\"):\n try:\n key, value = param.split(\"=\")\n except ValueError:\n break\n\n link[key.strip(replace_chars)] = value.strip(replace_chars)\n\n links.append(link)\n\n return links"}
{"repo":"requests","file":"src/requests/utils.py","line":1008,"symbol":"guess_json_utf","kind":"function","lang":"python","code":"def guess_json_utf(data: bytes) -> str | None:\n \"\"\"\n :rtype: str\n \"\"\"\n # JSON always starts with two ASCII characters, so detection is as\n # easy as counting the nulls and from their location and count\n # determine the encoding. Also detect a BOM, if present.\n sample = data[:4]\n if sample in (codecs.BOM_UTF32_LE, codecs.BOM_UTF32_BE):\n return \"utf-32\" # BOM included\n if sample[:3] == codecs.BOM_UTF8:\n return \"utf-8-sig\" # BOM included, MS style (discouraged)\n if sample[:2] in (codecs.BOM_UTF16_LE, codecs.BOM_UTF16_BE):\n return \"utf-16\" # BOM included\n nullcount = sample.count(_null)\n if nullcount == 0:\n return \"utf-8\"\n if nullcount == 2:\n if sample[::2] == _null2: # 1st and 3rd are null\n return \"utf-16-be\"\n if sample[1::2] == _null2: # 2nd and 4th are null\n return \"utf-16-le\"\n # Did not detect 2 valid UTF-16 ascii-range characters\n if nullcount == 3:\n if sample[:3] == _null3:\n return \"utf-32-be\"\n if sample[1:] == _null3:\n return \"utf-32-le\"\n # Did not detect a valid UTF-32 ascii-range character\n return None"}
{"repo":"requests","file":"src/requests/utils.py","line":1040,"symbol":"prepend_scheme_if_needed","kind":"function","lang":"python","code":"def prepend_scheme_if_needed(url: str, new_scheme: str) -> str:\n \"\"\"Given a URL that may or may not have a scheme, prepend the given scheme.\n Does not replace a present scheme with the one provided as an argument.\n\n :rtype: str\n \"\"\"\n parsed = parse_url(url)\n scheme, auth, _host, _port, path, query, fragment = parsed\n\n # A defect in urlparse determines that there isn't a netloc present in some\n # urls. We previously assumed parsing was overly cautious, and swapped the\n # netloc and path. Due to a lack of tests on the original defect, this is\n # maintained with parse_url for backwards compatibility.\n netloc = parsed.netloc\n if not netloc:\n netloc, path = path, netloc\n\n if auth:\n # parse_url doesn't provide the netloc with auth\n # so we'll add it ourselves.\n netloc = cast(str, netloc)\n netloc = \"@\".join([auth, netloc])\n if scheme is None:\n scheme = new_scheme\n if path is None:\n path = \"\"\n\n return urlunparse((scheme, netloc, path, \"\", query, fragment))"}
{"repo":"requests","file":"src/requests/utils.py","line":1070,"symbol":"get_auth_from_url","kind":"function","lang":"python","code":"def get_auth_from_url(url: str) -> tuple[str, str]:\n \"\"\"Given a url with authentication components, extract them into a tuple of\n username,password.\n\n :rtype: (str,str)\n \"\"\"\n parsed = urlparse(url)\n\n try:\n # except handles parsed.username/password being None\n auth = (unquote(parsed.username), unquote(parsed.password)) # type: ignore[arg-type]\n except (AttributeError, TypeError):\n auth = (\"\", \"\")\n\n return auth"}
{"repo":"requests","file":"src/requests/utils.py","line":1087,"symbol":"check_header_validity","kind":"function","lang":"python","code":"def check_header_validity(header: tuple[str | bytes, str | bytes]) -> None:\n \"\"\"Verifies that header parts don't contain leading whitespace\n reserved characters, or return characters.\n\n :param header: tuple, in the format (name, value).\n \"\"\"\n name, value = header\n _validate_header_part(header, name, 0)\n _validate_header_part(header, value, 1)"}
{"repo":"requests","file":"src/requests/utils.py","line":1098,"symbol":"_validate_header_part","kind":"function","lang":"python","code":"def _validate_header_part(\n header: tuple[str | bytes, str | bytes],\n header_part: str | bytes,\n header_validator_index: int,\n) -> None:\n if isinstance(header_part, str):\n validator = _HEADER_VALIDATORS_STR[header_validator_index]\n elif isinstance(header_part, bytes):\n # runtime guard for non-str/bytes input\n validator = _HEADER_VALIDATORS_BYTE[header_validator_index]\n else:\n raise InvalidHeader(\n f\"Header part ({header_part!r}) from {header} \"\n f\"must be of type str or bytes, not {type(header_part)}\"\n )\n\n if not validator.match(header_part): # type: ignore[arg-type]\n header_kind = \"name\" if header_validator_index == 0 else \"value\"\n raise InvalidHeader(\n f\"Invalid leading whitespace, reserved character(s), or return \"\n f\"character(s) in header {header_kind}: {header_part!r}\"\n )"}
{"repo":"requests","file":"src/requests/utils.py","line":1122,"symbol":"urldefragauth","kind":"function","lang":"python","code":"def urldefragauth(url: str) -> str:\n \"\"\"\n Given a url remove the fragment and the authentication part.\n\n :rtype: str\n \"\"\"\n scheme, netloc, path, params, query, _fragment = urlparse(url)\n\n # see func:`prepend_scheme_if_needed`\n if not netloc:\n netloc, path = path, netloc\n\n netloc = netloc.rsplit(\"@\", 1)[-1]\n\n return urlunparse((scheme, netloc, path, params, query, \"\"))"}
{"repo":"requests","file":"src/requests/utils.py","line":1139,"symbol":"rewind_body","kind":"function","lang":"python","code":"def rewind_body(prepared_request: PreparedRequest) -> None:\n \"\"\"Move file pointer back to its recorded starting position\n so it can be read again on redirect.\n \"\"\"\n body_seek = getattr(prepared_request.body, \"seek\", None)\n if body_seek is not None and isinstance(\n prepared_request._body_position,\n integer_types,\n ):\n try:\n body_seek(prepared_request._body_position)\n except OSError:\n raise UnrewindableBodyError(\n \"An error occurred when rewinding request body for redirect.\"\n )\n else:\n raise UnrewindableBodyError(\"Unable to rewind request body for redirect.\")"}
{"repo":"requests","file":"tests/certs/expired/Makefile","line":1,"symbol":".PHONY","kind":"target","lang":"make","code":".PHONY: all clean ca server"}
{"repo":"requests","file":"tests/certs/expired/Makefile","line":3,"symbol":"ca","kind":"target","lang":"make","code":"ca:\n\tmake -C $@ all"}
{"repo":"requests","file":"tests/certs/expired/Makefile","line":6,"symbol":"server","kind":"target","lang":"make","code":"server:\n\tmake -C $@ all"}
{"repo":"requests","file":"tests/certs/expired/Makefile","line":9,"symbol":"all","kind":"target","lang":"make","code":"all: ca server"}
{"repo":"requests","file":"tests/certs/expired/Makefile","line":11,"symbol":"clean","kind":"target","lang":"make","code":"clean:\n\tmake -C ca clean\n\tmake -C server clean"}
{"repo":"requests","file":"tests/certs/expired/ca/Makefile","line":1,"symbol":".PHONY","kind":"target","lang":"make","code":".PHONY: all clean"}
{"repo":"requests","file":"tests/certs/expired/ca/Makefile","line":3,"symbol":"root_files","kind":"variable","lang":"make","code":"root_files = ca-private.key ca.crt"}
{"repo":"requests","file":"tests/certs/expired/ca/Makefile","line":5,"symbol":"ca-private.key","kind":"target","lang":"make","code":"ca-private.key:\n\topenssl genrsa -out ca-private.key 2048"}
{"repo":"requests","file":"tests/certs/expired/ca/Makefile","line":8,"symbol":"all","kind":"target","lang":"make","code":"all: ca-private.key\n\topenssl req -x509 -sha256 -days 7300 -key ca-private.key -out ca.crt -config ca.cnf\n\tln -s ca.crt cacert.pem"}
{"repo":"requests","file":"tests/certs/expired/ca/Makefile","line":12,"symbol":"clean","kind":"target","lang":"make","code":"clean:\n\trm -f cacert.pem ca.crt ca-private.key *.csr"}
{"repo":"requests","file":"tests/certs/expired/server/Makefile","line":1,"symbol":".PHONY","kind":"target","lang":"make","code":".PHONY: all clean"}
{"repo":"requests","file":"tests/certs/expired/server/Makefile","line":3,"symbol":"server.key","kind":"target","lang":"make","code":"server.key:\n\topenssl genrsa -out $@ 2048"}
{"repo":"requests","file":"tests/certs/expired/server/Makefile","line":6,"symbol":"server.csr","kind":"target","lang":"make","code":"server.csr: server.key\n\topenssl req -key $< -new -out $@ -config cert.cnf"}
{"repo":"requests","file":"tests/certs/expired/server/Makefile","line":9,"symbol":"server.pem","kind":"target","lang":"make","code":"server.pem: server.csr\n\topenssl x509 -req -CA ../ca/ca.crt -CAkey ../ca/ca-private.key -in server.csr -outform PEM -out server.pem -days 0 -CAcreateserial\n\topenssl x509 -in ../ca/ca.crt -outform PEM >> $@"}
{"repo":"requests","file":"tests/certs/expired/server/Makefile","line":13,"symbol":"all","kind":"target","lang":"make","code":"all: server.pem"}
{"repo":"requests","file":"tests/certs/expired/server/Makefile","line":15,"symbol":"clean","kind":"target","lang":"make","code":"clean:\n\trm -f server.*"}
{"repo":"requests","file":"tests/certs/expired/server/server.pem","line":1,"symbol":"CERTIFICATE","kind":"field","lang":"pem","code":"-----BEGIN CERTIFICATE-----"}
{"repo":"requests","file":"tests/certs/expired/server/server.pem","line":23,"symbol":"CERTIFICATE","kind":"field","lang":"pem","code":"-----BEGIN CERTIFICATE-----"}
{"repo":"requests","file":"tests/certs/mtls/Makefile","line":1,"symbol":".PHONY","kind":"target","lang":"make","code":".PHONY: all clean"}
{"repo":"requests","file":"tests/certs/mtls/Makefile","line":3,"symbol":"all","kind":"target","lang":"make","code":"all:\n\tmake -C client all"}
{"repo":"requests","file":"tests/certs/mtls/Makefile","line":6,"symbol":"clean","kind":"target","lang":"make","code":"clean:\n\tmake -C client clean"}
{"repo":"requests","file":"tests/certs/mtls/client/Makefile","line":1,"symbol":".PHONY","kind":"target","lang":"make","code":".PHONY: all clean"}
{"repo":"requests","file":"tests/certs/mtls/client/Makefile","line":3,"symbol":"client.key","kind":"target","lang":"make","code":"client.key:\n\topenssl genrsa -out $@ 2048"}
{"repo":"requests","file":"tests/certs/mtls/client/Makefile","line":6,"symbol":"client.csr","kind":"target","lang":"make","code":"client.csr: client.key\n\topenssl req -key $< -new -out $@ -config cert.cnf"}
{"repo":"requests","file":"tests/certs/mtls/client/Makefile","line":9,"symbol":"client.pem","kind":"target","lang":"make","code":"client.pem: client.csr\n\topenssl x509 -req -CA ./ca/ca.crt -CAkey ./ca/ca-private.key -in client.csr -outform PEM -out client.pem -days 730 -CAcreateserial\n\topenssl x509 -in ./ca/ca.crt -outform PEM >> $@"}
{"repo":"requests","file":"tests/certs/mtls/client/Makefile","line":13,"symbol":"all","kind":"target","lang":"make","code":"all: client.pem"}
{"repo":"requests","file":"tests/certs/mtls/client/Makefile","line":15,"symbol":"clean","kind":"target","lang":"make","code":"clean:\n\trm -f client.*"}
{"repo":"requests","file":"tests/certs/mtls/client/client.pem","line":1,"symbol":"CERTIFICATE","kind":"field","lang":"pem","code":"-----BEGIN CERTIFICATE-----"}
{"repo":"requests","file":"tests/certs/mtls/client/client.pem","line":23,"symbol":"CERTIFICATE","kind":"field","lang":"pem","code":"-----BEGIN CERTIFICATE-----"}
{"repo":"requests","file":"tests/certs/valid/server/Makefile","line":1,"symbol":".PHONY","kind":"target","lang":"make","code":".PHONY: all clean"}
{"repo":"requests","file":"tests/certs/valid/server/Makefile","line":3,"symbol":"server.key","kind":"target","lang":"make","code":"server.key:\n\topenssl genrsa -out $@ 2048"}
{"repo":"requests","file":"tests/certs/valid/server/Makefile","line":6,"symbol":"server.csr","kind":"target","lang":"make","code":"server.csr: server.key\n\topenssl req -key $< -config cert.cnf -new -out $@"}
{"repo":"requests","file":"tests/certs/valid/server/Makefile","line":9,"symbol":"server.pem","kind":"target","lang":"make","code":"server.pem: server.csr\n\topenssl x509 -req -CA ../ca/ca.crt -CAkey ../ca/ca-private.key -in server.csr -outform PEM -out server.pem -extfile cert.cnf -extensions v3_ca -days 7200 -CAcreateserial\n\topenssl x509 -in ../ca/ca.crt -outform PEM >> $@"}
{"repo":"requests","file":"tests/certs/valid/server/Makefile","line":13,"symbol":"all","kind":"target","lang":"make","code":"all: server.pem"}
{"repo":"requests","file":"tests/certs/valid/server/Makefile","line":15,"symbol":"clean","kind":"target","lang":"make","code":"clean:\n\trm -f server.*"}
{"repo":"requests","file":"tests/certs/valid/server/server.pem","line":1,"symbol":"CERTIFICATE","kind":"field","lang":"pem","code":"-----BEGIN CERTIFICATE-----"}
{"repo":"requests","file":"tests/certs/valid/server/server.pem","line":25,"symbol":"CERTIFICATE","kind":"field","lang":"pem","code":"-----BEGIN CERTIFICATE-----"}
{"repo":"requests","file":"tests/compat.py","line":14,"symbol":"u","kind":"function","lang":"python","code":"def u(s):\n warnings.warn(\n (\n \"This helper function is no longer relevant in Python 3. \"\n \"Usage of this alias should be discontinued as it will be \"\n \"removed in a future release of Requests.\"\n ),\n DeprecationWarning,\n )\n return s"}
{"repo":"requests","file":"tests/conftest.py","line":15,"symbol":"prepare_url","kind":"function","lang":"python","code":"def prepare_url(value):\n # Issue #1483: Make sure the URL always has a trailing slash\n httpbin_url = value.url.rstrip(\"/\") + \"/\"\n\n def inner(*suffix):\n return urljoin(httpbin_url, \"/\".join(suffix))\n\n return inner"}
{"repo":"requests","file":"tests/conftest.py","line":19,"symbol":"inner","kind":"function","lang":"python","code":"def inner(*suffix):\n return urljoin(httpbin_url, \"/\".join(suffix))"}
{"repo":"requests","file":"tests/conftest.py","line":26,"symbol":"clean_proxy_environ","kind":"function","lang":"python","code":"def clean_proxy_environ(monkeypatch):\n \"\"\"Remove proxy related environment variables for every test.\"\"\"\n proxy_vars = (\"http_proxy\", \"https_proxy\", \"no_proxy\", \"ftp_proxy\", \"all_proxy\")\n for var in proxy_vars:\n monkeypatch.delenv(var, raising=False)\n monkeypatch.delenv(var.upper(), raising=False)"}
{"repo":"requests","file":"tests/conftest.py","line":35,"symbol":"httpbin","kind":"function","lang":"python","code":"def httpbin(httpbin):\n return prepare_url(httpbin)"}
{"repo":"requests","file":"tests/conftest.py","line":40,"symbol":"httpbin_secure","kind":"function","lang":"python","code":"def httpbin_secure(httpbin_secure):\n return prepare_url(httpbin_secure)"}
{"repo":"requests","file":"tests/conftest.py","line":45,"symbol":"nosan_server","kind":"function","lang":"python","code":"def nosan_server(tmp_path_factory):\n # delay importing until the fixture in order to make it possible\n # to deselect the test via command-line when trustme is not available\n import trustme\n\n tmpdir = tmp_path_factory.mktemp(\"certs\")\n ca = trustme.CA()\n # only commonName, no subjectAltName\n server_cert = ca.issue_cert(common_name=\"localhost\")\n ca_bundle = str(tmpdir / \"ca.pem\")\n ca.cert_pem.write_to_path(ca_bundle)\n\n context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)\n server_cert.configure_cert(context)\n server = HTTPServer((\"localhost\", 0), SimpleHTTPRequestHandler)\n server.socket = context.wrap_socket(server.socket, server_side=True)\n server_thread = threading.Thread(target=server.serve_forever)\n server_thread.start()\n\n yield \"localhost\", server.server_address[1], ca_bundle\n\n server.shutdown()\n server_thread.join()"}
{"repo":"requests","file":"tests/test_adapters.py","line":4,"symbol":"test_request_url_handles_leading_path_separators","kind":"function","lang":"python","code":"def test_request_url_handles_leading_path_separators():\n \"\"\"See also https://github.com/psf/requests/issues/6643.\"\"\"\n a = requests.adapters.HTTPAdapter()\n p = requests.Request(method=\"GET\", url=\"http://127.0.0.1:10000//v:h\").prepare()\n assert \"//v:h\" == a.request_url(p, {})"}
{"repo":"requests","file":"tests/test_help.py","line":6,"symbol":"test_system_ssl","kind":"function","lang":"python","code":"def test_system_ssl():\n \"\"\"Verify we're actually setting system_ssl when it should be available.\"\"\"\n assert info()[\"system_ssl\"][\"version\"] != \"\""}
{"repo":"requests","file":"tests/test_help.py","line":11,"symbol":"VersionedPackage","kind":"class","lang":"python","code":"class VersionedPackage:\n def __init__(self, version):\n self.__version__ = version"}
{"repo":"requests","file":"tests/test_help.py","line":12,"symbol":"__init__","kind":"function","lang":"python","code":"def __init__(self, version):\n self.__version__ = version"}
{"repo":"requests","file":"tests/test_help.py","line":16,"symbol":"test_idna_without_version_attribute","kind":"function","lang":"python","code":"def test_idna_without_version_attribute():\n \"\"\"Older versions of IDNA don't provide a __version__ attribute, verify\n that if we have such a package, we don't blow up.\n \"\"\"\n with mock.patch(\"requests.help.idna\", new=None):\n assert info()[\"idna\"] == {\"version\": \"\"}"}
{"repo":"requests","file":"tests/test_help.py","line":24,"symbol":"test_idna_with_version_attribute","kind":"function","lang":"python","code":"def test_idna_with_version_attribute():\n \"\"\"Verify we're actually setting idna version when it should be available.\"\"\"\n with mock.patch(\"requests.help.idna\", new=VersionedPackage(\"2.6\")):\n assert info()[\"idna\"] == {\"version\": \"2.6\"}"}
{"repo":"requests","file":"tests/test_hooks.py","line":6,"symbol":"hook","kind":"function","lang":"python","code":"def hook(value):\n return value[1:]"}
{"repo":"requests","file":"tests/test_hooks.py","line":17,"symbol":"test_hooks","kind":"function","lang":"python","code":"def test_hooks(hooks_list, result):\n assert hooks.dispatch_hook(\"response\", {\"response\": hooks_list}, \"Data\") == result"}
{"repo":"requests","file":"tests/test_hooks.py","line":21,"symbol":"test_default_hooks","kind":"function","lang":"python","code":"def test_default_hooks():\n assert hooks.default_hooks() == {\"response\": []}"}
{"repo":"requests","file":"tests/test_lowlevel.py","line":12,"symbol":"echo_response_handler","kind":"function","lang":"python","code":"def echo_response_handler(sock):\n \"\"\"Simple handler that will take request and echo it back to requester.\"\"\"\n request_content = consume_socket_content(sock, timeout=0.5)\n\n text_200 = (\n b\"HTTP/1.1 200 OK\\r\\n\"\n b\"Content-Length: %d\\r\\n\\r\\n\"\n b\"%s\"\n ) % (len(request_content), request_content)\n sock.send(text_200)"}
{"repo":"requests","file":"tests/test_lowlevel.py","line":24,"symbol":"test_chunked_upload","kind":"function","lang":"python","code":"def test_chunked_upload():\n \"\"\"can safely send generators\"\"\"\n close_server = threading.Event()\n server = Server.basic_response_server(wait_to_close_event=close_server)\n data = iter([b\"a\", b\"b\", b\"c\"])\n\n with server as (host, port):\n url = f\"http://{host}:{port}/\"\n r = requests.post(url, data=data, stream=True)\n close_server.set() # release server block\n\n assert r.status_code == 200\n assert r.request.headers[\"Transfer-Encoding\"] == \"chunked\""}
{"repo":"requests","file":"tests/test_lowlevel.py","line":39,"symbol":"test_chunked_encoding_error","kind":"function","lang":"python","code":"def test_chunked_encoding_error():\n \"\"\"get a ChunkedEncodingError if the server returns a bad response\"\"\"\n\n def incomplete_chunked_response_handler(sock):\n request_content = consume_socket_content(sock, timeout=0.5)\n\n # The server never ends the request and doesn't provide any valid chunks\n sock.send(\n b\"HTTP/1.1 200 OK\\r\\n\"\n b\"Transfer-Encoding: chunked\\r\\n\"\n )\n\n return request_content\n\n close_server = threading.Event()\n server = Server(incomplete_chunked_response_handler)\n\n with server as (host, port):\n url = f\"http://{host}:{port}/\"\n with pytest.raises(requests.exceptions.ChunkedEncodingError):\n requests.get(url)\n close_server.set() # release server block"}
{"repo":"requests","file":"tests/test_lowlevel.py","line":42,"symbol":"incomplete_chunked_response_handler","kind":"function","lang":"python","code":"def incomplete_chunked_response_handler(sock):\n request_content = consume_socket_content(sock, timeout=0.5)\n\n # The server never ends the request and doesn't provide any valid chunks\n sock.send(\n b\"HTTP/1.1 200 OK\\r\\n\"\n b\"Transfer-Encoding: chunked\\r\\n\"\n )\n\n return request_content"}
{"repo":"requests","file":"tests/test_lowlevel.py","line":63,"symbol":"test_chunked_upload_uses_only_specified_host_header","kind":"function","lang":"python","code":"def test_chunked_upload_uses_only_specified_host_header():\n \"\"\"Ensure we use only the specified Host header for chunked requests.\"\"\"\n close_server = threading.Event()\n server = Server(echo_response_handler, wait_to_close_event=close_server)\n\n data = iter([b\"a\", b\"b\", b\"c\"])\n custom_host = \"sample-host\"\n\n with server as (host, port):\n url = f\"http://{host}:{port}/\"\n r = requests.post(url, data=data, headers={\"Host\": custom_host}, stream=True)\n close_server.set() # release server block\n\n expected_header = b\"Host: %s\\r\\n\" % custom_host.encode(\"utf-8\")\n assert expected_header in r.content\n assert r.content.count(b\"Host: \") == 1"}
{"repo":"requests","file":"tests/test_lowlevel.py","line":81,"symbol":"test_chunked_upload_doesnt_skip_host_header","kind":"function","lang":"python","code":"def test_chunked_upload_doesnt_skip_host_header():\n \"\"\"Ensure we don't omit all Host headers with chunked requests.\"\"\"\n close_server = threading.Event()\n server = Server(echo_response_handler, wait_to_close_event=close_server)\n\n data = iter([b\"a\", b\"b\", b\"c\"])\n\n with server as (host, port):\n expected_host = f\"{host}:{port}\"\n url = f\"http://{host}:{port}/\"\n r = requests.post(url, data=data, stream=True)\n close_server.set() # release server block\n\n expected_header = b\"Host: %s\\r\\n\" % expected_host.encode(\"utf-8\")\n assert expected_header in r.content\n assert r.content.count(b\"Host: \") == 1"}
{"repo":"requests","file":"tests/test_lowlevel.py","line":99,"symbol":"test_conflicting_content_lengths","kind":"function","lang":"python","code":"def test_conflicting_content_lengths():\n \"\"\"Ensure we correctly throw an InvalidHeader error if multiple\n conflicting Content-Length headers are returned.\n \"\"\"\n\n def multiple_content_length_response_handler(sock):\n request_content = consume_socket_content(sock, timeout=0.5)\n response = (\n b\"HTTP/1.1 200 OK\\r\\n\"\n b\"Content-Type: text/plain\\r\\n\"\n b\"Content-Length: 16\\r\\n\"\n b\"Content-Length: 32\\r\\n\\r\\n\"\n b\"-- Bad Actor -- Original Content\\r\\n\"\n )\n sock.send(response)\n\n return request_content\n\n close_server = threading.Event()\n server = Server(multiple_content_length_response_handler)\n\n with server as (host, port):\n url = f\"http://{host}:{port}/\"\n with pytest.raises(requests.exceptions.InvalidHeader):\n requests.get(url)\n close_server.set()"}
{"repo":"requests","file":"tests/test_lowlevel.py","line":104,"symbol":"multiple_content_length_response_handler","kind":"function","lang":"python","code":"def multiple_content_length_response_handler(sock):\n request_content = consume_socket_content(sock, timeout=0.5)\n response = (\n b\"HTTP/1.1 200 OK\\r\\n\"\n b\"Content-Type: text/plain\\r\\n\"\n b\"Content-Length: 16\\r\\n\"\n b\"Content-Length: 32\\r\\n\\r\\n\"\n b\"-- Bad Actor -- Original Content\\r\\n\"\n )\n sock.send(response)\n\n return request_content"}
{"repo":"requests","file":"tests/test_lowlevel.py","line":127,"symbol":"test_digestauth_401_count_reset_on_redirect","kind":"function","lang":"python","code":"def test_digestauth_401_count_reset_on_redirect():\n \"\"\"Ensure we correctly reset num_401_calls after a successful digest auth,\n followed by a 302 redirect to another digest auth prompt.\n\n See https://github.com/psf/requests/issues/1979.\n \"\"\"\n text_401 = (b'HTTP/1.1 401 UNAUTHORIZED\\r\\n'\n b'Content-Length: 0\\r\\n'\n b'WWW-Authenticate: Digest nonce=\"6bf5d6e4da1ce66918800195d6b9130d\"'\n b', opaque=\"372825293d1c26955496c80ed6426e9e\", '\n b'realm=\"me@kennethreitz.com\", qop=auth\\r\\n\\r\\n')\n\n text_302 = (b'HTTP/1.1 302 FOUND\\r\\n'\n b'Content-Length: 0\\r\\n'\n b'Location: /\\r\\n\\r\\n')\n\n text_200 = (b'HTTP/1.1 200 OK\\r\\n'\n b'Content-Length: 0\\r\\n\\r\\n')\n\n expected_digest = (b'Authorization: Digest username=\"user\", '\n b'realm=\"me@kennethreitz.com\", '\n b'nonce=\"6bf5d6e4da1ce66918800195d6b9130d\", uri=\"/\"')\n\n auth = requests.auth.HTTPDigestAuth('user', 'pass')\n\n def digest_response_handler(sock):\n # Respond to initial GET with a challenge.\n request_content = consume_socket_content(sock, timeout=0.5)\n assert"}
{"repo":"requests","file":"tests/test_lowlevel.py","line":152,"symbol":"digest_response_handler","kind":"function","lang":"python","code":"def digest_response_handler(sock):\n # Respond to initial GET with a challenge.\n request_content = consume_socket_content(sock, timeout=0.5)\n assert request_content.startswith(b\"GET / HTTP/1.1\")\n sock.send(text_401)\n\n # Verify we receive an Authorization header in response, then redirect.\n request_content = consume_socket_content(sock, timeout=0.5)\n assert expected_digest in request_content\n sock.send(text_302)\n\n # Verify Authorization isn't sent to the redirected host,\n # then send another challenge.\n request_content = consume_socket_content(sock, timeout=0.5)\n assert b'Authorization:' not in request_content\n sock.send(text_401)\n\n # Verify Authorization is sent correctly again, and return 200 OK.\n request_content = consume_socket_content(sock, timeout=0.5)\n assert expected_digest in request_content\n sock.send(text_200)\n\n return request_content"}
{"repo":"requests","file":"tests/test_lowlevel.py","line":192,"symbol":"test_digestauth_401_only_sent_once","kind":"function","lang":"python","code":"def test_digestauth_401_only_sent_once():\n \"\"\"Ensure we correctly respond to a 401 challenge once, and then\n stop responding if challenged again.\n \"\"\"\n text_401 = (b'HTTP/1.1 401 UNAUTHORIZED\\r\\n'\n b'Content-Length: 0\\r\\n'\n b'WWW-Authenticate: Digest nonce=\"6bf5d6e4da1ce66918800195d6b9130d\"'\n b', opaque=\"372825293d1c26955496c80ed6426e9e\", '\n b'realm=\"me@kennethreitz.com\", qop=auth\\r\\n\\r\\n')\n\n expected_digest = (b'Authorization: Digest username=\"user\", '\n b'realm=\"me@kennethreitz.com\", '\n b'nonce=\"6bf5d6e4da1ce66918800195d6b9130d\", uri=\"/\"')\n\n auth = requests.auth.HTTPDigestAuth('user', 'pass')\n\n def digest_failed_response_handler(sock):\n # Respond to initial GET with a challenge.\n request_content = consume_socket_content(sock, timeout=0.5)\n assert request_content.startswith(b\"GET / HTTP/1.1\")\n sock.send(text_401)\n\n # Verify we receive an Authorization header in response, then\n # challenge again.\n request_content = consume_socket_content(sock, timeout=0.5)\n assert expected_digest in request_content\n "}
{"repo":"requests","file":"tests/test_lowlevel.py","line":208,"symbol":"digest_failed_response_handler","kind":"function","lang":"python","code":"def digest_failed_response_handler(sock):\n # Respond to initial GET with a challenge.\n request_content = consume_socket_content(sock, timeout=0.5)\n assert request_content.startswith(b\"GET / HTTP/1.1\")\n sock.send(text_401)\n\n # Verify we receive an Authorization header in response, then\n # challenge again.\n request_content = consume_socket_content(sock, timeout=0.5)\n assert expected_digest in request_content\n sock.send(text_401)\n\n # Verify the client didn't respond to second challenge.\n request_content = consume_socket_content(sock, timeout=0.5)\n assert request_content == b''\n\n return request_content"}
{"repo":"requests","file":"tests/test_lowlevel.py","line":238,"symbol":"test_digestauth_only_on_4xx","kind":"function","lang":"python","code":"def test_digestauth_only_on_4xx():\n \"\"\"Ensure we only send digestauth on 4xx challenges.\n\n See https://github.com/psf/requests/issues/3772.\n \"\"\"\n text_200_chal = (b'HTTP/1.1 200 OK\\r\\n'\n b'Content-Length: 0\\r\\n'\n b'WWW-Authenticate: Digest nonce=\"6bf5d6e4da1ce66918800195d6b9130d\"'\n b', opaque=\"372825293d1c26955496c80ed6426e9e\", '\n b'realm=\"me@kennethreitz.com\", qop=auth\\r\\n\\r\\n')\n\n auth = requests.auth.HTTPDigestAuth('user', 'pass')\n\n def digest_response_handler(sock):\n # Respond to GET with a 200 containing www-authenticate header.\n request_content = consume_socket_content(sock, timeout=0.5)\n assert request_content.startswith(b\"GET / HTTP/1.1\")\n sock.send(text_200_chal)\n\n # Verify the client didn't respond with auth.\n request_content = consume_socket_content(sock, timeout=0.5)\n assert request_content == b''\n\n return request_content\n\n close_server = threading.Event()\n server = Server(digest_response_handler, wait_to_close_event=close_server)\n\n with server as (host, port):\n url = f'http://{host}:{port}/'\n r ="}
{"repo":"requests","file":"tests/test_lowlevel.py","line":251,"symbol":"digest_response_handler","kind":"function","lang":"python","code":"def digest_response_handler(sock):\n # Respond to GET with a 200 containing www-authenticate header.\n request_content = consume_socket_content(sock, timeout=0.5)\n assert request_content.startswith(b\"GET / HTTP/1.1\")\n sock.send(text_200_chal)\n\n # Verify the client didn't respond with auth.\n request_content = consume_socket_content(sock, timeout=0.5)\n assert request_content == b''\n\n return request_content"}
{"repo":"requests","file":"tests/test_lowlevel.py","line":290,"symbol":"test_use_proxy_from_environment","kind":"function","lang":"python","code":"def test_use_proxy_from_environment(httpbin, var, scheme):\n url = f\"{scheme}://httpbin.org\"\n fake_proxy = Server() # do nothing with the requests; just close the socket\n with fake_proxy as (host, port):\n proxy_url = f\"socks5://{host}:{port}\"\n kwargs = {var: proxy_url}\n with override_environ(**kwargs):\n # fake proxy's lack of response will cause a ConnectionError\n with pytest.raises(requests.exceptions.ConnectionError):\n requests.get(url)\n\n # the fake proxy received a request\n assert len(fake_proxy.handler_results) == 1\n\n # it had actual content (not checking for SOCKS protocol for now)\n assert len(fake_proxy.handler_results[0]) > 0"}
{"repo":"requests","file":"tests/test_lowlevel.py","line":308,"symbol":"test_redirect_rfc1808_to_non_ascii_location","kind":"function","lang":"python","code":"def test_redirect_rfc1808_to_non_ascii_location():\n path = 'š'\n expected_path = b'%C5%A1'\n redirect_request = [] # stores the second request to the server\n\n def redirect_resp_handler(sock):\n consume_socket_content(sock, timeout=0.5)\n location = f'//{host}:{port}/{path}'\n sock.send(\n (\n b'HTTP/1.1 301 Moved Permanently\\r\\n'\n b'Content-Length: 0\\r\\n'\n b'Location: %s\\r\\n'\n b'\\r\\n'\n ) % location.encode('utf8')\n )\n redirect_request.append(consume_socket_content(sock, timeout=0.5))\n sock.send(b'HTTP/1.1 200 OK\\r\\n\\r\\n')\n\n close_server = threading.Event()\n server = Server(redirect_resp_handler, wait_to_close_event=close_server)\n\n with server as (host, port):\n url = f'http://{host}:{port}'\n r = requests.get(url=url, allow_redirects=True)\n assert r.status_code == 200\n assert len(r.history) == 1\n assert r.history[0].status_code == 301\n assert redirect_request[0].startswith(b'GET /' + expected_path + b' HTTP/1.1')\n assert r.url == '{}/{}'.format(url, expected_path.decode('ascii'))\n\n close_serve"}
{"repo":"requests","file":"tests/test_lowlevel.py","line":313,"symbol":"redirect_resp_handler","kind":"function","lang":"python","code":"def redirect_resp_handler(sock):\n consume_socket_content(sock, timeout=0.5)\n location = f'//{host}:{port}/{path}'\n sock.send(\n (\n b'HTTP/1.1 301 Moved Permanently\\r\\n'\n b'Content-Length: 0\\r\\n'\n b'Location: %s\\r\\n'\n b'\\r\\n'\n ) % location.encode('utf8')\n )\n redirect_request.append(consume_socket_content(sock, timeout=0.5))\n sock.send(b'HTTP/1.1 200 OK\\r\\n\\r\\n')"}
{"repo":"requests","file":"tests/test_lowlevel.py","line":342,"symbol":"test_fragment_not_sent_with_request","kind":"function","lang":"python","code":"def test_fragment_not_sent_with_request():\n \"\"\"Verify that the fragment portion of a URI isn't sent to the server.\"\"\"\n close_server = threading.Event()\n server = Server(echo_response_handler, wait_to_close_event=close_server)\n\n with server as (host, port):\n url = f'http://{host}:{port}/path/to/thing/#view=edit&token=hunter2'\n r = requests.get(url)\n raw_request = r.content\n\n assert r.status_code == 200\n headers, body = raw_request.split(b'\\r\\n\\r\\n', 1)\n status_line, headers = headers.split(b'\\r\\n', 1)\n\n assert status_line == b'GET /path/to/thing/ HTTP/1.1'\n for frag in (b'view', b'edit', b'token', b'hunter2'):\n assert frag not in headers\n assert frag not in body\n\n close_server.set()"}
{"repo":"requests","file":"tests/test_lowlevel.py","line":364,"symbol":"test_fragment_update_on_redirect","kind":"function","lang":"python","code":"def test_fragment_update_on_redirect():\n \"\"\"Verify we only append previous fragment if one doesn't exist on new\n location. If a new fragment is encountered in a Location header, it should\n be added to all subsequent requests.\n \"\"\"\n\n def response_handler(sock):\n consume_socket_content(sock, timeout=0.5)\n sock.send(\n b'HTTP/1.1 302 FOUND\\r\\n'\n b'Content-Length: 0\\r\\n'\n b'Location: /get#relevant-section\\r\\n\\r\\n'\n )\n consume_socket_content(sock, timeout=0.5)\n sock.send(\n b'HTTP/1.1 302 FOUND\\r\\n'\n b'Content-Length: 0\\r\\n'\n b'Location: /final-url/\\r\\n\\r\\n'\n )\n consume_socket_content(sock, timeout=0.5)\n sock.send(\n b'HTTP/1.1 200 OK\\r\\n\\r\\n'\n )\n\n close_server = threading.Event()\n server = Server(response_handler, wait_to_close_event=close_server)\n\n with server as (host, port):\n url = f'http://{host}:{port}/path/to/thing/#view=edit&token=hunter2'\n r = requests.get(url)\n\n assert r.status_code == 200\n assert len(r.history) == 2\n assert r.history[0].request.url == url\n\n # Verify we haven't"}
{"repo":"requests","file":"tests/test_lowlevel.py","line":370,"symbol":"response_handler","kind":"function","lang":"python","code":"def response_handler(sock):\n consume_socket_content(sock, timeout=0.5)\n sock.send(\n b'HTTP/1.1 302 FOUND\\r\\n'\n b'Content-Length: 0\\r\\n'\n b'Location: /get#relevant-section\\r\\n\\r\\n'\n )\n consume_socket_content(sock, timeout=0.5)\n sock.send(\n b'HTTP/1.1 302 FOUND\\r\\n'\n b'Content-Length: 0\\r\\n'\n b'Location: /final-url/\\r\\n\\r\\n'\n )\n consume_socket_content(sock, timeout=0.5)\n sock.send(\n b'HTTP/1.1 200 OK\\r\\n\\r\\n'\n )"}
{"repo":"requests","file":"tests/test_lowlevel.py","line":407,"symbol":"test_json_decode_compatibility_for_alt_utf_encodings","kind":"function","lang":"python","code":"def test_json_decode_compatibility_for_alt_utf_encodings():\n\n def response_handler(sock):\n consume_socket_content(sock, timeout=0.5)\n sock.send(\n b'HTTP/1.1 200 OK\\r\\n'\n b'Content-Length: 18\\r\\n\\r\\n'\n b'\\xff\\xfe{\\x00\"\\x00K0\"\\x00=\\x00\"\\x00\\xab0\"\\x00\\r\\n'\n )\n\n close_server = threading.Event()\n server = Server(response_handler, wait_to_close_event=close_server)\n\n with server as (host, port):\n url = f'http://{host}:{port}/'\n r = requests.get(url)\n r.encoding = None\n with pytest.raises(requests.exceptions.JSONDecodeError) as excinfo:\n r.json()\n assert isinstance(excinfo.value, requests.exceptions.RequestException)\n assert isinstance(excinfo.value, JSONDecodeError)\n assert r.text not in str(excinfo.value)"}
{"repo":"requests","file":"tests/test_lowlevel.py","line":409,"symbol":"response_handler","kind":"function","lang":"python","code":"def response_handler(sock):\n consume_socket_content(sock, timeout=0.5)\n sock.send(\n b'HTTP/1.1 200 OK\\r\\n'\n b'Content-Length: 18\\r\\n\\r\\n'\n b'\\xff\\xfe{\\x00\"\\x00K0\"\\x00=\\x00\"\\x00\\xab0\"\\x00\\r\\n'\n )"}
{"repo":"requests","file":"tests/test_packages.py","line":4,"symbol":"test_can_access_urllib3_attribute","kind":"function","lang":"python","code":"def test_can_access_urllib3_attribute():\n requests.packages.urllib3"}
{"repo":"requests","file":"tests/test_packages.py","line":8,"symbol":"test_can_access_idna_attribute","kind":"function","lang":"python","code":"def test_can_access_idna_attribute():\n requests.packages.idna"}
{"repo":"requests","file":"tests/test_packages.py","line":12,"symbol":"test_can_access_chardet_attribute","kind":"function","lang":"python","code":"def test_can_access_chardet_attribute():\n requests.packages.chardet"}
{"repo":"requests","file":"tests/test_requests.py","line":84,"symbol":"TestRequests","kind":"class","lang":"python","code":"class TestRequests:\n digest_auth_algo = (\"MD5\", \"SHA-256\", \"SHA-512\")\n\n def test_entry_points(self):\n requests.session\n requests.session().get\n requests.session().head\n requests.get\n requests.head\n requests.put\n requests.patch\n requests.post\n # Not really an entry point, but people rely on it.\n from requests.packages.urllib3.poolmanager import PoolManager # noqa:F401\n\n @pytest.mark.parametrize(\n \"exception, url\",\n (\n (MissingSchema, \"hiwpefhipowhefopw\"),\n (InvalidSchema, \"localhost:3128\"),\n (InvalidSchema, \"localhost.localdomain:3128/\"),\n (InvalidSchema, \"10.122.1.1:3128/\"),\n (InvalidURL, \"http://\"),\n (InvalidURL, \"http://*example.com\"),\n (InvalidURL, \"http://.example.com\"),\n ),\n )\n def test_invalid_url(self, exception, url):\n with pytest.raises(exception):\n requests.get(url)\n\n def test_basic_building(self):\n req = requests.Request()\n req.url = \"http://kennethreitz.org/\"\n req.data = {\"life\": \"42\"}\n\n pr = req.prepare()\n assert pr.url == req.url\n "}
{"repo":"requests","file":"tests/test_requests.py","line":87,"symbol":"test_entry_points","kind":"function","lang":"python","code":"def test_entry_points(self):\n requests.session\n requests.session().get\n requests.session().head\n requests.get\n requests.head\n requests.put\n requests.patch\n requests.post\n # Not really an entry point, but people rely on it.\n from requests.packages.urllib3.poolmanager import PoolManager # noqa:F401"}
{"repo":"requests","file":"tests/test_requests.py","line":111,"symbol":"test_invalid_url","kind":"function","lang":"python","code":"def test_invalid_url(self, exception, url):\n with pytest.raises(exception):\n requests.get(url)"}
{"repo":"requests","file":"tests/test_requests.py","line":115,"symbol":"test_basic_building","kind":"function","lang":"python","code":"def test_basic_building(self):\n req = requests.Request()\n req.url = \"http://kennethreitz.org/\"\n req.data = {\"life\": \"42\"}\n\n pr = req.prepare()\n assert pr.url == req.url\n assert pr.body == \"life=42\""}
{"repo":"requests","file":"tests/test_requests.py","line":125,"symbol":"test_no_content_length","kind":"function","lang":"python","code":"def test_no_content_length(self, httpbin, method):\n req = requests.Request(method, httpbin(method.lower())).prepare()\n assert \"Content-Length\" not in req.headers"}
{"repo":"requests","file":"tests/test_requests.py","line":130,"symbol":"test_no_body_content_length","kind":"function","lang":"python","code":"def test_no_body_content_length(self, httpbin, method):\n req = requests.Request(method, httpbin(method.lower())).prepare()\n assert req.headers[\"Content-Length\"] == \"0\""}
{"repo":"requests","file":"tests/test_requests.py","line":135,"symbol":"test_empty_content_length","kind":"function","lang":"python","code":"def test_empty_content_length(self, httpbin, method):\n req = requests.Request(method, httpbin(method.lower()), data=\"\").prepare()\n assert req.headers[\"Content-Length\"] == \"0\""}
{"repo":"requests","file":"tests/test_requests.py","line":139,"symbol":"test_override_content_length","kind":"function","lang":"python","code":"def test_override_content_length(self, httpbin):\n headers = {\"Content-Length\": \"not zero\"}\n r = requests.Request(\"POST\", httpbin(\"post\"), headers=headers).prepare()\n assert \"Content-Length\" in r.headers\n assert r.headers[\"Content-Length\"] == \"not zero\""}
{"repo":"requests","file":"tests/test_requests.py","line":145,"symbol":"test_path_is_not_double_encoded","kind":"function","lang":"python","code":"def test_path_is_not_double_encoded(self):\n request = requests.Request(\"GET\", \"http://0.0.0.0/get/test case\").prepare()\n\n assert request.path_url == \"/get/test%20case\""}
{"repo":"requests","file":"tests/test_requests.py","line":163,"symbol":"test_params_are_added_before_fragment","kind":"function","lang":"python","code":"def test_params_are_added_before_fragment(self, url, expected):\n request = requests.Request(\"GET\", url, params={\"a\": \"b\"}).prepare()\n assert request.url == expected"}
{"repo":"requests","file":"tests/test_requests.py","line":167,"symbol":"test_params_original_order_is_preserved_by_default","kind":"function","lang":"python","code":"def test_params_original_order_is_preserved_by_default(self):\n param_ordered_dict = collections.OrderedDict(\n ((\"z\", 1), (\"a\", 1), (\"k\", 1), (\"d\", 1))\n )\n session = requests.Session()\n request = requests.Request(\n \"GET\", \"http://example.com/\", params=param_ordered_dict\n )\n prep = session.prepare_request(request)\n assert prep.url == \"http://example.com/?z=1&a=1&k=1&d=1\""}
{"repo":"requests","file":"tests/test_requests.py","line":178,"symbol":"test_params_bytes_are_encoded","kind":"function","lang":"python","code":"def test_params_bytes_are_encoded(self):\n request = requests.Request(\n \"GET\", \"http://example.com\", params=b\"test=foo\"\n ).prepare()\n assert request.url == \"http://example.com/?test=foo\""}
{"repo":"requests","file":"tests/test_requests.py","line":184,"symbol":"test_binary_put","kind":"function","lang":"python","code":"def test_binary_put(self):\n request = requests.Request(\n \"PUT\", \"http://example.com\", data=\"ööö\".encode()\n ).prepare()\n assert isinstance(request.body, bytes)"}
{"repo":"requests","file":"tests/test_requests.py","line":190,"symbol":"test_whitespaces_are_removed_from_url","kind":"function","lang":"python","code":"def test_whitespaces_are_removed_from_url(self):\n # Test for issue #3696\n request = requests.Request(\"GET\", \" http://example.com\").prepare()\n assert request.url == \"http://example.com/\""}
{"repo":"requests","file":"tests/test_requests.py","line":196,"symbol":"test_mixed_case_scheme_acceptable","kind":"function","lang":"python","code":"def test_mixed_case_scheme_acceptable(self, httpbin, scheme):\n s = requests.Session()\n s.proxies = getproxies()\n parts = urlparse(httpbin(\"get\"))\n url = scheme + parts.netloc + parts.path\n r = requests.Request(\"GET\", url)\n r = s.send(r.prepare())\n assert r.status_code == 200, f\"failed for scheme {scheme}\""}
{"repo":"requests","file":"tests/test_requests.py","line":205,"symbol":"test_HTTP_200_OK_GET_ALTERNATIVE","kind":"function","lang":"python","code":"def test_HTTP_200_OK_GET_ALTERNATIVE(self, httpbin):\n r = requests.Request(\"GET\", httpbin(\"get\"))\n s = requests.Session()\n s.proxies = getproxies()\n\n r = s.send(r.prepare())\n\n assert r.status_code == 200"}
{"repo":"requests","file":"tests/test_requests.py","line":214,"symbol":"test_HTTP_302_ALLOW_REDIRECT_GET","kind":"function","lang":"python","code":"def test_HTTP_302_ALLOW_REDIRECT_GET(self, httpbin):\n r = requests.get(httpbin(\"redirect\", \"1\"))\n assert r.status_code == 200\n assert r.history[0].status_code == 302\n assert r.history[0].is_redirect"}
{"repo":"requests","file":"tests/test_requests.py","line":220,"symbol":"test_redirect_history_no_self_reference","kind":"function","lang":"python","code":"def test_redirect_history_no_self_reference(self, httpbin):\n r = requests.get(httpbin(\"redirect\", \"3\"))\n assert r.status_code == 200\n assert len(r.history) == 3\n for i, resp in enumerate(r.history):\n assert resp not in resp.history\n assert resp.history == r.history[:i]"}
{"repo":"requests","file":"tests/test_requests.py","line":228,"symbol":"test_HTTP_307_ALLOW_REDIRECT_POST","kind":"function","lang":"python","code":"def test_HTTP_307_ALLOW_REDIRECT_POST(self, httpbin):\n r = requests.post(\n httpbin(\"redirect-to\"),\n data=\"test\",\n params={\"url\": \"post\", \"status_code\": 307},\n )\n assert r.status_code == 200\n assert r.history[0].status_code == 307\n assert r.history[0].is_redirect\n assert r.json()[\"data\"] == \"test\""}
{"repo":"requests","file":"tests/test_requests.py","line":239,"symbol":"test_HTTP_307_ALLOW_REDIRECT_POST_WITH_SEEKABLE","kind":"function","lang":"python","code":"def test_HTTP_307_ALLOW_REDIRECT_POST_WITH_SEEKABLE(self, httpbin):\n byte_str = b\"test\"\n r = requests.post(\n httpbin(\"redirect-to\"),\n data=io.BytesIO(byte_str),\n params={\"url\": \"post\", \"status_code\": 307},\n )\n assert r.status_code == 200\n assert r.history[0].status_code == 307\n assert r.history[0].is_redirect\n assert r.json()[\"data\"] == byte_str.decode(\"utf-8\")"}
{"repo":"requests","file":"tests/test_requests.py","line":251,"symbol":"test_HTTP_302_TOO_MANY_REDIRECTS","kind":"function","lang":"python","code":"def test_HTTP_302_TOO_MANY_REDIRECTS(self, httpbin):\n try:\n requests.get(httpbin(\"relative-redirect\", \"50\"))\n except TooManyRedirects as e:\n url = httpbin(\"relative-redirect\", \"20\")\n assert e.request.url == url\n assert e.response.url == url\n assert len(e.response.history) == 30\n else:\n pytest.fail(\"Expected redirect to raise TooManyRedirects but it did not\")"}
{"repo":"requests","file":"tests/test_requests.py","line":262,"symbol":"test_HTTP_302_TOO_MANY_REDIRECTS_WITH_PARAMS","kind":"function","lang":"python","code":"def test_HTTP_302_TOO_MANY_REDIRECTS_WITH_PARAMS(self, httpbin):\n s = requests.session()\n s.max_redirects = 5\n try:\n s.get(httpbin(\"relative-redirect\", \"50\"))\n except TooManyRedirects as e:\n url = httpbin(\"relative-redirect\", \"45\")\n assert e.request.url == url\n assert e.response.url == url\n assert len(e.response.history) == 5\n else:\n pytest.fail(\n \"Expected custom max number of redirects to be respected but was not\"\n )"}
{"repo":"requests","file":"tests/test_requests.py","line":277,"symbol":"test_http_301_changes_post_to_get","kind":"function","lang":"python","code":"def test_http_301_changes_post_to_get(self, httpbin):\n r = requests.post(httpbin(\"status\", \"301\"))\n assert r.status_code == 200\n assert r.request.method == \"GET\"\n assert r.history[0].status_code == 301\n assert r.history[0].is_redirect"}
{"repo":"requests","file":"tests/test_requests.py","line":284,"symbol":"test_http_301_doesnt_change_head_to_get","kind":"function","lang":"python","code":"def test_http_301_doesnt_change_head_to_get(self, httpbin):\n r = requests.head(httpbin(\"status\", \"301\"), allow_redirects=True)\n print(r.content)\n assert r.status_code == 200\n assert r.request.method == \"HEAD\"\n assert r.history[0].status_code == 301\n assert r.history[0].is_redirect"}
{"repo":"requests","file":"tests/test_requests.py","line":292,"symbol":"test_http_302_changes_post_to_get","kind":"function","lang":"python","code":"def test_http_302_changes_post_to_get(self, httpbin):\n r = requests.post(httpbin(\"status\", \"302\"))\n assert r.status_code == 200\n assert r.request.method == \"GET\"\n assert r.history[0].status_code == 302\n assert r.history[0].is_redirect"}
{"repo":"requests","file":"tests/test_requests.py","line":299,"symbol":"test_http_302_doesnt_change_head_to_get","kind":"function","lang":"python","code":"def test_http_302_doesnt_change_head_to_get(self, httpbin):\n r = requests.head(httpbin(\"status\", \"302\"), allow_redirects=True)\n assert r.status_code == 200\n assert r.request.method == \"HEAD\"\n assert r.history[0].status_code == 302\n assert r.history[0].is_redirect"}
{"repo":"requests","file":"tests/test_requests.py","line":306,"symbol":"test_http_303_changes_post_to_get","kind":"function","lang":"python","code":"def test_http_303_changes_post_to_get(self, httpbin):\n r = requests.post(httpbin(\"status\", \"303\"))\n assert r.status_code == 200\n assert r.request.method == \"GET\"\n assert r.history[0].status_code == 303\n assert r.history[0].is_redirect"}
{"repo":"requests","file":"tests/test_requests.py","line":313,"symbol":"test_http_303_doesnt_change_head_to_get","kind":"function","lang":"python","code":"def test_http_303_doesnt_change_head_to_get(self, httpbin):\n r = requests.head(httpbin(\"status\", \"303\"), allow_redirects=True)\n assert r.status_code == 200\n assert r.request.method == \"HEAD\"\n assert r.history[0].status_code == 303\n assert r.history[0].is_redirect"}
{"repo":"requests","file":"tests/test_requests.py","line":320,"symbol":"test_header_and_body_removal_on_redirect","kind":"function","lang":"python","code":"def test_header_and_body_removal_on_redirect(self, httpbin):\n purged_headers = (\"Content-Length\", \"Content-Type\")\n ses = requests.Session()\n req = requests.Request(\"POST\", httpbin(\"post\"), data={\"test\": \"data\"})\n prep = ses.prepare_request(req)\n resp = ses.send(prep)\n\n # Mimic a redirect response\n resp.status_code = 302\n resp.headers[\"location\"] = \"get\"\n\n # Run request through resolve_redirects\n next_resp = next(ses.resolve_redirects(resp, prep))\n assert next_resp.request.body is None\n for header in purged_headers:\n assert header not in next_resp.request.headers"}
{"repo":"requests","file":"tests/test_requests.py","line":337,"symbol":"test_transfer_enc_removal_on_redirect","kind":"function","lang":"python","code":"def test_transfer_enc_removal_on_redirect(self, httpbin):\n purged_headers = (\"Transfer-Encoding\", \"Content-Type\")\n ses = requests.Session()\n req = requests.Request(\"POST\", httpbin(\"post\"), data=(b\"x\" for x in range(1)))\n prep = ses.prepare_request(req)\n assert \"Transfer-Encoding\" in prep.headers\n\n # Create Response to avoid https://github.com/kevin1024/pytest-httpbin/issues/33\n resp = requests.Response()\n resp.raw = io.BytesIO(b\"the content\")\n resp.request = prep\n setattr(resp.raw, \"release_conn\", lambda *args: args)\n\n # Mimic a redirect response\n resp.status_code = 302\n resp.headers[\"location\"] = httpbin(\"get\")\n\n # Run request through resolve_redirect\n next_resp = next(ses.resolve_redirects(resp, prep))\n assert next_resp.request.body is None\n for header in purged_headers:\n assert header not in next_resp.request.headers"}
{"repo":"requests","file":"tests/test_requests.py","line":360,"symbol":"test_fragment_maintained_on_redirect","kind":"function","lang":"python","code":"def test_fragment_maintained_on_redirect(self, httpbin):\n fragment = \"#view=edit&token=hunter2\"\n r = requests.get(httpbin(\"redirect-to?url=get\") + fragment)\n\n assert len(r.history) > 0\n assert r.history[0].request.url == httpbin(\"redirect-to?url=get\") + fragment\n assert r.url == httpbin(\"get\") + fragment"}
{"repo":"requests","file":"tests/test_requests.py","line":368,"symbol":"test_HTTP_200_OK_GET_WITH_PARAMS","kind":"function","lang":"python","code":"def test_HTTP_200_OK_GET_WITH_PARAMS(self, httpbin):\n heads = {\"User-agent\": \"Mozilla/5.0\"}\n\n r = requests.get(httpbin(\"user-agent\"), headers=heads)\n\n assert heads[\"User-agent\"] in r.text\n assert r.status_code == 200"}
{"repo":"requests","file":"tests/test_requests.py","line":376,"symbol":"test_HTTP_200_OK_GET_WITH_MIXED_PARAMS","kind":"function","lang":"python","code":"def test_HTTP_200_OK_GET_WITH_MIXED_PARAMS(self, httpbin):\n heads = {\"User-agent\": \"Mozilla/5.0\"}\n\n r = requests.get(\n httpbin(\"get\") + \"?test=true\", params={\"q\": \"test\"}, headers=heads\n )\n assert r.status_code == 200"}
{"repo":"requests","file":"tests/test_requests.py","line":384,"symbol":"test_set_cookie_on_301","kind":"function","lang":"python","code":"def test_set_cookie_on_301(self, httpbin):\n s = requests.session()\n url = httpbin(\"cookies/set?foo=bar\")\n s.get(url)\n assert s.cookies[\"foo\"] == \"bar\""}
{"repo":"requests","file":"tests/test_requests.py","line":390,"symbol":"test_cookie_sent_on_redirect","kind":"function","lang":"python","code":"def test_cookie_sent_on_redirect(self, httpbin):\n s = requests.session()\n s.get(httpbin(\"cookies/set?foo=bar\"))\n r = s.get(httpbin(\"redirect/1\")) # redirects to httpbin('get')\n assert \"Cookie\" in r.json()[\"headers\"]"}
{"repo":"requests","file":"tests/test_requests.py","line":396,"symbol":"test_cookie_removed_on_expire","kind":"function","lang":"python","code":"def test_cookie_removed_on_expire(self, httpbin):\n s = requests.session()\n s.get(httpbin(\"cookies/set?foo=bar\"))\n assert s.cookies[\"foo\"] == \"bar\"\n s.get(\n httpbin(\"response-headers\"),\n params={\"Set-Cookie\": \"foo=deleted; expires=Thu, 01-Jan-1970 00:00:01 GMT\"},\n )\n assert \"foo\" not in s.cookies"}
{"repo":"requests","file":"tests/test_requests.py","line":406,"symbol":"test_cookie_quote_wrapped","kind":"function","lang":"python","code":"def test_cookie_quote_wrapped(self, httpbin):\n s = requests.session()\n s.get(httpbin('cookies/set?foo=\"bar:baz\"'))\n assert s.cookies[\"foo\"] == '\"bar:baz\"'"}
{"repo":"requests","file":"tests/test_requests.py","line":411,"symbol":"test_cookie_persists_via_api","kind":"function","lang":"python","code":"def test_cookie_persists_via_api(self, httpbin):\n s = requests.session()\n r = s.get(httpbin(\"redirect/1\"), cookies={\"foo\": \"bar\"})\n assert \"foo\" in r.request.headers[\"Cookie\"]\n assert \"foo\" in r.history[0].request.headers[\"Cookie\"]"}
{"repo":"requests","file":"tests/test_requests.py","line":417,"symbol":"test_request_cookie_overrides_session_cookie","kind":"function","lang":"python","code":"def test_request_cookie_overrides_session_cookie(self, httpbin):\n s = requests.session()\n s.cookies[\"foo\"] = \"bar\"\n r = s.get(httpbin(\"cookies\"), cookies={\"foo\": \"baz\"})\n assert r.json()[\"cookies\"][\"foo\"] == \"baz\"\n # Session cookie should not be modified\n assert s.cookies[\"foo\"] == \"bar\""}
{"repo":"requests","file":"tests/test_requests.py","line":425,"symbol":"test_request_cookies_not_persisted","kind":"function","lang":"python","code":"def test_request_cookies_not_persisted(self, httpbin):\n s = requests.session()\n s.get(httpbin(\"cookies\"), cookies={\"foo\": \"baz\"})\n # Sending a request with cookies should not add cookies to the session\n assert not s.cookies"}
{"repo":"requests","file":"tests/test_requests.py","line":431,"symbol":"test_generic_cookiejar_works","kind":"function","lang":"python","code":"def test_generic_cookiejar_works(self, httpbin):\n cj = cookielib.CookieJar()\n cookiejar_from_dict({\"foo\": \"bar\"}, cj)\n s = requests.session()\n s.cookies = cj\n r = s.get(httpbin(\"cookies\"))\n # Make sure the cookie was sent\n assert r.json()[\"cookies\"][\"foo\"] == \"bar\"\n # Make sure the session cj is still the custom one\n assert s.cookies is cj"}
{"repo":"requests","file":"tests/test_requests.py","line":442,"symbol":"test_param_cookiejar_works","kind":"function","lang":"python","code":"def test_param_cookiejar_works(self, httpbin):\n cj = cookielib.CookieJar()\n cookiejar_from_dict({\"foo\": \"bar\"}, cj)\n s = requests.session()\n r = s.get(httpbin(\"cookies\"), cookies=cj)\n # Make sure the cookie was sent\n assert r.json()[\"cookies\"][\"foo\"] == \"bar\""}
{"repo":"requests","file":"tests/test_requests.py","line":450,"symbol":"test_cookielib_cookiejar_on_redirect","kind":"function","lang":"python","code":"def test_cookielib_cookiejar_on_redirect(self, httpbin):\n \"\"\"Tests resolve_redirect doesn't fail when merging cookies\n with non-RequestsCookieJar cookiejar.\n\n See GH #3579\n \"\"\"\n cj = cookiejar_from_dict({\"foo\": \"bar\"}, cookielib.CookieJar())\n s = requests.Session()\n s.cookies = cookiejar_from_dict({\"cookie\": \"tasty\"})\n\n # Prepare request without using Session\n req = requests.Request(\"GET\", httpbin(\"headers\"), cookies=cj)\n prep_req = req.prepare()\n\n # Send request and simulate redirect\n resp = s.send(prep_req)\n resp.status_code = 302\n resp.headers[\"location\"] = httpbin(\"get\")\n redirects = s.resolve_redirects(resp, prep_req)\n resp = next(redirects)\n\n # Verify CookieJar isn't being converted to RequestsCookieJar\n assert isinstance(prep_req._cookies, cookielib.CookieJar)\n assert isinstance(resp.request._cookies, cookielib.CookieJar)\n assert not isinstance(resp.request._cookies, requests.cookies.RequestsCookieJar)\n\n cookies = {}\n for c in resp.request._cookies:\n cookies[c.name] = c.value\n assert cookies[\"foo\"] == \"bar"}
{"repo":"requests","file":"tests/test_requests.py","line":482,"symbol":"test_requests_in_history_are_not_overridden","kind":"function","lang":"python","code":"def test_requests_in_history_are_not_overridden(self, httpbin):\n resp = requests.get(httpbin(\"redirect/3\"))\n urls = [r.url for r in resp.history]\n req_urls = [r.request.url for r in resp.history]\n assert urls == req_urls"}
{"repo":"requests","file":"tests/test_requests.py","line":488,"symbol":"test_history_is_always_a_list","kind":"function","lang":"python","code":"def test_history_is_always_a_list(self, httpbin):\n \"\"\"Show that even with redirects, Response.history is always a list.\"\"\"\n resp = requests.get(httpbin(\"get\"))\n assert isinstance(resp.history, list)\n resp = requests.get(httpbin(\"redirect/1\"))\n assert isinstance(resp.history, list)\n assert not isinstance(resp.history, tuple)"}
{"repo":"requests","file":"tests/test_requests.py","line":496,"symbol":"test_headers_on_session_with_None_are_not_sent","kind":"function","lang":"python","code":"def test_headers_on_session_with_None_are_not_sent(self, httpbin):\n \"\"\"Do not send headers in Session.headers with None values.\"\"\"\n ses = requests.Session()\n ses.headers[\"Accept-Encoding\"] = None\n req = requests.Request(\"GET\", httpbin(\"get\"))\n prep = ses.prepare_request(req)\n assert \"Accept-Encoding\" not in prep.headers"}
{"repo":"requests","file":"tests/test_requests.py","line":504,"symbol":"test_headers_preserve_order","kind":"function","lang":"python","code":"def test_headers_preserve_order(self, httpbin):\n \"\"\"Preserve order when headers provided as OrderedDict.\"\"\"\n ses = requests.Session()\n ses.headers = collections.OrderedDict()\n ses.headers[\"Accept-Encoding\"] = \"identity\"\n ses.headers[\"First\"] = \"1\"\n ses.headers[\"Second\"] = \"2\"\n headers = collections.OrderedDict([(\"Third\", \"3\"), (\"Fourth\", \"4\")])\n headers[\"Fifth\"] = \"5\"\n headers[\"Second\"] = \"222\"\n req = requests.Request(\"GET\", httpbin(\"get\"), headers=headers)\n prep = ses.prepare_request(req)\n items = list(prep.headers.items())\n assert items[0] == (\"Accept-Encoding\", \"identity\")\n assert items[1] == (\"First\", \"1\")\n assert items[2] == (\"Second\", \"222\")\n assert items[3] == (\"Third\", \"3\")\n assert items[4] == (\"Fourth\", \"4\")\n assert items[5] == (\"Fifth\", \"5\")"}
{"repo":"requests","file":"tests/test_requests.py","line":525,"symbol":"test_user_agent_transfers","kind":"function","lang":"python","code":"def test_user_agent_transfers(self, httpbin, key):\n heads = {key: \"Mozilla/5.0 (github.com/psf/requests)\"}\n\n r = requests.get(httpbin(\"user-agent\"), headers=heads)\n assert heads[key] in r.text"}
{"repo":"requests","file":"tests/test_requests.py","line":531,"symbol":"test_HTTP_200_OK_HEAD","kind":"function","lang":"python","code":"def test_HTTP_200_OK_HEAD(self, httpbin):\n r = requests.head(httpbin(\"get\"))\n assert r.status_code == 200"}
{"repo":"requests","file":"tests/test_requests.py","line":535,"symbol":"test_HTTP_200_OK_PUT","kind":"function","lang":"python","code":"def test_HTTP_200_OK_PUT(self, httpbin):\n r = requests.put(httpbin(\"put\"))\n assert r.status_code == 200"}
{"repo":"requests","file":"tests/test_requests.py","line":539,"symbol":"test_BASICAUTH_TUPLE_HTTP_200_OK_GET","kind":"function","lang":"python","code":"def test_BASICAUTH_TUPLE_HTTP_200_OK_GET(self, httpbin):\n auth = (\"user\", \"pass\")\n url = httpbin(\"basic-auth\", \"user\", \"pass\")\n\n r = requests.get(url, auth=auth)\n assert r.status_code == 200\n\n r = requests.get(url)\n assert r.status_code == 401\n\n s = requests.session()\n s.auth = auth\n r = s.get(url)\n assert r.status_code == 200"}
{"repo":"requests","file":"tests/test_requests.py","line":563,"symbol":"test_set_basicauth","kind":"function","lang":"python","code":"def test_set_basicauth(self, httpbin, username, password):\n auth = (username, password)\n url = httpbin(\"get\")\n\n r = requests.Request(\"GET\", url, auth=auth)\n p = r.prepare()\n\n assert p.headers[\"Authorization\"] == _basic_auth_str(username, password)"}
{"repo":"requests","file":"tests/test_requests.py","line":572,"symbol":"test_basicauth_encodes_byte_strings","kind":"function","lang":"python","code":"def test_basicauth_encodes_byte_strings(self):\n \"\"\"Ensure b'test' formats as the byte string \"test\" rather\n than the unicode string \"b'test'\" in Python 3.\n \"\"\"\n auth = (b\"\\xc5\\xafsername\", b\"test\\xc6\\xb6\")\n r = requests.Request(\"GET\", \"http://localhost\", auth=auth)\n p = r.prepare()\n\n assert p.headers[\"Authorization\"] == \"Basic xa9zZXJuYW1lOnRlc3TGtg==\""}
{"repo":"requests","file":"tests/test_requests.py","line":593,"symbol":"test_errors","kind":"function","lang":"python","code":"def test_errors(self, url, exception):\n with pytest.raises(exception):\n requests.get(url, timeout=1)"}
{"repo":"requests","file":"tests/test_requests.py","line":597,"symbol":"test_proxy_error","kind":"function","lang":"python","code":"def test_proxy_error(self):\n # any proxy related error (address resolution, no route to host, etc) should result in a ProxyError\n with pytest.raises(ProxyError):\n requests.get(\n \"http://localhost:1\", proxies={\"http\": \"non-resolvable-address\"}\n )"}
{"repo":"requests","file":"tests/test_requests.py","line":604,"symbol":"test_proxy_error_on_bad_url","kind":"function","lang":"python","code":"def test_proxy_error_on_bad_url(self, httpbin, httpbin_secure):\n with pytest.raises(InvalidProxyURL):\n requests.get(httpbin_secure(), proxies={\"https\": \"http:/badproxyurl:3128\"})\n\n with pytest.raises(InvalidProxyURL):\n requests.get(httpbin(), proxies={\"http\": \"http://:8080\"})\n\n with pytest.raises(InvalidProxyURL):\n requests.get(httpbin_secure(), proxies={\"https\": \"https://\"})\n\n with pytest.raises(InvalidProxyURL):\n requests.get(httpbin(), proxies={\"http\": \"http:///example.com:8080\"})"}
{"repo":"requests","file":"tests/test_requests.py","line":617,"symbol":"test_respect_proxy_env_on_send_self_prepared_request","kind":"function","lang":"python","code":"def test_respect_proxy_env_on_send_self_prepared_request(self, httpbin):\n with override_environ(http_proxy=INVALID_PROXY):\n with pytest.raises(ProxyError):\n session = requests.Session()\n request = requests.Request(\"GET\", httpbin())\n session.send(request.prepare())"}
{"repo":"requests","file":"tests/test_requests.py","line":624,"symbol":"test_respect_proxy_env_on_send_session_prepared_request","kind":"function","lang":"python","code":"def test_respect_proxy_env_on_send_session_prepared_request(self, httpbin):\n with override_environ(http_proxy=INVALID_PROXY):\n with pytest.raises(ProxyError):\n session = requests.Session()\n request = requests.Request(\"GET\", httpbin())\n prepared = session.prepare_request(request)\n session.send(prepared)"}
{"repo":"requests","file":"tests/test_requests.py","line":632,"symbol":"test_respect_proxy_env_on_send_with_redirects","kind":"function","lang":"python","code":"def test_respect_proxy_env_on_send_with_redirects(self, httpbin):\n with override_environ(http_proxy=INVALID_PROXY):\n with pytest.raises(ProxyError):\n session = requests.Session()\n url = httpbin(\"redirect/1\")\n print(url)\n request = requests.Request(\"GET\", url)\n session.send(request.prepare())"}
{"repo":"requests","file":"tests/test_requests.py","line":641,"symbol":"test_respect_proxy_env_on_get","kind":"function","lang":"python","code":"def test_respect_proxy_env_on_get(self, httpbin):\n with override_environ(http_proxy=INVALID_PROXY):\n with pytest.raises(ProxyError):\n session = requests.Session()\n session.get(httpbin())"}
{"repo":"requests","file":"tests/test_structures.py","line":6,"symbol":"TestCaseInsensitiveDict","kind":"class","lang":"python","code":"class TestCaseInsensitiveDict:\n @pytest.fixture(autouse=True)\n def setup(self):\n \"\"\"CaseInsensitiveDict instance with \"Accept\" header.\"\"\"\n self.case_insensitive_dict = CaseInsensitiveDict()\n self.case_insensitive_dict[\"Accept\"] = \"application/json\"\n\n def test_list(self):\n assert list(self.case_insensitive_dict) == [\"Accept\"]\n\n possible_keys = pytest.mark.parametrize(\n \"key\", (\"accept\", \"ACCEPT\", \"aCcEpT\", \"Accept\")\n )\n\n @possible_keys\n def test_getitem(self, key):\n assert self.case_insensitive_dict[key] == \"application/json\"\n\n @possible_keys\n def test_delitem(self, key):\n del self.case_insensitive_dict[key]\n assert key not in self.case_insensitive_dict\n\n def test_lower_items(self):\n assert list(self.case_insensitive_dict.lower_items()) == [\n (\"accept\", \"application/json\")\n ]\n\n def test_repr(self):\n assert repr(self.case_insensitive_dict) == \"{'Accept': 'application/json'}\"\n\n def test_copy(self):\n copy = self.case_insensitive_dict.copy()\n assert copy is not self.case_insensitive_dict\n assert copy == self.case_insensitive_dict\n\n @pytest.m"}
{"repo":"requests","file":"tests/test_structures.py","line":8,"symbol":"setup","kind":"function","lang":"python","code":"def setup(self):\n \"\"\"CaseInsensitiveDict instance with \"Accept\" header.\"\"\"\n self.case_insensitive_dict = CaseInsensitiveDict()\n self.case_insensitive_dict[\"Accept\"] = \"application/json\""}
{"repo":"requests","file":"tests/test_structures.py","line":13,"symbol":"test_list","kind":"function","lang":"python","code":"def test_list(self):\n assert list(self.case_insensitive_dict) == [\"Accept\"]"}
{"repo":"requests","file":"tests/test_structures.py","line":21,"symbol":"test_getitem","kind":"function","lang":"python","code":"def test_getitem(self, key):\n assert self.case_insensitive_dict[key] == \"application/json\""}
{"repo":"requests","file":"tests/test_structures.py","line":25,"symbol":"test_delitem","kind":"function","lang":"python","code":"def test_delitem(self, key):\n del self.case_insensitive_dict[key]\n assert key not in self.case_insensitive_dict"}
{"repo":"requests","file":"tests/test_structures.py","line":29,"symbol":"test_lower_items","kind":"function","lang":"python","code":"def test_lower_items(self):\n assert list(self.case_insensitive_dict.lower_items()) == [\n (\"accept\", \"application/json\")\n ]"}
{"repo":"requests","file":"tests/test_structures.py","line":34,"symbol":"test_repr","kind":"function","lang":"python","code":"def test_repr(self):\n assert repr(self.case_insensitive_dict) == \"{'Accept': 'application/json'}\""}
{"repo":"requests","file":"tests/test_structures.py","line":37,"symbol":"test_copy","kind":"function","lang":"python","code":"def test_copy(self):\n copy = self.case_insensitive_dict.copy()\n assert copy is not self.case_insensitive_dict\n assert copy == self.case_insensitive_dict"}
{"repo":"requests","file":"tests/test_structures.py","line":50,"symbol":"test_instance_equality","kind":"function","lang":"python","code":"def test_instance_equality(self, other, result):\n assert (self.case_insensitive_dict == other) is result"}
{"repo":"requests","file":"tests/test_structures.py","line":54,"symbol":"TestLookupDict","kind":"class","lang":"python","code":"class TestLookupDict:\n @pytest.fixture(autouse=True)\n def setup(self):\n \"\"\"LookupDict instance with \"bad_gateway\" attribute.\"\"\"\n self.lookup_dict = LookupDict(\"test\")\n self.lookup_dict.bad_gateway = 502\n\n def test_repr(self):\n assert repr(self.lookup_dict) == \"<lookup 'test'>\"\n\n get_item_parameters = pytest.mark.parametrize(\n \"key, value\",\n (\n (\"bad_gateway\", 502),\n (\"not_a_key\", None),\n ),\n )\n\n @get_item_parameters\n def test_getitem(self, key, value):\n assert self.lookup_dict[key] == value\n\n @get_item_parameters\n def test_get(self, key, value):\n assert self.lookup_dict.get(key) == value\n\n def test_hasattr(self):\n assert hasattr(self.lookup_dict, \"bad_gateway\") is True\n assert hasattr(self.lookup_dict, \"not_a_key\") is False\n\n def test_getattr(self):\n assert getattr(self.lookup_dict, \"bad_gateway\") == 502\n with pytest.raises(AttributeError):\n getattr(self.lookup_dict, \"not_a_key\")\n\n @get_item_parameters\n def test_getattr_default(self, key, value):\n assert getattr(self.lookup_dict, key, None) == value"}
{"repo":"requests","file":"tests/test_structures.py","line":56,"symbol":"setup","kind":"function","lang":"python","code":"def setup(self):\n \"\"\"LookupDict instance with \"bad_gateway\" attribute.\"\"\"\n self.lookup_dict = LookupDict(\"test\")\n self.lookup_dict.bad_gateway = 502"}
{"repo":"requests","file":"tests/test_structures.py","line":61,"symbol":"test_repr","kind":"function","lang":"python","code":"def test_repr(self):\n assert repr(self.lookup_dict) == \"<lookup 'test'>\""}
{"repo":"requests","file":"tests/test_structures.py","line":73,"symbol":"test_getitem","kind":"function","lang":"python","code":"def test_getitem(self, key, value):\n assert self.lookup_dict[key] == value"}
{"repo":"requests","file":"tests/test_structures.py","line":77,"symbol":"test_get","kind":"function","lang":"python","code":"def test_get(self, key, value):\n assert self.lookup_dict.get(key) == value"}
{"repo":"requests","file":"tests/test_structures.py","line":80,"symbol":"test_hasattr","kind":"function","lang":"python","code":"def test_hasattr(self):\n assert hasattr(self.lookup_dict, \"bad_gateway\") is True\n assert hasattr(self.lookup_dict, \"not_a_key\") is False"}
{"repo":"requests","file":"tests/test_structures.py","line":84,"symbol":"test_getattr","kind":"function","lang":"python","code":"def test_getattr(self):\n assert getattr(self.lookup_dict, \"bad_gateway\") == 502\n with pytest.raises(AttributeError):\n getattr(self.lookup_dict, \"not_a_key\")"}
{"repo":"requests","file":"tests/test_structures.py","line":90,"symbol":"test_getattr_default","kind":"function","lang":"python","code":"def test_getattr_default(self, key, value):\n assert getattr(self.lookup_dict, key, None) == value"}
{"repo":"requests","file":"tests/test_testserver.py","line":11,"symbol":"TestTestServer","kind":"class","lang":"python","code":"class TestTestServer:\n def test_basic(self):\n \"\"\"messages are sent and received properly\"\"\"\n question = b\"success?\"\n answer = b\"yeah, success\"\n\n def handler(sock):\n text = sock.recv(1000)\n assert text == question\n sock.sendall(answer)\n\n with Server(handler) as (host, port):\n sock = socket.socket()\n sock.connect((host, port))\n sock.sendall(question)\n text = sock.recv(1000)\n assert text == answer\n sock.close()\n\n def test_server_closes(self):\n \"\"\"the server closes when leaving the context manager\"\"\"\n with Server.basic_response_server() as (host, port):\n sock = socket.socket()\n sock.connect((host, port))\n\n sock.close()\n\n with pytest.raises(socket.error):\n new_sock = socket.socket()\n new_sock.connect((host, port))\n\n def test_text_response(self):\n \"\"\"the text_response_server sends the given text\"\"\"\n server = Server.text_response_server(\n \"HTTP/1.1 200 OK\\r\\nContent-Length: 6\\r\\n\\r\\nroflol\"\n )\n\n with server as (host, port):\n "}
{"repo":"requests","file":"tests/test_testserver.py","line":12,"symbol":"test_basic","kind":"function","lang":"python","code":"def test_basic(self):\n \"\"\"messages are sent and received properly\"\"\"\n question = b\"success?\"\n answer = b\"yeah, success\"\n\n def handler(sock):\n text = sock.recv(1000)\n assert text == question\n sock.sendall(answer)\n\n with Server(handler) as (host, port):\n sock = socket.socket()\n sock.connect((host, port))\n sock.sendall(question)\n text = sock.recv(1000)\n assert text == answer\n sock.close()"}
{"repo":"requests","file":"tests/test_testserver.py","line":17,"symbol":"handler","kind":"function","lang":"python","code":"def handler(sock):\n text = sock.recv(1000)\n assert text == question\n sock.sendall(answer)"}
{"repo":"requests","file":"tests/test_testserver.py","line":30,"symbol":"test_server_closes","kind":"function","lang":"python","code":"def test_server_closes(self):\n \"\"\"the server closes when leaving the context manager\"\"\"\n with Server.basic_response_server() as (host, port):\n sock = socket.socket()\n sock.connect((host, port))\n\n sock.close()\n\n with pytest.raises(socket.error):\n new_sock = socket.socket()\n new_sock.connect((host, port))"}
{"repo":"requests","file":"tests/test_testserver.py","line":42,"symbol":"test_text_response","kind":"function","lang":"python","code":"def test_text_response(self):\n \"\"\"the text_response_server sends the given text\"\"\"\n server = Server.text_response_server(\n \"HTTP/1.1 200 OK\\r\\nContent-Length: 6\\r\\n\\r\\nroflol\"\n )\n\n with server as (host, port):\n r = requests.get(f\"http://{host}:{port}\")\n\n assert r.status_code == 200\n assert r.text == \"roflol\"\n assert r.headers[\"Content-Length\"] == \"6\""}
{"repo":"requests","file":"tests/test_testserver.py","line":55,"symbol":"test_basic_response","kind":"function","lang":"python","code":"def test_basic_response(self):\n \"\"\"the basic response server returns an empty http response\"\"\"\n with Server.basic_response_server() as (host, port):\n r = requests.get(f\"http://{host}:{port}\")\n assert r.status_code == 200\n assert r.text == \"\"\n assert r.headers[\"Content-Length\"] == \"0\""}
{"repo":"requests","file":"tests/test_testserver.py","line":63,"symbol":"test_basic_waiting_server","kind":"function","lang":"python","code":"def test_basic_waiting_server(self):\n \"\"\"the server waits for the block_server event to be set before closing\"\"\"\n block_server = threading.Event()\n\n with Server.basic_response_server(wait_to_close_event=block_server) as (\n host,\n port,\n ):\n sock = socket.socket()\n sock.connect((host, port))\n sock.sendall(b\"send something\")\n time.sleep(2.5)\n sock.sendall(b\"still alive\")\n block_server.set() # release server block"}
{"repo":"requests","file":"tests/test_testserver.py","line":78,"symbol":"test_multiple_requests","kind":"function","lang":"python","code":"def test_multiple_requests(self):\n \"\"\"multiple requests can be served\"\"\"\n requests_to_handle = 5\n\n server = Server.basic_response_server(requests_to_handle=requests_to_handle)\n\n with server as (host, port):\n server_url = f\"http://{host}:{port}\"\n for _ in range(requests_to_handle):\n r = requests.get(server_url)\n assert r.status_code == 200\n\n # the (n+1)th request fails\n with pytest.raises(requests.exceptions.ConnectionError):\n r = requests.get(server_url)"}
{"repo":"requests","file":"tests/test_testserver.py","line":95,"symbol":"test_request_recovery","kind":"function","lang":"python","code":"def test_request_recovery(self):\n \"\"\"can check the requests content\"\"\"\n # TODO: figure out why this sometimes fails when using pytest-xdist.\n server = Server.basic_response_server(requests_to_handle=2)\n first_request = b\"put your hands up in the air\"\n second_request = b\"put your hand down in the floor\"\n\n with server as address:\n sock1 = socket.socket()\n sock2 = socket.socket()\n\n sock1.connect(address)\n sock1.sendall(first_request)\n sock1.close()\n\n sock2.connect(address)\n sock2.sendall(second_request)\n sock2.close()\n\n assert server.handler_results[0] == first_request\n assert server.handler_results[1] == second_request"}
{"repo":"requests","file":"tests/test_testserver.py","line":117,"symbol":"test_requests_after_timeout_are_not_received","kind":"function","lang":"python","code":"def test_requests_after_timeout_are_not_received(self):\n \"\"\"the basic response handler times out when receiving requests\"\"\"\n server = Server.basic_response_server(request_timeout=1)\n\n with server as address:\n sock = socket.socket()\n sock.connect(address)\n time.sleep(1.5)\n sock.sendall(b\"hehehe, not received\")\n sock.close()\n\n assert server.handler_results[0] == b\"\""}
{"repo":"requests","file":"tests/test_testserver.py","line":130,"symbol":"test_request_recovery_with_bigger_timeout","kind":"function","lang":"python","code":"def test_request_recovery_with_bigger_timeout(self):\n \"\"\"a biggest timeout can be specified\"\"\"\n server = Server.basic_response_server(request_timeout=3)\n data = b\"bananadine\"\n\n with server as address:\n sock = socket.socket()\n sock.connect(address)\n time.sleep(1.5)\n sock.sendall(data)\n sock.close()\n\n assert server.handler_results[0] == data"}
{"repo":"requests","file":"tests/test_testserver.py","line":144,"symbol":"test_server_finishes_on_error","kind":"function","lang":"python","code":"def test_server_finishes_on_error(self):\n \"\"\"the server thread exits even if an exception exits the context manager\"\"\"\n server = Server.basic_response_server()\n with pytest.raises(Exception):\n with server:\n raise Exception()\n\n assert len(server.handler_results) == 0\n\n # if the server thread fails to finish, the test suite will hang\n # and get killed by the jenkins timeout."}
{"repo":"requests","file":"tests/test_testserver.py","line":156,"symbol":"test_server_finishes_when_no_connections","kind":"function","lang":"python","code":"def test_server_finishes_when_no_connections(self):\n \"\"\"the server thread exits even if there are no connections\"\"\"\n server = Server.basic_response_server()\n with server:\n pass\n\n assert len(server.handler_results) == 0\n\n # if the server thread fails to finish, the test suite will hang\n # and get killed by the jenkins timeout."}
{"repo":"requests","file":"tests/test_utils.py","line":50,"symbol":"TestSuperLen","kind":"class","lang":"python","code":"class TestSuperLen:\n @pytest.mark.parametrize(\n \"stream, value\",\n (\n (StringIO.StringIO, \"Test\"),\n (BytesIO, b\"Test\"),\n pytest.param(\n cStringIO, \"Test\", marks=pytest.mark.skipif(\"cStringIO is None\")\n ),\n ),\n )\n def test_io_streams(self, stream, value):\n \"\"\"Ensures that we properly deal with different kinds of IO streams.\"\"\"\n assert super_len(stream()) == 0\n assert super_len(stream(value)) == 4\n\n def test_super_len_correctly_calculates_len_of_partially_read_file(self):\n \"\"\"Ensure that we handle partially consumed file like objects.\"\"\"\n s = StringIO.StringIO()\n s.write(\"foobarbogus\")\n assert super_len(s) == 0\n\n @pytest.mark.parametrize(\"error\", [IOError, OSError])\n def test_super_len_handles_files_raising_weird_errors_in_tell(self, error):\n \"\"\"If tell() raises errors, assume the cursor is at position zero.\"\"\"\n\n class BoomFile:\n def __len__(self):\n return 5\n\n def tell(self):\n raise error()\n\n assert super_len(BoomFile()) == 0\n\n @pytest.mark.parametrize(\"error\", [IOE"}
{"repo":"requests","file":"tests/test_utils.py","line":61,"symbol":"test_io_streams","kind":"function","lang":"python","code":"def test_io_streams(self, stream, value):\n \"\"\"Ensures that we properly deal with different kinds of IO streams.\"\"\"\n assert super_len(stream()) == 0\n assert super_len(stream(value)) == 4"}
{"repo":"requests","file":"tests/test_utils.py","line":66,"symbol":"test_super_len_correctly_calculates_len_of_partially_read_file","kind":"function","lang":"python","code":"def test_super_len_correctly_calculates_len_of_partially_read_file(self):\n \"\"\"Ensure that we handle partially consumed file like objects.\"\"\"\n s = StringIO.StringIO()\n s.write(\"foobarbogus\")\n assert super_len(s) == 0"}
{"repo":"requests","file":"tests/test_utils.py","line":73,"symbol":"test_super_len_handles_files_raising_weird_errors_in_tell","kind":"function","lang":"python","code":"def test_super_len_handles_files_raising_weird_errors_in_tell(self, error):\n \"\"\"If tell() raises errors, assume the cursor is at position zero.\"\"\"\n\n class BoomFile:\n def __len__(self):\n return 5\n\n def tell(self):\n raise error()\n\n assert super_len(BoomFile()) == 0"}
{"repo":"requests","file":"tests/test_utils.py","line":76,"symbol":"BoomFile","kind":"class","lang":"python","code":"class BoomFile:\n def __len__(self):\n return 5\n\n def tell(self):\n raise error()"}
{"repo":"requests","file":"tests/test_utils.py","line":77,"symbol":"__len__","kind":"function","lang":"python","code":"def __len__(self):\n return 5"}
{"repo":"requests","file":"tests/test_utils.py","line":80,"symbol":"tell","kind":"function","lang":"python","code":"def tell(self):\n raise error()"}
{"repo":"requests","file":"tests/test_utils.py","line":86,"symbol":"test_super_len_tell_ioerror","kind":"function","lang":"python","code":"def test_super_len_tell_ioerror(self, error):\n \"\"\"Ensure that if tell gives an IOError super_len doesn't fail\"\"\"\n\n class NoLenBoomFile:\n def tell(self):\n raise error()\n\n def seek(self, offset, whence):\n pass\n\n assert super_len(NoLenBoomFile()) == 0"}
{"repo":"requests","file":"tests/test_utils.py","line":89,"symbol":"NoLenBoomFile","kind":"class","lang":"python","code":"class NoLenBoomFile:\n def tell(self):\n raise error()\n\n def seek(self, offset, whence):\n pass"}
{"repo":"requests","file":"tests/test_utils.py","line":90,"symbol":"tell","kind":"function","lang":"python","code":"def tell(self):\n raise error()"}
{"repo":"requests","file":"tests/test_utils.py","line":93,"symbol":"seek","kind":"function","lang":"python","code":"def seek(self, offset, whence):\n pass"}
{"repo":"requests","file":"tests/test_utils.py","line":98,"symbol":"test_string","kind":"function","lang":"python","code":"def test_string(self):\n assert super_len(\"Test\") == 4"}
{"repo":"requests","file":"tests/test_utils.py","line":108,"symbol":"test_file","kind":"function","lang":"python","code":"def test_file(self, tmpdir, mode, warnings_num, recwarn):\n file_obj = tmpdir.join(\"test.txt\")\n file_obj.write(\"Test\")\n with file_obj.open(mode) as fd:\n assert super_len(fd) == 4\n assert len(recwarn) == warnings_num"}
{"repo":"requests","file":"tests/test_utils.py","line":115,"symbol":"test_tarfile_member","kind":"function","lang":"python","code":"def test_tarfile_member(self, tmpdir):\n file_obj = tmpdir.join(\"test.txt\")\n file_obj.write(\"Test\")\n\n tar_obj = str(tmpdir.join(\"test.tar\"))\n with tarfile.open(tar_obj, \"w\") as tar:\n tar.add(str(file_obj), arcname=\"test.txt\")\n\n with tarfile.open(tar_obj) as tar:\n member = tar.extractfile(\"test.txt\")\n assert super_len(member) == 4"}
{"repo":"requests","file":"tests/test_utils.py","line":127,"symbol":"test_super_len_with__len__","kind":"function","lang":"python","code":"def test_super_len_with__len__(self):\n foo = [1, 2, 3, 4]\n len_foo = super_len(foo)\n assert len_foo == 4"}
{"repo":"requests","file":"tests/test_utils.py","line":132,"symbol":"test_super_len_with_no__len__","kind":"function","lang":"python","code":"def test_super_len_with_no__len__(self):\n class LenFile:\n def __init__(self):\n self.len = 5\n\n assert super_len(LenFile()) == 5"}
{"repo":"requests","file":"tests/test_utils.py","line":133,"symbol":"LenFile","kind":"class","lang":"python","code":"class LenFile:\n def __init__(self):\n self.len = 5"}
{"repo":"requests","file":"tests/test_utils.py","line":134,"symbol":"__init__","kind":"function","lang":"python","code":"def __init__(self):\n self.len = 5"}
{"repo":"requests","file":"tests/test_utils.py","line":139,"symbol":"test_super_len_with_tell","kind":"function","lang":"python","code":"def test_super_len_with_tell(self):\n foo = StringIO.StringIO(\"12345\")\n assert super_len(foo) == 5\n foo.read(2)\n assert super_len(foo) == 3"}
{"repo":"requests","file":"tests/test_utils.py","line":145,"symbol":"test_super_len_with_fileno","kind":"function","lang":"python","code":"def test_super_len_with_fileno(self):\n with open(__file__, \"rb\") as f:\n length = super_len(f)\n file_data = f.read()\n assert length == len(file_data)"}
{"repo":"requests","file":"tests/test_utils.py","line":151,"symbol":"test_super_len_with_no_matches","kind":"function","lang":"python","code":"def test_super_len_with_no_matches(self):\n \"\"\"Ensure that objects without any length methods default to 0\"\"\"\n assert super_len(object()) == 0"}
{"repo":"requests","file":"tests/test_utils.py","line":156,"symbol":"TestGetNetrcAuth","kind":"class","lang":"python","code":"class TestGetNetrcAuth:\n def test_works(self, tmp_path, monkeypatch):\n netrc_path = tmp_path / \".netrc\"\n monkeypatch.setenv(\"NETRC\", str(netrc_path))\n with open(netrc_path, \"w\") as f:\n f.write(\"machine example.com login aaaa password bbbb\\n\")\n auth = get_netrc_auth(\"http://example.com/thing\")\n assert auth == (\"aaaa\", \"bbbb\")\n\n def test_not_vulnerable_to_bad_url_parsing(self, tmp_path, monkeypatch):\n netrc_path = tmp_path / \".netrc\"\n monkeypatch.setenv(\"NETRC\", str(netrc_path))\n with open(netrc_path, \"w\") as f:\n f.write(\"machine example.com login aaaa password bbbb\\n\")\n auth = get_netrc_auth(\"http://example.com:@evil.com/&apos;\")\n assert auth is None\n\n def test_empty_default_credentials_ignored(self, tmp_path, monkeypatch):\n \"\"\"Empty default credentials should not be returned.\"\"\"\n netrc_path = tmp_path / \".netrc\"\n monkeypatch.setenv(\"NETRC\", str(netrc_path))\n with open(netrc_path, \"w\") as f:\n f.write(\"machine example.com login user password pass\\ndefault\\n\")\n\n auth = get_netrc_auth(\"http://httpbin.org/\")\n assert auth is None"}
{"repo":"requests","file":"tests/test_utils.py","line":157,"symbol":"test_works","kind":"function","lang":"python","code":"def test_works(self, tmp_path, monkeypatch):\n netrc_path = tmp_path / \".netrc\"\n monkeypatch.setenv(\"NETRC\", str(netrc_path))\n with open(netrc_path, \"w\") as f:\n f.write(\"machine example.com login aaaa password bbbb\\n\")\n auth = get_netrc_auth(\"http://example.com/thing\")\n assert auth == (\"aaaa\", \"bbbb\")"}
{"repo":"requests","file":"tests/test_utils.py","line":165,"symbol":"test_not_vulnerable_to_bad_url_parsing","kind":"function","lang":"python","code":"def test_not_vulnerable_to_bad_url_parsing(self, tmp_path, monkeypatch):\n netrc_path = tmp_path / \".netrc\"\n monkeypatch.setenv(\"NETRC\", str(netrc_path))\n with open(netrc_path, \"w\") as f:\n f.write(\"machine example.com login aaaa password bbbb\\n\")\n auth = get_netrc_auth(\"http://example.com:@evil.com/&apos;\")\n assert auth is None"}
{"repo":"requests","file":"tests/test_utils.py","line":173,"symbol":"test_empty_default_credentials_ignored","kind":"function","lang":"python","code":"def test_empty_default_credentials_ignored(self, tmp_path, monkeypatch):\n \"\"\"Empty default credentials should not be returned.\"\"\"\n netrc_path = tmp_path / \".netrc\"\n monkeypatch.setenv(\"NETRC\", str(netrc_path))\n with open(netrc_path, \"w\") as f:\n f.write(\"machine example.com login user password pass\\ndefault\\n\")\n\n auth = get_netrc_auth(\"http://httpbin.org/\")\n assert auth is None"}
{"repo":"requests","file":"tests/test_utils.py","line":184,"symbol":"TestToKeyValList","kind":"class","lang":"python","code":"class TestToKeyValList:\n @pytest.mark.parametrize(\n \"value, expected\",\n (\n ([(\"key\", \"val\")], [(\"key\", \"val\")]),\n (((\"key\", \"val\"),), [(\"key\", \"val\")]),\n ({\"key\": \"val\"}, [(\"key\", \"val\")]),\n (None, None),\n ),\n )\n def test_valid(self, value, expected):\n assert to_key_val_list(value) == expected\n\n def test_invalid(self):\n with pytest.raises(ValueError):\n to_key_val_list(\"string\")"}
{"repo":"requests","file":"tests/test_utils.py","line":194,"symbol":"test_valid","kind":"function","lang":"python","code":"def test_valid(self, value, expected):\n assert to_key_val_list(value) == expected"}
{"repo":"requests","file":"tests/test_utils.py","line":197,"symbol":"test_invalid","kind":"function","lang":"python","code":"def test_invalid(self):\n with pytest.raises(ValueError):\n to_key_val_list(\"string\")"}
{"repo":"requests","file":"tests/test_utils.py","line":202,"symbol":"TestUnquoteHeaderValue","kind":"class","lang":"python","code":"class TestUnquoteHeaderValue:\n @pytest.mark.parametrize(\n \"value, expected\",\n (\n (None, None),\n (\"Test\", \"Test\"),\n ('\"Test\"', \"Test\"),\n ('\"Test\\\\\\\\\"', \"Test\\\\\"),\n ('\"\\\\\\\\Comp\\\\Res\"', \"\\\\Comp\\\\Res\"),\n ),\n )\n def test_valid(self, value, expected):\n assert unquote_header_value(value) == expected\n\n def test_is_filename(self):\n assert unquote_header_value('\"\\\\\\\\Comp\\\\Res\"', True) == \"\\\\\\\\Comp\\\\Res\""}
{"repo":"requests","file":"tests/test_utils.py","line":213,"symbol":"test_valid","kind":"function","lang":"python","code":"def test_valid(self, value, expected):\n assert unquote_header_value(value) == expected"}
{"repo":"requests","file":"tests/test_utils.py","line":216,"symbol":"test_is_filename","kind":"function","lang":"python","code":"def test_is_filename(self):\n assert unquote_header_value('\"\\\\\\\\Comp\\\\Res\"', True) == \"\\\\\\\\Comp\\\\Res\""}
{"repo":"requests","file":"tests/test_utils.py","line":220,"symbol":"TestGetEnvironProxies","kind":"class","lang":"python","code":"class TestGetEnvironProxies:\n \"\"\"Ensures that IP addresses are correctly matches with ranges\n in no_proxy variable.\n \"\"\"\n\n @pytest.fixture(autouse=True, params=[\"no_proxy\", \"NO_PROXY\"])\n def no_proxy(self, request, monkeypatch):\n monkeypatch.setenv(\n request.param, \"192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1\"\n )\n\n @pytest.mark.parametrize(\n \"url\",\n (\n \"http://192.168.0.1:5000/\",\n \"http://192.168.0.1/\",\n \"http://172.16.1.1/\",\n \"http://172.16.1.1:5000/\",\n \"http://localhost.localdomain:5000/v1.0/\",\n ),\n )\n def test_bypass(self, url):\n assert get_environ_proxies(url, no_proxy=None) == {}\n\n @pytest.mark.parametrize(\n \"url\",\n (\n \"http://192.168.1.1:5000/\",\n \"http://192.168.1.1/\",\n \"http://www.requests.com/\",\n ),\n )\n def test_not_bypass(self, url):\n assert get_environ_proxies(url, no_proxy=None) != {}\n\n @pytest.mark.parametrize(\n \"url\",\n (\n \"http://192.168.1.1:5000/\",\n \"http://192.168.1.1/\",\n \"http://www.requests.com/\",\n "}
{"repo":"requests","file":"tests/test_utils.py","line":226,"symbol":"no_proxy","kind":"function","lang":"python","code":"def no_proxy(self, request, monkeypatch):\n monkeypatch.setenv(\n request.param, \"192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1\"\n )"}
{"repo":"requests","file":"tests/test_utils.py","line":241,"symbol":"test_bypass","kind":"function","lang":"python","code":"def test_bypass(self, url):\n assert get_environ_proxies(url, no_proxy=None) == {}"}
{"repo":"requests","file":"tests/test_utils.py","line":252,"symbol":"test_not_bypass","kind":"function","lang":"python","code":"def test_not_bypass(self, url):\n assert get_environ_proxies(url, no_proxy=None) != {}"}
{"repo":"requests","file":"tests/test_utils.py","line":263,"symbol":"test_bypass_no_proxy_keyword","kind":"function","lang":"python","code":"def test_bypass_no_proxy_keyword(self, url):\n no_proxy = \"192.168.1.1,requests.com\"\n assert get_environ_proxies(url, no_proxy=no_proxy) == {}"}
{"repo":"requests","file":"tests/test_utils.py","line":277,"symbol":"test_not_bypass_no_proxy_keyword","kind":"function","lang":"python","code":"def test_not_bypass_no_proxy_keyword(self, url, monkeypatch):\n # This is testing that the 'no_proxy' argument overrides the\n # environment variable 'no_proxy'\n monkeypatch.setenv(\"http_proxy\", \"http://proxy.example.com:3128/\")\n no_proxy = \"192.168.1.1,requests.com\"\n assert get_environ_proxies(url, no_proxy=no_proxy) != {}"}
{"repo":"requests","file":"tests/test_utils.py","line":285,"symbol":"TestIsIPv4Address","kind":"class","lang":"python","code":"class TestIsIPv4Address:\n def test_valid(self):\n assert is_ipv4_address(\"8.8.8.8\")\n\n @pytest.mark.parametrize(\"value\", (\"8.8.8.8.8\", \"localhost.localdomain\"))\n def test_invalid(self, value):\n assert not is_ipv4_address(value)"}
{"repo":"requests","file":"tests/test_utils.py","line":286,"symbol":"test_valid","kind":"function","lang":"python","code":"def test_valid(self):\n assert is_ipv4_address(\"8.8.8.8\")"}
{"repo":"requests","file":"tests/test_utils.py","line":290,"symbol":"test_invalid","kind":"function","lang":"python","code":"def test_invalid(self, value):\n assert not is_ipv4_address(value)"}
{"repo":"requests","file":"tests/test_utils.py","line":294,"symbol":"TestIsValidCIDR","kind":"class","lang":"python","code":"class TestIsValidCIDR:\n def test_valid(self):\n assert is_valid_cidr(\"192.168.1.0/24\")\n\n @pytest.mark.parametrize(\n \"value\",\n (\n \"8.8.8.8\",\n \"192.168.1.0/a\",\n \"192.168.1.0/128\",\n \"192.168.1.0/-1\",\n \"192.168.1.999/24\",\n ),\n )\n def test_invalid(self, value):\n assert not is_valid_cidr(value)"}
{"repo":"requests","file":"tests/test_utils.py","line":295,"symbol":"test_valid","kind":"function","lang":"python","code":"def test_valid(self):\n assert is_valid_cidr(\"192.168.1.0/24\")"}
{"repo":"requests","file":"tests/test_utils.py","line":308,"symbol":"test_invalid","kind":"function","lang":"python","code":"def test_invalid(self, value):\n assert not is_valid_cidr(value)"}
{"repo":"requests","file":"tests/test_utils.py","line":312,"symbol":"TestAddressInNetwork","kind":"class","lang":"python","code":"class TestAddressInNetwork:\n def test_valid(self):\n assert address_in_network(\"192.168.1.1\", \"192.168.1.0/24\")\n\n def test_invalid(self):\n assert not address_in_network(\"172.16.0.1\", \"192.168.1.0/24\")"}
{"repo":"requests","file":"tests/test_utils.py","line":313,"symbol":"test_valid","kind":"function","lang":"python","code":"def test_valid(self):\n assert address_in_network(\"192.168.1.1\", \"192.168.1.0/24\")"}
{"repo":"requests","file":"tests/test_utils.py","line":316,"symbol":"test_invalid","kind":"function","lang":"python","code":"def test_invalid(self):\n assert not address_in_network(\"172.16.0.1\", \"192.168.1.0/24\")"}
{"repo":"requests","file":"tests/test_utils.py","line":320,"symbol":"TestGuessFilename","kind":"class","lang":"python","code":"class TestGuessFilename:\n @pytest.mark.parametrize(\n \"value\",\n (1, type(\"Fake\", (object,), {\"name\": 1})()),\n )\n def test_guess_filename_invalid(self, value):\n assert guess_filename(value) is None\n\n @pytest.mark.parametrize(\n \"value, expected_type\",\n (\n (b\"value\", compat.bytes),\n (b\"value\".decode(\"utf-8\"), compat.str),\n ),\n )\n def test_guess_filename_valid(self, value, expected_type):\n obj = type(\"Fake\", (object,), {\"name\": value})()\n result = guess_filename(obj)\n assert result == value\n assert isinstance(result, expected_type)"}
{"repo":"requests","file":"tests/test_utils.py","line":325,"symbol":"test_guess_filename_invalid","kind":"function","lang":"python","code":"def test_guess_filename_invalid(self, value):\n assert guess_filename(value) is None"}
{"repo":"requests","file":"tests/test_utils.py","line":335,"symbol":"test_guess_filename_valid","kind":"function","lang":"python","code":"def test_guess_filename_valid(self, value, expected_type):\n obj = type(\"Fake\", (object,), {\"name\": value})()\n result = guess_filename(obj)\n assert result == value\n assert isinstance(result, expected_type)"}
{"repo":"requests","file":"tests/test_utils.py","line":342,"symbol":"TestExtractZippedPaths","kind":"class","lang":"python","code":"class TestExtractZippedPaths:\n @pytest.mark.parametrize(\n \"path\",\n (\n \"/\",\n __file__,\n pytest.__file__,\n \"/etc/invalid/location\",\n ),\n )\n def test_unzipped_paths_unchanged(self, path):\n assert path == extract_zipped_paths(path)\n\n def test_zipped_paths_extracted(self, tmpdir):\n zipped_py = tmpdir.join(\"test.zip\")\n with zipfile.ZipFile(zipped_py.strpath, \"w\") as f:\n f.write(__file__)\n\n _, name = os.path.splitdrive(__file__)\n zipped_path = os.path.join(zipped_py.strpath, name.lstrip(r\"\\/\"))\n extracted_path = extract_zipped_paths(zipped_path)\n\n try:\n assert extracted_path != zipped_path\n assert os.path.exists(extracted_path)\n assert filecmp.cmp(extracted_path, __file__)\n finally:\n os.remove(extracted_path)\n\n def test_invalid_unc_path(self):\n path = r\"\\\\localhost\\invalid\\location\"\n assert extract_zipped_paths(path) == path"}
{"repo":"requests","file":"tests/test_utils.py","line":352,"symbol":"test_unzipped_paths_unchanged","kind":"function","lang":"python","code":"def test_unzipped_paths_unchanged(self, path):\n assert path == extract_zipped_paths(path)"}
{"repo":"requests","file":"tests/test_utils.py","line":355,"symbol":"test_zipped_paths_extracted","kind":"function","lang":"python","code":"def test_zipped_paths_extracted(self, tmpdir):\n zipped_py = tmpdir.join(\"test.zip\")\n with zipfile.ZipFile(zipped_py.strpath, \"w\") as f:\n f.write(__file__)\n\n _, name = os.path.splitdrive(__file__)\n zipped_path = os.path.join(zipped_py.strpath, name.lstrip(r\"\\/\"))\n extracted_path = extract_zipped_paths(zipped_path)\n\n try:\n assert extracted_path != zipped_path\n assert os.path.exists(extracted_path)\n assert filecmp.cmp(extracted_path, __file__)\n finally:\n os.remove(extracted_path)"}
{"repo":"requests","file":"tests/test_utils.py","line":371,"symbol":"test_invalid_unc_path","kind":"function","lang":"python","code":"def test_invalid_unc_path(self):\n path = r\"\\\\localhost\\invalid\\location\"\n assert extract_zipped_paths(path) == path"}
{"repo":"requests","file":"tests/test_utils.py","line":376,"symbol":"TestContentEncodingDetection","kind":"class","lang":"python","code":"class TestContentEncodingDetection:\n def test_none(self):\n encodings = get_encodings_from_content(\"\")\n assert not len(encodings)\n\n @pytest.mark.parametrize(\n \"content\",\n (\n # HTML5 meta charset attribute\n '<meta charset=\"UTF-8\">',\n # HTML4 pragma directive\n '<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\">',\n # XHTML 1.x served with text/html MIME type\n '<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\" />',\n # XHTML 1.x served as XML\n '<?xml version=\"1.0\" encoding=\"UTF-8\"?>',\n ),\n )\n def test_pragmas(self, content):\n encodings = get_encodings_from_content(content)\n assert len(encodings) == 1\n assert encodings[0] == \"UTF-8\"\n\n def test_precedence(self):\n content = \"\"\"\n <?xml version=\"1.0\" encoding=\"XML\"?>\n <meta charset=\"HTML5\">\n <meta http-equiv=\"Content-type\" content=\"text/html;charset=HTML4\" />\n \"\"\".strip()\n assert get_encodings_from_content(content) == [\"HTML5\", \"HTML4\", \"XML\"]"}
{"repo":"requests","file":"tests/test_utils.py","line":377,"symbol":"test_none","kind":"function","lang":"python","code":"def test_none(self):\n encodings = get_encodings_from_content(\"\")\n assert not len(encodings)"}
{"repo":"requests","file":"tests/test_utils.py","line":394,"symbol":"test_pragmas","kind":"function","lang":"python","code":"def test_pragmas(self, content):\n encodings = get_encodings_from_content(content)\n assert len(encodings) == 1\n assert encodings[0] == \"UTF-8\""}
{"repo":"requests","file":"tests/test_utils.py","line":399,"symbol":"test_precedence","kind":"function","lang":"python","code":"def test_precedence(self):\n content = \"\"\"\n <?xml version=\"1.0\" encoding=\"XML\"?>\n <meta charset=\"HTML5\">\n <meta http-equiv=\"Content-type\" content=\"text/html;charset=HTML4\" />\n \"\"\".strip()\n assert get_encodings_from_content(content) == [\"HTML5\", \"HTML4\", \"XML\"]"}
{"repo":"requests","file":"tests/test_utils.py","line":408,"symbol":"TestGuessJSONUTF","kind":"class","lang":"python","code":"class TestGuessJSONUTF:\n @pytest.mark.parametrize(\n \"encoding\",\n (\n \"utf-32\",\n \"utf-8-sig\",\n \"utf-16\",\n \"utf-8\",\n \"utf-16-be\",\n \"utf-16-le\",\n \"utf-32-be\",\n \"utf-32-le\",\n ),\n )\n def test_encoded(self, encoding):\n data = \"{}\".encode(encoding)\n assert guess_json_utf(data) == encoding\n\n def test_bad_utf_like_encoding(self):\n assert guess_json_utf(b\"\\x00\\x00\\x00\\x00\") is None\n\n @pytest.mark.parametrize(\n (\"encoding\", \"expected\"),\n (\n (\"utf-16-be\", \"utf-16\"),\n (\"utf-16-le\", \"utf-16\"),\n (\"utf-32-be\", \"utf-32\"),\n (\"utf-32-le\", \"utf-32\"),\n ),\n )\n def test_guess_by_bom(self, encoding, expected):\n data = \"\\ufeff{}\".encode(encoding)\n assert guess_json_utf(data) == expected"}
{"repo":"requests","file":"tests/test_utils.py","line":422,"symbol":"test_encoded","kind":"function","lang":"python","code":"def test_encoded(self, encoding):\n data = \"{}\".encode(encoding)\n assert guess_json_utf(data) == encoding"}
{"repo":"requests","file":"tests/test_utils.py","line":426,"symbol":"test_bad_utf_like_encoding","kind":"function","lang":"python","code":"def test_bad_utf_like_encoding(self):\n assert guess_json_utf(b\"\\x00\\x00\\x00\\x00\") is None"}
{"repo":"requests","file":"tests/testserver/server.py","line":7,"symbol":"consume_socket_content","kind":"function","lang":"python","code":"def consume_socket_content(sock, timeout=0.5):\n chunks = 65536\n content = b\"\"\n\n while True:\n more_to_read = select.select([sock], [], [], timeout)[0]\n if not more_to_read:\n break\n\n new_content = sock.recv(chunks)\n if not new_content:\n break\n\n content += new_content\n\n return content"}
{"repo":"requests","file":"tests/testserver/server.py","line":25,"symbol":"Server","kind":"class","lang":"python","code":"class Server(threading.Thread):\n \"\"\"Dummy server using for unit testing\"\"\"\n\n WAIT_EVENT_TIMEOUT = 5\n\n def __init__(\n self,\n handler=None,\n host=\"localhost\",\n port=0,\n requests_to_handle=1,\n wait_to_close_event=None,\n ):\n super().__init__()\n\n self.handler = handler or consume_socket_content\n self.handler_results = []\n\n self.host = host\n self.port = port\n self.requests_to_handle = requests_to_handle\n\n self.wait_to_close_event = wait_to_close_event\n self.ready_event = threading.Event()\n self.stop_event = threading.Event()\n\n @classmethod\n def text_response_server(cls, text, request_timeout=0.5, **kwargs):\n def text_response_handler(sock):\n request_content = consume_socket_content(sock, timeout=request_timeout)\n sock.send(text.encode(\"utf-8\"))\n\n return request_content\n\n return Server(text_response_handler, **kwargs)\n\n @classmethod\n def basic_response_server(cls, **kwargs):\n return cls.text_response_server(\n \"HTTP/1.1 200 OK\\r\\n\" + \"Content-Length: 0\\r\\n\\r\\n\", **kwargs\n )\n\n def run(self)"}
{"repo":"requests","file":"tests/testserver/server.py","line":30,"symbol":"__init__","kind":"function","lang":"python","code":"def __init__(\n self,\n handler=None,\n host=\"localhost\",\n port=0,\n requests_to_handle=1,\n wait_to_close_event=None,\n ):\n super().__init__()\n\n self.handler = handler or consume_socket_content\n self.handler_results = []\n\n self.host = host\n self.port = port\n self.requests_to_handle = requests_to_handle\n\n self.wait_to_close_event = wait_to_close_event\n self.ready_event = threading.Event()\n self.stop_event = threading.Event()"}
{"repo":"requests","file":"tests/testserver/server.py","line":52,"symbol":"text_response_server","kind":"function","lang":"python","code":"def text_response_server(cls, text, request_timeout=0.5, **kwargs):\n def text_response_handler(sock):\n request_content = consume_socket_content(sock, timeout=request_timeout)\n sock.send(text.encode(\"utf-8\"))\n\n return request_content\n\n return Server(text_response_handler, **kwargs)"}
{"repo":"requests","file":"tests/testserver/server.py","line":53,"symbol":"text_response_handler","kind":"function","lang":"python","code":"def text_response_handler(sock):\n request_content = consume_socket_content(sock, timeout=request_timeout)\n sock.send(text.encode(\"utf-8\"))\n\n return request_content"}
{"repo":"requests","file":"tests/testserver/server.py","line":62,"symbol":"basic_response_server","kind":"function","lang":"python","code":"def basic_response_server(cls, **kwargs):\n return cls.text_response_server(\n \"HTTP/1.1 200 OK\\r\\n\" + \"Content-Length: 0\\r\\n\\r\\n\", **kwargs\n )"}
{"repo":"requests","file":"tests/testserver/server.py","line":67,"symbol":"run","kind":"function","lang":"python","code":"def run(self):\n try:\n self.server_sock = self._create_socket_and_bind()\n # in case self.port = 0\n self.port = self.server_sock.getsockname()[1]\n self.ready_event.set()\n self._handle_requests()\n\n if self.wait_to_close_event:\n self.wait_to_close_event.wait(self.WAIT_EVENT_TIMEOUT)\n finally:\n self.ready_event.set() # just in case of exception\n self._close_server_sock_ignore_errors()\n self.stop_event.set()"}
{"repo":"requests","file":"tests/testserver/server.py","line":82,"symbol":"_create_socket_and_bind","kind":"function","lang":"python","code":"def _create_socket_and_bind(self):\n sock = socket.socket()\n sock.bind((self.host, self.port))\n sock.listen()\n return sock"}
{"repo":"requests","file":"tests/testserver/server.py","line":88,"symbol":"_close_server_sock_ignore_errors","kind":"function","lang":"python","code":"def _close_server_sock_ignore_errors(self):\n try:\n self.server_sock.close()\n except OSError:\n pass"}
{"repo":"requests","file":"tests/testserver/server.py","line":94,"symbol":"_handle_requests","kind":"function","lang":"python","code":"def _handle_requests(self):\n for _ in range(self.requests_to_handle):\n sock = self._accept_connection()\n if not sock:\n break\n\n handler_result = self.handler(sock)\n\n self.handler_results.append(handler_result)\n sock.close()"}
{"repo":"requests","file":"tests/testserver/server.py","line":105,"symbol":"_accept_connection","kind":"function","lang":"python","code":"def _accept_connection(self):\n try:\n ready, _, _ = select.select(\n [self.server_sock], [], [], self.WAIT_EVENT_TIMEOUT\n )\n if not ready:\n return None\n\n return self.server_sock.accept()[0]\n except OSError:\n return None"}
{"repo":"requests","file":"tests/testserver/server.py","line":117,"symbol":"__enter__","kind":"function","lang":"python","code":"def __enter__(self):\n self.start()\n if not self.ready_event.wait(self.WAIT_EVENT_TIMEOUT):\n raise RuntimeError(\"Timeout waiting for server to be ready.\")\n return self.host, self.port"}
{"repo":"requests","file":"tests/testserver/server.py","line":123,"symbol":"__exit__","kind":"function","lang":"python","code":"def __exit__(self, exc_type, exc_value, traceback):\n if exc_type is None:\n self.stop_event.wait(self.WAIT_EVENT_TIMEOUT)\n else:\n if self.wait_to_close_event:\n # avoid server from waiting for event timeouts\n # if an exception is found in the main thread\n self.wait_to_close_event.set()\n\n # ensure server thread doesn't get stuck waiting for connections\n self._close_server_sock_ignore_errors()\n self.join()\n return False # allow exceptions to propagate"}
{"repo":"requests","file":"tests/testserver/server.py","line":138,"symbol":"TLSServer","kind":"class","lang":"python","code":"class TLSServer(Server):\n def __init__(\n self,\n *,\n handler=None,\n host=\"localhost\",\n port=0,\n requests_to_handle=1,\n wait_to_close_event=None,\n cert_chain=None,\n keyfile=None,\n mutual_tls=False,\n cacert=None,\n ):\n super().__init__(\n handler=handler,\n host=host,\n port=port,\n requests_to_handle=requests_to_handle,\n wait_to_close_event=wait_to_close_event,\n )\n self.cert_chain = cert_chain\n self.keyfile = keyfile\n self.ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)\n self.ssl_context.load_cert_chain(self.cert_chain, keyfile=self.keyfile)\n self.mutual_tls = mutual_tls\n self.cacert = cacert\n if mutual_tls:\n # For simplicity, we're going to assume that the client cert is\n # issued by the same CA as our Server certificate\n self.ssl_context.verify_mode = ssl.CERT_OPTIONAL\n self.ssl_context.load_verify_locations(self.cacert)\n\n def _create_socket_and_bind(self):\n sock = socket.socket()\n sock = self.ssl_context.wrap_socket(sock, "}
{"repo":"requests","file":"tests/testserver/server.py","line":139,"symbol":"__init__","kind":"function","lang":"python","code":"def __init__(\n self,\n *,\n handler=None,\n host=\"localhost\",\n port=0,\n requests_to_handle=1,\n wait_to_close_event=None,\n cert_chain=None,\n keyfile=None,\n mutual_tls=False,\n cacert=None,\n ):\n super().__init__(\n handler=handler,\n host=host,\n port=port,\n requests_to_handle=requests_to_handle,\n wait_to_close_event=wait_to_close_event,\n )\n self.cert_chain = cert_chain\n self.keyfile = keyfile\n self.ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)\n self.ssl_context.load_cert_chain(self.cert_chain, keyfile=self.keyfile)\n self.mutual_tls = mutual_tls\n self.cacert = cacert\n if mutual_tls:\n # For simplicity, we're going to assume that the client cert is\n # issued by the same CA as our Server certificate\n self.ssl_context.verify_mode = ssl.CERT_OPTIONAL\n self.ssl_context.load_verify_locations(self.cacert)"}
{"repo":"requests","file":"tests/testserver/server.py","line":171,"symbol":"_create_socket_and_bind","kind":"function","lang":"python","code":"def _create_socket_and_bind(self):\n sock = socket.socket()\n sock = self.ssl_context.wrap_socket(sock, server_side=True)\n sock.bind((self.host, self.port))\n sock.listen()\n return sock"}
{"repo":"requests","file":"tests/utils.py","line":6,"symbol":"override_environ","kind":"function","lang":"python","code":"def override_environ(**kwargs):\n save_env = dict(os.environ)\n for key, value in kwargs.items():\n if value is None:\n del os.environ[key]\n else:\n os.environ[key] = value\n try:\n yield\n finally:\n os.environ.clear()\n os.environ.update(save_env)"}