Pyjo.Headers - HTTP headers¶
from Pyjo.Headers import Headers
# Parse
headers = Headers()
headers.parse('Content-Length: 42\x0d\x0a')
headers.parse('Content-Type: text/html\x0d\x0a\x0d\x0a')
print(headers.content_length)
print(headers.content_type)
# Or import the module, as in Google Python Style Guide
import Pyjo.Headers
# Parse
headers = Pyjo.Headers.new()
headers.parse('Content-Length: 42\x0d\x0a')
headers.parse('Content-Type: text/html\x0d\x0a\x0d\x0a')
print(headers.content_length)
print(headers.content_type)
# Build
headers = Pyjo.Headers.new()
headers.content_length = 42
headers.content_type = 'text/plain'
print(headers.to_str())
Pyjo.Headers is a container for HTTP headers, based on RFC 7230 and
RFC 7231.
The values are strings; bytes from the wire are decoded as ISO-8859-1, as
http.client does.
The headers also work with the Python standard library: they take an
email.message.Message, such as http.client.HTTPMessage, a
dict or a list of pairs, they are a mapping of the names to the values
without regard to case, and they turn into an email.message.Message
with to_message() or into a list of pairs with to_list().
# "text/html"
Pyjo.Headers.new({'Content-Type': 'text/html'})['content-type']
# [('Vary', 'Accept'), ('Vary', 'Accept-Encoding')]
Pyjo.Headers.new([('Vary', 'Accept'), ('Vary', 'Accept-Encoding')]).to_list()
See also¶
Pyjoyment, https://mojolicious.org.
Ported from Mojo::Headers of Mojolicious 9.49.
Classes¶
- class Pyjo.Headers.Pyjo_Headers(headers: Message | dict[str, Anything] | list[tuple[str, Anything]] | Pyjo_Headers | None = None, *, max_line_size: int | None = None, max_lines: int | None = None)[source]¶
Pyjo.Headersinherits all methods fromPyjo.BaseandPyjo.String.Mixinand implements the following new ones.- __contains__(name: Anything) bool[source]¶
boolean = 'Content-Type' in headers
Check if a header exists, without regard to case.
- __getitem__(name: str) str[source]¶
value = headers['Content-Type']
Same as
header(), but raisesKeyErrorfor a header that does not exist.
- __len__() int[source]¶
size = len(headers)
Number of headers, with the values of a header counting once.
- accept¶
accept = headers.accept headers.accept = '*/*'
Get or replace current header value, shortcut for the
Acceptheader.
- accept_charset¶
accept_charset = headers.accept_charset headers.accept_charset = 'UTF-8'
Get or replace current header value, shortcut for the
Accept-Charsetheader.
- accept_encoding¶
accept_encoding = headers.accept_encoding headers.accept_encoding = 'gzip'
Get or replace current header value, shortcut for the
Accept-Encodingheader.
- accept_language¶
accept_language = headers.accept_language headers.accept_language = 'de, en'
Get or replace current header value, shortcut for the
Accept-Languageheader.
- accept_ranges¶
accept_ranges = headers.accept_ranges headers.accept_ranges = 'bytes'
Get or replace current header value, shortcut for the
Accept-Rangesheader.
- access_control_allow_origin¶
access_control_allow_origin = headers.access_control_allow_origin headers.access_control_allow_origin = '*'
Get or replace current header value, shortcut for the
Access-Control-Allow-Originheader from Cross-Origin Resource Sharing.
- add(name: str, *values: Anything) Self[source]¶
headers = headers.add('Foo', 'one value') headers = headers.add('Foo', 'first value', 'second value')
Add header with one or more lines.
# "Vary: Accept # Vary: Accept-Encoding" headers.add('Vary', 'Accept').add('Vary', 'Accept-Encoding').to_str()
- allow¶
allow = headers.allow headers.allow = 'GET, POST'
Get or replace current header value, shortcut for the
Allowheader.
- append(name: str, value: Anything) Self[source]¶
headers = headers.append('Vary', 'Accept-Encoding')
Append value to header and flatten it if necessary.
# "Vary: Accept" headers.append('Vary', 'Accept').to_str() # "Vary: Accept, Accept-Encoding" headers.set(vary='Accept').append('Vary', 'Accept-Encoding').to_str()
- authorization¶
authorization = headers.authorization headers.authorization = 'Basic Zm9vOmJhcg=='
Get or replace current header value, shortcut for the
Authorizationheader.
- cache_control¶
cache_control = headers.cache_control headers.cache_control = 'max-age=1, no-cache'
Get or replace current header value, shortcut for the
Cache-Controlheader.
- clone() Self[source]¶
clone = headers.clone()
Return a new
Pyjo.Headersobject cloned from these headers.
- connection¶
connection = headers.connection headers.connection = 'close'
Get or replace current header value, shortcut for the
Connectionheader.
- content_disposition¶
content_disposition = headers.content_disposition headers.content_disposition = 'foo'
Get or replace current header value, shortcut for the
Content-Dispositionheader.
- content_encoding¶
content_encoding = headers.content_encoding headers.content_encoding = 'gzip'
Get or replace current header value, shortcut for the
Content-Encodingheader.
- content_language¶
content_language = headers.content_language headers.content_language = 'en'
Get or replace current header value, shortcut for the
Content-Languageheader.
- content_length¶
content_length = headers.content_length headers.content_length = 4000
Get or replace current header value, shortcut for the
Content-Lengthheader.
- content_location¶
content_location = headers.content_location headers.content_location = 'http://127.0.0.1/foo'
Get or replace current header value, shortcut for the
Content-Locationheader.
- content_range¶
content_range = headers.content_range headers.content_range = 'bytes 2-8/100'
Get or replace current header value, shortcut for the
Content-Rangeheader.
- content_security_policy¶
content_security_policy = headers.content_security_policy headers.content_security_policy = 'default-src https:'
Get or replace current header value, shortcut for the
Content-Security-Policyheader from Content Security Policy 1.0.
- content_type¶
content_type = headers.content_type headers.content_type = 'text/plain'
Get or replace current header value, shortcut for the
Content-Typeheader.
- cookie¶
cookie = headers.cookie headers.cookie = 'f=b'
Get or replace current header value, shortcut for the
Cookieheader from RFC 6265.
- date¶
date = headers.date headers.date = 'Sun, 17 Aug 2008 16:27:35 GMT'
Get or replace current header value, shortcut for the
Dateheader.
- dehop() Self[source]¶
headers = headers.dehop()
Remove hop-by-hop headers that should not be retransmitted.
- dnt¶
dnt = headers.dnt headers.dnt = 1
Get or replace current header value, shortcut for the
DNTheader (Do Not Track), which has no specification yet, but is very commonly used.
- etag¶
etag = headers.etag headers.etag = '"abc321"'
Get or replace current header value, shortcut for the
ETagheader.
- every_header(name: str) list[str][source]¶
all = headers.every_header('Location')
Similar to
header(), but returns all headers sharing the same name as a list.# Get first header value print(headers.every_header('Location')[0])
- expect¶
expect = headers.expect headers.expect = '100-continue'
Get or replace current header value, shortcut for the
Expectheader.
- expires¶
expires = headers.expires headers.expires = 'Thu, 01 Dec 1994 16:00:00 GMT'
Get or replace current header value, shortcut for the
Expiresheader.
- from_dict(d: dict[str, Anything]) Self[source]¶
headers = headers.from_dict({'Cookie': 'a=b'}) headers = headers.from_dict({'Cookie': ['a=b', 'c=d']}) headers = headers.from_dict({})
Parse headers from a
dict, an empty one removes all headers.
- get(name: str, default: str | None = None) str | None[source]¶
value = headers.get('Content-Type') value = headers.get('Content-Type', 'text/plain')
Same as
header(), but returns the default for a header that does not exist.
- header(name: str, /) str | None[source]¶
- header(name: str, value: Anything, /, *values: Anything) Self
value = headers.header('Foo') headers = headers.header('Foo', 'one value') headers = headers.header('Foo', 'first value', 'second value')
Get or replace the current header values.
- host¶
host = headers.host headers.host = '127.0.0.1'
Get or replace current header value, shortcut for the
Hostheader.
- if_modified_since¶
if_modified_since = headers.if_modified_since headers.if_modified_since = 'Sun, 17 Aug 2008 16:27:35 GMT'
Get or replace current header value, shortcut for the
If-Modified-Sinceheader.
- if_none_match¶
if_none_match = headers.if_none_match headers.if_none_match = '"abc321"'
Get or replace current header value, shortcut for the
If-None-Matchheader.
- property is_finished: bool[source]¶
boolean = headers.is_finished
Check if header parser is finished.
- property is_limit_exceeded: bool[source]¶
boolean = headers.is_limit_exceeded
Check if headers have exceeded
max_line_sizeormax_lines.
- items() list[tuple[str, str]][source]¶
items = headers.items()
Return a list of
names()with the values thatheader()gives.
- last_modified¶
last_modified = headers.last_modified headers.last_modified = 'Sun, 17 Aug 2008 16:27:35 GMT'
Get or replace current header value, shortcut for the
Last-Modifiedheader.
- leftovers() bytes[source]¶
data = headers.leftovers()
Get and remove leftover data from header parser.
- link¶
link = headers.link headers.link = '<http://127.0.0.1/foo/3>; rel="next"'
Get or replace current header value, shortcut for the
Linkheader from RFC 5988.
- property links: dict[str, dict[str, str]][source]¶
links = headers.links headers.links = {'next': 'http://example.com/foo', 'prev': 'http://example.com/bar'}
Get or set web links from or to
Linkheader according to RFC 5988.# Extract information about next page print(headers.links['next']['link']) print(headers.links['next']['title'])
- location¶
location = headers.location headers.location = 'http://127.0.0.1/foo'
Get or replace current header value, shortcut for the
Locationheader.
- property max_line_size: int[source]¶
size = headers.max_line_size headers.max_line_size = 1024
Maximum header line size in bytes, defaults to the value of the
PYJO_MAX_LINE_SIZEenvironment variable or8192(8KiB).
- property max_lines: int[source]¶
num = headers.max_lines headers.max_lines = 200
Maximum number of header lines, defaults to the value of the
PYJO_MAX_LINESenvironment variable or100.
- names() list[str][source]¶
names = headers.names()
Return a list with all currently defined headers.
# Names of all headers for name in headers.names(): print(name)
- origin¶
origin = headers.origin headers.origin = 'http://example.com'
Get or replace current header value, shortcut for the
Originheader from RFC 6454.
- parse(chunk: str | bytes | bytearray) Self[source]¶
headers = headers.parse('Content-Type: text/plain\x0d\x0a\x0d\x0a')
Parse formatted headers, given as characters or as bytes.
- proxy_authenticate¶
proxy_authenticate = headers.proxy_authenticate headers.proxy_authenticate = 'Basic "realm"'
Get or replace current header value, shortcut for the
Proxy-Authenticateheader.
- proxy_authorization¶
proxy_authorization = headers.proxy_authorization headers.proxy_authorization = 'Basic Zm9vOmJhcg=='
Get or replace current header value, shortcut for the
Proxy-Authorizationheader.
- range¶
range = headers.range headers.range = 'bytes=2-8'
Get or replace current header value, shortcut for the
Rangeheader.
- property referer: str | None[source]¶
referrer = headers.referer headers.referer = 'http://example.com'
Alias for
referrer.
- property referrer: str | None[source]¶
referrer = headers.referrer headers.referrer = 'http://example.com'
Get or replace current header value, shortcut for the
Refererheader, there was a typo in RFC 2068 which resulted inRefererbecoming an official header.
- sec_websocket_accept¶
sec_websocket_accept = headers.sec_websocket_accept headers.sec_websocket_accept = 's3pPLMBiTxaQ9kYGzzhZRbK+xOo='
Get or replace current header value, shortcut for the
Sec-WebSocket-Acceptheader from RFC 6455.
- sec_websocket_extensions¶
sec_websocket_extensions = headers.sec_websocket_extensions headers.sec_websocket_extensions = 'foo'
Get or replace current header value, shortcut for the
Sec-WebSocket-Extensionsheader from RFC 6455.
- sec_websocket_key¶
sec_websocket_key = headers.sec_websocket_key headers.sec_websocket_key = 'dGhlIHNhbXBsZSBub25jZQ=='
Get or replace current header value, shortcut for the
Sec-WebSocket-Keyheader from RFC 6455.
- sec_websocket_protocol¶
sec_websocket_protocol = headers.sec_websocket_protocol headers.sec_websocket_protocol = 'sample'
Get or replace current header value, shortcut for the
Sec-WebSocket-Protocolheader from RFC 6455.
- sec_websocket_version¶
sec_websocket_version = headers.sec_websocket_version headers.sec_websocket_version = 13
Get or replace current header value, shortcut for the
Sec-WebSocket-Versionheader from RFC 6455.
- server¶
server = headers.server headers.server = 'Pyjoyment'
Get or replace current header value, shortcut for the
Serverheader.
- server_timing¶
server_timing = headers.server_timing headers.server_timing = 'app;desc=Pyjoyment;dur=0.0001'
Get or replace current header value, shortcut for the
Server-Timingheader from Server Timing.
- set_cookie¶
set_cookie = headers.set_cookie headers.set_cookie = 'f=b; path=/'
Get or replace current header value, shortcut for the
Set-Cookieheader from RFC 6265.
- status¶
status = headers.status headers.status = '200 OK'
Get or replace current header value, shortcut for the
Statusheader from RFC 3875.
- strict_transport_security¶
strict_transport_security = headers.strict_transport_security headers.strict_transport_security = 'max-age=31536000'
Get or replace current header value, shortcut for the
Strict-Transport-Securityheader from RFC 6797.
- te¶
te = headers.te headers.te = 'chunked'
Get or replace current header value, shortcut for the
TEheader.
- to_bytes() bytes[source]¶
data = headers.to_bytes()
Turn headers into bytes, suitable for HTTP messages, with the characters encoded as ISO-8859-1.
- to_dict(multi: bool = False) dict[str, str] | dict[str, list[str]][source]¶
single = headers.to_dict() multi = headers.to_dict(True)
Turn headers into
dict, lists to represent multiple headers with the same name are disabled by default.print(headers.to_dict()['DNT'])
- to_list() list[tuple[str, str]][source]¶
pairs = headers.to_list()
Turn headers into a list of pairs, one for each value, as WSGI and
http.client.HTTPResponse.getheaders()have them.
- to_message() Message[source]¶
message = headers.to_message()
Turn headers into an
email.message.Message, with each value as a header of its own, ashttp.clienthas them.
- to_str() str[source]¶
string = headers.to_str()
Turn headers into a string, suitable for HTTP messages.
- trailer¶
trailer = headers.trailer headers.trailer = 'X-Foo'
Get or replace current header value, shortcut for the
Trailerheader.
- transfer_encoding¶
transfer_encoding = headers.transfer_encoding headers.transfer_encoding = 'chunked'
Get or replace current header value, shortcut for the
Transfer-Encodingheader.
- upgrade¶
upgrade = headers.upgrade headers.upgrade = 'websocket'
Get or replace current header value, shortcut for the
Upgradeheader.
- user_agent¶
user_agent = headers.user_agent headers.user_agent = 'Pyjoyment/1.0'
Get or replace current header value, shortcut for the
User-Agentheader.
- values() list[str][source]¶
values = headers.values()
Return a list of the values that
header()gives, in the order ofnames().
- vary¶
vary = headers.vary headers.vary = '*'
Get or replace current header value, shortcut for the
Varyheader.
- www_authenticate¶
www_authenticate = headers.www_authenticate headers.www_authenticate = 'Basic realm="realm"'
Get or replace current header value, shortcut for the
WWW-Authenticateheader.