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.Headers inherits all methods from Pyjo.Base and Pyjo.String.Mixin and implements the following new ones.

__bool__() → bool[source]
boolean = bool(headers)

Always true, also without headers.

__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 raises KeyError for a header that does not exist.

__iter__() → Iterator[str][source]
names = list(headers)

Iterate over names().

__len__() → int[source]
size = len(headers)

Number of headers, with the values of a header counting once.

__str__() → str[source]
string = str(headers)

Alias for to_str().

accept
accept = headers.accept
headers.accept = '*/*'

Get or replace current header value, shortcut for the Accept header.

accept_charset
accept_charset = headers.accept_charset
headers.accept_charset = 'UTF-8'

Get or replace current header value, shortcut for the Accept-Charset header.

accept_encoding
accept_encoding = headers.accept_encoding
headers.accept_encoding = 'gzip'

Get or replace current header value, shortcut for the Accept-Encoding header.

accept_language
accept_language = headers.accept_language
headers.accept_language = 'de, en'

Get or replace current header value, shortcut for the Accept-Language header.

accept_ranges
accept_ranges = headers.accept_ranges
headers.accept_ranges = 'bytes'

Get or replace current header value, shortcut for the Accept-Ranges header.

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-Origin header 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 Allow header.

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 Authorization header.

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-Control header.

clone() → Self[source]
clone = headers.clone()

Return a new Pyjo.Headers object cloned from these headers.

connection
connection = headers.connection
headers.connection = 'close'

Get or replace current header value, shortcut for the Connection header.

content_disposition
content_disposition = headers.content_disposition
headers.content_disposition = 'foo'

Get or replace current header value, shortcut for the Content-Disposition header.

content_encoding
content_encoding = headers.content_encoding
headers.content_encoding = 'gzip'

Get or replace current header value, shortcut for the Content-Encoding header.

content_language
content_language = headers.content_language
headers.content_language = 'en'

Get or replace current header value, shortcut for the Content-Language header.

content_length
content_length = headers.content_length
headers.content_length = 4000

Get or replace current header value, shortcut for the Content-Length header.

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-Location header.

content_range
content_range = headers.content_range
headers.content_range = 'bytes 2-8/100'

Get or replace current header value, shortcut for the Content-Range header.

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-Policy header 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-Type header.

cookie
cookie = headers.cookie
headers.cookie = 'f=b'

Get or replace current header value, shortcut for the Cookie header 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 Date header.

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 DNT header (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 ETag header.

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 Expect header.

expires
expires = headers.expires
headers.expires = 'Thu, 01 Dec 1994 16:00:00 GMT'

Get or replace current header value, shortcut for the Expires header.

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 Host header.

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-Since header.

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-Match header.

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_size or max_lines.

items() → list[tuple[str, str]][source]
items = headers.items()

Return a list of names() with the values that header() gives.

keys() → list[str][source]
names = headers.keys()

Alias for names().

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-Modified header.

leftovers() → bytes[source]
data = headers.leftovers()

Get and remove leftover data from header parser.

link = headers.link
headers.link = '<http://127.0.0.1/foo/3>; rel="next"'

Get or replace current header value, shortcut for the Link header from RFC 5988.

links = headers.links
headers.links = {'next': 'http://example.com/foo', 'prev': 'http://example.com/bar'}

Get or set web links from or to Link header 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 Location header.

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_SIZE environment variable or 8192 (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_LINES environment variable or 100.

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 Origin header 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-Authenticate header.

proxy_authorization
proxy_authorization = headers.proxy_authorization
headers.proxy_authorization = 'Basic Zm9vOmJhcg=='

Get or replace current header value, shortcut for the Proxy-Authorization header.

range
range = headers.range
headers.range = 'bytes=2-8'

Get or replace current header value, shortcut for the Range header.

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 Referer header, there was a typo in RFC 2068 which resulted in Referer becoming an official header.

remove(name: str) → Self[source]
headers = headers.remove('Foo')

Remove a 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-Accept header 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-Extensions header 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-Key header 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-Protocol header 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-Version header from RFC 6455.

server
server = headers.server
headers.server = 'Pyjoyment'

Get or replace current header value, shortcut for the Server header.

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-Timing header from Server Timing.

set_cookie = headers.set_cookie
headers.set_cookie = 'f=b; path=/'

Get or replace current header value, shortcut for the Set-Cookie header from RFC 6265.

status
status = headers.status
headers.status = '200 OK'

Get or replace current header value, shortcut for the Status header 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-Security header from RFC 6797.

te
te = headers.te
headers.te = 'chunked'

Get or replace current header value, shortcut for the TE header.

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, as http.client has 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 Trailer header.

transfer_encoding
transfer_encoding = headers.transfer_encoding
headers.transfer_encoding = 'chunked'

Get or replace current header value, shortcut for the Transfer-Encoding header.

upgrade
upgrade = headers.upgrade
headers.upgrade = 'websocket'

Get or replace current header value, shortcut for the Upgrade header.

user_agent
user_agent = headers.user_agent
headers.user_agent = 'Pyjoyment/1.0'

Get or replace current header value, shortcut for the User-Agent header.

values() → list[str][source]
values = headers.values()

Return a list of the values that header() gives, in the order of names().

vary
vary = headers.vary
headers.vary = '*'

Get or replace current header value, shortcut for the Vary header.

www_authenticate
www_authenticate = headers.www_authenticate
headers.www_authenticate = 'Basic realm="realm"'

Get or replace current header value, shortcut for the WWW-Authenticate header.