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.Access

Bases: Enum

Access mode.

create = 'create'
delete = 'delete'
read = 'read'
write = 'write'
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.Action

Bases: Node

Configurable GWS object.

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.Application

Bases: Node

The main Application object.

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

Get a value of a developer option.

helper(ext_type: str) Node | None

Get a Helper object by its extension type.

project(uid: str) Project | None

Get a Project object by its uid.

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

Bases: Data

Application manifest.

excludePlugins: list[str] | None

Names of the core plugins that should be deactivated.

locales: list[str]

Locale names supported by this application.

plugins: list[ApplicationManifestPlugin] | None

Custom plugins.

withFallbackConfig: bool = False

Use a minimal fallback configuration.

withStrictConfig: bool = False

Stop the application upon a configuration error.

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

Bases: Data

Plugin description.

name: str = ''

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

path: DirPath

Path to the plugin python module.

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.AuthManager

Bases: Node

Authentication manager.

guestSession: AuthSession

Preconfigured Guest session.

guestUser: User

Preconfigured Guest user.

methods: list[AuthMethod]

Authentication methods.

mfAdapters: list[AuthMultiFactorAdapter]

Authentication MFA handlers.

providers: list[AuthProvider]

Authentication providers.

sessionMgr: AuthSessionManager

Session manager.

systemUser: User

Preconfigured System user.

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_method(uid: str) AuthMethod | None

Get an authentication Method by its uid.

Parameters:

uid – Uid.

Returns:

A Method or None.

get_mf_adapter(uid: str) AuthMultiFactorAdapter | None

Get an authentication Provider by its uid.

Parameters:

uid – Uid.

Returns:

A Provider or None.

get_provider(uid: str) AuthProvider | None

Get an authentication Provider by its uid.

Parameters:

uid – Uid.

Returns:

A Provider or None.

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.

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.

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.

open_session(req: WebRequester) AuthSession | None

Attempt to open a Session for a Requester.

Parameters:

req – Requester object.

Returns:

A Session or None.

class gws.AuthMultiFactorAdapter

Bases: Node

Multi-factor authentication adapter.

lifeTime: int
maxRestarts: int
maxVerifyAttempts: int
message: str
cancel(mfa: AuthMultiFactorTransaction)

Cancel the transaction.

check_restart(mfa: AuthMultiFactorTransaction) bool

Check if the transaction can be restarted.

check_state(mfa: AuthMultiFactorTransaction) bool

Check if the MFA transaction is valid.

key_uri(secret: str | bytes, issuer_name: str, account_name: str) str | None

Generate a key uri for this adapter.

restart(mfa: AuthMultiFactorTransaction) AuthMultiFactorTransaction | None

Restart the transaction.

start(user: User) AuthMultiFactorTransaction | None

Initialize an MFA transaction for the user.

verify(mfa: AuthMultiFactorTransaction, payload: dict) AuthMultiFactorTransaction

Verify a payload.

class gws.AuthMultiFactorState

Bases: 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.

failed = 'failed'
ok = 'ok'
open = 'open'
retry = 'retry'
class gws.AuthMultiFactorTransaction(*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.

adapter: AuthMultiFactorAdapter
generateTime: int
message: str
restartCount: int
secret: str
startTime: int
state: AuthMultiFactorState
user: User
verifyCount: int
class gws.AuthProvider

Bases: Node

Authentication Provider.

allowedMethods: list[str]

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

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(local_uid: str) User | None

Get a User from its local uid.

Parameters:

local_uid – User local uid.

Returns:

A User 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.AuthSession

Authentication session.

created: datetime.datetime

Session create time.

data: dict

Session data.

isChanged: bool

Session has changed since the last update..

method: AuthMethod | None

Authentication method that created the session.

uid: str

Session uid.

updated: datetime.datetime

Session update time.

user: User

Authorized User.

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.

cleanup()

Remove invalid Sessions from the storage.

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_all() list[AuthSession]

Get all sessions.

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.

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.

class gws.Axis

Bases: Enum

Axis orientation.

xy = 'xy'
yx = 'yx'
exception gws.BadRequestError

Bases: Error

Generic ‘bad request’ error.

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

Bases: Data

Geo-referenced extent.

crs: Crs
extent: Extent
gws.ClassRef: TypeAlias

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

class gws.Client

Bases: Node

GWS Client control object.

elements: list
options: dict
class gws.CliParams(*args, **kwargs)

Bases: Data

CLI params

gws.Color: TypeAlias

CSS color name.

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

Bases: Data

Database column description.

columnIndex: int
comment: str
default: str
geometrySrid: int
geometryType: GeometryType
hasDefault: bool
isAutoincrement: bool
isNullable: bool
isPrimaryKey: bool
isUnique: bool
name: str
nativeType: str
options: dict
type: AttributeType
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.Config(*args, **kwargs)

Bases: Data

Object configuration.

uid: str = ''

Unique ID.

exception gws.ConfigurationError

Bases: Error

GWS Configuration error.

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

Bases: Config

Basic config with permissions.

access: AclStr | None

Permission to read or use the object. (deprecated in 8.0)

permissions: PermissionsConfig | None

Access permissions.

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.

headers: dict

Additional headers.

mime: str

Response mime type.

gws.create_root(specs: SpecRuntime) Root
class gws.Crs

Coordinate reference system.

axis: Axis

Axis orientation.

base: int

Base CRS code.

datum: str

Datum.

epsg: str

Name in the “epsg” format.

extent: Extent

CRS own Extent.

isGeographic: bool

This CRS is geographic.

isProjected: bool

This CRS is projected.

isYX: bool

This CRS has a lat/lon axis.

name: str

CRS name.

proj4text: str

Proj4 definition.

srid: int

CRS SRID.

uom: Uom

CRS unit.

uri: str

Name in the “uri” format.

url: str

Name in the “url” format.

urn: str

Name in the “urn” format.

urnx: str

Name in the “urnx” format.

wgsExtent: Extent

CRS Extent in the WGS projection.

wkt: str

WKT definition.

axis_for_format(fmt: CrsFormat) Axis

Get the axis depending on the string format.

We adhere to the GeoServer convention here: https://docs.geoserver.org/latest/en/user/services/wfs/axis_order.html

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

to_string(fmt: CrsFormat | None = None) str

Return a string representation of the CRS.

Parameters:

fmt – Format to use.

Returns:

A string.

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.

class gws.CrsFormat

Bases: Enum

CRS name format.

crs = 'crs'

Like crs84.

epsg = 'epsg'

Like EPSG:3857.

none = ''
srid = 'srid'

Like 3857.

uri = 'uri'

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

url = 'url'

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

urn = 'urn'

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

urnx = 'urnx'

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

gws.CrsName: TypeAlias

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

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.

set(key, val)

Set an attribute value.

Parameters:
  • key – Attribute name.

  • val – Attribute value.

setdefault(key, val)

Set an attribute value if not already set.

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.

class gws.DatabaseManager

Bases: Node

Database manager.

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

Bases: Model

Database-based data model.

db: DatabaseProvider
sqlFilter: str
tableName: str
column(column_name: str) sqlalchemy.Column
table() sqlalchemy.Table
uid_column() sqlalchemy.Column
class gws.DatabaseProvider

Bases: Node

Database Provider.

A database Provider wraps SQLAlchemy Engine and Connection objects and provides common db functionality.

url: str

Connection url.

column(table: DatabaseTableAlike, column_name: str) sqlalchemy.Column

SA Column object for a specific column.

connect() ContextManager[sqlalchemy.Connection]

Context manager for a SA Connection.

Context calls to this method can be nested. An inner call is a no-op, as no new connection is created. Only the outermost connection is closed upon exit:

with db.connect():
    ...
    with db.connect(): # no-op
        ...
    # connection remains open
    ...
# connection closed
count(table: DatabaseTableAlike) int

Return table record count or 0 if the table does not exist.

describe(table: DatabaseTableAlike) DataSetDescription

Describe a table.

engine(**kwargs) sqlalchemy.Engine

SA Engine object for this provider.

execute_text(sql: str, **kwargs) sqlalchemy.CursorResult

Execute a textual DML statement and return a result.

has_column(table: DatabaseTableAlike, column_name: str) bool

Check if a specific column exists.

has_table(table_name: str) bool

Check if a specific table exists.

join_table_name(schema: str, name: str) str

Create a full table name from the schema and table names.

select_text(sql: str, **kwargs) list[dict]

Execute a textual SELECT statement and return a list of record dicts.

split_table_name(table_name: str) tuple[str, str]

Split a full table name into the schema and table names.

table(table_name: str, **kwargs) sqlalchemy.Table

SA Table object for a specific table.

table_bounds(table: DatabaseTableAlike) Bounds | None

Compute a bounding box for the table primary geometry.

gws.DatabaseTableAlike: TypeAlias

SA Table object or a string table name.

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

Bases: Data

Description of a database Table or a GDAL Dataset.

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

Locale-aware date formatter.

format(fmt: DateTimeFormat | str, date: datetime.date | str | None = None) str

Formats the date.

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.

iso(date=None) str

Returns the date in the ISO 8601 format 2013-12-11.

long(date=None) str

Returns the date in the medium format 11. Dezember 2013.

medium(date=None) str

Returns the date in the medium format 11.12.2013.

short(date=None) str

Returns the date in the short format 11.12.13.

gws.DateStr: TypeAlias

ISO date string like 2019-01-30.

class gws.DateTimeFormat

Bases: Enum

Enumeration indicating the length of the date/time format.

iso = 'iso'

ISO 8601 format.

long = 'long'

Local long format.

medium = 'medium'

Local medium format.

short = 'short'

Local short format.

gws.DateTimeStr: TypeAlias

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

gws.DirPath: TypeAlias

Directory path on the server.

gws.Duration: TypeAlias

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

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

Bases: Data

Empty command request.

gws.EmptyValue

Special value for empty fields.

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.

exception gws.Error

Bases: Exception

GWS error.

gws.ErrorValue

Special value for invalid fields.

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.

owner: ExtObjectDescriptor

Descriptor of the command owner.

request: Request

Request sent to the command.

tArg: str

Type of the command argument.

tOwner: str

Type of the command owner.

gws.Extent: TypeAlias

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

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

Bases: Data

Extension object descriptor.

classPtr: type

Class object.

extName: str

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

extType: str

Extension type like wms.

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.Feature

Feature object.

attributes: dict
category: str
createWithFeatures: list[Feature]
cssSelector: str
errors: list[ModelValidationError]
insertedPrimaryKey: str
isNew: bool
model: Model
props: FeatureProps
record: FeatureRecord
views: dict
get(name: str, default=None) Any
has(name: str) bool
raw(name: str) Any
render_views(templates: list[Template], **kwargs) Feature
set(name: str, value: Any) 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.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.FeatureProps(*args, **kwargs)

Bases: Props

Feature Proprieties.

attributes: dict
createWithFeatures: list[FeatureProps] | None
cssSelector: str
errors: list[ModelValidationError] | None
isNew: bool
modelUid: str
uid: str
views: dict
class gws.FeatureRecord(*args, **kwargs)

Bases: Data

Raw data from a feature source.

attributes: dict
meta: dict
shape: Shape | None
uid: str | None
gws.FeatureUid: TypeAlias

Unique Feature id.

gws.FilePath: TypeAlias

File path on the server.

class gws.Finder

Bases: Node

Finder object.

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

Bases: Error

Generic ‘forbidden’ error.

gws.FormatStr: TypeAlias

Format string as used in Python.

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

circularstring = 'circularstring'
compoundcurve = 'compoundcurve'
curve = 'curve'
curvepolygon = 'curvepolygon'
geometry = 'geometry'
geometrycollection = 'geometrycollection'
line = 'line'
linearring = 'linearring'
linestring = 'linestring'
multicurve = 'multicurve'
multilinestring = 'multilinestring'
multipoint = 'multipoint'
multipolygon = 'multipolygon'
multisurface = 'multisurface'
point = 'point'
polygon = 'polygon'
polyhedralsurface = 'polyhedralsurface'
surface = 'surface'
tin = 'tin'
triangle = 'triangle'
class gws.Image

Image object.

add_box(color=None) Image

Creates a 1 pixel wide box on the image’s edge.

Parameters:

color – Color of the box’s lines.

Returns:

The image with a box around the edges.

add_text(text: str, x=0, y=0, color=None) Image

Adds text to an image object.

Parameters:
  • text – Text to be displayed.

  • x – x-coordinate.

  • y – y-coordinate.

  • color – Color of the text.

Returns:

The image object with the text displayed.

compare_to(other: Image) float

Compare this image to another one.

@TODO describe the alogrithm

Returns:

The similarity factor as a float (the more, the different). ‘0’ means images are equal.

compose(other: Image, opacity=1) Image

Places other image on top of the current image.

Parameters:
  • other – Image to place on top.

  • opacity – other image’s opacity.

Returns:

The image object with the other image on top as an alpha composition.

crop(box) Image

Crops the image with respect to the given box.

Parameters:

box(width, height)

Returns:

The cropped image object.

mode() str

Get the image mode.

Returns:

PIL image mode.

paste(other: Image, where=None) Image

Pastes an image to a specific location.

Parameters:
  • other – Image that will be placed.

  • where(x-coord, y-coord) indicating where the upper left corer should be pasted.

Returns:

The image object with the other image placed inside.

resize(size: Size, **kwargs) Image

Resizes the image and scales it to fit the new size.

Parameters:

size(width, height)

Returns:

The resized image object.

rotate(angle: int, **kwargs) Image

Rotates the image.

Parameters:

angle – Angle to rotate the image.

Returns:

The rotated image object.

size() Size

Get the image size.

Returns:

A tuple (width, height).

to_array() numpy.typing.NDArray

Converts the image to an array.

Returns:

The image as an array. For each row each entry contains the pixel information.

to_base64(mime: str | None = None, options: dict | None = None) str

Return the image content as a base64 encoded string.

to_bytes(mime: str | None = None, options: dict | None = None) bytes

Converts the image object to bytes.

The options dict can contain any PIL save option (see https://pillow.readthedocs.io/en/stable/handbook/image-file-formats.html).

An additional option mode is the image mode (see https://pillow.readthedocs.io/en/stable/handbook/concepts.html#concept-modes). If provided, the image is converted to that mode before saving.

An additional option background sets the color to replace the alpha channel with when converting from RGBA to RGB (default is white).

Parameters:
  • mime – The mime type.

  • options – A dict of options.

Returns:

The image as bytes.

to_data_url(mime: str | None = None, options: dict | None = None) str

Return the image content as a base64-based data url.

to_path(path: str, mime: str | None = None, options: dict | None = None) str

Saves the image object at a given path.

Parameters:
  • path – Image’s path location.

  • mime – The mime type.

  • options – A dict of options.

Returns:

The path to the image.

class gws.ImageFormat

Bases: Enum

Image format

png24 = 'png24'

png 24-bit

png8 = 'png8'

png 8-bit

gws.is_data_object(x)

True if the argument is a Data object.

class gws.Job

Background Job object.

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

Bases: Enum

Background job state.

cancel = 'cancel'

The job was cancelled.

complete = 'complete'

The job has been completed successfully.

error = 'error'

There was an error.

init = 'init'

The job is being created.

open = 'open'

The job is just created and waiting for start.

running = 'running'

The job is running.

class gws.Layer

Bases: Node

Layer object.

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

Bases: Data

Layer cache.

maxAge: int
maxLevel: int
requestBuffer: int
requestTiles: int
class gws.LayerClientOptions(*args, **kwargs)

Bases: Data

Client options for a layer.

exclusive: bool

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

expanded: bool

A layer is expanded in the list view.

hidden: bool

A layer is initially hidden.

selected: bool

A layer is initially selected.

unfolded: bool

A layer is not listed, but its children are.

unlisted: bool

A layer is hidden in the list view.

class gws.LayerDisplayMode

Bases: Enum

Layer display mode.

box = 'box'

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

client = 'client'

Draw a layer in the client.

tile = 'tile'

Display a layer in a tile grid.

class gws.LayerOws

Bases: Node

Layer OWS controller.

allowedServiceUids: list[str]
deniedServiceUids: list[str]
featureName: str
geometryName: str
layerName: str
models: list[Model]
xmlNamespace: XmlNamespace | None
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.LayerRenderInputType

Bases: Enum

Layer render input type.

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

Bases: Data

Layer render output.

content: bytes
tags: list[XmlElement]
class gws.Legend

Bases: Node

Legend object.

render(args: dict | None = None) LegendRenderOutput | None
class gws.LegendRenderOutput(*args, **kwargs)

Bases: Data

Legend render output.

html: str
image: Image
image_path: str
mime: str
size: Size
class gws.Locale(*args, **kwargs)

Bases: Data

Locale data.

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

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

dayNamesLong: list[str]
dayNamesNarrow: list[str]
dayNamesShort: list[str]
firstWeekDay: int
language: str

de

Type:

Language code

language3: str

deu.

Type:

ISO 3166-1 alpha-3 language code

languageBib: str

Bibliographic language code..

languageName: str

Deutsch.

Type:

Native language name

languageNameEn: str

German.

Type:

English language name

monthNamesLong: list[str]
monthNamesNarrow: list[str]
monthNamesShort: list[str]
numberDecimal: str
numberGroup: str
territory: str
territoryName: str
uid: str
class gws.Map

Bases: Node

Map object.

bounds: Bounds
center: Point
coordinatePrecision: int
initResolution: float
resolutions: list[float]
rootLayer: Layer
title: str
wgsExtent: Extent
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.MapRenderInputPlane(*args, **kwargs)

Bases: Data

Map render input plane.

features: list[Feature]
image: Image
layer: Layer
opacity: float
soupPoints: list[Point]
soupTags: list[Any]
styles: list[Style]
subLayers: list[str]
type: MapRenderInputPlaneType
class gws.MapRenderInputPlaneType

Bases: Enum

Map render input plane type.

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

Bases: Data

Map render output.

planes: list[MapRenderOutputPlane]
view: MapView
class gws.MapRenderOutputPlane(*args, **kwargs)

Bases: Data

Map render output plane.

elements: list[XmlElement]
image: Image
path: str
type: MapRenderOutputPlaneType
class gws.MapRenderOutputPlaneType

Bases: Enum

Map render output plane type.

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

Bases: Data

Map view.

bounds: Bounds
center: Point
dpi: int
mmSize: Size
pxSize: Size
rotation: int
scale: int
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
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
fees: str | None
image: str | None
inspireDegreeOfConformity: str | None
inspireKeywords: list[str] | None
inspireMandatoryKeyword: 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
isoScope: str | None
isoScopeName: str | None
isoServiceFunction: str | None
isoSpatialRepresentationType: str | None
isoSpatialResolution: str | None
isoTopicCategories: list[str] | None
keywords: list[str] | None
language: str | None
language3: str | None
languageName: str | None
license: MetadataLicense | None
name: str | None
parentIdentifier: str | None
title: str | None
class gws.MetadataAccessConstraint(*args, **kwargs)

Bases: Data

Metadata AccessConstraint.

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

Bases: Data

Metadata Attribution.

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

Bases: Data

Metadata License.

title: str | None
url: Url | None

Bases: Data

Link metadata.

about: str | None
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.MiddlewareManager

Bases: Node

Configurable GWS object.

objects() list[Node]

Return a list of registered middleware objects.

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

Register an object as a middleware.

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
create_feature(feature: Feature, mc: ModelContext) FeatureUid
delete_feature(feature: Feature, mc: ModelContext) FeatureUid
describe() DataSetDescription | None
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
field(name: str) ModelField | None
find_features(search: SearchQuery, mc: ModelContext) list[Feature]
get_features(uids: Iterable[str | int], mc: ModelContext) list[Feature]
init_feature(feature: Feature, mc: ModelContext)
related_models() list[Model]
update_feature(feature: Feature, mc: ModelContext) FeatureUid
validate_feature(feature: Feature, mc: ModelContext) bool
class gws.ModelContext(*args, **kwargs)

Bases: Data

Model context.

dbConnection: sqlalchemy.Connection
dbSelect: ModelDbSelect
maxDepth: int = 0
op: ModelOperation
project: Project
relDepth: int = 0
search: SearchQuery
target: ModelReadTarget
user: User
class gws.ModelDbSelect(*args, **kwargs)

Bases: Data

Database select statement.

columns: list[sqlalchemy.Column]
geometryWhere: list
keywordWhere: list
order: list
where: list
class gws.ModelField

Bases: Node

Model field.

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

Bases: Node

Model manager.

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

Bases: Enum

Model operation.

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

Bases: Enum

Target for the read operation.

editForm = 'editForm'

The feature is to be displayed in an edit form .

editList = 'editList'

The feature is to be displayed in an editable list view.

list = 'list'

The feature is to be displayed in a list view.

map = 'map'

The feature is to be drawn on a map.

searchResults = 'searchResults'

The feature is to be displayed in the search results list.

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

Bases: Data

Validation error.

fieldName: str
message: str
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.ModelWidget

Bases: Node

Model widget.

supportsTableView: bool = True
class gws.Node

Bases: Object

Configurable GWS object.

children: list[Node]

Child objects.

config: Config

Configuration for this object.

extName: str

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

extType: str

Extension type like wms.

parent: Node

Parent object.

root: Root

Root object.

uid: str

Unique ID.

activate()

Activation hook.

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.

configure()

Configuration 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.

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.

find_all(classref: ClassRef)

Find all children that match a specific class.

Parameters:

classref – Class reference.

Returns:

A list of objects.

find_ancestors(classref: ClassRef | None = None)

Find node ancestors that match a specific class.

Parameters:

classref – Class reference.

Returns:

A list of objects.

find_closest(classref: ClassRef)

Find the closest node ancestor that matches a specific class.

Parameters:

classref – Class reference.

Returns:

An object or None.

find_descendants(classref: ClassRef | None = None)

Find node descendants that match a specific class.

Parameters:

classref – Class reference.

Returns:

A list of objects in the depth-first order.

find_first(classref: ClassRef)

Find the first child that matches a specific class.

Parameters:

classref – Class reference.

Returns:

An object or None.

initialize(config)
is_a(classref: ClassRef)

Check if a the node matches the class reference.

Parameters:

classref – Class reference.

Returns:

A boolean.

post_configure()

Post-configuration hook.

pre_configure()

Pre-configuration hook.

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.

exception gws.NotFoundError

Bases: Error

Generic ‘object not found’ error.

class gws.NumberFormat

Bases: Enum

Enumeration indicating the number format.

currency = 'currency'

Locale currency format

decimal = 'decimal'

Locale decimal format.

grouped = 'grouped'

Locale grouped format.

percent = 'percent'

Locale percent format.

class gws.NumberFormatter

Locale-aware number formatter.

currency(n, currency: str, *args, **kwargs) str

Returns formatted currency value.

decimal(n, *args, **kwargs) str

Returns formatted decimal value.

format(fmt: NumberFormat | 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.

grouped(n, *args, **kwargs) str

Returns formatted decimal value with group separators.

percent(n, *args, **kwargs) str

Returns formatted percent value.

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

Bases: Enum

Grid origin.

lb = 'sw'

left bottom

lt = 'nw'

left top

ne = 'ne'

north-east

nw = 'nw'

north-west

rb = 'se'

right bottom

rt = 'ne'

right top

se = 'se'

south-east

sw = 'sw'

south-west

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.

password: str
type: str
username: str
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.OwsImageFormat(*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.

mimeTypes: list[str]

Mime types for this format.

options: dict

Image options.

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

Bases: Data

OWS operation.

allowedParameters: dict[str, list[str]]
constraints: dict[str, list[str]]
formats: list[str]
handlerName: str
params: dict[str, str]
postUrl: Url
preferredFormat: str
url: Url
verb: OwsVerb
class gws.OwsProtocol

Bases: Enum

Supported OWS protocol.

CSW = 'CSW'
WCS = 'WCS'
WFS = 'WFS'
WMS = 'WMS'
WMTS = 'WMTS'
class gws.OwsProvider

Bases: Node

OWS services Provider.

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

Bases: Node

OWS Service.

alwaysXY: bool

Force lon/lat order for geographic projections.

defaultFeatureCount: int

Default limit of features per page.

imageFormats: list[OwsImageFormat]

Supported image formats.

isOwsCommon: bool = False

Conforms to OGC Web Services Common Standard.

isRasterService: bool = False

Service provides raster services.

isVectorService: bool = False

Service provides vector services.

maxFeatureCount: int

Max limit of features per page.

metadata: Metadata

Service metadata.

name: str

Service name.

project: Project | None

Project this service is configured for.

protocol: OwsProtocol

Supported protocol.

rootLayer: Layer | None

Root layer of the service.

searchTolerance: UomValue

Default tolerance for spatial search.

supportedBounds: list[Bounds]

Supported bounds.

supportedOperations: list[OwsOperation]

Supported operations.

supportedVersions: list[str]

Supported versions.

templates: list[Template]

Service templates.

updateSequence: str

Service update sequence.

withInspireMeta: bool

Include INSPIRE metadata.

withStrictParams: bool

Strict parameter checking.

handle_request(req: WebRequester) ContentResponse

Handle a service request.

layer_is_suitable(layer: Layer) bool

True if layer can be used in this service.

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.PermissionsConfig

Permissions configuration.

all: AclStr | None

All permissions.

create: AclStr | None

Permission to create new objects.

delete: AclStr | None

Permission to delete objects.

edit: AclStr | None

A combination of write, create and delete.

read: AclStr | None

Permission to read the object.

write: AclStr | None

Permission to change the object.

gws.Point: TypeAlias

Point coordinates [x, y].

class gws.Printer

Bases: Node

Printer object.

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

Bases: Node

Print Manager.

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

Bases: Response

Print job information response.

jobUid: str
progress: int
state: JobState
stepName: str
stepType: str
url: str
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.PrintPlane(*args, **kwargs)

Bases: Data

Print plane.

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

Bases: Enum

Print plane type.

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

Bases: Request

Print request.

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

Bases: Enum

Type of the print request.

map = 'map'
template = 'template'
class gws.Project

Bases: Node

Project object.

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

Bases: Data

Object properties.

uid: str = ''

Unique ID.

gws.props_of(obj: Object, user: User, *context) Props | None
class gws.RedirectResponse(*args, **kwargs)

Bases: Response

Web redirect response.

headers: dict

Additional headers.

location: str

Redirect URL.

gws.Regex: TypeAlias

Regular expression, as used in Python.

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

Bases: Data

Database relationship description.

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

Bases: Data

Command request.

localeUid: str | None

Locale ID for this request.

projectUid: str | None

Unique ID of the project.

class gws.RequestMethod

Bases: Enum

Web request method.

CONNECT = 'CONNECT'
DELETE = 'DELETE'
GET = 'GET'
HEAD = 'HEAD'
OPTIONS = 'OPTIONS'
PATCH = 'PATCH'
POST = 'POST'
PUT = 'PUT'
TRACE = 'TRACE'
class gws.Response(*args, **kwargs)

Bases: Data

Command response.

error: ResponseError | None

Response error.

status: int

Response status or exit code.

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

Bases: Data

Response error.

code: int | None

Error code.

info: str | None

Information about the error.

exception gws.ResponseTooLargeError

Bases: Error

Generic error when a response is too large.

class gws.Root(specs: SpecRuntime)

Root node of the object tree.

app: Application

Application object.

configErrors: list

List of configuration errors.

configStack: list[Node]
nodes: list[Node]
specs: SpecRuntime

Specs runtime.

uidCount: int
uidMap: dict[str, Node]
activate()
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_application(config: Config = None, **kwargs) Application

Create the Application object.

Parameters:
  • config – Configuration.

  • **kwargs – Additional configuration properties.

Returns:

The Application object.

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.

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.

initialize(obj, config)
object_count() int

Return the number of objects in the tree.

post_initialize()

Post-initialization hook.

class gws.SearchManager

Bases: Node

Search Manager.

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
finder: Finder
layer: Layer
class gws.SearchSort(*args, **kwargs)

Bases: Data

Search sort specification.

fieldName: str
reverse: bool
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.

class gws.Shape

Bases: Object

Geo-referenced geometry.

crs: Crs

CRS of this shape.

type: GeometryType

Geometry type.

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.

contains(other: Shape) bool

Returns True if this shape contains the other.

covered_by(other: Shape) bool

Returns True if this shape is covered by the other.

covers(other: Shape) bool

Returns True if this shape covers 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.

equals(other: Shape) bool

Returns True if this shape is equal to the other.

intersection(*others: Shape) Shape

Computes an intersection of this shape and other shapes.

intersects(other: Shape) bool

Returns True if this shape intersects with the other.

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.

overlaps(other: Shape) bool

Returns True if this shape overlaps the other.

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_ewkt() str

Returns an EWKT representation of this shape.

to_geojson(always_xy=False) dict

Returns a GeoJSON representation of this shape.

to_multi() Shape

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

to_props() ShapeProps

Returns a GeoJSON representation of this shape.

to_type(new_type: GeometryType) Shape

Converts a geometry to another type.

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_wkt() str

Returns a WKT representation of this shape.

tolerance_polygon(tolerance, quad_segs=None) Shape

Builds a buffer polygon around the shape.

touches(other: Shape) bool

Returns True if this shape touches the other.

transformed_to(crs: Crs) Shape

Returns this shape transformed to another CRS.

union(others: list[Shape]) Shape

Computes a union of this shape and other shapes.

within(other: Shape) bool

Returns True if this shape is within the other.

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

Bases: Props

Shape properties.

crs: str
geometry: dict
gws.Size: TypeAlias

Size [width, height].

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

Bases: Data

Sort options.

fieldName: str
reverse: bool = False
class gws.SourceLayer(*args, **kwargs)

Bases: Data

Generic OGC Layer.

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

Bases: Data

Generic OGC Style.

isDefault: bool
legendUrl: Url
metadata: Metadata
name: str
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.SpecRuntime

Specification runtime.

appBundlePaths: list[str]

List of client bundle paths.

manifest: ApplicationManifest

Application manifest.

version: str

Application version.

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.

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.

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).

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.

register_object(ext_name: ClassRef, obj_type: str, cls: type)

Dynamically register an extension object.

class gws.StorageManager

Bases: Node

Storage manager.

providers: list[StorageProvider]
create_provider(cfg: Config, **kwargs) StorageProvider
find_provider(uid: str | None = None) StorageProvider | None
class gws.StorageProvider

Bases: Node

Storage provider.

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

Bases: Data

Storage record.

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

CSS Style object.

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

Bases: Props

CSS Style properties.

cssSelector: str | None
text: str | None
values: dict | None
class gws.StyleValues(*args, **kwargs)

Bases: Data

CSS Style values.

fill: Color
icon: str
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
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
offset_x: int
offset_y: int
point_size: int
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
with_geometry: Literal[all, none]
with_label: Literal[all, none]
class gws.Template

Bases: Node

Template object.

mapSize: UomSize

Default map size for the template.

mimeTypes: list[str]

MIME types the template can generate.

pageMargin: UomExtent

Default page margin for printing.

pageSize: UomSize

Default page size for printing.

subject: str

Template subject (category).

title: str

Template title.

render(tri: TemplateRenderInput) ContentResponse

Render the template and return the generated response.

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

Bases: Data

Template arguments.

app: Application

Application object.

date: DateFormatter

Locale-aware date formatter.

gwsBaseUrl: str

GWS server base url. (deprecated in 8.1)

gwsVersion: str

GWS version. (deprecated in 8.1)

locale: Locale

Current locale.

number: NumberFormatter

Locale-aware number formatter.

time: TimeFormatter

Locale-aware time formatter.

class gws.TemplateManager

Bases: Node

Template manager.

find_template(subject: str, where: list[Node], user: User = None, mime: str = None) Template | None
template_from_path(path: str) Template | None
class gws.TemplateQualityLevel(*args, **kwargs)

Bases: Data

Template quality level.

dpi: int
name: str
class gws.TemplateRenderInput(*args, **kwargs)

Bases: Data

Template render input.

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

Bases: Data

Text search options.

caseSensitive: bool = False

Use the case sensitive search.

minLength: int = 0

Minimal pattern length.

type: TextSearchType

Type of the search.

class gws.TextSearchType

Bases: Enum

Text search type.

any = 'any'

Match any substring.

begin = 'begin'

Match the beginning of the string.

end = 'end'

Match the end of the string.

exact = 'exact'

Match the whole string.

like = 'like'

Use the percent sign as a placeholder.

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

Bases: Data

Tile grid.

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

Bases: Data

WMTS TileMatrix object.

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

Bases: Data

WMTS TileMatrixSet object.

crs: Crs
matrices: list[TileMatrix]
uid: str
class gws.TimeFormatter

Locale-aware time formatter.

format(fmt: DateTimeFormat | str, time: datetime.time | str | None = None) str

Formats the time.

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

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

Returns:

A formatted time string.

iso(time=None) str

Returns the time and date in the ISO 8601 format.

long(time=None) str

Returns the time in the medium format 11:22:33.

medium(time=None) str

Returns the time in the medium format 11:22:33.

short(time=None) str

Returns the time in the short format 11:22.

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.Uom

Bases: Enum

Unit of measure.

ch = 'ch'

chain (EPSG 9097)

cm = 'cm'

centimetre (EPSG 1033)

deg = 'deg'

degree (EPSG 9102)

dm = 'dm'

decimeter dm

fath = 'fath'

fathom (EPSG 9014)

ft = 'ft'

foot (EPSG 9002)

grad = 'grad'

grad (EPSG 9105)

inch = 'in'

inch in

km = 'km'

kilometre (EPSG 9036)

kmi = 'kmi'

nautical mile (EPSG 9030)

link (EPSG 9098)

m = 'm'

metre (EPSG 9001)

mi = 'mi'

statute mile (EPSG 9093)

mm = 'mm'

millimetre (EPSG 1025)

pt = 'pt'

point

px = 'px'

pixel

rad = 'rad'

radian (EPSG 9101)

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

yd = 'yd'

yard (EPSG 9096)

gws.UomExtent: TypeAlias

Extent with a unit.

gws.UomExtentStr: TypeAlias

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

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.UomValue: TypeAlias

A value with a unit.

gws.UomValueStr: TypeAlias

A value with a unit like 5mm.

gws.Url: TypeAlias

URL.

class gws.User

Bases: Object

User object.

attributes: dict

Public user attributes.

authProvider: AuthProvider

User authorization provider.

authToken: str

Token used for authorization.

data: dict

Private user data.

displayName: str

User display name.

email: str

User email.

isGuest: bool

User is a Guest.

localUid: str

User uid within its authorization provider.

loginName: str

User login name.

mfaSecret: str

MFA secret.

mfaUid: str

MFA adapter uid.

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.

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.

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_edit(obj: Object, *context) bool

Check if the user has “edit” permissions 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.

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_layer(uid=None) Layer

Get a readable Layer object.

Parameters:

uid – Layer uid.

Returns:

A Layer object.

require_project(uid: str = None) Project

Get a readable Project object.

Parameters:

uid – Project uid.

Returns:

A Project object.

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

Bases: Data

CORS options.

allowCredentials: bool
allowHeaders: str
allowMethods: str
allowOrigin: str
class gws.WebDocumentRoot(*args, **kwargs)

Bases: Data

Web document root.

allowMime: list[str]

Allowed mime types.

denyMime: list[str]

Restricted mime types.

dir: DirPath

Local directory.

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.WebRequester

Web Requester object.

environ: dict

Request environment.

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.

method: RequestMethod

Request method.

root: Root

Object tree root.

session: AuthSession

Current session.

site: WebSite

Website the request is processed for.

user: User

Current use.

api_responder(response: Response) WebResponder

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

Parameters:

response – Response object.

Returns:

A Responder.

command() str

Command name to execute.

content_responder(response: ContentResponse) WebResponder

Return a Responder object for a content response.

Parameters:

response – Response object.

Returns:

A Responder.

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

Get a cookie.

Parameters:
  • key – Cookie name.

  • default – Default value.

Returns:

A cookie value.

data() bytes | None

Get POST data.

Returns:

Data bytes or None if request is not a POST.

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

Get an environment variable.

Parameters:
  • key – Variable name.

  • default – Default value.

Returns:

A variable value.

error_responder(exc: Exception) WebResponder

Return a Responder object for an Exception.

Parameters:

exc – An Exception.

Returns:

A Responder.

has_param(key: str) bool

Check if a GET parameter exists.

Parameters:

key – Parameter name.

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.

params() dict

GET parameters.

redirect_responder(response: RedirectResponse) WebResponder

Return a Responder object for a redirect response.

Parameters:

response – Response object.

Returns:

A Responder.

set_session(session: AuthSession)

Attach a session to the requester.

Parameters:

session – A Session object.

struct() dict

Structured JSON payload.

text() str | None

Get POST data as a text.

Returns:

Data string or None if request is not a POST.

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.

class gws.WebResponder

Web Responder object.

status: int

Response status.

add_header(key: str, value: str)

Add a header.

Parameters:
  • key – Header name.

  • value – Header value.

Delete a cookie.

Parameters:
  • key – Cookie name.

  • **kwargs – Cookie options.

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.

set_status(status: int)

Set the response status.

Parameters:

status – HTTP status code.

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

Bases: Data

Rewrite rule.

options: dict

Extra options.

pattern: Regex

URL matching pattern.

reversed: bool

Reversed rewrite rule.

target: str

Rule target, with dollar placeholders.

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.XmlElement

Bases: Iterable

XML Element.

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

attrib: dict

Dictionary of element attributes.

caseInsensitive: bool

Element is case-insensitive.

lcName: str

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

name: str

Element name (tag without a namespace).

tag: str

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

tail: str | None

Text after this element’s end tag.

text: str | None

Text before first subelement.

add(tag: str, attrib: dict | None = None, **extra) XmlElement

Creates a new XmlElementImpl and adds it as a child.

Parameters:
  • tag – XML tag.

  • attrib – XML attributes {key, value}.

Returns:

A XmlElementImpl.

append(subelement: XmlElement)

Adds the element subelement to the end of this element’s internal list of subelements.

attr(key: str, default=None)

Finds the value for a given key in the XmlElementImpl.

Parameters:
  • key – Key of the attribute.

  • default – The default return.

Returns:

The vale of the key, If the key is not found the default is returned.

children() list[XmlElement]

Returns the children of the current XmlElementImpl.

clear()

Resets an element.

extend(subelements: Iterable[XmlElement])

Appends subelements from a sequence object with zero or more elements.

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.

findfirst(*paths) XmlElement | None

Returns the first element in the current element.

Parameters:

paths – Path as tag/tag2/tag3 to the Element to search in.

Returns:

Returns the first found element.

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

Finds text for first matching element by name or path.

get(key: str, default=None)

Returns the value to a given key.

insert(index: int, subelement: XmlElement)

Inserts subelement at the given position in this element.

items() Iterable[tuple[str, Any]]

Returns the element attributes as a sequence of (name, value) pairs.

iter(tag: str | None = None) Iterable[XmlElement]

Creates a tree iterator.

iterfind(path: str | None = None) Iterable[XmlElement]

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

itertext() Iterable[str]

Creates a text iterator and returns all inner text.

keys() Iterable[str]

Returns the elements attribute names as a list.

remove(other: XmlElement)

Removes the other element from the element.

set(key: str, value: Any)

Set the attribute key on the element to value.

textdict(*paths, deep=False) dict[str, str]

Collects texts from child-elements.

Parameters:
  • paths – Path as tag/tag2/tag3 to the Element to collect texts from.

  • deep – If False it only looks into direct children, otherwise it searches for texts in the complete children-tree.

Returns:

A dict containing all the text from the child-elements.

textlist(*paths, deep=False) list[str]

Collects texts from child-elements.

Parameters:
  • paths – Path as tag/tag2/tag3 to the Element to collect texts from.

  • deep – If False it only looks into direct children, otherwise it searches for texts in the complete children-tree.

Returns:

A list containing all the text from the child-elements.

textof(*paths) str

Returns the text of a given child-element.

Parameters:

paths – Path as tag/tag2/tag3 to the Element.

Returns:

The text of the element.

to_dict() dict

Creates a dictionary from an XmlElement object.

to_list(fold_tags: bool = True, remove_namespaces: bool = False) list

Parse an XML element into a list of arguments.

Parameters:
  • fold_tags – If true, folds nested tag names into parent/child names.

  • remove_namespaces – If true, removes all namespaces.

to_string(extra_namespaces: list[XmlNamespace] | None = None, compact_whitespace: bool = False, remove_namespaces: bool = False, with_namespace_declarations: bool = False, with_schema_locations: bool = False, with_xml_declaration: bool = False) str

Converts the Element object to a string.

Parameters:
  • extra_namespaces – Extra namespaces to add to the document.

  • 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.

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

Bases: Data

XML namespace.

extendsGml: bool

Namespace schema extends the GML3 schema.

schemaLocation: Url

Namespace schema location.

uid: str

Unique ID.

uri: Url

Namespace uri.

version: str

Namespace version.

xmlns: str

Default prefix for this Namespace.