How to use the httpie.context.Environment function in httpie

To help you get started, we’ve selected a few httpie examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github jakubroztocil / httpie / tests / utils.py View on Github external
'[38;5;37m1.1\x1b[39m\x1b[38;5;245m \x1b[39m\x1b[38;5;37m200'
    '\x1b[39m\x1b[38;5;245m \x1b[39m\x1b[38;5;136mOK'
)


def mk_config_dir() -> Path:
    dirname = tempfile.mkdtemp(prefix='httpie_config_')
    return Path(dirname)


def add_auth(url, auth):
    proto, rest = url.split('://', 1)
    return proto + '://' + auth + '@' + rest


class MockEnvironment(Environment):
    """Environment subclass with reasonable defaults for testing."""
    colors = 0
    stdin_isatty = True,
    stdout_isatty = True
    is_windows = False

    def __init__(self, create_temp_config_dir=True, **kwargs):
        if 'stdout' not in kwargs:
            kwargs['stdout'] = tempfile.TemporaryFile(
                mode='w+b',
                prefix='httpie_stdout'
            )
        if 'stderr' not in kwargs:
            kwargs['stderr'] = tempfile.TemporaryFile(
                mode='w+t',
                prefix='httpie_stderr'
github jakubroztocil / httpie / tests / test_httpie.py View on Github external
def test_main_entry_point():
    # Patch stdin to bypass pytest capture
    with mock.patch.object(Environment, 'stdin', io.StringIO()):
        with pytest.raises(SystemExit) as e:
            httpie.__main__.main()
        assert e.value.code == ExitStatus.ERROR
github jakubroztocil / httpie / tests / test_httpie.py View on Github external
def test_main_entry_point_keyboard_interrupt(main):
    main.side_effect = KeyboardInterrupt()
    with mock.patch.object(Environment, 'stdin', io.StringIO()):
        with pytest.raises(SystemExit) as e:
            httpie.__main__.main()
        assert e.value.code == ExitStatus.ERROR_CTRL_C
github eliangcs / http-prompt / http_prompt / execution.py View on Github external
quoted_filepath = ('"' dquoted_filepath_char+ '"') /
                          ("'" squoted_filepath_char+ "'")
        dquoted_filepath_char = ~r'[^\r\n"]'
        squoted_filepath_char = ~r"[^\r\n']"
        unquoted_filepath = unquoted_filepath_char+
        unquoted_filepath_char = ~r"[^\s\"]"
    """
else:
    grammar += r"""
        filepath = string
    """

grammar = Grammar(grammar)


if Environment.colors == 256:
    from pygments.formatters.terminal256 import (
        Terminal256Formatter as TerminalFormatter)
else:
    from pygments.formatters.terminal import TerminalFormatter


def urljoin2(base, path, **kwargs):
    if not base.endswith('/'):
        base += '/'
    url = urljoin(base, path, **kwargs)
    if url.endswith('/') and not path.endswith('/'):
        url = url[:-1]
    return url


def generate_help_text():
github jakubroztocil / httpie / httpie / output / streams.py View on Github external
    def __init__(self, env=Environment(), **kwargs):
        super().__init__(**kwargs)
        if env.stdout_isatty:
            # Use the encoding supported by the terminal.
            output_encoding = env.stdout_encoding
        else:
            # Preserve the message encoding.
            output_encoding = self.msg.encoding
        # Default to utf8 when unsure.
        self.output_encoding = output_encoding or 'utf8'
github jakubroztocil / httpie / httpie / output / processing.py View on Github external
    def __init__(self, groups: List[str], env=Environment(), **kwargs):
        """
        :param groups: names of processor groups to be applied
        :param env: Environment
        :param kwargs: additional keyword arguments for processors

        """
        available_plugins = plugin_manager.get_formatters_grouped()
        self.enabled_plugins = []
        for group in groups:
            for cls in available_plugins[group]:
                p = cls(env=env, **kwargs)
                if p.enabled:
                    self.enabled_plugins.append(p)
github eliangcs / http-prompt / http_prompt / httpiewrapper.py View on Github external
def request(node_visitor, context, method):
    content = None
    args = _httpie_args_from_context(context, method)
    output = BytesIO()
    try:
        env = Environment(stdout=output, is_windows=False)

        # XXX: httpie_main() doesn't provide an API for us to get the
        # HTTP response object, so we use this super dirty hack -
        # sys.settrace() to intercept get_response() that is called in
        # httpie_main() internally. The HTTP response intercepted is
        # assigned to nodeVisitor.last_response, which may be useful for
        # nodeVisitor.listener.
        sys.settrace(node_visitor._trace_get_response)
        try:
            httpie_main(args, env=env)
        finally:
            sys.settrace(None)

        content = output.getvalue()
    finally:
        output.close()
github eliangcs / http-prompt / http_prompt / execution.py View on Github external
def _call_httpie_main(self):
        context = self._final_context()
        args = extract_args_for_httpie_main(context, self.method)
        env = Environment(stdout=self.output, stdin=sys.stdin,
                          is_windows=False)
        env.stdout_isatty = self.output.isatty()
        env.stdin_isatty = sys.stdin.isatty()

        # XXX: httpie_main() doesn't provide an API for us to get the
        # HTTP response object, so we use this super dirty hack -
        # sys.settrace() to intercept get_response() that is called in
        # httpie_main() internally. The HTTP response intercepted is
        # assigned to self.last_response, which self.listener may be
        # interested in.
        sys.settrace(self._trace_get_response)
        try:
            httpie_main(args, env=env)
        finally:
            sys.settrace(None)
github mblayman / httpony / httpony / application.py View on Github external
def make_app():
    """Make a WSGI app that has all the HTTPie pieces baked in."""
    env = Environment()
    # STDIN is ignored because HTTPony runs a server that doesn't care.
    # Additionally, it is needed or else pytest blows up.
    args = parser.parse_args(args=["/", "--ignore-stdin"], env=env)
    args.output_options = "HB"  # Output only requests.
    server = "HTTPony/{0}".format(__version__)

    def application(environ, start_response):
        # The WSGI server puts content length and type in the environment
        # even when not provided with the request. Drop them if they are empty.
        if environ.get("CONTENT_LENGTH") == "":
            del environ["CONTENT_LENGTH"]
        if environ.get("CONTENT_TYPE") == "":
            del environ["CONTENT_TYPE"]

        wrequest = WerkzeugRequest(environ)
        data = wrequest.get_data()
github jakubroztocil / httpie / httpie / core.py View on Github external
def main(
    args: List[Union[str, bytes]] = sys.argv,
    env=Environment(),
) -> ExitStatus:
    """
    The main function.

    Pre-process args, handle some special types of invocations,
    and run the main program with error handling.

    Return exit status code.

    """
    program_name, *args = args
    env.program_name = os.path.basename(program_name)
    args = decode_raw_args(args, env.stdin_encoding)
    plugin_manager.load_installed_plugins()

    from httpie.cli.definition import parser