Showing preview only (613K chars total). Download the full file or copy to clipboard to get everything.
Repository: venaxyt/mysterium
Branch: main
Commit: a8cff3064319
Files: 68
Total size: 586.1 KB
Directory structure:
gitextract_heteqtr4/
├── LICENSE
├── README.md
├── executable/
│ └── pyinstxtractor.py
├── modules/
│ ├── blue.py
│ ├── dhooks.py
│ ├── fade.py
│ ├── getmac.py
│ ├── gratient.py
│ ├── json.py
│ ├── playsound.py
│ ├── pycenter.py
│ ├── pyfade.py
│ ├── pyproxies.py
│ ├── random.py
│ ├── re.py
│ ├── requests/
│ │ ├── __init__.py
│ │ ├── __version__.py
│ │ ├── _internal_utils.py
│ │ ├── adapters.py
│ │ ├── api.py
│ │ ├── auth.py
│ │ ├── certs.py
│ │ ├── compat.py
│ │ ├── cookies.py
│ │ ├── exceptions.py
│ │ ├── help.py
│ │ ├── hooks.py
│ │ ├── models.py
│ │ ├── packages.py
│ │ ├── sessions.py
│ │ ├── status_codes.py
│ │ ├── structures.py
│ │ └── utils.py
│ ├── tkinter/
│ │ ├── colorchooser.py
│ │ ├── commondialog.py
│ │ ├── constants.py
│ │ ├── dialog.py
│ │ ├── dnd.py
│ │ ├── filedialog.py
│ │ ├── font.py
│ │ ├── messagebox.py
│ │ ├── scrolledtext.py
│ │ ├── simpledialog.py
│ │ └── test/
│ │ ├── README
│ │ ├── runtktests.py
│ │ ├── support.py
│ │ └── test_tkinter/
│ │ ├── test_colorchooser.py
│ │ ├── test_font.py
│ │ ├── test_geometry_managers.py
│ │ ├── test_images.py
│ │ ├── test_loadtk.py
│ │ ├── test_misc.py
│ │ ├── test_simpledialog.py
│ │ ├── test_text.py
│ │ ├── test_variables.py
│ │ └── test_widgets.py
│ └── urllib3/
│ ├── connection.py
│ ├── connectionpool.py
│ └── contrib/
│ ├── _appengine_environ.py
│ ├── _securetransport/
│ │ ├── bindings.py
│ │ └── low_level.py
│ ├── appengine.py
│ ├── ntlmpool.py
│ ├── pyopenssl.py
│ ├── securetransport.py
│ └── socks.py
├── mysterium.py
└── requirements.txt
================================================
FILE CONTENTS
================================================
================================================
FILE: LICENSE
================================================
MIT License
Copyright (c) 2021 Venax
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
================================================
FILE: README.md
================================================
# **𝙈 𝙔 𝙎 𝙏 𝙀 𝙍 𝙄 𝙐 𝙈**

```
Mysterium has been entirely made by @venaxyt.
```
```
Mysterium usage:
- If the file to be inspect extension is ".py" or ".pyc": You only have to drag it into Mysterium.
- If the file to be inspect extension is ".exe": If you don't know how to decompile an executable Python file, so you can wait for next Mysterium updates.
- If the file to be inspect is obfuscated with Pyarmor: You put the Python file and the pytransform folder into a zip file, drag it into Mysterium and input the Python file name.
```

### **YouTube Tutorial (FR): https://www.youtube.com/watch?v=1idhXNeluCc**<br>
> ### **Contact me on Telegram if you want to buy my PyArmor complete decryption tool (200$): https://t.me/srevna**<br>
### **All I ask is that you don't contact me for nothing, I remind you that the tool is chargeable and that I don't provide anything until we've completed the transaction, too many people have ripped me off or wasted my time, whether it's for screenshots or anything else, so I don't do it again until payment has been made. Thank you for your understanding. (Because of this type of people: https://github.com/venaxyt/mysterium/blob/main/just%20an%20example.jpg)**<br>
### **VIDEO Tutorial (FR): https://www.youtube.com/watch?v=1idhXNeluCc**<br>
https://t.me/blatoise (The tool costs 200$) (!!Discounted to 150$ until the end of the year)<br>
> ## **V E N A X**
================================================
FILE: executable/pyinstxtractor.py
================================================
"""
PyInstaller Extractor v2.0 (Supports pyinstaller 4.6, 4.5.1, 4.5, 4.4, 4.3, 4.2, 4.1, 4.0, 3.6, 3.5, 3.4, 3.3, 3.2, 3.1, 3.0, 2.1, 2.0)
Author : Extreme Coders
E-mail : extremecoders(at)hotmail(dot)com
Web : https://0xec.blogspot.com
Date : 26-March-2020
Url : https://github.com/extremecoders-re/pyinstxtractor
For any suggestions, leave a comment on
https://forum.tuts4you.com/topic/34455-pyinstaller-extractor/
This script extracts a pyinstaller generated executable file.
Pyinstaller installation is not needed. The script has it all.
For best results, it is recommended to run this script in the
same version of python as was used to create the executable.
This is just to prevent unmarshalling errors(if any) while
extracting the PYZ archive.
Usage : Just copy this script to the directory where your exe resides
and run the script with the exe file name as a parameter
C:\path\to\exe\>python pyinstxtractor.py <filename>
$ /path/to/exe/python pyinstxtractor.py <filename>
Licensed under GNU General Public License (GPL) v3.
You are free to modify this source.
CHANGELOG
================================================
Version 1.1 (Jan 28, 2014)
-------------------------------------------------
- First Release
- Supports only pyinstaller 2.0
Version 1.2 (Sept 12, 2015)
-------------------------------------------------
- Added support for pyinstaller 2.1 and 3.0 dev
- Cleaned up code
- Script is now more verbose
- Executable extracted within a dedicated sub-directory
(Support for pyinstaller 3.0 dev is experimental)
Version 1.3 (Dec 12, 2015)
-------------------------------------------------
- Added support for pyinstaller 3.0 final
- Script is compatible with both python 2.x & 3.x (Thanks to Moritz Kroll @ Avira Operations GmbH & Co. KG)
Version 1.4 (Jan 19, 2016)
-------------------------------------------------
- Fixed a bug when writing pyc files >= version 3.3 (Thanks to Daniello Alto: https://github.com/Djamana)
Version 1.5 (March 1, 2016)
-------------------------------------------------
- Added support for pyinstaller 3.1 (Thanks to Berwyn Hoyt for reporting)
Version 1.6 (Sept 5, 2016)
-------------------------------------------------
- Added support for pyinstaller 3.2
- Extractor will use a random name while extracting unnamed files.
- For encrypted pyz archives it will dump the contents as is. Previously, the tool would fail.
Version 1.7 (March 13, 2017)
-------------------------------------------------
- Made the script compatible with python 2.6 (Thanks to Ross for reporting)
Version 1.8 (April 28, 2017)
-------------------------------------------------
- Support for sub-directories in .pyz files (Thanks to Moritz Kroll @ Avira Operations GmbH & Co. KG)
Version 1.9 (November 29, 2017)
-------------------------------------------------
- Added support for pyinstaller 3.3
- Display the scripts which are run at entry (Thanks to Michael Gillespie @ malwarehunterteam for the feature request)
Version 2.0 (March 26, 2020)
-------------------------------------------------
- Project migrated to github
- Supports pyinstaller 3.6
- Added support for Python 3.7, 3.8
- The header of all extracted pyc's are now automatically fixed
"""
from __future__ import print_function
import os
import struct
import marshal
import zlib
import sys
from uuid import uuid4 as uniquename
# imp is deprecated in Python3 in favour of importlib
if sys.version_info.major == 3:
from importlib.util import MAGIC_NUMBER
pyc_magic = MAGIC_NUMBER
else:
import imp
pyc_magic = imp.get_magic()
class CTOCEntry:
def __init__(self, position, cmprsdDataSize, uncmprsdDataSize, cmprsFlag, typeCmprsData, name):
self.position = position
self.cmprsdDataSize = cmprsdDataSize
self.uncmprsdDataSize = uncmprsdDataSize
self.cmprsFlag = cmprsFlag
self.typeCmprsData = typeCmprsData
self.name = name
class PyInstArchive:
PYINST20_COOKIE_SIZE = 24 # For pyinstaller 2.0
PYINST21_COOKIE_SIZE = 24 + 64 # For pyinstaller 2.1+
MAGIC = b'MEI\014\013\012\013\016' # Magic number which identifies pyinstaller
def __init__(self, path):
self.filePath = path
def open(self):
try:
self.fPtr = open(self.filePath, 'rb')
self.fileSize = os.stat(self.filePath).st_size
except:
print('[!] Error: Could not open {0}'.format(self.filePath))
return False
return True
def close(self):
try:
self.fPtr.close()
except:
pass
def checkFile(self):
print('[+] Processing {0}'.format(self.filePath))
searchChunkSize = 8192
endPos = self.fileSize
self.cookiePos = -1
if endPos < len(self.MAGIC):
print('[!] Error : File is too short or truncated')
return False
while True:
startPos = endPos - searchChunkSize if endPos >= searchChunkSize else 0
chunkSize = endPos - startPos
if chunkSize < len(self.MAGIC):
break
self.fPtr.seek(startPos, os.SEEK_SET)
data = self.fPtr.read(chunkSize)
offs = data.rfind(self.MAGIC)
if offs != -1:
self.cookiePos = startPos + offs
break
endPos = startPos + len(self.MAGIC) - 1
if startPos == 0:
break
if self.cookiePos == -1:
print('[!] Error : Missing cookie, unsupported pyinstaller version or not a pyinstaller archive')
return False
self.fPtr.seek(self.cookiePos + self.PYINST20_COOKIE_SIZE, os.SEEK_SET)
if b'python' in self.fPtr.read(64):
print('[+] Pyinstaller version: 2.1+')
self.pyinstVer = 21 # pyinstaller 2.1+
else:
self.pyinstVer = 20 # pyinstaller 2.0
print('[+] Pyinstaller version: 2.0')
return True
def getCArchiveInfo(self):
try:
if self.pyinstVer == 20:
self.fPtr.seek(self.cookiePos, os.SEEK_SET)
# Read CArchive cookie
(magic, lengthofPackage, toc, tocLen, self.pyver) = \
struct.unpack('!8siiii', self.fPtr.read(self.PYINST20_COOKIE_SIZE))
elif self.pyinstVer == 21:
self.fPtr.seek(self.cookiePos, os.SEEK_SET)
# Read CArchive cookie
(magic, lengthofPackage, toc, tocLen, self.pyver, pylibname) = \
struct.unpack('!8siiii64s', self.fPtr.read(self.PYINST21_COOKIE_SIZE))
except:
print('[!] Error : The file is not a pyinstaller archive')
return False
print('[+] Python version: {0}'.format(self.pyver))
# Additional data after the cookie
tailBytes = self.fileSize - self.cookiePos - (self.PYINST20_COOKIE_SIZE if self.pyinstVer == 20 else self.PYINST21_COOKIE_SIZE)
# Overlay is the data appended at the end of the PE
self.overlaySize = lengthofPackage + tailBytes
self.overlayPos = self.fileSize - self.overlaySize
self.tableOfContentsPos = self.overlayPos + toc
self.tableOfContentsSize = tocLen
print('[+] Length of package: {0} bytes'.format(lengthofPackage))
return True
def parseTOC(self):
# Go to the table of contents
self.fPtr.seek(self.tableOfContentsPos, os.SEEK_SET)
self.tocList = []
parsedLen = 0
# Parse table of contents
while parsedLen < self.tableOfContentsSize:
(entrySize, ) = struct.unpack('!i', self.fPtr.read(4))
nameLen = struct.calcsize('!iiiiBc')
(entryPos, cmprsdDataSize, uncmprsdDataSize, cmprsFlag, typeCmprsData, name) = \
struct.unpack( \
'!iiiBc{0}s'.format(entrySize - nameLen), \
self.fPtr.read(entrySize - 4))
name = name.decode('utf-8').rstrip('\0')
if len(name) == 0:
name = str(uniquename())
print('[!] Warning: Found an unamed file in CArchive. Using random name {0}'.format(name))
self.tocList.append( \
CTOCEntry( \
self.overlayPos + entryPos, \
cmprsdDataSize, \
uncmprsdDataSize, \
cmprsFlag, \
typeCmprsData, \
name \
))
parsedLen += entrySize
print('[+] Found {0} files in CArchive'.format(len(self.tocList)))
def _writeRawData(self, filepath, data):
nm = filepath.replace('\\', os.path.sep).replace('/', os.path.sep).replace('..', '__')
nmDir = os.path.dirname(nm)
if nmDir != '' and not os.path.exists(nmDir): # Check if path exists, create if not
os.makedirs(nmDir)
with open(nm, 'wb') as f:
f.write(data)
def extractFiles(self):
print('[+] Beginning extraction...please standby')
extractionDir = os.path.join(os.getcwd(), os.path.basename(self.filePath) + '_extracted')
if not os.path.exists(extractionDir):
os.mkdir(extractionDir)
os.chdir(extractionDir)
for entry in self.tocList:
basePath = os.path.dirname(entry.name)
if basePath != '':
# Check if path exists, create if not
if not os.path.exists(basePath):
os.makedirs(basePath)
self.fPtr.seek(entry.position, os.SEEK_SET)
data = self.fPtr.read(entry.cmprsdDataSize)
if entry.cmprsFlag == 1:
data = zlib.decompress(data)
# Malware may tamper with the uncompressed size
# Comment out the assertion in such a case
assert len(data) == entry.uncmprsdDataSize # Sanity Check
if entry.typeCmprsData == b's':
# s -> ARCHIVE_ITEM_PYSOURCE
# Entry point are expected to be python scripts
print('[+] Possible entry point: {0}.pyc'.format(entry.name))
self._writePyc(entry.name + '.pyc', data)
elif entry.typeCmprsData == b'M' or entry.typeCmprsData == b'm':
# M -> ARCHIVE_ITEM_PYPACKAGE
# m -> ARCHIVE_ITEM_PYMODULE
# packages and modules are pyc files with their header's intact
self._writeRawData(entry.name + '.pyc', data)
else:
self._writeRawData(entry.name, data)
if entry.typeCmprsData == b'z' or entry.typeCmprsData == b'Z':
self._extractPyz(entry.name)
def _writePyc(self, filename, data):
with open(filename, 'wb') as pycFile:
pycFile.write(pyc_magic) # pyc magic
if self.pyver >= 37: # PEP 552 -- Deterministic pycs
pycFile.write(b'\0' * 4) # Bitfield
pycFile.write(b'\0' * 8) # (Timestamp + size) || hash
else:
pycFile.write(b'\0' * 4) # Timestamp
if self.pyver >= 33:
pycFile.write(b'\0' * 4) # Size parameter added in Python 3.3
pycFile.write(data)
def _extractPyz(self, name):
dirName = name + '_extracted'
# Create a directory for the contents of the pyz
if not os.path.exists(dirName):
os.mkdir(dirName)
with open(name, 'rb') as f:
pyzMagic = f.read(4)
assert pyzMagic == b'PYZ\0' # Sanity Check
pycHeader = f.read(4) # Python magic value
# Skip PYZ extraction if not running under the same python version
if pyc_magic != pycHeader:
print('[!] Warning: This script is running in a different Python version than the one used to build the executable.')
print('[!] Please run this script in Python{0} to prevent extraction errors during unmarshalling'.format(self.pyver))
print('[!] Skipping pyz extraction')
return
(tocPosition, ) = struct.unpack('!i', f.read(4))
f.seek(tocPosition, os.SEEK_SET)
try:
toc = marshal.load(f)
except:
print('[!] Unmarshalling FAILED. Cannot extract {0}. Extracting remaining files.'.format(name))
return
print('[+] Found {0} files in PYZ archive'.format(len(toc)))
# From pyinstaller 3.1+ toc is a list of tuples
if type(toc) == list:
toc = dict(toc)
for key in toc.keys():
(ispkg, pos, length) = toc[key]
f.seek(pos, os.SEEK_SET)
fileName = key
try:
# for Python > 3.3 some keys are bytes object some are str object
fileName = fileName.decode('utf-8')
except:
pass
# Prevent writing outside dirName
fileName = fileName.replace('..', '__').replace('.', os.path.sep)
if ispkg == 1:
filePath = os.path.join(dirName, fileName, '__init__.pyc')
else:
filePath = os.path.join(dirName, fileName + '.pyc')
fileDir = os.path.dirname(filePath)
if not os.path.exists(fileDir):
os.makedirs(fileDir)
try:
data = f.read(length)
data = zlib.decompress(data)
except:
print('[!] Error: Failed to decompress {0}, probably encrypted. Extracting as is.'.format(filePath))
open(filePath + '.encrypted', 'wb').write(data)
else:
self._writePyc(filePath, data)
def main():
if len(sys.argv) < 2:
print('[+] Usage: pyinstxtractor.py <filename>')
else:
arch = PyInstArchive(sys.argv[1])
if arch.open():
if arch.checkFile():
if arch.getCArchiveInfo():
arch.parseTOC()
arch.extractFiles()
arch.close()
print('[+] Successfully extracted pyinstaller archive: {0}'.format(sys.argv[1]))
print('')
print('You can now use a python decompiler on the pyc files within the extracted directory')
return
arch.close()
if __name__ == '__main__':
main()
================================================
FILE: modules/blue.py
================================================
# Module created by @Bleu-No / Bleu#7728
from datetime import datetime
from colorama import Fore, Style
from re import search
from time import time
from inspect import getfullargspec
class Blue:
def __init__(self, filePath, fileName):
self.start = time()
self.fake_variables_array = ['printl']
self.logs = []
self.variables = {}
self.imports = {}
self.data = {}
self.init_ = 0
self.filePath = filePath
self.content = None
self.fileName = fileName
self.options = {
"bloque_request": False,
"save_logs": False,
"create_code": False
}
self.debug(f'{Fore.GREEN}INFO{Style.RESET_ALL}', 'Welcome to Blue Mysterium made by Bleu#7728 (v1.0) !')
self.settings()
print('\n\n')
self.debug(f'{Fore.GREEN}INFO{Style.RESET_ALL}', 'Starting debug...')
self.reading_file()
self.define_fake_variables_and_function({
"print": "printl"
})
self.execute_file()
self.finding_variables()
if self.options['save_logs'] == True:
self.save_logs()
if self.options['create_code'] == True:
self.create_source_code()
print('\n')
self.end = time()
self.debug(f'{Fore.BLUE}FINISH{Style.RESET_ALL}', f'Finish to debug file "{Fore.YELLOW}{self.fileName}{Style.RESET_ALL}" ! Time: {Fore.RED}{str(self.end - self.start)[slice(3)]}s{Style.RESET_ALL}.')
def add_logs(self, text):
if self.options['save_logs'] == False:
return
now = datetime.now().timetuple()
self.logs.append(
f'#SOURCE CODE [{now.tm_hour}:{now.tm_min}:{now.tm_sec}] {text}\n'
)
def debug(self, type, value, a=False) -> str:
now = datetime.now().timetuple()
return print(f'~{Fore.RED}{now.tm_hour}:{now.tm_min}:{now.tm_sec}{Style.RESET_ALL}{Fore.MAGENTA}~{Style.RESET_ALL} > {type} < {Fore.MAGENTA}<-->{Style.RESET_ALL} {Fore.YELLOW}{value}{Style.RESET_ALL}')
def question_options(self, text, option):
op = input(str(text)).lower()
if op in ["y", "n"]:
self.options[option] = True if op == "y" else False
else:
print(f'{Fore.RED}[ERROR] Invalid option !{Style.RESET_ALL}')
exit()
def settings(self):
self.question_options(
f'[{Fore.CYAN}QUESTION{Style.RESET_ALL}]{Fore.YELLOW} Do you want to block the requests? (Y/N) {Style.RESET_ALL}',
'bloque_request'
)
self.question_options(
f'[{Fore.CYAN}QUESTION{Style.RESET_ALL}]{Fore.YELLOW} Do you want to save the logs? (Y/N) {Style.RESET_ALL}',
'save_logs'
)
self.question_options(
f'[{Fore.CYAN}QUESTION{Style.RESET_ALL}]{Fore.YELLOW} Do you want the software to try to recreate the code? (Y/N) {Style.RESET_ALL}',
'create_code'
)
def reading_file(self):
self.debug(f'{Fore.GREEN}INFO{Style.RESET_ALL}', 'Opening and reading file...')
with open(self.filePath, 'rb') as f:
self.content = f.read().decode('latin-1')
f.close()
def define_fake_variables_and_function(self, v_name):
self.debug(f'{Fore.GREEN}INFO{Style.RESET_ALL}', 'Defining fake variables and functions...')
fake_variables = "";
for name in v_name:
fake_variables += f'{name}={v_name[name]};'
self.content = f'{fake_variables}\n\n{self.content}';
def finding_variables(self):
print("\n")
for name in self.variables:
if "<function" in str(self.variables[name]):
name_function_s = search(r"^<(function) ([a-zA-Z0-9]*) (at) ([a-zA-Z0-9]*)>$", str(self.variables[name]))
name_function = name_function_s.group(2)
code_function = name_function_s.group(4)
if name_function in self.fake_variables_array:
continue
self.data[self.init_] = {
'type': 'function',
'data': {
'name': name_function,
'code': code_function,
}
}
self.init_ += 1
self.debug(f'{Fore.RED}DEBUG{Style.RESET_ALL}', f'{Fore.CYAN}VARIABLE_FUNCTION{Style.RESET_ALL}: {str(self.variables[name])} || {Fore.LIGHTMAGENTA_EX}NAME{Style.RESET_ALL}: {name}')
self.add_logs(f'VARIABLE_FUNCTION: {str(self.variables[name])} || NAME: {name}\ndef {name}():\n\treturn')
elif "<module" in str(self.variables[name]):
match_import = search(r"^<(module) '([a-zA-Z0-9]*)' (from) '([a-zA-Z0-9:\\.]*)'>$", str(self.variables[name]))
name_import = match_import.group(2)
path_import = match_import.group(4)
self.debug(f'{Fore.RED}DEBUG{Style.RESET_ALL}', f'{Fore.CYAN}IMPORT_FUNCTION{Style.RESET_ALL}: {name_import} || {Fore.LIGHTMAGENTA_EX}PATH{Style.RESET_ALL}: {path_import}')
self.add_logs(f'IMPORT_FUNCTION: {name_import} || PATH: {path_import}\nimport {name_import}')
self.imports[name_import] = path_import
else:
content_variable = str(f'{str(self.variables[name])[slice(4)]}... ({len(str(self.variables[name]))-4} characters)').replace("\n", "")
if type(self.variables[name]) is bool or type(self.variables[name]) is int or type(self.variables[name]) is list:
self.add_logs(f'VARIABLE: {name} || CODE: {name} = "{content_variable}"; || VALUE: {content_variable}\n{name} = {self.variables[name]};')
elif type(self.variables[name]) is str:
if len(self.variables[name]) > 10:
self.add_logs(f'VARIABLE: {name} || CODE: {name} = "{content_variable}"; || VALUE: {content_variable}\n{name} = """{self.variables[name]}""";')
else:
self.add_logs(f'VARIABLE: {name} || CODE: {name} = "{content_variable}"; || VALUE: {content_variable}\n{name} = "{self.variables[name]}";')
else:
self.add_logs(f'VARIABLE: {name} || CODE: {name} = "{content_variable}"; || VALUE: {content_variable}\n{name} = "{self.variables[name]}";')
self.data[self.init_] = {
'type': 'variable',
'data': {
'name': name,
'content': self.variables[name],
}
}
self.init_ += 1
self.debug(f'{Fore.RED}DEBUG{Style.RESET_ALL}', f'{Fore.CYAN}VARIABLE{Style.RESET_ALL}: {name} || {Fore.LIGHTMAGENTA_EX}CODE{Style.RESET_ALL}: {name} = "{content_variable}"; || {Fore.GREEN}VALUE{Style.RESET_ALL}: {content_variable}', True)
def execute_file(self):
self.debug(f'{Fore.GREEN}INFO{Style.RESET_ALL}', 'Executing file and loading functions...')
self.debug(f'{Fore.LIGHTYELLOW_EX}MODULE{Style.RESET_ALL}', 'Loading simple function...')
global printl
def printl(text):
self.add_logs(f'FAKE_FUNCTION: print || CODE: print("{text}"); || VALUE: {text}\nprint("{text}");')
self.data[self.init_] = {'type': 'fake_function','data': {'code': f'print("{text}");'}}
self.init_ += 1
return self.debug(f'{Fore.RED}DEBUG{Style.RESET_ALL}', f'{Fore.CYAN}FAKE_FUNCTION{Style.RESET_ALL}: print || {Fore.LIGHTMAGENTA_EX}CODE{Style.RESET_ALL}: print("{text}"); || {Fore.GREEN}VALUE{Style.RESET_ALL}: {text}')
print('\n\n')
exec(self.content, globals(), self.variables)
def save_logs(self):
print('\n')
self.debug(f'{Fore.MAGENTA}LOGS{Style.RESET_ALL}', f'Saving logs... ( {len(self.logs)} log(s) )')
with open(f'{self.fileName}_logs_{time()}.py', 'w') as f:
for name in self.logs:
f.write(f'{name}\n')
f.close()
def create_source_code(self):
with open(f'{self.fileName}_debug.py', 'w') as f:
for name_import in self.imports:
f.write(f'import {name_import}\n')
f.write('\n')
for x in self.data:
if self.data[x]['type'] == 'function':
print(getfullargspec(self.data[x]["data"]["name"]))
f.write(f'def {str(self.data[x]["data"]["name"])}(): \n\treturn\n\n')
elif self.data[x]['type'] == 'variable':
if type(self.data[x]['data']['content']) is str:
if len(self.data[x]['data']['content']) > 10:
f.write(f'{self.data[x]["data"]["name"]} = """{self.data[x]["data"]["content"]}""";\n')
else:
f.write(f"{self.data[x]['data']['name']} = \"{self.data[x]['data']['content']}\";\n")
elif type(self.data[x]['data']['content']) is bool or type(self.data[x]['data']['content']) is int or type(self.data[x]['data']['content']) is list:
f.write(f"{self.data[x]['data']['name']} = {self.data[x]['data']['content']};\n")
else:
f.write(f"{self.data[x]['data']['name']} = \"{self.data[x]['data']['content']}\";\n")
elif self.data[x]['type'] == "fake_function":
f.write(f'{self.data[x]["data"]["code"]}\n\n')
================================================
FILE: modules/dhooks.py
================================================
print("import dhooks")
class Webhook:
def __init__(self, url, **kwargs):
print("from dhooks import Webhook")
print(f'webhook = dhooks.Webhook(url="{url}")')
def send(self, content: str = "", **kwargs):
print(f'webhook.send(content="{content}")')
def modify(self, name, **kwargs):
print(f'webhook.modify(name="{name}")')
def get_info(self):
print("webhook.get_info()")
return ""
def close(self):
print("webhook.close()")
def delete(self):
print("webhook.delete()")
================================================
FILE: modules/fade.py
================================================
print("import fade")
def blackwhite(text):
print(f'fade.blackwhite(text="{text}")')
return text
def purplepink(text):
print(f'fade.purplepink(text="{text}")')
return text
def greenblue(text):
print(f'fade.greenblue(text="{text}")')
return text
def pinkred(text):
print(f'fade.pinkred(text="{text}")')
return text
def purpleblue(text):
print(f'fade.purpleblue(text="{text}")')
return text
def water(text):
print(f'fade.water(text="{text}")')
return text
def fire(text):
print(f'fade.fire(text="{text}")')
return text
def brazil(text):
print(f'fade.brazil(text="{text}")')
return text
def random(text):
print(f'fade.random(text="{text}")')
return text
================================================
FILE: modules/getmac.py
================================================
print("import getmac")
def get_mac_address(interface=None, ip=None, ip6=None, hostname=None, network_request=True):
get_mac_address_content = f"{f'interface={interface}' if interface else ''}{f', ip={ip}' if ip else ''}{f', ip6={ip6}' if ip6 else ''}{f', hostname={hostname}' if hostname else ''}{f', network_request={network_request}' if network_request and not network_request == True else ''}"
print(f'getmac.get_mac_address({get_mac_address_content})')
return "00:00:00:00:00:00"
================================================
FILE: modules/gratient.py
================================================
print("import gratient")
def black(text):
print(f'gratient.black(text="{text}")')
return text
def green(text):
print(f'gratient.green(text="{text}")')
return text
def blue(text):
print(f'gratient.blue(text="{text}")')
return text
def purple(text):
print(f'gratient.purple(text="{text}")')
return text
def yellow(text):
print(f'gratient.yellow(text="{text}")')
return text
def red(text):
print(f'gratient.red(text="{text}")')
return text
================================================
FILE: modules/json.py
================================================
print("import json")
def dump(obj, fp=False, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw):
dump_content = f"{f'obj={obj}' if obj else ''}{f', fp={fp}' if fp else ''}{f', skipkeys={skipkeys}' if skipkeys else ''}{f', ensure_ascii={ensure_ascii}' if ensure_ascii and not ensure_ascii == True else ''}{f', check_circular={check_circular}' if check_circular and not check_circular == True else ''}{f', allow_nan={allow_nan}' if allow_nan and not allow_nan == True else ''}{f', cls={cls}' if cls else ''}{f', indent={indent}' if indent else ''}{f', separators={separators}' if separators else ''}{f', default={default}' if default else ''}"
print(f"json.dump({dump_content})")
return ""
def dumps(obj, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw):
dumps_content = f"{f'obj={obj}' if obj else ''}{f', skipkeys={skipkeys}' if skipkeys else ''}{f', ensure_ascii={ensure_ascii}' if ensure_ascii and not ensure_ascii == True else ''}{f', check_circular={check_circular}' if check_circular and not check_circular == True else ''}{f', allow_nan={allow_nan}' if allow_nan and not allow_nan == True else ''}{f', cls={cls}' if cls else ''}{f', indent={indent}' if indent else ''}{f', separators={separators}' if separators else ''}{f', default={default}' if default else ''}"
print(f"json.dumps({dumps_content})")
return ""
def detect_encoding(b):
print(f"json.detect_encoding(b={b})")
return ""
def load(fp, *, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw):
load_content = f"{f'fp={fp}' if fp else ''}{f', cls={cls}' if cls else ''}{f', object_hook={object_hook}' if object_hook else ''}{f', parse_float={parse_float}' if parse_float else ''}{f', parse_int={parse_int}' if parse_int else ''}{f', parse_constant={parse_constant}' if parse_constant else ''}{f', object_pairs_hook={object_pairs_hook}' if object_pairs_hook else ''}"
print(f"json.load({load_content})")
return ""
def loads(s, *, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw):
loads_content = f"{f's={s}' if s else ''}{f', cls={cls}' if cls else ''}{f', object_hook={object_hook}' if object_hook else ''}{f', parse_float={parse_float}' if parse_float else ''}{f', parse_int={parse_int}' if parse_int else ''}{f', parse_constant={parse_constant}' if parse_constant else ''}{f', object_pairs_hook={object_pairs_hook}' if object_pairs_hook else ''}"
print(f"json.load({loads_content})")
return ""
================================================
FILE: modules/playsound.py
================================================
print("import playsound")
def playsound(sound, block=True):
sound = f'"{sound}"'
print(f"playsound.playsound({sound}{f', block={block}' if block else ''})")
================================================
FILE: modules/pycenter.py
================================================
print("import pycenter")
def center(var: str, space: int = None, icon: str = "", sep: bool = False):
center_content = f"{f'var={var}' if var else ''}{f', space={space}' if space else ''}{f', icon={icon}' if icon else ''}{f', sep={sep}' if sep else ''}"
print(f'pycenter.center("{center_content}")')
return var
def makebox(content: str):
print(f'pycenter.makebox("{content}")')
return content
================================================
FILE: modules/pyfade.py
================================================
print("import pyfade")
def init():
print("pyfade.init()")
def ditto(text):
return f'"{text}"'
class Fade:
def check(line):
print(f'Fade.check(line="{line}")')
return False
def Vertical(color, text: str, speed: int = 1, start: int = 0, stop: int = 0):
vertical_content = f"{f'color={color}' if color else ''}{f', text={ditto(text)}' if text else ''}{f', speed={speed}' if speed and not speed == 1 else ''}{f', start={start}' if start and not start == 0 else ''}{f', stop={stop}' if stop and not stop == 0 else ''}"
print(f"Fade.Vertical({vertical_content})")
return text
def Horizontal(color, text: str, speed: int = 1, start: int = 0, stop: int = 0):
horizontal_content = f"{f'color={color}' if color else ''}{f', text={ditto(text)}' if text else ''}{f', speed={speed}' if speed and not speed == 1 else ''}{f', start={start}' if start and not start == 0 else ''}{f', stop={stop}' if stop and not stop == 0 else ''}"
print(f"Fade.Horizontal({horizontal_content})")
return text
def Diagonal(color, text: str, speed: int = 1, start: int = 0, stop: int = 0):
diagonal_content = f"{f'color={color}' if color else ''}{f', text={ditto(text)}' if text else ''}{f', speed={speed}' if speed and not speed == 1 else ''}{f', start={start}' if start and not start == 0 else ''}{f', stop={stop}' if stop and not stop == 0 else ''}"
print(f"Fade.diagonal({diagonal_content})")
return text
class Colors:
black_to_white = ["m;m;m"]
black_to_red = ["m;0;0"]
black_to_green = ["0;m;0"]
black_to_blue = ["0;0;m"]
white_to_black = ["n;n;n"]
white_to_red = ["255;n;n"]
white_to_green = ["n;255;n"]
white_to_blue = ["n;n;255"]
red_to_black = ["n;0;0"]
red_to_white = ["255;m;m"]
red_to_yellow = ["255;m;0"]
red_to_purple = ["255;0;m"]
green_to_black = ["0;n;0"]
green_to_white = ["m;255;m"]
green_to_yellow = ["m;255;0"]
green_to_cyan = ["0;255;m"]
blue_to_black = ["0;0;n"]
blue_to_white = ["m;m;255"]
blue_to_cyan = ["0;m;255"]
blue_to_purple = ["m;0;255"]
yellow_to_red = ["255;n;0"]
yellow_to_green = ["n;255;0"]
purple_to_red = ["255;0;n"]
purple_to_blue = ["n;0;255"]
cyan_to_green = ["0;255;n"]
cyan_to_blue = ["0;n;255"]
================================================
FILE: modules/pyproxies.py
================================================
print("import pyproxies")
def proxy(server, timeout = 5):
print(f'pyproxies.proxy(server="{server}"{f", timeout={timeout}" if timeout and not timeout == 5 else ""})')
return {"https": f"http://198.162.1.1:8080"}
================================================
FILE: modules/random.py
================================================
print("import random")
class Random:
def randbytes(n):
print(f"random.randbytes({n})")
return 0
def randrange(start, stop=None, step=1):
randrange_content = f"{f'start={start}' if start else ''}{f', stop={stop}' if stop else ''}{f', step={step}' if step and not step == 1 else ''}"
print(f"random.randrange({randrange_content})")
return 0
def randint(a, b):
print(f"random.randint(a={a}, b={b})")
return 0
def choice(seq):
print(f"random.choice(seq={seq})")
return 0
def gauss(mu, sigma):
print(f"random.gauss(mu={mu}, sigma={sigma})")
return 0
def random():
print("random.random()")
return 0
def getrandbits(k):
print(f"random.getrandbits(k={k})")
return 0
================================================
FILE: modules/re.py
================================================
print("import re")
def findall(pattern, string, flags=0):
print(f"re.findall({pattern}, {string})")
return ""
def split(pattern, string, maxsplit=0, flags=0):
print(f"re.split({pattern}, {string})")
return ""
def subn(pattern, repl, string, count=0, flags=0):
print(f"re.subn({pattern}, {repl}, {string})")
return ""
def sub(pattern, repl, string, count=0, flags=0):
print(f"re.sub({pattern}, {repl}, {string})")
return ""
def search(pattern, string, flags=0):
print(f"re.search({pattern}, {string})")
return ""
def fullmatch(pattern, string, flags=0):
print(f"re.fullmatch({pattern}, {string})")
return None
def match(pattern, string, flags=0):
print(f"re.match({pattern}, {string})")
return None
def finditer(pattern, string, flags=0):
print(f"re.finditer({pattern}, {string})")
return ""
def purge():
print("re.purge()")
return ""
def template(pattern, flags=0):
print(f"re.template({pattern})")
return ""
def escape(pattern):
print(f"re.escape({pattern})")
return ""
def compile(pattern, flags=0):
pattern = ""
return ""
ASCII = ""
IGNORECASE = ""
LOCALE = ""
UNICODE = ""
MULTILINE = ""
DOTALL = ""
VERBOSE = ""
TEMPLATE = ""
DEBUG = ""
print("import re")
def findall(pattern, string, flags=0):
print(f"re.findall({pattern}, {string})")
return ""
def split(pattern, string, maxsplit=0, flags=0):
print(f"re.split({pattern}, {string})")
return ""
def subn(pattern, repl, string, count=0, flags=0):
print(f"re.subn({pattern}, {repl}, {string})")
return ""
def sub(pattern, repl, string, count=0, flags=0):
print(f"re.sub({pattern}, {repl}, {string})")
return ""
def search(pattern, string, flags=0):
print(f"re.search({pattern}, {string})")
return ""
def fullmatch(pattern, string, flags=0):
print(f"re.fullmatch({pattern}, {string})")
return None
def match(pattern, string, flags=0):
print(f"re.match({pattern}, {string})")
return None
def finditer(pattern, string, flags=0):
print(f"re.finditer({pattern}, {string})")
return ""
def purge():
print("re.purge()")
return ""
def template(pattern, flags=0):
print(f"re.template({pattern})")
return ""
def escape(pattern):
print(f"re.escape({pattern})")
return ""
def compile(pattern, flags=0):
pattern = ""
return ""
ASCII = ""
IGNORECASE = ""
LOCALE = ""
UNICODE = ""
MULTILINE = ""
DOTALL = ""
VERBOSE = ""
TEMPLATE = ""
DEBUG = ""
================================================
FILE: modules/requests/__init__.py
================================================
print("import requests")
class Session:
pass
def get(url=False, auth=None, json=False, data=False, hooks=None, files=False, params=False, proxies=False, headers=False, timeout=False, encoding=False, allow_redirects=True):
url = f'"{url}"'
request_content = f"{f'url={url}'}{f', auth={auth}' if auth else ''}{f', json={json}' if json else ''}{f', data={data}' if data else ''}{f', hooks={hooks}' if hooks else ''}{f', files={files}' if files else ''}{f', params={params}' if params else ''}{f', proxies={proxies}' if proxies else ''}{f', headers={headers}' if headers else ''}{f', timeout={timeout}' if timeout else ''}{f', encoding={encoding}' if encoding else ''}{f', allow_redirects={allow_redirects}' if allow_redirects and not allow_redirects == True else ''}"
print(f"requests.get({request_content})")
class fake_response:
text = ""
json = ""
content = ""
cookies = ""
headers = ""
status_code = 200
return fake_response
def post(url=False, auth=None, json=False, data=False, hooks=None, files=False, params=False, proxies=False, headers=False, timeout=False, encoding=False, allow_redirects=True):
url = f'"{url}"'
request_content = f"{f'url={url}'}{f', auth={auth}' if auth else ''}{f', json={json}' if json else ''}{f', data={data}' if data else ''}{f', hooks={hooks}' if hooks else ''}{f', files={files}' if files else ''}{f', params={params}' if params else ''}{f', proxies={proxies}' if proxies else ''}{f', headers={headers}' if headers else ''}{f', timeout={timeout}' if timeout else ''}{f', encoding={encoding}' if encoding else ''}{f', allow_redirects={allow_redirects}' if allow_redirects and not allow_redirects == True else ''}"
print(f"requests.post({request_content})")
class fake_response:
text = ""
json = ""
content = ""
cookies = ""
headers = ""
status_code = 200
return fake_response
def patch(url=False, auth=None, json=False, data=False, hooks=None, files=False, params=False, proxies=False, headers=False, timeout=False, encoding=False, allow_redirects=True):
url = f'"{url}"'
request_content = f"{f'url={url}'}{f', auth={auth}' if auth else ''}{f', json={json}' if json else ''}{f', data={data}' if data else ''}{f', hooks={hooks}' if hooks else ''}{f', files={files}' if files else ''}{f', params={params}' if params else ''}{f', proxies={proxies}' if proxies else ''}{f', headers={headers}' if headers else ''}{f', timeout={timeout}' if timeout else ''}{f', encoding={encoding}' if encoding else ''}{f', allow_redirects={allow_redirects}' if allow_redirects and not allow_redirects == True else ''}"
print(f"requests.patch({request_content})")
class fake_response:
text = ""
json = ""
content = ""
cookies = ""
headers = ""
status_code = 200
return fake_response
def delete(url=False, auth=None, json=False, data=False, hooks=None, files=False, params=False, proxies=False, headers=False, timeout=False, encoding=False, allow_redirects=True):
url = f'"{url}"'
request_content = f"{f'url={url}'}{f', auth={auth}' if auth else ''}{f', json={json}' if json else ''}{f', data={data}' if data else ''}{f', hooks={hooks}' if hooks else ''}{f', files={files}' if files else ''}{f', params={params}' if params else ''}{f', proxies={proxies}' if proxies else ''}{f', headers={headers}' if headers else ''}{f', timeout={timeout}' if timeout else ''}{f', encoding={encoding}' if encoding else ''}{f', allow_redirects={allow_redirects}' if allow_redirects and not allow_redirects == True else ''}"
print(f"requests.delete({request_content})")
class fake_response:
text = ""
json = ""
content = ""
cookies = ""
headers = ""
status_code = 200
return fake_response
================================================
FILE: modules/requests/__version__.py
================================================
# .-. .-. .-. . . .-. .-. .-. .-.
# |( |- |.| | | |- `-. | `-.
# ' ' `-' `-`.`-' `-' `-' ' `-'
__title__ = 'requests'
__description__ = 'Python HTTP for Humans.'
__url__ = 'https://requests.readthedocs.io'
__version__ = '2.26.0'
__build__ = 0x022600
__author__ = 'Kenneth Reitz'
__author_email__ = 'me@kennethreitz.org'
__license__ = 'Apache 2.0'
__copyright__ = 'Copyright 2020 Kenneth Reitz'
__cake__ = u'\u2728 \U0001f370 \u2728'
================================================
FILE: modules/requests/_internal_utils.py
================================================
# -*- coding: utf-8 -*-
"""
requests._internal_utils
~~~~~~~~~~~~~~
Provides utility functions that are consumed internally by Requests
which depend on extremely few external helpers (such as compat)
"""
from .compat import is_py2, builtin_str, str
def to_native_string(string, encoding='ascii'):
"""Given a string object, regardless of type, returns a representation of
that string in the native string type, encoding and decoding where
necessary. This assumes ASCII unless told otherwise.
"""
if isinstance(string, builtin_str):
out = string
else:
if is_py2:
out = string.encode(encoding)
else:
out = string.decode(encoding)
return out
def unicode_is_ascii(u_string):
"""Determine if unicode string only contains ASCII characters.
:param str u_string: unicode string to check. Must be unicode
and not Python 2 `str`.
:rtype: bool
"""
assert isinstance(u_string, str)
try:
u_string.encode('ascii')
return True
except UnicodeEncodeError:
return False
================================================
FILE: modules/requests/adapters.py
================================================
# -*- coding: utf-8 -*-
"""
requests.adapters
~~~~~~~~~~~~~~~~~
This module contains the transport adapters that Requests uses to define
and maintain connections.
"""
import os.path
import socket
from urllib3.poolmanager import PoolManager, proxy_from_url
from urllib3.response import HTTPResponse
from urllib3.util import parse_url
from urllib3.util import Timeout as TimeoutSauce
from urllib3.util.retry import Retry
from urllib3.exceptions import ClosedPoolError
from urllib3.exceptions import ConnectTimeoutError
from urllib3.exceptions import HTTPError as _HTTPError
from urllib3.exceptions import MaxRetryError
from urllib3.exceptions import NewConnectionError
from urllib3.exceptions import ProxyError as _ProxyError
from urllib3.exceptions import ProtocolError
from urllib3.exceptions import ReadTimeoutError
from urllib3.exceptions import SSLError as _SSLError
from urllib3.exceptions import ResponseError
from urllib3.exceptions import LocationValueError
from .models import Response
from .compat import urlparse, basestring
from .utils import (DEFAULT_CA_BUNDLE_PATH, extract_zipped_paths,
get_encoding_from_headers, prepend_scheme_if_needed,
get_auth_from_url, urldefragauth, select_proxy)
from .structures import CaseInsensitiveDict
from .cookies import extract_cookies_to_jar
from .exceptions import (ConnectionError, ConnectTimeout, ReadTimeout, SSLError,
ProxyError, RetryError, InvalidSchema, InvalidProxyURL,
InvalidURL)
from .auth import _basic_auth_str
try:
from urllib3.contrib.socks import SOCKSProxyManager
except ImportError:
def SOCKSProxyManager(*args, **kwargs):
raise InvalidSchema("Missing dependencies for SOCKS support.")
DEFAULT_POOLBLOCK = False
DEFAULT_POOLSIZE = 10
DEFAULT_RETRIES = 0
DEFAULT_POOL_TIMEOUT = None
class BaseAdapter(object):
"""The Base Transport Adapter"""
def __init__(self):
super(BaseAdapter, self).__init__()
def send(self, request, stream=False, timeout=None, verify=True,
cert=None, proxies=None):
"""Sends PreparedRequest object. Returns Response object.
:param request: The :class:`PreparedRequest <PreparedRequest>` being sent.
:param stream: (optional) Whether to stream the request content.
:param timeout: (optional) How long to wait for the server to send
data before giving up, as a float, or a :ref:`(connect timeout,
read timeout) <timeouts>` tuple.
:type timeout: float or tuple
:param verify: (optional) Either a boolean, in which case it controls whether we verify
the server's TLS certificate, or a string, in which case it must be a path
to a CA bundle to use
:param cert: (optional) Any user-provided SSL certificate to be trusted.
:param proxies: (optional) The proxies dictionary to apply to the request.
"""
raise NotImplementedError
def close(self):
"""Cleans up adapter specific items."""
raise NotImplementedError
class HTTPAdapter(BaseAdapter):
"""The built-in HTTP Adapter for urllib3.
Provides a general-case interface for Requests sessions to contact HTTP and
HTTPS urls by implementing the Transport Adapter interface. This class will
usually be created by the :class:`Session <Session>` class under the
covers.
:param pool_connections: The number of urllib3 connection pools to cache.
:param pool_maxsize: The maximum number of connections to save in the pool.
:param max_retries: The maximum number of retries each connection
should attempt. Note, this applies only to failed DNS lookups, socket
connections and connection timeouts, never to requests where data has
made it to the server. By default, Requests does not retry failed
connections. If you need granular control over the conditions under
which we retry a request, import urllib3's ``Retry`` class and pass
that instead.
:param pool_block: Whether the connection pool should block for connections.
Usage::
>>> import requests
>>> s = requests.Session()
>>> a = requests.adapters.HTTPAdapter(max_retries=3)
>>> s.mount('http://', a)
"""
__attrs__ = ['max_retries', 'config', '_pool_connections', '_pool_maxsize',
'_pool_block']
def __init__(self, pool_connections=DEFAULT_POOLSIZE,
pool_maxsize=DEFAULT_POOLSIZE, max_retries=DEFAULT_RETRIES,
pool_block=DEFAULT_POOLBLOCK):
if max_retries == DEFAULT_RETRIES:
self.max_retries = Retry(0, read=False)
else:
self.max_retries = Retry.from_int(max_retries)
self.config = {}
self.proxy_manager = {}
super(HTTPAdapter, self).__init__()
self._pool_connections = pool_connections
self._pool_maxsize = pool_maxsize
self._pool_block = pool_block
self.init_poolmanager(pool_connections, pool_maxsize, block=pool_block)
def __getstate__(self):
return {attr: getattr(self, attr, None) for attr in self.__attrs__}
def __setstate__(self, state):
# Can't handle by adding 'proxy_manager' to self.__attrs__ because
# self.poolmanager uses a lambda function, which isn't pickleable.
self.proxy_manager = {}
self.config = {}
for attr, value in state.items():
setattr(self, attr, value)
self.init_poolmanager(self._pool_connections, self._pool_maxsize,
block=self._pool_block)
def init_poolmanager(self, connections, maxsize, block=DEFAULT_POOLBLOCK, **pool_kwargs):
"""Initializes a urllib3 PoolManager.
This method should not be called from user code, and is only
exposed for use when subclassing the
:class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
:param connections: The number of urllib3 connection pools to cache.
:param maxsize: The maximum number of connections to save in the pool.
:param block: Block when no free connections are available.
:param pool_kwargs: Extra keyword arguments used to initialize the Pool Manager.
"""
# save these values for pickling
self._pool_connections = connections
self._pool_maxsize = maxsize
self._pool_block = block
self.poolmanager = PoolManager(num_pools=connections, maxsize=maxsize,
block=block, strict=True, **pool_kwargs)
def proxy_manager_for(self, proxy, **proxy_kwargs):
"""Return urllib3 ProxyManager for the given proxy.
This method should not be called from user code, and is only
exposed for use when subclassing the
:class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
:param proxy: The proxy to return a urllib3 ProxyManager for.
:param proxy_kwargs: Extra keyword arguments used to configure the Proxy Manager.
:returns: ProxyManager
:rtype: urllib3.ProxyManager
"""
if proxy in self.proxy_manager:
manager = self.proxy_manager[proxy]
elif proxy.lower().startswith('socks'):
username, password = get_auth_from_url(proxy)
manager = self.proxy_manager[proxy] = SOCKSProxyManager(
proxy,
username=username,
password=password,
num_pools=self._pool_connections,
maxsize=self._pool_maxsize,
block=self._pool_block,
**proxy_kwargs
)
else:
proxy_headers = self.proxy_headers(proxy)
manager = self.proxy_manager[proxy] = proxy_from_url(
proxy,
proxy_headers=proxy_headers,
num_pools=self._pool_connections,
maxsize=self._pool_maxsize,
block=self._pool_block,
**proxy_kwargs)
return manager
def cert_verify(self, conn, url, verify, cert):
"""Verify a SSL certificate. This method should not be called from user
code, and is only exposed for use when subclassing the
:class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
:param conn: The urllib3 connection object associated with the cert.
:param url: The requested URL.
:param verify: Either a boolean, in which case it controls whether we verify
the server's TLS certificate, or a string, in which case it must be a path
to a CA bundle to use
:param cert: The SSL certificate to verify.
"""
if url.lower().startswith('https') and verify:
cert_loc = None
# Allow self-specified cert location.
if verify is not True:
cert_loc = verify
if not cert_loc:
cert_loc = extract_zipped_paths(DEFAULT_CA_BUNDLE_PATH)
if not cert_loc or not os.path.exists(cert_loc):
raise IOError("Could not find a suitable TLS CA certificate bundle, "
"invalid path: {}".format(cert_loc))
conn.cert_reqs = 'CERT_REQUIRED'
if not os.path.isdir(cert_loc):
conn.ca_certs = cert_loc
else:
conn.ca_cert_dir = cert_loc
else:
conn.cert_reqs = 'CERT_NONE'
conn.ca_certs = None
conn.ca_cert_dir = None
if cert:
if not isinstance(cert, basestring):
conn.cert_file = cert[0]
conn.key_file = cert[1]
else:
conn.cert_file = cert
conn.key_file = None
if conn.cert_file and not os.path.exists(conn.cert_file):
raise IOError("Could not find the TLS certificate file, "
"invalid path: {}".format(conn.cert_file))
if conn.key_file and not os.path.exists(conn.key_file):
raise IOError("Could not find the TLS key file, "
"invalid path: {}".format(conn.key_file))
def build_response(self, req, resp):
"""Builds a :class:`Response <requests.Response>` object from a urllib3
response. This should not be called from user code, and is only exposed
for use when subclassing the
:class:`HTTPAdapter <requests.adapters.HTTPAdapter>`
:param req: The :class:`PreparedRequest <PreparedRequest>` used to generate the response.
:param resp: The urllib3 response object.
:rtype: requests.Response
"""
response = Response()
# Fallback to None if there's no status_code, for whatever reason.
response.status_code = getattr(resp, 'status', None)
# Make headers case-insensitive.
response.headers = CaseInsensitiveDict(getattr(resp, 'headers', {}))
# Set encoding.
response.encoding = get_encoding_from_headers(response.headers)
response.raw = resp
response.reason = response.raw.reason
if isinstance(req.url, bytes):
response.url = req.url.decode('utf-8')
else:
response.url = req.url
# Add new cookies from the server.
extract_cookies_to_jar(response.cookies, req, resp)
# Give the Response some context.
response.request = req
response.connection = self
return response
def get_connection(self, url, proxies=None):
"""Returns a urllib3 connection for the given URL. This should not be
called from user code, and is only exposed for use when subclassing the
:class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
:param url: The URL to connect to.
:param proxies: (optional) A Requests-style dictionary of proxies used on this request.
:rtype: urllib3.ConnectionPool
"""
proxy = select_proxy(url, proxies)
if proxy:
proxy = prepend_scheme_if_needed(proxy, 'http')
proxy_url = parse_url(proxy)
if not proxy_url.host:
raise InvalidProxyURL("Please check proxy URL. It is malformed"
" and could be missing the host.")
proxy_manager = self.proxy_manager_for(proxy)
conn = proxy_manager.connection_from_url(url)
else:
# Only scheme should be lower case
parsed = urlparse(url)
url = parsed.geturl()
conn = self.poolmanager.connection_from_url(url)
return conn
def close(self):
"""Disposes of any internal state.
Currently, this closes the PoolManager and any active ProxyManager,
which closes any pooled connections.
"""
self.poolmanager.clear()
for proxy in self.proxy_manager.values():
proxy.clear()
def request_url(self, request, proxies):
"""Obtain the url to use when making the final request.
If the message is being sent through a HTTP proxy, the full URL has to
be used. Otherwise, we should only use the path portion of the URL.
This should not be called from user code, and is only exposed for use
when subclassing the
:class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
:param request: The :class:`PreparedRequest <PreparedRequest>` being sent.
:param proxies: A dictionary of schemes or schemes and hosts to proxy URLs.
:rtype: str
"""
proxy = select_proxy(request.url, proxies)
scheme = urlparse(request.url).scheme
is_proxied_http_request = (proxy and scheme != 'https')
using_socks_proxy = False
if proxy:
proxy_scheme = urlparse(proxy).scheme.lower()
using_socks_proxy = proxy_scheme.startswith('socks')
url = request.path_url
if is_proxied_http_request and not using_socks_proxy:
url = urldefragauth(request.url)
return url
def add_headers(self, request, **kwargs):
"""Add any headers needed by the connection. As of v2.0 this does
nothing by default, but is left for overriding by users that subclass
the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
This should not be called from user code, and is only exposed for use
when subclassing the
:class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
:param request: The :class:`PreparedRequest <PreparedRequest>` to add headers to.
:param kwargs: The keyword arguments from the call to send().
"""
pass
def proxy_headers(self, proxy):
"""Returns a dictionary of the headers to add to any request sent
through a proxy. This works with urllib3 magic to ensure that they are
correctly sent to the proxy, rather than in a tunnelled request if
CONNECT is being used.
This should not be called from user code, and is only exposed for use
when subclassing the
:class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
:param proxy: The url of the proxy being used for this request.
:rtype: dict
"""
headers = {}
username, password = get_auth_from_url(proxy)
if username:
headers['Proxy-Authorization'] = _basic_auth_str(username,
password)
return headers
def send(self, request, stream=False, timeout=None, verify=True, cert=None, proxies=None):
"""Sends PreparedRequest object. Returns Response object.
:param request: The :class:`PreparedRequest <PreparedRequest>` being sent.
:param stream: (optional) Whether to stream the request content.
:param timeout: (optional) How long to wait for the server to send
data before giving up, as a float, or a :ref:`(connect timeout,
read timeout) <timeouts>` tuple.
:type timeout: float or tuple or urllib3 Timeout object
:param verify: (optional) Either a boolean, in which case it controls whether
we verify the server's TLS certificate, or a string, in which case it
must be a path to a CA bundle to use
:param cert: (optional) Any user-provided SSL certificate to be trusted.
:param proxies: (optional) The proxies dictionary to apply to the request.
:rtype: requests.Response
"""
try:
conn = self.get_connection(request.url, proxies)
except LocationValueError as e:
raise InvalidURL(e, request=request)
self.cert_verify(conn, request.url, verify, cert)
url = self.request_url(request, proxies)
self.add_headers(request, stream=stream, timeout=timeout, verify=verify, cert=cert, proxies=proxies)
chunked = not (request.body is None or 'Content-Length' in request.headers)
if isinstance(timeout, tuple):
try:
connect, read = timeout
timeout = TimeoutSauce(connect=connect, read=read)
except ValueError as e:
# this may raise a string formatting error.
err = ("Invalid timeout {}. Pass a (connect, read) "
"timeout tuple, or a single float to set "
"both timeouts to the same value".format(timeout))
raise ValueError(err)
elif isinstance(timeout, TimeoutSauce):
pass
else:
timeout = TimeoutSauce(connect=timeout, read=timeout)
try:
if not chunked:
resp = conn.urlopen(
method=request.method,
url=url,
body=request.body,
headers=request.headers,
redirect=False,
assert_same_host=False,
preload_content=False,
decode_content=False,
retries=self.max_retries,
timeout=timeout
)
# Send the request.
else:
if hasattr(conn, 'proxy_pool'):
conn = conn.proxy_pool
low_conn = conn._get_conn(timeout=DEFAULT_POOL_TIMEOUT)
try:
low_conn.putrequest(request.method,
url,
skip_accept_encoding=True)
for header, value in request.headers.items():
low_conn.putheader(header, value)
low_conn.endheaders()
for i in request.body:
low_conn.send(hex(len(i))[2:].encode('utf-8'))
low_conn.send(b'\r\n')
low_conn.send(i)
low_conn.send(b'\r\n')
low_conn.send(b'0\r\n\r\n')
# Receive the response from the server
try:
# For Python 2.7, use buffering of HTTP responses
r = low_conn.getresponse(buffering=True)
except TypeError:
# For compatibility with Python 3.3+
r = low_conn.getresponse()
resp = HTTPResponse.from_httplib(
r,
pool=conn,
connection=low_conn,
preload_content=False,
decode_content=False
)
except:
# If we hit any problems here, clean up the connection.
# Then, reraise so that we can handle the actual exception.
low_conn.close()
raise
except (ProtocolError, socket.error) as err:
raise ConnectionError(err, request=request)
except MaxRetryError as e:
if isinstance(e.reason, ConnectTimeoutError):
# TODO: Remove this in 3.0.0: see #2811
if not isinstance(e.reason, NewConnectionError):
raise ConnectTimeout(e, request=request)
if isinstance(e.reason, ResponseError):
raise RetryError(e, request=request)
if isinstance(e.reason, _ProxyError):
raise ProxyError(e, request=request)
if isinstance(e.reason, _SSLError):
# This branch is for urllib3 v1.22 and later.
raise SSLError(e, request=request)
raise ConnectionError(e, request=request)
except ClosedPoolError as e:
raise ConnectionError(e, request=request)
except _ProxyError as e:
raise ProxyError(e)
except (_SSLError, _HTTPError) as e:
if isinstance(e, _SSLError):
# This branch is for urllib3 versions earlier than v1.22
raise SSLError(e, request=request)
elif isinstance(e, ReadTimeoutError):
raise ReadTimeout(e, request=request)
else:
raise
return self.build_response(request, resp)
================================================
FILE: modules/requests/api.py
================================================
# -*- coding: utf-8 -*-
"""
requests.api
~~~~~~~~~~~~
This module implements the Requests API.
:copyright: (c) 2012 by Kenneth Reitz.
:license: Apache2, see LICENSE for more details.
"""
from . import sessions
def request(method, url, **kwargs):
"""Constructs and sends a :class:`Request <Request>`.
:param method: method for the new :class:`Request` object: ``GET``, ``OPTIONS``, ``HEAD``, ``POST``, ``PUT``, ``PATCH``, or ``DELETE``.
:param url: URL for the new :class:`Request` object.
:param params: (optional) Dictionary, list of tuples or bytes to send
in the query string for the :class:`Request`.
:param data: (optional) Dictionary, list of tuples, bytes, or file-like
object to send in the body of the :class:`Request`.
:param json: (optional) A JSON serializable Python object to send in the body of the :class:`Request`.
:param headers: (optional) Dictionary of HTTP Headers to send with the :class:`Request`.
:param cookies: (optional) Dict or CookieJar object to send with the :class:`Request`.
:param files: (optional) Dictionary of ``'name': file-like-objects`` (or ``{'name': file-tuple}``) for multipart encoding upload.
``file-tuple`` can be a 2-tuple ``('filename', fileobj)``, 3-tuple ``('filename', fileobj, 'content_type')``
or a 4-tuple ``('filename', fileobj, 'content_type', custom_headers)``, where ``'content-type'`` is a string
defining the content type of the given file and ``custom_headers`` a dict-like object containing additional headers
to add for the file.
:param auth: (optional) Auth tuple to enable Basic/Digest/Custom HTTP Auth.
:param timeout: (optional) How many seconds to wait for the server to send data
before giving up, as a float, or a :ref:`(connect timeout, read
timeout) <timeouts>` tuple.
:type timeout: float or tuple
:param allow_redirects: (optional) Boolean. Enable/disable GET/OPTIONS/POST/PUT/PATCH/DELETE/HEAD redirection. Defaults to ``True``.
:type allow_redirects: bool
:param proxies: (optional) Dictionary mapping protocol to the URL of the proxy.
:param verify: (optional) Either a boolean, in which case it controls whether we verify
the server's TLS certificate, or a string, in which case it must be a path
to a CA bundle to use. Defaults to ``True``.
:param stream: (optional) if ``False``, the response content will be immediately downloaded.
:param cert: (optional) if String, path to ssl client cert file (.pem). If Tuple, ('cert', 'key') pair.
:return: :class:`Response <Response>` object
:rtype: requests.Response
Usage::
>>> import requests
>>> req = requests.request('GET', 'https://httpbin.org/get')
>>> req
<Response [200]>
"""
# By using the 'with' statement we are sure the session is closed, thus we
# avoid leaving sockets open which can trigger a ResourceWarning in some
# cases, and look like a memory leak in others.
with sessions.Session() as session:
return session.request(method=method, url=url, **kwargs)
def get(url, params=None, **kwargs):
r"""Sends a GET request.
:param url: URL for the new :class:`Request` object.
:param params: (optional) Dictionary, list of tuples or bytes to send
in the query string for the :class:`Request`.
:param \*\*kwargs: Optional arguments that ``request`` takes.
:return: :class:`Response <Response>` object
:rtype: requests.Response
"""
return request('get', url, params=params, **kwargs)
def options(url, **kwargs):
r"""Sends an OPTIONS request.
:param url: URL for the new :class:`Request` object.
:param \*\*kwargs: Optional arguments that ``request`` takes.
:return: :class:`Response <Response>` object
:rtype: requests.Response
"""
return request('options', url, **kwargs)
def head(url, **kwargs):
r"""Sends a HEAD request.
:param url: URL for the new :class:`Request` object.
:param \*\*kwargs: Optional arguments that ``request`` takes. If
`allow_redirects` is not provided, it will be set to `False` (as
opposed to the default :meth:`request` behavior).
:return: :class:`Response <Response>` object
:rtype: requests.Response
"""
kwargs.setdefault('allow_redirects', False)
return request('head', url, **kwargs)
def post(url, data=None, json=None, **kwargs):
r"""Sends a POST request.
:param url: URL for the new :class:`Request` object.
:param data: (optional) Dictionary, list of tuples, bytes, or file-like
object to send in the body of the :class:`Request`.
:param json: (optional) json data to send in the body of the :class:`Request`.
:param \*\*kwargs: Optional arguments that ``request`` takes.
:return: :class:`Response <Response>` object
:rtype: requests.Response
"""
return request('post', url, data=data, json=json, **kwargs)
def put(url, data=None, **kwargs):
r"""Sends a PUT request.
:param url: URL for the new :class:`Request` object.
:param data: (optional) Dictionary, list of tuples, bytes, or file-like
object to send in the body of the :class:`Request`.
:param json: (optional) json data to send in the body of the :class:`Request`.
:param \*\*kwargs: Optional arguments that ``request`` takes.
:return: :class:`Response <Response>` object
:rtype: requests.Response
"""
return request('put', url, data=data, **kwargs)
def patch(url, data=None, **kwargs):
r"""Sends a PATCH request.
:param url: URL for the new :class:`Request` object.
:param data: (optional) Dictionary, list of tuples, bytes, or file-like
object to send in the body of the :class:`Request`.
:param json: (optional) json data to send in the body of the :class:`Request`.
:param \*\*kwargs: Optional arguments that ``request`` takes.
:return: :class:`Response <Response>` object
:rtype: requests.Response
"""
return request('patch', url, data=data, **kwargs)
def delete(url, **kwargs):
r"""Sends a DELETE request.
:param url: URL for the new :class:`Request` object.
:param \*\*kwargs: Optional arguments that ``request`` takes.
:return: :class:`Response <Response>` object
:rtype: requests.Response
"""
return request('delete', url, **kwargs)
================================================
FILE: modules/requests/auth.py
================================================
# -*- coding: utf-8 -*-
"""
requests.auth
~~~~~~~~~~~~~
This module contains the authentication handlers for Requests.
"""
import os
import re
import time
import hashlib
import threading
import warnings
from base64 import b64encode
from .compat import urlparse, str, basestring
from .cookies import extract_cookies_to_jar
from ._internal_utils import to_native_string
from .utils import parse_dict_header
CONTENT_TYPE_FORM_URLENCODED = 'application/x-www-form-urlencoded'
CONTENT_TYPE_MULTI_PART = 'multipart/form-data'
def _basic_auth_str(username, password):
"""Returns a Basic Auth string."""
# "I want us to put a big-ol' comment on top of it that
# says that this behaviour is dumb but we need to preserve
# it because people are relying on it."
# - Lukasa
#
# These are here solely to maintain backwards compatibility
# for things like ints. This will be removed in 3.0.0.
if not isinstance(username, basestring):
warnings.warn(
"Non-string usernames will no longer be supported in Requests "
"3.0.0. Please convert the object you've passed in ({!r}) to "
"a string or bytes object in the near future to avoid "
"problems.".format(username),
category=DeprecationWarning,
)
username = str(username)
if not isinstance(password, basestring):
warnings.warn(
"Non-string passwords will no longer be supported in Requests "
"3.0.0. Please convert the object you've passed in ({!r}) to "
"a string or bytes object in the near future to avoid "
"problems.".format(type(password)),
category=DeprecationWarning,
)
password = str(password)
# -- End Removal --
if isinstance(username, str):
username = username.encode('latin1')
if isinstance(password, str):
password = password.encode('latin1')
authstr = 'Basic ' + to_native_string(
b64encode(b':'.join((username, password))).strip()
)
return authstr
class AuthBase(object):
"""Base class that all auth implementations derive from"""
def __call__(self, r):
raise NotImplementedError('Auth hooks must be callable.')
class HTTPBasicAuth(AuthBase):
"""Attaches HTTP Basic Authentication to the given Request object."""
def __init__(self, username, password):
self.username = username
self.password = password
def __eq__(self, other):
return all([
self.username == getattr(other, 'username', None),
self.password == getattr(other, 'password', None)
])
def __ne__(self, other):
return not self == other
def __call__(self, r):
r.headers['Authorization'] = _basic_auth_str(self.username, self.password)
return r
class HTTPProxyAuth(HTTPBasicAuth):
"""Attaches HTTP Proxy Authentication to a given Request object."""
def __call__(self, r):
r.headers['Proxy-Authorization'] = _basic_auth_str(self.username, self.password)
return r
class HTTPDigestAuth(AuthBase):
"""Attaches HTTP Digest Authentication to the given Request object."""
def __init__(self, username, password):
self.username = username
self.password = password
# Keep state in per-thread local storage
self._thread_local = threading.local()
def init_per_thread_state(self):
# Ensure state is initialized just once per-thread
if not hasattr(self._thread_local, 'init'):
self._thread_local.init = True
self._thread_local.last_nonce = ''
self._thread_local.nonce_count = 0
self._thread_local.chal = {}
self._thread_local.pos = None
self._thread_local.num_401_calls = None
def build_digest_header(self, method, url):
"""
:rtype: str
"""
realm = self._thread_local.chal['realm']
nonce = self._thread_local.chal['nonce']
qop = self._thread_local.chal.get('qop')
algorithm = self._thread_local.chal.get('algorithm')
opaque = self._thread_local.chal.get('opaque')
hash_utf8 = None
if algorithm is None:
_algorithm = 'MD5'
else:
_algorithm = algorithm.upper()
# lambdas assume digest modules are imported at the top level
if _algorithm == 'MD5' or _algorithm == 'MD5-SESS':
def md5_utf8(x):
if isinstance(x, str):
x = x.encode('utf-8')
return hashlib.md5(x).hexdigest()
hash_utf8 = md5_utf8
elif _algorithm == 'SHA':
def sha_utf8(x):
if isinstance(x, str):
x = x.encode('utf-8')
return hashlib.sha1(x).hexdigest()
hash_utf8 = sha_utf8
elif _algorithm == 'SHA-256':
def sha256_utf8(x):
if isinstance(x, str):
x = x.encode('utf-8')
return hashlib.sha256(x).hexdigest()
hash_utf8 = sha256_utf8
elif _algorithm == 'SHA-512':
def sha512_utf8(x):
if isinstance(x, str):
x = x.encode('utf-8')
return hashlib.sha512(x).hexdigest()
hash_utf8 = sha512_utf8
KD = lambda s, d: hash_utf8("%s:%s" % (s, d))
if hash_utf8 is None:
return None
# XXX not implemented yet
entdig = None
p_parsed = urlparse(url)
#: path is request-uri defined in RFC 2616 which should not be empty
path = p_parsed.path or "/"
if p_parsed.query:
path += '?' + p_parsed.query
A1 = '%s:%s:%s' % (self.username, realm, self.password)
A2 = '%s:%s' % (method, path)
HA1 = hash_utf8(A1)
HA2 = hash_utf8(A2)
if nonce == self._thread_local.last_nonce:
self._thread_local.nonce_count += 1
else:
self._thread_local.nonce_count = 1
ncvalue = '%08x' % self._thread_local.nonce_count
s = str(self._thread_local.nonce_count).encode('utf-8')
s += nonce.encode('utf-8')
s += time.ctime().encode('utf-8')
s += os.urandom(8)
cnonce = (hashlib.sha1(s).hexdigest()[:16])
if _algorithm == 'MD5-SESS':
HA1 = hash_utf8('%s:%s:%s' % (HA1, nonce, cnonce))
if not qop:
respdig = KD(HA1, "%s:%s" % (nonce, HA2))
elif qop == 'auth' or 'auth' in qop.split(','):
noncebit = "%s:%s:%s:%s:%s" % (
nonce, ncvalue, cnonce, 'auth', HA2
)
respdig = KD(HA1, noncebit)
else:
# XXX handle auth-int.
return None
self._thread_local.last_nonce = nonce
# XXX should the partial digests be encoded too?
base = 'username="%s", realm="%s", nonce="%s", uri="%s", ' \
'response="%s"' % (self.username, realm, nonce, path, respdig)
if opaque:
base += ', opaque="%s"' % opaque
if algorithm:
base += ', algorithm="%s"' % algorithm
if entdig:
base += ', digest="%s"' % entdig
if qop:
base += ', qop="auth", nc=%s, cnonce="%s"' % (ncvalue, cnonce)
return 'Digest %s' % (base)
def handle_redirect(self, r, **kwargs):
"""Reset num_401_calls counter on redirects."""
if r.is_redirect:
self._thread_local.num_401_calls = 1
def handle_401(self, r, **kwargs):
"""
Takes the given response and tries digest-auth, if needed.
:rtype: requests.Response
"""
# If response is not 4xx, do not auth
# See https://github.com/psf/requests/issues/3772
if not 400 <= r.status_code < 500:
self._thread_local.num_401_calls = 1
return r
if self._thread_local.pos is not None:
# Rewind the file position indicator of the body to where
# it was to resend the request.
r.request.body.seek(self._thread_local.pos)
s_auth = r.headers.get('www-authenticate', '')
if 'digest' in s_auth.lower() and self._thread_local.num_401_calls < 2:
self._thread_local.num_401_calls += 1
pat = re.compile(r'digest ', flags=re.IGNORECASE)
self._thread_local.chal = parse_dict_header(pat.sub('', s_auth, count=1))
# Consume content and release the original connection
# to allow our new request to reuse the same one.
r.content
r.close()
prep = r.request.copy()
extract_cookies_to_jar(prep._cookies, r.request, r.raw)
prep.prepare_cookies(prep._cookies)
prep.headers['Authorization'] = self.build_digest_header(
prep.method, prep.url)
_r = r.connection.send(prep, **kwargs)
_r.history.append(r)
_r.request = prep
return _r
self._thread_local.num_401_calls = 1
return r
def __call__(self, r):
# Initialize per-thread state, if needed
self.init_per_thread_state()
# If we have a saved nonce, skip the 401
if self._thread_local.last_nonce:
r.headers['Authorization'] = self.build_digest_header(r.method, r.url)
try:
self._thread_local.pos = r.body.tell()
except AttributeError:
# In the case of HTTPDigestAuth being reused and the body of
# the previous request was a file-like object, pos has the
# file position of the previous body. Ensure it's set to
# None.
self._thread_local.pos = None
r.register_hook('response', self.handle_401)
r.register_hook('response', self.handle_redirect)
self._thread_local.num_401_calls = 1
return r
def __eq__(self, other):
return all([
self.username == getattr(other, 'username', None),
self.password == getattr(other, 'password', None)
])
def __ne__(self, other):
return not self == other
================================================
FILE: modules/requests/certs.py
================================================
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
requests.certs
~~~~~~~~~~~~~~
This module returns the preferred default CA certificate bundle. There is
only one — the one from the certifi package.
If you are packaging Requests, e.g., for a Linux distribution or a managed
environment, you can change the definition of where() to return a separately
packaged CA bundle.
"""
from certifi import where
if __name__ == '__main__':
print(where())
================================================
FILE: modules/requests/compat.py
================================================
# -*- coding: utf-8 -*-
"""
requests.compat
~~~~~~~~~~~~~~~
This module handles import compatibility issues between Python 2 and
Python 3.
"""
try:
import chardet
except ImportError:
import charset_normalizer as chardet
import sys
# -------
# Pythons
# -------
# Syntax sugar.
_ver = sys.version_info
#: Python 2.x?
is_py2 = (_ver[0] == 2)
#: Python 3.x?
is_py3 = (_ver[0] == 3)
try:
import simplejson as json
except ImportError:
import json
# ---------
# Specifics
# ---------
if is_py2:
from urllib import (
quote, unquote, quote_plus, unquote_plus, urlencode, getproxies,
proxy_bypass, proxy_bypass_environment, getproxies_environment)
from urlparse import urlparse, urlunparse, urljoin, urlsplit, urldefrag
from urllib2 import parse_http_list
import cookielib
from Cookie import Morsel
from StringIO import StringIO
# Keep OrderedDict for backwards compatibility.
from collections import Callable, Mapping, MutableMapping, OrderedDict
builtin_str = str
bytes = str
str = unicode
basestring = basestring
numeric_types = (int, long, float)
integer_types = (int, long)
elif is_py3:
from urllib.parse import urlparse, urlunparse, urljoin, urlsplit, urlencode, quote, unquote, quote_plus, unquote_plus, urldefrag
from urllib.request import parse_http_list, getproxies, proxy_bypass, proxy_bypass_environment, getproxies_environment
from http import cookiejar as cookielib
from http.cookies import Morsel
from io import StringIO
# Keep OrderedDict for backwards compatibility.
from collections import OrderedDict
from collections.abc import Callable, Mapping, MutableMapping
builtin_str = str
str = str
bytes = bytes
basestring = (str, bytes)
numeric_types = (int, float)
integer_types = (int,)
================================================
FILE: modules/requests/cookies.py
================================================
# -*- coding: utf-8 -*-
"""
requests.cookies
~~~~~~~~~~~~~~~~
Compatibility code to be able to use `cookielib.CookieJar` with requests.
requests.utils imports from here, so be careful with imports.
"""
import copy
import time
import calendar
from ._internal_utils import to_native_string
from .compat import cookielib, urlparse, urlunparse, Morsel, MutableMapping
try:
import threading
except ImportError:
import dummy_threading as threading
class MockRequest(object):
"""Wraps a `requests.Request` to mimic a `urllib2.Request`.
The code in `cookielib.CookieJar` expects this interface in order to correctly
manage cookie policies, i.e., determine whether a cookie can be set, given the
domains of the request and the cookie.
The original request object is read-only. The client is responsible for collecting
the new headers via `get_new_headers()` and interpreting them appropriately. You
probably want `get_cookie_header`, defined below.
"""
def __init__(self, request):
self._r = request
self._new_headers = {}
self.type = urlparse(self._r.url).scheme
def get_type(self):
return self.type
def get_host(self):
return urlparse(self._r.url).netloc
def get_origin_req_host(self):
return self.get_host()
def get_full_url(self):
# Only return the response's URL if the user hadn't set the Host
# header
if not self._r.headers.get('Host'):
return self._r.url
# If they did set it, retrieve it and reconstruct the expected domain
host = to_native_string(self._r.headers['Host'], encoding='utf-8')
parsed = urlparse(self._r.url)
# Reconstruct the URL as we expect it
return urlunparse([
parsed.scheme, host, parsed.path, parsed.params, parsed.query,
parsed.fragment
])
def is_unverifiable(self):
return True
def has_header(self, name):
return name in self._r.headers or name in self._new_headers
def get_header(self, name, default=None):
return self._r.headers.get(name, self._new_headers.get(name, default))
def add_header(self, key, val):
"""cookielib has no legitimate use for this method; add it back if you find one."""
raise NotImplementedError("Cookie headers should be added with add_unredirected_header()")
def add_unredirected_header(self, name, value):
self._new_headers[name] = value
def get_new_headers(self):
return self._new_headers
@property
def unverifiable(self):
return self.is_unverifiable()
@property
def origin_req_host(self):
return self.get_origin_req_host()
@property
def host(self):
return self.get_host()
class MockResponse(object):
"""Wraps a `httplib.HTTPMessage` to mimic a `urllib.addinfourl`.
...what? Basically, expose the parsed HTTP headers from the server response
the way `cookielib` expects to see them.
"""
def __init__(self, headers):
"""Make a MockResponse for `cookielib` to read.
:param headers: a httplib.HTTPMessage or analogous carrying the headers
"""
self._headers = headers
def info(self):
return self._headers
def getheaders(self, name):
self._headers.getheaders(name)
def extract_cookies_to_jar(jar, request, response):
"""Extract the cookies from the response into a CookieJar.
:param jar: cookielib.CookieJar (not necessarily a RequestsCookieJar)
:param request: our own requests.Request object
:param response: urllib3.HTTPResponse object
"""
if not (hasattr(response, '_original_response') and
response._original_response):
return
# the _original_response field is the wrapped httplib.HTTPResponse object,
req = MockRequest(request)
# pull out the HTTPMessage with the headers and put it in the mock:
res = MockResponse(response._original_response.msg)
jar.extract_cookies(res, req)
def get_cookie_header(jar, request):
"""
Produce an appropriate Cookie header string to be sent with `request`, or None.
:rtype: str
"""
r = MockRequest(request)
jar.add_cookie_header(r)
return r.get_new_headers().get('Cookie')
def remove_cookie_by_name(cookiejar, name, domain=None, path=None):
"""Unsets a cookie by name, by default over all domains and paths.
Wraps CookieJar.clear(), is O(n).
"""
clearables = []
for cookie in cookiejar:
if cookie.name != name:
continue
if domain is not None and domain != cookie.domain:
continue
if path is not None and path != cookie.path:
continue
clearables.append((cookie.domain, cookie.path, cookie.name))
for domain, path, name in clearables:
cookiejar.clear(domain, path, name)
class CookieConflictError(RuntimeError):
"""There are two cookies that meet the criteria specified in the cookie jar.
Use .get and .set and include domain and path args in order to be more specific.
"""
class RequestsCookieJar(cookielib.CookieJar, MutableMapping):
"""Compatibility class; is a cookielib.CookieJar, but exposes a dict
interface.
This is the CookieJar we create by default for requests and sessions that
don't specify one, since some clients may expect response.cookies and
session.cookies to support dict operations.
Requests does not use the dict interface internally; it's just for
compatibility with external client code. All requests code should work
out of the box with externally provided instances of ``CookieJar``, e.g.
``LWPCookieJar`` and ``FileCookieJar``.
Unlike a regular CookieJar, this class is pickleable.
.. warning:: dictionary operations that are normally O(1) may be O(n).
"""
def get(self, name, default=None, domain=None, path=None):
"""Dict-like get() that also supports optional domain and path args in
order to resolve naming collisions from using one cookie jar over
multiple domains.
.. warning:: operation is O(n), not O(1).
"""
try:
return self._find_no_duplicates(name, domain, path)
except KeyError:
return default
def set(self, name, value, **kwargs):
"""Dict-like set() that also supports optional domain and path args in
order to resolve naming collisions from using one cookie jar over
multiple domains.
"""
# support client code that unsets cookies by assignment of a None value:
if value is None:
remove_cookie_by_name(self, name, domain=kwargs.get('domain'), path=kwargs.get('path'))
return
if isinstance(value, Morsel):
c = morsel_to_cookie(value)
else:
c = create_cookie(name, value, **kwargs)
self.set_cookie(c)
return c
def iterkeys(self):
"""Dict-like iterkeys() that returns an iterator of names of cookies
from the jar.
.. seealso:: itervalues() and iteritems().
"""
for cookie in iter(self):
yield cookie.name
def keys(self):
"""Dict-like keys() that returns a list of names of cookies from the
jar.
.. seealso:: values() and items().
"""
return list(self.iterkeys())
def itervalues(self):
"""Dict-like itervalues() that returns an iterator of values of cookies
from the jar.
.. seealso:: iterkeys() and iteritems().
"""
for cookie in iter(self):
yield cookie.value
def values(self):
"""Dict-like values() that returns a list of values of cookies from the
jar.
.. seealso:: keys() and items().
"""
return list(self.itervalues())
def iteritems(self):
"""Dict-like iteritems() that returns an iterator of name-value tuples
from the jar.
.. seealso:: iterkeys() and itervalues().
"""
for cookie in iter(self):
yield cookie.name, cookie.value
def items(self):
"""Dict-like items() that returns a list of name-value tuples from the
jar. Allows client-code to call ``dict(RequestsCookieJar)`` and get a
vanilla python dict of key value pairs.
.. seealso:: keys() and values().
"""
return list(self.iteritems())
def list_domains(self):
"""Utility method to list all the domains in the jar."""
domains = []
for cookie in iter(self):
if cookie.domain not in domains:
domains.append(cookie.domain)
return domains
def list_paths(self):
"""Utility method to list all the paths in the jar."""
paths = []
for cookie in iter(self):
if cookie.path not in paths:
paths.append(cookie.path)
return paths
def multiple_domains(self):
"""Returns True if there are multiple domains in the jar.
Returns False otherwise.
:rtype: bool
"""
domains = []
for cookie in iter(self):
if cookie.domain is not None and cookie.domain in domains:
return True
domains.append(cookie.domain)
return False # there is only one domain in jar
def get_dict(self, domain=None, path=None):
"""Takes as an argument an optional domain and path and returns a plain
old Python dict of name-value pairs of cookies that meet the
requirements.
:rtype: dict
"""
dictionary = {}
for cookie in iter(self):
if (
(domain is None or cookie.domain == domain) and
(path is None or cookie.path == path)
):
dictionary[cookie.name] = cookie.value
return dictionary
def __contains__(self, name):
try:
return super(RequestsCookieJar, self).__contains__(name)
except CookieConflictError:
return True
def __getitem__(self, name):
"""Dict-like __getitem__() for compatibility with client code. Throws
exception if there are more than one cookie with name. In that case,
use the more explicit get() method instead.
.. warning:: operation is O(n), not O(1).
"""
return self._find_no_duplicates(name)
def __setitem__(self, name, value):
"""Dict-like __setitem__ for compatibility with client code. Throws
exception if there is already a cookie of that name in the jar. In that
case, use the more explicit set() method instead.
"""
self.set(name, value)
def __delitem__(self, name):
"""Deletes a cookie given a name. Wraps ``cookielib.CookieJar``'s
``remove_cookie_by_name()``.
"""
remove_cookie_by_name(self, name)
def set_cookie(self, cookie, *args, **kwargs):
if hasattr(cookie.value, 'startswith') and cookie.value.startswith('"') and cookie.value.endswith('"'):
cookie.value = cookie.value.replace('\\"', '')
return super(RequestsCookieJar, self).set_cookie(cookie, *args, **kwargs)
def update(self, other):
"""Updates this jar with cookies from another CookieJar or dict-like"""
if isinstance(other, cookielib.CookieJar):
for cookie in other:
self.set_cookie(copy.copy(cookie))
else:
super(RequestsCookieJar, self).update(other)
def _find(self, name, domain=None, path=None):
"""Requests uses this method internally to get cookie values.
If there are conflicting cookies, _find arbitrarily chooses one.
See _find_no_duplicates if you want an exception thrown if there are
conflicting cookies.
:param name: a string containing name of cookie
:param domain: (optional) string containing domain of cookie
:param path: (optional) string containing path of cookie
:return: cookie.value
"""
for cookie in iter(self):
if cookie.name == name:
if domain is None or cookie.domain == domain:
if path is None or cookie.path == path:
return cookie.value
raise KeyError('name=%r, domain=%r, path=%r' % (name, domain, path))
def _find_no_duplicates(self, name, domain=None, path=None):
"""Both ``__get_item__`` and ``get`` call this function: it's never
used elsewhere in Requests.
:param name: a string containing name of cookie
:param domain: (optional) string containing domain of cookie
:param path: (optional) string containing path of cookie
:raises KeyError: if cookie is not found
:raises CookieConflictError: if there are multiple cookies
that match name and optionally domain and path
:return: cookie.value
"""
toReturn = None
for cookie in iter(self):
if cookie.name == name:
if domain is None or cookie.domain == domain:
if path is None or cookie.path == path:
if toReturn is not None: # if there are multiple cookies that meet passed in criteria
raise CookieConflictError('There are multiple cookies with name, %r' % (name))
toReturn = cookie.value # we will eventually return this as long as no cookie conflict
if toReturn:
return toReturn
raise KeyError('name=%r, domain=%r, path=%r' % (name, domain, path))
def __getstate__(self):
"""Unlike a normal CookieJar, this class is pickleable."""
state = self.__dict__.copy()
# remove the unpickleable RLock object
state.pop('_cookies_lock')
return state
def __setstate__(self, state):
"""Unlike a normal CookieJar, this class is pickleable."""
self.__dict__.update(state)
if '_cookies_lock' not in self.__dict__:
self._cookies_lock = threading.RLock()
def copy(self):
"""Return a copy of this RequestsCookieJar."""
new_cj = RequestsCookieJar()
new_cj.set_policy(self.get_policy())
new_cj.update(self)
return new_cj
def get_policy(self):
"""Return the CookiePolicy instance used."""
return self._policy
def _copy_cookie_jar(jar):
if jar is None:
return None
if hasattr(jar, 'copy'):
# We're dealing with an instance of RequestsCookieJar
return jar.copy()
# We're dealing with a generic CookieJar instance
new_jar = copy.copy(jar)
new_jar.clear()
for cookie in jar:
new_jar.set_cookie(copy.copy(cookie))
return new_jar
def create_cookie(name, value, **kwargs):
"""Make a cookie from underspecified parameters.
By default, the pair of `name` and `value` will be set for the domain ''
and sent on every request (this is sometimes called a "supercookie").
"""
result = {
'version': 0,
'name': name,
'value': value,
'port': None,
'domain': '',
'path': '/',
'secure': False,
'expires': None,
'discard': True,
'comment': None,
'comment_url': None,
'rest': {'HttpOnly': None},
'rfc2109': False,
}
badargs = set(kwargs) - set(result)
if badargs:
err = 'create_cookie() got unexpected keyword arguments: %s'
raise TypeError(err % list(badargs))
result.update(kwargs)
result['port_specified'] = bool(result['port'])
result['domain_specified'] = bool(result['domain'])
result['domain_initial_dot'] = result['domain'].startswith('.')
result['path_specified'] = bool(result['path'])
return cookielib.Cookie(**result)
def morsel_to_cookie(morsel):
"""Convert a Morsel object into a Cookie containing the one k/v pair."""
expires = None
if morsel['max-age']:
try:
expires = int(time.time() + int(morsel['max-age']))
except ValueError:
raise TypeError('max-age: %s must be integer' % morsel['max-age'])
elif morsel['expires']:
time_template = '%a, %d-%b-%Y %H:%M:%S GMT'
expires = calendar.timegm(
time.strptime(morsel['expires'], time_template)
)
return create_cookie(
comment=morsel['comment'],
comment_url=bool(morsel['comment']),
discard=False,
domain=morsel['domain'],
expires=expires,
name=morsel.key,
path=morsel['path'],
port=None,
rest={'HttpOnly': morsel['httponly']},
rfc2109=False,
secure=bool(morsel['secure']),
value=morsel.value,
version=morsel['version'] or 0,
)
def cookiejar_from_dict(cookie_dict, cookiejar=None, overwrite=True):
"""Returns a CookieJar from a key/value dictionary.
:param cookie_dict: Dict of key/values to insert into CookieJar.
:param cookiejar: (optional) A cookiejar to add the cookies to.
:param overwrite: (optional) If False, will not replace cookies
already in the jar with new ones.
:rtype: CookieJar
"""
if cookiejar is None:
cookiejar = RequestsCookieJar()
if cookie_dict is not None:
names_from_jar = [cookie.name for cookie in cookiejar]
for name in cookie_dict:
if overwrite or (name not in names_from_jar):
cookiejar.set_cookie(create_cookie(name, cookie_dict[name]))
return cookiejar
def merge_cookies(cookiejar, cookies):
"""Add cookies to cookiejar and returns a merged CookieJar.
:param cookiejar: CookieJar object to add the cookies to.
:param cookies: Dictionary or CookieJar object to be added.
:rtype: CookieJar
"""
if not isinstance(cookiejar, cookielib.CookieJar):
raise ValueError('You can only merge into CookieJar')
if isinstance(cookies, dict):
cookiejar = cookiejar_from_dict(
cookies, cookiejar=cookiejar, overwrite=False)
elif isinstance(cookies, cookielib.CookieJar):
try:
cookiejar.update(cookies)
except AttributeError:
for cookie_in_jar in cookies:
cookiejar.set_cookie(cookie_in_jar)
return cookiejar
================================================
FILE: modules/requests/exceptions.py
================================================
# -*- coding: utf-8 -*-
"""
requests.exceptions
~~~~~~~~~~~~~~~~~~~
This module contains the set of Requests' exceptions.
"""
from urllib3.exceptions import HTTPError as BaseHTTPError
class RequestException(IOError):
"""There was an ambiguous exception that occurred while handling your
request.
"""
def __init__(self, *args, **kwargs):
"""Initialize RequestException with `request` and `response` objects."""
response = kwargs.pop('response', None)
self.response = response
self.request = kwargs.pop('request', None)
if (response is not None and not self.request and
hasattr(response, 'request')):
self.request = self.response.request
super(RequestException, self).__init__(*args, **kwargs)
class InvalidJSONError(RequestException):
"""A JSON error occurred."""
class HTTPError(RequestException):
"""An HTTP error occurred."""
class ConnectionError(RequestException):
"""A Connection error occurred."""
class ProxyError(ConnectionError):
"""A proxy error occurred."""
class SSLError(ConnectionError):
"""An SSL error occurred."""
class Timeout(RequestException):
"""The request timed out.
Catching this error will catch both
:exc:`~requests.exceptions.ConnectTimeout` and
:exc:`~requests.exceptions.ReadTimeout` errors.
"""
class ConnectTimeout(ConnectionError, Timeout):
"""The request timed out while trying to connect to the remote server.
Requests that produced this error are safe to retry.
"""
class ReadTimeout(Timeout):
"""The server did not send any data in the allotted amount of time."""
class URLRequired(RequestException):
"""A valid URL is required to make a request."""
class TooManyRedirects(RequestException):
"""Too many redirects."""
class MissingSchema(RequestException, ValueError):
"""The URL schema (e.g. http or https) is missing."""
class InvalidSchema(RequestException, ValueError):
"""See defaults.py for valid schemas."""
class InvalidURL(RequestException, ValueError):
"""The URL provided was somehow invalid."""
class InvalidHeader(RequestException, ValueError):
"""The header value provided was somehow invalid."""
class InvalidProxyURL(InvalidURL):
"""The proxy URL provided is invalid."""
class ChunkedEncodingError(RequestException):
"""The server declared chunked encoding but sent an invalid chunk."""
class ContentDecodingError(RequestException, BaseHTTPError):
"""Failed to decode response content."""
class StreamConsumedError(RequestException, TypeError):
"""The content for this response was already consumed."""
class RetryError(RequestException):
"""Custom retries logic failed"""
class UnrewindableBodyError(RequestException):
"""Requests encountered an error when trying to rewind a body."""
# Warnings
class RequestsWarning(Warning):
"""Base warning for Requests."""
class FileModeWarning(RequestsWarning, DeprecationWarning):
"""A file was opened in text mode, but Requests determined its binary length."""
class RequestsDependencyWarning(RequestsWarning):
"""An imported dependency doesn't match the expected version range."""
================================================
FILE: modules/requests/help.py
================================================
"""Module containing bug report helper(s)."""
from __future__ import print_function
import json
import platform
import sys
import ssl
import idna
import urllib3
from . import __version__ as requests_version
try:
import charset_normalizer
except ImportError:
charset_normalizer = None
try:
import chardet
except ImportError:
chardet = None
try:
from urllib3.contrib import pyopenssl
except ImportError:
pyopenssl = None
OpenSSL = None
cryptography = None
else:
import OpenSSL
import cryptography
def _implementation():
"""Return a dict with the Python implementation and version.
Provide both the name and the version of the Python implementation
currently running. For example, on CPython 2.7.5 it will return
{'name': 'CPython', 'version': '2.7.5'}.
This function works best on CPython and PyPy: in particular, it probably
doesn't work for Jython or IronPython. Future investigation should be done
to work out the correct shape of the code for those platforms.
"""
implementation = platform.python_implementation()
if implementation == 'CPython':
implementation_version = platform.python_version()
elif implementation == 'PyPy':
implementation_version = '%s.%s.%s' % (sys.pypy_version_info.major,
sys.pypy_version_info.minor,
sys.pypy_version_info.micro)
if sys.pypy_version_info.releaselevel != 'final':
implementation_version = ''.join([
implementation_version, sys.pypy_version_info.releaselevel
])
elif implementation == 'Jython':
implementation_version = platform.python_version() # Complete Guess
elif implementation == 'IronPython':
implementation_version = platform.python_version() # Complete Guess
else:
implementation_version = 'Unknown'
return {'name': implementation, 'version': implementation_version}
def info():
"""Generate information for a bug report."""
try:
platform_info = {
'system': platform.system(),
'release': platform.release(),
}
except IOError:
platform_info = {
'system': 'Unknown',
'release': 'Unknown',
}
implementation_info = _implementation()
urllib3_info = {'version': urllib3.__version__}
charset_normalizer_info = {'version': None}
chardet_info = {'version': None}
if charset_normalizer:
charset_normalizer_info = {'version': charset_normalizer.__version__}
if chardet:
chardet_info = {'version': chardet.__version__}
pyopenssl_info = {
'version': None,
'openssl_version': '',
}
if OpenSSL:
pyopenssl_info = {
'version': OpenSSL.__version__,
'openssl_version': '%x' % OpenSSL.SSL.OPENSSL_VERSION_NUMBER,
}
cryptography_info = {
'version': getattr(cryptography, '__version__', ''),
}
idna_info = {
'version': getattr(idna, '__version__', ''),
}
system_ssl = ssl.OPENSSL_VERSION_NUMBER
system_ssl_info = {
'version': '%x' % system_ssl if system_ssl is not None else ''
}
return {
'platform': platform_info,
'implementation': implementation_info,
'system_ssl': system_ssl_info,
'using_pyopenssl': pyopenssl is not None,
'using_charset_normalizer': chardet is None,
'pyOpenSSL': pyopenssl_info,
'urllib3': urllib3_info,
'chardet': chardet_info,
'charset_normalizer': charset_normalizer_info,
'cryptography': cryptography_info,
'idna': idna_info,
'requests': {
'version': requests_version,
},
}
def main():
"""Pretty-print the bug information as JSON."""
print(json.dumps(info(), sort_keys=True, indent=2))
if __name__ == '__main__':
main()
================================================
FILE: modules/requests/hooks.py
================================================
# -*- coding: utf-8 -*-
"""
requests.hooks
~~~~~~~~~~~~~~
This module provides the capabilities for the Requests hooks system.
Available hooks:
``response``:
The response generated from a Request.
"""
HOOKS = ['response']
def default_hooks():
return {event: [] for event in HOOKS}
# TODO: response is the only one
def dispatch_hook(key, hooks, hook_data, **kwargs):
"""Dispatches a hook dictionary on a given piece of data."""
hooks = hooks or {}
hooks = hooks.get(key)
if hooks:
if hasattr(hooks, '__call__'):
hooks = [hooks]
for hook in hooks:
_hook_data = hook(hook_data, **kwargs)
if _hook_data is not None:
hook_data = _hook_data
return hook_data
================================================
FILE: modules/requests/models.py
================================================
# -*- coding: utf-8 -*-
"""
requests.models
~~~~~~~~~~~~~~~
This module contains the primary objects that power Requests.
"""
import datetime
import sys
# Import encoding now, to avoid implicit import later.
# Implicit import within threads may cause LookupError when standard library is in a ZIP,
# such as in Embedded Python. See https://github.com/psf/requests/issues/3578.
import encodings.idna
from urllib3.fields import RequestField
from urllib3.filepost import encode_multipart_formdata
from urllib3.util import parse_url
from urllib3.exceptions import (
DecodeError, ReadTimeoutError, ProtocolError, LocationParseError)
from io import UnsupportedOperation
from .hooks import default_hooks
from .structures import CaseInsensitiveDict
from .auth import HTTPBasicAuth
from .cookies import cookiejar_from_dict, get_cookie_header, _copy_cookie_jar
from .exceptions import (
HTTPError, MissingSchema, InvalidURL, ChunkedEncodingError,
ContentDecodingError, ConnectionError, StreamConsumedError, InvalidJSONError)
from ._internal_utils import to_native_string, unicode_is_ascii
from .utils import (
guess_filename, get_auth_from_url, requote_uri,
stream_decode_response_unicode, to_key_val_list, parse_header_links,
iter_slices, guess_json_utf, super_len, check_header_validity)
from .compat import (
Callable, Mapping,
cookielib, urlunparse, urlsplit, urlencode, str, bytes,
is_py2, chardet, builtin_str, basestring)
from .compat import json as complexjson
from .status_codes import codes
#: The set of HTTP status codes that indicate an automatically
#: processable redirect.
REDIRECT_STATI = (
codes.moved, # 301
codes.found, # 302
codes.other, # 303
codes.temporary_redirect, # 307
codes.permanent_redirect, # 308
)
DEFAULT_REDIRECT_LIMIT = 30
CONTENT_CHUNK_SIZE = 10 * 1024
ITER_CHUNK_SIZE = 512
class RequestEncodingMixin(object):
@property
def path_url(self):
"""Build the path URL to use."""
url = []
p = urlsplit(self.url)
path = p.path
if not path:
path = '/'
url.append(path)
query = p.query
if query:
url.append('?')
url.append(query)
return ''.join(url)
@staticmethod
def _encode_params(data):
"""Encode parameters in a piece of data.
Will successfully encode parameters when passed as a dict or a list of
2-tuples. Order is retained if data is a list of 2-tuples but arbitrary
if parameters are supplied as a dict.
"""
if isinstance(data, (str, bytes)):
return data
elif hasattr(data, 'read'):
return data
elif hasattr(data, '__iter__'):
result = []
for k, vs in to_key_val_list(data):
if isinstance(vs, basestring) or not hasattr(vs, '__iter__'):
vs = [vs]
for v in vs:
if v is not None:
result.append(
(k.encode('utf-8') if isinstance(k, str) else k,
v.encode('utf-8') if isinstance(v, str) else v))
return urlencode(result, doseq=True)
else:
return data
@staticmethod
def _encode_files(files, data):
"""Build the body for a multipart/form-data request.
Will successfully encode files when passed as a dict or a list of
tuples. Order is retained if data is a list of tuples but arbitrary
if parameters are supplied as a dict.
The tuples may be 2-tuples (filename, fileobj), 3-tuples (filename, fileobj, contentype)
or 4-tuples (filename, fileobj, contentype, custom_headers).
"""
if (not files):
raise ValueError("Files must be provided.")
elif isinstance(data, basestring):
raise ValueError("Data must not be a string.")
new_fields = []
fields = to_key_val_list(data or {})
files = to_key_val_list(files or {})
for field, val in fields:
if isinstance(val, basestring) or not hasattr(val, '__iter__'):
val = [val]
for v in val:
if v is not None:
# Don't call str() on bytestrings: in Py3 it all goes wrong.
if not isinstance(v, bytes):
v = str(v)
new_fields.append(
(field.decode('utf-8') if isinstance(field, bytes) else field,
v.encode('utf-8') if isinstance(v, str) else v))
for (k, v) in files:
# support for explicit filename
ft = None
fh = None
if isinstance(v, (tuple, list)):
if len(v) == 2:
fn, fp = v
elif len(v) == 3:
fn, fp, ft = v
else:
fn, fp, ft, fh = v
else:
fn = guess_filename(v) or k
fp = v
if isinstance(fp, (str, bytes, bytearray)):
fdata = fp
elif hasattr(fp, 'read'):
fdata = fp.read()
elif fp is None:
continue
else:
fdata = fp
rf = RequestField(name=k, data=fdata, filename=fn, headers=fh)
rf.make_multipart(content_type=ft)
new_fields.append(rf)
body, content_type = encode_multipart_formdata(new_fields)
return body, content_type
class RequestHooksMixin(object):
def register_hook(self, event, hook):
"""Properly register a hook."""
if event not in self.hooks:
raise ValueError('Unsupported event specified, with event name "%s"' % (event))
if isinstance(hook, Callable):
self.hooks[event].append(hook)
elif hasattr(hook, '__iter__'):
self.hooks[event].extend(h for h in hook if isinstance(h, Callable))
def deregister_hook(self, event, hook):
"""Deregister a previously registered hook.
Returns True if the hook existed, False if not.
"""
try:
self.hooks[event].remove(hook)
return True
except ValueError:
return False
class Request(RequestHooksMixin):
"""A user-created :class:`Request <Request>` object.
Used to prepare a :class:`PreparedRequest <PreparedRequest>`, which is sent to the server.
:param method: HTTP method to use.
:param url: URL to send.
:param headers: dictionary of headers to send.
:param files: dictionary of {filename: fileobject} files to multipart upload.
:param data: the body to attach to the request. If a dictionary or
list of tuples ``[(key, value)]`` is provided, form-encoding will
take place.
:param json: json for the body to attach to the request (if files or data is not specified).
:param params: URL parameters to append to the URL. If a dictionary or
list of tuples ``[(key, value)]`` is provided, form-encoding will
take place.
:param auth: Auth handler or (user, pass) tuple.
:param cookies: dictionary or CookieJar of cookies to attach to this request.
:param hooks: dictionary of callback hooks, for internal usage.
Usage::
>>> import requests
>>> req = requests.Request('GET', 'https://httpbin.org/get')
>>> req.prepare()
<PreparedRequest [GET]>
"""
def __init__(self,
method=None, url=None, headers=None, files=None, data=None,
params=None, auth=None, cookies=None, hooks=None, json=None):
# Default empty dicts for dict params.
data = [] if data is None else data
files = [] if files is None else files
headers = {} if headers is None else headers
params = {} if params is None else params
hooks = {} if hooks is None else hooks
self.hooks = default_hooks()
for (k, v) in list(hooks.items()):
self.register_hook(event=k, hook=v)
self.method = method
self.url = url
self.headers = headers
self.files = files
self.data = data
self.json = json
self.params = params
self.auth = auth
self.cookies = cookies
def __repr__(self):
return '<Request [%s]>' % (self.method)
def prepare(self):
"""Constructs a :class:`PreparedRequest <PreparedRequest>` for transmission and returns it."""
p = PreparedRequest()
p.prepare(
method=self.method,
url=self.url,
headers=self.headers,
files=self.files,
data=self.data,
json=self.json,
params=self.params,
auth=self.auth,
cookies=self.cookies,
hooks=self.hooks,
)
return p
class PreparedRequest(RequestEncodingMixin, RequestHooksMixin):
"""The fully mutable :class:`PreparedRequest <PreparedRequest>` object,
containing the exact bytes that will be sent to the server.
Instances are generated from a :class:`Request <Request>` object, and
should not be instantiated manually; doing so may produce undesirable
effects.
Usage::
>>> import requests
>>> req = requests.Request('GET', 'https://httpbin.org/get')
>>> r = req.prepare()
>>> r
<PreparedRequest [GET]>
>>> s = requests.Session()
>>> s.send(r)
<Response [200]>
"""
def __init__(self):
#: HTTP verb to send to the server.
self.method = None
#: HTTP URL to send the request to.
self.url = None
#: dictionary of HTTP headers.
self.headers = None
# The `CookieJar` used to create the Cookie header will be stored here
# after prepare_cookies is called
self._cookies = None
#: request body to send to the server.
self.body = None
#: dictionary of callback hooks, for internal usage.
self.hooks = default_hooks()
#: integer denoting starting position of a readable file-like body.
self._body_position = None
def prepare(self,
method=None, url=None, headers=None, files=None, data=None,
params=None, auth=None, cookies=None, hooks=None, json=None):
"""Prepares the entire request with the given parameters."""
self.prepare_method(method)
self.prepare_url(url, params)
self.prepare_headers(headers)
self.prepare_cookies(cookies)
self.prepare_body(data, files, json)
self.prepare_auth(auth, url)
# Note that prepare_auth must be last to enable authentication schemes
# such as OAuth to work on a fully prepared request.
# This MUST go after prepare_auth. Authenticators could add a hook
self.prepare_hooks(hooks)
def __repr__(self):
return '<PreparedRequest [%s]>' % (self.method)
def copy(self):
p = PreparedRequest()
p.method = self.method
p.url = self.url
p.headers = self.headers.copy() if self.headers is not None else None
p._cookies = _copy_cookie_jar(self._cookies)
p.body = self.body
p.hooks = self.hooks
p._body_position = self._body_position
return p
def prepare_method(self, method):
"""Prepares the given HTTP method."""
self.method = method
if self.method is not None:
self.method = to_native_string(self.method.upper())
@staticmethod
def _get_idna_encoded_host(host):
import idna
try:
host = idna.encode(host, uts46=True).decode('utf-8')
except idna.IDNAError:
raise UnicodeError
return host
def prepare_url(self, url, params):
"""Prepares the given HTTP URL."""
#: Accept objects that have string representations.
#: We're unable to blindly call unicode/str functions
#: as this will include the bytestring indicator (b'')
#: on python 3.x.
#: https://github.com/psf/requests/pull/2238
if isinstance(url, bytes):
url = url.decode('utf8')
else:
url = unicode(url) if is_py2 else str(url)
# Remove leading whitespaces from url
url = url.lstrip()
# Don't do any URL preparation for non-HTTP schemes like `mailto`,
# `data` etc to work around exceptions from `url_parse`, which
# handles RFC 3986 only.
if ':' in url and not url.lower().startswith('http'):
self.url = url
return
# Support for unicode domain names and paths.
try:
scheme, auth, host, port, path, query, fragment = parse_url(url)
except LocationParseError as e:
raise InvalidURL(*e.args)
if not scheme:
error = ("Invalid URL {0!r}: No schema supplied. Perhaps you meant http://{0}?")
error = error.format(to_native_string(url, 'utf8'))
raise MissingSchema(error)
if not host:
raise InvalidURL("Invalid URL %r: No host supplied" % url)
# In general, we want to try IDNA encoding the hostname if the string contains
# non-ASCII characters. This allows users to automatically get the correct IDNA
# behaviour. For strings containing only ASCII characters, we need to also verify
# it doesn't start with a wildcard (*), before allowing the unencoded hostname.
if not unicode_is_ascii(host):
try:
host = self._get_idna_encoded_host(host)
except UnicodeError:
raise InvalidURL('URL has an invalid label.')
elif host.startswith(u'*'):
raise InvalidURL('URL has an invalid label.')
# Carefully reconstruct the network location
netloc = auth or ''
if netloc:
netloc += '@'
netloc += host
if port:
netloc += ':' + str(port)
# Bare domains aren't valid URLs.
if not path:
path = '/'
if is_py2:
if isinstance(scheme, str):
scheme = scheme.encode('utf-8')
if isinstance(netloc, str):
netloc = netloc.encode('utf-8')
if isinstance(path, str):
path = path.encode('utf-8')
if isinstance(query, str):
query = query.encode('utf-8')
if isinstance(fragment, str):
fragment = fragment.encode('utf-8')
if isinstance(params, (str, bytes)):
params = to_native_string(params)
enc_params = self._encode_params(params)
if enc_params:
if query:
query = '%s&%s' % (query, enc_params)
else:
query = enc_params
url = requote_uri(urlunparse([scheme, netloc, path, None, query, fragment]))
self.url = url
def prepare_headers(self, headers):
"""Prepares the given HTTP headers."""
self.headers = CaseInsensitiveDict()
if headers:
for header in headers.items():
# Raise exception on invalid header value.
check_header_validity(header)
name, value = header
self.headers[to_native_string(name)] = value
def prepare_body(self, data, files, json=None):
"""Prepares the given HTTP body data."""
# Check if file, fo, generator, iterator.
# If not, run through normal process.
# Nottin' on you.
body = None
content_type = None
if not data and json is not None:
# urllib3 requires a bytes-like body. Python 2's json.dumps
# provides this natively, but Python 3 gives a Unicode string.
content_type = 'application/json'
try:
body = complexjson.dumps(json, allow_nan=False)
except ValueError as ve:
raise InvalidJSONError(ve, request=self)
if not isinstance(body, bytes):
body = body.encode('utf-8')
is_stream = all([
hasattr(data, '__iter__'),
not isinstance(data, (basestring, list, tuple, Mapping))
])
if is_stream:
try:
length = super_len(data)
except (TypeError, AttributeError, UnsupportedOperation):
length = None
body = data
if getattr(body, 'tell', None) is not None:
# Record the current file position before reading.
# This will allow us to rewind a file in the event
# of a redirect.
try:
self._body_position = body.tell()
except (IOError, OSError):
# This differentiates from None, allowing us to catch
# a failed `tell()` later when trying to rewind the body
self._body_position = object()
if files:
raise NotImplementedError('Streamed bodies and files are mutually exclusive.')
if length:
self.headers['Content-Length'] = builtin_str(length)
else:
self.headers['Transfer-Encoding'] = 'chunked'
else:
# Multi-part file uploads.
if files:
(body, content_type) = self._encode_files(files, data)
else:
if data:
body = self._encode_params(data)
if isinstance(data, basestring) or hasattr(data, 'read'):
content_type = None
else:
content_type = 'application/x-www-form-urlencoded'
self.prepare_content_length(body)
# Add content-type if it wasn't explicitly provided.
if content_type and ('content-type' not in self.headers):
self.headers['Content-Type'] = content_type
self.body = body
def prepare_content_length(self, body):
"""Prepare Content-Length header based on request method and body"""
if body is not None:
length = super_len(body)
if length:
# If length exists, set it. Otherwise, we fallback
# to Transfer-Encoding: chunked.
self.headers['Content-Length'] = builtin_str(length)
elif self.method not in ('GET', 'HEAD') and self.headers.get('Content-Length') is None:
# Set Content-Length to 0 for methods that can have a body
# but don't provide one. (i.e. not GET or HEAD)
self.headers['Content-Length'] = '0'
def prepare_auth(self, auth, url=''):
"""Prepares the given HTTP auth data."""
# If no Auth is explicitly provided, extract it from the URL first.
if auth is None:
url_auth = get_auth_from_url(self.url)
auth = url_auth if any(url_auth) else None
if auth:
if isinstance(auth, tuple) and len(auth) == 2:
# special-case basic HTTP auth
auth = HTTPBasicAuth(*auth)
# Allow auth to make its changes.
r = auth(self)
# Update self to reflect the auth changes.
self.__dict__.update(r.__dict__)
# Recompute Content-Length
self.prepare_content_length(self.body)
def prepare_cookies(self, cookies):
"""Prepares the given HTTP cookie data.
This function eventually generates a ``Cookie`` header from the
given cookies using cookielib. Due to cookielib's design, the header
will not be regenerated if it already exists, meaning this function
can only be called once for the life of the
:class:`PreparedRequest <PreparedRequest>` object. Any subsequent calls
to ``prepare_cookies`` will have no actual effect, unless the "Cookie"
header is removed beforehand.
"""
if isinstance(cookies, cookielib.CookieJar):
self._cookies = cookies
else:
self._cookies = cookiejar_from_dict(cookies)
cookie_header = get_cookie_header(self._cookies, self)
if cookie_header is not None:
self.headers['Cookie'] = cookie_header
def prepare_hooks(self, hooks):
"""Prepares the given hooks."""
# hooks can be passed as None to the prepare method and to this
# method. To prevent iterating over None, simply use an empty list
# if hooks is False-y
hooks = hooks or []
for event in hooks:
self.register_hook(event, hooks[event])
class Response(object):
"""The :class:`Response <Response>` object, which contains a
server's response to an HTTP request.
"""
__attrs__ = [
'_content', 'status_code', 'headers', 'url', 'history',
'encoding', 'reason', 'cookies', 'elapsed', 'request'
]
def __init__(self):
self._content = False
self._content_consumed = False
self._next = None
#: Integer Code of responded HTTP Status, e.g. 404 or 200.
self.status_code = None
#: Case-insensitive Dictionary of Response Headers.
#: For example, ``headers['content-encoding']`` will return the
#: value of a ``'Content-Encoding'`` response header.
self.headers = CaseInsensitiveDict()
#: File-like object representation of response (for advanced usage).
#: Use of ``raw`` requires that ``stream=True`` be set on the request.
#: This requirement does not apply for use internally to Requests.
self.raw = None
#: Final URL location of Response.
self.url = None
#: Encoding to decode with when accessing r.text.
self.encoding = None
#: A list of :class:`Response <Response>` objects from
#: the history of the Request. Any redirect responses will end
#: up here. The list is sorted from the oldest to the most recent request.
self.history = []
#: Textual reason of responded HTTP Status, e.g. "Not Found" or "OK".
self.reason = None
#: A CookieJar of Cookies the server sent back.
self.cookies = cookiejar_from_dict({})
#: The amount of time elapsed between sending the request
#: and the arrival of the response (as a timedelta).
#: This property specifically measures the time taken between sending
#: the first byte of the request and finishing parsing the headers. It
#: is therefore unaffected by consuming the response content or the
#: value of the ``stream`` keyword argument.
self.elapsed = datetime.timedelta(0)
#: The :class:`PreparedRequest <PreparedRequest>` object to which this
#: is a response.
self.request = None
def __enter__(self):
return self
def __exit__(self, *args):
self.close()
def __getstate__(self):
# Consume everything; accessing the content attribute makes
# sure the content has been fully read.
if not self._content_consumed:
self.content
return {attr: getattr(self, attr, None) for attr in self.__attrs__}
def __setstate__(self, state):
for name, value in state.items():
setattr(self, name, value)
# pickled objects do not have .raw
setattr(self, '_content_consumed', True)
setattr(self, 'raw', None)
def __repr__(self):
return '<Response [%s]>' % (self.status_code)
def __bool__(self):
"""Returns True if :attr:`status_code` is less than 400.
This attribute checks if the status code of the response is between
400 and 600 to see if there was a client error or a server error. If
the status code, is between 200 and 400, this will return True. This
is **not** a check to see if the response code is ``200 OK``.
"""
return self.ok
def __nonzero__(self):
"""Returns True if :attr:`status_code` is less than 400.
This attribute checks if the status code of the response is between
400 and 600 to see if there was a client error or a server error. If
the status code, is between 200 and 400, this will return True. This
is **not** a check to see if the response code is ``200 OK``.
"""
return self.ok
def __iter__(self):
"""Allows you to use a response as an iterator."""
return self.iter_content(128)
@property
def ok(self):
"""Returns True if :attr:`status_code` is less than 400, False if not.
This attribute checks if the status code of the response is between
400 and 600 to see if there was a client error or a server error. If
the status code is between 200 and 400, this will return True. This
is **not** a check to see if the response code is ``200 OK``.
"""
try:
self.raise_for_status()
except HTTPError:
return False
return True
@property
def is_redirect(self):
"""True if this Response is a well-formed HTTP redirect that could have
been processed automatically (by :meth:`Session.resolve_redirects`).
"""
return ('location' in self.headers and self.status_code in REDIRECT_STATI)
@property
def is_permanent_redirect(self):
"""True if this Response one of the permanent versions of redirect."""
return ('location' in self.headers and self.status_code in (codes.moved_permanently, codes.permanent_redirect))
@property
def next(self):
"""Returns a PreparedRequest for the next request in a redirect chain, if there is one."""
return self._next
@property
def apparent_encoding(self):
"""The apparent encoding, provided by the charset_normalizer or chardet libraries."""
return chardet.detect(self.content)['encoding']
def iter_content(self, chunk_size=1, decode_unicode=False):
"""Iterates over the response data. When stream=True is set on the
request, this avoids reading the content at once into memory for
large responses. The chunk size is the number of bytes it should
read into memory. This is not necessarily the length of each item
returned as decoding can take place.
chunk_size must be of type int or None. A value of None will
function differently depending on the value of `stream`.
stream=True will read data as it arrives in whatever size the
chunks are received. If stream=False, data is returned as
a single chunk.
If decode_unicode is True, content will be decoded using the best
available encoding based on the response.
"""
def generate():
# Special case for urllib3.
if hasattr(self.raw, 'stream'):
try:
for chunk in self.raw.stream(chunk_size, decode_content=True):
yield chunk
except ProtocolError as e:
raise ChunkedEncodingError(e)
except DecodeError as e:
raise ContentDecodingError(e)
except ReadTimeoutError as e:
raise ConnectionError(e)
else:
# Standard file-like object.
while True:
chunk = self.raw.read(chunk_size)
if not chunk:
break
yield chunk
self._content_consumed = True
if self._content_consumed and isinstance(self._content, bool):
raise StreamConsumedError()
elif chunk_size is not None and not isinstance(chunk_size, int):
raise TypeError("chunk_size must be an int, it is instead a %s." % type(chunk_size))
# simulate reading small chunks of the content
reused_chunks = iter_slices(self._content, chunk_size)
stream_chunks = generate()
chunks = reused_chunks if self._content_consumed else stream_chunks
if decode_unicode:
chunks = stream_decode_response_unicode(chunks, self)
return chunks
def iter_lines(self, chunk_size=ITER_CHUNK_SIZE, decode_unicode=False, delimiter=None):
"""Iterates over the response data, one line at a time. When
stream=True is set on the request, this avoids reading the
content at once into memory for large responses.
.. note:: This method is not reentrant safe.
"""
pending = None
for chunk in self.iter_content(chunk_size=chunk_size, decode_unicode=decode_unicode):
if pending is not None:
chunk = pending + chunk
if delimiter:
lines = chunk.split(delimiter)
else:
lines = chunk.splitlines()
if lines and lines[-1] and chunk and lines[-1][-1] == chunk[-1]:
pending = lines.pop()
else:
pending = None
for line in lines:
yield line
if pending is not None:
yield pending
@property
def content(self):
"""Content of the response, in bytes."""
if self._content is False:
# Read the contents.
if self._content_consumed:
raise RuntimeError(
'The content for this response was already consumed')
if self.status_code == 0 or self.raw is None:
self._content = None
else:
self._content = b''.join(self.iter_content(CONTENT_CHUNK_SIZE)) or b''
self._content_consumed = True
# don't need to release the connection; that's been handled by urllib3
# since we exhausted the data.
return self._content
@property
def text(self):
"""Content of the response, in unicode.
If Response.encoding is None, encoding will be guessed using
``charset_normalizer`` or ``chardet``.
The encoding of the response content is determined based solely on HTTP
headers, following RFC 2616 to the letter. If you can take advantage of
non-HTTP knowledge to make a better guess at the encoding, you should
set ``r.encoding`` appropriately before accessing this property.
"""
# Try charset from content-type
content = None
encoding = self.encoding
if not self.content:
return str('')
# Fallback to auto-detected encoding.
if self.encoding is None:
encoding = self.apparent_encoding
# Decode unicode from given encoding.
try:
content = str(self.content, encoding, errors='replace')
except (LookupError, TypeError):
# A LookupError is raised if the encoding was not found which could
# indicate a misspelling or similar mistake.
#
# A TypeError can be raised if encoding is None
#
# So we try blindly encoding.
content = str(self.content, errors='replace')
return content
def json(self, **kwargs):
r"""Returns the json-encoded content of a response, if any.
:param \*\*kwargs: Optional arguments that ``json.loads`` takes.
:raises simplejson.JSONDecodeError: If the response body does not
contain valid json and simplejson is installed.
:raises json.JSONDecodeError: If the response body does not contain
valid json and simplejson is not installed on Python 3.
:raises ValueError: If the response body does not contain valid
json and simplejson is not installed on Python 2.
"""
if not self.encoding and self.content and len(self.content) > 3:
# No encoding set. JSON RFC 4627 section 3 states we should expect
# UTF-8, -16 or -32. Detect which one to use; If the detection or
# decoding fails, fall back to `self.text` (using charset_normalizer to make
# a best guess).
encoding = guess_json_utf(self.content)
if encoding is not None:
try:
return complexjson.loads(
self.content.decode(encoding), **kwargs
)
except UnicodeDecodeError:
# Wrong UTF codec detected; usually because it's not UTF-8
# but some other 8-bit codec. This is an RFC violation,
# and the server didn't bother to tell us what codec *was*
# used.
pass
return complexjson.loads(self.text, **kwargs)
@property
def links(self):
"""Returns the parsed header links of the response, if any."""
header = self.headers.get('link')
# l = MultiDict()
l = {}
if header:
links = parse_header_links(header)
for link in links:
key = link.get('rel') or link.get('url')
l[key] = link
return l
def raise_for_status(self):
"""Raises :class:`HTTPError`, if one occurred."""
http_error_msg = ''
if isinstance(self.reason, bytes):
# We attempt to decode utf-8 first because some servers
# choose to localize their reason strings. If the string
# isn't utf-8, we fall back to iso-8859-1 for all other
# encodings. (See PR #3538)
try:
reason = self.reason.decode('utf-8')
except UnicodeDecodeError:
reason = self.reason.decode('iso-8859-1')
else:
reason = self.reason
if 400 <= self.status_code < 500:
http_error_msg = u'%s Client Error: %s for url: %s' % (self.status_code, reason, self.url)
elif 500 <= self.status_code < 600:
http_error_msg = u'%s Server Error: %s for url: %s' % (self.status_code, reason, self.url)
if http_error_msg:
raise HTTPError(http_error_msg, response=self)
def close(self):
"""Releases the connection back to the pool. Once this method has been
called the underlying ``raw`` object must not be accessed again.
*Note: Should not normally need to be called explicitly.*
"""
if not self._content_consumed:
self.raw.close()
release_conn = getattr(self.raw, 'release_conn', None)
if release_conn is not None:
release_conn()
================================================
FILE: modules/requests/packages.py
================================================
import sys
try:
import chardet
except ImportError:
import charset_normalizer as chardet
import warnings
warnings.filterwarnings('ignore', 'Trying to detect', module='charset_normalizer')
# This code exists for backwards compatibility reasons.
# I don't like it either. Just look the other way. :)
for package in ('urllib3', 'idna'):
locals()[package] = __import__(package)
# This traversal is apparently necessary such that the identities are
# preserved (requests.packages.urllib3.* is urllib3.*)
for mod in list(sys.modules):
if mod == package or mod.startswith(package + '.'):
sys.modules['requests.packages.' + mod] = sys.modules[mod]
target = chardet.__name__
for mod in list(sys.modules):
if mod == target or mod.startswith(target + '.'):
sys.modules['requests.packages.' + target.replace(target, 'chardet')] = sys.modules[mod]
# Kinda cool, though, right?
================================================
FILE: modules/requests/sessions.py
================================================
# -*- coding: utf-8 -*-
"""
requests.sessions
~~~~~~~~~~~~~~~~~
This module provides a Session object to manage and persist settings across
requests (cookies, auth, proxies).
"""
import os
import sys
import time
from datetime import timedelta
from collections import OrderedDict
from .auth import _basic_auth_str
from .compat import cookielib, is_py3, urljoin, urlparse, Mapping
from .cookies import (
cookiejar_from_dict, extract_cookies_to_jar, RequestsCookieJar, merge_cookies)
from .models import Request, PreparedRequest, DEFAULT_REDIRECT_LIMIT
from .hooks import default_hooks, dispatch_hook
from ._internal_utils import to_native_string
from .utils import to_key_val_list, default_headers, DEFAULT_PORTS
from .exceptions import (
TooManyRedirects, InvalidSchema, ChunkedEncodingError, ContentDecodingError)
from .structures import CaseInsensitiveDict
from .adapters import HTTPAdapter
from .utils import (
requote_uri, get_environ_proxies, get_netrc_auth, should_bypass_proxies,
get_auth_from_url, rewind_body
)
from .status_codes import codes
# formerly defined here, reexposed here for backward compatibility
from .models import REDIRECT_STATI
# Preferred clock, based on which one is more accurate on a given system.
if sys.platform == 'win32':
try: # Python 3.4+
preferred_clock = time.perf_counter
except AttributeError: # Earlier than Python 3.
preferred_clock = time.clock
else:
preferred_clock = time.time
def merge_setting(request_setting, session_setting, dict_class=OrderedDict):
"""Determines appropriate setting for a given request, taking into account
the explicit setting on that request, and the setting in the session. If a
setting is a dictionary, they will be merged together using `dict_class`
"""
if session_setting is None:
return request_setting
if request_setting is None:
return session_setting
# Bypass if not a dictionary (e.g. verify)
if not (
isinstance(session_setting, Mapping) and
isinstance(request_setting, Mapping)
):
return request_setting
merged_setting = dict_class(to_key_val_list(session_setting))
merged_setting.update(to_key_val_list(request_setting))
# Remove keys that are set to None. Extract keys first to avoid altering
# the dictionary during iteration.
none_keys = [k for (k, v) in merged_setting.items() if v is None]
for key in none_keys:
del merged_setting[key]
return merged_setting
def merge_hooks(request_hooks, session_hooks, dict_class=OrderedDict):
"""Properly merges both requests and session hooks.
This is necessary because when request_hooks == {'response': []}, the
merge breaks Session hooks entirely.
"""
if session_hooks is None or session_hooks.get('response') == []:
return request_hooks
if request_hooks is None or request_hooks.get('response') == []:
return session_hooks
return merge_setting(request_hooks, session_hooks, dict_class)
class SessionRedirectMixin(object):
def get_redirect_target(self, resp):
"""Receives a Response. Returns a redirect URI or ``None``"""
# Due to the nature of how requests processes redirects this method will
# be called at least once upon the original response and at least twice
# on each subsequent redirect response (if any).
# If a custom mixin is used to handle this logic, it may be advantageous
# to cache the redirect location onto the response object as a private
# attribute.
if resp.is_redirect:
location = resp.headers['location']
# Currently the underlying http module on py3 decode headers
# in latin1, but empirical evidence suggests that latin1 is very
# rarely used with non-ASCII characters in HTTP headers.
# It is more likely to get UTF8 header rather than latin1.
# This causes incorrect handling of UTF8 encoded location headers.
# To solve this, we re-encode the location in latin1.
if is_py3:
location = location.encode('latin1')
return to_native_string(location, 'utf8')
return None
def should_strip_auth(self, old_url, new_url):
"""Decide whether Authorization header should be removed when redirecting"""
old_parsed = urlparse(old_url)
new_parsed = urlparse(new_url)
if old_parsed.hostname != new_parsed.hostname:
return True
# Special case: allow http -> https redirect when using the standard
# ports. This isn't specified by RFC 7235, but is kept to avoid
# breaking backwards compatibility with older versions of requests
# that allowed any redirects on the same host.
if (old_parsed.scheme == 'http' and old_parsed.port in (80, None)
and new_parsed.scheme == 'https' and new_parsed.port in (443, None)):
return False
# Handle default port usage corresponding to scheme.
changed_port = old_parsed.port != new_parsed.port
changed_scheme = old_parsed.scheme != new_parsed.scheme
default_port = (DEFAULT_PORTS.get(old_parsed.scheme, None), None)
if (not changed_scheme and old_parsed.port in default_port
and new_parsed.port in default_port):
return False
# Standard case: root URI must match
return changed_port or changed_scheme
def resolve_redirects(self, resp, req, stream=False, timeout=None,
verify=True, cert=None, proxies=None, yield_requests=False, **adapter_kwargs):
"""Receives a Response. Returns a generator of Responses or Requests."""
hist = [] # keep track of history
url = self.get_redirect_target(resp)
previous_fragment = urlparse(req.url).fragment
while url:
prepared_request = req.copy()
# Update history and keep track of redirects.
# resp.history must ignore the original request in this loop
hist.append(resp)
resp.history = hist[1:]
try:
resp.content # Consume socket so it can be released
except (ChunkedEncodingError, ContentDecodingError, RuntimeError):
resp.raw.read(decode_content=False)
if len(resp.history) >= self.max_redirects:
raise TooManyRedirects('Exceeded {} redirects.'.format(self.max_redirects), response=resp)
# Release the connection back into the pool.
resp.close()
# Handle redirection without scheme (see: RFC 1808 Section 4)
if url.startswith('//'):
parsed_rurl = urlparse(resp.url)
url = ':'.join([to_native_string(parsed_rurl.scheme), url])
# Normalize url case and attach previous fragment if needed (RFC 7231 7.1.2)
parsed = urlparse(url)
if parsed.fragment == '' and previous_fragment:
parsed = parsed._replace(fragment=previous_fragment)
elif parsed.fragment:
previous_fragment = parsed.fragment
url = parsed.geturl()
# Facilitate relative 'location' headers, as allowed by RFC 7231.
# (e.g. '/path/to/resource' instead of 'http://domain.tld/path/to/resource')
# Compliant with RFC3986, we percent encode the url.
if not parsed.netloc:
url = urljoin(resp.url, requote_uri(url))
else:
url = requote_uri(url)
prepared_request.url = to_native_string(url)
self.rebuild_method(prepared_request, resp)
# https://github.com/psf/requests/issues/1084
if resp.status_code not in (codes.temporary_redirect, codes.permanent_redirect):
# https://github.com/psf/requests/issues/3490
purged_headers = ('Content-Length', 'Content-Type', 'Transfer-Encoding')
for header in purged_headers:
prepared_request.headers.pop(header, None)
prepared_request.body = None
headers = prepared_request.headers
headers.pop('Cookie', None)
# Extract any cookies sent on the response to the cookiejar
# in the new request. Because we've mutated our copied prepared
# request, use the old one that we haven't yet touched.
extract_cookies_to_jar(prepared_request._cookies, req, resp.raw)
merge_cookies(prepared_request._cookies, self.cookies)
prepared_request.prepare_cookies(prepared_request._cookies)
# Rebuild auth and proxy information.
proxies = self.rebuild_proxies(prepared_request, proxies)
self.rebuild_auth(prepared_request, resp)
# A failed tell() sets `_body_position` to `object()`. This non-None
# value ensures `rewindable` will be True, allowing us to raise an
# UnrewindableBodyError, instead of hanging the connection.
rewindable = (
prepared_request._body_position is not None and
('Content-Length' in headers or 'Transfer-Encoding' in headers)
)
# Attempt to rewind consumed file-like object.
if rewindable:
rewind_body(prepared_request)
# Override the original request.
req = prepared_request
if yield_requests:
yield req
else:
resp = self.send(
req,
stream=stream,
timeout=timeout,
verify=verify,
cert=cert,
proxies=proxies,
allow_redirects=False,
**adapter_kwargs
)
extract_cookies_to_jar(self.cookies, prepared_request, resp.raw)
# extract redirect url, if any, for the next loop
url = self.get_redirect_target(resp)
yield resp
def rebuild_auth(self, prepared_request, response):
"""When being redirected we may want to strip authentication from the
request to avoid leaking credentials. This method intelligently removes
and reapplies authentication where possible to avoid credential loss.
"""
headers = prepared_request.headers
url = prepared_request.url
if 'Authorization' in headers and self.should_strip_auth(response.request.url, url):
# If we get redirected to a new host, we should strip out any
# authentication headers.
del headers['Authorization']
# .netrc might have more auth for us on our new host.
new_auth = get_netrc_auth(url) if self.trust_env else None
if new_auth is not None:
prepared_request.prepare_auth(new_auth)
def rebuild_proxies(self, prepared_request, proxies):
"""This method re-evaluates the proxy configuration by considering the
environment variables. If we are redirected to a URL covered by
NO_PROXY, we strip the proxy configuration. Otherwise, we set missing
proxy keys for this URL (in case they were stripped by a previous
redirect).
This method also replaces the Proxy-Authorization header where
necessary.
:rtype: dict
"""
proxies = proxies if proxies is not None else {}
headers = prepared_request.headers
url = prepared_request.url
scheme = urlparse(url).scheme
new_proxies = proxies.copy()
no_proxy = proxies.get('no_proxy')
bypass_proxy = should_bypass_proxies(url, no_proxy=no_proxy)
if self.trust_env and not bypass_proxy:
environ_proxies = get_environ_proxies(url, no_proxy=no_proxy)
proxy = environ_proxies.get(scheme, environ_proxies.get('all'))
if proxy:
new_proxies.setdefault(scheme, proxy)
if 'Proxy-Authorization' in headers:
del headers['Proxy-Authorization']
try:
username, password = get_auth_from_url(new_proxies[scheme])
except KeyError:
username, password = None, None
if username and password:
headers['Proxy-Authorization'] = _basic_auth_str(username, password)
return new_proxies
def rebuild_method(self, prepared_request, response):
"""When being redirected we may want to change the method of the request
based on certain specs or browser behavior.
"""
method = prepared_request.method
# https://tools.ietf.org/html/rfc7231#section-6.4.4
if response.status_code == codes.see_other and method != 'HEAD':
method = 'GET'
# Do what the browsers do, despite standards...
# First, turn 302s into GETs.
if response.status_code == codes.found and method != 'HEAD':
method = 'GET'
# Second, if a POST is responded to with a 301, turn it into a GET.
# This bizarre behaviour is explained in Issue 1704.
if response.status_code == codes.moved and method == 'POST':
method = 'GET'
prepared_request.method = method
class Session(SessionRedirectMixin):
"""A Requests session.
Provides cookie persistence, connection-pooling, and configuration.
Basic Usage::
>>> import requests
>>> s = requests.Session()
>>> s.get('https://httpbin.org/get')
<Response [200]>
Or as a context manager::
>>> with requests.Session() as s:
... s.get('https://httpbin.org/get')
<Response [200]>
"""
__attrs__ = [
'headers', 'cookies', 'auth', 'proxies', 'hooks', 'params', 'verify',
'cert', 'adapters', 'stream', 'trust_env',
'max_redirects',
]
def __init__(self):
#: A case-insensitive dictionary of headers to be sent on each
#: :class:`Request <Request>` sent from this
#: :class:`Session <Session>`.
self.headers = default_headers()
#: Default Authentication tuple or object to attach to
#: :class:`Request <Request>`.
self.auth = None
#: Dictionary mapping protocol or protocol and host to the URL of the proxy
#: (e.g. {'http': 'foo.bar:3128', 'http://host.name': 'foo.bar:4012'}) to
#: be used on each :class:`Request <Request>`.
self.proxies = {}
#: Event-handling hooks.
self.hooks = default_hooks()
#: Dictionary of querystring data to attach to each
#: :class:`Request <Request>`. The dictionary values may be lists for
#: representing multivalued query parameters.
self.params = {}
#: Stream response content default.
self.stream = False
#: SSL Verification default.
#: Defaults to `True`, requiring requests to verify the TLS certificate at the
#: remote end.
#: If verify is set to `False`, requests will accept any TLS certificate
#: presented by the server, and will ignore hostname mismatches and/or
#: expired certificates, which will make your application vulnerable to
#: man-in-the-middle (MitM) attacks.
#: Only set this to `False` for testing.
self.verify = True
#: SSL client certificate default, if String, path to ssl client
#: cert file (.pem). If Tuple, ('cert', 'key') pair.
self.cert = None
#: Maximum number of redirects allowed. If the request exceeds this
#: limit, a :class:`TooManyRedirects` exception is raised.
#: This defaults to requests.models.DEFAULT_REDIRECT_LIMIT, which is
#: 30.
self.max_redirects = DEFAULT_REDIRECT_LIMIT
#: Trust environment settings for proxy configuration, default
#: authentication and similar.
self.trust_env = True
#: A CookieJar containing all currently outstanding cookies set on this
#: session. By default it is a
#: :class:`RequestsCookieJar <requests.cookies.RequestsCookieJar>`, but
#: may be any other ``cookielib.CookieJar`` compatible object.
self.cookies = cookiejar_from_dict({})
# Default connection adapters.
self.adapters = OrderedDict()
self.mount('https://', HTTPAdapter())
self.mount('http://', HTTPAdapter())
def __enter__(self):
return self
def __exit__(self, *args):
self.close()
def prepare_request(self, request):
"""Constructs a :class:`PreparedRequest <PreparedRequest>` for
transmission and returns it. The :class:`PreparedRequest` has settings
merged from the :class:`Request <Request>` instance and those of the
:class:`Session`.
:param request: :class:`Request` instance to prepare with this
session's settings.
:rtype: requests.PreparedRequest
"""
cookies = request.cookies or {}
# Bootstrap CookieJar.
if not isinstance(cookies, cookielib.CookieJar):
cookies = cookiejar_from_dict(cookies)
# Merge with session cookies
merged_cookies = merge_cookies(
merge_cookies(RequestsCookieJar(), self.cookies), cookies)
# Set environment's basic authentication if not explicitly set.
auth = request.auth
if self.trust_env and not auth and not self.auth:
auth = get_netrc_auth(request.url)
p = PreparedRequest()
p.prepare(
method=request.method.upper(),
url=request.url,
files=request.files,
data=request.data,
json=request.json,
headers=merge_setting(request.headers, self.headers, dict_class=CaseInsensitiveDict),
params=merge_setting(request.params, self.params),
auth=merge_setting(auth, self.auth),
cookies=merged_cookies,
hooks=merge_hooks(request.hooks, self.hooks),
)
return p
def request(self, method, url,
params=None, data=None, headers=None, cookies=None, files=None,
auth=None, timeout=None, allow_redirects=True, proxies=None,
hooks=None, stream=None, verify=None, cert=None, json=None):
"""Constructs a :class:`Request <Request>`, prepares it and sends it.
Returns :class:`Response <Response>` object.
:param method: method for the new :class:`Request` object.
:param url: URL for the new :class:`Request` object.
:param params: (optional) Dictionary or bytes to be sent in the query
string for the :class:`Request`.
:param data: (optional) Dictionary, list of tuples, bytes, or file-like
object to send in the body of the :class:`Request`.
:param json: (optional) json to send in the body of the
:class:`Request`.
:param headers: (optional) Dictionary of HTTP Headers to send with the
:class:`Request`.
:param cookies: (optional) Dict or CookieJar object to send with the
:class:`Request`.
:param files: (optional) Dictionary of ``'filename': file-like-objects``
for multipart encoding upload.
:param auth: (optional) Auth tuple or callable to enable
Basic/Digest/Custom HTTP Auth.
:param timeout: (optional) How long to wait for the server to send
data before giving up, as a float, or a :ref:`(connect timeout,
read timeout) <timeouts>` tuple.
:type timeout: float or tuple
:param allow_redirects: (optional) Set to True by default.
:type allow_redirects: bool
:param proxies: (optional) Dictionary mapping protocol or protocol and
hostname to the URL of the proxy.
:param stream: (optional) whether to immediately download the response
content. Defaults to ``False``.
:param verify: (optional) Either a boolean, in which case it controls whether we verify
the server's TLS certificate, or a string, in which case it must be a path
to a CA bundle to use. Defaults to ``True``. When set to
``False``, requests will accept any TLS certificate presented by
the server, and will ignore hostname mismatches and/or expired
certificates, which will make your application vulnerable to
man-in-the-middle (MitM) attacks. Setting verify to ``False``
may be useful during local development or testing.
:param cert: (optional) if String, path to ssl client cert file (.pem).
If Tuple, ('cert', 'key') pair.
:rtype: requests.Response
"""
# Create the Request.
req = Request(
method=method.upper(),
url=url,
headers=headers,
files=files,
data=data or {},
json=json,
params=params or {},
auth=auth,
cookies=cookies,
hooks=hooks,
)
prep = self.prepare_request(req)
proxies = proxies or {}
settings = self.merge_environment_settings(
prep.url, proxies, stream, verify, cert
)
# Send the request.
send_kwargs = {
'timeout': timeout,
'allow_redirects': allow_redirects,
}
send_kwargs.update(settings)
resp = self.send(prep, **send_kwargs)
return resp
def get(self, url, **kwargs):
r"""Sends a GET request. Returns :class:`Response` object.
:param url: URL for the new :class:`Request` object.
:param \*\*kwargs: Optional arguments that ``request`` takes.
:rtype: requests.Response
"""
kwargs.setdefault('allow_redirects', True)
return self.request('GET', url, **kwargs)
def options(self, url, **kwargs):
r"""Sends a OPTIONS request. Returns :class:`Response` object.
:param url: URL for the new :class:`Request` object.
:param \*\*kwargs: Optional arguments that ``request`` takes.
:rtype: requests.Response
"""
kwargs.setdefault('allow_redirects', True)
return self.request('OPTIONS', url, **kwargs)
def head(self, url, **kwargs):
r"""Sends a HEAD request. Returns :class:`Response` object.
:param url: URL for the new :class:`Request` object.
:param \*\*kwargs: Optional arguments that ``request`` takes.
:rtype: requests.Response
"""
kwargs.setdefault('allow_redirects', False)
return self.request('HEAD', url, **kwargs)
def post(self, url, data=None, json=None, **kwargs):
r"""Sends a POST request. Returns :class:`Response` object.
:param url: URL for the new :class:`Request` object.
:param data: (optional) Dictionary, list of tuples, bytes, or file-like
object to send in the body of the :class:`Request`.
:param json: (optional) json to send in the body of the :class:`Request`.
:param \*\*kwargs: Optional arguments that ``request`` takes.
:rtype: requests.Response
"""
return self.request('POST', url, data=data, json=json, **kwargs)
def put(self, url, data=None, **kwargs):
r"""Sends a PUT request. Returns :class:`Response` object.
:param url: URL for the new :class:`Request` object.
:param data: (optional) Dictionary, list of tuples, bytes, or file-like
object to send in the body of the :class:`Request`.
:param \*\*kwargs: Optional arguments that ``request`` takes.
:rtype: requests.Response
"""
return self.request('PUT', url, data=data, **kwargs)
def patch(self, url, data=None, **kwargs):
r"""Sends a PATCH request. Returns :class:`Response` object.
:param url: URL for the new :class:`Request` object.
:param data: (optional) Dictionary, list of tuples, bytes, or file-like
object to send in the body of the :class:`Request`.
:param \*\*kwargs: Optional arguments that ``request`` takes.
:rtype: requests.Response
"""
return self.request('PATCH', url, data=data, **kwargs)
def delete(self, url, **kwargs):
r"""Sends a DELETE request. Returns :class:`Response` object.
:param url: URL for the new :class:`Request` object.
:param \*\*kwargs: Optional arguments that ``request`` takes.
:rtype: requests.Response
"""
return self.request('DELETE', url, **kwargs)
def send(self, request, **kwargs):
"""Send a given PreparedRequest.
:rtype: requests.Response
"""
# Set defaults that the hooks can utilize to ensure they always have
# the correct parameters to reproduce the previous request.
kwargs.setdefault('stream', self.stream)
kwargs.setdefault('verify', self.verify)
kwargs.setdefault('cert', self.cert)
kwargs.setdefault('proxies', self.rebuild_proxies(request, self.proxies))
# It's possible that users might accidentally send a Request object.
# Guard against that specific failure case.
if isinstance(request, Request):
raise ValueError('You can only send PreparedRequests.')
# Set up variables needed for resolve_redirects and dispatching of hooks
allow_redirects = kwargs.pop('allow_redirects', True)
stream = kwargs.get('stream')
hooks = request.hooks
# Get the appropriate adapter to use
adapter = self.get_adapter(url=request.url)
# Start time (approximately) of the request
start = preferred_clock()
# Send the request
r = adapter.send(request, **kwargs)
# Total elapsed time of the request (approximately)
elapsed = preferred_clock() - start
r.elapsed = timedelta(seconds=elapsed)
# Response manipulation hooks
r = dispatch_hook('response', hooks, r, **kwargs)
# Persist cookies
if r.history:
# If the hooks create history then we want those cookies too
for resp in r.history:
extract_cookies_to_jar(self.cookies, resp.request, resp.raw)
extract_cookies_to_jar(self.cookies, request, r.raw)
# Resolve redirects if allowed.
if allow_redirects:
# Redirect resolving generator.
gen = self.resolve_redirects(r, request, **kwargs)
history = [resp for resp in gen]
else:
history = []
# Shuffle things around if there's history.
if history:
# Insert the first (original) request at the start
history.insert(0, r)
# Get the last request made
r = history.pop()
r.history = history
# If redirects aren't being followed, store the response on the Request for Response.next().
if not allow_redirects:
try:
r._next = next(self.resolve_redirects(r, request, yield_requests=True, **kwargs))
except StopIteration:
pass
if not stream:
r.content
return r
def merge_environment_settings(self, url, proxies, stream, verify, cert):
"""
Check the environment and merge it with some settings.
:rtype: dict
"""
# Gather clues from the surrounding environment.
if self.trust_env:
# Set environment's proxies.
no_proxy = proxies.get('no_proxy') if proxies is not None else None
env_proxies = get_environ_proxies(url, no_proxy=no_proxy)
for (k, v) in env_proxies.items():
proxies.setdefault(k, v)
# Look for requests environment configuration and be compatible
# with cURL.
if verify is True or verify is None:
verify = (os.environ.get('REQUESTS_CA_BUNDLE') or
os.environ.get('CURL_CA_BUNDLE'))
# Merge all the kwargs.
proxies = merge_setting(proxies, self.proxies)
stream = merge_setting(stream, self.stream)
verify = merge_setting(verify, self.verify)
cert = merge_setting(cert, self.cert)
return {'verify': verify, 'proxies': proxies, 'stream': stream,
'cert': cert}
def get_adapter(self, url):
"""
Returns the appropriate connection adapter for the given URL.
:rtype: requests.adapters.BaseAdapter
"""
for (prefix, adapter) in self.adapters.items():
if url.lower().startswith(prefix.lower()):
return adapter
# Nothing matches :-/
raise InvalidSchema("No connection adapters were found for {!r}".format(url))
def close(self):
"""Closes all adapters and as such the session"""
for v in self.adapters.values():
v.close()
def mount(self, prefix, adapter):
"""Registers a connection adapter to a prefix.
Adapters are sorted in descending order by prefix length.
"""
self.adapters[prefix] = adapter
keys_to_move = [k for k in self.adapters if len(k) < len(prefix)]
for key in keys_to_move:
self.adapters[key] = self.adapters.pop(key)
def __getstate__(self):
state = {attr: getattr(self, attr, None) for attr in self.__attrs__}
return state
def __setstate__(self, state):
for attr, value in state.items():
setattr(self, attr, value)
def session():
"""
Returns a :class:`Session` for context-management.
.. deprecated:: 1.0.0
This method has been deprecated since version 1.0.0 and is only kept for
backwards compatibility. New code should use :class:`~requests.sessions.Session`
to create a session. This may be removed at a future date.
:rtype: Session
"""
return Session()
================================================
FILE: modules/requests/status_codes.py
================================================
# -*- coding: utf-8 -*-
r"""
The ``codes`` object defines a mapping from common names for HTTP statuses
to their numerical codes, accessible either as attributes or as dictionary
items.
Example::
>>> import requests
>>> requests.codes['temporary_redirect']
307
>>> requests.codes.teapot
418
>>> requests.codes['\o/']
200
Some codes have multiple names, and both upper- and lower-case versions of
the names are allowed. For example, ``codes.ok``, ``codes.OK``, and
``codes.okay`` all correspond to the HTTP status code 200.
"""
from .structures import LookupDict
_codes = {
# Informational.
100: ('continue',),
101: ('switching_protocols',),
102: ('processing',),
103: ('checkpoint',),
122: ('uri_too_long', 'request_uri_too_long'),
200: ('ok', 'okay', 'all_ok', 'all_okay', 'all_good', '\\o/', '✓'),
201: ('created',),
202: ('accepted',),
203: ('non_authoritative_info', 'non_authoritative_information'),
204: ('no_content',),
205: ('reset_content', 'reset'),
206: ('partial_content', 'partial'),
207: ('multi_status', 'multiple_status', 'multi_stati', 'multiple_stati'),
208: ('already_reported',),
226: ('im_used',),
# Redirection.
300: ('multiple_choices',),
301: ('moved_permanently', 'moved', '\\o-'),
302: ('found',),
303: ('see_other', 'other'),
304: ('not_modified',),
305: ('use_proxy',),
306: ('switch_proxy',),
307: ('temporary_redirect', 'temporary_moved', 'temporary'),
308: ('permanent_redirect',
'resume_incomplete', 'resume',), # These 2 to be removed in 3.0
# Client Error.
400: ('bad_request', 'bad'),
401: ('unauthorized',),
402: ('payment_required', 'payment'),
403: ('forbidden',),
404: ('not_found', '-o-'),
405: ('method_not_allowed', 'not_allowed'),
406: ('not_acceptable',),
407: ('proxy_authentication_required', 'proxy_auth', 'proxy_authentication'),
408: ('request_timeout', 'timeout'),
409: ('conflict',),
410: ('gone',),
411: ('length_required',),
412: ('precondition_failed', 'precondition'),
413: ('request_entity_too_large',),
414: ('request_uri_too_large',),
415: ('unsupported_media_type', 'unsupported_media', 'media_type'),
416: ('requested_range_not_satisfiable', 'requested_range', 'range_not_satisfiable'),
417: ('expectation_failed',),
418: ('im_a_teapot', 'teapot', 'i_am_a_teapot'),
421: ('misdirected_request',),
422: ('unprocessable_entity', 'unprocessable'),
423: ('locked',),
424: ('failed_dependency', 'dependency'),
425: ('unordered_collection', 'unordered'),
426: ('upgrade_required', 'upgrade'),
428: ('precondition_required', 'precondition'),
429: ('too_many_requests', 'too_many'),
431: ('header_fields_too_large', 'fields_too_large'),
444: ('no_response', 'none'),
449: ('retry_with', 'retry'),
450: ('blocked_by_windows_parental_controls', 'parental_controls'),
451: ('unavailable_for_legal_reasons', 'legal_reasons'),
499: ('client_closed_request',),
# Server Error.
500: ('internal_server_error', 'server_error', '/o\\', '✗'),
501: ('not_implemented',),
502: ('bad_gateway',),
503: ('service_unavailable', 'unavailable'),
504: ('gateway_timeout',),
505: ('http_version_not_supported', 'http_version'),
506: ('variant_also_negotiates',),
507: ('insufficient_storage',),
509: ('bandwidth_limit_exceeded', 'bandwidth'),
510: ('not_extended',),
511: ('network_authentication_required', 'network_auth', 'network_authentication'),
}
codes = LookupDict(name='status_codes')
def _init():
for code, titles in _codes.items():
for title in titles:
setattr(codes, title, code)
if not title.startswith(('\\', '/')):
setattr(codes, title.upper(), code)
def doc(code):
names = ', '.join('``%s``' % n for n in _codes[code])
return '* %d: %s' % (code, names)
global __doc__
__doc__ = (__doc__ + '\n' +
'\n'.join(doc(code) for code in sorted(_codes))
if __doc__ is not None else None)
_init()
================================================
FILE: modules/requests/structures.py
================================================
# -*- coding: utf-8 -*-
"""
requests.structures
~~~~~~~~~~~~~~~~~~~
Data structures that power Requests.
"""
from collections import OrderedDict
from .compat import Mapping, MutableMapping
class CaseInsensitiveDict(MutableMapping):
"""A case-insensitive ``dict``-like object.
Implements all methods and operations of
``MutableMapping`` as well as dict's ``copy``. Also
provides ``lower_items``.
All keys are expected to be strings. The structure remembers the
case of the last key to be set, and ``iter(instance)``,
``keys()``, ``items()``, ``iterkeys()``, and ``iteritems()``
will contain case-sensitive keys. However, querying and contains
testing is case insensitive::
cid = CaseInsensitiveDict()
cid['Accept'] = 'application/json'
cid['aCCEPT'] == 'application/json' # True
list(cid) == ['Accept'] # True
For example, ``headers['content-encoding']`` will return the
value of a ``'Content-Encoding'`` response header, regardless
of how the header name was originally stored.
If the constructor, ``.update``, or equality comparison
operations are given keys that have equal ``.lower()``s, the
behavior is undefined.
"""
def __init__(self, data=None, **kwargs):
self._store = OrderedDict()
if data is None:
data = {}
self.update(data, **kwargs)
def __setitem__(self, key, value):
# Use the lowercased key for lookups, but store the actual
# key alongside the value.
self._store[key.lower()] = (key, value)
def __getitem__(self, key):
return self._store[key.lower()][1]
def __delitem__(self, key):
del self._store[key.lower()]
def __iter__(self):
return (casedkey for casedkey, mappedvalue in self._store.values())
def __len__(self):
return len(self._store)
def lower_items(self):
"""Like iteritems(), but with all lowercase keys."""
return (
(lowerkey, keyval[1])
for (lowerkey, keyval)
in self._store.items()
)
def __eq__(self, other):
if isinstance(other, Mapping):
other = CaseInsensitiveDict(other)
else:
return NotImplemented
# Compare insensitively
return dict(self.lower_items()) == dict(other.lower_items())
# Copy is required
def copy(self):
return CaseInsensitiveDict(self._store.values())
def __repr__(self):
return str(dict(self.items()))
class LookupDict(dict):
"""Dictionary lookup object."""
def __init__(self, name=None):
self.name = name
super(LookupDict, self).__init__()
def __repr__(self):
return '<lookup \'%s\'>' % (self.name)
def __getitem__(self, key):
# We allow fall-through here, so values default to None
return self.__dict__.get(key, None)
def get(self, key, default=None):
return self.__dict__.get(key, default)
================================================
FILE: modules/requests/utils.py
================================================
# -*- coding: utf-8 -*-
"""
requests.utils
~~~~~~~~~~~~~~
This module provides utility functions that are used within Requests
that are also useful for external consumption.
"""
import codecs
import contextlib
import io
import os
import re
import socket
import struct
import sys
import tempfile
import warnings
import zipfile
from collections import OrderedDict
from urllib3.util import make_headers
from .__version__ import __version__
from . import certs
# to_native_string is unused here, but imported here for backwards compatibility
from ._internal_utils import to_native_string
from .compat import parse_http_list as _parse_list_header
from .compat import (
quote, urlparse, bytes, str, unquote, getproxies,
proxy_bypass, urlunparse, basestring, integer_types, is_py3,
proxy_bypass_environment, getproxies_environment, Mapping)
from .cookies import cookiejar_from_dict
from .structures import CaseInsensitiveDict
from .exceptions import (
InvalidURL, InvalidHeader, FileModeWarning, UnrewindableBodyError)
NETRC_FILES = ('.netrc', '_netrc')
DEFAULT_CA_BUNDLE_PATH = certs.where()
DEFAULT_PORTS = {'http': 80, 'https': 443}
# Ensure that ', ' is used to preserve previous delimiter behavior.
DEFAULT_ACCEPT_ENCODING = ", ".join(
re.split(r",\s*", make_headers(accept_encoding=True)["accept-encoding"])
)
if sys.platform == 'win32':
# provide a proxy_bypass version on Windows without DNS lookups
def proxy_bypass_registry(host):
try:
if is_py3:
import winreg
else:
import _winreg as winreg
except ImportError:
return False
try:
internetSettings = winreg.OpenKey(winreg.HKEY_CURRENT_USER,
r'Software\Microsoft\Windows\CurrentVersion\Internet Settings')
# ProxyEnable could be REG_SZ or REG_DWORD, normalizing it
proxyEnable = int(winreg.QueryValueEx(internetSettings,
'ProxyEnable')[0])
# ProxyOverride is almost always a string
proxyOverride = winreg.QueryValueEx(internetSettings,
'ProxyOverride')[0]
except OSError:
return False
if not proxyEnable or not proxyOverride:
return False
# make a check value list from the registry entry: replace the
# '<local>' string by the localhost entry and the corresponding
# canonical entry.
proxyOverride = proxyOverride.split(';')
# now check if we match one of the registry values.
for test in proxyOverride:
if test == '<local>':
if '.' not in host:
return True
test = test.replace(".", r"\.") # mask dots
test = test.replace("*", r".*") # change glob sequence
test = test.replace("?", r".") # change glob char
if re.match(test, host, re.I):
return True
return False
def proxy_bypass(host): # noqa
"""Return True, if the host should be bypassed.
Checks proxy settings gathered from the environment, if specified,
or the registry.
"""
if getproxies_environment():
return proxy_bypass_environment(host)
else:
return proxy_bypass_registry(host)
def dict_to_sequence(d):
"""Returns an internal sequence dictionary update."""
if hasattr(d, 'items'):
d = d.items()
return d
def super_len(o):
total_length = None
current_position = 0
if hasattr(o, '__len__'):
total_length = len(o)
elif hasattr(o, 'len'):
total_length = o.len
elif hasattr(o, 'fileno'):
try:
fileno = o.fileno()
except io.UnsupportedOperation:
pass
else:
total_length = os.fstat(fileno).st_size
# Having used fstat to determine the file length, we need to
# confirm that this file was opened up in binary mode.
if 'b' not in o.mode:
warnings.warn((
"Requests has determined the content-length for this "
"request using the binary size of the file: however, the "
"file has been opened in text mode (i.e. without the 'b' "
"flag in the mode). This may lead to an incorrect "
"content-length. In Requests 3.0, support will be removed "
"for files in text mode."),
FileModeWarning
)
if hasattr(o, 'tell'):
try:
current_position = o.tell()
except (OSError, IOError):
# This can happen in some weird situations, such as when the file
# is actually a special file descriptor like stdin. In this
# instance, we don't know what the length is, so set it to zero and
# let requests chunk it instead.
if total_length is not None:
current_position = total_length
else:
if hasattr(o, 'seek') and total_length is None:
# StringIO and BytesIO have seek but no useable fileno
try:
# seek to end of file
o.seek(0, 2)
total_length = o.tell()
# seek back to current position to support
# partially read file-like objects
o.seek(current_position or 0)
except (OSError, IOError):
total_length = 0
if total_length is None:
total_length = 0
return max(0, total_length - current_position)
def get_netrc_auth(url, raise_errors=False):
"""Returns the Requests tuple auth for a given url from netrc."""
netrc_file = os.environ.get('NETRC')
if netrc_file is not None:
netrc_locations = (netrc_file,)
else:
netrc_locations = ('~/{}'.format(f) for f in NETRC_FILES)
try:
from netrc import netrc, NetrcParseError
netrc_path = None
for f in netrc_locations:
try:
loc = os.path.expanduser(f)
except KeyError:
# os.path.expanduser can fail when $HOME is undefined and
# getpwuid fails. See https://bugs.python.org/issue20164 &
# https://github.com/psf/requests/issues/1846
return
if os.path.exists(loc):
netrc_path = loc
break
# Abort early if there isn't one.
if netrc_path is None:
return
ri = urlparse(url)
# Strip port numbers from netloc. This weird `if...encode`` dance is
# used for Python 3.2, which doesn't support unicode literals.
splitstr = b':'
if isinstance(url, str):
splitstr = splitstr.decode('ascii')
host = ri.netloc.split(splitstr)[0]
try:
_netrc = netrc(netrc_path).authenticators(host)
if _netrc:
# Return with login / password
login_i = (0 if _netrc[0] else 1)
return (_netrc[login_i], _netrc[2])
except (NetrcParseError, IOError):
# If there was a parsing error or a permissions issue reading the file,
# we'll just skip netrc auth unless explicitly asked to raise errors.
if raise_errors:
raise
# App Engine hackiness.
except (ImportError, AttributeError):
pass
def guess_filename(obj):
"""Tries to guess the filename of the given object."""
name = getattr(obj, 'name', None)
if (name and isinstance(name, basestring) and name[0] != '<' and
name[-1] != '>'):
return os.path.basename(name)
def extract_zipped_paths(path):
"""Replace nonexistent paths that look like they refer to a member of a zip
archive with the location of an extracted copy of the target, or else
just return the provided path unchanged.
"""
if os.path.exists(path):
# this is already a valid path, no need to do anything further
return path
# find the first valid part of the provided path and treat that as a zip archive
# assume the rest of the path is the name of a member in the archive
archive, member = os.path.split(path)
while archive and not os.path.exists(archive):
archive, prefix = os.path.split(archive)
member = '/'.join([prefix, member])
if not zipfile.is_zipfile(archive):
return path
zip_file = zipfile.ZipFile(archive)
if member not in zip_file.namelist():
return path
# we have a valid zip archive and a valid member of that archive
tmp = tempfile.gettempdir()
extracted_path = os.path.join(tmp, member.split('/')[-1])
if not os.path.exists(extracted_path):
# use read + write to avoid the creating nested folders, we only want the file, avoids mkdir racing condition
with atomic_open(extracted_path) as file_handler:
file_handler.write(zip_file.read(member))
return extracted_path
@contextlib.contextmanager
def atomic_open(filename):
"""Write a file to the disk in an atomic fashion"""
replacer = os.rename if sys.version_info[0] == 2 else os.replace
tmp_descriptor, tmp_name = tempfile.mkstemp(dir=os.path.dirname(filename))
try:
with os.fdopen(tmp_descriptor, 'wb') as tmp_handler:
yield tmp_handler
replacer(tmp_name, filename)
except BaseException:
os.remove(tmp_name)
raise
def from_key_val_list(value):
"""Take an object and test to see if it can be represented as a
dictionary. Unless it can not be represented as such, return an
OrderedDict, e.g.,
::
>>> from_key_val_list([('key', 'val')])
OrderedDict([('key', 'val')])
>>> from_key_val_list('string')
Traceback (most recent call last):
...
ValueError: cannot encode objects that are not 2-tuples
>>> from_key_val_list({'key': 'val'})
OrderedDict([('key', 'val')])
:rtype: OrderedDict
"""
if value is None:
return None
if isinstance(value, (str, bytes, bool, int)):
raise ValueError('cannot encode objects that are not 2-tuples')
return OrderedDict(value)
def to_key_val_list(value):
"""Take an object and test to see if it can be represented as a
dictionary. If it can be, return a list of tuples, e.g.,
::
>>> to_key_val_list([('key', 'val')])
[('key', 'val')]
>>> to_key_val_list({'key': 'val'})
[('key', 'val')]
>>> to_key_val_list('string')
Traceback (most recent call last):
...
ValueError: cannot encode objects that are not 2-tuples
:rtype: list
"""
if value is None:
return None
if isinstance(value, (str, bytes, bool, int)):
raise ValueError('cannot encode objects that are not 2-tuples')
if isinstance(value, Mapping):
value = value.items()
return list(value)
# From mitsuhiko/werkzeug (used with permission).
def parse_list_header(value):
"""Parse lists as described by RFC 2068 Section 2.
In pa
gitextract_heteqtr4/ ├── LICENSE ├── README.md ├── executable/ │ └── pyinstxtractor.py ├── modules/ │ ├── blue.py │ ├── dhooks.py │ ├── fade.py │ ├── getmac.py │ ├── gratient.py │ ├── json.py │ ├── playsound.py │ ├── pycenter.py │ ├── pyfade.py │ ├── pyproxies.py │ ├── random.py │ ├── re.py │ ├── requests/ │ │ ├── __init__.py │ │ ├── __version__.py │ │ ├── _internal_utils.py │ │ ├── adapters.py │ │ ├── api.py │ │ ├── auth.py │ │ ├── certs.py │ │ ├── compat.py │ │ ├── cookies.py │ │ ├── exceptions.py │ │ ├── help.py │ │ ├── hooks.py │ │ ├── models.py │ │ ├── packages.py │ │ ├── sessions.py │ │ ├── status_codes.py │ │ ├── structures.py │ │ └── utils.py │ ├── tkinter/ │ │ ├── colorchooser.py │ │ ├── commondialog.py │ │ ├── constants.py │ │ ├── dialog.py │ │ ├── dnd.py │ │ ├── filedialog.py │ │ ├── font.py │ │ ├── messagebox.py │ │ ├── scrolledtext.py │ │ ├── simpledialog.py │ │ └── test/ │ │ ├── README │ │ ├── runtktests.py │ │ ├── support.py │ │ └── test_tkinter/ │ │ ├── test_colorchooser.py │ │ ├── test_font.py │ │ ├── test_geometry_managers.py │ │ ├── test_images.py │ │ ├── test_loadtk.py │ │ ├── test_misc.py │ │ ├── test_simpledialog.py │ │ ├── test_text.py │ │ ├── test_variables.py │ │ └── test_widgets.py │ └── urllib3/ │ ├── connection.py │ ├── connectionpool.py │ └── contrib/ │ ├── _appengine_environ.py │ ├── _securetransport/ │ │ ├── bindings.py │ │ └── low_level.py │ ├── appengine.py │ ├── ntlmpool.py │ ├── pyopenssl.py │ ├── securetransport.py │ └── socks.py ├── mysterium.py └── requirements.txt
SYMBOL INDEX (1080 symbols across 59 files)
FILE: executable/pyinstxtractor.py
class CTOCEntry (line 103) | class CTOCEntry:
method __init__ (line 104) | def __init__(self, position, cmprsdDataSize, uncmprsdDataSize, cmprsFl...
class PyInstArchive (line 113) | class PyInstArchive:
method __init__ (line 118) | def __init__(self, path):
method open (line 122) | def open(self):
method close (line 132) | def close(self):
method checkFile (line 139) | def checkFile(self):
method getCArchiveInfo (line 187) | def getCArchiveInfo(self):
method parseTOC (line 222) | def parseTOC(self):
method _writeRawData (line 258) | def _writeRawData(self, filepath, data):
method extractFiles (line 268) | def extractFiles(self):
method _writePyc (line 312) | def _writePyc(self, filename, data):
method _extractPyz (line 328) | def _extractPyz(self, name):
function main (line 396) | def main():
FILE: modules/blue.py
class Blue (line 9) | class Blue:
method __init__ (line 11) | def __init__(self, filePath, fileName):
method add_logs (line 57) | def add_logs(self, text):
method debug (line 66) | def debug(self, type, value, a=False) -> str:
method question_options (line 70) | def question_options(self, text, option):
method settings (line 78) | def settings(self):
method reading_file (line 92) | def reading_file(self):
method define_fake_variables_and_function (line 99) | def define_fake_variables_and_function(self, v_name):
method finding_variables (line 109) | def finding_variables(self):
method execute_file (line 160) | def execute_file(self):
method save_logs (line 175) | def save_logs(self):
method create_source_code (line 184) | def create_source_code(self):
FILE: modules/dhooks.py
class Webhook (line 3) | class Webhook:
method __init__ (line 4) | def __init__(self, url, **kwargs):
method send (line 8) | def send(self, content: str = "", **kwargs):
method modify (line 11) | def modify(self, name, **kwargs):
method get_info (line 14) | def get_info(self):
method close (line 18) | def close(self):
method delete (line 21) | def delete(self):
FILE: modules/fade.py
function blackwhite (line 3) | def blackwhite(text):
function purplepink (line 7) | def purplepink(text):
function greenblue (line 11) | def greenblue(text):
function pinkred (line 15) | def pinkred(text):
function purpleblue (line 19) | def purpleblue(text):
function water (line 23) | def water(text):
function fire (line 27) | def fire(text):
function brazil (line 31) | def brazil(text):
function random (line 35) | def random(text):
FILE: modules/getmac.py
function get_mac_address (line 3) | def get_mac_address(interface=None, ip=None, ip6=None, hostname=None, ne...
FILE: modules/gratient.py
function black (line 3) | def black(text):
function green (line 7) | def green(text):
function blue (line 11) | def blue(text):
function purple (line 15) | def purple(text):
function yellow (line 19) | def yellow(text):
function red (line 23) | def red(text):
FILE: modules/json.py
function dump (line 3) | def dump(obj, fp=False, *, skipkeys=False, ensure_ascii=True, check_circ...
function dumps (line 8) | def dumps(obj, *, skipkeys=False, ensure_ascii=True, check_circular=True...
function detect_encoding (line 13) | def detect_encoding(b):
function load (line 17) | def load(fp, *, cls=None, object_hook=None, parse_float=None, parse_int=...
function loads (line 22) | def loads(s, *, cls=None, object_hook=None, parse_float=None, parse_int=...
FILE: modules/playsound.py
function playsound (line 3) | def playsound(sound, block=True):
FILE: modules/pycenter.py
function center (line 3) | def center(var: str, space: int = None, icon: str = "", sep: bool = False):
function makebox (line 8) | def makebox(content: str):
FILE: modules/pyfade.py
function init (line 3) | def init():
function ditto (line 6) | def ditto(text):
class Fade (line 9) | class Fade:
method check (line 10) | def check(line):
method Vertical (line 14) | def Vertical(color, text: str, speed: int = 1, start: int = 0, stop: i...
method Horizontal (line 19) | def Horizontal(color, text: str, speed: int = 1, start: int = 0, stop:...
method Diagonal (line 24) | def Diagonal(color, text: str, speed: int = 1, start: int = 0, stop: i...
class Colors (line 29) | class Colors:
FILE: modules/pyproxies.py
function proxy (line 3) | def proxy(server, timeout = 5):
FILE: modules/random.py
class Random (line 3) | class Random:
method randbytes (line 4) | def randbytes(n):
method randrange (line 8) | def randrange(start, stop=None, step=1):
method randint (line 13) | def randint(a, b):
method choice (line 17) | def choice(seq):
method gauss (line 21) | def gauss(mu, sigma):
method random (line 25) | def random():
method getrandbits (line 29) | def getrandbits(k):
FILE: modules/re.py
function findall (line 3) | def findall(pattern, string, flags=0):
function split (line 7) | def split(pattern, string, maxsplit=0, flags=0):
function subn (line 11) | def subn(pattern, repl, string, count=0, flags=0):
function sub (line 15) | def sub(pattern, repl, string, count=0, flags=0):
function search (line 19) | def search(pattern, string, flags=0):
function fullmatch (line 23) | def fullmatch(pattern, string, flags=0):
function match (line 27) | def match(pattern, string, flags=0):
function finditer (line 31) | def finditer(pattern, string, flags=0):
function purge (line 35) | def purge():
function template (line 39) | def template(pattern, flags=0):
function escape (line 43) | def escape(pattern):
function compile (line 47) | def compile(pattern, flags=0):
function findall (line 62) | def findall(pattern, string, flags=0):
function split (line 66) | def split(pattern, string, maxsplit=0, flags=0):
function subn (line 70) | def subn(pattern, repl, string, count=0, flags=0):
function sub (line 74) | def sub(pattern, repl, string, count=0, flags=0):
function search (line 78) | def search(pattern, string, flags=0):
function fullmatch (line 82) | def fullmatch(pattern, string, flags=0):
function match (line 86) | def match(pattern, string, flags=0):
function finditer (line 90) | def finditer(pattern, string, flags=0):
function purge (line 94) | def purge():
function template (line 98) | def template(pattern, flags=0):
function escape (line 102) | def escape(pattern):
function compile (line 106) | def compile(pattern, flags=0):
FILE: modules/requests/__init__.py
class Session (line 3) | class Session:
function get (line 6) | def get(url=False, auth=None, json=False, data=False, hooks=None, files=...
function post (line 20) | def post(url=False, auth=None, json=False, data=False, hooks=None, files...
function patch (line 34) | def patch(url=False, auth=None, json=False, data=False, hooks=None, file...
function delete (line 48) | def delete(url=False, auth=None, json=False, data=False, hooks=None, fil...
FILE: modules/requests/_internal_utils.py
function to_native_string (line 14) | def to_native_string(string, encoding='ascii'):
function unicode_is_ascii (line 30) | def unicode_is_ascii(u_string):
FILE: modules/requests/adapters.py
function SOCKSProxyManager (line 46) | def SOCKSProxyManager(*args, **kwargs):
class BaseAdapter (line 55) | class BaseAdapter(object):
method __init__ (line 58) | def __init__(self):
method send (line 61) | def send(self, request, stream=False, timeout=None, verify=True,
method close (line 79) | def close(self):
class HTTPAdapter (line 84) | class HTTPAdapter(BaseAdapter):
method __init__ (line 113) | def __init__(self, pool_connections=DEFAULT_POOLSIZE,
method __getstate__ (line 131) | def __getstate__(self):
method __setstate__ (line 134) | def __setstate__(self, state):
method init_poolmanager (line 146) | def init_poolmanager(self, connections, maxsize, block=DEFAULT_POOLBLO...
method proxy_manager_for (line 166) | def proxy_manager_for(self, proxy, **proxy_kwargs):
method cert_verify (line 203) | def cert_verify(self, conn, url, verify, cert):
method build_response (line 255) | def build_response(self, req, resp):
method get_connection (line 292) | def get_connection(self, url, proxies=None):
method close (line 319) | def close(self):
method request_url (line 329) | def request_url(self, request, proxies):
method add_headers (line 358) | def add_headers(self, request, **kwargs):
method proxy_headers (line 372) | def proxy_headers(self, proxy):
method send (line 394) | def send(self, request, stream=False, timeout=None, verify=True, cert=...
FILE: modules/requests/api.py
function request (line 16) | def request(method, url, **kwargs):
function get (line 64) | def get(url, params=None, **kwargs):
function options (line 78) | def options(url, **kwargs):
function head (line 90) | def head(url, **kwargs):
function post (line 105) | def post(url, data=None, json=None, **kwargs):
function put (line 120) | def put(url, data=None, **kwargs):
function patch (line 135) | def patch(url, data=None, **kwargs):
function delete (line 150) | def delete(url, **kwargs):
FILE: modules/requests/auth.py
function _basic_auth_str (line 28) | def _basic_auth_str(username, password):
class AuthBase (line 72) | class AuthBase(object):
method __call__ (line 75) | def __call__(self, r):
class HTTPBasicAuth (line 79) | class HTTPBasicAuth(AuthBase):
method __init__ (line 82) | def __init__(self, username, password):
method __eq__ (line 86) | def __eq__(self, other):
method __ne__ (line 92) | def __ne__(self, other):
method __call__ (line 95) | def __call__(self, r):
class HTTPProxyAuth (line 100) | class HTTPProxyAuth(HTTPBasicAuth):
method __call__ (line 103) | def __call__(self, r):
class HTTPDigestAuth (line 108) | class HTTPDigestAuth(AuthBase):
method __init__ (line 111) | def __init__(self, username, password):
method init_per_thread_state (line 117) | def init_per_thread_state(self):
method build_digest_header (line 127) | def build_digest_header(self, method, url):
method handle_redirect (line 229) | def handle_redirect(self, r, **kwargs):
method handle_401 (line 234) | def handle_401(self, r, **kwargs):
method __call__ (line 278) | def __call__(self, r):
method __eq__ (line 298) | def __eq__(self, other):
method __ne__ (line 304) | def __ne__(self, other):
FILE: modules/requests/cookies.py
class MockRequest (line 25) | class MockRequest(object):
method __init__ (line 37) | def __init__(self, request):
method get_type (line 42) | def get_type(self):
method get_host (line 45) | def get_host(self):
method get_origin_req_host (line 48) | def get_origin_req_host(self):
method get_full_url (line 51) | def get_full_url(self):
method is_unverifiable (line 65) | def is_unverifiable(self):
method has_header (line 68) | def has_header(self, name):
method get_header (line 71) | def get_header(self, name, default=None):
method add_header (line 74) | def add_header(self, key, val):
method add_unredirected_header (line 78) | def add_unredirected_header(self, name, value):
method get_new_headers (line 81) | def get_new_headers(self):
method unverifiable (line 85) | def unverifiable(self):
method origin_req_host (line 89) | def origin_req_host(self):
method host (line 93) | def host(self):
class MockResponse (line 97) | class MockResponse(object):
method __init__ (line 104) | def __init__(self, headers):
method info (line 111) | def info(self):
method getheaders (line 114) | def getheaders(self, name):
function extract_cookies_to_jar (line 118) | def extract_cookies_to_jar(jar, request, response):
function get_cookie_header (line 135) | def get_cookie_header(jar, request):
function remove_cookie_by_name (line 146) | def remove_cookie_by_name(cookiejar, name, domain=None, path=None):
class CookieConflictError (line 165) | class CookieConflictError(RuntimeError):
class RequestsCookieJar (line 171) | class RequestsCookieJar(cookielib.CookieJar, MutableMapping):
method get (line 189) | def get(self, name, default=None, domain=None, path=None):
method set (line 201) | def set(self, name, value, **kwargs):
method iterkeys (line 218) | def iterkeys(self):
method keys (line 227) | def keys(self):
method itervalues (line 235) | def itervalues(self):
method values (line 244) | def values(self):
method iteritems (line 252) | def iteritems(self):
method items (line 261) | def items(self):
method list_domains (line 270) | def list_domains(self):
method list_paths (line 278) | def list_paths(self):
method multiple_domains (line 286) | def multiple_domains(self):
method get_dict (line 299) | def get_dict(self, domain=None, path=None):
method __contains__ (line 315) | def __contains__(self, name):
method __getitem__ (line 321) | def __getitem__(self, name):
method __setitem__ (line 330) | def __setitem__(self, name, value):
method __delitem__ (line 337) | def __delitem__(self, name):
method set_cookie (line 343) | def set_cookie(self, cookie, *args, **kwargs):
method update (line 348) | def update(self, other):
method _find (line 356) | def _find(self, name, domain=None, path=None):
method _find_no_duplicates (line 376) | def _find_no_duplicates(self, name, domain=None, path=None):
method __getstate__ (line 401) | def __getstate__(self):
method __setstate__ (line 408) | def __setstate__(self, state):
method copy (line 414) | def copy(self):
method get_policy (line 421) | def get_policy(self):
function _copy_cookie_jar (line 426) | def _copy_cookie_jar(jar):
function create_cookie (line 441) | def create_cookie(name, value, **kwargs):
function morsel_to_cookie (line 477) | def morsel_to_cookie(morsel):
function cookiejar_from_dict (line 508) | def cookiejar_from_dict(cookie_dict, cookiejar=None, overwrite=True):
function merge_cookies (line 529) | def merge_cookies(cookiejar, cookies):
FILE: modules/requests/exceptions.py
class RequestException (line 12) | class RequestException(IOError):
method __init__ (line 17) | def __init__(self, *args, **kwargs):
class InvalidJSONError (line 28) | class InvalidJSONError(RequestException):
class HTTPError (line 32) | class HTTPError(RequestException):
class ConnectionError (line 36) | class ConnectionError(RequestException):
class ProxyError (line 40) | class ProxyError(ConnectionError):
class SSLError (line 44) | class SSLError(ConnectionError):
class Timeout (line 48) | class Timeout(RequestException):
class ConnectTimeout (line 57) | class ConnectTimeout(ConnectionError, Timeout):
class ReadTimeout (line 64) | class ReadTimeout(Timeout):
class URLRequired (line 68) | class URLRequired(RequestException):
class TooManyRedirects (line 72) | class TooManyRedirects(RequestException):
class MissingSchema (line 76) | class MissingSchema(RequestException, ValueError):
class InvalidSchema (line 80) | class InvalidSchema(RequestException, ValueError):
class InvalidURL (line 84) | class InvalidURL(RequestException, ValueError):
class InvalidHeader (line 88) | class InvalidHeader(RequestException, ValueError):
class InvalidProxyURL (line 92) | class InvalidProxyURL(InvalidURL):
class ChunkedEncodingError (line 96) | class ChunkedEncodingError(RequestException):
class ContentDecodingError (line 100) | class ContentDecodingError(RequestException, BaseHTTPError):
class StreamConsumedError (line 104) | class StreamConsumedError(RequestException, TypeError):
class RetryError (line 108) | class RetryError(RequestException):
class UnrewindableBodyError (line 112) | class UnrewindableBodyError(RequestException):
class RequestsWarning (line 118) | class RequestsWarning(Warning):
class FileModeWarning (line 122) | class FileModeWarning(RequestsWarning, DeprecationWarning):
class RequestsDependencyWarning (line 126) | class RequestsDependencyWarning(RequestsWarning):
FILE: modules/requests/help.py
function _implementation (line 35) | def _implementation():
function info (line 68) | def info():
function main (line 129) | def main():
FILE: modules/requests/hooks.py
function default_hooks (line 17) | def default_hooks():
function dispatch_hook (line 23) | def dispatch_hook(key, hooks, hook_data, **kwargs):
FILE: modules/requests/models.py
class RequestEncodingMixin (line 60) | class RequestEncodingMixin(object):
method path_url (line 62) | def path_url(self):
method _encode_params (line 83) | def _encode_params(data):
method _encode_files (line 110) | def _encode_files(files, data):
class RequestHooksMixin (line 174) | class RequestHooksMixin(object):
method register_hook (line 175) | def register_hook(self, event, hook):
method deregister_hook (line 186) | def deregister_hook(self, event, hook):
class Request (line 198) | class Request(RequestHooksMixin):
method __init__ (line 226) | def __init__(self,
method __repr__ (line 251) | def __repr__(self):
method prepare (line 254) | def prepare(self):
class PreparedRequest (line 272) | class PreparedRequest(RequestEncodingMixin, RequestHooksMixin):
method __init__ (line 293) | def __init__(self):
method prepare (line 310) | def prepare(self,
method __repr__ (line 328) | def __repr__(self):
method copy (line 331) | def copy(self):
method prepare_method (line 342) | def prepare_method(self, method):
method _get_idna_encoded_host (line 349) | def _get_idna_encoded_host(host):
method prepare_url (line 358) | def prepare_url(self, url, params):
method prepare_headers (line 444) | def prepare_headers(self, headers):
method prepare_body (line 455) | def prepare_body(self, data, files, json=None):
method prepare_content_length (line 529) | def prepare_content_length(self, body):
method prepare_auth (line 542) | def prepare_auth(self, auth, url=''):
method prepare_cookies (line 564) | def prepare_cookies(self, cookies):
method prepare_hooks (line 584) | def prepare_hooks(self, hooks):
class Response (line 594) | class Response(object):
method __init__ (line 604) | def __init__(self):
method __enter__ (line 651) | def __enter__(self):
method __exit__ (line 654) | def __exit__(self, *args):
method __getstate__ (line 657) | def __getstate__(self):
method __setstate__ (line 665) | def __setstate__(self, state):
method __repr__ (line 673) | def __repr__(self):
method __bool__ (line 676) | def __bool__(self):
method __nonzero__ (line 686) | def __nonzero__(self):
method __iter__ (line 696) | def __iter__(self):
method ok (line 701) | def ok(self):
method is_redirect (line 716) | def is_redirect(self):
method is_permanent_redirect (line 723) | def is_permanent_redirect(self):
method next (line 728) | def next(self):
method apparent_encoding (line 733) | def apparent_encoding(self):
method iter_content (line 737) | def iter_content(self, chunk_size=1, decode_unicode=False):
method iter_lines (line 792) | def iter_lines(self, chunk_size=ITER_CHUNK_SIZE, decode_unicode=False,...
method content (line 824) | def content(self):
method text (line 844) | def text(self):
method json (line 881) | def json(self, **kwargs):
method links (line 913) | def links(self):
method raise_for_status (line 930) | def raise_for_status(self):
method close (line 955) | def close(self):
FILE: modules/requests/sessions.py
function merge_setting (line 50) | def merge_setting(request_setting, session_setting, dict_class=OrderedDi...
function merge_hooks (line 81) | def merge_hooks(request_hooks, session_hooks, dict_class=OrderedDict):
class SessionRedirectMixin (line 96) | class SessionRedirectMixin(object):
method get_redirect_target (line 98) | def get_redirect_target(self, resp):
method should_strip_auth (line 119) | def should_strip_auth(self, old_url, new_url):
method resolve_redirects (line 144) | def resolve_redirects(self, resp, req, stream=False, timeout=None,
method rebuild_auth (line 254) | def rebuild_auth(self, prepared_request, response):
method rebuild_proxies (line 273) | def rebuild_proxies(self, prepared_request, proxies):
method rebuild_method (line 314) | def rebuild_method(self, prepared_request, response):
class Session (line 337) | class Session(SessionRedirectMixin):
method __init__ (line 362) | def __init__(self):
method __enter__ (line 424) | def __enter__(self):
method __exit__ (line 427) | def __exit__(self, *args):
method prepare_request (line 430) | def prepare_request(self, request):
method request (line 470) | def request(self, method, url,
method get (line 546) | def get(self, url, **kwargs):
method options (line 557) | def options(self, url, **kwargs):
method head (line 568) | def head(self, url, **kwargs):
method post (line 579) | def post(self, url, data=None, json=None, **kwargs):
method put (line 592) | def put(self, url, data=None, **kwargs):
method patch (line 604) | def patch(self, url, data=None, **kwargs):
method delete (line 616) | def delete(self, url, **kwargs):
method send (line 626) | def send(self, request, **kwargs):
method merge_environment_settings (line 701) | def merge_environment_settings(self, url, proxies, stream, verify, cert):
method get_adapter (line 730) | def get_adapter(self, url):
method close (line 744) | def close(self):
method mount (line 749) | def mount(self, prefix, adapter):
method __getstate__ (line 760) | def __getstate__(self):
method __setstate__ (line 764) | def __setstate__(self, state):
function session (line 769) | def session():
FILE: modules/requests/status_codes.py
function _init (line 107) | def _init():
FILE: modules/requests/structures.py
class CaseInsensitiveDict (line 15) | class CaseInsensitiveDict(MutableMapping):
method __init__ (line 42) | def __init__(self, data=None, **kwargs):
method __setitem__ (line 48) | def __setitem__(self, key, value):
method __getitem__ (line 53) | def __getitem__(self, key):
method __delitem__ (line 56) | def __delitem__(self, key):
method __iter__ (line 59) | def __iter__(self):
method __len__ (line 62) | def __len__(self):
method lower_items (line 65) | def lower_items(self):
method __eq__ (line 73) | def __eq__(self, other):
method copy (line 82) | def copy(self):
method __repr__ (line 85) | def __repr__(self):
class LookupDict (line 89) | class LookupDict(dict):
method __init__ (line 92) | def __init__(self, name=None):
method __repr__ (line 96) | def __repr__(self):
method __getitem__ (line 99) | def __getitem__(self, key):
method get (line 104) | def get(self, key, default=None):
FILE: modules/requests/utils.py
function proxy_bypass_registry (line 54) | def proxy_bypass_registry(host):
function proxy_bypass (line 93) | def proxy_bypass(host): # noqa
function dict_to_sequence (line 105) | def dict_to_sequence(d):
function super_len (line 114) | def super_len(o):
function get_netrc_auth (line 175) | def get_netrc_auth(url, raise_errors=False):
function guess_filename (line 232) | def guess_filename(obj):
function extract_zipped_paths (line 240) | def extract_zipped_paths(path):
function atomic_open (line 274) | def atomic_open(filename):
function from_key_val_list (line 287) | def from_key_val_list(value):
function to_key_val_list (line 314) | def to_key_val_list(value):
function parse_list_header (line 344) | def parse_list_header(value):
function parse_dict_header (line 376) | def parse_dict_header(value):
function unquote_header_value (line 411) | def unquote_header_value(value, is_filename=False):
function dict_from_cookiejar (line 436) | def dict_from_cookiejar(cj):
function add_dict_to_cookiejar (line 451) | def add_dict_to_cookiejar(cj, cookie_dict):
function get_encodings_from_content (line 462) | def get_encodings_from_content(content):
function _parse_content_type_header (line 482) | def _parse_content_type_header(header):
function get_encoding_from_headers (line 507) | def get_encoding_from_headers(headers):
function stream_decode_response_unicode (line 532) | def stream_decode_response_unicode(iterator, r):
function iter_slices (line 550) | def iter_slices(string, slice_length):
function get_unicode_from_response (line 560) | def get_unicode_from_response(r):
function unquote_unreserved (line 601) | def unquote_unreserved(uri):
function requote_uri (line 625) | def requote_uri(uri):
function address_in_network (line 647) | def address_in_network(ip, net):
function dotted_netmask (line 662) | def dotted_netmask(mask):
function is_ipv4_address (line 673) | def is_ipv4_address(string_ip):
function is_valid_cidr (line 684) | def is_valid_cidr(string_network):
function set_environ (line 709) | def set_environ(env_name, value):
function should_bypass_proxies (line 730) | def should_bypass_proxies(url, no_proxy):
function get_environ_proxies (line 791) | def get_environ_proxies(url, no_proxy=None):
function select_proxy (line 803) | def select_proxy(url, proxies):
function default_user_agent (line 829) | def default_user_agent(name="python-requests"):
function default_headers (line 838) | def default_headers():
function parse_header_links (line 850) | def parse_header_links(value):
function guess_json_utf (line 893) | def guess_json_utf(data):
function prepend_scheme_if_needed (line 925) | def prepend_scheme_if_needed(url, new_scheme):
function get_auth_from_url (line 942) | def get_auth_from_url(url):
function check_header_validity (line 963) | def check_header_validity(header):
function urldefragauth (line 984) | def urldefragauth(url):
function rewind_body (line 1001) | def rewind_body(prepared_request):
FILE: modules/tkinter/colorchooser.py
class Chooser (line 17) | class Chooser(Dialog):
method _fixoptions (line 35) | def _fixoptions(self):
method _fixresult (line 48) | def _fixresult(self, widget, result):
function askcolor (line 68) | def askcolor(color=None, **options):
FILE: modules/tkinter/commondialog.py
class Dialog (line 16) | class Dialog:
method __init__ (line 20) | def __init__(self, master=None, **options):
method _fixoptions (line 26) | def _fixoptions(self):
method _fixresult (line 29) | def _fixresult(self, widget, result):
method show (line 32) | def show(self, **options):
FILE: modules/tkinter/dialog.py
class Dialog (line 10) | class Dialog(Widget):
method __init__ (line 11) | def __init__(self, master=None, cnf={}, **kw):
method destroy (line 24) | def destroy(self): pass
function _test (line 27) | def _test():
FILE: modules/tkinter/dnd.py
function dnd_start (line 109) | def dnd_start(source, event):
class DndHandler (line 119) | class DndHandler:
method __init__ (line 123) | def __init__(self, source, event):
method __del__ (line 143) | def __del__(self):
method on_motion (line 152) | def on_motion(self, event):
method on_release (line 179) | def on_release(self, event):
method cancel (line 182) | def cancel(self, event=None):
method finish (line 185) | def finish(self, event, commit=0):
class Icon (line 208) | class Icon:
method __init__ (line 210) | def __init__(self, name):
method attach (line 214) | def attach(self, canvas, x=10, y=10):
method detach (line 230) | def detach(self):
method press (line 240) | def press(self, event):
method move (line 248) | def move(self, event):
method putback (line 252) | def putback(self):
method where (line 255) | def where(self, canvas, event):
method dnd_end (line 265) | def dnd_end(self, target, event):
class Tester (line 269) | class Tester:
method __init__ (line 271) | def __init__(self, root):
method dnd_accept (line 277) | def dnd_accept(self, source, event):
method dnd_enter (line 280) | def dnd_enter(self, source, event):
method dnd_motion (line 288) | def dnd_motion(self, source, event):
method dnd_leave (line 293) | def dnd_leave(self, source, event):
method dnd_commit (line 298) | def dnd_commit(self, source, event):
function test (line 304) | def test():
FILE: modules/tkinter/filedialog.py
class FileDialog (line 33) | class FileDialog:
method __init__ (line 58) | def __init__(self, master, title=None):
method go (line 122) | def go(self, dir_or_file=os.curdir, pattern="*", default="", key=None):
method quit (line 147) | def quit(self, how=None):
method dirs_double_event (line 151) | def dirs_double_event(self, event):
method dirs_select_event (line 154) | def dirs_select_event(self, event):
method files_double_event (line 160) | def files_double_event(self, event):
method files_select_event (line 163) | def files_select_event(self, event):
method ok_event (line 167) | def ok_event(self, event):
method ok_command (line 170) | def ok_command(self):
method filter_command (line 173) | def filter_command(self, event=None):
method get_filter (line 201) | def get_filter(self):
method get_selection (line 208) | def get_selection(self):
method cancel_command (line 213) | def cancel_command(self, event=None):
method set_filter (line 216) | def set_filter(self, dir, pat):
method set_selection (line 228) | def set_selection(self, file):
class LoadFileDialog (line 233) | class LoadFileDialog(FileDialog):
method ok_command (line 239) | def ok_command(self):
class SaveFileDialog (line 247) | class SaveFileDialog(FileDialog):
method ok_command (line 253) | def ok_command(self):
class _Dialog (line 304) | class _Dialog(commondialog.Dialog):
method _fixoptions (line 306) | def _fixoptions(self):
method _fixresult (line 313) | def _fixresult(self, widget, result):
class Open (line 332) | class Open(_Dialog):
method _fixresult (line 337) | def _fixresult(self, widget, result):
class SaveAs (line 352) | class SaveAs(_Dialog):
class Directory (line 359) | class Directory(commondialog.Dialog):
method _fixresult (line 364) | def _fixresult(self, widget, result):
function askopenfilename (line 381) | def askopenfilename(**options):
function asksaveasfilename (line 387) | def asksaveasfilename(**options):
function askopenfilenames (line 393) | def askopenfilenames(**options):
function askopenfile (line 405) | def askopenfile(mode = "r", **options):
function askopenfiles (line 414) | def askopenfiles(mode = "r", **options):
function asksaveasfile (line 431) | def asksaveasfile(mode = "w", **options):
function askdirectory (line 440) | def askdirectory (**options):
function test (line 448) | def test():
FILE: modules/tkinter/font.py
function nametofont (line 20) | def nametofont(name):
class Font (line 26) | class Font:
method _set (line 50) | def _set(self, kw):
method _get (line 57) | def _get(self, args):
method _mkdict (line 63) | def _mkdict(self, args):
method __init__ (line 69) | def __init__(self, root=None, font=None, name=None, exists=False,
method __str__ (line 100) | def __str__(self):
method __eq__ (line 103) | def __eq__(self, other):
method __getitem__ (line 108) | def __getitem__(self, key):
method __setitem__ (line 111) | def __setitem__(self, key, value):
method __del__ (line 114) | def __del__(self):
method copy (line 121) | def copy(self):
method actual (line 125) | def actual(self, option=None, displayof=None):
method cget (line 137) | def cget(self, option):
method config (line 141) | def config(self, **options):
method measure (line 152) | def measure(self, text, displayof=None):
method metrics (line 159) | def metrics(self, *options, **kw):
function families (line 180) | def families(root=None, displayof=None):
function names (line 190) | def names(root=None):
FILE: modules/tkinter/messagebox.py
class Message (line 61) | class Message(Dialog):
function _show (line 71) | def _show(title=None, message=None, _icon=None, _type=None, **options):
function showinfo (line 86) | def showinfo(title=None, message=None, **options):
function showwarning (line 92) | def showwarning(title=None, message=None, **options):
function showerror (line 98) | def showerror(title=None, message=None, **options):
function askquestion (line 104) | def askquestion(title=None, message=None, **options):
function askokcancel (line 110) | def askokcancel(title=None, message=None, **options):
function askyesno (line 117) | def askyesno(title=None, message=None, **options):
function askyesnocancel (line 124) | def askyesnocancel(title=None, message=None, **options):
function askretrycancel (line 135) | def askretrycancel(title=None, message=None, **options):
FILE: modules/tkinter/scrolledtext.py
class ScrolledText (line 20) | class ScrolledText(Text):
method __init__ (line 21) | def __init__(self, master=None, **kw):
method __str__ (line 41) | def __str__(self):
function example (line 45) | def example():
FILE: modules/tkinter/simpledialog.py
class SimpleDialog (line 30) | class SimpleDialog:
method __init__ (line 32) | def __init__(self, master,
method _set_transient (line 63) | def _set_transient(self, master, relx=0.5, rely=0.3):
method go (line 92) | def go(self):
method return_event (line 99) | def return_event(self, event):
method wm_delete_window (line 105) | def wm_delete_window(self):
method done (line 111) | def done(self, num):
class Dialog (line 116) | class Dialog(Toplevel):
method __init__ (line 123) | def __init__(self, parent, title = None):
method destroy (line 178) | def destroy(self):
method body (line 186) | def body(self, master):
method buttonbox (line 195) | def buttonbox(self):
method ok (line 216) | def ok(self, event=None):
method cancel (line 230) | def cancel(self, event=None):
method validate (line 240) | def validate(self):
method apply (line 249) | def apply(self):
function _setup_dialog (line 259) | def _setup_dialog(w):
class _QueryDialog (line 269) | class _QueryDialog(Dialog):
method __init__ (line 271) | def __init__(self, title, prompt,
method destroy (line 284) | def destroy(self):
method body (line 288) | def body(self, master):
method validate (line 302) | def validate(self):
class _QueryInteger (line 336) | class _QueryInteger(_QueryDialog):
method getresult (line 339) | def getresult(self):
function askinteger (line 343) | def askinteger(title, prompt, **kw):
class _QueryFloat (line 358) | class _QueryFloat(_QueryDialog):
method getresult (line 361) | def getresult(self):
function askfloat (line 365) | def askfloat(title, prompt, **kw):
class _QueryString (line 380) | class _QueryString(_QueryDialog):
method __init__ (line 381) | def __init__(self, *args, **kw):
method body (line 389) | def body(self, master):
method getresult (line 395) | def getresult(self):
function askstring (line 399) | def askstring(title, prompt, **kw):
function test (line 416) | def test():
FILE: modules/tkinter/test/runtktests.py
function is_package (line 15) | def is_package(path):
function get_tests_modules (line 21) | def get_tests_modules(basepath=this_dir_path, gui=True, packages=None):
function get_tests (line 53) | def get_tests(text=True, gui=True, packages=None):
FILE: modules/tkinter/test/support.py
class AbstractTkTest (line 6) | class AbstractTkTest:
method setUpClass (line 9) | def setUpClass(cls):
method tearDownClass (line 24) | def tearDownClass(cls):
method setUp (line 31) | def setUp(self):
method tearDown (line 34) | def tearDown(self):
class AbstractDefaultRootTest (line 40) | class AbstractDefaultRootTest:
method setUp (line 42) | def setUp(self):
method tearDown (line 48) | def tearDown(self):
method _test_widget (line 53) | def _test_widget(self, constructor):
function destroy_default_root (line 66) | def destroy_default_root():
function simulate_mouse_click (line 72) | def simulate_mouse_click(widget, x, y):
function requires_tcl (line 84) | def requires_tcl(*version):
function get_tk_patchlevel (line 100) | def get_tk_patchlevel():
function pixels_conv (line 122) | def pixels_conv(value):
function tcl_obj_eq (line 125) | def tcl_obj_eq(actual, expected):
function widget_eq (line 138) | def widget_eq(actual, expected):
FILE: modules/tkinter/test/test_tkinter/test_colorchooser.py
class ChooserTest (line 10) | class ChooserTest(AbstractTkTest, unittest.TestCase):
method setUpClass (line 13) | def setUpClass(cls):
method test_fixoptions (line 17) | def test_fixoptions(self):
method test_fixresult (line 30) | def test_fixresult(self):
FILE: modules/tkinter/test/test_tkinter/test_font.py
class FontTest (line 11) | class FontTest(AbstractTkTest, unittest.TestCase):
method setUpClass (line 14) | def setUpClass(cls):
method test_configure (line 21) | def test_configure(self):
method test_unicode_family (line 38) | def test_unicode_family(self):
method test_actual (line 48) | def test_actual(self):
method test_name (line 62) | def test_name(self):
method test_equality (line 66) | def test_equality(self):
method test_measure (line 82) | def test_measure(self):
method test_metrics (line 85) | def test_metrics(self):
method test_families (line 94) | def test_families(self):
method test_names (line 102) | def test_names(self):
class DefaultRootTest (line 112) | class DefaultRootTest(AbstractDefaultRootTest, unittest.TestCase):
method test_families (line 114) | def test_families(self):
method test_names (line 127) | def test_names(self):
FILE: modules/tkinter/test/test_tkinter/test_geometry_managers.py
class PackTest (line 13) | class PackTest(AbstractWidgetTest, unittest.TestCase):
method create2 (line 17) | def create2(self):
method test_pack_configure_after (line 27) | def test_pack_configure_after(self):
method test_pack_configure_anchor (line 43) | def test_pack_configure_anchor(self):
method test_pack_configure_before (line 60) | def test_pack_configure_before(self):
method test_pack_configure_expand (line 76) | def test_pack_configure_expand(self):
method test_pack_configure_in (line 100) | def test_pack_configure_in(self):
method test_pack_configure_padx_ipadx_fill (line 117) | def test_pack_configure_padx_ipadx_fill(self):
method test_pack_configure_pady_ipady_fill (line 159) | def test_pack_configure_pady_ipady_fill(self):
method test_pack_configure_side (line 201) | def test_pack_configure_side(self):
method test_pack_forget (line 215) | def test_pack_forget(self):
method test_pack_info (line 227) | def test_pack_info(self):
method test_pack_propagate (line 257) | def test_pack_propagate(self):
method test_pack_slaves (line 270) | def test_pack_slaves(self):
class PlaceTest (line 279) | class PlaceTest(AbstractWidgetTest, unittest.TestCase):
method create2 (line 283) | def create2(self):
method test_place_configure_in (line 292) | def test_place_configure_in(self):
method test_place_configure_x (line 305) | def test_place_configure_x(self):
method test_place_configure_y (line 322) | def test_place_configure_y(self):
method test_place_configure_relx (line 339) | def test_place_configure_relx(self):
method test_place_configure_rely (line 357) | def test_place_configure_rely(self):
method test_place_configure_anchor (line 375) | def test_place_configure_anchor(self):
method test_place_configure_width (line 385) | def test_place_configure_width(self):
method test_place_configure_height (line 396) | def test_place_configure_height(self):
method test_place_configure_relwidth (line 407) | def test_place_configure_relwidth(self):
method test_place_configure_relheight (line 419) | def test_place_configure_relheight(self):
method test_place_configure_bordermode (line 431) | def test_place_configure_bordermode(self):
method test_place_forget (line 441) | def test_place_forget(self):
method test_place_info (line 451) | def test_place_info(self):
method test_place_slaves (line 473) | def test_place_slaves(self):
class GridTest (line 483) | class GridTest(AbstractWidgetTest, unittest.TestCase):
method tearDown (line 487) | def tearDown(self):
method test_grid_configure (line 498) | def test_grid_configure(self):
method test_grid_configure_column (line 509) | def test_grid_configure_column(self):
method test_grid_configure_columnspan (line 517) | def test_grid_configure_columnspan(self):
method test_grid_configure_in (line 525) | def test_grid_configure_in(self):
method test_grid_configure_ipadx (line 536) | def test_grid_configure_ipadx(self):
method test_grid_configure_ipady (line 547) | def test_grid_configure_ipady(self):
method test_grid_configure_padx (line 558) | def test_grid_configure_padx(self):
method test_grid_configure_pady (line 571) | def test_grid_configure_pady(self):
method test_grid_configure_row (line 584) | def test_grid_configure_row(self):
method test_grid_configure_rownspan (line 592) | def test_grid_configure_rownspan(self):
method test_grid_configure_sticky (line 600) | def test_grid_configure_sticky(self):
method test_grid_columnconfigure (line 609) | def test_grid_columnconfigure(self):
method test_grid_columnconfigure_minsize (line 633) | def test_grid_columnconfigure_minsize(self):
method test_grid_columnconfigure_weight (line 640) | def test_grid_columnconfigure_weight(self):
method test_grid_columnconfigure_pad (line 650) | def test_grid_columnconfigure_pad(self):
method test_grid_columnconfigure_uniform (line 660) | def test_grid_columnconfigure_uniform(self):
method test_grid_rowconfigure (line 665) | def test_grid_rowconfigure(self):
method test_grid_rowconfigure_minsize (line 689) | def test_grid_rowconfigure_minsize(self):
method test_grid_rowconfigure_weight (line 696) | def test_grid_rowconfigure_weight(self):
method test_grid_rowconfigure_pad (line 706) | def test_grid_rowconfigure_pad(self):
method test_grid_rowconfigure_uniform (line 716) | def test_grid_rowconfigure_uniform(self):
method test_grid_forget (line 721) | def test_grid_forget(self):
method test_grid_remove (line 741) | def test_grid_remove(self):
method test_grid_info (line 761) | def test_grid_info(self):
method test_grid_anchor (line 778) | def test_grid_anchor(self):
method test_grid_bbox (line 788) | def test_grid_bbox(self):
method test_grid_location (line 819) | def test_grid_location(self):
method test_grid_propagate (line 851) | def test_grid_propagate(self):
method test_grid_size (line 873) | def test_grid_size(self):
method test_grid_slaves (line 883) | def test_grid_slaves(self):
FILE: modules/tkinter/test/test_tkinter/test_images.py
class MiscTest (line 9) | class MiscTest(AbstractTkTest, unittest.TestCase):
method test_image_types (line 11) | def test_image_types(self):
method test_image_names (line 17) | def test_image_names(self):
class DefaultRootTest (line 22) | class DefaultRootTest(AbstractDefaultRootTest, unittest.TestCase):
method test_image_types (line 24) | def test_image_types(self):
method test_image_names (line 35) | def test_image_names(self):
method test_image_create_bitmap (line 44) | def test_image_create_bitmap(self):
method test_image_create_photo (line 53) | def test_image_create_photo(self):
class BitmapImageTest (line 63) | class BitmapImageTest(AbstractTkTest, unittest.TestCase):
method setUpClass (line 66) | def setUpClass(cls):
method test_create_from_file (line 70) | def test_create_from_file(self):
method test_create_from_data (line 83) | def test_create_from_data(self):
method assertEqualStrList (line 98) | def assertEqualStrList(self, actual, expected):
method test_configure_data (line 102) | def test_configure_data(self):
method test_configure_file (line 118) | def test_configure_file(self):
method test_configure_background (line 132) | def test_configure_background(self):
method test_configure_foreground (line 138) | def test_configure_foreground(self):
class PhotoImageTest (line 147) | class PhotoImageTest(AbstractTkTest, unittest.TestCase):
method setUpClass (line 150) | def setUpClass(cls):
method create (line 154) | def create(self):
method colorlist (line 158) | def colorlist(self, *args):
method check_create_from_file (line 164) | def check_create_from_file(self, ext):
method check_create_from_data (line 179) | def check_create_from_data(self, ext):
method test_create_from_ppm_file (line 197) | def test_create_from_ppm_file(self):
method test_create_from_ppm_data (line 200) | def test_create_from_ppm_data(self):
method test_create_from_pgm_file (line 203) | def test_create_from_pgm_file(self):
method test_create_from_pgm_data (line 206) | def test_create_from_pgm_data(self):
method test_create_from_gif_file (line 209) | def test_create_from_gif_file(self):
method test_create_from_gif_data (line 212) | def test_create_from_gif_data(self):
method test_create_from_png_file (line 216) | def test_create_from_png_file(self):
method test_create_from_png_data (line 220) | def test_create_from_png_data(self):
method test_configure_data (line 223) | def test_configure_data(self):
method test_configure_format (line 234) | def test_configure_format(self):
method test_configure_file (line 243) | def test_configure_file(self):
method test_configure_gamma (line 251) | def test_configure_gamma(self):
method test_configure_width_height (line 257) | def test_configure_width_height(self):
method test_configure_palette (line 268) | def test_configure_palette(self):
method test_blank (line 276) | def test_blank(self):
method test_copy (line 283) | def test_copy(self):
method test_subsample (line 290) | def test_subsample(self):
method test_zoom (line 302) | def test_zoom(self):
method test_put (line 316) | def test_put(self):
method test_get (line 332) | def test_get(self):
method test_write (line 342) | def test_write(self):
method test_transparency (line 368) | def test_transparency(self):
FILE: modules/tkinter/test/test_tkinter/test_loadtk.py
class TkLoadTest (line 9) | class TkLoadTest(unittest.TestCase):
method testLoadTk (line 12) | def testLoadTk(self):
method testLoadTkFailure (line 19) | def testLoadTkFailure(self):
FILE: modules/tkinter/test/test_tkinter/test_misc.py
class MiscTest (line 8) | class MiscTest(AbstractTkTest, unittest.TestCase):
method test_all (line 10) | def test_all(self):
method test_repr (line 24) | def test_repr(self):
method test_generated_names (line 29) | def test_generated_names(self):
method test_tk_setPalette (line 37) | def test_tk_setPalette(self):
method test_after (line 65) | def test_after(self):
method test_after_idle (line 100) | def test_after_idle(self):
method test_after_cancel (line 132) | def test_after_cancel(self):
method test_clipboard (line 173) | def test_clipboard(self):
method test_clipboard_astral (line 184) | def test_clipboard_astral(self):
method test_winfo_rgb (line 195) | def test_winfo_rgb(self):
method test_event_repr_defaults (line 215) | def test_event_repr_defaults(self):
method test_event_repr (line 236) | def test_event_repr(self):
method test_getboolean (line 264) | def test_getboolean(self):
method test_mainloop (line 274) | def test_mainloop(self):
class DefaultRootTest (line 287) | class DefaultRootTest(AbstractDefaultRootTest, unittest.TestCase):
method test_default_root (line 289) | def test_default_root(self):
method test_no_default_root (line 303) | def test_no_default_root(self):
method test_getboolean (line 323) | def test_getboolean(self):
method test_mainloop (line 332) | def test_mainloop(self):
FILE: modules/tkinter/test/test_tkinter/test_simpledialog.py
class DefaultRootTest (line 10) | class DefaultRootTest(AbstractDefaultRootTest, unittest.TestCase):
method test_askinteger (line 12) | def test_askinteger(self):
FILE: modules/tkinter/test/test_tkinter/test_text.py
class TextTest (line 8) | class TextTest(AbstractTkTest, unittest.TestCase):
method setUp (line 10) | def setUp(self):
method test_debug (line 14) | def test_debug(self):
method test_search (line 26) | def test_search(self):
FILE: modules/tkinter/test/test_tkinter/test_variables.py
class Var (line 12) | class Var(Variable):
method set (line 17) | def set(self, value):
class TestBase (line 22) | class TestBase(unittest.TestCase):
method setUp (line 24) | def setUp(self):
method tearDown (line 27) | def tearDown(self):
class TestVariable (line 31) | class TestVariable(TestBase):
method info_exists (line 33) | def info_exists(self, *args):
method test_default (line 36) | def test_default(self):
method test_name_and_value (line 41) | def test_name_and_value(self):
method test___del__ (line 46) | def test___del__(self):
method test_dont_unset_not_existing (line 54) | def test_dont_unset_not_existing(self):
method test_equality (line 66) | def test_equality(self):
method test_invalid_name (line 92) | def test_invalid_name(self):
method test_null_in_name (line 96) | def test_null_in_name(self):
method test_initialize (line 108) | def test_initialize(self):
method test_trace_old (line 114) | def test_trace_old(self):
method test_trace (line 164) | def test_trace(self):
class TestStringVar (line 214) | class TestStringVar(TestBase):
method test_default (line 216) | def test_default(self):
method test_get (line 220) | def test_get(self):
method test_get_null (line 226) | def test_get_null(self):
class TestIntVar (line 233) | class TestIntVar(TestBase):
method test_default (line 235) | def test_default(self):
method test_get (line 239) | def test_get(self):
method test_invalid_value (line 247) | def test_invalid_value(self):
class TestDoubleVar (line 254) | class TestDoubleVar(TestBase):
method test_default (line 256) | def test_default(self):
method test_get (line 260) | def test_get(self):
method test_get_from_int (line 266) | def test_get_from_int(self):
method test_invalid_value (line 274) | def test_invalid_value(self):
class TestBooleanVar (line 281) | class TestBooleanVar(TestBase):
method test_default (line 283) | def test_default(self):
method test_get (line 287) | def test_get(self):
method test_set (line 299) | def test_set(self):
method test_invalid_value_domain (line 314) | def test_invalid_value_domain(self):
class DefaultRootTest (line 328) | class DefaultRootTest(AbstractDefaultRootTest, unittest.TestCase):
method test_variable (line 330) | def test_variable(self):
FILE: modules/tkinter/test/test_tkinter/test_widgets.py
function float_round (line 18) | def float_round(x):
class AbstractToplevelTest (line 22) | class AbstractToplevelTest(AbstractWidgetTest, PixelSizeTests):
method test_configure_class (line 25) | def test_configure_class(self):
method test_configure_colormap (line 34) | def test_configure_colormap(self):
method test_configure_container (line 42) | def test_configure_container(self):
method test_configure_visual (line 50) | def test_configure_visual(self):
class ToplevelTest (line 60) | class ToplevelTest(AbstractToplevelTest, unittest.TestCase):
method create (line 69) | def create(self, **kwargs):
method test_configure_menu (line 72) | def test_configure_menu(self):
method test_configure_screen (line 78) | def test_configure_screen(self):
method test_configure_use (line 90) | def test_configure_use(self):
class FrameTest (line 101) | class FrameTest(AbstractToplevelTest, unittest.TestCase):
method create (line 109) | def create(self, **kwargs):
class LabelFrameTest (line 114) | class LabelFrameTest(AbstractToplevelTest, unittest.TestCase):
method create (line 124) | def create(self, **kwargs):
method test_configure_labelanchor (line 127) | def test_configure_labelanchor(self):
method test_configure_labelwidget (line 134) | def test_configure_labelwidget(self):
class AbstractLabelTest (line 141) | class AbstractLabelTest(AbstractWidgetTest, IntegerSizeTests):
method test_configure_highlightthickness (line 144) | def test_configure_highlightthickness(self):
class LabelTest (line 151) | class LabelTest(AbstractLabelTest, unittest.TestCase):
method create (line 162) | def create(self, **kwargs):
class ButtonTest (line 167) | class ButtonTest(AbstractLabelTest, unittest.TestCase):
method create (line 179) | def create(self, **kwargs):
method test_configure_default (line 182) | def test_configure_default(self):
class CheckbuttonTest (line 188) | class CheckbuttonTest(AbstractLabelTest, unittest.TestCase):
method create (line 203) | def create(self, **kwargs):
method test_configure_offvalue (line 207) | def test_configure_offvalue(self):
method test_configure_onvalue (line 211) | def test_configure_onvalue(self):
class RadiobuttonTest (line 217) | class RadiobuttonTest(AbstractLabelTest, unittest.TestCase):
method create (line 231) | def create(self, **kwargs):
method test_configure_value (line 234) | def test_configure_value(self):
class MenubuttonTest (line 240) | class MenubuttonTest(AbstractLabelTest, unittest.TestCase):
method create (line 254) | def create(self, **kwargs):
method test_configure_direction (line 257) | def test_configure_direction(self):
method test_configure_height (line 262) | def test_configure_height(self):
method test_configure_image (line 269) | def test_configure_image(self):
method test_configure_menu (line 283) | def test_configure_menu(self):
method test_configure_padx (line 289) | def test_configure_padx(self):
method test_configure_pady (line 294) | def test_configure_pady(self):
method test_configure_width (line 299) | def test_configure_width(self):
class OptionMenuTest (line 304) | class OptionMenuTest(MenubuttonTest, unittest.TestCase):
method create (line 306) | def create(self, default='b', values=('a', 'b', 'c'), **kwargs):
method test_bad_kwarg (line 309) | def test_bad_kwarg(self):
class EntryTest (line 315) | class EntryTest(AbstractWidgetTest, unittest.TestCase):
method create (line 329) | def create(self, **kwargs):
method test_configure_disabledbackground (line 332) | def test_configure_disabledbackground(self):
method test_configure_insertborderwidth (line 336) | def test_configure_insertborderwidth(self):
method test_configure_insertwidth (line 343) | def test_configure_insertwidth(self):
method test_configure_invalidcommand (line 353) | def test_configure_invalidcommand(self):
method test_configure_readonlybackground (line 358) | def test_configure_readonlybackground(self):
method test_configure_show (line 362) | def test_configure_show(self):
method test_configure_state (line 368) | def test_configure_state(self):
method test_configure_validate (line 373) | def test_configure_validate(self):
method test_configure_validatecommand (line 378) | def test_configure_validatecommand(self):
method test_selection_methods (line 383) | def test_selection_methods(self):
class SpinboxTest (line 410) | class SpinboxTest(EntryTest, unittest.TestCase):
method create (line 428) | def create(self, **kwargs):
method test_configure_buttonbackground (line 433) | def test_configure_buttonbackground(self):
method test_configure_buttoncursor (line 437) | def test_configure_buttoncursor(self):
method test_configure_buttondownrelief (line 441) | def test_configure_buttondownrelief(self):
method test_configure_buttonuprelief (line 445) | def test_configure_buttonuprelief(self):
method test_configure_format (line 449) | def test_configure_format(self):
method test_configure_from (line 464) | def test_configure_from(self):
method test_configure_increment (line 471) | def test_configure_increment(self):
method test_configure_to (line 475) | def test_configure_to(self):
method test_configure_values (line 482) | def test_configure_values(self):
method test_configure_wrap (line 493) | def test_configure_wrap(self):
method test_bbox (line 497) | def test_bbox(self):
method test_selection_methods (line 505) | def test_selection_methods(self):
method test_selection_element (line 529) | def test_selection_element(self):
class TextTest (line 539) | class TextTest(AbstractWidgetTest, unittest.TestCase):
method create (line 556) | def create(self, **kwargs):
method test_configure_autoseparators (line 559) | def test_configure_autoseparators(self):
method test_configure_blockcursor (line 564) | def test_configure_blockcursor(self):
method test_configure_endline (line 569) | def test_configure_endline(self):
method test_configure_height (line 582) | def test_configure_height(self):
method test_configure_maxundo (line 588) | def test_configure_maxundo(self):
method test_configure_inactiveselectbackground (line 593) | def test_configure_inactiveselectbackground(self):
method test_configure_insertunfocussed (line 598) | def test_configure_insertunfocussed(self):
method test_configure_selectborderwidth (line 603) | def test_configure_selectborderwidth(self):
method test_configure_spacing1 (line 609) | def test_configure_spacing1(self):
method test_configure_spacing2 (line 614) | def test_configure_spacing2(self):
method test_configure_spacing3 (line 619) | def test_configure_spacing3(self):
method test_configure_startline (line 625) | def test_configure_startline(self):
method test_configure_state (line 638) | def test_configure_state(self):
method test_configure_tabs (line 645) | def test_configure_tabs(self):
method test_configure_tabstyle (line 661) | def test_configure_tabstyle(self):
method test_configure_undo (line 665) | def test_configure_undo(self):
method test_configure_width (line 669) | def test_configure_width(self):
method test_configure_wrap (line 675) | def test_configure_wrap(self):
method test_bbox (line 682) | def test_bbox(self):
class CanvasTest (line 693) | class CanvasTest(AbstractWidgetTest, unittest.TestCase):
method create (line 710) | def create(self, **kwargs):
method test_configure_closeenough (line 713) | def test_configure_closeenough(self):
method test_configure_confine (line 718) | def test_configure_confine(self):
method test_configure_offset (line 722) | def test_configure_offset(self):
method test_configure_scrollregion (line 731) | def test_configure_scrollregion(self):
method test_configure_state (line 743) | def test_configure_state(self):
method test_configure_xscrollincrement (line 748) | def test_configure_xscrollincrement(self):
method test_configure_yscrollincrement (line 753) | def test_configure_yscrollincrement(self):
method test_moveto (line 759) | def test_moveto(self):
class ListboxTest (line 783) | class ListboxTest(AbstractWidgetTest, unittest.TestCase):
method create (line 795) | def create(self, **kwargs):
method test_configure_activestyle (line 798) | def test_configure_activestyle(self):
method test_configure_listvariable (line 805) | def test_configure_listvariable(self):
method test_configure_selectmode (line 810) | def test_configure_selectmode(self):
method test_configure_state (line 817) | def test_configure_state(self):
method test_itemconfigure (line 821) | def test_itemconfigure(self):
method check_itemconfigure (line 848) | def check_itemconfigure(self, name, value):
method test_itemconfigure_background (line 857) | def test_itemconfigure_background(self):
method test_itemconfigure_bg (line 860) | def test_itemconfigure_bg(self):
method test_itemconfigure_fg (line 863) | def test_itemconfigure_fg(self):
method test_itemconfigure_foreground (line 866) | def test_itemconfigure_foreground(self):
method test_itemconfigure_selectbackground (line 869) | def test_itemconfigure_selectbackground(self):
method test_itemconfigure_selectforeground (line 872) | def test_itemconfigure_selectforeground(self):
method test_box (line 875) | def test_box(self):
method test_curselection (line 887) | def test_curselection(self):
method test_get (line 896) | def test_get(self):
class ScaleTest (line 917) | class ScaleTest(AbstractWidgetTest, unittest.TestCase):
method create (line 929) | def create(self, **kwargs):
method test_configure_bigincrement (line 932) | def test_configure_bigincrement(self):
method test_configure_digits (line 936) | def test_configure_digits(self):
method test_configure_from (line 940) | def test_configure_from(self):
method test_configure_label (line 945) | def test_configure_label(self):
method test_configure_length (line 950) | def test_configure_length(self):
method test_configure_resolution (line 954) | def test_configure_resolution(self):
method test_configure_showvalue (line 958) | def test_configure_showvalue(self):
method test_configure_sliderlength (line 962) | def test_configure_sliderlength(self):
method test_configure_sliderrelief (line 967) | def test_configure_sliderrelief(self):
method test_configure_tickinterval (line 971) | def test_configure_tickinterval(self):
method test_configure_to (line 978) | def test_configure_to(self):
class ScrollbarTest (line 985) | class ScrollbarTest(AbstractWidgetTest, unittest.TestCase):
method create (line 999) | def create(self, **kwargs):
method test_configure_activerelief (line 1002) | def test_configure_activerelief(self):
method test_configure_elementborderwidth (line 1006) | def test_configure_elementborderwidth(self):
method test_configure_orient (line 1010) | def test_configure_orient(self):
method test_activate (line 1015) | def test_activate(self):
method test_set (line 1024) | def test_set(self):
class PanedWindowTest (line 1036) | class PanedWindowTest(AbstractWidgetTest, unittest.TestCase):
method create (line 1048) | def create(self, **kwargs):
method test_configure_handlepad (line 1051) | def test_configure_handlepad(self):
method test_configure_handlesize (line 1055) | def test_configure_handlesize(self):
method test_configure_height (line 1060) | def test_configure_height(self):
method test_configure_opaqueresize (line 1065) | def test_configure_opaqueresize(self):
method test_configure_proxybackground (line 1070) | def test_configure_proxybackground(self):
method test_configure_proxyborderwidth (line 1075) | def test_configure_proxyborderwidth(self):
method test_configure_proxyrelief (line 1082) | def test_configure_proxyrelief(self):
method test_configure_sashcursor (line 1086) | def test_configure_sashcursor(self):
method test_configure_sashpad (line 1090) | def test_configure_sashpad(self):
method test_configure_sashrelief (line 1094) | def test_configure_sashrelief(self):
method test_configure_sashwidth (line 1098) | def test_configure_sashwidth(self):
method test_configure_showhandle (line 1103) | def test_configure_showhandle(self):
method test_configure_width (line 1107) | def test_configure_width(self):
method create2 (line 1112) | def create2(self):
method test_paneconfigure (line 1120) | def test_paneconfigure(self):
method check_paneconfigure (line 1130) | def check_paneconfigure(self, p, b, name, value, expected, stringify=F...
method check_paneconfigure_bad (line 1140) | def check_paneconfigure_bad(self, p, b, name, msg):
method test_paneconfigure_after (line 1144) | def test_paneconfigure_after(self):
method test_paneconfigure_before (line 1150) | def test_paneconfigure_before(self):
method test_paneconfigure_height (line 1156) | def test_paneconfigure_height(self):
method test_paneconfigure_hide (line 1164) | def test_paneconfigure_hide(self):
method test_paneconfigure_minsize (line 1170) | def test_paneconfigure_minsize(self):
method test_paneconfigure_padx (line 1176) | def test_paneconfigure_padx(self):
method test_paneconfigure_pady (line 1182) | def test_paneconfigure_pady(self):
method test_paneconfigure_sticky (line 1188) | def test_paneconfigure_sticky(self):
method test_paneconfigure_stretch (line 1197) | def test_paneconfigure_stretch(self):
method test_paneconfigure_width (line 1204) | def test_paneconfigure_width(self):
class MenuTest (line 1213) | class MenuTest(AbstractWidgetTest, unittest.TestCase):
method create (line 1223) | def create(self, **kwargs):
method test_configure_postcommand (line 1226) | def test_configure_postcommand(self):
method test_configure_tearoff (line 1230) | def test_configure_tearoff(self):
method test_configure_tearoffcommand (line 1234) | def test_configure_tearoffcommand(self):
method test_configure_title (line 1238) | def test_configure_title(self):
method test_configure_type (line 1242) | def test_configure_type(self):
method test_entryconfigure (line 1247) | def test_entryconfigure(self):
method test_entryconfigure_label (line 1263) | def test_entryconfigure_label(self):
method test_entryconfigure_variable (line 1270) | def test_entryconfigure_variable(self):
class MessageTest (line 1282) | class MessageTest(AbstractWidgetTest, unittest.TestCase):
method create (line 1292) | def create(self, **kwargs):
method test_configure_aspect (line 1295) | def test_configure_aspect(self):
class DefaultRootTest (line 1300) | class DefaultRootTest(AbstractDefaultRootTest, unittest.TestCase):
method test_frame (line 1302) | def test_frame(self):
method test_label (line 1305) | def test_label(self):
FILE: modules/urllib3/connection.py
class BaseSSLError (line 24) | class BaseSSLError(BaseException):
class ConnectionError (line 33) | class ConnectionError(Exception):
class BrokenPipeError (line 42) | class BrokenPipeError(Exception):
class HTTPConnection (line 75) | class HTTPConnection(_HTTPConnection, object):
method __init__ (line 110) | def __init__(self, *args, **kw):
method host (line 128) | def host(self):
method host (line 147) | def host(self, value):
method _new_conn (line 156) | def _new_conn(self):
method _is_using_tunnel (line 187) | def _is_using_tunnel(self):
method _prepare_conn (line 191) | def _prepare_conn(self, conn):
method connect (line 199) | def connect(self):
method putrequest (line 203) | def putrequest(self, method, url, *args, **kwargs):
method putheader (line 216) | def putheader(self, header, *values):
method request (line 226) | def request(self, method, url, body=None, headers=None):
method request_chunked (line 236) | def request_chunked(self, method, url, body=None, headers=None):
class HTTPSConnection (line 276) | class HTTPSConnection(HTTPConnection):
method __init__ (line 292) | def __init__(
method set_cert (line 318) | def set_cert(
method connect (line 351) | def connect(self):
method _connect_tls_proxy (line 471) | def _connect_tls_proxy(self, hostname, conn):
function _match_hostname (line 510) | def _match_hostname(cert, asserted_hostname):
function _get_default_user_agent (line 525) | def _get_default_user_agent():
class DummyConnection (line 529) | class DummyConnection(object):
FILE: modules/urllib3/connectionpool.py
class ConnectionPool (line 60) | class ConnectionPool(object):
method __init__ (line 74) | def __init__(self, host, port=None):
method __str__ (line 82) | def __str__(self):
method __enter__ (line 85) | def __enter__(self):
method __exit__ (line 88) | def __exit__(self, exc_type, exc_val, exc_tb):
method close (line 93) | def close(self):
class HTTPConnectionPool (line 104) | class HTTPConnectionPool(ConnectionPool, RequestMethods):
method __init__ (line 168) | def __init__(
method _new_conn (line 222) | def _new_conn(self):
method _get_conn (line 243) | def _get_conn(self, timeout=None):
method _put_conn (line 282) | def _put_conn(self, conn):
method _validate_conn (line 310) | def _validate_conn(self, conn):
method _prepare_proxy (line 316) | def _prepare_proxy(self, conn):
method _get_timeout (line 320) | def _get_timeout(self, timeout):
method _raise_timeout (line 332) | def _raise_timeout(self, err, url, timeout_value):
method _make_request (line 357) | def _make_request(
method _absolute_url (line 476) | def _absolute_url(self, path):
method close (line 479) | def close(self):
method is_same_host (line 497) | def is_same_host(self, url):
method urlopen (line 518) | def urlopen(
class HTTPSConnectionPool (line 865) | class HTTPSConnectionPool(HTTPConnectionPool):
method __init__ (line 882) | def __init__(
method _prepare_conn (line 931) | def _prepare_conn(self, conn):
method _prepare_proxy (line 951) | def _prepare_proxy(self, conn):
method _new_conn (line 966) | def _new_conn(self):
method _validate_conn (line 1002) | def _validate_conn(self, conn):
function connection_from_url (line 1024) | def connection_from_url(url, **kw):
function _normalize_host (line 1052) | def _normalize_host(host, scheme):
FILE: modules/urllib3/contrib/_appengine_environ.py
function is_appengine (line 8) | def is_appengine():
function is_appengine_sandbox (line 12) | def is_appengine_sandbox():
function is_local_appengine (line 22) | def is_local_appengine():
function is_prod_appengine (line 28) | def is_prod_appengine():
function is_prod_appengine_mvms (line 34) | def is_prod_appengine_mvms():
FILE: modules/urllib3/contrib/_securetransport/bindings.py
function load_cdll (line 65) | def load_cdll(name, macos10_16_path):
class CFConst (line 423) | class CFConst(object):
class SecurityConst (line 432) | class SecurityConst(object):
FILE: modules/urllib3/contrib/_securetransport/low_level.py
function _cf_data_from_bytes (line 27) | def _cf_data_from_bytes(bytestring):
function _cf_dictionary_from_tuples (line 37) | def _cf_dictionary_from_tuples(tuples):
function _cfstr (line 59) | def _cfstr(py_bstr):
function _create_cfstring_array (line 73) | def _create_cfstring_array(lst):
function _cf_string_to_unicode (line 104) | def _cf_string_to_unicode(value):
function _assert_no_error (line 129) | def _assert_no_error(error, exception_class=None):
function _cert_array_from_pem (line 150) | def _cert_array_from_pem(pem_bundle):
function _is_cert (line 195) | def _is_cert(item):
function _is_identity (line 203) | def _is_identity(item):
function _temporary_keychain (line 211) | def _temporary_keychain():
function _load_items_from_file (line 246) | def _load_items_from_file(keychain, path):
function _load_client_cert_chain (line 301) | def _load_client_cert_chain(keychain, *paths):
function _build_tls_unknown_ca_alert (line 385) | def _build_tls_unknown_ca_alert(version):
FILE: modules/urllib3/contrib/appengine.py
class AppEnginePlatformWarning (line 71) | class AppEnginePlatformWarning(HTTPWarning):
class AppEnginePlatformError (line 75) | class AppEnginePlatformError(HTTPError):
class AppEngineManager (line 79) | class AppEngineManager(RequestMethods):
method __init__ (line 99) | def __init__(
method __enter__ (line 124) | def __enter__(self):
method __exit__ (line 127) | def __exit__(self, exc_type, exc_val, exc_tb):
method urlopen (line 131) | def urlopen(
method _urlfetch_response_to_http_response (line 245) | def _urlfetch_response_to_http_response(self, urlfetch_resp, **respons...
method _get_absolute_timeout (line 281) | def _get_absolute_timeout(self, timeout):
method _get_retries (line 294) | def _get_retries(self, retries, redirect):
FILE: modules/urllib3/contrib/ntlmpool.py
class NTLMConnectionPool (line 18) | class NTLMConnectionPool(HTTPSConnectionPool):
method __init__ (line 25) | def __init__(self, user, pw, authurl, *args, **kwargs):
method _new_conn (line 39) | def _new_conn(self):
method urlopen (line 106) | def urlopen(
FILE: modules/urllib3/contrib/pyopenssl.py
class UnsupportedExtension (line 59) | class UnsupportedExtension(Exception):
function inject_into_urllib3 (line 119) | def inject_into_urllib3():
function extract_from_urllib3 (line 132) | def extract_from_urllib3():
function _validate_dependencies_met (line 143) | def _validate_dependencies_met():
function _dnsname_to_stdlib (line 169) | def _dnsname_to_stdlib(name):
function get_subj_alt_name (line 212) | def get_subj_alt_name(peer_cert):
class WrappedSocket (line 266) | class WrappedSocket(object):
method __init__ (line 273) | def __init__(self, connection, socket, suppress_ragged_eofs=True):
method fileno (line 280) | def fileno(self):
method _decref_socketios (line 284) | def _decref_socketios(self):
method recv (line 290) | def recv(self, *args, **kwargs):
method recv_into (line 315) | def recv_into(self, *args, **kwargs):
method settimeout (line 338) | def settimeout(self, timeout):
method _send_until_done (line 341) | def _send_until_done(self, data):
method sendall (line 352) | def sendall(self, data):
method shutdown (line 360) | def shutdown(self):
method close (line 364) | def close(self):
method getpeercert (line 374) | def getpeercert(self, binary_form=False):
method version (line 388) | def version(self):
method _reuse (line 391) | def _reuse(self):
method _drop (line 394) | def _drop(self):
function makefile (line 403) | def makefile(self, mode, bufsize=-1):
class PyOpenSSLContext (line 414) | class PyOpenSSLContext(object):
method __init__ (line 421) | def __init__(self, protocol):
method options (line 428) | def options(self):
method options (line 432) | def options(self, value):
method verify_mode (line 437) | def verify_mode(self):
method verify_mode (line 441) | def verify_mode(self, value):
method set_default_verify_paths (line 444) | def set_default_verify_paths(self):
method set_ciphers (line 447) | def set_ciphers(self, ciphers):
method load_verify_locations (line 452) | def load_verify_locations(self, cafile=None, capath=None, cadata=None):
method load_cert_chain (line 464) | def load_cert_chain(self, certfile, keyfile=None, password=None):
method set_alpn_protocols (line 472) | def set_alpn_protocols(self, protocols):
method wrap_socket (line 476) | def wrap_socket(
function _verify_callback (line 508) | def _verify_callback(cnx, x509, err_no, err_depth, return_code):
FILE: modules/urllib3/contrib/securetransport.py
function inject_into_urllib3 (line 187) | def inject_into_urllib3():
function extract_from_urllib3 (line 199) | def extract_from_urllib3():
function _read_callback (line 211) | def _read_callback(connection_id, data_buffer, data_length_pointer):
function _write_callback (line 266) | def _write_callback(connection_id, data_buffer, data_length_pointer):
class WrappedSocket (line 324) | class WrappedSocket(object):
method __init__ (line 332) | def __init__(self, socket):
method _raise_on_error (line 351) | def _raise_on_error(self):
method _set_ciphers (line 371) | def _set_ciphers(self):
method _set_alpn_protocols (line 384) | def _set_alpn_protocols(self, protocols):
method _custom_validate (line 397) | def _custom_validate(self, verify, trust_bundle):
method _evaluate_trust (line 432) | def _evaluate_trust(self, trust_bundle):
method handshake (line 472) | def handshake(
method fileno (line 565) | def fileno(self):
method _decref_socketios (line 569) | def _decref_socketios(self):
method recv (line 575) | def recv(self, bufsiz):
method recv_into (line 581) | def recv_into(self, buffer, nbytes=None):
method settimeout (line 624) | def settimeout(self, timeout):
method gettimeout (line 627) | def gettimeout(self):
method send (line 630) | def send(self, data):
method sendall (line 647) | def sendall(self, data):
method shutdown (line 653) | def shutdown(self):
method close (line 657) | def close(self):
method getpeercert (line 676) | def getpeercert(self, binary_form=False):
method version (line 734) | def version(self):
method _reuse (line 755) | def _reuse(self):
method _drop (line 758) | def _drop(self):
function makefile (line 767) | def makefile(self, mode, bufsize=-1):
function makefile (line 774) | def makefile(self, mode="r", buffering=None, *args, **kwargs):
class SecureTransportContext (line 784) | class SecureTransportContext(object):
method __init__ (line 791) | def __init__(self, protocol):
method check_hostname (line 802) | def check_hostname(self):
method check_hostname (line 810) | def check_hostname(self, value):
method options (line 818) | def options(self):
method options (line 828) | def options(self, value):
method verify_mode (line 833) | def verify_mode(self):
method verify_mode (line 837) | def verify_mode(self, value):
method set_default_verify_paths (line 840) | def set_default_verify_paths(self):
method load_default_certs (line 852) | def load_default_certs(self):
method set_ciphers (line 855) | def set_ciphers(self, ciphers):
method load_verify_locations (line 860) | def load_verify_locations(self, cafile=None, capath=None, cadata=None):
method load_cert_chain (line 872) | def load_cert_chain(self, certfile, keyfile=None, password=None):
method set_alpn_protocols (line 877) | def set_alpn_protocols(self, protocols):
method wrap_socket (line 889) | def wrap_socket(
FILE: modules/urllib3/contrib/socks.py
class SOCKSConnection (line 75) | class SOCKSConnection(HTTPConnection):
method __init__ (line 80) | def __init__(self, *args, **kwargs):
method _new_conn (line 84) | def _new_conn(self):
class SOCKSHTTPSConnection (line 147) | class SOCKSHTTPSConnection(SOCKSConnection, HTTPSConnection):
class SOCKSHTTPConnectionPool (line 151) | class SOCKSHTTPConnectionPool(HTTPConnectionPool):
class SOCKSHTTPSConnectionPool (line 155) | class SOCKSHTTPSConnectionPool(HTTPSConnectionPool):
class SOCKSProxyManager (line 159) | class SOCKSProxyManager(PoolManager):
method __init__ (line 170) | def __init__(
FILE: mysterium.py
function clear (line 34) | def clear():
function pause (line 40) | def pause():
function leave (line 46) | def leave():
function error (line 52) | def error(error):
function purple (line 58) | def purple(text):
Condensed preview — 68 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (632K chars).
[
{
"path": "LICENSE",
"chars": 1062,
"preview": "MIT License\n\nCopyright (c) 2021 Venax\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof t"
},
{
"path": "README.md",
"chars": 1838,
"preview": "# **𝙈 𝙔 𝙎 𝙏 𝙀 "
},
{
"path": "executable/pyinstxtractor.py",
"chars": 14875,
"preview": "\"\"\"\nPyInstaller Extractor v2.0 (Supports pyinstaller 4.6, 4.5.1, 4.5, 4.4, 4.3, 4.2, 4.1, 4.0, 3.6, 3.5, 3.4, 3.3, 3.2, "
},
{
"path": "modules/blue.py",
"chars": 9547,
"preview": "# Module created by @Bleu-No / Bleu#7728\n\nfrom datetime import datetime\nfrom colorama import Fore, Style\nfrom re import "
},
{
"path": "modules/dhooks.py",
"chars": 578,
"preview": "print(\"import dhooks\")\r\n\r\nclass Webhook:\r\n def __init__(self, url, **kwargs):\r\n print(\"from dhooks import Webh"
},
{
"path": "modules/fade.py",
"chars": 766,
"preview": "print(\"import fade\")\r\n\r\ndef blackwhite(text):\r\n print(f'fade.blackwhite(text=\"{text}\")')\r\n return text\r\n\r\ndef purp"
},
{
"path": "modules/getmac.py",
"chars": 501,
"preview": "print(\"import getmac\")\r\n\r\ndef get_mac_address(interface=None, ip=None, ip6=None, hostname=None, network_request=True):\r\n"
},
{
"path": "modules/gratient.py",
"chars": 514,
"preview": "print(\"import gratient\")\r\n\r\ndef black(text):\r\n print(f'gratient.black(text=\"{text}\")')\r\n return text\r\n\r\ndef green("
},
{
"path": "modules/json.py",
"chars": 2774,
"preview": "print(\"import json\")\r\n\r\ndef dump(obj, fp=False, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=Tru"
},
{
"path": "modules/playsound.py",
"chars": 169,
"preview": "print(\"import playsound\")\r\n\r\ndef playsound(sound, block=True):\r\n sound = f'\"{sound}\"'\r\n print(f\"playsound.playsoun"
},
{
"path": "modules/pycenter.py",
"chars": 422,
"preview": "print(\"import pycenter\")\r\n\r\ndef center(var: str, space: int = None, icon: str = \"\", sep: bool = False):\r\n center_cont"
},
{
"path": "modules/pyfade.py",
"chars": 2394,
"preview": "print(\"import pyfade\")\r\n\r\ndef init():\r\n print(\"pyfade.init()\")\r\n\r\ndef ditto(text):\r\n return f'\"{text}\"'\r\n\r\nclass F"
},
{
"path": "modules/pyproxies.py",
"chars": 224,
"preview": "print(\"import pyproxies\")\r\n\r\ndef proxy(server, timeout = 5):\r\n print(f'pyproxies.proxy(server=\"{server}\"{f\", timeout="
},
{
"path": "modules/random.py",
"chars": 842,
"preview": "print(\"import random\")\r\n\r\nclass Random:\r\n def randbytes(n):\r\n print(f\"random.randbytes({n})\")\r\n return "
},
{
"path": "modules/re.py",
"chars": 2712,
"preview": "print(\"import re\")\r\n\r\ndef findall(pattern, string, flags=0):\r\n print(f\"re.findall({pattern}, {string})\")\r\n return "
},
{
"path": "modules/requests/__init__.py",
"chars": 3866,
"preview": "print(\"import requests\")\n\nclass Session:\n pass\n\ndef get(url=False, auth=None, json=False, data=False, hooks=None, fil"
},
{
"path": "modules/requests/__version__.py",
"chars": 441,
"preview": "# .-. .-. .-. . . .-. .-. .-. .-.\n# |( |- |.| | | |- `-. | `-.\n# ' ' `-' `-`.`-' `-' `-' ' `-'\n\n__title__ = 'requ"
},
{
"path": "modules/requests/_internal_utils.py",
"chars": 1096,
"preview": "# -*- coding: utf-8 -*-\n\n\"\"\"\nrequests._internal_utils\n~~~~~~~~~~~~~~\n\nProvides utility functions that are consumed inter"
},
{
"path": "modules/requests/adapters.py",
"chars": 21344,
"preview": "# -*- coding: utf-8 -*-\n\n\"\"\"\nrequests.adapters\n~~~~~~~~~~~~~~~~~\n\nThis module contains the transport adapters that Reque"
},
{
"path": "modules/requests/api.py",
"chars": 6402,
"preview": "# -*- coding: utf-8 -*-\n\n\"\"\"\nrequests.api\n~~~~~~~~~~~~\n\nThis module implements the Requests API.\n\n:copyright: (c) 2012 b"
},
{
"path": "modules/requests/auth.py",
"chars": 10207,
"preview": "# -*- coding: utf-8 -*-\n\n\"\"\"\nrequests.auth\n~~~~~~~~~~~~~\n\nThis module contains the authentication handlers for Requests."
},
{
"path": "modules/requests/certs.py",
"chars": 451,
"preview": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"\nrequests.certs\n~~~~~~~~~~~~~~\n\nThis module returns the preferred defa"
},
{
"path": "modules/requests/compat.py",
"chars": 1852,
"preview": "# -*- coding: utf-8 -*-\n\n\"\"\"\nrequests.compat\n~~~~~~~~~~~~~~~\n\nThis module handles import compatibility issues between Py"
},
{
"path": "modules/requests/cookies.py",
"chars": 18430,
"preview": "# -*- coding: utf-8 -*-\n\n\"\"\"\nrequests.cookies\n~~~~~~~~~~~~~~~~\n\nCompatibility code to be able to use `cookielib.CookieJa"
},
{
"path": "modules/requests/exceptions.py",
"chars": 3238,
"preview": "# -*- coding: utf-8 -*-\n\n\"\"\"\nrequests.exceptions\n~~~~~~~~~~~~~~~~~~~\n\nThis module contains the set of Requests' exceptio"
},
{
"path": "modules/requests/help.py",
"chars": 3968,
"preview": "\"\"\"Module containing bug report helper(s).\"\"\"\nfrom __future__ import print_function\n\nimport json\nimport platform\nimport "
},
{
"path": "modules/requests/hooks.py",
"chars": 757,
"preview": "# -*- coding: utf-8 -*-\n\n\"\"\"\nrequests.hooks\n~~~~~~~~~~~~~~\n\nThis module provides the capabilities for the Requests hooks"
},
{
"path": "modules/requests/models.py",
"chars": 34859,
"preview": "# -*- coding: utf-8 -*-\n\n\"\"\"\nrequests.models\n~~~~~~~~~~~~~~~\n\nThis module contains the primary objects that power Reques"
},
{
"path": "modules/requests/packages.py",
"chars": 932,
"preview": "import sys\n\ntry:\n import chardet\nexcept ImportError:\n import charset_normalizer as chardet\n import warnings\n\n "
},
{
"path": "modules/requests/sessions.py",
"chars": 30168,
"preview": "# -*- coding: utf-8 -*-\n\n\"\"\"\nrequests.sessions\n~~~~~~~~~~~~~~~~~\n\nThis module provides a Session object to manage and pe"
},
{
"path": "modules/requests/status_codes.py",
"chars": 4184,
"preview": "# -*- coding: utf-8 -*-\n\nr\"\"\"\nThe ``codes`` object defines a mapping from common names for HTTP statuses\nto their numeri"
},
{
"path": "modules/requests/structures.py",
"chars": 3005,
"preview": "# -*- coding: utf-8 -*-\n\n\"\"\"\nrequests.structures\n~~~~~~~~~~~~~~~~~~~\n\nData structures that power Requests.\n\"\"\"\n\nfrom col"
},
{
"path": "modules/requests/utils.py",
"chars": 31382,
"preview": "# -*- coding: utf-8 -*-\n\n\"\"\"\nrequests.utils\n~~~~~~~~~~~~~~\n\nThis module provides utility functions that are used within "
},
{
"path": "modules/tkinter/colorchooser.py",
"chars": 2746,
"preview": "# tk common color chooser dialogue\r\n#\r\n# this module provides an interface to the native color dialogue\r\n# available in "
},
{
"path": "modules/tkinter/commondialog.py",
"chars": 1303,
"preview": "# base class for tk common dialogues\r\n#\r\n# this module provides a base class for accessing the common\r\n# dialogues avail"
},
{
"path": "modules/tkinter/constants.py",
"chars": 1603,
"preview": "# Symbolic constants for Tk\r\n\r\n# Booleans\r\nNO=FALSE=OFF=0\r\nYES=TRUE=ON=1\r\n\r\n# -anchor and -sticky\r\nN='n'\r\nS='s'\r\nW='w'\r\n"
},
{
"path": "modules/tkinter/dialog.py",
"chars": 1592,
"preview": "# dialog.py -- Tkinter interface to the tk_dialog script.\r\n\r\nfrom tkinter import _cnfmerge, Widget, TclError, Button, Pa"
},
{
"path": "modules/tkinter/dnd.py",
"chars": 11852,
"preview": "\"\"\"Drag-and-drop support for Tkinter.\r\n\r\nThis is very preliminary. I currently only support dnd *within* one\r\napplicati"
},
{
"path": "modules/tkinter/filedialog.py",
"chars": 15440,
"preview": "\"\"\"File selection dialog classes.\r\n\r\nClasses:\r\n\r\n- FileDialog\r\n- LoadFileDialog\r\n- SaveFileDialog\r\n\r\nThis module also pr"
},
{
"path": "modules/tkinter/font.py",
"chars": 7056,
"preview": "# Tkinter font wrapper\r\n#\r\n# written by Fredrik Lundh, February 1998\r\n#\r\n\r\nimport itertools\r\nimport tkinter\r\n\r\n__version"
},
{
"path": "modules/tkinter/messagebox.py",
"chars": 4716,
"preview": "# tk common message boxes\r\n#\r\n# this module provides an interface to the native message boxes\r\n# available in Tk 4.2 and"
},
{
"path": "modules/tkinter/scrolledtext.py",
"chars": 1872,
"preview": "\"\"\"A ScrolledText widget feels like a text widget but also has a\r\nvertical scroll bar on its right. (Later, options may"
},
{
"path": "modules/tkinter/simpledialog.py",
"chars": 12197,
"preview": "#\r\n# An Introduction to Tkinter\r\n#\r\n# Copyright (c) 1997 by Fredrik Lundh\r\n#\r\n# This copyright applies to Dialog, askint"
},
{
"path": "modules/tkinter/test/README",
"chars": 580,
"preview": "Writing new tests\r\n=================\r\n\r\nPrecaution\r\n----------\r\n\r\n New tests should always use only one Tk window at "
},
{
"path": "modules/tkinter/test/runtktests.py",
"chars": 2299,
"preview": "\"\"\"\r\nUse this module to get and run all tk tests.\r\n\r\ntkinter tests should live in a package inside the directory where t"
},
{
"path": "modules/tkinter/test/support.py",
"chars": 4733,
"preview": "import functools\r\nimport re\r\nimport tkinter\r\nimport unittest\r\n\r\nclass AbstractTkTest:\r\n\r\n @classmethod\r\n def setUp"
},
{
"path": "modules/tkinter/test/test_tkinter/test_colorchooser.py",
"chars": 1400,
"preview": "import unittest\r\nimport tkinter\r\nfrom test.support import requires, run_unittest, swap_attr\r\nfrom tkinter.test.support i"
},
{
"path": "modules/tkinter/test/test_tkinter/test_font.py",
"chars": 5460,
"preview": "import unittest\r\nimport tkinter\r\nfrom tkinter import font\r\nfrom test.support import requires, run_unittest, gc_collect, "
},
{
"path": "modules/tkinter/test/test_tkinter/test_geometry_managers.py",
"chars": 41921,
"preview": "import unittest\r\nimport re\r\nimport tkinter\r\nfrom tkinter import TclError\r\nfrom test.support import requires\r\n\r\nfrom tkin"
},
{
"path": "modules/tkinter/test/test_tkinter/test_images.py",
"chars": 15895,
"preview": "import unittest\r\nimport tkinter\r\nfrom test import support\r\nfrom tkinter.test.support import AbstractTkTest, AbstractDefa"
},
{
"path": "modules/tkinter/test/test_tkinter/test_loadtk.py",
"chars": 1549,
"preview": "import os\r\nimport sys\r\nimport unittest\r\nimport test.support as test_support\r\nfrom tkinter import Tcl, TclError\r\n\r\ntest_s"
},
{
"path": "modules/tkinter/test/test_tkinter/test_misc.py",
"chars": 12848,
"preview": "import unittest\r\nimport tkinter\r\nfrom test import support\r\nfrom tkinter.test.support import AbstractTkTest, AbstractDefa"
},
{
"path": "modules/tkinter/test/test_tkinter/test_simpledialog.py",
"chars": 805,
"preview": "import unittest\r\nimport tkinter\r\nfrom test.support import requires, run_unittest, swap_attr\r\nfrom tkinter.test.support i"
},
{
"path": "modules/tkinter/test/test_tkinter/test_text.py",
"chars": 1489,
"preview": "import unittest\r\nimport tkinter\r\nfrom test.support import requires, run_unittest\r\nfrom tkinter.test.support import Abstr"
},
{
"path": "modules/tkinter/test/test_tkinter/test_variables.py",
"chars": 11316,
"preview": "import unittest\r\nfrom test import support\r\n\r\nimport gc\r\nimport tkinter\r\nfrom tkinter import (Variable, StringVar, IntVar"
},
{
"path": "modules/tkinter/test/test_tkinter/test_widgets.py",
"chars": 52974,
"preview": "import unittest\r\nimport tkinter\r\nfrom tkinter import TclError\r\nimport os\r\nfrom test.support import requires\r\n\r\nfrom tkin"
},
{
"path": "modules/urllib3/connection.py",
"chars": 18748,
"preview": "from __future__ import absolute_import\n\nimport datetime\nimport logging\nimport os\nimport re\nimport socket\nimport warnings"
},
{
"path": "modules/urllib3/connectionpool.py",
"chars": 37133,
"preview": "from __future__ import absolute_import\n\nimport errno\nimport logging\nimport socket\nimport sys\nimport warnings\nfrom socket"
},
{
"path": "modules/urllib3/contrib/_appengine_environ.py",
"chars": 957,
"preview": "\"\"\"\nThis module provides means to detect the App Engine environment.\n\"\"\"\n\nimport os\n\n\ndef is_appengine():\n return is_"
},
{
"path": "modules/urllib3/contrib/_securetransport/bindings.py",
"chars": 17637,
"preview": "\"\"\"\nThis module uses ctypes to bind a whole bunch of functions and constants from\nSecureTransport. The goal here is to p"
},
{
"path": "modules/urllib3/contrib/_securetransport/low_level.py",
"chars": 13908,
"preview": "\"\"\"\nLow-level helpers for the SecureTransport bindings.\n\nThese are Python functions that are not directly related to the"
},
{
"path": "modules/urllib3/contrib/appengine.py",
"chars": 11010,
"preview": "\"\"\"\nThis module provides a pool manager that uses Google App Engine's\n`URLFetch Service <https://cloud.google.com/appeng"
},
{
"path": "modules/urllib3/contrib/ntlmpool.py",
"chars": 4160,
"preview": "\"\"\"\nNTLM authenticating pool, contributed by erikcederstran\n\nIssue #10, see: http://code.google.com/p/urllib3/issues/det"
},
{
"path": "modules/urllib3/contrib/pyopenssl.py",
"chars": 16778,
"preview": "\"\"\"\nTLS with SNI_-support for Python 2. Follow these instructions if you would\nlike to verify TLS certificates in Python"
},
{
"path": "modules/urllib3/contrib/securetransport.py",
"chars": 34286,
"preview": "\"\"\"\nSecureTranport support for urllib3 via ctypes.\n\nThis makes platform-native TLS available to urllib3 users on macOS w"
},
{
"path": "modules/urllib3/contrib/socks.py",
"chars": 7097,
"preview": "# -*- coding: utf-8 -*-\n\"\"\"\nThis module contains provisional support for SOCKS proxies from within\nurllib3. This module "
},
{
"path": "mysterium.py",
"chars": 8957,
"preview": "# Made by @venaxyt on Github (helped by @IDRALOU, @Bleu-No and @vjousse)\r\n# @venaxyt: All code and interface | @Bleu-No:"
},
{
"path": "requirements.txt",
"chars": 20,
"preview": "wheel\nfade\ngratient\n"
}
]
About this extraction
This page contains the full source code of the venaxyt/mysterium GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 68 files (586.1 KB), approximately 140.5k tokens, and a symbol index with 1080 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.