0
# Constants and Utilities
1
2
HTTPie provides various constants, utility functions, and helper classes for HTTP processing and command-line parsing.
3
4
```python
5
from httpie.cli.constants import *
6
from httpie.utils import *
7
from httpie.status import ExitStatus
8
from typing import Any, List, Optional, Tuple, Dict
9
import enum
10
```
11
12
## Capabilities
13
14
### HTTP Method Constants
15
16
Standard HTTP method constants used throughout HTTPie.
17
18
```python { .api }
19
HTTP_GET: str = 'GET'
20
HTTP_POST: str = 'POST'
21
HTTP_OPTIONS: str = 'OPTIONS'
22
```
23
24
### Request Separators
25
26
Constants defining separators for parsing command-line request items.
27
28
```python { .api }
29
# Header separators
30
SEPARATOR_HEADER: str = ':'
31
SEPARATOR_HEADER_EMPTY: str = ';'
32
SEPARATOR_HEADER_EMBED: str = ':@'
33
34
# Data separators
35
SEPARATOR_DATA_STRING: str = '='
36
SEPARATOR_DATA_RAW_JSON: str = ':='
37
SEPARATOR_DATA_EMBED_FILE_CONTENTS: str = '=@'
38
SEPARATOR_DATA_EMBED_RAW_JSON_FILE: str = ':=@'
39
40
# File upload separator
41
SEPARATOR_FILE_UPLOAD: str = '@'
42
43
# Query parameter separators
44
SEPARATOR_QUERY_PARAM: str = '=='
45
SEPARATOR_QUERY_EMBED_FILE: str = '==@'
46
47
# Separator groups
48
SEPARATOR_GROUP_DATA_ITEMS: frozenset
49
SEPARATORS_GROUP_MULTIPART: frozenset
50
SEPARATOR_GROUP_ALL_ITEMS: frozenset
51
```
52
53
### Output Options Constants
54
55
Constants for controlling HTTPie output display.
56
57
```python { .api }
58
# Output option characters
59
OUT_REQ_HEAD: str = 'H' # Request headers
60
OUT_REQ_BODY: str = 'B' # Request body
61
OUT_RESP_HEAD: str = 'h' # Response headers
62
OUT_RESP_BODY: str = 'b' # Response body
63
OUT_RESP_META: str = 'm' # Response metadata
64
65
# Output option groups
66
BASE_OUTPUT_OPTIONS: frozenset
67
OUTPUT_OPTIONS: frozenset
68
69
# Default output configurations
70
OUTPUT_OPTIONS_DEFAULT: str
71
OUTPUT_OPTIONS_DEFAULT_STDOUT_REDIRECTED: str
72
OUTPUT_OPTIONS_DEFAULT_OFFLINE: str
73
```
74
75
### Pretty Printing Options
76
77
Configuration for output formatting and colorization.
78
79
```python { .api }
80
class PrettyOptions(enum.Enum):
81
STDOUT_TTY_ONLY = enum.auto()
82
83
PRETTY_MAP: Dict[str, List[str]] = {
84
'all': ['format', 'colors'],
85
'colors': ['colors'],
86
'format': ['format'],
87
'none': []
88
}
89
90
DEFAULT_FORMAT_OPTIONS: List[str]
91
SORTED_FORMAT_OPTIONS: List[str]
92
```
93
94
### Utility Functions
95
96
General utility functions for HTTP processing and data handling.
97
98
```python { .api }
99
def load_json_preserve_order_and_dupe_keys(s: str) -> 'JsonDictPreservingDuplicateKeys':
100
"""Load JSON string preserving order and duplicate keys."""
101
102
def humanize_bytes(n: int, precision: int = 2) -> str:
103
"""Convert byte count to human-readable format."""
104
105
def get_content_type(filename: str) -> str:
106
"""Guess content type from filename."""
107
108
def split_cookies(cookie_header: str) -> List[str]:
109
"""Split Set-Cookie header value into individual cookies."""
110
111
def parse_content_type_header(header: str) -> Tuple[str, Dict[str, str]]:
112
"""Parse Content-Type header into type and parameters."""
113
114
def url_as_host(url: str) -> str:
115
"""Extract hostname from URL."""
116
117
def repr_dict(d: dict) -> str:
118
"""Create readable string representation of dictionary."""
119
120
def unwrap_context(exception: Exception) -> Exception:
121
"""Unwrap exception context to find root cause."""
122
```
123
124
### Specialized Classes
125
126
Utility classes for specific HTTP processing needs.
127
128
```python { .api }
129
class JsonDictPreservingDuplicateKeys(OrderedDict):
130
"""A specialized JSON dict preserving duplicate keys."""
131
132
SUPPORTS_SORTING: bool
133
134
def __init__(self, items: List[Tuple[str, Any]]): ...
135
136
class ExplicitNullAuth(requests.auth.AuthBase):
137
"""Authentication class for explicitly disabling auth."""
138
139
def __call__(self, request): ...
140
141
class LockFileError(Exception):
142
"""File locking related error."""
143
pass
144
```
145
146
### Cookie Utilities
147
148
Functions for handling HTTP cookies.
149
150
```python { .api }
151
def get_expired_cookies(jar: requests.cookies.RequestsCookieJar, host: str) -> List[str]:
152
"""Get list of expired cookie names for a host."""
153
154
def parse_cookie_header(header: str) -> Dict[str, str]:
155
"""Parse cookie header into name-value pairs."""
156
```
157
158
### File and Path Utilities
159
160
Utilities for file handling and path operations.
161
162
```python { .api }
163
def get_content_type(filename: str) -> Optional[str]:
164
"""Determine MIME type from filename."""
165
166
def is_file_path(value: str) -> bool:
167
"""Check if string represents a file path."""
168
169
def normalize_file_path(path: str) -> str:
170
"""Normalize file path for cross-platform compatibility."""
171
```
172
173
### Usage Examples
174
175
#### Using Constants for Request Parsing
176
177
```python
178
from httpie.cli.constants import SEPARATOR_DATA_STRING, SEPARATOR_HEADER
179
180
def parse_request_item(item: str):
181
if SEPARATOR_DATA_STRING in item:
182
key, value = item.split(SEPARATOR_DATA_STRING, 1)
183
return 'data', key, value
184
elif SEPARATOR_HEADER in item:
185
key, value = item.split(SEPARATOR_HEADER, 1)
186
return 'header', key, value
187
return 'unknown', item, None
188
```
189
190
#### Utility Function Usage
191
192
```python
193
from httpie.utils import humanize_bytes, get_content_type
194
195
# Format file sizes
196
size = humanize_bytes(1536) # Returns "1.5 KB"
197
198
# Detect content types
199
content_type = get_content_type('data.json') # Returns "application/json"
200
```
201
202
#### JSON Processing with Duplicate Keys
203
204
```python
205
from httpie.utils import JsonDictPreservingDuplicateKeys
206
207
# Preserve duplicate keys in JSON
208
data = JsonDictPreservingDuplicateKeys([
209
("name", "John"),
210
("name", "Jane"), # Duplicate key preserved
211
("age", 30)
212
])
213
214
json_str = json.dumps(data, indent=2)
215
```
216
217
### Error Handling
218
219
```python
220
from httpie.utils import LockFileError
221
222
try:
223
# File operations that might fail
224
with file_lock('/tmp/httpie.lock'):
225
process_data()
226
except LockFileError as e:
227
print(f"Could not acquire file lock: {e}")
228
```