psycodict.encoding

This module provides functions for encoding data for storage in Postgres and decoding the results.

class psycodict.encoding.Json(obj)[source]

Bases: object

A wrapper marking a value for storage as json/jsonb, encoded with psycodict’s extended encoding (Sage types etc.).

With psycopg2 this subclassed psycopg2.extras.Json; with psycopg3 adaptation happens through JsonWrapperDumper below instead. The wrapped value is available as both .obj (psycopg3 convention) and .adapted (psycopg2 convention, kept for backward compatibility).

classmethod dumps(obj)[source]

Serialize obj to json text using the extended encoding (see prep()).

classmethod loads(s)[source]

Parse json text and decode the extended encoding back to Python and Sage objects (see extract()).

classmethod prep(obj, escape_backslashes=False)[source]

Returns a version of the object that is parsable by the standard json dumps function. For example, replace Integers with ints, encode various Sage types using dictionaries….

classmethod extract(obj)[source]

Takes an object extracted by the json parser and decodes the special-formating dictionaries used to store special types.

class psycodict.encoding.Array(seq)[source]

Bases: object

Since we use Json by default for lists, this class lets us get back the original behavior of encoding as a Postgres array when needed.

getquoted()[source]

The Postgres array literal for the wrapped sequence, as bytes.

psycodict.encoding.copy_dumps(inp, typ, recursing=False, *, sep='|')[source]

Output a string formatted as needed for loading by Postgres’ COPY FROM.

INPUT:

  • inp – a Python or Sage object that directly translates to a postgres type (e.g. Integer, RealLiteral, dict…

  • typ – the Postgres type of the column in which this data is being stored.

  • recursing – used internally to format the elements of an array. The value is rendered as an array member (quoted and escaped for the array parser as needed) rather than as a complete COPY field, and sep plays no role: the separator is escaped in a single pass over the assembled field by the top-level call.

  • sep – (keyword only) the column separator that the resulting file will be loaded with (default "|"). Occurrences of this character anywhere in the formatted field – inside text values, but also in dates and negative numbers for sep="-", times for sep=":", JSON text and the braces, commas and quotes of array literals – are backslash-escaped, matching what Postgres’ COPY (text format) does on output, so that they are not mistaken for column boundaries on the way back in. This must agree with the separator eventually passed to COPY FROM. Separators that cannot work (see check_copy_sep()) raise a ValueError.