gws

Basic types.

This module contains essential type definitions and utilities from the core GWS library. It should be imported in every gws module.

Source code: gws

Subpackages

Package Contents

class gws.Data(*args, **kwargs)

Basic data object.

This object can be instantiated by passing one or or dict arguments and/or keyword args. All dicts keys and keywords become attributes of the object.

Accessing an undefined attribute returns None and no error is raised, unless the attribute name starts with an underscore.

get(key, default=None)

Get an attribute value.

Parameters:
  • key – Attribute name.

  • default – Default value, returned if the attribute is undefined.

setdefault(key, val)

Set an attribute value if not already set.

Parameters:
  • key – Attribute name.

  • val – Attribute value.

set(key, val)

Set an attribute value.

Parameters:
  • key – Attribute name.

  • val – Attribute value.

update(*args, **kwargs)

Update the object with keys and values from args and keywords.

Parameters:
  • *args – Dicts or Mappings.

  • kwargs – Keyword args.

gws.is_data_object(x)

True if the argument is a Data object.

gws.to_data_object(x) Data

Convert a value to a Data object.

If the argument is already a Data object, simply return it. If the argument is None, an empty object is returned.

Parameters:

x – A Mapping or None.

class gws.Enum

Bases: enum.Enum

Enumeration type.

Despite being declared as extending Enum (for IDE support), this class is actually just a simple object and intended to be used as a collection of attributes. It doesn’t provide any Enum-specific utilities.

The rationale behind this is that we need Enum members (e.g. Color.RED) to be scalars, and not complex objects as in the standard Enum.

gws.Extent: TypeAlias

An array of 4 elements representing extent coordinates [min-x, min-y, max-x, max-y].

gws.Point: TypeAlias

Point coordinates [x, y].

gws.Size: TypeAlias

Size [width, height].

class gws.Origin

Bases: Enum

Grid origin.

nw = 'nw'

north-west

sw = 'sw'

south-west

ne = 'ne'

north-east

se = 'se'

south-east

lt = 'nw'

left top

lb = 'sw'

left bottom

rt = 'ne'

right top

rb = 'se'

right bottom

gws.FilePath: TypeAlias

File path on the server.

gws.DirPath: TypeAlias

Directory path on the server.

gws.Duration: TypeAlias

Duration like 1w 2d 3h 4m 5s or an integer number of seconds.

gws.Color: TypeAlias

CSS color name.

gws.Regex: TypeAlias

Regular expression, as used in Python.

gws.FormatStr: TypeAlias

Format string as used in Python.

gws.DateStr: TypeAlias

ISO date string like 2019-01-30.

gws.DateTimeStr: TypeAlias

ISO datetime string like 2019-01-30 01:02:03.

gws.Url: TypeAlias

URL.

gws.ClassRef: TypeAlias

Class reference, a type, and ‘ext’ object or a class name.

class gws.Config(*args, **kwargs)

Bases: Data

Object configuration.

uid: str = ''

Unique ID.

class gws.Props(*args, **kwargs)

Bases: Data

Object properties.

uid: str = ''

Unique ID.

class gws.Request(*args, **kwargs)

Bases: Data

Command request.

projectUid: str | None

Unique ID of the project.

localeUid: str | None

Locale ID for this request.

class gws.EmptyRequest(*args, **kwargs)

Bases: Data

Empty command request.

class gws.ResponseError(*args, **kwargs)

Bases: Data

Response error.

code: int | None

Error code.

info: str | None

Information about the error.

class gws.Response(*args, **kwargs)

Bases: Data

Command response.

error: ResponseError | None

Response error.

status: int

Response status or exit code.

class gws.ContentResponse(*args, **kwargs)

Bases: Response

Web response with literal content.

asAttachment: bool

Serve the content as an attachment.

attachmentName: str

Name for the attachment.

content: bytes | str

Response content.

contentPath: str

Local path with the content.

mime: str

Response mime type.

headers: dict

Additional headers.

class gws.RedirectResponse(*args, **kwargs)

Bases: Response

Web redirect response.

location: str

Redirect URL.

headers: dict

Additional headers.

class gws.AttributeType

Bases: Enum

Feature attribute type.

bool = 'bool'
bytes = 'bytes'
date = 'date'
datetime = 'datetime'
feature = 'feature'
featurelist = 'featurelist'
file = 'file'
float = 'float'
floatlist = 'floatlist'
geometry = 'geometry'
int = 'int'
intlist = 'intlist'
str = 'str'
strlist = 'strlist'
time = 'time'
class gws.GeometryType

Bases: Enum

Feature geometry type.

OGC and SQL/MM geometry types.

References

OGC 06-103r4 (https://www.ogc.org/standards/sfa), https://postgis.net/docs/manual-3.3/using_postgis_dbmanagement.html

geometry = 'geometry'
point = 'point'
curve = 'curve'
surface = 'surface'
geometrycollection = 'geometrycollection'
linestring = 'linestring'
line = 'line'
linearring = 'linearring'
polygon = 'polygon'
triangle = 'triangle'
polyhedralsurface = 'polyhedralsurface'
tin = 'tin'
multipoint = 'multipoint'
multicurve = 'multicurve'
multilinestring = 'multilinestring'
multipolygon = 'multipolygon'
multisurface = 'multisurface'
circularstring = 'circularstring'
compoundcurve = 'compoundcurve'
curvepolygon = 'curvepolygon'
class gws.CliParams(*args, **kwargs)

Bases: Data

CLI params

gws.Acl: TypeAlias

Access Control list.

A list of tuples (ACL bit, role-name) where ACL bit is 1 if the access is allowed and 0 otherwise.

gws.AclStr: TypeAlias

A string of comma-separated pairs allow <role> or deny <role>.

class gws.Access

Bases: Enum

Access mode.

read = 'read'
write = 'write'
create = 'create'
delete = 'delete'
class gws.PermissionsConfig

Permissions configuration.

read: AclStr | None

Permission to read the object.

write: AclStr | None

Permission to change the object.

create: AclStr | None

Permission to create new objects.

delete: AclStr | None

Permission to delete objects.

edit: AclStr | None

A combination of read, write, create and delete.

class gws.ConfigWithAccess(*args, **kwargs)

Bases: Config

Basic config with permissions.

access: AclStr | None

Permission to read or use the object.

permissions: PermissionsConfig | None

Additional permissions.

exception gws.Error

Bases: Exception

GWS error.

exception gws.ConfigurationError

Bases: Error

GWS Configuration error.

exception gws.NotFoundError

Bases: Error

Generic ‘object not found’ error.

exception gws.ForbiddenError

Bases: Error

Generic ‘forbidden’ error.

exception gws.BadRequestError

Bases: Error

Generic ‘bad request’ error.

exception gws.ResponseTooLargeError

Bases: Error

Generic error when a response is too large.

class gws.ApplicationManifestPlugin(*args, **kwargs)

Bases: Data

Plugin description.

path: DirPath

Path to the plugin python module.

name: str = ''

Optional name, when omitted, the directory name will be used.

class gws.ApplicationManifest(*args, **kwargs)

Bases: Data

Application manifest.

excludePlugins: list[str] | None

Names of the core plugins that should be deactivated.

plugins: list[ApplicationManifestPlugin] | None

Custom plugins.

locales: list[str]

Locale names supported by this application.

withFallbackConfig: bool = False

Use a minimal fallback configuration.

withStrictConfig: bool = False

Stop the application upon a configuration error.

class gws.ExtObjectDescriptor(*args, **kwargs)

Bases: Data

Extension object descriptor.

extName: str

Full extension name like gws.ext.object.layer.wms.

extType: str

Extension type like wms.

classPtr: type

Class object.

ident: str

Identifier.

modName: str

Name of the module that contains the class.

modPath: str

Path to the module that contains the class.

class gws.ExtCommandDescriptor(*args, **kwargs)

Bases: Data

Basic data object.

This object can be instantiated by passing one or or dict arguments and/or keyword args. All dicts keys and keywords become attributes of the object.

Accessing an undefined attribute returns None and no error is raised, unless the attribute name starts with an underscore.

extName: str

Full extension name like gws.ext.object.layer.wms.

extType: str

Extension type like wms.

methodName: str

Command method name.

methodPtr: Callable

Command method.

request: Request

Request sent to the command.

tArg: str

Type of the command argument.

tOwner: str

Type of the command owner.

owner: ExtObjectDescriptor

Descriptor of the command owner.

class gws.SpecReadOption

Bases: Enum

Read options.

acceptExtraProps = 'acceptExtraProps'

Accept extra object properties.

allowMissing = 'allowMissing'

Allow otherwise required properties to be missing.

caseInsensitive = 'caseInsensitive'

Case insensitive search for properties.

convertValues = 'convertValues'

Try to convert values to specified types.

ignoreExtraProps = 'ignoreExtraProps'

Silently ignore extra object properties.

verboseErrors = 'verboseErrors'

Provide verbose error messages.

class gws.CommandCategory

Bases: Enum

Command category.

api = 'api'

API command.

cli = 'cli'

CLI command.

get = 'get'

Web GET command.

post = 'post'

Web POST command.

class gws.SpecRuntime

Specification runtime.

version: str

Application version.

manifest: ApplicationManifest

Application manifest.

appBundlePaths: list[str]

List of client bundle paths.

read(value, type_name: str, path: str = '', options=Optional[set[SpecReadOption]])

Read a raw value according to a spec.

Parameters:
  • value – Raw value from config or request.

  • type_name – Object type name.

  • path – Config file path.

  • options – Read options.

Returns:

A parsed object.

object_descriptor(type_name: str) ExtObjectDescriptor | None

Get an object descriptor.

Parameters:

type_name – Object type name.

Returns:

A descriptor or None if the type is not found.

command_descriptor(command_category: CommandCategory, command_name: str) ExtCommandDescriptor | None

Get a command descriptor.

Parameters:
  • command_category – Command category.

  • command_name – Command name.

Returns:

A descriptor or None if the command is not found.

get_class(classref: ClassRef, ext_type: str | None = None) type | None

Get a class object for a class reference.

Parameters:
  • classref – Class reference.

  • ext_type – Extension type.

Returns:

A class or None if the reference is not found.

parse_classref(classref: ClassRef) tuple[type | None, str, str]

Parse a class reference.

Parameters:

classref – Class reference.

Returns:

A tuple (class object, class name, extension name).

class gws.Object

GWS object.

permissions: dict[Access, Acl]

Mapping from an access mode to a list of ACL tuples.

props(user: User) Props

Generate a Props struct for this object.

Parameters:

user – The user for which the props should be generated.

class gws.Node

Bases: Object

Configurable GWS object.

extName: str

Full extension name like gws.ext.object.layer.wms.

extType: str

Extension type like wms.

config: Config

Configuration for this object.

root: Root

Root object.

parent: Node

Parent object.

children: list[Node]

Child objects.

uid: str

Unique ID.

initialize(config)
pre_configure()

Pre-configuration hook.

configure()

Configuration hook.

post_configure()

Post-configuration hook.

activate()

Activation hook.

create_child(classref: ClassRef, config: Config = None, **kwargs)

Create a child object.

Parameters:
  • classref – Class reference.

  • config – Configuration.

  • **kwargs – Additional configuration properties.

Returns:

A newly created object or None if the object cannot be initialized.

create_child_if_configured(classref: ClassRef, config=None, **kwargs)

Create a child object if the configuration is not None.

Parameters:
  • classref – Class reference.

  • config – Configuration.

  • **kwargs – Additional configuration properties.

Returns:

A newly created object or None if the configuration is None or the object cannot be initialized.

create_children(classref: ClassRef, configs: list[Config], **kwargs)

Create a list of child objects from a list of configurations.

Parameters:
  • classref – Class reference.

  • configs – List of configurations.

  • **kwargs – Additional configuration properties.

Returns:

A list of newly created objects.

cfg(key: str, default=None)

Fetch a configuration property.

Parameters:
  • key – Property key. If it contains dots, fetch nested properties.

  • default – Default to return if the property is not found.

Returns:

A property value.

find_all(classref: ClassRef)

Find all children that match a specific class.

Parameters:

classref – Class reference.

Returns:

A list of objects.

find_first(classref: ClassRef)

Find the first child that matches a specific class.

Parameters:

classref – Class reference.

Returns:

An object or None.

find_closest(classref: ClassRef)

Find the closest node ancestor that matches a specific class.

Parameters:

classref – Class reference.

Returns:

An object or None.

find_ancestors(classref: ClassRef)

Find node ancestors that match a specific class.

Parameters:

classref – Class reference.

Returns:

A list of objects.

find_descendants(classref: ClassRef)

Find node descendants that match a specific class.

Parameters:

classref – Class reference.

Returns:

A list of objects in the depth-first order.

enter_middleware(req: WebRequester) WebResponder | None

Begin middleware processing.

Parameters:

req – Requester object.

Returns:

A Responder object or None.

exit_middleware(req: WebRequester, res: WebResponder)

Finish middleware processing.

Parameters:
  • req – Requester object.

  • res – Current responder object.

register_middleware(name: str, depends_on: list[str] | None = None)

Register itself as a middleware handler.

Parameters:
  • name – Handler name.

  • depends_on – List of handler names this handler depends on.

class gws.Root(specs: SpecRuntime)

Root node of the object tree.

app: Application

Application object.

specs: SpecRuntime

Specs runtime.

configErrors: list

List of configuration errors.

nodes: list[Node]
uidMap: dict[str, Node]
uidCount: int
configStack: list[Node]
initialize(obj, config)
post_initialize()

Post-initialization hook.

activate()
find_all(classref: ClassRef)

Find all objects that match a specific class.

Parameters:

classref – Class reference.

Returns:

A list of objects.

find_first(classref: ClassRef)

Find the first object that match a specific class.

Parameters:

classref – Class reference.

Returns:

An object or None.

get(uid: str = None, classref: ClassRef | None = None)

Get an object by its unique ID.

Parameters:
  • uid – Object uid.

  • classref – Class reference. If provided, ensures that the object matches the reference.

Returns:

An object or None.

object_count() int

Return the number of objects in the tree.

create(classref: ClassRef, parent: Node | None = None, config: Config = None, **kwargs)

Create an object.

Parameters:
  • classref – Class reference.

  • parent – Parent object.

  • config – Configuration.

  • **kwargs – Additional configuration properties.

Returns:

A newly created object or None if the object cannot be initialized.

create_shared(classref: ClassRef, config: Config = None, **kwargs)

Create a shared object, attached directly to the root.

Parameters:
  • classref – Class reference.

  • config – Configuration.

  • **kwargs – Additional configuration properties.

Returns:

A newly created object or None if the object cannot be initialized.

create_temporary(classref: ClassRef, config: Config = None, **kwargs)

Create a temporary object, not attached to the tree.

Parameters:
  • classref – Class reference.

  • config – Configuration.

  • **kwargs – Additional configuration properties.

Returns:

A newly created object or None if the object cannot be initialized.

create_application(config: Config = None, **kwargs) Application

Create the Application object.

Parameters:
  • config – Configuration.

  • **kwargs – Additional configuration properties.

Returns:

The Application object.

gws.create_root(specs: SpecRuntime) Root
gws.props_of(obj: Object, user: User, *context) Props | None
class gws.ImageFormat

Bases: Enum

Image format

png8 = 'png8'

png 8-bit

png24 = 'png24'

png 24-bit

class gws.Image

Image object.

size() Size
add_box(color=None) Image
add_text(text: str, x=0, y=0, color=None) Image
compose(other: Image, opacity=1) Image
crop(box) Image
paste(other: Image, where=None) Image
resize(size: Size, **kwargs) Image
rotate(angle: int, **kwargs) Image
to_bytes(mime: str | None = None) bytes
to_path(path: str, mime: str | None = None) str
to_array() numpy.typing.NDArray
class gws.Locale(*args, **kwargs)

Bases: Data

Locale data.

id: str
dateFormatLong: str
dateFormatMedium: str
dateFormatShort: str
dateUnits: str

date unit names, e.g. ‘YMD’ for ‘en’, ‘JMT’ for ‘de’

dayNamesLong: list[str]
dayNamesShort: list[str]
dayNamesNarrow: list[str]
firstWeekDay: int
language: str
languageName: str
monthNamesLong: list[str]
monthNamesShort: list[str]
monthNamesNarrow: list[str]
numberDecimal: str
numberGroup: str
class gws.DateTimeFormatType

Bases: Enum

Enumeration indicating the length of the date/time format.

short = 'short'

Local short format.

medium = 'medium'

Local medium format.

long = 'long'

Local long format.

iso = 'iso'

ISO 8601 format.

class gws.NumberFormatType

Bases: Enum

Enumeration indicating the number format.

decimal = 'decimal'

Locale decimal format.

grouped = 'grouped'

Locale grouped format.

currency = 'currency'

Locale currency format

percent = 'percent'

Locale percent format.

class gws.DateFormatter

Used for date formatting

format(fmt: DateTimeFormatType | str, date=None) str

Formats the date with respect to the locale.

Parameters:
  • fmt – Format type or a strftime format string

  • date – Date, if none is given the current date will be used as default.

Returns:

A formatted date string.

class gws.TimeFormatter

Used for date formatting

format(fmt: DateTimeFormatType | str, time=None) str

Formats the time with respect to the locale.

Parameters:
  • fmt – Format type or a strftime format string

  • time – Date, if none is given the current time will be used as default.

Returns:

A formatted time string.

class gws.NumberFormatter

Used for number formatting

format(fmt: NumberFormatType | str, n, *args, **kwargs) str

Formats the number with respect to the locale.

Parameters:
  • fmt – Format type or a python format string

  • n – Number.

  • kwargs – Passes the currency parameter forward.

Returns:

A formatted number.

class gws.JobState

Bases: Enum

Background job state.

init = 'init'

The job is being created.

open = 'open'

The job is just created and waiting for start.

running = 'running'

The job is running.

complete = 'complete'

The job has been completed successfully.

error = 'error'

There was an error.

cancel = 'cancel'

The job was cancelled.

class gws.Job

Background Job object.

error: str
payload: dict
state: JobState
uid: str
user: User
run()
update(payload: dict | None = None, state: JobState | None = None, error: str | None = None)
cancel()
remove()

Bases: Data

Link metadata.

description: str | None
format: str | None
formatVersion: str | None
function: str | None
mimeType: str | None
scheme: str | None
title: str | None
type: str | None
url: Url | None
class gws.MetadataAccessConstraint(*args, **kwargs)

Bases: Data

Metadata AccessConstraint.

title: str | None
type: str | None
class gws.MetadataLicense(*args, **kwargs)

Bases: Data

Metadata License.

title: str | None
url: Url | None
class gws.MetadataAttribution(*args, **kwargs)

Bases: Data

Metadata Attribution.

title: str | None
url: Url | None
class gws.Metadata(*args, **kwargs)

Bases: Data

Metadata.

abstract: str | None
accessConstraints: list[MetadataAccessConstraint] | None
attribution: MetadataAttribution | None
authorityIdentifier: str | None
authorityName: str | None
authorityUrl: str | None
catalogCitationUid: str | None
catalogUid: str | None
fees: str | None
image: str | None
keywords: list[str] | None
language3: str | None
language: str | None
languageName: str | None
license: MetadataLicense | None
name: str | None
parentIdentifier: str | None
title: str | None
contactAddress: str | None
contactAddressType: str | None
contactArea: str | None
contactCity: str | None
contactCountry: str | None
contactEmail: str | None
contactFax: str | None
contactOrganization: str | None
contactPerson: str | None
contactPhone: str | None
contactPosition: str | None
contactProviderName: str | None
contactProviderSite: str | None
contactRole: str | None
contactUrl: str | None
contactZip: str | None
dateBegin: str | None
dateCreated: str | None
dateEnd: str | None
dateUpdated: str | None
inspireKeywords: list[str] | None
inspireMandatoryKeyword: str | None
inspireDegreeOfConformity: str | None
inspireResourceType: str | None
inspireSpatialDataServiceType: str | None
inspireSpatialScope: str | None
inspireSpatialScopeName: str | None
inspireTheme: str | None
inspireThemeName: str | None
inspireThemeNameEn: str | None
isoMaintenanceFrequencyCode: str | None
isoQualityConformanceExplanation: str | None
isoQualityConformanceQualityPass: bool | None
isoQualityConformanceSpecificationDate: str | None
isoQualityConformanceSpecificationTitle: str | None
isoQualityLineageSource: str | None
isoQualityLineageSourceScale: int | None
isoQualityLineageStatement: str | None
isoRestrictionCode: str | None
isoServiceFunction: str | None
isoScope: str | None
isoScopeName: str | None
isoSpatialRepresentationType: str | None
isoTopicCategories: list[str] | None
isoSpatialResolution: str | None
class gws.StyleValues(*args, **kwargs)

Bases: Data

CSS Style values.

fill: Color
stroke: Color
stroke_dasharray: list[int]
stroke_dashoffset: int
stroke_linecap: Literal[butt, round, square]
stroke_linejoin: Literal[bevel, round, miter]
stroke_miterlimit: int
stroke_width: int
marker: Literal[circle, square, arrow, cross]
marker_fill: Color
marker_size: int
marker_stroke: Color
marker_stroke_dasharray: list[int]
marker_stroke_dashoffset: int
marker_stroke_linecap: Literal[butt, round, square]
marker_stroke_linejoin: Literal[bevel, round, miter]
marker_stroke_miterlimit: int
marker_stroke_width: int
with_geometry: Literal[all, none]
with_label: Literal[all, none]
label_align: Literal[left, right, center]
label_background: Color
label_fill: Color
label_font_family: str
label_font_size: int
label_font_style: Literal[normal, italic]
label_font_weight: Literal[normal, bold]
label_line_height: int
label_max_scale: int
label_min_scale: int
label_offset_x: int
label_offset_y: int
label_padding: list[int]
label_placement: Literal[start, end, middle]
label_stroke: Color
label_stroke_dasharray: list[int]
label_stroke_dashoffset: int
label_stroke_linecap: Literal[butt, round, square]
label_stroke_linejoin: Literal[bevel, round, miter]
label_stroke_miterlimit: int
label_stroke_width: int
point_size: int
icon: str
offset_x: int
offset_y: int
class gws.StyleProps(*args, **kwargs)

Bases: Props

CSS Style properties.

cssSelector: str | None
text: str | None
values: dict | None
class gws.Style

CSS Style object.

cssSelector: str
text: str
values: StyleValues
class gws.XmlNamespace(*args, **kwargs)

Bases: Data

XML namespace.

uid: str

Unique ID.

xmlns: str

Default prefix for this Namespace.

uri: Url

Namespace uri.

schemaLocation: Url

Namespace schema location.

version: str

Namespace version.

class gws.XmlElement

Bases: Iterable

XML Element.

Extends ElementTree.Element (https://docs.python.org/3/library/xml.etree.elementtree.html#element-objects).

tag: str

Tag name, with an optional namespace in the Clark notation.

text: str | None

Text before first subelement.

tail: str | None

Text after this element’s end tag.

attrib: dict

Dictionary of element attributes.

name: str

Element name (tag without a namespace).

lcName: str

Element name (tag without a namespace) in lower case.

caseInsensitive: bool

Element is case-insensitive.

append(subelement: XmlElement)
attr(key: str, default=None) Any
clear()
extend(subelements: Iterable[XmlElement])
find(path: str) XmlElement | None

Finds first matching element by tag name or path.

findall(path: str) list[XmlElement]

Finds all matching subelements by name or path.

findtext(path: str, default: str | None = None) str

Finds text for first matching element by name or path.

get(key: str, default=None) Any
insert(index: int, subelement: XmlElement)
items() Iterable[Any]
iter(tag: str | None = None) Iterable[XmlElement]
iterfind(path: str | None = None) Iterable[XmlElement]

Returns an iterable of all matching subelements by name or path.

itertext() Iterable[str]
keys() Iterable[str]
remove(other: XmlElement)
set(key: str, value: Any)
add(tag: str, attrib: dict | None = None, **extra) XmlElement
children() list[XmlElement]
findfirst(*paths) XmlElement | None
textof(*paths) str
textlist(*paths, deep=False) list[str]
textdict(*paths, deep=False) dict[str, str]
to_string(compact_whitespace=False, remove_namespaces=False, with_namespace_declarations=False, with_schema_locations=False, with_xml_declaration=False) str

Converts the Element object to a string.

Parameters:
  • compact_whitespace – Remove all whitespace outside of tags and elements.

  • remove_namespaces – Remove all namespace references.

  • with_namespace_declarations – Include the namespace declarations.

  • with_schema_locations – Include schema locations.

  • with_xml_declaration – Include the xml declaration.

Returns:

An XML string.

to_dict() dict

Creates a dictionary from an XmlElement object.

Returns:

A dict with the keys tag, attrib, text, tail, tail, children.

class gws.Uom

Bases: Enum

Unit of measure.

mi = 'mi'

statute mile (EPSG 9093)

us_ch = 'us-ch'

us survey chain (EPSG 9033)

us_ft = 'us-ft'

us survey foot (EPSG 9003)

us_in = 'us-in'

us survey inch us_in

us_mi = 'us-mi'

us survey mile (EPSG 9035)

us_yd = 'us-yd'

us survey yard us_yd

cm = 'cm'

centimetre (EPSG 1033)

ch = 'ch'

chain (EPSG 9097)

dm = 'dm'

decimeter dm

deg = 'deg'

degree (EPSG 9102)

fath = 'fath'

fathom (EPSG 9014)

ft = 'ft'

foot (EPSG 9002)

grad = 'grad'

grad (EPSG 9105)

inch = 'in'

inch in

km = 'km'

kilometre (EPSG 9036)

link (EPSG 9098)

m = 'm'

metre (EPSG 9001)

mm = 'mm'

millimetre (EPSG 1025)

kmi = 'kmi'

nautical mile (EPSG 9030)

rad = 'rad'

radian (EPSG 9101)

yd = 'yd'

yard (EPSG 9096)

px = 'px'

pixel

pt = 'pt'

point

gws.UomValue: TypeAlias

A value with a unit.

gws.UomValueStr: TypeAlias

A value with a unit like 5mm.

gws.UomPoint: TypeAlias

A Point with a unit.

gws.UomPointStr: TypeAlias

A Point with a unit like ["1mm", "2mm"].

gws.UomSize: TypeAlias

A Size with a unit.

gws.UomSizeStr: TypeAlias

A Size with a unit like ["1mm", "2mm"].

gws.UomExtent: TypeAlias

Extent with a unit.

gws.UomExtentStr: TypeAlias

Extent with a unit like ["1mm", "2mm", "3mm", "4mm"].

gws.CrsName: TypeAlias

A CRS code like EPSG:3857 or a SRID like 3857.

class gws.CrsFormat

Bases: Enum

CRS name format.

none = ''
crs = 'crs'

Like crs84.

srid = 'srid'

Like 3857.

epsg = 'epsg'

Like EPSG:3857.

url = 'url'

Like http://www.opengis.net/gml/srs/epsg.xml#3857.

uri = 'uri'

Like http://www.opengis.net/def/crs/epsg/0/3857.

urnx = 'urnx'

Like urn:x-ogc:def:crs:EPSG:3857.

urn = 'urn'

Like urn:ogc:def:crs:EPSG::3857.

class gws.Axis

Bases: Enum

Axis orientation.

xy = 'xy'
yx = 'yx'
class gws.Bounds(*args, **kwargs)

Bases: Data

Geo-referenced extent.

crs: Crs
extent: Extent
class gws.Crs

Coordinate reference system.

srid: int

CRS SRID.

axis: Axis

Axis orientation.

uom: Uom

CRS unit.

isGeographic: bool

This CRS is geographic.

isProjected: bool

This CRS is projected.

isYX: bool

This CRS has a lat/lon axis.

proj4text: str

Proj4 definition.

wkt: str

WKT definition.

epsg: str

Name in the “epsg” format.

urn: str

Name in the “urn” format.

urnx: str

Name in the “urnx” format.

url: str

Name in the “url” format.

uri: str

Name in the “uri” format.

name: str

CRS name.

base: int

Base CRS code.

datum: str

Datum.

wgsExtent: Extent

CRS Extent in the WGS projection.

extent: Extent

CRS own Extent.

transform_extent(extent: Extent, crs_to: Crs) Extent

Transform an Extent from this CRS to another.

Parameters:
  • extent – Extent.

  • crs_to – Target CRS.

Returns:

A transformed Extent.

transformer(crs_to: Crs) Callable

Create a transformer function to another CRS.

Parameters:

crs_to – Target CRS.

Returns:

A function.

to_string(fmt: CrsFormat | None = None) str

Return a string representation of the CRS.

Parameters:

fmt – Format to use.

Returns:

A string.

to_geojson() dict

Return a geojson representation of the CRS (as per GJ2008).

Returns:

A GeoJson dict.

References

https://geojson.org/geojson-spec#named-crs

class gws.MapView(*args, **kwargs)

Bases: Data

Map view.

bounds: Bounds
center: Point
rotation: int
scale: int
mmSize: Size
pxSize: Size
dpi: int
class gws.MapRenderInputPlaneType

Bases: Enum

Map render input plane type.

features = 'features'
image = 'image'
imageLayer = 'imageLayer'
svgLayer = 'svgLayer'
svgSoup = 'svgSoup'
class gws.MapRenderInputPlane(*args, **kwargs)

Bases: Data

Map render input plane.

type: MapRenderInputPlaneType
features: list[Feature]
image: Image
layer: Layer
opacity: float
soupPoints: list[Point]
soupTags: list[Any]
styles: list[Style]
subLayers: list[str]
class gws.MapRenderInput(*args, **kwargs)

Bases: Data

Map render input.

backgroundColor: int
bbox: Extent
center: Point
crs: Crs
dpi: int
mapSize: UomSize
notify: Callable
planes: list[MapRenderInputPlane]
project: Project
rotation: int
scale: int
user: User
visibleLayers: list[Layer] | None
class gws.MapRenderOutputPlaneType

Bases: Enum

Map render output plane type.

image = 'image'
path = 'path'
svg = 'svg'
class gws.MapRenderOutputPlane(*args, **kwargs)

Bases: Data

Map render output plane.

type: MapRenderOutputPlaneType
path: str
elements: list[XmlElement]
image: Image
class gws.MapRenderOutput(*args, **kwargs)

Bases: Data

Map render output.

planes: list[MapRenderOutputPlane]
view: MapView
class gws.LayerRenderInputType

Bases: Enum

Layer render input type.

box = 'box'
xyz = 'xyz'
svg = 'svg'
class gws.LayerRenderInput(*args, **kwargs)

Bases: Data

Layer render input.

boxBuffer: int
boxSize: int
extraParams: dict
project: Project
style: Style
type: LayerRenderInputType
user: User
view: MapView
x: int
y: int
z: int
class gws.LayerRenderOutput(*args, **kwargs)

Bases: Data

Layer render output.

content: bytes
tags: list[XmlElement]
class gws.TileMatrix(*args, **kwargs)

Bases: Data

WMTS TileMatrix object.

uid: str
scale: float
x: float
y: float
width: float
height: float
tileWidth: float
tileHeight: float
extent: Extent
class gws.TileMatrixSet(*args, **kwargs)

Bases: Data

WMTS TileMatrixSet object.

uid: str
crs: Crs
matrices: list[TileMatrix]
class gws.SourceStyle(*args, **kwargs)

Bases: Data

Generic OGC Style.

isDefault: bool
legendUrl: Url
metadata: Metadata
name: str
class gws.SourceLayer(*args, **kwargs)

Bases: Data

Generic OGC Layer.

aLevel: int
aPath: str
aUid: str
dataSource: dict
metadata: Metadata
supportedCrs: list[Crs]
wgsBounds: Bounds
isExpanded: bool
isGroup: bool
isImage: bool
isQueryable: bool
isVisible: bool
layers: list[SourceLayer]
name: str
title: str
legendUrl: Url
opacity: int
scaleRange: list[float]
styles: list[SourceStyle]
defaultStyle: SourceStyle | None
tileMatrixIds: list[str]
tileMatrixSets: list[TileMatrixSet]
imageFormat: str
resourceUrls: dict
sourceId: str
properties: dict
class gws.ServerManager

Bases: Node

Server configuration manager.

templates: list[Template]
create_server_configs(target_dir: str, script_path: str, pid_paths: dict)

Create server configuration files.

class gws.ServerMonitor

Bases: Node

File Monitor facility.

add_directory(path: str, pattern: Regex)

Add a directory to monitor.

Parameters:
  • path – Directory path.

  • pattern – Regex pattern for files to watch.

add_file(path: str)

Add a file to watch.

Parameters:

path – File path.

start()

Start the monitor.

gws.FeatureUid: TypeAlias

Unique Feature id.

class gws.FeatureRecord(*args, **kwargs)

Bases: Data

Raw data from a feature source.

attributes: dict
meta: dict
uid: str | None
shape: Shape | None
class gws.FeatureProps(*args, **kwargs)

Bases: Props

Feature Proprieties.

attributes: dict
cssSelector: str
errors: list[ModelValidationError] | None
createWithFeatures: list[FeatureProps] | None
isNew: bool
modelUid: str
uid: str
views: dict
class gws.Feature

Feature object.

attributes: dict
category: str
cssSelector: str
errors: list[ModelValidationError]
isNew: bool
model: Model
props: FeatureProps
record: FeatureRecord
views: dict
createWithFeatures: list[Feature]
insertedPrimaryKey: str
get(name: str, default=None) Any
has(name: str) bool
set(name: str, value: Any) Feature
raw(name: str) Any
render_views(templates: list[Template], **kwargs) Feature
shape() Shape | None
to_geojson(user: User) dict
to_svg(view: MapView, label: str | None = None, style: Style | None = None) list[XmlElement]
transform_to(crs: Crs) Feature
uid() FeatureUid
class gws.ShapeProps(*args, **kwargs)

Bases: Props

Shape properties.

crs: str
geometry: dict
class gws.Shape

Bases: Object

Geo-referenced geometry.

type: GeometryType

Geometry type.

crs: Crs

CRS of this shape.

x: float | None

X-coordinate for Point geometries, None otherwise.

y: float | None

Y-coordinate for Point geometries, None otherwise.

area() float

Computes the area of the geometry.

bounds() Bounds

Returns a Bounds object that bounds this shape.

centroid() Shape

Returns a centroid as a Point shape.

to_wkb() bytes

Returns a WKB representation of this shape as a binary string.

to_wkb_hex() str

Returns a WKB representation of this shape as a hex string.

to_ewkb() bytes

Returns an EWKB representation of this shape as a binary string.

to_ewkb_hex() str

Returns an EWKB representation of this shape as a hex string.

to_wkt() str

Returns a WKT representation of this shape.

to_ewkt() str

Returns an EWKT representation of this shape.

to_geojson(always_xy=False) dict

Returns a GeoJSON representation of this shape.

to_props() ShapeProps

Returns a GeoJSON representation of this shape.

is_empty() bool

Returns True if this shape is empty.

is_ring() bool

Returns True if this shape is a ring.

is_simple() bool

Returns True if this shape is ‘simple’.

is_valid() bool

Returns True if this shape is valid.

equals(other: Shape) bool

Returns True if this shape is equal to the other.

contains(other: Shape) bool

Returns True if this shape contains the other.

covers(other: Shape) bool

Returns True if this shape covers the other.

covered_by(other: Shape) bool

Returns True if this shape is covered by the other.

crosses(other: Shape) bool

Returns True if this shape crosses the other.

disjoint(other: Shape) bool

Returns True if this shape does not intersect with the other.

intersects(other: Shape) bool

Returns True if this shape intersects with the other.

overlaps(other: Shape) bool

Returns True if this shape overlaps the other.

touches(other: Shape) bool

Returns True if this shape touches the other.

within(other: Shape) bool

Returns True if this shape is within the other.

union(others: list[Shape]) Shape

Computes a union of this shape and other shapes.

intersection(*others: Shape) Shape

Computes an intersection of this shape and other shapes.

to_multi() Shape

Converts a singly-geometry shape to a multi-geometry one.

to_type(new_type: GeometryType) Shape

Converts a geometry to another type.

tolerance_polygon(tolerance, quad_segs=None) Shape

Builds a buffer polygon around the shape.

transformed_to(crs: Crs) Shape

Returns this shape transformed to another CRS.

class gws.ActionManager

Bases: Node

Action manager.

actions_for_project(project: Project, user: User) list[Action]

Get a list of actions for a Project, to which a User has access to.

find_action(project: Project | None, ext_type: str, user: User) Action | None

Locate an Action object.

Parameters:
  • project – Project to se

  • ext_type

  • user

Returns:

prepare_action(command_category: CommandCategory, command_name: str, params: dict, user: User, read_options=None) tuple[Callable, Request]
class gws.Action

Bases: Node

Configurable GWS object.

class gws.User

Bases: Object

User object.

attributes: dict

Custom user attributes.

authToken: str

Token used for authorization.

displayName: str

User display name.

isGuest: bool

User is a Guest.

localUid: str

User uid within its authorization provider.

loginName: str

User login name.

provider: AuthProvider

User authorization provider.

roles: set[str]

User roles.

uid: str

Global user uid.

acl_bit(access: Access, obj: Object) int | None

Get the ACL bit for a specific object.

Parameters:
  • access – Access mode.

  • obj – Requested object.

Returns:

1 or 0 if the user’s permissions have the bit and None otherwise.

can(access: Access, obj: Object, *context) bool

Check if the user can access an object.

Parameters:
  • access – Access mode.

  • obj – Requested object.

  • *context – Further objects to check.

Returns:

True is access is granted.

can_create(obj: Object, *context) bool

Check if the user has “create” permission on an object.

can_delete(obj: Object, *context) bool

Check if the user has “delete” permission on an object.

can_read(obj: Object, *context) bool

Check if the user has “read” permission on an object.

can_use(obj: Object, *context) bool

Check if the user has “read” permission on an object.

can_write(obj: Object, *context) bool

Check if the user has “write” permission on an object.

can_edit(obj: Object, *context) bool

Check if the user has “edit” permissions on an object.

acquire(uid: str = None, classref: ClassRef | None = None, access: Access | None = None) Object | None

Get a readable object by uid.

Parameters:
  • uid – Object uid.

  • classref – Class reference. If provided, ensures that the object matches the reference.

  • access – Access mode, assumed Access.read if omitted.

Returns:

A readable object or None if the object does not exists or user doesn’t have a permission.

require(uid: str = None, classref: ClassRef | None = None, access: Access | None = None) Object

Get a readable object by uid and fail if not found.

Parameters:
  • uid – Object uid.

  • classref – Class reference. If provided, ensures that the object matches the reference.

  • access – Access mode, assumed Access.read if omitted.

Returns:

A readable object.

Raises:
  • NotFoundError if the object doesn't exist.

  • ForbiddenError if the user cannot read the object.

require_project(uid: str = None) Project

Get a readable Project object.

Parameters:

uid – Project uid.

Returns:

A Project object.

require_layer(uid=None) Layer

Get a readable Layer object.

Parameters:

uid – Layer uid.

Returns:

A Layer object.

class gws.AuthManager

Bases: Node

Authentication manager.

guestSession: AuthSession

Preconfigured Guest session.

guestUser: User

Preconfigured Guest user.

systemUser: User

Preconfigured System user.

providers: list[AuthProvider]

Authentication providers.

methods: list[AuthMethod]

Authentication methods.

mfa: list[AuthMfa]

Authentication MFA handlers.

sessionMgr: AuthSessionManager

Session manager.

authenticate(method: AuthMethod, credentials: Data) User | None

Authenticate a user.

Parameters:
  • method – Authentication method.

  • credentials – Credentials object.

Returns:

An authenticated User or None if authentication failed.

get_user(user_uid: str) User | None

Get a User by its global uid.

Parameters:

user_uid – Global user uid.

Returns:

A User or None.

get_provider(uid: str) AuthProvider | None

Get an authentication Provider by its uid.

Parameters:

uid – Uid.

Returns:

A Provider or None.

get_method(uid: str) AuthMethod | None

Get an authentication Method by its uid.

Parameters:

uid – Uid.

Returns:

A Method or None.

get_mfa(uid: str) AuthMfa | None

Get an authentication Provider by its uid.

Parameters:

uid – Uid.

Returns:

A Provider or None.

serialize_user(user: User) str

Return a string representation of a User.

Parameters:

user – A User object.

Returns:

A json string.

unserialize_user(ser: str) User | None

Restore a User object from a serialized representation.

Parameters:

ser – A json string.

Returns:

A User object.

class gws.AuthMethod

Bases: Node

Authentication Method.

authMgr: AuthManager
secure: bool

Method is only allowed in a secure context.

open_session(req: WebRequester) AuthSession | None

Attempt to open a Session for a Requester.

Parameters:

req – Requester object.

Returns:

A Session or None.

close_session(req: WebRequester, res: WebResponder) bool

Close a previously opened Session.

Parameters:
  • req – Requester object.

  • res – Responder object.

Returns:

True if the Session was successfully closed.

class gws.AuthMfa

Bases: Node

Authentication MFA handler.

autoStart: bool
lifeTime: int
maxAttempts: int
maxRestarts: int
start(user: User)
is_valid(user: User) bool
cancel(user: User)
verify(user: User, request: Data) bool
restart(user: User) bool
class gws.AuthProvider

Bases: Node

Authentication Provider.

allowedMethods: list[str]

List of Method types allowed to be used with this Provider.

get_user(local_uid: str) User | None

Get a User from its local uid.

Parameters:

local_uid – User local uid.

Returns:

A User or None.

authenticate(method: AuthMethod, credentials: Data) User | None

Authenticate a user.

Parameters:
  • method – Authentication method.

  • credentials – Credentials object.

Returns:

An authenticated User or None if authentication failed.

serialize_user(user: User) str

Return a string representation of a User.

Parameters:

user – A User object.

Returns:

A json string.

unserialize_user(ser: str) User | None

Restore a User object from a serialized representation.

Parameters:

ser – A json string.

Returns:

A User object.

class gws.AuthSession

Authentication session.

uid: str

Session uid.

method: AuthMethod | None

Authentication method that created the session.

user: User

Authorized User.

data: dict

Session data.

created: datetime.datetime

Session create time.

updated: datetime.datetime

Session update time.

isChanged: bool

Session has changed since the last update..

get(key: str, default=None)

Get a session data value.

Parameters:
  • key – Value name.

  • default – Default value.

Returns:

A value or the default.

set(key: str, value)

Set a session data value.

Parameters:
  • key – Value name.

  • value – A value.

class gws.AuthSessionManager

Bases: Node

Authentication session Manager.

lifeTime: int

Session lifetime in seconds.

create(method: AuthMethod, user: User, data: dict | None = None) AuthSession

Create a new Session,

Parameters:
  • method – Auth Method that creates the Session.

  • user – ‘User’ for which the Session is created.

  • data – Session data.

Returns:

A new Session.

delete(sess: AuthSession)

Delete a Session.

Parameters:

sess – Session object.

delete_all()

Delete all Sessions.

get(uid: str) AuthSession | None

Get Session by its uid.

Parameters:

uid – Session uid.

Returns:

A Session or None.

get_valid(uid: str) AuthSession | None

Get a valid Session by its uid.

Parameters:

uid – Session uid.

Returns:

A Session or None if uid does not exists or the Session is not valid.

get_all() list[AuthSession]

Get all sessions.

save(sess: AuthSession)

Save the Session state into a persistent storage.

Parameters:

sess – Session object.

touch(sess: AuthSession)

Update the Session last activity timestamp.

Parameters:

sess – Session object.

cleanup()

Remove invalid Sessions from the storage.

class gws.LayerDisplayMode

Bases: Enum

Layer display mode.

box = 'box'

Display a layer as one big image (WMS-alike).

tile = 'tile'

Display a layer in a tile grid.

client = 'client'

Draw a layer in the client.

class gws.LayerClientOptions(*args, **kwargs)

Bases: Data

Client options for a layer.

expanded: bool

A layer is expanded in the list view.

unlisted: bool

A layer is hidden in the list view.

selected: bool

A layer is initially selected.

hidden: bool

A layer is initially hidden.

unfolded: bool

A layer is not listed, but its children are.

exclusive: bool

Only one of this layer’s children is visible at a time.

class gws.TileGrid(*args, **kwargs)

Bases: Data

Tile grid.

uid: str
bounds: Bounds
origin: Origin
resolutions: list[float]
tileSize: int
class gws.LayerCache(*args, **kwargs)

Bases: Data

Layer cache.

maxAge: int
maxLevel: int
requestBuffer: int
requestTiles: int
class gws.FeatureLoadingStrategy

Bases: Enum

Loading strategy for features.

all = 'all'

Load all features.

bbox = 'bbox'

Load only features in the current map extent.

lazy = 'lazy'

Load features on demand.

class gws.LayerOwsOptions(*args, **kwargs)

Bases: Data

Layer options for OWS services.

enabled: bool
layerName: str
featureName: str
xmlNamespace: XmlNamespace
geometryName: str
class gws.Layer

Bases: Node

Layer object.

canRenderBox: bool
canRenderSvg: bool
canRenderXyz: bool
isEnabledForOws: bool
isGroup: bool
isSearchable: bool
hasLegend: bool
bounds: Bounds
wgsExtent: Extent
mapCrs: Crs
clientOptions: LayerClientOptions
displayMode: LayerDisplayMode
loadingStrategy: FeatureLoadingStrategy
imageFormat: str
opacity: float
resolutions: list[float]
title: str
owsOptions: LayerOwsOptions | None
grid: TileGrid | None
cache: LayerCache | None
metadata: Metadata
legend: Legend | None
legendUrl: str
finders: list[Finder]
templates: list[Template]
models: list[Model]
layers: list[Layer]
provider: Node
sourceLayers: list[SourceLayer]
render(lri: LayerRenderInput) LayerRenderOutput | None
get_features_for_view(search: SearchQuery, user: User, view_names: list[str] | None = None) list[Feature]
render_legend(args: dict | None = None) LegendRenderOutput | None
url_path(kind: str) str
class gws.LegendRenderOutput(*args, **kwargs)

Bases: Data

Legend render output.

html: str
image: Image
image_path: str
size: Size
mime: str
class gws.Legend

Bases: Node

Legend object.

render(args: dict | None = None) LegendRenderOutput | None
class gws.Map

Bases: Node

Map object.

rootLayer: Layer
bounds: Bounds
center: Point
coordinatePrecision: int
initResolution: float
resolutions: list[float]
title: str
wgsExtent: Extent
class gws.ModelValidationError(*args, **kwargs)

Bases: Data

Validation error.

fieldName: str
message: str
class gws.ModelOperation

Bases: Enum

Model operation.

read = 'read'
create = 'create'
update = 'update'
delete = 'delete'
class gws.ModelReadMode

Bases: Enum

Model reading mode.

render = 'render'
search = 'search'
list = 'list'
form = 'form'
class gws.ModelDbSelect(*args, **kwargs)

Bases: Data

Database select statement.

columns: list[sqlalchemy.Column]
geometryWhere: list
keywordWhere: list
where: list
order: list
class gws.ModelContext(*args, **kwargs)

Bases: Data

Model context.

op: ModelOperation
readMode: ModelReadMode
user: User
project: Project
relDepth: int = 0
maxDepth: int = 0
search: SearchQuery
dbSelect: ModelDbSelect
dbConnection: sqlalchemy.Connection
gws.EmptyValue

Special value for empty fields.

gws.ErrorValue

Special value for invalid fields.

class gws.ModelWidget

Bases: Node

Model widget.

supportsTableView: bool = True
class gws.ModelValidator

Bases: Node

Model Validator.

message: str
ops: set[ModelOperation]
validate(field: ModelField, feature: Feature, mc: ModelContext) bool
class gws.ModelValue

Bases: Node

Model value.

isDefault: bool
ops: set[ModelOperation]
compute(field: ModelField, feature: Feature, mc: ModelContext)
class gws.ModelField

Bases: Node

Model field.

name: str
title: str
attributeType: AttributeType
widget: ModelWidget | None
values: list[ModelValue]
validators: list[ModelValidator]
isPrimaryKey: bool
isRequired: bool
isUnique: bool
isAuto: bool
supportsFilterSearch: bool = False
supportsGeometrySearch: bool = False
supportsKeywordSearch: bool = False
model: Model
before_select(mc: ModelContext)
after_select(features: list[Feature], mc: ModelContext)
before_create(feature: Feature, mc: ModelContext)
after_create(feature: Feature, mc: ModelContext)
before_update(feature: Feature, mc: ModelContext)
after_update(feature: Feature, mc: ModelContext)
before_delete(feature: Feature, mc: ModelContext)
after_delete(feature: Feature, mc: ModelContext)
do_init(feature: Feature, mc: ModelContext)
do_validate(feature: Feature, mc: ModelContext)
from_props(feature: Feature, mc: ModelContext)
to_props(feature: Feature, mc: ModelContext)
from_record(feature: Feature, mc: ModelContext)
to_record(feature: Feature, mc: ModelContext)
related_models() list[Model]
find_relatable_features(search: SearchQuery, mc: ModelContext) list[Feature]
raw_to_python(feature: Feature, value, mc: ModelContext)
prop_to_python(feature: Feature, value, mc: ModelContext)
python_to_raw(feature: Feature, value, mc: ModelContext)
python_to_prop(feature: Feature, value, mc: ModelContext)
describe() ColumnDescription | None
class gws.Model

Bases: Node

Data Model.

defaultSort: list[SearchSort]
fields: list[ModelField]
geometryCrs: Crs | None
geometryName: str
geometryType: GeometryType | None
isEditable: bool
loadingStrategy: FeatureLoadingStrategy
title: str
uidName: str
withTableView: bool
find_features(search: SearchQuery, mc: ModelContext) list[Feature]
get_features(uids: Iterable[str | int], mc: ModelContext) list[Feature]
init_feature(feature: Feature, mc: ModelContext)
create_feature(feature: Feature, mc: ModelContext) FeatureUid
update_feature(feature: Feature, mc: ModelContext) FeatureUid
delete_feature(feature: Feature, mc: ModelContext) FeatureUid
validate_feature(feature: Feature, mc: ModelContext) bool
feature_from_props(props: FeatureProps, mc: ModelContext) Feature
feature_to_props(feature: Feature, mc: ModelContext) FeatureProps
feature_to_view_props(feature: Feature, mc: ModelContext) FeatureProps
describe() DataSetDescription | None
field(name: str) ModelField | None
related_models() list[Model]
class gws.ModelManager

Bases: Node

Model manager.

get_model(uid: str, user: User = None, access: Access = None) Model | None
locate_model(*objects, user: User = None, access: Access = None) Model | None
editable_models(project: Project, user: User) list[Model]
default_model() Model
class gws.DatabaseModel

Bases: Model

Database-based data model.

provider: DatabaseProvider
sqlFilter: str
tableName: str
table() sqlalchemy.Table
column(column_name: str) sqlalchemy.Column
uid_column() sqlalchemy.Column
connection() sqlalchemy.Connection
execute(sql: sqlalchemy.Executable, mc: ModelContext, parameters=None) sqlalchemy.CursorResult
class gws.ColumnDescription(*args, **kwargs)

Bases: Data

Database column description.

columnIndex: int
comment: str
default: str
geometrySrid: int
geometryType: GeometryType
isAutoincrement: bool
isNullable: bool
isPrimaryKey: bool
isUnique: bool
hasDefault: bool
name: str
nativeType: str
options: dict
type: AttributeType
class gws.RelationshipDescription(*args, **kwargs)

Bases: Data

Database relationship description.

name: str
schema: str
fullName: str
foreignKeys: str
referredKeys: str
class gws.DataSetDescription(*args, **kwargs)

Bases: Data

GDAL Dataset description.

columns: list[ColumnDescription]
columnMap: dict[str, ColumnDescription]
fullName: str
geometryName: str
geometrySrid: int
geometryType: GeometryType
name: str
schema: str
class gws.DatabaseManager

Bases: Node

Database manager.

create_provider(cfg: Config, **kwargs) DatabaseProvider
providers() list[DatabaseProvider]
provider(uid: str) DatabaseProvider | None
first_provider(ext_type: str) DatabaseProvider | None
class gws.DatabaseProvider

Bases: Node

Database Provider.

mgr: DatabaseManager
url: str
models: list[DatabaseModel]
connection() sqlalchemy.Connection
engine(**kwargs) sqlalchemy.Engine
split_table_name(table_name: str) tuple[str, str]
join_table_name(schema: str, name: str) str
table(table_name: str, **kwargs) sqlalchemy.Table
has_table(table_name: str) bool
column(table: sqlalchemy.Table, column_name: str) sqlalchemy.Column
has_column(table: sqlalchemy.Table, column_name: str) bool
describe(table_name: str) DataSetDescription
table_bounds(table_name) Bounds | None
class gws.OwsProtocol

Bases: Enum

Supported OWS protocol.

WMS = 'WMS'
WMTS = 'WMTS'
WCS = 'WCS'
WFS = 'WFS'
CSW = 'CSW'
class gws.OwsAuthorization(*args, **kwargs)

Bases: Data

Basic data object.

This object can be instantiated by passing one or or dict arguments and/or keyword args. All dicts keys and keywords become attributes of the object.

Accessing an undefined attribute returns None and no error is raised, unless the attribute name starts with an underscore.

type: str
username: str
password: str
class gws.OwsVerb

Bases: Enum

OWS verb.

CreateStoredQuery = 'CreateStoredQuery'
DescribeCoverage = 'DescribeCoverage'
DescribeFeatureType = 'DescribeFeatureType'
DescribeLayer = 'DescribeLayer'
DescribeRecord = 'DescribeRecord'
DescribeStoredQueries = 'DescribeStoredQueries'
DropStoredQuery = 'DropStoredQuery'
GetCapabilities = 'GetCapabilities'
GetFeature = 'GetFeature'
GetFeatureInfo = 'GetFeatureInfo'
GetFeatureWithLock = 'GetFeatureWithLock'
GetLegendGraphic = 'GetLegendGraphic'
GetMap = 'GetMap'
GetPrint = 'GetPrint'
GetPropertyValue = 'GetPropertyValue'
GetRecordById = 'GetRecordById'
GetRecords = 'GetRecords'
GetTile = 'GetTile'
ListStoredQueries = 'ListStoredQueries'
LockFeature = 'LockFeature'
Transaction = 'Transaction'
class gws.OwsOperation(*args, **kwargs)

Bases: Data

OWS operation.

allowedParameters: dict[str, list[str]]
constraints: dict[str, list[str]]
formats: list[str]
params: dict[str, str]
postUrl: Url
preferredFormat: str
url: Url
verb: OwsVerb
class gws.OwsCapabilities(*args, **kwargs)

Bases: Data

OWS capabilities structure.

metadata: Metadata
operations: list[OwsOperation]
sourceLayers: list[SourceLayer]
tileMatrixSets: list[TileMatrixSet]
version: str
class gws.OwsService

Bases: Node

OWS Service.

isRasterService: bool
isVectorService: bool
metadata: Metadata
name: str
protocol: OwsProtocol
supportedBounds: list[Bounds]
supportedVersions: list[str]
supportedOperations: list[OwsOperation]
templates: list[Template]
updateSequence: str
version: str
withInspireMeta: bool
withStrictParams: bool
handle_request(req: WebRequester) ContentResponse
class gws.OwsProvider

Bases: Node

OWS services Provider.

alwaysXY: bool
authorization: OwsAuthorization | None
forceCrs: Crs
maxRequests: int
metadata: Metadata
operations: list[OwsOperation]
protocol: OwsProtocol
sourceLayers: list[SourceLayer]
url: Url
version: str
get_operation(verb: OwsVerb, method: RequestMethod | None = None) OwsOperation | None
get_features(args: SearchQuery, source_layers: list[SourceLayer]) list[FeatureRecord]
class gws.PrintPlaneType

Bases: Enum

Print plane type.

bitmap = 'bitmap'
url = 'url'
features = 'features'
raster = 'raster'
vector = 'vector'
soup = 'soup'
class gws.PrintPlane(*args, **kwargs)

Bases: Data

Print plane.

type: PrintPlaneType
opacity: float | None
cssSelector: str | None
bitmapData: bytes | None
bitmapMode: str | None
bitmapWidth: int | None
bitmapHeight: int | None
url: str | None
features: list[FeatureProps] | None
layerUid: str | None
subLayers: list[str] | None
soupPoints: list[Point] | None
soupTags: list[Any] | None
class gws.PrintMap(*args, **kwargs)

Bases: Data

Map properties for printing.

backgroundColor: int | None
bbox: Extent | None
center: Point | None
planes: list[PrintPlane]
rotation: int | None
scale: int
styles: list[StyleProps] | None
visibleLayers: list[str] | None
class gws.PrintRequestType

Bases: Enum

Type of the print request.

template = 'template'
map = 'map'
class gws.PrintRequest(*args, **kwargs)

Bases: Request

Print request.

type: PrintRequestType
args: dict | None
crs: CrsName | None
outputFormat: str | None
maps: list[PrintMap] | None
printerUid: str | None
dpi: int | None
outputSize: Size | None
class gws.PrintJobResponse(*args, **kwargs)

Bases: Response

Print job information response.

jobUid: str
progress: int
state: JobState
stepType: str
stepName: str
url: str
class gws.Printer

Bases: Node

Printer object.

title: str
template: Template
models: list[Model]
qualityLevels: list[TemplateQualityLevel]
class gws.PrinterManager

Bases: Node

Print Manager.

printers_for_project(project: Project, user: User) list[Printer]
start_job(request: PrintRequest, user: User) Job
get_job(uid: str, user: User) Job | None
run_job(request: PrintRequest, user: User)
cancel_job(job: Job)
result_path(job: Job) str
status(job: Job) PrintJobResponse
class gws.Client

Bases: Node

GWS Client control object.

options: dict
elements: list
class gws.Project

Bases: Node

Project object.

assetsRoot: WebDocumentRoot | None
client: Client
localeUids: list[str]
map: Map
metadata: Metadata
actions: list[Action]
finders: list[Finder]
models: list[Model]
printers: list[Printer]
templates: list[Template]
owsServices: list[OwsService]
class gws.SearchSort(*args, **kwargs)

Bases: Data

Search sort specification.

fieldName: str
reverse: bool
class gws.SearchOgcFilter(*args, **kwargs)

Bases: Data

Search filter.

name: str
operator: str
shape: Shape
subFilters: list[SearchOgcFilter]
value: str
class gws.SearchQuery(*args, **kwargs)

Bases: Data

Search query.

access: Access
all: bool
bounds: Bounds
extraColumns: list
extraParams: dict
extraWhere: list
keyword: str
layers: list[Layer]
limit: int
ogcFilter: SearchOgcFilter
project: Project
relDepth: int
resolution: float
shape: Shape
sort: list[SearchSort]
tolerance: UomValue
uids: list[str]
class gws.SearchResult(*args, **kwargs)

Bases: Data

Search result.

feature: Feature
layer: Layer
finder: Finder
class gws.TextSearchType

Bases: Enum

Text search type.

exact = 'exact'

Match the whole string.

begin = 'begin'

Match the beginning of the string.

end = 'end'

Match the end of the string.

any = 'any'

Match any substring.

like = 'like'

Use the percent sign as a placeholder.

class gws.TextSearchOptions(*args, **kwargs)

Bases: Data

Text search options.

type: TextSearchType

Type of the search.

minLength: int = 0

Minimal pattern length.

caseSensitive: bool = False

Use the case sensitive search.

class gws.SortOptions(*args, **kwargs)

Bases: Data

Sort options.

fieldName: str
reverse: bool = False
class gws.SearchManager

Bases: Node

Search Manager.

class gws.Finder

Bases: Node

Finder object.

title: str
supportsFilterSearch: bool = False
supportsGeometrySearch: bool = False
supportsKeywordSearch: bool = False
withFilter: bool
withGeometry: bool
withKeyword: bool
templates: list[Template]
models: list[Model]
provider: Node
sourceLayers: list[SourceLayer]
tolerance: UomValue
run(search: SearchQuery, user: User, layer: Layer | None = None) list[Feature]
can_run(search: SearchQuery, user: User) bool
class gws.StorageManager

Bases: Node

Storage manager.

provider(uid: str) StorageProvider | None
first_provider() StorageProvider | None
class gws.StorageRecord(*args, **kwargs)

Bases: Data

Storage record.

name: str
userUid: str
data: str
created: int
updated: int
class gws.StorageProvider

Bases: Node

Storage provider.

list_names(category: str) list[str]
read(category: str, name: str) StorageRecord | None
write(category: str, name: str, data: str, user_uid: str)
delete(category: str, name: str)
class gws.TemplateArgs(*args, **kwargs)

Bases: Data

Template arguments.

app: Application

Application object.

gwsVersion: str

GWS version.

gwsBaseUrl: str

GWS server base url.

locale: Locale

Current locale.

date: DateFormatter

Locale-dependent date formatter.

time: TimeFormatter

Locale-dependent time formatter.

number: NumberFormatter

Locale-dependent number formatter.

class gws.TemplateRenderInput(*args, **kwargs)

Bases: Data

Template render input.

args: dict | Data
crs: Crs
dpi: int
localeUid: str
maps: list[MapRenderInput]
mimeOut: str
notify: Callable
project: Project
user: User
class gws.TemplateQualityLevel(*args, **kwargs)

Bases: Data

Template quality level.

name: str
dpi: int
class gws.Template

Bases: Node

Template object.

mapSize: UomSize

Default map size for the template.

mimeTypes: list[str]

MIME types the template can generate.

pageSize: UomSize

Default page size for printing.

pageMargin: UomExtent

Default page margin for printing.

subject: str

Template subject (category).

title: str

Template title.

render(tri: TemplateRenderInput) Response

Render the template and return the generated response.

class gws.TemplateManager

Bases: Node

Template manager.

find_template(*objects, user: User = None, subject: str = None, mime: str = None) Template | None
template_from_path(path: str) Template | None
class gws.RequestMethod

Bases: Enum

Web request method.

GET = 'GET'
HEAD = 'HEAD'
POST = 'POST'
PUT = 'PUT'
DELETE = 'DELETE'
CONNECT = 'CONNECT'
OPTIONS = 'OPTIONS'
TRACE = 'TRACE'
PATCH = 'PATCH'
class gws.WebRequester

Web Requester object.

environ: dict

Request environment.

method: RequestMethod

Request method.

root: Root

Object tree root.

site: WebSite

Website the request is processed for.

params: dict

GET parameters.

command: str

Command name to execute.

session: AuthSession

Current session.

user: User

Current use.

isApi: bool

The request is an ‘api’ request.

isGet: bool

The request is a ‘get’ request.

isPost: bool

The request is a ‘post’ request.

isSecure: bool

The request is secure.

initialize()

Initialize the Requester.

cookie(key: str, default: str = '') str

Get a cookie.

Parameters:
  • key – Cookie name.

  • default – Default value.

Returns:

A cookie value.

header(key: str, default: str = '') str

Get a header.

Parameters:
  • key – Header name.

  • default – Default value.

Returns:

A header value.

param(key: str, default: str = '') str

Get a GET parameter.

Parameters:
  • key – Parameter name.

  • default – Default value.

Returns:

A parameter value.

env(key: str, default: str = '') str

Get an environment variable.

Parameters:
  • key – Variable name.

  • default – Default value.

Returns:

A variable value.

data() bytes | None

Get POST data.

Returns:

Data bytes or None if request is not a POST.

text() str | None

Get POST data as a text.

Returns:

Data string or None if request is not a POST.

content_responder(response: ContentResponse) WebResponder

Return a Responder object for a content response.

Parameters:

response – Response object.

Returns:

A Responder.

redirect_responder(response: RedirectResponse) WebResponder

Return a Responder object for a redirect response.

Parameters:

response – Response object.

Returns:

A Responder.

api_responder(response: Response) WebResponder

Return a Responder object for an Api (structured) response.

Parameters:

response – Response object.

Returns:

A Responder.

error_responder(exc: Exception) WebResponder

Return a Responder object for an Exception.

Parameters:

exc – An Exception.

Returns:

A Responder.

url_for(request_path: str, **kwargs) str

Return a canonical Url for the given request path.

Parameters:
  • request_path – Request path.

  • **kwargs – Additional GET parameters.

Returns:

An URL.

set_session(session: AuthSession)

Attach a session to the requester.

Parameters:

session – A Session object.

class gws.WebResponder

Web Responder object.

status: int

Response status.

send_response(environ: dict, start_response: Callable)

Send the response to the client.

Parameters:
  • environ – WSGI environment.

  • start_response – WSGI start_response function.

Set a cookie.

Parameters:
  • key – Cookie name.

  • value – Cookie value.

  • **kwargs – Cookie options.

Delete a cookie.

Parameters:
  • key – Cookie name.

  • **kwargs – Cookie options.

set_status(status: int)

Set the response status.

Parameters:

status – HTTP status code.

add_header(key: str, value: str)

Add a header.

Parameters:
  • key – Header name.

  • value – Header value.

class gws.WebDocumentRoot(*args, **kwargs)

Bases: Data

Web document root.

dir: DirPath

Local directory.

allowMime: list[str]

Allowed mime types.

denyMime: list[str]

Restricted mime types.

class gws.WebRewriteRule(*args, **kwargs)

Bases: Data

Rewrite rule.

pattern: Regex

URL matching pattern.

target: str

Rule target, with dollar placeholders.

options: dict

Extra options.

reversed: bool

Reversed rewrite rule.

class gws.WebCors(*args, **kwargs)

Bases: Data

CORS options.

allowCredentials: bool
allowHeaders: str
allowMethods: str
allowOrigin: str
class gws.WebManager

Bases: Node

Web manager.

sites: list[WebSite]

Configured web sites.

site_from_environ(environ: dict) WebSite

Returns a site object for the given request environment.

Parameters:

environ – WSGI environment.

Returns:

A Site object.

class gws.WebSite

Bases: Node

Web site.

assetsRoot: WebDocumentRoot | None

Root directory for assets.

corsOptions: WebCors

CORS options.

errorPage: Template | None

Error page template.

host: str

Host name for this site.

rewriteRules: list[WebRewriteRule]

Rewrite rule.

staticRoot: WebDocumentRoot

Root directory for static files.

url_for(req: WebRequester, path: str, **kwargs) str

Rewrite a request path to an Url.

Parameters:
  • req – Web Requester.

  • path – Raw request path.

  • **kwargs – Extra GET params.

Returns:

A rewritten URL.

class gws.MiddlewareManager

Bases: Node

Configurable GWS object.

register(obj: Node, name: str, depends_on: list[str] | None = None)

Register an object as a middleware.

objects() list[Node]

Return a list of registered middleware objects.

class gws.Application

Bases: Node

The main Application object.

client: Client
localeUids: list[str]
metadata: Metadata
monitor: ServerMonitor
version: str
versionString: str
defaultPrinter: Printer
actionMgr: ActionManager
authMgr: AuthManager
databaseMgr: DatabaseManager
modelMgr: ModelManager
printerMgr: PrinterManager
searchMgr: SearchManager
storageMgr: StorageManager
templateMgr: TemplateManager
serverMgr: ServerManager
webMgr: WebManager
middlewareMgr: MiddlewareManager
actions: list[Action]
projects: list[Project]
finders: list[Finder]
templates: list[Template]
printers: list[Printer]
models: list[Model]
owsServices: list[OwsService]
project(uid: str) Project | None

Get a Project object by its uid.

helper(ext_type: str) Node | None

Get a Helper object by its extension type.

developer_option(key: str)

Get a value of a developer option.