repo
stringclasses
454 values
file_path
stringlengths
5
201
extension
stringclasses
1 value
content
stringlengths
8
509k
num_lines
int64
3
16.9k
size_bytes
int64
8
511k
records
tests/test_transactions.py
.py
"""Test manipulating database table in various transaction scenarios. Varying conditions: - db for different database backends (see `db` fixture) - query run via - `db=records.Database(); db.query() - `conn=db.get_connection(); conn.query()` - transaction - not used at all - used and created in diff...
84
2,425
records
tests/test_records.py
.py
from collections import namedtuple import records from pytest import raises IdRecord = namedtuple('IdRecord', 'id') def check_id(i, row): assert row.id == i class TestRecordCollection: def test_iter(self): rows = records.RecordCollection(IdRecord(i) for i in range(10)) for i, row in enum...
148
4,699
records
tests/conftest.py
.py
"""Shared pytest fixtures. """ import pytest import records @pytest.fixture( params=[ # request: (sql_url_id, sql_url_template) ("sqlite_memory", "sqlite:///:memory:"), # ('sqlite_file', 'sqlite:///{dbfile}'), # ('psql', 'postgresql://records:records@localhost/records') ], ...
50
1,252
records
examples/randomuser-sqlite.py
.py
#!/usr/bin/env python3 # coding: utf-8 import json import requests import records # Fetch random user data from randomuser.me API response = requests.get('http://api.randomuser.me/0.6/?nat=us&results=10') user_data = response.json()['results'] # Database connection string DATABASE_URL = 'sqlite:///users.db' # Initi...
37
1,062
httpie
setup.py
.py
from setuptools import setup setup()
4
38
httpie
extras/packaging/linux/build.py
.py
import stat import subprocess from pathlib import Path from typing import Iterator, Tuple BUILD_DIR = Path(__file__).parent HTTPIE_DIR = BUILD_DIR.parent.parent.parent EXTRAS_DIR = HTTPIE_DIR / 'extras' MAN_PAGES_DIR = EXTRAS_DIR / 'man' SCRIPT_DIR = BUILD_DIR / Path('scripts') HOOKS_DIR = SCRIPT_DIR / 'hooks' DIS...
110
2,767
httpie
extras/packaging/linux/scripts/httpie_cli.py
.py
from httpie.manager.__main__ import main if __name__ == '__main__': import sys sys.exit(main())
6
105
httpie
extras/packaging/linux/scripts/http_cli.py
.py
from httpie.__main__ import main if __name__ == '__main__': import sys sys.exit(main())
6
97
httpie
extras/packaging/linux/scripts/hooks/hook-pip.py
.py
from pathlib import Path from PyInstaller.utils.hooks import collect_all def hook(hook_api): for pkg in [ 'pip', 'setuptools', 'distutils', 'pkg_resources' ]: datas, binaries, hiddenimports = collect_all(pkg) hook_api.add_datas(datas) hook_api.add_binarie...
15
377
httpie
extras/scripts/generate_man_pages.py
.py
import os import re from contextlib import contextmanager from pathlib import Path from typing import Optional, Iterator, Iterable # So that httpie.cli.definition can provide man-page-specific output. Must be set before importing httpie. os.environ['HTTPIE_BUILDING_MAN_PAGES'] = '1' import httpie from httpie.cli.def...
189
6,042
httpie
extras/profiling/run.py
.py
""" Run the HTTPie benchmark suite with multiple environments. This script is configured in a way that, it will create two (or more) isolated environments and compare the *last commit* of this repository with it's master. > If you didn't commit yet, it won't be showing results. You can also pass --fresh, which would...
288
8,613
httpie
extras/profiling/benchmarks.py
.py
""" This file is the declaration of benchmarks for HTTPie. It is also used to run them with the current environment. Each instance of BaseRunner class will be an individual benchmark. And if run without any arguments, this file will execute every benchmark instance and report the timings. The benchmarks are run throu...
203
5,925
httpie
docs/contributors/generate.py
.py
""" Generate snippets to copy-paste. """ import sys from jinja2 import Template from fetch import HERE, load_awesome_people TPL_FILE = HERE / 'snippet.jinja2' HTTPIE_TEAM = { 'claudiatd', 'jakubroztocil', 'jkbr', 'isidentical' } BOT_ACCOUNTS = { 'dependabot-sr' } IGNORE_ACCOUNTS = HTTPIE_TEAM ...
54
1,110
httpie
docs/contributors/fetch.py
.py
""" Generate the contributors database. FIXME: replace `requests` calls with the HTTPie API, when available. """ import json import os import re import sys from copy import deepcopy from datetime import datetime from pathlib import Path from subprocess import check_output from time import sleep from typing import Any,...
282
8,916
httpie
docs/installation/generate.py
.py
import re import sys from pathlib import Path from typing import Dict import yaml from jinja2 import Template Database = Dict[str, dict] # Files HERE = Path(__file__).parent DB_FILE = HERE / 'methods.yml' DOC_FILE = HERE.parent / 'README.md' TPL_FILE = HERE / 'installation.jinja2' # Database keys KEY_DOC_STRUCTURE ...
86
2,390
httpie
tests/test_cookie.py
.py
from http.cookies import SimpleCookie from http.server import BaseHTTPRequestHandler, HTTPServer from threading import Thread from .utils import http class TestIntegration: def setup_mock_server(self, handler): """Configure mock server.""" # Passing 0 as the port will cause a random free port to...
48
1,876
httpie
tests/test_meta.py
.py
import pytest from httpie.models import ELAPSED_TIME_LABEL from httpie.output.formatters.colors import PIE_STYLE_NAMES from .utils import http, MockEnvironment, COLOR def test_meta_elapsed_time(httpbin): r = http('--meta', httpbin + '/delay/1') assert f'{ELAPSED_TIME_LABEL}: 1.' in r @pytest.mark.parametri...
18
570
httpie
tests/test_encoding.py
.py
""" Various encoding handling related tests. """ import pytest import responses from charset_normalizer.constant import TOO_SMALL_SEQUENCE from httpie.cli.constants import PRETTY_MAP from httpie.encoding import UTF8 from .utils import http, HTTP_OK, DUMMY_URL, MockEnvironment from .fixtures import UNICODE CHARSET_...
223
6,697
httpie
tests/test_errors.py
.py
import pytest import socket from unittest import mock from pytest import raises from requests import Request from requests.exceptions import ConnectionError from httpie.status import ExitStatus from .utils import HTTP_OK, http @mock.patch('httpie.core.program') def test_error(program): exc = ConnectionError('Con...
77
2,392
httpie
tests/test_transport_plugin.py
.py
from io import BytesIO from requests.adapters import BaseAdapter from requests.models import Response from requests.utils import get_encoding_from_headers from httpie.plugins import TransportPlugin from httpie.plugins.registry import plugin_manager from .utils import HTTP_OK, http SCHEME = 'http+fake' class FakeA...
46
1,229
httpie
tests/test_stream.py
.py
import json import pytest import responses from unittest.mock import Mock from httpie.compat import is_windows from httpie.cli.constants import PRETTY_MAP from httpie.output.streams import BINARY_SUPPRESSED_NOTICE from httpie.plugins import ConverterPlugin from httpie.plugins.registry import plugin_manager from .uti...
151
4,507
httpie
tests/test_plugins_cli.py
.py
import pytest from httpie.status import ExitStatus from tests.utils.plugins_cli import parse_listing @pytest.mark.requires_installation @pytest.mark.parametrize('cli_mode', [True, False]) def test_plugins_installation(httpie_plugins_success, interface, dummy_plugin, cli_mode): lines = httpie_plugins_success('ins...
156
5,784
httpie
tests/test_compress.py
.py
""" We test against httpbin which doesn't return the request data in a consistent way: 1. Non-form requests: the `data` field contains base64 encoded version of our zlib-encoded request data. 2. Form requests: `form` contains a messed up version of the data. """ import base64 import zlib from .fixtures import FILE_...
141
3,874
httpie
tests/test_offline.py
.py
from .fixtures import FILE_CONTENT, FILE_PATH_ARG from .utils import http def test_offline(): r = http( '--offline', 'https://this-should.never-resolve/foo', ) assert 'GET /foo' in r def test_offline_raw(): r = http( '--offline', '--raw', 'foo bar', 'h...
97
1,979
httpie
tests/test_cli_ui.py
.py
import pytest import shutil import os from tests.utils import http NAKED_BASE_TEMPLATE = """\ usage: http {extra_args}[METHOD] URL [REQUEST_ITEM ...] error: {error_msg} for more information: run 'http --help' or visit https://httpie.io/docs/cli """ NAKED_HELP_MESSAGE = NAKED_BASE_TEMPLATE.format( e...
66
2,025
httpie
tests/test_httpie_cli.py
.py
import pytest import shutil import json from httpie.sessions import SESSIONS_DIR_NAME from httpie.status import ExitStatus from httpie.cli.options import PARSER_SPEC_VERSION from tests.utils import DUMMY_HOST, httpie from tests.fixtures import SESSION_FILES_PATH, SESSION_FILES_NEW, SESSION_FILES_OLD, read_session_file ...
139
4,403
httpie
tests/test_config.py
.py
from pathlib import Path import pytest from _pytest.monkeypatch import MonkeyPatch from httpie.compat import is_windows from httpie.encoding import UTF8 from httpie.config import ( Config, DEFAULT_CONFIG_DIRNAME, DEFAULT_RELATIVE_LEGACY_CONFIG_DIR, DEFAULT_RELATIVE_XDG_CONFIG_HOME, DEFAULT_WINDOWS_CONFIG_DIR,...
105
3,765
httpie
tests/test_tokens.py
.py
""" The ideas behind these test and the named templates is to ensure consistent output across all supported different scenarios: TODO: cover more scenarios * terminal vs. redirect stdout * different combinations of `--print=HBhb` (request/response headers/body) * multipart requests * streamed uploads """ from .ut...
119
3,992
httpie
tests/test_cli_utils.py
.py
import pytest from argparse import ArgumentParser from unittest.mock import Mock from httpie.cli.utils import LazyChoices def test_lazy_choices(): mock = Mock() getter = mock.getter getter.return_value = ['a', 'b', 'c'] parser = ArgumentParser() parser.register('action', 'lazy_choices', LazyChoic...
87
2,322
httpie
tests/test_auth.py
.py
"""HTTP authentication-related tests.""" from unittest import mock import pytest from httpie.plugins.builtin import HTTPBasicAuth from httpie.status import ExitStatus from httpie.utils import ExplicitNullAuth from .utils import http, add_auth, HTTP_OK, MockEnvironment import httpie.cli.constants import httpie.cli.defi...
156
5,169
httpie
tests/test_cookie_on_redirects.py
.py
import pytest from .utils import http @pytest.mark.parametrize('target_httpbin', [ 'httpbin', 'remote_httpbin', ]) def test_explicit_user_set_cookie(httpbin, target_httpbin, request): """User set cookies ARE NOT persisted within redirects when there is no session, even on the same domain.""" target_ht...
251
7,232
httpie
tests/test_parser_schema.py
.py
from httpie.cli.options import ParserSpec, Qualifiers def test_parser_serialization(): small_parser = ParserSpec("test_parser") group_1 = small_parser.add_group("group_1") group_1.add_argument("regular_arg", help="regular arg", short_help="short") group_1.add_argument( "variadic_arg", ...
64
2,085
httpie
tests/test_windows.py
.py
import pytest from httpie.context import Environment from .utils import MockEnvironment, http from httpie.compat import is_windows @pytest.mark.skipif(not is_windows, reason='windows-only') class TestWindowsOnly: @pytest.mark.skipif(True, reason='this test for some reason kills the proce...
26
948
httpie
tests/test_defaults.py
.py
""" Tests for the provided defaults regarding HTTP method, and --json vs. --form. """ from io import BytesIO from httpie.client import JSON_ACCEPT from .utils import MockEnvironment, http, HTTP_OK from .fixtures import FILE_PATH def test_default_headers_case_insensitive(httpbin): """ <https://github.com/htt...
133
4,831
httpie
tests/test_regressions.py
.py
"""Miscellaneous regression tests""" import pytest from httpie.compat import is_windows from .utils.matching import assert_output_matches, Expect from .utils import HTTP_OK, MockEnvironment, http def test_Host_header_overwrite(httpbin): """ https://github.com/httpie/cli/issues/235 """ host = 'pie.de...
50
1,142
httpie
tests/test_sessions.py
.py
import json import os import shutil from contextlib import contextmanager from datetime import datetime from unittest import mock from pathlib import Path from typing import Iterator import pytest from .fixtures import FILE_PATH_ARG, UNICODE from httpie.context import Environment from httpie.encoding import UTF8 from...
853
27,509
httpie
tests/test_httpie.py
.py
"""High-level tests.""" import io from unittest import mock import pytest import httpie import httpie.__main__ from .fixtures import FILE_CONTENT, FILE_PATH from httpie.cli.exceptions import ParseError from httpie.context import Environment from httpie.encoding import UTF8 from httpie.status import ExitStatus from .u...
373
10,381
httpie
tests/test_ssl.py
.py
import ssl import pytest import pytest_httpbin.certs import requests.exceptions import urllib3 from unittest import mock from httpie.ssl_ import AVAILABLE_SSL_VERSION_ARG_MAPPING, DEFAULT_SSL_CIPHERS_STRING from httpie.status import ExitStatus from .utils import HTTP_OK, TESTS_ROOT, IS_PYOPENSSL, http try: # ...
212
7,354
httpie
tests/test_json.py
.py
import json import pytest import responses from httpie.cli.constants import PRETTY_MAP from httpie.cli.exceptions import ParseError from httpie.cli.nested_json import NestedJSONSyntaxError from httpie.output.formatters.colors import ColorFormatter from httpie.utils import JsonDictPreservingDuplicateKeys from .fixtur...
584
18,699
httpie
tests/test_auth_plugins.py
.py
from unittest import mock from httpie.cli.constants import SEPARATOR_CREDENTIALS from httpie.plugins import AuthPlugin from httpie.plugins.registry import plugin_manager from .utils import http, HTTP_OK # TODO: run all these tests in session mode as well USERNAME = 'user' PASSWORD = 'password' # Basic auth encoded ...
136
3,689
httpie
tests/test_exit_status.py
.py
from unittest import mock from httpie.status import ExitStatus from .utils import MockEnvironment, http, HTTP_OK def test_keyboard_interrupt_during_arg_parsing_exit_status(httpbin): with mock.patch('httpie.cli.definition.parser.parse_args', side_effect=KeyboardInterrupt()): r = http('...
75
2,642
httpie
tests/test_downloads.py
.py
import os import tempfile import time import requests from unittest import mock from urllib.request import urlopen import pytest from requests.structures import CaseInsensitiveDict from httpie.downloads import ( parse_content_range, filename_from_content_disposition, filename_from_url, get_unique_filename, Co...
262
9,735
httpie
tests/test_binary.py
.py
"""Tests for dealing with binary request and response data.""" import requests from .fixtures import BIN_FILE_PATH, BIN_FILE_CONTENT, BIN_FILE_PATH_ARG from httpie.output.streams import BINARY_SUPPRESSED_NOTICE from .utils import MockEnvironment, http class TestBinaryRequestData: def test_binary_stdin(self, htt...
51
1,974
httpie
tests/test_xml.py
.py
import sys import pytest import responses from httpie.encoding import UTF8 from httpie.output.formatters.xml import parse_xml, pretty_xml from .fixtures import XML_FILES_PATH, XML_FILES_VALID, XML_FILES_INVALID, XML_DATA_RAW, XML_DATA_FORMATTED from .utils import http, DUMMY_URL @pytest.mark.parametrize( 'opti...
100
2,869
httpie
tests/test_cli.py
.py
"""CLI argument parsing related tests.""" import argparse import pytest from requests.exceptions import InvalidSchema import httpie.cli.argparser from httpie.cli import constants from httpie.cli.definition import parser from httpie.cli.argtypes import KeyValueArg, KeyValueArgType from httpie.cli.requestitems import R...
378
14,245
httpie
tests/test_uploads.py
.py
import os import json import sys import subprocess import time import contextlib import httpie.__main__ as main import pytest from httpie.cli.exceptions import ParseError from httpie.client import FORM_CONTENT_TYPE from httpie.compat import is_windows from httpie.status import ExitStatus from .utils import ( Mock...
404
12,843
httpie
tests/test_output.py
.py
import argparse from pathlib import Path from unittest import mock import json import os import io import warnings from urllib.request import urlopen import pytest import requests import responses from httpie.cli.argtypes import ( PARSED_DEFAULT_FORMAT_OPTIONS, parse_format_options, ) from httpie.cli.definit...
632
20,742
httpie
tests/test_redirects.py
.py
"""High-level tests.""" import pytest from httpie.compat import is_windows from httpie.status import ExitStatus from .fixtures import FILE_PATH_ARG, FILE_CONTENT from .utils import http, HTTP_OK from .utils.matching import assert_output_matches, Expect, ExpectSequence # <https://developer.mozilla.org/en-US/docs/Web/...
117
3,537
httpie
tests/test_update_warnings.py
.py
import json import tempfile import time from contextlib import suppress from datetime import datetime from pathlib import Path import pytest from httpie.internal.daemon_runner import STATUS_FILE from httpie.internal.daemons import spawn_daemon from httpie.status import ExitStatus from .utils import PersistentMockEnv...
241
6,637
httpie
tests/conftest.py
.py
import socket import pytest from pytest_httpbin import certs from pytest_httpbin.serve import Server as PyTestHttpBinServer from .utils import ( # noqa HTTPBIN_WITH_CHUNKED_SUPPORT_DOMAIN, HTTPBIN_WITH_CHUNKED_SUPPORT, REMOTE_HTTPBIN_DOMAIN, IS_PYOPENSSL, mock_env ) from .utils.plugins_cli import...
97
2,558
httpie
tests/utils/__init__.py
.py
"""Utilities for HTTPie test suite.""" import re import shlex import os import sys import time import json import tempfile import warnings import pytest from contextlib import suppress from io import BytesIO from pathlib import Path from typing import Any, Optional, Union, List, Iterable import httpie.core as core imp...
456
12,993
httpie
tests/utils/http_server.py
.py
import threading import json from collections import defaultdict from contextlib import contextmanager from http import HTTPStatus from http.cookies import SimpleCookie from http.server import HTTPServer, BaseHTTPRequestHandler from urllib.parse import urlparse, parse_qs import pytest class TestHandler(BaseHTTPRequ...
159
4,482
httpie
tests/utils/plugins_cli.py
.py
import secrets import site import sys import textwrap import pytest from collections import defaultdict from dataclasses import dataclass, field, asdict from pathlib import Path from typing import Any, List, Dict, Tuple from unittest.mock import patch from httpie.context import Environment from httpie.compat import ...
236
6,572
httpie
tests/utils/matching/__init__.py
.py
""" Utilities for testing output composition. """ from typing import Iterable import pytest from .parsing import OutputMatchingError, expect_tokens from .tokens import Expect, ExpectSequence __all__ = [ 'assert_output_matches', 'assert_output_does_not_match', 'Expect', 'ExpectSequence', ] def ass...
39
1,004
httpie
tests/utils/matching/parsing.py
.py
import re from typing import Iterable from httpie.output.writer import MESSAGE_SEPARATOR from .tokens import Expect from ...utils import CRLF SEPARATOR_RE = re.compile(f'^{MESSAGE_SEPARATOR}') KEY_VALUE_RE = re.compile(r'[\n]*((.*?):(.+)[\n]?)+[\n]*') def make_headers_re(message_type: Expect): assert message_t...
99
2,596
httpie
tests/utils/matching/test_matching.py
.py
""" Here we test our output parsing and matching implementation, not HTTPie itself. """ from httpie.models import ELAPSED_TIME_LABEL from httpie.output.writer import MESSAGE_SEPARATOR from ...utils import CRLF from . import assert_output_does_not_match, assert_output_matches, Expect def test_assert_output_matches_he...
215
5,827
httpie
tests/utils/matching/tokens.py
.py
from enum import Enum, auto class Expect(Enum): """ Predefined token types we can expect in the output. """ REQUEST_HEADERS = auto() RESPONSE_HEADERS = auto() RESPONSE_META = auto() BODY = auto() SEPARATOR = auto() class ExpectSequence: """ Standard combined chunks. These pr...
57
1,106
httpie
tests/fixtures/__init__.py
.py
"""Test data""" import json from pathlib import Path from typing import Optional, Dict, Any import httpie from httpie.encoding import UTF8 from httpie.output.formatters.xml import pretty_xml, parse_xml def patharg(path): """ Back slashes need to be escaped in ITEM args, even in Windows paths. """ ...
67
2,091
httpie
httpie/utils.py
.py
import os import base64 import json import mimetypes import re import sys import time import tempfile import sysconfig from collections import OrderedDict from contextlib import contextmanager from http.cookiejar import parse_ns_headers from pathlib import Path from pprint import pformat from urllib.parse import urlsp...
310
9,147
httpie
httpie/cookies.py
.py
from http import cookiejar _LOCALHOST = 'localhost' _LOCALHOST_SUFFIX = '.localhost' class HTTPieCookiePolicy(cookiejar.DefaultCookiePolicy): def return_ok_secure(self, cookie, request): """Check whether the given cookie is sent to a secure host.""" is_secure_protocol = super().return_ok_secure...
26
1,069
httpie
httpie/models.py
.py
from time import monotonic import requests from urllib3.util import SKIP_HEADER, SKIPPABLE_HEADERS from enum import Enum, auto from typing import Iterable, Union, NamedTuple from urllib.parse import urlsplit from .cli.constants import ( OUT_REQ_BODY, OUT_REQ_HEAD, OUT_RESP_BODY, OUT_RESP_HEAD, OU...
234
6,483
httpie
httpie/__main__.py
.py
"""The main entry point. Invoke as `http' or `python -m httpie'. """ def main(): try: from httpie.core import main exit_status = main() except KeyboardInterrupt: from httpie.status import ExitStatus exit_status = ExitStatus.ERROR_CTRL_C return exit_status.value if __nam...
20
394
httpie
httpie/__init__.py
.py
""" HTTPie: modern, user-friendly command-line HTTP client for the API era. """ __version__ = '3.2.4' __date__ = '2024-11-01' __author__ = 'Jakub Roztocil' __licence__ = 'BSD'
10
178
httpie
httpie/sessions.py
.py
""" Persistent, JSON-serialized sessions. """ import os import re from http.cookies import SimpleCookie from http.cookiejar import Cookie from pathlib import Path from typing import Any, Dict, List, Optional, Union from requests.auth import AuthBase from requests.cookies import RequestsCookieJar, remove_cookie_by_na...
323
9,705
httpie
httpie/uploads.py
.py
import sys import os import zlib import functools import threading from typing import Any, Callable, IO, Iterable, Optional, Tuple, Union, TYPE_CHECKING from urllib.parse import urlencode import requests from requests.utils import super_len if TYPE_CHECKING: from requests_toolbelt import MultipartEncoder from .c...
270
7,744
httpie
httpie/adapters.py
.py
from httpie.cli.dicts import HTTPHeadersDict from requests.adapters import HTTPAdapter class HTTPieHTTPAdapter(HTTPAdapter): def build_response(self, req, resp): """Wrap the original headers with the `HTTPHeadersDict` to preserve multiple headers that have the same name""" response = sup...
14
448
httpie
httpie/ssl_.py
.py
import ssl from typing import NamedTuple, Optional # noinspection PyPackageRequirements from urllib3.util.ssl_ import ( create_urllib3_context, resolve_ssl_version, ) from .adapters import HTTPAdapter from .compat import ensure_default_certs_loaded SSL_VERSION_ARG_MAPPING = { 'ssl2.3': 'PROTOCOL_SSLv23'...
110
3,408
httpie
httpie/client.py
.py
import argparse import http.client import json import sys from contextlib import contextmanager from time import monotonic from typing import Any, Dict, Callable, Iterable from urllib.parse import urlparse, urlunparse import requests # noinspection PyPackageRequirements import urllib3 from urllib3.util import SKIP_HEA...
401
13,396
httpie
httpie/context.py
.py
import argparse import sys import os import warnings from contextlib import contextmanager from pathlib import Path from typing import Iterator, IO, Optional, TYPE_CHECKING from enum import Enum try: import curses except ImportError: curses = None # Compiled w/o curses from .compat import is_windows, cached...
218
6,739
httpie
httpie/encoding.py
.py
from typing import Union, Tuple from charset_normalizer import from_bytes from charset_normalizer.constant import TOO_SMALL_SEQUENCE UTF8 = 'utf-8' ContentBytes = Union[bytearray, bytes] def detect_encoding(content: ContentBytes) -> str: """ We default to UTF-8 if text too short, because the detection ...
51
1,385
httpie
httpie/status.py
.py
from enum import IntEnum, unique @unique class ExitStatus(IntEnum): """Program exit status code constants.""" SUCCESS = 0 ERROR = 1 ERROR_TIMEOUT = 2 # See --check-status ERROR_HTTP_3XX = 3 ERROR_HTTP_4XX = 4 ERROR_HTTP_5XX = 5 ERROR_TOO_MANY_REDIRECTS = 6 PLUGIN_ERROR = 7 ...
41
987
httpie
httpie/compat.py
.py
import sys from ssl import SSLContext from typing import Any, Optional, Iterable from httpie.cookies import HTTPieCookiePolicy from http import cookiejar # noqa # Request does not carry the original policy attached to the # cookie jar, so until it is resolved we change the global cookie # policy. <https://github.co...
114
3,847
httpie
httpie/config.py
.py
import json import os from pathlib import Path from typing import Any, Dict, Union from . import __version__ from .compat import is_windows from .encoding import UTF8 ENV_XDG_CONFIG_HOME = 'XDG_CONFIG_HOME' ENV_HTTPIE_CONFIG_DIR = 'HTTPIE_CONFIG_DIR' DEFAULT_CONFIG_DIRNAME = 'httpie' DEFAULT_RELATIVE_XDG_CONFIG_HOME...
173
5,005
httpie
httpie/downloads.py
.py
""" Download mode implementation. """ import mimetypes import os import re from mailbox import Message from time import monotonic from typing import IO, Optional, Tuple from urllib.parse import urlsplit import requests from .models import HTTPResponse, OutputOptions from .output.streams import RawStream from .contex...
378
11,802
httpie
httpie/core.py
.py
import argparse import os import platform import sys import socket from typing import List, Optional, Union, Callable import requests from pygments import __version__ as pygments_version from requests import __version__ as requests_version from . import __version__ as httpie_version from .cli.constants import OUT_REQ...
299
10,450
httpie
httpie/output/utils.py
.py
import json import re from typing import Tuple from ..utils import load_json_preserve_order_and_dupe_keys from .lexers.json import PREFIX_REGEX def load_prefixed_json(data: str) -> Tuple[str, json.JSONDecoder]: """Simple JSON loading from `data`. """ # First, the full data. try: return '', l...
38
1,066
httpie
httpie/output/writer.py
.py
import errno import requests from typing import Any, Dict, IO, Optional, TextIO, Tuple, Type, Union from ..cli.dicts import HTTPHeadersDict from ..context import Environment from ..models import ( HTTPRequest, HTTPResponse, HTTPMessage, RequestsMessage, RequestsMessageKind, OutputOptions, ) fro...
205
6,515
httpie
httpie/output/models.py
.py
import argparse from typing import Any, Dict, Union, List, NamedTuple, Optional from httpie.context import Environment from httpie.cli.constants import PrettyOptions, PRETTY_MAP, PRETTY_STDOUT_TTY_ONLY from httpie.cli.argtypes import PARSED_DEFAULT_FORMAT_OPTIONS from httpie.output.formatters.colors import AUTO_STYLE ...
45
1,400
httpie
httpie/output/streams.py
.py
from abc import ABCMeta, abstractmethod from itertools import chain from typing import Callable, Iterable, Optional, Union from .processing import Conversion, Formatting from ..context import Environment from ..encoding import smart_decode, smart_encode, UTF8 from ..models import HTTPMessage, OutputOptions from ..util...
255
8,155
httpie
httpie/output/processing.py
.py
import re from typing import Optional, List from ..plugins import ConverterPlugin from ..plugins.registry import plugin_manager from ..context import Environment MIME_RE = re.compile(r'^[^/]+/[^/]+$') def is_valid_mime(mime): return mime and MIME_RE.match(mime) class Conversion: @staticmethod def ge...
59
1,763
httpie
httpie/output/lexers/json.py
.py
import re from pygments.lexer import bygroups, using, RegexLexer from pygments.lexers.data import JsonLexer from pygments.token import Token PREFIX_TOKEN = Token.Error PREFIX_REGEX = r'[^{\["]+' class EnhancedJsonLexer(RegexLexer): """ Enhanced JSON lexer for Pygments. It adds support for eventual data...
32
851
httpie
httpie/output/lexers/metadata.py
.py
import pygments from httpie.models import ELAPSED_TIME_LABEL from httpie.output.lexers.common import precise SPEED_TOKENS = { 0.45: pygments.token.Number.SPEED.FAST, 1.00: pygments.token.Number.SPEED.AVG, 2.50: pygments.token.Number.SPEED.SLOW, } def speed_based_token(lexer, match, ctx): try: ...
60
1,672
httpie
httpie/output/lexers/http.py
.py
import re import pygments from httpie.output.lexers.common import precise RE_STATUS_LINE = re.compile(r'(\d{3})( +)?(.+)?') STATUS_TYPES = { '1': pygments.token.Number.HTTP.INFO, '2': pygments.token.Number.HTTP.OK, '3': pygments.token.Number.HTTP.REDIRECT, '4': pygments.token.Number.HTTP.CLIENT_ERR, ...
98
3,044
httpie
httpie/output/lexers/common.py
.py
def precise(lexer, precise_token, parent_token): # Due to a pygments bug*, custom tokens will look bad # on outside styles. Until it is fixed on upstream, we'll # convey whether the client is using pie style or not # through precise option and return more precise tokens # depending on it's value. ...
13
517
httpie
httpie/output/formatters/xml.py
.py
from typing import TYPE_CHECKING, Optional from ...encoding import UTF8 from ...plugins import FormatterPlugin if TYPE_CHECKING: from xml.dom.minidom import Document XML_DECLARATION_OPEN = '<?xml' XML_DECLARATION_CLOSE = '?>' def parse_xml(data: str) -> 'Document': """Parse given XML `data` string into an...
80
2,505
httpie
httpie/output/formatters/json.py
.py
import json from ...plugins import FormatterPlugin class JSONFormatter(FormatterPlugin): def __init__(self, **kwargs): super().__init__(**kwargs) self.enabled = self.format_options['json']['format'] def format_body(self, body: str, mime: str) -> str: maybe_json = [ 'json...
35
1,123
httpie
httpie/output/formatters/headers.py
.py
from ...plugins import FormatterPlugin class HeadersFormatter(FormatterPlugin): def __init__(self, **kwargs): super().__init__(**kwargs) self.enabled = self.format_options['headers']['sort'] def format_headers(self, headers: str) -> str: """ Sorts headers by name while retain...
19
552
httpie
httpie/output/formatters/colors.py
.py
import json from typing import Optional, Type, Tuple import pygments.formatters import pygments.lexer import pygments.lexers import pygments.style import pygments.styles import pygments.token from pygments.formatters.terminal import TerminalFormatter from pygments.formatters.terminal256 import Terminal256Formatter fro...
389
13,002
httpie
httpie/output/ui/rich_help.py
.py
import re import textwrap from typing import AbstractSet, Iterable, Optional, Tuple from rich.console import RenderableType from rich.highlighter import RegexHighlighter from rich.padding import Padding from rich.table import Table from rich.text import Text from httpie.cli.constants import SEPARATOR_GROUP_ALL_ITEMS ...
231
6,565
httpie
httpie/output/ui/rich_progress.py
.py
from dataclasses import dataclass from typing import TYPE_CHECKING, Optional from httpie.context import Environment if TYPE_CHECKING: from rich.console import Console @dataclass class BaseDisplay: env: Environment def start( self, *, total: Optional[float], at: float, description: str ) -> ...
142
3,980
httpie
httpie/output/ui/rich_utils.py
.py
import os from typing import Iterator from contextlib import contextmanager from rich.console import Console, RenderableType from rich.highlighter import Highlighter from httpie.output.ui.rich_palette import _make_rich_color_theme def render_as_string(renderable: RenderableType) -> str: """Render any `rich` ob...
35
973
httpie
httpie/output/ui/palette.py
.py
from dataclasses import dataclass, field from enum import Enum, auto from typing import Optional, List PYGMENTS_BRIGHT_BLACK = 'ansibrightblack' AUTO_STYLE = 'auto' # Follows terminal ANSI color styles class Styles(Enum): PIE = auto() ANSI = auto() class PieStyle(str, Enum): UNIVERSAL = 'pie' DA...
270
7,226
httpie
httpie/output/ui/rich_palette.py
.py
from collections import ChainMap from typing import TYPE_CHECKING, Any, Optional if TYPE_CHECKING: from rich.theme import Theme from httpie.output.ui.palette import GenericColor, PieStyle, Styles, ColorString, _StyledGenericColor # noqa RICH_BOLD = ColorString('bold') # Rich-specific color code declarations # ...
74
2,294
httpie
httpie/output/ui/man_pages.py
.py
"""Logic for checking and displaying man pages.""" import subprocess import os from httpie.context import Environment MAN_COMMAND = 'man' NO_MAN_PAGES = os.getenv('HTTPIE_NO_MAN_PAGES', False) # On some systems, HTTP(n) might exist, but we are only interested in HTTP(1). # For more information on man page sections:...
49
1,305
httpie
httpie/internal/daemons.py
.py
""" This module provides an interface to spawn a detached task to be run with httpie.internal.daemon_runner on a separate process. It is based on DVC's daemon system. https://github.com/iterative/dvc/blob/main/dvc/daemon.py """ import inspect import os import platform import sys import httpie.__main__ from contextlib ...
122
3,403
httpie
httpie/internal/daemon_runner.py
.py
import argparse from contextlib import redirect_stderr, redirect_stdout from typing import List from httpie.context import Environment from httpie.internal.update_warnings import _fetch_updates, _get_suppress_context from httpie.status import ExitStatus STATUS_FILE = '.httpie-test-daemon-status' def _check_status(e...
51
1,521
httpie
httpie/internal/update_warnings.py
.py
import json from contextlib import nullcontext, suppress from datetime import datetime, timedelta from pathlib import Path from typing import Any, Optional, Callable import requests import httpie from httpie.context import Environment, LogLevel from httpie.internal.__build_channel__ import BUILD_CHANNEL from httpie.i...
172
5,178
httpie
httpie/manager/__main__.py
.py
import argparse import sys from typing import List, Union from httpie.context import Environment from httpie.status import ExitStatus from httpie.manager.cli import parser from httpie.manager.core import MSG_COMMAND_CONFUSION, program as main_program def is_http_command(args: List[Union[str, bytes]], env: Environme...
62
1,707
httpie
httpie/manager/compat.py
.py
import sys import shutil import subprocess from contextlib import suppress from typing import List, Optional from httpie.compat import is_frozen class PipError(Exception): """An exception that occurs when pip exits with an error status code.""" def __init__(self, stdout, stderr): self.stdout = stdou...
69
2,001
httpie
httpie/manager/cli.py
.py
from textwrap import dedent from httpie.cli.argparser import HTTPieManagerArgumentParser from httpie.cli.options import Qualifiers, ARGPARSE_QUALIFIER_MAP, map_qualifiers, parser_to_parser_spec from httpie import __version__ CLI_SESSION_UPGRADE_FLAGS = [ { 'flags': ['--bind-cookies'], 'action': 'st...
182
5,371