├── .idea
├── .name
├── encodings.xml
├── misc.xml
├── modules.xml
├── vcs.xml
├── workspace.xml
└── wxpytest.iml
├── README.md
├── config.yaml
├── cxkd.py
├── cxkdurllib.py
├── imgtest.py
├── index.wsgi
├── templates
└── reply_text.xml
├── vendor
├── requests-2.10.0.dist-info
│ ├── DESCRIPTION.rst
│ ├── INSTALLER
│ ├── METADATA
│ ├── RECORD
│ ├── WHEEL
│ ├── metadata.json
│ └── top_level.txt
└── requests
│ ├── __init__.py
│ ├── __init__.pyc
│ ├── adapters.py
│ ├── adapters.pyc
│ ├── api.py
│ ├── api.pyc
│ ├── auth.py
│ ├── auth.pyc
│ ├── cacert.pem
│ ├── certs.py
│ ├── certs.pyc
│ ├── compat.py
│ ├── compat.pyc
│ ├── cookies.py
│ ├── cookies.pyc
│ ├── exceptions.py
│ ├── exceptions.pyc
│ ├── hooks.py
│ ├── hooks.pyc
│ ├── models.py
│ ├── models.pyc
│ ├── packages
│ ├── __init__.py
│ ├── __init__.pyc
│ ├── chardet
│ │ ├── __init__.py
│ │ ├── __init__.pyc
│ │ ├── big5freq.py
│ │ ├── big5freq.pyc
│ │ ├── big5prober.py
│ │ ├── big5prober.pyc
│ │ ├── chardetect.py
│ │ ├── chardetect.pyc
│ │ ├── chardistribution.py
│ │ ├── chardistribution.pyc
│ │ ├── charsetgroupprober.py
│ │ ├── charsetgroupprober.pyc
│ │ ├── charsetprober.py
│ │ ├── charsetprober.pyc
│ │ ├── codingstatemachine.py
│ │ ├── codingstatemachine.pyc
│ │ ├── compat.py
│ │ ├── compat.pyc
│ │ ├── constants.py
│ │ ├── constants.pyc
│ │ ├── cp949prober.py
│ │ ├── cp949prober.pyc
│ │ ├── escprober.py
│ │ ├── escprober.pyc
│ │ ├── escsm.py
│ │ ├── escsm.pyc
│ │ ├── eucjpprober.py
│ │ ├── eucjpprober.pyc
│ │ ├── euckrfreq.py
│ │ ├── euckrfreq.pyc
│ │ ├── euckrprober.py
│ │ ├── euckrprober.pyc
│ │ ├── euctwfreq.py
│ │ ├── euctwfreq.pyc
│ │ ├── euctwprober.py
│ │ ├── euctwprober.pyc
│ │ ├── gb2312freq.py
│ │ ├── gb2312freq.pyc
│ │ ├── gb2312prober.py
│ │ ├── gb2312prober.pyc
│ │ ├── hebrewprober.py
│ │ ├── hebrewprober.pyc
│ │ ├── jisfreq.py
│ │ ├── jisfreq.pyc
│ │ ├── jpcntx.py
│ │ ├── jpcntx.pyc
│ │ ├── langbulgarianmodel.py
│ │ ├── langbulgarianmodel.pyc
│ │ ├── langcyrillicmodel.py
│ │ ├── langcyrillicmodel.pyc
│ │ ├── langgreekmodel.py
│ │ ├── langgreekmodel.pyc
│ │ ├── langhebrewmodel.py
│ │ ├── langhebrewmodel.pyc
│ │ ├── langhungarianmodel.py
│ │ ├── langhungarianmodel.pyc
│ │ ├── langthaimodel.py
│ │ ├── langthaimodel.pyc
│ │ ├── latin1prober.py
│ │ ├── latin1prober.pyc
│ │ ├── mbcharsetprober.py
│ │ ├── mbcharsetprober.pyc
│ │ ├── mbcsgroupprober.py
│ │ ├── mbcsgroupprober.pyc
│ │ ├── mbcssm.py
│ │ ├── mbcssm.pyc
│ │ ├── sbcharsetprober.py
│ │ ├── sbcharsetprober.pyc
│ │ ├── sbcsgroupprober.py
│ │ ├── sbcsgroupprober.pyc
│ │ ├── sjisprober.py
│ │ ├── sjisprober.pyc
│ │ ├── universaldetector.py
│ │ ├── universaldetector.pyc
│ │ ├── utf8prober.py
│ │ └── utf8prober.pyc
│ └── urllib3
│ │ ├── __init__.py
│ │ ├── __init__.pyc
│ │ ├── _collections.py
│ │ ├── _collections.pyc
│ │ ├── connection.py
│ │ ├── connection.pyc
│ │ ├── connectionpool.py
│ │ ├── connectionpool.pyc
│ │ ├── contrib
│ │ ├── __init__.py
│ │ ├── __init__.pyc
│ │ ├── appengine.py
│ │ ├── appengine.pyc
│ │ ├── ntlmpool.py
│ │ ├── ntlmpool.pyc
│ │ ├── pyopenssl.py
│ │ ├── pyopenssl.pyc
│ │ ├── socks.py
│ │ └── socks.pyc
│ │ ├── exceptions.py
│ │ ├── exceptions.pyc
│ │ ├── fields.py
│ │ ├── fields.pyc
│ │ ├── filepost.py
│ │ ├── filepost.pyc
│ │ ├── packages
│ │ ├── __init__.py
│ │ ├── __init__.pyc
│ │ ├── ordered_dict.py
│ │ ├── ordered_dict.pyc
│ │ ├── six.py
│ │ ├── six.pyc
│ │ └── ssl_match_hostname
│ │ │ ├── __init__.py
│ │ │ ├── __init__.pyc
│ │ │ ├── _implementation.py
│ │ │ └── _implementation.pyc
│ │ ├── poolmanager.py
│ │ ├── poolmanager.pyc
│ │ ├── request.py
│ │ ├── request.pyc
│ │ ├── response.py
│ │ ├── response.pyc
│ │ └── util
│ │ ├── __init__.py
│ │ ├── __init__.pyc
│ │ ├── connection.py
│ │ ├── connection.pyc
│ │ ├── request.py
│ │ ├── request.pyc
│ │ ├── response.py
│ │ ├── response.pyc
│ │ ├── retry.py
│ │ ├── retry.pyc
│ │ ├── ssl_.py
│ │ ├── ssl_.pyc
│ │ ├── timeout.py
│ │ ├── timeout.pyc
│ │ ├── url.py
│ │ └── url.pyc
│ ├── sessions.py
│ ├── sessions.pyc
│ ├── status_codes.py
│ ├── status_codes.pyc
│ ├── structures.py
│ ├── structures.pyc
│ ├── utils.py
│ └── utils.pyc
└── weixinInterface.py
/.idea/.name:
--------------------------------------------------------------------------------
1 | wxpytest
--------------------------------------------------------------------------------
/.idea/encodings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
--------------------------------------------------------------------------------
/.idea/modules.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/.idea/vcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/.idea/wxpytest.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # wxpytest
2 | Python 微信公众号开发
3 |
4 | https://zhuanlan.zhihu.com/p/21354943
5 |
--------------------------------------------------------------------------------
/config.yaml:
--------------------------------------------------------------------------------
1 | name: wxpytest
2 | version: 1
3 |
4 | libraries:
5 | - name: webpy
6 | version: "0.36"
7 |
8 | - name: lxml
9 | version: "2.3.4"
10 |
11 | - name: requests
12 | version: "2.9.0"
13 |
14 | ...
--------------------------------------------------------------------------------
/cxkd.py:
--------------------------------------------------------------------------------
1 | import requests
2 | import json
3 | global s
4 | s = requests.session()
5 | headers = {
6 | 'Host':'www.kuaidi100.com',
7 | 'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0',
8 | 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
9 | 'Accept-Language': 'zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3',
10 | 'Accept-Encoding': 'gzip, deflate',
11 | 'Connection': 'keep-alive',
12 | }
13 |
14 |
15 | def detect_com(postid):
16 | r = s.get('http://www.kuaidi100.com/autonumber/autoComNum?text='+postid)
17 | j = r.json()
18 | kuaiditpye = j["auto"][0]['comCode']
19 | #print kuaiditpye
20 | return kuaiditpye
21 |
22 |
23 | def cxkd(postid):
24 | kuaiditype = detect_com(postid)
25 | r = s.post('http://www.kuaidi100.com/query?type='+kuaiditype+'&postid='+postid, headers=headers)
26 | # print(r.json())
27 | j = r.json()
28 | # print(j)
29 | # print(j.keys())
30 | # print(j['data'])
31 | outcome = ''
32 | for c in j['data']:
33 | outcome = outcome + c['time']+' '+c['context']+'\n'
34 | return outcome
35 |
36 | #a = cxkd('280472503105')
37 | #print a
38 |
39 |
40 |
--------------------------------------------------------------------------------
/cxkdurllib.py:
--------------------------------------------------------------------------------
1 | import urllib2
2 | import json
3 |
4 |
5 | def detect_com(postid):
6 | r = urllib2.urlopen('http://www.kuaidi100.com/autonumber/autoComNum?text='+postid)
7 | h = r.read()
8 | #j = json.dumps(h)
9 | #k = json.loads(j)
10 | k = eval(h)
11 | kuaiditpye = k["auto"][0]['comCode']
12 | #print kuaiditpye
13 | return kuaiditpye
14 |
15 |
16 | def cxkd(postid):
17 | kuaiditype = detect_com(postid)
18 | r = urllib2.urlopen('http://www.kuaidi100.com/query?type='+kuaiditype+'&postid='+postid)
19 | h = r.read()
20 | # print(r.json())
21 | #j = json.dumps(h)
22 | j = eval(h)
23 | # print(j)
24 | # print(j.keys())
25 | # print(j['data'])
26 | outcome = ''
27 | for c in j['data']:
28 | outcome = outcome + c['time']+' '+c['context']+'\n'
29 | return outcome
30 |
31 | #a = cxkd('280472503105')
32 | #print a
33 |
34 |
35 |
--------------------------------------------------------------------------------
/imgtest.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | import requests
3 | import re
4 | def imgtest(picurl):
5 | s = requests.session()
6 | url = 'http://how-old.net/Home/Analyze?isTest=False&source=&version=001'
7 | header = {
8 | 'Accept-Encoding':'gzip, deflate',
9 | 'User-Agent': "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:34.0) Gecko/20100101 Firefox/34.0",
10 | 'Host': "how-old.net",
11 | 'Referer': "http://how-old.net/",
12 | 'X-Requested-With': "XMLHttpRequest"
13 | }
14 |
15 |
16 | data = {'file':s.get(picurl).content}
17 | #data = {'file': open(sid+'.jpg', 'rb')}
18 | #此处打开指定的jpg文件
19 |
20 | r = s.post(url, files=data, headers=header)
21 | h = r.content
22 | i = h.replace('\\','')
23 | #j = eval(i)
24 |
25 | gender = re.search(r'"gender": "(.*?)"rn', i)
26 | age = re.search(r'"age": (.*?),rn', i)
27 | if gender.group(1) == 'Male':
28 | gender1 = '男'
29 | else:
30 | gender1 = '女'
31 | #print gender1
32 | #print age.group(1)
33 | datas = [gender1, age.group(1)]
34 | return datas
35 | #picurl = 'http://ent.cnr.cn/list/20151111/W020151111322757495693.jpg'
36 | #imgtest(picurl)
--------------------------------------------------------------------------------
/index.wsgi:
--------------------------------------------------------------------------------
1 | # coding: UTF-8
2 | import os
3 | import sae
4 | import web
5 | import sae
6 | sae.add_vendor_dir('vendor')
7 | from weixinInterface import WeixinInterface
8 |
9 | urls = (
10 | '/weixin','WeixinInterface'
11 | )
12 |
13 | app_root = os.path.dirname(__file__)
14 | templates_root = os.path.join(app_root, 'templates')
15 | render = web.template.render(templates_root)
16 |
17 | app = web.application(urls, globals()).wsgifunc()
18 | application = sae.create_wsgi_app(app)
--------------------------------------------------------------------------------
/templates/reply_text.xml:
--------------------------------------------------------------------------------
1 | $def with (toUser,fromUser,createTime,content)
2 |
3 |
4 |
5 | $createTime
6 |
7 |
8 |
--------------------------------------------------------------------------------
/vendor/requests-2.10.0.dist-info/INSTALLER:
--------------------------------------------------------------------------------
1 | pip
2 |
--------------------------------------------------------------------------------
/vendor/requests-2.10.0.dist-info/WHEEL:
--------------------------------------------------------------------------------
1 | Wheel-Version: 1.0
2 | Generator: bdist_wheel (0.29.0)
3 | Root-Is-Purelib: true
4 | Tag: py2-none-any
5 | Tag: py3-none-any
6 |
7 |
--------------------------------------------------------------------------------
/vendor/requests-2.10.0.dist-info/metadata.json:
--------------------------------------------------------------------------------
1 | {"classifiers": ["Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "Natural Language :: English", "License :: OSI Approved :: Apache Software License", "Programming Language :: Python", "Programming Language :: Python :: 2.6", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.3", "Programming Language :: Python :: 3.4", "Programming Language :: Python :: 3.5", "Programming Language :: Python :: Implementation :: CPython", "Programming Language :: Python :: Implementation :: PyPy"], "extensions": {"python.details": {"contacts": [{"email": "me@kennethreitz.com", "name": "Kenneth Reitz", "role": "author"}], "document_names": {"description": "DESCRIPTION.rst"}, "project_urls": {"Home": "http://python-requests.org"}}}, "extras": ["security", "socks"], "generator": "bdist_wheel (0.29.0)", "license": "Apache 2.0", "metadata_version": "2.0", "name": "requests", "run_requires": [{"extra": "socks", "requires": ["PySocks (>=1.5.6)"]}, {"extra": "security", "requires": ["ndg-httpsclient", "pyOpenSSL (>=0.13)", "pyasn1"]}], "summary": "Python HTTP for Humans.", "test_requires": [{"requires": ["pytest (>=2.8.0)", "pytest-cov", "pytest-httpbin (==0.0.7)"]}], "version": "2.10.0"}
--------------------------------------------------------------------------------
/vendor/requests-2.10.0.dist-info/top_level.txt:
--------------------------------------------------------------------------------
1 | requests
2 |
--------------------------------------------------------------------------------
/vendor/requests/__init__.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
3 | # __
4 | # /__) _ _ _ _ _/ _
5 | # / ( (- (/ (/ (- _) / _)
6 | # /
7 |
8 | """
9 | Requests HTTP library
10 | ~~~~~~~~~~~~~~~~~~~~~
11 |
12 | Requests is an HTTP library, written in Python, for human beings. Basic GET
13 | usage:
14 |
15 | >>> import requests
16 | >>> r = requests.get('https://www.python.org')
17 | >>> r.status_code
18 | 200
19 | >>> 'Python is a programming language' in r.content
20 | True
21 |
22 | ... or POST:
23 |
24 | >>> payload = dict(key1='value1', key2='value2')
25 | >>> r = requests.post('http://httpbin.org/post', data=payload)
26 | >>> print(r.text)
27 | {
28 | ...
29 | "form": {
30 | "key2": "value2",
31 | "key1": "value1"
32 | },
33 | ...
34 | }
35 |
36 | The other HTTP methods are supported - see `requests.api`. Full documentation
37 | is at .
38 |
39 | :copyright: (c) 2016 by Kenneth Reitz.
40 | :license: Apache 2.0, see LICENSE for more details.
41 |
42 | """
43 |
44 | __title__ = 'requests'
45 | __version__ = '2.10.0'
46 | __build__ = 0x021000
47 | __author__ = 'Kenneth Reitz'
48 | __license__ = 'Apache 2.0'
49 | __copyright__ = 'Copyright 2016 Kenneth Reitz'
50 |
51 | # Attempt to enable urllib3's SNI support, if possible
52 | try:
53 | from .packages.urllib3.contrib import pyopenssl
54 | pyopenssl.inject_into_urllib3()
55 | except ImportError:
56 | pass
57 |
58 | import warnings
59 |
60 | # urllib3's DependencyWarnings should be silenced.
61 | from .packages.urllib3.exceptions import DependencyWarning
62 | warnings.simplefilter('ignore', DependencyWarning)
63 |
64 | from . import utils
65 | from .models import Request, Response, PreparedRequest
66 | from .api import request, get, head, post, patch, put, delete, options
67 | from .sessions import session, Session
68 | from .status_codes import codes
69 | from .exceptions import (
70 | RequestException, Timeout, URLRequired,
71 | TooManyRedirects, HTTPError, ConnectionError,
72 | FileModeWarning, ConnectTimeout, ReadTimeout
73 | )
74 |
75 | # Set default logging handler to avoid "No handler found" warnings.
76 | import logging
77 | try: # Python 2.7+
78 | from logging import NullHandler
79 | except ImportError:
80 | class NullHandler(logging.Handler):
81 | def emit(self, record):
82 | pass
83 |
84 | logging.getLogger(__name__).addHandler(NullHandler())
85 |
86 | import warnings
87 |
88 | # FileModeWarnings go off per the default.
89 | warnings.simplefilter('default', FileModeWarning, append=True)
90 |
--------------------------------------------------------------------------------
/vendor/requests/__init__.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/loveQt/wxpytest/c8923b2298a5f71aca4bcee656125dc219d45592/vendor/requests/__init__.pyc
--------------------------------------------------------------------------------
/vendor/requests/adapters.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/loveQt/wxpytest/c8923b2298a5f71aca4bcee656125dc219d45592/vendor/requests/adapters.pyc
--------------------------------------------------------------------------------
/vendor/requests/api.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
3 | """
4 | requests.api
5 | ~~~~~~~~~~~~
6 |
7 | This module implements the Requests API.
8 |
9 | :copyright: (c) 2012 by Kenneth Reitz.
10 | :license: Apache2, see LICENSE for more details.
11 |
12 | """
13 |
14 | from . import sessions
15 |
16 |
17 | def request(method, url, **kwargs):
18 | """Constructs and sends a :class:`Request `.
19 |
20 | :param method: method for the new :class:`Request` object.
21 | :param url: URL for the new :class:`Request` object.
22 | :param params: (optional) Dictionary or bytes to be sent in the query string for the :class:`Request`.
23 | :param data: (optional) Dictionary, bytes, or file-like object to send in the body of the :class:`Request`.
24 | :param json: (optional) json data to send in the body of the :class:`Request`.
25 | :param headers: (optional) Dictionary of HTTP Headers to send with the :class:`Request`.
26 | :param cookies: (optional) Dict or CookieJar object to send with the :class:`Request`.
27 | :param files: (optional) Dictionary of ``'name': file-like-objects`` (or ``{'name': file-tuple}``) for multipart encoding upload.
28 | ``file-tuple`` can be a 2-tuple ``('filename', fileobj)``, 3-tuple ``('filename', fileobj, 'content_type')``
29 | or a 4-tuple ``('filename', fileobj, 'content_type', custom_headers)``, where ``'content-type'`` is a string
30 | defining the content type of the given file and ``custom_headers`` a dict-like object containing additional headers
31 | to add for the file.
32 | :param auth: (optional) Auth tuple to enable Basic/Digest/Custom HTTP Auth.
33 | :param timeout: (optional) How long to wait for the server to send data
34 | before giving up, as a float, or a :ref:`(connect timeout, read
35 | timeout) ` tuple.
36 | :type timeout: float or tuple
37 | :param allow_redirects: (optional) Boolean. Set to True if POST/PUT/DELETE redirect following is allowed.
38 | :type allow_redirects: bool
39 | :param proxies: (optional) Dictionary mapping protocol to the URL of the proxy.
40 | :param verify: (optional) whether the SSL cert will be verified. A CA_BUNDLE path can also be provided. Defaults to ``True``.
41 | :param stream: (optional) if ``False``, the response content will be immediately downloaded.
42 | :param cert: (optional) if String, path to ssl client cert file (.pem). If Tuple, ('cert', 'key') pair.
43 | :return: :class:`Response ` object
44 | :rtype: requests.Response
45 |
46 | Usage::
47 |
48 | >>> import requests
49 | >>> req = requests.request('GET', 'http://httpbin.org/get')
50 |
51 | """
52 |
53 | # By using the 'with' statement we are sure the session is closed, thus we
54 | # avoid leaving sockets open which can trigger a ResourceWarning in some
55 | # cases, and look like a memory leak in others.
56 | with sessions.Session() as session:
57 | return session.request(method=method, url=url, **kwargs)
58 |
59 |
60 | def get(url, params=None, **kwargs):
61 | """Sends a GET request.
62 |
63 | :param url: URL for the new :class:`Request` object.
64 | :param params: (optional) Dictionary or bytes to be sent in the query string for the :class:`Request`.
65 | :param \*\*kwargs: Optional arguments that ``request`` takes.
66 | :return: :class:`Response ` object
67 | :rtype: requests.Response
68 | """
69 |
70 | kwargs.setdefault('allow_redirects', True)
71 | return request('get', url, params=params, **kwargs)
72 |
73 |
74 | def options(url, **kwargs):
75 | """Sends a OPTIONS request.
76 |
77 | :param url: URL for the new :class:`Request` object.
78 | :param \*\*kwargs: Optional arguments that ``request`` takes.
79 | :return: :class:`Response ` object
80 | :rtype: requests.Response
81 | """
82 |
83 | kwargs.setdefault('allow_redirects', True)
84 | return request('options', url, **kwargs)
85 |
86 |
87 | def head(url, **kwargs):
88 | """Sends a HEAD request.
89 |
90 | :param url: URL for the new :class:`Request` object.
91 | :param \*\*kwargs: Optional arguments that ``request`` takes.
92 | :return: :class:`Response ` object
93 | :rtype: requests.Response
94 | """
95 |
96 | kwargs.setdefault('allow_redirects', False)
97 | return request('head', url, **kwargs)
98 |
99 |
100 | def post(url, data=None, json=None, **kwargs):
101 | """Sends a POST request.
102 |
103 | :param url: URL for the new :class:`Request` object.
104 | :param data: (optional) Dictionary, bytes, or file-like object to send in the body of the :class:`Request`.
105 | :param json: (optional) json data to send in the body of the :class:`Request`.
106 | :param \*\*kwargs: Optional arguments that ``request`` takes.
107 | :return: :class:`Response ` object
108 | :rtype: requests.Response
109 | """
110 |
111 | return request('post', url, data=data, json=json, **kwargs)
112 |
113 |
114 | def put(url, data=None, **kwargs):
115 | """Sends a PUT request.
116 |
117 | :param url: URL for the new :class:`Request` object.
118 | :param data: (optional) Dictionary, bytes, or file-like object to send in the body of the :class:`Request`.
119 | :param \*\*kwargs: Optional arguments that ``request`` takes.
120 | :return: :class:`Response ` object
121 | :rtype: requests.Response
122 | """
123 |
124 | return request('put', url, data=data, **kwargs)
125 |
126 |
127 | def patch(url, data=None, **kwargs):
128 | """Sends a PATCH request.
129 |
130 | :param url: URL for the new :class:`Request` object.
131 | :param data: (optional) Dictionary, bytes, or file-like object to send in the body of the :class:`Request`.
132 | :param \*\*kwargs: Optional arguments that ``request`` takes.
133 | :return: :class:`Response ` object
134 | :rtype: requests.Response
135 | """
136 |
137 | return request('patch', url, data=data, **kwargs)
138 |
139 |
140 | def delete(url, **kwargs):
141 | """Sends a DELETE request.
142 |
143 | :param url: URL for the new :class:`Request` object.
144 | :param \*\*kwargs: Optional arguments that ``request`` takes.
145 | :return: :class:`Response ` object
146 | :rtype: requests.Response
147 | """
148 |
149 | return request('delete', url, **kwargs)
150 |
--------------------------------------------------------------------------------
/vendor/requests/api.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/loveQt/wxpytest/c8923b2298a5f71aca4bcee656125dc219d45592/vendor/requests/api.pyc
--------------------------------------------------------------------------------
/vendor/requests/auth.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
3 | """
4 | requests.auth
5 | ~~~~~~~~~~~~~
6 |
7 | This module contains the authentication handlers for Requests.
8 | """
9 |
10 | import os
11 | import re
12 | import time
13 | import hashlib
14 | import threading
15 |
16 | from base64 import b64encode
17 |
18 | from .compat import urlparse, str
19 | from .cookies import extract_cookies_to_jar
20 | from .utils import parse_dict_header, to_native_string
21 | from .status_codes import codes
22 |
23 | CONTENT_TYPE_FORM_URLENCODED = 'application/x-www-form-urlencoded'
24 | CONTENT_TYPE_MULTI_PART = 'multipart/form-data'
25 |
26 |
27 | def _basic_auth_str(username, password):
28 | """Returns a Basic Auth string."""
29 |
30 | authstr = 'Basic ' + to_native_string(
31 | b64encode(('%s:%s' % (username, password)).encode('latin1')).strip()
32 | )
33 |
34 | return authstr
35 |
36 |
37 | class AuthBase(object):
38 | """Base class that all auth implementations derive from"""
39 |
40 | def __call__(self, r):
41 | raise NotImplementedError('Auth hooks must be callable.')
42 |
43 |
44 | class HTTPBasicAuth(AuthBase):
45 | """Attaches HTTP Basic Authentication to the given Request object."""
46 | def __init__(self, username, password):
47 | self.username = username
48 | self.password = password
49 |
50 | def __eq__(self, other):
51 | return all([
52 | self.username == getattr(other, 'username', None),
53 | self.password == getattr(other, 'password', None)
54 | ])
55 |
56 | def __ne__(self, other):
57 | return not self == other
58 |
59 | def __call__(self, r):
60 | r.headers['Authorization'] = _basic_auth_str(self.username, self.password)
61 | return r
62 |
63 |
64 | class HTTPProxyAuth(HTTPBasicAuth):
65 | """Attaches HTTP Proxy Authentication to a given Request object."""
66 | def __call__(self, r):
67 | r.headers['Proxy-Authorization'] = _basic_auth_str(self.username, self.password)
68 | return r
69 |
70 |
71 | class HTTPDigestAuth(AuthBase):
72 | """Attaches HTTP Digest Authentication to the given Request object."""
73 | def __init__(self, username, password):
74 | self.username = username
75 | self.password = password
76 | # Keep state in per-thread local storage
77 | self._thread_local = threading.local()
78 |
79 | def init_per_thread_state(self):
80 | # Ensure state is initialized just once per-thread
81 | if not hasattr(self._thread_local, 'init'):
82 | self._thread_local.init = True
83 | self._thread_local.last_nonce = ''
84 | self._thread_local.nonce_count = 0
85 | self._thread_local.chal = {}
86 | self._thread_local.pos = None
87 | self._thread_local.num_401_calls = None
88 |
89 | def build_digest_header(self, method, url):
90 |
91 | realm = self._thread_local.chal['realm']
92 | nonce = self._thread_local.chal['nonce']
93 | qop = self._thread_local.chal.get('qop')
94 | algorithm = self._thread_local.chal.get('algorithm')
95 | opaque = self._thread_local.chal.get('opaque')
96 | hash_utf8 = None
97 |
98 | if algorithm is None:
99 | _algorithm = 'MD5'
100 | else:
101 | _algorithm = algorithm.upper()
102 | # lambdas assume digest modules are imported at the top level
103 | if _algorithm == 'MD5' or _algorithm == 'MD5-SESS':
104 | def md5_utf8(x):
105 | if isinstance(x, str):
106 | x = x.encode('utf-8')
107 | return hashlib.md5(x).hexdigest()
108 | hash_utf8 = md5_utf8
109 | elif _algorithm == 'SHA':
110 | def sha_utf8(x):
111 | if isinstance(x, str):
112 | x = x.encode('utf-8')
113 | return hashlib.sha1(x).hexdigest()
114 | hash_utf8 = sha_utf8
115 |
116 | KD = lambda s, d: hash_utf8("%s:%s" % (s, d))
117 |
118 | if hash_utf8 is None:
119 | return None
120 |
121 | # XXX not implemented yet
122 | entdig = None
123 | p_parsed = urlparse(url)
124 | #: path is request-uri defined in RFC 2616 which should not be empty
125 | path = p_parsed.path or "/"
126 | if p_parsed.query:
127 | path += '?' + p_parsed.query
128 |
129 | A1 = '%s:%s:%s' % (self.username, realm, self.password)
130 | A2 = '%s:%s' % (method, path)
131 |
132 | HA1 = hash_utf8(A1)
133 | HA2 = hash_utf8(A2)
134 |
135 | if nonce == self._thread_local.last_nonce:
136 | self._thread_local.nonce_count += 1
137 | else:
138 | self._thread_local.nonce_count = 1
139 | ncvalue = '%08x' % self._thread_local.nonce_count
140 | s = str(self._thread_local.nonce_count).encode('utf-8')
141 | s += nonce.encode('utf-8')
142 | s += time.ctime().encode('utf-8')
143 | s += os.urandom(8)
144 |
145 | cnonce = (hashlib.sha1(s).hexdigest()[:16])
146 | if _algorithm == 'MD5-SESS':
147 | HA1 = hash_utf8('%s:%s:%s' % (HA1, nonce, cnonce))
148 |
149 | if not qop:
150 | respdig = KD(HA1, "%s:%s" % (nonce, HA2))
151 | elif qop == 'auth' or 'auth' in qop.split(','):
152 | noncebit = "%s:%s:%s:%s:%s" % (
153 | nonce, ncvalue, cnonce, 'auth', HA2
154 | )
155 | respdig = KD(HA1, noncebit)
156 | else:
157 | # XXX handle auth-int.
158 | return None
159 |
160 | self._thread_local.last_nonce = nonce
161 |
162 | # XXX should the partial digests be encoded too?
163 | base = 'username="%s", realm="%s", nonce="%s", uri="%s", ' \
164 | 'response="%s"' % (self.username, realm, nonce, path, respdig)
165 | if opaque:
166 | base += ', opaque="%s"' % opaque
167 | if algorithm:
168 | base += ', algorithm="%s"' % algorithm
169 | if entdig:
170 | base += ', digest="%s"' % entdig
171 | if qop:
172 | base += ', qop="auth", nc=%s, cnonce="%s"' % (ncvalue, cnonce)
173 |
174 | return 'Digest %s' % (base)
175 |
176 | def handle_redirect(self, r, **kwargs):
177 | """Reset num_401_calls counter on redirects."""
178 | if r.is_redirect:
179 | self._thread_local.num_401_calls = 1
180 |
181 | def handle_401(self, r, **kwargs):
182 | """Takes the given response and tries digest-auth, if needed."""
183 |
184 | if self._thread_local.pos is not None:
185 | # Rewind the file position indicator of the body to where
186 | # it was to resend the request.
187 | r.request.body.seek(self._thread_local.pos)
188 | s_auth = r.headers.get('www-authenticate', '')
189 |
190 | if 'digest' in s_auth.lower() and self._thread_local.num_401_calls < 2:
191 |
192 | self._thread_local.num_401_calls += 1
193 | pat = re.compile(r'digest ', flags=re.IGNORECASE)
194 | self._thread_local.chal = parse_dict_header(pat.sub('', s_auth, count=1))
195 |
196 | # Consume content and release the original connection
197 | # to allow our new request to reuse the same one.
198 | r.content
199 | r.close()
200 | prep = r.request.copy()
201 | extract_cookies_to_jar(prep._cookies, r.request, r.raw)
202 | prep.prepare_cookies(prep._cookies)
203 |
204 | prep.headers['Authorization'] = self.build_digest_header(
205 | prep.method, prep.url)
206 | _r = r.connection.send(prep, **kwargs)
207 | _r.history.append(r)
208 | _r.request = prep
209 |
210 | return _r
211 |
212 | self._thread_local.num_401_calls = 1
213 | return r
214 |
215 | def __call__(self, r):
216 | # Initialize per-thread state, if needed
217 | self.init_per_thread_state()
218 | # If we have a saved nonce, skip the 401
219 | if self._thread_local.last_nonce:
220 | r.headers['Authorization'] = self.build_digest_header(r.method, r.url)
221 | try:
222 | self._thread_local.pos = r.body.tell()
223 | except AttributeError:
224 | # In the case of HTTPDigestAuth being reused and the body of
225 | # the previous request was a file-like object, pos has the
226 | # file position of the previous body. Ensure it's set to
227 | # None.
228 | self._thread_local.pos = None
229 | r.register_hook('response', self.handle_401)
230 | r.register_hook('response', self.handle_redirect)
231 | self._thread_local.num_401_calls = 1
232 |
233 | return r
234 |
235 | def __eq__(self, other):
236 | return all([
237 | self.username == getattr(other, 'username', None),
238 | self.password == getattr(other, 'password', None)
239 | ])
240 |
241 | def __ne__(self, other):
242 | return not self == other
243 |
--------------------------------------------------------------------------------
/vendor/requests/auth.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/loveQt/wxpytest/c8923b2298a5f71aca4bcee656125dc219d45592/vendor/requests/auth.pyc
--------------------------------------------------------------------------------
/vendor/requests/certs.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # -*- coding: utf-8 -*-
3 |
4 | """
5 | certs.py
6 | ~~~~~~~~
7 |
8 | This module returns the preferred default CA certificate bundle.
9 |
10 | If you are packaging Requests, e.g., for a Linux distribution or a managed
11 | environment, you can change the definition of where() to return a separately
12 | packaged CA bundle.
13 | """
14 | import os.path
15 |
16 | try:
17 | from certifi import where
18 | except ImportError:
19 | def where():
20 | """Return the preferred certificate bundle."""
21 | # vendored bundle inside Requests
22 | return os.path.join(os.path.dirname(__file__), 'cacert.pem')
23 |
24 | if __name__ == '__main__':
25 | print(where())
26 |
--------------------------------------------------------------------------------
/vendor/requests/certs.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/loveQt/wxpytest/c8923b2298a5f71aca4bcee656125dc219d45592/vendor/requests/certs.pyc
--------------------------------------------------------------------------------
/vendor/requests/compat.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
3 | """
4 | pythoncompat
5 | """
6 |
7 | from .packages import chardet
8 |
9 | import sys
10 |
11 | # -------
12 | # Pythons
13 | # -------
14 |
15 | # Syntax sugar.
16 | _ver = sys.version_info
17 |
18 | #: Python 2.x?
19 | is_py2 = (_ver[0] == 2)
20 |
21 | #: Python 3.x?
22 | is_py3 = (_ver[0] == 3)
23 |
24 | try:
25 | import simplejson as json
26 | except (ImportError, SyntaxError):
27 | # simplejson does not support Python 3.2, it throws a SyntaxError
28 | # because of u'...' Unicode literals.
29 | import json
30 |
31 | # ---------
32 | # Specifics
33 | # ---------
34 |
35 | if is_py2:
36 | from urllib import quote, unquote, quote_plus, unquote_plus, urlencode, getproxies, proxy_bypass
37 | from urlparse import urlparse, urlunparse, urljoin, urlsplit, urldefrag
38 | from urllib2 import parse_http_list
39 | import cookielib
40 | from Cookie import Morsel
41 | from StringIO import StringIO
42 | from .packages.urllib3.packages.ordered_dict import OrderedDict
43 |
44 | builtin_str = str
45 | bytes = str
46 | str = unicode
47 | basestring = basestring
48 | numeric_types = (int, long, float)
49 |
50 | elif is_py3:
51 | from urllib.parse import urlparse, urlunparse, urljoin, urlsplit, urlencode, quote, unquote, quote_plus, unquote_plus, urldefrag
52 | from urllib.request import parse_http_list, getproxies, proxy_bypass
53 | from http import cookiejar as cookielib
54 | from http.cookies import Morsel
55 | from io import StringIO
56 | from collections import OrderedDict
57 |
58 | builtin_str = str
59 | str = str
60 | bytes = bytes
61 | basestring = (str, bytes)
62 | numeric_types = (int, float)
63 |
--------------------------------------------------------------------------------
/vendor/requests/compat.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/loveQt/wxpytest/c8923b2298a5f71aca4bcee656125dc219d45592/vendor/requests/compat.pyc
--------------------------------------------------------------------------------
/vendor/requests/cookies.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/loveQt/wxpytest/c8923b2298a5f71aca4bcee656125dc219d45592/vendor/requests/cookies.pyc
--------------------------------------------------------------------------------
/vendor/requests/exceptions.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
3 | """
4 | requests.exceptions
5 | ~~~~~~~~~~~~~~~~~~~
6 |
7 | This module contains the set of Requests' exceptions.
8 |
9 | """
10 | from .packages.urllib3.exceptions import HTTPError as BaseHTTPError
11 |
12 |
13 | class RequestException(IOError):
14 | """There was an ambiguous exception that occurred while handling your
15 | request."""
16 |
17 | def __init__(self, *args, **kwargs):
18 | """
19 | Initialize RequestException with `request` and `response` objects.
20 | """
21 | response = kwargs.pop('response', None)
22 | self.response = response
23 | self.request = kwargs.pop('request', None)
24 | if (response is not None and not self.request and
25 | hasattr(response, 'request')):
26 | self.request = self.response.request
27 | super(RequestException, self).__init__(*args, **kwargs)
28 |
29 |
30 | class HTTPError(RequestException):
31 | """An HTTP error occurred."""
32 |
33 |
34 | class ConnectionError(RequestException):
35 | """A Connection error occurred."""
36 |
37 |
38 | class ProxyError(ConnectionError):
39 | """A proxy error occurred."""
40 |
41 |
42 | class SSLError(ConnectionError):
43 | """An SSL error occurred."""
44 |
45 |
46 | class Timeout(RequestException):
47 | """The request timed out.
48 |
49 | Catching this error will catch both
50 | :exc:`~requests.exceptions.ConnectTimeout` and
51 | :exc:`~requests.exceptions.ReadTimeout` errors.
52 | """
53 |
54 |
55 | class ConnectTimeout(ConnectionError, Timeout):
56 | """The request timed out while trying to connect to the remote server.
57 |
58 | Requests that produced this error are safe to retry.
59 | """
60 |
61 |
62 | class ReadTimeout(Timeout):
63 | """The server did not send any data in the allotted amount of time."""
64 |
65 |
66 | class URLRequired(RequestException):
67 | """A valid URL is required to make a request."""
68 |
69 |
70 | class TooManyRedirects(RequestException):
71 | """Too many redirects."""
72 |
73 |
74 | class MissingSchema(RequestException, ValueError):
75 | """The URL schema (e.g. http or https) is missing."""
76 |
77 |
78 | class InvalidSchema(RequestException, ValueError):
79 | """See defaults.py for valid schemas."""
80 |
81 |
82 | class InvalidURL(RequestException, ValueError):
83 | """ The URL provided was somehow invalid. """
84 |
85 |
86 | class ChunkedEncodingError(RequestException):
87 | """The server declared chunked encoding but sent an invalid chunk."""
88 |
89 |
90 | class ContentDecodingError(RequestException, BaseHTTPError):
91 | """Failed to decode response content"""
92 |
93 |
94 | class StreamConsumedError(RequestException, TypeError):
95 | """The content for this response was already consumed"""
96 |
97 |
98 | class RetryError(RequestException):
99 | """Custom retries logic failed"""
100 |
101 |
102 | # Warnings
103 |
104 |
105 | class RequestsWarning(Warning):
106 | """Base warning for Requests."""
107 | pass
108 |
109 |
110 | class FileModeWarning(RequestsWarning, DeprecationWarning):
111 | """
112 | A file was opened in text mode, but Requests determined its binary length.
113 | """
114 | pass
115 |
--------------------------------------------------------------------------------
/vendor/requests/exceptions.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/loveQt/wxpytest/c8923b2298a5f71aca4bcee656125dc219d45592/vendor/requests/exceptions.pyc
--------------------------------------------------------------------------------
/vendor/requests/hooks.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
3 | """
4 | requests.hooks
5 | ~~~~~~~~~~~~~~
6 |
7 | This module provides the capabilities for the Requests hooks system.
8 |
9 | Available hooks:
10 |
11 | ``response``:
12 | The response generated from a Request.
13 |
14 | """
15 | HOOKS = ['response']
16 |
17 | def default_hooks():
18 | return dict((event, []) for event in HOOKS)
19 |
20 | # TODO: response is the only one
21 |
22 |
23 | def dispatch_hook(key, hooks, hook_data, **kwargs):
24 | """Dispatches a hook dictionary on a given piece of data."""
25 | hooks = hooks or dict()
26 | hooks = hooks.get(key)
27 | if hooks:
28 | if hasattr(hooks, '__call__'):
29 | hooks = [hooks]
30 | for hook in hooks:
31 | _hook_data = hook(hook_data, **kwargs)
32 | if _hook_data is not None:
33 | hook_data = _hook_data
34 | return hook_data
35 |
--------------------------------------------------------------------------------
/vendor/requests/hooks.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/loveQt/wxpytest/c8923b2298a5f71aca4bcee656125dc219d45592/vendor/requests/hooks.pyc
--------------------------------------------------------------------------------
/vendor/requests/models.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/loveQt/wxpytest/c8923b2298a5f71aca4bcee656125dc219d45592/vendor/requests/models.pyc
--------------------------------------------------------------------------------
/vendor/requests/packages/__init__.py:
--------------------------------------------------------------------------------
1 | '''
2 | Debian and other distributions "unbundle" requests' vendored dependencies, and
3 | rewrite all imports to use the global versions of ``urllib3`` and ``chardet``.
4 | The problem with this is that not only requests itself imports those
5 | dependencies, but third-party code outside of the distros' control too.
6 |
7 | In reaction to these problems, the distro maintainers replaced
8 | ``requests.packages`` with a magical "stub module" that imports the correct
9 | modules. The implementations were varying in quality and all had severe
10 | problems. For example, a symlink (or hardlink) that links the correct modules
11 | into place introduces problems regarding object identity, since you now have
12 | two modules in `sys.modules` with the same API, but different identities::
13 |
14 | requests.packages.urllib3 is not urllib3
15 |
16 | With version ``2.5.2``, requests started to maintain its own stub, so that
17 | distro-specific breakage would be reduced to a minimum, even though the whole
18 | issue is not requests' fault in the first place. See
19 | https://github.com/kennethreitz/requests/pull/2375 for the corresponding pull
20 | request.
21 | '''
22 |
23 | from __future__ import absolute_import
24 | import sys
25 |
26 | try:
27 | from . import urllib3
28 | except ImportError:
29 | import urllib3
30 | sys.modules['%s.urllib3' % __name__] = urllib3
31 |
32 | try:
33 | from . import chardet
34 | except ImportError:
35 | import chardet
36 | sys.modules['%s.chardet' % __name__] = chardet
37 |
--------------------------------------------------------------------------------
/vendor/requests/packages/__init__.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/loveQt/wxpytest/c8923b2298a5f71aca4bcee656125dc219d45592/vendor/requests/packages/__init__.pyc
--------------------------------------------------------------------------------
/vendor/requests/packages/chardet/__init__.py:
--------------------------------------------------------------------------------
1 | ######################## BEGIN LICENSE BLOCK ########################
2 | # This library is free software; you can redistribute it and/or
3 | # modify it under the terms of the GNU Lesser General Public
4 | # License as published by the Free Software Foundation; either
5 | # version 2.1 of the License, or (at your option) any later version.
6 | #
7 | # This library is distributed in the hope that it will be useful,
8 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
9 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
10 | # Lesser General Public License for more details.
11 | #
12 | # You should have received a copy of the GNU Lesser General Public
13 | # License along with this library; if not, write to the Free Software
14 | # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
15 | # 02110-1301 USA
16 | ######################### END LICENSE BLOCK #########################
17 |
18 | __version__ = "2.3.0"
19 | from sys import version_info
20 |
21 |
22 | def detect(aBuf):
23 | if ((version_info < (3, 0) and isinstance(aBuf, unicode)) or
24 | (version_info >= (3, 0) and not isinstance(aBuf, bytes))):
25 | raise ValueError('Expected a bytes object, not a unicode object')
26 |
27 | from . import universaldetector
28 | u = universaldetector.UniversalDetector()
29 | u.reset()
30 | u.feed(aBuf)
31 | u.close()
32 | return u.result
33 |
--------------------------------------------------------------------------------
/vendor/requests/packages/chardet/__init__.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/loveQt/wxpytest/c8923b2298a5f71aca4bcee656125dc219d45592/vendor/requests/packages/chardet/__init__.pyc
--------------------------------------------------------------------------------
/vendor/requests/packages/chardet/big5freq.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/loveQt/wxpytest/c8923b2298a5f71aca4bcee656125dc219d45592/vendor/requests/packages/chardet/big5freq.pyc
--------------------------------------------------------------------------------
/vendor/requests/packages/chardet/big5prober.py:
--------------------------------------------------------------------------------
1 | ######################## BEGIN LICENSE BLOCK ########################
2 | # The Original Code is Mozilla Communicator client code.
3 | #
4 | # The Initial Developer of the Original Code is
5 | # Netscape Communications Corporation.
6 | # Portions created by the Initial Developer are Copyright (C) 1998
7 | # the Initial Developer. All Rights Reserved.
8 | #
9 | # Contributor(s):
10 | # Mark Pilgrim - port to Python
11 | #
12 | # This library is free software; you can redistribute it and/or
13 | # modify it under the terms of the GNU Lesser General Public
14 | # License as published by the Free Software Foundation; either
15 | # version 2.1 of the License, or (at your option) any later version.
16 | #
17 | # This library is distributed in the hope that it will be useful,
18 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
19 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20 | # Lesser General Public License for more details.
21 | #
22 | # You should have received a copy of the GNU Lesser General Public
23 | # License along with this library; if not, write to the Free Software
24 | # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
25 | # 02110-1301 USA
26 | ######################### END LICENSE BLOCK #########################
27 |
28 | from .mbcharsetprober import MultiByteCharSetProber
29 | from .codingstatemachine import CodingStateMachine
30 | from .chardistribution import Big5DistributionAnalysis
31 | from .mbcssm import Big5SMModel
32 |
33 |
34 | class Big5Prober(MultiByteCharSetProber):
35 | def __init__(self):
36 | MultiByteCharSetProber.__init__(self)
37 | self._mCodingSM = CodingStateMachine(Big5SMModel)
38 | self._mDistributionAnalyzer = Big5DistributionAnalysis()
39 | self.reset()
40 |
41 | def get_charset_name(self):
42 | return "Big5"
43 |
--------------------------------------------------------------------------------
/vendor/requests/packages/chardet/big5prober.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/loveQt/wxpytest/c8923b2298a5f71aca4bcee656125dc219d45592/vendor/requests/packages/chardet/big5prober.pyc
--------------------------------------------------------------------------------
/vendor/requests/packages/chardet/chardetect.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | """
3 | Script which takes one or more file paths and reports on their detected
4 | encodings
5 |
6 | Example::
7 |
8 | % chardetect somefile someotherfile
9 | somefile: windows-1252 with confidence 0.5
10 | someotherfile: ascii with confidence 1.0
11 |
12 | If no paths are provided, it takes its input from stdin.
13 |
14 | """
15 |
16 | from __future__ import absolute_import, print_function, unicode_literals
17 |
18 | import argparse
19 | import sys
20 | from io import open
21 |
22 | from chardet import __version__
23 | from chardet.universaldetector import UniversalDetector
24 |
25 |
26 | def description_of(lines, name='stdin'):
27 | """
28 | Return a string describing the probable encoding of a file or
29 | list of strings.
30 |
31 | :param lines: The lines to get the encoding of.
32 | :type lines: Iterable of bytes
33 | :param name: Name of file or collection of lines
34 | :type name: str
35 | """
36 | u = UniversalDetector()
37 | for line in lines:
38 | u.feed(line)
39 | u.close()
40 | result = u.result
41 | if result['encoding']:
42 | return '{0}: {1} with confidence {2}'.format(name, result['encoding'],
43 | result['confidence'])
44 | else:
45 | return '{0}: no result'.format(name)
46 |
47 |
48 | def main(argv=None):
49 | '''
50 | Handles command line arguments and gets things started.
51 |
52 | :param argv: List of arguments, as if specified on the command-line.
53 | If None, ``sys.argv[1:]`` is used instead.
54 | :type argv: list of str
55 | '''
56 | # Get command line arguments
57 | parser = argparse.ArgumentParser(
58 | description="Takes one or more file paths and reports their detected \
59 | encodings",
60 | formatter_class=argparse.ArgumentDefaultsHelpFormatter,
61 | conflict_handler='resolve')
62 | parser.add_argument('input',
63 | help='File whose encoding we would like to determine.',
64 | type=argparse.FileType('rb'), nargs='*',
65 | default=[sys.stdin])
66 | parser.add_argument('--version', action='version',
67 | version='%(prog)s {0}'.format(__version__))
68 | args = parser.parse_args(argv)
69 |
70 | for f in args.input:
71 | if f.isatty():
72 | print("You are running chardetect interactively. Press " +
73 | "CTRL-D twice at the start of a blank line to signal the " +
74 | "end of your input. If you want help, run chardetect " +
75 | "--help\n", file=sys.stderr)
76 | print(description_of(f, f.name))
77 |
78 |
79 | if __name__ == '__main__':
80 | main()
81 |
--------------------------------------------------------------------------------
/vendor/requests/packages/chardet/chardetect.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/loveQt/wxpytest/c8923b2298a5f71aca4bcee656125dc219d45592/vendor/requests/packages/chardet/chardetect.pyc
--------------------------------------------------------------------------------
/vendor/requests/packages/chardet/chardistribution.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/loveQt/wxpytest/c8923b2298a5f71aca4bcee656125dc219d45592/vendor/requests/packages/chardet/chardistribution.pyc
--------------------------------------------------------------------------------
/vendor/requests/packages/chardet/charsetgroupprober.py:
--------------------------------------------------------------------------------
1 | ######################## BEGIN LICENSE BLOCK ########################
2 | # The Original Code is Mozilla Communicator client code.
3 | #
4 | # The Initial Developer of the Original Code is
5 | # Netscape Communications Corporation.
6 | # Portions created by the Initial Developer are Copyright (C) 1998
7 | # the Initial Developer. All Rights Reserved.
8 | #
9 | # Contributor(s):
10 | # Mark Pilgrim - port to Python
11 | #
12 | # This library is free software; you can redistribute it and/or
13 | # modify it under the terms of the GNU Lesser General Public
14 | # License as published by the Free Software Foundation; either
15 | # version 2.1 of the License, or (at your option) any later version.
16 | #
17 | # This library is distributed in the hope that it will be useful,
18 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
19 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20 | # Lesser General Public License for more details.
21 | #
22 | # You should have received a copy of the GNU Lesser General Public
23 | # License along with this library; if not, write to the Free Software
24 | # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
25 | # 02110-1301 USA
26 | ######################### END LICENSE BLOCK #########################
27 |
28 | from . import constants
29 | import sys
30 | from .charsetprober import CharSetProber
31 |
32 |
33 | class CharSetGroupProber(CharSetProber):
34 | def __init__(self):
35 | CharSetProber.__init__(self)
36 | self._mActiveNum = 0
37 | self._mProbers = []
38 | self._mBestGuessProber = None
39 |
40 | def reset(self):
41 | CharSetProber.reset(self)
42 | self._mActiveNum = 0
43 | for prober in self._mProbers:
44 | if prober:
45 | prober.reset()
46 | prober.active = True
47 | self._mActiveNum += 1
48 | self._mBestGuessProber = None
49 |
50 | def get_charset_name(self):
51 | if not self._mBestGuessProber:
52 | self.get_confidence()
53 | if not self._mBestGuessProber:
54 | return None
55 | # self._mBestGuessProber = self._mProbers[0]
56 | return self._mBestGuessProber.get_charset_name()
57 |
58 | def feed(self, aBuf):
59 | for prober in self._mProbers:
60 | if not prober:
61 | continue
62 | if not prober.active:
63 | continue
64 | st = prober.feed(aBuf)
65 | if not st:
66 | continue
67 | if st == constants.eFoundIt:
68 | self._mBestGuessProber = prober
69 | return self.get_state()
70 | elif st == constants.eNotMe:
71 | prober.active = False
72 | self._mActiveNum -= 1
73 | if self._mActiveNum <= 0:
74 | self._mState = constants.eNotMe
75 | return self.get_state()
76 | return self.get_state()
77 |
78 | def get_confidence(self):
79 | st = self.get_state()
80 | if st == constants.eFoundIt:
81 | return 0.99
82 | elif st == constants.eNotMe:
83 | return 0.01
84 | bestConf = 0.0
85 | self._mBestGuessProber = None
86 | for prober in self._mProbers:
87 | if not prober:
88 | continue
89 | if not prober.active:
90 | if constants._debug:
91 | sys.stderr.write(prober.get_charset_name()
92 | + ' not active\n')
93 | continue
94 | cf = prober.get_confidence()
95 | if constants._debug:
96 | sys.stderr.write('%s confidence = %s\n' %
97 | (prober.get_charset_name(), cf))
98 | if bestConf < cf:
99 | bestConf = cf
100 | self._mBestGuessProber = prober
101 | if not self._mBestGuessProber:
102 | return 0.0
103 | return bestConf
104 | # else:
105 | # self._mBestGuessProber = self._mProbers[0]
106 | # return self._mBestGuessProber.get_confidence()
107 |
--------------------------------------------------------------------------------
/vendor/requests/packages/chardet/charsetgroupprober.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/loveQt/wxpytest/c8923b2298a5f71aca4bcee656125dc219d45592/vendor/requests/packages/chardet/charsetgroupprober.pyc
--------------------------------------------------------------------------------
/vendor/requests/packages/chardet/charsetprober.py:
--------------------------------------------------------------------------------
1 | ######################## BEGIN LICENSE BLOCK ########################
2 | # The Original Code is Mozilla Universal charset detector code.
3 | #
4 | # The Initial Developer of the Original Code is
5 | # Netscape Communications Corporation.
6 | # Portions created by the Initial Developer are Copyright (C) 2001
7 | # the Initial Developer. All Rights Reserved.
8 | #
9 | # Contributor(s):
10 | # Mark Pilgrim - port to Python
11 | # Shy Shalom - original C code
12 | #
13 | # This library is free software; you can redistribute it and/or
14 | # modify it under the terms of the GNU Lesser General Public
15 | # License as published by the Free Software Foundation; either
16 | # version 2.1 of the License, or (at your option) any later version.
17 | #
18 | # This library is distributed in the hope that it will be useful,
19 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
20 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
21 | # Lesser General Public License for more details.
22 | #
23 | # You should have received a copy of the GNU Lesser General Public
24 | # License along with this library; if not, write to the Free Software
25 | # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
26 | # 02110-1301 USA
27 | ######################### END LICENSE BLOCK #########################
28 |
29 | from . import constants
30 | import re
31 |
32 |
33 | class CharSetProber:
34 | def __init__(self):
35 | pass
36 |
37 | def reset(self):
38 | self._mState = constants.eDetecting
39 |
40 | def get_charset_name(self):
41 | return None
42 |
43 | def feed(self, aBuf):
44 | pass
45 |
46 | def get_state(self):
47 | return self._mState
48 |
49 | def get_confidence(self):
50 | return 0.0
51 |
52 | def filter_high_bit_only(self, aBuf):
53 | aBuf = re.sub(b'([\x00-\x7F])+', b' ', aBuf)
54 | return aBuf
55 |
56 | def filter_without_english_letters(self, aBuf):
57 | aBuf = re.sub(b'([A-Za-z])+', b' ', aBuf)
58 | return aBuf
59 |
60 | def filter_with_english_letters(self, aBuf):
61 | # TODO
62 | return aBuf
63 |
--------------------------------------------------------------------------------
/vendor/requests/packages/chardet/charsetprober.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/loveQt/wxpytest/c8923b2298a5f71aca4bcee656125dc219d45592/vendor/requests/packages/chardet/charsetprober.pyc
--------------------------------------------------------------------------------
/vendor/requests/packages/chardet/codingstatemachine.py:
--------------------------------------------------------------------------------
1 | ######################## BEGIN LICENSE BLOCK ########################
2 | # The Original Code is mozilla.org code.
3 | #
4 | # The Initial Developer of the Original Code is
5 | # Netscape Communications Corporation.
6 | # Portions created by the Initial Developer are Copyright (C) 1998
7 | # the Initial Developer. All Rights Reserved.
8 | #
9 | # Contributor(s):
10 | # Mark Pilgrim - port to Python
11 | #
12 | # This library is free software; you can redistribute it and/or
13 | # modify it under the terms of the GNU Lesser General Public
14 | # License as published by the Free Software Foundation; either
15 | # version 2.1 of the License, or (at your option) any later version.
16 | #
17 | # This library is distributed in the hope that it will be useful,
18 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
19 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20 | # Lesser General Public License for more details.
21 | #
22 | # You should have received a copy of the GNU Lesser General Public
23 | # License along with this library; if not, write to the Free Software
24 | # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
25 | # 02110-1301 USA
26 | ######################### END LICENSE BLOCK #########################
27 |
28 | from .constants import eStart
29 | from .compat import wrap_ord
30 |
31 |
32 | class CodingStateMachine:
33 | def __init__(self, sm):
34 | self._mModel = sm
35 | self._mCurrentBytePos = 0
36 | self._mCurrentCharLen = 0
37 | self.reset()
38 |
39 | def reset(self):
40 | self._mCurrentState = eStart
41 |
42 | def next_state(self, c):
43 | # for each byte we get its class
44 | # if it is first byte, we also get byte length
45 | # PY3K: aBuf is a byte stream, so c is an int, not a byte
46 | byteCls = self._mModel['classTable'][wrap_ord(c)]
47 | if self._mCurrentState == eStart:
48 | self._mCurrentBytePos = 0
49 | self._mCurrentCharLen = self._mModel['charLenTable'][byteCls]
50 | # from byte's class and stateTable, we get its next state
51 | curr_state = (self._mCurrentState * self._mModel['classFactor']
52 | + byteCls)
53 | self._mCurrentState = self._mModel['stateTable'][curr_state]
54 | self._mCurrentBytePos += 1
55 | return self._mCurrentState
56 |
57 | def get_current_charlen(self):
58 | return self._mCurrentCharLen
59 |
60 | def get_coding_state_machine(self):
61 | return self._mModel['name']
62 |
--------------------------------------------------------------------------------
/vendor/requests/packages/chardet/codingstatemachine.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/loveQt/wxpytest/c8923b2298a5f71aca4bcee656125dc219d45592/vendor/requests/packages/chardet/codingstatemachine.pyc
--------------------------------------------------------------------------------
/vendor/requests/packages/chardet/compat.py:
--------------------------------------------------------------------------------
1 | ######################## BEGIN LICENSE BLOCK ########################
2 | # Contributor(s):
3 | # Ian Cordasco - port to Python
4 | #
5 | # This library is free software; you can redistribute it and/or
6 | # modify it under the terms of the GNU Lesser General Public
7 | # License as published by the Free Software Foundation; either
8 | # version 2.1 of the License, or (at your option) any later version.
9 | #
10 | # This library is distributed in the hope that it will be useful,
11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 | # Lesser General Public License for more details.
14 | #
15 | # You should have received a copy of the GNU Lesser General Public
16 | # License along with this library; if not, write to the Free Software
17 | # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
18 | # 02110-1301 USA
19 | ######################### END LICENSE BLOCK #########################
20 |
21 | import sys
22 |
23 |
24 | if sys.version_info < (3, 0):
25 | base_str = (str, unicode)
26 | else:
27 | base_str = (bytes, str)
28 |
29 |
30 | def wrap_ord(a):
31 | if sys.version_info < (3, 0) and isinstance(a, base_str):
32 | return ord(a)
33 | else:
34 | return a
35 |
--------------------------------------------------------------------------------
/vendor/requests/packages/chardet/compat.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/loveQt/wxpytest/c8923b2298a5f71aca4bcee656125dc219d45592/vendor/requests/packages/chardet/compat.pyc
--------------------------------------------------------------------------------
/vendor/requests/packages/chardet/constants.py:
--------------------------------------------------------------------------------
1 | ######################## BEGIN LICENSE BLOCK ########################
2 | # The Original Code is Mozilla Universal charset detector code.
3 | #
4 | # The Initial Developer of the Original Code is
5 | # Netscape Communications Corporation.
6 | # Portions created by the Initial Developer are Copyright (C) 2001
7 | # the Initial Developer. All Rights Reserved.
8 | #
9 | # Contributor(s):
10 | # Mark Pilgrim - port to Python
11 | # Shy Shalom - original C code
12 | #
13 | # This library is free software; you can redistribute it and/or
14 | # modify it under the terms of the GNU Lesser General Public
15 | # License as published by the Free Software Foundation; either
16 | # version 2.1 of the License, or (at your option) any later version.
17 | #
18 | # This library is distributed in the hope that it will be useful,
19 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
20 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
21 | # Lesser General Public License for more details.
22 | #
23 | # You should have received a copy of the GNU Lesser General Public
24 | # License along with this library; if not, write to the Free Software
25 | # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
26 | # 02110-1301 USA
27 | ######################### END LICENSE BLOCK #########################
28 |
29 | _debug = 0
30 |
31 | eDetecting = 0
32 | eFoundIt = 1
33 | eNotMe = 2
34 |
35 | eStart = 0
36 | eError = 1
37 | eItsMe = 2
38 |
39 | SHORTCUT_THRESHOLD = 0.95
40 |
--------------------------------------------------------------------------------
/vendor/requests/packages/chardet/constants.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/loveQt/wxpytest/c8923b2298a5f71aca4bcee656125dc219d45592/vendor/requests/packages/chardet/constants.pyc
--------------------------------------------------------------------------------
/vendor/requests/packages/chardet/cp949prober.py:
--------------------------------------------------------------------------------
1 | ######################## BEGIN LICENSE BLOCK ########################
2 | # The Original Code is mozilla.org code.
3 | #
4 | # The Initial Developer of the Original Code is
5 | # Netscape Communications Corporation.
6 | # Portions created by the Initial Developer are Copyright (C) 1998
7 | # the Initial Developer. All Rights Reserved.
8 | #
9 | # Contributor(s):
10 | # Mark Pilgrim - port to Python
11 | #
12 | # This library is free software; you can redistribute it and/or
13 | # modify it under the terms of the GNU Lesser General Public
14 | # License as published by the Free Software Foundation; either
15 | # version 2.1 of the License, or (at your option) any later version.
16 | #
17 | # This library is distributed in the hope that it will be useful,
18 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
19 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20 | # Lesser General Public License for more details.
21 | #
22 | # You should have received a copy of the GNU Lesser General Public
23 | # License along with this library; if not, write to the Free Software
24 | # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
25 | # 02110-1301 USA
26 | ######################### END LICENSE BLOCK #########################
27 |
28 | from .mbcharsetprober import MultiByteCharSetProber
29 | from .codingstatemachine import CodingStateMachine
30 | from .chardistribution import EUCKRDistributionAnalysis
31 | from .mbcssm import CP949SMModel
32 |
33 |
34 | class CP949Prober(MultiByteCharSetProber):
35 | def __init__(self):
36 | MultiByteCharSetProber.__init__(self)
37 | self._mCodingSM = CodingStateMachine(CP949SMModel)
38 | # NOTE: CP949 is a superset of EUC-KR, so the distribution should be
39 | # not different.
40 | self._mDistributionAnalyzer = EUCKRDistributionAnalysis()
41 | self.reset()
42 |
43 | def get_charset_name(self):
44 | return "CP949"
45 |
--------------------------------------------------------------------------------
/vendor/requests/packages/chardet/cp949prober.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/loveQt/wxpytest/c8923b2298a5f71aca4bcee656125dc219d45592/vendor/requests/packages/chardet/cp949prober.pyc
--------------------------------------------------------------------------------
/vendor/requests/packages/chardet/escprober.py:
--------------------------------------------------------------------------------
1 | ######################## BEGIN LICENSE BLOCK ########################
2 | # The Original Code is mozilla.org code.
3 | #
4 | # The Initial Developer of the Original Code is
5 | # Netscape Communications Corporation.
6 | # Portions created by the Initial Developer are Copyright (C) 1998
7 | # the Initial Developer. All Rights Reserved.
8 | #
9 | # Contributor(s):
10 | # Mark Pilgrim - port to Python
11 | #
12 | # This library is free software; you can redistribute it and/or
13 | # modify it under the terms of the GNU Lesser General Public
14 | # License as published by the Free Software Foundation; either
15 | # version 2.1 of the License, or (at your option) any later version.
16 | #
17 | # This library is distributed in the hope that it will be useful,
18 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
19 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20 | # Lesser General Public License for more details.
21 | #
22 | # You should have received a copy of the GNU Lesser General Public
23 | # License along with this library; if not, write to the Free Software
24 | # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
25 | # 02110-1301 USA
26 | ######################### END LICENSE BLOCK #########################
27 |
28 | from . import constants
29 | from .escsm import (HZSMModel, ISO2022CNSMModel, ISO2022JPSMModel,
30 | ISO2022KRSMModel)
31 | from .charsetprober import CharSetProber
32 | from .codingstatemachine import CodingStateMachine
33 | from .compat import wrap_ord
34 |
35 |
36 | class EscCharSetProber(CharSetProber):
37 | def __init__(self):
38 | CharSetProber.__init__(self)
39 | self._mCodingSM = [
40 | CodingStateMachine(HZSMModel),
41 | CodingStateMachine(ISO2022CNSMModel),
42 | CodingStateMachine(ISO2022JPSMModel),
43 | CodingStateMachine(ISO2022KRSMModel)
44 | ]
45 | self.reset()
46 |
47 | def reset(self):
48 | CharSetProber.reset(self)
49 | for codingSM in self._mCodingSM:
50 | if not codingSM:
51 | continue
52 | codingSM.active = True
53 | codingSM.reset()
54 | self._mActiveSM = len(self._mCodingSM)
55 | self._mDetectedCharset = None
56 |
57 | def get_charset_name(self):
58 | return self._mDetectedCharset
59 |
60 | def get_confidence(self):
61 | if self._mDetectedCharset:
62 | return 0.99
63 | else:
64 | return 0.00
65 |
66 | def feed(self, aBuf):
67 | for c in aBuf:
68 | # PY3K: aBuf is a byte array, so c is an int, not a byte
69 | for codingSM in self._mCodingSM:
70 | if not codingSM:
71 | continue
72 | if not codingSM.active:
73 | continue
74 | codingState = codingSM.next_state(wrap_ord(c))
75 | if codingState == constants.eError:
76 | codingSM.active = False
77 | self._mActiveSM -= 1
78 | if self._mActiveSM <= 0:
79 | self._mState = constants.eNotMe
80 | return self.get_state()
81 | elif codingState == constants.eItsMe:
82 | self._mState = constants.eFoundIt
83 | self._mDetectedCharset = codingSM.get_coding_state_machine() # nopep8
84 | return self.get_state()
85 |
86 | return self.get_state()
87 |
--------------------------------------------------------------------------------
/vendor/requests/packages/chardet/escprober.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/loveQt/wxpytest/c8923b2298a5f71aca4bcee656125dc219d45592/vendor/requests/packages/chardet/escprober.pyc
--------------------------------------------------------------------------------
/vendor/requests/packages/chardet/escsm.py:
--------------------------------------------------------------------------------
1 | ######################## BEGIN LICENSE BLOCK ########################
2 | # The Original Code is mozilla.org code.
3 | #
4 | # The Initial Developer of the Original Code is
5 | # Netscape Communications Corporation.
6 | # Portions created by the Initial Developer are Copyright (C) 1998
7 | # the Initial Developer. All Rights Reserved.
8 | #
9 | # Contributor(s):
10 | # Mark Pilgrim - port to Python
11 | #
12 | # This library is free software; you can redistribute it and/or
13 | # modify it under the terms of the GNU Lesser General Public
14 | # License as published by the Free Software Foundation; either
15 | # version 2.1 of the License, or (at your option) any later version.
16 | #
17 | # This library is distributed in the hope that it will be useful,
18 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
19 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20 | # Lesser General Public License for more details.
21 | #
22 | # You should have received a copy of the GNU Lesser General Public
23 | # License along with this library; if not, write to the Free Software
24 | # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
25 | # 02110-1301 USA
26 | ######################### END LICENSE BLOCK #########################
27 |
28 | from .constants import eStart, eError, eItsMe
29 |
30 | HZ_cls = (
31 | 1,0,0,0,0,0,0,0, # 00 - 07
32 | 0,0,0,0,0,0,0,0, # 08 - 0f
33 | 0,0,0,0,0,0,0,0, # 10 - 17
34 | 0,0,0,1,0,0,0,0, # 18 - 1f
35 | 0,0,0,0,0,0,0,0, # 20 - 27
36 | 0,0,0,0,0,0,0,0, # 28 - 2f
37 | 0,0,0,0,0,0,0,0, # 30 - 37
38 | 0,0,0,0,0,0,0,0, # 38 - 3f
39 | 0,0,0,0,0,0,0,0, # 40 - 47
40 | 0,0,0,0,0,0,0,0, # 48 - 4f
41 | 0,0,0,0,0,0,0,0, # 50 - 57
42 | 0,0,0,0,0,0,0,0, # 58 - 5f
43 | 0,0,0,0,0,0,0,0, # 60 - 67
44 | 0,0,0,0,0,0,0,0, # 68 - 6f
45 | 0,0,0,0,0,0,0,0, # 70 - 77
46 | 0,0,0,4,0,5,2,0, # 78 - 7f
47 | 1,1,1,1,1,1,1,1, # 80 - 87
48 | 1,1,1,1,1,1,1,1, # 88 - 8f
49 | 1,1,1,1,1,1,1,1, # 90 - 97
50 | 1,1,1,1,1,1,1,1, # 98 - 9f
51 | 1,1,1,1,1,1,1,1, # a0 - a7
52 | 1,1,1,1,1,1,1,1, # a8 - af
53 | 1,1,1,1,1,1,1,1, # b0 - b7
54 | 1,1,1,1,1,1,1,1, # b8 - bf
55 | 1,1,1,1,1,1,1,1, # c0 - c7
56 | 1,1,1,1,1,1,1,1, # c8 - cf
57 | 1,1,1,1,1,1,1,1, # d0 - d7
58 | 1,1,1,1,1,1,1,1, # d8 - df
59 | 1,1,1,1,1,1,1,1, # e0 - e7
60 | 1,1,1,1,1,1,1,1, # e8 - ef
61 | 1,1,1,1,1,1,1,1, # f0 - f7
62 | 1,1,1,1,1,1,1,1, # f8 - ff
63 | )
64 |
65 | HZ_st = (
66 | eStart,eError, 3,eStart,eStart,eStart,eError,eError,# 00-07
67 | eError,eError,eError,eError,eItsMe,eItsMe,eItsMe,eItsMe,# 08-0f
68 | eItsMe,eItsMe,eError,eError,eStart,eStart, 4,eError,# 10-17
69 | 5,eError, 6,eError, 5, 5, 4,eError,# 18-1f
70 | 4,eError, 4, 4, 4,eError, 4,eError,# 20-27
71 | 4,eItsMe,eStart,eStart,eStart,eStart,eStart,eStart,# 28-2f
72 | )
73 |
74 | HZCharLenTable = (0, 0, 0, 0, 0, 0)
75 |
76 | HZSMModel = {'classTable': HZ_cls,
77 | 'classFactor': 6,
78 | 'stateTable': HZ_st,
79 | 'charLenTable': HZCharLenTable,
80 | 'name': "HZ-GB-2312"}
81 |
82 | ISO2022CN_cls = (
83 | 2,0,0,0,0,0,0,0, # 00 - 07
84 | 0,0,0,0,0,0,0,0, # 08 - 0f
85 | 0,0,0,0,0,0,0,0, # 10 - 17
86 | 0,0,0,1,0,0,0,0, # 18 - 1f
87 | 0,0,0,0,0,0,0,0, # 20 - 27
88 | 0,3,0,0,0,0,0,0, # 28 - 2f
89 | 0,0,0,0,0,0,0,0, # 30 - 37
90 | 0,0,0,0,0,0,0,0, # 38 - 3f
91 | 0,0,0,4,0,0,0,0, # 40 - 47
92 | 0,0,0,0,0,0,0,0, # 48 - 4f
93 | 0,0,0,0,0,0,0,0, # 50 - 57
94 | 0,0,0,0,0,0,0,0, # 58 - 5f
95 | 0,0,0,0,0,0,0,0, # 60 - 67
96 | 0,0,0,0,0,0,0,0, # 68 - 6f
97 | 0,0,0,0,0,0,0,0, # 70 - 77
98 | 0,0,0,0,0,0,0,0, # 78 - 7f
99 | 2,2,2,2,2,2,2,2, # 80 - 87
100 | 2,2,2,2,2,2,2,2, # 88 - 8f
101 | 2,2,2,2,2,2,2,2, # 90 - 97
102 | 2,2,2,2,2,2,2,2, # 98 - 9f
103 | 2,2,2,2,2,2,2,2, # a0 - a7
104 | 2,2,2,2,2,2,2,2, # a8 - af
105 | 2,2,2,2,2,2,2,2, # b0 - b7
106 | 2,2,2,2,2,2,2,2, # b8 - bf
107 | 2,2,2,2,2,2,2,2, # c0 - c7
108 | 2,2,2,2,2,2,2,2, # c8 - cf
109 | 2,2,2,2,2,2,2,2, # d0 - d7
110 | 2,2,2,2,2,2,2,2, # d8 - df
111 | 2,2,2,2,2,2,2,2, # e0 - e7
112 | 2,2,2,2,2,2,2,2, # e8 - ef
113 | 2,2,2,2,2,2,2,2, # f0 - f7
114 | 2,2,2,2,2,2,2,2, # f8 - ff
115 | )
116 |
117 | ISO2022CN_st = (
118 | eStart, 3,eError,eStart,eStart,eStart,eStart,eStart,# 00-07
119 | eStart,eError,eError,eError,eError,eError,eError,eError,# 08-0f
120 | eError,eError,eItsMe,eItsMe,eItsMe,eItsMe,eItsMe,eItsMe,# 10-17
121 | eItsMe,eItsMe,eItsMe,eError,eError,eError, 4,eError,# 18-1f
122 | eError,eError,eError,eItsMe,eError,eError,eError,eError,# 20-27
123 | 5, 6,eError,eError,eError,eError,eError,eError,# 28-2f
124 | eError,eError,eError,eItsMe,eError,eError,eError,eError,# 30-37
125 | eError,eError,eError,eError,eError,eItsMe,eError,eStart,# 38-3f
126 | )
127 |
128 | ISO2022CNCharLenTable = (0, 0, 0, 0, 0, 0, 0, 0, 0)
129 |
130 | ISO2022CNSMModel = {'classTable': ISO2022CN_cls,
131 | 'classFactor': 9,
132 | 'stateTable': ISO2022CN_st,
133 | 'charLenTable': ISO2022CNCharLenTable,
134 | 'name': "ISO-2022-CN"}
135 |
136 | ISO2022JP_cls = (
137 | 2,0,0,0,0,0,0,0, # 00 - 07
138 | 0,0,0,0,0,0,2,2, # 08 - 0f
139 | 0,0,0,0,0,0,0,0, # 10 - 17
140 | 0,0,0,1,0,0,0,0, # 18 - 1f
141 | 0,0,0,0,7,0,0,0, # 20 - 27
142 | 3,0,0,0,0,0,0,0, # 28 - 2f
143 | 0,0,0,0,0,0,0,0, # 30 - 37
144 | 0,0,0,0,0,0,0,0, # 38 - 3f
145 | 6,0,4,0,8,0,0,0, # 40 - 47
146 | 0,9,5,0,0,0,0,0, # 48 - 4f
147 | 0,0,0,0,0,0,0,0, # 50 - 57
148 | 0,0,0,0,0,0,0,0, # 58 - 5f
149 | 0,0,0,0,0,0,0,0, # 60 - 67
150 | 0,0,0,0,0,0,0,0, # 68 - 6f
151 | 0,0,0,0,0,0,0,0, # 70 - 77
152 | 0,0,0,0,0,0,0,0, # 78 - 7f
153 | 2,2,2,2,2,2,2,2, # 80 - 87
154 | 2,2,2,2,2,2,2,2, # 88 - 8f
155 | 2,2,2,2,2,2,2,2, # 90 - 97
156 | 2,2,2,2,2,2,2,2, # 98 - 9f
157 | 2,2,2,2,2,2,2,2, # a0 - a7
158 | 2,2,2,2,2,2,2,2, # a8 - af
159 | 2,2,2,2,2,2,2,2, # b0 - b7
160 | 2,2,2,2,2,2,2,2, # b8 - bf
161 | 2,2,2,2,2,2,2,2, # c0 - c7
162 | 2,2,2,2,2,2,2,2, # c8 - cf
163 | 2,2,2,2,2,2,2,2, # d0 - d7
164 | 2,2,2,2,2,2,2,2, # d8 - df
165 | 2,2,2,2,2,2,2,2, # e0 - e7
166 | 2,2,2,2,2,2,2,2, # e8 - ef
167 | 2,2,2,2,2,2,2,2, # f0 - f7
168 | 2,2,2,2,2,2,2,2, # f8 - ff
169 | )
170 |
171 | ISO2022JP_st = (
172 | eStart, 3,eError,eStart,eStart,eStart,eStart,eStart,# 00-07
173 | eStart,eStart,eError,eError,eError,eError,eError,eError,# 08-0f
174 | eError,eError,eError,eError,eItsMe,eItsMe,eItsMe,eItsMe,# 10-17
175 | eItsMe,eItsMe,eItsMe,eItsMe,eItsMe,eItsMe,eError,eError,# 18-1f
176 | eError, 5,eError,eError,eError, 4,eError,eError,# 20-27
177 | eError,eError,eError, 6,eItsMe,eError,eItsMe,eError,# 28-2f
178 | eError,eError,eError,eError,eError,eError,eItsMe,eItsMe,# 30-37
179 | eError,eError,eError,eItsMe,eError,eError,eError,eError,# 38-3f
180 | eError,eError,eError,eError,eItsMe,eError,eStart,eStart,# 40-47
181 | )
182 |
183 | ISO2022JPCharLenTable = (0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
184 |
185 | ISO2022JPSMModel = {'classTable': ISO2022JP_cls,
186 | 'classFactor': 10,
187 | 'stateTable': ISO2022JP_st,
188 | 'charLenTable': ISO2022JPCharLenTable,
189 | 'name': "ISO-2022-JP"}
190 |
191 | ISO2022KR_cls = (
192 | 2,0,0,0,0,0,0,0, # 00 - 07
193 | 0,0,0,0,0,0,0,0, # 08 - 0f
194 | 0,0,0,0,0,0,0,0, # 10 - 17
195 | 0,0,0,1,0,0,0,0, # 18 - 1f
196 | 0,0,0,0,3,0,0,0, # 20 - 27
197 | 0,4,0,0,0,0,0,0, # 28 - 2f
198 | 0,0,0,0,0,0,0,0, # 30 - 37
199 | 0,0,0,0,0,0,0,0, # 38 - 3f
200 | 0,0,0,5,0,0,0,0, # 40 - 47
201 | 0,0,0,0,0,0,0,0, # 48 - 4f
202 | 0,0,0,0,0,0,0,0, # 50 - 57
203 | 0,0,0,0,0,0,0,0, # 58 - 5f
204 | 0,0,0,0,0,0,0,0, # 60 - 67
205 | 0,0,0,0,0,0,0,0, # 68 - 6f
206 | 0,0,0,0,0,0,0,0, # 70 - 77
207 | 0,0,0,0,0,0,0,0, # 78 - 7f
208 | 2,2,2,2,2,2,2,2, # 80 - 87
209 | 2,2,2,2,2,2,2,2, # 88 - 8f
210 | 2,2,2,2,2,2,2,2, # 90 - 97
211 | 2,2,2,2,2,2,2,2, # 98 - 9f
212 | 2,2,2,2,2,2,2,2, # a0 - a7
213 | 2,2,2,2,2,2,2,2, # a8 - af
214 | 2,2,2,2,2,2,2,2, # b0 - b7
215 | 2,2,2,2,2,2,2,2, # b8 - bf
216 | 2,2,2,2,2,2,2,2, # c0 - c7
217 | 2,2,2,2,2,2,2,2, # c8 - cf
218 | 2,2,2,2,2,2,2,2, # d0 - d7
219 | 2,2,2,2,2,2,2,2, # d8 - df
220 | 2,2,2,2,2,2,2,2, # e0 - e7
221 | 2,2,2,2,2,2,2,2, # e8 - ef
222 | 2,2,2,2,2,2,2,2, # f0 - f7
223 | 2,2,2,2,2,2,2,2, # f8 - ff
224 | )
225 |
226 | ISO2022KR_st = (
227 | eStart, 3,eError,eStart,eStart,eStart,eError,eError,# 00-07
228 | eError,eError,eError,eError,eItsMe,eItsMe,eItsMe,eItsMe,# 08-0f
229 | eItsMe,eItsMe,eError,eError,eError, 4,eError,eError,# 10-17
230 | eError,eError,eError,eError, 5,eError,eError,eError,# 18-1f
231 | eError,eError,eError,eItsMe,eStart,eStart,eStart,eStart,# 20-27
232 | )
233 |
234 | ISO2022KRCharLenTable = (0, 0, 0, 0, 0, 0)
235 |
236 | ISO2022KRSMModel = {'classTable': ISO2022KR_cls,
237 | 'classFactor': 6,
238 | 'stateTable': ISO2022KR_st,
239 | 'charLenTable': ISO2022KRCharLenTable,
240 | 'name': "ISO-2022-KR"}
241 |
242 | # flake8: noqa
243 |
--------------------------------------------------------------------------------
/vendor/requests/packages/chardet/escsm.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/loveQt/wxpytest/c8923b2298a5f71aca4bcee656125dc219d45592/vendor/requests/packages/chardet/escsm.pyc
--------------------------------------------------------------------------------
/vendor/requests/packages/chardet/eucjpprober.py:
--------------------------------------------------------------------------------
1 | ######################## BEGIN LICENSE BLOCK ########################
2 | # The Original Code is mozilla.org code.
3 | #
4 | # The Initial Developer of the Original Code is
5 | # Netscape Communications Corporation.
6 | # Portions created by the Initial Developer are Copyright (C) 1998
7 | # the Initial Developer. All Rights Reserved.
8 | #
9 | # Contributor(s):
10 | # Mark Pilgrim - port to Python
11 | #
12 | # This library is free software; you can redistribute it and/or
13 | # modify it under the terms of the GNU Lesser General Public
14 | # License as published by the Free Software Foundation; either
15 | # version 2.1 of the License, or (at your option) any later version.
16 | #
17 | # This library is distributed in the hope that it will be useful,
18 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
19 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20 | # Lesser General Public License for more details.
21 | #
22 | # You should have received a copy of the GNU Lesser General Public
23 | # License along with this library; if not, write to the Free Software
24 | # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
25 | # 02110-1301 USA
26 | ######################### END LICENSE BLOCK #########################
27 |
28 | import sys
29 | from . import constants
30 | from .mbcharsetprober import MultiByteCharSetProber
31 | from .codingstatemachine import CodingStateMachine
32 | from .chardistribution import EUCJPDistributionAnalysis
33 | from .jpcntx import EUCJPContextAnalysis
34 | from .mbcssm import EUCJPSMModel
35 |
36 |
37 | class EUCJPProber(MultiByteCharSetProber):
38 | def __init__(self):
39 | MultiByteCharSetProber.__init__(self)
40 | self._mCodingSM = CodingStateMachine(EUCJPSMModel)
41 | self._mDistributionAnalyzer = EUCJPDistributionAnalysis()
42 | self._mContextAnalyzer = EUCJPContextAnalysis()
43 | self.reset()
44 |
45 | def reset(self):
46 | MultiByteCharSetProber.reset(self)
47 | self._mContextAnalyzer.reset()
48 |
49 | def get_charset_name(self):
50 | return "EUC-JP"
51 |
52 | def feed(self, aBuf):
53 | aLen = len(aBuf)
54 | for i in range(0, aLen):
55 | # PY3K: aBuf is a byte array, so aBuf[i] is an int, not a byte
56 | codingState = self._mCodingSM.next_state(aBuf[i])
57 | if codingState == constants.eError:
58 | if constants._debug:
59 | sys.stderr.write(self.get_charset_name()
60 | + ' prober hit error at byte ' + str(i)
61 | + '\n')
62 | self._mState = constants.eNotMe
63 | break
64 | elif codingState == constants.eItsMe:
65 | self._mState = constants.eFoundIt
66 | break
67 | elif codingState == constants.eStart:
68 | charLen = self._mCodingSM.get_current_charlen()
69 | if i == 0:
70 | self._mLastChar[1] = aBuf[0]
71 | self._mContextAnalyzer.feed(self._mLastChar, charLen)
72 | self._mDistributionAnalyzer.feed(self._mLastChar, charLen)
73 | else:
74 | self._mContextAnalyzer.feed(aBuf[i - 1:i + 1], charLen)
75 | self._mDistributionAnalyzer.feed(aBuf[i - 1:i + 1],
76 | charLen)
77 |
78 | self._mLastChar[0] = aBuf[aLen - 1]
79 |
80 | if self.get_state() == constants.eDetecting:
81 | if (self._mContextAnalyzer.got_enough_data() and
82 | (self.get_confidence() > constants.SHORTCUT_THRESHOLD)):
83 | self._mState = constants.eFoundIt
84 |
85 | return self.get_state()
86 |
87 | def get_confidence(self):
88 | contxtCf = self._mContextAnalyzer.get_confidence()
89 | distribCf = self._mDistributionAnalyzer.get_confidence()
90 | return max(contxtCf, distribCf)
91 |
--------------------------------------------------------------------------------
/vendor/requests/packages/chardet/eucjpprober.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/loveQt/wxpytest/c8923b2298a5f71aca4bcee656125dc219d45592/vendor/requests/packages/chardet/eucjpprober.pyc
--------------------------------------------------------------------------------
/vendor/requests/packages/chardet/euckrfreq.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/loveQt/wxpytest/c8923b2298a5f71aca4bcee656125dc219d45592/vendor/requests/packages/chardet/euckrfreq.pyc
--------------------------------------------------------------------------------
/vendor/requests/packages/chardet/euckrprober.py:
--------------------------------------------------------------------------------
1 | ######################## BEGIN LICENSE BLOCK ########################
2 | # The Original Code is mozilla.org code.
3 | #
4 | # The Initial Developer of the Original Code is
5 | # Netscape Communications Corporation.
6 | # Portions created by the Initial Developer are Copyright (C) 1998
7 | # the Initial Developer. All Rights Reserved.
8 | #
9 | # Contributor(s):
10 | # Mark Pilgrim - port to Python
11 | #
12 | # This library is free software; you can redistribute it and/or
13 | # modify it under the terms of the GNU Lesser General Public
14 | # License as published by the Free Software Foundation; either
15 | # version 2.1 of the License, or (at your option) any later version.
16 | #
17 | # This library is distributed in the hope that it will be useful,
18 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
19 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20 | # Lesser General Public License for more details.
21 | #
22 | # You should have received a copy of the GNU Lesser General Public
23 | # License along with this library; if not, write to the Free Software
24 | # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
25 | # 02110-1301 USA
26 | ######################### END LICENSE BLOCK #########################
27 |
28 | from .mbcharsetprober import MultiByteCharSetProber
29 | from .codingstatemachine import CodingStateMachine
30 | from .chardistribution import EUCKRDistributionAnalysis
31 | from .mbcssm import EUCKRSMModel
32 |
33 |
34 | class EUCKRProber(MultiByteCharSetProber):
35 | def __init__(self):
36 | MultiByteCharSetProber.__init__(self)
37 | self._mCodingSM = CodingStateMachine(EUCKRSMModel)
38 | self._mDistributionAnalyzer = EUCKRDistributionAnalysis()
39 | self.reset()
40 |
41 | def get_charset_name(self):
42 | return "EUC-KR"
43 |
--------------------------------------------------------------------------------
/vendor/requests/packages/chardet/euckrprober.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/loveQt/wxpytest/c8923b2298a5f71aca4bcee656125dc219d45592/vendor/requests/packages/chardet/euckrprober.pyc
--------------------------------------------------------------------------------
/vendor/requests/packages/chardet/euctwfreq.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/loveQt/wxpytest/c8923b2298a5f71aca4bcee656125dc219d45592/vendor/requests/packages/chardet/euctwfreq.pyc
--------------------------------------------------------------------------------
/vendor/requests/packages/chardet/euctwprober.py:
--------------------------------------------------------------------------------
1 | ######################## BEGIN LICENSE BLOCK ########################
2 | # The Original Code is mozilla.org code.
3 | #
4 | # The Initial Developer of the Original Code is
5 | # Netscape Communications Corporation.
6 | # Portions created by the Initial Developer are Copyright (C) 1998
7 | # the Initial Developer. All Rights Reserved.
8 | #
9 | # Contributor(s):
10 | # Mark Pilgrim - port to Python
11 | #
12 | # This library is free software; you can redistribute it and/or
13 | # modify it under the terms of the GNU Lesser General Public
14 | # License as published by the Free Software Foundation; either
15 | # version 2.1 of the License, or (at your option) any later version.
16 | #
17 | # This library is distributed in the hope that it will be useful,
18 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
19 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20 | # Lesser General Public License for more details.
21 | #
22 | # You should have received a copy of the GNU Lesser General Public
23 | # License along with this library; if not, write to the Free Software
24 | # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
25 | # 02110-1301 USA
26 | ######################### END LICENSE BLOCK #########################
27 |
28 | from .mbcharsetprober import MultiByteCharSetProber
29 | from .codingstatemachine import CodingStateMachine
30 | from .chardistribution import EUCTWDistributionAnalysis
31 | from .mbcssm import EUCTWSMModel
32 |
33 | class EUCTWProber(MultiByteCharSetProber):
34 | def __init__(self):
35 | MultiByteCharSetProber.__init__(self)
36 | self._mCodingSM = CodingStateMachine(EUCTWSMModel)
37 | self._mDistributionAnalyzer = EUCTWDistributionAnalysis()
38 | self.reset()
39 |
40 | def get_charset_name(self):
41 | return "EUC-TW"
42 |
--------------------------------------------------------------------------------
/vendor/requests/packages/chardet/euctwprober.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/loveQt/wxpytest/c8923b2298a5f71aca4bcee656125dc219d45592/vendor/requests/packages/chardet/euctwprober.pyc
--------------------------------------------------------------------------------
/vendor/requests/packages/chardet/gb2312freq.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/loveQt/wxpytest/c8923b2298a5f71aca4bcee656125dc219d45592/vendor/requests/packages/chardet/gb2312freq.pyc
--------------------------------------------------------------------------------
/vendor/requests/packages/chardet/gb2312prober.py:
--------------------------------------------------------------------------------
1 | ######################## BEGIN LICENSE BLOCK ########################
2 | # The Original Code is mozilla.org code.
3 | #
4 | # The Initial Developer of the Original Code is
5 | # Netscape Communications Corporation.
6 | # Portions created by the Initial Developer are Copyright (C) 1998
7 | # the Initial Developer. All Rights Reserved.
8 | #
9 | # Contributor(s):
10 | # Mark Pilgrim - port to Python
11 | #
12 | # This library is free software; you can redistribute it and/or
13 | # modify it under the terms of the GNU Lesser General Public
14 | # License as published by the Free Software Foundation; either
15 | # version 2.1 of the License, or (at your option) any later version.
16 | #
17 | # This library is distributed in the hope that it will be useful,
18 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
19 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20 | # Lesser General Public License for more details.
21 | #
22 | # You should have received a copy of the GNU Lesser General Public
23 | # License along with this library; if not, write to the Free Software
24 | # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
25 | # 02110-1301 USA
26 | ######################### END LICENSE BLOCK #########################
27 |
28 | from .mbcharsetprober import MultiByteCharSetProber
29 | from .codingstatemachine import CodingStateMachine
30 | from .chardistribution import GB2312DistributionAnalysis
31 | from .mbcssm import GB2312SMModel
32 |
33 | class GB2312Prober(MultiByteCharSetProber):
34 | def __init__(self):
35 | MultiByteCharSetProber.__init__(self)
36 | self._mCodingSM = CodingStateMachine(GB2312SMModel)
37 | self._mDistributionAnalyzer = GB2312DistributionAnalysis()
38 | self.reset()
39 |
40 | def get_charset_name(self):
41 | return "GB2312"
42 |
--------------------------------------------------------------------------------
/vendor/requests/packages/chardet/gb2312prober.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/loveQt/wxpytest/c8923b2298a5f71aca4bcee656125dc219d45592/vendor/requests/packages/chardet/gb2312prober.pyc
--------------------------------------------------------------------------------
/vendor/requests/packages/chardet/hebrewprober.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/loveQt/wxpytest/c8923b2298a5f71aca4bcee656125dc219d45592/vendor/requests/packages/chardet/hebrewprober.pyc
--------------------------------------------------------------------------------
/vendor/requests/packages/chardet/jisfreq.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/loveQt/wxpytest/c8923b2298a5f71aca4bcee656125dc219d45592/vendor/requests/packages/chardet/jisfreq.pyc
--------------------------------------------------------------------------------
/vendor/requests/packages/chardet/jpcntx.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/loveQt/wxpytest/c8923b2298a5f71aca4bcee656125dc219d45592/vendor/requests/packages/chardet/jpcntx.pyc
--------------------------------------------------------------------------------
/vendor/requests/packages/chardet/langbulgarianmodel.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/loveQt/wxpytest/c8923b2298a5f71aca4bcee656125dc219d45592/vendor/requests/packages/chardet/langbulgarianmodel.pyc
--------------------------------------------------------------------------------
/vendor/requests/packages/chardet/langcyrillicmodel.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/loveQt/wxpytest/c8923b2298a5f71aca4bcee656125dc219d45592/vendor/requests/packages/chardet/langcyrillicmodel.pyc
--------------------------------------------------------------------------------
/vendor/requests/packages/chardet/langgreekmodel.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/loveQt/wxpytest/c8923b2298a5f71aca4bcee656125dc219d45592/vendor/requests/packages/chardet/langgreekmodel.pyc
--------------------------------------------------------------------------------
/vendor/requests/packages/chardet/langhebrewmodel.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/loveQt/wxpytest/c8923b2298a5f71aca4bcee656125dc219d45592/vendor/requests/packages/chardet/langhebrewmodel.pyc
--------------------------------------------------------------------------------
/vendor/requests/packages/chardet/langhungarianmodel.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/loveQt/wxpytest/c8923b2298a5f71aca4bcee656125dc219d45592/vendor/requests/packages/chardet/langhungarianmodel.pyc
--------------------------------------------------------------------------------
/vendor/requests/packages/chardet/langthaimodel.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/loveQt/wxpytest/c8923b2298a5f71aca4bcee656125dc219d45592/vendor/requests/packages/chardet/langthaimodel.pyc
--------------------------------------------------------------------------------
/vendor/requests/packages/chardet/latin1prober.py:
--------------------------------------------------------------------------------
1 | ######################## BEGIN LICENSE BLOCK ########################
2 | # The Original Code is Mozilla Universal charset detector code.
3 | #
4 | # The Initial Developer of the Original Code is
5 | # Netscape Communications Corporation.
6 | # Portions created by the Initial Developer are Copyright (C) 2001
7 | # the Initial Developer. All Rights Reserved.
8 | #
9 | # Contributor(s):
10 | # Mark Pilgrim - port to Python
11 | # Shy Shalom - original C code
12 | #
13 | # This library is free software; you can redistribute it and/or
14 | # modify it under the terms of the GNU Lesser General Public
15 | # License as published by the Free Software Foundation; either
16 | # version 2.1 of the License, or (at your option) any later version.
17 | #
18 | # This library is distributed in the hope that it will be useful,
19 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
20 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
21 | # Lesser General Public License for more details.
22 | #
23 | # You should have received a copy of the GNU Lesser General Public
24 | # License along with this library; if not, write to the Free Software
25 | # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
26 | # 02110-1301 USA
27 | ######################### END LICENSE BLOCK #########################
28 |
29 | from .charsetprober import CharSetProber
30 | from .constants import eNotMe
31 | from .compat import wrap_ord
32 |
33 | FREQ_CAT_NUM = 4
34 |
35 | UDF = 0 # undefined
36 | OTH = 1 # other
37 | ASC = 2 # ascii capital letter
38 | ASS = 3 # ascii small letter
39 | ACV = 4 # accent capital vowel
40 | ACO = 5 # accent capital other
41 | ASV = 6 # accent small vowel
42 | ASO = 7 # accent small other
43 | CLASS_NUM = 8 # total classes
44 |
45 | Latin1_CharToClass = (
46 | OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, # 00 - 07
47 | OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, # 08 - 0F
48 | OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, # 10 - 17
49 | OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, # 18 - 1F
50 | OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, # 20 - 27
51 | OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, # 28 - 2F
52 | OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, # 30 - 37
53 | OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, # 38 - 3F
54 | OTH, ASC, ASC, ASC, ASC, ASC, ASC, ASC, # 40 - 47
55 | ASC, ASC, ASC, ASC, ASC, ASC, ASC, ASC, # 48 - 4F
56 | ASC, ASC, ASC, ASC, ASC, ASC, ASC, ASC, # 50 - 57
57 | ASC, ASC, ASC, OTH, OTH, OTH, OTH, OTH, # 58 - 5F
58 | OTH, ASS, ASS, ASS, ASS, ASS, ASS, ASS, # 60 - 67
59 | ASS, ASS, ASS, ASS, ASS, ASS, ASS, ASS, # 68 - 6F
60 | ASS, ASS, ASS, ASS, ASS, ASS, ASS, ASS, # 70 - 77
61 | ASS, ASS, ASS, OTH, OTH, OTH, OTH, OTH, # 78 - 7F
62 | OTH, UDF, OTH, ASO, OTH, OTH, OTH, OTH, # 80 - 87
63 | OTH, OTH, ACO, OTH, ACO, UDF, ACO, UDF, # 88 - 8F
64 | UDF, OTH, OTH, OTH, OTH, OTH, OTH, OTH, # 90 - 97
65 | OTH, OTH, ASO, OTH, ASO, UDF, ASO, ACO, # 98 - 9F
66 | OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, # A0 - A7
67 | OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, # A8 - AF
68 | OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, # B0 - B7
69 | OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, # B8 - BF
70 | ACV, ACV, ACV, ACV, ACV, ACV, ACO, ACO, # C0 - C7
71 | ACV, ACV, ACV, ACV, ACV, ACV, ACV, ACV, # C8 - CF
72 | ACO, ACO, ACV, ACV, ACV, ACV, ACV, OTH, # D0 - D7
73 | ACV, ACV, ACV, ACV, ACV, ACO, ACO, ACO, # D8 - DF
74 | ASV, ASV, ASV, ASV, ASV, ASV, ASO, ASO, # E0 - E7
75 | ASV, ASV, ASV, ASV, ASV, ASV, ASV, ASV, # E8 - EF
76 | ASO, ASO, ASV, ASV, ASV, ASV, ASV, OTH, # F0 - F7
77 | ASV, ASV, ASV, ASV, ASV, ASO, ASO, ASO, # F8 - FF
78 | )
79 |
80 | # 0 : illegal
81 | # 1 : very unlikely
82 | # 2 : normal
83 | # 3 : very likely
84 | Latin1ClassModel = (
85 | # UDF OTH ASC ASS ACV ACO ASV ASO
86 | 0, 0, 0, 0, 0, 0, 0, 0, # UDF
87 | 0, 3, 3, 3, 3, 3, 3, 3, # OTH
88 | 0, 3, 3, 3, 3, 3, 3, 3, # ASC
89 | 0, 3, 3, 3, 1, 1, 3, 3, # ASS
90 | 0, 3, 3, 3, 1, 2, 1, 2, # ACV
91 | 0, 3, 3, 3, 3, 3, 3, 3, # ACO
92 | 0, 3, 1, 3, 1, 1, 1, 3, # ASV
93 | 0, 3, 1, 3, 1, 1, 3, 3, # ASO
94 | )
95 |
96 |
97 | class Latin1Prober(CharSetProber):
98 | def __init__(self):
99 | CharSetProber.__init__(self)
100 | self.reset()
101 |
102 | def reset(self):
103 | self._mLastCharClass = OTH
104 | self._mFreqCounter = [0] * FREQ_CAT_NUM
105 | CharSetProber.reset(self)
106 |
107 | def get_charset_name(self):
108 | return "windows-1252"
109 |
110 | def feed(self, aBuf):
111 | aBuf = self.filter_with_english_letters(aBuf)
112 | for c in aBuf:
113 | charClass = Latin1_CharToClass[wrap_ord(c)]
114 | freq = Latin1ClassModel[(self._mLastCharClass * CLASS_NUM)
115 | + charClass]
116 | if freq == 0:
117 | self._mState = eNotMe
118 | break
119 | self._mFreqCounter[freq] += 1
120 | self._mLastCharClass = charClass
121 |
122 | return self.get_state()
123 |
124 | def get_confidence(self):
125 | if self.get_state() == eNotMe:
126 | return 0.01
127 |
128 | total = sum(self._mFreqCounter)
129 | if total < 0.01:
130 | confidence = 0.0
131 | else:
132 | confidence = ((self._mFreqCounter[3] - self._mFreqCounter[1] * 20.0)
133 | / total)
134 | if confidence < 0.0:
135 | confidence = 0.0
136 | # lower the confidence of latin1 so that other more accurate
137 | # detector can take priority.
138 | confidence = confidence * 0.73
139 | return confidence
140 |
--------------------------------------------------------------------------------
/vendor/requests/packages/chardet/latin1prober.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/loveQt/wxpytest/c8923b2298a5f71aca4bcee656125dc219d45592/vendor/requests/packages/chardet/latin1prober.pyc
--------------------------------------------------------------------------------
/vendor/requests/packages/chardet/mbcharsetprober.py:
--------------------------------------------------------------------------------
1 | ######################## BEGIN LICENSE BLOCK ########################
2 | # The Original Code is Mozilla Universal charset detector code.
3 | #
4 | # The Initial Developer of the Original Code is
5 | # Netscape Communications Corporation.
6 | # Portions created by the Initial Developer are Copyright (C) 2001
7 | # the Initial Developer. All Rights Reserved.
8 | #
9 | # Contributor(s):
10 | # Mark Pilgrim - port to Python
11 | # Shy Shalom - original C code
12 | # Proofpoint, Inc.
13 | #
14 | # This library is free software; you can redistribute it and/or
15 | # modify it under the terms of the GNU Lesser General Public
16 | # License as published by the Free Software Foundation; either
17 | # version 2.1 of the License, or (at your option) any later version.
18 | #
19 | # This library is distributed in the hope that it will be useful,
20 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
21 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
22 | # Lesser General Public License for more details.
23 | #
24 | # You should have received a copy of the GNU Lesser General Public
25 | # License along with this library; if not, write to the Free Software
26 | # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
27 | # 02110-1301 USA
28 | ######################### END LICENSE BLOCK #########################
29 |
30 | import sys
31 | from . import constants
32 | from .charsetprober import CharSetProber
33 |
34 |
35 | class MultiByteCharSetProber(CharSetProber):
36 | def __init__(self):
37 | CharSetProber.__init__(self)
38 | self._mDistributionAnalyzer = None
39 | self._mCodingSM = None
40 | self._mLastChar = [0, 0]
41 |
42 | def reset(self):
43 | CharSetProber.reset(self)
44 | if self._mCodingSM:
45 | self._mCodingSM.reset()
46 | if self._mDistributionAnalyzer:
47 | self._mDistributionAnalyzer.reset()
48 | self._mLastChar = [0, 0]
49 |
50 | def get_charset_name(self):
51 | pass
52 |
53 | def feed(self, aBuf):
54 | aLen = len(aBuf)
55 | for i in range(0, aLen):
56 | codingState = self._mCodingSM.next_state(aBuf[i])
57 | if codingState == constants.eError:
58 | if constants._debug:
59 | sys.stderr.write(self.get_charset_name()
60 | + ' prober hit error at byte ' + str(i)
61 | + '\n')
62 | self._mState = constants.eNotMe
63 | break
64 | elif codingState == constants.eItsMe:
65 | self._mState = constants.eFoundIt
66 | break
67 | elif codingState == constants.eStart:
68 | charLen = self._mCodingSM.get_current_charlen()
69 | if i == 0:
70 | self._mLastChar[1] = aBuf[0]
71 | self._mDistributionAnalyzer.feed(self._mLastChar, charLen)
72 | else:
73 | self._mDistributionAnalyzer.feed(aBuf[i - 1:i + 1],
74 | charLen)
75 |
76 | self._mLastChar[0] = aBuf[aLen - 1]
77 |
78 | if self.get_state() == constants.eDetecting:
79 | if (self._mDistributionAnalyzer.got_enough_data() and
80 | (self.get_confidence() > constants.SHORTCUT_THRESHOLD)):
81 | self._mState = constants.eFoundIt
82 |
83 | return self.get_state()
84 |
85 | def get_confidence(self):
86 | return self._mDistributionAnalyzer.get_confidence()
87 |
--------------------------------------------------------------------------------
/vendor/requests/packages/chardet/mbcharsetprober.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/loveQt/wxpytest/c8923b2298a5f71aca4bcee656125dc219d45592/vendor/requests/packages/chardet/mbcharsetprober.pyc
--------------------------------------------------------------------------------
/vendor/requests/packages/chardet/mbcsgroupprober.py:
--------------------------------------------------------------------------------
1 | ######################## BEGIN LICENSE BLOCK ########################
2 | # The Original Code is Mozilla Universal charset detector code.
3 | #
4 | # The Initial Developer of the Original Code is
5 | # Netscape Communications Corporation.
6 | # Portions created by the Initial Developer are Copyright (C) 2001
7 | # the Initial Developer. All Rights Reserved.
8 | #
9 | # Contributor(s):
10 | # Mark Pilgrim - port to Python
11 | # Shy Shalom - original C code
12 | # Proofpoint, Inc.
13 | #
14 | # This library is free software; you can redistribute it and/or
15 | # modify it under the terms of the GNU Lesser General Public
16 | # License as published by the Free Software Foundation; either
17 | # version 2.1 of the License, or (at your option) any later version.
18 | #
19 | # This library is distributed in the hope that it will be useful,
20 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
21 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
22 | # Lesser General Public License for more details.
23 | #
24 | # You should have received a copy of the GNU Lesser General Public
25 | # License along with this library; if not, write to the Free Software
26 | # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
27 | # 02110-1301 USA
28 | ######################### END LICENSE BLOCK #########################
29 |
30 | from .charsetgroupprober import CharSetGroupProber
31 | from .utf8prober import UTF8Prober
32 | from .sjisprober import SJISProber
33 | from .eucjpprober import EUCJPProber
34 | from .gb2312prober import GB2312Prober
35 | from .euckrprober import EUCKRProber
36 | from .cp949prober import CP949Prober
37 | from .big5prober import Big5Prober
38 | from .euctwprober import EUCTWProber
39 |
40 |
41 | class MBCSGroupProber(CharSetGroupProber):
42 | def __init__(self):
43 | CharSetGroupProber.__init__(self)
44 | self._mProbers = [
45 | UTF8Prober(),
46 | SJISProber(),
47 | EUCJPProber(),
48 | GB2312Prober(),
49 | EUCKRProber(),
50 | CP949Prober(),
51 | Big5Prober(),
52 | EUCTWProber()
53 | ]
54 | self.reset()
55 |
--------------------------------------------------------------------------------
/vendor/requests/packages/chardet/mbcsgroupprober.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/loveQt/wxpytest/c8923b2298a5f71aca4bcee656125dc219d45592/vendor/requests/packages/chardet/mbcsgroupprober.pyc
--------------------------------------------------------------------------------
/vendor/requests/packages/chardet/mbcssm.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/loveQt/wxpytest/c8923b2298a5f71aca4bcee656125dc219d45592/vendor/requests/packages/chardet/mbcssm.pyc
--------------------------------------------------------------------------------
/vendor/requests/packages/chardet/sbcharsetprober.py:
--------------------------------------------------------------------------------
1 | ######################## BEGIN LICENSE BLOCK ########################
2 | # The Original Code is Mozilla Universal charset detector code.
3 | #
4 | # The Initial Developer of the Original Code is
5 | # Netscape Communications Corporation.
6 | # Portions created by the Initial Developer are Copyright (C) 2001
7 | # the Initial Developer. All Rights Reserved.
8 | #
9 | # Contributor(s):
10 | # Mark Pilgrim - port to Python
11 | # Shy Shalom - original C code
12 | #
13 | # This library is free software; you can redistribute it and/or
14 | # modify it under the terms of the GNU Lesser General Public
15 | # License as published by the Free Software Foundation; either
16 | # version 2.1 of the License, or (at your option) any later version.
17 | #
18 | # This library is distributed in the hope that it will be useful,
19 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
20 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
21 | # Lesser General Public License for more details.
22 | #
23 | # You should have received a copy of the GNU Lesser General Public
24 | # License along with this library; if not, write to the Free Software
25 | # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
26 | # 02110-1301 USA
27 | ######################### END LICENSE BLOCK #########################
28 |
29 | import sys
30 | from . import constants
31 | from .charsetprober import CharSetProber
32 | from .compat import wrap_ord
33 |
34 | SAMPLE_SIZE = 64
35 | SB_ENOUGH_REL_THRESHOLD = 1024
36 | POSITIVE_SHORTCUT_THRESHOLD = 0.95
37 | NEGATIVE_SHORTCUT_THRESHOLD = 0.05
38 | SYMBOL_CAT_ORDER = 250
39 | NUMBER_OF_SEQ_CAT = 4
40 | POSITIVE_CAT = NUMBER_OF_SEQ_CAT - 1
41 | #NEGATIVE_CAT = 0
42 |
43 |
44 | class SingleByteCharSetProber(CharSetProber):
45 | def __init__(self, model, reversed=False, nameProber=None):
46 | CharSetProber.__init__(self)
47 | self._mModel = model
48 | # TRUE if we need to reverse every pair in the model lookup
49 | self._mReversed = reversed
50 | # Optional auxiliary prober for name decision
51 | self._mNameProber = nameProber
52 | self.reset()
53 |
54 | def reset(self):
55 | CharSetProber.reset(self)
56 | # char order of last character
57 | self._mLastOrder = 255
58 | self._mSeqCounters = [0] * NUMBER_OF_SEQ_CAT
59 | self._mTotalSeqs = 0
60 | self._mTotalChar = 0
61 | # characters that fall in our sampling range
62 | self._mFreqChar = 0
63 |
64 | def get_charset_name(self):
65 | if self._mNameProber:
66 | return self._mNameProber.get_charset_name()
67 | else:
68 | return self._mModel['charsetName']
69 |
70 | def feed(self, aBuf):
71 | if not self._mModel['keepEnglishLetter']:
72 | aBuf = self.filter_without_english_letters(aBuf)
73 | aLen = len(aBuf)
74 | if not aLen:
75 | return self.get_state()
76 | for c in aBuf:
77 | order = self._mModel['charToOrderMap'][wrap_ord(c)]
78 | if order < SYMBOL_CAT_ORDER:
79 | self._mTotalChar += 1
80 | if order < SAMPLE_SIZE:
81 | self._mFreqChar += 1
82 | if self._mLastOrder < SAMPLE_SIZE:
83 | self._mTotalSeqs += 1
84 | if not self._mReversed:
85 | i = (self._mLastOrder * SAMPLE_SIZE) + order
86 | model = self._mModel['precedenceMatrix'][i]
87 | else: # reverse the order of the letters in the lookup
88 | i = (order * SAMPLE_SIZE) + self._mLastOrder
89 | model = self._mModel['precedenceMatrix'][i]
90 | self._mSeqCounters[model] += 1
91 | self._mLastOrder = order
92 |
93 | if self.get_state() == constants.eDetecting:
94 | if self._mTotalSeqs > SB_ENOUGH_REL_THRESHOLD:
95 | cf = self.get_confidence()
96 | if cf > POSITIVE_SHORTCUT_THRESHOLD:
97 | if constants._debug:
98 | sys.stderr.write('%s confidence = %s, we have a'
99 | 'winner\n' %
100 | (self._mModel['charsetName'], cf))
101 | self._mState = constants.eFoundIt
102 | elif cf < NEGATIVE_SHORTCUT_THRESHOLD:
103 | if constants._debug:
104 | sys.stderr.write('%s confidence = %s, below negative'
105 | 'shortcut threshhold %s\n' %
106 | (self._mModel['charsetName'], cf,
107 | NEGATIVE_SHORTCUT_THRESHOLD))
108 | self._mState = constants.eNotMe
109 |
110 | return self.get_state()
111 |
112 | def get_confidence(self):
113 | r = 0.01
114 | if self._mTotalSeqs > 0:
115 | r = ((1.0 * self._mSeqCounters[POSITIVE_CAT]) / self._mTotalSeqs
116 | / self._mModel['mTypicalPositiveRatio'])
117 | r = r * self._mFreqChar / self._mTotalChar
118 | if r >= 1.0:
119 | r = 0.99
120 | return r
121 |
--------------------------------------------------------------------------------
/vendor/requests/packages/chardet/sbcharsetprober.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/loveQt/wxpytest/c8923b2298a5f71aca4bcee656125dc219d45592/vendor/requests/packages/chardet/sbcharsetprober.pyc
--------------------------------------------------------------------------------
/vendor/requests/packages/chardet/sbcsgroupprober.py:
--------------------------------------------------------------------------------
1 | ######################## BEGIN LICENSE BLOCK ########################
2 | # The Original Code is Mozilla Universal charset detector code.
3 | #
4 | # The Initial Developer of the Original Code is
5 | # Netscape Communications Corporation.
6 | # Portions created by the Initial Developer are Copyright (C) 2001
7 | # the Initial Developer. All Rights Reserved.
8 | #
9 | # Contributor(s):
10 | # Mark Pilgrim - port to Python
11 | # Shy Shalom - original C code
12 | #
13 | # This library is free software; you can redistribute it and/or
14 | # modify it under the terms of the GNU Lesser General Public
15 | # License as published by the Free Software Foundation; either
16 | # version 2.1 of the License, or (at your option) any later version.
17 | #
18 | # This library is distributed in the hope that it will be useful,
19 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
20 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
21 | # Lesser General Public License for more details.
22 | #
23 | # You should have received a copy of the GNU Lesser General Public
24 | # License along with this library; if not, write to the Free Software
25 | # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
26 | # 02110-1301 USA
27 | ######################### END LICENSE BLOCK #########################
28 |
29 | from .charsetgroupprober import CharSetGroupProber
30 | from .sbcharsetprober import SingleByteCharSetProber
31 | from .langcyrillicmodel import (Win1251CyrillicModel, Koi8rModel,
32 | Latin5CyrillicModel, MacCyrillicModel,
33 | Ibm866Model, Ibm855Model)
34 | from .langgreekmodel import Latin7GreekModel, Win1253GreekModel
35 | from .langbulgarianmodel import Latin5BulgarianModel, Win1251BulgarianModel
36 | from .langhungarianmodel import Latin2HungarianModel, Win1250HungarianModel
37 | from .langthaimodel import TIS620ThaiModel
38 | from .langhebrewmodel import Win1255HebrewModel
39 | from .hebrewprober import HebrewProber
40 |
41 |
42 | class SBCSGroupProber(CharSetGroupProber):
43 | def __init__(self):
44 | CharSetGroupProber.__init__(self)
45 | self._mProbers = [
46 | SingleByteCharSetProber(Win1251CyrillicModel),
47 | SingleByteCharSetProber(Koi8rModel),
48 | SingleByteCharSetProber(Latin5CyrillicModel),
49 | SingleByteCharSetProber(MacCyrillicModel),
50 | SingleByteCharSetProber(Ibm866Model),
51 | SingleByteCharSetProber(Ibm855Model),
52 | SingleByteCharSetProber(Latin7GreekModel),
53 | SingleByteCharSetProber(Win1253GreekModel),
54 | SingleByteCharSetProber(Latin5BulgarianModel),
55 | SingleByteCharSetProber(Win1251BulgarianModel),
56 | SingleByteCharSetProber(Latin2HungarianModel),
57 | SingleByteCharSetProber(Win1250HungarianModel),
58 | SingleByteCharSetProber(TIS620ThaiModel),
59 | ]
60 | hebrewProber = HebrewProber()
61 | logicalHebrewProber = SingleByteCharSetProber(Win1255HebrewModel,
62 | False, hebrewProber)
63 | visualHebrewProber = SingleByteCharSetProber(Win1255HebrewModel, True,
64 | hebrewProber)
65 | hebrewProber.set_model_probers(logicalHebrewProber, visualHebrewProber)
66 | self._mProbers.extend([hebrewProber, logicalHebrewProber,
67 | visualHebrewProber])
68 |
69 | self.reset()
70 |
--------------------------------------------------------------------------------
/vendor/requests/packages/chardet/sbcsgroupprober.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/loveQt/wxpytest/c8923b2298a5f71aca4bcee656125dc219d45592/vendor/requests/packages/chardet/sbcsgroupprober.pyc
--------------------------------------------------------------------------------
/vendor/requests/packages/chardet/sjisprober.py:
--------------------------------------------------------------------------------
1 | ######################## BEGIN LICENSE BLOCK ########################
2 | # The Original Code is mozilla.org code.
3 | #
4 | # The Initial Developer of the Original Code is
5 | # Netscape Communications Corporation.
6 | # Portions created by the Initial Developer are Copyright (C) 1998
7 | # the Initial Developer. All Rights Reserved.
8 | #
9 | # Contributor(s):
10 | # Mark Pilgrim - port to Python
11 | #
12 | # This library is free software; you can redistribute it and/or
13 | # modify it under the terms of the GNU Lesser General Public
14 | # License as published by the Free Software Foundation; either
15 | # version 2.1 of the License, or (at your option) any later version.
16 | #
17 | # This library is distributed in the hope that it will be useful,
18 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
19 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20 | # Lesser General Public License for more details.
21 | #
22 | # You should have received a copy of the GNU Lesser General Public
23 | # License along with this library; if not, write to the Free Software
24 | # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
25 | # 02110-1301 USA
26 | ######################### END LICENSE BLOCK #########################
27 |
28 | import sys
29 | from .mbcharsetprober import MultiByteCharSetProber
30 | from .codingstatemachine import CodingStateMachine
31 | from .chardistribution import SJISDistributionAnalysis
32 | from .jpcntx import SJISContextAnalysis
33 | from .mbcssm import SJISSMModel
34 | from . import constants
35 |
36 |
37 | class SJISProber(MultiByteCharSetProber):
38 | def __init__(self):
39 | MultiByteCharSetProber.__init__(self)
40 | self._mCodingSM = CodingStateMachine(SJISSMModel)
41 | self._mDistributionAnalyzer = SJISDistributionAnalysis()
42 | self._mContextAnalyzer = SJISContextAnalysis()
43 | self.reset()
44 |
45 | def reset(self):
46 | MultiByteCharSetProber.reset(self)
47 | self._mContextAnalyzer.reset()
48 |
49 | def get_charset_name(self):
50 | return self._mContextAnalyzer.get_charset_name()
51 |
52 | def feed(self, aBuf):
53 | aLen = len(aBuf)
54 | for i in range(0, aLen):
55 | codingState = self._mCodingSM.next_state(aBuf[i])
56 | if codingState == constants.eError:
57 | if constants._debug:
58 | sys.stderr.write(self.get_charset_name()
59 | + ' prober hit error at byte ' + str(i)
60 | + '\n')
61 | self._mState = constants.eNotMe
62 | break
63 | elif codingState == constants.eItsMe:
64 | self._mState = constants.eFoundIt
65 | break
66 | elif codingState == constants.eStart:
67 | charLen = self._mCodingSM.get_current_charlen()
68 | if i == 0:
69 | self._mLastChar[1] = aBuf[0]
70 | self._mContextAnalyzer.feed(self._mLastChar[2 - charLen:],
71 | charLen)
72 | self._mDistributionAnalyzer.feed(self._mLastChar, charLen)
73 | else:
74 | self._mContextAnalyzer.feed(aBuf[i + 1 - charLen:i + 3
75 | - charLen], charLen)
76 | self._mDistributionAnalyzer.feed(aBuf[i - 1:i + 1],
77 | charLen)
78 |
79 | self._mLastChar[0] = aBuf[aLen - 1]
80 |
81 | if self.get_state() == constants.eDetecting:
82 | if (self._mContextAnalyzer.got_enough_data() and
83 | (self.get_confidence() > constants.SHORTCUT_THRESHOLD)):
84 | self._mState = constants.eFoundIt
85 |
86 | return self.get_state()
87 |
88 | def get_confidence(self):
89 | contxtCf = self._mContextAnalyzer.get_confidence()
90 | distribCf = self._mDistributionAnalyzer.get_confidence()
91 | return max(contxtCf, distribCf)
92 |
--------------------------------------------------------------------------------
/vendor/requests/packages/chardet/sjisprober.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/loveQt/wxpytest/c8923b2298a5f71aca4bcee656125dc219d45592/vendor/requests/packages/chardet/sjisprober.pyc
--------------------------------------------------------------------------------
/vendor/requests/packages/chardet/universaldetector.py:
--------------------------------------------------------------------------------
1 | ######################## BEGIN LICENSE BLOCK ########################
2 | # The Original Code is Mozilla Universal charset detector code.
3 | #
4 | # The Initial Developer of the Original Code is
5 | # Netscape Communications Corporation.
6 | # Portions created by the Initial Developer are Copyright (C) 2001
7 | # the Initial Developer. All Rights Reserved.
8 | #
9 | # Contributor(s):
10 | # Mark Pilgrim - port to Python
11 | # Shy Shalom - original C code
12 | #
13 | # This library is free software; you can redistribute it and/or
14 | # modify it under the terms of the GNU Lesser General Public
15 | # License as published by the Free Software Foundation; either
16 | # version 2.1 of the License, or (at your option) any later version.
17 | #
18 | # This library is distributed in the hope that it will be useful,
19 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
20 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
21 | # Lesser General Public License for more details.
22 | #
23 | # You should have received a copy of the GNU Lesser General Public
24 | # License along with this library; if not, write to the Free Software
25 | # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
26 | # 02110-1301 USA
27 | ######################### END LICENSE BLOCK #########################
28 |
29 | from . import constants
30 | import sys
31 | import codecs
32 | from .latin1prober import Latin1Prober # windows-1252
33 | from .mbcsgroupprober import MBCSGroupProber # multi-byte character sets
34 | from .sbcsgroupprober import SBCSGroupProber # single-byte character sets
35 | from .escprober import EscCharSetProber # ISO-2122, etc.
36 | import re
37 |
38 | MINIMUM_THRESHOLD = 0.20
39 | ePureAscii = 0
40 | eEscAscii = 1
41 | eHighbyte = 2
42 |
43 |
44 | class UniversalDetector:
45 | def __init__(self):
46 | self._highBitDetector = re.compile(b'[\x80-\xFF]')
47 | self._escDetector = re.compile(b'(\033|~{)')
48 | self._mEscCharSetProber = None
49 | self._mCharSetProbers = []
50 | self.reset()
51 |
52 | def reset(self):
53 | self.result = {'encoding': None, 'confidence': 0.0}
54 | self.done = False
55 | self._mStart = True
56 | self._mGotData = False
57 | self._mInputState = ePureAscii
58 | self._mLastChar = b''
59 | if self._mEscCharSetProber:
60 | self._mEscCharSetProber.reset()
61 | for prober in self._mCharSetProbers:
62 | prober.reset()
63 |
64 | def feed(self, aBuf):
65 | if self.done:
66 | return
67 |
68 | aLen = len(aBuf)
69 | if not aLen:
70 | return
71 |
72 | if not self._mGotData:
73 | # If the data starts with BOM, we know it is UTF
74 | if aBuf[:3] == codecs.BOM_UTF8:
75 | # EF BB BF UTF-8 with BOM
76 | self.result = {'encoding': "UTF-8-SIG", 'confidence': 1.0}
77 | elif aBuf[:4] == codecs.BOM_UTF32_LE:
78 | # FF FE 00 00 UTF-32, little-endian BOM
79 | self.result = {'encoding': "UTF-32LE", 'confidence': 1.0}
80 | elif aBuf[:4] == codecs.BOM_UTF32_BE:
81 | # 00 00 FE FF UTF-32, big-endian BOM
82 | self.result = {'encoding': "UTF-32BE", 'confidence': 1.0}
83 | elif aBuf[:4] == b'\xFE\xFF\x00\x00':
84 | # FE FF 00 00 UCS-4, unusual octet order BOM (3412)
85 | self.result = {
86 | 'encoding': "X-ISO-10646-UCS-4-3412",
87 | 'confidence': 1.0
88 | }
89 | elif aBuf[:4] == b'\x00\x00\xFF\xFE':
90 | # 00 00 FF FE UCS-4, unusual octet order BOM (2143)
91 | self.result = {
92 | 'encoding': "X-ISO-10646-UCS-4-2143",
93 | 'confidence': 1.0
94 | }
95 | elif aBuf[:2] == codecs.BOM_LE:
96 | # FF FE UTF-16, little endian BOM
97 | self.result = {'encoding': "UTF-16LE", 'confidence': 1.0}
98 | elif aBuf[:2] == codecs.BOM_BE:
99 | # FE FF UTF-16, big endian BOM
100 | self.result = {'encoding': "UTF-16BE", 'confidence': 1.0}
101 |
102 | self._mGotData = True
103 | if self.result['encoding'] and (self.result['confidence'] > 0.0):
104 | self.done = True
105 | return
106 |
107 | if self._mInputState == ePureAscii:
108 | if self._highBitDetector.search(aBuf):
109 | self._mInputState = eHighbyte
110 | elif ((self._mInputState == ePureAscii) and
111 | self._escDetector.search(self._mLastChar + aBuf)):
112 | self._mInputState = eEscAscii
113 |
114 | self._mLastChar = aBuf[-1:]
115 |
116 | if self._mInputState == eEscAscii:
117 | if not self._mEscCharSetProber:
118 | self._mEscCharSetProber = EscCharSetProber()
119 | if self._mEscCharSetProber.feed(aBuf) == constants.eFoundIt:
120 | self.result = {'encoding': self._mEscCharSetProber.get_charset_name(),
121 | 'confidence': self._mEscCharSetProber.get_confidence()}
122 | self.done = True
123 | elif self._mInputState == eHighbyte:
124 | if not self._mCharSetProbers:
125 | self._mCharSetProbers = [MBCSGroupProber(), SBCSGroupProber(),
126 | Latin1Prober()]
127 | for prober in self._mCharSetProbers:
128 | if prober.feed(aBuf) == constants.eFoundIt:
129 | self.result = {'encoding': prober.get_charset_name(),
130 | 'confidence': prober.get_confidence()}
131 | self.done = True
132 | break
133 |
134 | def close(self):
135 | if self.done:
136 | return
137 | if not self._mGotData:
138 | if constants._debug:
139 | sys.stderr.write('no data received!\n')
140 | return
141 | self.done = True
142 |
143 | if self._mInputState == ePureAscii:
144 | self.result = {'encoding': 'ascii', 'confidence': 1.0}
145 | return self.result
146 |
147 | if self._mInputState == eHighbyte:
148 | proberConfidence = None
149 | maxProberConfidence = 0.0
150 | maxProber = None
151 | for prober in self._mCharSetProbers:
152 | if not prober:
153 | continue
154 | proberConfidence = prober.get_confidence()
155 | if proberConfidence > maxProberConfidence:
156 | maxProberConfidence = proberConfidence
157 | maxProber = prober
158 | if maxProber and (maxProberConfidence > MINIMUM_THRESHOLD):
159 | self.result = {'encoding': maxProber.get_charset_name(),
160 | 'confidence': maxProber.get_confidence()}
161 | return self.result
162 |
163 | if constants._debug:
164 | sys.stderr.write('no probers hit minimum threshhold\n')
165 | for prober in self._mCharSetProbers[0].mProbers:
166 | if not prober:
167 | continue
168 | sys.stderr.write('%s confidence = %s\n' %
169 | (prober.get_charset_name(),
170 | prober.get_confidence()))
171 |
--------------------------------------------------------------------------------
/vendor/requests/packages/chardet/universaldetector.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/loveQt/wxpytest/c8923b2298a5f71aca4bcee656125dc219d45592/vendor/requests/packages/chardet/universaldetector.pyc
--------------------------------------------------------------------------------
/vendor/requests/packages/chardet/utf8prober.py:
--------------------------------------------------------------------------------
1 | ######################## BEGIN LICENSE BLOCK ########################
2 | # The Original Code is mozilla.org code.
3 | #
4 | # The Initial Developer of the Original Code is
5 | # Netscape Communications Corporation.
6 | # Portions created by the Initial Developer are Copyright (C) 1998
7 | # the Initial Developer. All Rights Reserved.
8 | #
9 | # Contributor(s):
10 | # Mark Pilgrim - port to Python
11 | #
12 | # This library is free software; you can redistribute it and/or
13 | # modify it under the terms of the GNU Lesser General Public
14 | # License as published by the Free Software Foundation; either
15 | # version 2.1 of the License, or (at your option) any later version.
16 | #
17 | # This library is distributed in the hope that it will be useful,
18 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
19 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20 | # Lesser General Public License for more details.
21 | #
22 | # You should have received a copy of the GNU Lesser General Public
23 | # License along with this library; if not, write to the Free Software
24 | # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
25 | # 02110-1301 USA
26 | ######################### END LICENSE BLOCK #########################
27 |
28 | from . import constants
29 | from .charsetprober import CharSetProber
30 | from .codingstatemachine import CodingStateMachine
31 | from .mbcssm import UTF8SMModel
32 |
33 | ONE_CHAR_PROB = 0.5
34 |
35 |
36 | class UTF8Prober(CharSetProber):
37 | def __init__(self):
38 | CharSetProber.__init__(self)
39 | self._mCodingSM = CodingStateMachine(UTF8SMModel)
40 | self.reset()
41 |
42 | def reset(self):
43 | CharSetProber.reset(self)
44 | self._mCodingSM.reset()
45 | self._mNumOfMBChar = 0
46 |
47 | def get_charset_name(self):
48 | return "utf-8"
49 |
50 | def feed(self, aBuf):
51 | for c in aBuf:
52 | codingState = self._mCodingSM.next_state(c)
53 | if codingState == constants.eError:
54 | self._mState = constants.eNotMe
55 | break
56 | elif codingState == constants.eItsMe:
57 | self._mState = constants.eFoundIt
58 | break
59 | elif codingState == constants.eStart:
60 | if self._mCodingSM.get_current_charlen() >= 2:
61 | self._mNumOfMBChar += 1
62 |
63 | if self.get_state() == constants.eDetecting:
64 | if self.get_confidence() > constants.SHORTCUT_THRESHOLD:
65 | self._mState = constants.eFoundIt
66 |
67 | return self.get_state()
68 |
69 | def get_confidence(self):
70 | unlike = 0.99
71 | if self._mNumOfMBChar < 6:
72 | for i in range(0, self._mNumOfMBChar):
73 | unlike = unlike * ONE_CHAR_PROB
74 | return 1.0 - unlike
75 | else:
76 | return unlike
77 |
--------------------------------------------------------------------------------
/vendor/requests/packages/chardet/utf8prober.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/loveQt/wxpytest/c8923b2298a5f71aca4bcee656125dc219d45592/vendor/requests/packages/chardet/utf8prober.pyc
--------------------------------------------------------------------------------
/vendor/requests/packages/urllib3/__init__.py:
--------------------------------------------------------------------------------
1 | """
2 | urllib3 - Thread-safe connection pooling and re-using.
3 | """
4 |
5 | from __future__ import absolute_import
6 | import warnings
7 |
8 | from .connectionpool import (
9 | HTTPConnectionPool,
10 | HTTPSConnectionPool,
11 | connection_from_url
12 | )
13 |
14 | from . import exceptions
15 | from .filepost import encode_multipart_formdata
16 | from .poolmanager import PoolManager, ProxyManager, proxy_from_url
17 | from .response import HTTPResponse
18 | from .util.request import make_headers
19 | from .util.url import get_host
20 | from .util.timeout import Timeout
21 | from .util.retry import Retry
22 |
23 |
24 | # Set default logging handler to avoid "No handler found" warnings.
25 | import logging
26 | try: # Python 2.7+
27 | from logging import NullHandler
28 | except ImportError:
29 | class NullHandler(logging.Handler):
30 | def emit(self, record):
31 | pass
32 |
33 | __author__ = 'Andrey Petrov (andrey.petrov@shazow.net)'
34 | __license__ = 'MIT'
35 | __version__ = '1.15.1'
36 |
37 | __all__ = (
38 | 'HTTPConnectionPool',
39 | 'HTTPSConnectionPool',
40 | 'PoolManager',
41 | 'ProxyManager',
42 | 'HTTPResponse',
43 | 'Retry',
44 | 'Timeout',
45 | 'add_stderr_logger',
46 | 'connection_from_url',
47 | 'disable_warnings',
48 | 'encode_multipart_formdata',
49 | 'get_host',
50 | 'make_headers',
51 | 'proxy_from_url',
52 | )
53 |
54 | logging.getLogger(__name__).addHandler(NullHandler())
55 |
56 |
57 | def add_stderr_logger(level=logging.DEBUG):
58 | """
59 | Helper for quickly adding a StreamHandler to the logger. Useful for
60 | debugging.
61 |
62 | Returns the handler after adding it.
63 | """
64 | # This method needs to be in this __init__.py to get the __name__ correct
65 | # even if urllib3 is vendored within another package.
66 | logger = logging.getLogger(__name__)
67 | handler = logging.StreamHandler()
68 | handler.setFormatter(logging.Formatter('%(asctime)s %(levelname)s %(message)s'))
69 | logger.addHandler(handler)
70 | logger.setLevel(level)
71 | logger.debug('Added a stderr logging handler to logger: %s', __name__)
72 | return handler
73 |
74 | # ... Clean up.
75 | del NullHandler
76 |
77 |
78 | # All warning filters *must* be appended unless you're really certain that they
79 | # shouldn't be: otherwise, it's very hard for users to use most Python
80 | # mechanisms to silence them.
81 | # SecurityWarning's always go off by default.
82 | warnings.simplefilter('always', exceptions.SecurityWarning, append=True)
83 | # SubjectAltNameWarning's should go off once per host
84 | warnings.simplefilter('default', exceptions.SubjectAltNameWarning, append=True)
85 | # InsecurePlatformWarning's don't vary between requests, so we keep it default.
86 | warnings.simplefilter('default', exceptions.InsecurePlatformWarning,
87 | append=True)
88 | # SNIMissingWarnings should go off only once.
89 | warnings.simplefilter('default', exceptions.SNIMissingWarning, append=True)
90 |
91 |
92 | def disable_warnings(category=exceptions.HTTPWarning):
93 | """
94 | Helper for quickly disabling all urllib3 warnings.
95 | """
96 | warnings.simplefilter('ignore', category)
97 |
--------------------------------------------------------------------------------
/vendor/requests/packages/urllib3/__init__.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/loveQt/wxpytest/c8923b2298a5f71aca4bcee656125dc219d45592/vendor/requests/packages/urllib3/__init__.pyc
--------------------------------------------------------------------------------
/vendor/requests/packages/urllib3/_collections.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/loveQt/wxpytest/c8923b2298a5f71aca4bcee656125dc219d45592/vendor/requests/packages/urllib3/_collections.pyc
--------------------------------------------------------------------------------
/vendor/requests/packages/urllib3/connection.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/loveQt/wxpytest/c8923b2298a5f71aca4bcee656125dc219d45592/vendor/requests/packages/urllib3/connection.pyc
--------------------------------------------------------------------------------
/vendor/requests/packages/urllib3/connectionpool.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/loveQt/wxpytest/c8923b2298a5f71aca4bcee656125dc219d45592/vendor/requests/packages/urllib3/connectionpool.pyc
--------------------------------------------------------------------------------
/vendor/requests/packages/urllib3/contrib/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/loveQt/wxpytest/c8923b2298a5f71aca4bcee656125dc219d45592/vendor/requests/packages/urllib3/contrib/__init__.py
--------------------------------------------------------------------------------
/vendor/requests/packages/urllib3/contrib/__init__.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/loveQt/wxpytest/c8923b2298a5f71aca4bcee656125dc219d45592/vendor/requests/packages/urllib3/contrib/__init__.pyc
--------------------------------------------------------------------------------
/vendor/requests/packages/urllib3/contrib/appengine.py:
--------------------------------------------------------------------------------
1 | from __future__ import absolute_import
2 | import logging
3 | import os
4 | import warnings
5 |
6 | from ..exceptions import (
7 | HTTPError,
8 | HTTPWarning,
9 | MaxRetryError,
10 | ProtocolError,
11 | TimeoutError,
12 | SSLError
13 | )
14 |
15 | from ..packages.six import BytesIO
16 | from ..request import RequestMethods
17 | from ..response import HTTPResponse
18 | from ..util.timeout import Timeout
19 | from ..util.retry import Retry
20 |
21 | try:
22 | from google.appengine.api import urlfetch
23 | except ImportError:
24 | urlfetch = None
25 |
26 |
27 | log = logging.getLogger(__name__)
28 |
29 |
30 | class AppEnginePlatformWarning(HTTPWarning):
31 | pass
32 |
33 |
34 | class AppEnginePlatformError(HTTPError):
35 | pass
36 |
37 |
38 | class AppEngineManager(RequestMethods):
39 | """
40 | Connection manager for Google App Engine sandbox applications.
41 |
42 | This manager uses the URLFetch service directly instead of using the
43 | emulated httplib, and is subject to URLFetch limitations as described in
44 | the App Engine documentation here:
45 |
46 | https://cloud.google.com/appengine/docs/python/urlfetch
47 |
48 | Notably it will raise an AppEnginePlatformError if:
49 | * URLFetch is not available.
50 | * If you attempt to use this on GAEv2 (Managed VMs), as full socket
51 | support is available.
52 | * If a request size is more than 10 megabytes.
53 | * If a response size is more than 32 megabtyes.
54 | * If you use an unsupported request method such as OPTIONS.
55 |
56 | Beyond those cases, it will raise normal urllib3 errors.
57 | """
58 |
59 | def __init__(self, headers=None, retries=None, validate_certificate=True):
60 | if not urlfetch:
61 | raise AppEnginePlatformError(
62 | "URLFetch is not available in this environment.")
63 |
64 | if is_prod_appengine_mvms():
65 | raise AppEnginePlatformError(
66 | "Use normal urllib3.PoolManager instead of AppEngineManager"
67 | "on Managed VMs, as using URLFetch is not necessary in "
68 | "this environment.")
69 |
70 | warnings.warn(
71 | "urllib3 is using URLFetch on Google App Engine sandbox instead "
72 | "of sockets. To use sockets directly instead of URLFetch see "
73 | "https://urllib3.readthedocs.org/en/latest/contrib.html.",
74 | AppEnginePlatformWarning)
75 |
76 | RequestMethods.__init__(self, headers)
77 | self.validate_certificate = validate_certificate
78 |
79 | self.retries = retries or Retry.DEFAULT
80 |
81 | def __enter__(self):
82 | return self
83 |
84 | def __exit__(self, exc_type, exc_val, exc_tb):
85 | # Return False to re-raise any potential exceptions
86 | return False
87 |
88 | def urlopen(self, method, url, body=None, headers=None,
89 | retries=None, redirect=True, timeout=Timeout.DEFAULT_TIMEOUT,
90 | **response_kw):
91 |
92 | retries = self._get_retries(retries, redirect)
93 |
94 | try:
95 | response = urlfetch.fetch(
96 | url,
97 | payload=body,
98 | method=method,
99 | headers=headers or {},
100 | allow_truncated=False,
101 | follow_redirects=(
102 | redirect and
103 | retries.redirect != 0 and
104 | retries.total),
105 | deadline=self._get_absolute_timeout(timeout),
106 | validate_certificate=self.validate_certificate,
107 | )
108 | except urlfetch.DeadlineExceededError as e:
109 | raise TimeoutError(self, e)
110 |
111 | except urlfetch.InvalidURLError as e:
112 | if 'too large' in str(e):
113 | raise AppEnginePlatformError(
114 | "URLFetch request too large, URLFetch only "
115 | "supports requests up to 10mb in size.", e)
116 | raise ProtocolError(e)
117 |
118 | except urlfetch.DownloadError as e:
119 | if 'Too many redirects' in str(e):
120 | raise MaxRetryError(self, url, reason=e)
121 | raise ProtocolError(e)
122 |
123 | except urlfetch.ResponseTooLargeError as e:
124 | raise AppEnginePlatformError(
125 | "URLFetch response too large, URLFetch only supports"
126 | "responses up to 32mb in size.", e)
127 |
128 | except urlfetch.SSLCertificateError as e:
129 | raise SSLError(e)
130 |
131 | except urlfetch.InvalidMethodError as e:
132 | raise AppEnginePlatformError(
133 | "URLFetch does not support method: %s" % method, e)
134 |
135 | http_response = self._urlfetch_response_to_http_response(
136 | response, **response_kw)
137 |
138 | # Check for redirect response
139 | if (http_response.get_redirect_location() and
140 | retries.raise_on_redirect and redirect):
141 | raise MaxRetryError(self, url, "too many redirects")
142 |
143 | # Check if we should retry the HTTP response.
144 | if retries.is_forced_retry(method, status_code=http_response.status):
145 | retries = retries.increment(
146 | method, url, response=http_response, _pool=self)
147 | log.info("Forced retry: %s", url)
148 | retries.sleep()
149 | return self.urlopen(
150 | method, url,
151 | body=body, headers=headers,
152 | retries=retries, redirect=redirect,
153 | timeout=timeout, **response_kw)
154 |
155 | return http_response
156 |
157 | def _urlfetch_response_to_http_response(self, urlfetch_resp, **response_kw):
158 |
159 | if is_prod_appengine():
160 | # Production GAE handles deflate encoding automatically, but does
161 | # not remove the encoding header.
162 | content_encoding = urlfetch_resp.headers.get('content-encoding')
163 |
164 | if content_encoding == 'deflate':
165 | del urlfetch_resp.headers['content-encoding']
166 |
167 | transfer_encoding = urlfetch_resp.headers.get('transfer-encoding')
168 | # We have a full response's content,
169 | # so let's make sure we don't report ourselves as chunked data.
170 | if transfer_encoding == 'chunked':
171 | encodings = transfer_encoding.split(",")
172 | encodings.remove('chunked')
173 | urlfetch_resp.headers['transfer-encoding'] = ','.join(encodings)
174 |
175 | return HTTPResponse(
176 | # In order for decoding to work, we must present the content as
177 | # a file-like object.
178 | body=BytesIO(urlfetch_resp.content),
179 | headers=urlfetch_resp.headers,
180 | status=urlfetch_resp.status_code,
181 | **response_kw
182 | )
183 |
184 | def _get_absolute_timeout(self, timeout):
185 | if timeout is Timeout.DEFAULT_TIMEOUT:
186 | return 5 # 5s is the default timeout for URLFetch.
187 | if isinstance(timeout, Timeout):
188 | if timeout._read is not timeout._connect:
189 | warnings.warn(
190 | "URLFetch does not support granular timeout settings, "
191 | "reverting to total timeout.", AppEnginePlatformWarning)
192 | return timeout.total
193 | return timeout
194 |
195 | def _get_retries(self, retries, redirect):
196 | if not isinstance(retries, Retry):
197 | retries = Retry.from_int(
198 | retries, redirect=redirect, default=self.retries)
199 |
200 | if retries.connect or retries.read or retries.redirect:
201 | warnings.warn(
202 | "URLFetch only supports total retries and does not "
203 | "recognize connect, read, or redirect retry parameters.",
204 | AppEnginePlatformWarning)
205 |
206 | return retries
207 |
208 |
209 | def is_appengine():
210 | return (is_local_appengine() or
211 | is_prod_appengine() or
212 | is_prod_appengine_mvms())
213 |
214 |
215 | def is_appengine_sandbox():
216 | return is_appengine() and not is_prod_appengine_mvms()
217 |
218 |
219 | def is_local_appengine():
220 | return ('APPENGINE_RUNTIME' in os.environ and
221 | 'Development/' in os.environ['SERVER_SOFTWARE'])
222 |
223 |
224 | def is_prod_appengine():
225 | return ('APPENGINE_RUNTIME' in os.environ and
226 | 'Google App Engine/' in os.environ['SERVER_SOFTWARE'] and
227 | not is_prod_appengine_mvms())
228 |
229 |
230 | def is_prod_appengine_mvms():
231 | return os.environ.get('GAE_VM', False) == 'true'
232 |
--------------------------------------------------------------------------------
/vendor/requests/packages/urllib3/contrib/appengine.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/loveQt/wxpytest/c8923b2298a5f71aca4bcee656125dc219d45592/vendor/requests/packages/urllib3/contrib/appengine.pyc
--------------------------------------------------------------------------------
/vendor/requests/packages/urllib3/contrib/ntlmpool.py:
--------------------------------------------------------------------------------
1 | """
2 | NTLM authenticating pool, contributed by erikcederstran
3 |
4 | Issue #10, see: http://code.google.com/p/urllib3/issues/detail?id=10
5 | """
6 | from __future__ import absolute_import
7 |
8 | try:
9 | from http.client import HTTPSConnection
10 | except ImportError:
11 | from httplib import HTTPSConnection
12 | from logging import getLogger
13 | from ntlm import ntlm
14 |
15 | from urllib3 import HTTPSConnectionPool
16 |
17 |
18 | log = getLogger(__name__)
19 |
20 |
21 | class NTLMConnectionPool(HTTPSConnectionPool):
22 | """
23 | Implements an NTLM authentication version of an urllib3 connection pool
24 | """
25 |
26 | scheme = 'https'
27 |
28 | def __init__(self, user, pw, authurl, *args, **kwargs):
29 | """
30 | authurl is a random URL on the server that is protected by NTLM.
31 | user is the Windows user, probably in the DOMAIN\\username format.
32 | pw is the password for the user.
33 | """
34 | super(NTLMConnectionPool, self).__init__(*args, **kwargs)
35 | self.authurl = authurl
36 | self.rawuser = user
37 | user_parts = user.split('\\', 1)
38 | self.domain = user_parts[0].upper()
39 | self.user = user_parts[1]
40 | self.pw = pw
41 |
42 | def _new_conn(self):
43 | # Performs the NTLM handshake that secures the connection. The socket
44 | # must be kept open while requests are performed.
45 | self.num_connections += 1
46 | log.debug('Starting NTLM HTTPS connection no. %d: https://%s%s',
47 | self.num_connections, self.host, self.authurl)
48 |
49 | headers = {}
50 | headers['Connection'] = 'Keep-Alive'
51 | req_header = 'Authorization'
52 | resp_header = 'www-authenticate'
53 |
54 | conn = HTTPSConnection(host=self.host, port=self.port)
55 |
56 | # Send negotiation message
57 | headers[req_header] = (
58 | 'NTLM %s' % ntlm.create_NTLM_NEGOTIATE_MESSAGE(self.rawuser))
59 | log.debug('Request headers: %s', headers)
60 | conn.request('GET', self.authurl, None, headers)
61 | res = conn.getresponse()
62 | reshdr = dict(res.getheaders())
63 | log.debug('Response status: %s %s', res.status, res.reason)
64 | log.debug('Response headers: %s', reshdr)
65 | log.debug('Response data: %s [...]', res.read(100))
66 |
67 | # Remove the reference to the socket, so that it can not be closed by
68 | # the response object (we want to keep the socket open)
69 | res.fp = None
70 |
71 | # Server should respond with a challenge message
72 | auth_header_values = reshdr[resp_header].split(', ')
73 | auth_header_value = None
74 | for s in auth_header_values:
75 | if s[:5] == 'NTLM ':
76 | auth_header_value = s[5:]
77 | if auth_header_value is None:
78 | raise Exception('Unexpected %s response header: %s' %
79 | (resp_header, reshdr[resp_header]))
80 |
81 | # Send authentication message
82 | ServerChallenge, NegotiateFlags = \
83 | ntlm.parse_NTLM_CHALLENGE_MESSAGE(auth_header_value)
84 | auth_msg = ntlm.create_NTLM_AUTHENTICATE_MESSAGE(ServerChallenge,
85 | self.user,
86 | self.domain,
87 | self.pw,
88 | NegotiateFlags)
89 | headers[req_header] = 'NTLM %s' % auth_msg
90 | log.debug('Request headers: %s', headers)
91 | conn.request('GET', self.authurl, None, headers)
92 | res = conn.getresponse()
93 | log.debug('Response status: %s %s', res.status, res.reason)
94 | log.debug('Response headers: %s', dict(res.getheaders()))
95 | log.debug('Response data: %s [...]', res.read()[:100])
96 | if res.status != 200:
97 | if res.status == 401:
98 | raise Exception('Server rejected request: wrong '
99 | 'username or password')
100 | raise Exception('Wrong server response: %s %s' %
101 | (res.status, res.reason))
102 |
103 | res.fp = None
104 | log.debug('Connection established')
105 | return conn
106 |
107 | def urlopen(self, method, url, body=None, headers=None, retries=3,
108 | redirect=True, assert_same_host=True):
109 | if headers is None:
110 | headers = {}
111 | headers['Connection'] = 'Keep-Alive'
112 | return super(NTLMConnectionPool, self).urlopen(method, url, body,
113 | headers, retries,
114 | redirect,
115 | assert_same_host)
116 |
--------------------------------------------------------------------------------
/vendor/requests/packages/urllib3/contrib/ntlmpool.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/loveQt/wxpytest/c8923b2298a5f71aca4bcee656125dc219d45592/vendor/requests/packages/urllib3/contrib/ntlmpool.pyc
--------------------------------------------------------------------------------
/vendor/requests/packages/urllib3/contrib/pyopenssl.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/loveQt/wxpytest/c8923b2298a5f71aca4bcee656125dc219d45592/vendor/requests/packages/urllib3/contrib/pyopenssl.pyc
--------------------------------------------------------------------------------
/vendor/requests/packages/urllib3/contrib/socks.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | """
3 | SOCKS support for urllib3
4 | ~~~~~~~~~~~~~~~~~~~~~~~~~
5 |
6 | This contrib module contains provisional support for SOCKS proxies from within
7 | urllib3. This module supports SOCKS4 (specifically the SOCKS4A variant) and
8 | SOCKS5. To enable its functionality, either install PySocks or install this
9 | module with the ``socks`` extra.
10 |
11 | Known Limitations:
12 |
13 | - Currently PySocks does not support contacting remote websites via literal
14 | IPv6 addresses. Any such connection attempt will fail.
15 | - Currently PySocks does not support IPv6 connections to the SOCKS proxy. Any
16 | such connection attempt will fail.
17 | """
18 | from __future__ import absolute_import
19 |
20 | try:
21 | import socks
22 | except ImportError:
23 | import warnings
24 | from ..exceptions import DependencyWarning
25 |
26 | warnings.warn((
27 | 'SOCKS support in urllib3 requires the installation of optional '
28 | 'dependencies: specifically, PySocks. For more information, see '
29 | 'https://urllib3.readthedocs.org/en/latest/contrib.html#socks-proxies'
30 | ),
31 | DependencyWarning
32 | )
33 | raise
34 |
35 | from socket import error as SocketError, timeout as SocketTimeout
36 |
37 | from ..connection import (
38 | HTTPConnection, HTTPSConnection
39 | )
40 | from ..connectionpool import (
41 | HTTPConnectionPool, HTTPSConnectionPool
42 | )
43 | from ..exceptions import ConnectTimeoutError, NewConnectionError
44 | from ..poolmanager import PoolManager
45 | from ..util.url import parse_url
46 |
47 | try:
48 | import ssl
49 | except ImportError:
50 | ssl = None
51 |
52 |
53 | class SOCKSConnection(HTTPConnection):
54 | """
55 | A plain-text HTTP connection that connects via a SOCKS proxy.
56 | """
57 | def __init__(self, *args, **kwargs):
58 | self._socks_options = kwargs.pop('_socks_options')
59 | super(SOCKSConnection, self).__init__(*args, **kwargs)
60 |
61 | def _new_conn(self):
62 | """
63 | Establish a new connection via the SOCKS proxy.
64 | """
65 | extra_kw = {}
66 | if self.source_address:
67 | extra_kw['source_address'] = self.source_address
68 |
69 | if self.socket_options:
70 | extra_kw['socket_options'] = self.socket_options
71 |
72 | try:
73 | conn = socks.create_connection(
74 | (self.host, self.port),
75 | proxy_type=self._socks_options['socks_version'],
76 | proxy_addr=self._socks_options['proxy_host'],
77 | proxy_port=self._socks_options['proxy_port'],
78 | proxy_username=self._socks_options['username'],
79 | proxy_password=self._socks_options['password'],
80 | timeout=self.timeout,
81 | **extra_kw
82 | )
83 |
84 | except SocketTimeout as e:
85 | raise ConnectTimeoutError(
86 | self, "Connection to %s timed out. (connect timeout=%s)" %
87 | (self.host, self.timeout))
88 |
89 | except socks.ProxyError as e:
90 | # This is fragile as hell, but it seems to be the only way to raise
91 | # useful errors here.
92 | if e.socket_err:
93 | error = e.socket_err
94 | if isinstance(error, SocketTimeout):
95 | raise ConnectTimeoutError(
96 | self,
97 | "Connection to %s timed out. (connect timeout=%s)" %
98 | (self.host, self.timeout)
99 | )
100 | else:
101 | raise NewConnectionError(
102 | self,
103 | "Failed to establish a new connection: %s" % error
104 | )
105 | else:
106 | raise NewConnectionError(
107 | self,
108 | "Failed to establish a new connection: %s" % e
109 | )
110 |
111 | except SocketError as e: # Defensive: PySocks should catch all these.
112 | raise NewConnectionError(
113 | self, "Failed to establish a new connection: %s" % e)
114 |
115 | return conn
116 |
117 |
118 | # We don't need to duplicate the Verified/Unverified distinction from
119 | # urllib3/connection.py here because the HTTPSConnection will already have been
120 | # correctly set to either the Verified or Unverified form by that module. This
121 | # means the SOCKSHTTPSConnection will automatically be the correct type.
122 | class SOCKSHTTPSConnection(SOCKSConnection, HTTPSConnection):
123 | pass
124 |
125 |
126 | class SOCKSHTTPConnectionPool(HTTPConnectionPool):
127 | ConnectionCls = SOCKSConnection
128 |
129 |
130 | class SOCKSHTTPSConnectionPool(HTTPSConnectionPool):
131 | ConnectionCls = SOCKSHTTPSConnection
132 |
133 |
134 | class SOCKSProxyManager(PoolManager):
135 | """
136 | A version of the urllib3 ProxyManager that routes connections via the
137 | defined SOCKS proxy.
138 | """
139 | pool_classes_by_scheme = {
140 | 'http': SOCKSHTTPConnectionPool,
141 | 'https': SOCKSHTTPSConnectionPool,
142 | }
143 |
144 | def __init__(self, proxy_url, username=None, password=None,
145 | num_pools=10, headers=None, **connection_pool_kw):
146 | parsed = parse_url(proxy_url)
147 |
148 | if parsed.scheme == 'socks5':
149 | socks_version = socks.PROXY_TYPE_SOCKS5
150 | elif parsed.scheme == 'socks4':
151 | socks_version = socks.PROXY_TYPE_SOCKS4
152 | else:
153 | raise ValueError(
154 | "Unable to determine SOCKS version from %s" % proxy_url
155 | )
156 |
157 | self.proxy_url = proxy_url
158 |
159 | socks_options = {
160 | 'socks_version': socks_version,
161 | 'proxy_host': parsed.host,
162 | 'proxy_port': parsed.port,
163 | 'username': username,
164 | 'password': password,
165 | }
166 | connection_pool_kw['_socks_options'] = socks_options
167 |
168 | super(SOCKSProxyManager, self).__init__(
169 | num_pools, headers, **connection_pool_kw
170 | )
171 |
172 | self.pool_classes_by_scheme = SOCKSProxyManager.pool_classes_by_scheme
173 |
--------------------------------------------------------------------------------
/vendor/requests/packages/urllib3/contrib/socks.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/loveQt/wxpytest/c8923b2298a5f71aca4bcee656125dc219d45592/vendor/requests/packages/urllib3/contrib/socks.pyc
--------------------------------------------------------------------------------
/vendor/requests/packages/urllib3/exceptions.py:
--------------------------------------------------------------------------------
1 | from __future__ import absolute_import
2 | # Base Exceptions
3 |
4 |
5 | class HTTPError(Exception):
6 | "Base exception used by this module."
7 | pass
8 |
9 |
10 | class HTTPWarning(Warning):
11 | "Base warning used by this module."
12 | pass
13 |
14 |
15 | class PoolError(HTTPError):
16 | "Base exception for errors caused within a pool."
17 | def __init__(self, pool, message):
18 | self.pool = pool
19 | HTTPError.__init__(self, "%s: %s" % (pool, message))
20 |
21 | def __reduce__(self):
22 | # For pickling purposes.
23 | return self.__class__, (None, None)
24 |
25 |
26 | class RequestError(PoolError):
27 | "Base exception for PoolErrors that have associated URLs."
28 | def __init__(self, pool, url, message):
29 | self.url = url
30 | PoolError.__init__(self, pool, message)
31 |
32 | def __reduce__(self):
33 | # For pickling purposes.
34 | return self.__class__, (None, self.url, None)
35 |
36 |
37 | class SSLError(HTTPError):
38 | "Raised when SSL certificate fails in an HTTPS connection."
39 | pass
40 |
41 |
42 | class ProxyError(HTTPError):
43 | "Raised when the connection to a proxy fails."
44 | pass
45 |
46 |
47 | class DecodeError(HTTPError):
48 | "Raised when automatic decoding based on Content-Type fails."
49 | pass
50 |
51 |
52 | class ProtocolError(HTTPError):
53 | "Raised when something unexpected happens mid-request/response."
54 | pass
55 |
56 |
57 | #: Renamed to ProtocolError but aliased for backwards compatibility.
58 | ConnectionError = ProtocolError
59 |
60 |
61 | # Leaf Exceptions
62 |
63 | class MaxRetryError(RequestError):
64 | """Raised when the maximum number of retries is exceeded.
65 |
66 | :param pool: The connection pool
67 | :type pool: :class:`~urllib3.connectionpool.HTTPConnectionPool`
68 | :param string url: The requested Url
69 | :param exceptions.Exception reason: The underlying error
70 |
71 | """
72 |
73 | def __init__(self, pool, url, reason=None):
74 | self.reason = reason
75 |
76 | message = "Max retries exceeded with url: %s (Caused by %r)" % (
77 | url, reason)
78 |
79 | RequestError.__init__(self, pool, url, message)
80 |
81 |
82 | class HostChangedError(RequestError):
83 | "Raised when an existing pool gets a request for a foreign host."
84 |
85 | def __init__(self, pool, url, retries=3):
86 | message = "Tried to open a foreign host with url: %s" % url
87 | RequestError.__init__(self, pool, url, message)
88 | self.retries = retries
89 |
90 |
91 | class TimeoutStateError(HTTPError):
92 | """ Raised when passing an invalid state to a timeout """
93 | pass
94 |
95 |
96 | class TimeoutError(HTTPError):
97 | """ Raised when a socket timeout error occurs.
98 |
99 | Catching this error will catch both :exc:`ReadTimeoutErrors
100 | ` and :exc:`ConnectTimeoutErrors `.
101 | """
102 | pass
103 |
104 |
105 | class ReadTimeoutError(TimeoutError, RequestError):
106 | "Raised when a socket timeout occurs while receiving data from a server"
107 | pass
108 |
109 |
110 | # This timeout error does not have a URL attached and needs to inherit from the
111 | # base HTTPError
112 | class ConnectTimeoutError(TimeoutError):
113 | "Raised when a socket timeout occurs while connecting to a server"
114 | pass
115 |
116 |
117 | class NewConnectionError(ConnectTimeoutError, PoolError):
118 | "Raised when we fail to establish a new connection. Usually ECONNREFUSED."
119 | pass
120 |
121 |
122 | class EmptyPoolError(PoolError):
123 | "Raised when a pool runs out of connections and no more are allowed."
124 | pass
125 |
126 |
127 | class ClosedPoolError(PoolError):
128 | "Raised when a request enters a pool after the pool has been closed."
129 | pass
130 |
131 |
132 | class LocationValueError(ValueError, HTTPError):
133 | "Raised when there is something wrong with a given URL input."
134 | pass
135 |
136 |
137 | class LocationParseError(LocationValueError):
138 | "Raised when get_host or similar fails to parse the URL input."
139 |
140 | def __init__(self, location):
141 | message = "Failed to parse: %s" % location
142 | HTTPError.__init__(self, message)
143 |
144 | self.location = location
145 |
146 |
147 | class ResponseError(HTTPError):
148 | "Used as a container for an error reason supplied in a MaxRetryError."
149 | GENERIC_ERROR = 'too many error responses'
150 | SPECIFIC_ERROR = 'too many {status_code} error responses'
151 |
152 |
153 | class SecurityWarning(HTTPWarning):
154 | "Warned when perfoming security reducing actions"
155 | pass
156 |
157 |
158 | class SubjectAltNameWarning(SecurityWarning):
159 | "Warned when connecting to a host with a certificate missing a SAN."
160 | pass
161 |
162 |
163 | class InsecureRequestWarning(SecurityWarning):
164 | "Warned when making an unverified HTTPS request."
165 | pass
166 |
167 |
168 | class SystemTimeWarning(SecurityWarning):
169 | "Warned when system time is suspected to be wrong"
170 | pass
171 |
172 |
173 | class InsecurePlatformWarning(SecurityWarning):
174 | "Warned when certain SSL configuration is not available on a platform."
175 | pass
176 |
177 |
178 | class SNIMissingWarning(HTTPWarning):
179 | "Warned when making a HTTPS request without SNI available."
180 | pass
181 |
182 |
183 | class DependencyWarning(HTTPWarning):
184 | """
185 | Warned when an attempt is made to import a module with missing optional
186 | dependencies.
187 | """
188 | pass
189 |
190 |
191 | class ResponseNotChunked(ProtocolError, ValueError):
192 | "Response needs to be chunked in order to read it as chunks."
193 | pass
194 |
195 |
196 | class ProxySchemeUnknown(AssertionError, ValueError):
197 | "ProxyManager does not support the supplied scheme"
198 | # TODO(t-8ch): Stop inheriting from AssertionError in v2.0.
199 |
200 | def __init__(self, scheme):
201 | message = "Not supported proxy scheme %s" % scheme
202 | super(ProxySchemeUnknown, self).__init__(message)
203 |
204 |
205 | class HeaderParsingError(HTTPError):
206 | "Raised by assert_header_parsing, but we convert it to a log.warning statement."
207 | def __init__(self, defects, unparsed_data):
208 | message = '%s, unparsed data: %r' % (defects or 'Unknown', unparsed_data)
209 | super(HeaderParsingError, self).__init__(message)
210 |
--------------------------------------------------------------------------------
/vendor/requests/packages/urllib3/exceptions.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/loveQt/wxpytest/c8923b2298a5f71aca4bcee656125dc219d45592/vendor/requests/packages/urllib3/exceptions.pyc
--------------------------------------------------------------------------------
/vendor/requests/packages/urllib3/fields.py:
--------------------------------------------------------------------------------
1 | from __future__ import absolute_import
2 | import email.utils
3 | import mimetypes
4 |
5 | from .packages import six
6 |
7 |
8 | def guess_content_type(filename, default='application/octet-stream'):
9 | """
10 | Guess the "Content-Type" of a file.
11 |
12 | :param filename:
13 | The filename to guess the "Content-Type" of using :mod:`mimetypes`.
14 | :param default:
15 | If no "Content-Type" can be guessed, default to `default`.
16 | """
17 | if filename:
18 | return mimetypes.guess_type(filename)[0] or default
19 | return default
20 |
21 |
22 | def format_header_param(name, value):
23 | """
24 | Helper function to format and quote a single header parameter.
25 |
26 | Particularly useful for header parameters which might contain
27 | non-ASCII values, like file names. This follows RFC 2231, as
28 | suggested by RFC 2388 Section 4.4.
29 |
30 | :param name:
31 | The name of the parameter, a string expected to be ASCII only.
32 | :param value:
33 | The value of the parameter, provided as a unicode string.
34 | """
35 | if not any(ch in value for ch in '"\\\r\n'):
36 | result = '%s="%s"' % (name, value)
37 | try:
38 | result.encode('ascii')
39 | except (UnicodeEncodeError, UnicodeDecodeError):
40 | pass
41 | else:
42 | return result
43 | if not six.PY3 and isinstance(value, six.text_type): # Python 2:
44 | value = value.encode('utf-8')
45 | value = email.utils.encode_rfc2231(value, 'utf-8')
46 | value = '%s*=%s' % (name, value)
47 | return value
48 |
49 |
50 | class RequestField(object):
51 | """
52 | A data container for request body parameters.
53 |
54 | :param name:
55 | The name of this request field.
56 | :param data:
57 | The data/value body.
58 | :param filename:
59 | An optional filename of the request field.
60 | :param headers:
61 | An optional dict-like object of headers to initially use for the field.
62 | """
63 | def __init__(self, name, data, filename=None, headers=None):
64 | self._name = name
65 | self._filename = filename
66 | self.data = data
67 | self.headers = {}
68 | if headers:
69 | self.headers = dict(headers)
70 |
71 | @classmethod
72 | def from_tuples(cls, fieldname, value):
73 | """
74 | A :class:`~urllib3.fields.RequestField` factory from old-style tuple parameters.
75 |
76 | Supports constructing :class:`~urllib3.fields.RequestField` from
77 | parameter of key/value strings AND key/filetuple. A filetuple is a
78 | (filename, data, MIME type) tuple where the MIME type is optional.
79 | For example::
80 |
81 | 'foo': 'bar',
82 | 'fakefile': ('foofile.txt', 'contents of foofile'),
83 | 'realfile': ('barfile.txt', open('realfile').read()),
84 | 'typedfile': ('bazfile.bin', open('bazfile').read(), 'image/jpeg'),
85 | 'nonamefile': 'contents of nonamefile field',
86 |
87 | Field names and filenames must be unicode.
88 | """
89 | if isinstance(value, tuple):
90 | if len(value) == 3:
91 | filename, data, content_type = value
92 | else:
93 | filename, data = value
94 | content_type = guess_content_type(filename)
95 | else:
96 | filename = None
97 | content_type = None
98 | data = value
99 |
100 | request_param = cls(fieldname, data, filename=filename)
101 | request_param.make_multipart(content_type=content_type)
102 |
103 | return request_param
104 |
105 | def _render_part(self, name, value):
106 | """
107 | Overridable helper function to format a single header parameter.
108 |
109 | :param name:
110 | The name of the parameter, a string expected to be ASCII only.
111 | :param value:
112 | The value of the parameter, provided as a unicode string.
113 | """
114 | return format_header_param(name, value)
115 |
116 | def _render_parts(self, header_parts):
117 | """
118 | Helper function to format and quote a single header.
119 |
120 | Useful for single headers that are composed of multiple items. E.g.,
121 | 'Content-Disposition' fields.
122 |
123 | :param header_parts:
124 | A sequence of (k, v) typles or a :class:`dict` of (k, v) to format
125 | as `k1="v1"; k2="v2"; ...`.
126 | """
127 | parts = []
128 | iterable = header_parts
129 | if isinstance(header_parts, dict):
130 | iterable = header_parts.items()
131 |
132 | for name, value in iterable:
133 | if value:
134 | parts.append(self._render_part(name, value))
135 |
136 | return '; '.join(parts)
137 |
138 | def render_headers(self):
139 | """
140 | Renders the headers for this request field.
141 | """
142 | lines = []
143 |
144 | sort_keys = ['Content-Disposition', 'Content-Type', 'Content-Location']
145 | for sort_key in sort_keys:
146 | if self.headers.get(sort_key, False):
147 | lines.append('%s: %s' % (sort_key, self.headers[sort_key]))
148 |
149 | for header_name, header_value in self.headers.items():
150 | if header_name not in sort_keys:
151 | if header_value:
152 | lines.append('%s: %s' % (header_name, header_value))
153 |
154 | lines.append('\r\n')
155 | return '\r\n'.join(lines)
156 |
157 | def make_multipart(self, content_disposition=None, content_type=None,
158 | content_location=None):
159 | """
160 | Makes this request field into a multipart request field.
161 |
162 | This method overrides "Content-Disposition", "Content-Type" and
163 | "Content-Location" headers to the request parameter.
164 |
165 | :param content_type:
166 | The 'Content-Type' of the request body.
167 | :param content_location:
168 | The 'Content-Location' of the request body.
169 |
170 | """
171 | self.headers['Content-Disposition'] = content_disposition or 'form-data'
172 | self.headers['Content-Disposition'] += '; '.join([
173 | '', self._render_parts(
174 | (('name', self._name), ('filename', self._filename))
175 | )
176 | ])
177 | self.headers['Content-Type'] = content_type
178 | self.headers['Content-Location'] = content_location
179 |
--------------------------------------------------------------------------------
/vendor/requests/packages/urllib3/fields.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/loveQt/wxpytest/c8923b2298a5f71aca4bcee656125dc219d45592/vendor/requests/packages/urllib3/fields.pyc
--------------------------------------------------------------------------------
/vendor/requests/packages/urllib3/filepost.py:
--------------------------------------------------------------------------------
1 | from __future__ import absolute_import
2 | import codecs
3 |
4 | from uuid import uuid4
5 | from io import BytesIO
6 |
7 | from .packages import six
8 | from .packages.six import b
9 | from .fields import RequestField
10 |
11 | writer = codecs.lookup('utf-8')[3]
12 |
13 |
14 | def choose_boundary():
15 | """
16 | Our embarassingly-simple replacement for mimetools.choose_boundary.
17 | """
18 | return uuid4().hex
19 |
20 |
21 | def iter_field_objects(fields):
22 | """
23 | Iterate over fields.
24 |
25 | Supports list of (k, v) tuples and dicts, and lists of
26 | :class:`~urllib3.fields.RequestField`.
27 |
28 | """
29 | if isinstance(fields, dict):
30 | i = six.iteritems(fields)
31 | else:
32 | i = iter(fields)
33 |
34 | for field in i:
35 | if isinstance(field, RequestField):
36 | yield field
37 | else:
38 | yield RequestField.from_tuples(*field)
39 |
40 |
41 | def iter_fields(fields):
42 | """
43 | .. deprecated:: 1.6
44 |
45 | Iterate over fields.
46 |
47 | The addition of :class:`~urllib3.fields.RequestField` makes this function
48 | obsolete. Instead, use :func:`iter_field_objects`, which returns
49 | :class:`~urllib3.fields.RequestField` objects.
50 |
51 | Supports list of (k, v) tuples and dicts.
52 | """
53 | if isinstance(fields, dict):
54 | return ((k, v) for k, v in six.iteritems(fields))
55 |
56 | return ((k, v) for k, v in fields)
57 |
58 |
59 | def encode_multipart_formdata(fields, boundary=None):
60 | """
61 | Encode a dictionary of ``fields`` using the multipart/form-data MIME format.
62 |
63 | :param fields:
64 | Dictionary of fields or list of (key, :class:`~urllib3.fields.RequestField`).
65 |
66 | :param boundary:
67 | If not specified, then a random boundary will be generated using
68 | :func:`mimetools.choose_boundary`.
69 | """
70 | body = BytesIO()
71 | if boundary is None:
72 | boundary = choose_boundary()
73 |
74 | for field in iter_field_objects(fields):
75 | body.write(b('--%s\r\n' % (boundary)))
76 |
77 | writer(body).write(field.render_headers())
78 | data = field.data
79 |
80 | if isinstance(data, int):
81 | data = str(data) # Backwards compatibility
82 |
83 | if isinstance(data, six.text_type):
84 | writer(body).write(data)
85 | else:
86 | body.write(data)
87 |
88 | body.write(b'\r\n')
89 |
90 | body.write(b('--%s--\r\n' % (boundary)))
91 |
92 | content_type = str('multipart/form-data; boundary=%s' % boundary)
93 |
94 | return body.getvalue(), content_type
95 |
--------------------------------------------------------------------------------
/vendor/requests/packages/urllib3/filepost.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/loveQt/wxpytest/c8923b2298a5f71aca4bcee656125dc219d45592/vendor/requests/packages/urllib3/filepost.pyc
--------------------------------------------------------------------------------
/vendor/requests/packages/urllib3/packages/__init__.py:
--------------------------------------------------------------------------------
1 | from __future__ import absolute_import
2 |
3 | from . import ssl_match_hostname
4 |
5 | __all__ = ('ssl_match_hostname', )
6 |
--------------------------------------------------------------------------------
/vendor/requests/packages/urllib3/packages/__init__.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/loveQt/wxpytest/c8923b2298a5f71aca4bcee656125dc219d45592/vendor/requests/packages/urllib3/packages/__init__.pyc
--------------------------------------------------------------------------------
/vendor/requests/packages/urllib3/packages/ordered_dict.py:
--------------------------------------------------------------------------------
1 | # Backport of OrderedDict() class that runs on Python 2.4, 2.5, 2.6, 2.7 and pypy.
2 | # Passes Python2.7's test suite and incorporates all the latest updates.
3 | # Copyright 2009 Raymond Hettinger, released under the MIT License.
4 | # http://code.activestate.com/recipes/576693/
5 | try:
6 | from thread import get_ident as _get_ident
7 | except ImportError:
8 | from dummy_thread import get_ident as _get_ident
9 |
10 | try:
11 | from _abcoll import KeysView, ValuesView, ItemsView
12 | except ImportError:
13 | pass
14 |
15 |
16 | class OrderedDict(dict):
17 | 'Dictionary that remembers insertion order'
18 | # An inherited dict maps keys to values.
19 | # The inherited dict provides __getitem__, __len__, __contains__, and get.
20 | # The remaining methods are order-aware.
21 | # Big-O running times for all methods are the same as for regular dictionaries.
22 |
23 | # The internal self.__map dictionary maps keys to links in a doubly linked list.
24 | # The circular doubly linked list starts and ends with a sentinel element.
25 | # The sentinel element never gets deleted (this simplifies the algorithm).
26 | # Each link is stored as a list of length three: [PREV, NEXT, KEY].
27 |
28 | def __init__(self, *args, **kwds):
29 | '''Initialize an ordered dictionary. Signature is the same as for
30 | regular dictionaries, but keyword arguments are not recommended
31 | because their insertion order is arbitrary.
32 |
33 | '''
34 | if len(args) > 1:
35 | raise TypeError('expected at most 1 arguments, got %d' % len(args))
36 | try:
37 | self.__root
38 | except AttributeError:
39 | self.__root = root = [] # sentinel node
40 | root[:] = [root, root, None]
41 | self.__map = {}
42 | self.__update(*args, **kwds)
43 |
44 | def __setitem__(self, key, value, dict_setitem=dict.__setitem__):
45 | 'od.__setitem__(i, y) <==> od[i]=y'
46 | # Setting a new item creates a new link which goes at the end of the linked
47 | # list, and the inherited dictionary is updated with the new key/value pair.
48 | if key not in self:
49 | root = self.__root
50 | last = root[0]
51 | last[1] = root[0] = self.__map[key] = [last, root, key]
52 | dict_setitem(self, key, value)
53 |
54 | def __delitem__(self, key, dict_delitem=dict.__delitem__):
55 | 'od.__delitem__(y) <==> del od[y]'
56 | # Deleting an existing item uses self.__map to find the link which is
57 | # then removed by updating the links in the predecessor and successor nodes.
58 | dict_delitem(self, key)
59 | link_prev, link_next, key = self.__map.pop(key)
60 | link_prev[1] = link_next
61 | link_next[0] = link_prev
62 |
63 | def __iter__(self):
64 | 'od.__iter__() <==> iter(od)'
65 | root = self.__root
66 | curr = root[1]
67 | while curr is not root:
68 | yield curr[2]
69 | curr = curr[1]
70 |
71 | def __reversed__(self):
72 | 'od.__reversed__() <==> reversed(od)'
73 | root = self.__root
74 | curr = root[0]
75 | while curr is not root:
76 | yield curr[2]
77 | curr = curr[0]
78 |
79 | def clear(self):
80 | 'od.clear() -> None. Remove all items from od.'
81 | try:
82 | for node in self.__map.itervalues():
83 | del node[:]
84 | root = self.__root
85 | root[:] = [root, root, None]
86 | self.__map.clear()
87 | except AttributeError:
88 | pass
89 | dict.clear(self)
90 |
91 | def popitem(self, last=True):
92 | '''od.popitem() -> (k, v), return and remove a (key, value) pair.
93 | Pairs are returned in LIFO order if last is true or FIFO order if false.
94 |
95 | '''
96 | if not self:
97 | raise KeyError('dictionary is empty')
98 | root = self.__root
99 | if last:
100 | link = root[0]
101 | link_prev = link[0]
102 | link_prev[1] = root
103 | root[0] = link_prev
104 | else:
105 | link = root[1]
106 | link_next = link[1]
107 | root[1] = link_next
108 | link_next[0] = root
109 | key = link[2]
110 | del self.__map[key]
111 | value = dict.pop(self, key)
112 | return key, value
113 |
114 | # -- the following methods do not depend on the internal structure --
115 |
116 | def keys(self):
117 | 'od.keys() -> list of keys in od'
118 | return list(self)
119 |
120 | def values(self):
121 | 'od.values() -> list of values in od'
122 | return [self[key] for key in self]
123 |
124 | def items(self):
125 | 'od.items() -> list of (key, value) pairs in od'
126 | return [(key, self[key]) for key in self]
127 |
128 | def iterkeys(self):
129 | 'od.iterkeys() -> an iterator over the keys in od'
130 | return iter(self)
131 |
132 | def itervalues(self):
133 | 'od.itervalues -> an iterator over the values in od'
134 | for k in self:
135 | yield self[k]
136 |
137 | def iteritems(self):
138 | 'od.iteritems -> an iterator over the (key, value) items in od'
139 | for k in self:
140 | yield (k, self[k])
141 |
142 | def update(*args, **kwds):
143 | '''od.update(E, **F) -> None. Update od from dict/iterable E and F.
144 |
145 | If E is a dict instance, does: for k in E: od[k] = E[k]
146 | If E has a .keys() method, does: for k in E.keys(): od[k] = E[k]
147 | Or if E is an iterable of items, does: for k, v in E: od[k] = v
148 | In either case, this is followed by: for k, v in F.items(): od[k] = v
149 |
150 | '''
151 | if len(args) > 2:
152 | raise TypeError('update() takes at most 2 positional '
153 | 'arguments (%d given)' % (len(args),))
154 | elif not args:
155 | raise TypeError('update() takes at least 1 argument (0 given)')
156 | self = args[0]
157 | # Make progressively weaker assumptions about "other"
158 | other = ()
159 | if len(args) == 2:
160 | other = args[1]
161 | if isinstance(other, dict):
162 | for key in other:
163 | self[key] = other[key]
164 | elif hasattr(other, 'keys'):
165 | for key in other.keys():
166 | self[key] = other[key]
167 | else:
168 | for key, value in other:
169 | self[key] = value
170 | for key, value in kwds.items():
171 | self[key] = value
172 |
173 | __update = update # let subclasses override update without breaking __init__
174 |
175 | __marker = object()
176 |
177 | def pop(self, key, default=__marker):
178 | '''od.pop(k[,d]) -> v, remove specified key and return the corresponding value.
179 | If key is not found, d is returned if given, otherwise KeyError is raised.
180 |
181 | '''
182 | if key in self:
183 | result = self[key]
184 | del self[key]
185 | return result
186 | if default is self.__marker:
187 | raise KeyError(key)
188 | return default
189 |
190 | def setdefault(self, key, default=None):
191 | 'od.setdefault(k[,d]) -> od.get(k,d), also set od[k]=d if k not in od'
192 | if key in self:
193 | return self[key]
194 | self[key] = default
195 | return default
196 |
197 | def __repr__(self, _repr_running={}):
198 | 'od.__repr__() <==> repr(od)'
199 | call_key = id(self), _get_ident()
200 | if call_key in _repr_running:
201 | return '...'
202 | _repr_running[call_key] = 1
203 | try:
204 | if not self:
205 | return '%s()' % (self.__class__.__name__,)
206 | return '%s(%r)' % (self.__class__.__name__, self.items())
207 | finally:
208 | del _repr_running[call_key]
209 |
210 | def __reduce__(self):
211 | 'Return state information for pickling'
212 | items = [[k, self[k]] for k in self]
213 | inst_dict = vars(self).copy()
214 | for k in vars(OrderedDict()):
215 | inst_dict.pop(k, None)
216 | if inst_dict:
217 | return (self.__class__, (items,), inst_dict)
218 | return self.__class__, (items,)
219 |
220 | def copy(self):
221 | 'od.copy() -> a shallow copy of od'
222 | return self.__class__(self)
223 |
224 | @classmethod
225 | def fromkeys(cls, iterable, value=None):
226 | '''OD.fromkeys(S[, v]) -> New ordered dictionary with keys from S
227 | and values equal to v (which defaults to None).
228 |
229 | '''
230 | d = cls()
231 | for key in iterable:
232 | d[key] = value
233 | return d
234 |
235 | def __eq__(self, other):
236 | '''od.__eq__(y) <==> od==y. Comparison to another OD is order-sensitive
237 | while comparison to a regular mapping is order-insensitive.
238 |
239 | '''
240 | if isinstance(other, OrderedDict):
241 | return len(self)==len(other) and self.items() == other.items()
242 | return dict.__eq__(self, other)
243 |
244 | def __ne__(self, other):
245 | return not self == other
246 |
247 | # -- the following methods are only used in Python 2.7 --
248 |
249 | def viewkeys(self):
250 | "od.viewkeys() -> a set-like object providing a view on od's keys"
251 | return KeysView(self)
252 |
253 | def viewvalues(self):
254 | "od.viewvalues() -> an object providing a view on od's values"
255 | return ValuesView(self)
256 |
257 | def viewitems(self):
258 | "od.viewitems() -> a set-like object providing a view on od's items"
259 | return ItemsView(self)
260 |
--------------------------------------------------------------------------------
/vendor/requests/packages/urllib3/packages/ordered_dict.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/loveQt/wxpytest/c8923b2298a5f71aca4bcee656125dc219d45592/vendor/requests/packages/urllib3/packages/ordered_dict.pyc
--------------------------------------------------------------------------------
/vendor/requests/packages/urllib3/packages/six.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/loveQt/wxpytest/c8923b2298a5f71aca4bcee656125dc219d45592/vendor/requests/packages/urllib3/packages/six.pyc
--------------------------------------------------------------------------------
/vendor/requests/packages/urllib3/packages/ssl_match_hostname/__init__.py:
--------------------------------------------------------------------------------
1 | try:
2 | # Python 3.2+
3 | from ssl import CertificateError, match_hostname
4 | except ImportError:
5 | try:
6 | # Backport of the function from a pypi module
7 | from backports.ssl_match_hostname import CertificateError, match_hostname
8 | except ImportError:
9 | # Our vendored copy
10 | from ._implementation import CertificateError, match_hostname
11 |
12 | # Not needed, but documenting what we provide.
13 | __all__ = ('CertificateError', 'match_hostname')
14 |
--------------------------------------------------------------------------------
/vendor/requests/packages/urllib3/packages/ssl_match_hostname/__init__.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/loveQt/wxpytest/c8923b2298a5f71aca4bcee656125dc219d45592/vendor/requests/packages/urllib3/packages/ssl_match_hostname/__init__.pyc
--------------------------------------------------------------------------------
/vendor/requests/packages/urllib3/packages/ssl_match_hostname/_implementation.py:
--------------------------------------------------------------------------------
1 | """The match_hostname() function from Python 3.3.3, essential when using SSL."""
2 |
3 | # Note: This file is under the PSF license as the code comes from the python
4 | # stdlib. http://docs.python.org/3/license.html
5 |
6 | import re
7 |
8 | __version__ = '3.4.0.2'
9 |
10 | class CertificateError(ValueError):
11 | pass
12 |
13 |
14 | def _dnsname_match(dn, hostname, max_wildcards=1):
15 | """Matching according to RFC 6125, section 6.4.3
16 |
17 | http://tools.ietf.org/html/rfc6125#section-6.4.3
18 | """
19 | pats = []
20 | if not dn:
21 | return False
22 |
23 | # Ported from python3-syntax:
24 | # leftmost, *remainder = dn.split(r'.')
25 | parts = dn.split(r'.')
26 | leftmost = parts[0]
27 | remainder = parts[1:]
28 |
29 | wildcards = leftmost.count('*')
30 | if wildcards > max_wildcards:
31 | # Issue #17980: avoid denials of service by refusing more
32 | # than one wildcard per fragment. A survey of established
33 | # policy among SSL implementations showed it to be a
34 | # reasonable choice.
35 | raise CertificateError(
36 | "too many wildcards in certificate DNS name: " + repr(dn))
37 |
38 | # speed up common case w/o wildcards
39 | if not wildcards:
40 | return dn.lower() == hostname.lower()
41 |
42 | # RFC 6125, section 6.4.3, subitem 1.
43 | # The client SHOULD NOT attempt to match a presented identifier in which
44 | # the wildcard character comprises a label other than the left-most label.
45 | if leftmost == '*':
46 | # When '*' is a fragment by itself, it matches a non-empty dotless
47 | # fragment.
48 | pats.append('[^.]+')
49 | elif leftmost.startswith('xn--') or hostname.startswith('xn--'):
50 | # RFC 6125, section 6.4.3, subitem 3.
51 | # The client SHOULD NOT attempt to match a presented identifier
52 | # where the wildcard character is embedded within an A-label or
53 | # U-label of an internationalized domain name.
54 | pats.append(re.escape(leftmost))
55 | else:
56 | # Otherwise, '*' matches any dotless string, e.g. www*
57 | pats.append(re.escape(leftmost).replace(r'\*', '[^.]*'))
58 |
59 | # add the remaining fragments, ignore any wildcards
60 | for frag in remainder:
61 | pats.append(re.escape(frag))
62 |
63 | pat = re.compile(r'\A' + r'\.'.join(pats) + r'\Z', re.IGNORECASE)
64 | return pat.match(hostname)
65 |
66 |
67 | def match_hostname(cert, hostname):
68 | """Verify that *cert* (in decoded format as returned by
69 | SSLSocket.getpeercert()) matches the *hostname*. RFC 2818 and RFC 6125
70 | rules are followed, but IP addresses are not accepted for *hostname*.
71 |
72 | CertificateError is raised on failure. On success, the function
73 | returns nothing.
74 | """
75 | if not cert:
76 | raise ValueError("empty or no certificate")
77 | dnsnames = []
78 | san = cert.get('subjectAltName', ())
79 | for key, value in san:
80 | if key == 'DNS':
81 | if _dnsname_match(value, hostname):
82 | return
83 | dnsnames.append(value)
84 | if not dnsnames:
85 | # The subject is only checked when there is no dNSName entry
86 | # in subjectAltName
87 | for sub in cert.get('subject', ()):
88 | for key, value in sub:
89 | # XXX according to RFC 2818, the most specific Common Name
90 | # must be used.
91 | if key == 'commonName':
92 | if _dnsname_match(value, hostname):
93 | return
94 | dnsnames.append(value)
95 | if len(dnsnames) > 1:
96 | raise CertificateError("hostname %r "
97 | "doesn't match either of %s"
98 | % (hostname, ', '.join(map(repr, dnsnames))))
99 | elif len(dnsnames) == 1:
100 | raise CertificateError("hostname %r "
101 | "doesn't match %r"
102 | % (hostname, dnsnames[0]))
103 | else:
104 | raise CertificateError("no appropriate commonName or "
105 | "subjectAltName fields were found")
106 |
--------------------------------------------------------------------------------
/vendor/requests/packages/urllib3/packages/ssl_match_hostname/_implementation.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/loveQt/wxpytest/c8923b2298a5f71aca4bcee656125dc219d45592/vendor/requests/packages/urllib3/packages/ssl_match_hostname/_implementation.pyc
--------------------------------------------------------------------------------
/vendor/requests/packages/urllib3/poolmanager.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/loveQt/wxpytest/c8923b2298a5f71aca4bcee656125dc219d45592/vendor/requests/packages/urllib3/poolmanager.pyc
--------------------------------------------------------------------------------
/vendor/requests/packages/urllib3/request.py:
--------------------------------------------------------------------------------
1 | from __future__ import absolute_import
2 | try:
3 | from urllib.parse import urlencode
4 | except ImportError:
5 | from urllib import urlencode
6 |
7 | from .filepost import encode_multipart_formdata
8 |
9 |
10 | __all__ = ['RequestMethods']
11 |
12 |
13 | class RequestMethods(object):
14 | """
15 | Convenience mixin for classes who implement a :meth:`urlopen` method, such
16 | as :class:`~urllib3.connectionpool.HTTPConnectionPool` and
17 | :class:`~urllib3.poolmanager.PoolManager`.
18 |
19 | Provides behavior for making common types of HTTP request methods and
20 | decides which type of request field encoding to use.
21 |
22 | Specifically,
23 |
24 | :meth:`.request_encode_url` is for sending requests whose fields are
25 | encoded in the URL (such as GET, HEAD, DELETE).
26 |
27 | :meth:`.request_encode_body` is for sending requests whose fields are
28 | encoded in the *body* of the request using multipart or www-form-urlencoded
29 | (such as for POST, PUT, PATCH).
30 |
31 | :meth:`.request` is for making any kind of request, it will look up the
32 | appropriate encoding format and use one of the above two methods to make
33 | the request.
34 |
35 | Initializer parameters:
36 |
37 | :param headers:
38 | Headers to include with all requests, unless other headers are given
39 | explicitly.
40 | """
41 |
42 | _encode_url_methods = set(['DELETE', 'GET', 'HEAD', 'OPTIONS'])
43 |
44 | def __init__(self, headers=None):
45 | self.headers = headers or {}
46 |
47 | def urlopen(self, method, url, body=None, headers=None,
48 | encode_multipart=True, multipart_boundary=None,
49 | **kw): # Abstract
50 | raise NotImplemented("Classes extending RequestMethods must implement "
51 | "their own ``urlopen`` method.")
52 |
53 | def request(self, method, url, fields=None, headers=None, **urlopen_kw):
54 | """
55 | Make a request using :meth:`urlopen` with the appropriate encoding of
56 | ``fields`` based on the ``method`` used.
57 |
58 | This is a convenience method that requires the least amount of manual
59 | effort. It can be used in most situations, while still having the
60 | option to drop down to more specific methods when necessary, such as
61 | :meth:`request_encode_url`, :meth:`request_encode_body`,
62 | or even the lowest level :meth:`urlopen`.
63 | """
64 | method = method.upper()
65 |
66 | if method in self._encode_url_methods:
67 | return self.request_encode_url(method, url, fields=fields,
68 | headers=headers,
69 | **urlopen_kw)
70 | else:
71 | return self.request_encode_body(method, url, fields=fields,
72 | headers=headers,
73 | **urlopen_kw)
74 |
75 | def request_encode_url(self, method, url, fields=None, headers=None,
76 | **urlopen_kw):
77 | """
78 | Make a request using :meth:`urlopen` with the ``fields`` encoded in
79 | the url. This is useful for request methods like GET, HEAD, DELETE, etc.
80 | """
81 | if headers is None:
82 | headers = self.headers
83 |
84 | extra_kw = {'headers': headers}
85 | extra_kw.update(urlopen_kw)
86 |
87 | if fields:
88 | url += '?' + urlencode(fields)
89 |
90 | return self.urlopen(method, url, **extra_kw)
91 |
92 | def request_encode_body(self, method, url, fields=None, headers=None,
93 | encode_multipart=True, multipart_boundary=None,
94 | **urlopen_kw):
95 | """
96 | Make a request using :meth:`urlopen` with the ``fields`` encoded in
97 | the body. This is useful for request methods like POST, PUT, PATCH, etc.
98 |
99 | When ``encode_multipart=True`` (default), then
100 | :meth:`urllib3.filepost.encode_multipart_formdata` is used to encode
101 | the payload with the appropriate content type. Otherwise
102 | :meth:`urllib.urlencode` is used with the
103 | 'application/x-www-form-urlencoded' content type.
104 |
105 | Multipart encoding must be used when posting files, and it's reasonably
106 | safe to use it in other times too. However, it may break request
107 | signing, such as with OAuth.
108 |
109 | Supports an optional ``fields`` parameter of key/value strings AND
110 | key/filetuple. A filetuple is a (filename, data, MIME type) tuple where
111 | the MIME type is optional. For example::
112 |
113 | fields = {
114 | 'foo': 'bar',
115 | 'fakefile': ('foofile.txt', 'contents of foofile'),
116 | 'realfile': ('barfile.txt', open('realfile').read()),
117 | 'typedfile': ('bazfile.bin', open('bazfile').read(),
118 | 'image/jpeg'),
119 | 'nonamefile': 'contents of nonamefile field',
120 | }
121 |
122 | When uploading a file, providing a filename (the first parameter of the
123 | tuple) is optional but recommended to best mimick behavior of browsers.
124 |
125 | Note that if ``headers`` are supplied, the 'Content-Type' header will
126 | be overwritten because it depends on the dynamic random boundary string
127 | which is used to compose the body of the request. The random boundary
128 | string can be explicitly set with the ``multipart_boundary`` parameter.
129 | """
130 | if headers is None:
131 | headers = self.headers
132 |
133 | extra_kw = {'headers': {}}
134 |
135 | if fields:
136 | if 'body' in urlopen_kw:
137 | raise TypeError(
138 | "request got values for both 'fields' and 'body', can only specify one.")
139 |
140 | if encode_multipart:
141 | body, content_type = encode_multipart_formdata(fields, boundary=multipart_boundary)
142 | else:
143 | body, content_type = urlencode(fields), 'application/x-www-form-urlencoded'
144 |
145 | extra_kw['body'] = body
146 | extra_kw['headers'] = {'Content-Type': content_type}
147 |
148 | extra_kw['headers'].update(headers)
149 | extra_kw.update(urlopen_kw)
150 |
151 | return self.urlopen(method, url, **extra_kw)
152 |
--------------------------------------------------------------------------------
/vendor/requests/packages/urllib3/request.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/loveQt/wxpytest/c8923b2298a5f71aca4bcee656125dc219d45592/vendor/requests/packages/urllib3/request.pyc
--------------------------------------------------------------------------------
/vendor/requests/packages/urllib3/response.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/loveQt/wxpytest/c8923b2298a5f71aca4bcee656125dc219d45592/vendor/requests/packages/urllib3/response.pyc
--------------------------------------------------------------------------------
/vendor/requests/packages/urllib3/util/__init__.py:
--------------------------------------------------------------------------------
1 | from __future__ import absolute_import
2 | # For backwards compatibility, provide imports that used to be here.
3 | from .connection import is_connection_dropped
4 | from .request import make_headers
5 | from .response import is_fp_closed
6 | from .ssl_ import (
7 | SSLContext,
8 | HAS_SNI,
9 | IS_PYOPENSSL,
10 | assert_fingerprint,
11 | resolve_cert_reqs,
12 | resolve_ssl_version,
13 | ssl_wrap_socket,
14 | )
15 | from .timeout import (
16 | current_time,
17 | Timeout,
18 | )
19 |
20 | from .retry import Retry
21 | from .url import (
22 | get_host,
23 | parse_url,
24 | split_first,
25 | Url,
26 | )
27 |
28 | __all__ = (
29 | 'HAS_SNI',
30 | 'IS_PYOPENSSL',
31 | 'SSLContext',
32 | 'Retry',
33 | 'Timeout',
34 | 'Url',
35 | 'assert_fingerprint',
36 | 'current_time',
37 | 'is_connection_dropped',
38 | 'is_fp_closed',
39 | 'get_host',
40 | 'parse_url',
41 | 'make_headers',
42 | 'resolve_cert_reqs',
43 | 'resolve_ssl_version',
44 | 'split_first',
45 | 'ssl_wrap_socket',
46 | )
47 |
--------------------------------------------------------------------------------
/vendor/requests/packages/urllib3/util/__init__.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/loveQt/wxpytest/c8923b2298a5f71aca4bcee656125dc219d45592/vendor/requests/packages/urllib3/util/__init__.pyc
--------------------------------------------------------------------------------
/vendor/requests/packages/urllib3/util/connection.py:
--------------------------------------------------------------------------------
1 | from __future__ import absolute_import
2 | import socket
3 | try:
4 | from select import poll, POLLIN
5 | except ImportError: # `poll` doesn't exist on OSX and other platforms
6 | poll = False
7 | try:
8 | from select import select
9 | except ImportError: # `select` doesn't exist on AppEngine.
10 | select = False
11 |
12 |
13 | def is_connection_dropped(conn): # Platform-specific
14 | """
15 | Returns True if the connection is dropped and should be closed.
16 |
17 | :param conn:
18 | :class:`httplib.HTTPConnection` object.
19 |
20 | Note: For platforms like AppEngine, this will always return ``False`` to
21 | let the platform handle connection recycling transparently for us.
22 | """
23 | sock = getattr(conn, 'sock', False)
24 | if sock is False: # Platform-specific: AppEngine
25 | return False
26 | if sock is None: # Connection already closed (such as by httplib).
27 | return True
28 |
29 | if not poll:
30 | if not select: # Platform-specific: AppEngine
31 | return False
32 |
33 | try:
34 | return select([sock], [], [], 0.0)[0]
35 | except socket.error:
36 | return True
37 |
38 | # This version is better on platforms that support it.
39 | p = poll()
40 | p.register(sock, POLLIN)
41 | for (fno, ev) in p.poll(0.0):
42 | if fno == sock.fileno():
43 | # Either data is buffered (bad), or the connection is dropped.
44 | return True
45 |
46 |
47 | # This function is copied from socket.py in the Python 2.7 standard
48 | # library test suite. Added to its signature is only `socket_options`.
49 | def create_connection(address, timeout=socket._GLOBAL_DEFAULT_TIMEOUT,
50 | source_address=None, socket_options=None):
51 | """Connect to *address* and return the socket object.
52 |
53 | Convenience function. Connect to *address* (a 2-tuple ``(host,
54 | port)``) and return the socket object. Passing the optional
55 | *timeout* parameter will set the timeout on the socket instance
56 | before attempting to connect. If no *timeout* is supplied, the
57 | global default timeout setting returned by :func:`getdefaulttimeout`
58 | is used. If *source_address* is set it must be a tuple of (host, port)
59 | for the socket to bind as a source address before making the connection.
60 | An host of '' or port 0 tells the OS to use the default.
61 | """
62 |
63 | host, port = address
64 | if host.startswith('['):
65 | host = host.strip('[]')
66 | err = None
67 | for res in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM):
68 | af, socktype, proto, canonname, sa = res
69 | sock = None
70 | try:
71 | sock = socket.socket(af, socktype, proto)
72 |
73 | # If provided, set socket level options before connecting.
74 | # This is the only addition urllib3 makes to this function.
75 | _set_socket_options(sock, socket_options)
76 |
77 | if timeout is not socket._GLOBAL_DEFAULT_TIMEOUT:
78 | sock.settimeout(timeout)
79 | if source_address:
80 | sock.bind(source_address)
81 | sock.connect(sa)
82 | return sock
83 |
84 | except socket.error as e:
85 | err = e
86 | if sock is not None:
87 | sock.close()
88 | sock = None
89 |
90 | if err is not None:
91 | raise err
92 |
93 | raise socket.error("getaddrinfo returns an empty list")
94 |
95 |
96 | def _set_socket_options(sock, options):
97 | if options is None:
98 | return
99 |
100 | for opt in options:
101 | sock.setsockopt(*opt)
102 |
--------------------------------------------------------------------------------
/vendor/requests/packages/urllib3/util/connection.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/loveQt/wxpytest/c8923b2298a5f71aca4bcee656125dc219d45592/vendor/requests/packages/urllib3/util/connection.pyc
--------------------------------------------------------------------------------
/vendor/requests/packages/urllib3/util/request.py:
--------------------------------------------------------------------------------
1 | from __future__ import absolute_import
2 | from base64 import b64encode
3 |
4 | from ..packages.six import b
5 |
6 | ACCEPT_ENCODING = 'gzip,deflate'
7 |
8 |
9 | def make_headers(keep_alive=None, accept_encoding=None, user_agent=None,
10 | basic_auth=None, proxy_basic_auth=None, disable_cache=None):
11 | """
12 | Shortcuts for generating request headers.
13 |
14 | :param keep_alive:
15 | If ``True``, adds 'connection: keep-alive' header.
16 |
17 | :param accept_encoding:
18 | Can be a boolean, list, or string.
19 | ``True`` translates to 'gzip,deflate'.
20 | List will get joined by comma.
21 | String will be used as provided.
22 |
23 | :param user_agent:
24 | String representing the user-agent you want, such as
25 | "python-urllib3/0.6"
26 |
27 | :param basic_auth:
28 | Colon-separated username:password string for 'authorization: basic ...'
29 | auth header.
30 |
31 | :param proxy_basic_auth:
32 | Colon-separated username:password string for 'proxy-authorization: basic ...'
33 | auth header.
34 |
35 | :param disable_cache:
36 | If ``True``, adds 'cache-control: no-cache' header.
37 |
38 | Example::
39 |
40 | >>> make_headers(keep_alive=True, user_agent="Batman/1.0")
41 | {'connection': 'keep-alive', 'user-agent': 'Batman/1.0'}
42 | >>> make_headers(accept_encoding=True)
43 | {'accept-encoding': 'gzip,deflate'}
44 | """
45 | headers = {}
46 | if accept_encoding:
47 | if isinstance(accept_encoding, str):
48 | pass
49 | elif isinstance(accept_encoding, list):
50 | accept_encoding = ','.join(accept_encoding)
51 | else:
52 | accept_encoding = ACCEPT_ENCODING
53 | headers['accept-encoding'] = accept_encoding
54 |
55 | if user_agent:
56 | headers['user-agent'] = user_agent
57 |
58 | if keep_alive:
59 | headers['connection'] = 'keep-alive'
60 |
61 | if basic_auth:
62 | headers['authorization'] = 'Basic ' + \
63 | b64encode(b(basic_auth)).decode('utf-8')
64 |
65 | if proxy_basic_auth:
66 | headers['proxy-authorization'] = 'Basic ' + \
67 | b64encode(b(proxy_basic_auth)).decode('utf-8')
68 |
69 | if disable_cache:
70 | headers['cache-control'] = 'no-cache'
71 |
72 | return headers
73 |
--------------------------------------------------------------------------------
/vendor/requests/packages/urllib3/util/request.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/loveQt/wxpytest/c8923b2298a5f71aca4bcee656125dc219d45592/vendor/requests/packages/urllib3/util/request.pyc
--------------------------------------------------------------------------------
/vendor/requests/packages/urllib3/util/response.py:
--------------------------------------------------------------------------------
1 | from __future__ import absolute_import
2 | from ..packages.six.moves import http_client as httplib
3 |
4 | from ..exceptions import HeaderParsingError
5 |
6 |
7 | def is_fp_closed(obj):
8 | """
9 | Checks whether a given file-like object is closed.
10 |
11 | :param obj:
12 | The file-like object to check.
13 | """
14 |
15 | try:
16 | # Check via the official file-like-object way.
17 | return obj.closed
18 | except AttributeError:
19 | pass
20 |
21 | try:
22 | # Check if the object is a container for another file-like object that
23 | # gets released on exhaustion (e.g. HTTPResponse).
24 | return obj.fp is None
25 | except AttributeError:
26 | pass
27 |
28 | raise ValueError("Unable to determine whether fp is closed.")
29 |
30 |
31 | def assert_header_parsing(headers):
32 | """
33 | Asserts whether all headers have been successfully parsed.
34 | Extracts encountered errors from the result of parsing headers.
35 |
36 | Only works on Python 3.
37 |
38 | :param headers: Headers to verify.
39 | :type headers: `httplib.HTTPMessage`.
40 |
41 | :raises urllib3.exceptions.HeaderParsingError:
42 | If parsing errors are found.
43 | """
44 |
45 | # This will fail silently if we pass in the wrong kind of parameter.
46 | # To make debugging easier add an explicit check.
47 | if not isinstance(headers, httplib.HTTPMessage):
48 | raise TypeError('expected httplib.Message, got {0}.'.format(
49 | type(headers)))
50 |
51 | defects = getattr(headers, 'defects', None)
52 | get_payload = getattr(headers, 'get_payload', None)
53 |
54 | unparsed_data = None
55 | if get_payload: # Platform-specific: Python 3.
56 | unparsed_data = get_payload()
57 |
58 | if defects or unparsed_data:
59 | raise HeaderParsingError(defects=defects, unparsed_data=unparsed_data)
60 |
61 |
62 | def is_response_to_head(response):
63 | """
64 | Checks whether the request of a response has been a HEAD-request.
65 | Handles the quirks of AppEngine.
66 |
67 | :param conn:
68 | :type conn: :class:`httplib.HTTPResponse`
69 | """
70 | # FIXME: Can we do this somehow without accessing private httplib _method?
71 | method = response._method
72 | if isinstance(method, int): # Platform-specific: Appengine
73 | return method == 3
74 | return method.upper() == 'HEAD'
75 |
--------------------------------------------------------------------------------
/vendor/requests/packages/urllib3/util/response.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/loveQt/wxpytest/c8923b2298a5f71aca4bcee656125dc219d45592/vendor/requests/packages/urllib3/util/response.pyc
--------------------------------------------------------------------------------
/vendor/requests/packages/urllib3/util/retry.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/loveQt/wxpytest/c8923b2298a5f71aca4bcee656125dc219d45592/vendor/requests/packages/urllib3/util/retry.pyc
--------------------------------------------------------------------------------
/vendor/requests/packages/urllib3/util/ssl_.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/loveQt/wxpytest/c8923b2298a5f71aca4bcee656125dc219d45592/vendor/requests/packages/urllib3/util/ssl_.pyc
--------------------------------------------------------------------------------
/vendor/requests/packages/urllib3/util/timeout.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/loveQt/wxpytest/c8923b2298a5f71aca4bcee656125dc219d45592/vendor/requests/packages/urllib3/util/timeout.pyc
--------------------------------------------------------------------------------
/vendor/requests/packages/urllib3/util/url.py:
--------------------------------------------------------------------------------
1 | from __future__ import absolute_import
2 | from collections import namedtuple
3 |
4 | from ..exceptions import LocationParseError
5 |
6 |
7 | url_attrs = ['scheme', 'auth', 'host', 'port', 'path', 'query', 'fragment']
8 |
9 |
10 | class Url(namedtuple('Url', url_attrs)):
11 | """
12 | Datastructure for representing an HTTP URL. Used as a return value for
13 | :func:`parse_url`.
14 | """
15 | slots = ()
16 |
17 | def __new__(cls, scheme=None, auth=None, host=None, port=None, path=None,
18 | query=None, fragment=None):
19 | if path and not path.startswith('/'):
20 | path = '/' + path
21 | return super(Url, cls).__new__(cls, scheme, auth, host, port, path,
22 | query, fragment)
23 |
24 | @property
25 | def hostname(self):
26 | """For backwards-compatibility with urlparse. We're nice like that."""
27 | return self.host
28 |
29 | @property
30 | def request_uri(self):
31 | """Absolute path including the query string."""
32 | uri = self.path or '/'
33 |
34 | if self.query is not None:
35 | uri += '?' + self.query
36 |
37 | return uri
38 |
39 | @property
40 | def netloc(self):
41 | """Network location including host and port"""
42 | if self.port:
43 | return '%s:%d' % (self.host, self.port)
44 | return self.host
45 |
46 | @property
47 | def url(self):
48 | """
49 | Convert self into a url
50 |
51 | This function should more or less round-trip with :func:`.parse_url`. The
52 | returned url may not be exactly the same as the url inputted to
53 | :func:`.parse_url`, but it should be equivalent by the RFC (e.g., urls
54 | with a blank port will have : removed).
55 |
56 | Example: ::
57 |
58 | >>> U = parse_url('http://google.com/mail/')
59 | >>> U.url
60 | 'http://google.com/mail/'
61 | >>> Url('http', 'username:password', 'host.com', 80,
62 | ... '/path', 'query', 'fragment').url
63 | 'http://username:password@host.com:80/path?query#fragment'
64 | """
65 | scheme, auth, host, port, path, query, fragment = self
66 | url = ''
67 |
68 | # We use "is not None" we want things to happen with empty strings (or 0 port)
69 | if scheme is not None:
70 | url += scheme + '://'
71 | if auth is not None:
72 | url += auth + '@'
73 | if host is not None:
74 | url += host
75 | if port is not None:
76 | url += ':' + str(port)
77 | if path is not None:
78 | url += path
79 | if query is not None:
80 | url += '?' + query
81 | if fragment is not None:
82 | url += '#' + fragment
83 |
84 | return url
85 |
86 | def __str__(self):
87 | return self.url
88 |
89 |
90 | def split_first(s, delims):
91 | """
92 | Given a string and an iterable of delimiters, split on the first found
93 | delimiter. Return two split parts and the matched delimiter.
94 |
95 | If not found, then the first part is the full input string.
96 |
97 | Example::
98 |
99 | >>> split_first('foo/bar?baz', '?/=')
100 | ('foo', 'bar?baz', '/')
101 | >>> split_first('foo/bar?baz', '123')
102 | ('foo/bar?baz', '', None)
103 |
104 | Scales linearly with number of delims. Not ideal for large number of delims.
105 | """
106 | min_idx = None
107 | min_delim = None
108 | for d in delims:
109 | idx = s.find(d)
110 | if idx < 0:
111 | continue
112 |
113 | if min_idx is None or idx < min_idx:
114 | min_idx = idx
115 | min_delim = d
116 |
117 | if min_idx is None or min_idx < 0:
118 | return s, '', None
119 |
120 | return s[:min_idx], s[min_idx + 1:], min_delim
121 |
122 |
123 | def parse_url(url):
124 | """
125 | Given a url, return a parsed :class:`.Url` namedtuple. Best-effort is
126 | performed to parse incomplete urls. Fields not provided will be None.
127 |
128 | Partly backwards-compatible with :mod:`urlparse`.
129 |
130 | Example::
131 |
132 | >>> parse_url('http://google.com/mail/')
133 | Url(scheme='http', host='google.com', port=None, path='/mail/', ...)
134 | >>> parse_url('google.com:80')
135 | Url(scheme=None, host='google.com', port=80, path=None, ...)
136 | >>> parse_url('/foo?bar')
137 | Url(scheme=None, host=None, port=None, path='/foo', query='bar', ...)
138 | """
139 |
140 | # While this code has overlap with stdlib's urlparse, it is much
141 | # simplified for our needs and less annoying.
142 | # Additionally, this implementations does silly things to be optimal
143 | # on CPython.
144 |
145 | if not url:
146 | # Empty
147 | return Url()
148 |
149 | scheme = None
150 | auth = None
151 | host = None
152 | port = None
153 | path = None
154 | fragment = None
155 | query = None
156 |
157 | # Scheme
158 | if '://' in url:
159 | scheme, url = url.split('://', 1)
160 |
161 | # Find the earliest Authority Terminator
162 | # (http://tools.ietf.org/html/rfc3986#section-3.2)
163 | url, path_, delim = split_first(url, ['/', '?', '#'])
164 |
165 | if delim:
166 | # Reassemble the path
167 | path = delim + path_
168 |
169 | # Auth
170 | if '@' in url:
171 | # Last '@' denotes end of auth part
172 | auth, url = url.rsplit('@', 1)
173 |
174 | # IPv6
175 | if url and url[0] == '[':
176 | host, url = url.split(']', 1)
177 | host += ']'
178 |
179 | # Port
180 | if ':' in url:
181 | _host, port = url.split(':', 1)
182 |
183 | if not host:
184 | host = _host
185 |
186 | if port:
187 | # If given, ports must be integers.
188 | if not port.isdigit():
189 | raise LocationParseError(url)
190 | port = int(port)
191 | else:
192 | # Blank ports are cool, too. (rfc3986#section-3.2.3)
193 | port = None
194 |
195 | elif not host and url:
196 | host = url
197 |
198 | if not path:
199 | return Url(scheme, auth, host, port, path, query, fragment)
200 |
201 | # Fragment
202 | if '#' in path:
203 | path, fragment = path.split('#', 1)
204 |
205 | # Query
206 | if '?' in path:
207 | path, query = path.split('?', 1)
208 |
209 | return Url(scheme, auth, host, port, path, query, fragment)
210 |
211 |
212 | def get_host(url):
213 | """
214 | Deprecated. Use :func:`.parse_url` instead.
215 | """
216 | p = parse_url(url)
217 | return p.scheme or 'http', p.hostname, p.port
218 |
--------------------------------------------------------------------------------
/vendor/requests/packages/urllib3/util/url.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/loveQt/wxpytest/c8923b2298a5f71aca4bcee656125dc219d45592/vendor/requests/packages/urllib3/util/url.pyc
--------------------------------------------------------------------------------
/vendor/requests/sessions.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/loveQt/wxpytest/c8923b2298a5f71aca4bcee656125dc219d45592/vendor/requests/sessions.pyc
--------------------------------------------------------------------------------
/vendor/requests/status_codes.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
3 | from .structures import LookupDict
4 |
5 | _codes = {
6 |
7 | # Informational.
8 | 100: ('continue',),
9 | 101: ('switching_protocols',),
10 | 102: ('processing',),
11 | 103: ('checkpoint',),
12 | 122: ('uri_too_long', 'request_uri_too_long'),
13 | 200: ('ok', 'okay', 'all_ok', 'all_okay', 'all_good', '\\o/', '✓'),
14 | 201: ('created',),
15 | 202: ('accepted',),
16 | 203: ('non_authoritative_info', 'non_authoritative_information'),
17 | 204: ('no_content',),
18 | 205: ('reset_content', 'reset'),
19 | 206: ('partial_content', 'partial'),
20 | 207: ('multi_status', 'multiple_status', 'multi_stati', 'multiple_stati'),
21 | 208: ('already_reported',),
22 | 226: ('im_used',),
23 |
24 | # Redirection.
25 | 300: ('multiple_choices',),
26 | 301: ('moved_permanently', 'moved', '\\o-'),
27 | 302: ('found',),
28 | 303: ('see_other', 'other'),
29 | 304: ('not_modified',),
30 | 305: ('use_proxy',),
31 | 306: ('switch_proxy',),
32 | 307: ('temporary_redirect', 'temporary_moved', 'temporary'),
33 | 308: ('permanent_redirect',
34 | 'resume_incomplete', 'resume',), # These 2 to be removed in 3.0
35 |
36 | # Client Error.
37 | 400: ('bad_request', 'bad'),
38 | 401: ('unauthorized',),
39 | 402: ('payment_required', 'payment'),
40 | 403: ('forbidden',),
41 | 404: ('not_found', '-o-'),
42 | 405: ('method_not_allowed', 'not_allowed'),
43 | 406: ('not_acceptable',),
44 | 407: ('proxy_authentication_required', 'proxy_auth', 'proxy_authentication'),
45 | 408: ('request_timeout', 'timeout'),
46 | 409: ('conflict',),
47 | 410: ('gone',),
48 | 411: ('length_required',),
49 | 412: ('precondition_failed', 'precondition'),
50 | 413: ('request_entity_too_large',),
51 | 414: ('request_uri_too_large',),
52 | 415: ('unsupported_media_type', 'unsupported_media', 'media_type'),
53 | 416: ('requested_range_not_satisfiable', 'requested_range', 'range_not_satisfiable'),
54 | 417: ('expectation_failed',),
55 | 418: ('im_a_teapot', 'teapot', 'i_am_a_teapot'),
56 | 421: ('misdirected_request',),
57 | 422: ('unprocessable_entity', 'unprocessable'),
58 | 423: ('locked',),
59 | 424: ('failed_dependency', 'dependency'),
60 | 425: ('unordered_collection', 'unordered'),
61 | 426: ('upgrade_required', 'upgrade'),
62 | 428: ('precondition_required', 'precondition'),
63 | 429: ('too_many_requests', 'too_many'),
64 | 431: ('header_fields_too_large', 'fields_too_large'),
65 | 444: ('no_response', 'none'),
66 | 449: ('retry_with', 'retry'),
67 | 450: ('blocked_by_windows_parental_controls', 'parental_controls'),
68 | 451: ('unavailable_for_legal_reasons', 'legal_reasons'),
69 | 499: ('client_closed_request',),
70 |
71 | # Server Error.
72 | 500: ('internal_server_error', 'server_error', '/o\\', '✗'),
73 | 501: ('not_implemented',),
74 | 502: ('bad_gateway',),
75 | 503: ('service_unavailable', 'unavailable'),
76 | 504: ('gateway_timeout',),
77 | 505: ('http_version_not_supported', 'http_version'),
78 | 506: ('variant_also_negotiates',),
79 | 507: ('insufficient_storage',),
80 | 509: ('bandwidth_limit_exceeded', 'bandwidth'),
81 | 510: ('not_extended',),
82 | 511: ('network_authentication_required', 'network_auth', 'network_authentication'),
83 | }
84 |
85 | codes = LookupDict(name='status_codes')
86 |
87 | for code, titles in _codes.items():
88 | for title in titles:
89 | setattr(codes, title, code)
90 | if not title.startswith('\\'):
91 | setattr(codes, title.upper(), code)
92 |
--------------------------------------------------------------------------------
/vendor/requests/status_codes.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/loveQt/wxpytest/c8923b2298a5f71aca4bcee656125dc219d45592/vendor/requests/status_codes.pyc
--------------------------------------------------------------------------------
/vendor/requests/structures.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
3 | """
4 | requests.structures
5 | ~~~~~~~~~~~~~~~~~~~
6 |
7 | Data structures that power Requests.
8 |
9 | """
10 |
11 | import collections
12 |
13 | from .compat import OrderedDict
14 |
15 |
16 | class CaseInsensitiveDict(collections.MutableMapping):
17 | """
18 | A case-insensitive ``dict``-like object.
19 |
20 | Implements all methods and operations of
21 | ``collections.MutableMapping`` as well as dict's ``copy``. Also
22 | provides ``lower_items``.
23 |
24 | All keys are expected to be strings. The structure remembers the
25 | case of the last key to be set, and ``iter(instance)``,
26 | ``keys()``, ``items()``, ``iterkeys()``, and ``iteritems()``
27 | will contain case-sensitive keys. However, querying and contains
28 | testing is case insensitive::
29 |
30 | cid = CaseInsensitiveDict()
31 | cid['Accept'] = 'application/json'
32 | cid['aCCEPT'] == 'application/json' # True
33 | list(cid) == ['Accept'] # True
34 |
35 | For example, ``headers['content-encoding']`` will return the
36 | value of a ``'Content-Encoding'`` response header, regardless
37 | of how the header name was originally stored.
38 |
39 | If the constructor, ``.update``, or equality comparison
40 | operations are given keys that have equal ``.lower()``s, the
41 | behavior is undefined.
42 |
43 | """
44 | def __init__(self, data=None, **kwargs):
45 | self._store = OrderedDict()
46 | if data is None:
47 | data = {}
48 | self.update(data, **kwargs)
49 |
50 | def __setitem__(self, key, value):
51 | # Use the lowercased key for lookups, but store the actual
52 | # key alongside the value.
53 | self._store[key.lower()] = (key, value)
54 |
55 | def __getitem__(self, key):
56 | return self._store[key.lower()][1]
57 |
58 | def __delitem__(self, key):
59 | del self._store[key.lower()]
60 |
61 | def __iter__(self):
62 | return (casedkey for casedkey, mappedvalue in self._store.values())
63 |
64 | def __len__(self):
65 | return len(self._store)
66 |
67 | def lower_items(self):
68 | """Like iteritems(), but with all lowercase keys."""
69 | return (
70 | (lowerkey, keyval[1])
71 | for (lowerkey, keyval)
72 | in self._store.items()
73 | )
74 |
75 | def __eq__(self, other):
76 | if isinstance(other, collections.Mapping):
77 | other = CaseInsensitiveDict(other)
78 | else:
79 | return NotImplemented
80 | # Compare insensitively
81 | return dict(self.lower_items()) == dict(other.lower_items())
82 |
83 | # Copy is required
84 | def copy(self):
85 | return CaseInsensitiveDict(self._store.values())
86 |
87 | def __repr__(self):
88 | return str(dict(self.items()))
89 |
90 | class LookupDict(dict):
91 | """Dictionary lookup object."""
92 |
93 | def __init__(self, name=None):
94 | self.name = name
95 | super(LookupDict, self).__init__()
96 |
97 | def __repr__(self):
98 | return '' % (self.name)
99 |
100 | def __getitem__(self, key):
101 | # We allow fall-through here, so values default to None
102 |
103 | return self.__dict__.get(key, None)
104 |
105 | def get(self, key, default=None):
106 | return self.__dict__.get(key, default)
107 |
--------------------------------------------------------------------------------
/vendor/requests/structures.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/loveQt/wxpytest/c8923b2298a5f71aca4bcee656125dc219d45592/vendor/requests/structures.pyc
--------------------------------------------------------------------------------
/vendor/requests/utils.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/loveQt/wxpytest/c8923b2298a5f71aca4bcee656125dc219d45592/vendor/requests/utils.pyc
--------------------------------------------------------------------------------
/weixinInterface.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | import hashlib
3 | import web
4 | import lxml
5 | import time
6 | import requests
7 | import os
8 | import urllib2
9 | import json
10 | from lxml import etree
11 | import cookielib
12 | import re
13 | import random
14 | import cxkd
15 | from imgtest import *
16 |
17 | class WeixinInterface:
18 |
19 | def __init__(self):
20 | self.app_root = os.path.dirname(__file__)
21 | self.templates_root = os.path.join(self.app_root, 'templates')
22 | self.render = web.template.render(self.templates_root)
23 |
24 | def GET(self):
25 | #获取输入参数
26 | data = web.input()
27 | signature=data.signature
28 | timestamp=data.timestamp
29 | nonce=data.nonce
30 | echostr = data.echostr
31 | #自己的token
32 | token="wxpytest" #这里改写你在微信公众平台里输入的token
33 | #字典序排序
34 | list=[token,timestamp,nonce]
35 | list.sort()
36 | sha1=hashlib.sha1()
37 | map(sha1.update,list)
38 | hashcode=sha1.hexdigest()
39 | #sha1加密算法
40 |
41 | #如果是来自微信的请求,则回复echostr
42 | if hashcode == signature:
43 | return echostr
44 |
45 | def POST(self):
46 | str_xml = web.data() #获得post来的数据
47 | xml = etree.fromstring(str_xml)#进行XML解析
48 | #content=xml.find("Content").text#获得用户所输入的内容
49 | msgType=xml.find("MsgType").text
50 | fromUser=xml.find("FromUserName").text
51 | toUser=xml.find("ToUserName").text
52 | #picurl = xml.find('PicUrl').text
53 | #return self.render.reply_text(fromUser,toUser,int(time.time()), content)
54 | if msgType == 'image':
55 | try:
56 | picurl = xml.find('PicUrl').text
57 | datas = imgtest(picurl)
58 | return self.render.reply_text(fromUser, toUser, int(time.time()), '图中人物性别为'+datas[0]+'\n'+'年龄为'+datas[1])
59 | except:
60 | return self.render.reply_text(fromUser, toUser, int(time.time()), '识别失败,换张图片试试吧')
61 | else:
62 | content = xml.find("Content").text # 获得用户所输入的内容
63 | if content[0:2] == u"快递":
64 | post = str(content[2:])
65 | #result = cxkd.cxkd('PQ00708467161')
66 |
67 | r = urllib2.urlopen('http://www.kuaidi100.com/autonumber/autoComNum?text='+post)
68 | h = r.read()
69 | k = eval(h)
70 | kuaidi = k["auto"][0]['comCode']
71 | '''
72 | j = requests.get('http://www.kuaidi100.com/query?type=huitongkuaidi&postid=280472503105')
73 | l = j.text
74 | #l = j.read()
75 | #m = eval(l)
76 | #outcome = ''
77 | #for c in m['data']:
78 | '''
79 | #outcome = outcome + c['time']+' '+c['context']+'\n'
80 |
81 | return self.render.reply_text(fromUser,toUser,int(time.time()), kuaidi)
82 |
83 | else:
84 | return self.render.reply_text(fromUser,toUser,int(time.time()), content)
85 |
86 |
87 |
88 |
89 |
--------------------------------------------------------------------------------