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(*args, **kwds)

Bases: Enum

Access mode.

create = 'create'

Permission to create new objects.

delete = 'delete'

Permission to delete objects.

read = 'read'

Permission to read the object.

write = 'write'

Permission to change the object.

type gws.Acl = list[tuple[int, str]]

Access Control list.

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

type gws.AclStr = str

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

class gws.Action

Bases: Node

Base Action class.

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.

Parameters:
  • project – The project requiring actions.

  • user – The user for whom the actions are retrieved.

Returns:

A list of accessible actions.

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

Locate an Action object.

Parameters:
  • project – If provided, find the action for that project; otherwise, search globally.

  • ext_type – The extension type to search for.

  • user – Locate actions only for this user.

Returns:

The located action object, or None if no match is found.

prepare_action(command_category: CommandCategory, command_name: str, params: dict, user: User, read_options: set[SpecReadOption] | None = None) tuple[Callable, Request]

Prepare an action to be executed based on the provided parameters.

Parameters:
  • command_category – The category of the command to execute.

  • command_name – The name of the command to execute.

  • params – Additional parameters required for the action.

  • user – The user initiating the action.

  • read_options – Read options for parsing parameters.

Returns:

A tuple containing the callable to execute and the associated request object.

class gws.Application

Bases: Node

Main Application object.

actionMgr: ActionManager

Manager for application actions.

actions: list[Action]

List of defined application actions.

authMgr: AuthManager

Manager for authentication operations.

client: Client

Represents the client object associated with the application.

databaseMgr: DatabaseManager

Manager for database operations.

defaultPrinter: Printer

Default printer object.

finders: list[Finder]

List of finder objects.

jobMgr: JobManager

Manager for handling jobs.

localeUids: list[str]

List of locale identifiers.

metadata: Metadata

Metadata for the application.

middlewareMgr: MiddlewareManager

Manager for middleware and dependencies.

modelMgr: ModelManager

Manager for model operations.

models: list[Model]

List of global models.

monitor: ServerMonitor

Server monitor object.

owsServices: list[OwsService]

List of OWS services.

printerMgr: PrinterManager

Manager for printers.

printers: list[Printer]

List of global printer objects.

projects: list[Project]

List of configured projects.

searchMgr: SearchManager

Manager for search functionality.

serverMgr: ServerManager

Manager for server operations.

storageMgr: StorageManager

Manager for storage operations.

templateMgr: TemplateManager

Manager for templates.

templates: list[Template]

List of global templates.

vars: dict

Application variables.

version: str

Application version as a string.

versionString: str

Full version string for display purposes.

webMgr: WebManager

Manager for web operations.

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.

tsConfig: list[str]

Path to tsconfig.json.

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(*args, **kwds)

Bases: Enum

Feature attribute type.

bool = 'bool'

Boolean value.

bytes = 'bytes'

Binary data.

date = 'date'

Date value.

datetime = 'datetime'

Date and time value.

feature = 'feature'

Feature reference.

featurelist = 'featurelist'

List of features.

file = 'file'

File reference.

float = 'float'

Floating-point number.

floatlist = 'floatlist'

List of floating-point numbers.

geometry = 'geometry'

Geometry reference.

int = 'int'

Integer number.

intlist = 'intlist'

List of integer numbers.

str = 'str'

String value.

strlist = 'strlist'

List of strings.

time = 'time'

Time value.

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_multi_factor_adapter(uid: str) AuthMultiFactorAdapter | None

Get a Multi-Factor Adapter by its uid.

Parameters:

uid – Adapter uid.

Returns:

A Multi-Factor Adapter or None if not found.

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.

is_public_object(obj: Object, *context) bool

Check if an object is public.

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.

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(*args, **kwds)

Bases: Enum

State of a multifactor authorization transaction.

failed = 'failed'

Authorization failed.

ok = 'ok'

Transaction completed successfully.

open = 'open'

Transaction opened.

retry = 'retry'

Authorization has to be retried.

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

Bases: Data

Multifactor authorization transaction.

adapter: AuthMultiFactorAdapter

The MFA adapter handling this transaction.

generateTime: int

The timestamp when the code was last generated.

message: str

A message associated with the transaction.

restartCount: int

The number of times the transaction has been restarted.

secret: str

The secret associated with this transaction.

startTime: int

The timestamp when the transaction started.

state: AuthMultiFactorState

The current state of the authorization transaction.

user: User

The user associated with this transaction.

verifyCount: int

The number of verification attempts made.

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(*args, **kwds)

Bases: Enum

Axis orientation.

xy = 'xy'

XY (longitude/latitude) axis orientation.

yx = 'yx'

YX (latitude/longitude) axis orientation.

exception gws.BadRequestError

Bases: Error

Generic ‘bad request’ error.

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

Bases: Data

Geo-referenced extent.

crs: Crs
extent: Extent
type gws.ClassRef = type | str

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

type gws.Color = str

CSS color name.

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

Bases: Data

Description of a dataset column.

columnIndex: int

The index of the column within the table.

comment: str

Column comment or description provided in the database metadata.

default: str

The default value assigned to the column, if any.

geometrySrid: int

The Spatial Reference Identifier (SRID) for geometry columns.

geometryType: GeometryType

The type of geometry stored in the column (e.g., Point, Polygon).

hasDefault: bool

Indicates if the column has a database-defined default value.

isAutoincrement: bool

Indicates if the column is auto-incremented.

isIndexed: bool

Indicates if the column has an index.

isNullable: bool

Specifies if the column permits NULL values.

isPrimaryKey: bool

Specifies if the column is part of the primary key.

isUnique: bool

Indicates if the column has a unique constraint.

name: str

The name of the column.

nativeType: str

The database-specific data type of the column.

options: dict

Additional options or configurations for the column, if any.

type: AttributeType

The abstract type of the column used in higher-level processing.

class gws.CommandCategory(*args, **kwds)

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.

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

Bases: Data

Configuration context for parsing and validation.

errors: list
paths: set[str]
readOptions: set[SpecReadOption]
specs: SpecRuntime
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.

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.

bounds: Bounds

CRS own Bounds.

coordinatePrecision: int

Preferred precision for coordinates in this CRS.

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

extent_size_in_meters(extent: Extent) Size

Calculate the width and height of an extent in meters;

Parameters:

extent – Extent.

point_offset_in_meters(xy: Point, dist: float, az: int) Point

Calculate a point with an offset in meters. :param xy: Point. :param dist: Distance in meters. :param az: Azimuth in degrees (0 = North, 90 = East, etc.).

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(*args, **kwds)

Bases: Enum

CRS name format.

crs = 'crs'

Like crs84.

epsg = 'epsg'

Like EPSG:3857.

none = ''

No format.

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.

type gws.CrsName = int | str

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

Database connection.

Extends sqlalchemy.Connection and provides some convenience methods.

saConn: sqlalchemy.Connection
close()
commit()
exec(stmt: DatabaseStmt, **params) sqlalchemy.CursorResult
exec_commit(stmt: DatabaseStmt, **params) sqlalchemy.CursorResult
exec_rollback(stmt: DatabaseStmt, **params) sqlalchemy.CursorResult
execute(stmt: sqlalchemy.Executable, params=None, execution_options: dict = None) sqlalchemy.CursorResult
fetch_all(stmt: DatabaseStmt, **params) list[dict]
fetch_first(stmt: DatabaseStmt, **params) dict | None
fetch_int(stmt: DatabaseStmt, **params) int | None
fetch_ints(stmt: DatabaseStmt, **params) list[int]
fetch_scalar(stmt: DatabaseStmt, **params) Any
fetch_scalars(stmt: DatabaseStmt, **params) list
fetch_string(stmt: DatabaseStmt, **params) str | None
fetch_strings(stmt: DatabaseStmt, **params) list[str]
rollback()
class gws.DatabaseManager

Bases: Node

Database manager.

providers: list[DatabaseProvider]

A list of database providers managed by this DatabaseManager.

create_provider(cfg: Config, **kwargs) DatabaseProvider

Create and return a DatabaseProvider instance based on the given configuration.

Parameters:
  • cfg – The configuration object for the database provider.

  • **kwargs – Additional keyword arguments to customize the provider creation.

Returns:

A new database provider instance.

Return type:

DatabaseProvider

find_provider(uid: str | None = None, ext_type: str | None = None) DatabaseProvider | None

Find and return a DatabaseProvider that matches the given UID and/or extension type.

Parameters:
  • uid – The unique identifier of the database provider to find.

  • ext_type – The type of the database provider to find.

Returns:

The matching database provider if found, otherwise None.

class gws.DatabaseModel

Bases: Model

Database-based data model.

db: DatabaseProvider

Database provider.

sqlFilter: str

Literal SQL condition applied when selecting rows.

tableName: str

Table name associated with this model.

build_select(mc: ModelContext) sqlalchemy.Select | None

Build a SQLAlchemy Select statement based on the provided ModelContext.

column(column_name: str) sqlalchemy.Column

Retrieve the SQLAlchemy Column object for the given column name.

fetch_features(select: sqlalchemy.Select) list[Feature]

Fetch features from the database based on the provided SQLAlchemy Select statement.

table() sqlalchemy.Table

Return the SQLAlchemy Table object for this database model.

uid_column() sqlalchemy.Column

Return the SQLAlchemy Column object representing the unique identifier column.

class gws.DatabaseProvider

Bases: Node

Database Provider.

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

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

SQLAlchemy Column object for a specific column.

connect() DatabaseConnection

Context manager for SQLAlchemy 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.

create_engine(**kwargs) sqlalchemy.Engine

CreateSQLAlchemy Engine object for this provider.

describe(table: DatabaseTableAlike) DataSetDescription

Describe a table.

engine() sqlalchemy.Engine

Get SQLAlchemy Engine object for this provider.

engine_options(**kwargs)

Add defaults to the SA engine options.

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

Execute a textual DML stmt 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 stmt 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: DatabaseTableAlike, **kwargs) sqlalchemy.Table

SQLAlchemy Table object for a specific table.

table_bounds(table: DatabaseTableAlike) Bounds | None

Compute a bounding box for the table primary geometry.

url() str

Return the connection URL.

type gws.DatabaseStmt = 'sqlalchemy.Executable' | str

An Executable SQLAlchemy object or a string SQL statement.

type gws.DatabaseTableAlike = 'sqlalchemy.Table' | str

An SQLAlchemy Table object or a string table name.

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

Bases: Data

Description of a dataset, like a DB table or a GDAL data set.

columnMap: dict[str, ColumnDescription]

A dictionary mapping column names to their descriptions.

columns: list[ColumnDescription]

A list of column descriptions.

fullName: str

The full name of the dataset, including schema if applicable.

geometryName: str

The name of the geometry column, if any.

geometrySrid: int

The Spatial Reference Identifier (SRID) for the geometry.

geometryType: GeometryType

The type of geometry stored in the dataset.

name: str

The name of the dataset or table.

schema: str

The schema to which the dataset belongs.

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.

type gws.DateStr = str

ISO date string like 2019-01-30.

class gws.DateTimeFormat(*args, **kwds)

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.

type gws.DateTimeStr = str

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

type gws.DirPath = str

Directory path on the server.

type gws.Duration = str

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(*args, **kwds)

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

Generic GWS error.

gws.ErrorValue

Special value for invalid fields.

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

Bases: Data

Represents a command descriptor for an extension.

Contains attributes to describe and handle a specific extension command.

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.

type gws.Extent = tuple[float, float, float, float]

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: int | str | None
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_svg(view: MapView, label: str | None = None, style: Style | None = None) list[XmlElement]
transform_to(crs: Crs) Feature
uid() FeatureUid
class gws.FeatureLoadingStrategy(*args, **kwds)

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
category: str | None
createWithFeatures: list[FeatureProps] | None
cssSelector: str
errors: list[ModelValidationError] | None
isNew: bool
modelUid: str
uid: str

Unique ID.

views: dict
class gws.FeatureRecord(*args, **kwargs)

Bases: Data

Raw data from a feature source.

attributes: dict
ewkt: str
meta: dict
shape: Shape | None
uid: str | None
type gws.FeatureUid = str

Unique Feature id.

type gws.FilePath = str

File path on the server.

class gws.Finder

Bases: Node

Finder object.

category: str
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.

type gws.FormatStr = str

Format string as used in Python.

class gws.GeometryType(*args, **kwds)

Bases: Enum

Feature geometry type.

OGC and SQL/MM geometry types.

References

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(*args, **kwargs)

Bases: Data

Image format

mimeTypes: list[str]

Mime types for this format.

options: dict

Image options.

gws.is_data_object(x)

True if the argument is a Data object.

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

Bases: Data

Background job data.

error: str
numSteps: int
payload: dict
state: JobState
step: int
stepName: str
uid: str
user: User
worker: str
class gws.JobManager

Bases: Node

Job Manager.

cancel_job(job: Job) Job | None
create_job(user: User, worker: type, payload: dict = None) Job
get_job(job_uid: str, user: User = None, state: JobState = None) Job | None
handle_cancel_request(req: WebRequester, p: JobRequest) JobStatusResponse
handle_status_request(req: WebRequester, p: JobRequest) JobStatusResponse
job_status_response(job: Job, **kwargs) JobStatusResponse
remove_job(job: Job)
require_job(req: WebRequester, p: JobRequest) Job
run_job(job: Job) Job | None
schedule_job(job: Job) Job
update_job(job: Job, **kwargs) Job | None
class gws.JobRequest(*args, **kwargs)

Bases: Request

Command request.

jobUid: str
class gws.JobState(*args, **kwds)

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.JobStatusResponse(*args, **kwargs)

Bases: Response

Command response.

jobUid: str
output: dict
progress: int
state: JobState
stepName: str
exception gws.JobTerminated

Bases: Exception

Common base class for all non-exit exceptions.

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: ImageFormat
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
zoomBounds: Bounds
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 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.

treeClassName: str

CSS class name for the layer tree item.

unfolded: bool

A layer is not listed, but its children are.

unlisted: bool

A layer is hidden in the list view.

class gws.LayerDisplayMode(*args, **kwds)

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.

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

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
type gws.LocaleUid = str

Locale uid like de_DE.

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.

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

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(*args, **kwds)

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

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.

abstract: str
accessConstraints: str
accessConstraintsType: str
attribution: str
attributionUrl: str
authorityIdentifier: str
authorityName: str
authorityUrl: str
catalogCitationUid: str
catalogUid: str
contactAddress: str
contactAddressType: str
contactArea: str
contactCity: str
contactCountry: str
contactEmail: str
contactFax: str
contactOrganization: str
contactPerson: str
contactPhone: str
contactPosition: str
contactProviderName: str
contactProviderSite: str
contactRole: str
contactUrl: str
contactZip: str
crs: Crs | None
dateCreated: datetime.datetime | None
dateUpdated: datetime.datetime | None
fees: str
image: str
inspireDegreeOfConformity: str
inspireMandatoryKeyword: str
inspireResourceType: str
inspireSpatialDataServiceType: str
inspireSpatialScope: str
inspireSpatialScopeName: str
inspireTheme: str
inspireThemeNameEn: str
inspireThemeNameLocal: str
isoMaintenanceFrequencyCode: str
isoQualityConformanceExplanation: str
isoQualityConformanceQualityPass: bool
isoQualityConformanceSpecificationDate: str
isoQualityConformanceSpecificationTitle: str
isoQualityLineageSource: str
isoQualityLineageSourceScale: int
isoQualityLineageStatement: str
isoRestrictionCode: str
isoScope: str
isoScopeName: str
isoServiceFunction: str
isoSpatialRepresentationType: str
isoSpatialResolution: str
isoTopicCategories: list[str]
keywords: list[str]
language: str
language3: str
languageBib: str
languageName: str
license: str
licenseUrl: str
name: str
parentIdentifier: str
serviceMetadataURL: str
temporalBegin: datetime.datetime | None
temporalEnd: datetime.datetime | None
title: str
wgsExtent: Extent | None

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.

about: str
description: str
format: str
formatVersion: str
function: str
mimeType: str
scheme: str
title: str
type: str
url: str
class gws.MiddlewareManager

Bases: Node

Manage middleware and their dependencies.

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.

type gws.MimeType = str

A mime type or an alias.

class gws.Model

Bases: Node

Data Model.

clientOptions: ModelClientOptions
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.ModelClientOptions(*args, **kwargs)

Bases: Data

Client options for a model

keepFormOpen: bool | None
class gws.ModelContext(*args, **kwargs)

Bases: Data

Model context.

dbSelect: ModelSelectBuild
maxDepth: int = 0
op: ModelOperation
project: Project
relDepth: int = 0
search: SearchQuery
target: ModelReadTarget
user: User
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 = 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(*args, **kwds)

Bases: Enum

Model operation.

create = 'create'
delete = 'delete'
read = 'read'
update = 'update'
class gws.ModelReadTarget(*args, **kwds)

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.ModelSelectBuild(*args, **kwargs)

Bases: Data

Database select statement.

columns: list[sqlalchemy.Column]
geometryWhere: list
keywordWhere: list
order: list
where: 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

GWS object tree node.

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) Node | None

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) Node | None

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) list[Node]

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 | None = None) list[Node]

Find all children that match a specific class.

Parameters:

classref – Class reference.

Returns:

A list of objects.

find_ancestors(classref: ClassRef | None = None) list[Node]

Find node ancestors that match a specific class.

Parameters:

classref – Class reference.

Returns:

A list of objects.

find_closest(classref: ClassRef | None = None) Node | None

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) list[Node]

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 | None = None) Node | None

Find the first child that matches a specific class.

Parameters:

classref – Class reference.

Returns:

An object or None.

initialize(config)
is_a(classref: ClassRef) bool

Check if a the node matches the class reference.

Parameters:

classref – Class reference.

Returns:

A boolean.

periodic_task()

Periodic task hook.

post_configure()

Post-configuration hook.

pre_configure()

Pre-configuration hook.

exception gws.NotFoundError

Bases: Error

Generic ‘object not found’ error.

class gws.NumberFormat(*args, **kwds)

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

Basic 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(*args, **kwds)

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.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(*args, **kwds)

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[ImageFormat]

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_compatible(layer: Layer) bool

True if layer can be used in this service.

class gws.OwsVerb(*args, **kwds)

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.

type gws.Point = tuple[float, float]

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.

exec_print(request: PrintRequest, out_path: str)
start_print_job(request: PrintRequest, user: User) JobStatusResponse
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
compositeLayerUids: list[str] | None
cssSelector: str | None
features: list[FeatureProps] | None
layerUid: str | None
opacity: float | None
soupPoints: list[Point] | None
soupTags: list[Any] | None
type: PrintPlaneType
url: str | None
class gws.PrintPlaneType(*args, **kwds)

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(*args, **kwds)

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]
vars: dict
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.

type gws.Regex = str

Regular expression, as used in Python.

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(*args, **kwds)

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.

configPaths: list[str]
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) Node | None

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) Node | None

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) Node | None

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 | None = None) list[Node]

Find all objects that match a specific class.

Parameters:

classref – Class reference.

Returns:

A list of objects.

find_first(classref: ClassRef | None = None) Node | None

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) Node | 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.SearchFilter(*args, **kwargs)

Bases: Data

Search filter.

escapeChar: str
matchAction: SearchFilterMatchAction
matchCase: bool
operator: SearchFilterOperator
property: str
shape: Shape
singleChar: str
subFilters: list[SearchFilter]
value: str
wildCard: str
class gws.SearchFilterMatchAction(*args, **kwds)

Bases: Enum

Search filter match action.

All = 'All'
Any = 'Any'
One = 'One'
class gws.SearchFilterOperator(*args, **kwds)

Bases: Enum

Search filter operator.

And = 'And'
BBOX = 'BBOX'
Beyond = 'Beyond'
Contains = 'Contains'
Crosses = 'Crosses'
Disjoint = 'Disjoint'
DWithin = 'DWithin'
Equals = 'Equals'
Intersects = 'Intersects'
Not = 'Not'
Or = 'Or'
Overlaps = 'Overlaps'
PropertyIsBetween = 'PropertyIsBetween'
PropertyIsEqualTo = 'PropertyIsEqualTo'
PropertyIsGreaterThan = 'PropertyIsGreaterThan'
PropertyIsGreaterThanOrEqualTo = 'PropertyIsGreaterThanOrEqualTo'
PropertyIsLessThan = 'PropertyIsLessThan'
PropertyIsLessThanOrEqualTo = 'PropertyIsLessThanOrEqualTo'
PropertyIsLike = 'PropertyIsLike'
PropertyIsNil = 'PropertyIsNil'
PropertyIsNotEqualTo = 'PropertyIsNotEqualTo'
PropertyIsNull = 'PropertyIsNull'
Touches = 'Touches'
Within = 'Within'
class gws.SearchManager

Bases: Node

Search Manager.

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

Bases: Data

Search query.

bounds: Bounds

Search bounds.

extraArgs: dict

Extra arguments for custom searches.

extraColumns: list

Extra columns to select.

extraParams: dict

Extra parameters to pass to a provider

extraWhere: list

Extra where clauses.

filter: SearchFilter

Search filter.

keyword: str

Keyword to search for.

layers: list[Layer]

Layers to search in.

limit: int

Limit the number of results.

project: Project

Project to search in.

resolution: float

Pixel resolution for geometry search.

shape: Shape

Shape to search in.

sort: list[SearchSort]

Sort options.

tolerance: UomValue

Tolerance for geometry search.

uids: list[str]

UIDs to search for.

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.

register_periodic_task(obj: Node)

Register an object as a periodic task handler.

Parameters:

obj – A node with a periodic_task method.

schedule_reload(with_reconfigure: bool = False)

Schedule a system reload.

Parameters:

with_reconfigure – Reconfigure the server before reloading.

start()

Start the monitor.

watch_directory(path: str, pattern: Regex, recursive=False)

Add a directory to watch.

Parameters:
  • path – Directory path.

  • pattern – Regex pattern for files to watch.

  • recursive – Watch subdirectories.

watch_file(path: str)

Add a file to watch.

Parameters:

path – File path.

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_2d() Shape

Converts a geometry to 2-dimensional.

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(trim=False, rounding_precision=-1, output_dimension=3) str

Returns an EWKT representation of this shape.

to_geojson(keep_crs=False) dict

Returns a GeoJSON representation of this shape.

Parameters:

keep_crs – Do not transform to WGS.

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(trim=False, rounding_precision=-1, output_dimension=3) str

Returns a WKT representation of this shape.

tolerance_polygon(tolerance=None, 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
type gws.Size = tuple[float, float]

Size [width, height].

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

Bases: Data

Sort options.

fieldName: str

Field name to sort by.

reverse: bool = False

Sort in reverse order.

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: float
properties: dict
resourceUrls: dict
scaleRange: list[float]
sourceId: str
styles: list[SourceStyle]
supportedCrs: list[Crs]
tileMatrixIds: list[str]
tileMatrixSets: list[TileMatrixSet]
title: str
wgsExtent: Extent
class gws.SourceStyle(*args, **kwargs)

Bases: Data

Generic OGC Style.

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

Bases: Enum

Options for structured reading based on Specs.

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: set[SpecReadOption] = None)

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
find_templates(subjects: list[str], where: list[Node], user: User = None, mime: str = None) list[Template]
template_from_path(path: str) Template | None
class gws.TemplateQualityLevel(*args, **kwargs)

Bases: Data

Template quality level.

dpi: int

DPI for the quality level.

name: str

Quality level name.

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(*args, **kwds)

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(*args, **kwds)

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)

type gws.UomExtent = tuple[float, float, float, float, Uom]

Extent with a unit.

type gws.UomExtentStr = list[str]

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

type gws.UomPoint = tuple[float, float, Uom]

A Point with a unit.

type gws.UomPointStr = list[str]

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

type gws.UomSize = tuple[float, float, Uom]

A Size with a unit.

type gws.UomSizeStr = list[str]

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

type gws.UomValue = tuple[float, Uom]

A value with a unit.

type gws.UomValueStr = str

A value with a unit like 5mm.

type gws.Url = str

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.

contentType: str

Request content type.

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 element and adds it as a child.

Parameters:
  • tag – XML tag.

  • attrib – XML attributes {key, value}.

append(subelement: XmlElement)

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

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

Alias for ‘get’.

children() list[XmlElement]

Returns the children of the current element.

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

Given a list of paths, returns the first matching element.

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

Finds text for first matching element by name or path.

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

Gets the element attribute named key.

hasattr(key: str) bool

Check if an attribute exists.

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 – List of paths to search for.

  • deep – If False it only looks into direct children, otherwise search the entire subtree.

Returns:

A dict tag name -> text.

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

Collects texts from child elements.

Parameters:
  • paths – List of paths to search for.

  • deep – If False it only looks into direct children, otherwise search the entire subtree.

Returns:

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

textof(*paths) str

Given a list of paths, returns the text of the first matching element that has text.

to_dict() dict

Creates a dictionary from an XmlElement object.

to_list(opts: XmlOptions | None = None) list

Parse an XML element into a list of arguments (reverse of gws.lib.xmlx.tag).

Parameters:

opts – XML options for serialization.

to_string(opts: XmlOptions | None = None) str

Converts the Element object to a string.

Parameters:

opts – XML options for serialization.

Returns:

An XML string.

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

Bases: Data

XML namespace.

extendsGml: bool

Namespace schema extends the GML3 schema.

isDefault: bool

Is this the default namespace for the given xmlns prefix.

schemaLocation: Url

Namespace schema location.

uid: str

Unique ID.

uri: Url

Namespace uri.

version: str

Namespace version.

xmlns: str

Default prefix for this Namespace.

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

Bases: Data

XML options for serialization.

compactWhitespace: bool = False

Remove all whitespace outside of tags and elements.

defaultNamespace: XmlNamespace | None = None

Default namespace to use for serialization.

docype: str | None = None

Document type definition (DTD) to use.

foldTags: bool = False

If true, folds nested tag names into parent/child names.

namespaces: dict[str, XmlNamespace] | None = None

Mapping of prefixes to namespaces.

removeNamespaces: bool = False

Remove all namespace references.

withNamespaceDeclarations: bool = False

Include the namespace declarations.

withSchemaLocations: bool = False

Include schema locations.

withXmlDeclaration: bool = False

Include the xml declaration.

xmlnsReplacements: dict[str, str] | None = None

A mapping of namespace prefixes to custom prefixes.